1

As I am setting .vimrc, I found these two code blocks have the same functionality.

au Filetype python set
     \ tabstop=4
     \ softtabstop=4
     \ shiftwidth=4
     \ textwidth=79

and

au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79

I reckon that there is a very subtle difference between them, but cannot figure it out. Like, vim interprets Filetype when opening the file etc.

3

Your intuition is correct: the two autocommands are very similar.

The second autocommand runs when you read or start editing a new file with a name that ends in the .py extension. The first runs when the file type is set to Python, which Vim will generally do automatically for .py files.

However, try running the following commands with each of the two autocommands in place:

:new
:w new.py

You will find that the Filetype autocommand runs, but the other does not. For this reason, you should probably use the first version if you want to use an autocommand for this.

However, in my opinion, there is an even better solution. Create a file in the location:

~/.vim/after/ftplugin/python.vim

And enter the contents:

set tabstop=4
set softtabstop=4
set shiftwidth=4
set textwidth=79

This will have the same effect, no autocommands required!

  • 2
    @SongchengLi I think Vim's Python ftplugin also reads shebangs (so a file with no extension but #! /usr/bin/python as the shebang gets detected as a Python file). – muru Dec 11 '18 at 2:01

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

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