Vim run autocmd on all filetypes EXCEPT

风流意气都作罢 提交于 2019-11-26 15:23:23

问题


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.

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.


回答1:


*.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



回答2:


Another choice of one line way:

let blacklist = ['rb', 'js', 'pl']
autocmd BufWritePre * if index(blacklist, &ft) < 0 | do somthing you like

Then you can do something you like for all filetypes except those in blacklist.




回答3:


The easiest way would be to set a local variable for the one filetype to true. Then set the automcommand if that variable is false (if set for everything else) or if it exists at all (no need to preset it).

autocmd BufWritePre *.foo let b:foo=true

if !exists("b:foo")
    autocmd ...
endif

changed variable prefixes based on comment



来源:https://stackoverflow.com/questions/6496778/vim-run-autocmd-on-all-filetypes-except

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