* net/tramp-sh.el (tramp-do-file-attributes-with-stat)
[bpt/emacs.git] / lisp / emacs-lisp / regexp-opt.el
1 ;;; regexp-opt.el --- generate efficient regexps to match strings
2
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
4 ;; 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Simon Marshall <simon@gnu.org>
7 ;; Maintainer: FSF
8 ;; Keywords: strings, regexps, extensions
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
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
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; The "opt" in "regexp-opt" stands for "optim\\(al\\|i[sz]e\\)".
28 ;;
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:
31 ;;
32 ;; (regexp-opt strings)
33 ;;
34 ;; is equivalent to, but more efficient than, the regexp generated by:
35 ;;
36 ;; (mapconcat 'regexp-quote strings "\\|")
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 ;;
48 ;; Searching using the above example `regexp-opt' regexp takes approximately
49 ;; two-thirds of the time taken using the equivalent `mapconcat' regexp.
50
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 ;;
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
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.
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.
84 \f
85 ;;; Code:
86
87 ;;;###autoload
88 (defun regexp-opt (strings &optional paren)
89 "Return a regexp to match a string in the list STRINGS.
90 Each string should be unique in STRINGS and should not contain any regexps,
91 quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
92 is enclosed by at least one regexp grouping construct.
93 The returned regexp is typically more efficient than the equivalent regexp:
94
95 (let ((open (if PAREN \"\\\\(\" \"\")) (close (if PAREN \"\\\\)\" \"\")))
96 (concat open (mapconcat 'regexp-quote STRINGS \"\\\\|\") close))
97
98 If PAREN is `words', then the resulting regexp is additionally surrounded
99 by \\=\\< and \\>.
100 If PAREN is `symbols', then the resulting regexp is additionally surrounded
101 by \\=\\_< and \\_>."
102 (save-match-data
103 ;; Recurse on the sorted list.
104 (let* ((max-lisp-eval-depth 10000)
105 (max-specpdl-size 10000)
106 (completion-ignore-case nil)
107 (completion-regexp-list nil)
108 (open (cond ((stringp paren) paren) (paren "\\(")))
109 (sorted-strings (delete-dups
110 (sort (copy-sequence strings) 'string-lessp)))
111 (re (regexp-opt-group sorted-strings (or open t) (not open))))
112 (cond ((eq paren 'words)
113 (concat "\\<" re "\\>"))
114 ((eq paren 'symbols)
115 (concat "\\_<" re "\\_>"))
116 (t re)))))
117
118 ;;;###autoload
119 (defun regexp-opt-depth (regexp)
120 "Return the depth of REGEXP.
121 This means the number of non-shy regexp grouping constructs
122 \(parenthesized expressions) in REGEXP."
123 (save-match-data
124 ;; Hack to signal an error if REGEXP does not have balanced parentheses.
125 (string-match regexp "")
126 ;; Count the number of open parentheses in REGEXP.
127 (let ((count 0) start last)
128 (while (string-match "\\\\(\\(\\?[0-9]*:\\)?" regexp start)
129 (setq start (match-end 0)) ; Start of next search.
130 (when (and (not (match-beginning 1))
131 (subregexp-context-p regexp (match-beginning 0) last))
132 ;; It's not a shy group and it's not inside brackets or after
133 ;; a backslash: it's really a group-open marker.
134 (setq last start) ; Speed up next regexp-opt-re-context-p.
135 (setq count (1+ count))))
136 count)))
137 \f
138 ;;; Workhorse functions.
139
140 (eval-when-compile
141 (require 'cl))
142
143 (defun regexp-opt-group (strings &optional paren lax)
144 ;; Return a regexp to match a string in the sorted list STRINGS.
145 ;; If PAREN non-nil, output regexp parentheses around returned regexp.
146 ;; If LAX non-nil, don't output parentheses if it doesn't require them.
147 ;; Merges keywords to avoid backtracking in Emacs' regexp matcher.
148
149 ;; The basic idea is to find the shortest common prefix or suffix, remove it
150 ;; and recurse. If there is no prefix, we divide the list into two so that
151 ;; \(at least) one half will have at least a one-character common prefix.
152
153 ;; Also we delay the addition of grouping parenthesis as long as possible
154 ;; until we're sure we need them, and try to remove one-character sequences
155 ;; so we can use character sets rather than grouping parenthesis.
156 (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
157 (close-group (if paren "\\)" ""))
158 (open-charset (if lax "" open-group))
159 (close-charset (if lax "" close-group)))
160 (cond
161 ;;
162 ;; If there are no strings, just return the empty string.
163 ((= (length strings) 0)
164 "")
165 ;;
166 ;; If there is only one string, just return it.
167 ((= (length strings) 1)
168 (if (= (length (car strings)) 1)
169 (concat open-charset (regexp-quote (car strings)) close-charset)
170 (concat open-group (regexp-quote (car strings)) close-group)))
171 ;;
172 ;; If there is an empty string, remove it and recurse on the rest.
173 ((= (length (car strings)) 0)
174 (concat open-charset
175 (regexp-opt-group (cdr strings) t t) "?"
176 close-charset))
177 ;;
178 ;; If there are several one-char strings, use charsets
179 ((and (= (length (car strings)) 1)
180 (let ((strs (cdr strings)))
181 (while (and strs (/= (length (car strs)) 1))
182 (pop strs))
183 strs))
184 (let (letters rest)
185 ;; Collect one-char strings
186 (dolist (s strings)
187 (if (= (length s) 1) (push (string-to-char s) letters) (push s rest)))
188
189 (if rest
190 ;; several one-char strings: take them and recurse
191 ;; on the rest (first so as to match the longest).
192 (concat open-group
193 (regexp-opt-group (nreverse rest))
194 "\\|" (regexp-opt-charset letters)
195 close-group)
196 ;; all are one-char strings: just return a character set.
197 (concat open-charset
198 (regexp-opt-charset letters)
199 close-charset))))
200 ;;
201 ;; We have a list of different length strings.
202 (t
203 (let ((prefix (try-completion "" strings)))
204 (if (> (length prefix) 0)
205 ;; common prefix: take it and recurse on the suffixes.
206 (let* ((n (length prefix))
207 (suffixes (mapcar (lambda (s) (substring s n)) strings)))
208 (concat open-group
209 (regexp-quote prefix)
210 (regexp-opt-group suffixes t t)
211 close-group))
212
213 (let* ((sgnirts (mapcar (lambda (s)
214 (concat (nreverse (string-to-list s))))
215 strings))
216 (xiffus (try-completion "" sgnirts)))
217 (if (> (length xiffus) 0)
218 ;; common suffix: take it and recurse on the prefixes.
219 (let* ((n (- (length xiffus)))
220 (prefixes
221 ;; Sorting is necessary in cases such as ("ad" "d").
222 (sort (mapcar (lambda (s) (substring s 0 n)) strings)
223 'string-lessp)))
224 (concat open-group
225 (regexp-opt-group prefixes t t)
226 (regexp-quote
227 (concat (nreverse (string-to-list xiffus))))
228 close-group))
229
230 ;; Otherwise, divide the list into those that start with a
231 ;; particular letter and those that do not, and recurse on them.
232 (let* ((char (substring-no-properties (car strings) 0 1))
233 (half1 (all-completions char strings))
234 (half2 (nthcdr (length half1) strings)))
235 (concat open-group
236 (regexp-opt-group half1)
237 "\\|" (regexp-opt-group half2)
238 close-group))))))))))
239
240
241 (defun regexp-opt-charset (chars)
242 ;;
243 ;; Return a regexp to match a character in CHARS.
244 ;;
245 ;; The basic idea is to find character ranges. Also we take care in the
246 ;; position of character set meta characters in the character set regexp.
247 ;;
248 (let* ((charmap (make-char-table 'case-table))
249 (start -1) (end -2)
250 (charset "")
251 (bracket "") (dash "") (caret ""))
252 ;;
253 ;; Make a character map but extract character set meta characters.
254 (dolist (char chars)
255 (case char
256 (?\]
257 (setq bracket "]"))
258 (?^
259 (setq caret "^"))
260 (?-
261 (setq dash "-"))
262 (otherwise
263 (aset charmap char t))))
264 ;;
265 ;; Make a character set from the map using ranges where applicable.
266 (map-char-table
267 (lambda (c v)
268 (when v
269 (if (consp c)
270 (if (= (1- (car c)) end) (setq end (cdr c))
271 (if (> end (+ start 2))
272 (setq charset (format "%s%c-%c" charset start end))
273 (while (>= end start)
274 (setq charset (format "%s%c" charset start))
275 (incf start)))
276 (setq start (car c) end (cdr c)))
277 (if (= (1- c) end) (setq end c)
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)))
283 (setq start c end c)))))
284 charmap)
285 (when (>= end start)
286 (if (> end (+ start 2))
287 (setq charset (format "%s%c-%c" charset start end))
288 (while (>= end start)
289 (setq charset (format "%s%c" charset start))
290 (incf start))))
291 ;;
292 ;; Make sure a caret is not first and a dash is first or last.
293 (if (and (string-equal charset "") (string-equal bracket ""))
294 (concat "[" dash caret "]")
295 (concat "[" bracket charset caret dash "]"))))
296
297 (provide 'regexp-opt)
298
299 ;; arch-tag: 6c5a66f4-29af-4fd6-8c3b-4b554d5b4370
300 ;;; regexp-opt.el ends here