C++11 mode or settings for emacs?

Joseph Garvin picture Joseph Garvin · Dec 18, 2011 · Viewed 11.2k times · Source

I'm running Emacs 23.3.1 (Ubuntu, Oneiric package) and emacs doesn't appear to understand any of the new C++11 keywords, constexpr, thread_local, etc. Also it doesn't understand that '>>' is now permitted in template parameters, or the new 'enum class' syntax. Is there an updated or alternative module somewhere? Or failing that, some settings to make emacs more C++11 friendly in the mean time?

Answer

Andreas Spindler picture Andreas Spindler · Oct 17, 2012

Well, I'm using 24.1. Some C++98 keywords are missing, and all new C++11 keywords. It does not even fontify number constants. It seems as if c++-mode hasn't been updated for a decade.

I'm using the following code for a long time now, and recently added C++11 keywords. Try putting it in your .emacs; it should fill some holes.

(require 'font-lock)

(defun --copy-face (new-face face)
  "Define NEW-FACE from existing FACE."
  (copy-face face new-face)
  (eval `(defvar ,new-face nil))
  (set new-face new-face))

(--copy-face 'font-lock-label-face  ; labels, case, public, private, proteced, namespace-tags
         'font-lock-keyword-face)
(--copy-face 'font-lock-doc-markup-face ; comment markups such as Javadoc-tags
         'font-lock-doc-face)
(--copy-face 'font-lock-doc-string-face ; comment markups
         'font-lock-comment-face)

(global-font-lock-mode t)
(setq font-lock-maximum-decoration t)


(add-hook 'c++-mode-hook
      '(lambda()
        (font-lock-add-keywords
         nil '(;; complete some fundamental keywords
           ("\\<\\(void\\|unsigned\\|signed\\|char\\|short\\|bool\\|int\\|long\\|float\\|double\\)\\>" . font-lock-keyword-face)
           ;; add the new C++11 keywords
           ("\\<\\(alignof\\|alignas\\|constexpr\\|decltype\\|noexcept\\|nullptr\\|static_assert\\|thread_local\\|override\\|final\\)\\>" . font-lock-keyword-face)
           ("\\<\\(char[0-9]+_t\\)\\>" . font-lock-keyword-face)
           ;; PREPROCESSOR_CONSTANT
           ("\\<[A-Z]+[A-Z_]+\\>" . font-lock-constant-face)
           ;; hexadecimal numbers
           ("\\<0[xX][0-9A-Fa-f]+\\>" . font-lock-constant-face)
           ;; integer/float/scientific numbers
           ("\\<[\\-+]*[0-9]*\\.?[0-9]+\\([ulUL]+\\|[eE][\\-+]?[0-9]+\\)?\\>" . font-lock-constant-face)
           ;; user-types (customize!)
           ("\\<[A-Za-z_]+[A-Za-z_0-9]*_\\(t\\|type\\|ptr\\)\\>" . font-lock-type-face)
           ("\\<\\(xstring\\|xchar\\)\\>" . font-lock-type-face)
           ))
        ) t)

Hope this helps.