vim编辑器,使用日志文件导航源代码

时间:2011-07-07 09:17:56

标签: logging vim

这个问题可能非常抽象,所以请事先道歉。

我有一个日志文件,其中包含符合某种模式的行(文件名,行,函数,跟踪语句)。例如

file1.cpp, 12, function1, "we are in function 1"
file2.cpp, 104, add, "add function"
another_file.cpp, 300, function2, "This is a trace"

我想要的是将vim编辑器分成两个窗口。一个窗口有日志文件,每当我将光标移动到一条跟踪线时,另一个窗口将以正确的代码行打开真实文件。

例如,在顶部窗口中,我的光标位于行

file2.cpp, 104, add, "add function"

和第二个(vim在两个窗口中拆分)窗口打开第104行的file2.cpp(在第二个窗口的中心)。

是否有机会使用结构化文件(日志文件)作为源代码的“导航器”? 如果是的话,我们怎么能在vim中做到这一点?如果没有,让我们做吧! (但我不想重新发明轮子:-))

3 个答案:

答案 0 :(得分:5)

您所描述的内容在Vim中称为quickfix窗口。您可能会从:make命令的结果中熟悉它。您可以使用:cfile打开quickfix窗口。格式由errorformat变量确定。查看有关这些内容的Vim帮助以获取更多详细信息。

对于您的示例(文件名,行,函数,跟踪语句),您可以这样做:

:set errorformat=%f\\\,\\\ %l\\\,\\\ %m
:cfile log.txt

免费的三重反斜杠用来绕过:set命令中的转义序列。格式转换为%f\,\ %l\,\ %m

或者,您可以以gcc格式输出日志。在这种情况下,默认的errorformat将能够解析它,您只需使用:cfile命令打开它。

加载后,您可以使用:clist:copen

查看日志

答案 1 :(得分:2)

这是一项非常重要的练习,但肯定可以做到。

你需要一个autocmd来调用某些操作的函数(特别是当光标移动时),如下所示:

autocmd CursorMoved mylogfile.txt call LogFileUpdate()

您可能还想使用CursorMovedI和其他人,但我会将其作为练习留给您...请参阅:

:help autocommand-events

在该功能中,您执行'魔术'。这是未经测试的,没有错误检查;它旨在为您提供一些可以玩的东西,并从中构建您的脚本。

function! LogFileUpdate()
    " Make sure the cursor stays put
    let saved_view = winsaveview()

    " This is a slightly lazy way of making a consistent split: you could do something
    " clever here, working out whether there is a split at present and re-using it:

    " Close all other windows
    only

    " Get the current line into a variable
    let current_line = getline('.')
    " Split on commas:
    let parts = split(current_line, ',')

    " Get the filename and line number (removing leading and trailing spaces)
    let filename = substitute(parts[0],'^\s*\(.*\)\s*$','\1','')
    let number_str = substitute(parts[1],'^\s*\(.*\)\s*$','\1','')

    " Open the file at the required line number
    exe 'sp +'.number_str filename
    " Set the file type (doesn't seem to happen automatically in a CursorMoved autocmd)
    filetype detect

    " Switch back to the log file window
    wincmd w

    " Restore the cursor to its original position
    call winrestview(saved_view)
endfunction

答案 2 :(得分:0)

使用Vim在源代码中导航的常用方法是使用ctags

见:

ctags是一个外部程序,它将生成变量,函数等的标识符列表,然后Vim将使用该列表跳转到函数的定义。

要生成tag文件,只需在项目目录中运行ctags -R *.cpp,*.hpp即可。它将递归地索引每个cpp和hpp文件。

正确生成标记文件并在Vim的标记路径中,当光标位于“时,您可以”跳转到 CTRL + ] 的标识符functionName”。 ctags考虑了参数的数量,但我认为只使用它应该起作用的名称。

然后,您可以使用 CTRL + T CTRL + o 返回日志文件。

它无法完全按照您的意愿工作,但您可以在日志文件和代码之间快速来回跳转。

您还可以在StackOverflow上搜索以获取更多信息。

相关问题