8

I have this coding in my .vimrc:

enter image description here

If any line contains trailing whitespace, then this function terminates silently, but otherwise I get this error message:

enter image description here

I could add silent! to the autocmd, but I have other code in this function, for which I do not want any error output to be suppressed.

How can I suppress the error message for just this single substitute command?

nst0022
  • 496
  • 3
  • 7

1 Answers1

10

You can silence individual commands inside a function by prepending :silent! just as well, so either :silent! execute or :execute 'silent! %s... would do.

However, you don't need any of this, because :substitute understands a /e flag that suppresses any errors resulting from no pattern matches (cp. :help :s_e).

Also, you only need :execute when you need to interpolate variable contents into a command. Your substitution uses a constant pattern, so you're just making the command more complex (because of the doubling of backslashes) without any benefit:

%s/\s\+$//e

Additional comments on style

  • You don't need the : in :call; this is only needed in (interactive or in a mapping) normal mode to switch to command-line mode. As :autocmd already takes an Ex command, it's superfluous.
  • The == 0 is superfluous as well. 'readonly' is a boolean flag that evaluates to 0 if unset, and 0 evaluates to false in a conditional.
Ingo Karkat
  • 17,819
  • 1
  • 45
  • 61
  • Thanks for your extended explanations. I learned a lot today :-). Just the if will remain as is, for philosophical reasons :-). – nst0022 Nov 07 '18 at 16:35