16

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.

knub
  • 3,892
  • 8
  • 38
  • 63

3 Answers3

19

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.

piojo
  • 6,351
  • 1
  • 26
  • 36
  • 1
    Thank you for adding this answer. The title brought me here, and it works with my version of vim. – Doug Mar 31 '23 at 12:14
11

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.

Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125
  • 3
    "set formatoptions=-or" did not work actually, even though the documentation says so. I am using "set formatoptions=tnq" now. Thanks! http://stackoverflow.com/questions/6076592/vim-set-formatoptions-being-lost was useful, as well. – knub Feb 18 '12 at 10:06
  • 2
    @knub `set formatoptions-=o | set formatoptions-=r` is the syntax that works for removing options. `set formatoptions-=ro` works only if they are consecutive in the options string as "ro" exactly. – piojo Jan 14 '19 at 03:43
6

See :help 'formatoptions' - I know how annoying this is!

Try this:

:set fo-=or
Peter
  • 127,331
  • 53
  • 180
  • 211