How to sort commas in Vim

In Python code, I often run import statements such as this:

from foo import ppp, zzz, abc

Is there any Vim trick, for example :sortfor strings, to sort by this address:

from foo import abc, ppp, zzz
+4
source share
4 answers

Yes there is:

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

The key elements are:

To respond to the comment, if you want to apply the replacement in a visual selection, this would be:

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

New key elements this time:

  • :h /\%Vwhich states that the next matching character must belong to the visual selection
  • :h /\@!, , ( \%V), . .

BTW, s i_CTRL-R_= ( ยต):

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

:

  • , , :

    from foo import 
    ppp, zzz, abc
    
  • :

    from foo import 
    ppp, zzz, abc,
    
  • , , Shift - v. :, !xargs -n1 | sort | xargs. :

    :'<,'>!xargs -n1 | sort | xargs
    

    Enter.

    from foo import 
    abc, ppp, zzz,
    
  • (, Shift - j).

    from foo import abc, ppp, zzz
    

Vim, :

+2

, , , , ,

    relationships = {
        'project', 'freelancer', 'task', 'managers', 'team'
    }

, / , .

Chris Toomey sort-motion, : https://github.com/christoomey/vim-sort-motion. .

0

Source: https://habr.com/ru/post/1684733/


All Articles