Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent (g)vim from auto-indenting comments

A while ago, I had to put

filetype plugin on

in my .vimrc for a plugin I use.

But this caused a change in autoindent: Whenever I write a comment "//", and then press enter, vim autoindentation automatically enters another "//" in the next line.

// This is a comment. <ENTER>
// <-- vim automatically puts '// ' there

What can I do to avoid this? I use the autoindent setting in my vim file. I already tried

filetype plugin indent off

but it does not work.

like image 731
knub Avatar asked Feb 17 '12 18:02

knub


People also ask

How do I turn off auto indent in Vim?

How to Turn Off Vim Auto Indent. You can also temporarily turn off automatic indenting by typing :set paste in command mode. (:unset paste to turn it back on again.) This is useful — as you might guess from the command name — if you're pasting in chunks of text or code to avoid getting annoying extraneous indents.

How do I turn on auto indent in Vim?

How to Turn On Auto Indent in Vim. To automatically indent when editing a file in Vim, enable the auto indenting feature using the :set autoindent flag in command mode: Press Enter, and this will auto-indent the file you are currently editing.

How do I paste without formatting in Vim?

Press F2 (toggles the 'paste' option on). Use your terminal to paste text from the clipboard. Press F2 (toggles the 'paste' option off).


2 Answers

I am answering your title rather than the body of your question, since your title brings people to this page who are looking to stop Vim from indenting comments.

The variable that controls whether Vim auto-indents a new character is indentkeys. I've noticed incorrect indentation only in Python and Yaml, so I've turned off auto-indentation only for the "#" character at the beginning of the line: :set indentkeys-=0#

Since loading the filetype indentation plugin will override any .vimrc settings you've made, you can set up an autocmd to change the indentkeys after a file is created or loaded. Here are mine:

autocmd BufNewFile,BufReadPost * if &filetype == "python" | set indentkeys-=0# | endif
autocmd BufNewFile,BufReadPost * if &filetype == "yaml" | set expandtab shiftwidth=2 indentkeys-=0# | endif

See :h indentkeys

Note that because of (possibly) a bug, if you use Neovim you must also specify filetype plugin indent on, or the filetype won't be set.

like image 184
piojo Avatar answered Sep 23 '22 04:09

piojo


Take a look at :h formatoptions and :h fo-table. The options you need to turn off are r and o. Turning them off prevents vim from automatically inserting the comment leader (in this case "//") when you press enter in insert mode or when you press o or O in normal mode.

like image 36
Michael Kristofik Avatar answered Sep 24 '22 04:09

Michael Kristofik