我在Vim中有一个简单的死函数,它通过调用:retab和删除尾随空格来清理源代码,如下所示:
:function CodeClean()
: retab
: %s/\s\+$//
:endfunction
Run Code Online (Sandbox Code Playgroud)
如果我的源代码没有尾随空格,我收到以下错误消息:
Error detected while processing function CodeClean:
line 2:
E486: Pattern not found: \s\+$
Run Code Online (Sandbox Code Playgroud)
所以对于我的目的,我要么告诉匹配错误的替换命令应该是静默的,或者告诉函数调用忽略错误,或者别的什么.如何在替换失败时压制错误消息?
Eri*_*sui 10
您可以尝试将"e"选项添加到替换中,或者将其:silent!
用作任何命令的前缀
:%s/\s\+$//e
:silent! %s/\s\+$//
Run Code Online (Sandbox Code Playgroud)
注意:
你需要使用:silent!,as:silent只删除正常的消息(只有第一个错误,后面的消息才会显示)--- @Marth的评论,谢谢!
使用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}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用:silent! %s/\s\+$//
忽略所有错误消息。