Tips for using Emacs for Java coding

If you're one of those dinosaurs for whom "IDE" means "I dig Emacs", then this page is for you. It contains lots of things I put in my .emacs file to make Java coding easier. Old school, baby!

Adhering to JavaNLP coding conventions

The JavaNLP code conventions specify that space characters, not tabs, should be used for indentation, and that the indentation unit should be 2 spaces. To achieve this in Emacs, put the following in your .emacs file:

(add-hook 'java-mode-hook '(lambda () (setq c-basic-offset 2)))
(setq-default indent-tabs-mode nil)     ; use only spaces, not tabs

Controlling formatting

Here are some other things I use to control formatting:

(global-font-lock-mode) ; colorize based on syntax

(add-hook 'java-mode-hook 'turn-off-auto-fill)  ; don't wrap long lines

(defun fill-column-hook () (setq fill-column 80))
(add-hook 'java-mode-hook 'fill-column-hook)    ; use 80 column width

(defun comment-column-hook () (setq comment-column 40))
(add-hook 'java-mode-hook 'comment-column-hook) ; start comments in column 40

Navigation shortcut

When chasing bugs, you need to go to a line number quickly.

(global-set-key "\M-g"  'goto-line) ; use M-g for goto-line

Handling annotations

Annotations on classes and methods were introduced in Java 1.5, but the default java-mode in Emacs does not display them properly. To remedy this, put the following in your .emacs file:

(add-hook 
 'java-mode-hook
 '(lambda () "Treat Java 1.5 @-style annotations as comments."
    (setq c-comment-start-regexp "\\(@\\|/\\(/\\|[*][*]?\\)\\)")
    (modify-syntax-entry ?@ "< b" java-mode-syntax-table)))

Shortcuts for Javadoc comments

When you're writing Javadoc comments, you often want to use <code> tags to indicate that an identifier should appear in a fixed-width font, or use the {@link Object} notation to indicate an inline link. Putting the following in your .emacs file allows you to use "C-c c" and "C-c l", respectively, to wrap the current token with <code> tags or the {@link Object} notation.

(defun wrap-current-word-with-html-tag (tagstring)
  (skip-chars-backward "^ \n")            ; go backward to a space
  (insert (format "<%s>" tagstring))
  (skip-chars-forward "^ \n")             ; go forward to a space
  (insert (format "" tagstring)))

;; e.g. "Object" => "<code>Object</code>"
(defun wrap-html-code-tag ()
  (interactive)
  (wrap-current-word-with-html-tag "code"))

(add-hook 'java-mode-hook
	  '(lambda ()
	     (local-set-key "\C-cc" 'wrap-html-code-tag)))

;; e.g. "Object" => "{@link Object}"
(defun wrap-current-word-with-javadoc-link ()
  (interactive)
  (skip-chars-backward "^ \n")            ; go backward to a space
  (insert "{@link ")
  (skip-chars-forward "^ \n")             ; go forward to a space
  (insert "}"))

(add-hook 'java-mode-hook
	  '(lambda ()
	     (local-set-key "\C-cl" 'wrap-current-word-with-javadoc-link)))

Darbar.


Contact: Bill MacCartney