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

macros, search, vim

Solution

- Save the current search register with `let old = @/`,

- do your thing,

- delete the last search from the history with `call histdel('/', -1)`,

- 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.

Problem

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: - Searched for 'hello' - Use the macro to comment a line - Search again (by typing 'n' or /,keyup,enter) - 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?

Original source

Related problems