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?
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
:%s/$/$/
:g/^\w/s/^/\r/
ggddGp
:g/^\w/,/^$/-1join!
:%sort
:%s/\$/\r/g
:g/^$/d
def a():
pass
def b():
pass
def c():
pass
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With