I'm looking for a simple way to make emacs remember of declared variable in a single function in C/C++. By "simple", I mean without any external package, just with some elisp lines in configuration files.

My default Emacs configuration colors variables names in yellow on declaration, but let them white on use.

char toto; // 'char' is green, 'toto' is yellow

toto = 42; // 'toto' is white

I would like to make every "toto" of the same function/scope colored in yellow as well.

I've already looked on this question but I would like something simpler. I also tried to do something with font-lock mode, but I didn't succeed to make something adaptable to variable names.

I already have an idea for C++ class member names (using a name pattern), so I just want a local variable match here.

  • 3
    This is probably harder than it looks. nobugs.org/developer/parsingcpp
    – wasamasa
    Aug 3, 2015 at 17:00
  • 8
    Why don't you want to use any packages? If there is a package that provides this feature, installing it will almost certainly require less elisp in your config than re-creating the feature from scratch.
    – Tyler
    Oct 8, 2015 at 14:03
  • 11
    This sounds a lot like the color-identifiers-mode package. (Posting this as a comment because you said you didn't want to consider external packages.) Oct 12, 2015 at 3:24
  • 7
    Every "external package" can also be described as "some elisp lines in configuration files". Avoiding pre-existing code on the basis that someone has provided it in package form is absurd.
    – phils
    May 29, 2016 at 11:43
  • What version of Emacs do you have? Apr 22, 2017 at 14:08

1 Answer 1


You could muster a regexp for your variable scheme, something that matches (pseudo regexp code)[char|other|types] [a-z]; and [a-z] =*; and add it to the font-lock keyword list for your mode ; From the manual at the Customizing-Keywords page :

For example, the following code adds two fontification patterns for C mode: one to fontify the word ‘FIXME’, even in comments, and another to fontify the words ‘and’, ‘or’ and ‘not’ as keywords.

 (font-lock-add-keywords 'c-mode
  '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
    ("\\<\\(and\\|or\\|not\\)\\>" . font-lock-keyword-face)))

This example affects only C mode proper. To add the same patterns to C mode and all modes derived from it, do this instead:

 (add-hook 'c-mode-hook
  (lambda ()
   (font-lock-add-keywords nil
    '(("\\<\\(FIXME\\):" 1 font-lock-warning-face prepend)
      ("\\<\\(and\\|or\\|not\\)\\>" .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.