What Vim command(s) can be used to quote/unquote words?

surround.vim is going to be your easiest answer. If you are truly set against using it, here are some examples for what you can do. Not necessarily the most efficient, but that's why surround.vim was written.

  • Quote a word, using single quotes
    ciw'Ctrl+r"'
    • ciw - Delete the word the cursor is on, and end up in insert mode.
    • ' - add the first quote.
    • Ctrl+r" - Insert the contents of the " register, aka the last yank/delete.
    • ' - add the closing quote.

  • Unquote a word that's enclosed in single quotes
    di'hPl2x
    • di' - Delete the word enclosed by single quotes.
    • hP - Move the cursor left one place (on top of the opening quote) and put the just deleted text before the quote.
    • l - Move the cursor right one place (on top of the opening quote).
    • 2x - Delete the two quotes.

  • Change single quotes to double quotes
    va':s/\%V'\%V/"/g
    • va' - Visually select the quoted word and the quotes.
    • :s/ - Start a replacement.
    • \%V'\%V - Only match single quotes that are within the visually selected region.
    • /"/g - Replace them all with double quotes.

Quote a word, using single quotes

ciw'Ctrl+r"'

It was easier for me to do it this way

ciw '' Esc P

Here's some mapping that could help:

:nnoremap <Leader>q" ciw""<Esc>P
:nnoremap <Leader>q' ciw''<Esc>P
:nnoremap <Leader>qd daW"=substitute(@@,"'\\\|\"","","g")<CR>P

If you haven't changed the mapleader variable, then activate the mapping with \q" \q' or \qd. They add double quote around the word under the cursor, single quote around the word under the cursor, delete any quotes around the word under the cursor respectively.


The macro ways !

  1. press q and q for recording into q register (we use "q" as shortcut to remember "quotes").

  2. press shift + b move cursor to front of current word

  3. press i type ' (a single quotes)

  4. press esc then press e to move to end of word

  5. press a then press ' again to surround the word with quotes.

  6. press esc to get into normal mode.

  7. finally press q to record it into q register.

How to use

  1. Move cursor to a desired word.
  2. Press @q to surround a word with quotes.
  3. Press @@ if you want repeat it into another word.

You can alter step 4 with anything you like {a line, a word until found some character, etc}.

Make recorded macro persistent

  1. open .vimrc
  2. go to end of file
  3. change to insert mode. type this to make it persistent:
let @q='ctrl + r ctrl + r q'
  1. save and quit

  2. open your files, go to some words

  3. now press @q

if you do it correctly, magic things should appear in your words.

You can apply this to other macros you loved.