IndentingJava

Annotations

In very old versions of emacs (<24.1?, cc-mode < 5.32?), java-mode below does not indent Java 1.5 @-style annotations correctly. A quick fix is to define them as comments:[1]

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

A more complete solution is provided by Lisp:java-mode-indent-annotations.el.

Tab width

The most important thing to remember is that Java files use a different style. Therefore, to customize Java indentation, use the java-mode-hook:

    (add-hook 'java-mode-hook (lambda ()
                                (setq c-basic-offset 4)))

The ‘c-basic-offset’ variable controls the basic “unit” of the indentation engine. When you hit the TAB key, you tell the indentation engine to indent to “the right place”. This will insert tabs and spaces as required. Therefore, hitting TAB will usually advance point by 4 when indenting Java source.

When you read other people’s Java source, however, tab characters will still be 8 wide.

Here is how to fix it:

    (add-hook 'java-mode-hook (lambda ()
                                (setq c-basic-offset 4
                                      tab-width 4
                                      indent-tabs-mode t)))

This says that hitting TAB should advance point by 4, that tab characters in source files should display 4 wide, and that Emacs should use tab characters when it can. Therefore, the TAB key will insert tab characters, and they will display 4 wide.

If you set ‘indent-tabs-mode’ to nil, then Emacs will insert 4 spaces instead.

See also IndentingC and SmartTabs for more info.


CategoryIndentation CategoryJava