VIM Restore last search pattern

2020-07-06 07:30发布

问题:

I remapped [[ and ]] to find the previous and next pattern in the file. The mappings are as follows:

nmap [[ ?^.section <CR>
nmap ]] /?section /<CR>

The issue is that when I use any of them, I "loose" the current search pattern, so when doing n for the next match, I search for the next "section".

Is there a way to restore the search pattern, or for the [[ and ]] mappings to not affect the current search pattern?

回答1:

You can probably do it by hand by saving and restoring the "/ register. However, a better way is to just move your code into a function; returning from a function automatically restores it. To quote the VIM documentation:

                                                                                                                              *function-search-undo*
The last used search pattern and the redo command "." will not be changed by the function. This also implies that the effect of |:nohlsearch| is undone when the function returns.

This would look something like this in your .vimrc:

function! Ayman_NextSection
    /?section /
endfunction
nmap ]] call Ayman_NextSection()<CR>

Hope that helps.



回答2:

After typing '/' or '?' for begin the search, just use up-down arrow to bring the search buffer line by line.



标签: vim