Defining new keywords with font-lock-add-keywords breaks/overrides variable-name coloring (emacs)

768 views Asked by At

I was trying to get emacs to color some additional keywords in C. In particular, I to add RESTRICT. I did:

(add-hook 'c-mode-common-hook
      (lambda ()
        (font-lock-add-keywords nil
                    '(("\\<\\(RESTRICT\\)\\>" . font-lock-keyword-face))) ))

However, this (unsurprisingly) just causes emacs to color instances of "RESTRICT" with keyword-face.

"restrict" (lower case) is already part of emacs' knowledge of C keywords. So if I declare:

int * restrict foo;

The "int" is colored with type-face, "restrict" is colored with keyword-face, and "foo" is colored with variable-name-face. But with my new RESTRICT word, if I declare:

int * RESTRICT bar;

"int" is colored as before, and RESTRICT is colored with keyword-face. But "bar" has no effects on it. Without my rule in place, "RESTRICT" would be colored variable-name-face, and "bar" would be unmodified, which is proper.

Anyway, the question is: how can I make emacs color "bar" in the second code-block with variable-name-face? I want emacs to actually treat "RESTRICT" as a keyword in the language (so that variable names get colored), not just color instances of "RESTRICT" a certain way.

1

There are 1 answers

1
jtahlborn On

my guess is that you somehow want to override this definition in cc-langs.el (part of cc-mode):

(c-lang-defconst c-type-modifier-kwds
  "Type modifier keywords.  These can occur almost anywhere in types
but they don't build a type of themselves.  Unlike the keywords on
`c-primitive-type-kwds', they are fontified with the keyword face and
not the type face."
  t    nil
  c    '("const" "restrict" "volatile")
  c++  '("const" "volatile" "throw")
  objc '("const" "volatile"))

however, i'm no expert in cc-mode but i couldn't find an obvious way to override this binding.