created November 9, 2001 · complexity basic · author Joachim Hofmann · version 5.7
Saving Keystrokes for common Substituting and SearchingEdit
Sorry, there is not much that can be saved for common Searching. It's just hitting
I think, common substitution requires pretty many keystrokes. So I use the following macro with my favorite substitution options:
:map <F4> :%s//gc<Left><Left><Left>
This ends up with the cursor after the first '/' in the commandline. To complete it, you only have to enter
Remark: I mapped it to <F4> (cause of tribute to the <F4> of the good old Norton Commander editor). You may map it where you want to.
Searching for resp. Substituting of the current word under the cursorEdit
The following macro extends the one above with automatically inserting the current word under the cursor into the from - pattern of the :s command.
:map <S-F4> :%s/<C-r><C-w>//gc<Left><Left><Left>
To complete it, just enter
I use this i.e. for reliable and quickly renaming a variable in the entire buffer.
I mapped it to Shift-<F4>. You may map it to the keystroke you want.
Explanation: CTRL-r+CTRL-w expands to the word under the cursor.
Searching and Substituting for an arbitrary visually selected part of textEdit
If you want to look or substitute (for) an arbitrary pattern (which already exists at least once in your text), the following 2 mappings do it for you.
The advantage is that you don't have to type again or cut and paste the appropriate text but only have to visually select it.
:vmap / y:execute "/".escape(@",'/\.*')<CR>
This immediately finds to the next occurrence of the previously visually selected text.
:vmap <F4> y:execute "%s/".escape(@",'/')."//gc"<Left><Left><Left><Left>
Again, as in the mapping in chapter 2), you just have to complete it by entering
What both Substituting and Searching in this way generally does is:
Yank the selected text.
Inserting the visually selected via addressing the '"' register with '@"' as a parameter of the escape() function going finally into the 'myoldpattern' part. The tricky problem is, if you have characters in your myoldpattern, which are regular expression chars, they are recognized and treated accordingly. That is most likely not what you wanted. To escape them, these chars have to be declared by the second parameter of the excape() function, which then escapes them with a backslash. The few characters above work for me. If you run into problems, you should check for additional regexp chars in your text, and try to escape them by adding them to the escape() function parameter.
With the appropriate mappings in your vimrc you can save keystrokes when Searching or Substituting and avoid typing errors. That way, you can take lunch sooner.
Great to find escape()
I have the following map, as a consequence:
cm <C-A> <C-R>=escape(@",'/\.*')<CR> vm * y/<C-A><CR>| vm / y:%s/<C-A>/ vm # y?<C-A><CR>| vm ? y:g/<C-A>/t$<CR>