Comments (#) go to start of line in the insert mode in Vim

PythonVimCommentsIndentation

Python Problem Overview


Whenever I want to add a comment to an indented line in vim, I hit Shift-o (open a new row above the current, switch to insert mode) and start typing a Python comment (using #). That hash is then magically moved to the start of the line (no indentation) and I have to click tab a few times.

Anyone know how to work around it?

Python Solutions


Solution 1 - Python

I suppose you have set smartindent in your .vimrc

See :h 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.

I believe you don't need smartindenting while coding python. So just remove it from your settings or add the following to your .vimrc:

au! FileType python setl nosmartindent

Solution 2 - Python

try putting that in your .vimrc:

autocmd BufRead *.py inoremap # X<c-h>#

This will make that the insertion of the hash (pound) sign is always indented in Python source files.

Solution 3 - Python

I came across this because I was having the same issue in haskell when using cindent.

You can configure what prompts the reindenting by modifying the contents of cinkeys:

I added the following to my vimrc to stop # triggering the behaviour

"when you type a hash as the first character stop it triggering reindent
set cinkeys -=0#

Solution 4 - Python

You may want to try Nerd Commenter, which is a plugin that allows you to add comments to lines in most languages automatically. You simply place the cursor at the line you are interested in and type ,cSpace and the line will be commented out. The same keystrokes will remove the comment to reveal the line.

So if you have:

def func():
print("indented") <- cursor position in command mode

Type ,cSpace and you get:

def func():
#print("indented")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonatan LittkeView Question on Stackoverflow
Solution 1 - PythonMaxim KimView Answer on Stackoverflow
Solution 2 - PythonHaesView Answer on Stackoverflow
Solution 3 - PythonJonnyRaaView Answer on Stackoverflow
Solution 4 - PythonPierre-Antoine LaFayetteView Answer on Stackoverflow