Trailing whitepace deleted.
[emacs.git] / lisp / emacs-lisp / regexp-opt.el
blob486cf006e4b1d12a77d7aa640805bf1fb4ced1cb
1 ;;; regexp-opt.el --- generate efficient regexps to match strings
3 ;; Copyright (C) 1994,95,96,97,98,99,2000 Free Software Foundation, Inc.
5 ;; Author: Simon Marshall <simon@gnu.org>
6 ;; Maintainer: FSF
7 ;; Keywords: strings, regexps, extensions
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 2, or (at your option)
14 ;; 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; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;; The "opt" in "regexp-opt" stands for "optim\\(al\\|i[sz]e\\)".
30 ;; This package generates a regexp from a given list of strings (which matches
31 ;; one of those strings) so that the regexp generated by:
33 ;; (regexp-opt strings)
35 ;; is equivalent to, but more efficient than, the regexp generated by:
37 ;; (mapconcat 'regexp-quote strings "\\|")
39 ;; For example:
41 ;; (let ((strings '("cond" "if" "when" "unless" "while"
42 ;; "let" "let*" "progn" "prog1" "prog2"
43 ;; "save-restriction" "save-excursion" "save-window-excursion"
44 ;; "save-current-buffer" "save-match-data"
45 ;; "catch" "throw" "unwind-protect" "condition-case")))
46 ;; (concat "(" (regexp-opt strings t) "\\>"))
47 ;; => "(\\(c\\(atch\\|ond\\(ition-case\\)?\\)\\|if\\|let\\*?\\|prog[12n]\\|save-\\(current-buffer\\|excursion\\|match-data\\|restriction\\|window-excursion\\)\\|throw\\|un\\(less\\|wind-protect\\)\\|wh\\(en\\|ile\\)\\)\\>"
49 ;; Searching using the above example `regexp-opt' regexp takes approximately
50 ;; two-thirds of the time taken using the equivalent `mapconcat' regexp.
52 ;; Since this package was written to produce efficient regexps, not regexps
53 ;; efficiently, it is probably not a good idea to in-line too many calls in
54 ;; your code, unless you use the following trick with `eval-when-compile':
56 ;; (defvar definition-regexp
57 ;; (eval-when-compile
58 ;; (concat "^("
59 ;; (regexp-opt '("defun" "defsubst" "defmacro" "defalias"
60 ;; "defvar" "defconst") t)
61 ;; "\\>")))
63 ;; The `byte-compile' code will be as if you had defined the variable thus:
65 ;; (defvar definition-regexp
66 ;; "^(\\(def\\(alias\\|const\\|macro\\|subst\\|un\\|var\\)\\)\\>")
68 ;; Note that if you use this trick for all instances of `regexp-opt' and
69 ;; `regexp-opt-depth' in your code, regexp-opt.el would only have to be loaded
70 ;; at compile time. But note also that using this trick means that should
71 ;; regexp-opt.el be changed, perhaps to fix a bug or to add a feature to
72 ;; improve the efficiency of `regexp-opt' regexps, you would have to recompile
73 ;; your code for such changes to have effect in your code.
75 ;; Originally written for font-lock.el, from an idea from Stig's hl319.el, with
76 ;; thanks for ideas also to Michael Ernst, Bob Glickstein, Dan Nicolaescu and
77 ;; Stefan Monnier.
78 ;; No doubt `regexp-opt' doesn't always produce optimal regexps, so code, ideas
79 ;; or any other information to improve things are welcome.
81 ;; One possible improvement would be to compile '("aa" "ab" "ba" "bb")
82 ;; into "[ab][ab]" rather than "a[ab]\\|b[ab]". I'm not sure it's worth
83 ;; it but if someone knows how to do it without going through too many
84 ;; contortions, I'm all ears.
86 ;;; Code:
88 ;;;###autoload
89 (defun regexp-opt (strings &optional paren)
90 "Return a regexp to match a string in STRINGS.
91 Each string should be unique in STRINGS and should not contain any regexps,
92 quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
93 is enclosed by at least one regexp grouping construct.
94 The returned regexp is typically more efficient than the equivalent regexp:
96 (let ((open (if PAREN \"\\\\(\" \"\")) (close (if PAREN \"\\\\)\" \"\")))
97 (concat open (mapconcat 'regexp-quote STRINGS \"\\\\|\") close))
99 If PAREN is `words', then the resulting regexp is additionally surrounded
100 by \\=\\< and \\>."
101 (save-match-data
102 ;; Recurse on the sorted list.
103 (let* ((max-lisp-eval-depth (* 1024 1024))
104 (max-specpdl-size (* 1024 1024))
105 (completion-ignore-case nil)
106 (completion-regexp-list nil)
107 (words (eq paren 'words))
108 (open (cond ((stringp paren) paren) (paren "\\(")))
109 (sorted-strings (sort (copy-sequence strings) 'string-lessp))
110 (re (regexp-opt-group sorted-strings open)))
111 (if words (concat "\\<" re "\\>") re))))
113 ;;;###autoload
114 (defun regexp-opt-depth (regexp)
115 "Return the depth of REGEXP.
116 This means the number of regexp grouping constructs (parenthesised expressions)
117 in REGEXP."
118 (save-match-data
119 ;; Hack to signal an error if REGEXP does not have balanced parentheses.
120 (string-match regexp "")
121 ;; Count the number of open parentheses in REGEXP.
122 (let ((count 0) start)
123 (while (string-match "\\(\\`\\|[^\\]\\)\\\\\\(\\\\\\\\\\)*([^?]"
124 regexp start)
125 (setq count (1+ count)
126 ;; Go back 2 chars (one for [^?] and one for [^\\]).
127 start (- (match-end 0) 2)))
128 count)))
130 ;;; Workhorse functions.
132 (eval-when-compile
133 (require 'cl))
135 (defun regexp-opt-group (strings &optional paren lax)
136 ;; Return a regexp to match a string in the sorted list STRINGS.
137 ;; If PAREN non-nil, output regexp parentheses around returned regexp.
138 ;; If LAX non-nil, don't output parentheses if it doesn't require them.
139 ;; Merges keywords to avoid backtracking in Emacs' regexp matcher.
141 ;; The basic idea is to find the shortest common prefix or suffix, remove it
142 ;; and recurse. If there is no prefix, we divide the list into two so that
143 ;; \(at least) one half will have at least a one-character common prefix.
145 ;; Also we delay the addition of grouping parenthesis as long as possible
146 ;; until we're sure we need them, and try to remove one-character sequences
147 ;; so we can use character sets rather than grouping parenthesis.
148 (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
149 (close-group (if paren "\\)" ""))
150 (open-charset (if lax "" open-group))
151 (close-charset (if lax "" close-group)))
152 (cond
154 ;; If there are no strings, just return the empty string.
155 ((= (length strings) 0)
158 ;; If there is only one string, just return it.
159 ((= (length strings) 1)
160 (if (= (length (car strings)) 1)
161 (concat open-charset (regexp-quote (car strings)) close-charset)
162 (concat open-group (regexp-quote (car strings)) close-group)))
164 ;; If there is an empty string, remove it and recurse on the rest.
165 ((= (length (car strings)) 0)
166 (concat open-charset
167 (regexp-opt-group (cdr strings) t t) "?"
168 close-charset))
170 ;; If there are several one-char strings, use charsets
171 ((and (= (length (car strings)) 1)
172 (let ((strs (cdr strings)))
173 (while (and strs (/= (length (car strs)) 1))
174 (pop strs))
175 strs))
176 (let (letters rest)
177 ;; Collect one-char strings
178 (dolist (s strings)
179 (if (= (length s) 1) (push (string-to-char s) letters) (push s rest)))
181 (if rest
182 ;; several one-char strings: take them and recurse
183 ;; on the rest (first so as to match the longest).
184 (concat open-group
185 (regexp-opt-group (nreverse rest))
186 "\\|" (regexp-opt-charset letters)
187 close-group)
188 ;; all are one-char strings: just return a character set.
189 (concat open-charset
190 (regexp-opt-charset letters)
191 close-charset))))
193 ;; We have a list of different length strings.
195 (let ((prefix (try-completion "" strings)))
196 (if (> (length prefix) 0)
197 ;; common prefix: take it and recurse on the suffixes.
198 (let* ((n (length prefix))
199 (suffixes (mapcar (lambda (s) (substring s n)) strings)))
200 (concat open-group
201 (regexp-quote prefix)
202 (regexp-opt-group suffixes t t)
203 close-group))
205 (let* ((sgnirts (mapcar (lambda (s)
206 (concat (nreverse (string-to-list s))))
207 strings))
208 (xiffus (try-completion "" sgnirts)))
209 (if (> (length xiffus) 0)
210 ;; common suffix: take it and recurse on the prefixes.
211 (let* ((n (- (length xiffus)))
212 (prefixes
213 ;; Sorting is necessary in cases such as ("ad" "d").
214 (sort (mapcar (lambda (s) (substring s 0 n)) strings)
215 'string-lessp)))
216 (concat open-group
217 (regexp-opt-group prefixes t t)
218 (regexp-quote
219 (concat (nreverse (string-to-list xiffus))))
220 close-group))
222 ;; Otherwise, divide the list into those that start with a
223 ;; particular letter and those that do not, and recurse on them.
224 (let* ((char (char-to-string (string-to-char (car strings))))
225 (half1 (all-completions char strings))
226 (half2 (nthcdr (length half1) strings)))
227 (concat open-group
228 (regexp-opt-group half1)
229 "\\|" (regexp-opt-group half2)
230 close-group))))))))))
233 (defun regexp-opt-charset (chars)
235 ;; Return a regexp to match a character in CHARS.
237 ;; The basic idea is to find character ranges. Also we take care in the
238 ;; position of character set meta characters in the character set regexp.
240 (let* ((charmap (make-char-table 'case-table))
241 (start -1) (end -2)
242 (charset "")
243 (bracket "") (dash "") (caret ""))
245 ;; Make a character map but extract character set meta characters.
246 (dolist (char chars)
247 (case char
248 (?\]
249 (setq bracket "]"))
251 (setq caret "^"))
253 (setq dash "-"))
254 (otherwise
255 (aset charmap char t))))
257 ;; Make a character set from the map using ranges where applicable.
258 (map-char-table
259 (lambda (c v)
260 (when v
261 (if (= (1- c) end) (setq end c)
262 (if (> end (+ start 2))
263 (setq charset (format "%s%c-%c" charset start end))
264 (while (>= end start)
265 (setq charset (format "%s%c" charset start))
266 (incf start)))
267 (setq start c end c))))
268 charmap)
269 (when (>= end start)
270 (if (> end (+ start 2))
271 (setq charset (format "%s%c-%c" charset start end))
272 (while (>= end start)
273 (setq charset (format "%s%c" charset start))
274 (incf start))))
276 ;; Make sure a caret is not first and a dash is first or last.
277 (if (and (string-equal charset "") (string-equal bracket ""))
278 (concat "[" dash caret "]")
279 (concat "[" bracket charset caret dash "]"))))
281 (provide 'regexp-opt)
283 ;;; regexp-opt.el ends here