Highlight current search result in vim - vim

In emacs, when you do a search, there will be one highlight color for all occurences in the buffer, and another color for the occurence that your cursor happens to be on. I was wondering if anyone knew about similar behavior in vim, a vim plugin, or even some ideas on how to accomplish it myself in vimscript.
(note, I already know about hl-IncSearch, which is close, but not what I am looking for)

It sounds like you want to highlight all results in the buffer. You can say
:set hls
Which will turn on hlsearch. Then you can say
:set nohls # turn off permanently
:noh # turn off until next time you search.
You can also search for / highlight the word under the cursor with * (forwards) or # (backwards).

As far as I know there isn't a built-in way to do what you want.
If I were to try to implement it myself... Well one way you could do it is by overriding *, n and p and combining it with something like this function:
noremap n n:call HighlightNearCursor()<CR>
noremap p p:call HighlightNearCursor()<CR>
noremap * *:call HighlightNearCursor()<CR>
function HighlightNearCursor()
if !exists("s:highlightcursor")
match Todo /\k*\%#\k*/
let s:highlightcursor=1
else
match None
unlet s:highlightcursor
endif
endfunction
I haven't tested it out, so this isn't a complete solution, but I think it is at least a viable approach.
EDIT : You will probably have to set some custom highlight colours. This vimwiki page gives some information about that, although I remember seeing a terser example somewhere.
EDIT AGAIN: Maybe a cleaner solution is to use Mark.vim in conjunction with the first technique. Then it would all boil down to something like:
noremap n \nn\m
noremap p \np\m
noremap * \n*\m

I just wrote a vim plugin that does what you requested.
https://github.com/timakro/vim-searchant

