* lisp/emacs-lisp/smie.el (smie-next-sexp): Fix up "other-end" info when
[bpt/emacs.git] / lisp / emacs-lisp / regexp-opt.el
CommitLineData
55535639 1;;; regexp-opt.el --- generate efficient regexps to match strings
56329bc5 2
ba318903 3;; Copyright (C) 1994-2014 Free Software Foundation, Inc.
56329bc5 4
5762abec 5;; Author: Simon Marshall <simon@gnu.org>
34dc21db 6;; Maintainer: emacs-devel@gnu.org
370893a1 7;; Keywords: strings, regexps, extensions
56329bc5
RS
8
9;; This file is part of GNU Emacs.
10
d6cba7ae 11;; GNU Emacs is free software: you can redistribute it and/or modify
56329bc5 12;; it under the terms of the GNU General Public License as published by
d6cba7ae
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
56329bc5
RS
15
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.
20
21;; You should have received a copy of the GNU General Public License
d6cba7ae 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
56329bc5
RS
23
24;;; Commentary:
25
b02b54a8 26;; The "opt" in "regexp-opt" stands for "optim\\(al\\|i[sz]e\\)".
56329bc5 27;;
25544ce1
SM
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:
56329bc5 30;;
25544ce1
SM
31;; (regexp-opt strings)
32;;
33;; is equivalent to, but more efficient than, the regexp generated by:
34;;
35;; (mapconcat 'regexp-quote strings "\\|")
56329bc5
RS
36;;
37;; For example:
38;;
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\\)\\)\\>"
46;;
25544ce1
SM
47;; Searching using the above example `regexp-opt' regexp takes approximately
48;; two-thirds of the time taken using the equivalent `mapconcat' regexp.
49
56329bc5
RS
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':
53;;
54;; (defvar definition-regexp
55;; (eval-when-compile
56;; (concat "^("
57;; (regexp-opt '("defun" "defsubst" "defmacro" "defalias"
58;; "defvar" "defconst") t)
59;; "\\>")))
60;;
61;; The `byte-compile' code will be as if you had defined the variable thus:
62;;
63;; (defvar definition-regexp
64;; "^(\\(def\\(alias\\|const\\|macro\\|subst\\|un\\|var\\)\\)\\>")
65;;
25544ce1
SM
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.
72
73;; Originally written for font-lock.el, from an idea from Stig's hl319.el, with
b02b54a8
GM
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.
c0056275
SM
78;;
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.
56329bc5 83\f
c0056275 84;;; Code:
56329bc5
RS
85
86;;;###autoload
87(defun regexp-opt (strings &optional paren)
784c9f3c 88 "Return a regexp to match a string in the list STRINGS.
582305b0
RS
89Each string should be unique in STRINGS and should not contain any regexps,
90quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
91is enclosed by at least one regexp grouping construct.
56329bc5
RS
92The returned regexp is typically more efficient than the equivalent regexp:
93
908bb42f
SM
94 (let ((open (if PAREN \"\\\\(\" \"\")) (close (if PAREN \"\\\\)\" \"\")))
95 (concat open (mapconcat 'regexp-quote STRINGS \"\\\\|\") close))
96
97If PAREN is `words', then the resulting regexp is additionally surrounded
07ff7702
MB
98by \\=\\< and \\>.
99If PAREN is `symbols', then the resulting regexp is additionally surrounded
100by \\=\\_< and \\_>."
56329bc5
RS
101 (save-match-data
102 ;; Recurse on the sorted list.
dbf3ef78
CY
103 (let* ((max-lisp-eval-depth 10000)
104 (max-specpdl-size 10000)
908bb42f 105 (completion-ignore-case nil)
08cf00d8 106 (completion-regexp-list nil)
908bb42f 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))))
07ff7702
MB
111 (cond ((eq paren 'words)
112 (concat "\\<" re "\\>"))
113 ((eq paren 'symbols)
114 (concat "\\_<" re "\\_>"))
115 (t re)))))
56329bc5
RS
116
117;;;###autoload
118(defun regexp-opt-depth (regexp)
119 "Return the depth of REGEXP.
22864a48 120This means the number of non-shy regexp grouping constructs
8665b2b6 121\(parenthesized expressions) in REGEXP."
56329bc5
RS
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.
22864a48 126 (let ((count 0) start last)
cf38dd42 127 (while (string-match "\\\\(\\(\\?[0-9]*:\\)?" regexp start)
22864a48
SM
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))))
56329bc5
RS
135 count)))
136\f
137;;; Workhorse functions.
138
56329bc5 139(defun regexp-opt-group (strings &optional paren lax)
a7769c30
SM
140 "Return a regexp to match a string in the sorted list STRINGS.
141If PAREN non-nil, output regexp parentheses around returned regexp.
142If LAX non-nil, don't output parentheses if it doesn't require them.
44e97401 143Merges keywords to avoid backtracking in Emacs's regexp matcher."
94abe30b
SM
144 ;; The basic idea is to find the shortest common prefix or suffix, remove it
145 ;; and recurse. If there is no prefix, we divide the list into two so that
146 ;; \(at least) one half will have at least a one-character common prefix.
147
148 ;; Also we delay the addition of grouping parenthesis as long as possible
149 ;; until we're sure we need them, and try to remove one-character sequences
150 ;; so we can use character sets rather than grouping parenthesis.
c0056275 151 (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
56329bc5
RS
152 (close-group (if paren "\\)" ""))
153 (open-charset (if lax "" open-group))
c0056275 154 (close-charset (if lax "" close-group)))
56329bc5 155 (cond
b02b54a8
GM
156 ;;
157 ;; If there are no strings, just return the empty string.
158 ((= (length strings) 0)
159 "")
160 ;;
56329bc5
RS
161 ;; If there is only one string, just return it.
162 ((= (length strings) 1)
163 (if (= (length (car strings)) 1)
164 (concat open-charset (regexp-quote (car strings)) close-charset)
165 (concat open-group (regexp-quote (car strings)) close-group)))
166 ;;
167 ;; If there is an empty string, remove it and recurse on the rest.
168 ((= (length (car strings)) 0)
169 (concat open-charset
170 (regexp-opt-group (cdr strings) t t) "?"
171 close-charset))
172 ;;
c0056275
SM
173 ;; If there are several one-char strings, use charsets
174 ((and (= (length (car strings)) 1)
175 (let ((strs (cdr strings)))
176 (while (and strs (/= (length (car strs)) 1))
177 (pop strs))
178 strs))
179 (let (letters rest)
180 ;; Collect one-char strings
181 (dolist (s strings)
5cda4b07 182 (if (= (length s) 1) (push (string-to-char s) letters) (push s rest)))
c0056275
SM
183
184 (if rest
185 ;; several one-char strings: take them and recurse
186 ;; on the rest (first so as to match the longest).
187 (concat open-group
188 (regexp-opt-group (nreverse rest))
189 "\\|" (regexp-opt-charset letters)
190 close-group)
191 ;; all are one-char strings: just return a character set.
192 (concat open-charset
193 (regexp-opt-charset letters)
194 close-charset))))
56329bc5
RS
195 ;;
196 ;; We have a list of different length strings.
197 (t
91fc05b1 198 (let ((prefix (try-completion "" strings)))
c0056275
SM
199 (if (> (length prefix) 0)
200 ;; common prefix: take it and recurse on the suffixes.
201 (let* ((n (length prefix))
202 (suffixes (mapcar (lambda (s) (substring s n)) strings)))
bba6564c 203 (concat open-group
c0056275
SM
204 (regexp-quote prefix)
205 (regexp-opt-group suffixes t t)
bba6564c 206 close-group))
c0056275
SM
207
208 (let* ((sgnirts (mapcar (lambda (s)
209 (concat (nreverse (string-to-list s))))
210 strings))
91fc05b1 211 (xiffus (try-completion "" sgnirts)))
c0056275
SM
212 (if (> (length xiffus) 0)
213 ;; common suffix: take it and recurse on the prefixes.
214 (let* ((n (- (length xiffus)))
7e1d6bdb
SM
215 (prefixes
216 ;; Sorting is necessary in cases such as ("ad" "d").
217 (sort (mapcar (lambda (s) (substring s 0 n)) strings)
218 'string-lessp)))
bba6564c 219 (concat open-group
c0056275
SM
220 (regexp-opt-group prefixes t t)
221 (regexp-quote
222 (concat (nreverse (string-to-list xiffus))))
bba6564c 223 close-group))
a1506d29 224
c0056275
SM
225 ;; Otherwise, divide the list into those that start with a
226 ;; particular letter and those that do not, and recurse on them.
75407435 227 (let* ((char (substring-no-properties (car strings) 0 1))
91fc05b1 228 (half1 (all-completions char strings))
94abe30b 229 (half2 (nthcdr (length half1) strings)))
c0056275
SM
230 (concat open-group
231 (regexp-opt-group half1)
232 "\\|" (regexp-opt-group half2)
233 close-group))))))))))
234
56329bc5
RS
235
236(defun regexp-opt-charset (chars)
55802e4a
CY
237 "Return a regexp to match a character in CHARS.
238CHARS should be a list of characters."
56329bc5
RS
239 ;; The basic idea is to find character ranges. Also we take care in the
240 ;; position of character set meta characters in the character set regexp.
241 ;;
5cda4b07
SM
242 (let* ((charmap (make-char-table 'case-table))
243 (start -1) (end -2)
56329bc5
RS
244 (charset "")
245 (bracket "") (dash "") (caret ""))
246 ;;
247 ;; Make a character map but extract character set meta characters.
5cda4b07 248 (dolist (char chars)
c505aaeb
CY
249 (cond
250 ((eq char ?\])
251 (setq bracket "]"))
252 ((eq char ?^)
253 (setq caret "^"))
254 ((eq char ?-)
255 (setq dash "-"))
256 (t
257 (aset charmap char t))))
56329bc5
RS
258 ;;
259 ;; Make a character set from the map using ranges where applicable.
5cda4b07
SM
260 (map-char-table
261 (lambda (c v)
262 (when v
6466bb34
KH
263 (if (consp c)
264 (if (= (1- (car c)) end) (setq end (cdr c))
265 (if (> end (+ start 2))
266 (setq charset (format "%s%c-%c" charset start end))
267 (while (>= end start)
268 (setq charset (format "%s%c" charset start))
c505aaeb 269 (setq start (1+ start))))
6466bb34
KH
270 (setq start (car c) end (cdr c)))
271 (if (= (1- c) end) (setq end c)
272 (if (> end (+ start 2))
5cda4b07
SM
273 (setq charset (format "%s%c-%c" charset start end))
274 (while (>= end start)
275 (setq charset (format "%s%c" charset start))
c505aaeb 276 (setq start (1+ start))))
6466bb34 277 (setq start c end c)))))
5cda4b07
SM
278 charmap)
279 (when (>= end start)
280 (if (> end (+ start 2))
281 (setq charset (format "%s%c-%c" charset start end))
282 (while (>= end start)
283 (setq charset (format "%s%c" charset start))
c505aaeb 284 (setq start (1+ start)))))
56329bc5
RS
285 ;;
286 ;; Make sure a caret is not first and a dash is first or last.
287 (if (and (string-equal charset "") (string-equal bracket ""))
bf4906d7
CD
288 (if (string-equal dash "")
289 "\\^" ; [^] is not a valid regexp
290 (concat "[" dash caret "]"))
56329bc5
RS
291 (concat "[" bracket charset caret dash "]"))))
292
293(provide 'regexp-opt)
294
295;;; regexp-opt.el ends here