I'm new to emacs (spacemacs) and have been trying to get org-mode to highlight quoted strings "like this" and quoted strings 'like this'. I followed the example here, and came up with this:

  ;; Fancy custom syntax highlighting of quoted strings!
  (add-hook 'org-mode-hook
            (lambda ()
              (font-lock-add-keywords nil '(("\".*?\"" 1 font-lock-constant-face t)
                                            ("'.*?'" 1 font-lock-doc-face t)))))

This seems to break syntax highlighting all together, and doesn't succeed in higlighting my quoted strings at all. What am I doing wrong?

  • 1
    There's a great series of articles on font lock by Sebastian Wiesner here: 1, 2, 3 – izkon Nov 2 '17 at 23:14
  • @izkon your links no longer work. Would it be possible to update these ? – Axel Bregnsbo Mar 21 at 20:08

For strings and comments it's better to use syntactic fontification. The syntax table for a given major mode has to be defined in variable <major-mode-name>-syntax-table.

This entry from the Emacs manual helps clarifying how Font Lock works: Font Lock mode finds text to highlight in two ways: through syntactic parsing based on the syntax table, and through searching (usually for regular expressions). Syntactic fontification happens first; it finds comments and string constants and highlights them. Search-based fontification happens second.

Now, there are a couple of problems with your code:

  • Your regexp is badly written. To escape characters within a regexp string you have to use \\, so "\".*?\"" should be "\\".*?\\"".

  • Don't put the code on a hook, just add (font-lock-add-keywords 'org-mode ...) to your init file. Otherwise, whenever you enter Org mode you'll be adding that entry to font-lock-keywords.

  • The fontification definition is badly writen. The number is used for groups, which you have none and so you should be using ("\\".*?\\"" 0 'font-lock-constant-face t). Read the documentation of font-lock-keywords for further details. It's pretty helpful.

  • If you need to use more complex regexps take a look at package rx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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