4

This might be a silly question, or someone may say it lacks research, but I really cannot understand what does the exclamation mark after silent mean.

For example, in the following function that removes extra characters such as ^M:

function! RemoveExtraCharacters()
  let l:initialCol = getcurpos()[2]
  let l:line = getline('.')[0:initialCol-1]

  let l:numRemoved = len(l:line) - len(substitute(l:line, '[^[:print:]\t]', '', 'g'))

  let l:save = winsaveview()
  keeppatterns silent! %s/[^[:print:]\t]//g
  call winrestview(l:save)

  if l:numRemoved != 0
    call cursor(line('.'), (l:initialCol-l:numRemoved))
  endif
endfun
autocmd! BufWritePre * call RemoveExtraCharacters()

You can either use :silent or :silent! as a prefix to any command or you can add the e option to the substitute, which is often easier.

:%s/x/y/ge
:silent! %s/x/y/g
:silent %s/x/y/g

- https://stackoverflow.com/a/1043613

1 Answer 1

6

It's explained in :help :silent

                        *:sil* *:silent* *:silent!*
:sil[ent][!] {command}  Execute {command} silently.  Normal messages will not
            be given or added to the message history.
            When [!] is added, error messages will also be
            skipped, and commands and mappings will not be aborted
            when an error is detected.  |v:errmsg| is still set.
            When [!] is not used, an error message will cause
            further messages to be displayed normally.          

This is one of those examples where punctuation in the argument to :help makes a difference.

  • :help silent takes you to the -silent help topic
  • :help :silent takes you to the :silent command
3
  • Yes, I erroneously tried help silent without the colon, thanks. So it seems :%s/x/y/ge works the same as :silent! %s/x/y/g, but not the same as :silent %s/x/y/g (which is the "weaker" option), right?
    – john c. j.
    Sep 2, 2021 at 21:20
  • 2
    Might want to mention :h help-summary which explains the help topic syntax (:foo, -foo, 'foo', i_foo, etc.)
    – B Layer
    Sep 3, 2021 at 6:23
  • 1
    silent colo mightnotexist will error if there is no colorscheme, silent! colo mightnotexist will not.
    – Maxim Kim
    Sep 3, 2021 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.