;;; lazy-lock.el --- Lazy demand-driven fontification for fast Font Lock mode.

;; Copyright (C) 1994, 1995 Free Software Foundation, Inc.
;; Copyright (C) 2000 Ben Wing.

;; Author: Simon Marshall <simon@gnu.ai.mit.edu>
;; X-Modified-By: Ben Wing <ben@xemacs.org>
;; Maintainer: XEmacs Development Team
;; Keywords: faces files
;; Version: XEmacs of May 17, 2000.

;;; This file is part of XEmacs.

;; XEmacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

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

;; You should have received a copy of the GNU General Public License
;; along with XEmacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Synched up with: Divergent from FSF.

;;; Commentary:

;; This version of Lazy Lock has special modifications for XEmacs by Ben Wing
;; that have never been merged into the FSF's version.  The FSF version
;; supports GNU Emacs only, and relies on C support that is extremely
;; kludgy and not supported by XEmacs.  This version uses `pre-idle-hook'
;; instead.

;; For reasons that are not at all clear to me, someone went ahead and
;; created another lazy fontification package for XEmacs (lazy-shot).
;; That package relies on the extent property `initial-redisplay-function',
;; which would not be so bad except that the implementation of this
;; function is broken in that the function is called through an eval
;; event, which is executed *after* redisplay.  Thus, horrible redisplay
;; flashing.  To fix this, let the function be called at pre-idle-hook
;; time.

;; (NB Steve claimed that lazy-lock is too slow or something.  However,
;; I used to use it regularly on a Pentium 90 with no problems.)
;;
;; --ben

;; Purpose:
;;
;; To make visiting buffers in `font-lock-mode' faster by making fontification
;; be demand-driven and stealthy.
;; Fontification only occurs when, and where, necessary.
;;
;; See caveats and feedback below.  See also the defer-lock and fast-lock
;; packages.  (But don't use lazy-lock.el and fast-lock.el or lazy-shot.el
;; at the same time!)

;; Installation:
;;
;; (add-hook 'font-lock-mode-hook 'turn-on-lazy-lock)
;;
;; Start up a new Emacs and use font-lock as usual (except that you can use the
;; so-called "gaudier" fontification regexps on big files without frustration).
;;
;; In a buffer (which has `font-lock-mode' enabled) which is at least
;; `lazy-lock-minimum-size' characters long, only the visible portion of the
;; buffer will be fontified.  Motion around the buffer will fontify those
;; visible portions that were not previous fontified.  If the variable
;; `lazy-lock-hide-invisible' is non-nil, redisplay will be delayed until after
;; fontification.  Otherwise, text that has not yet been fontified is displayed
;; in `lazy-lock-invisible-foreground'.
;;
;; If stealth fontification is enabled, fontification will occur in invisible
;; parts of the buffer after `lazy-lock-stealth-time' seconds of idle time.
;; Caveats:
;;
;; Lazy Lock mode does not work efficiently with Outline mode.  This is because
;; when in Outline mode, although text may be hidden (not visible in the
;; window), the text is visible to Emacs Lisp code (not surprisingly) and Lazy
;; Lock fontifies it mercilessly.  Hopefully this will be fixed one day.

;; Feedback:
;;
;; Feedback is welcome.
;; To submit a bug report (or make comments) please send to ben@xemacs.org.

