Fix bug #9221 with memory leak in bidi display.
[emacs.git] / lisp / emacs-lisp / regexp-opt.el
blobb538a7a294302c0a707f6ccf3bb60b631ceff467
1 ;;; regexp-opt.el --- generate efficient regexps to match strings
3 ;; Copyright (C) 1994-2011 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 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/>.
24 ;;; Commentary:
26 ;; The "opt" in "regexp-opt" stands for "optim\\(al\\|i[sz]e\\)".
28 ;; This package generates a regexp from a given list of strings (which matches
29 ;; one of those strings) so that the regexp generated by:
31 ;; (regexp-opt strings)
33 ;; is equivalent to, but more efficient than, the regexp generated by:
35 ;; (mapconcat 'regexp-quote strings "\\|")
37 ;; For example:
39 ;; (let ((strings '("cond" "if" "when" "unless" "while"
40 ;; "let" "let*" "progn" "prog1" "prog2"
41 ;; "save-restriction" "save-excursion" "save-window-excursion"
42 ;; "save-current-buffer" "save-match-data"
43 ;; "catch" "throw" "unwind-protect" "condition-case")))
44 ;; (concat "(" (regexp-opt strings t) "\\>"))
45 ;; => "(\\(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\\)\\)\\>"
47 ;; Searching using the above example `regexp-opt' regexp takes approximately
48 ;; two-thirds of the time taken using the equivalent `mapconcat' regexp.
50 ;; Since this package was written to produce efficient regexps, not regexps
51 ;; efficiently, it is probably not a good idea to in-line too many calls in
52 ;; your code, unless you use the following trick with `eval-when-compile':
54 ;; (defvar definition-regexp
55 ;; (eval-when-compile
56 ;; (concat "^("
57 ;; (regexp-opt '("defun" "defsubst" "defmacro" "defalias"
58 ;; "defvar" "defconst") t)
59 ;; "\\>")))
61 ;; The `byte-compile' code will be as if you had defined the variable thus:
63 ;; (defvar definition-regexp
64 ;; "^(\\(def\\(alias\\|const\\|macro\\|subst\\|un\\|var\\)\\)\\>")
66 ;; Note that if you use this trick for all instances of `regexp-opt' and
67 ;; `regexp-opt-depth' in your code, regexp-opt.el would only have to be loaded
68 ;; at compile time. But note also that using this trick means that should
69 ;; regexp-opt.el be changed, perhaps to fix a bug or to add a feature to
70 ;; improve the efficiency of `regexp-opt' regexps, you would have to recompile
71 ;; your code for such changes to have effect in your code.
73 ;; Originally written for font-lock.el, from an idea from Stig's hl319.el, with
74 ;; thanks for ideas also to Michael Ernst, Bob Glickstein, Dan Nicolaescu and
75 ;; Stefan Monnier.
76 ;; No doubt `regexp-opt' doesn't always produce optimal regexps, so code, ideas
77 ;; or any other information to improve things are welcome.
79 ;; One possible improvement would be to compile '("aa" "ab" "ba" "bb")
80 ;; into "[ab][ab]" rather than "a[ab]\\|b[ab]". I'm not sure it's worth
81 ;; it but if someone knows how to do it without going through too many
82 ;; contortions, I'm all ears.
84 ;;; Code:
86 ;;;###autoload
87 (defun regexp-opt (strings &optional paren)
88 "Return a regexp to match a string in the list STRINGS.
89 Each string should be unique in STRINGS and should not contain any regexps,
90 quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
91 is enclosed by at least one regexp grouping construct.
92 The returned regexp is typically more efficient than the equivalent regexp:
94 (let ((open (if PAREN \"\\\\(\" \"\")) (close (if PAREN \"\\\\)\" \"\")))
95 (concat open (mapconcat 'regexp-quote STRINGS \"\\\\|\") close))
97 If PAREN is `words', then the resulting regexp is additionally surrounded
98 by \\=\\< and \\>.
99 If PAREN is `symbols', 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 10000)
104 (max-specpdl-size 10000)
105 (completion-ignore-case nil)
106 (completion-regexp-list nil)
107 (open (cond ((stringp paren) paren) (paren "\\(")))
108 (sorted-strings (delete-dups
109 (sort (copy-sequence strings) 'string-lessp)))
110 (re (regexp-opt-group sorted-strings (or open t) (not open))))
111 (cond ((eq paren 'words)
112 (concat "\\<" re "\\>"))
113 ((eq paren 'symbols)
114 (concat "\\_<" re "\\_>"))
115 (t re)))))
117 ;;;###autoload
118 (defun regexp-opt-depth (regexp)
119 "Return the depth of REGEXP.
120 This means the number of non-shy regexp grouping constructs
121 \(parenthesized expressions) in REGEXP."
122 (save-match-data
123 ;; Hack to signal an error if REGEXP does not have balanced parentheses.
124 (string-match regexp "")
125 ;; Count the number of open parentheses in REGEXP.
126 (let ((count 0) start last)
127 (while (string-match "\\\\(\\(\\?[0-9]*:\\)?" regexp start)
128 (setq start (match-end 0)) ; Start of next search.
129 (when (and (not (match-beginning 1))
130 (subregexp-context-p regexp (match-beginning 0) last))
131 ;; It's not a shy group and it's not inside brackets or after
132 ;; a backslash: it's really a group-open marker.
133 (setq last start) ; Speed up next regexp-opt-re-context-p.
134 (setq count (1+ count))))
135 count)))
137 ;;; Workhorse functions.
139 (eval-when-compile
140 (require 'cl))
142 (defun regexp-opt-group (strings &optional paren lax)
143 "Return a regexp to match a string in the sorted list STRINGS.
144 If PAREN non-nil, output regexp parentheses around returned regexp.
145 If LAX non-nil, don't output parentheses if it doesn't require them.
146 Merges keywords to avoid backtracking in Emacs' regexp matcher."
147 ;; The basic idea is to find the shortest common prefix or suffix, remove it
148 ;; and recurse. If there is no prefix, we divide the list into two so that
149 ;; \(at least) one half will have at least a one-character common prefix.
151 ;; Also we delay the addition of grouping parenthesis as long as possible
152 ;; until we're sure we need them, and try to remove one-character sequences
153 ;; so we can use character sets rather than grouping parenthesis.
154 (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
155 (close-group (if paren "\\)" ""))
156 (open-charset (if lax "" open-group))
157 (close-charset (if lax "" close-group)))
158 (cond
160 ;; If there are no strings, just return the empty string.
161 ((= (length strings) 0)
164 ;; If there is only one string, just return it.
165 ((= (length strings) 1)
166 (if (= (length (car strings)) 1)
167 (concat open-charset (regexp-quote (car strings)) close-charset)
168 (concat open-group (regexp-quote (car strings)) close-group)))
170 ;; If there is an empty string, remove it and recurse on the rest.
171 ((= (length (car strings)) 0)
172 (concat open-charset
173 (regexp-opt-group (cdr strings) t t) "?"
174 close-charset))
176 ;; If there are several one-char strings, use charsets
177 ((and (= (length (car strings)) 1)
178 (let ((strs (cdr strings)))
179 (while (and strs (/= (length (car strs)) 1))
180 (pop strs))
181 strs))
182 (let (letters rest)
183 ;; Collect one-char strings
184 (dolist (s strings)
185 (if (= (length s) 1) (push (string-to-char s) letters) (push s rest)))
187 (if rest
188 ;; several one-char strings: take them and recurse
189 ;; on the rest (first so as to match the longest).
190 (concat open-group
191 (regexp-opt-group (nreverse rest))
192 "\\|" (regexp-opt-charset letters)
193 close-group)
194 ;; all are one-char strings: just return a character set.
195 (concat open-charset
196 (regexp-opt-charset letters)
197 close-charset))))
199 ;; We have a list of different length strings.
201 (let ((prefix (try-completion "" strings)))
202 (if (> (length prefix) 0)
203 ;; common prefix: take it and recurse on the suffixes.
204 (let* ((n (length prefix))
205 (suffixes (mapcar (lambda (s) (substring s n)) strings)))
206 (concat open-group
207 (regexp-quote prefix)
208 (regexp-opt-group suffixes t t)
209 close-group))
211 (let* ((sgnirts (mapcar (lambda (s)
212 (concat (nreverse (string-to-list s))))
213 strings))
214 (xiffus (try-completion "" sgnirts)))
215 (if (> (length xiffus) 0)
216 ;; common suffix: take it and recurse on the prefixes.
217 (let* ((n (- (length xiffus)))
218 (prefixes
219 ;; Sorting is necessary in cases such as ("ad" "d").
220 (sort (mapcar (lambda (s) (substring s 0 n)) strings)
221 'string-lessp)))
222 (concat open-group
223 (regexp-opt-group prefixes t t)
224 (regexp-quote
225 (concat (nreverse (string-to-list xiffus))))
226 close-group))
228 ;; Otherwise, divide the list into those that start with a
229 ;; particular letter and those that do not, and recurse on them.
230 (let* ((char (substring-no-properties (car strings) 0 1))
231 (half1 (all-completions char strings))
232 (half2 (nthcdr (length half1) strings)))
233 (concat open-group
234 (regexp-opt-group half1)
235 "\\|" (regexp-opt-group half2)
236 close-group))))))))))
239 (defun regexp-opt-charset (chars)
240 "Return a regexp to match a character in CHARS."
241 ;; The basic idea is to find character ranges. Also we take care in the
242 ;; position of character set meta characters in the character set regexp.
244 (let* ((charmap (make-char-table 'case-table))
245 (start -1) (end -2)
246 (charset "")
247 (bracket "") (dash "") (caret ""))
249 ;; Make a character map but extract character set meta characters.
250 (dolist (char chars)
251 (case char
252 (?\]
253 (setq bracket "]"))
255 (setq caret "^"))
257 (setq dash "-"))
258 (otherwise
259 (aset charmap char t))))
261 ;; Make a character set from the map using ranges where applicable.
262 (map-char-table
263 (lambda (c v)
264 (when v
265 (if (consp c)
266 (if (= (1- (car c)) end) (setq end (cdr c))
267 (if (> end (+ start 2))
268 (setq charset (format "%s%c-%c" charset start end))
269 (while (>= end start)
270 (setq charset (format "%s%c" charset start))
271 (incf start)))
272 (setq start (car c) end (cdr c)))
273 (if (= (1- c) end) (setq end c)
274 (if (> end (+ start 2))
275 (setq charset (format "%s%c-%c" charset start end))
276 (while (>= end start)
277 (setq charset (format "%s%c" charset start))
278 (incf start)))
279 (setq start c end c)))))
280 charmap)
281 (when (>= end start)
282 (if (> end (+ start 2))
283 (setq charset (format "%s%c-%c" charset start end))
284 (while (>= end start)
285 (setq charset (format "%s%c" charset start))
286 (incf start))))
288 ;; Make sure a caret is not first and a dash is first or last.
289 (if (and (string-equal charset "") (string-equal bracket ""))
290 (concat "[" dash caret "]")
291 (concat "[" bracket charset caret dash "]"))))
293 (provide 'regexp-opt)
295 ;;; regexp-opt.el ends here