Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort methods into alphabetical order in VIM?

Tags:

vim

class MyClass

  def zzz
    # method body
  end

  def aaa
    # method body
  end

end

How would I get VIM to organise these into alphabetical order such that the definition of aaa precedes the definition of zzz?

like image 522
Jack Kinsella Avatar asked Jan 30 '12 13:01

Jack Kinsella


1 Answers

Well you can set up code folding e.g. by indentation, and close those functions/fold, then do it manuall with dd then p but that is not an ideal solution with a large file.

It's not an easy task. You can set up some line-joining, e.g.:

  1. put some specific comment/identifier before every first level def, like

    # DEFINITION

    def zzz

    ...

    end

    # END DEF

  2. then join those lines into one with some multiline regex magic (and/or column editing), using some placeholder which generally does not occur in your code.

  3. then sort it via standard unix sort (e.g. visually select your joined lines, then

    :'<,'>!sort

  4. then split on the inserted pattern...

Still less than ideal, but it can be done...

See this answer too.

like image 188
Zsolt Botykai Avatar answered Nov 15 '22 10:11

Zsolt Botykai