Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy built-in way to delete the first and last line of a block in vim?

Tags:

vim

Quite a common task in programming is to remove the condition on the current block.

In vim, is there an easy way to delete the first line (the 'if' statement) and last line (the closing curly brace) of the current block and perhaps reindent accordingly. If there is no simple key combination for this built in, what is a straightforward way to script it?

Thinking about this a bit further, of course the condition on the if statement may span multiple lines so presumably a script is required to capture this completely. However, for my code just deleting the first and last lines would capture 95% of cases.

like image 598
jpickard Avatar asked Dec 28 '22 14:12

jpickard


2 Answers

Possible solution

yiBvaBVpgv<
  • yiB yanks the inner block
  • vaBV viaually select a block, then select it linewise
  • p paste over visually selected text
  • gv< reselect text and de-indent

Surround like mappings aka delete surrounding block:

nnoremap dsB yiBvaBVpgv<

ib provided a shorter solution. This solution will not mutate the visual marks: '<, '>

diB]pkdk
  • diB deletes the current inner block
  • ]p paste the newly deleted text below the end of the block but adjust the indent.
  • kdk move up a line and then delete 2 lines up thereby deleting the start and end of the block.
like image 135
Peter Rincker Avatar answered Jan 30 '23 02:01

Peter Rincker


How about something like di{ dk k "2p? Or a little more elegant, <i{ di{ dk k "2p. Note that you have to be inside the block for this to work — if you're on the opening or closing lines of the block, you'll affect the surrounding block instead.

like image 27
hobbs Avatar answered Jan 30 '23 01:01

hobbs