I want to replace in highlighted text the angle brackets < and > with &lt; and &gt;. The following line in my .vimrc doesn't seem to work:

vmap <F9> :'<,'>s/</\&lt;/g | '<,'>s/>/\&gt;/g

What am I doing wrong?

1 Answer 1


There are several issues. First of all what happens when you make a visual selection and then go to the command line with :? You see how it's pre-populated with '<,'>. You should drop that from the first substitution in your mapping as it's redundant. (Or you can leave it in and make the first part of your mapping <C-U> as in Ctrl-U. That will clear the '<,'> from the command line before the rest of your mapped commands are inserted.)

Next issue is that you can't combine commands with | in a mapping unless you escape that character with backslash. Alternatively you can use <bar> instead of \|. If you don't do this then the second command will be run when you run the map command itself.

Finally, you are missing a key part of any command. The carriage return that submits it for execution. In a mapping you can specify this with <CR>.

So that all adds up to either one of these (I'm showing both ways to handle the implied '<,'> here)...

:vnoremap <F9> :s/</\&lt;/g <bar> '<,'>s/>/\&gt;/g<CR>
:vnoremap <F9> :<C-U>'<,'>s/</\&lt;/g <bar> '<,'>s/>/\&gt;/g<CR>

Note that I'm using vnoremap here. As a rule of thumb, unless you know the difference between the two and you know that you truly need vmap you should always use the "noremap" version. This holds for other mapping types, too, like nmap/nnoremap.

Pro Tip: You may notice when using this mapping that you get output from the substitutions like "5 substitutions on 3 lines" and you must hit enter to clear it. To avoid this you can just append <C-L> to the end of the mapping above and that will automatically clear things for you.

  • @B thanks, that's very helpful. The only little thing, I still have to Esc after pressing F9 in order for it to be executed--can that be avoided?
    – ajo
    Mar 22, 2020 at 0:25
  • @ajo So you visually select some text, hit F9 and it just hangs there until you hit Esc...? Because it shouldn't do that. Does F9 have any system wide function. Like when you're not in vim? What do you see if in Vim in Insert mode if you type ctrl-v followed by F9?
    – B Layer
    Mar 22, 2020 at 2:44
  • On an unrelated note I corrected an error in the answer. You should only remove '<,'> from the first substitution (or you can use the alternate solution with <C-U>).
    – B Layer
    Mar 22, 2020 at 3:14
  • 1
    @B This is working now smoothly. Thanks for your help and explanations.
    – ajo
    Mar 22, 2020 at 9:29
  • I think you can use * as the range in the second substitute as a shorthand.
    – D. Ben Knoble
    Mar 22, 2020 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.