(require 'font-lock)

(eval-when-compile
  ;; Only `require' so `ediff-multiframe-setup-p' is expanded at compile time.
  (condition-case nil (require 'ediff) (file-error))
  ;; Well, shouldn't Lazy Lock be as lazy as possible?
  ;(setq byte-compile-dynamic t byte-compile-dynamic-docstrings t)
  (defvar deactivate-mark)		; I think this is obsolete...
  ;;
  ;; We use this for clarity and speed.  Naughty but nice.
  (defmacro do-while (test &rest body)
    "(do-while TEST BODY...): eval BODY... and repeat if TEST yields non-nil.
The order of execution is thus BODY, TEST, BODY, TEST and so on
until TEST returns nil."
    (` (while (progn (,@ body) (, test)))))
  (put 'do-while 'lisp-indent-function (get 'while 'lisp-indent-function))
  ;;
  ;; We use this for compatibility with a future Emacs.
  (or (fboundp 'with-temp-message)
      (defmacro with-temp-message (message &rest body)
	(` (let ((temp-message (, message)) current-message)
	     (unwind-protect
		 (progn
		   (when temp-message
		     (setq current-message (current-message))
		     (message temp-message))
		   (,@ body))
	       (when temp-message
		 (message current-message)))))))
  ;;
  )

(defvar lazy-lock-cache-start nil)	; for window fontifiction
(defvar lazy-lock-cache-end nil)	; for window fontifiction

(defgroup lazy-lock nil
  "Lazy-lock customizations"
  :group 'font-lock
  :prefix "lazy-lock-")

;;;###autoload
(defcustom lazy-lock-mode nil
  "Non nil means `lazy-lock-mode' is on."
  :group 'lazy-lock
  :require 'lazy-lock ;; which in turn requires font-lock.
  :type 'boolean
  :initialize 'custom-initialize-default
  :set '(lambda (var val)
	  (if val
	      (progn
		(lazy-lock-mode 1)
		(add-hook 'font-lock-mode-hook 'turn-on-lazy-lock))
	    (lazy-lock-mode -1)
	    (remove-hook 'font-lock-mode-hook 'turn-on-lazy-lock))
	  (setq-default lazy-lock-mode val))
  )


;; User Variables:

(defcustom lazy-lock-minimum-size (* 25 1024)
    "*Minimum size of a buffer for demand-driven fontification.
On-demand fontification occurs if the buffer size is greater than this value.
If nil, means demand-driven fontification is never performed."
    :type '(choice (const :tag "Off" nil)
		   (integer :tag "Size"))
    :group 'lazy-lock)

(defcustom lazy-lock-walk-windows 'all-frames
  "*If non-nil, fontify windows other than the selected window.
If `all-frames', fontify windows even on other frames.
A non-nil value slows down redisplay."
  :type 'boolean
  :group 'lazy-lock)

;; not by default because it's not stealthy enough -- it can cause
;; annoying and unpredictable delays when it's running and you try to
;; do something.
(defcustom lazy-lock-stealth-time nil ;(if lazy-lock-running-xemacs-p 12 30)
  "*Time in seconds to delay before beginning stealth fontification.
Stealth fontification occurs if there is no input within this time.
If nil, means stealth fontification is never performed.

The value of this variable is used when Lazy Lock mode is turned on."
  :type '(choice (const :tag "never" nil)
		 (number :tag "seconds"))
  :group 'lazy-lock)

(defcustom lazy-lock-stealth-lines (if font-lock-maximum-decoration 100 250)
  "*Maximum size of a chunk of stealth fontification.
Each iteration of stealth fontification can fontify this number of lines.
To speed up input response during stealth fontification, at the cost of stealth
taking longer to fontify, you could reduce the value of this variable."
  :type '(integer :tag "lines")
  :group 'lazy-lock)

(defcustom lazy-lock-stealth-load
  (if (condition-case nil (load-average) (error)) 200)
  "*Load in percentage above which stealth fontification is suspended.
Stealth fontification pauses when the system short-term load average (as
returned by the function `load-average' if supported) goes above this level,
thus reducing the demand that stealth fontification makes on the system.
If nil, means stealth fontification is never suspended.
To reduce machine load during stealth fontification, at the cost of stealth
taking longer to fontify, you could reduce the value of this variable.
See also `lazy-lock-stealth-nice'."
  :type (if (condition-case nil (load-average) (error))
	    '(choice (const :tag "never" nil)
		     (integer :tag "load"))
	  '(const :format "%t: unsupported\n" nil))
  :group 'lazy-lock)

(defcustom lazy-lock-stealth-nice 0.125
  "*Time in seconds to pause between chunks of stealth fontification.
Each iteration of stealth fontification is separated by this amount of time,
thus reducing the demand that stealth fontification makes on the system.
If nil, means stealth fontification is never paused.
To reduce machine load during stealth fontification, at the cost of stealth
taking longer to fontify, you could increase the value of this variable.
See also `lazy-lock-stealth-load'."
  :type '(choice (const :tag "never" nil)
		 (number :tag "seconds"))
  :group 'lazy-lock)

(defcustom lazy-lock-stealth-verbose (not (null font-lock-verbose))
  "*If non-nil, means stealth fontification should show status messages."
  :type 'boolean
  :group 'lazy-lock)

(defvar lazy-lock-ignore-commands
  (append
   ;; Standard commands...
   '(universal-argument digit-argument negative-argument
     isearch-other-control-char isearch-other-meta-char)
   ;; And some resulting from non-standard packages...
   (if (fboundp 'calc) '(calcDigit-key)))
  "A list of commands after which fontification should not occur.
To speed up typing response, at the cost of Lazy Lock not fontifying when
insertion causes scrolling, you could add `self-insert-command' to this list.")

(defcustom lazy-lock-hide-invisible t
  "*If non-nil, hide invisible text while it is fontified.
If non-nil, redisplay is delayed until after fontification occurs.  If nil,
text is shown (in `lazy-lock-invisible-foreground') while it is fontified.
A non-nil value slows down redisplay and can slow down cursor motion.
But a nil value causes terribly annoying flashing, so you really don't
want to change this variable."
  :type 'boolean
  :group 'lazy-lock)

(defcustom lazy-lock-invisible-foreground "gray50"
  "The foreground colour to use to display invisible text.
If nil, the default foreground is used.  If t, the default background is used.
If a string, it should be a colour to use (either its name or its RGB value).
Invisible text is momentarily seen (if `lazy-lock-hide-invisible' is nil) when
scrolling into unfontified regions."
  :type 'string
  :group 'lazy-lock)


;; User Functions:

;;;###autoload
(defun lazy-lock-mode (&optional arg)
  "Toggle Lazy Lock mode.
With arg, turn Lazy Lock mode on if and only if arg is positive.  Enable it
automatically in your `~/.emacs' by:

 (add-hook 'font-lock-mode-hook 'turn-on-lazy-lock)

When Lazy Lock mode is enabled, fontification can be lazy in a number of ways:

- Demand-driven buffer fontification if `lazy-lock-minimum-size' is non-nil.
  This means initial fontification does not occur if the buffer is greater than
  `lazy-lock-minimum-size' characters in length.  Instead, fontification occurs
  when necessary, such as when scrolling through the buffer would otherwise
  reveal unfontified areas.  This is useful if buffer fontification is too slow
  for large buffers.

- Stealthy buffer fontification if `lazy-lock-stealth-time' is non-nil.
  This means remaining unfontified areas of buffers are fontified if Emacs has
  been idle for `lazy-lock-stealth-time' seconds, while Emacs remains idle.
  This is useful if any buffer has any deferred fontification.

Stealth fontification only occurs while the system remains unloaded.
If the system load rises above `lazy-lock-stealth-load' percent, stealth
fontification is suspended.  Stealth fontification intensity is controlled via
the variable `lazy-lock-stealth-nice' and `lazy-lock-stealth-lines', and
verbosity is controlled via the variable `lazy-lock-stealth-verbose'.

If `lazy-lock-hide-invisible' is non-nil, text is not displayed until it is
fontified, otherwise it is displayed in `lazy-lock-invisible-foreground'.

See also variables `lazy-lock-walk-windows' and `lazy-lock-ignore-commands'."

; From doc string of lazy-lock 2.11
;- Deferred scroll fontification if `lazy-lock-defer-on-scrolling' is non-nil.
;  This means demand-driven fontification does not occur as you
;  scroll.  Instead, fontification is deferred until after
;  `lazy-lock-defer-time' seconds of Emacs idle time, while Emacs
;  remains idle.  This is useful if fontification is too slow to keep
;  up with scrolling.

;- Deferred on-the-fly fontification if `lazy-lock-defer-on-the-fly' is
;  non-nil.  This means on-the-fly fontification does not occur as you
;  type.  Instead, fontification is deferred until after
;  `lazy-lock-defer-time' seconds of Emacs idle time, while Emacs
;  remains idle.  This is useful if fontification is too slow to keep
;  up with your typing.

;- Deferred context fontification if `lazy-lock-defer-contextually' is non-nil.
;  This means fontification updates the buffer corresponding to true
;  syntactic context, after `lazy-lock-defer-time' seconds of Emacs
;  idle time, while Emacs remains idle.  Otherwise, fontification
;  occurs on modified lines only, and subsequent lines can remain
;  fontified corresponding to previous syntactic contexts.  This is
;  useful where strings or comments span lines.

;Basic Font Lock mode on-the-fly fontification behaviour fontifies
;modified lines only.  Thus, if `lazy-lock-defer-contextually' is
;non-nil, Lazy Lock mode on-the-fly fontification may fontify
;differently, albeit correctly.  In any event, to refontify some lines
;you can use \\[font-lock-fontify-region].

  (interactive "P")
  (set (make-local-variable 'lazy-lock-mode)
       (and (<= (or lazy-lock-minimum-size 0) (buffer-size))
	    (if arg (> (prefix-numeric-value arg) 0) (not lazy-lock-mode))))
  (if (and lazy-lock-mode (not font-lock-mode))
      ;; Turned on `lazy-lock-mode' rather than using `font-lock-mode-hook'.
      (progn
	(add-hook 'font-lock-mode-hook 'turn-on-lazy-lock)
	(font-lock-mode 1))
    (lazy-lock-fixup-hooks)
    ;; Let's get down to business.
    (if (not lazy-lock-mode)
	(let ((modified (buffer-modified-p)) (inhibit-read-only t)
	      (buffer-undo-list t)
	      deactivate-mark buffer-file-name buffer-file-truename)
	  (remove-text-properties (point-min) (point-max) '(fontified nil))
	  (or modified (set-buffer-modified-p nil)))
      (if (and (not lazy-lock-hide-invisible) lazy-lock-invisible-foreground)
	  (lazy-lock-colour-invisible))
      (set (make-local-variable 'lazy-lock-cache-start) 0)
      (set (make-local-variable 'lazy-lock-cache-end) 0)
      (set (make-local-variable 'font-lock-fontified) t))))

;;;###autoload
(defun turn-on-lazy-lock ()
  "Unconditionally turn on Lazy Lock mode."
  (lazy-lock-mode 1))

;; API Functions:

(defun lazy-lock-fixup-hooks ()
  ;; Make sure our hooks are correct.
  (remove-hook 'pre-idle-hook 'lazy-lock-pre-idle-fontify-windows)
  (remove-hook 'post-command-hook 'lazy-lock-post-command-fontify-stealthily)
  ;; Make sure our hooks are at the end.  Font-lock in XEmacs installs
  ;; its own pre-idle-hook to implement deferral (#### something that
  ;; should really be merged with this file; or more likely, lazy-lock
  ;; in its entirety should be merged into font-lock).
  (add-hook 'pre-idle-hook 'lazy-lock-pre-idle-fontify-windows t)
  (add-hook 'post-command-hook 'lazy-lock-post-command-fontify-stealthily t)
  ;; Fascistically remove font-lock's after-change-function and install
  ;; our own.  We know better than font-lock what to do.  Otherwise,
  ;; revert-buffer, insert-file, etc. cause full refontification of the
  ;; entire changed area.
  (if lazy-lock-mode
      (progn
	(remove-hook 'after-change-functions 'font-lock-after-change-function
		     t)
	(make-local-hook 'after-change-functions)
	(add-hook 'after-change-functions 'lazy-lock-after-change-function
		  nil t))
    (remove-hook 'after-change-functions 'lazy-lock-after-change-function t)
    (if font-lock-mode
	(add-hook 'after-change-functions 'font-lock-after-change-function
		  nil t)))
)

;; use put-nonduplicable-text-property to avoid unfriendly behavior
;; when doing undo, etc.  We really don't want syntax-highlighting text
;; properties copied into strings or tracked by undo.
;;
;; #### If start-open and end-open really behaved like they are supposed to,
;; we wouldn't really need this.  I kind of fixed them up, but there's still
;; a bug -- inserting text into the middle of a region of
;; (start-open t end-open t) text should cause it not to inherit, but it
;; does.

(defalias 'lazy-lock-put-text-property 'put-nonduplicable-text-property)

(defun lazy-lock-fontify-region (start end &optional buffer)
  "Fontify between START and END in BUFFER where necessary."
  (save-excursion
    (and buffer (set-buffer buffer))
    (save-restriction
      (narrow-to-region start end)
      (let ((lazy-lock-stealth-lines (count-lines start end)))
	(while (text-property-not-all start end 'lazy-lock-fontified t)
	  (lazy-lock-fontify-stealthily))))))

(defun lazy-lock-after-fontify-buffer ()
  ;; Mark the buffer as `fontified'.
  (let ((modified (buffer-modified-p)) (inhibit-read-only t)
	(buffer-undo-list t)
	deactivate-mark buffer-file-name buffer-file-truename)
    (lazy-lock-put-text-property (point-min) (point-max)
				 'lazy-lock-fontified t)
    (or modified (set-buffer-modified-p nil))))


;; Functions for hooks:

;; lazy-lock optimization:
;;
;; pre-idle-hook is called an awful lot -- pretty much every time the
;; mouse moves or a timeout expires, for example.  On Linux (sometimes),
;; IRIX 5.x, and Solaris 2.something, it happens every 1/4 of a second
;; due to the 1/4-second timers installed to compensate for various
;; operating system deficiencies in the handling of SIGIO and SIGCHLD.
;; (Those timers cause a cycle of the event loop.  They don't necessarily
;; have to, but rewriting to avoid this is fairly tricky and requires
;; having significant amounts of code called from signal handlers, which
;; (despite that fact that FSF Emacs reads its X input during a signal
;; handler ?!), is almost always a bad idea -- it's extremely easy to
;; introduce race conditions, which are very hard to track down.
;;
;; So to improve things, I added `frame-modified-tick'.  This is an
;; internal counter that gets ticked any time that any internal
;; redisplay variable gets ticked.  If `frame-modified-tick' is
;; the same as the last time we checked, it means that redisplay will
;; do absolutely nothing when encountering this frame, and thus we
;; can skip out immediately.  This happens when the 1/4-second timer
;; fires while we're idle, or if we just move the mouse. (Moving
;; around in a buffer changes `frame-modified-tick' because the
;; internal redisplay variable "point_changed" gets ticked.  We could
;; easily improve things further by adding more tick counters, mirroring
;; more closely the internal redisplay counters -- e.g. if we had
;; another counter that didn't get ticked when point moved, we could
;; tell if anything was going to happen by seeing if point is within
;; window-start and window-end, since we know that redisplay will
;; only do a window-scroll if it's not. (If window-start or window-end
;; or window-buffer or anything else changed, windows_changed or
;; some other variable will get ticked.))
;;
;; Also, it's wise to try and avoid things that cons.  Avoiding
;; `save-window-excursion', as we do, is definitely a major win
;; because that's a heavy-duty consing function.  In fact, we do no
;; consing at all (or change any global state, e.g. by calling
;; select-window, for that matter) until the frame-modified tick goes
;; off, and even then the only potential consing we do is
;; save-excursion; but in fact, that is consless too.


(defun lazy-lock-pre-idle-fontify-windows ()
;  (princ (frame-property 'lazy-lock-modified-tick (selected-frame))
;	 'external-debugging-output)
;  (print (frame-modified-tick (selected-frame)) 'external-debugging-output)
  (unless (memq this-command lazy-lock-ignore-commands)
    ;; Do the visible parts of the buffer(s), i.e., the window(s).
    (if (or (not lazy-lock-walk-windows)
	    (and (eq lazy-lock-walk-windows t) (one-window-p t)))
       (or (window-minibuffer-p (selected-window))
	    (lazy-lock-maybe-fontify-window (selected-window)))
      (if (eq lazy-lock-walk-windows t)
	  (lazy-lock-maybe-fontify-frame (selected-frame))
	;; Visit all visible non-minibuffer-only frames on the selected device.
	;; This is harder than it looks, since the `next-frame'
	;; interface is error-prone - finding the starting frame is hard.
	(catch 'lazy-lock-frame-loop-done
	  (let* ((starting-frame (selected-frame))
		 (frame starting-frame))
	    (when (or (not (frame-visible-p frame))
		      (frame-minibuffer-only-p frame))
	      ;; starting-frame not suitable.
	      (setq starting-frame (next-frame starting-frame 'visible-nomini))
	      (when (eq starting-frame frame)
		;; No suitable frames.
		(throw 'lazy-lock-frame-loop-done t))
	      (setq frame starting-frame))
	    (while t
	      (lazy-lock-maybe-fontify-frame frame)
	      (setq frame (next-frame frame 'visible-nomini))
	      (when (eq frame starting-frame)
		(throw 'lazy-lock-frame-loop-done t)))))))))

(defun lazy-lock-maybe-fontify-frame (frame)
  ;; Fontify the given frame if we need to.  We first check the
  ;; appropriate frame-modified-tick to avoid changing global state.
  (let ((tick (frame-modified-tick frame)))
    (unless (eq tick (frame-property frame 'lazy-lock-modified-tick))
      (set-frame-property frame 'lazy-lock-modified-tick tick)
      (with-selected-frame frame
	(walk-windows #'lazy-lock-maybe-fontify-window 'no-minibuf)))))

(defun lazy-lock-after-change-function (beg end old-len)
  (when lazy-lock-mode
    (if (= beg end)
	(font-lock-after-change-function beg end old-len)
      (lazy-lock-put-text-property beg end 'lazy-lock-fontified nil))))

(defvar lazy-lock-timeout-id nil)

(defun lazy-lock-post-command-fontify-stealthily ()
  ;; we used to use sit-for to do the idle delay.  this was a holdover
  ;; from FSF Emacs, which doesn't (or didn't?) have built-in timers.
  ;; using sit-for is unfriendly and can cause weird interactions.
  (when (and (not (memq this-command lazy-lock-ignore-commands))
            (not (window-minibuffer-p (selected-window)))
	     lazy-lock-stealth-time)
    (if lazy-lock-timeout-id (disable-timeout lazy-lock-timeout-id))
    (setq lazy-lock-timeout-id
	  (add-timeout lazy-lock-stealth-time
		       #'lazy-lock-fontify-walk-stealthily nil))))

(defun lazy-lock-post-setup-emacs-fontify-windows ()
  ;; Fontify all windows in all frames.
  (let ((lazy-lock-walk-windows 'all-frames) executing-kbd-macro this-command)
    (lazy-lock-pre-idle-fontify-windows)))

(defun lazy-lock-post-setup-ediff-control-frame ()
  ;; Fontify all windows in all frames when using the Ediff control frame.
  (make-local-variable 'lazy-lock-walk-windows)
  (setq lazy-lock-walk-windows (if (ediff-multiframe-setup-p) 'all-frames t))
  (lazy-lock-fixup-hooks))

;; Functions for fontification:

(defun lazy-lock-maybe-fontify-window (window)
  ;; Fontify the given window if we need to.  We first check the
  ;; buffer-local value of lazy-lock-mode to make sure we should do
  ;; the more accurate (but semi-expensive) checks in
  ;; lazy-lock-fontify-window.  In this function, we are careful not
  ;; to change any global state by calling select-window, which will
  ;; trip frame-modified-tick, until we've verified that we need to
  ;; proceed to lazy-lock-fontify-window.
  (when (symbol-value-in-buffer 'lazy-lock-mode (window-buffer window))
    (save-selected-window
      (select-window window)
      (lazy-lock-fontify-window))))

(defun lazy-lock-fontify-window ()
  ;; Fontify the visible part of the buffer where necessary.
  (let ((ws (if lazy-lock-hide-invisible
		(save-excursion
		  (end-of-line) (forward-line (- (window-height))) (point))
	      (min (max (window-start) (point-min)) (point-max))))
	(we (if lazy-lock-hide-invisible
		(save-excursion
		  (end-of-line) (forward-line (window-height)) (point))
	      ;; use the GUARANTEE option on window-end to be more accurate.
	      (min (max (1- (window-end nil t)) (point-min)) (point-max)))))
    (if (or (not (eq ws lazy-lock-cache-start))
	    (not (eq we lazy-lock-cache-end)))
	;; Find where we haven't `fontified' before.
	(let* ((start (or (text-property-not-all ws we
						 'lazy-lock-fontified t) ws))
	       (end (or (text-property-any start we
					   'lazy-lock-fontified t) we))
	       (modified (buffer-modified-p))
	       (inhibit-read-only t)
	       ;; We do the following to prevent: undo list addition; region
	       ;; highlight disappearance; supersession/locking checks.
	       (buffer-undo-list t)
	       deactivate-mark buffer-file-name buffer-file-truename
	       ;; Ensure Emacs 19.30 syntactic fontification is always correct.
	       font-lock-beginning-of-syntax-function
	       ;; Prevent XEmacs 19.13 during fontification from messages.
	       font-lock-verbose)
	  (while (< start end)
	    ;; Fontify and flag the region as `fontified'.
	    ;; XEmacs: need to bind `font-lock-always-fontify-immediately'
	    ;; or we'll mess up in the presence of deferred font-locking.
	    (let ((font-lock-always-fontify-immediately t))
	      (font-lock-after-change-function start end 0))
	    (lazy-lock-put-text-property start end 'lazy-lock-fontified t)
	    ;; Find the next region.
	    (setq start (or (text-property-not-all ws we
						   'lazy-lock-fontified t) ws)
		  end (or (text-property-any start we
					     'lazy-lock-fontified t) we)))
	  (setq lazy-lock-cache-start ws lazy-lock-cache-end we)
	  (or modified (set-buffer-modified-p nil))))))

(defun lazy-lock-fontify-stealthily ()
  ;; Fontify an invisible part of the buffer where necessary.
  (save-excursion
    ;; Move to the end in case the character to the left is not `fontified'.
    (end-of-line)
    ;; Find where the next and previous regions not `fontified' begin and end.
    (let ((next (text-property-not-all (point) (point-max)
				       'lazy-lock-fontified t))
	  (prev (let ((p (previous-single-property-change
			  (point) 'lazy-lock-fontified)))
		  (and p (> p (point-min)) p)))
	  (modified (buffer-modified-p)) (inhibit-read-only t) start end
	  ;; We do the following to prevent: undo list addition; region
	  ;; highlight disappearance; supersession/locking checks.
	  (buffer-undo-list t)
	  deactivate-mark buffer-file-name buffer-file-truename
	  ;; Ensure Emacs 19.30 syntactic fontification is always correct.
	  font-lock-beginning-of-syntax-function
	  ;; Prevent XEmacs 19.13 during fontification from spewing messages.
	  font-lock-verbose)
      (cond ((and (null next) (null prev))
	     ;; Nothing has been `fontified' yet.
	     (beginning-of-line 1) (setq start (point))
	     (forward-line (or lazy-lock-stealth-lines (window-height)))
	     (setq end (point)))
	    ((or (null prev)
		 (and next (> (- (point) prev) (- next (point)))))
	     ;; The next region is the nearest not `fontified'.
	     (goto-char next) (beginning-of-line 1) (setq start (point))
	     (forward-line (or lazy-lock-stealth-lines (window-height)))
	     ;; Maybe the region is already partially `fontified'.
	     (setq end (or (text-property-any next (point)
					      'lazy-lock-fontified t)
			   (point))))
	    (t
	     ;; The previous region is the nearest not `fontified'.
	     (goto-char prev) (forward-line 1) (setq end (point))
	     (forward-line (- (or lazy-lock-stealth-lines (window-height))))
	     ;; Maybe the region is already partially `fontified'.
	     (setq start
	      (or (previous-single-property-change
		   prev
		   'lazy-lock-fontified nil (point))
		  (point)))))
      ;; Fontify and flag the region as `fontified'.
      ;; XEmacs: need to bind `font-lock-always-fontify-immediately'
      ;; or we'll mess up in the presence of deferred font-locking.
      (let ((font-lock-always-fontify-immediately t))
	(font-lock-after-change-function start end 0))
      (lazy-lock-put-text-property start end 'lazy-lock-fontified t)
      (or modified (set-buffer-modified-p nil)))))

(defun lazy-lock-fontify-walk-stealthily (ignored)
  ;; Loop over all buffers, fontify stealthily for each if necessary.
  (let ((buffers (buffer-list)) (continue t) message
	log-message-max-size ;minibuffer-auto-raise
	)
    (save-excursion
      (do-while (and buffers continue)
	(set-buffer (car buffers))
	(if (not (and lazy-lock-mode (lazy-lock-unfontified-p)))
	    (setq continue (not (input-pending-p)))
	  ;; Fontify regions in this buffer while there is no input.
	  (with-temp-message
	   (when lazy-lock-stealth-verbose
	     "Fontifying stealthily...")
	   (do-while (and (lazy-lock-unfontified-p) continue)
	     (if (and lazy-lock-stealth-load
		      (> (car (load-average)) lazy-lock-stealth-load))
		 ;; Wait a while before continuing with the loop.
		 (progn
		   (when message
		     (message "Fontifying stealthily...suspended")
		     (setq message nil))
		   (setq continue (sit-for (or lazy-lock-stealth-time 30))))
	       ;; Fontify a chunk.
	       (when lazy-lock-stealth-verbose
		 (if message
		     (message "Fontifying stealthily... %2d%% of %s"
			      (lazy-lock-percent-fontified) (buffer-name))
		   (message "Fontifying stealthily...")
		   (setq message t)))
	       ;; We `save-restriction' and `widen' around everything as
	       ;; `lazy-lock-fontify-stealthily' doesn't and we `sit-for'.
	       (save-restriction (widen) (lazy-lock-fontify-stealthily))
	       (setq continue (sit-for (or lazy-lock-stealth-nice 0)))))))
	(setq buffers (cdr buffers))))))

(defun lazy-lock-unfontified-p ()
  ;; Return non-nil if there is anywhere still to be `fontified'.
  (save-restriction
    (widen)
    (text-property-not-all (point-min) (point-max) 'lazy-lock-fontified t)))

(defun lazy-lock-percent-fontified ()
  ;; Return the percentage (of characters) of the buffer that are `fontified'.
  (save-restriction
    (widen)
    (let ((size 0) (start (point-min)) (max (point-max)) end)
      (while (setq start (text-property-any start max 'lazy-lock-fontified t))
	(setq end (or (text-property-not-all start max
					     'lazy-lock-fontified t) max)
	      size (+ size (- end start))
	      start end))
      ;; Saying "99% done" is probably better than "100% done" when it isn't.
      (truncate (/ (* size 100.0) (buffer-size))))))

(defun lazy-lock-colour-invisible ()
  ;; Fontify the current buffer in `lazy-lock-invisible-face'.
  (save-restriction
    (widen)
    (let ((face 'lazy-lock-invisible-face)
	  (fore (if (stringp lazy-lock-invisible-foreground)
		    lazy-lock-invisible-foreground
		  (cdr (assq 'background-color (frame-parameters)))))
	  (modified (buffer-modified-p)) (inhibit-read-only t)
	  (buffer-undo-list t)
	  deactivate-mark buffer-file-name buffer-file-truename)
      (make-face face)
      (if (not (equal (face-foreground face) fore))
	  (condition-case nil
	      (set-face-foreground face fore)
	    (error (message "Unable to use foreground \"%s\"" fore))))
      (lazy-lock-put-text-property (point-min) (point-max) 'face face)
      (lazy-lock-put-text-property (point-min) (point-max)
				   'lazy-lock-fontified nil)
      (or modified (set-buffer-modified-p nil)))))

(add-hook 'font-lock-after-fontify-buffer-hook
	  'lazy-lock-after-fontify-buffer)


;; Install ourselves:

;; We don't install ourselves on `font-lock-mode-hook' as other packages can be
;; used with font-lock.el, and lazy-lock.el should be dumpable without forcing
;; people to get lazy or making it difficult for people to use alternatives.
;; make sure we add after font-lock's own pre-idle-hook.
(add-hook 'window-setup-hook 'lazy-lock-post-setup-emacs-fontify-windows)

;; Package-specific.
(add-hook 'ediff-after-setup-control-frame-hooks
	  'lazy-lock-post-setup-ediff-control-frame)

;; Maybe save on the modeline?
;;(setcdr (assq 'font-lock-mode minor-mode-alist) '(" Lazy"))

;(or (assq 'lazy-lock-mode minor-mode-alist)
;    (setq minor-mode-alist (cons '(lazy-lock-mode " Lazy") minor-mode-alist)))

;; XEmacs change: do it the right way.  This works with modeline mousing.
;;;###autoload
(add-minor-mode 'lazy-lock-mode " Lazy")

;; Provide ourselves:

(provide 'lazy-lock)

;;; lazy-lock.el ends here
