Very new to emacs. (I only started day before yesterday.) I'm writing some Java and was wondering if there's an option or something I can set up so it will indent Javadoc comments correctly.

What I mean by that is, if I type:

public class NiftyClass {

     * Here's what this method does.
     * @return the answer

every time I hit enter to start a new line in the Javadoc comments the pointer is at the left margin. Inside the body of a method when I hit enter it takes me to the next line at the correct indentation. I'd prefer that it do something similar with these comments, such that the pointer aligns itself underneath the previous *. Or, better yet, that it add the next *space for me and start me right after that.

Is there anything that can do this?

  • 1
    M-j opens new line in comments, but what exactly it does depends on the mode settings. It is bound to comment-indent-new-line.
    – wvxvw
    Commented Jan 17, 2015 at 13:23
  • M-j does exactly what I wanted! Thank you!
    – Reagankm
    Commented Jan 17, 2015 at 19:19
  • @wvxvw If you want to repost your comment below, I'd mark it as the answer :]
    – Reagankm
    Commented Jan 23, 2015 at 18:16
  • I think phils had a better explanation (M-j could be bound to something other than comment-indent-new-line, but in general Emacs user would learn to expect M-j to continue comment on a new line.
    – wvxvw
    Commented Jan 23, 2015 at 22:13

1 Answer 1


You could try:

(electric-indent-mode +1)

(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))

(add-hook 'prog-mode-hook #'my-newline-and-indent-mode-hook)

Pressing return will continue comment or newline-and-indent -- press C-return to end the comment with a plain newline.

  • Instead of (key-binding (kbd "M-j")), you can just use "M-j" for (essentially) the same effect. But the right way is to use the actual function name.
    – Malabarba
    Commented Jan 17, 2015 at 19:31
  • Malabarba: No, there's a very good reason for doing it as Fromage has shown -- that key binding (M-j) is standard for this functionality, but the function it's bound to can vary between major modes. Simply making RET do the same thing as M-j is a simpler and more-reliable approach.
    – phils
    Commented Jan 18, 2015 at 22:07
  • And given that this is for prog-mode-hook, setting a single specific function for this would be wrong, for the same reasons. You would need a map of exceptions to go with it.
    – phils
    Commented Jan 18, 2015 at 22:14
  • See also stackoverflow.com/questions/9058889/…
    – phils
    Commented Jan 18, 2015 at 22:24

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.