Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set an autocmd in the vimrc to only run with specific filetypes?

Tags:

vim

autocmd

The Explanation:

Recently I acquired a .vimrc file from a git repository, and have found it incredibly useful so far. One of the useful tools that came with it is that it automatically deletes trailing white space when you write the file.

However, I just started using markdown, which gives a clear format on how to write text files, making it easy to convert those files to different types such as html.

The problem is markdown uses two trailing spaces to signify a newline. My .vimrc automatically deletes these. I found the autocmd that does this. It is:

autocmd BufWrite * :call DeleteTrailingWS()

The DeleteTrailingWS is the function that actually deletes the white space.

My Question:

How do I modify this so that it will only run/set this autocmd if the type of file is not markdown? (.md) Please explain in such a way so I could call generic functions, not just the one above. Also, how do you do this with multiple file types. For example, run/set this command only if the file is not of type .md, .abcd, or .efgh?

Thank you all.

like image 767
kirypto Avatar asked Dec 20 '22 08:12

kirypto


2 Answers

Simply check in the autocommand for the filetype:

autocmd BufWrite * if &ft!~?'markdown'|:call DeleteTrailingWS()|endif
like image 161
Christian Brabandt Avatar answered Jan 22 '23 16:01

Christian Brabandt


Christian's answer works well when you want to except some filetypes. For the other case, defining autocmds for just some filetypes, the usual approach is to define buffer-local autocmds via

:autocmd BufWrite <buffer> call ...

this can be done via other prepended :autocmd Filetype ... autocmd ..., or a filetype plugin in ~/.vim/ftplugin/...

like image 22
Ingo Karkat Avatar answered Jan 22 '23 16:01

Ingo Karkat