2

After a search command / (i.e., in normal mode) is done, I would like another command to be executed automatically. At the moment the other command should be :normal! zz, in order to center the found line.

Previously I had a solution where both the search command (either / or search()) and the center command zz run in the Ex command-line concatenated by |.

But this way is now not appropriate.

An autocommand would be suitable, but in the list of available events such an event "do after each search command" is not contained.

I have found this internet article:

https://stackoverflow.com/questions/21535350/creating-a-user-defined-event-in-vim

This sounds to be just the solution to my question. But in vim help I read that User will never be executed automatically. Thus not suitable.

Is this possible at all?

I am using vim version 8.2, in the moment in KNOPPIX 9.1

1 Answer 1

1

I believe the "classic" solution remaps various search keys:

" If you have other <Enter> mappings, you might want `:nmap` here
:cnoremap <expr> <Enter> getcmdtype =~# '[?/]' ? '<CR>zz' : '<CR>'
:nnoremap n nzz
:nnoremap N Nzz
" etc.

but I have had problems with this in the past (I can't recall exactly how, but occasionally zz would show up in my buffer).

I must not be having the same problems now, because I use the following mappings:

nnoremap <silent> n n:call bk#cursor#blink(0.2)<cr>
nnoremap <silent> N N:call bk#cursor#blink(0.2)<cr>

where the function is defined in my personal autoload like

function bk#cursor#blink(time) abort
  call bk#cursor#hl_on()
  let time_in_ms = float2nr(a:time * 1000)
  if has('timers')
    let _ = timer_start(time_in_ms, {_ -> bk#cursor#hl_off()})
  else
    exec 'sleep'  time_in_ms  'm'
    call bk#cursor#hl_off()
  endif
endfunction

function bk#cursor#hl_on() abort
  set cursorline cursorcolumn
  redraw
endfunction

function bk#cursor#hl_off() abort
  set nocursorline nocursorcolumn
  redraw
endfunction

Coupled with :set hlsearch (optionally https://github.com/romainl/vim-cool) and a mapping on <space><space><space> (triple-<leader>) that calls the same blink function, I almost never lose my place anymore.

3
  • Should this be a cnoremap <expr> <Enter> (instead of nnoremap) to trap the Enter at the end of the / command-line?
    – filbranden
    Commented Sep 27, 2022 at 17:28
  • 1
    Hm, probably @filbranden. Changing
    – D. Ben Knoble
    Commented Sep 27, 2022 at 18:10
  • 1
    I have nnoremap n nzzzv and nnoremap N Nzzzv in my vimrc so anything that happens to be in a fold is uncovered.
    – MDeBusk
    Commented Sep 27, 2022 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.