Daniel Diniz
Daniel Diniz

Reputation: 3

Adding a char to beginning and end of a word in VIM

'Enveloping' a word or a string in a given character is one of my most executed actions in VIM.

Most common char combinations (added at beginning and end, respectively): <>, (), '', "", **, __,--, etc...

Is there a native way of doing this in VIM? If not, how could we set up a macro for this?

Upvotes: 0

Views: 700

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11800

You can create a function abstracting all the chang inner word:

if !exists('*AddSingleQuotes')
    function! AddSingleQuotes()
        exec "normal! ciw''\<Esc>P"
    endfunction
endif
nmap <Leader>q :call AddSingleQuotes()<CR>

And also modify to add double quotes:

if !exists('*AddDoubleQuotes')
    function! AddDoubleQuotes()
        exec "normal! ciw\"\"\<Esc>P"
    endfunction
endif
nmap <Leader>q :call AddDoubleQuotes()<CR>

NOTE: the if !exists part ensures vim will not load the function more than once, even if you reload your vimrc.

Upvotes: 1

romainl
romainl

Reputation: 196566

The most "native" way to surround a word with a given pair of characters is to:

  1. change the word with ciw (the word is put into register " by default),
  2. insert the opening character,
  3. insert the content of register " with <C-r>",
  4. insert the closing character,
  5. go back to normal mode with <Esc>.

In short:

ciw(<C-r>")<Esc>

This is the most efficient you can get without making custom mappings or installing plugins like Surround or Sandwich.

Upvotes: 2

Related Questions