5

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
...
#endif
}

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

int main()
{
    #ifdef foo
    ...
    #endif
}

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?

Gonçalo Ribeiro
  • 1,991
  • 1
  • 18
  • 28

1 Answers1

6

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.

jamessan
  • 11,045
  • 2
  • 38
  • 53
  • 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? – Gonçalo Ribeiro Apr 15 '15 at 15:19
  • @GonçaloRibeiro It can't be done: http://stackoverflow.com/questions/16047521/make-vim-indent-c-preprocessor-directives-the-same-as-other-statements –  Feb 28 '17 at 11:35