4

Is there any way to sort multiline imports with vim built-in functionality (alphabetically)?

E.g.

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

Should become:

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

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

romanofski
  • 1,122
  • 1
  • 12
  • 18
  • Similar question: http://stackoverflow.com/questions/11531073/how-do-you-sort-a-range-of-lines-by-length – pb2q Aug 27 '12 at 01:18
  • I think when you start to want to order your imports alphabetically, you may be a little too far on the "polishing code" road. :) – Tshirtman Aug 28 '12 at 15:53

2 Answers2

5

Vim can only sort by line. So you can

  • replace \\\n to |
  • sort
  • replace | to \\\n

Try this:

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

Note: \@<= is the same as \zs here.

kev
  • 155,172
  • 47
  • 273
  • 272
  • I understand. So all you do is, "marking" all newline separators with a "|", which also joins all lines. Now I can sort. The third line, simply replaces all "markers" with the previous newline separators? Seems to be good enough for me :) Cheers!!! – romanofski Aug 27 '12 at 01:54
  • ugly as it is, this is what I used today. Perhaps... a plugin should be made :) – sehe Mar 08 '13 at 13:07
1

Probably it is not fully relevant but this question is among first Google hits for vim sort python imports, so I'll leave it here:

If you don't worry about multiline imports but want to handle both import xyz and from xyz import xyz forms then the following command will help you:

:sort /[if][^ ]*/

This means "ignore anything matching the pattern and sort by what comes next".

MarSoft
  • 3,555
  • 1
  • 33
  • 38