15.13.1 Traditional Font Lock

“Traditional” methods of providing font-lock information are based on regular-expression search and on syntactic analysis using syntax tables built into Emacs. This subsection describes the use and customization of font-lock for major modes which use these traditional methods.

You can control the amount of fontification applied by Font Lock mode by customizing the variable font-lock-maximum-decoration, for major modes that support this feature. The value of this variable should be a number (with 1 representing a minimal amount of fontification; some modes support levels as high as 3); or t, meaning “as high as possible” (the default). To be effective for a given file buffer, the customization of font-lock-maximum-decoration should be done before the file is visited; if you already have the file visited in a buffer when you customize this variable, kill the buffer and visit the file again after the customization.

You can also specify different numbers for particular major modes; for example, to use level 1 for C/C++ modes, and the default level otherwise, use the value

'((c-mode . 1) (c++-mode . 1)))

Comment and string fontification (or “syntactic” fontification) relies on analysis of the syntactic structure of the buffer text. For the sake of speed, some modes, including Lisp mode, rely on a special convention: an open-parenthesis or open-brace in the leftmost column always defines the beginning of a defun, and is thus always outside any string or comment. Therefore, you should avoid placing an open-parenthesis or open-brace in the leftmost column, if it is inside a string or comment. See Left Margin Convention, for details.

Font Lock highlighting patterns already exist for most modes, but you may want to fontify additional patterns. You can use the function font-lock-add-keywords, to add your own highlighting patterns for a particular mode. For example, to highlight ‘FIXME:’ words in C comments, use this:

(add-hook 'c-mode-hook
          (lambda ()
           (font-lock-add-keywords nil
            '(("\\<\\(FIXME\\):" 1
               font-lock-warning-face t)))))

To remove keywords from the font-lock highlighting patterns, use the function font-lock-remove-keywords. See Search-based Fontification in The Emacs Lisp Reference Manual. Alternatively, you can selectively disable highlighting due to some keywords by customizing the font-lock-ignore option, see Customizing Keywords in The Emacs Lisp Reference Manual.