1 ;;; re-builder.el --- building Regexps with visual feedback
3 ;; Copyright (C) 1999, 2000, 2001 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 ;; When I have to come up with regular expressions that are more
28 ;; complex than simple string matchers, especially if they contain sub
29 ;; expressions, I find myself spending quite some time in the
30 ;; `development cycle'. `re-builder' aims to shorten this time span
31 ;; so I can get on with the more interesting bits.
33 ;; With it you can have immediate visual feedback about how well the
34 ;; regexp behaves to your expectations on the intended data.
36 ;; When called up `re-builder' attaches itself to the current buffer
37 ;; which becomes its target buffer, where all the matching is done.
38 ;; The active window is split so you have a view on the data while
39 ;; authoring the RE. If the edited expression is valid the matches in
40 ;; the target buffer are marked automatically with colored overlays
41 ;; (for non-color displays see below) giving you feedback over the
42 ;; extents of the matched (sub) expressions. The (non-)validity is
43 ;; shown only in the modeline without throwing the errors at you. If
44 ;; you want to know the reason why RE Builder considers it as invalid
45 ;; call `reb-force-update' ("\C-c\C-u") which should reveal the error.
47 ;; The target buffer can be changed with `reb-change-target-buffer'
48 ;; ("\C-c\C-b"). Changing the target buffer automatically removes
49 ;; the overlays from the old buffer and displays the new one in the
52 ;; The `re-builder' keeps the focus while updating the matches in the
53 ;; target buffer so corrections are easy to incorporate. If you are
54 ;; satisfied with the result you can paste the RE to the kill-ring
55 ;; with `reb-copy' ("\C-c\C-w"), quit the `re-builder' ("\C-c\C-q")
56 ;; and use it wherever you need it.
58 ;; As the automatic updates can take some time on large buffers, they
59 ;; can be limited by `reb-auto-match-limit' so that they should not
60 ;; have a negative impact on the editing. Setting it to nil makes
61 ;; even the auto updates go all the way. Forcing an update overrides
62 ;; this limit allowing an easy way to see all matches.
64 ;; Currently `re-builder' understands four different forms of input,
65 ;; namely `read', `string', `sregex' and `lisp-re' syntax. Read
66 ;; syntax and string syntax are both delimited by `"'s and behave
67 ;; according to their name. With the `string' syntax there's no need
68 ;; to escape the backslashes and double quotes simplifying the editing
69 ;; somewhat. The other two allow editing of symbolic regular
70 ;; expressions supported by the packages of the same name. (`lisp-re'
71 ;; is a package by me and its support may go away as it is nearly the
72 ;; same as the `sregex' package in Emacs)
74 ;; Editing symbolic expressions is done through a major mode derived
75 ;; from `emacs-lisp-mode' so you'll get all the good stuff like
76 ;; automatic indentation and font-locking etc.
78 ;; When editing a symbolic regular expression, only the first
79 ;; expression in the RE Builder buffer is considered, which helps
80 ;; limiting the extent of the expression like the `"'s do for the text
81 ;; modes. For the `sregex' syntax the function `sregex' is applied to
82 ;; the evaluated expression read. So you can use quoted arguments
83 ;; with something like '("findme") or you can construct arguments to
84 ;; your hearts delight with a valid ELisp expression. (The compiled
85 ;; string form will be copied by `reb-copy') If you want to take
86 ;; a glance at the corresponding string you can temporarily change the
89 ;; Changing the input syntax is transparent (for the obvious exception
90 ;; non-symbolic -> symbolic) so you can change your mind as often as
93 ;; There is also a shortcut function for toggling the
94 ;; `case-fold-search' variable in the target buffer with an immediate
98 ;; Q: But what if my display cannot show colored overlays?
99 ;; A: Then the cursor will flash around the matched text making it stand
102 ;; Q: But how can I then make out the sub-expressions?
103 ;; A: Thats where the `sub-expression mode' comes in. In it only the
104 ;; digit keys are assigned to perform an update that will flash the
105 ;; corresponding subexp only.
110 ;; On XEmacs, load the overlay compatibility library
111 (if (not (fboundp 'make-overlay
))
114 ;; User costomizable variables
115 (defgroup re-builder nil
116 "Options for the RE Builder."
120 (defcustom reb-blink-delay
0.5
121 "*Seconds to blink cursor for next/previous match in RE Builder."
125 (defcustom reb-mode-hook nil
126 "*Hooks to run on entering RE Builder mode."
130 (defcustom reb-re-syntax
'read
131 "*Syntax for the REs in the RE Builder.
132 Can either be `read', `string', `sregex' or `lisp-re'."
134 :type
'(choice (const :tag
"Read syntax" read
)
135 (const :tag
"String syntax" string
)
136 (const :tag
"`sregex' syntax" sregex
)
137 (const :tag
"`lisp-re' syntax" lisp-re
)
140 (defcustom reb-auto-match-limit
200
141 "*Positive integer limiting the matches for RE Builder auto updates.
142 Set it to nil if you don't want limits here."
144 :type
'(restricted-sexp :match-alternatives
149 '((((class color
) (background light
))
150 :background
"lightblue")
151 (((class color
) (background dark
))
152 :background
"steelblue4")
155 "Used for displaying the whole match."
159 '((((class color
) (background light
))
160 :background
"aquamarine")
161 (((class color
) (background dark
))
165 "Used for displaying the first matching subexpression."
169 '((((class color
) (background light
))
170 :background
"springgreen")
171 (((class color
) (background dark
))
172 :background
"chartreuse4")
175 "Used for displaying the second matching subexpression."
179 '((((class color
) (background light
))
180 :background
"yellow")
181 (((class color
) (background dark
))
182 :background
"sienna4")
185 "Used for displaying the third matching subexpression."
188 ;; Internal variables below
190 "Enables the RE Builder minor mode.")
192 (defvar reb-target-buffer nil
193 "Buffer to which the RE is applied to.")
195 (defvar reb-target-window nil
196 "Window to which the RE is applied to.")
198 (defvar reb-regexp nil
199 "Last regexp used by RE Builder.")
201 (defvar reb-regexp-src nil
202 "Last regexp used by RE Builder before processing it.
203 Except for Lisp syntax this is the same as `reb-regexp'.")
205 (defvar reb-overlays nil
206 "List of overlays of the RE Builder.")
208 (defvar reb-window-config nil
209 "Old window configuration.")
211 (defvar reb-subexp-mode nil
212 "Indicates whether sub-exp mode is active.")
214 (defvar reb-subexp-displayed nil
215 "Indicates which sub-exp is active.")
217 (defvar reb-mode-string
""
218 "String in mode line for additional info.")
220 (defvar reb-valid-string
""
221 "String in mode line showing validity of RE.")
223 (make-variable-buffer-local 'reb-overlays
)
224 (make-variable-buffer-local 'reb-regexp
)
225 (make-variable-buffer-local 'reb-regexp-src
)
227 (defconst reb-buffer
"*RE-Builder*"
228 "Buffer to use for the RE Builder.")
230 ;; Define the local "\C-c" keymap
231 (defvar reb-mode-map nil
232 "Keymap used by the RE Builder.")
234 (if (not reb-mode-map
)
236 (setq reb-mode-map
(make-sparse-keymap))
237 (define-key reb-mode-map
"\C-c\C-c" 'reb-toggle-case
)
238 (define-key reb-mode-map
"\C-c\C-q" 'reb-quit
)
239 (define-key reb-mode-map
"\C-c\C-w" 'reb-copy
)
240 (define-key reb-mode-map
"\C-c\C-s" 'reb-next-match
)
241 (define-key reb-mode-map
"\C-c\C-r" 'reb-prev-match
)
242 (define-key reb-mode-map
"\C-c\C-i" 'reb-change-syntax
)
243 (define-key reb-mode-map
"\C-c\C-e" 'reb-enter-subexp-mode
)
244 (define-key reb-mode-map
"\C-c\C-b" 'reb-change-target-buffer
)
245 (define-key reb-mode-map
"\C-c\C-u" 'reb-force-update
)))
248 "Major mode for interactively building Regular Expressions.
251 (kill-all-local-variables)
252 (setq major-mode
'reb-mode
253 mode-name
"RE Builder")
254 (use-local-map reb-mode-map
)
256 (run-hooks 'reb-mode-hook
))
258 (define-derived-mode reb-lisp-mode
259 emacs-lisp-mode
"RE Builder Lisp"
260 "Major mode for interactively building symbolic Regular Expressions."
261 (cond ((eq reb-re-syntax
'lisp-re
) ; Pull in packages
262 (require 'lisp-re
)) ; as needed
263 ((eq reb-re-syntax
'sregex
) ; sregex is not autoloaded
264 (require 'sregex
))) ; right now..
267 ;; Use the same "\C-c" keymap as `reb-mode' and use font-locking from
269 (define-key reb-lisp-mode-map
"\C-c"
270 (lookup-key reb-mode-map
"\C-c"))
272 (defvar reb-subexp-mode-map
273 (let ((m (make-keymap)))
275 ;; Again share the "\C-c" keymap for the commands
276 (define-key m
"\C-c" (lookup-key reb-mode-map
"\C-c"))
277 (define-key m
"q" 'reb-quit-subexp-mode
)
279 (define-key m
(int-to-string digit
) 'reb-display-subexp
))
281 "Keymap used by the RE Builder for the subexpression mode.")
283 (defun reb-mode-common ()
284 "Setup functions common to functions `reb-mode' and `reb-mode-lisp'."
286 (setq reb-mode-string
""
288 mode-line-buffer-identification
289 '(25 .
("%b" reb-mode-string reb-valid-string
)))
290 (reb-update-modestring)
291 (make-local-variable 'after-change-functions
)
292 (add-hook 'after-change-functions
294 ;; At least make the overlays go away if the buffer is killed
295 (make-local-variable 'reb-kill-buffer
)
296 (add-hook 'kill-buffer-hook
'reb-kill-buffer
)
297 (reb-auto-update nil nil nil
))
300 ;; Handy macro for doing things in other windows
301 (defmacro reb-with-current-window
(window &rest body
)
302 "With WINDOW selected evaluate BODY forms and reselect previous window."
304 (let ((oldwindow (make-symbol "*oldwindow*")))
305 `(let ((,oldwindow
(selected-window)))
306 (select-window ,window
)
310 (select-window ,oldwindow
)))))
311 (put 'reb-with-current-window
'lisp-indent-function
0)
313 (defun reb-color-display-p ()
314 "Return t if display is capable of displaying colors."
316 ;; emacs/xemacs compatibility
317 (if (fboundp 'frame-parameter
)
318 (frame-parameter (selected-frame) 'display-type
)
319 (frame-property (selected-frame) 'display-type
))))
321 (defsubst reb-lisp-syntax-p
()
322 "Return non-nil if RE Builder uses a Lisp syntax."
323 (memq reb-re-syntax
'(lisp-re sregex
)))
325 (defmacro reb-target-binding
(symbol)
326 "Return binding for SYMBOL in the RE Builder target buffer."
327 `(with-current-buffer reb-target-buffer
,symbol
))
332 "Call up the RE Builder for the current window."
335 (if (and (string= (buffer-name) reb-buffer
)
336 (memq major-mode
'(reb-mode reb-lisp-mode
)))
337 (message "Already in the RE Builder")
338 (if reb-target-buffer
339 (reb-delete-overlays))
340 (setq reb-target-buffer
(current-buffer)
341 reb-target-window
(selected-window)
342 reb-window-config
(current-window-configuration))
343 (select-window (split-window (selected-window) (- (window-height) 4)))
344 (switch-to-buffer (get-buffer-create reb-buffer
))
347 (goto-char (+ 2 (point-min)))
353 (defun reb-change-target-buffer (buf)
354 "Change the target buffer and display it in the target window."
355 (interactive "bSet target buffer to: ")
357 (let ((buffer (get-buffer buf
)))
359 (error "No such buffer")
360 (reb-delete-overlays)
361 (setq reb-target-buffer buffer
)
363 (if reb-subexp-mode reb-subexp-displayed nil
))
364 (reb-update-modestring))))
366 (defun reb-force-update ()
367 "Forces an update in the RE Builder target window without a match limit."
370 (let ((reb-auto-match-limit nil
))
372 (if reb-subexp-mode reb-subexp-displayed nil
))))
375 "Quit the RE Builder mode."
378 (setq reb-subexp-mode nil
379 reb-subexp-displayed nil
)
380 (reb-delete-overlays)
382 (set-window-configuration reb-window-config
))
384 (defun reb-next-match ()
385 "Go to next match in the RE Builder target window."
388 (reb-assert-buffer-in-window)
389 (reb-with-current-window
391 (if (not (re-search-forward reb-regexp
(point-max) t
))
392 (message "No more matches.")
394 (or (and reb-subexp-mode reb-subexp-displayed
) 0)
397 (defun reb-prev-match ()
398 "Go to previous match in the RE Builder target window."
401 (reb-assert-buffer-in-window)
402 (reb-with-current-window reb-target-window
403 (goto-char (1- (point)))
404 (if (not (re-search-backward reb-regexp
(point-min) t
))
405 (message "No more matches.")
407 (or (and reb-subexp-mode reb-subexp-displayed
) 0)
410 (defun reb-toggle-case ()
411 "Toggle case sensitivity of searches for RE Builder target buffer."
414 (with-current-buffer reb-target-buffer
415 (setq case-fold-search
(not case-fold-search
)))
416 (reb-update-modestring)
417 (reb-auto-update nil nil nil t
))
420 "Copy current RE into the kill ring for later insertion."
424 (let ((re (with-output-to-string
425 (print (reb-target-binding reb-regexp
)))))
426 (kill-new (substring re
1 (1- (length re
))))
427 (message "Regexp copied to kill-ring")))
429 ;; The subexpression mode is not electric because the number of
430 ;; matches should be seen rather than a prompt.
431 (defun reb-enter-subexp-mode ()
432 "Enter the subexpression mode in the RE Builder."
434 (setq reb-subexp-mode t
)
435 (reb-update-modestring)
436 (use-local-map reb-subexp-mode-map
)
437 (message "`0'-`9' to display subexpressions `q' to quit subexp mode."))
439 (defun reb-show-subexp (subexp &optional pause
)
440 "Visually show limit of subexpression SUBEXP of recent search.
441 On color displays this just puts point to the end of the expression as
442 the match should already be marked by an overlay.
443 On other displays jump to the beginning and the end of it.
444 If the optional PAUSE is non-nil then pause at the end in any case."
445 (reb-with-current-window reb-target-window
446 (if (not (reb-color-display-p))
447 (progn (goto-char (match-beginning subexp
))
448 (sit-for reb-blink-delay
)))
449 (goto-char (match-end subexp
))
450 (if (or (not (reb-color-display-p)) pause
)
451 (sit-for reb-blink-delay
))))
453 (defun reb-quit-subexp-mode ()
454 "Quit the subexpression mode in the RE Builder."
456 (setq reb-subexp-mode nil
457 reb-subexp-displayed nil
)
458 (reb-update-modestring)
459 (use-local-map reb-mode-map
)
462 (defun reb-change-syntax (&optional syntax
)
463 "Change the syntax used by the RE Builder.
464 Optional argument SYNTAX must be specified if called non-interactively."
467 (completing-read "Select syntax: "
468 (mapcar (lambda (el) (cons (symbol-name el
) 1))
469 '(read string lisp-re sregex
))
470 nil t
(symbol-name reb-re-syntax
)))))
472 (if (memq syntax
'(read string lisp-re sregex
))
473 (let ((buffer (get-buffer reb-buffer
)))
474 (setq reb-re-syntax syntax
)
476 (with-current-buffer buffer
479 (goto-char (+ 2 (point-min)))
480 (cond ((reb-lisp-syntax-p)
483 (error "Invalid syntax: %s" syntax
)))
486 ;; Non-interactive functions below
487 (defun reb-do-update (&optional subexp
)
488 "Update matches in the RE Builder target window.
489 If SUBEXP is non-nil mark only the corresponding sub-expressions."
491 (reb-assert-buffer-in-window)
493 (reb-update-overlays subexp
))
495 (defun reb-auto-update (beg end lenold
&optional force
)
496 "Called from `after-update-functions' to update the display.
497 BEG END and LENOLD are passed in from the hook.
498 An actual update is only done if the regexp has changed or if the
499 optional fourth argument FORCE is non-nil."
500 (let ((prev-valid reb-valid-string
)
504 (if (or (reb-update-regexp) force
)
506 (reb-assert-buffer-in-window)
509 (error " *invalid*"))))
510 (setq reb-valid-string new-valid
)
511 (force-mode-line-update)
513 ;; Through the caching of the re a change invalidating the syntax
514 ;; for symbolic expressions will not delete the overlays so we
516 (if (and (reb-lisp-syntax-p)
517 (not (string= prev-valid new-valid
))
518 (string= prev-valid
""))
519 (reb-delete-overlays))))
521 (defun reb-delete-overlays ()
522 "Delete all RE Builder overlays in the `reb-target-buffer' buffer."
523 (if (buffer-live-p reb-target-buffer
)
524 (with-current-buffer reb-target-buffer
525 (mapcar 'delete-overlay reb-overlays
)
526 (setq reb-overlays nil
))))
528 (defun reb-assert-buffer-in-window ()
529 "Assert that `reb-target-buffer' is displayed in `reb-target-window'."
531 (if (not (eq reb-target-buffer
(window-buffer reb-target-window
)))
532 (set-window-buffer reb-target-window reb-target-buffer
)))
534 (defun reb-update-modestring ()
535 "Update the variable `reb-mode-string' displayed in the mode line."
536 (setq reb-mode-string
539 (format " (subexp %s)" (or reb-subexp-displayed
"-"))
541 (if (not (reb-target-binding case-fold-search
))
544 (force-mode-line-update))
546 (defun reb-display-subexp (&optional subexp
)
547 "Highlight only subexpression SUBEXP in the RE Builder."
550 (setq reb-subexp-displayed
551 (or subexp
(string-to-int (format "%c" last-command-char
))))
552 (reb-update-modestring)
553 (reb-do-update reb-subexp-displayed
))
555 (defun reb-kill-buffer ()
556 "When the RE Builder buffer is killed make sure no overlays stay around."
558 (if (member major-mode
'(reb-mode reb-lisp-mode
))
559 (reb-delete-overlays)))
562 ;; The next functions are the interface between the regexp and
563 ;; its textual representation in the RE Builder buffer.
564 ;; They are the only functions concerned with the actual syntax
566 (defun reb-read-regexp ()
569 (cond ((eq reb-re-syntax
'read
)
570 (goto-char (point-min))
571 (read (current-buffer)))
572 ((eq reb-re-syntax
'string
)
573 (goto-char (point-min))
574 (re-search-forward "\"")
576 (goto-char (point-max))
577 (re-search-backward "\"")
578 (buffer-substring-no-properties beg
(point))))
582 (defun reb-empty-regexp ()
583 "Return empty RE for current syntax."
584 (cond ((reb-lisp-syntax-p) "'()")
587 (defun reb-insert-regexp ()
590 (let ((re (or (reb-target-binding reb-regexp
)
591 (reb-empty-regexp))))
592 (cond ((eq reb-re-syntax
'read
)
593 (print re
(current-buffer)))
594 ((eq reb-re-syntax
'string
)
595 (insert "\n\"" re
"\""))
596 ;; For the Lisp syntax we need the "source" of the regexp
598 (insert (or (reb-target-binding reb-regexp-src
)
599 (reb-empty-regexp)))))))
601 (defun reb-cook-regexp (re)
602 "Return RE after processing it according to `reb-re-syntax'."
603 (cond ((eq reb-re-syntax
'lisp-re
)
604 (lre-compile-string (eval (car (read-from-string re
)))))
605 ((eq reb-re-syntax
'sregex
)
606 (apply 'sregex
(eval (car (read-from-string re
)))))
609 (defun reb-update-regexp ()
610 "Update the regexp for the target buffer.
611 Return t if the (cooked) expression changed."
612 (let* ((re-src (reb-read-regexp))
613 (re (reb-cook-regexp re-src
)))
614 (with-current-buffer reb-target-buffer
615 (let ((oldre reb-regexp
))
617 (not (string= oldre re
))
619 ;; Only update the source re for the lisp formats
620 (if (reb-lisp-syntax-p)
621 (setq reb-regexp-src re-src
)))))))
624 ;; And now the real core of the whole thing
625 (defun reb-count-subexps (re)
626 "Return number of sub-expressions in the regexp RE."
629 (while (string-match "\\\\(" re beg
)
635 (defun reb-update-overlays (&optional subexp
)
636 "Switch to `reb-target-buffer' and mark all matches of `reb-regexp'.
637 If SUBEXP is non-nil mark only the corresponding sub-expressions."
639 (let* ((re (reb-target-binding reb-regexp
))
640 (subexps (reb-count-subexps re
))
645 (set-buffer reb-target-buffer
)
646 (reb-delete-overlays)
647 (goto-char (point-min))
648 (while (and (re-search-forward re
(point-max) t
)
649 (or (not reb-auto-match-limit
)
650 (< matches reb-auto-match-limit
)))
651 (if (= 0 (length (match-string 0)))
652 (error "Empty regular expression!"))
654 (setq matches
(1+ matches
))
655 (while (<= i subexps
)
656 (if (and (or (not subexp
) (= subexp i
))
658 (let ((overlay (make-overlay (match-beginning i
)
660 (face-name (format "reb-match-%d" i
)))
662 (setq firstmatch
(match-data)))
663 (setq reb-overlays
(cons overlay reb-overlays
)
664 submatches
(1+ submatches
))
667 (or (intern-soft face-name
)
668 (error "Too many subexpressions - face `%s' not defined"
670 (overlay-put overlay
'priority i
)))
672 (let ((count (if subexp submatches matches
)))
673 (message"%s %smatch(es)%s"
674 (if (= 0 count
) "No" (int-to-string count
))
675 (if subexp
"subexpression " "")
676 (if (and reb-auto-match-limit
677 (= reb-auto-match-limit count
))
678 " (limit reached)" "")))
680 (progn (store-match-data firstmatch
)
681 (reb-show-subexp (or subexp
0))))))
683 (provide 're-builder
)
685 ;;; re-builder.el ends here