2

Suppose, I want to wrap a single word with braces in normal mode using keyboard map (say <F5>), I could add the following mapping

:nnoremap <F5> i{<Esc>ea}<Esc>

But, now I want to extend this for visual mode, where I can select some text and wrap it with braces the same way. How do I achieve this?

Rich
  • 31,891
  • 3
  • 72
  • 139

2 Answers2

1

I would do:

vnoremap <F5> c{}<Esc>P
  • c for change
  • {} to insert the braces
  • <Esc> to leave insert mode
  • P to past the text before the closing brace
Vivian De Smedt
  • 16,336
  • 3
  • 18
  • 37
  • It seemed so natural to me to select some text, and then press either { or } to get it surrounded by curly braces that I just did: vnoremap { c{}<EscP and also vnoremap } c{}<EscP And I'll do the same for ( [ " ' – Pierre Sep 29 '23 at 08:25
1

You could start by improving your normal mode mapping:

nnoremap <F5> ciw{<C-r>"}<C-c>

where we:

  1. "change" the current word (which means "cut it into the unnamed register and enter insert mode") with ciw, see :help c and :help text-object,
  2. insert a {,
  3. insert the content of the unnamed register with <C-r>", see :help i_ctrl-r,
  4. insert the closing },
  5. and finally leave insert mode with <C-c>, which has fewer side effects than <Esc>.

Pros:

  • fewer unnecessary mode changes,
  • fewer side effects,
  • cursor can be on any character of the word,
  • more idiomatic.

Cons:

  • none.

From there, it is easy to devise a visual mode mapping by simply removing the iw text object:

xnoremap <F5> c{<C-r>"}<C-c>
romainl
  • 40,486
  • 5
  • 85
  • 117