regexp-opt.el 11 KB

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