VIM: Sort python multiline import

Is there a way to sort multi-line imports with vim built-in functionality (in alphabetical order)?

eg.

import Fred import Foo, Baz,\ Bar, Spam, Eggs import Python 

It should become:

 import Foo, Baz,\ Bar, Spam, Eggs import Fred import Python 

I checked: help sort. In particular, pattern matching comes close to what I want, but it leaves the imported classes separate under the sorted block.

+4
source share
2 answers

Vim can only sort by line. So you can

  • replace \\\n with |
  • kind
  • replace | on \\\n

Try the following:

 :%s/\\\@<=\n/| :sort :%s/\\\@<=|/\r 

Note. \@<= here \zs .

+5
source

Perhaps this is not entirely relevant, but this question relates to the first Google hits for vim sort python imports , so I will leave it here:

If you are not worried about multi-line import, but want to process import xyz and from xyz import xyz forms, then the following command will help you:

 :sort /[if][^ ]*/ 

This means "ignore everything that matches the pattern and sort by the following."

+1
source

All Articles