Reordering methods using vim

Tag: vim Author: Jevon Date: 2009-07-11

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

Best Answer

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.

comments:

You, sir, just blew my mind :)
+1 for complete awesomeness, is there a way to solve this without the G key? so it works in context of a big class
wow :)
You can use dap}p (replace G with } to move to the next method instead of the end of the file, and thus handle the situation where there is more code after the second method.
Explaining dap: The 'a' character, in visual mode or after an operator, allows you to select an object. p stands for paragraph, so dap = delete a paragraph. You could say das to delete a sentence, and so on. Look up text object selection in vim help for more.

Other Answer1

Similar to Spatz's

d}}p

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

Other Answer2

Found another method ( from godlygeek on #vim ):

with:

def function():
    first
    first
    first

def lol():
    second
    second
    second

From line 1, count up until the 'def lol', which is 5. Then:

:1,5m$

Other Answer3

A couple of ways off the top of my head. You could say

5dd/end[enter key]pO

Deletes five lines, searches for end, places the lines underneath, adds a space.

If you have VimRuby installed, I believe you can use % to jump between def and end. In that case, you could say

v%x5jpO

Edit: I defer to spatz on this :P

Other Answer4

From line 1, 5ddGp , or 5dd:5p is the most concise/shortest I can think of.

comments:

any way to avoid the line counting in the head problem?

Other Answer5

personally, I would go '4dd' then down under bar and press 'p', but I'm not a vim guru