12

How to make Emacs to indent cases like this

switch ($foo) {
    case "foo":
        $foo .= " bar";
        break
    case "bar":
        $foo .= " baz";
        break
    default:
        $foo .= " undefined";
}

instead of

switch ($foo) {
case "foo":
    $foo .= " bar";
    break
case "bar":
    $foo .= " baz";
    break
default:
    $foo .= " undefined";
}
jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

20

You need to add something like this to your .emacs (either as a general setting or for the specific programming modes you care about):

;; set this in all c-based programming modes
(add-hook 'c-mode-common-hook
          (lambda ()
             (c-set-offset 'case-label '+)))

to add this to another mode, use the same pattern above with the relevant mode name substituted in for the hook, e.g.: <mode-name>-hook.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • 1
    `c-set-offset` is bound to `C-c C-o` if you need to adjust something on the fly for a specific file. – pmr Jan 24 '12 at 17:50
  • Thanks. I put 4 as offset and it work for php-mode and C-mode. Do you know how to set it for JavaScript too? – jcubic Jan 24 '12 at 18:46
  • @jcubic - what javascript mode do you use? – jtahlborn Jan 24 '12 at 19:11
  • @jcubic - so you could just use `js-mode-hook` per my added note above. – jtahlborn Jan 24 '12 at 21:05
  • Yes I try it (also `javascript-mode-hook`) and it doesn't work for JS. I also try to set `statement-case-intro` with no results in JS – jcubic Jan 24 '12 at 23:58
  • There is a slight typo in your elisp. The c-set-offset call should look like: (c-set-offset 'case-label '+) (the "+" should be quoted). – tkf May 10 '13 at 23:57