在Vim中如何对逗号分隔的单词进行排序

11
在Python代码中,我经常遇到像这样的导入语句:
from foo import ppp, zzz, abc

有没有类似于:sort对于行的Vim技巧,可以将其排序成这样:

from foo import abc, ppp, zzz
5个回答

15

没错,有这个东西:

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

关键要素包括:

回答评论,如果你想对视觉选择应用替换,则变成:

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

新的关键元素这一次是:

  • :h /\%V,表示下一个匹配的字符应该属于可视选择
  • :h /\@!我使用它来表达(与\%V结合),下一个字符不应属于可视选择。那个字符不会被包含在匹配表达式中。

顺便一提,我们还可以交互地使用si_CTRL-R_=,或将其放入映射(此处触发为µ):

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

我能否将逗号分隔的列表部分进行可视化标记,并对其应用此操作?这可能更通用,因为我可以将其应用于其他类型的Python代码(例如实际列表的元素)。 - Ashwin Nanjappa
在我的系统(Debian 10)中,键入“:h sub-replace-=”比“:h s/=”给出了更好的结果。它应该是相同的,但是... - Daniel Bandeira

4

或者,您可以执行以下步骤:

  1. Move the words you want to sort to the next line:

    from foo import 
    ppp, zzz, abc
    
  2. Add a comma at the end of the words list:

    from foo import 
    ppp, zzz, abc,
    
  3. Select the word list for example with Shift-v. Now hit : and then enter !xargs -n1 | sort | xargs. It should look like this:

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

    Hit Enter.

    from foo import 
    abc, ppp, zzz,
    
  4. Now remove the trailing comma and merge the word list back to the original line (for example with Shift-j).

    from foo import abc, ppp, zzz
    

以下是可能对您有用的Vim插件:


1
AdvancedSorters插件看起来非常有用。谢谢! :) - Ashwin Nanjappa
@AshwinNanjappa 很高兴我能帮到你 ;) - Mateusz Piotrowski

2
我来这里是为了寻找一种快速排序逗号分隔列表的方法,通常情况下,例如。
    relationships = {
        'project', 'freelancer', 'task', 'managers', 'team'
    }

我的习惯是用换行符替换空格并调用 shell sort,但那太麻烦了。
最终我找到了 Chris Toomey 的 `sort-motion` 插件,正好符合我的需求:https://github.com/christoomey/vim-sort-motion。非常推荐。

1

0
在可视模式下选择逗号分隔的文本,:,然后运行此命令:
'<,'>!tr ',' '\n' | sort -f | paste -sd ','

-提示 此评论


macOS/ BSD 版本的 paste 命令会报错,错误信息为 usage: paste [-s] [-d delimiters] file ...。为了确保它在标准输入上正常工作,需要在末尾加上一个 -,例如 !tr ',' '\n' | sort -f | paste -sd ',' - oschrenk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接