Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap some text in vim with '', "", (), [], {}, etc?

Tags:

vim

I'm new to vim. And I'm pressing too many buttons doing basic text wrapping:

  1. string -> "string"
  2. long string with many words -> 'long string with many words'
  3. a + b * c -> (a + b) * c
  4. (elem0, elem1, elem2) -> [elem0, elem1, elem2] (optional)

I'm doing all that manually: go to begin, Insert mode, press key, Normal mode, (the same for second character).

How to do it faster? E.g.: visually select the text, smart-wrap it with what you need. Or even without visual selection.

like image 453
Mikhail M. Avatar asked Oct 24 '25 09:10

Mikhail M.


2 Answers

  1. string -> "string"

    ciw"<C-r>""
    
  2. long string with many words -> 'long string with many words'

    veeeeec'<C-r>"'
    
  3. a + b * c -> (a + b) * c

    vwwc(<C-r>")
    
  4. (elem0, elem1, elem2) -> [elem0, elem1, elem2] (optional)

    "edibxs[<C-r>e]
    

    That one is a bit more complicated:

    "edib        cut the content of those parentheses into
                 an arbitrary register, here I used "e
    
    xs           cut the closing parenthese then cut the opening one
                 and enter insert mode
    
    [<C-r>e]     insert the opening bracket, followed by the content of
                 register e, followed by the closing bracket
    

But yeah, use Tim Pope's Surround.

like image 58
romainl Avatar answered Oct 27 '25 01:10

romainl


You can use visuall mode for this. For example you have string. ^ will be cursor positioning. Start in normal mode

1. string # press viwc(your word will be selected and deleted to unnamed register)
   ^
2. # press " and then <C-r>"(this will paste your selected text) and then press again "

This method can be with any surrounding parenthesis or brackets and with any number of words. you just need to change your selection in visual mode

like image 22
Sardorbek Imomaliev Avatar answered Oct 27 '25 00:10

Sardorbek Imomaliev