Search code examples
sortingvim

How to sort comma separated words in Vim


In Python code, I frequently run into import statements like this:

from foo import ppp, zzz, abc

Is there any Vim trick, like :sort for lines, to sort to this:

from foo import abc, ppp, zzz

Solution

  • Yep, there is:

    %s/import\s*\zs.*/\=join(sort(split(submatch(0), '\s*,\s*')),', ')
    

    The key elements are:

    To answer the comment, if you want to apply the substitution on a visual selection, it becomes:

    '<,'>s/\%V.*\%V\@!/\=join(sort(split(submatch(0), '\s*,\s*')), ', ')
    

    The new key elements are this time:

    • :h /\%V that says the next character matched shall belong to the visual selection
    • :h /\@! that I use, in order to express (combined with \%V), that the next character shall not belong to the visual selection. That next character isn't kept in the matched expression.

    BTW, we can also use s and i_CTRL-R_= interactively, or put it in a mapping (here triggered on µ):

    :xnoremap µ s<c-r>=join(sort(split(@", '\s*,\s*')), ', ')<cr><esc>