1

I have ths line in my .vimrc:

map gu :%s/\s\+$//<enter> :w<enter>

to remove trailing spaces and saving the file in the same time.

When there are trailing spaces in the file, it works OK (it removes the spaces and saves the file), but when there are not trailing spaces it doesn't save the file, it just says Pattern not found: \s+$.

NOTE: I found this, but I'm curious about the way I'm asking.

Community
  • 1
  • 1
tirenweb
  • 30,963
  • 73
  • 183
  • 303
  • i think it is also problematic for files where you have no write permissions - I simply do a write afterwards by hand – epsilonhalbe Jun 21 '12 at 21:12

1 Answers1

7

Add an e to the search flags to suppress error messages:

map gu :%s/\s\+$//e<enter> :w<enter>

From :help substitute:

[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
pb2q
  • 58,613
  • 19
  • 146
  • 147