1 ;;; re-builder.el --- building Regexps with visual feedback
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: Detlev Zundel <dzu@gnu.org>
7 ;; Keywords: matching, lisp, tools
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; When I have to come up with regular expressions that are more
27 ;; complex than simple string matchers, especially if they contain sub
28 ;; expressions, I find myself spending quite some time in the
29 ;; `development cycle'. `re-builder' aims to shorten this time span
30 ;; so I can get on with the more interesting bits.
32 ;; With it you can have immediate visual feedback about how well the
33 ;; regexp behaves to your expectations on the intended data.
35 ;; When called up `re-builder' attaches itself to the current buffer
36 ;; which becomes its target buffer, where all the matching is done.
37 ;; The active window is split so you have a view on the data while
38 ;; authoring the RE. If the edited expression is valid the matches in
39 ;; the target buffer are marked automatically with colored overlays
40 ;; (for non-color displays see below) giving you feedback over the
41 ;; extents of the matched (sub) expressions. The (non-)validity is
42 ;; shown only in the modeline without throwing the errors at you. If
43 ;; you want to know the reason why RE Builder considers it as invalid
44 ;; call `reb-force-update' ("\C-c\C-u") which should reveal the error.
46 ;; The target buffer can be changed with `reb-change-target-buffer'
47 ;; ("\C-c\C-b"). Changing the target buffer automatically removes
48 ;; the overlays from the old buffer and displays the new one in the
51 ;; The `re-builder' keeps the focus while updating the matches in the
52 ;; target buffer so corrections are easy to incorporate. If you are
53 ;; satisfied with the result you can paste the RE to the kill-ring
54 ;; with `reb-copy' ("\C-c\C-w"), quit the `re-builder' ("\C-c\C-q")
55 ;; and use it wherever you need it.
57 ;; As the automatic updates can take some time on large buffers, they
58 ;; can be limited by `reb-auto-match-limit' so that they should not
59 ;; have a negative impact on the editing. Setting it to nil makes
60 ;; even the auto updates go all the way. Forcing an update overrides
61 ;; this limit allowing an easy way to see all matches.
63 ;; Currently `re-builder' understands five different forms of input,
64 ;; namely `read', `string', `rx', and `sregex' syntax. Read
65 ;; syntax and string syntax are both delimited by `"'s and behave
66 ;; according to their name. With the `string' syntax there's no need
67 ;; to escape the backslashes and double quotes simplifying the editing
68 ;; somewhat. The other three allow editing of symbolic regular
69 ;; expressions supported by the packages of the same name.
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 ;; On XEmacs, load the overlay compatibility library
108 (unless (fboundp 'make-overlay
)
111 ;; User customizable variables
112 (defgroup re-builder nil
113 "Options for the RE Builder."
117 (defcustom reb-blink-delay
0.5
118 "Seconds to blink cursor for next/previous match in RE Builder."
122 (defcustom reb-mode-hook nil
123 "Hooks to run on entering RE Builder mode."
127 (defcustom reb-re-syntax
'read
128 "Syntax for the REs in the RE Builder.
129 Can either be `read', `string', `sregex', or `rx'."
131 :type
'(choice (const :tag
"Read syntax" read
)
132 (const :tag
"String syntax" string
)
133 (const :tag
"`sregex' syntax" sregex
)
134 (const :tag
"`rx' syntax" rx
)))
136 (defcustom reb-auto-match-limit
200
137 "Positive integer limiting the matches for RE Builder auto updates.
138 Set it to nil if you don't want limits here."
140 :type
'(restricted-sexp :match-alternatives
145 '((((class color
) (background light
))
146 :background
"lightblue")
147 (((class color
) (background dark
))
148 :background
"steelblue4")
151 "Used for displaying the whole match."
155 '((((class color
) (background light
))
156 :background
"aquamarine")
157 (((class color
) (background dark
))
161 "Used for displaying the first matching subexpression."
165 '((((class color
) (background light
))
166 :background
"springgreen")
167 (((class color
) (background dark
))
168 :background
"chartreuse4")
171 "Used for displaying the second matching subexpression."
175 '((((min-colors 88) (class color
) (background light
))
176 :background
"yellow1")
177 (((class color
) (background light
))
178 :background
"yellow")
179 (((class color
) (background dark
))
180 :background
"sienna4")
183 "Used for displaying the third matching subexpression."
186 ;; Internal variables below
188 "Enables the RE Builder minor mode.")
190 (defvar reb-target-buffer nil
191 "Buffer to which the RE is applied to.")
193 (defvar reb-target-window nil
194 "Window to which the RE is applied to.")
196 (defvar reb-regexp nil
197 "Last regexp used by RE Builder.")
199 (defvar reb-regexp-src nil
200 "Last regexp used by RE Builder before processing it.
201 Except for Lisp syntax this is the same as `reb-regexp'.")
203 (defvar reb-overlays nil
204 "List of overlays of the RE Builder.")
206 (defvar reb-window-config nil
207 "Old window configuration.")
209 (defvar reb-subexp-mode nil
210 "Indicates whether sub-exp mode is active.")
212 (defvar reb-subexp-displayed nil
213 "Indicates which sub-exp is active.")
215 (defvar reb-mode-string
""
216 "String in mode line for additional info.")
218 (defvar reb-valid-string
""
219 "String in mode line showing validity of RE.")
221 (make-variable-buffer-local 'reb-overlays
)
222 (make-variable-buffer-local 'reb-regexp
)
223 (make-variable-buffer-local 'reb-regexp-src
)
225 (defconst reb-buffer
"*RE-Builder*"
226 "Buffer to use for the RE Builder.")
228 ;; Define the local "\C-c" keymap
230 (let ((map (make-sparse-keymap))
231 (menu-map (make-sparse-keymap)))
232 (define-key map
"\C-c\C-c" 'reb-toggle-case
)
233 (define-key map
"\C-c\C-q" 'reb-quit
)
234 (define-key map
"\C-c\C-w" 'reb-copy
)
235 (define-key map
"\C-c\C-s" 'reb-next-match
)
236 (define-key map
"\C-c\C-r" 'reb-prev-match
)
237 (define-key map
"\C-c\C-i" 'reb-change-syntax
)
238 (define-key map
"\C-c\C-e" 'reb-enter-subexp-mode
)
239 (define-key map
"\C-c\C-b" 'reb-change-target-buffer
)
240 (define-key map
"\C-c\C-u" 'reb-force-update
)
241 (define-key map
[menu-bar reb-mode
] (cons "Re-Builder" menu-map
))
242 (define-key menu-map
[rq]
243 '(menu-item "Quit" reb-quit
244 :help "Quit the RE Builder mode"))
245 (define-key menu-map [rt]
246 '(menu-item "Case sensitive" reb-toggle-case
247 :button (:toggle . case-fold-search)
248 :help "Toggle case sensitivity of searches for RE Builder target buffer"))
249 (define-key menu-map [rb]
250 '(menu-item "Change target buffer..." reb-change-target-buffer
251 :help "Change the target buffer and display it in the target window"))
252 (define-key menu-map [rs]
253 '(menu-item "Change syntax..." reb-change-syntax
254 :help "Change the syntax used by the RE Builder"))
255 (define-key menu-map [re]
256 '(menu-item "Enter subexpression mode" reb-enter-subexp-mode
257 :help "Enter the subexpression mode in the RE Builder"))
258 (define-key menu-map [ru]
259 '(menu-item "Force update" reb-force-update
260 :help "Force an update in the RE Builder target window without a match limit"))
261 (define-key menu-map [rn]
262 '(menu-item "Go to next match" reb-next-match
263 :help "Go to next match in the RE Builder target window"))
264 (define-key menu-map [rp]
265 '(menu-item "Go to previous match" reb-prev-match
266 :help "Go to previous match in the RE Builder target window"))
267 (define-key menu-map [rc]
268 '(menu-item "Copy current RE" reb-copy
269 :help "Copy current RE into the kill ring for later insertion"))
271 "Keymap used by the RE Builder.")
273 (define-derived-mode reb-mode nil "RE Builder"
274 "Major mode for interactively building Regular Expressions."
275 (set (make-local-variable 'blink-matching-paren) nil)
278 (define-derived-mode reb-lisp-mode
279 emacs-lisp-mode "RE Builder Lisp"
280 "Major mode for interactively building symbolic Regular Expressions."
281 ;; Pull in packages as needed
282 (cond ((eq reb-re-syntax 'sregex) ; sregex is not autoloaded
283 (require 'sregex)) ; right now..
284 ((eq reb-re-syntax 'rx) ; rx-to-string is autoloaded
285 (require 'rx))) ; require rx anyway
288 ;; Use the same "\C-c" keymap as `reb-mode' and use font-locking from
290 (define-key reb-lisp-mode-map "\C-c"
291 (lookup-key reb-mode-map "\C-c"))
293 (defvar reb-subexp-mode-map
294 (let ((m (make-keymap)))
296 ;; Again share the "\C-c" keymap for the commands
297 (define-key m "\C-c" (lookup-key reb-mode-map "\C-c"))
298 (define-key m "q" 'reb-quit-subexp-mode)
300 (define-key m (int-to-string digit) 'reb-display-subexp))
302 "Keymap used by the RE Builder for the subexpression mode.")
304 (defun reb-mode-common ()
305 "Setup functions common to functions `reb-mode' and `reb-mode-lisp'."
307 (setq reb-mode-string ""
309 mode-line-buffer-identification
310 '(25 . ("%b" reb-mode-string reb-valid-string)))
311 (reb-update-modestring)
312 (add-hook 'after-change-functions 'reb-auto-update nil t)
313 ;; At least make the overlays go away if the buffer is killed
314 (add-hook 'kill-buffer-hook 'reb-kill-buffer nil t)
315 (reb-auto-update nil nil nil))
317 (defun reb-color-display-p ()
318 "Return t if display is capable of displaying colors."
320 ;; emacs/xemacs compatibility
321 (if (fboundp 'frame-parameter)
322 (frame-parameter (selected-frame) 'display-type)
323 (if (fboundp 'frame-property)
324 (frame-property (selected-frame) 'display-type)))))
326 (defsubst reb-lisp-syntax-p ()
327 "Return non-nil if RE Builder uses a Lisp syntax."
328 (memq reb-re-syntax '(sregex rx)))
330 (defmacro reb-target-binding (symbol)
331 "Return binding for SYMBOL in the RE Builder target buffer."
332 `(with-current-buffer reb-target-buffer ,symbol))
334 (defun reb-initialize-buffer ()
335 "Initialize the current buffer as a RE Builder buffer."
338 (goto-char (+ 2 (point-min)))
339 (cond ((reb-lisp-syntax-p)
344 (defun reb-mode-buffer-p ()
345 "Return non-nil if the current buffer is a RE Builder buffer."
346 (memq major-mode '(reb-mode reb-lisp-mode)))
348 ;;; This is to help people find this in Apropos.
350 (defalias 'regexp-builder 're-builder)
354 "Construct a regexp interactively."
357 (if (and (string= (buffer-name) reb-buffer)
359 (message "Already in the RE Builder")
360 (when reb-target-buffer
361 (reb-delete-overlays))
362 (setq reb-target-buffer (current-buffer)
363 reb-target-window (selected-window))
364 (select-window (or (get-buffer-window reb-buffer)
366 (setq reb-window-config (current-window-configuration))
367 (split-window (selected-window) (- (window-height) 4)))))
368 (switch-to-buffer (get-buffer-create reb-buffer))
369 (reb-initialize-buffer)))
371 (defun reb-change-target-buffer (buf)
372 "Change the target buffer and display it in the target window."
373 (interactive "bSet target buffer to: ")
375 (let ((buffer (get-buffer buf)))
377 (error "No such buffer")
378 (reb-delete-overlays)
379 (setq reb-target-buffer buffer)
381 (if reb-subexp-mode reb-subexp-displayed nil))
382 (reb-update-modestring))))
384 (defun reb-force-update ()
385 "Force an update in the RE Builder target window without a match limit."
388 (let ((reb-auto-match-limit nil))
390 (if reb-subexp-mode reb-subexp-displayed nil))))
393 "Quit the RE Builder mode."
396 (setq reb-subexp-mode nil
397 reb-subexp-displayed nil)
398 (reb-delete-overlays)
400 (set-window-configuration reb-window-config))
402 (defun reb-next-match ()
403 "Go to next match in the RE Builder target window."
406 (reb-assert-buffer-in-window)
407 (with-selected-window reb-target-window
408 (if (not (re-search-forward reb-regexp (point-max) t))
409 (message "No more matches")
411 (or (and reb-subexp-mode reb-subexp-displayed) 0)
414 (defun reb-prev-match ()
415 "Go to previous match in the RE Builder target window."
418 (reb-assert-buffer-in-window)
419 (with-selected-window reb-target-window
422 (if (re-search-backward reb-regexp (point-min) t)
424 (or (and reb-subexp-mode reb-subexp-displayed) 0)
427 (message "No more matches")))))
429 (defun reb-toggle-case ()
430 "Toggle case sensitivity of searches for RE Builder target buffer."
433 (with-current-buffer reb-target-buffer
434 (setq case-fold-search (not case-fold-search)))
435 (reb-update-modestring)
436 (reb-auto-update nil nil nil t))
439 "Copy current RE into the kill ring for later insertion."
443 (let ((re (with-output-to-string
444 (print (reb-target-binding reb-regexp)))))
445 (kill-new (substring re 1 (1- (length re))))
446 (message "Regexp copied to kill-ring")))
448 ;; The subexpression mode is not electric because the number of
449 ;; matches should be seen rather than a prompt.
450 (defun reb-enter-subexp-mode ()
451 "Enter the subexpression mode in the RE Builder."
453 (setq reb-subexp-mode t)
454 (reb-update-modestring)
455 (use-local-map reb-subexp-mode-map)
456 (message "`0'-`9' to display subexpressions `q' to quit subexp mode"))
458 (defun reb-show-subexp (subexp &optional pause)
459 "Visually show limit of subexpression SUBEXP of recent search.
460 On color displays this just puts point to the end of the expression as
461 the match should already be marked by an overlay.
462 On other displays jump to the beginning and the end of it.
463 If the optional PAUSE is non-nil then pause at the end in any case."
464 (with-selected-window reb-target-window
465 (unless (reb-color-display-p)
466 (goto-char (match-beginning subexp))
467 (sit-for reb-blink-delay))
468 (goto-char (match-end subexp))
469 (when (or (not (reb-color-display-p)) pause)
470 (sit-for reb-blink-delay))))
472 (defun reb-quit-subexp-mode ()
473 "Quit the subexpression mode in the RE Builder."
475 (setq reb-subexp-mode nil
476 reb-subexp-displayed nil)
477 (reb-update-modestring)
478 (use-local-map reb-mode-map)
481 (defun reb-change-syntax (&optional syntax)
482 "Change the syntax used by the RE Builder.
483 Optional argument SYNTAX must be specified if called non-interactively."
486 (completing-read "Select syntax: "
487 (mapcar (lambda (el) (cons (symbol-name el) 1))
488 '(read string sregex rx))
489 nil t (symbol-name reb-re-syntax)))))
491 (if (memq syntax '(read string sregex rx))
492 (let ((buffer (get-buffer reb-buffer)))
493 (setq reb-re-syntax syntax)
495 (with-current-buffer buffer
496 (reb-initialize-buffer))))
497 (error "Invalid syntax: %s" syntax)))
500 ;; Non-interactive functions below
501 (defun reb-do-update (&optional subexp)
502 "Update matches in the RE Builder target window.
503 If SUBEXP is non-nil mark only the corresponding sub-expressions."
505 (reb-assert-buffer-in-window)
507 (reb-update-overlays subexp))
509 (defun reb-auto-update (beg end lenold &optional force)
510 "Called from `after-update-functions' to update the display.
511 BEG, END and LENOLD are passed in from the hook.
512 An actual update is only done if the regexp has changed or if the
513 optional fourth argument FORCE is non-nil."
514 (let ((prev-valid reb-valid-string)
518 (when (or (reb-update-regexp) force)
521 (error " *invalid*"))))
522 (setq reb-valid-string new-valid)
523 (force-mode-line-update)
525 ;; Through the caching of the re a change invalidating the syntax
526 ;; for symbolic expressions will not delete the overlays so we
528 (when (and (reb-lisp-syntax-p)
529 (not (string= prev-valid new-valid))
530 (string= prev-valid ""))
531 (reb-delete-overlays))))
533 (defun reb-delete-overlays ()
534 "Delete all RE Builder overlays in the `reb-target-buffer' buffer."
535 (when (buffer-live-p reb-target-buffer)
536 (with-current-buffer reb-target-buffer
537 (mapc 'delete-overlay reb-overlays)
538 (setq reb-overlays nil))))
540 (defun reb-assert-buffer-in-window ()
541 "Assert that `reb-target-buffer' is displayed in `reb-target-window'."
543 (if (not (eq reb-target-buffer (window-buffer reb-target-window)))
544 (set-window-buffer reb-target-window reb-target-buffer)))
546 (defun reb-update-modestring ()
547 "Update the variable `reb-mode-string' displayed in the mode line."
548 (setq reb-mode-string
551 (format " (subexp %s)" (or reb-subexp-displayed "-"))
553 (if (not (reb-target-binding case-fold-search))
556 (force-mode-line-update))
558 (defun reb-display-subexp (&optional subexp)
559 "Highlight only subexpression SUBEXP in the RE Builder."
562 (setq reb-subexp-displayed
563 (or subexp (string-to-number (format "%c" last-command-event))))
564 (reb-update-modestring)
565 (reb-do-update reb-subexp-displayed))
567 (defun reb-kill-buffer ()
568 "When the RE Builder buffer is killed make sure no overlays stay around."
570 (when (reb-mode-buffer-p)
571 (reb-delete-overlays)))
574 ;; The next functions are the interface between the regexp and
575 ;; its textual representation in the RE Builder buffer.
576 ;; They are the only functions concerned with the actual syntax
578 (defun reb-read-regexp ()
581 (cond ((eq reb-re-syntax 'read)
582 (goto-char (point-min))
583 (read (current-buffer)))
584 ((eq reb-re-syntax 'string)
585 (goto-char (point-min))
586 (re-search-forward "\"")
588 (goto-char (point-max))
589 (re-search-backward "\"")
590 (buffer-substring-no-properties beg (point))))
594 (defun reb-empty-regexp ()
595 "Return empty RE for current syntax."
596 (cond ((reb-lisp-syntax-p) "'()")
599 (defun reb-insert-regexp ()
602 (let ((re (or (reb-target-binding reb-regexp)
603 (reb-empty-regexp))))
604 (cond ((eq reb-re-syntax 'read)
605 (print re (current-buffer)))
606 ((eq reb-re-syntax 'string)
607 (insert "\n\"" re "\""))
608 ;; For the Lisp syntax we need the "source" of the regexp
610 (insert (or (reb-target-binding reb-regexp-src)
611 (reb-empty-regexp)))))))
613 (defun reb-cook-regexp (re)
614 "Return RE after processing it according to `reb-re-syntax'."
615 (cond ((eq reb-re-syntax 'sregex)
616 (apply 'sregex (eval (car (read-from-string re)))))
617 ((eq reb-re-syntax 'rx)
618 (rx-to-string (eval (car (read-from-string re)))))
621 (defun reb-update-regexp ()
622 "Update the regexp for the target buffer.
623 Return t if the (cooked) expression changed."
624 (let* ((re-src (reb-read-regexp))
625 (re (reb-cook-regexp re-src)))
626 (with-current-buffer reb-target-buffer
627 (let ((oldre reb-regexp))
629 (not (string= oldre re))
631 ;; Only update the source re for the lisp formats
632 (when (reb-lisp-syntax-p)
633 (setq reb-regexp-src re-src)))))))
636 ;; And now the real core of the whole thing
637 (defun reb-count-subexps (re)
638 "Return number of sub-expressions in the regexp RE."
641 (while (string-match "\\\\(" re beg)
646 (defun reb-update-overlays (&optional subexp)
647 "Switch to `reb-target-buffer' and mark all matches of `reb-regexp'.
648 If SUBEXP is non-nil mark only the corresponding sub-expressions."
649 (let* ((re (reb-target-binding reb-regexp))
650 (subexps (reb-count-subexps re))
654 (with-current-buffer reb-target-buffer
655 (reb-delete-overlays)
656 (goto-char (point-min))
657 (while (and (not (eobp))
658 (re-search-forward re (point-max) t)
659 (or (not reb-auto-match-limit)
660 (< matches reb-auto-match-limit)))
661 (when (and (= 0 (length (match-string 0)))
666 (setq matches (1+ matches))
667 (while (<= i subexps)
668 (when (and (or (not subexp) (= subexp i))
670 (let ((overlay (make-overlay (match-beginning i)
672 ;; When we have exceeded the number of provided faces,
673 ;; cycle thru them where `max-suffix' denotes the maximum
674 ;; suffix for `reb-match-*' that has been defined and
675 ;; `suffix' the suffix calculated for the current match.
679 (if (= suffix max-suffix)
681 (setq suffix (1+ suffix)))
682 (intern-soft (format "reb-match-%d" suffix)))
683 ((intern-soft (format "reb-match-%d" i)))
684 ((setq max-suffix (1- i))
686 ;; `reb-match-1' must exist.
688 (unless firstmatch (setq firstmatch (match-data)))
689 (setq reb-overlays (cons overlay reb-overlays)
690 submatches (1+ submatches))
691 (overlay-put overlay 'face face)
692 (overlay-put overlay 'priority i)))
694 (let ((count (if subexp submatches matches)))
695 (message "%s %smatch%s%s"
696 (if (= 0 count) "No" (int-to-string count))
697 (if subexp "subexpression " "")
698 (if (= 1 count) "" "es")
699 (if (and reb-auto-match-limit
700 (= reb-auto-match-limit count))
701 " (limit reached)" "")))
703 (store-match-data firstmatch)
704 (reb-show-subexp (or subexp 0)))))
707 (defun re-builder-unload-function ()
708 "Unload the RE Builder library."
709 (when (buffer-live-p (get-buffer reb-buffer))
710 (with-current-buffer reb-buffer
711 (remove-hook 'after-change-functions 'reb-auto-update t)
712 (remove-hook 'kill-buffer-hook 'reb-kill-buffer t)
713 (when (reb-mode-buffer-p)
714 (reb-delete-overlays)
715 (funcall (or (default-value 'major-mode) 'fundamental-mode)))))
716 ;; continue standard unloading
719 (provide 're-builder)
721 ;; arch-tag: 5c5515ac-4085-4524-a421-033f44f032e7
722 ;;; re-builder.el ends here