2

In my vimrc file I have the following entry to surround a word with '+':

:nnoremap <silent> q+ wbi+<ESC>ea+<Esc>

I would like to change this to surround a word with any other symbol, for example a quote, but I would not like to use another plugin or to insert one more map. I would like something like this in my vimrc:

:nnoremap <silent> qX wbiX<ESC>eaX<Esc>

where X would be the character to put around the word.

How can this be done in VIM?

Thanks

mljrg
  • 4,430
  • 2
  • 36
  • 49

2 Answers2

5

The general idea:

:nnoremap q :let c=nr2char(getchar())\|:exec "normal wbi".c."\eea".c."\e"<CR>

But I don't think that q is a good choice, especially for your example with quotes, because q starts the extremely handy recording feature from vim. The normal q command also does expect a second character (the recording target register) and it actually can be ". This will be quite confusing for you when you're on another computer or if someone else is using your vim. You should preprend a leader for q. With a leader:

:nnoremap <leader>q :let c=nr2char(getchar())\|:exec "normal wbi".c."\eea".c."\e"<CR>

The default leader value is \, but this can be changed. Note that it had to be changed before defining the mapping. You can see the currently configured leader with let mapleader (which prints an error message if there's no leader configured). With these statements,

:let mapleader=','
:nnoremap <leader>q :let c=nr2char(getchar())\|:exec "normal wbi".c."\eea".c."\e"<CR>

you can type ,q+ to surround your word with + and ,q" in order to surround your word with ".


By the way: Your mapping doesn't work if your cursor is on the last character on line. Change the mapping to:

:nnoremap <leader>q :let c=nr2char(getchar())\|:exec "normal viwo\ei".c."\eea".c."\e"<CR>
Community
  • 1
  • 1
steffen
  • 16,138
  • 4
  • 42
  • 81
  • I really appreciate your answer because it not only solves my problem, but also introduces me to some useful Vim syntatic and semantic constructs. Thanks! – mljrg Jan 27 '16 at 23:18
2

Use Tim Pope's surround.vim plugin!

To surround a word with + signs:

ysiw+
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
  • I already knew about that plugin, but I prefer to avoid plugins to prevent conflicts between them. Thanks anyway for your answer. – mljrg Jan 27 '16 at 23:19
  • Tim Pope's plugin is *super* popular. It would be probably be considered an issue/bug with the other conflicting plugin. I personally consider surround.vim to be a "must have" plugin. – Peter Rincker Jan 27 '16 at 23:32
  • Well, it may change key mappings that other plugins may defined, or not? My concern here is for me to be unaware of this kind of conflict when I install a novel plugin... – mljrg Jan 27 '16 at 23:40