Skip to content

Instantly share code, notes, and snippets.

@michaelbartnett
Last active May 3, 2017 19:22
Show Gist options
  • Select an option

  • Save michaelbartnett/be9369c2230ebdff207eaeba575e1894 to your computer and use it in GitHub Desktop.

Select an option

Save michaelbartnett/be9369c2230ebdff207eaeba575e1894 to your computer and use it in GitHub Desktop.
[EDIT: Don't use this. Just upgrade your CC-Mode manually. It's easy.] Emacs enum class indent cc-mode hack (update from SO answer)
;; Based on http://stackoverflow.com/questions/6497374/emacs-cc-mode-indentation-problem-with-c0x-enum-class/6550361#6550361
;; Gist from the SO answer: https://gist.github.com/nschum/2626303
; I know it's a disgusting regex, I'm sorry. I kept the source that generated it.
(defun my/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
;; (letf* ((+ "+")
;; (* "*")
;; (| "\\|")
;; (maybe "?")
;; (word-boundary "\\b")
;; ((symbol-function 'group) (lambda (&rest args) (list "\\(" args "\\)")))
;; ((symbol-function 'group?) (lambda (&rest args) (list (group args) maybe)))
;; (identifier (list (group "_" | "\\w") +))
;; (whitespace (group "\\s-" | "\r" | "\n"))
;; (class-or-struct (list (group "class" | "struct") word-boundary)))
;; (apply
;; #'concat
;; (-flatten
;; (list "enum" whitespace +
;; class-or-struct whitespace *
;; (group? identifier whitespace *
;; (group? ":" whitespace *
;; (group? identifier whitespace *)))))))
"enum\\(\\s-\\|\r\\|\n\\)+\\(class\\|struct\\)\\b\\(\\s-\\|\r\\|\n\\)*\\(\\(_\\|\\w\\)+\\(\\s-\\|\r\\|\n\\)*\\(:\\(\\s-\\|\r\\|\n\\)*\\(\\(_\\|\\w\\)+\\(\\s-\\|\r\\|\n\\)*\\)?\\)?\\)?"
))))
(defun my/align-enum-class (langelem)
(if (my/inside-class-enum-p (c-langelem-pos langelem))
0
(c-lineup-topmost-intro-cont langelem)))
(defun my/align-enum-class-closing-brace (langelem)
(if (my/inside-class-enum-p (c-langelem-pos langelem))
0
'+))
(defun my/fix-enum-class ()
"Setup `c++-mode' to better handle \"enum class\"."
(add-to-list 'c-offsets-alist '(topmost-intro-cont . my/align-enum-class))
(add-to-list 'c-offsets-alist
'(statement-cont . my/align-enum-class-closing-brace)))
(add-hook 'c++-mode-hook #'my/fix-enum-class)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment