如何防止在 Vim 中保存具有特定名称的文件?

编程入门 行业动态 更新时间:2024-10-27 17:09:33
本文介绍了如何防止在 Vim 中保存具有特定名称的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我打字速度非常快,有时不小心保存了一个文件,文件名由单个 ;: 组成.(当我输入 :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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-27 18:16:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1159798.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何防止   名称   文件   Vim

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!