Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to surround visual block with quotes (or similar) in vim

Tags:

vim

Given a visual block selection in Vim, how does one wrap quotes around it?

I often find myself with the objective to take a list of fields - such as

name
address
telephone

to transform it into something like this in my code

declare name      = 'name';
declare address   = 'address';
declare telephone = 'telephone';

I'm comfortable getting to the following stage with a series of visual block selects and changes, etc.

declare name      = 'name
declare address   = 'address
declare telephone = 'telephone

but how do I do the last part inserting the trailing quote and semi-colon in an efficient way? Having to do an ex-mode substitute here somehow feels wrong.

Edit: I recall Damian Conway demonstrating this here - "More Instantly Better Vim" - 37:00. It's hard to tell but is he taking advantage of something in the dragvisuals.vim plugin or something native to vim when he appends the last quotes?

like image 780
shalomb Avatar asked Sep 13 '25 05:09

shalomb


1 Answers

Visual Block

You can use $ and A with visual block mode. You can probably use gv to restart the Visual block mode up again.

gv$A';<esc>

Substitution

Visually select your lines then do :s/$/';

Better Substitution

Forget doing the visual block business and other stuff. Just start with your list and do the following substitution:

:%s/.*/declare & = '&';/

You could do a visual range if you rather. If you want to keep indention at the beginning of the line do: :%s/^\s*\zs.*/declare & = '&'/

Sidebar: Alignment

You can use a the plugin, Tabular, to do alignment.

:Tabularize /\zs=

Other alignment plugins are: Align and vim-easy-align.

Conclusion

I prefer the "Better Substitution" method and followed by :Tabularize.

For more information see:

:h visual-block
:h blockwise-operators
:h v_b_A
:h v_b_A_example
:h gv
:h /\zs
:h :s/\&
like image 62
Peter Rincker Avatar answered Sep 16 '25 06:09

Peter Rincker