mljrg
mljrg

Reputation: 4620

Vim mapping to surround word with a character

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

Upvotes: 2

Views: 1401

Answers (2)

Peter Rincker
Peter Rincker

Reputation: 45117

Use Tim Pope's surround.vim plugin!

To surround a word with + signs:

ysiw+

Upvotes: 2

steffen
steffen

Reputation: 16948

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>

Upvotes: 5

Related Questions