Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to refactor a Ruby ‘if’ statement into one-line shorthand form in Vim?

Tags:

vim

I have the following Ruby code:

if some_cond && another
  foo_bar
end

and I want to change it to:

foo_bar if some_cond && another

What are the most idiomatic ways to do that in Vim?

like image 712
Sławosz Avatar asked Dec 27 '22 14:12

Sławosz


1 Answers

Assuming that the cursor is located at the if-line prior to refactoring (not necessarily at the beginning of that line), I would use the following sequence of Normal-mode commands:

ddjVpkJ<<

or this chain of Ex commands:

:m+|-j|<|+d

Here the if-line is first moved down one line by the :move + command. The :move command cuts a given range of lines (the current line, if not specified) and pastes it below the line addressed by the argument. The + address is a shorthand for .+1 referring to the next line (see :help {address}).

Second, the line containing the body of the conditional statement is joined with the just moved if-line. The :join command concatenates a given range of lines into a single line. The - range is a shortened form of the .-1 address referring to the line just above the cursor (see :help {address}).

Third, the newly joined line is unindented by one shiftwidth using the :< command.

Finally, the remaining end-line, which can now be addressed as +, is removed by the :delete command.

like image 149
ib. Avatar answered Apr 29 '23 02:04

ib.