* lisp/hi-lock.el: Rework the default face and the serialize regexp code.
[bpt/emacs.git] / lisp / hi-lock.el
1 ;;; hi-lock.el --- minor mode for interactive automatic highlighting -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2000-2012 Free Software Foundation, Inc.
4
5 ;; Author: David M. Koppelman <koppel@ece.lsu.edu>
6 ;; Keywords: faces, minor-mode, matching, display
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 3 of the License, or
13 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24 ;;
25 ;; With the hi-lock commands text matching interactively entered
26 ;; regexp's can be highlighted. For example, `M-x highlight-regexp
27 ;; RET clearly RET RET' will highlight all occurrences of `clearly'
28 ;; using a yellow background face. New occurrences of `clearly' will
29 ;; be highlighted as they are typed. `M-x unhighlight-regexp RET'
30 ;; will remove the highlighting. Any existing face can be used for
31 ;; highlighting and a set of appropriate faces is provided. The
32 ;; regexps can be written into the current buffer in a form that will
33 ;; be recognized the next time the corresponding file is read (when
34 ;; file patterns is turned on).
35 ;;
36 ;; Applications:
37 ;;
38 ;; In program source code highlight a variable to quickly see all
39 ;; places it is modified or referenced:
40 ;; M-x highlight-regexp ground_contact_switches_closed RET RET
41 ;;
42 ;; In a shell or other buffer that is showing lots of program
43 ;; output, highlight the parts of the output you're interested in:
44 ;; M-x highlight-regexp Total execution time [0-9]+ RET hi-blue-b RET
45 ;;
46 ;; In buffers displaying tables, highlight the lines you're interested in:
47 ;; M-x highlight-lines-matching-regexp January 2000 RET hi-black-b RET
48 ;;
49 ;; When writing text, highlight personal cliches. This can be
50 ;; amusing.
51 ;; M-x highlight-phrase as can be seen RET RET
52 ;;
53 ;; Setup:
54 ;;
55 ;; Put the following code in your init file. This turns on
56 ;; hi-lock mode and adds a "Regexp Highlighting" entry
57 ;; to the edit menu.
58 ;;
59 ;; (global-hi-lock-mode 1)
60 ;;
61 ;; To enable the use of patterns found in files (presumably placed
62 ;; there by hi-lock) include the following in your init file:
63 ;;
64 ;; (setq hi-lock-file-patterns-policy 'ask)
65 ;;
66 ;; If you get tired of being asked each time a file is loaded replace
67 ;; `ask' with a function that returns t if patterns should be read.
68 ;;
69 ;; You might also want to bind the hi-lock commands to more
70 ;; finger-friendly sequences:
71
72 ;; (define-key hi-lock-map "\C-z\C-h" 'highlight-lines-matching-regexp)
73 ;; (define-key hi-lock-map "\C-zi" 'hi-lock-find-patterns)
74 ;; (define-key hi-lock-map "\C-zh" 'highlight-regexp)
75 ;; (define-key hi-lock-map "\C-zp" 'highlight-phrase)
76 ;; (define-key hi-lock-map "\C-zr" 'unhighlight-regexp)
77 ;; (define-key hi-lock-map "\C-zb" 'hi-lock-write-interactive-patterns))
78
79 ;; See the documentation for hi-lock-mode `C-h f hi-lock-mode' for
80 ;; additional instructions.
81
82 ;; Sample file patterns:
83
84 ; Hi-lock: (("^;;; .*" (0 (quote hi-black-hb) t)))
85 ; Hi-lock: ( ("make-variable-buffer-\\(local\\)" (0 font-lock-keyword-face)(1 'italic append)))))
86 ; Hi-lock: end
87
88 ;;; Code:
89
90 (require 'font-lock)
91
92 (defgroup hi-lock nil
93 "Interactively add and remove font-lock patterns for highlighting text."
94 :link '(custom-manual "(emacs)Highlight Interactively")
95 :group 'font-lock)
96
97 (defcustom hi-lock-file-patterns-range 10000
98 "Limit of search in a buffer for hi-lock patterns.
99 When a file is visited and hi-lock mode is on, patterns starting
100 up to this limit are added to font-lock's patterns. See documentation
101 of functions `hi-lock-mode' and `hi-lock-find-patterns'."
102 :type 'integer
103 :group 'hi-lock)
104
105 (defcustom hi-lock-highlight-range 200000
106 "Size of area highlighted by hi-lock when font-lock not active.
107 Font-lock is not active in buffers that do their own highlighting,
108 such as the buffer created by `list-colors-display'. In those buffers
109 hi-lock patterns will only be applied over a range of
110 `hi-lock-highlight-range' characters. If font-lock is active then
111 highlighting will be applied throughout the buffer."
112 :type 'integer
113 :group 'hi-lock)
114
115 (defcustom hi-lock-exclude-modes
116 '(rmail-mode mime/viewer-mode gnus-article-mode)
117 "List of major modes in which hi-lock will not run.
118 For security reasons since font lock patterns can specify function
119 calls."
120 :type '(repeat symbol)
121 :group 'hi-lock)
122
123 (defcustom hi-lock-file-patterns-policy 'ask
124 "Specify when hi-lock should use patterns found in file.
125 If `ask', prompt when patterns found in buffer; if bound to a function,
126 use patterns when function returns t (function is called with patterns
127 as first argument); if nil or `never' or anything else, don't use file
128 patterns."
129 :type '(choice (const :tag "Do not use file patterns" never)
130 (const :tag "Ask about file patterns" ask)
131 (function :tag "Function to check file patterns"))
132 :group 'hi-lock
133 :version "22.1")
134
135 ;; It can have a function value.
136 (put 'hi-lock-file-patterns-policy 'risky-local-variable t)
137
138 (defcustom hi-lock-auto-select-face nil
139 "Non-nil if highlighting commands should not prompt for face names.
140 When non-nil, each hi-lock command will cycle through faces in
141 `hi-lock-face-defaults' without prompting."
142 :type 'boolean
143 :version "24.4")
144
145 (defgroup hi-lock-faces nil
146 "Faces for hi-lock."
147 :group 'hi-lock
148 :group 'faces)
149
150 (defface hi-yellow
151 '((((min-colors 88) (background dark))
152 (:background "yellow1" :foreground "black"))
153 (((background dark)) (:background "yellow" :foreground "black"))
154 (((min-colors 88)) (:background "yellow1"))
155 (t (:background "yellow")))
156 "Default face for hi-lock mode."
157 :group 'hi-lock-faces)
158
159 (defface hi-pink
160 '((((background dark)) (:background "pink" :foreground "black"))
161 (t (:background "pink")))
162 "Face for hi-lock mode."
163 :group 'hi-lock-faces)
164
165 (defface hi-green
166 '((((min-colors 88) (background dark))
167 (:background "green1" :foreground "black"))
168 (((background dark)) (:background "green" :foreground "black"))
169 (((min-colors 88)) (:background "green1"))
170 (t (:background "green")))
171 "Face for hi-lock mode."
172 :group 'hi-lock-faces)
173
174 (defface hi-blue
175 '((((background dark)) (:background "light blue" :foreground "black"))
176 (t (:background "light blue")))
177 "Face for hi-lock mode."
178 :group 'hi-lock-faces)
179
180 (defface hi-black-b
181 '((t (:weight bold)))
182 "Face for hi-lock mode."
183 :group 'hi-lock-faces)
184
185 (defface hi-blue-b
186 '((((min-colors 88)) (:weight bold :foreground "blue1"))
187 (t (:weight bold :foreground "blue")))
188 "Face for hi-lock mode."
189 :group 'hi-lock-faces)
190
191 (defface hi-green-b
192 '((((min-colors 88)) (:weight bold :foreground "green1"))
193 (t (:weight bold :foreground "green")))
194 "Face for hi-lock mode."
195 :group 'hi-lock-faces)
196
197 (defface hi-red-b
198 '((((min-colors 88)) (:weight bold :foreground "red1"))
199 (t (:weight bold :foreground "red")))
200 "Face for hi-lock mode."
201 :group 'hi-lock-faces)
202
203 (defface hi-black-hb
204 '((t (:weight bold :height 1.67 :inherit variable-pitch)))
205 "Face for hi-lock mode."
206 :group 'hi-lock-faces)
207
208 (defvar hi-lock-file-patterns nil
209 "Patterns found in file for hi-lock. Should not be changed.")
210
211 (defvar hi-lock-interactive-patterns nil
212 "Patterns provided to hi-lock by user. Should not be changed.")
213
214 (define-obsolete-variable-alias 'hi-lock-face-history
215 'hi-lock-face-defaults "23.1")
216 (defvar hi-lock-face-defaults
217 '("hi-yellow" "hi-pink" "hi-green" "hi-blue" "hi-black-b"
218 "hi-blue-b" "hi-red-b" "hi-green-b" "hi-black-hb")
219 "Default faces for hi-lock interactive functions.")
220
221 (define-obsolete-variable-alias 'hi-lock-regexp-history
222 'regexp-history
223 "23.1")
224
225 (defvar hi-lock-file-patterns-prefix "Hi-lock"
226 "Search target for finding hi-lock patterns at top of file.")
227
228 (defvar hi-lock-archaic-interface-message-used nil
229 "True if user alerted that `global-hi-lock-mode' is now the global switch.
230 Earlier versions of hi-lock used `hi-lock-mode' as the global switch;
231 the message is issued if it appears that `hi-lock-mode' is used assuming
232 that older functionality. This variable avoids multiple reminders.")
233
234 (defvar hi-lock-archaic-interface-deduce nil
235 "If non-nil, sometimes assume that `hi-lock-mode' means `global-hi-lock-mode'.
236 Assumption is made if `hi-lock-mode' used in the *scratch* buffer while
237 a library is being loaded.")
238
239 (make-variable-buffer-local 'hi-lock-interactive-patterns)
240 (put 'hi-lock-interactive-patterns 'permanent-local t)
241 (make-variable-buffer-local 'hi-lock-file-patterns)
242 (put 'hi-lock-file-patterns 'permanent-local t)
243
244 (defvar hi-lock-menu
245 (let ((map (make-sparse-keymap "Hi Lock")))
246 (define-key-after map [highlight-regexp]
247 '(menu-item "Highlight Regexp..." highlight-regexp
248 :help "Highlight text matching PATTERN (a regexp)."))
249
250 (define-key-after map [highlight-phrase]
251 '(menu-item "Highlight Phrase..." highlight-phrase
252 :help "Highlight text matching PATTERN (a regexp processed to match phrases)."))
253
254 (define-key-after map [highlight-lines-matching-regexp]
255 '(menu-item "Highlight Lines..." highlight-lines-matching-regexp
256 :help "Highlight lines containing match of PATTERN (a regexp)."))
257
258 (define-key-after map [unhighlight-regexp]
259 '(menu-item "Remove Highlighting..." unhighlight-regexp
260 :help "Remove previously entered highlighting pattern."
261 :enable hi-lock-interactive-patterns))
262
263 (define-key-after map [hi-lock-write-interactive-patterns]
264 '(menu-item "Patterns to Buffer" hi-lock-write-interactive-patterns
265 :help "Insert interactively added REGEXPs into buffer at point."
266 :enable hi-lock-interactive-patterns))
267
268 (define-key-after map [hi-lock-find-patterns]
269 '(menu-item "Patterns from Buffer" hi-lock-find-patterns
270 :help "Use patterns (if any) near top of buffer."))
271 map)
272 "Menu for hi-lock mode.")
273
274 (defvar hi-lock-map
275 (let ((map (make-sparse-keymap "Hi Lock")))
276 (define-key map "\C-xwi" 'hi-lock-find-patterns)
277 (define-key map "\C-xwl" 'highlight-lines-matching-regexp)
278 (define-key map "\C-xwp" 'highlight-phrase)
279 (define-key map "\C-xwh" 'highlight-regexp)
280 (define-key map "\C-xwr" 'unhighlight-regexp)
281 (define-key map "\C-xwb" 'hi-lock-write-interactive-patterns)
282 map)
283 "Key map for hi-lock.")
284
285 ;; Visible Functions
286
287 ;;;###autoload
288 (define-minor-mode hi-lock-mode
289 "Toggle selective highlighting of patterns (Hi Lock mode).
290 With a prefix argument ARG, enable Hi Lock mode if ARG is
291 positive, and disable it otherwise. If called from Lisp, enable
292 the mode if ARG is omitted or nil.
293
294 Hi Lock mode is automatically enabled when you invoke any of the
295 highlighting commands listed below, such as \\[highlight-regexp].
296 To enable Hi Lock mode in all buffers, use `global-hi-lock-mode'
297 or add (global-hi-lock-mode 1) to your init file.
298
299 In buffers where Font Lock mode is enabled, patterns are
300 highlighted using font lock. In buffers where Font Lock mode is
301 disabled, patterns are applied using overlays; in this case, the
302 highlighting will not be updated as you type.
303
304 When Hi Lock mode is enabled, a \"Regexp Highlighting\" submenu
305 is added to the \"Edit\" menu. The commands in the submenu,
306 which can be called interactively, are:
307
308 \\[highlight-regexp] REGEXP FACE
309 Highlight matches of pattern REGEXP in current buffer with FACE.
310
311 \\[highlight-phrase] PHRASE FACE
312 Highlight matches of phrase PHRASE in current buffer with FACE.
313 (PHRASE can be any REGEXP, but spaces will be replaced by matches
314 to whitespace and initial lower-case letters will become case insensitive.)
315
316 \\[highlight-lines-matching-regexp] REGEXP FACE
317 Highlight lines containing matches of REGEXP in current buffer with FACE.
318
319 \\[unhighlight-regexp] REGEXP
320 Remove highlighting on matches of REGEXP in current buffer.
321
322 \\[hi-lock-write-interactive-patterns]
323 Write active REGEXPs into buffer as comments (if possible). They may
324 be read the next time file is loaded or when the \\[hi-lock-find-patterns] command
325 is issued. The inserted regexps are in the form of font lock keywords.
326 (See `font-lock-keywords'.) They may be edited and re-loaded with \\[hi-lock-find-patterns],
327 any valid `font-lock-keywords' form is acceptable. When a file is
328 loaded the patterns are read if `hi-lock-file-patterns-policy' is
329 'ask and the user responds y to the prompt, or if
330 `hi-lock-file-patterns-policy' is bound to a function and that
331 function returns t.
332
333 \\[hi-lock-find-patterns]
334 Re-read patterns stored in buffer (in the format produced by \\[hi-lock-write-interactive-patterns]).
335
336 When hi-lock is started and if the mode is not excluded or patterns
337 rejected, the beginning of the buffer is searched for lines of the
338 form:
339 Hi-lock: FOO
340
341 where FOO is a list of patterns. The patterns must start before
342 position \(number of characters into buffer)
343 `hi-lock-file-patterns-range'. Patterns will be read until
344 Hi-lock: end is found. A mode is excluded if it's in the list
345 `hi-lock-exclude-modes'."
346 :group 'hi-lock
347 :lighter (:eval (if (or hi-lock-interactive-patterns
348 hi-lock-file-patterns)
349 " Hi" ""))
350 :global nil
351 :keymap hi-lock-map
352 (when (and (equal (buffer-name) "*scratch*")
353 load-in-progress
354 (not (called-interactively-p 'interactive))
355 (not hi-lock-archaic-interface-message-used))
356 (setq hi-lock-archaic-interface-message-used t)
357 (if hi-lock-archaic-interface-deduce
358 (global-hi-lock-mode hi-lock-mode)
359 (warn
360 "Possible archaic use of (hi-lock-mode).
361 Use (global-hi-lock-mode 1) in .emacs to enable hi-lock for all buffers,
362 use (hi-lock-mode 1) for individual buffers. For compatibility with Emacs
363 versions before 22 use the following in your init file:
364
365 (if (functionp 'global-hi-lock-mode)
366 (global-hi-lock-mode 1)
367 (hi-lock-mode 1))
368 ")))
369 (if hi-lock-mode
370 ;; Turned on.
371 (progn
372 (define-key-after menu-bar-edit-menu [hi-lock]
373 (cons "Regexp Highlighting" hi-lock-menu))
374 (hi-lock-find-patterns)
375 (add-hook 'font-lock-mode-hook 'hi-lock-font-lock-hook nil t))
376 ;; Turned off.
377 (when (or hi-lock-interactive-patterns
378 hi-lock-file-patterns)
379 (when hi-lock-interactive-patterns
380 (font-lock-remove-keywords nil hi-lock-interactive-patterns)
381 (setq hi-lock-interactive-patterns nil))
382 (when hi-lock-file-patterns
383 (font-lock-remove-keywords nil hi-lock-file-patterns)
384 (setq hi-lock-file-patterns nil))
385 (remove-overlays nil nil 'hi-lock-overlay t)
386 (when font-lock-fontified (font-lock-fontify-buffer)))
387 (define-key-after menu-bar-edit-menu [hi-lock] nil)
388 (remove-hook 'font-lock-mode-hook 'hi-lock-font-lock-hook t)))
389
390 ;;;###autoload
391 (define-globalized-minor-mode global-hi-lock-mode
392 hi-lock-mode turn-on-hi-lock-if-enabled
393 :group 'hi-lock)
394
395 (defun turn-on-hi-lock-if-enabled ()
396 (setq hi-lock-archaic-interface-message-used t)
397 (unless (memq major-mode hi-lock-exclude-modes)
398 (hi-lock-mode 1)))
399
400 ;;;###autoload
401 (defalias 'highlight-lines-matching-regexp 'hi-lock-line-face-buffer)
402 ;;;###autoload
403 (defun hi-lock-line-face-buffer (regexp &optional face)
404 "Set face of all lines containing a match of REGEXP to FACE.
405 Interactively, prompt for REGEXP then FACE, using a buffer-local
406 history list for REGEXP and a global history list for FACE.
407
408 If Font Lock mode is enabled in the buffer, it is used to
409 highlight REGEXP. If Font Lock mode is disabled, overlays are
410 used for highlighting; in this case, the highlighting will not be
411 updated as you type."
412 (interactive
413 (list
414 (hi-lock-regexp-okay
415 (read-regexp "Regexp to highlight line" (car regexp-history)))
416 (hi-lock-read-face-name)))
417 (or (facep face) (setq face 'hi-yellow))
418 (unless hi-lock-mode (hi-lock-mode 1))
419 (hi-lock-set-pattern
420 ;; The \\(?:...\\) grouping construct ensures that a leading ^, +, * or ?
421 ;; or a trailing $ in REGEXP will be interpreted correctly.
422 (concat "^.*\\(?:" regexp "\\).*$") face))
423
424
425 ;;;###autoload
426 (defalias 'highlight-regexp 'hi-lock-face-buffer)
427 ;;;###autoload
428 (defun hi-lock-face-buffer (regexp &optional face)
429 "Set face of each match of REGEXP to FACE.
430 Interactively, prompt for REGEXP then FACE, using a buffer-local
431 history list for REGEXP and a global history list for FACE.
432
433 If Font Lock mode is enabled in the buffer, it is used to
434 highlight REGEXP. If Font Lock mode is disabled, overlays are
435 used for highlighting; in this case, the highlighting will not be
436 updated as you type."
437 (interactive
438 (list
439 (hi-lock-regexp-okay
440 (read-regexp "Regexp to highlight" (car regexp-history)))
441 (hi-lock-read-face-name)))
442 (or (facep face) (setq face 'hi-yellow))
443 (unless hi-lock-mode (hi-lock-mode 1))
444 (hi-lock-set-pattern regexp face))
445
446 ;;;###autoload
447 (defalias 'highlight-phrase 'hi-lock-face-phrase-buffer)
448 ;;;###autoload
449 (defun hi-lock-face-phrase-buffer (regexp &optional face)
450 "Set face of each match of phrase REGEXP to FACE.
451 If called interactively, replaces whitespace in REGEXP with
452 arbitrary whitespace and makes initial lower-case letters case-insensitive.
453
454 If Font Lock mode is enabled in the buffer, it is used to
455 highlight REGEXP. If Font Lock mode is disabled, overlays are
456 used for highlighting; in this case, the highlighting will not be
457 updated as you type."
458 (interactive
459 (list
460 (hi-lock-regexp-okay
461 (hi-lock-process-phrase
462 (read-regexp "Phrase to highlight" (car regexp-history))))
463 (hi-lock-read-face-name)))
464 (or (facep face) (setq face 'hi-yellow))
465 (unless hi-lock-mode (hi-lock-mode 1))
466 (hi-lock-set-pattern regexp face))
467
468 (declare-function x-popup-menu "menu.c" (position menu))
469
470 (defun hi-lock--regexps-at-point ()
471 (let ((regexps '()))
472 ;; When using overlays, there is no ambiguity on the best
473 ;; choice of regexp.
474 (let ((regexp (get-char-property (point) 'hi-lock-overlay-regexp)))
475 (when regexp (push regexp regexps)))
476 ;; With font-locking on, check if the cursor is on an highlighted text.
477 ;; Checking for hi-lock face is a good heuristic.
478 (and (string-match "\\`hi-lock-" (face-name (face-at-point)))
479 (let* ((hi-text
480 (buffer-substring-no-properties
481 (previous-single-property-change (point) 'face)
482 (next-single-property-change (point) 'face))))
483 ;; Compute hi-lock patterns that match the
484 ;; highlighted text at point. Use this later in
485 ;; during completing-read.
486 (dolist (hi-lock-pattern hi-lock-interactive-patterns)
487 (let ((regexp (car hi-lock-pattern)))
488 (if (string-match regexp hi-text)
489 (push regexp regexps))))))))
490
491 (defvar-local hi-lock--last-face nil)
492
493 ;;;###autoload
494 (defalias 'unhighlight-regexp 'hi-lock-unface-buffer)
495 ;;;###autoload
496 (defun hi-lock-unface-buffer (regexp)
497 "Remove highlighting of each match to REGEXP set by hi-lock.
498 Interactively, prompt for REGEXP, accepting only regexps
499 previously inserted by hi-lock interactive functions.
500 If REGEXP is t (or if \\[universal-argument] was specified interactively),
501 then remove all hi-lock highlighting."
502 (interactive
503 (cond
504 (current-prefix-arg (list t))
505 ((and (display-popup-menus-p)
506 (listp last-nonmenu-event)
507 use-dialog-box)
508 (catch 'snafu
509 (or
510 (x-popup-menu
511 t
512 (cons
513 `keymap
514 (cons "Select Pattern to Unhighlight"
515 (mapcar (lambda (pattern)
516 (list (car pattern)
517 (format
518 "%s (%s)" (car pattern)
519 (cadr (cadr (cadr pattern))))
520 (cons nil nil)
521 (car pattern)))
522 hi-lock-interactive-patterns))))
523 ;; If the user clicks outside the menu, meaning that they
524 ;; change their mind, x-popup-menu returns nil, and
525 ;; interactive signals a wrong number of arguments error.
526 ;; To prevent that, we return an empty string, which will
527 ;; effectively disable the rest of the function.
528 (throw 'snafu '("")))))
529 (t
530 ;; Un-highlighting triggered via keyboard action.
531 (unless hi-lock-interactive-patterns
532 (error "No highlighting to remove"))
533 ;; Infer the regexp to un-highlight based on cursor position.
534 (let* ((defaults (hi-lock--regexps-at-point)))
535 (list
536 (completing-read (if (null defaults)
537 "Regexp to unhighlight: "
538 (format "Regexp to unhighlight (default %s): "
539 (car defaults)))
540 hi-lock-interactive-patterns
541 nil t nil nil defaults))))))
542 (dolist (keyword (if (eq regexp t) hi-lock-interactive-patterns
543 (list (assoc regexp hi-lock-interactive-patterns))))
544 (when keyword
545 (let ((face (cadr (cadr (cadr keyword)))))
546 ;; Make `face' the next one to use by default.
547 (setq hi-lock--last-face
548 (cadr (member (symbol-name face)
549 (reverse hi-lock-face-defaults)))))
550 (font-lock-remove-keywords nil (list keyword))
551 (setq hi-lock-interactive-patterns
552 (delq keyword hi-lock-interactive-patterns))
553 (remove-overlays
554 nil nil 'hi-lock-overlay-regexp (hi-lock--hashcons regexp))
555 (when font-lock-fontified (font-lock-fontify-buffer)))))
556
557 ;;;###autoload
558 (defun hi-lock-write-interactive-patterns ()
559 "Write interactively added patterns, if any, into buffer at point.
560
561 Interactively added patterns are those normally specified using
562 `highlight-regexp' and `highlight-lines-matching-regexp'; they can
563 be found in variable `hi-lock-interactive-patterns'."
564 (interactive)
565 (if (null hi-lock-interactive-patterns)
566 (error "There are no interactive patterns"))
567 (let ((beg (point)))
568 (mapc
569 (lambda (pattern)
570 (insert (format "%s: (%s)\n"
571 hi-lock-file-patterns-prefix
572 (prin1-to-string pattern))))
573 hi-lock-interactive-patterns)
574 (comment-region beg (point)))
575 (when (> (point) hi-lock-file-patterns-range)
576 (warn "Inserted keywords not close enough to top of file")))
577
578 ;; Implementation Functions
579
580 (defun hi-lock-process-phrase (phrase)
581 "Convert regexp PHRASE to a regexp that matches phrases.
582
583 Blanks in PHRASE replaced by regexp that matches arbitrary whitespace
584 and initial lower-case letters made case insensitive."
585 (let ((mod-phrase nil))
586 ;; FIXME fragile; better to just bind case-fold-search? (Bug#7161)
587 (setq mod-phrase
588 (replace-regexp-in-string
589 "\\(^\\|\\s-\\)\\([a-z]\\)"
590 (lambda (m) (format "%s[%s%s]"
591 (match-string 1 m)
592 (upcase (match-string 2 m))
593 (match-string 2 m))) phrase))
594 ;; FIXME fragile; better to use search-spaces-regexp?
595 (setq mod-phrase
596 (replace-regexp-in-string
597 "\\s-+" "[ \t\n]+" mod-phrase nil t))))
598
599 (defun hi-lock-regexp-okay (regexp)
600 "Return REGEXP if it appears suitable for a font-lock pattern.
601
602 Otherwise signal an error. A pattern that matches the null string is
603 not suitable."
604 (if (string-match regexp "")
605 (error "Regexp cannot match an empty string")
606 regexp))
607
608 (defun hi-lock-read-face-name ()
609 "Return face for interactive highlighting.
610 When `hi-lock-auto-select-face' is non-nil, just return the next face.
611 Otherwise, read face name from minibuffer with completion and history."
612 (let ((default (or (cadr (member hi-lock--last-face hi-lock-face-defaults))
613 (car hi-lock-face-defaults))))
614 (setq hi-lock--last-face
615 (if (and hi-lock-auto-select-face (not current-prefix-arg))
616 default
617 (completing-read
618 (format "Highlight using face (default %s): " default)
619 obarray 'facep t nil 'face-name-history
620 (append (member default hi-lock-face-defaults)
621 hi-lock-face-defaults))))
622 (unless (member hi-lock--last-face hi-lock-face-defaults)
623 (setq hi-lock-face-defaults
624 (append hi-lock-face-defaults (list hi-lock--last-face))))
625 (intern hi-lock--last-face)))
626
627 (defun hi-lock-set-pattern (regexp face)
628 "Highlight REGEXP with face FACE."
629 ;; Hashcons the regexp, so it can be passed to remove-overlays later.
630 (setq regexp (hi-lock--hashcons regexp))
631 (let ((pattern (list regexp (list 0 (list 'quote face) t))))
632 (unless (member pattern hi-lock-interactive-patterns)
633 (push pattern hi-lock-interactive-patterns)
634 (if font-lock-mode
635 (progn
636 (font-lock-add-keywords nil (list pattern) t)
637 (font-lock-fontify-buffer))
638 (let* ((range-min (- (point) (/ hi-lock-highlight-range 2)))
639 (range-max (+ (point) (/ hi-lock-highlight-range 2)))
640 (search-start
641 (max (point-min)
642 (- range-min (max 0 (- range-max (point-max))))))
643 (search-end
644 (min (point-max)
645 (+ range-max (max 0 (- (point-min) range-min))))))
646 (save-excursion
647 (goto-char search-start)
648 (while (re-search-forward regexp search-end t)
649 (let ((overlay (make-overlay (match-beginning 0) (match-end 0))))
650 (overlay-put overlay 'hi-lock-overlay t)
651 (overlay-put overlay 'hi-lock-overlay-regexp regexp)
652 (overlay-put overlay 'face face))
653 (goto-char (match-end 0)))))))))
654
655 (defun hi-lock-set-file-patterns (patterns)
656 "Replace file patterns list with PATTERNS and refontify."
657 (when (or hi-lock-file-patterns patterns)
658 (font-lock-remove-keywords nil hi-lock-file-patterns)
659 (setq hi-lock-file-patterns patterns)
660 (font-lock-add-keywords nil hi-lock-file-patterns t)
661 (font-lock-fontify-buffer)))
662
663 (defun hi-lock-find-patterns ()
664 "Find patterns in current buffer for hi-lock."
665 (interactive)
666 (unless (memq major-mode hi-lock-exclude-modes)
667 (let ((all-patterns nil)
668 (target-regexp (concat "\\<" hi-lock-file-patterns-prefix ":")))
669 (save-excursion
670 (save-restriction
671 (widen)
672 (goto-char (point-min))
673 (re-search-forward target-regexp
674 (+ (point) hi-lock-file-patterns-range) t)
675 (beginning-of-line)
676 (while (and (re-search-forward target-regexp (+ (point) 100) t)
677 (not (looking-at "\\s-*end")))
678 (condition-case nil
679 (setq all-patterns (append (read (current-buffer)) all-patterns))
680 (error (message "Invalid pattern list expression at %d"
681 (line-number-at-pos)))))))
682 (when (and all-patterns
683 hi-lock-mode
684 (cond
685 ((eq this-command 'hi-lock-find-patterns) t)
686 ((functionp hi-lock-file-patterns-policy)
687 (funcall hi-lock-file-patterns-policy all-patterns))
688 ((eq hi-lock-file-patterns-policy 'ask)
689 (y-or-n-p "Add patterns from this buffer to hi-lock? "))
690 (t nil)))
691 (hi-lock-set-file-patterns all-patterns)
692 (if (called-interactively-p 'interactive)
693 (message "Hi-lock added %d patterns." (length all-patterns)))))))
694
695 (defun hi-lock-font-lock-hook ()
696 "Add hi-lock patterns to font-lock's."
697 (when font-lock-fontified
698 (font-lock-add-keywords nil hi-lock-file-patterns t)
699 (font-lock-add-keywords nil hi-lock-interactive-patterns t)))
700
701 (defvar hi-lock--hashcons-hash
702 (make-hash-table :test 'equal :weakness t)
703 "Hash table used to hash cons regexps.")
704
705 (defun hi-lock--hashcons (string)
706 "Return unique object equal to STRING."
707 (or (gethash string hi-lock--hashcons-hash)
708 (puthash string string hi-lock--hashcons-hash)))
709
710 (defun hi-lock-unload-function ()
711 "Unload the Hi-Lock library."
712 (global-hi-lock-mode -1)
713 ;; continue standard unloading
714 nil)
715
716 (provide 'hi-lock)
717
718 ;;; hi-lock.el ends here