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

4.3k views Asked by At

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.

4

There are 4 answers

0
Christian Brabandt On BEST ANSWER

Simply check in the autocommand for the filetype:

autocmd BufWrite * if &ft!~?'markdown'|:call DeleteTrailingWS()|endif
1
Zach On

The * in the auto command specifies which kind of file to run on, so you just need to replace it with *.md.

autocmd BufWrite *.md :call DeleteTrailingWS()
0
Ingo Karkat On

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

0
Ingo Karkat On

For a robust solution, have a look at my DeleteTrailingWhitespace plugin. Together with the ShowTrailingWhitespace plugin, it already detects filetypes such as Markdown (in a customizable way) and then adds an exception (more finegrained than simply turning it off; i.e. allowing two or more spaces, but still highlighting trailing tabs in Markdown).