Vim run autocmd on all filetypes EXCEPT

后端 未结 5 1824
悲哀的现实
悲哀的现实 2020-12-02 07:55

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

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 08:38

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

提交回复
热议问题