1 ;;; re-builder.el --- Building Regexps with visual feedback
3 ;; Copyright (C) 1999, 2000 Free Software Foundation, Inc.
5 ;; Author: Detlev Zundel <dzu@gnu.org>
6 ;; Keywords: matching, lisp, tools
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
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.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; $Id: re-builder.el,v 1.1 2000/03/09 20:20:32 gerd Exp $
29 ;; When I have to come up with regular expressions that are more
30 ;; complex than simple string matchers, especially if they contain sub
31 ;; expressions, I find myself spending quite some time in the
32 ;; `development cycle'. `re-builder' aims to shorten this time span
33 ;; so I can get on with the more interesting bits.
35 ;; With it you can have immediate visual feedback about how well the
36 ;; regexp behaves to your expectations on the intended data.
38 ;; When called up `re-builder' attaches itself to the current buffer
39 ;; which becomes its target buffer, where all the matching is done.
40 ;; The active window is split so you have a view on the data while
41 ;; authoring the RE. If the edited expression is valid the matches in
42 ;; the target buffer are marked automatically with colored overlays
43 ;; (for non-color displays see below) giving you feedback over the
44 ;; extents of the matched (sub) expressions. The (non-)validity is
45 ;; shown only in the modeline without throwing the errors at you. If
46 ;; you want to know the reason why RE Builder considers it as invalid
47 ;; call `reb-force-update' ("\C-c\C-u") which should reveal the error.
49 ;; The `re-builder' keeps the focus while updating the matches in the
50 ;; target buffer so corrections are easy to incorporate. If you are
51 ;; satisfied with the result you can paste the RE to the kill-ring
52 ;; with `reb-copy' ("\C-c\C-w"), quit the `re-builder' ("\C-c\C-q")
53 ;; and use it wherever you need it.
55 ;; As the automatic updates can take some time on large buffers, they
56 ;; can be limited by `reb-auto-match-limit' so that they should not
57 ;; have a negative impact on the editing. Setting it to nil makes
58 ;; even the auto updates go all the way. Forcing an update overrides
59 ;; this limit allowing an easy way to see all matches.
61 ;; Currently `re-builder' understands four different forms of input,
62 ;; namely `read', `string', `sregex' and `lisp-re' syntax. Read
63 ;; syntax and string syntax are both delimited by `"'s and behave
64 ;; according to their name. With the `string' syntax there's no need
65 ;; to escape the backslashes and double quotes simplifying the editing
66 ;; somewhat. The other two allow editing of symbolic regular
67 ;; expressions supported by the packages of the same name. (`lisp-re'
68 ;; is a package by me and its support may go away as it is nearly the
69 ;; same as the `sregex' package in Emacs)
71 ;; Editing symbolic expressions is done through a major mode derived
72 ;; from `emacs-lisp-mode' so you'll get all the good stuff like
73 ;; automatic indentation and font-locking etc.
75 ;; When editing a symbolic regular expression, only the first
76 ;; expression in the RE Builder buffer is considered, which helps
77 ;; limiting the extent of the expression like the `"'s do for the text
78 ;; modes. For the `sregex' syntax the function `sregex' is applied to
79 ;; the evaluated expression read. So you can use quoted arguments
80 ;; with something like '("findme") or you can construct arguments to
81 ;; your hearts delight with a valid ELisp expression. (The compiled
82 ;; string form will be copied by `reb-copy') If you want to take
83 ;; a glance at the corresponding string you can temporarily change the
86 ;; Changing the input syntax is transparent (for the obvious exception
87 ;; non-symbolic -> symbolic) so you can change your mind as often as
90 ;; There is also a shortcut function for toggling the
91 ;; `case-fold-search' variable in the target buffer with an immediate
95 ;; Q: But what if my display cannot show colored overlays?
96 ;; A: Then the cursor will flash around the matched text making it stand
99 ;; Q: But how can I then make out the sub-expressions?
100 ;; A: Thats where the `sub-expression mode' comes in. In it only the
101 ;; digit keys are assigned to perform an update that will flash the
102 ;; corresponding subexp only.
107 ;; Changes from Version 1.2:
108 ;; - Fixed a bug preventing normal startup after killing the (previous)
110 ;; - Fixed XEmacs support
112 ;; Changes from Version 1.2:
113 ;; - Fixed a bug preventing normal startup after killing the (previous)
115 ;; - Fixed XEmacs support
117 ;; Changes from Version 1.1:
118 ;; - The editing is now done through two major-modes rather than
119 ;; having one minor-mode that behaves exactly like a major-mode
120 ;; - Automatic updates for valid re's simplify the user interface
121 ;; - Easy interface for changing the input syntax and case
122 ;; sensitivity of the target buffer
123 ;; - As nobody reported the bugs that were fixed you probably don't
124 ;; want to know about them...
128 ;; On XEmacs, load the overlay compatibility library
129 (if (not (fboundp 'make-overlay))
132 ;; User costomizable variables
133 (defgroup re-builder nil
134 "Options for the RE Builder."
138 (defcustom reb-blink-delay 0.5
139 "*Seconds to blink cursor for next/previous match in RE Builder."
143 (defcustom reb-mode-hook nil
144 "*Hooks to run on entering RE Builder mode."
148 (defcustom reb-re-syntax 'read
149 "*Syntax for the REs in the RE Builder.
150 Can either be `read', `string', `sregex' or `lisp-re'."
152 :type '(choice (const :tag "Read syntax" read)
153 (const :tag "String syntax" string)
154 (const :tag "`sregex' syntax" sregex)
155 (const :tag "`lisp-re' syntax" lisp-re)
158 (defcustom reb-auto-match-limit 200
159 "*Positive integer limiting the matches for RE Builder auto updates.
160 Set it to nil if you don't want limits here."
162 :type '(restricted-sexp :match-alternatives
168 (:background "lightblue"))
169 (t (:inverse-video t)))
170 "Used for displaying the whole match."
175 (:background "aquamarine"))
176 (t (:inverse-video t)))
177 "Used for displaying the first matching subexpression."
182 (:background "springgreen"))
183 (t (:inverse-video t)))
184 "Used for displaying the second matching subexpression."
189 (:background "yellow"))
190 (t (:inverse-video t)))
191 "Used for displaying the third matching subexpression."
194 ;; Internal variables below
196 "Enables the RE Builder minor mode.")
198 (defvar reb-target-buffer nil
199 "Buffer to which the RE is applied to.")
201 (defvar reb-target-window nil
202 "Window to which the RE is applied to.")
204 (defvar reb-regexp nil
205 "Last regexp used by RE Builder.")
207 (defvar reb-regexp-src nil
208 "Last regexp used by RE Builder before processing it.
209 Except for Lisp syntax this is the same as `reb-regexp'.")
211 (defvar reb-overlays nil
212 "List of overlays of the RE Builder.")
214 (defvar reb-window-config nil
215 "Old window configuration.")
217 (defvar reb-subexp-mode nil
218 "Indicates whether sub-exp mode is active.")
220 (defvar reb-subexp-displayed nil
221 "Indicates which sub-exp is active.")
223 (defvar reb-mode-string ""
224 "String in mode line for additional info.")
226 (defvar reb-valid-string ""
227 "String in mode line showing validity of RE.")
229 (make-variable-buffer-local 'reb-overlays)
230 (make-variable-buffer-local 'reb-regexp)
231 (make-variable-buffer-local 'reb-regexp-src)
233 (defconst reb-buffer "*RE-Builder*"
234 "Buffer to use for the RE Builder.")
236 ;; Define the local "\C-c" keymap
237 (defvar reb-mode-map nil
238 "Keymap used by the RE Builder.")
240 (if (not reb-mode-map)
242 (setq reb-mode-map (make-sparse-keymap))
243 (define-key reb-mode-map "\C-c\C-c" 'reb-toggle-case)
244 (define-key reb-mode-map "\C-c\C-q" 'reb-quit)
245 (define-key reb-mode-map "\C-c\C-w" 'reb-copy)
246 (define-key reb-mode-map "\C-c\C-s" 'reb-next-match)
247 (define-key reb-mode-map "\C-c\C-r" 'reb-prev-match)
248 (define-key reb-mode-map "\C-c\C-i" 'reb-change-syntax)
249 (define-key reb-mode-map "\C-c\C-e" 'reb-enter-subexp-mode)
250 (define-key reb-mode-map "\C-c\C-u" 'reb-force-update)))
253 "Major mode for interactively building Regular Expressions.
257 (setq major-mode 'reb-mode
258 mode-name "RE Builder")
259 (use-local-map reb-mode-map)
261 (run-hooks reb-mode-hook))
263 (define-derived-mode reb-lisp-mode
264 emacs-lisp-mode "RE Builder Lisp"
265 "Major mode for interactively building symbolic Regular Expressions.
266 \\{reb-lisp-mode-map}"
267 (cond ((eq reb-re-syntax 'lisp-re) ; Pull in packages
268 (require 'lisp-re)) ; as needed
269 ((eq reb-re-syntax 'sregex) ; sregex is not autoloaded
270 (require 'sregex))) ; right now..
273 ;; Use the same "\C-c" keymap as `reb-mode' and use font-locking from
275 (define-key reb-lisp-mode-map "\C-c"
276 (lookup-key reb-mode-map "\C-c"))
278 (if (boundp 'font-lock-defaults-alist)
279 (setq font-lock-defaults-alist
280 (cons (cons 'reb-lisp-mode
281 (cdr (assoc 'emacs-lisp-mode
282 font-lock-defaults-alist)))
283 font-lock-defaults-alist)))
285 (defvar reb-subexp-mode-map nil
286 "Keymap used by the RE Builder for the subexpression mode.")
288 (if (not reb-subexp-mode-map)
290 (setq reb-subexp-mode-map (make-sparse-keymap))
291 (suppress-keymap reb-subexp-mode-map)
292 ;; Again share the "\C-c" keymap for the commands
293 (define-key reb-subexp-mode-map "\C-c"
294 (lookup-key reb-mode-map "\C-c"))
295 (define-key reb-subexp-mode-map "q" 'reb-quit-subexp-mode)
296 (mapcar (lambda (digit)
297 (define-key reb-subexp-mode-map (int-to-string digit)
298 'reb-display-subexp))
299 '(0 1 2 3 4 5 6 7 8 9))))
301 (defun reb-mode-common ()
302 "Setup functions common to functions `reb-mode' and `reb-mode-lisp'."
304 (setq reb-mode-string ""
306 mode-line-buffer-identification
307 '(25 . ("%b" reb-mode-string reb-valid-string)))
308 (reb-update-modestring)
309 (make-local-variable 'after-change-functions)
310 (add-hook 'after-change-functions
312 ;; At least make the overlays go away if the buffer is killed
313 (make-local-variable 'reb-kill-buffer)
314 (add-hook 'kill-buffer-hook 'reb-kill-buffer)
315 (reb-auto-update nil nil nil))
318 ;; Handy macro for doing things in other windows
319 (defmacro reb-with-current-window (window &rest body)
320 "With WINDOW selected evaluate BODY forms and reselect previous window."
322 (let ((oldwindow (make-symbol "*oldwindow*")))
323 `(let ((,oldwindow (selected-window)))
324 (select-window ,window)
328 (select-window ,oldwindow)))))
329 (put 'reb-with-current-window 'lisp-indent-function 0)
331 (defun reb-color-display-p ()
332 "Return t if display is capable of displaying colors."
334 ;; emacs/xemacs compatibility
335 (if (fboundp 'frame-parameter)
336 (frame-parameter (selected-frame) 'display-type)
337 (frame-property (selected-frame) 'display-type))))
339 (defsubst reb-lisp-syntax-p ()
340 "Return non-nil if RE Builder uses a Lisp syntax."
341 (memq reb-re-syntax '(lisp-re sregex)))
343 (defmacro reb-target-binding (symbol)
344 "Return binding for SYMBOL in the RE Builder target buffer."
345 `(with-current-buffer reb-target-buffer ,symbol))
350 "Call up the RE Builder for the current window."
353 (if reb-target-buffer
354 (reb-delete-overlays))
355 (setq reb-target-buffer (current-buffer)
356 reb-target-window (selected-window)
357 reb-window-config (current-window-configuration))
358 (select-window (split-window (selected-window) (- (window-height) 4)))
359 (switch-to-buffer (get-buffer-create reb-buffer))
362 (goto-char (+ 2 (point-min)))
369 (defun reb-force-update ()
370 "Forces an update in the RE Builder target window without a match limit."
373 (let ((reb-auto-match-limit nil))
375 (if reb-subexp-mode reb-subexp-displayed nil))))
378 "Quit the RE Builder mode."
381 (setq reb-subexp-mode nil
382 reb-subexp-displayed nil)
383 (reb-delete-overlays)
385 (set-window-configuration reb-window-config))
387 (defun reb-next-match ()
388 "Go to next match in the RE Builder target window."
391 (reb-assert-buffer-in-window)
392 (reb-with-current-window
394 (if (not (re-search-forward reb-regexp (point-max) t))
395 (message "No more matches.")
397 (or (and reb-subexp-mode reb-subexp-displayed) 0)
400 (defun reb-prev-match ()
401 "Go to previous match in the RE Builder target window."
404 (reb-assert-buffer-in-window)
405 (reb-with-current-window reb-target-window
406 (goto-char (1- (point)))
407 (if (not (re-search-backward reb-regexp (point-min) t))
408 (message "No more matches.")
410 (or (and reb-subexp-mode reb-subexp-displayed) 0)
413 (defun reb-toggle-case ()
414 "Toggle case sensitivity of searches for RE Builder target buffer."
417 (with-current-buffer reb-target-buffer
418 (setq case-fold-search (not case-fold-search)))
419 (reb-update-modestring)
420 (reb-auto-update nil nil nil t))
423 "Copy current RE into the kill ring for later insertion."
427 (let ((re (with-output-to-string
428 (print (reb-target-binding reb-regexp)))))
429 (kill-new (substring re 1 (1- (length re))))
430 (message "Regexp copied to kill-ring")))
432 ;; The subexpression mode is not electric because the number of
433 ;; matches should be seen rather than a prompt.
434 (defun reb-enter-subexp-mode ()
435 "Enter the subexpression mode in the RE Builder."
438 (setq reb-subexp-mode t)
439 (reb-update-modestring)
440 (use-local-map reb-subexp-mode-map)
441 (message "`0'-`9' to display subexpressions `q' to quit subexp mode."))
443 (defun reb-show-subexp (subexp &optional pause)
444 "Visually show limit of subexpression SUBEXP of recent search.
445 On color displays this just puts point to the end of the expression as
446 the match should already be marked by an overlay.
447 On other displays jump to the beginning and the end of it.
448 If the optional PAUSE is non-nil then pause at the end in any case."
449 (reb-with-current-window reb-target-window
450 (if (not (reb-color-display-p))
451 (progn (goto-char (match-beginning subexp))
452 (sit-for reb-blink-delay)))
453 (goto-char (match-end subexp))
454 (if (or (not (reb-color-display-p)) pause)
455 (sit-for reb-blink-delay))))
457 (defun reb-quit-subexp-mode ()
458 "Quit the subexpression mode in the RE Builder."
461 (setq reb-subexp-mode nil
462 reb-subexp-displayed nil)
463 (reb-update-modestring)
464 (use-local-map reb-mode-map)
467 (defun reb-change-syntax (&optional syntax)
468 "Change the syntax used by the RE Builder.
469 Optional argument SYNTAX must be specified if called non-interactively."
472 (completing-read "Select syntax: "
473 (mapcar (lambda (el) (cons (symbol-name el) 1))
474 '(read string lisp-re sregex))
475 nil t (symbol-name reb-re-syntax)))))
477 (if (memq syntax '(read string lisp-re sregex))
478 (let ((buffer (get-buffer reb-buffer)))
479 (setq reb-re-syntax syntax)
481 (with-current-buffer buffer
484 (goto-char (+ 2 (point-min)))
485 (cond ((reb-lisp-syntax-p)
488 (error "Invalid syntax: %s" syntax)))
491 ;; Non-interactive functions below
492 (defun reb-do-update (&optional subexp)
493 "Update matches in the RE Builder target window.
494 If SUBEXP is non-nil mark only the corresponding sub-expressions."
496 (reb-assert-buffer-in-window)
498 (reb-update-overlays subexp))
500 (defun reb-auto-update (beg end lenold &optional force)
501 "Called from `after-update-functions' to update the display.
502 BEG END and LENOLD are passed in from the hook.
503 An actual update is only done if the regexp has changed or if the
504 optional fourth argument FORCE is non-nil."
505 (let ((prev-valid reb-valid-string)
509 (if (or (reb-update-regexp) force)
511 (reb-assert-buffer-in-window)
514 (error " *invalid*"))))
515 (setq reb-valid-string new-valid)
516 (force-mode-line-update)
518 ;; Through the caching of the re a change invalidating the syntax
519 ;; for symbolic expressions will not delete the overlays so we
521 (if (and (reb-lisp-syntax-p)
522 (not (string= prev-valid new-valid))
523 (string= prev-valid ""))
524 (reb-delete-overlays))))
526 (defun reb-delete-overlays ()
527 "Delete all RE Builder overlays in the `reb-target-buffer' buffer."
528 (if (buffer-live-p reb-target-buffer)
529 (with-current-buffer reb-target-buffer
530 (mapcar 'delete-overlay reb-overlays)
531 (setq reb-overlays nil))))
533 (defun reb-assert-buffer-in-window ()
534 "Assert that `reb-target-buffer' is displayed in `reb-target-window'."
536 (if (not (eq reb-target-buffer (window-buffer reb-target-window)))
537 (set-window-buffer reb-target-window reb-target-buffer)))
539 (defun reb-update-modestring ()
540 "Update the variable `reb-mode-string' displayed in the mode line."
541 (setq reb-mode-string
544 (concat " (subexp " (or reb-subexp-displayed "-") ")")
546 (if (not (reb-target-binding case-fold-search))
549 (force-mode-line-update))
551 (defun reb-display-subexp (&optional subexp)
552 "Highlight only subexpression SUBEXP in the RE Builder."
555 (setq reb-subexp-displayed
556 (or subexp (string-to-int (format "%c" last-command-char))))
557 (reb-update-modestring)
558 (reb-do-update reb-subexp-displayed))
560 (defun reb-kill-buffer ()
561 "When the RE Builder buffer is killed make sure no overlays stay around."
563 (if (member major-mode '(reb-mode reb-lisp-mode))
564 (reb-delete-overlays)))
567 ;; The next functions are the interface between the regexp and
568 ;; its textual representation in the RE Builder buffer.
569 ;; They are the only functions concerned with the actual syntax
571 (defun reb-read-regexp ()
574 (cond ((eq reb-re-syntax 'read)
575 (goto-char (point-min))
576 (read (current-buffer)))
577 ((eq reb-re-syntax 'string)
578 (goto-char (point-min))
579 (re-search-forward "\"")
581 (goto-char (point-max))
582 (re-search-backward "\"")
583 (buffer-substring-no-properties beg (point))))
587 (defun reb-empty-regexp ()
588 "Return empty RE for current syntax."
589 (cond ((reb-lisp-syntax-p) "'()")
592 (defun reb-insert-regexp ()
595 (let ((re (or (reb-target-binding reb-regexp)
596 (reb-empty-regexp))))
597 (cond ((eq reb-re-syntax 'read)
598 (print re (current-buffer)))
599 ((eq reb-re-syntax 'string)
600 (insert "\n\"" re "\""))
601 ;; For the Lisp syntax we need the "source" of the regexp
603 (insert (or (reb-target-binding reb-regexp-src)
604 (reb-empty-regexp)))))))
606 (defun reb-cook-regexp (re)
607 "Return RE after processing it according to `reb-re-syntax'."
608 (cond ((eq reb-re-syntax 'lisp-re)
609 (lre-compile-string (eval (car (read-from-string re)))))
610 ((eq reb-re-syntax 'sregex)
611 (apply 'sregex (eval (car (read-from-string re)))))
614 (defun reb-update-regexp ()
615 "Update the regexp for the target buffer.
616 Return t if the (cooked) expression changed."
617 (let* ((re-src (reb-read-regexp))
618 (re (reb-cook-regexp re-src)))
619 (with-current-buffer reb-target-buffer
620 (let ((oldre reb-regexp))
622 (not (string= oldre re))
624 ;; Only update the source re for the lisp formats
625 (if (reb-lisp-syntax-p)
626 (setq reb-regexp-src re-src)))))))
629 ;; And now the real core of the whole thing
630 (defun reb-count-subexps (re)
631 "Return number of sub-expressions in the regexp RE."
634 (while (string-match "\\\\(" re beg)
640 (defun reb-update-overlays (&optional subexp)
641 "Switch to `reb-target-buffer' and mark all matches of `reb-regexp'.
642 If SUBEXP is non-nil mark only the corresponding sub-expressions."
644 (let* ((re (reb-target-binding reb-regexp))
645 (subexps (reb-count-subexps re))
650 (set-buffer reb-target-buffer)
651 (reb-delete-overlays)
652 (goto-char (point-min))
653 (while (and (re-search-forward re (point-max) t)
654 (or (not reb-auto-match-limit)
655 (< matches reb-auto-match-limit)))
656 (if (= 0 (length (match-string 0)))
657 (error "Empty regular expression!"))
659 (setq matches (1+ matches))
660 (while (<= i subexps)
661 (if (and (or (not subexp) (= subexp i))
663 (let ((overlay (make-overlay (match-beginning i)
665 (face-name (format "reb-match-%d" i)))
667 (setq firstmatch (match-data)))
668 (setq reb-overlays (cons overlay reb-overlays)
669 submatches (1+ submatches))
672 (or (intern-soft face-name)
673 (error "Too many subexpressions - face `%s' not defined"
675 (overlay-put overlay 'priority i)))
677 (let ((count (if subexp submatches matches)))
678 (message"%s %smatch(es)%s"
679 (if (= 0 count) "No" (int-to-string count))
680 (if subexp "subexpression " "")
681 (if (and reb-auto-match-limit
682 (= reb-auto-match-limit count))
683 " (limit reached)" "")))
685 (progn (store-match-data firstmatch)
686 (reb-show-subexp (or subexp 0))))))
688 ;;; re-builder.el ends here