Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable error messages when a substitution fails inside a Vim function?

Tags:

vim

I have a dead simple function in Vim that cleans source code by calling :retab and removing trailing whitespace, like so:

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

If my source code has no trailing whitespace, I get the following error messages:

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

So for my purposes, I either need to tell the substitution command that match errors should be silent, or tell the function invocation to ignore errors, or something else. How do I surpress error messages on substitution failure?

like image 292
Steve Hollasch Avatar asked Jun 27 '15 22:06

Steve Hollasch


People also ask

How do you call a function in Vim?

Calling A Function Vim has a :call command to call a function. The call command does not output the return value. Let's call it with echo . To clear any confusion, you have just used two different call commands: the :call command-line command and the call() function.

How do I comment in a Vim script?

Using the up and down arrow key, highlight the lines you wish to comment out. Once you have the lines selected, press the SHIFT + I keys to enter insert mode. Enter your command symbol, for example, # sign, and press the ESC key. Vim will comment out all the highlighted lines.


1 Answers

You can try add the 'e' option to the substitute or use :silent! as a prefix to any command

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

Notice:

You'll need to use :silent!, as :silent only removes normal messages (and only up to the first error, subsequent messages will all be shown)---comment of @Marth, Thanks!

like image 158
Eric Tsui Avatar answered Oct 19 '22 06:10

Eric Tsui