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" 

def Bar
  puts "hello"
  puts "bar" 

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.


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


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 ):


def function():

def lol():

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


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


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.


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