Using a simple mapping and only a couple Vim features, swap types of quotes, i.e. from “foo” to ‘foo’.

I often find myself dealing with Bash or Perl code, and I like to be strict about the type of quotes I use:

Oftentimes, I start writing a chunk of text in single quotes and only later realise I’d like to insert a variable in it. As an example:

my $foo = 'This is foo';
foo='This is foo'

If I’m in the middle of the string, i.e. is, I’d then have to perform some vim gymnastics to perform the swap.

So I’ve automated it. In my ~/.vimrc I have:

" Swap single for double quotes (and the other way around) for this chunk
nnoremap <Leader>' mqva"l:s/\%V"\%V/'/g<CR>`q
nnoremap <Leader>" mqva'l:s/\%V'\%V/"/g<CR>`q
" Add quotes around (at start of, and at end of) visually selected text
vnoremap <Leader>' <Esc>`>a'<Esc>`<i'<Esc>
vnoremap <Leader>" <Esc>`>a"<Esc>`<i"<Esc>

No matter whether I’m in normal mode “inside of” a string, I can hit <Leader>' to swap double quotes for single quotes, or <Leader>" for swapping single quotes to double quotes.

If I’m instead wanting to add quotes to a chunk of text, I can just visually select it and hit <Leader>' to surround it with single quotes, or <Leader>" to surround it with double quotes.

Much simpler than doing it manually.