Prevent saving files with certain names in Vim

半腔热情 提交于 2019-11-30 14:40:22

问题


I type really fast and realize that sometimes I accidentally save a file with the name of ; or : (I type :wq and sometimes a typo is introduced).

Is there any way to write a macro that rejects saving files matching certain names?


回答1:


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 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 more details), e.g.

:noa w :ok.txt


来源:https://stackoverflow.com/questions/6210946/prevent-saving-files-with-certain-names-in-vim

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!