Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto indent after inserting a semicolon or curly brace

Tags:

emacs

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,

like image 638
ant2009 Avatar asked May 14 '14 07:05

ant2009


1 Answers

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.
like image 173
itsjeyd Avatar answered Sep 28 '22 08:09

itsjeyd