Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering methods using vim

Tags:

vim

I have 2 methods in a source file:

def Foo
  puts "hello"
  puts "bar" 
end 

def Bar
  puts "hello"
  puts "bar" 
end

I would like to swap the order of the methods, so Bar is first.

Assuming the cursor is on the d in def Foo, the simple way is to:

shift v -> jjjj -> d -> jjj -> p -> O -> esc 

But that feels a little long winded and does not account well for arbitrarily long methods:

What is the most efficient way to do this in Vim, keystroke wise?

EDIT Keep in mind, I would like the solution to account for a situation where the methods are in a context of a big class, so G is probably best avoided

like image 888
Sam Saffron Avatar asked Nov 29 '22 20:11

Sam Saffron


2 Answers

Assuming the cursor is somewhere in the first method, press dap}p and they should be swapped.

What dap does is simply "delete a paragraph". Try :help object-select to learn other way of deleting/selecting text objects in VIM.

EDIT: Replaced G with } in the command.

like image 67
drrlvn Avatar answered Dec 05 '22 00:12

drrlvn


Similar to Spatz's

d}}p

delete to the next blank line (below Foo), skip to the next blank line (below Bar), paste.

like image 33
glenn jackman Avatar answered Dec 05 '22 00:12

glenn jackman