There are a few cases where the file extension isn't necessarily indicative of the file contents, and filetype needs to be set with a modeline. For example, Salt *.sls files can contain many different types of data, including YAML, Jinja2, or Python code, and I include a modeline at the bottom of those to set the correct filetype for syntax highlighting.

# vim:ft=python

I have a BufWritePost autocommand in my .vimrc that runs a style linter on my python code any time I save a buffer:

    au BufWritePost *.py call Flake8()

I would like to do something similar whenever a buffer of FileType python is written, but haven't been able to find an autocommand that matches on filetype. Is there one? Or is there some other approach that will get the effect I want?

  • How is it possible to look for "an autocommand that matches on filetype" without finding :help FileType?
    – romainl
    Dec 3, 2022 at 9:45
  • @romainl In what way is that response helpful? Clearly I'm aware of FileType or I wouldn't have mentioned it twice in my post. I'm also clearly looking for an autocommand that is triggered "whenever a buffer of FileType python is written", which is not what au FileType appears to do. If I've missed something, and you want to offer some indication of what exactly I've missed, then please share.
    – mpounsett
    Dec 3, 2022 at 18:09

1 Answer 1


You don't "find" autocommands, you write them.

First, choose the most appropriate event.

Either of BufWritePost or BufWritePre is the event you need. Which one to choose depends on what that Flake8() function does: if it operates on the buffer, use BufWritePre, if it operates on a file, use BufWritePost.

So, assuming Flake8() operates on the buffer:

autocmd BufWritePre *.py call Flake8()

Second, decide on a strategy.

Here you must choose between two approaches: keep the autocommand in your vimrc or move it to a proper filetype plugin.

If you want to keep the autocommand in your vimrc, you will need to change the pattern to * and add logic to the right-hand side because BufWritePre and BufWritePost don't know anything about filetypes:

autocmd BufWritePre * if &filetype == "python" | call Flake8() | endif

This gives you an autocommand that will decide whether or not to call Flake8() whenever you write a buffer, any buffer. That works but what a mess! You have some logic that will be executed very often and for nothing.

The better strategy is to move your autocommand to a proper filetype plugin:


This gives you:

  • a cleaner vimrc,

  • access to the special pattern <buffer>, see :help autocmd-buflocal,

  • and a much simpler autocommand:

      autocmd BufWritePre <buffer> call Flake8()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.