In my vimrc I have the following line, which figures all the indentation of my files.

filetype plugin indent on

When writing C programs sometimes I use preprocessor directives like #ifdef foo and #endif. When writing one such directive inside a block Vim indents the directive like this.

int main()
#ifdef foo

But I would like them to be indented as any other statement, i.e.

int main()
    #ifdef foo

indentkeys might be able to do the job. From :help 'indentkeys'

A list of keys that, when typed in Insert mode, cause reindenting of the current line. Only happens if 'indentexpr' isn't empty.

But my indentexpr is empty and I have no idea what I should put there; or if there is a better solution.

On the Vim wiki I have read

If you plan on using file type based indentation, don't set 'smartindent' or 'cindent'. You may still set 'autoindent', since it doesn't interfere.

So, since I am using file type based indentation I don't want to use smartindent nor cindent.

How can I achieve my intended indentation for preprocessor directives?

  • Vim uses cindent for C. See :help cinoptions-values.
    – romainl
    Commented Apr 9, 2015 at 12:42

1 Answer 1


This specific behavior is handled by the 'cinkeys' option. 'cinkeys' is similar to 'indentkeys' but is only used when 'cindent' is enabled.

By default, it contains the 0# setting which causes the leading indentation to be removed when a line starts with #. To disable this, you could add

setlocal cinkeys-=0#

to ~/.vim/after/indent/c.vim and ~/.vim/after/indent/cpp.vim.

  • Thank you. This seems seems to work when I write a new directive. But if I try to reindent an old one, say by doing gg=G, it leaves the directives unchanged. How could I make it work in both cases? Commented Apr 15, 2015 at 15:19
  • @GonçaloRibeiro It can't be done: stackoverflow.com/questions/16047521/…
    – user859
    Commented Feb 28, 2017 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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