在vim中按名称对函数进行排序 [英] sort function by name in vim

查看:37
本文介绍了在vim中按名称对函数进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vim 可以使用 "sort" 命令对行进行排序.我想使用 vim 对源代码中的函数进行排序.例如:之前

Vim can sort lines using "sort" command. I'd like to sort functions in source code using vim. For example: before

def a():
    pass
def c():
    pass
def b():
    pass

之后:

def a():
    pass
def b():
    pass
def c():
    pass

我可以这样做吗?

推荐答案

对于诸如:

def a():
    stmt1

    stmt2
def b():
    stmt3

或 C:

void a()
{
    stmt1;

    stmt2;
}

void b()
{
    stmt3;
}

您需要足够的语义知识来确定 stmt1 和 stmt2 之间的空白区域仍然是 a 的一部分.

You would need enough semantic knowledge to determine that the empty space between stmt1 and stmt2 is still part of a.

对于python,这意味着您要提前阅读以找到既不是空白也不是缩进的第一行.您还需要考虑嵌套缩进(当函数是类或模块的一部分并且 def 已经缩进时).

For python this means you read ahead to find the first line that is not either blank or indented. You would also need to account for nested indentation (when functions are part of a class or module and the def is already indented).

对于 C,您需要提前阅读直到匹配的结束大括号——这意味着您需要考虑嵌套的大括号.

For C you need to read ahead until the matching end brace -- which means you would need to account for nested braces.

有一个关于 C++ 的类似主题尚未得到解答:在 C++ 代码中按字母顺序自动排序函数

There is a similar topic regarding C++ that has been unanswered: Automatically sort functions alphabetically in C++ code

我相信在一般情况下这不是微不足道的,你最好使用 yacc 或其他一些语义解析器.您还可以手动添加开始和结束标记,并执行类似于 kev 建议的操作.

I believe this is non-trivial in the general case and you would be better off using yacc or some other semantic parser. You could also manually add markers for beginning and end and do something similar to kev's suggestion.

MaRkNeXt
def a():
    stmt1

    stmt2
MaRkNeXt
def b():
    stmt3
MaRkNeXt

然后是这样的:

:%s/$/$/
:g/^MaRkNeXt/,/MaRkNeXt/-1join!
:%sort
:%s/\$/\r/g
:g/MaRkNeXt/d

这篇关于在vim中按名称对函数进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