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?

1

2 Answers 2

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
1
  • 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, 2023 at 8: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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.