Reman
Reman

Reputation: 8109

Highlight entire line when there are matches

Does anyone know how to highlight the entire line if there is or if there are matches after doing a search.

p.e. I do a search for /user

Now I want to highlight the entire line if there are matches.

EDIT
I want to use the highlighting as in the search highlighting.
I don't want to use the highlighting groups.

Upvotes: 2

Views: 457

Answers (3)

Ingo Karkat
Ingo Karkat

Reputation: 172570

If you use

:let @/ = '.*\%(' . @/ . '\m\).*'

that should work for most regexp patterns (e.g. the bracketing takes care of \| branches). You could refine that to recognize ^ and $, and magic modifiers like \V.

Upvotes: 2

Peter Rincker
Peter Rincker

Reputation: 45117

An alternative to highlighting the the lines might be using the quickfix list. For example doing following will put all lines matching the pattern /user/ into the quickfix list for the current file (%).

:vimgrep /user/ %

You can display in a separate window the contents of the quickfix list by doing :copen. You can move between matching lines by :cnext, :cprev, and friends. I personally recommend Tim Pope's excellent unimpaired.vim plugin to provide some rather nice and natural feeling mappings like [q and ]q to move through the quickfix list. You can also add a g flag to find multiple matches per line and add them to the quickfix list as well.

You may want to mapping to this vimgrep command to make it a bit faster. I personally use the following in my ~/.vimrc

nnoremap <leader>/ :vimgrep/<c-r>//g %<cr>:copen<cr>

A disadvantage to using :vimgrep command is that it needs a saved file, so unsaved buffers must be saved first. You can overcome this with using a combination of :global and :cgetexpr as shown below.

:cexpr []
:g//caddexpr expand("%").":".line(".").":".getline(".")

However maybe you really do just want to highlight the lines with a match instead of using the quickfix list. The I would suggest using :match like so

:match Search /.*user.*/

You can use whatever highlight group you want. I choose Search as it seemed appropriate. To turn off the highlighting just execute :match with out any arguments.

I personally prefer using :vimgrep and the quickfix list, but your needs may vary from mine.

For more help see:

:h quickfix
:h :vimgrep
:h :cnext
:h :cexpr
:h :caddexpr
:h :match

Upvotes: 4

Kent
Kent

Reputation: 195059

I don't know if this is acceptable for you:

first you need to define a highlight group: e.g. userline

:highlight userline ctermbg=darkred guibg=darkred

then you could:

:match userline /.*user.*/

all lines containing "user" would be highlighted.

Upvotes: 1

Related Questions