Replacing matching {brackets} with do / end in Vim (Ruby)

Does anyone have a plugin or macro to replace the corresponding { curly brackets } with do and end in Vim? It is preferable to use a one-line operator as follows:

 foo.each { |f| f.whatever } 

in

 foo.each do |f| f.whatever end 

I could make a macro myself for this one case, but I would like something that could also handle existing multi-line, potentially complex blocks, for example:

 foo.each { |f| f.bars.each { |b| b.whatever } hash = { a: 123, b: 456 } } 

in

 foo.each do |f| f.bars.each { |b| b.whatever } hash = { a: 123, b: 456 } end 

I looked through vim-surround and rails.vim and did not find the path using.

+6
source share
2 answers

There is a Vim plugin called Vim Blockle that performs this function.

After installing the plugin, place the cursor on { } do or end and press <Leader>b to change the block styles.

+7
source

I assume that in your multi-line example, the output will look like this:

 foo.each do |f| f.bars.each do |b| b.whatever end hash = { a: 123, b: 456 } end 

that is, you should also replace f.bars.each{...} .

if this is the goal, try the following:

 gg/each\s*{<enter>qqf{%send<esc><co>sdo<esc> nq200@q 

brief explanation:

 gg " move cursor to top /each\s*{<enter> " search pattern we want qq " start recording macro to register q f{ " move to { %send<esc> " move to closing {, and change it to "end", back to normal <co>sdo " back to beginning { and change it into "do" <esc>nq " back to normal, and go to next match, stop recording 

then you can do, for example, 200@q and check the result.

0
source

All Articles