当Vim函数内的替换失败时,如何禁用错误消息?

时间:2015-06-27 22:01:43

标签: vim

我在Vim中有一个简单的死函数,它通过调用:retab和删除尾随空格来清理源代码,如下所示:

:function CodeClean()
:  retab
:  %s/\s\+$//
:endfunction

如果我的源代码没有尾随空格,我会收到以下错误消息:

Error detected while processing function CodeClean:
line    2:
E486: Pattern not found: \s\+$

因此,出于我的目的,我要么告诉匹配错误的替换命令应该是静默的,或者告诉函数调用忽略错误,或者别的什么。如何在替换失败时抑制错误消息?

2 个答案:

答案 0 :(得分:9)

您可以尝试添加' e'替换选项或使用:silent!作为任何命令的前缀

:%s/\s\+$//e
:silent! %s/\s\+$//  

注意:

  

您需要使用:silent!,as:silent仅删除普通邮件   (并且只有第一个错误,后续消息都将是   显示)--- @Marth的评论,谢谢!

答案 1 :(得分:5)

使用e标记,即:%s/\s\+$//e

来自:h s_flags

[e]     When the search pattern fails, do not issue an error message and, in
        particular, continue in maps as if no error occurred.  This is most
        useful to prevent the "No match" error from breaking a mapping.  Vim
        does not suppress the following error messages, however:
            Regular expressions can't be delimited by letters
            \ should be followed by /, ? or &
            No previous substitute regular expression
            Trailing characters
            Interrupted
        {not in Vi}

或者您可以使用:silent! %s/\s\+$//忽略所有错误消息。