Vim 对所有文件类型运行 autocmd,除了 [英] Vim run autocmd on all filetypes EXCEPT

查看:35
本文介绍了Vim 对所有文件类型运行 autocmd,除了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Vim autocmd,可以在写入之前删除文件中的尾随空格.我几乎 100% 都希望这样做,但是我希望禁用一些文件类型.传统智慧是在逗号分隔的列表中列出您希望 autocmd 运行的文件类型,例如:

I have a Vim autocmd that removes trailing whitespace in files before write. I want this almost 100% of the time, but there are a few filetypes that I'd like it disabled. Conventional wisdom is to list the filetypes you want an autocmd to run against in a comma-separated list, eg:

autocmd BufWritePre *.rb, *.js, *.pl

但在这种情况下,这将是繁重的.

But in this case that would be onerous.

有没有办法将 autocmd 模式与所有文件匹配,除了那些匹配模式的文件?我在文档中找不到与 NOT 匹配器等效的东西.

Is there a way to match an autocmd pattern against all files EXCEPT those matching the pattern? I cannot find the equivalent to a NOT matcher in the docs.

推荐答案

*.rb 不是文件类型.这是一个文件模式.ruby 是文件类型,甚至可以在没有 .rb 扩展名的文件上设置.因此,您最有可能需要的是一个函数,您的 autocmd 会调用该函数来检查不应对其执行的文件类型并去除空格.

*.rb isn't a filetype. It's a file pattern. ruby is the filetype and could even be set on files that don't have a .rb extension. So, what you most likely want is a function that your autocmd calls to both check for filetypes which shouldn't be acted on and strips the whitespace.

fun! StripTrailingWhitespace()
    " Don't strip on these filetypes
    if &ft =~ 'ruby\|javascript\|perl'
        return
    endif
    %s/\s\+$//e
endfun

autocmd BufWritePre * call StripTrailingWhitespace()

<小时>

根据埃文的回答,您可以检查缓冲区局部变量并确定是否使用该变量进行条带化.如果您决定不想剥离通常会剥离的文件类型的缓冲区,这也将允许您一次性禁用.


Building on evan's answer, you could check for a buffer-local variable and determine whether to do the strip using that. This would also allow you to do one-off disabling if you decided that you don't want to strip a buffer that's a filetype you normally would strip.

fun! StripTrailingWhitespace()
    " Only strip if the b:noStripeWhitespace variable isn't set
    if exists('b:noStripWhitespace')
        return
    endif
    %s/\s\+$//e
endfun

autocmd BufWritePre * call StripTrailingWhitespace()
autocmd FileType ruby,javascript,perl let b:noStripWhitespace=1

这篇关于Vim 对所有文件类型运行 autocmd,除了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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