13

I work on projects with varying levels of indentation. In many of these projects, because of how the files are typically structured, most lines are indented at least two levels (such as methods in Java files).

This would mean that creating a new line when on a line line

public void something () {

Would bring my cursor to the next line, automatically indented in, like

public void something () {
    [cursor]

While I can hit the tab key a few times on a new line to get it to line up, is there a better way of doing this (possible automatically)?

10

This can be done using a combination of the autoindent option and the filetype plugin.

The autoindent option will copy your current indentation when creating a new line. So if your current indentation level is 4 when you start the new line, the cursor will be moved to the same indentation level on the next line.

In your ~/.vimrc file, you would put

set autoindent

You can use the filetype plugin as well to automatically determine the next indentation level based on the file type.

You can enable this on the fly with

:filetype indent on

Or, in your ~/.vimrc file you would put

filetype plugin indent on

Which will automatically determine the indentation based on the file type.

6

Use :set cindent (:set cin for short) or :set smartindent (:set si for short). If your line ends in an opening brace, and you hit Enter, the following line will automatically be indented one additional level. (This is better than :set autoindent, which merely indents the next line at the same level.) cindent is better tailored to C-like languages, while smartindent is more versatile for use with other programming languages.

The amount and type of indentation is controlled by :set shiftwidth=…, :set tabstop=…, and :set expandtab.

  • 'smartindent' is deprecated, so that's not the best choice. It has been replaced by 'cindent' and 'cinoptions' for C-like languages. In general, though, file type indenting is the way to go, with 'autoindent' as a fallback. – jamessan Feb 4 '15 at 5:25
  • @jamessan smartindent isn't deprecated, but cindent is worth noting. I've updated the answer. (Thanks!) – 200_success Feb 4 '15 at 7:15
  • I'd also recommend you taking a look at editorconfig.org . There's of course a plugin for vim (and many other editors) and it's a great way to keep your editor defaults on your VCS – Cyber Oliveira Feb 4 '15 at 8:50
0

At bottom of the file, I'm using:

# vim: ts=2 sw=2 sts=2 sr noet st ai si

For example Dockerfile:

FROM centos-7
RUN ...
CMD ...

# vim: ts=2 sw=2 sts=2 sr noet st ai si

If you want keep the indentation only, use # vim: st ai si

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.