Search code examples
regexemacsspecial-characterskeywordfont-face

How to color @ (at symbol) in Emacs?


I can color keywords in emacs using the following lisp code in .emacs:

(add-hook 'c-mode-common-hook
          (lambda () (font-lock-add-keywords nil
           '(("\\<\\(bla[a-zA-Z1-9_]*\\)" 1 font-lock-warning-face t)))))

This code color all keywords that start with "bla". Example: blaTest123_test

However when I try to add @ (the 'at' symbol) instead of "bla", it doesn't seem to work. I don't think @ is a special character for regular expressions.

Do you know how I can get emacs to highlight keywords starting with the @ symbol?


Solution

  • Your problem is the \< in your regexp, which

    matches the empty string, but only at the beginning of a word. `\<' matches at the beginning of the buffer (or string) only if a word-constituent character follows.

    and @ is not a word-constituent character.

    See: M-: (info "(elisp) Regexp Backslash") RET

    This unrestricted pattern will colour any @:

    (font-lock-add-keywords nil
      '(("@" 0 font-lock-warning-face t)))
    

    And this will do something like what you want, by requiring either BOL or some white space immediately beforehand.

    (font-lock-add-keywords nil
      '(("\\(?:^\\|\\s-\\)\\(@[a-zA-Z1-9_]*\\)" 1 font-lock-warning-face t)))