Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search "off the record" in Vim, or remove search pattern from search history?

Tags:

vim

search

macros

I have in my .vrimrc cute little macros which add/remove c++ style comments from code:

" remove c++ style comment
nmap _ :s/^[ \t]*\/\///<CR>==:nohls<cr>
" comment line, c++ style
nmap - :s/^[ \t]*/\/\/ /<CR>==:nohls<cr>

These work by replacing the beginning of line pattern with another. In one case adding // and in another removing the slashes (if found).

The problem I bump into is that those macros use search-and-replace. As a result, unwanted search patterns are saved into vim's search history, cluttering it.

Consider the sequence:

  1. Searched for 'hello'
  2. Use the macro to comment a line
  3. Search again (by typing 'n' or /,keyup,enter)
  4. Result: the search does not look for 'hello', because the search pattern is set to whatever the macro was using, which is ^[ \t]*

How can this macro be modified to not inject unwanted patterns into the search history?

like image 334
tivoni Avatar asked Jan 13 '14 08:01

tivoni


3 Answers

Recent Vims have the :keeppattern modifier, which will prevent the pattern from adding to the history.

like image 153
Christian Brabandt Avatar answered Oct 31 '22 22:10

Christian Brabandt


  1. Save the current search register with let old = @/,
  2. do your thing,
  3. delete the last search from the history with call histdel('/', -1),
  4. restore the search register with let @/ = old.

Like this:

" remove c++ style comment
nnoremap <silent> _ :let old = @/<bar>s/^[ \t]*\/\///<CR>==:nohls<bar>call histdel('/', -1)<bar>let @/ = old<cr>
" comment line, c++ style
nnoremap <silent> - :let old = @/<bar>s/^[ \t]*/\/\/ /<CR>==:nohls<bar>call histdel('/', -1)<bar>let @/ = old<cr>

Or use Tim Pope's Commentary.

like image 7
romainl Avatar answered Oct 31 '22 22:10

romainl


Also, there's a search() function, which doesn't touch the search history.

like image 2
Bohr Avatar answered Oct 31 '22 23:10

Bohr