Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM Restore last search pattern

Tags:

vim

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?

like image 800
Ayman Avatar asked Sep 06 '09 08:09

Ayman


3 Answers

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

like image 166
Francisco Velez Avatar answered Oct 26 '22 23:10

Francisco Velez


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.

like image 38
derobert Avatar answered Oct 26 '22 23:10

derobert


I think you should use the function search() because it will not mess with your search register:

:call search('pattern')
:call search('pattern', 'b')

The flag b means, search backward instead of forward

like image 30
SergioAraujo Avatar answered Oct 27 '22 01:10

SergioAraujo