First and foremost, for most cases like this you'll want to use a command! instead of an abbreviation. This allows you to create a custom command-line command that will not mess up other inputs.
However, you can't override default vim commands with command!. So an abbreviation is probably acceptable here.
Abbreviations can use the special <expr> argument which allows an expression to be used in the right hand side. Using this we can construct an abbreviation that only triggers at the beginning of the line:
cnoreabbrev <expr> w (getcmdtype() == ':' && getcmdline() =~ '^w$')? 'call SaveBuffer()' : 'w'
getcmdtype() == ':' Ensures that you are in command-line mode and not search mode (or others).
getcmdline() Gets the text that is currently in the command line.
=~ '^w$' A regex that only matches if there is a "w" and nothing else.
()? '' : '' A turnary statement that will use the first '' if the expression in the parentheses is true, or the second '' if it is false.
This abbreviation will technically trigger all the time, but in the other cases it simply replaces w with w so no harm done.
For more info see :help E174 (for help on how to use command!) and :help :map-<expr>.
/was well. It would be best to also checkgetcmdtype() == ':'. e.g.cnoreabbrev <expr> w getcmdtype() == ":" && getcmdline() == 'w' ? 'call SaveBuffer()' : 'w'. There is also cmdalias.vim if you like plugins better. – Peter Rincker Jul 10 '17 at 19:04cmdalias.vim. Simply putau VimEnter * Alias w call SaveBuffer()in.vimrcand it works decently. – Arnie97 May 19 '20 at 03:52