Setting Emacs tab stops for Java

I have a problem with Java code: with classes, methods, exception blocks, loops, etc, there's a lot of indentation. Especially when I'm posting code to this blog, with its narrow text column, things quickly flow off the right side of the page. And it's so unnecessary. I don't think 4-column tab stops, which I was using, is needed to produce readable code. The key to solve this is in the following file on my Linux system:
~/.emacs.d/init.el
This contains "elisp" commands which are executed upon emacs start-up. Elisp is the Emacs variant of LISP. Honestly, even though I am good with basic MIT Scheme, and also the Elk Scheme I use at work, I find Elisp fairly challenging. But Google is my friend, so I inserted the following:
;Basic unit of spaces for each indentation level.
; c-basic-offset: sets offset for "C-class" languages
; I specifically set it smaller in Java, which tends to have extra indents
; with its class structure.

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

; force emacs to use spaces
(setq-default indent-tabs-mode nil)
Now "C-class" languages default to an offset of columns, but because Java tends to have so many tab stops, I set the Java indent to 2 columns. Two works pretty well for me: enough indent for structure, but obviously not so much that things get pushed off to the right. The last two lines of the above suppress use of the tab character in files. Tab characters are a general disaster, as different environments assume different tab spacing. A few extra bytes to fill these in with spaces is well invested in any case where anything but an arbitrary value for tab spacing is unacceptable.

Comments

Garrett Lau said…
When I read this, I thought, "What? The default is 2." Then I launched Emacs and discovered that it is 2 for C, but 4 for Java.
djconnel said…
Wow -- someone read this! Garrett, you make me happy :). Amazing people still use emacs, but once your fingers learn the keystrokes without requiring cranial intervention, nothing else seems to work as well.
Garrett Lau said…
Yeah, it's nice to find another Emacs user. Nobody else at my company uses it.

Popular posts from this blog

Marin Avenue (Berkeley)

hummingbird feeder physics

Gallium Pro geometry