Sort by name in vim

Vim can sort strings using the sort command. I would like to sort the functions in the 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 it?

+3
source share
3 answers

For things like:

 def a(): stmt1 stmt2 def b(): stmt3 

Or C:

 void a() { stmt1; stmt2; } void b() { stmt3; } 

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

For python, this means that you are reading ahead to find the first line that is not empty or indented. You will also need to consider nested indentation (when functions are part of a class or module, and def already indented).

For C, you need to read ahead while matching the parenthesis β€” this means that you will need to consider nested braces.

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

I believe this is not trivial in the general case, and you would be better off using yacc or some other semantic parser. You can also manually add markers for start and end and do something similar to the kev clause.

 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 
+6
source

Run the following command (with confidence):

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

Conclusion:

 def a(): pass def b(): pass def c(): pass 
+1
source

An alternative approach would be to use the vlist taglist plugin. Which is the most popular and downloaded plugin for vim.

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

You can then easily browse functions alphabetically or in the order in which they are defined.

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

let Tlist_Sort_Type = "name"

You can press the 's' key on the Taglist tab to switch the order.

Find "Tlist_Sort_Type" in the link below for white papers:

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

+1
source

All Articles