regexp-opt.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. (eval-when-compile
  123. (require 'cl))
  124. (defun regexp-opt-group (strings &optional paren lax)
  125. "Return a regexp to match a string in the sorted list STRINGS.
  126. If PAREN non-nil, output regexp parentheses around returned regexp.
  127. If LAX non-nil, don't output parentheses if it doesn't require them.
  128. Merges keywords to avoid backtracking in Emacs's regexp matcher."
  129. ;; The basic idea is to find the shortest common prefix or suffix, remove it
  130. ;; and recurse. If there is no prefix, we divide the list into two so that
  131. ;; \(at least) one half will have at least a one-character common prefix.
  132. ;; Also we delay the addition of grouping parenthesis as long as possible
  133. ;; until we're sure we need them, and try to remove one-character sequences
  134. ;; so we can use character sets rather than grouping parenthesis.
  135. (let* ((open-group (cond ((stringp paren) paren) (paren "\\(?:") (t "")))
  136. (close-group (if paren "\\)" ""))
  137. (open-charset (if lax "" open-group))
  138. (close-charset (if lax "" close-group)))
  139. (cond
  140. ;;
  141. ;; If there are no strings, just return the empty string.
  142. ((= (length strings) 0)
  143. "")
  144. ;;
  145. ;; If there is only one string, just return it.
  146. ((= (length strings) 1)
  147. (if (= (length (car strings)) 1)
  148. (concat open-charset (regexp-quote (car strings)) close-charset)
  149. (concat open-group (regexp-quote (car strings)) close-group)))
  150. ;;
  151. ;; If there is an empty string, remove it and recurse on the rest.
  152. ((= (length (car strings)) 0)
  153. (concat open-charset
  154. (regexp-opt-group (cdr strings) t t) "?"
  155. close-charset))
  156. ;;
  157. ;; If there are several one-char strings, use charsets
  158. ((and (= (length (car strings)) 1)
  159. (let ((strs (cdr strings)))
  160. (while (and strs (/= (length (car strs)) 1))
  161. (pop strs))
  162. strs))
  163. (let (letters rest)
  164. ;; Collect one-char strings
  165. (dolist (s strings)
  166. (if (= (length s) 1) (push (string-to-char s) letters) (push s rest)))
  167. (if rest
  168. ;; several one-char strings: take them and recurse
  169. ;; on the rest (first so as to match the longest).
  170. (concat open-group
  171. (regexp-opt-group (nreverse rest))
  172. "\\|" (regexp-opt-charset letters)
  173. close-group)
  174. ;; all are one-char strings: just return a character set.
  175. (concat open-charset
  176. (regexp-opt-charset letters)
  177. close-charset))))
  178. ;;
  179. ;; We have a list of different length strings.
  180. (t
  181. (let ((prefix (try-completion "" strings)))
  182. (if (> (length prefix) 0)
  183. ;; common prefix: take it and recurse on the suffixes.
  184. (let* ((n (length prefix))
  185. (suffixes (mapcar (lambda (s) (substring s n)) strings)))
  186. (concat open-group
  187. (regexp-quote prefix)
  188. (regexp-opt-group suffixes t t)
  189. close-group))
  190. (let* ((sgnirts (mapcar (lambda (s)
  191. (concat (nreverse (string-to-list s))))
  192. strings))
  193. (xiffus (try-completion "" sgnirts)))
  194. (if (> (length xiffus) 0)
  195. ;; common suffix: take it and recurse on the prefixes.
  196. (let* ((n (- (length xiffus)))
  197. (prefixes
  198. ;; Sorting is necessary in cases such as ("ad" "d").
  199. (sort (mapcar (lambda (s) (substring s 0 n)) strings)
  200. 'string-lessp)))
  201. (concat open-group
  202. (regexp-opt-group prefixes t t)
  203. (regexp-quote
  204. (concat (nreverse (string-to-list xiffus))))
  205. close-group))
  206. ;; Otherwise, divide the list into those that start with a
  207. ;; particular letter and those that do not, and recurse on them.
  208. (let* ((char (substring-no-properties (car strings) 0 1))
  209. (half1 (all-completions char strings))
  210. (half2 (nthcdr (length half1) strings)))
  211. (concat open-group
  212. (regexp-opt-group half1)
  213. "\\|" (regexp-opt-group half2)
  214. close-group))))))))))
  215. (defun regexp-opt-charset (chars)
  216. "Return a regexp to match a character in CHARS."
  217. ;; The basic idea is to find character ranges. Also we take care in the
  218. ;; position of character set meta characters in the character set regexp.
  219. ;;
  220. (let* ((charmap (make-char-table 'case-table))
  221. (start -1) (end -2)
  222. (charset "")
  223. (bracket "") (dash "") (caret ""))
  224. ;;
  225. ;; Make a character map but extract character set meta characters.
  226. (dolist (char chars)
  227. (case char
  228. (?\]
  229. (setq bracket "]"))
  230. (?^
  231. (setq caret "^"))
  232. (?-
  233. (setq dash "-"))
  234. (otherwise
  235. (aset charmap char t))))
  236. ;;
  237. ;; Make a character set from the map using ranges where applicable.
  238. (map-char-table
  239. (lambda (c v)
  240. (when v
  241. (if (consp c)
  242. (if (= (1- (car c)) end) (setq end (cdr c))
  243. (if (> end (+ start 2))
  244. (setq charset (format "%s%c-%c" charset start end))
  245. (while (>= end start)
  246. (setq charset (format "%s%c" charset start))
  247. (incf start)))
  248. (setq start (car c) end (cdr c)))
  249. (if (= (1- c) end) (setq end c)
  250. (if (> end (+ start 2))
  251. (setq charset (format "%s%c-%c" charset start end))
  252. (while (>= end start)
  253. (setq charset (format "%s%c" charset start))
  254. (incf start)))
  255. (setq start c end c)))))
  256. charmap)
  257. (when (>= end start)
  258. (if (> end (+ start 2))
  259. (setq charset (format "%s%c-%c" charset start end))
  260. (while (>= end start)
  261. (setq charset (format "%s%c" charset start))
  262. (incf start))))
  263. ;;
  264. ;; Make sure a caret is not first and a dash is first or last.
  265. (if (and (string-equal charset "") (string-equal bracket ""))
  266. (concat "[" dash caret "]")
  267. (concat "[" bracket charset caret dash "]"))))
  268. (provide 'regexp-opt)
  269. ;;; regexp-opt.el ends here