(rmail-reply): Don't forget to narrow header in
[bpt/emacs.git] / lisp / jit-lock.el
1 ;;; jit-lock.el --- just-in-time fontification.
2
3 ;; Copyright (C) 1998, 2000, 2001 Free Software Foundation, Inc.
4
5 ;; Author: Gerd Moellmann <gerd@gnu.org>
6 ;; Keywords: faces files
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 the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Just-in-time fontification, triggered by C redisplay code.
28
29 ;;; Code:
30
31
32 (eval-when-compile
33 (defmacro with-buffer-unmodified (&rest body)
34 "Eval BODY, preserving the current buffer's modified state."
35 (let ((modified (make-symbol "modified")))
36 `(let ((,modified (buffer-modified-p)))
37 (unwind-protect
38 (progn ,@body)
39 (unless ,modified
40 (restore-buffer-modified-p nil))))))
41
42 (defmacro with-buffer-prepared-for-jit-lock (&rest body)
43 "Execute BODY in current buffer, overriding several variables.
44 Preserves the `buffer-modified-p' state of the current buffer."
45 `(with-buffer-unmodified
46 (let ((buffer-undo-list t)
47 (inhibit-read-only t)
48 (inhibit-point-motion-hooks t)
49 (inhibit-modification-hooks t)
50 deactivate-mark
51 buffer-file-name
52 buffer-file-truename)
53 ,@body))))
54
55
56 \f
57 ;;; Customization.
58
59 (defcustom jit-lock-chunk-size 500
60 "*Jit-lock chunks of this many characters, or smaller."
61 :type 'integer
62 :group 'jit-lock)
63
64
65 (defcustom jit-lock-stealth-time 3
66 "*Time in seconds to wait before beginning stealth fontification.
67 Stealth fontification occurs if there is no input within this time.
68 If nil, stealth fontification is never performed.
69
70 The value of this variable is used when JIT Lock mode is turned on."
71 :type '(choice (const :tag "never" nil)
72 (number :tag "seconds"))
73 :group 'jit-lock)
74
75
76 (defcustom jit-lock-stealth-nice 0.125
77 "*Time in seconds to pause between chunks of stealth fontification.
78 Each iteration of stealth fontification is separated by this amount of time,
79 thus reducing the demand that stealth fontification makes on the system.
80 If nil, means stealth fontification is never paused.
81 To reduce machine load during stealth fontification, at the cost of stealth
82 taking longer to fontify, you could increase the value of this variable.
83 See also `jit-lock-stealth-load'."
84 :type '(choice (const :tag "never" nil)
85 (number :tag "seconds"))
86 :group 'jit-lock)
87
88
89 (defcustom jit-lock-stealth-load
90 (if (condition-case nil (load-average) (error)) 200)
91 "*Load in percentage above which stealth fontification is suspended.
92 Stealth fontification pauses when the system short-term load average (as
93 returned by the function `load-average' if supported) goes above this level,
94 thus reducing the demand that stealth fontification makes on the system.
95 If nil, means stealth fontification is never suspended.
96 To reduce machine load during stealth fontification, at the cost of stealth
97 taking longer to fontify, you could reduce the value of this variable.
98 See also `jit-lock-stealth-nice'."
99 :type (if (condition-case nil (load-average) (error))
100 '(choice (const :tag "never" nil)
101 (integer :tag "load"))
102 '(const :format "%t: unsupported\n" nil))
103 :group 'jit-lock)
104
105
106 (defcustom jit-lock-stealth-verbose nil
107 "*If non-nil, means stealth fontification should show status messages."
108 :type 'boolean
109 :group 'jit-lock)
110
111
112 (defcustom jit-lock-defer-contextually 'syntax-driven
113 "*If non-nil, means deferred fontification should be syntactically true.
114 If nil, means deferred fontification occurs only on those lines modified. This
115 means where modification on a line causes syntactic change on subsequent lines,
116 those subsequent lines are not refontified to reflect their new context.
117 If t, means deferred fontification occurs on those lines modified and all
118 subsequent lines. This means those subsequent lines are refontified to reflect
119 their new syntactic context, either immediately or when scrolling into them.
120 If any other value, e.g., `syntax-driven', means deferred syntactically true
121 fontification occurs only if syntactic fontification is performed using the
122 buffer mode's syntax table, i.e., only if `font-lock-keywords-only' is nil.
123
124 The value of this variable is used when JIT Lock mode is turned on."
125 :type '(choice (const :tag "never" nil)
126 (const :tag "always" t)
127 (other :tag "syntax-driven" syntax-driven))
128 :group 'jit-lock)
129
130
131 \f
132 ;;; Variables that are not customizable.
133
134 (defvar jit-lock-mode nil
135 "Non-nil means Just-in-time Lock mode is active.")
136 (make-variable-buffer-local 'jit-lock-mode)
137
138 (defvar jit-lock-functions nil
139 "Functions to do the actual fontification.
140 They are called with two arguments: the START and END of the region to fontify.")
141 (make-variable-buffer-local 'jit-lock-functions)
142
143 (defvar jit-lock-first-unfontify-pos nil
144 "Consider text after this position as contextually unfontified.
145 If nil, contextual fontification is disabled.")
146 (make-variable-buffer-local 'jit-lock-first-unfontify-pos)
147
148
149 (defvar jit-lock-stealth-timer nil
150 "Timer for stealth fontification in Just-in-time Lock mode.")
151 \f
152 ;;; JIT lock mode
153
154 (defun jit-lock-mode (arg)
155 "Toggle Just-in-time Lock mode.
156 Turn Just-in-time Lock mode on if and only if ARG is non-nil.
157 Enable it automatically by customizing group `font-lock'.
158
159 When Just-in-time Lock mode is enabled, fontification is different in the
160 following ways:
161
162 - Demand-driven buffer fontification triggered by Emacs C code.
163 This means initial fontification of the whole buffer does not occur.
164 Instead, fontification occurs when necessary, such as when scrolling
165 through the buffer would otherwise reveal unfontified areas. This is
166 useful if buffer fontification is too slow for large buffers.
167
168 - Stealthy buffer fontification if `jit-lock-stealth-time' is non-nil.
169 This means remaining unfontified areas of buffers are fontified if Emacs has
170 been idle for `jit-lock-stealth-time' seconds, while Emacs remains idle.
171 This is useful if any buffer has any deferred fontification.
172
173 - Deferred context fontification if `jit-lock-defer-contextually' is
174 non-nil. This means fontification updates the buffer corresponding to
175 true syntactic context, after `jit-lock-stealth-time' seconds of Emacs
176 idle time, while Emacs remains idle. Otherwise, fontification occurs
177 on modified lines only, and subsequent lines can remain fontified
178 corresponding to previous syntactic contexts. This is useful where
179 strings or comments span lines.
180
181 Stealth fontification only occurs while the system remains unloaded.
182 If the system load rises above `jit-lock-stealth-load' percent, stealth
183 fontification is suspended. Stealth fontification intensity is controlled via
184 the variable `jit-lock-stealth-nice'."
185 (setq jit-lock-mode arg)
186 (cond (;; Turn Just-in-time Lock mode on.
187 jit-lock-mode
188
189 ;; Mark the buffer for refontification
190 (jit-lock-refontify)
191
192 ;; Install an idle timer for stealth fontification.
193 (when (and jit-lock-stealth-time (null jit-lock-stealth-timer))
194 (setq jit-lock-stealth-timer
195 (run-with-idle-timer jit-lock-stealth-time
196 jit-lock-stealth-time
197 'jit-lock-stealth-fontify)))
198
199 ;; Initialize deferred contextual fontification if requested.
200 (when (eq jit-lock-defer-contextually t)
201 (setq jit-lock-first-unfontify-pos
202 (or jit-lock-first-unfontify-pos (point-max))))
203
204 ;; Setup our hooks.
205 (add-hook 'after-change-functions 'jit-lock-after-change nil t)
206 (add-hook 'fontification-functions 'jit-lock-function))
207
208 ;; Turn Just-in-time Lock mode off.
209 (t
210 ;; Cancel our idle timer.
211 (when jit-lock-stealth-timer
212 (cancel-timer jit-lock-stealth-timer)
213 (setq jit-lock-stealth-timer nil))
214
215 ;; Remove hooks.
216 (remove-hook 'after-change-functions 'jit-lock-after-change t)
217 (remove-hook 'fontification-functions 'jit-lock-function))))
218
219 ;;;###autoload
220 (defun jit-lock-register (fun &optional contextual)
221 "Register FUN as a fontification function to be called in this buffer.
222 FUN will be called with two arguments START and END indicating the region
223 that needs to be (re)fontified.
224 If non-nil, CONTEXTUAL means that a contextual fontification would be useful."
225 (add-hook 'jit-lock-functions fun nil t)
226 (when (and contextual jit-lock-defer-contextually)
227 (set (make-local-variable 'jit-lock-defer-contextually) t))
228 (jit-lock-mode t))
229
230 (defun jit-lock-unregister (fun)
231 "Unregister FUN as a fontification function.
232 Only applies to the current buffer."
233 (remove-hook 'jit-lock-functions fun t)
234 (unless jit-lock-functions (jit-lock-mode nil)))
235
236 ;; This function is used to prevent font-lock-fontify-buffer from
237 ;; fontifying eagerly the whole buffer. This is important for
238 ;; things like CWarn mode which adds/removes a few keywords and
239 ;; does a refontify (which takes ages on large files).
240 (defun jit-lock-refontify (&optional beg end)
241 "Force refontification of the region BEG..END (default whole buffer)."
242 (with-buffer-prepared-for-jit-lock
243 (save-restriction
244 (widen)
245 (add-text-properties (or beg (point-min)) (or end (point-max))
246 '(fontified nil)))))
247 \f
248 ;;; On demand fontification.
249
250 (defun jit-lock-function (start)
251 "Fontify current buffer starting at position START.
252 This function is added to `fontification-functions' when `jit-lock-mode'
253 is active."
254 (when jit-lock-mode
255 (jit-lock-fontify-now start (+ start jit-lock-chunk-size))))
256
257
258 (defun jit-lock-fontify-now (&optional start end)
259 "Fontify current buffer from START to END.
260 Defaults to the whole buffer. END can be out of bounds."
261 (with-buffer-prepared-for-jit-lock
262 (save-excursion
263 (save-restriction
264 (widen)
265 (unless start (setq start (point-min)))
266 (setq end (if end (min end (point-max)) (point-max)))
267 ;; This did bind `font-lock-beginning-of-syntax-function' to
268 ;; nil at some point, for an unknown reason. Don't do this; it
269 ;; can make highlighting slow due to expensive calls to
270 ;; `parse-partial-sexp' in function
271 ;; `font-lock-fontify-syntactically-region'. Example: paging
272 ;; from the end of a buffer to its start, can do repeated
273 ;; `parse-partial-sexp' starting from `point-min', which can
274 ;; take a long time in a large buffer.
275 (let (next)
276 (save-match-data
277 ;; Fontify chunks beginning at START. The end of a
278 ;; chunk is either `end', or the start of a region
279 ;; before `end' that has already been fontified.
280 (while start
281 ;; Determine the end of this chunk.
282 (setq next (or (text-property-any start end 'fontified t)
283 end))
284
285 ;; Decide which range of text should be fontified.
286 ;; The problem is that START and NEXT may be in the
287 ;; middle of something matched by a font-lock regexp.
288 ;; Until someone has a better idea, let's start
289 ;; at the start of the line containing START and
290 ;; stop at the start of the line following NEXT.
291 (goto-char next) (setq next (line-beginning-position 2))
292 (goto-char start) (setq start (line-beginning-position))
293
294 ;; Fontify the chunk, and mark it as fontified.
295 ;; We mark it first, to make sure that we don't indefinitely
296 ;; re-execute this fontification if an error occurs.
297 (add-text-properties start next '(fontified t))
298 (run-hook-with-args 'jit-lock-functions start next)
299
300 ;; Find the start of the next chunk, if any.
301 (setq start (text-property-any next end 'fontified nil)))))))))
302
303 \f
304 ;;; Stealth fontification.
305
306 (defsubst jit-lock-stealth-chunk-start (around)
307 "Return the start of the next chunk to fontify around position AROUND..
308 Value is nil if there is nothing more to fontify."
309 (if (zerop (buffer-size))
310 nil
311 (save-restriction
312 (widen)
313 (let* ((next (text-property-any around (point-max) 'fontified nil))
314 (prev (previous-single-property-change around 'fontified))
315 (prop (get-text-property (max (point-min) (1- around))
316 'fontified))
317 (start (cond
318 ((null prev)
319 ;; There is no property change between AROUND
320 ;; and the start of the buffer. If PROP is
321 ;; non-nil, everything in front of AROUND is
322 ;; fontified, otherwise nothing is fontified.
323 (if prop
324 nil
325 (max (point-min)
326 (- around (/ jit-lock-chunk-size 2)))))
327 (prop
328 ;; PREV is the start of a region of fontified
329 ;; text containing AROUND. Start fontifying a
330 ;; chunk size before the end of the unfontified
331 ;; region in front of that.
332 (max (or (previous-single-property-change prev 'fontified)
333 (point-min))
334 (- prev jit-lock-chunk-size)))
335 (t
336 ;; PREV is the start of a region of unfontified
337 ;; text containing AROUND. Start at PREV or
338 ;; chunk size in front of AROUND, whichever is
339 ;; nearer.
340 (max prev (- around jit-lock-chunk-size)))))
341 (result (cond ((null start) next)
342 ((null next) start)
343 ((< (- around start) (- next around)) start)
344 (t next))))
345 result))))
346
347
348 (defun jit-lock-stealth-fontify ()
349 "Fontify buffers stealthily.
350 This functions is called after Emacs has been idle for
351 `jit-lock-stealth-time' seconds."
352 (unless (or executing-kbd-macro
353 (window-minibuffer-p (selected-window)))
354 (let ((buffers (buffer-list))
355 minibuffer-auto-raise
356 message-log-max)
357 (while (and buffers (not (input-pending-p)))
358 (let ((buffer (car buffers)))
359 (setq buffers (cdr buffers))
360
361 (with-current-buffer buffer
362 (when jit-lock-mode
363 ;; This is funny. Calling sit-for with 3rd arg non-nil
364 ;; so that it doesn't redisplay, internally calls
365 ;; wait_reading_process_input also with a parameter
366 ;; saying "don't redisplay." Since this function here
367 ;; is called periodically, this effectively leads to
368 ;; process output not being redisplayed at all because
369 ;; redisplay_internal is never called. (That didn't
370 ;; work in the old redisplay either.) So, we learn that
371 ;; we mustn't call sit-for that way here. But then, we
372 ;; have to be cautious not to call sit-for in a widened
373 ;; buffer, since this could display hidden parts of that
374 ;; buffer. This explains the seemingly weird use of
375 ;; save-restriction/widen here.
376
377 (with-temp-message (if jit-lock-stealth-verbose
378 (concat "JIT stealth lock "
379 (buffer-name)))
380
381 ;; Perform deferred unfontification, if any.
382 (when jit-lock-first-unfontify-pos
383 (save-restriction
384 (widen)
385 (when (and (>= jit-lock-first-unfontify-pos (point-min))
386 (< jit-lock-first-unfontify-pos (point-max)))
387 (with-buffer-prepared-for-jit-lock
388 (put-text-property jit-lock-first-unfontify-pos
389 (point-max) 'fontified nil))
390 (setq jit-lock-first-unfontify-pos (point-max)))))
391
392 ;; In the following code, the `sit-for' calls cause a
393 ;; redisplay, so it's required that the
394 ;; buffer-modified flag of a buffer that is displayed
395 ;; has the right value---otherwise the mode line of
396 ;; an unmodified buffer would show a `*'.
397 (let (start
398 (nice (or jit-lock-stealth-nice 0))
399 (point (point)))
400 (while (and (setq start
401 (jit-lock-stealth-chunk-start point))
402 (sit-for nice))
403
404 ;; Wait a little if load is too high.
405 (when (and jit-lock-stealth-load
406 (> (car (load-average)) jit-lock-stealth-load))
407 (sit-for (or jit-lock-stealth-time 30)))
408
409 ;; Unless there's input pending now, fontify.
410 (unless (input-pending-p)
411 (jit-lock-fontify-now
412 start (+ start jit-lock-chunk-size)))))))))))))
413
414
415 \f
416 ;;; Deferred fontification.
417
418 (defun jit-lock-after-change (start end old-len)
419 "Mark the rest of the buffer as not fontified after a change.
420 Installed on `after-change-functions'.
421 START and END are the start and end of the changed text. OLD-LEN
422 is the pre-change length.
423 This function ensures that lines following the change will be refontified
424 in case the syntax of those lines has changed. Refontification
425 will take place when text is fontified stealthily."
426 (when jit-lock-mode
427 (save-excursion
428 (with-buffer-prepared-for-jit-lock
429 ;; It's important that the `fontified' property be set from the
430 ;; beginning of the line, else font-lock will properly change the
431 ;; text's face, but the display will have been done already and will
432 ;; be inconsistent with the buffer's content.
433 (goto-char start)
434 (setq start (line-beginning-position))
435
436 ;; If we're in text that matches a multi-line font-lock pattern,
437 ;; make sure the whole text will be redisplayed.
438 (when (get-text-property start 'font-lock-multiline)
439 (setq start (or (previous-single-property-change
440 start 'font-lock-multiline)
441 (point-min))))
442
443 ;; Make sure we change at least one char (in case of deletions).
444 (setq end (min (max end (1+ start)) (point-max)))
445 ;; Request refontification.
446 (put-text-property start end 'fontified nil))
447 ;; Mark the change for deferred contextual refontification.
448 (when jit-lock-first-unfontify-pos
449 (setq jit-lock-first-unfontify-pos
450 (min jit-lock-first-unfontify-pos start))))))
451
452 (provide 'jit-lock)
453
454 ;; jit-lock.el ends here