Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort function by name in vim

Tags:

python

vim

Vim can sort lines using "sort" command. I'd like to sort functions in source code using vim. For example: before

def a():
    pass
def c():
    pass
def b():
    pass

after:

def a():
    pass
def b():
    pass
def c():
    pass

Can I do that?

like image 256
monax Avatar asked Feb 14 '12 11:02

monax


3 Answers

For things like:

def a():
    stmt1

    stmt2
def b():
    stmt3

Or C:

void a()
{
    stmt1;

    stmt2;
}

void b()
{
    stmt3;
}

You would need enough semantic knowledge to determine that the empty space between stmt1 and stmt2 is still part of a.

For python this means you read ahead to find the first line that is not either blank or indented. You would also need to account for nested indentation (when functions are part of a class or module and the def is already indented).

For C you need to read ahead until the matching end brace -- which means you would need to account for nested braces.

There is a similar topic regarding C++ that has been unanswered: Automatically sort functions alphabetically in C++ code

I believe this is non-trivial in the general case and you would be better off using yacc or some other semantic parser. You could also manually add markers for beginning and end and do something similar to kev's suggestion.

MaRkNeXt
def a():
    stmt1

    stmt2
MaRkNeXt
def b():
    stmt3
MaRkNeXt

Then something like:

:%s/$/$/
:g/^MaRkNeXt/,/MaRkNeXt/-1join!
:%sort
:%s/\$/\r/g
:g/MaRkNeXt/d
like image 188
RunHolt Avatar answered Nov 20 '22 21:11

RunHolt


Do following command(with confidence):

:%s/$/$/
:g/^\w/s/^/\r/
ggddGp
:g/^\w/,/^$/-1join!
:%sort
:%s/\$/\r/g
:g/^$/d

Output:

def a():
    pass
def b():
    pass
def c():
    pass
like image 28
kev Avatar answered Nov 20 '22 19:11

kev


An alternate approach might be to use the vim Taglist plugin. Which is the top rated and most downloaded plugin for vim.

http://vim-taglist.sourceforge.net/

Then you can easily view the functions ordered alphabetically or in the order they are defined.

By adding the following line to your vimrc file, the default order will be alphabetical.

let Tlist_Sort_Type = "name"

You can press the 's' key in the Taglist tab to toggle the order.

search for "Tlist_Sort_Type" in the link below for the official docs:

http://vim-taglist.sourceforge.net/manual.html

like image 25
AJ Dhaliwal Avatar answered Nov 20 '22 19:11

AJ Dhaliwal