Add 2011 to FSF/AIST copyright years.
[bpt/emacs.git] / lisp / emacs-lisp / regexp-opt.el
CommitLineData
55535639 1;;; regexp-opt.el --- generate efficient regexps to match strings
56329bc5 2
d59c3137 3;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
5df4f04c 4;; 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
56329bc5 5
5762abec 6;; Author: Simon Marshall <simon@gnu.org>
fcc31755 7;; Maintainer: FSF
370893a1 8;; Keywords: strings, regexps, extensions
56329bc5
RS
9
10;; This file is part of GNU Emacs.
11
d6cba7ae 12;; GNU Emacs is free software: you can redistribute it and/or modify
56329bc5 13;; it under the terms of the GNU General Public License as published by
d6cba7ae
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
56329bc5
RS
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
d6cba7ae 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
56329bc5
RS
24
25;;; Commentary:
26
b02b54a8 27;; The "opt" in "regexp-opt" stands for "optim\\(al\\|i[sz]e\\)".
56329bc5 28;;
25544ce1
SM
29;; This package generates a regexp from a given list of strings (which matches
30;; one of those strings) so that the regexp generated by:
56329bc5 31;;
25544ce1
SM
32;; (regexp-opt strings)
33;;
34;; is equivalent to, but more efficient than, the regexp generated by:
35;;
36;; (mapconcat 'regexp-quote strings "\\|")
56329bc5
RS
37;;
38;; For example:
39;;
40;; (let ((strings '("cond" "if" "when" "unless" "while"
41;; "let" "let*" "progn" "prog1" "prog2"
42;; "save-restriction" "save-excursion" "save-window-excursion"
43;; "save-current-buffer" "save-match-data"
44;; "catch" "throw" "unwind-protect" "condition-case")))
45;; (concat "(" (regexp-opt strings t) "\\>"))
46;; => "(\\(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;;
25544ce1
SM
48;; Searching using the above example `regexp-opt' regexp takes approximately
49;; two-thirds of the time taken using the equivalent `mapconcat' regexp.
50
56329bc5
RS
51;; Since this package was written to produce efficient regexps, not regexps
52;; efficiently, it is probably not a good idea to in-line too many calls in
53;; your code, unless you use the following trick with `eval-when-compile':
54;;
55;; (defvar definition-regexp
56;; (eval-when-compile
57;; (concat "^("
58;; (regexp-opt '("defun" "defsubst" "defmacro" "defalias"
59;; "defvar" "defconst") t)
60;; "\\>")))
61;;
62;; The `byte-compile' code will be as if you had defined the variable thus:
63;;
64;; (defvar definition-regexp
65;; "^(\\(def\\(alias\\|const\\|macro\\|subst\\|un\\|var\\)\\)\\>")
66;;
25544ce1
SM
67;; Note that if you use this trick for all instances of `regexp-opt' and
68;; `regexp-opt-depth' in your code, regexp-opt.el would only have to be loaded
69;; at compile time. But note also that using this trick means that should
70;; regexp-opt.el be changed, perhaps to fix a bug or to add a feature to
71;; improve the efficiency of `regexp-opt' regexps, you would have to recompile
72;; your code for such changes to have effect in your code.
73
74;; Originally written for font-lock.el, from an idea from Stig's hl319.el, with
b02b54a8
GM
75;; thanks for ideas also to Michael Ernst, Bob Glickstein, Dan Nicolaescu and
76;; Stefan Monnier.
77;; No doubt `regexp-opt' doesn't always produce optimal regexps, so code, ideas
78;; or any other information to improve things are welcome.
c0056275
SM
79;;
80;; One possible improvement would be to compile '("aa" "ab" "ba" "bb")
81;; into "[ab][ab]" rather than "a[ab]\\|b[ab]". I'm not sure it's worth
82;; it but if someone knows how to do it without going through too many
83;; contortions, I'm all ears.
56329bc5 84\f
c0056275 85;;; Code:
56329bc5
RS
86
87;;;###autoload
88(defun regexp-opt (strings &optional paren)
784c9f3c 89 "Return a regexp to match a string in the list STRINGS.
582305b0
RS
90Each string should be unique in STRINGS and should not contain any regexps,
91quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
92is enclosed by at least one regexp grouping construct.
56329bc5
RS
93The returned regexp is typically more efficient than the equivalent regexp:
94
908bb42f
SM
95 (let ((open (if PAREN \"\\\\(\" \"\")) (close (if PAREN \"\\\\)\" \"\")))
96 (concat open (mapconcat 'regexp-quote STRINGS \"\\\\|\") close))
97
98If PAREN is `words', then the resulting regexp is additionally surrounded
99by \\=\\< and \\>."
56329bc5
RS
100 (save-match-data
101 ;; Recurse on the sorted list.
dbf3ef78
CY
102 (let* ((max-lisp-eval-depth 10000)
103 (max-specpdl-size 10000)
908bb42f 104 (completion-ignore-case nil)
08cf00d8 105 (completion-regexp-list nil)
908bb42f
SM
106 (words (eq paren 'words))
107 (open (cond ((stringp paren) paren) (paren "\\(")))
22864a48
SM
108 (sorted-strings (delete-dups
109 (sort (copy-sequence strings) 'string-lessp)))
9cc236e0 110 (re (regexp-opt-group sorted-strings (or open t) (not open))))
908bb42f 111 (if words (concat "\\<" re "\\>") re))))
56329bc5
RS
112
113;;;###autoload
114(defun regexp-opt-depth (regexp)
115 "Return the depth of REGEXP.
22864a48 116This means the number of non-shy regexp grouping constructs
8665b2b6 117\(parenthesized expressions) in REGEXP."
56329bc5
RS
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.
22864a48
SM
122 (let ((count 0) start last)
123 (while (string-match "\\\\(\\(\\?:\\)?" regexp start)
124 (setq start (match-end 0)) ; Start of next search.
125 (when (and (not (match-beginning 1))
126 (subregexp-context-p regexp (match-beginning 0) last))
127 ;; It's not a shy group and it's not inside brackets or after
128 ;; a backslash: it's really a group-open marker.
129 (setq last start) ; Speed up next regexp-opt-re-context-p.
130 (setq count (1+ count))))
56329bc5
RS
131 count)))
132\f
133;;; Workhorse functions.
134
135(eval-when-compile
136 (require 'cl))
137
56329bc5 138(defun regexp-opt-group (strings &optional paren lax)
a7769c30
SM
139 "Return a regexp to match a string in the sorted list STRINGS.
140If PAREN non-nil, output regexp parentheses around returned regexp.
141If LAX non-nil, don't output parentheses if it doesn't require them.
142Merges keywords to avoid backtracking in Emacs' regexp matcher."
94abe30b
SM
143 ;; The basic idea is to find the shortest common prefix or suffix, remove it
144 ;; and recurse. If there is no prefix, we divide the list into two so that
145 ;; \(at least) one half will have at least a one-character common prefix.
146
147 ;; Also we delay the addition of grouping parenthesis as long as possible
148 ;; until we're sure we need them, and try to remove one-character sequences
149 ;; so we can use character sets rather than grouping parenthesis.
c0056275 150 (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
56329bc5
RS
151 (close-group (if paren "\\)" ""))
152 (open-charset (if lax "" open-group))
c0056275 153 (close-charset (if lax "" close-group)))
56329bc5 154 (cond
b02b54a8
GM
155 ;;
156 ;; If there are no strings, just return the empty string.
157 ((= (length strings) 0)
158 "")
159 ;;
56329bc5
RS
160 ;; If there is only one string, just return it.
161 ((= (length strings) 1)
162 (if (= (length (car strings)) 1)
163 (concat open-charset (regexp-quote (car strings)) close-charset)
164 (concat open-group (regexp-quote (car strings)) close-group)))
165 ;;
166 ;; If there is an empty string, remove it and recurse on the rest.
167 ((= (length (car strings)) 0)
168 (concat open-charset
169 (regexp-opt-group (cdr strings) t t) "?"
170 close-charset))
171 ;;
c0056275
SM
172 ;; If there are several one-char strings, use charsets
173 ((and (= (length (car strings)) 1)
174 (let ((strs (cdr strings)))
175 (while (and strs (/= (length (car strs)) 1))
176 (pop strs))
177 strs))
178 (let (letters rest)
179 ;; Collect one-char strings
180 (dolist (s strings)
5cda4b07 181 (if (= (length s) 1) (push (string-to-char s) letters) (push s rest)))
c0056275
SM
182
183 (if rest
184 ;; several one-char strings: take them and recurse
185 ;; on the rest (first so as to match the longest).
186 (concat open-group
187 (regexp-opt-group (nreverse rest))
188 "\\|" (regexp-opt-charset letters)
189 close-group)
190 ;; all are one-char strings: just return a character set.
191 (concat open-charset
192 (regexp-opt-charset letters)
193 close-charset))))
56329bc5
RS
194 ;;
195 ;; We have a list of different length strings.
196 (t
91fc05b1 197 (let ((prefix (try-completion "" strings)))
c0056275
SM
198 (if (> (length prefix) 0)
199 ;; common prefix: take it and recurse on the suffixes.
200 (let* ((n (length prefix))
201 (suffixes (mapcar (lambda (s) (substring s n)) strings)))
bba6564c 202 (concat open-group
c0056275
SM
203 (regexp-quote prefix)
204 (regexp-opt-group suffixes t t)
bba6564c 205 close-group))
c0056275
SM
206
207 (let* ((sgnirts (mapcar (lambda (s)
208 (concat (nreverse (string-to-list s))))
209 strings))
91fc05b1 210 (xiffus (try-completion "" sgnirts)))
c0056275
SM
211 (if (> (length xiffus) 0)
212 ;; common suffix: take it and recurse on the prefixes.
213 (let* ((n (- (length xiffus)))
7e1d6bdb
SM
214 (prefixes
215 ;; Sorting is necessary in cases such as ("ad" "d").
216 (sort (mapcar (lambda (s) (substring s 0 n)) strings)
217 'string-lessp)))
bba6564c 218 (concat open-group
c0056275
SM
219 (regexp-opt-group prefixes t t)
220 (regexp-quote
221 (concat (nreverse (string-to-list xiffus))))
bba6564c 222 close-group))
a1506d29 223
c0056275
SM
224 ;; Otherwise, divide the list into those that start with a
225 ;; particular letter and those that do not, and recurse on them.
75407435 226 (let* ((char (substring-no-properties (car strings) 0 1))
91fc05b1 227 (half1 (all-completions char strings))
94abe30b 228 (half2 (nthcdr (length half1) strings)))
c0056275
SM
229 (concat open-group
230 (regexp-opt-group half1)
231 "\\|" (regexp-opt-group half2)
232 close-group))))))))))
233
56329bc5
RS
234
235(defun regexp-opt-charset (chars)
a7769c30 236 "Return a regexp to match a character in CHARS."
56329bc5
RS
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.
239 ;;
5cda4b07
SM
240 (let* ((charmap (make-char-table 'case-table))
241 (start -1) (end -2)
56329bc5
RS
242 (charset "")
243 (bracket "") (dash "") (caret ""))
244 ;;
245 ;; Make a character map but extract character set meta characters.
5cda4b07 246 (dolist (char chars)
25544ce1
SM
247 (case char
248 (?\]
249 (setq bracket "]"))
250 (?^
251 (setq caret "^"))
252 (?-
253 (setq dash "-"))
254 (otherwise
255 (aset charmap char t))))
56329bc5
RS
256 ;;
257 ;; Make a character set from the map using ranges where applicable.
5cda4b07
SM
258 (map-char-table
259 (lambda (c v)
260 (when v
6466bb34
KH
261 (if (consp c)
262 (if (= (1- (car c)) end) (setq end (cdr c))
263 (if (> end (+ start 2))
264 (setq charset (format "%s%c-%c" charset start end))
265 (while (>= end start)
266 (setq charset (format "%s%c" charset start))
267 (incf start)))
268 (setq start (car c) end (cdr c)))
269 (if (= (1- c) end) (setq end c)
270 (if (> end (+ start 2))
5cda4b07
SM
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)))
6466bb34 275 (setq start c end c)))))
5cda4b07
SM
276 charmap)
277 (when (>= end start)
278 (if (> end (+ start 2))
279 (setq charset (format "%s%c-%c" charset start end))
280 (while (>= end start)
281 (setq charset (format "%s%c" charset start))
282 (incf start))))
56329bc5
RS
283 ;;
284 ;; Make sure a caret is not first and a dash is first or last.
285 (if (and (string-equal charset "") (string-equal bracket ""))
286 (concat "[" dash caret "]")
287 (concat "[" bracket charset caret dash "]"))))
288
289(provide 'regexp-opt)
290
22864a48 291;; arch-tag: 6c5a66f4-29af-4fd6-8c3b-4b554d5b4370
56329bc5 292;;; regexp-opt.el ends here