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?

  • Vim uses cindent for C. See :help cinoptions-values. – romainl Apr 9 '15 at 12:42
5

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? – Gonçalo Ribeiro Apr 15 '15 at 15:19
  • @GonçaloRibeiro It can't be done: stackoverflow.com/questions/16047521/… – user859 Feb 28 '17 at 11:35

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.