Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
better "enum class" indent in Emacs
;; This hack fixes indentation for C++11's "enum class" in Emacs.
;; http://stackoverflow.com/questions/6497374/emacs-cc-mode-indentation-problem-with-c0x-enum-class/6550361#6550361
(defun inside-class-enum-p (pos)
"Checks if POS is within the braces of a C++ \"enum class\"."
(ignore-errors
(save-excursion
(goto-char pos)
(up-list -1)
(backward-sexp 1)
(looking-back "enum[ \t]+class[ \t]+[^}]+"))))
(defun align-enum-class (langelem)
(if (inside-class-enum-p (c-langelem-pos langelem))
0
(c-lineup-topmost-intro-cont langelem)))
(defun align-enum-class-closing-brace (langelem)
(if (inside-class-enum-p (c-langelem-pos langelem))
'-
'+))
(defun fix-enum-class ()
"Setup `c++-mode' to better handle \"class enum\"."
(add-to-list 'c-offsets-alist '(topmost-intro-cont . align-enum-class))
(add-to-list 'c-offsets-alist
'(statement-cont . align-enum-class-closing-brace)))
(add-hook 'c++-mode-hook 'fix-enum-class)
@duyanning

This comment has been minimized.

Copy link

commented Nov 16, 2012

It does not work on emacs 24.2.
The last + in the regexp should be changed to *.
And the closing brace of enum class cannot be aligned correctly.
Can you fix it? Thank you very much.

@duyanning

This comment has been minimized.

Copy link

commented Nov 17, 2012

haha, it is casued by c-gnu-impose-minimum. If you change to 'stroustrup' style, it is ok! thank you!!!

@whitty

This comment has been minimized.

Copy link

commented Jun 10, 2015

In emacs 24.3.1 - I find the regexp "enum[ \t]+class[ \t]+" is required because up-list takes me to the open brace, then backward-sexp takes me to the first letter of the enum class's name, - in the example below: "Foo"

    ie here - thus looking-back into "enum class "
           v
enum class Foo
{
}
@michaelbartnett

This comment has been minimized.

Copy link

commented Jan 17, 2016

I tweaked the regexp to handle the enum-base case, e.g. enum class Foo : uint8_t {

      (or (looking-back "enum\\s-+class\\s-+")
          (looking-back "enum\\s-+class\\s-+\\sw+\\s-*:\\s-*")))

Only missing thing is looking-back doesn' t do newlines.

enum
class Foo1 : uint_t { }


enum class
Foo2 : uint_t { }

That's beyond my elisp fu :(

@hhyyrylainen

This comment has been minimized.

Copy link

commented Jun 26, 2016

For me

(or (looking-back "enum\\s-+class\\s-+")
          (looking-back "enum\\s-+class\\s-+\\S-+\\s-*:\\s-*"))

worked

@jgarvin

This comment has been minimized.

Copy link

commented Oct 4, 2017

even with the solution from hhyyrylainen the closing brace has an extra space in front of it for some reason

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.