11

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.

Aracthor
  • 173
  • 7
  • 3
    This is probably harder than it looks. http://www.nobugs.org/developer/parsingcpp/ – wasamasa Aug 03 '15 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 08 '15 at 14:03
  • 11
    This sounds a lot like the [`color-identifiers-mode` package](https://github.com/ankurdave/color-identifiers-mode). (Posting this as a comment because you said you didn't want to consider external packages.) – Aaron Harris Oct 12 '15 at 03: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 '16 at 11:43
  • What version of Emacs do you have? – D A Vincent Apr 22 '17 at 14:08

1 Answers1

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\\)\\>" .
       font-lock-keyword-face)))))
yPhil
  • 963
  • 5
  • 22