3

When using the autoindent configuration from VIM, it will automatically indent your cursor to a meaningful position after creating a new line. But when the first character you enter is a hash character (#) then the indentation will be removed and the # will be inserted as the first character of the line.

Why does this happen? How to configure VIM to not do that?

Example (_ as the empty cursor position):

def python_function():
    _

after clicking the# on the keyboard this happens:

def python_function():
#_

but what should have happened is this:

def python_function():
    #_
erikbstack
  • 12,878
  • 21
  • 81
  • 115
  • 2
    Check out http://stackoverflow.com/questions/191201/indenting-comments-to-match-code-in-vim and http://stackoverflow.com/questions/385327/what-setting-in-vim-counteracts-smartindents-refusal-to-indent-comments-in-sh – Hari Menon Jun 20 '12 at 13:58
  • You are right, I just didn't really know how to search that term. – erikbstack Jun 20 '12 at 14:01

3 Answers3

4

:help smartindent

Use the mapping :inoremap # X^H# (^h is entered via CTRL-V CTRL-H)

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    The help section on smartindent gives a brief explanation. vim has a strong legacy as an editor for C source code, and typically lines beginning with '#' are not indented. – William Pursell Jun 20 '12 at 14:13
  • 1
    @erikb85, The answer to your question is http://stackoverflow.com/questions/35156448/autoindent-smartindent-and-indentexpr – dlmeetei Feb 02 '16 at 21:06
4

You might have smartindent or cindent instead of (or as well as) autoindent; these indent styles are designed for C-syntax languages. It's a good idea when editing Python to use :filetype plugin indent on as this will load appropriate indent settings for Python.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
0

For me it was also the case that the indentation was not properly working when I have forgotten to disable paste mode with :set nopaste, when initially turning it on for copy pasting.

avenir
  • 149
  • 7