1 ;;; re-builder.el --- building Regexps with visual feedback -*- lexical-binding: t -*-
3 ;; Copyright (C) 1999-2013 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 3 of the License, or
13 ;; (at your option) any later version.
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. If not, see <http://www.gnu.org/licenses/>.
25 ;; When I have to come up with regular expressions that are more
26 ;; complex than simple string matchers, especially if they contain sub
27 ;; expressions, I find myself spending quite some time in the
28 ;; `development cycle'. `re-builder' aims to shorten this time span
29 ;; so I can get on with the more interesting bits.
31 ;; With it you can have immediate visual feedback about how well the
32 ;; regexp behaves to your expectations on the intended data.
34 ;; When called up `re-builder' attaches itself to the current buffer
35 ;; which becomes its target buffer, where all the matching is done.
36 ;; The active window is split so you have a view on the data while
37 ;; authoring the RE. If the edited expression is valid the matches in
38 ;; the target buffer are marked automatically with colored overlays
39 ;; (for non-color displays see below) giving you feedback over the
40 ;; extents of the matched (sub) expressions. The (non-)validity is
41 ;; shown only in the mode line without throwing the errors at you. If
42 ;; you want to know the reason why RE Builder considers it as invalid
43 ;; call `reb-force-update' ("\C-c\C-u") which should reveal the error.
45 ;; The target buffer can be changed with `reb-change-target-buffer'
46 ;; ("\C-c\C-b"). Changing the target buffer automatically removes
47 ;; the overlays from the old buffer and displays the new one in the
50 ;; The `re-builder' keeps the focus while updating the matches in the
51 ;; target buffer so corrections are easy to incorporate. If you are
52 ;; satisfied with the result you can paste the RE to the kill-ring
53 ;; with `reb-copy' ("\C-c\C-w"), quit the `re-builder' ("\C-c\C-q")
54 ;; and use it wherever you need it.
56 ;; As the automatic updates can take some time on large buffers, they
57 ;; can be limited by `reb-auto-match-limit' so that they should not
58 ;; have a negative impact on the editing. Setting it to nil makes
59 ;; even the auto updates go all the way. Forcing an update overrides
60 ;; this limit allowing an easy way to see all matches.
62 ;; Currently `re-builder' understands three different forms of input,
63 ;; namely `read', `string', and `rx' syntax. Read
64 ;; syntax and string syntax are both delimited by `"'s and behave
65 ;; according to their name. With the `string' syntax there's no need
66 ;; to escape the backslashes and double quotes simplifying the editing
67 ;; somewhat. The other three allow editing of symbolic regular
68 ;; expressions supported by the packages of the same name.
70 ;; Editing symbolic expressions is done through a major mode derived
71 ;; from `emacs-lisp-mode' so you'll get all the good stuff like
72 ;; automatic indentation and font-locking etc.
74 ;; When editing a symbolic regular expression, only the first
75 ;; expression in the RE Builder buffer is considered, which helps
76 ;; limiting the extent of the expression like the `"'s do for the text
77 ;; modes. For the `rx' syntax the function `rx-to-string' is applied to
78 ;; the evaluated expression read. So you can use quoted arguments
79 ;; with something like '("findme") or you can construct arguments to
80 ;; your hearts delight with a valid ELisp expression. (The compiled
81 ;; string form will be copied by `reb-copy') If you want to take
82 ;; a glance at the corresponding string you can temporarily change the
85 ;; Changing the input syntax is transparent (for the obvious exception
86 ;; non-symbolic -> symbolic) so you can change your mind as often as
89 ;; There is also a shortcut function for toggling the
90 ;; `case-fold-search' variable in the target buffer with an immediate
94 ;; Q: But what if my display cannot show colored overlays?
95 ;; A: Then the cursor will flash around the matched text making it stand
98 ;; Q: But how can I then make out the sub-expressions?
99 ;; A: Thats where the `sub-expression mode' comes in. In it only the
100 ;; digit keys are assigned to perform an update that will flash the
101 ;; corresponding subexp only.
106 ;; On XEmacs, load the overlay compatibility library
107 (unless (fboundp 'make-overlay
)
110 ;; User customizable variables
111 (defgroup re-builder nil
112 "Options for the RE Builder."
116 (defcustom reb-blink-delay
0.5
117 "Seconds to blink cursor for next/previous match in RE Builder."
121 (defcustom reb-mode-hook nil
122 "Hooks to run on entering RE Builder mode."
126 (defcustom reb-re-syntax
'read
127 "Syntax for the REs in the RE Builder.
128 Can either be `read', `string', or `rx'."
130 :type
'(choice (const :tag
"Read syntax" read
)
131 (const :tag
"String syntax" string
)
132 (const :tag
"`rx' syntax" rx
)))
134 (defcustom reb-auto-match-limit
200
135 "Positive integer limiting the matches for RE Builder auto updates.
136 Set it to nil if you don't want limits here."
138 :type
'(restricted-sexp :match-alternatives
143 '((((class color
) (background light
))
144 :background
"lightblue")
145 (((class color
) (background dark
))
146 :background
"steelblue4")
149 "Used for displaying the whole match."
153 '((((class color
) (background light
))
154 :background
"aquamarine")
155 (((class color
) (background dark
))
159 "Used for displaying the first matching subexpression."
163 '((((class color
) (background light
))
164 :background
"springgreen")
165 (((class color
) (background dark
))
166 :background
"chartreuse4")
169 "Used for displaying the second matching subexpression."
173 '((((min-colors 88) (class color
) (background light
))
174 :background
"yellow1")
175 (((class color
) (background light
))
176 :background
"yellow")
177 (((class color
) (background dark
))
178 :background
"sienna4")
181 "Used for displaying the third matching subexpression."
184 ;; Internal variables below
186 "Enables the RE Builder minor mode.")
188 (defvar reb-target-buffer nil
189 "Buffer to which the RE is applied to.")
191 (defvar reb-target-window nil
192 "Window to which the RE is applied to.")
194 (defvar reb-regexp nil
195 "Last regexp used by RE Builder.")
197 (defvar reb-regexp-src nil
198 "Last regexp used by RE Builder before processing it.
199 Except for Lisp syntax this is the same as `reb-regexp'.")
201 (defvar reb-overlays nil
202 "List of overlays of the RE Builder.")
204 (defvar reb-window-config nil
205 "Old window configuration.")
207 (defvar reb-subexp-mode nil
208 "Indicates whether sub-exp mode is active.")
210 (defvar reb-subexp-displayed nil
211 "Indicates which sub-exp is active.")
213 (defvar reb-mode-string
""
214 "String in mode line for additional info.")
216 (defvar reb-valid-string
""
217 "String in mode line showing validity of RE.")
219 (make-variable-buffer-local 'reb-overlays
)
220 (make-variable-buffer-local 'reb-regexp
)
221 (make-variable-buffer-local 'reb-regexp-src
)
223 (defconst reb-buffer
"*RE-Builder*"
224 "Buffer to use for the RE Builder.")
226 ;; Define the local "\C-c" keymap
228 (let ((map (make-sparse-keymap))
229 (menu-map (make-sparse-keymap)))
230 (define-key map
"\C-c\C-c" 'reb-toggle-case
)
231 (define-key map
"\C-c\C-q" 'reb-quit
)
232 (define-key map
"\C-c\C-w" 'reb-copy
)
233 (define-key map
"\C-c\C-s" 'reb-next-match
)
234 (define-key map
"\C-c\C-r" 'reb-prev-match
)
235 (define-key map
"\C-c\C-i" 'reb-change-syntax
)
236 (define-key map
"\C-c\C-e" 'reb-enter-subexp-mode
)
237 (define-key map
"\C-c\C-b" 'reb-change-target-buffer
)
238 (define-key map
"\C-c\C-u" 'reb-force-update
)
239 (define-key map
[menu-bar reb-mode
] (cons "Re-Builder" menu-map
))
240 (define-key menu-map
[rq]
241 '(menu-item "Quit" reb-quit
242 :help "Quit the RE Builder mode"))
243 (define-key menu-map [rt]
244 '(menu-item "Case sensitive" reb-toggle-case
245 :button (:toggle . (with-current-buffer
247 (null 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 (defvar reb-lisp-mode-map
279 (let ((map (make-sparse-keymap)))
280 ;; Use the same "\C-c" keymap as `reb-mode' and use font-locking from
282 (define-key map "\C-c" (lookup-key reb-mode-map "\C-c"))
285 (define-derived-mode reb-lisp-mode
286 emacs-lisp-mode "RE Builder Lisp"
287 "Major mode for interactively building symbolic Regular Expressions."
288 ;; Pull in packages as needed
289 (cond ((memq reb-re-syntax '(sregex rx)) ; rx-to-string is autoloaded
290 (require 'rx))) ; require rx anyway
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 nil '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.
355 This command makes the current buffer the \"target\" buffer of
356 the regexp builder. It displays a buffer named \"*RE-Builder*\"
357 in another window, initially containing an empty regexp.
359 As you edit the regexp in the \"*RE-Builder*\" buffer, the
360 matching parts of the target buffer will be highlighted."
362 (if (and (string= (buffer-name) reb-buffer)
364 (message "Already in the RE Builder")
365 (when reb-target-buffer
366 (reb-delete-overlays))
367 (setq reb-target-buffer (current-buffer)
368 reb-target-window (selected-window))
369 (select-window (or (get-buffer-window reb-buffer)
371 (setq reb-window-config (current-window-configuration))
372 (split-window (selected-window) (- (window-height) 4)))))
373 (switch-to-buffer (get-buffer-create reb-buffer))
374 (reb-initialize-buffer)))
376 (defun reb-change-target-buffer (buf)
377 "Change the target buffer and display it in the target window."
378 (interactive "bSet target buffer to: ")
380 (let ((buffer (get-buffer buf)))
382 (error "No such buffer")
383 (reb-delete-overlays)
384 (setq reb-target-buffer buffer)
386 (if reb-subexp-mode reb-subexp-displayed nil))
387 (reb-update-modestring))))
389 (defun reb-force-update ()
390 "Force an update in the RE Builder target window without a match limit."
393 (let ((reb-auto-match-limit nil))
395 (if reb-subexp-mode reb-subexp-displayed nil))))
398 "Quit the RE Builder mode."
401 (setq reb-subexp-mode nil
402 reb-subexp-displayed nil)
403 (reb-delete-overlays)
405 (set-window-configuration reb-window-config))
407 (defun reb-next-match ()
408 "Go to next match in the RE Builder target window."
411 (reb-assert-buffer-in-window)
412 (with-selected-window reb-target-window
413 (if (not (re-search-forward reb-regexp (point-max) t))
414 (message "No more matches")
416 (or (and reb-subexp-mode reb-subexp-displayed) 0)
419 (defun reb-prev-match ()
420 "Go to previous match in the RE Builder target window."
423 (reb-assert-buffer-in-window)
424 (with-selected-window reb-target-window
427 (if (re-search-backward reb-regexp (point-min) t)
429 (or (and reb-subexp-mode reb-subexp-displayed) 0)
432 (message "No more matches")))))
434 (defun reb-toggle-case ()
435 "Toggle case sensitivity of searches for RE Builder target buffer."
438 (with-current-buffer reb-target-buffer
439 (setq case-fold-search (not case-fold-search)))
440 (reb-update-modestring)
441 (reb-auto-update nil nil nil t))
444 "Copy current RE into the kill ring for later insertion."
448 (let ((re (with-output-to-string
449 (print (reb-target-binding reb-regexp)))))
450 (kill-new (substring re 1 (1- (length re))))
451 (message "Regexp copied to kill-ring")))
453 ;; The subexpression mode is not electric because the number of
454 ;; matches should be seen rather than a prompt.
455 (defun reb-enter-subexp-mode ()
456 "Enter the subexpression mode in the RE Builder."
458 (setq reb-subexp-mode t)
459 (reb-update-modestring)
460 (use-local-map reb-subexp-mode-map)
461 (message "`0'-`9' to display subexpressions `q' to quit subexp mode"))
463 (defun reb-show-subexp (subexp &optional pause)
464 "Visually show limit of subexpression SUBEXP of recent search.
465 On color displays this just puts point to the end of the expression as
466 the match should already be marked by an overlay.
467 On other displays jump to the beginning and the end of it.
468 If the optional PAUSE is non-nil then pause at the end in any case."
469 (with-selected-window reb-target-window
470 (unless (reb-color-display-p)
471 (goto-char (match-beginning subexp))
472 (sit-for reb-blink-delay))
473 (goto-char (match-end subexp))
474 (when (or (not (reb-color-display-p)) pause)
475 (sit-for reb-blink-delay))))
477 (defun reb-quit-subexp-mode ()
478 "Quit the subexpression mode in the RE Builder."
480 (setq reb-subexp-mode nil
481 reb-subexp-displayed nil)
482 (reb-update-modestring)
483 (use-local-map reb-mode-map)
486 (defun reb-change-syntax (&optional syntax)
487 "Change the syntax used by the RE Builder.
488 Optional argument SYNTAX must be specified if called non-interactively."
491 (completing-read "Select syntax: "
492 (mapcar (lambda (el) (cons (symbol-name el) 1))
493 '(read string sregex rx))
494 nil t (symbol-name reb-re-syntax)))))
496 (if (memq syntax '(read string sregex rx))
497 (let ((buffer (get-buffer reb-buffer)))
498 (setq reb-re-syntax syntax)
500 (with-current-buffer buffer
501 (reb-initialize-buffer))))
502 (error "Invalid syntax: %s" syntax)))
505 ;; Non-interactive functions below
506 (defun reb-do-update (&optional subexp)
507 "Update matches in the RE Builder target window.
508 If SUBEXP is non-nil mark only the corresponding sub-expressions."
510 (reb-assert-buffer-in-window)
512 (reb-update-overlays subexp))
514 (defun reb-auto-update (_beg _end _lenold &optional force)
515 "Called from `after-update-functions' to update the display.
516 BEG, END and LENOLD are passed in from the hook.
517 An actual update is only done if the regexp has changed or if the
518 optional fourth argument FORCE is non-nil."
519 (let ((prev-valid reb-valid-string)
523 (when (or (reb-update-regexp) force)
526 (error " *invalid*"))))
527 (setq reb-valid-string new-valid)
528 (force-mode-line-update)
530 ;; Through the caching of the re a change invalidating the syntax
531 ;; for symbolic expressions will not delete the overlays so we
533 (when (and (reb-lisp-syntax-p)
534 (not (string= prev-valid new-valid))
535 (string= prev-valid ""))
536 (reb-delete-overlays))))
538 (defun reb-delete-overlays ()
539 "Delete all RE Builder overlays in the `reb-target-buffer' buffer."
540 (when (buffer-live-p reb-target-buffer)
541 (with-current-buffer reb-target-buffer
542 (mapc 'delete-overlay reb-overlays)
543 (setq reb-overlays nil))))
545 (defun reb-assert-buffer-in-window ()
546 "Assert that `reb-target-buffer' is displayed in `reb-target-window'."
548 (if (not (eq reb-target-buffer (window-buffer reb-target-window)))
549 (set-window-buffer reb-target-window reb-target-buffer)))
551 (defun reb-update-modestring ()
552 "Update the variable `reb-mode-string' displayed in the mode line."
553 (setq reb-mode-string
556 (format " (subexp %s)" (or reb-subexp-displayed "-"))
558 (if (not (reb-target-binding case-fold-search))
561 (force-mode-line-update))
563 (defun reb-display-subexp (&optional subexp)
564 "Highlight only subexpression SUBEXP in the RE Builder."
567 (setq reb-subexp-displayed
568 (or subexp (string-to-number (format "%c" last-command-event))))
569 (reb-update-modestring)
570 (reb-do-update reb-subexp-displayed))
572 (defun reb-kill-buffer ()
573 "When the RE Builder buffer is killed make sure no overlays stay around."
575 (when (reb-mode-buffer-p)
576 (reb-delete-overlays)))
579 ;; The next functions are the interface between the regexp and
580 ;; its textual representation in the RE Builder buffer.
581 ;; They are the only functions concerned with the actual syntax
583 (defun reb-read-regexp ()
586 (cond ((eq reb-re-syntax 'read)
587 (goto-char (point-min))
588 (read (current-buffer)))
589 ((eq reb-re-syntax 'string)
590 (goto-char (point-min))
591 (re-search-forward "\"")
593 (goto-char (point-max))
594 (re-search-backward "\"")
595 (buffer-substring-no-properties beg (point))))
599 (defun reb-empty-regexp ()
600 "Return empty RE for current syntax."
601 (cond ((reb-lisp-syntax-p) "'()")
604 (defun reb-insert-regexp ()
607 (let ((re (or (reb-target-binding reb-regexp)
608 (reb-empty-regexp))))
609 (cond ((eq reb-re-syntax 'read)
610 (print re (current-buffer)))
611 ((eq reb-re-syntax 'string)
612 (insert "\n\"" re "\""))
613 ;; For the Lisp syntax we need the "source" of the regexp
615 (insert (or (reb-target-binding reb-regexp-src)
616 (reb-empty-regexp)))))))
618 (defun reb-cook-regexp (re)
619 "Return RE after processing it according to `reb-re-syntax'."
620 (cond ((memq reb-re-syntax '(sregex rx))
621 (rx-to-string (eval (car (read-from-string re)))))
624 (defun reb-update-regexp ()
625 "Update the regexp for the target buffer.
626 Return t if the (cooked) expression changed."
627 (let* ((re-src (reb-read-regexp))
628 (re (reb-cook-regexp re-src)))
629 (with-current-buffer reb-target-buffer
630 (let ((oldre reb-regexp))
632 (not (string= oldre re))
634 ;; Only update the source re for the lisp formats
635 (when (reb-lisp-syntax-p)
636 (setq reb-regexp-src re-src)))))))
639 ;; And now the real core of the whole thing
640 (defun reb-count-subexps (re)
641 "Return number of sub-expressions in the regexp RE."
644 (while (string-match "\\\\(" re beg)
649 (defun reb-update-overlays (&optional subexp)
650 "Switch to `reb-target-buffer' and mark all matches of `reb-regexp'.
651 If SUBEXP is non-nil mark only the corresponding sub-expressions."
652 (let* ((re (reb-target-binding reb-regexp))
653 (subexps (reb-count-subexps re))
657 (with-current-buffer reb-target-buffer
658 (reb-delete-overlays)
659 (goto-char (point-min))
660 (while (and (not (eobp))
661 (re-search-forward re (point-max) t)
662 (or (not reb-auto-match-limit)
663 (< matches reb-auto-match-limit)))
664 (when (and (= 0 (length (match-string 0)))
669 (setq matches (1+ matches))
670 (while (<= i subexps)
671 (when (and (or (not subexp) (= subexp i))
673 (let ((overlay (make-overlay (match-beginning i)
675 ;; When we have exceeded the number of provided faces,
676 ;; cycle thru them where `max-suffix' denotes the maximum
677 ;; suffix for `reb-match-*' that has been defined and
678 ;; `suffix' the suffix calculated for the current match.
682 (if (= suffix max-suffix)
684 (setq suffix (1+ suffix)))
685 (intern-soft (format "reb-match-%d" suffix)))
686 ((intern-soft (format "reb-match-%d" i)))
687 ((setq max-suffix (1- i))
689 ;; `reb-match-1' must exist.
691 (unless firstmatch (setq firstmatch (match-data)))
692 (setq reb-overlays (cons overlay reb-overlays)
693 submatches (1+ submatches))
694 (overlay-put overlay 'face face)
695 (overlay-put overlay 'priority i)))
697 (let ((count (if subexp submatches matches)))
698 (message "%s %smatch%s%s"
699 (if (= 0 count) "No" (int-to-string count))
700 (if subexp "subexpression " "")
701 (if (= 1 count) "" "es")
702 (if (and reb-auto-match-limit
703 (= reb-auto-match-limit count))
704 " (limit reached)" "")))
706 (store-match-data firstmatch)
707 (reb-show-subexp (or subexp 0)))))
710 (defun re-builder-unload-function ()
711 "Unload the RE Builder library."
712 (when (buffer-live-p (get-buffer reb-buffer))
713 (with-current-buffer reb-buffer
714 (remove-hook 'after-change-functions 'reb-auto-update t)
715 (remove-hook 'kill-buffer-hook 'reb-kill-buffer t)
716 (when (reb-mode-buffer-p)
717 (reb-delete-overlays))))
718 ;; continue standard unloading
721 (provide 're-builder)
723 ;;; re-builder.el ends here