Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent saving files with certain names in Vim?

Tags:

vim

autocmd

I type really fast and sometimes accidentally save a file with the name consisting of a single ; or :. (A typo is sometimes introduced as I type the :wq command.)

Is there any way to write a macro that rejects files matching certain names from being saved?

like image 835
disappearedng Avatar asked Jun 02 '11 05:06

disappearedng


1 Answers

A simple yet effective solution would be to define an auto-command matching potentially mistyped file names, that issues a warning and terminates saving:

:autocmd BufWritePre [:;]* throw 'Forbidden file name: ' . expand('<afile>')

Note that the :throw command is necessary to make Vim stop writing the contents of a buffer.

In order to avoid getting the E605 error because of an uncaught exception, one can issue an error using the :echoerr command run in the try block—:echoerr raises its error message as an exception when called from inside a try construct (see :help :echoerr).

:autocmd BufWritePre [:;]*
\   try | echoerr 'Forbidden file name: ' . expand('<afile>') | endtry

If it is ever needed to save a file with a name matching the pattern used in the above auto-command, one can prepend a writing command with :noautocmd or set the eventignore option accordingly (see :help :noautocmd and :help eventignore for details), e.g.:

:noa w :ok.txt
like image 160
ib. Avatar answered Oct 13 '22 20:10

ib.