font-lock.el 101 KB
Newer Older
1
;;; font-lock.el --- Electric font lock mode  -*- lexical-binding:t -*-
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1992-2019 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

5 6 7
;; Author: Jamie Zawinski
;;	Richard Stallman
;;	Stefan Monnier
8
;; Maintainer: emacs-devel@gnu.org
Richard M. Stallman's avatar
Richard M. Stallman committed
9
;; Keywords: languages, faces
10
;; Package: emacs
Richard M. Stallman's avatar
Richard M. Stallman committed
11 12 13

;; This file is part of GNU Emacs.

14
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
15
;; it under the terms of the GNU General Public License as published by
16 17
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
18 19 20 21 22 23 24

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
25
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
26 27 28

;;; Commentary:

29 30
;; Font Lock mode is a minor mode that causes your comments to be displayed in
;; one face, strings in another, reserved words in another, and so on.
Richard M. Stallman's avatar
Richard M. Stallman committed
31 32 33
;;
;; Comments will be displayed in `font-lock-comment-face'.
;; Strings will be displayed in `font-lock-string-face'.
34
;; Regexps are used to display selected patterns in other faces.
Richard M. Stallman's avatar
Richard M. Stallman committed
35
;;
36 37 38
;; To make the text you type be fontified, use M-x font-lock-mode RET.
;; When this minor mode is on, the faces of the current line are updated with
;; every insertion or deletion.
Richard M. Stallman's avatar
Richard M. Stallman committed
39
;;
40
;; To turn Font Lock mode on automatically, add this to your init file:
Richard M. Stallman's avatar
Richard M. Stallman committed
41
;;
42
;;  (add-hook 'emacs-lisp-mode-hook #'turn-on-font-lock)
Richard M. Stallman's avatar
Richard M. Stallman committed
43
;;
44 45 46 47
;; Or if you want to turn Font Lock mode on in many modes:
;;
;;  (global-font-lock-mode t)
;;
48 49 50
;; Fontification for a particular mode may be available in a number of levels
;; of decoration.  The higher the level, the more decoration, but the more time
;; it takes to fontify.  See the variable `font-lock-maximum-decoration', and
51 52
;; also the variable `font-lock-maximum-size'.  Support modes for Font Lock
;; mode can be used to speed up Font Lock mode.  See `font-lock-support-mode'.
53

54 55 56 57 58 59 60 61 62 63
;;; How Font Lock mode fontifies:

;; When Font Lock mode is turned on in a buffer, it (a) fontifies the entire
;; buffer and (b) installs one of its fontification functions on one of the
;; hook variables that are run by Emacs after every buffer change (i.e., an
;; insertion or deletion).  Fontification means the replacement of `face' text
;; properties in a given region; Emacs displays text with these `face' text
;; properties appropriately.
;;
;; Fontification normally involves syntactic (i.e., strings and comments) and
64 65 66 67 68 69
;; regexp (i.e., keywords and everything else) passes.  There are actually
;; three passes; (a) the syntactic keyword pass, (b) the syntactic pass and (c)
;; the keyword pass.  Confused?
;;
;; The syntactic keyword pass places `syntax-table' text properties in the
;; buffer according to the variable `font-lock-syntactic-keywords'.  It is
70
;; necessary because Emacs's syntax table is not powerful enough to describe all
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
;; the different syntactic constructs required by the sort of people who decide
;; that a single quote can be syntactic or not depending on the time of day.
;; (What sort of person could decide to overload the meaning of a quote?)
;; Obviously the syntactic keyword pass must occur before the syntactic pass.
;;
;; The syntactic pass places `face' text properties in the buffer according to
;; syntactic context, i.e., according to the buffer's syntax table and buffer
;; text's `syntax-table' text properties.  It involves using a syntax parsing
;; function to determine the context of different parts of a region of text.  A
;; syntax parsing function is necessary because generally strings and/or
;; comments can span lines, and so the context of a given region is not
;; necessarily apparent from the content of that region.  Because the keyword
;; pass only works within a given region, it is not generally appropriate for
;; syntactic fontification.  This is the first fontification pass that makes
;; changes visible to the user; it fontifies strings and comments.
;;
;; The keyword pass places `face' text properties in the buffer according to
;; the variable `font-lock-keywords'.  It involves searching for given regexps
;; (or calling given search functions) within the given region.  This is the
;; second fontification pass that makes changes visible to the user; it
;; fontifies language reserved words, etc.
;;
;; Oh, and the answer is, "Yes, obviously just about everything should be done
;; in a single syntactic pass, but the only syntactic parser available
;; understands only strings and comments."  Perhaps one day someone will write
;; some syntactic parsers for common languages and a son-of-font-lock.el could
;; use them rather then relying so heavily on the keyword (regexp) pass.
98

99 100 101 102
;;; How Font Lock mode supports modes or is supported by modes:

;; Modes that support Font Lock mode do so by defining one or more variables
;; whose values specify the fontification.  Font Lock mode knows of these
103 104 105 106
;; variable names from the buffer local variable `font-lock-defaults'.
;; (Font Lock mode is set up via (a) where a mode's patterns are
;; distributed with the mode's package library, and (b) where a mode's
;; patterns are distributed with font-lock.el itself.  An example of (a)
107 108 109 110
;; is Pascal mode, an example of (b) is Lisp mode.  Normally, the mechanism is
;; (a); (b) is used where it is not clear which package library should contain
;; the pattern definitions.)  Font Lock mode chooses which variable to use for
;; fontification based on `font-lock-maximum-decoration'.
111
;;
Glenn Morris's avatar
Glenn Morris committed
112
;; Font Lock mode fontification behavior can be modified in a number of ways.
113
;; See the below comments and the comments distributed throughout this file.
114 115 116

;;; Constructing patterns:

117 118
;; See the documentation for the variable `font-lock-keywords'.
;;
119 120
;; Efficient regexps for use as MATCHERs for `font-lock-keywords' and
;; `font-lock-syntactic-keywords' can be generated via the function
121
;; `regexp-opt'.
122

123 124 125 126 127 128 129 130
;;; Adding patterns for modes that already support Font Lock:

;; Though Font Lock highlighting patterns already exist for many modes, it's
;; likely there's something that you want fontified that currently isn't, even
;; at the maximum fontification level.  You can add highlighting patterns via
;; `font-lock-add-keywords'.  For example, say in some C
;; header file you #define the token `and' to expand to `&&', etc., to make
;; your C code almost readable.  In your ~/.emacs there could be:
131
;;
132
;;  (font-lock-add-keywords 'c-mode '("\\<\\(and\\|or\\|not\\)\\>"))
133
;;
134 135 136 137 138 139 140 141 142 143 144 145 146
;; Some modes provide specific ways to modify patterns based on the values of
;; other variables.  For example, additional C types can be specified via the
;; variable `c-font-lock-extra-types'.

;;; Adding patterns for modes that do not support Font Lock:

;; Not all modes support Font Lock mode.  If you (as a user of the mode) add
;; patterns for a new mode, you must define in your ~/.emacs a variable or
;; variables that specify regexp fontification.  Then, you should indicate to
;; Font Lock mode, via the mode hook setting `font-lock-defaults', exactly what
;; support is required.  For example, say Foo mode should have the following
;; regexps fontified case-sensitively, and comments and strings should not be
;; fontified automagically.  In your ~/.emacs there could be:
147
;;
148
;;  (defvar foo-font-lock-keywords
149 150
;;    '(("\\<\\(one\\|two\\|three\\)\\>" . 'font-lock-keyword-face)
;;      ("\\<\\(four\\|five\\|six\\)\\>" . 'font-lock-type-face))
151
;;    "Default expressions to highlight in Foo mode.")
152
;;
153
;;  (add-hook 'foo-mode-hook
154
;;   (lambda ()
155 156
;;     (set (make-local-variable 'font-lock-defaults)
;;          '(foo-font-lock-keywords t))))
157 158 159 160 161 162 163 164 165 166 167

;;; Adding Font Lock support for modes:

;; Of course, it would be better that the mode already supports Font Lock mode.
;; The package author would do something similar to above.  The mode must
;; define at the top-level a variable or variables that specify regexp
;; fontification.  Then, the mode command should indicate to Font Lock mode,
;; via `font-lock-defaults', exactly what support is required.  For example,
;; say Bar mode should have the following regexps fontified case-insensitively,
;; and comments and strings should be fontified automagically.  In bar.el there
;; could be:
168
;;
169
;;  (defvar bar-font-lock-keywords
170 171
;;    '(("\\<\\(uno\\|due\\|tre\\)\\>" . 'font-lock-keyword-face)
;;      ("\\<\\(quattro\\|cinque\\|sei\\)\\>" . 'font-lock-type-face))
172
;;    "Default expressions to highlight in Bar mode.")
173
;;
174
;; and within `bar-mode' there could be:
175
;;
176 177
;;  (set (make-local-variable 'font-lock-defaults)
;;       '(bar-font-lock-keywords nil t))
178

179 180 181 182 183 184 185 186 187
;; What is fontification for?  You might say, "It's to make my code look nice."
;; I think it should be for adding information in the form of cues.  These cues
;; should provide you with enough information to both (a) distinguish between
;; different items, and (b) identify the item meanings, without having to read
;; the items and think about it.  Therefore, fontification allows you to think
;; less about, say, the structure of code, and more about, say, why the code
;; doesn't work.  Or maybe it allows you to think less and drift off to sleep.
;;
;; So, here are my opinions/advice/guidelines:
188
;;
189 190 191 192 193
;; - Highlight conceptual objects, such as function and variable names, and
;;   different objects types differently, i.e., (a) and (b) above, highlight
;;   function names differently to variable names.
;; - Keep the faces distinct from each other as far as possible.
;;   i.e., (a) above.
194 195 196 197
;; - Use the same face for the same conceptual object, across all modes.
;;   i.e., (b) above, all modes that have items that can be thought of as, say,
;;   keywords, should be highlighted with the same face, etc.
;; - Make the face attributes fit the concept as far as possible.
Glenn Morris's avatar
Glenn Morris committed
198 199
;;   i.e., function names might be a bold color such as blue, comments might
;;   be a bright color such as red, character strings might be brown, because,
200 201 202 203 204 205
;;   err, strings are brown (that was not the reason, please believe me).
;; - Don't use a non-nil OVERRIDE unless you have a good reason.
;;   Only use OVERRIDE for special things that are easy to define, such as the
;;   way `...' quotes are treated in strings and comments in Emacs Lisp mode.
;;   Don't use it to, say, highlight keywords in commented out code or strings.
;; - Err, that's it.
206

207 208
;;; Code:

Stefan Monnier's avatar
Stefan Monnier committed
209
(require 'syntax)
Stefan Monnier's avatar
Stefan Monnier committed
210
(eval-when-compile (require 'cl-lib))
Stefan Monnier's avatar
Stefan Monnier committed
211

212
;; Define core `font-lock' group.
Kenichi Handa's avatar
Kenichi Handa committed
213
(defgroup font-lock '((jit-lock custom-group))
214
  "Font Lock mode text highlighting package."
215 216
  :link '(custom-manual :tag "Emacs Manual" "(emacs)Font Lock")
  :link '(custom-manual :tag "Elisp Manual" "(elisp)Font Lock Mode")
217 218
  :group 'faces)

219
(defgroup font-lock-faces nil
220
  "Faces for highlighting text."
221
  :prefix "font-lock-"
222 223 224 225 226
  :group 'font-lock)

(defgroup font-lock-extra-types nil
  "Extra mode-specific type names for highlighting declarations."
  :group 'font-lock)
227

228 229
;; User variables.

230
(defcustom font-lock-maximum-size 256000
231 232 233 234 235
  "Maximum buffer size for unsupported buffer fontification.
When `font-lock-support-mode' is nil, only buffers smaller than
this are fontified.  This variable has no effect if a Font Lock
support mode (usually `jit-lock-mode') is enabled.

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
If nil, means size is irrelevant.
If a list, each element should be a cons pair of the form (MAJOR-MODE . SIZE),
where MAJOR-MODE is a symbol or t (meaning the default).  For example:
 ((c-mode . 256000) (c++-mode . 256000) (rmail-mode . 1048576))
means that the maximum size is 250K for buffers in C or C++ modes, one megabyte
for buffers in Rmail mode, and size is irrelevant otherwise."
  :type '(choice (const :tag "none" nil)
		 (integer :tag "size")
		 (repeat :menu-tag "mode specific" :tag "mode specific"
			 :value ((t . nil))
			 (cons :tag "Instance"
			       (radio :tag "Mode"
				      (const :tag "all" t)
				      (symbol :tag "name"))
			       (radio :tag "Size"
				      (const :tag "none" nil)
				      (integer :tag "size")))))
253
  :group 'font-lock)
254
(make-obsolete-variable 'font-lock-maximum-size nil "24.1")
255

256
(defcustom font-lock-maximum-decoration t
Lute Kamstra's avatar
Lute Kamstra committed
257
  "Maximum decoration level for fontification.
258 259 260
If nil, use the default decoration (typically the minimum available).
If t, use the maximum decoration available.
If a number, use that level of decoration (or if not available the maximum).
261
The higher the number, the more decoration is done.
262 263
If a list, each element should be a cons pair of the form (MAJOR-MODE . LEVEL),
where MAJOR-MODE is a symbol or t (meaning the default).  For example:
264 265
 ((c-mode . t) (c++-mode . 2) (t . 1))
means use the maximum decoration available for buffers in C mode, level 2
266
decoration for buffers in C++ mode, and level 1 decoration otherwise."
Simon Marshall's avatar
Simon Marshall committed
267 268 269 270 271 272 273 274 275 276 277
  :type '(choice (const :tag "default" nil)
		 (const :tag "maximum" t)
		 (integer :tag "level" 1)
		 (repeat :menu-tag "mode specific" :tag "mode specific"
			 :value ((t . t))
			 (cons :tag "Instance"
			       (radio :tag "Mode"
				      (const :tag "all" t)
				      (symbol :tag "name"))
			       (radio :tag "Decoration"
				      (const :tag "default" nil)
Dave Love's avatar
Dave Love committed
278
				      (const :tag "maximum" t)
Simon Marshall's avatar
Simon Marshall committed
279
				      (integer :tag "level" 1)))))
280 281
  :group 'font-lock)

282
(defcustom font-lock-verbose nil
Lute Kamstra's avatar
Lute Kamstra committed
283
  "If non-nil, means show status messages for buffer fontification.
284 285
If a number, only buffers greater than this size have fontification messages."
  :type '(choice (const :tag "never" nil)
286 287
		 (other :tag "always" t)
		 (integer :tag "size"))
288 289
  :group 'font-lock
  :version "24.1")
290

291 292 293 294 295 296

;; Originally these variable values were face names such as `bold' etc.
;; Now we create our own faces, but we keep these variables for compatibility
;; and they give users another mechanism for changing face appearance.
;; We now allow a FACENAME in `font-lock-keywords' to be any expression that
;; returns a face.  So the easiest thing is to continue using these variables,
Paul Eggert's avatar
Paul Eggert committed
297
;; rather than sometimes evalling FACENAME and sometimes not.  sm.
Glenn Morris's avatar
Glenn Morris committed
298 299 300 301 302

;; Note that in new code, in the vast majority of cases there is no
;; need to create variables that specify face names.  Simply using
;; faces directly is enough.  Font-lock is not a template to be
;; followed in this area.
303 304 305
(defvar font-lock-comment-face		'font-lock-comment-face
  "Face name to use for comments.")

306
(defvar font-lock-comment-delimiter-face 'font-lock-comment-delimiter-face
307
  "Face name to use for comment delimiters.")
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
(defvar font-lock-string-face		'font-lock-string-face
  "Face name to use for strings.")

(defvar font-lock-doc-face		'font-lock-doc-face
  "Face name to use for documentation.")

(defvar font-lock-keyword-face		'font-lock-keyword-face
  "Face name to use for keywords.")

(defvar font-lock-builtin-face		'font-lock-builtin-face
  "Face name to use for builtins.")

(defvar font-lock-function-name-face	'font-lock-function-name-face
  "Face name to use for function names.")

(defvar font-lock-variable-name-face	'font-lock-variable-name-face
  "Face name to use for variable names.")

(defvar font-lock-type-face		'font-lock-type-face
  "Face name to use for type and class names.")

Glenn Morris's avatar
Glenn Morris committed
330 331 332
(define-obsolete-variable-alias
  'font-lock-reference-face 'font-lock-constant-face "20.3")

333 334 335 336 337 338
(defvar font-lock-constant-face		'font-lock-constant-face
  "Face name to use for constant and label names.")

(defvar font-lock-warning-face		'font-lock-warning-face
  "Face name to use for things that should stand out.")

339 340 341 342
(defvar font-lock-negation-char-face	'font-lock-negation-char-face
  "Face name to use for easy to overlook negation.
This can be an \"!\" or the \"n\" in \"ifndef\".")

343 344 345
(defvar font-lock-preprocessor-face	'font-lock-preprocessor-face
  "Face name to use for preprocessor directives.")

346 347
;; Fontification variables:

Richard M. Stallman's avatar
Richard M. Stallman committed
348
(defvar font-lock-keywords nil
349
  "A list of the keywords to highlight.
350 351 352 353 354 355 356 357 358
There are two kinds of values: user-level, and compiled.

A user-level keywords list is what a major mode or the user would
set up.  Normally the list would come from `font-lock-defaults'.
through selection of a fontification level and evaluation of any
contained expressions.  You can also alter it by calling
`font-lock-add-keywords' or `font-lock-remove-keywords' with MODE = nil.

Each element in a user-level keywords list should have one of these forms:
359

360
 MATCHER
361
 (MATCHER . SUBEXP)
362 363 364
 (MATCHER . FACENAME)
 (MATCHER . HIGHLIGHT)
 (MATCHER HIGHLIGHT ...)
365
 (eval . FORM)
366

367 368 369 370 371 372 373 374 375 376 377
where MATCHER can be either the regexp to search for, or the
function name to call to make the search (called with one
argument, the limit of the search; it should return non-nil, move
point, and set `match-data' appropriately if it succeeds; like
`re-search-forward' would).  MATCHER regexps can be generated via
the function `regexp-opt'.

FORM is an expression, whose value should be a keyword element,
evaluated when the keyword is (first) used in a buffer.  This
feature can be used to provide a keyword that can only be
generated when Font Lock mode is actually turned on.
378

Stefan Monnier's avatar
Stefan Monnier committed
379 380
HIGHLIGHT should be either MATCH-HIGHLIGHT or MATCH-ANCHORED.

381 382 383 384 385 386
For highlighting single items, for example each instance of the
word \"foo\", typically only MATCH-HIGHLIGHT is required.
However, if an item or (typically) items are to be highlighted
following the instance of another item (the anchor), for example
each instance of the word \"bar\" following the word \"anchor\"
then MATCH-ANCHORED may be required.
387 388 389

MATCH-HIGHLIGHT should be of the form:

390
 (SUBEXP FACENAME [OVERRIDE [LAXMATCH]])
391

392 393
SUBEXP is the number of the subexpression of MATCHER to be
highlighted.
394 395

FACENAME is an expression whose value is the face name to use.
396 397 398 399 400
Instead of a face, FACENAME can evaluate to a property list of
the form (face FACE PROP1 VAL1 PROP2 VAL2 ...)  in which case all
the listed text-properties will be set rather than just FACE.  In
such a case, you will most likely want to put those properties in
`font-lock-extra-managed-props' or to override
Stefan Monnier's avatar
Stefan Monnier committed
401
`font-lock-unfontify-region-function'.
402

403 404 405 406 407 408
OVERRIDE and LAXMATCH are flags.  If OVERRIDE is t, existing
fontification can be overwritten.  If `keep', only parts not
already fontified are highlighted.  If `prepend' or `append',
existing fontification is merged with the new, in which the new
or existing fontification, respectively, takes precedence.  If
LAXMATCH is non-nil, that means don't signal an error if there is
409
no match for SUBEXP in MATCHER.
410

411 412 413 414 415 416 417 418 419 420 421 422 423
For example, an element of the form highlights (if not already
highlighted):

 \"\\\\\\=<foo\\\\\\=>\"
  Discrete occurrences of \"foo\" in the value of the variable
  `font-lock-keyword-face'.

 (\"fu\\\\(bar\\\\)\" . 1)
  Substring \"bar\" within all occurrences of \"fubar\" in the
  value of `font-lock-keyword-face'.

 (\"fubar\" . fubar-face)
  Occurrences of \"fubar\" in the value of `fubar-face'.
424 425

 (\"foo\\\\|bar\" 0 foo-bar-face t)
426 427 428
  Occurrences of either \"foo\" or \"bar\" in the value of
  `foo-bar-face', even if already highlighted.

429
 (fubar-match 1 fubar-face)
430 431 432
  The first subexpression within all occurrences of whatever the
  function `fubar-match' finds and matches in the value of
  `fubar-face'.
433 434 435 436 437

MATCH-ANCHORED should be of the form:

 (MATCHER PRE-MATCH-FORM POST-MATCH-FORM MATCH-HIGHLIGHT ...)

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
where MATCHER is a regexp to search for or the function name to
call to make the search, as for MATCH-HIGHLIGHT above, but with
one exception; see below.  PRE-MATCH-FORM and POST-MATCH-FORM are
evaluated before the first, and after the last, instance
MATCH-ANCHORED's MATCHER is used.  Therefore they can be used to
initialize before, and cleanup after, MATCHER is used.
Typically, PRE-MATCH-FORM is used to move to some position
relative to the original MATCHER, before starting with
MATCH-ANCHORED's MATCHER.  POST-MATCH-FORM might be used to move
back, before resuming with MATCH-ANCHORED's parent's MATCHER.

For example, an element of the form highlights (if not already
highlighted):

 (\"\\\\\\=<anchor\\\\\\=>\" (0 anchor-face)
  (\"\\\\\\=<item\\\\\\=>\" nil nil (0 item-face)))

  Discrete occurrences of \"anchor\" in the value of
  `anchor-face', and subsequent discrete occurrences of
  \"item\" (on the same line) in the value of `item-face'.
  (Here PRE-MATCH-FORM and POST-MATCH-FORM are nil.  Therefore
  \"item\" is initially searched for starting from the end of the
  match of \"anchor\", and searching for subsequent instances of
  \"anchor\" resumes from where searching for \"item\" concluded.)

The above-mentioned exception is as follows.  The limit of the
MATCHER search defaults to the end of the line after
PRE-MATCH-FORM is evaluated.  However, if PRE-MATCH-FORM returns
a position greater than the position after PRE-MATCH-FORM is
evaluated, that position is used as the limit of the search.  It
is generally a bad idea to return a position greater than the end
of the line, i.e., cause the MATCHER search to span lines.

These regular expressions can match text which spans lines,
although it is better to avoid it if possible since updating them
while editing text is slower, and it is not guaranteed to be
always correct when using support modes like jit-lock or
lazy-lock.

This variable is set by major modes via the variable
`font-lock-defaults'.  Be careful when composing regexps for this
list; a poorly written pattern can dramatically slow things down!

A compiled keywords list starts with t.  It is produced
internally by `font-lock-compile-keywords' from a user-level
keywords list.  Its second element is the user-level keywords
list that was compiled.  The remaining elements have the same
form as user-level keywords, but normally their values have been
486
optimized.")
Richard M. Stallman's avatar
Richard M. Stallman committed
487

488
(defvar font-lock-keywords-alist nil
489 490
  "Alist of additional `font-lock-keywords' elements for major modes.

491
Each element has the form (MODE KEYWORDS . HOW).
492
Function `font-lock-set-defaults' adds the elements in the list KEYWORDS to
493 494
`font-lock-keywords' when Font Lock is turned on in major mode MODE.

495
If HOW is nil, KEYWORDS are added at the beginning of
496
`font-lock-keywords'.  If it is `set', they are used to replace the
497
value of `font-lock-keywords'.  If HOW is any other non-nil value,
498 499
they are added at the end.

500 501
This is normally set via `font-lock-add-keywords' and
`font-lock-remove-keywords'.")
502
(put 'font-lock-keywords-alist 'risky-local-variable t)
503 504

(defvar font-lock-removed-keywords-alist nil
505 506
  "Alist of `font-lock-keywords' elements to be removed for major modes.

507
Each element has the form (MODE . KEYWORDS).  Function `font-lock-set-defaults'
508 509 510
removes the elements in the list KEYWORDS from `font-lock-keywords'
when Font Lock is turned on in major mode MODE.

511 512
This is normally set via `font-lock-add-keywords' and
`font-lock-remove-keywords'.")
513

514
(defvar font-lock-keywords-only nil
515
  "Non-nil means Font Lock should not fontify comments or strings.
516
This is normally set via `font-lock-defaults'.")
517

Richard M. Stallman's avatar
Richard M. Stallman committed
518
(defvar font-lock-keywords-case-fold-search nil
519
  "Non-nil means the patterns in `font-lock-keywords' are case-insensitive.
520 521
This is set via the function `font-lock-set-defaults', based on
the CASE-FOLD argument of `font-lock-defaults'.")
522
(make-variable-buffer-local 'font-lock-keywords-case-fold-search)
Richard M. Stallman's avatar
Richard M. Stallman committed
523

524 525 526 527 528 529
(defvar font-lock-syntactically-fontified 0
  "Point up to which `font-lock-syntactic-keywords' has been applied.
If nil, this is ignored, in which case the syntactic fontification may
sometimes be slightly incorrect.")
(make-variable-buffer-local 'font-lock-syntactically-fontified)

530 531 532 533 534 535
(defvar font-lock-syntactic-face-function
  (lambda (state)
    (if (nth 3 state) font-lock-string-face font-lock-comment-face))
  "Function to determine which face to use when fontifying syntactically.
The function is called with a single parameter (the state as returned by
`parse-partial-sexp' at the beginning of the region to highlight) and
536
should return a face.  This is normally set via `font-lock-defaults'.")
537

538
(defvar font-lock-syntactic-keywords nil
539 540 541 542
  "A list of the syntactic keywords to put syntax properties on.
The value can be the list itself, or the name of a function or variable
whose value is the list.

543
See `font-lock-keywords' for a description of the form of this list;
544
only the differences are stated here.  MATCH-HIGHLIGHT should be of the form:
545

546
 (SUBEXP SYNTAX OVERRIDE LAXMATCH)
547

548 549 550
where SYNTAX can be a string (as taken by `modify-syntax-entry'), a syntax
table, a cons cell (as returned by `string-to-syntax') or an expression whose
value is such a form.  OVERRIDE cannot be `prepend' or `append'.
551

552 553
Here are two examples of elements of `font-lock-syntactic-keywords'
and what they do:
554

555
 (\"\\\\$\\\\(#\\\\)\" 1 \".\")
556

557 558 559
 gives a hash character punctuation syntax (\".\") when following a
 dollar-sign character.  Hash characters in other contexts will still
 follow whatever the syntax table says about the hash character.
560

561
 (\"\\\\(\\='\\\\).\\\\(\\='\\\\)\"
562 563
  (1 \"\\\"\")
  (2 \"\\\"\"))
564

565 566 567
 gives a pair of apostrophes, which surround a single character, a
 SYNTAX of \"\\\"\" (meaning string quote syntax).  Apostrophes in other

568
 contexts will not be affected.
569

570
This is normally set via `font-lock-defaults'.")
571 572
(make-obsolete-variable 'font-lock-syntactic-keywords
                        'syntax-propertize-function "24.1")
573

574
(defvar font-lock-syntax-table nil
575
  "Non-nil means use this syntax table for fontifying.
576 577 578
If this is nil, the major mode's syntax table is used.
This is normally set via `font-lock-defaults'.")

579
(defvar font-lock-mark-block-function nil
580
  "Non-nil means use this function to mark a block of text.
581 582 583 584
When called with no args it should leave point at the beginning of any
enclosing textual block and mark at the end.
This is normally set via `font-lock-defaults'.")

585
(defvar font-lock-fontify-buffer-function #'font-lock-default-fontify-buffer
586 587 588
  "Function to use for fontifying the buffer.
This is normally set via `font-lock-defaults'.")

589
(defvar font-lock-unfontify-buffer-function #'font-lock-default-unfontify-buffer
590 591 592 593
  "Function to use for unfontifying the buffer.
This is used when turning off Font Lock mode.
This is normally set via `font-lock-defaults'.")

594
(defvar font-lock-fontify-region-function #'font-lock-default-fontify-region
595 596
  "Function to use for fontifying a region.
It should take two args, the beginning and end of the region, and an optional
597
third arg VERBOSE.  If VERBOSE is non-nil, the function should print status
598 599 600 601
messages.  This is normally set via `font-lock-defaults'.
If it fontifies a larger region, it should ideally return a list of the form
\(jit-lock-bounds BEG . END) indicating the bounds of the region actually
fontified.")
602

603
(defvar font-lock-unfontify-region-function #'font-lock-default-unfontify-region
604 605 606 607 608 609
  "Function to use for unfontifying a region.
It should take two args, the beginning and end of the region.
This is normally set via `font-lock-defaults'.")

(defvar font-lock-inhibit-thing-lock nil
  "List of Font Lock mode related modes that should not be turned on.
Dave Love's avatar
Dave Love committed
610
Currently, valid mode names are `fast-lock-mode', `jit-lock-mode' and
611
`lazy-lock-mode'.  This is normally set via `font-lock-defaults'.")
612
(make-obsolete-variable 'font-lock-inhibit-thing-lock nil "25.1")
613

614
(defvar-local font-lock-multiline nil
615 616 617 618 619 620
  "Whether font-lock should cater to multiline keywords.
If nil, don't try to handle multiline patterns.
If t, always handle multiline patterns.
If `undecided', don't try to handle multiline patterns until you see one.
Major/minor modes can set this variable if they know which option applies.")

621
(defvar-local font-lock-fontified nil)	; Whether we have fontified the buffer.
Richard M. Stallman's avatar
Richard M. Stallman committed
622

623 624 625
;; Font Lock mode.

(eval-when-compile
626 627 628
  ;;
  ;; Borrowed from lazy-lock.el.
  ;; We use this to preserve or protect things when modifying text properties.
629
  (defmacro save-buffer-state (&rest body)
630
    "Bind variables according to VARLIST and eval BODY restoring buffer state."
631 632
    (declare (indent 0) (debug t))
    `(let ((inhibit-point-motion-hooks t))
633
       (with-silent-modifications
634
         ,@body))))
Richard M. Stallman's avatar
Richard M. Stallman committed
635

636 637
(defvar-local font-lock-set-defaults nil) ; Whether we have set up defaults.

638 639 640 641
(defun font-lock-specified-p (mode)
  "Return non-nil if the current buffer is ready for fontification.
The MODE argument, if non-nil, means Font Lock mode is about to
be enabled."
642
  (or font-lock-defaults
643 644
      (and (boundp 'font-lock-keywords)
	   font-lock-keywords)
645 646 647 648 649
      (and mode
	   font-lock-set-defaults
	   font-lock-major-mode
	   (not (eq font-lock-major-mode major-mode)))))

650 651 652
(defun font-lock-initial-fontify ()
  ;; The first fontification after turning the mode on.  This must
  ;;  only be called after the mode hooks have been run.
653
  (when (and font-lock-mode
654
	     (font-lock-specified-p t))
655 656 657 658
    (let ((max-size (font-lock-value-in-major-mode font-lock-maximum-size)))
      (cond (font-lock-fontified
	     nil)
	    ((or (null max-size) (> max-size (buffer-size)))
659
             (with-no-warnings (font-lock-fontify-buffer)))
660 661 662
	    (font-lock-verbose
	     (message "Fontifying %s...buffer size greater than font-lock-maximum-size"
		      (buffer-name)))))))
663

664 665 666
(defun font-lock-mode-internal (arg)
  ;; Turn on Font Lock mode.
  (when arg
667
    (add-hook 'after-change-functions #'font-lock-after-change-function t t)
668
    (font-lock-set-defaults)
669
    (font-lock-turn-on-thing-lock))
670 671
  ;; Turn off Font Lock mode.
  (unless font-lock-mode
672
    (remove-hook 'after-change-functions #'font-lock-after-change-function t)
673 674 675
    (font-lock-unfontify-buffer)
    (font-lock-turn-off-thing-lock)))

676
(defun font-lock-add-keywords (mode keywords &optional how)
677
  "Add highlighting KEYWORDS for MODE.
678

679
MODE should be a symbol, the major mode command name, such as `c-mode'
680
or nil.  If nil, highlighting keywords are added for the current buffer.
681 682
KEYWORDS should be a list; see the variable `font-lock-keywords'.
By default they are added at the beginning of the current highlighting list.
683 684
If optional argument HOW is `set', they are used to replace the current
highlighting list.  If HOW is any other non-nil value, they are added at the
685
end of the current highlighting list.
686 687 688

For example:

Paul Eggert's avatar
Paul Eggert committed
689 690 691
 (font-lock-add-keywords \\='c-mode
  \\='((\"\\\\\\=<\\\\(FIXME\\\\):\" 1 \\='font-lock-warning-face prepend)
    (\"\\\\\\=<\\\\(and\\\\|or\\\\|not\\\\)\\\\\\=>\" . \\='font-lock-keyword-face)))
692 693

adds two fontification patterns for C mode, to fontify `FIXME:' words, even in
694 695
comments, and to fontify `and', `or' and `not' words as keywords.

696 697 698 699 700 701
The above procedure will only add the keywords for C mode, not
for modes derived from C mode.  To add them for derived modes too,
pass nil for MODE and add the call to c-mode-hook.

For example:

702
 (add-hook \\='c-mode-hook
703
  (lambda ()
704
   (font-lock-add-keywords nil
705
    \\='((\"\\\\\\=<\\\\(FIXME\\\\):\" 1 \\='font-lock-warning-face prepend)
706
      (\"\\\\\\=<\\\\(and\\\\|or\\\\|not\\\\)\\\\\\=>\" .
707
       \\='font-lock-keyword-face)))))
708 709 710 711

The above procedure may fail to add keywords to derived modes if
some involved major mode does not follow the standard conventions.
File a bug report if this happens, so the major mode can be corrected.
Stefan Monnier's avatar
Stefan Monnier committed
712

713
Note that some modes have specialized support for additional patterns, e.g.,
714 715
see the variables `c-font-lock-extra-types', `c++-font-lock-extra-types',
`objc-font-lock-extra-types' and `java-font-lock-extra-types'."
716
  (cond (mode
717
	 ;; If MODE is non-nil, add the KEYWORDS and HOW spec to
718
	 ;; `font-lock-keywords-alist' so `font-lock-set-defaults' uses them.
719
	 (let ((spec (cons keywords how)) cell)
720
	   (if (setq cell (assq mode font-lock-keywords-alist))
721
	       (if (eq how 'set)
722 723 724 725 726
		   (setcdr cell (list spec))
		 (setcdr cell (append (cdr cell) (list spec))))
	     (push (list mode spec) font-lock-keywords-alist)))
	 ;; Make sure that `font-lock-removed-keywords-alist' does not
	 ;; contain the new keywords.
727
	 (font-lock-update-removed-keyword-alist mode keywords how))
728
	(t
729 730 731 732 733 734 735 736
         (when (and font-lock-mode
                    (not (or font-lock-keywords font-lock-defaults)))
           ;; The major mode has not set any keywords, so when we enabled
           ;; font-lock-mode it only enabled the font-core.el part, not the
           ;; font-lock-mode-internal.  Try again.
           (font-lock-mode -1)
           (set (make-local-variable 'font-lock-defaults) '(nil t))
           (font-lock-mode 1))
737
	 ;; Otherwise set or add the keywords now.
738 739
	 ;; This is a no-op if it has been done already in this buffer
	 ;; for the correct major mode.
740
	 (font-lock-set-defaults)
741 742 743 744 745
	 (let ((was-compiled (eq (car font-lock-keywords) t)))
	   ;; Bring back the user-level (uncompiled) keywords.
	   (if was-compiled
	       (setq font-lock-keywords (cadr font-lock-keywords)))
	   ;; Now modify or replace them.
746
	   (if (eq how 'set)
747 748 749 750 751
	       (setq font-lock-keywords keywords)
	     (font-lock-remove-keywords nil keywords) ;to avoid duplicates
	     (let ((old (if (eq (car-safe font-lock-keywords) t)
			    (cdr font-lock-keywords)
			  font-lock-keywords)))
752
	       (setq font-lock-keywords (if how
753 754 755 756
					    (append old keywords)
					  (append keywords old)))))
	   ;; If the keywords were compiled before, compile them again.
	   (if was-compiled
757
	       (setq font-lock-keywords
758
                     (font-lock-compile-keywords font-lock-keywords)))))))
759

760
(defun font-lock-update-removed-keyword-alist (mode keywords how)
761
  "Update `font-lock-removed-keywords-alist' when adding new KEYWORDS to MODE."
762 763 764 765 766 767
  ;; When font-lock is enabled first all keywords in the list
  ;; `font-lock-keywords-alist' are added, then all keywords in the
  ;; list `font-lock-removed-keywords-alist' are removed.  If a
  ;; keyword was once added, removed, and then added again it must be
  ;; removed from the removed-keywords list.  Otherwise the second add
  ;; will not take effect.
768
  (let ((cell (assq mode font-lock-removed-keywords-alist)))
769
    (if cell
770
	(if (eq how 'set)
771 772 773 774 775 776 777
	    ;; A new set of keywords is defined.  Forget all about
	    ;; our old keywords that should be removed.
	    (setq font-lock-removed-keywords-alist
		  (delq cell font-lock-removed-keywords-alist))
	  ;; Delete all previously removed keywords.
	  (dolist (kword keywords)
	    (setcdr cell (delete kword (cdr cell))))
778
	  ;; Delete the mode cell if empty.
779 780 781 782
	  (if (null (cdr cell))
	      (setq font-lock-removed-keywords-alist
		    (delq cell font-lock-removed-keywords-alist)))))))

783
;; Written by Anders Lindgren
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
;;
;; Case study:
;; (I)  The keywords are removed from a major mode.
;;      In this case the keyword could be local (i.e. added earlier by
;;      `font-lock-add-keywords'), global, or both.
;;
;;      (a) In the local case we remove the keywords from the variable
;;          `font-lock-keywords-alist'.
;;
;;      (b) The actual global keywords are not known at this time.
;;          All keywords are added to `font-lock-removed-keywords-alist',
;;          when font-lock is enabled those keywords are removed.
;;
;;      Note that added keywords are taken out of the list of removed
;;      keywords.  This ensure correct operation when the same keyword
;;      is added and removed several times.
;;
;; (II) The keywords are removed from the current buffer.
802 803
(defun font-lock-remove-keywords (mode keywords)
  "Remove highlighting KEYWORDS for MODE.
804

805 806 807 808 809
MODE should be a symbol, the major mode command name, such as
`c-mode' or nil.  If nil, highlighting keywords are removed for
the current buffer.

For a description of KEYWORDS, see `font-lock-add-keywords'.
Stefan Monnier's avatar
Stefan Monnier committed
810

811 812 813 814 815
To make the removal apply to modes derived from MODE as well,
pass nil for MODE and add the call to MODE-hook.  This may fail
for some derived modes if some involved major mode does not
follow the standard conventions.  File a bug report if this
happens, so the major mode can be corrected."
816 817 818 819 820
  (cond (mode
	 ;; Remove one keyword at the time.
	 (dolist (keyword keywords)
	   (let ((top-cell (assq mode font-lock-keywords-alist)))
	     ;; If MODE is non-nil, remove the KEYWORD from
821 822
	     ;; `font-lock-keywords-alist'.
	     (when top-cell
823 824 825
	       (dolist (keyword-list-how-pair (cdr top-cell))
		 ;; `keywords-list-how-pair' is a cons with a list of
		 ;; keywords in the car top-cell and the original how
826
		 ;; argument in the cdr top-cell.
827 828 829 830
		 (setcar keyword-list-how-pair
			 (delete keyword (car keyword-list-how-pair))))
	       ;; Remove keyword list/how pair when the keyword list
	       ;; is empty and how doesn't specify `set'.  (If it
831 832 833 834 835 836 837 838 839 840 841 842 843 844
	       ;; should be deleted then previously deleted keywords
	       ;; would appear again.)
	       (let ((cell top-cell))
		 (while (cdr cell)
		   (if (and (null (car (car (cdr cell))))
			    (not (eq (cdr (car (cdr cell))) 'set)))
		       (setcdr cell (cdr (cdr cell)))
		     (setq cell (cdr cell)))))
	       ;; Final cleanup, remove major mode cell if last keyword
	       ;; was deleted.
	       (if (null (cdr top-cell))
		   (setq font-lock-keywords-alist
			 (delq top-cell font-lock-keywords-alist))))
	     ;; Remember the keyword in case it is not local.
845
	     (let ((cell (assq mode font-lock-removed-keywords-alist)))
846 847 848
	       (if cell
		   (unless (member keyword (cdr cell))
		     (nconc cell (list keyword)))
849 850 851 852 853
		 (push (cons mode (list keyword))
		       font-lock-removed-keywords-alist))))))
	(t
	 ;; Otherwise remove it immediately.
	 (font-lock-set-defaults)
854 855 856 857 858 859 860 861 862 863 864 865 866
	 (let ((was-compiled (eq (car font-lock-keywords) t)))
	   ;; Bring back the user-level (uncompiled) keywords.
	   (if was-compiled
	       (setq font-lock-keywords (cadr font-lock-keywords)))

	   ;; Edit them.
	   (setq font-lock-keywords (copy-sequence font-lock-keywords))
	   (dolist (keyword keywords)
	     (setq font-lock-keywords
		   (delete keyword font-lock-keywords)))

	   ;; If the keywords were compiled before, compile them again.
	   (if was-compiled
867
	       (setq font-lock-keywords
868
                     (font-lock-compile-keywords font-lock-keywords)))))))
869

870 871
;;; Font Lock Support mode.

872 873 874 875 876 877
;; This is the code used to interface font-lock.el with any of its add-on
;; packages, and provide the user interface.  Packages that have their own
;; local buffer fontification functions (see below) may have to call
;; `font-lock-after-fontify-buffer' and/or `font-lock-after-unfontify-buffer'
;; themselves.

878
(defcustom font-lock-support-mode 'jit-lock-mode
Lute Kamstra's avatar
Lute Kamstra committed
879
  "Support mode for Font Lock mode.
880
Support modes speed up Font Lock mode by being choosy about when fontification
881 882 883 884 885 886 887
occurs.  The default support mode, Just-in-time Lock mode (symbol
`jit-lock-mode'), is recommended.

Other, older support modes are Fast Lock mode (symbol `fast-lock-mode') and
Lazy Lock mode (symbol `lazy-lock-mode').  See those modes for more info.
However, they are no longer recommended, as Just-in-time Lock mode is better.

888 889 890 891 892 893 894 895
If nil, means support for Font Lock mode is never performed.
If a symbol, use that support mode.
If a list, each element should be of the form (MAJOR-MODE . SUPPORT-MODE),
where MAJOR-MODE is a symbol or t (meaning the default).  For example:
 ((c-mode . fast-lock-mode) (c++-mode . fast-lock-mode) (t . lazy-lock-mode))
means that Fast Lock mode is used to support Font Lock mode for buffers in C or
C++ modes, and Lazy Lock mode is used to support Font Lock mode otherwise.

896
The value of this variable is used when Font Lock mode is turned on."
Simon Marshall's avatar
Simon Marshall committed
897 898 899
  :type '(choice (const :tag "none" nil)
		 (const :tag "fast lock" fast-lock-mode)
		 (const :tag "lazy lock" lazy-lock-mode)
900
		 (const :tag "jit lock" jit-lock-mode)
Simon Marshall's avatar
Simon Marshall committed
901
		 (repeat :menu-tag "mode specific" :tag "mode specific"
902
			 :value ((t . jit-lock-mode))
Simon Marshall's avatar
Simon Marshall committed
903 904 905 906
			 (cons :tag "Instance"
			       (radio :tag "Mode"
				      (const :tag "all" t)
				      (symbol :tag "name"))
907 908
			       (radio :tag "Support"
				      (const :tag "none" nil)
Simon Marshall's avatar
Simon Marshall committed
909
				      (const :tag "fast lock" fast-lock-mode)
910 911
				      (const :tag "lazy lock" lazy-lock-mode)
				      (const :tag "JIT lock" jit-lock-mode)))
Simon Marshall's avatar
Simon Marshall committed
912
			 ))
913
  :version "21.1"
914
  :group 'font-lock)
915

916 917 918
(defvar fast-lock-mode)
(defvar lazy-lock-mode)
(defvar jit-lock-mode)
919

920 921 922 923 924 925
(declare-function fast-lock-after-fontify-buffer "fast-lock")
(declare-function fast-lock-after-unfontify-buffer "fast-lock")
(declare-function fast-lock-mode "fast-lock")
(declare-function lazy-lock-after-fontify-buffer "lazy-lock")
(declare-function lazy-lock-after-unfontify-buffer "lazy-lock")
(declare-function lazy-lock-mode "lazy-lock")
Dan Nicolaescu's avatar
Dan Nicolaescu committed
926

927
(defun font-lock-turn-on-thing-lock ()
Stefan Monnier's avatar
Stefan Monnier committed
928
  (pcase (font-lock-value-in-major-mode font-lock-support-mode)
929 930 931
    ('fast-lock-mode (fast-lock-mode t))
    ('lazy-lock-mode (lazy-lock-mode t))
    ('jit-lock-mode
932 933
     ;; Prepare for jit-lock
     (remove-hook 'after-change-functions
934
                  #'font-lock-after-change-function t)
935
     (set (make-local-variable 'font-lock-flush-function)
936
          #'jit-lock-refontify)
937
     (set (make-local-variable 'font-lock-ensure-function)
938
          #'jit-lock-fontify-now)
939 940 941 942
     ;; Prevent font-lock-fontify-buffer from fontifying eagerly the whole
     ;; buffer.  This is important for things like CWarn mode which
     ;; adds/removes a few keywords and does a refontify (which takes ages on
     ;; large files).
943
     (set (make-local-variable 'font-lock-fontify-buffer-function)
944
          #'jit-lock-refontify)
945 946 947
     ;; Don't fontify eagerly (and don't abort if the buffer is large).
     (set (make-local-variable 'font-lock-fontified) t)
     ;; Use jit-lock.
948
     (jit-lock-register #'font-lock-fontify-region
949 950 951
                        (not font-lock-keywords-only))
     ;; Tell jit-lock how we extend the region to refontify.
     (add-hook 'jit-lock-after-change-extend-region-functions
952
               #'font-lock-extend-jit-lock-region-after-change
953
               nil t))))
954 955

(defun font-lock-turn-off-thing-lock ()
956
  (cond ((bound-and-true-p fast-lock-mode)
957
	 (fast-lock-mode -1))
958
	((bound-and-true-p jit-lock-mode)
959 960 961
	 (jit-lock-unregister 'font-lock-fontify-region)
	 ;; Reset local vars to the non-jit-lock case.
	 (kill-local-variable 'font-lock-fontify-buffer-function))
962
	((bound-and-true-p lazy-lock-mode)
963
	 (lazy-lock-mode -1))))
964 965

(defun font-lock-after-fontify-buffer ()
966
  (cond ((bound-and-true-p fast-lock-mode)
967
	 (fast-lock-after-fontify-buffer))
968 969 970
	;; Useless now that jit-lock intercepts font-lock-fontify-buffer.  -sm
	;; (jit-lock-mode
	;;  (jit-lock-after-fontify-buffer))
971
	((bound-and-true-p lazy-lock-mode)
972 973 974
	 (lazy-lock-after-fontify-buffer))))

(defun font-lock-after-unfontify-buffer ()
975
  (cond ((bound-and-true-p fast-lock-mode)
976
	 (fast-lock-after-unfontify-buffer))
977 978 979 980 981
	;; Useless as well.  It's only called when:
	;; - turning off font-lock: it does not matter if we leave spurious
	;;   `fontified' text props around since jit-lock-mode is also off.
	;; - font-lock-default-fontify-buffer fails: this is not run
	;;   any more anyway.   -sm
982
	;;
983 984
	;; (jit-lock-mode
	;;  (jit-lock-after-unfontify-buffer))
985
	((bound-and-true-p lazy-lock-mode)
986 987
	 (lazy-lock-after-unfontify-buffer))))

988
;;; End of Font Lock Support mode.
989

990
;;; Fontification functions.
991

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
;; Rather than the function, e.g., `font-lock-fontify-region' containing the
;; code to fontify a region, the function runs the function whose name is the
;; value of the variable, e.g., `font-lock-fontify-region-function'.  Normally,
;; the value of this variable is, e.g., `font-lock-default-fontify-region'
;; which does contain the code to fontify a region.  However, the value of the
;; variable could be anything and thus, e.g., `font-lock-fontify-region' could
;; do anything.  The indirection of the fontification functions gives major
;; modes the capability of modifying the way font-lock.el fontifies.  Major
;; modes can modify the values of, e.g., `font-lock-fontify-region-function',
;; via the variable `font-lock-defaults'.
;;
;; For example, Rmail mode sets the variable `font-lock-defaults' so that
;; font-lock.el uses its own function for buffer fontification.  This function
;; makes fontification be on a message-by-message basis and so visiting an
;; RMAIL file is much faster.  A clever implementation of the function might
;; fontify the headers differently than the message body.  (It should, and
;; correspondingly for Mail mode, but I can't be bothered to do the work.  Can
;; you?)  This hints at a more interesting use...
;;
;; Languages that contain text normally contained in different major modes
;; could define their own fontification functions that treat text differently
;; depending on its context.  For example, Perl mode could arrange that here
;; docs are fontified differently than Perl code.  Or Yacc mode could fontify
;; rules one way and C code another.  Neat!
;;
;; A further reason to use the fontification indirection feature is when the
Paul Eggert's avatar
Paul Eggert committed
1018
;; default syntactic fontification, or the default fontification in general,
1019
;; is not flexible enough for a particular major mode.  For example, perhaps
1020 1021 1022 1023
;; comments are just too hairy for `font-lock-fontify-syntactically-region' to
;; cope with.  You need to write your own version of that function, e.g.,
;; `hairy-fontify-syntactically-region', and make your own version of
;; `hairy-fontify-region' call that function before calling
1024 1025 1026
;; `font-lock-fontify-keywords-region' for the normal regexp fontification
;; pass.  And Hairy mode would set `font-lock-defaults' so that font-lock.el
;; would call your region fontification function instead of its own.  For
1027
;; example, TeX modes could fontify {\foo ...} and \bar{...}  etc. multi-line
1028 1029 1030
;; directives correctly and cleanly.  (It is the same problem as fontifying
;; multi-line strings and comments; regexps are not appropriate for the job.)

1031
(defvar font-lock-extend-after-change-region-function nil
1032
  "A function that determines the region to refontify after a change.
1033 1034 1035 1036 1037 1038 1039 1040

This variable is either nil, or is a function that determines the
region to refontify after a change.
It is usually set by the major mode via `font-lock-defaults'.
Font-lock calls this function after each buffer change.

The function is given three parameters, the standard BEG, END, and OLD-LEN
from `after-change-functions'.  It should return either a cons of the beginning
1041
and end buffer positions \(in that order) of the region to refontify, or nil
1042 1043
\(which directs the caller to fontify a default region).
This function should preserve the match-data.
1044
The region it returns may start or end in the middle of a line.")
1045
(make-variable-buffer-local 'font-lock-extend-after-change-region-function)
1046

1047
(defun font-lock-fontify-buffer (&optional interactively)
Dave Love's avatar
Dave Love committed
1048
  "Fontify the current buffer the way the function `font-lock-mode' would."
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  (declare
   ;; When called from Lisp, this function is a big mess.  The caller usually
   ;; expects one of the following behaviors:
   ;; - refresh the highlighting (because the font-lock-keywords have been
   ;;   changed).
   ;; - apply font-lock highlighting even if font-lock-mode is not enabled.
   ;; - reset the highlighting rules because font-lock-defaults
   ;;   has been changed (and then rehighlight everything).
   ;; Of course, this function doesn't do all of the above in all situations
   ;; (e.g. depending on whether jit-lock is in use) and it can't guess what
   ;; the caller wants.
1060
   (interactive-only "use `font-lock-ensure' or `font-lock-flush' instead."))
1061
  (interactive "p")
1062
  (font-lock-set-defaults)
1063
  (let ((font-lock-verbose (or font-lock-verbose interactively)))
1064 1065 1066 1067 1068 1069
    (funcall font-lock-fontify-buffer-function)))

(defun font-lock-unfontify-buffer ()
  (funcall font-lock-unfontify-buffer-function))

(defun font-lock-fontify-region (beg end &optional loudly)
1070 1071 1072
  "Fontify the text between BEG and END.
If LOUDLY is non-nil, print status messages while fontifying.
This works by calling `font-lock-fontify-region-function'."
1073
  (font-lock-set-defaults)
1074 1075 1076
  (funcall font-lock-fontify-region-function beg end loudly))

(defun font-lock-unfontify-region (beg end)
1077 1078
  "Unfontify the text between BEG and END.
This works by calling `font-lock-unfontify-region-function'."
1079
  (save-buffer-state
1080
    (funcall font-lock-unfontify-region-function beg end)))
1081

1082 1083 1084 1085 1086 1087
(defvar font-lock-flush-function #'font-lock-after-change-function
  "Function to use to mark a region for refontification.
Called with two arguments BEG and END.")

(defun font-lock-flush (&optional beg end)
  "Declare the region BEG...END's fontification as out-of-date.
1088 1089
If the region is not specified, it defaults to the entire
accessible portion of the current buffer."
1090 1091 1092 1093 1094 1095
  (and font-lock-mode
       font-lock-fontified
       (funcall font-lock-flush-function
                (or beg (point-min)) (or end (point-max)))))

(defvar font-lock-ensure-function
1096
  (lambda (beg end)
1097
    (unless font-lock-fontified
1098
      (save-excursion
1099
        (font-lock-fontify-region beg end))))
1100 1101 1102 1103 1104
  "Function to make sure a region has been fontified.
Called with two arguments BEG and END.")

(defun font-lock-ensure (&optional beg end)
  "Make sure the region BEG...END has been fontified.
1105 1106
If the region is not specified, it defaults to the entire accessible
portion of the buffer."
1107 1108 1109 1110
  (font-lock-set-defaults)
  (funcall font-lock-ensure-function
           (or beg (point-min)) (or end (point-max))))

1111
(defun font-lock-default-fontify-buffer ()
Chong Yidong's avatar
Chong Yidong committed
1112
  "Fontify the whole buffer using `font-lock-fontify-region-function'."
1113 1114 1115
  (let ((verbose (if (numberp font-lock-verbose)
		     (> (buffer-size) font-lock-verbose)
		   font-lock-verbose)))
1116
    (with-temp-message
1117 1118
	(when verbose
	  (format "Fontifying %s..." (buffer-name)))
1119 1120
      ;; Make sure we fontify etc. in the whole buffer.
      (save-restriction
1121
        (unless font-lock-dont-widen (widen))
1122 1123 1124 1125 1126 1127 1128
	(condition-case nil
	    (save-excursion
	      (save-match-data
		(font-lock-fontify-region (point-min) (point-max) verbose)
		(font-lock-after-fontify-buffer)
		(setq font-lock-fontified t)))
	  ;; We don't restore the old fontification, so it's best to unfontify.
Stefan Monnier's avatar
Stefan Monnier committed
1129
	  (quit (font-lock-unfontify-buffer)))))))
1130

1131
(defun font-lock-default-unfontify-buffer ()
1132
  "Unfontify the whole buffer using `font-lock-unfontify-region-function'."
1133
  ;; Make sure we unfontify etc. in the whole buffer.
1134 1135 1136
  (save-restriction
    (widen)
    (font-lock-unfontify-region (point-min) (point-max))
1137
    (font-lock-after-unfontify-buffer)
1138
    (setq font-lock-fontified nil)))
1139

1140 1141 1142 1143 1144
(defvar font-lock-dont-widen nil
  "If non-nil, font-lock will work on the non-widened buffer.
Useful for things like RMAIL and Info where the whole buffer is not
a very meaningful entity to highlight.")

1145 1146 1147 1148

(defvar font-lock-beg) (defvar font-lock-end)
(defvar font-lock-extend-region-functions
  '(font-lock-extend-region-wholelines
1149 1150 1151 1152 1153 1154
    ;; This use of font-lock-multiline property is unreliable but is just
    ;; a handy heuristic: in case you don't have a function that does
    ;; /identification/ of multiline elements, you may still occasionally
    ;; discover them by accident (or you may /identify/ them but not in all
    ;; cases), in which case the font-lock-multiline property can help make
    ;; sure you will properly *re*identify them during refontification.
1155