I don't have a real answer, but a simple way to get maybe 75% of what you want may be to just change the highlighting of the cursor. The default gray cursor block doesn't contrast well with the default yellow of search highlights. So just change cursor highlighting to (a) something that contrasts more with yellow and (2) also contrasts with other colors in your colorscheme. For me something like this works pretty well:
highlight Cursor guifg=green guibg=red
For me the blinking red cursor on first letter of current search match stands out pretty well. Not as good as a full-blown solution, but dead-simple. (I assume it works just as well in terminal Vim if you add those items to the highlight command but haven't tested it there.)

Related

Cycling and/or highlighting through a vim selection

The feature I am thinking of is kind of inspired by a feature that I really like about sublime text.
In sublime text, if you select a sequence of characters, it automatically puts a little box around it (to distinguish it from the word that you just highlighted). For me, this is very helpful because I can see and find specific things of the code much faster.
It would be awesome to have something similar to my vim environment. It does not have to be exactly the same as the one in sublime though, but it would be awesome if it were as similar as possible plus the additional feature to easy cycling through similar words.
Currently, what I am doing is highlight the work I want and then manually typing it to the search command /. It would be much better if I can just highlight it in visual mode and then automatically highlight similar words on the current screen with a different colour from the highlighting in visual mode and then have a quick key short cut to cycling through them, if I wished to do that.
I am not sure if a there exists a plugin or something that already does that, but that would cool! Ideally, I would want to to know as many details of the commands/changes to the vimrc file, so that I have the most control over this feature and be able to customize it as I wish.
You can get the highlighting you are looking for by enabling the hlsearch option:
:set hlsearch
It will highlight every occurrence of the last search pattern and thus work after all the following commands (and their relatives):
/foo<CR>
?bar<CR>
:s/fizz/buzz/g
*
#
You can use n to jump to the next occurrence in the direction of your search and N to do the same in the opposite direction.
To highlight every occurrence of the current word "without" moving the cursor, you can simply do:
*N
or:
*``
to jump to the next occurrence and jump back immediately.
Doing the same for visually selected text is a bit trickier but still possibleā€¦
either via a lightweight plugin like visualstar or The Search Party,
or with a tiny bit of crude vimscript in your ~/.vimrc:
" this function cleans up the search pattern
function! GetVisualSelection()
let old_reg = #v
normal! gv"vy
let raw_search = #v
let #v = old_reg
return substitute(escape(raw_search, '\/.*$^~[]'), "\n", '\\n', "g")
endfunction
" map * and # in visual mode so that they do the same as *N and #N in normal mode
xnoremap * :<C-u>/<C-r>=GetVisualSelection()<CR><CR>N
xnoremap # :<C-u>?<C-r>=GetVisualSelection()<CR><CR>N
My SearchHighlighting plugin changes the * command so that it just toggles the highlighting for the current word, without the movement to the next match (for which you can press n, or pass a count). This also works in visual mode, using the selection. I find this very handy for highlighting all matches.
There's also a mode that automatically highlights the current word / selection, like what many IDEs offer.
Other plugins
If you want more permanent highlighting, separate from searching, the Mark plugin offers that.
To get an orientation about the number of matches (without highlighting them), I have the SearchPosition plugin.

Vim: Vertical "f" and "t"

One tiny piece of functionality I find myself missing increasingly often is the ability to move vertically in a similar fashion to f and t. Usually what I want is to move to the top or bottom of a paragraph without losing my column position, and while I "could" just write a script for it, I wondered if there is any known way around this problem that you guys know of.
Example ( [ ] = current position, < > = destination ):
set tabstop=4
set shiftwidth=4
set <s>ofttabstop=4
set gfn=Source\ Code\ Pro:h14
set encoding=utf-8
set [t]_Co=256
set number
Like a vertical fs, or t<space>.
Again, this is usually useful when working with blocks of code. Any ideas?
vim regex provides \%nc (n is col idx) to match only in certain column.
so without installing plugin, what you could do is :
nnoremap <leader>f :<c-u>exe line('.').'/\%'.col('.').'c'.nr2char(getchar())<cr>
in this way, you press <leader>f, then press a key, vim will search that char in the same col. next, you press n/N
If you want to have the same but search backwards, use ?.
The most basic way is to use forward search, /t_<CR> and backward search, ?so<CR>, ideally with set incsearch.
But there are quite a lot of plugins designed around that idea:
EasyMotion,
Sneak,
Fanfingtastic,
and a few othersā€¦
For moving vertically without changing columns, you can use <n>j or <n>k. That doesn't completely help with "top of paragraph" or "bottom of paragraph" without counting the lines. There's also '{' and '}' for jumping between paragraphs. Not sure there's a single command to do exactly what you want...
I recently implemented the JumpToVerticalOccurrence plugin (just published), which implements an f{char} equivalent as ]V{char}. It also has related mappings that jump to the same character the cursor is under, or to non-whitespace in the same column.
I have a mapping that might be useful in visual selection.
To extend the selection downwards (<leader>j) or upwards (<leader>k) from the current column, but not beyond the block of text:
vnoremap <leader>j <Esc>m`:let b:ss=#/<CR>:let b:zz=col('.') - 1<CR>/\%<C-r>=b:zz<CR>c.\zs.\+\n.\{,<C-r>=b:zz<CR>}$<CR>:let #/=b:ss<CR><C-v>``o
vnoremap <leader>k <Esc>m`:let b:ss=#/<CR>:let b:zz=col('.') - 1<CR>?^.\{,<C-r>=b:zz<CR>}\n.*\%<C-r>=b:zz<CR>c.\zs.<CR>:let #/=b:ss<CR><C-v>``o
It also avoids clobbering the search register. At least, that's how I avoid clobbering the search register.

Not highlighting search in vim if it is a part of a command

