I start vanilla vim8 $ vim -u NONE with these settings:

:set ft=python
:set smartindent
:set cinkeys-=0#

When I enter in insertion mode the following:


The # is automatically unindent as follow:


Of course if I enable :set cindent everything works because cinkeys is now taken in account.

My question is why is # automatically moved left while cindent is disabled? Is there any better solution other than using an auto command?

autocmd FileType python setlocal cindent

Typing the # character causes an outdent because you have set 'smartindent', which is designed for C-like languages (where # indicates the start of a preprocessor directive).

Quoting from the output of :help 'smartindent'

When typing '#' as the first character in a new line, the indent for that line is removed, the '#' is put in the first column. The indent is restored for the next line. If you don't want this, use this mapping: ":inoremap # X^H#", where ^H is entered with CTRL-V CTRL-H. When using the ">>" command, lines starting with '#' are not shifted right.

(emphasis mine)

If you wish to continue using 'cindent' but want a better way of setting it than an autocommand, you can simply place a file containing:

setlocal cindent

In the location: ~/.vim/after/ftplugin/python.vim.

Alternatively, you could simply turn off 'smartindent' and use 'autoindent', or, perhaps best, look into obtaining a plugin that is designed specifically to implement Python indentation. Here's one. Here's another.

| improve this answer | |

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.