I've read several answers on here and on Google and have tried several solutions but nothing is fixing this for me.

Right now, if I try to write C code Emacs indents it like so:

#include <stdio.h>

    int main()

I would think main() should really be on the same indentation level as #include. Also, I would think the printf() line should be indented further in than the curly braces.

The suggestions I've found here and elsewhere say to put this in my .emacs file, which I did:

;;C configuration
(require 'cc-mode)
(setq-default c-basic-offset 4)
(setq c-default-style (cons '(c-mode . "java") c-default-style))
(setq-default tab-width 4 indent-tabs-mode t)
(define-key c-mode-base-map (kbd "RET") 'newline-and-indent)
(add-hook 'c-mode-hook
       (lambda ()
         (setq-local electric-indent-chars
                     (remq ?\n electric-indent-chars))))

Sorry for being such a newb. Can you help point me in the right direction as to why this is going wrong?

  • You get this with C-x h TAB?
    – abo-abo
    Commented Mar 3, 2015 at 8:42
  • What's your Emacs version? Is that code snippet the only configuration your .emacs file? I had no problem using your configuration, even setting to python as default style.
    – Tu Do
    Commented Mar 3, 2015 at 9:34
  • Setting the default "C" style to "java" seems weird. I think you don't need that line at all.
    – Tom Tromey
    Commented Mar 4, 2015 at 13:58
  • Also, try commenting out that part of your .emacs and restarting. If the problem persists then it is elsewhere. And, see if it happens with "emacs -q"
    – Tom Tromey
    Commented Mar 4, 2015 at 13:59

1 Answer 1


Thanks for the suggestions. I found the culprit. Per my previous question on here, in which I was trying to get Javadoc comment indentation to behave the way I wanted, I had these lines in .emacs:

(defun my-newline-and-indent-mode-hook ()
  (local-set-key (kbd "RET") (key-binding (kbd "M-j")))
  (local-set-key (kbd "<C-return>") #'electric-indent-just-newline)

I commented out the (local-set-key (kbd "RET") (key-binding (kbd "M-j"))) and then it quit being so weird writing C. I'll have to do more research later, though, to figure out how to enable that key binding just when I'm writing Java.

  • 1
    You can add the above function to java-mode-hook using (add-hook 'java-mode-hook #'my-newline-and-indent-mode-hook). Even better way would be to set those keys in java-mode-map: (define-key 'java-mode-map (kbd "RET") (key-binding (kbd "M-j"))) Commented Mar 5, 2015 at 14:28

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.