In my .vimrc I've enabled highlighting the searched text (which I find to be a handy feature and wouldn't want to disable it).
set hlsearch
And, following answers to this question, I've made a mapping to be able to clear the highlight:
nmap <silent> ,/ :nohlsearch<CR>
The problem comes with commands which include search. For example, delete to next character 'x':
d/x
This will automatically highlight all the instances of 'x'. To remove this highlight I have to punch ,/ to clear it, which is quite annoying.
The question. Is it possible to enforce :nohl if the search is a part of a preceding command? Maybe, it is possible at least for a selected list of commands (say, d, y and c) before / character is hit?
d/x does not work for me as you describe. (I'm on vim 7.3 here and it can't make sense of the / following d in normal mode, so disregards the d and starts a regular / search.)
If you want to delete to the next x, then dfx or dtx are what I would use (depending on whether you want to also delete the x itself or not).
No highlighting involved.
Hope that helps.
[Following some clarification in the comments.]
I'm thinking that it should be possible to write a custom function to do what you want, and then assign a custom key sequence to call that function.
I played around a little, but am not very well versed in vim functions and couldn't make it work.
Here's what I tried:
function! g:DeleteToSearchAndNohls(term)
:normal d/a:term
:nohlsearch
endfunc
If 'x' is on the same line than the cursor, you can use dtx (meaning delete to x).

In vim, is there a way to rebind "*" to highlight the current word, without advancing to the next? [duplicate]

This question already has answers here:
Vim: search and highlight but do not jump
(14 answers)
Closed 4 years ago.
I often use * to highlight all instances of the current word, and the fact that it advances to the next word is pretty annoying. I'd like to disable this behavior, knowing that I can always use "n" if I actually need to advance.
Any insight?
EDIT: I should add that I'd like to avoid a screen redraw at all costs as it is visually distracting.
Try this:
nnoremap * :let #/ = "\\<<C-R><C-W>\\>"<CR>
(Assumes you have 'hlsearch' on). This just changes the current search pattern to the word under the cursor (surrounded by \< and \> to match word boundaries). If you have hlsearch enabled, it will highlight the word. n and N will then work as normal.
See:
:help :let-#
:help quote/
:help c_CTRL-R_CTRL-W
Try this Vim Tip. I find it very useful. The most interesting is that you can have more matches and every one in different color.
I cannot give an exact answer, but this Vim Tip tells you what you have to add to your .vimrc to simply highlight the word under the cursor when Vim is in idle state.
Works without any key-remapping...
You can remap it to return:
nnoremap * '*N'
(but this redraws the screen)

How do I make vim syntax highlight a whole line?

I'd like to have vim highlight entire lines that match certain patterns. I can get all the text in a line to highlight (by doing syn match MyMatch "^.*text-to-match.*$"), but it always stops at the end of the text. I'd like to to continue to the end of the term, like highlighting CursorLine.
I've tried replacing $ with a \n^, hoping that would wrap it around. No change. (I didn't actually expect this would work, but there's no harm in trying.) I also tried adjusting the syn-pattern-offset (which I read about here: http://vimdoc.sourceforge.net/htmldoc/syntax.html#:syn-pattern). Long story short, adding he=he-5 will highlight 5 fewer characters, but he=he+5 doesn't show any extra characters because there aren't characters to highlight.
This is my first attempt at making a vim syntax and I'm relatively new to vim. Please be gentle and include explanations.
Thanks!
(edit: Forgot to include, this is a multiline highlight. That probably increases the complexity a bit.)
It's not very adaptive as the filename (buffer) and line to full row highlight needs to be explicitly identified, but apparently the sign command can be used:
It is possible to highlight an entire
line using the :sign mechanism.
An example can be found at :help
sign-commands
In a nutshell:
:sign define wholeline linehl=ErrorMsg
:sign place 1 name=wholeline line=123 file=thisfile.txt
Obviously, you should pick a higlight
group that changes the color of the
background for the linehl argument.
source: Erik Falor, vim mailing list
From the documentation on syn-pattern:
The highlighted area will never be
outside of the matched text.
I'd count myself surprised if you got this to work, but then again, Vim is always full of surprises.
could also try
:set cursorline
:set cursorcolumn
change colors like this:
:hi cursorline
:hi cursorcolumn
using the usual term=, ctermfg=, ctermbg= etc
see this answer
VIM Highlight the whole current line

Resources