Question

GNU Emacs 24.3.1

Hello,

I am doing some coding in Java using emacs. Just to make my coding easier I want to auto indent each time I insert a semi-colon or curly brace {

;; Auto indent for java mode
(add-hook 'java-mode-hook '(lambda ()
      (local-set-key (kbd "RET") 'newline-and-indent)))

(add-hook 'java-mode-hook '(lambda ()
      (local-set-key (kbd "{") 'newline-and-indent)))

(add-hook 'java-mode-hook '(lambda ()
      (local-set-key (kbd ";") 'newline-and-indent)))

The return works as expected. However, the curly brace and semi-colon just returns without entering the the ; or {.

Is this possible?

many thanks for any suggestions,

Was it helpful?

Solution

It's possible. Here is one way of doing it (replace the second and third call to add-hook with this):

(defun java-autoindent ()
  (when (and (eq major-mode 'java-mode) (looking-back "[{;]"))
    (newline-and-indent)))

(add-hook 'post-self-insert-hook 'java-autoindent)

The way this works is that every time you type a character in a java-mode buffer, Emacs will

  • check if that character is { or ;, and if that's the case
  • run newline-and-indent.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top