如何防止在 Vim 中保存具有特定名称的文件? [英] How to prevent saving files with certain names in Vim?

查看:33
本文介绍了如何防止在 Vim 中保存具有特定名称的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打字速度非常快,有时不小心保存了一个文件,文件名由单个 ;: 组成.(当我输入 :wq 命令时,有时会出现拼写错误.)

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?

推荐答案

一个简单而有效的解决方案是定义一个自动命令匹配可能输入错误的文件名,发出警告并终止保存:

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>')

注意 :throw 命令是让 Vim 停止写入所必需的缓冲区的内容.

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

为了避免由于未捕获而出现 E605 错误异常,可以使用 :echoerr 命令运行发出错误在 try 块中 - :echoerr 将其错误消息作为异常引发当从 try 结构内部调用时(参见 :help :echoerr).

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

如果需要保存名称与模式匹配的文件在上面的自动命令中使用,可以在前面添加一个写入命令使用 :noautocmd 或相应地设置 eventignore 选项(请参阅:help :noautocmd:help eventignore 了解详情),例如:

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

这篇关于如何防止在 Vim 中保存具有特定名称的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