(view-file-other-window): Re-add missing argument to
[bpt/emacs.git] / lisp / font-lock.el
1 ;; Electric Font Lock Mode
2 ;; Copyright (C) 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
3
4 ;; Author: jwz, then rms and sm <simon@gnu.ai.mit.edu>
5 ;; Maintainer: FSF
6 ;; Keywords: languages, faces
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;; Font Lock mode is a minor mode that causes your comments to be displayed in
27 ;; one face, strings in another, reserved words in another, and so on.
28 ;;
29 ;; Comments will be displayed in `font-lock-comment-face'.
30 ;; Strings will be displayed in `font-lock-string-face'.
31 ;; Regexps are used to display selected patterns in other faces.
32 ;;
33 ;; To make the text you type be fontified, use M-x font-lock-mode.
34 ;; When this minor mode is on, the faces of the current line are
35 ;; updated with every insertion or deletion.
36 ;;
37 ;; To turn Font Lock mode on automatically, add this to your .emacs file:
38 ;;
39 ;; (add-hook 'emacs-lisp-mode-hook 'turn-on-font-lock)
40 ;;
41 ;; On a Sparc2, `font-lock-fontify-buffer' takes about 10 seconds for a 120k
42 ;; file of C code using the default configuration, and about 25 seconds using
43 ;; the more extensive configuration, though times also depend on file contents.
44 ;; You can speed this up substantially by removing some of the patterns that
45 ;; are highlighted by default. Fontifying Lisp code is significantly faster,
46 ;; because Lisp has a more regular syntax than C, so the expressions don't have
47 ;; to be as hairy.
48 ;;
49 ;; If you add patterns for a new mode, say foo.el's `foo-mode', say in which
50 ;; you don't want syntactic fontification to occur, you can make Font Lock mode
51 ;; use your regexps when turning on Font Lock by adding to `foo-mode-hook':
52 ;;
53 ;; (add-hook 'foo-mode-hook
54 ;; '(lambda () (make-local-variable 'font-lock-defaults)
55 ;; (setq font-lock-defaults '(foo-font-lock-keywords t))))
56 ;;
57 ;; Nasty regexps of the form "bar\\(\\|lo\\)\\|f\\(oo\\|u\\(\\|bar\\)\\)\\|lo"
58 ;; are made thusly: (make-regexp '("foo" "fu" "fubar" "bar" "barlo" "lo")) for
59 ;; efficiency. See /pub/gnu/emacs/elisp-archive/functions/make-regexp.el.Z on
60 ;; archive.cis.ohio-state.edu for this and other functions.
61 \f
62 ;;; Code:
63
64 (defvar font-lock-comment-face 'font-lock-comment-face
65 "Face to use for comments.")
66
67 (defvar font-lock-string-face 'font-lock-string-face
68 "Face to use for strings.")
69
70 (defvar font-lock-function-name-face 'font-lock-function-name-face
71 "Face to use for function names.")
72
73 (defvar font-lock-variable-name-face 'font-lock-variable-name-face
74 "Face to use for variable names.")
75
76 (defvar font-lock-keyword-face 'font-lock-keyword-face
77 "Face to use for keywords.")
78
79 (defvar font-lock-type-face 'font-lock-type-face
80 "Face to use for data types.")
81
82 (defvar font-lock-reference-face 'font-lock-reference-face
83 "Face to use for references.")
84
85 (defvar font-lock-no-comments nil
86 "Non-nil means Font Lock should not fontify comments or strings.")
87
88 (make-obsolete-variable 'font-lock-doc-string-face 'font-lock-string-face)
89
90 (make-variable-buffer-local 'font-lock-keywords)
91 (defvar font-lock-keywords nil
92 "*The keywords to highlight.
93 Elements should be of the form:
94
95 MATCHER
96 (MATCHER . MATCH)
97 (MATCHER . FACENAME)
98 (MATCHER . HIGHLIGHT)
99 (MATCHER HIGHLIGHT ...)
100
101 where HIGHLIGHT should be of the form (MATCH FACENAME OVERRIDE LAXMATCH).
102 MATCHER can be either the regexp to search for, or the function name to call to
103 make the search (called with one argument, the limit of the search). MATCH is
104 the subexpression of MATCHER to be highlighted. FACENAME is an expression
105 whose value is the face name to use. FACENAME's default attributes may be
106 defined in `font-lock-face-attributes'.
107
108 OVERRIDE and LAXMATCH are flags. If OVERRIDE is t, existing fontification may
109 be overriden. If `keep', only parts not already fontified are highlighted.
110 If LAXMATCH is non-nil, no error is signalled if there is no MATCH in MATCHER.
111
112 These regular expressions should not match text which spans lines. While
113 \\[font-lock-fontify-buffer] handles multi-line patterns correctly, updating
114 when you edit the buffer does not, since it considers text one line at a time.
115
116 Be careful composing regexps for this list;
117 the wrong pattern can dramatically slow things down!")
118
119 (defvar font-lock-defaults nil
120 "If set by a major mode, should be the defaults for Font Lock mode.
121 The value should look like the `cdr' of an item in `font-lock-defaults-alist'.")
122
123 (defvar font-lock-defaults-alist
124 (let ((tex-mode-defaults '(tex-font-lock-keywords nil nil ((?$ . "\""))))
125 (c-mode-defaults
126 '((c-font-lock-keywords c-font-lock-keywords-1 c-font-lock-keywords-2)
127 nil nil ((?_ . "w"))))
128 (c++-mode-defaults
129 '((c++-font-lock-keywords c++-font-lock-keywords-1
130 c++-font-lock-keywords-2)
131 nil nil ((?_ . "w"))))
132 (lisp-mode-defaults
133 '((lisp-font-lock-keywords lisp-font-lock-keywords-1
134 lisp-font-lock-keywords-2)
135 nil nil ((?: . "w") (?- . "w") (?* . "w")))))
136 (list
137 (cons 'bibtex-mode tex-mode-defaults)
138 (cons 'c++-c-mode c-mode-defaults)
139 (cons 'c++-mode c++-mode-defaults)
140 (cons 'c-mode c-mode-defaults)
141 (cons 'emacs-lisp-mode lisp-mode-defaults)
142 (cons 'latex-mode tex-mode-defaults)
143 (cons 'lisp-mode lisp-mode-defaults)
144 (cons 'plain-tex-mode tex-mode-defaults)
145 (cons 'scheme-mode lisp-mode-defaults)
146 (cons 'slitex-mode tex-mode-defaults)
147 (cons 'tex-mode tex-mode-defaults)))
148 "*Alist of default major mode and Font Lock defaults.
149 Each item should be a list of the form:
150 (MAJOR-MODE . (FONT-LOCK-KEYWORDS KEYWORDS-ONLY CASE-FOLD FONT-LOCK-SYNTAX))
151 where MAJOR-MODE is a symbol, and FONT-LOCK-KEYWORDS may be a symbol or a list
152 of symbols. If KEYWORDS-ONLY is non-nil, syntactic fontification (strings and
153 comments) is not performed. If CASE-FOLD is non-nil, the case of the keywords
154 is ignored when fontifying. FONT-LOCK-SYNTAX should be a list of cons pairs of
155 the form (CHAR . STRING), it is used to set the local Font Lock syntax table
156 for keyword fontification.")
157
158 (defvar font-lock-keywords-case-fold-search nil
159 "*Non-nil means the patterns in `font-lock-keywords' are case-insensitive.")
160
161 (defvar font-lock-syntax-table nil
162 "Non-nil means use this syntax table for fontifying.
163 If this is nil, the major mode's syntax table is used.")
164
165 (defvar font-lock-verbose t
166 "*Non-nil means `font-lock-fontify-buffer' should print status messages.")
167
168 ;;;###autoload
169 (defvar font-lock-maximum-decoration nil
170 "Non-nil means use the maximum decoration for fontifying.
171 If nil, use the default decoration (typically the minimum available).
172 If t, use the maximum decoration available.
173 If a number, use that level of decoration (or if not available the maximum).")
174
175 (defvar font-lock-maximum-size
176 (if font-lock-maximum-decoration (* 150 1024) (* 300 1024))
177 "*If non-nil, the maximum size for buffers.
178 Only buffers less than this can be fontified when Font Lock mode is turned on.
179 If nil, means size is irrelevant.")
180
181 ;;;###autoload
182 (defvar font-lock-mode-hook nil
183 "Function or functions to run on entry to Font Lock mode.")
184 \f
185 ;; Colour etc. support.
186
187 (defvar font-lock-display-type nil
188 "A symbol indicating the display Emacs is running under.
189 The symbol should be one of `color', `grayscale' or `mono'.
190 If Emacs guesses this display attribute wrongly, either set this variable in
191 your `~/.emacs' or set the resource `Emacs.displayType' in your `~/.Xdefaults'.
192 See also `font-lock-background-mode' and `font-lock-face-attributes'.")
193
194 (defvar font-lock-background-mode nil
195 "A symbol indicating the Emacs background brightness.
196 The symbol should be one of `light' or `dark'.
197 If Emacs guesses this frame attribute wrongly, either set this variable in
198 your `~/.emacs' or set the resource `Emacs.backgroundMode' in your
199 `~/.Xdefaults'.
200 See also `font-lock-display-type' and `font-lock-face-attributes'.")
201
202 (defvar font-lock-face-attributes nil
203 "A list of default attributes to use for face attributes.
204 Each element of the list should be of the form
205
206 (FACE FOREGROUND BACKGROUND BOLD-P ITALIC-P UNDERLINE-P)
207
208 where FACE should be one of the face symbols `font-lock-comment-face',
209 `font-lock-string-face', `font-lock-keyword-face', `font-lock-type-face',
210 `font-lock-function-name-face', `font-lock-variable-name-face', and
211 `font-lock-reference-face'. A form for each of these face symbols should be
212 provided in the list, but other face symbols and attributes may be given and
213 used in highlighting. See `font-lock-keywords'.
214
215 Subsequent element items should be the attributes for the corresponding
216 Font Lock mode faces. Attributes FOREGROUND and BACKGROUND should be strings
217 \(default if nil), while BOLD-P, ITALIC-P, and UNDERLINE-P should specify the
218 corresponding face attributes (yes if non-nil).
219
220 Emacs uses default attributes based on display type and background brightness.
221 See variables `font-lock-display-type' and `font-lock-background-mode'.
222
223 Resources can be used to over-ride these face attributes. For example, the
224 resource `Emacs.font-lock-comment-face.attributeUnderline' can be used to
225 specify the UNDERLINE-P attribute for face `font-lock-comment-face'.")
226
227 (defun font-lock-make-faces (&optional override)
228 "Make faces from `font-lock-face-attributes'.
229 A default list is used if this is nil.
230 If optional OVERRIDE is non-nil, faces that already exist are reset.
231 See `font-lock-make-face' and `list-faces-display'."
232 ;; We don't need to `setq' any of these variables, but the user can see what
233 ;; is being used if we do.
234 (if (null font-lock-display-type)
235 (setq font-lock-display-type
236 (let ((display-resource (x-get-resource ".displayType"
237 "DisplayType")))
238 (cond (display-resource (intern (downcase display-resource)))
239 ((x-display-color-p) 'color)
240 ((x-display-grayscale-p) 'grayscale)
241 (t 'mono)))))
242 (if (null font-lock-background-mode)
243 (setq font-lock-background-mode
244 (let ((bg-resource (x-get-resource ".backgroundMode"
245 "BackgroundMode"))
246 (params (frame-parameters)))
247 (cond (bg-resource (intern (downcase bg-resource)))
248 ((< (apply '+ (x-color-values
249 (cdr (assq 'background-color params))))
250 (/ (apply '+ (x-color-values "white")) 3))
251 'dark)
252 (t 'light)))))
253 (if (null font-lock-face-attributes)
254 (setq font-lock-face-attributes
255 (let ((light-bg (eq font-lock-background-mode 'light)))
256 (cond ((memq font-lock-display-type '(mono monochrome))
257 ;; Emacs 19.25's font-lock defaults:
258 ;;'((font-lock-comment-face nil nil nil t nil)
259 ;; (font-lock-string-face nil nil nil nil t)
260 ;; (font-lock-keyword-face nil nil t nil nil)
261 ;; (font-lock-function-name-face nil nil t t nil)
262 ;; (font-lock-type-face nil nil nil t nil))
263 (list '(font-lock-comment-face nil nil t t nil)
264 '(font-lock-string-face nil nil nil t nil)
265 '(font-lock-keyword-face nil nil t nil nil)
266 (list
267 'font-lock-function-name-face
268 (cdr (assq 'background-color (frame-parameters)))
269 (cdr (assq 'foreground-color (frame-parameters)))
270 t nil nil)
271 '(font-lock-variable-name-face nil nil t t nil)
272 '(font-lock-type-face nil nil t nil t)
273 '(font-lock-reference-face nil nil t nil t)))
274 ((memq font-lock-display-type '(grayscale greyscale
275 grayshade greyshade))
276 (list
277 (list 'font-lock-comment-face
278 (if light-bg "DimGray" "Gray80") nil t t nil)
279 (list 'font-lock-string-face
280 (if light-bg "Gray50" "LightGray") nil nil t nil)
281 (list 'font-lock-keyword-face
282 (if light-bg "DimGray" "Gray90") nil t nil nil)
283 (list 'font-lock-function-name-face
284 (cdr (assq 'background-color (frame-parameters)))
285 (cdr (assq 'foreground-color (frame-parameters)))
286 t nil nil)
287 (list 'font-lock-variable-name-face
288 (if light-bg "DimGray" "Gray90") nil t t nil)
289 (list 'font-lock-type-face
290 (if light-bg "DimGray" "Gray80") nil t nil t)
291 (list 'font-lock-reference-face
292 (if light-bg "Gray50" "LightGray") nil t nil t)))
293 (light-bg ; light colour background
294 '((font-lock-comment-face "Firebrick")
295 (font-lock-string-face "RosyBrown")
296 (font-lock-keyword-face "Purple")
297 (font-lock-function-name-face "Blue")
298 (font-lock-variable-name-face "DarkGoldenrod")
299 (font-lock-type-face "DarkOliveGreen")
300 (font-lock-reference-face "CadetBlue")))
301 (t ; dark colour background
302 '((font-lock-comment-face "OrangeRed")
303 (font-lock-string-face "LightSalmon")
304 (font-lock-keyword-face "LightSteelBlue")
305 (font-lock-function-name-face "LightSkyBlue")
306 (font-lock-variable-name-face "LightGoldenrod")
307 (font-lock-type-face "PaleGreen")
308 (font-lock-reference-face "Aquamarine")))))))
309 ;; Now make the faces if we have to.
310 (mapcar (function (lambda (face-attributes)
311 (let ((face (nth 0 face-attributes)))
312 (if (and (not override) (facep face))
313 ;; The face exists. Only set the variable if it's nil.
314 (if (or (not (boundp face)) (symbol-value face))
315 (set face face))
316 ;; The face doesn't exist or we can stomp all over it anyway.
317 (font-lock-make-face face-attributes)))))
318 font-lock-face-attributes))
319
320 (defun font-lock-make-face (face-attributes)
321 "Make a face from FACE-ATTRIBUTES.
322 FACE-ATTRIBUTES should be like an element `font-lock-face-attributes', so that
323 the face name is the first item in the list. A variable with the same name as
324 the face is also set; its value is the face name."
325 (let* ((face (nth 0 face-attributes))
326 (face-name (symbol-name face))
327 (set-p (function (lambda (face-name resource)
328 (x-get-resource (concat face-name ".attribute" resource)
329 (concat "Face.Attribute" resource)))))
330 (on-p (function (lambda (face-name resource)
331 (let ((set (funcall set-p face-name resource)))
332 (and set (member (downcase set) '("on" "true"))))))))
333 (make-face face)
334 ;; Set attributes not set from X resources (and therefore `make-face').
335 (or (funcall set-p face-name "Foreground")
336 (condition-case nil
337 (set-face-foreground face (nth 1 face-attributes))
338 (error nil)))
339 (or (funcall set-p face-name "Background")
340 (condition-case nil
341 (set-face-background face (nth 2 face-attributes))
342 (error nil)))
343 (if (funcall set-p face-name "Bold")
344 (and (funcall on-p face-name "Bold") (make-face-bold face nil t))
345 (and (nth 3 face-attributes) (make-face-bold face nil t)))
346 (if (funcall set-p face-name "Italic")
347 (and (funcall on-p face-name "Italic") (make-face-italic face nil t))
348 (and (nth 4 face-attributes) (make-face-italic face nil t)))
349 (or (funcall set-p face-name "Underline")
350 (set-face-underline-p face (nth 5 face-attributes)))
351 (set face face)))
352 \f
353 ;; Fontification.
354
355 ;; These variables record, for each buffer, the parse state at a particular
356 ;; position, always the start of a line. Used to make font-lock-fontify-region
357 ;; faster.
358 (defvar font-lock-cache-position nil)
359 (defvar font-lock-cache-state nil)
360 (make-variable-buffer-local 'font-lock-cache-position)
361 (make-variable-buffer-local 'font-lock-cache-state)
362
363 (defun font-lock-fontify-region (start end &optional loudly)
364 "Put proper face on each string and comment between START and END."
365 (save-excursion
366 (save-restriction
367 (widen)
368 (goto-char start)
369 (beginning-of-line)
370 (if loudly (message "Fontifying %s... (syntactically...)" (buffer-name)))
371 (let ((inhibit-read-only t) (buffer-undo-list t) (buffer-file-name)
372 (modified (buffer-modified-p))
373 (old-syntax (syntax-table))
374 (synstart (if comment-start-skip
375 (concat "\\s\"\\|" comment-start-skip)
376 "\\s\""))
377 (comstart (if comment-start-skip
378 (concat "\\s<\\|" comment-start-skip)
379 "\\s<"))
380 (startline (point))
381 state prev prevstate)
382 (unwind-protect
383 (progn
384 (if font-lock-syntax-table
385 (set-syntax-table font-lock-syntax-table))
386 ;; Find the state at the line-beginning before START.
387 (if (eq startline font-lock-cache-position)
388 (setq state font-lock-cache-state)
389 ;; Find outermost containing sexp.
390 (beginning-of-defun)
391 ;; Find the state at STARTLINE.
392 (while (< (point) startline)
393 (setq state (parse-partial-sexp (point) startline 0)))
394 (setq font-lock-cache-state state
395 font-lock-cache-position (point)))
396 ;; Now find the state precisely at START.
397 (setq state (parse-partial-sexp (point) start nil nil state))
398 ;; If the region starts inside a string, show the extent of it.
399 (if (nth 3 state)
400 (let ((beg (point)))
401 (while (and (re-search-forward "\\s\"" end 'move)
402 (nth 3 (parse-partial-sexp beg (point) nil nil
403 state))))
404 (put-text-property beg (point) 'face font-lock-string-face)
405 (setq state (parse-partial-sexp beg (point)
406 nil nil state))))
407 ;; Likewise for a comment.
408 (if (or (nth 4 state) (nth 7 state))
409 (let ((beg (point)))
410 (save-restriction
411 (narrow-to-region (point-min) end)
412 (condition-case nil
413 (progn
414 (re-search-backward comstart (point-min) 'move)
415 (forward-comment 1)
416 ;; forward-comment skips all whitespace,
417 ;; so go back to the real end of the comment.
418 (skip-chars-backward " \t"))
419 (error (goto-char end))))
420 (put-text-property beg (point) 'face
421 font-lock-comment-face)
422 (setq state (parse-partial-sexp beg (point)
423 nil nil state))))
424 ;; Find each interesting place between here and END.
425 (while (and (< (point) end)
426 (setq prev (point) prevstate state)
427 (re-search-forward synstart end t)
428 (progn
429 ;; Clear out the fonts of what we skip over.
430 (remove-text-properties prev (point) '(face nil))
431 ;; Verify the state at that place
432 ;; so we don't get fooled by \" or \;.
433 (setq state (parse-partial-sexp prev (point)
434 nil nil state))))
435 (let ((here (point)))
436 (if (or (nth 4 state) (nth 7 state))
437 ;; We found a real comment start.
438 (let ((beg (match-beginning 0)))
439 (goto-char beg)
440 (save-restriction
441 (narrow-to-region (point-min) end)
442 (condition-case nil
443 (progn
444 (forward-comment 1)
445 ;; forward-comment skips all whitespace,
446 ;; so go back to the real end of the comment.
447 (skip-chars-backward " \t"))
448 (error (goto-char end))))
449 (put-text-property beg (point) 'face
450 font-lock-comment-face)
451 (setq state (parse-partial-sexp here (point)
452 nil nil state)))
453 (if (nth 3 state)
454 (let ((beg (match-beginning 0)))
455 (while (and (re-search-forward "\\s\"" end 'move)
456 (nth 3 (parse-partial-sexp
457 here (point) nil nil state))))
458 (put-text-property beg (point) 'face
459 font-lock-string-face)
460 (setq state (parse-partial-sexp here (point)
461 nil nil state))))))
462 ;; Make sure PREV is non-nil after the loop
463 ;; only if it was set on the very last iteration.
464 (setq prev nil)))
465 (set-syntax-table old-syntax))
466 (and prev
467 (remove-text-properties prev end '(face nil)))
468 (and (buffer-modified-p)
469 (not modified)
470 (set-buffer-modified-p nil))))))
471
472
473 (defun font-lock-unfontify-region (beg end)
474 (let ((modified (buffer-modified-p))
475 (buffer-undo-list t) (inhibit-read-only t) (buffer-file-name))
476 (remove-text-properties beg end '(face nil))
477 (and (buffer-modified-p)
478 (not modified)
479 (set-buffer-modified-p nil))))
480
481 ;; Called when any modification is made to buffer text.
482 (defun font-lock-after-change-function (beg end old-len)
483 (save-excursion
484 (save-match-data
485 ;; Discard the cache info if text before it has changed.
486 (and font-lock-cache-position
487 (> font-lock-cache-position beg)
488 (setq font-lock-cache-position nil))
489 ;; Rescan between start of line from `beg' and start of line after `end'.
490 (goto-char beg)
491 (beginning-of-line)
492 (setq beg (point))
493 (goto-char end)
494 (forward-line 1)
495 (setq end (point))
496 ;; First scan for strings and comments.
497 ;; Must scan from line start in case of
498 ;; inserting space into `intfoo () {}', and after widened.
499 (if font-lock-no-comments
500 (font-lock-unfontify-region beg end)
501 (font-lock-fontify-region beg end))
502 ;; Now scan for keywords.
503 (font-lock-hack-keywords beg end))))
504
505 ;; The following must be rethought, since keywords can override fontification.
506 ; ;; Now scan for keywords, but not if we are inside a comment now.
507 ; (or (and (not font-lock-no-comments)
508 ; (let ((state (parse-partial-sexp beg end nil nil
509 ; font-lock-cache-state)))
510 ; (or (nth 4 state) (nth 7 state))))
511 ; (font-lock-hack-keywords beg end))
512 \f
513 ;;; Fontifying arbitrary patterns
514
515 (defun font-lock-compile-keywords (&optional keywords)
516 ;; Compile `font-lock-keywords' into the form (t KEYWORD ...) where KEYWORD
517 ;; is the (MATCHER HIGHLIGHT ...) shown in the variable's doc string.
518 (let ((keywords (or keywords font-lock-keywords)))
519 (setq font-lock-keywords
520 (if (eq (car-safe keywords) t)
521 keywords
522 (cons t
523 (mapcar
524 (function (lambda (item)
525 (cond ((nlistp item)
526 (list item '(0 font-lock-keyword-face)))
527 ((numberp (cdr item))
528 (list (car item) (list (cdr item) 'font-lock-keyword-face)))
529 ((symbolp (cdr item))
530 (list (car item) (list 0 (cdr item))))
531 ((nlistp (nth 1 item))
532 (list (car item) (cdr item)))
533 (t
534 item))))
535 keywords))))))
536
537 (defsubst font-lock-apply-highlight (highlight)
538 "Apply HIGHLIGHT following a match. See `font-lock-keywords'."
539 (let* ((match (nth 0 highlight))
540 (beg (match-beginning match)) (end (match-end match))
541 (override (nth 2 highlight)))
542 (cond ((not beg)
543 ;; No match but we might not signal an error
544 (or (nth 3 highlight) (error "Highlight %S failed" highlight)))
545 ((and (not override) (text-property-not-all beg end 'face nil))
546 ;; Can't override and already fontified
547 nil)
548 ((not (eq override 'keep))
549 ;; Can override but need not keep existing fontification
550 (put-text-property beg end 'face (eval (nth 1 highlight))))
551 (t
552 ;; Can override but must keep existing fontification
553 (let ((pos (text-property-any beg end 'face nil)) next
554 (face (eval (nth 1 highlight))))
555 (while pos
556 (setq next (next-single-property-change pos 'face nil end))
557 (put-text-property pos next 'face face)
558 (setq pos (text-property-any next end 'face nil))))))))
559
560 (defun font-lock-hack-keywords (start end &optional loudly)
561 "Fontify according to `font-lock-keywords' between START and END."
562 (let ((case-fold-search font-lock-keywords-case-fold-search)
563 (keywords (cdr (if (eq (car-safe font-lock-keywords) t)
564 font-lock-keywords
565 (font-lock-compile-keywords))))
566 (count 0)
567 (inhibit-read-only t) (buffer-undo-list t) (buffer-file-name)
568 (modified (buffer-modified-p))
569 (old-syntax (syntax-table))
570 (bufname (buffer-name)))
571 (unwind-protect
572 (let (keyword matcher highlights)
573 (if loudly (message "Fontifying %s... (regexps...)" bufname))
574 (if font-lock-syntax-table (set-syntax-table font-lock-syntax-table))
575 (while keywords
576 (setq keyword (car keywords) keywords (cdr keywords)
577 matcher (car keyword) highlights (cdr keyword))
578 (goto-char start)
579 (while (if (stringp matcher)
580 (re-search-forward matcher end t)
581 (funcall matcher end))
582 (mapcar 'font-lock-apply-highlight highlights))
583 (if loudly (message "Fontifying %s... (regexps...%s)" bufname
584 (make-string (setq count (1+ count)) ?.)))))
585 (set-syntax-table old-syntax))
586 (and (buffer-modified-p)
587 (not modified)
588 (set-buffer-modified-p nil))))
589 \f
590 ;; The user level functions
591
592 (defvar font-lock-mode nil) ; for modeline
593
594 (defvar font-lock-fontified nil) ; whether we have hacked this buffer
595 (put 'font-lock-fontified 'permanent-local t)
596
597 ;;;###autoload
598 (defun font-lock-mode (&optional arg)
599 "Toggle Font Lock mode.
600 With arg, turn Font Lock mode on if and only if arg is positive.
601
602 When Font Lock mode is enabled, text is fontified as you type it:
603
604 - Comments are displayed in `font-lock-comment-face';
605 - Strings are displayed in `font-lock-string-face';
606 - Certain other expressions are displayed in other faces according to the
607 value of the variable `font-lock-keywords'.
608
609 You can enable Font Lock mode in any major mode automatically by turning on in
610 the major mode's hook. For example, put in your ~/.emacs:
611
612 (add-hook 'c-mode-hook 'turn-on-font-lock)
613
614 Or for any visited file with the following in your ~/.emacs:
615
616 (add-hook 'find-file-hooks 'turn-on-font-lock)
617
618 The default Font Lock mode faces and their attributes are defined in the
619 variable `font-lock-face-attributes', and Font Lock mode default settings in
620 the variable `font-lock-defaults-alist'.
621
622 Where modes support different levels of fontification, you can use the variable
623 `font-lock-maximum-decoration' to specify which level you generally prefer.
624 When you turn Font Lock mode on/off the buffer is fontified/defontified, though
625 fontification occurs only if the buffer is less than `font-lock-maximum-size'.
626 To fontify a buffer without turning on Font Lock mode, and regardless of buffer
627 size, you can use \\[font-lock-fontify-buffer]."
628 (interactive "P")
629 (let ((on-p (if arg (> (prefix-numeric-value arg) 0) (not font-lock-mode))))
630 (if (equal (buffer-name) " *Compiler Input*") ; hack for bytecomp...
631 (setq on-p nil))
632 (if (not on-p)
633 (remove-hook 'after-change-functions 'font-lock-after-change-function)
634 (make-local-variable 'after-change-functions)
635 (add-hook 'after-change-functions 'font-lock-after-change-function))
636 (set (make-local-variable 'font-lock-mode) on-p)
637 (cond (on-p
638 (font-lock-set-defaults)
639 (make-local-variable 'before-revert-hook)
640 (make-local-variable 'after-revert-hook)
641 ;; If buffer is reverted, must clean up the state.
642 (add-hook 'before-revert-hook 'font-lock-revert-setup)
643 (add-hook 'after-revert-hook 'font-lock-revert-cleanup)
644 (run-hooks 'font-lock-mode-hook)
645 (cond (font-lock-fontified
646 nil)
647 ((or (null font-lock-maximum-size)
648 (> font-lock-maximum-size (buffer-size)))
649 (font-lock-fontify-buffer))
650 (font-lock-verbose
651 (message "Fontifying %s... buffer too big." (buffer-name)))))
652 (font-lock-fontified
653 (setq font-lock-fontified nil)
654 (remove-hook 'before-revert-hook 'font-lock-revert-setup)
655 (remove-hook 'after-revert-hook 'font-lock-revert-cleanup)
656 (font-lock-unfontify-region (point-min) (point-max))
657 (font-lock-thing-lock-cleanup))
658 (t
659 (remove-hook 'before-revert-hook 'font-lock-revert-setup)
660 (remove-hook 'after-revert-hook 'font-lock-revert-cleanup)
661 (font-lock-thing-lock-cleanup)))
662 (force-mode-line-update)))
663
664 ;;;###autoload
665 (defun turn-on-font-lock ()
666 "Unconditionally turn on Font Lock mode."
667 (font-lock-mode 1))
668
669 ;; Turn off other related packages if they're on. I prefer a hook.
670 ;; These explicit calls are easier to understand
671 ;; because people know what they will do.
672 ;; A hook is a mystery because it might do anything whatever. -- rms.
673 (defun font-lock-thing-lock-cleanup ()
674 (cond ((and (boundp 'fast-lock-mode) fast-lock-mode)
675 (fast-lock-mode -1))
676 ((and (boundp 'lazy-lock-mode) lazy-lock-mode)
677 (lazy-lock-mode -1))))
678
679 ;; Do something special for these packages after fontifying. I prefer a hook.
680 (defun font-lock-after-fontify-buffer ()
681 (cond ((and (boundp 'fast-lock-mode) fast-lock-mode)
682 (fast-lock-after-fontify-buffer))
683 ((and (boundp 'lazy-lock-mode) lazy-lock-mode)
684 (lazy-lock-after-fontify-buffer))))
685
686 ;; If the buffer is about to be reverted, it won't be fontified afterward.
687 (defun font-lock-revert-setup ()
688 (setq font-lock-fontified nil))
689
690 ;; If the buffer has just been reverted, normally that turns off
691 ;; Font Lock mode. So turn the mode back on if necessary.
692 (defun font-lock-revert-cleanup ()
693 (font-lock-mode 1))
694
695 ;;;###autoload
696 (defun font-lock-fontify-buffer ()
697 "Fontify the current buffer the way `font-lock-mode' would."
698 (interactive)
699 (let ((was-on font-lock-mode)
700 (verbose (and (or font-lock-verbose (interactive-p))
701 (not (zerop (buffer-size)))))
702 (modified (buffer-modified-p)))
703 (set (make-local-variable 'font-lock-fontified) nil)
704 (if verbose (message "Fontifying %s..." (buffer-name)))
705 ;; Turn it on to run hooks and get the right `font-lock-keywords' etc.
706 (or was-on (font-lock-set-defaults))
707 (condition-case nil
708 (save-excursion
709 (if font-lock-no-comments
710 (font-lock-unfontify-region (point-min) (point-max))
711 (font-lock-fontify-region (point-min) (point-max) verbose))
712 (font-lock-hack-keywords (point-min) (point-max) verbose)
713 (setq font-lock-fontified t))
714 ;; We don't restore the old fontification, so it's best to unfontify.
715 (quit (font-lock-unfontify-region (point-min) (point-max))))
716 (if verbose (message "Fontifying %s... %s." (buffer-name)
717 (if font-lock-fontified "done" "aborted")))
718 (and (buffer-modified-p)
719 (not modified)
720 (set-buffer-modified-p nil))
721 (font-lock-after-fontify-buffer)))
722 \f
723 ;;; Various information shared by several modes.
724 ;;; Information specific to a single mode should go in its load library.
725
726 (defconst lisp-font-lock-keywords-1
727 (list
728 ;; highlight defining forms. This doesn't work too nicely for
729 ;; (defun (setf foo) ...) but it does work for (defvar foo) which
730 ;; is more important.
731 (list (concat "^(\\(def\\(const\\|ine-key\\(\\|-after\\)\\|var\\)\\)\\>"
732 "[ \t']*\\([^ \t\n\(\)]+\\)?")
733 '(1 font-lock-keyword-face) '(4 font-lock-variable-name-face nil t))
734 (list (concat "^(\\(def[^ \t\n\(\)]+\\|eval-"
735 "\\(a\\(fter-load\\|nd-compile\\)\\|when-compile\\)\\)\\>"
736 "[ \t']*\\([^ \t\n\(\)]+\\)?")
737 '(1 font-lock-keyword-face) '(4 font-lock-function-name-face nil t))
738 )
739 "Subdued level highlighting Lisp modes.")
740
741 (defconst lisp-font-lock-keywords-2
742 (append lisp-font-lock-keywords-1
743 (let ((word-char "[-+a-zA-Z0-9_:*]"))
744 (list
745 ;;
746 ;; Control structures.
747 ;; ELisp:
748 ; ("cond" "if" "while" "let\\*?" "prog[nv12*]?" "catch" "throw"
749 ; "save-restriction" "save-excursion" "save-window-excursion"
750 ; "save-selected-window" "save-match-data" "unwind-protect"
751 ; "condition-case" "track-mouse")
752 (cons
753 (concat
754 "(\\("
755 "c\\(atch\\|ond\\(\\|ition-case\\)\\)\\|if\\|let\\*?\\|prog[nv12*]?\\|"
756 "save-\\(excursion\\|match-data\\|restriction\\|"
757 "selected-window\\|window-excursion\\)\\|"
758 "t\\(hrow\\|rack-mouse\\)\\|unwind-protect\\|while"
759 "\\)\\>") 1)
760 ;; CLisp:
761 ; ("when" "unless" "do" "flet" "labels" "return" "return-from")
762 '("(\\(do\\|flet\\|labels\\|return\\(\\|-from\\)\\|unless\\|when\\)\\>"
763 . 1)
764 ;;
765 ;; Fontify CLisp keywords.
766 (concat "\\<:" word-char "+\\>")
767 ;;
768 ;; Function names in emacs-lisp docstrings (in the syntax that
769 ;; `substitute-command-keys' understands).
770 (list (concat "\\\\\\\\\\[\\(" word-char "+\\)]")
771 1 font-lock-reference-face t)
772 ;;
773 ;; Words inside `' which tend to be symbol names.
774 (list (concat "`\\(" word-char word-char "+\\)'")
775 1 'font-lock-reference-face t)
776 ;;
777 ;; & keywords as types
778 '("\\&\\(optional\\|rest\\|whole\\)\\>" . font-lock-type-face)
779 )))
780 "Gaudy level highlighting for Lisp modes.")
781
782 (defvar lisp-font-lock-keywords lisp-font-lock-keywords-1
783 "Default expressions to highlight in Lisp modes.")
784
785
786 (defconst c-font-lock-keywords-1 nil
787 "Subdued level highlighting for C modes.")
788
789 (defconst c-font-lock-keywords-2 nil
790 "Gaudy level highlighting for C modes.")
791
792 (defconst c++-font-lock-keywords-1 nil
793 "Subdued level highlighting for C++ modes.")
794
795 (defconst c++-font-lock-keywords-2 nil
796 "Gaudy level highlighting for C++ modes.")
797
798 (let ((c-keywords
799 ; ("break" "continue" "do" "else" "for" "if" "return" "switch" "while")
800 "break\\|continue\\|do\\|else\\|for\\|if\\|return\\|switch\\|while")
801 (c-type-types
802 ; ("auto" "extern" "register" "static" "typedef" "struct" "union" "enum"
803 ; "signed" "unsigned" "short" "long" "int" "char" "float" "double"
804 ; "void" "volatile" "const")
805 (concat "auto\\|c\\(har\\|onst\\)\\|double\\|e\\(num\\|xtern\\)\\|"
806 "float\\|int\\|long\\|register\\|"
807 "s\\(hort\\|igned\\|t\\(atic\\|ruct\\)\\)\\|typedef\\|"
808 "un\\(ion\\|signed\\)\\|vo\\(id\\|latile\\)")) ; 6 ()s deep.
809 (c++-keywords
810 ; ("break" "continue" "do" "else" "for" "if" "return" "switch" "while"
811 ; "asm" "catch" "delete" "new" "operator" "sizeof" "this" "throw" "try"
812 ; "protected" "private" "public")
813 (concat "asm\\|break\\|c\\(atch\\|ontinue\\)\\|d\\(elete\\|o\\)\\|"
814 "else\\|for\\|if\\|new\\|operator\\|"
815 "p\\(r\\(ivate\\|otected\\)\\|ublic\\)\\|return\\|"
816 "s\\(izeof\\|witch\\)\\|t\\(h\\(is\\|row\\)\\|ry\\)\\|while"))
817 (c++-type-types
818 ; ("auto" "extern" "register" "static" "typedef" "struct" "union" "enum"
819 ; "signed" "unsigned" "short" "long" "int" "char" "float" "double"
820 ; "void" "volatile" "const" "class" "inline" "friend" "bool"
821 ; "virtual" "complex" "template")
822 (concat "auto\\|bool\\|c\\(har\\|lass\\|o\\(mplex\\|nst\\)\\)\\|"
823 "double\\|e\\(num\\|xtern\\)\\|f\\(loat\\|riend\\)\\|"
824 "in\\(line\\|t\\)\\|long\\|register\\|"
825 "s\\(hort\\|igned\\|t\\(atic\\|ruct\\)\\)\\|"
826 "t\\(emplate\\|ypedef\\)\\|un\\(ion\\|signed\\)\\|"
827 "v\\(irtual\\|o\\(id\\|latile\\)\\)")) ; 11 ()s deep.
828 (ctoken "[a-zA-Z0-9_:~]+"))
829 (setq c-font-lock-keywords-1
830 (list
831 ;;
832 ;; Fontify filenames in #include <...> preprocessor directives.
833 '("^#[ \t]*include[ \t]+\\(<[^>\"\n]+>\\)" 1 font-lock-string-face)
834 ;;
835 ;; Fontify function macro names.
836 '("^#[ \t]*define[ \t]+\\(\\(\\sw+\\)(\\)" 2 font-lock-function-name-face)
837 ;;
838 ;; Fontify otherwise as symbol names, and the preprocessor directive names.
839 '("^\\(#[ \t]*[a-z]+\\)\\>[ \t]*\\(\\sw+\\)?"
840 (1 font-lock-reference-face) (2 font-lock-variable-name-face nil t))
841 ;;
842 ;; Fontify function name definitions (without type on line).
843 (list (concat "^\\(" ctoken "\\)[ \t]*(") 1 'font-lock-function-name-face)
844 ))
845
846 (setq c-font-lock-keywords-2
847 (append c-font-lock-keywords-1
848 (list
849 ;;
850 ;; Fontify all storage classes and type specifiers (before declarations).
851 (cons (concat "\\<\\(" c-type-types "\\)\\>") 'font-lock-type-face)
852 ;;
853 ;; Fontify variable/structure name declarations and definitions, or
854 ;; function name declarations (plus definitions with type on same line).
855 (list (concat "\\<\\(" c-type-types "\\)[ \t*]+"
856 "\\(" ctoken "[ \t*]+\\)*"
857 "\\(" ctoken "\\)[ \t]*\\((\\)?")
858 9
859 '(if (match-beginning 10)
860 font-lock-function-name-face
861 font-lock-variable-name-face))
862 ;;
863 ;; Fontify function/variable name declarations at the start of the line.
864 ;; (Not everyone follows the GNU convention of function name at the start.)
865 (list (concat "^" ctoken "[ \t*]+"
866 "\\(" ctoken "[ \t*]+\\)*"
867 "\\(" ctoken "\\)[ \t]*\\((\\)?")
868 2
869 '(if (match-beginning 3)
870 font-lock-function-name-face
871 font-lock-variable-name-face))
872 ;;
873 ;; Fontify variable names declared with structures, or typedef names.
874 '("}[ \t*]*\\(\\sw+\\)[ \t]*[;,[]" 1 font-lock-variable-name-face)
875 ;;
876 ;; Fontify all builtin keywords (except case, default and goto; see below).
877 (concat "\\<\\(" c-keywords "\\)\\>")
878 ;;
879 ;; Fontify case/goto keywords and targets, and goto tags (incl "default:").
880 '("\\<\\(case\\|goto\\)\\>[ \t]*\\([^ \t\n:;]+\\)?"
881 (1 font-lock-keyword-face) (2 font-lock-reference-face nil t))
882 '("^[ \t]*\\(\\sw+\\)[ \t]*:" 1 font-lock-reference-face)
883 )))
884
885 (setq c++-font-lock-keywords-1 c-font-lock-keywords-1)
886 (setq c++-font-lock-keywords-2
887 (append c++-font-lock-keywords-1
888 (list
889 ;; We don't just add to the C keywords for subtle differences and speed.
890 ;; See the above comments for `c-font-lock-keywords-2'.
891 (cons (concat "\\<\\(" c++-type-types "\\)\\>") 'font-lock-type-face)
892 (list (concat "\\<\\(" c++-type-types "\\)[ \t*&]+"
893 "\\(" ctoken "[ \t*&]+\\)*"
894 "\\(" ctoken "\\)[ \t]*\\((\\)?")
895 14
896 '(if (match-beginning 15)
897 font-lock-function-name-face
898 font-lock-variable-name-face))
899 (list (concat "^" ctoken "[ \t*]+"
900 "\\(" ctoken "[ \t*]+\\)*"
901 "\\(" ctoken "\\)[ \t]*\\((\\)?")
902 2
903 '(if (match-beginning 3)
904 font-lock-function-name-face
905 font-lock-variable-name-face))
906 '("}[ \t*]*\\(\\sw+\\)[ \t]*[;,[]" 1 font-lock-variable-name-face)
907 (concat "\\<\\(" c++-keywords "\\)\\>")
908 '("\\<\\(case\\|goto\\)\\>[ \t]*\\([^ \t\n:;]+\\)?"
909 (1 font-lock-keyword-face) (2 font-lock-reference-face nil t))
910 '("^[ \t]*\\(\\sw+\\)[ \t]*:[^:]" 1 font-lock-reference-face))))
911 )
912
913 (defvar c-font-lock-keywords c-font-lock-keywords-1
914 "Default expressions to highlight in C mode.")
915
916 (defvar c++-font-lock-keywords c++-font-lock-keywords-1
917 "Default expressions to highlight in C++ mode.")
918
919 (defvar tex-font-lock-keywords
920 ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
921 '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
922 2 font-lock-function-name-face)
923 ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
924 2 font-lock-reference-face)
925 ;; It seems a bit dubious to use `bold' and `italic' faces since we might
926 ;; not be able to display those fonts.
927 ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
928 ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
929 ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
930 ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
931 "Additional expressions to highlight in TeX mode.")
932
933 (defun font-lock-choose-keywords (keywords level)
934 ;; Return evaled LEVELth element of KEYWORDS. A LEVEL of nil is equal to a
935 ;; LEVEL of 0, a LEVEL of t is equal to (1- (length KEYWORDS)).
936 (eval (cond ((symbolp keywords)
937 keywords)
938 ((numberp level)
939 (or (nth level keywords) (car (reverse keywords))))
940 ((eq level t)
941 (car (reverse keywords)))
942 (t
943 (car keywords)))))
944
945 (defun font-lock-set-defaults ()
946 "Set fontification defaults appropriately for this mode.
947 Sets `font-lock-keywords', `font-lock-no-comments', `font-lock-syntax-table'
948 and `font-lock-keywords-case-fold-search' using `font-lock-defaults' (or, if
949 nil, using `font-lock-defaults-alist') and `font-lock-maximum-decoration'."
950 ;; Set face defaults.
951 (font-lock-make-faces)
952 ;; Set fontification defaults.
953 (or font-lock-keywords
954 (let ((defaults (or font-lock-defaults
955 (cdr (assq major-mode font-lock-defaults-alist)))))
956 ;; Keywords?
957 (setq font-lock-keywords (font-lock-choose-keywords (nth 0 defaults)
958 font-lock-maximum-decoration))
959 ;; Syntactic?
960 (if (nth 1 defaults)
961 (set (make-local-variable 'font-lock-no-comments) t))
962 ;; Case fold?
963 (if (nth 2 defaults)
964 (set (make-local-variable 'font-lock-keywords-case-fold-search) t))
965 ;; Syntax table?
966 (if (nth 3 defaults)
967 (let ((slist (nth 3 defaults)))
968 (set (make-local-variable 'font-lock-syntax-table)
969 (copy-syntax-table (syntax-table)))
970 (while slist
971 (modify-syntax-entry (car (car slist)) (cdr (car slist))
972 font-lock-syntax-table)
973 (setq slist (cdr slist))))))))
974
975 ;; Install ourselves:
976
977 (or (assq 'font-lock-mode minor-mode-alist)
978 (setq minor-mode-alist (cons '(font-lock-mode " Font") minor-mode-alist)))
979
980 ;; Provide ourselves:
981
982 (provide 'font-lock)
983
984 ;;; font-lock.el ends here