Search code examples
javascriptemacssyntax-highlightingfont-lock

emacs font-lock-mode for JavaScript: would like to highlight 'self' just like 'this'


Because I often have to preserve this from getting overwritten in closures, I like to do: var self = this; at the top of my constructors. I'd like to subsequently highlight self exactly how and when this is currently highlighted. However after studying the emacs documentation, websites, and examples here, and adapting the examples, it's not working. I'm evaluating this expression:

(font-lock-add-keywords 'javascript-mode
        '(("self" . 'font-lock-keyword-face)))

both in my .emacs file and in the javascript buffer, and also toggling font-lock-mode to force a refresh. I've tried variations with the confusing "\\<self\\>" syntax but I'm clearly throwing darts because that also fails. I see many variations of font-lock-add-keywords but being only an Emacs power user and not a developer, it seems byzantine.

As context, this is GNU Emacs 24.5.1 running as a native Mac OS X 10.11.5 App, not in terminal.


Solution

  • Interesting how posting here improves my own troubleshooting. :-)

    JavaScript mode is actually js-mode, not javascript-mode. I don't have the patience to figure out why there's two, probably historical. So this worked, fixing two niceties (word boundary, and correct face) along the way:

    (add-hook 'js-mode-hook (lambda() 
              (font-lock-add-keywords 'js-mode '(("\\<self\\>" . 'font-lock-constant-face)))))