1;;; fast-lock.el --- automagic text properties caching for fast Font Lock mode
2
3;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 2001, 2002, 2003, 2004,
4;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Simon Marshall <simon@gnu.org>
7;; Maintainer: FSF
8;; Keywords: faces files
9;; Version: 3.14
10
11;; This file is part of GNU Emacs.
12
13;; GNU Emacs is free software; you can redistribute it and/or modify
14;; it under the terms of the GNU General Public License as published by
15;; the Free Software Foundation; either version 2, or (at your option)
16;; any later version.
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
24;; along with GNU Emacs; see the file COPYING.  If not, write to the
25;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26;; Boston, MA 02110-1301, USA.
27
28;;; Commentary:
29
30;; Fast Lock mode is a Font Lock support mode.
31;; It makes visiting a file in Font Lock mode faster by restoring its face text
32;; properties from automatically saved associated Font Lock cache files.
33;;
34;; See caveats and feedback below.
35;; See also the lazy-lock package.  (But don't use the two at the same time!)
36
37;; Installation:
38;;
39;; Put in your ~/.emacs:
40;;
41;; (setq font-lock-support-mode 'fast-lock-mode)
42;;
43;; Start up a new Emacs and use font-lock as usual (except that you can use the
44;; so-called "gaudier" fontification regexps on big files without frustration).
45;;
46;; When you visit a file (which has `font-lock-mode' enabled) that has a
47;; corresponding Font Lock cache file associated with it, the Font Lock cache
48;; will be loaded from that file instead of being generated by Font Lock code.
49
50;; Caveats:
51;;
52;; A cache will be saved when visiting a compressed file using crypt++, but not
53;; be read.  This is a "feature"/"consequence"/"bug" of crypt++.
54;;
55;; Version control packages are likely to stamp all over file modification
56;; times.  Therefore the act of checking out may invalidate a cache.
57
58;; History:
59;;
60;; 0.02--1.00:
61;; - Changed name from turbo-prop to fast-lock.  Automagic for font-lock only
62;; - Made `fast-lock-mode' a minor mode, like G. Dinesh Dutt's fss-mode
63;; 1.00--1.01:
64;; - Turn on `fast-lock-mode' only if `buffer-file-name' or `interactive-p'
65;; - Made `fast-lock-file-name' use `buffer-name' if `buffer-file-name' is nil
66;; - Moved save-all conditions to `fast-lock-save-cache'
67;; - Added `fast-lock-save-text-properties' to `kill-buffer-hook'
68;; 1.01--2.00: complete rewrite---not worth the space to document
69;; - Changed structure of text properties cache and threw out file mod checks
70;; 2.00--2.01:
71;; - Made `condition-case' forms understand `quit'.
72;; - Made `fast-lock' require `font-lock'
73;; - Made `fast-lock-cache-name' chase links (from Ben Liblit)
74;; 2.01--3.00:
75;; - Changed structure of cache to include `font-lock-keywords' (from rms)
76;; - Changed `fast-lock-cache-mechanisms' to `fast-lock-cache-directories'
77;; - Removed `fast-lock-read-others'
78;; - Made `fast-lock-read-cache' ignore cache owner
79;; - Made `fast-lock-save-cache-external' create cache directory
80;; - Made `fast-lock-save-cache-external' save `font-lock-keywords'
81;; - Made `fast-lock-cache-data' check `font-lock-keywords'
82;; 3.00--3.01: incorporated port of 2.00 to Lucid, made by Barry Warsaw
83;; - Package now provides itself
84;; - Lucid: Use `font-lock-any-extents-p' for `font-lock-any-properties-p'
85;; - Lucid: Use `list-faces' for `face-list'
86;; - Lucid: Added `set-text-properties'
87;; - Lucid: Made `turn-on-fast-lock' pass 1 not t to `fast-lock-mode'
88;; - Removed test for `fast-lock-mode' from `fast-lock-read-cache'
89;; - Lucid: Added Lucid-specific `fast-lock-get-face-properties'
90;; 3.01--3.02: now works with Lucid Emacs, thanks to Barry Warsaw
91;; - Made `fast-lock-cache-name' map ":" to ";" for OS/2 (from Serganova Vera)
92;; - Made `fast-lock-cache-name' use abbreviated file name (from Barry Warsaw)
93;; - Lucid: Separated handlers for `error' and `quit' for `condition-case'
94;; 3.02--3.03:
95;; - Changed `fast-lock-save-cache-external' to `fast-lock-save-cache-data'
96;; - Lucid: Added Lucid-specific `fast-lock-set-face-properties'
97;; 3.03--3.04:
98;; - Corrected `subrp' test of Lucid code
99;; - Replaced `font-lock-any-properties-p' with `text-property-not-all'
100;; - Lucid: Made `fast-lock-set-face-properties' put `text-prop' on extents
101;; - Made `fast-lock-cache-directories' a regexp alist (from Colin Rafferty)
102;; - Made `fast-lock-cache-directory' to return a usable cache file directory
103;; 3.04--3.05:
104;; - Lucid: Fix for XEmacs 19.11 `text-property-not-all'
105;; - Replaced `subrp' test of Lucid code with `emacs-version' `string-match'
106;; - Made `byte-compile-warnings' omit `unresolved' on compilation
107;; - Made `fast-lock-save-cache-data' use a buffer (from Rick Sladkey)
108;; - Reverted to old `fast-lock-get-face-properties' (from Rick Sladkey)
109;; 3.05--3.06: incorporated hack of 3.03, made by Jonathan Stigelman (Stig)
110;; - Reverted to 3.04 version of `fast-lock-get-face-properties'
111;; - XEmacs: Removed `list-faces' `defalias'
112;; - Made `fast-lock-mode' and `turn-on-fast-lock' succeed `autoload' cookies
113;; - Added `fast-lock-submit-bug-report'
114;; - Renamed `fast-lock-save-size' to `fast-lock-minimum-size'
115;; - Made `fast-lock-save-cache' output a message if no save ever attempted
116;; - Made `fast-lock-save-cache-data' output a message if save attempted
117;; - Made `fast-lock-cache-data' output a message if load attempted
118;; - Made `fast-lock-save-cache-data' do `condition-case' not `unwind-protect'
119;; - Made `fast-lock-save-cache' and `fast-lock-read-cache' return nothing
120;; - Made `fast-lock-save-cache' check `buffer-modified-p' (Stig)
121;; - Added `fast-lock-save-events'
122;; - Added `fast-lock-after-save-hook' to `after-save-hook' (Stig)
123;; - Added `fast-lock-kill-buffer-hook' to `kill-buffer-hook'
124;; - Changed `fast-lock-save-caches' to `fast-lock-kill-emacs-hook'
125;; - Added `fast-lock-kill-emacs-hook' to `kill-emacs-hook'
126;; - Made `fast-lock-save-cache' check `verify-visited-file-modtime' (Stig)
127;; - Made `visited-file-modtime' be the basis of the timestamp (Stig)
128;; - Made `fast-lock-save-cache-1' and `fast-lock-cache-data' use/reformat it
129;; - Added `fast-lock-cache-filename' to keep track of the cache file name
130;; - Added `fast-lock-after-fontify-buffer'
131;; - Added `fast-lock-save-faces' list of faces to save (idea from Stig/Tibor)
132;; - Made `fast-lock-get-face-properties' functions use it
133;; - XEmacs: Made `fast-lock-set-face-properties' do extents the Font Lock way
134;; - XEmacs: Removed fix for `text-property-not-all' (19.11 support dropped)
135;; - Made `fast-lock-mode' ensure `font-lock-mode' is on
136;; - Made `fast-lock-save-cache' do `cdr-safe' not `cdr' (from Dave Foster)
137;; - Made `fast-lock-save-cache' do `set-buffer' first (from Dave Foster)
138;; - Made `fast-lock-save-cache' loop until saved or quit (from Georg Nikodym)
139;; - Made `fast-lock-cache-data' check `buffer-modified-p'
140;; - Made `fast-lock-cache-data' do `font-lock-compile-keywords' if necessary
141;; - XEmacs: Made `font-lock-compile-keywords' `defalias'
142;; 3.06--3.07:
143;; - XEmacs: Add `fast-lock-after-fontify-buffer' to the Font Lock hook
144;; - Made `fast-lock-cache-name' explain the use of `directory-abbrev-alist'
145;; - Made `fast-lock-mode' use `buffer-file-truename' not `buffer-file-name'
146;; 3.07--3.08:
147;; - Made `fast-lock-read-cache' set `fast-lock-cache-filename'
148;; 3.08--3.09:
149;; - Made `fast-lock-save-cache' cope if `fast-lock-minimum-size' is an a list
150;; - Made `fast-lock-mode' respect the value of `font-lock-inhibit-thing-lock'
151;; - Added `fast-lock-after-unfontify-buffer'
152;; 3.09--3.10:
153;; - Rewrite for Common Lisp macros
154;; - Made fast-lock.el barf on a crap 8+3 pseudo-OS (Eli Zaretskii help)
155;; - XEmacs: Made `add-minor-mode' succeed `autoload' cookie
156;; - XEmacs: Made `fast-lock-save-faces' default to `font-lock-face-list'
157;; - Made `fast-lock-save-cache' use `font-lock-value-in-major-mode'
158;; - Wrap with `save-buffer-state' (Ray Van Tassle report)
159;; - Made `fast-lock-mode' wrap `font-lock-support-mode'
160;; 3.10--3.11:
161;; - Made `fast-lock-get-face-properties' cope with face lists
162;; - Added `fast-lock-verbose'
163;; - XEmacs: Add `font-lock-value-in-major-mode' if necessary
164;; - Removed `fast-lock-submit-bug-report' and bade farewell
165;; 3.11--3.12:
166;; - Added Custom support (Hrvoje Niksic help)
167;; - Made `save-buffer-state' wrap `inhibit-point-motion-hooks'
168;; - Made `fast-lock-cache-data' simplify calls of `font-lock-compile-keywords'
169;; 3.12--3.13:
170;; - Removed `byte-*' variables from `eval-when-compile' (Erik Naggum hint)
171;; - Changed structure of cache to include `font-lock-syntactic-keywords'
172;; - Made `fast-lock-save-cache-1' save syntactic fontification data
173;; - Made `fast-lock-cache-data' take syntactic fontification data
174;; - Added `fast-lock-get-syntactic-properties'
175;; - Renamed `fast-lock-set-face-properties' to `fast-lock-add-properties'
176;; - Made `fast-lock-add-properties' add syntactic and face fontification data
177;; 3.13--3.14:
178;; - Made `fast-lock-cache-name' cope with `windowsnt' (Geoff Voelker fix)
179;; - Made `fast-lock-verbose' use `other' widget (Andreas Schwab fix)
180;; - Used `with-temp-message' where possible to make messages temporary.
181
182;;; Code:
183
184(require 'font-lock)
185
186;; Make sure fast-lock.el is supported.
187(if (and (eq system-type 'ms-dos) (not (msdos-long-file-names)))
188    (error "`fast-lock' was written for long file name systems"))
189
190(defvar font-lock-face-list)
191
192(eval-when-compile
193 ;;
194 ;; We don't do this at the top-level as we only use non-autoloaded macros.
195 (require 'cl)
196 ;;
197 ;; We use this to preserve or protect things when modifying text properties.
198 (defmacro save-buffer-state (varlist &rest body)
199   "Bind variables according to VARLIST and eval BODY restoring buffer state."
200   `(let* (,@(append varlist
201                     '((modified (buffer-modified-p)) (buffer-undo-list t)
202                       (inhibit-read-only t) (inhibit-point-motion-hooks t)
203                       before-change-functions after-change-functions
204                       deactivate-mark buffer-file-name buffer-file-truename)))
205     ,@body
206     (when (and (not modified) (buffer-modified-p))
207       (set-buffer-modified-p nil))))
208 (put 'save-buffer-state 'lisp-indent-function 1)
209 ;;
210 ;; We use this to verify that a face should be saved.
211 (defmacro fast-lock-save-facep (face)
212   "Return non-nil if FACE is one of `fast-lock-save-faces'."
213   `(or (null fast-lock-save-faces)
214     (if (symbolp ,face)
215         (memq ,face fast-lock-save-faces)
216         (let ((faces ,face))
217           (while (unless (memq (car faces) fast-lock-save-faces)
218                    (setq faces (cdr faces))))
219           faces))))
220 ;;
221 ;; We use this for compatibility with a future Emacs.
222 (or (fboundp 'with-temp-message)
223     (defmacro with-temp-message (message &rest body)
224       `(let ((temp-message ,message) current-message)
225         (unwind-protect
226              (progn
227                (when temp-message
228                  (setq current-message (current-message))
229                  (message "%s" temp-message))
230                ,@body)
231           (when temp-message
232             (message "%s" current-message))))))
233 ;;
234 ;; We use this for compatibility with a future Emacs.
235 (or (fboundp 'defcustom)
236     (defmacro defcustom (symbol value doc &rest args)
237       `(defvar ,symbol ,value ,doc))))
238
239;;(defun fast-lock-submit-bug-report ()
240;;  "Submit via mail a bug report on fast-lock.el."
241;;  (interactive)
242;;  (let ((reporter-prompt-for-summary-p t))
243;;    (reporter-submit-bug-report "simon@gnu.org" "fast-lock 3.14"
244;;     '(fast-lock-cache-directories fast-lock-minimum-size
245;;       fast-lock-save-others fast-lock-save-events fast-lock-save-faces
246;;       fast-lock-verbose)
247;;     nil nil
248;;     (concat "Hi Si.,
249;;
250;;I want to report a bug.  I've read the `Bugs' section of `Info' on Emacs, so I
251;;know how to make a clear and unambiguous report.  To reproduce the bug:
252;;
253;;Start a fresh editor via `" invocation-name " -no-init-file -no-site-file'.
254;;In the `*scratch*' buffer, evaluate:"))))
255
256(defgroup fast-lock nil
257  "Font Lock support mode to cache fontification."
258  :load 'fast-lock
259  :group 'font-lock)
260
261(defvar fast-lock-mode nil)		; Whether we are turned on.
262(defvar fast-lock-cache-timestamp nil)	; For saving/reading.
263(defvar fast-lock-cache-filename nil)	; For deleting.
264
265;; User Variables:
266
267(defcustom fast-lock-minimum-size 25600
268  "*Minimum size of a buffer for cached fontification.
269Only buffers more than this can have associated Font Lock cache files saved.
270If nil, means cache files are never created.
271If a list, each element should be a cons pair of the form (MAJOR-MODE . SIZE),
272where MAJOR-MODE is a symbol or t (meaning the default).  For example:
273 ((c-mode . 25600) (c++-mode . 25600) (rmail-mode . 1048576))
274means that the minimum size is 25K for buffers in C or C++ modes, one megabyte
275for buffers in Rmail mode, and size is irrelevant otherwise."
276  :type '(choice (const :tag "none" nil)
277		 (integer :tag "size")
278		 (repeat :menu-tag "mode specific" :tag "mode specific"
279			 :value ((t . nil))
280			 (cons :tag "Instance"
281			       (radio :tag "Mode"
282				      (const :tag "all" t)
283				      (symbol :tag "name"))
284			       (radio :tag "Size"
285				      (const :tag "none" nil)
286				      (integer :tag "size")))))
287  :group 'fast-lock)
288
289(defcustom fast-lock-cache-directories '("~/.emacs-flc")
290; - `internal', keep each file's Font Lock cache file in the same file.
291; - `external', keep each file's Font Lock cache file in the same directory.
292  "*Directories in which Font Lock cache files are saved and read.
293Each item should be either DIR or a cons pair of the form (REGEXP . DIR) where
294DIR is a directory name (relative or absolute) and REGEXP is a regexp.
295
296An attempt will be made to save or read Font Lock cache files using these items
297until one succeeds (i.e., until a readable or writable one is found).  If an
298item contains REGEXP, DIR is used only if the buffer file name matches REGEXP.
299For example:
300
301 (let ((home (expand-file-name (abbreviate-file-name (file-truename \"~/\")))))
302   (list (cons (concat \"^\" (regexp-quote home)) \".\") \"~/.emacs-flc\"))
303    =>
304 ((\"^/your/true/home/directory/\" . \".\") \"~/.emacs-flc\")
305
306would cause a file's current directory to be used if the file is under your
307home directory hierarchy, or otherwise the absolute directory `~/.emacs-flc'.
308For security reasons, it is not advisable to use the file's current directory
309to avoid the possibility of using the cache of another user."
310  :type '(repeat (radio (directory :tag "directory")
311			(cons :tag "Matching"
312			      (regexp :tag "regexp")
313			      (directory :tag "directory"))))
314  :group 'fast-lock)
315(put 'fast-lock-cache-directories 'risky-local-variable t)
316
317(defcustom fast-lock-save-events '(kill-buffer kill-emacs)
318  "*Events under which caches will be saved.
319Valid events are `save-buffer', `kill-buffer' and `kill-emacs'.
320If concurrent editing sessions use the same associated cache file for a file's
321buffer, then you should add `save-buffer' to this list."
322  :type '(set (const :tag "buffer saving" save-buffer)
323	      (const :tag "buffer killing" kill-buffer)
324	      (const :tag "emacs killing" kill-emacs))
325  :group 'fast-lock)
326
327(defcustom fast-lock-save-others t
328  "*If non-nil, save Font Lock cache files irrespective of file owner.
329If nil, means only buffer files known to be owned by you can have associated
330Font Lock cache files saved.  Ownership may be unknown for networked files."
331  :type 'boolean
332  :group 'fast-lock)
333
334(defcustom fast-lock-verbose font-lock-verbose
335  "*If non-nil, means show status messages for cache processing.
336If a number, only buffers greater than this size have processing messages."
337  :type '(choice (const :tag "never" nil)
338		 (other :tag "always" t)
339		 (integer :tag "size"))
340  :group 'fast-lock)
341
342(defvar fast-lock-save-faces
343  (when (save-match-data (string-match "XEmacs" (emacs-version)))
344    ;; XEmacs uses extents for everything, so we have to pick the right ones.
345    font-lock-face-list)
346  "Faces that will be saved in a Font Lock cache file.
347If nil, means information for all faces will be saved.")
348
349;; User Functions:
350
351;;;###autoload
352(defun fast-lock-mode (&optional arg)
353  "Toggle Fast Lock mode.
354With arg, turn Fast Lock mode on if and only if arg is positive and the buffer
355is associated with a file.  Enable it automatically in your `~/.emacs' by:
356
357 (setq font-lock-support-mode 'fast-lock-mode)
358
359If Fast Lock mode is enabled, and the current buffer does not contain any text
360properties, any associated Font Lock cache is used if its timestamp matches the
361buffer's file, and its `font-lock-keywords' match those that you are using.
362
363Font Lock caches may be saved:
364- When you save the file's buffer.
365- When you kill an unmodified file's buffer.
366- When you exit Emacs, for all unmodified or saved buffers.
367Depending on the value of `fast-lock-save-events'.
368See also the commands `fast-lock-read-cache' and `fast-lock-save-cache'.
369
370Use \\[font-lock-fontify-buffer] to fontify the buffer if the cache is bad.
371
372Various methods of control are provided for the Font Lock cache.  In general,
373see variable `fast-lock-cache-directories' and function `fast-lock-cache-name'.
374For saving, see variables `fast-lock-minimum-size', `fast-lock-save-events',
375`fast-lock-save-others' and `fast-lock-save-faces'."
376  (interactive "P")
377  ;; Only turn on if we are visiting a file.  We could use `buffer-file-name',
378  ;; but many packages temporarily wrap that to nil when doing their own thing.
379  (set (make-local-variable 'fast-lock-mode)
380       (and buffer-file-truename
381	    (not (memq 'fast-lock-mode font-lock-inhibit-thing-lock))
382	    (if arg (> (prefix-numeric-value arg) 0) (not fast-lock-mode))))
383  (if (and fast-lock-mode (not font-lock-mode))
384      ;; Turned on `fast-lock-mode' rather than `font-lock-mode'.
385      (progn
386        (message "Use font-lock-support-mode rather than calling fast-lock-mode")
387        (sit-for 2))
388    ;; Let's get down to business.
389    (set (make-local-variable 'fast-lock-cache-timestamp) nil)
390    (set (make-local-variable 'fast-lock-cache-filename) nil)
391    (when (and fast-lock-mode (not font-lock-fontified))
392      (fast-lock-read-cache))))
393
394(defun fast-lock-read-cache ()
395  "Read the Font Lock cache for the current buffer.
396
397The following criteria must be met for a Font Lock cache file to be read:
398- Fast Lock mode must be turned on in the buffer.
399- The buffer must not be modified.
400- The buffer's `font-lock-keywords' must match the cache's.
401- The buffer file's timestamp must match the cache's.
402- Criteria imposed by `fast-lock-cache-directories'.
403
404See `fast-lock-mode'."
405  (interactive)
406  (let ((directories fast-lock-cache-directories)
407	(modified (buffer-modified-p)) (inhibit-read-only t)
408	(fontified font-lock-fontified))
409    (set (make-local-variable 'font-lock-fontified) nil)
410    ;; Keep trying directories until fontification is turned off.
411    (while (and directories (not font-lock-fontified))
412      (let ((directory (fast-lock-cache-directory (car directories) nil)))
413	(condition-case nil
414	    (when directory
415	      (setq fast-lock-cache-filename (fast-lock-cache-name directory))
416	      (when (file-readable-p fast-lock-cache-filename)
417		(load fast-lock-cache-filename t t t)))
418	  (error nil) (quit nil))
419	(setq directories (cdr directories))))
420    ;; Unset `fast-lock-cache-filename', and restore `font-lock-fontified', if
421    ;; we don't use a cache.  (Note that `fast-lock-cache-data' sets the value
422    ;; of `fast-lock-cache-timestamp'.)
423    (set-buffer-modified-p modified)
424    (unless font-lock-fontified
425      (setq fast-lock-cache-filename nil font-lock-fontified fontified))))
426
427(defun fast-lock-save-cache (&optional buffer)
428  "Save the Font Lock cache of BUFFER or the current buffer.
429
430The following criteria must be met for a Font Lock cache file to be saved:
431- Fast Lock mode must be turned on in the buffer.
432- The event must be one of `fast-lock-save-events'.
433- The buffer must be at least `fast-lock-minimum-size' bytes long.
434- The buffer file must be owned by you, or `fast-lock-save-others' must be t.
435- The buffer must contain at least one `face' text property.
436- The buffer must not be modified.
437- The buffer file's timestamp must be the same as the file's on disk.
438- The on disk file's timestamp must be different than the buffer's cache.
439- Criteria imposed by `fast-lock-cache-directories'.
440
441See `fast-lock-mode'."
442  (interactive)
443  (save-excursion
444    (when buffer
445      (set-buffer buffer))
446    (let ((min-size (font-lock-value-in-major-mode fast-lock-minimum-size))
447	  (file-timestamp (visited-file-modtime)) (saved nil))
448      (when (and fast-lock-mode
449	     ;;
450	     ;; "Only save if the buffer matches the file, the file has
451	     ;; changed, and it was changed by the current emacs session."
452	     ;;
453	     ;; Only save if the buffer is not modified,
454	     ;; (i.e., so we don't save for something not on disk)
455	     (not (buffer-modified-p))
456	     ;; and the file's timestamp is the same as the buffer's,
457	     ;; (i.e., someone else hasn't written the file in the meantime)
458	     (verify-visited-file-modtime (current-buffer))
459	     ;; and the file's timestamp is different from the cache's.
460	     ;; (i.e., a save has occurred since the cache was read)
461	     (not (equal fast-lock-cache-timestamp file-timestamp))
462	     ;;
463	     ;; Only save if user's restrictions are satisfied.
464	     (and min-size (>= (buffer-size) min-size))
465	     (or fast-lock-save-others
466		 (eq (user-uid) (nth 2 (file-attributes buffer-file-name))))
467	     ;;
468	     ;; Only save if there are `face' properties to save.
469	     (text-property-not-all (point-min) (point-max) 'face nil))
470	;;
471	;; Try each directory until we manage to save or the user quits.
472	(let ((directories fast-lock-cache-directories))
473	  (while (and directories (memq saved '(nil error)))
474	    (let* ((dir (fast-lock-cache-directory (car directories) t))
475		   (file (and dir (fast-lock-cache-name dir))))
476	      (when (and file (file-writable-p file))
477		(setq saved (fast-lock-save-cache-1 file file-timestamp)))
478	      (setq directories (cdr directories)))))))))
479
480;;;###autoload
481(defun turn-on-fast-lock ()
482  "Unconditionally turn on Fast Lock mode."
483  (fast-lock-mode t))
484
485;;; API Functions:
486
487(defun fast-lock-after-fontify-buffer ()
488  ;; Delete the Font Lock cache file used to restore fontification, if any.
489  (when fast-lock-cache-filename
490    (if (file-writable-p fast-lock-cache-filename)
491	(delete-file fast-lock-cache-filename)
492      (message "File %s font lock cache cannot be deleted" (buffer-name))))
493  ;; Flag so that a cache will be saved later even if the file is never saved.
494  (setq fast-lock-cache-timestamp nil))
495
496(defalias 'fast-lock-after-unfontify-buffer
497  'ignore)
498
499;; Miscellaneous Functions:
500
501(defun fast-lock-save-cache-after-save-file ()
502  ;; Do `fast-lock-save-cache' if `save-buffer' is on `fast-lock-save-events'.
503  (when (memq 'save-buffer fast-lock-save-events)
504    (fast-lock-save-cache)))
505
506(defun fast-lock-save-cache-before-kill-buffer ()
507  ;; Do `fast-lock-save-cache' if `kill-buffer' is on `fast-lock-save-events'.
508  (when (memq 'kill-buffer fast-lock-save-events)
509    (fast-lock-save-cache)))
510
511(defun fast-lock-save-caches-before-kill-emacs ()
512  ;; Do `fast-lock-save-cache's if `kill-emacs' is on `fast-lock-save-events'.
513  (when (memq 'kill-emacs fast-lock-save-events)
514    (mapcar 'fast-lock-save-cache (buffer-list))))
515
516(defun fast-lock-cache-directory (directory create)
517  "Return usable directory based on DIRECTORY.
518Returns nil if the directory does not exist, or, if CREATE non-nil, cannot be
519created.  DIRECTORY may be a string or a cons pair of the form (REGEXP . DIR).
520See `fast-lock-cache-directories'."
521  (let ((dir
522	 (cond ((not buffer-file-name)
523		;; Should never be nil, but `crypt++' screws it up.
524		nil)
525	       ((stringp directory)
526		;; Just a directory.
527		directory)
528	       (t
529		;; A directory iff the file name matches the regexp.
530		(let ((bufile (expand-file-name buffer-file-truename))
531		      (case-fold-search nil))
532		  (when (save-match-data (string-match (car directory) bufile))
533		    (cdr directory)))))))
534    (cond ((not dir)
535	   nil)
536	  ((file-accessible-directory-p dir)
537	   dir)
538	  (create
539	   (condition-case nil
540	       (progn (make-directory dir t) dir)
541	     (error nil))))))
542
543;; If you are wondering why we only hash if the directory is not ".", rather
544;; than if `file-name-absolute-p', it is because if we just appended ".flc" for
545;; relative cache directories (that are not ".") then it is possible that more
546;; than one file would have the same cache name in that directory, if the luser
547;; made a link from one relative cache directory to another.  (Phew!)
548(defun fast-lock-cache-name (directory)
549  "Return full cache file name using caching DIRECTORY.
550If DIRECTORY is `.', the file name is the buffer file name appended with `.flc'.
551Otherwise, the file name is constructed from DIRECTORY and the buffer's true
552abbreviated file name, with all `/' characters in the name replaced with `#'
553characters, and appended with `.flc'.
554
555If the same file has different cache file names when edited on different
556machines, e.g., on one machine the cache file name has the prefix `#home',
557perhaps due to automount, try putting in your `~/.emacs' something like:
558
559 (setq directory-abbrev-alist (cons '(\"^/home/\" . \"/\") directory-abbrev-alist))
560
561Emacs automagically removes the common `/tmp_mnt' automount prefix by default.
562
563See `fast-lock-cache-directory'."
564  (if (string-equal directory ".")
565      (concat buffer-file-name ".flc")
566    (let* ((bufile (expand-file-name buffer-file-truename))
567	   (chars-alist
568	    (if (memq system-type '(emx windows-nt cygwin))
569		'((?/ . (?#)) (?# . (?# ?#)) (?: . (?\;)) (?\; . (?\; ?\;)))
570	      '((?/ . (?#)) (?# . (?# ?#)))))
571	   (mapchars
572	    (function (lambda (c) (or (cdr (assq c chars-alist)) (list c))))))
573      (concat
574       (file-name-as-directory (expand-file-name directory))
575       (mapconcat 'char-to-string (apply 'append (mapcar mapchars bufile)) "")
576       ".flc"))))
577
578;; Font Lock Cache Processing Functions:
579
580;; The version 3 format of the cache is:
581;;
582;; (fast-lock-cache-data VERSION TIMESTAMP
583;;  font-lock-syntactic-keywords SYNTACTIC-PROPERTIES
584;;  font-lock-keywords FACE-PROPERTIES)
585
586(defun fast-lock-save-cache-1 (file timestamp)
587  ;; Save the FILE with the TIMESTAMP plus fontification data.
588  ;; Returns non-nil if a save was attempted to a writable cache file.
589  (let ((tpbuf (generate-new-buffer " *fast-lock*"))
590	(verbose (if (numberp fast-lock-verbose)
591		     (> (buffer-size) fast-lock-verbose)
592		   fast-lock-verbose))
593	(saved t))
594    (with-temp-message
595	(when verbose
596	  (format "Saving %s font lock cache..." (buffer-name)))
597      (condition-case nil
598	  (save-excursion
599	    (print (list 'fast-lock-cache-data 3
600			 (list 'quote timestamp)
601			 (list 'quote font-lock-syntactic-keywords)
602			 (list 'quote (fast-lock-get-syntactic-properties))
603			 (list 'quote font-lock-keywords)
604			 (list 'quote (fast-lock-get-face-properties)))
605		   tpbuf)
606	    (set-buffer tpbuf)
607	    (write-region (point-min) (point-max) file nil 'quietly)
608	    (setq fast-lock-cache-timestamp timestamp
609		  fast-lock-cache-filename file))
610	(error (setq saved 'error)) (quit (setq saved 'quit)))
611      (kill-buffer tpbuf))
612    (cond ((eq saved 'quit)
613	   (message "Saving %s font lock cache...quit" (buffer-name)))
614	  ((eq saved 'error)
615	   (message "Saving %s font lock cache...failed" (buffer-name))))
616    ;; We return non-nil regardless of whether a failure occurred.
617    saved))
618
619(defun fast-lock-cache-data (version timestamp
620			     syntactic-keywords syntactic-properties
621			     keywords face-properties
622			     &rest ignored)
623  ;; Find value of syntactic keywords in case it is a symbol.
624  (setq font-lock-syntactic-keywords (font-lock-eval-keywords
625				      font-lock-syntactic-keywords))
626  ;; Compile all keywords in case some are and some aren't.
627  (when font-lock-syntactic-keywords
628    (setq font-lock-syntactic-keywords (font-lock-compile-keywords
629					font-lock-syntactic-keywords t)))
630  (when syntactic-keywords
631    (setq syntactic-keywords (font-lock-compile-keywords syntactic-keywords t)))
632  (setq font-lock-keywords (font-lock-compile-keywords font-lock-keywords)
633	keywords (font-lock-compile-keywords keywords))
634  ;; Use the Font Lock cache SYNTACTIC-PROPERTIES and FACE-PROPERTIES if we're
635  ;; using cache VERSION format 3, the current buffer's file timestamp matches
636  ;; the TIMESTAMP, the current buffer's `font-lock-syntactic-keywords' are the
637  ;; same as SYNTACTIC-KEYWORDS, and the current buffer's `font-lock-keywords'
638  ;; are the same as KEYWORDS.
639  (let ((buf-timestamp (visited-file-modtime))
640	(verbose (if (numberp fast-lock-verbose)
641		     (> (buffer-size) fast-lock-verbose)
642		   fast-lock-verbose))
643	(loaded t))
644    (if (or (/= version 3)
645	    (buffer-modified-p)
646	    (not (equal timestamp buf-timestamp))
647	    (not (equal syntactic-keywords font-lock-syntactic-keywords))
648	    (not (equal keywords font-lock-keywords)))
649	(setq loaded nil)
650      (with-temp-message
651	  (when verbose
652	    (format "Loading %s font lock cache..." (buffer-name)))
653	(condition-case nil
654	    (fast-lock-add-properties syntactic-properties face-properties)
655	  (error (setq loaded 'error)) (quit (setq loaded 'quit))))
656      (cond ((eq loaded 'quit)
657	     (message "Loading %s font lock cache...quit" (buffer-name)))
658	    ((eq loaded 'error)
659	     (message "Loading %s font lock cache...failed" (buffer-name)))))
660    (setq font-lock-fontified (eq loaded t)
661	  fast-lock-cache-timestamp (and (eq loaded t) timestamp))))
662
663;; Text Properties Processing Functions:
664
665;; This is fast, but fails if adjacent characters have different `face' text
666;; properties.  Maybe that's why I dropped it in the first place?
667;(defun fast-lock-get-face-properties ()
668;  "Return a list of `face' text properties in the current buffer.
669;Each element of the list is of the form (VALUE START1 END1 START2 END2 ...)
670;where VALUE is a `face' property value and STARTx and ENDx are positions."
671;  (save-restriction
672;    (widen)
673;    (let ((start (text-property-not-all (point-min) (point-max) 'face nil))
674;	  (limit (point-max)) end properties value cell)
675;      (while start
676;	(setq end (next-single-property-change start 'face nil limit)
677;	      value (get-text-property start 'face))
678;	;; Make, or add to existing, list of regions with same `face'.
679;	(if (setq cell (assq value properties))
680;	    (setcdr cell (cons start (cons end (cdr cell))))
681;	  (setq properties (cons (list value start end) properties)))
682;	(setq start (next-single-property-change end 'face)))
683;      properties)))
684
685;; This is slow, but copes if adjacent characters have different `face' text
686;; properties, but fails if they are lists.
687;(defun fast-lock-get-face-properties ()
688;  "Return a list of `face' text properties in the current buffer.
689;Each element of the list is of the form (VALUE START1 END1 START2 END2 ...)
690;where VALUE is a `face' property value and STARTx and ENDx are positions.
691;Only those `face' VALUEs in `fast-lock-save-faces' are returned."
692;  (save-restriction
693;    (widen)
694;    (let ((faces (or fast-lock-save-faces (face-list))) (limit (point-max))
695;	  properties regions face start end)
696;      (while faces
697;	(setq face (car faces) faces (cdr faces) regions () end (point-min))
698;	;; Make a list of start/end regions with `face' property face.
699;	(while (setq start (text-property-any end limit 'face face))
700;	  (setq end (or (text-property-not-all start limit 'face face) limit)
701;		regions (cons start (cons end regions))))
702;	;; Add `face' face's regions, if any, to properties.
703;	(when regions
704;	  (push (cons face regions) properties)))
705;      properties)))
706
707(defun fast-lock-get-face-properties ()
708  "Return a list of `face' text properties in the current buffer.
709Each element of the list is of the form (VALUE START1 END1 START2 END2 ...)
710where VALUE is a `face' property value and STARTx and ENDx are positions."
711  (save-restriction
712    (widen)
713    (let ((start (text-property-not-all (point-min) (point-max) 'face nil))
714	  end properties value cell)
715      (while start
716	(setq end (next-single-property-change start 'face nil (point-max))
717	      value (get-text-property start 'face))
718	;; Make, or add to existing, list of regions with same `face'.
719	(cond ((setq cell (assoc value properties))
720	       (setcdr cell (cons start (cons end (cdr cell)))))
721	      ((fast-lock-save-facep value)
722	       (push (list value start end) properties)))
723	(setq start (text-property-not-all end (point-max) 'face nil)))
724      properties)))
725
726(defun fast-lock-get-syntactic-properties ()
727  "Return a list of `syntax-table' text properties in the current buffer.
728See `fast-lock-get-face-properties'."
729  (save-restriction
730    (widen)
731    (let ((start (text-property-not-all (point-min) (point-max) 'syntax-table
732					nil))
733	  end properties value cell)
734      (while start
735	(setq end (next-single-property-change start 'syntax-table nil
736					       (point-max))
737	      value (get-text-property start 'syntax-table))
738	;; Make, or add to existing, list of regions with same `syntax-table'.
739	(if (setq cell (assoc value properties))
740	    (setcdr cell (cons start (cons end (cdr cell))))
741	  (push (list value start end) properties))
742	(setq start (text-property-not-all end (point-max) 'syntax-table nil)))
743      properties)))
744
745(defun fast-lock-add-properties (syntactic-properties face-properties)
746  "Add `syntax-table' and `face' text properties to the current buffer.
747Any existing `syntax-table' and `face' text properties are removed first.
748See `fast-lock-get-face-properties'."
749  (save-buffer-state (plist regions)
750    (save-restriction
751      (widen)
752      (font-lock-unfontify-region (point-min) (point-max))
753      ;;
754      ;; Set the `syntax-table' property for each start/end region.
755      (while syntactic-properties
756	(setq plist (list 'syntax-table (car (car syntactic-properties)))
757	      regions (cdr (car syntactic-properties))
758	      syntactic-properties (cdr syntactic-properties))
759	(while regions
760	  (add-text-properties (nth 0 regions) (nth 1 regions) plist)
761	  (setq regions (nthcdr 2 regions))))
762      ;;
763      ;; Set the `face' property for each start/end region.
764      (while face-properties
765	(setq plist (list 'face (car (car face-properties)))
766	      regions (cdr (car face-properties))
767	      face-properties (cdr face-properties))
768	(while regions
769	  (add-text-properties (nth 0 regions) (nth 1 regions) plist)
770	  (setq regions (nthcdr 2 regions)))))))
771
772;; Functions for XEmacs:
773
774(when (save-match-data (string-match "XEmacs" (emacs-version)))
775  ;;
776  ;; It would be better to use XEmacs' `map-extents' over extents with a
777  ;; `font-lock' property, but `face' properties are on different extents.
778  (defun fast-lock-get-face-properties ()
779    "Return a list of `face' text properties in the current buffer.
780Each element of the list is of the form (VALUE START1 END1 START2 END2 ...)
781where VALUE is a `face' property value and STARTx and ENDx are positions.
782Only those `face' VALUEs in `fast-lock-save-faces' are returned."
783    (save-restriction
784      (widen)
785      (let ((properties ()) cell)
786	(map-extents
787	 (function (lambda (extent ignore)
788	    (let ((value (extent-face extent)))
789	      ;; We're only interested if it's one of `fast-lock-save-faces'.
790	      (when (and value (fast-lock-save-facep value))
791		(let ((start (extent-start-position extent))
792		      (end (extent-end-position extent)))
793		  ;; Make or add to existing list of regions with the same
794		  ;; `face' property value.
795		  (if (setq cell (assoc value properties))
796		      (setcdr cell (cons start (cons end (cdr cell))))
797		    (push (list value start end) properties))))
798	      ;; Return nil to keep `map-extents' going.
799	      nil))))
800	properties)))
801  ;;
802  ;; XEmacs does not support the `syntax-table' text property.
803  (defalias 'fast-lock-get-syntactic-properties
804    'ignore)
805  ;;
806  ;; Make extents just like XEmacs' font-lock.el does.
807  (defun fast-lock-add-properties (syntactic-properties face-properties)
808    "Set `face' text properties in the current buffer.
809Any existing `face' text properties are removed first.
810See `fast-lock-get-face-properties'."
811    (save-restriction
812      (widen)
813      (font-lock-unfontify-region (point-min) (point-max))
814      ;; Set the `face' property, etc., for each start/end region.
815      (while face-properties
816	(let ((face (car (car face-properties)))
817	      (regions (cdr (car face-properties))))
818	  (while regions
819	    (font-lock-set-face (nth 0 regions) (nth 1 regions) face)
820	    (setq regions (nthcdr 2 regions)))
821	  (setq face-properties (cdr face-properties))))
822      ;; XEmacs does not support the `syntax-table' text property.
823      ))
824  ;;
825  ;; XEmacs 19.12 font-lock.el's `font-lock-fontify-buffer' runs a hook.
826  (add-hook 'font-lock-after-fontify-buffer-hook
827	    'fast-lock-after-fontify-buffer))
828
829(unless (boundp 'font-lock-syntactic-keywords)
830  (defvar font-lock-syntactic-keywords nil))
831
832(unless (boundp 'font-lock-inhibit-thing-lock)
833  (defvar font-lock-inhibit-thing-lock nil))
834
835(unless (fboundp 'font-lock-compile-keywords)
836  (defalias 'font-lock-compile-keywords 'identity))
837
838(unless (fboundp 'font-lock-eval-keywords)
839  (defun font-lock-eval-keywords (keywords)
840    (if (symbolp keywords)
841	(font-lock-eval-keywords (if (fboundp keywords)
842				     (funcall keywords)
843				   (eval keywords)))
844      keywords)))
845
846(unless (fboundp 'font-lock-value-in-major-mode)
847  (defun font-lock-value-in-major-mode (alist)
848    (if (consp alist)
849	(cdr (or (assq major-mode alist) (assq t alist)))
850      alist)))
851
852(unless (fboundp 'current-message)
853  (defun current-message ()
854    ""))
855
856;; Install ourselves:
857
858(add-hook 'after-save-hook 'fast-lock-save-cache-after-save-file)
859(add-hook 'kill-buffer-hook 'fast-lock-save-cache-before-kill-buffer)
860(add-hook 'kill-emacs-hook 'fast-lock-save-caches-before-kill-emacs)
861
862;;;###autoload
863(when (fboundp 'add-minor-mode)
864  (defvar fast-lock-mode nil)
865  (add-minor-mode 'fast-lock-mode nil))
866;;;###dont-autoload
867(unless (assq 'fast-lock-mode minor-mode-alist)
868  (setq minor-mode-alist (append minor-mode-alist '((fast-lock-mode nil)))))
869
870;; Provide ourselves:
871
872(provide 'fast-lock)
873
874;; arch-tag: 638c431e-8cae-4538-80a1-963ff97d233e
875;;; fast-lock.el ends here
876