代码之家  ›  专栏  ›  技术社区  ›  knipknap

在.vimrc中运行shell脚本(并处理输出)

  •  5
  • knipknap  · 技术社区  · 16 年前

    我正在尝试从.vimrc文件中运行shell脚本(脚本中标记了三个问题):

    function! CheckMe(file)
        let shellcmd = 'checkme '.a:file
    
        " Start the command and return 0 on success.
        " XXX: How do you evaluate the return code?
        execute '!'.shellcmd
        if !result
            return 0
        endif
    
        " Ending up here, the command returned an error.
        " XXX: Where to you get the output?
        let pair = split(output, '\S')
        let line = pair[0]
        let char = pair[1]
    
        " Jump to the errenous column and line.
        " XXX: Why does this not work?
        normal '/\%'.line.'l\%'.char.'c'
        return 1
    endfunction
    

    所以,总结一下,您如何获得脚本的结果/输出,以及为什么跳转语句不起作用?

    其他详细信息:

    • shell脚本成功时返回0,失败时返回1。失败时,脚本将两个数字(行号和列号)打印到stdout,用空格字符分隔。
    • 根据 Vim docs “normal”关键字的参数是“像键入的那样执行”,但显然情况并非如此。当我键入它时(在正常命令模式下,不带“:”前导),它工作得很好,但在脚本(“e78:未知标记”)中不起作用。
    2 回复  |  直到 16 年前
        1
  •  6
  •   ZyX    16 年前
    function! CheckMe(file)
        let shellcmd = 'checkme '.a:file
    
        let output=system(shellcmd)
        if !v:shell_error
            return 0
        endif
    
        " Are you sure you want to split on non-blanks? This 
        " will result in list of blank strings.
        " My variant:
        let [line, char]=split(output)
    
        " Normal is not an execute: this is what it will do:
        " «'/» means «Go to mark /», produces an error E78 because /
        " is not a valid symbol for mark. Than normal stops after error occured.
        " If you need to use variables in nomal use «execute 'normal '.ncmd».
        " And you can not use «normal» to perform search
        execute '/\%'.line.'l\%'.char.'c'
        " or
        call setpos('.', [0, line, char, 0])
        return 1
    endfunction
    

    根据vim文档,“normal”关键字的参数是“像键入的那样执行”,但显然情况并非如此。当我键入它时(在正常命令模式下,不带“:”前导),它工作得很好,但在脚本(“e78:未知标记”)中不起作用。

    只需键入“_~”/“即可获得此错误。

        2
  •  6
  •   Dennis Williamson    16 年前

    我想你想用 system() function 而不是 ! 外壳命令。

    从链接页:

    The result is a String.  Example:
                :let files = system("ls " .  shellescape(expand('%:h')))
    

    The resulting error code can be found in |v:shell_error|.
    

    所以你的 output 将来自系统调用和您的 result 将来自 v:shell_error . 那你的跳跃就可以了。