Search code examples
pythonvimindentationauto-indent

Auto-indent not working on Python's "with"


I am using VIM 7.4 on Ubuntu 16.04, and am coding for Python 3.5.

When writing a Python file (.py), the indentation works perfectly, except for the with statement. Namely, I could remap tab to indent by four spaces, VIM automatically indents by four spaces after a colon (:), and so on.

But when it comes to the with ... as syntax, it fails indenting a newline.

Visual example:

if x == 12:

then tab results on an indented newline, but

with open("test.txt", 'r') as file:

then tab resultes on a not indented newline.

I checked a lot of questions, that I won't link because they are too numerous, but here are some of the things I tried:

  • Adding set autoindent in my .vimrc;
  • Adding set smartindent in my .vimrc;
  • Typing filetype indent on in VIM's interpreter;
  • Typing :set indentkeys? and checking if the colon was in the list (it was).

It is nearly empty, so I doubt it will be useful, but here is my .vimrc:

set nocompatible
set autoindent
set smartindent
set tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab
inoremap <S-Tab> <C-d>

How can I fix VIM so it recognizes with...as and indents after this on a newline?


Solution

  • The solution is indeed in the filetype indent on command.

    For some reason, typing it in the VIM interpreter will not do anything. Therefore, one could think that this is not the way to fix this.

    However, adding the following line to the .vimrc effectively fixed the problem:

    filetype indent on