Fix Bug#32983
[emacs.git] / lisp / emacs-lisp / rx.el
blobbb759011513a5dc4d5fe8e298493e621cca0bed6
1 ;;; rx.el --- sexp notation for regular expressions
3 ;; Copyright (C) 2001-2018 Free Software Foundation, Inc.
5 ;; Author: Gerd Moellmann <gerd@gnu.org>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: strings, regexps, extensions
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This is another implementation of sexp-form regular expressions.
27 ;; It was unfortunately written without being aware of the Sregex
28 ;; package coming with Emacs, but as things stand, Rx completely
29 ;; covers all regexp features, which Sregex doesn't, doesn't suffer
30 ;; from the bugs mentioned in the commentary section of Sregex, and
31 ;; uses a nicer syntax (IMHO, of course :-).
33 ;; This significantly extended version of the original, is almost
34 ;; compatible with Sregex. The only incompatibility I (fx) know of is
35 ;; that the `repeat' form can't have multiple regexp args.
37 ;; Now alternative forms are provided for a degree of compatibility
38 ;; with Olin Shivers' attempted definitive SRE notation. SRE forms
39 ;; not catered for include: dsm, uncase, w/case, w/nocase, ,@<exp>,
40 ;; ,<exp>, (word ...), word+, posix-string, and character class forms.
41 ;; Some forms are inconsistent with SRE, either for historical reasons
42 ;; or because of the implementation -- simple translation into Emacs
43 ;; regexp strings. These include: any, word. Also, case-sensitivity
44 ;; and greediness are controlled by variables external to the regexp,
45 ;; and you need to feed the forms to the `posix-' functions to get
46 ;; SRE's POSIX semantics. There are probably more difficulties.
48 ;; Rx translates a sexp notation for regular expressions into the
49 ;; usual string notation. The translation can be done at compile-time
50 ;; by using the `rx' macro. It can be done at run-time by calling
51 ;; function `rx-to-string'. See the documentation of `rx' for a
52 ;; complete description of the sexp notation.
54 ;; Some examples of string regexps and their sexp counterparts:
56 ;; "^[a-z]*"
57 ;; (rx (and line-start (0+ (in "a-z"))))
59 ;; "\n[^ \t]"
60 ;; (rx (and "\n" (not (any " \t"))))
62 ;; "\\*\\*\\* EOOH \\*\\*\\*\n"
63 ;; (rx "*** EOOH ***\n")
65 ;; "\\<\\(catch\\|finally\\)\\>[^_]"
66 ;; (rx (and word-start (submatch (or "catch" "finally")) word-end
67 ;; (not (any ?_))))
69 ;; "[ \t\n]*:\\([^:]+\\|$\\)"
70 ;; (rx (and (zero-or-more (in " \t\n")) ":"
71 ;; (submatch (or line-end (one-or-more (not (any ?:)))))))
73 ;; "^content-transfer-encoding:\\(\n?[\t ]\\)*quoted-printable\\(\n?[\t ]\\)*"
74 ;; (rx (and line-start
75 ;; "content-transfer-encoding:"
76 ;; (+ (? ?\n)) (any " \t")
77 ;; "quoted-printable"
78 ;; (+ (? ?\n)) (any " \t"))
80 ;; (concat "^\\(?:" something-else "\\)")
81 ;; (rx (and line-start (eval something-else))), statically or
82 ;; (rx-to-string '(and line-start ,something-else)), dynamically.
84 ;; (regexp-opt '(STRING1 STRING2 ...))
85 ;; (rx (or STRING1 STRING2 ...)), or in other words, `or' automatically
86 ;; calls `regexp-opt' as needed.
88 ;; "^;;\\s-*\n\\|^\n"
89 ;; (rx (or (and line-start ";;" (0+ space) ?\n)
90 ;; (and line-start ?\n)))
92 ;; "\\$[I]d: [^ ]+ \\([^ ]+\\) "
93 ;; (rx (and "$Id: "
94 ;; (1+ (not (in " ")))
95 ;; " "
96 ;; (submatch (1+ (not (in " "))))
97 ;; " "))
99 ;; "\\\\\\\\\\[\\w+"
100 ;; (rx (and ?\\ ?\\ ?\[ (1+ word)))
102 ;; etc.
104 ;;; History:
107 ;;; Code:
109 (require 'cl-lib)
111 ;; FIXME: support macros.
113 (defvar rx-constituents ;Not `const' because some modes extend it.
114 '((and . (rx-and 1 nil))
115 (seq . and) ; SRE
116 (: . and) ; SRE
117 (sequence . and) ; sregex
118 (or . (rx-or 1 nil))
119 (| . or) ; SRE
120 (not-newline . ".")
121 (nonl . not-newline) ; SRE
122 (anything . (rx-anything 0 nil))
123 (any . (rx-any 1 nil rx-check-any)) ; inconsistent with SRE
124 (any . ".") ; sregex
125 (in . any)
126 (char . any) ; sregex
127 (not-char . (rx-not-char 1 nil rx-check-any)) ; sregex
128 (not . (rx-not 1 1 rx-check-not))
129 (repeat . (rx-repeat 2 nil))
130 (= . (rx-= 2 nil)) ; SRE
131 (>= . (rx->= 2 nil)) ; SRE
132 (** . (rx-** 2 nil)) ; SRE
133 (submatch . (rx-submatch 1 nil)) ; SRE
134 (group . submatch) ; sregex
135 (submatch-n . (rx-submatch-n 2 nil))
136 (group-n . submatch-n)
137 (zero-or-more . (rx-kleene 1 nil))
138 (one-or-more . (rx-kleene 1 nil))
139 (zero-or-one . (rx-kleene 1 nil))
140 (\? . zero-or-one) ; SRE
141 (\?? . zero-or-one)
142 (* . zero-or-more) ; SRE
143 (*? . zero-or-more)
144 (0+ . zero-or-more)
145 (+ . one-or-more) ; SRE
146 (+? . one-or-more)
147 (1+ . one-or-more)
148 (optional . zero-or-one)
149 (opt . zero-or-one) ; sregex
150 (minimal-match . (rx-greedy 1 1))
151 (maximal-match . (rx-greedy 1 1))
152 (backref . (rx-backref 1 1 rx-check-backref))
153 (line-start . "^")
154 (bol . line-start) ; SRE
155 (line-end . "$")
156 (eol . line-end) ; SRE
157 (string-start . "\\`")
158 (bos . string-start) ; SRE
159 (bot . string-start) ; sregex
160 (string-end . "\\'")
161 (eos . string-end) ; SRE
162 (eot . string-end) ; sregex
163 (buffer-start . "\\`")
164 (buffer-end . "\\'")
165 (point . "\\=")
166 (word-start . "\\<")
167 (bow . word-start) ; SRE
168 (word-end . "\\>")
169 (eow . word-end) ; SRE
170 (word-boundary . "\\b")
171 (not-word-boundary . "\\B") ; sregex
172 (symbol-start . "\\_<")
173 (symbol-end . "\\_>")
174 (syntax . (rx-syntax 1 1))
175 (not-syntax . (rx-not-syntax 1 1)) ; sregex
176 (category . (rx-category 1 1 rx-check-category))
177 (eval . (rx-eval 1 1))
178 (regexp . (rx-regexp 1 1 stringp))
179 (regex . regexp) ; sregex
180 (digit . "[[:digit:]]")
181 (numeric . digit) ; SRE
182 (num . digit) ; SRE
183 (control . "[[:cntrl:]]") ; SRE
184 (cntrl . control) ; SRE
185 (hex-digit . "[[:xdigit:]]") ; SRE
186 (hex . hex-digit) ; SRE
187 (xdigit . hex-digit) ; SRE
188 (blank . "[[:blank:]]") ; SRE
189 (graphic . "[[:graph:]]") ; SRE
190 (graph . graphic) ; SRE
191 (printing . "[[:print:]]") ; SRE
192 (print . printing) ; SRE
193 (alphanumeric . "[[:alnum:]]") ; SRE
194 (alnum . alphanumeric) ; SRE
195 (letter . "[[:alpha:]]")
196 (alphabetic . letter) ; SRE
197 (alpha . letter) ; SRE
198 (ascii . "[[:ascii:]]") ; SRE
199 (nonascii . "[[:nonascii:]]")
200 (lower . "[[:lower:]]") ; SRE
201 (lower-case . lower) ; SRE
202 (punctuation . "[[:punct:]]") ; SRE
203 (punct . punctuation) ; SRE
204 (space . "[[:space:]]") ; SRE
205 (whitespace . space) ; SRE
206 (white . space) ; SRE
207 (upper . "[[:upper:]]") ; SRE
208 (upper-case . upper) ; SRE
209 (word . "[[:word:]]") ; inconsistent with SRE
210 (wordchar . word) ; sregex
211 (not-wordchar . "\\W"))
212 "Alist of sexp form regexp constituents.
213 Each element of the alist has the form (SYMBOL . DEFN).
214 SYMBOL is a valid constituent of sexp regular expressions.
215 If DEFN is a string, SYMBOL is translated into DEFN.
216 If DEFN is a symbol, use the definition of DEFN, recursively.
217 Otherwise, DEFN must be a list (FUNCTION MIN-ARGS MAX-ARGS PREDICATE).
218 FUNCTION is used to produce code for SYMBOL. MIN-ARGS and MAX-ARGS
219 are the minimum and maximum number of arguments the function-form
220 sexp constituent SYMBOL may have in sexp regular expressions.
221 MAX-ARGS nil means no limit. PREDICATE, if specified, means that
222 all arguments must satisfy PREDICATE.")
225 (defconst rx-syntax
226 '((whitespace . ?-)
227 (punctuation . ?.)
228 (word . ?w)
229 (symbol . ?_)
230 (open-parenthesis . ?\()
231 (close-parenthesis . ?\))
232 (expression-prefix . ?\')
233 (string-quote . ?\")
234 (paired-delimiter . ?$)
235 (escape . ?\\)
236 (character-quote . ?/)
237 (comment-start . ?<)
238 (comment-end . ?>)
239 (string-delimiter . ?|)
240 (comment-delimiter . ?!))
241 "Alist mapping Rx syntax symbols to syntax characters.
242 Each entry has the form (SYMBOL . CHAR), where SYMBOL is a valid
243 symbol in `(syntax SYMBOL)', and CHAR is the syntax character
244 corresponding to SYMBOL, as it would be used with \\s or \\S in
245 regular expressions.")
248 (defconst rx-categories
249 '((consonant . ?0)
250 (base-vowel . ?1)
251 (upper-diacritical-mark . ?2)
252 (lower-diacritical-mark . ?3)
253 (tone-mark . ?4)
254 (symbol . ?5)
255 (digit . ?6)
256 (vowel-modifying-diacritical-mark . ?7)
257 (vowel-sign . ?8)
258 (semivowel-lower . ?9)
259 (not-at-end-of-line . ?<)
260 (not-at-beginning-of-line . ?>)
261 (alpha-numeric-two-byte . ?A)
262 (chinese-two-byte . ?C)
263 (chinse-two-byte . ?C) ;; A typo in Emacs 21.1-24.3.
264 (greek-two-byte . ?G)
265 (japanese-hiragana-two-byte . ?H)
266 (indian-two-byte . ?I)
267 (japanese-katakana-two-byte . ?K)
268 (korean-hangul-two-byte . ?N)
269 (cyrillic-two-byte . ?Y)
270 (combining-diacritic . ?^)
271 (ascii . ?a)
272 (arabic . ?b)
273 (chinese . ?c)
274 (ethiopic . ?e)
275 (greek . ?g)
276 (korean . ?h)
277 (indian . ?i)
278 (japanese . ?j)
279 (japanese-katakana . ?k)
280 (latin . ?l)
281 (lao . ?o)
282 (tibetan . ?q)
283 (japanese-roman . ?r)
284 (thai . ?t)
285 (vietnamese . ?v)
286 (hebrew . ?w)
287 (cyrillic . ?y)
288 (can-break . ?|))
289 "Alist mapping symbols to category characters.
290 Each entry has the form (SYMBOL . CHAR), where SYMBOL is a valid
291 symbol in `(category SYMBOL)', and CHAR is the category character
292 corresponding to SYMBOL, as it would be used with `\\c' or `\\C' in
293 regular expression strings.")
296 (defvar rx-greedy-flag t
297 "Non-nil means produce greedy regular expressions for `zero-or-one',
298 `zero-or-more', and `one-or-more'. Dynamically bound.")
301 (defun rx-info (op head)
302 "Return parsing/code generation info for OP.
303 If OP is the space character ASCII 32, return info for the symbol `?'.
304 If OP is the character `?', return info for the symbol `??'.
305 See also `rx-constituents'.
306 If HEAD is non-nil, then OP is the head of a sexp, otherwise it's
307 a standalone symbol."
308 (cond ((eq op ? ) (setq op '\?))
309 ((eq op ??) (setq op '\??)))
310 (let (old-op)
311 (while (and (not (null op)) (symbolp op))
312 (setq old-op op)
313 (setq op (cdr (assq op rx-constituents)))
314 (when (if head (stringp op) (consp op))
315 ;; We found something but of the wrong kind. Let's look for an
316 ;; alternate definition for the other case.
317 (let ((new-op
318 (cdr (assq old-op (cdr (memq (assq old-op rx-constituents)
319 rx-constituents))))))
320 (if (and new-op (not (if head (stringp new-op) (consp new-op))))
321 (setq op new-op))))))
325 (defun rx-check (form)
326 "Check FORM according to its car's parsing info."
327 (unless (listp form)
328 (error "rx `%s' needs argument(s)" form))
329 (let* ((rx (rx-info (car form) 'head))
330 (nargs (1- (length form)))
331 (min-args (nth 1 rx))
332 (max-args (nth 2 rx))
333 (type-pred (nth 3 rx)))
334 (when (and (not (null min-args))
335 (< nargs min-args))
336 (error "rx form `%s' requires at least %d args"
337 (car form) min-args))
338 (when (and (not (null max-args))
339 (> nargs max-args))
340 (error "rx form `%s' accepts at most %d args"
341 (car form) max-args))
342 (when (not (null type-pred))
343 (dolist (sub-form (cdr form))
344 (unless (funcall type-pred sub-form)
345 (error "rx form `%s' requires args satisfying `%s'"
346 (car form) type-pred))))))
349 (defun rx-group-if (regexp group)
350 "Put shy groups around REGEXP if seemingly necessary when GROUP
351 is non-nil."
352 (cond
353 ;; for some repetition
354 ((eq group '*) (if (rx-atomic-p regexp) (setq group nil)))
355 ;; for concatenation
356 ((eq group ':)
357 (if (rx-atomic-p
358 (if (string-match
359 "\\(?:[?*+]\\??\\|\\\\{[0-9]*,?[0-9]*\\\\}\\)\\'" regexp)
360 (substring regexp 0 (match-beginning 0))
361 regexp))
362 (setq group nil)))
363 ;; for OR
364 ((eq group '|) (setq group nil))
365 ;; do anyway
366 ((eq group t))
367 ((rx-atomic-p regexp t) (setq group nil)))
368 (if group
369 (concat "\\(?:" regexp "\\)")
370 regexp))
373 (defvar rx-parent)
374 ;; dynamically bound in some functions.
377 (defun rx-and (form)
378 "Parse and produce code from FORM.
379 FORM is of the form `(and FORM1 ...)'."
380 (rx-check form)
381 (rx-group-if
382 (mapconcat (lambda (x) (rx-form x ':)) (cdr form) nil)
383 (and (memq rx-parent '(* t)) rx-parent)))
386 (defun rx-or (form)
387 "Parse and produce code from FORM, which is `(or FORM1 ...)'."
388 (rx-check form)
389 (rx-group-if
390 (if (memq nil (mapcar 'stringp (cdr form)))
391 (mapconcat (lambda (x) (rx-form x '|)) (cdr form) "\\|")
392 (regexp-opt (cdr form)))
393 (and (memq rx-parent '(: * t)) rx-parent)))
396 (defun rx-anything (form)
397 "Match any character."
398 (if (consp form)
399 (error "rx `anything' syntax error: %s" form))
400 (rx-or (list 'or 'not-newline ?\n)))
403 (defun rx-any-delete-from-range (char ranges)
404 "Delete by side effect character CHAR from RANGES.
405 Only both edges of each range is checked."
406 (let (m)
407 (cond
408 ((memq char ranges) (setq ranges (delq char ranges)))
409 ((setq m (assq char ranges))
410 (if (eq (1+ char) (cdr m))
411 (setcar (memq m ranges) (1+ char))
412 (setcar m (1+ char))))
413 ((setq m (rassq char ranges))
414 (if (eq (1- char) (car m))
415 (setcar (memq m ranges) (1- char))
416 (setcdr m (1- char)))))
417 ranges))
420 (defun rx-any-condense-range (args)
421 "Condense by side effect ARGS as range for Rx `any'."
422 (let (str
424 ;; set STR list of all strings
425 ;; set L list of all ranges
426 (mapc (lambda (e) (cond ((stringp e) (push e str))
427 ((numberp e) (push (cons e e) l))
428 (t (push e l))))
429 args)
430 ;; condense overlapped ranges in L
431 (let ((tail (setq l (sort l #'car-less-than-car)))
433 (while (setq d (cdr tail))
434 (if (>= (cdar tail) (1- (caar d)))
435 (progn
436 (setcdr (car tail) (max (cdar tail) (cdar d)))
437 (setcdr tail (cdr d)))
438 (setq tail d))))
439 ;; Separate small ranges to single number, and delete dups.
440 (nconc
441 (apply #'nconc
442 (mapcar (lambda (e)
443 (cond
444 ((= (car e) (cdr e)) (list (car e)))
445 ((= (1+ (car e)) (cdr e)) (list (car e) (cdr e)))
446 ((list e))))
448 (delete-dups str))))
451 (defun rx-check-any-string (str)
452 "Check string argument STR for Rx `any'."
453 (let ((i 0)
454 c1 c2 l)
455 (if (= 0 (length str))
456 (error "String arg for Rx `any' must not be empty"))
457 (while (string-match ".-." str i)
458 ;; string before range: convert it to characters
459 (if (< i (match-beginning 0))
460 (setq l (nconc
462 (append (substring str i (match-beginning 0)) nil))))
463 ;; range
464 (setq i (match-end 0)
465 c1 (aref str (match-beginning 0))
466 c2 (aref str (1- i)))
467 (cond
468 ((< c1 c2) (setq l (nconc l (list (cons c1 c2)))))
469 ((= c1 c2) (setq l (nconc l (list c1))))))
470 ;; rest?
471 (if (< i (length str))
472 (setq l (nconc l (append (substring str i) nil))))
476 (defun rx-check-any (arg)
477 "Check arg ARG for Rx `any'."
478 (cond
479 ((integerp arg) (list arg))
480 ((symbolp arg)
481 (let ((translation (condition-case nil
482 (rx-form arg)
483 (error nil))))
484 (if (or (null translation)
485 (null (string-match "\\`\\[\\[:[-a-z]+:\\]\\]\\'" translation)))
486 (error "Invalid char class `%s' in Rx `any'" arg))
487 (list (substring translation 1 -1)))) ; strip outer brackets
488 ((and (integerp (car-safe arg)) (integerp (cdr-safe arg)))
489 (list arg))
490 ((stringp arg) (rx-check-any-string arg))
491 ((error
492 "rx `any' requires string, character, char pair or char class args"))))
495 (defun rx-any (form)
496 "Parse and produce code from FORM, which is `(any ARG ...)'.
497 ARG is optional."
498 (rx-check form)
499 (let* ((args (rx-any-condense-range
500 (apply
501 #'nconc
502 (mapcar #'rx-check-any (cdr form)))))
505 (cond
506 ;; single close bracket
507 ;; => "[]...-]" or "[]...--.]"
508 ((memq ?\] args)
509 ;; set ] at the beginning
510 (setq args (cons ?\] (delq ?\] args)))
511 ;; set - at the end
512 (if (or (memq ?- args) (assq ?- args))
513 (setq args (nconc (rx-any-delete-from-range ?- args)
514 (list ?-)))))
515 ;; close bracket starts a range
516 ;; => "[]-....-]" or "[]-.--....]"
517 ((setq m (assq ?\] args))
518 ;; bring it to the beginning
519 (setq args (cons m (delq m args)))
520 (cond ((memq ?- args)
521 ;; to the end
522 (setq args (nconc (delq ?- args) (list ?-))))
523 ((setq m (assq ?- args))
524 ;; next to the bracket's range, make the second range
525 (setcdr args (cons m (delq m (cdr args)))))))
526 ;; bracket in the end range
527 ;; => "[]...-]"
528 ((setq m (rassq ?\] args))
529 ;; set ] at the beginning
530 (setq args (cons ?\] (rx-any-delete-from-range ?\] args)))
531 ;; set - at the end
532 (if (or (memq ?- args) (assq ?- args))
533 (setq args (nconc (rx-any-delete-from-range ?- args)
534 (list ?-)))))
535 ;; {no close bracket appears}
537 ;; bring single bar to the beginning
538 ((memq ?- args)
539 (setq args (cons ?- (delq ?- args))))
540 ;; bar start a range, bring it to the beginning
541 ((setq m (assq ?- args))
542 (setq args (cons m (delq m args))))
544 ;; hat at the beginning?
545 ((or (eq (car args) ?^) (eq (car-safe (car args)) ?^))
546 (setq args (if (cdr args)
547 `(,(cadr args) ,(car args) ,@(cddr args))
548 (nconc (rx-any-delete-from-range ?^ args)
549 (list ?^))))))
550 ;; some 1-char?
551 (if (and (null (cdr args)) (numberp (car args))
552 (or (= 1 (length
553 (setq s (regexp-quote (string (car args))))))
554 (and (equal (car args) ?^) ;; unnecessary predicate?
555 (null (eq rx-parent '!)))))
557 (concat "["
558 (mapconcat
559 (lambda (e) (cond
560 ((numberp e) (string e))
561 ((consp e)
562 (if (and (= (1+ (car e)) (cdr e))
563 ;; rx-any-condense-range should
564 ;; prevent this case from happening.
565 (null (memq (car e) '(?\] ?-)))
566 (null (memq (cdr e) '(?\] ?-))))
567 (string (car e) (cdr e))
568 (string (car e) ?- (cdr e))))
569 (e)))
570 args
571 nil)
572 "]"))))
575 (defun rx-check-not (arg)
576 "Check arg ARG for Rx `not'."
577 (unless (or (and (symbolp arg)
578 (string-match "\\`\\[\\[:[-a-z]+:\\]\\]\\'"
579 (condition-case nil
580 (rx-form arg)
581 (error ""))))
582 (eq arg 'word-boundary)
583 (and (consp arg)
584 (memq (car arg) '(not any in syntax category))))
585 (error "rx `not' syntax error: %s" arg))
589 (defun rx-not (form)
590 "Parse and produce code from FORM. FORM is `(not ...)'."
591 (rx-check form)
592 (let ((result (rx-form (cadr form) '!))
593 case-fold-search)
594 (cond ((string-match "\\`\\[^" result)
595 (cond
596 ((equal result "[^]") "[^^]")
597 ((and (= (length result) 4) (null (eq rx-parent '!)))
598 (regexp-quote (substring result 2 3)))
599 ((concat "[" (substring result 2)))))
600 ((eq ?\[ (aref result 0))
601 (concat "[^" (substring result 1)))
602 ((string-match "\\`\\\\[scbw]" result)
603 (concat (upcase (substring result 0 2))
604 (substring result 2)))
605 ((string-match "\\`\\\\[SCBW]" result)
606 (concat (downcase (substring result 0 2))
607 (substring result 2)))
609 (concat "[^" result "]")))))
612 (defun rx-not-char (form)
613 "Parse and produce code from FORM. FORM is `(not-char ...)'."
614 (rx-check form)
615 (rx-not `(not (in ,@(cdr form)))))
618 (defun rx-not-syntax (form)
619 "Parse and produce code from FORM. FORM is `(not-syntax SYNTAX)'."
620 (rx-check form)
621 (rx-not `(not (syntax ,@(cdr form)))))
624 (defun rx-trans-forms (form &optional skip)
625 "If FORM's length is greater than two, transform it to length two.
626 A form (HEAD REST ...) becomes (HEAD (and REST ...)).
627 If SKIP is non-nil, allow that number of items after the head, i.e.
628 `(= N REST ...)' becomes `(= N (and REST ...))' if SKIP is 1."
629 (unless skip (setq skip 0))
630 (let ((tail (nthcdr (1+ skip) form)))
631 (if (= (length tail) 1)
632 form
633 (let ((form (copy-sequence form)))
634 (setcdr (nthcdr skip form) (list (cons 'and tail)))
635 form))))
638 (defun rx-= (form)
639 "Parse and produce code from FORM `(= N ...)'."
640 (rx-check form)
641 (setq form (rx-trans-forms form 1))
642 (unless (and (integerp (nth 1 form))
643 (> (nth 1 form) 0))
644 (error "rx `=' requires positive integer first arg"))
645 (format "%s\\{%d\\}" (rx-form (nth 2 form) '*) (nth 1 form)))
648 (defun rx->= (form)
649 "Parse and produce code from FORM `(>= N ...)'."
650 (rx-check form)
651 (setq form (rx-trans-forms form 1))
652 (unless (and (integerp (nth 1 form))
653 (> (nth 1 form) 0))
654 (error "rx `>=' requires positive integer first arg"))
655 (format "%s\\{%d,\\}" (rx-form (nth 2 form) '*) (nth 1 form)))
658 (defun rx-** (form)
659 "Parse and produce code from FORM `(** N M ...)'."
660 (rx-check form)
661 (rx-form (cons 'repeat (cdr (rx-trans-forms form 2))) '*))
664 (defun rx-repeat (form)
665 "Parse and produce code from FORM.
666 FORM is either `(repeat N FORM1)' or `(repeat N M FORMS...)'."
667 (rx-check form)
668 (if (> (length form) 4)
669 (setq form (rx-trans-forms form 2)))
670 (if (null (nth 2 form))
671 (setq form (cons (nth 0 form) (cons (nth 1 form) (nthcdr 3 form)))))
672 (cond ((= (length form) 3)
673 (unless (and (integerp (nth 1 form))
674 (> (nth 1 form) 0))
675 (error "rx `repeat' requires positive integer first arg"))
676 (format "%s\\{%d\\}" (rx-form (nth 2 form) '*) (nth 1 form)))
677 ((or (not (integerp (nth 2 form)))
678 (< (nth 2 form) 0)
679 (not (integerp (nth 1 form)))
680 (< (nth 1 form) 0)
681 (< (nth 2 form) (nth 1 form)))
682 (error "rx `repeat' range error"))
684 (format "%s\\{%d,%d\\}" (rx-form (nth 3 form) '*)
685 (nth 1 form) (nth 2 form)))))
688 (defun rx-submatch (form)
689 "Parse and produce code from FORM, which is `(submatch ...)'."
690 (concat "\\("
691 (if (= 2 (length form))
692 ;; Only one sub-form.
693 (rx-form (cadr form))
694 ;; Several sub-forms implicitly concatenated.
695 (mapconcat (lambda (re) (rx-form re ':)) (cdr form) nil))
696 "\\)"))
698 (defun rx-submatch-n (form)
699 "Parse and produce code from FORM, which is `(submatch-n N ...)'."
700 (let ((n (nth 1 form)))
701 (concat "\\(?" (number-to-string n) ":"
702 (if (= 3 (length form))
703 ;; Only one sub-form.
704 (rx-form (nth 2 form))
705 ;; Several sub-forms implicitly concatenated.
706 (mapconcat (lambda (re) (rx-form re ':)) (cddr form) nil))
707 "\\)")))
709 (defun rx-backref (form)
710 "Parse and produce code from FORM, which is `(backref N)'."
711 (rx-check form)
712 (format "\\%d" (nth 1 form)))
714 (defun rx-check-backref (arg)
715 "Check arg ARG for Rx `backref'."
716 (or (and (integerp arg) (>= arg 1) (<= arg 9))
717 (error "rx `backref' requires numeric 1<=arg<=9: %s" arg)))
719 (defun rx-kleene (form)
720 "Parse and produce code from FORM.
721 FORM is `(OP FORM1)', where OP is one of the `zero-or-one',
722 `zero-or-more' etc. operators.
723 If OP is one of `*', `+', `?', produce a greedy regexp.
724 If OP is one of `*?', `+?', `??', produce a non-greedy regexp.
725 If OP is anything else, produce a greedy regexp if `rx-greedy-flag'
726 is non-nil."
727 (rx-check form)
728 (setq form (rx-trans-forms form))
729 (let ((suffix (cond ((memq (car form) '(* + ?\s)) "")
730 ((memq (car form) '(*? +? ??)) "?")
731 (rx-greedy-flag "")
732 (t "?")))
733 (op (cond ((memq (car form) '(* *? 0+ zero-or-more)) "*")
734 ((memq (car form) '(+ +? 1+ one-or-more)) "+")
735 (t "?"))))
736 (rx-group-if
737 (concat (rx-form (cadr form) '*) op suffix)
738 (and (memq rx-parent '(t *)) rx-parent))))
741 (defun rx-atomic-p (r &optional lax)
742 "Return non-nil if regexp string R is atomic.
743 An atomic regexp R is one such that a suffix operator
744 appended to R will apply to all of R. For example, \"a\"
745 \"[abc]\" and \"\\(ab\\|ab*c\\)\" are atomic and \"ab\",
746 \"[ab]c\", and \"ab\\|ab*c\" are not atomic.
748 This function may return false negatives, but it will not
749 return false positives. It is nevertheless useful in
750 situations where an efficiency shortcut can be taken only if a
751 regexp is atomic. The function can be improved to detect
752 more cases of atomic regexps. Presently, this function
753 detects the following categories of atomic regexp;
755 a group or shy group: \\(...\\)
756 a character class: [...]
757 a single character: a
759 On the other hand, false negatives will be returned for
760 regexps that are atomic but end in operators, such as
761 \"a+\". I think these are rare. Probably such cases could
762 be detected without much effort. A guarantee of no false
763 negatives would require a theoretic specification of the set
764 of all atomic regexps."
765 (let ((l (length r)))
766 (cond
767 ((<= l 1))
768 ((= l 2) (= (aref r 0) ?\\))
769 ((= l 3) (string-match "\\`\\(?:\\\\[cCsS_]\\|\\[[^^]\\]\\)" r))
770 ((null lax)
771 (cond
772 ((string-match "\\`\\[^?\]?\\(?:\\[:[a-z]+:]\\|[^]]\\)*\\]\\'" r))
773 ((string-match "\\`\\\\(\\(?:[^\\]\\|\\\\[^)]\\)*\\\\)\\'" r)))))))
776 (defun rx-syntax (form)
777 "Parse and produce code from FORM, which is `(syntax SYMBOL)'."
778 (rx-check form)
779 (let* ((sym (cadr form))
780 (syntax (cdr (assq sym rx-syntax))))
781 (unless syntax
782 ;; Try sregex compatibility.
783 (cond
784 ((characterp sym) (setq syntax sym))
785 ((symbolp sym)
786 (let ((name (symbol-name sym)))
787 (if (= 1 (length name))
788 (setq syntax (aref name 0))))))
789 (unless syntax
790 (error "Unknown rx syntax `%s'" sym)))
791 (format "\\s%c" syntax)))
794 (defun rx-check-category (form)
795 "Check the argument FORM of a `(category FORM)'."
796 (unless (or (integerp form)
797 (cdr (assq form rx-categories)))
798 (error "Unknown category `%s'" form))
802 (defun rx-category (form)
803 "Parse and produce code from FORM, which is `(category SYMBOL)'."
804 (rx-check form)
805 (let ((char (if (integerp (cadr form))
806 (cadr form)
807 (cdr (assq (cadr form) rx-categories)))))
808 (format "\\c%c" char)))
811 (defun rx-eval (form)
812 "Parse and produce code from FORM, which is `(eval FORM)'."
813 (rx-check form)
814 (rx-form (eval (cadr form)) rx-parent))
817 (defun rx-greedy (form)
818 "Parse and produce code from FORM.
819 If FORM is `(minimal-match FORM1)', non-greedy versions of `*',
820 `+', and `?' operators will be used in FORM1. If FORM is
821 `(maximal-match FORM1)', greedy operators will be used."
822 (rx-check form)
823 (let ((rx-greedy-flag (eq (car form) 'maximal-match)))
824 (rx-form (cadr form) rx-parent)))
827 (defun rx-regexp (form)
828 "Parse and produce code from FORM, which is `(regexp STRING)'."
829 (rx-check form)
830 (rx-group-if (cadr form) rx-parent))
833 (defun rx-form (form &optional rx-parent)
834 "Parse and produce code for regular expression FORM.
835 FORM is a regular expression in sexp form.
836 RX-PARENT shows which type of expression calls and controls putting of
837 shy groups around the result and some more in other functions."
838 (cond
839 ((stringp form)
840 (rx-group-if (regexp-quote form)
841 (if (and (eq rx-parent '*) (< 1 (length form)))
842 rx-parent)))
843 ((integerp form)
844 (regexp-quote (char-to-string form)))
845 ((symbolp form)
846 (let ((info (rx-info form nil)))
847 (cond ((stringp info)
848 info)
849 ((null info)
850 (error "Unknown rx form `%s'" form))
852 (funcall (nth 0 info) form)))))
853 ((consp form)
854 (let ((info (rx-info (car form) 'head)))
855 (unless (consp info)
856 (error "Unknown rx form `%s'" (car form)))
857 (funcall (nth 0 info) form)))
859 (error "rx syntax error at `%s'" form))))
862 ;;;###autoload
863 (defun rx-to-string (form &optional no-group)
864 "Parse and produce code for regular expression FORM.
865 FORM is a regular expression in sexp form.
866 NO-GROUP non-nil means don't put shy groups around the result."
867 (rx-group-if (rx-form form) (null no-group)))
870 ;;;###autoload
871 (defmacro rx (&rest regexps)
872 "Translate regular expressions REGEXPS in sexp form to a regexp string.
873 REGEXPS is a non-empty sequence of forms of the sort listed below.
875 Note that `rx' is a Lisp macro; when used in a Lisp program being
876 compiled, the translation is performed by the compiler.
877 See `rx-to-string' for how to do such a translation at run-time.
879 The following are valid subforms of regular expressions in sexp
880 notation.
882 STRING
883 matches string STRING literally.
885 CHAR
886 matches character CHAR literally.
888 `not-newline', `nonl'
889 matches any character except a newline.
891 `anything'
892 matches any character
894 `(any SET ...)'
895 `(in SET ...)'
896 `(char SET ...)'
897 matches any character in SET .... SET may be a character or string.
898 Ranges of characters can be specified as `A-Z' in strings.
899 Ranges may also be specified as conses like `(?A . ?Z)'.
901 SET may also be the name of a character class: `digit',
902 `control', `hex-digit', `blank', `graph', `print', `alnum',
903 `alpha', `ascii', `nonascii', `lower', `punct', `space', `upper',
904 `word', or one of their synonyms.
906 `(not (any SET ...))'
907 matches any character not in SET ...
909 `line-start', `bol'
910 matches the empty string, but only at the beginning of a line
911 in the text being matched
913 `line-end', `eol'
914 is similar to `line-start' but matches only at the end of a line
916 `string-start', `bos', `bot'
917 matches the empty string, but only at the beginning of the
918 string being matched against.
920 `string-end', `eos', `eot'
921 matches the empty string, but only at the end of the
922 string being matched against.
924 `buffer-start'
925 matches the empty string, but only at the beginning of the
926 buffer being matched against. Actually equivalent to `string-start'.
928 `buffer-end'
929 matches the empty string, but only at the end of the
930 buffer being matched against. Actually equivalent to `string-end'.
932 `point'
933 matches the empty string, but only at point.
935 `word-start', `bow'
936 matches the empty string, but only at the beginning of a word.
938 `word-end', `eow'
939 matches the empty string, but only at the end of a word.
941 `word-boundary'
942 matches the empty string, but only at the beginning or end of a
943 word.
945 `(not word-boundary)'
946 `not-word-boundary'
947 matches the empty string, but not at the beginning or end of a
948 word.
950 `symbol-start'
951 matches the empty string, but only at the beginning of a symbol.
953 `symbol-end'
954 matches the empty string, but only at the end of a symbol.
956 `digit', `numeric', `num'
957 matches 0 through 9.
959 `control', `cntrl'
960 matches ASCII control characters.
962 `hex-digit', `hex', `xdigit'
963 matches 0 through 9, a through f and A through F.
965 `blank'
966 matches horizontal whitespace, as defined by Annex C of the
967 Unicode Technical Standard #18. In particular, it matches
968 spaces, tabs, and other characters whose Unicode
969 `general-category' property indicates they are spacing
970 separators.
972 `graphic', `graph'
973 matches graphic characters--everything except whitespace, ASCII
974 and non-ASCII control characters, surrogates, and codepoints
975 unassigned by Unicode.
977 `printing', `print'
978 matches whitespace and graphic characters.
980 `alphanumeric', `alnum'
981 matches alphabetic characters and digits. For multibyte characters,
982 it matches characters whose Unicode `general-category' property
983 indicates they are alphabetic or decimal number characters.
985 `letter', `alphabetic', `alpha'
986 matches alphabetic characters. For multibyte characters,
987 it matches characters whose Unicode `general-category' property
988 indicates they are alphabetic characters.
990 `ascii'
991 matches ASCII (unibyte) characters.
993 `nonascii'
994 matches non-ASCII (multibyte) characters.
996 `lower', `lower-case'
997 matches anything lower-case, as determined by the current case
998 table. If `case-fold-search' is non-nil, this also matches any
999 upper-case letter.
1001 `upper', `upper-case'
1002 matches anything upper-case, as determined by the current case
1003 table. If `case-fold-search' is non-nil, this also matches any
1004 lower-case letter.
1006 `punctuation', `punct'
1007 matches punctuation. (But at present, for multibyte characters,
1008 it matches anything that has non-word syntax.)
1010 `space', `whitespace', `white'
1011 matches anything that has whitespace syntax.
1013 `word', `wordchar'
1014 matches anything that has word syntax.
1016 `not-wordchar'
1017 matches anything that has non-word syntax.
1019 `(syntax SYNTAX)'
1020 matches a character with syntax SYNTAX. SYNTAX must be one
1021 of the following symbols, or a symbol corresponding to the syntax
1022 character, e.g. `\\.' for `\\s.'.
1024 `whitespace' (\\s- in string notation)
1025 `punctuation' (\\s.)
1026 `word' (\\sw)
1027 `symbol' (\\s_)
1028 `open-parenthesis' (\\s()
1029 `close-parenthesis' (\\s))
1030 `expression-prefix' (\\s')
1031 `string-quote' (\\s\")
1032 `paired-delimiter' (\\s$)
1033 `escape' (\\s\\)
1034 `character-quote' (\\s/)
1035 `comment-start' (\\s<)
1036 `comment-end' (\\s>)
1037 `string-delimiter' (\\s|)
1038 `comment-delimiter' (\\s!)
1040 `(not (syntax SYNTAX))'
1041 matches a character that doesn't have syntax SYNTAX.
1043 `(category CATEGORY)'
1044 matches a character with category CATEGORY. CATEGORY must be
1045 either a character to use for C, or one of the following symbols.
1047 `consonant' (\\c0 in string notation)
1048 `base-vowel' (\\c1)
1049 `upper-diacritical-mark' (\\c2)
1050 `lower-diacritical-mark' (\\c3)
1051 `tone-mark' (\\c4)
1052 `symbol' (\\c5)
1053 `digit' (\\c6)
1054 `vowel-modifying-diacritical-mark' (\\c7)
1055 `vowel-sign' (\\c8)
1056 `semivowel-lower' (\\c9)
1057 `not-at-end-of-line' (\\c<)
1058 `not-at-beginning-of-line' (\\c>)
1059 `alpha-numeric-two-byte' (\\cA)
1060 `chinese-two-byte' (\\cC)
1061 `greek-two-byte' (\\cG)
1062 `japanese-hiragana-two-byte' (\\cH)
1063 `indian-tow-byte' (\\cI)
1064 `japanese-katakana-two-byte' (\\cK)
1065 `korean-hangul-two-byte' (\\cN)
1066 `cyrillic-two-byte' (\\cY)
1067 `combining-diacritic' (\\c^)
1068 `ascii' (\\ca)
1069 `arabic' (\\cb)
1070 `chinese' (\\cc)
1071 `ethiopic' (\\ce)
1072 `greek' (\\cg)
1073 `korean' (\\ch)
1074 `indian' (\\ci)
1075 `japanese' (\\cj)
1076 `japanese-katakana' (\\ck)
1077 `latin' (\\cl)
1078 `lao' (\\co)
1079 `tibetan' (\\cq)
1080 `japanese-roman' (\\cr)
1081 `thai' (\\ct)
1082 `vietnamese' (\\cv)
1083 `hebrew' (\\cw)
1084 `cyrillic' (\\cy)
1085 `can-break' (\\c|)
1087 `(not (category CATEGORY))'
1088 matches a character that doesn't have category CATEGORY.
1090 `(and SEXP1 SEXP2 ...)'
1091 `(: SEXP1 SEXP2 ...)'
1092 `(seq SEXP1 SEXP2 ...)'
1093 `(sequence SEXP1 SEXP2 ...)'
1094 matches what SEXP1 matches, followed by what SEXP2 matches, etc.
1096 `(submatch SEXP1 SEXP2 ...)'
1097 `(group SEXP1 SEXP2 ...)'
1098 like `and', but makes the match accessible with `match-end',
1099 `match-beginning', and `match-string'.
1101 `(submatch-n N SEXP1 SEXP2 ...)'
1102 `(group-n N SEXP1 SEXP2 ...)'
1103 like `group', but make it an explicitly-numbered group with
1104 group number N.
1106 `(or SEXP1 SEXP2 ...)'
1107 `(| SEXP1 SEXP2 ...)'
1108 matches anything that matches SEXP1 or SEXP2, etc. If all
1109 args are strings, use `regexp-opt' to optimize the resulting
1110 regular expression.
1112 `(minimal-match SEXP)'
1113 produce a non-greedy regexp for SEXP. Normally, regexps matching
1114 zero or more occurrences of something are \"greedy\" in that they
1115 match as much as they can, as long as the overall regexp can
1116 still match. A non-greedy regexp matches as little as possible.
1118 `(maximal-match SEXP)'
1119 produce a greedy regexp for SEXP. This is the default.
1121 Below, `SEXP ...' represents a sequence of regexp forms, treated as if
1122 enclosed in `(and ...)'.
1124 `(zero-or-more SEXP ...)'
1125 `(0+ SEXP ...)'
1126 matches zero or more occurrences of what SEXP ... matches.
1128 `(* SEXP ...)'
1129 like `zero-or-more', but always produces a greedy regexp, independent
1130 of `rx-greedy-flag'.
1132 `(*? SEXP ...)'
1133 like `zero-or-more', but always produces a non-greedy regexp,
1134 independent of `rx-greedy-flag'.
1136 `(one-or-more SEXP ...)'
1137 `(1+ SEXP ...)'
1138 matches one or more occurrences of SEXP ...
1140 `(+ SEXP ...)'
1141 like `one-or-more', but always produces a greedy regexp.
1143 `(+? SEXP ...)'
1144 like `one-or-more', but always produces a non-greedy regexp.
1146 `(zero-or-one SEXP ...)'
1147 `(optional SEXP ...)'
1148 `(opt SEXP ...)'
1149 matches zero or one occurrences of A.
1151 `(? SEXP ...)'
1152 like `zero-or-one', but always produces a greedy regexp.
1154 `(?? SEXP ...)'
1155 like `zero-or-one', but always produces a non-greedy regexp.
1157 `(repeat N SEXP)'
1158 `(= N SEXP ...)'
1159 matches N occurrences.
1161 `(>= N SEXP ...)'
1162 matches N or more occurrences.
1164 `(repeat N M SEXP)'
1165 `(** N M SEXP ...)'
1166 matches N to M occurrences.
1168 `(backref N)'
1169 matches what was matched previously by submatch N.
1171 `(eval FORM)'
1172 evaluate FORM and insert result. If result is a string,
1173 `regexp-quote' it.
1175 `(regexp REGEXP)'
1176 include REGEXP in string notation in the result."
1177 (cond ((null regexps)
1178 (error "No regexp"))
1179 ((cdr regexps)
1180 (rx-to-string `(and ,@regexps) t))
1182 (rx-to-string (car regexps) t))))
1185 (pcase-defmacro rx (&rest regexps)
1186 "Build a `pcase' pattern matching `rx' REGEXPS in sexp form.
1187 The REGEXPS are interpreted as in `rx'. The pattern matches any
1188 string that is a match for the regular expression so constructed,
1189 as if by `string-match'.
1191 In addition to the usual `rx' constructs, REGEXPS can contain the
1192 following constructs:
1194 (let REF SEXP...) creates a new explicitly named reference to
1195 a submatch that matches regular expressions
1196 SEXP, and binds the match to REF.
1197 (backref REF) creates a backreference to the submatch
1198 introduced by a previous (let REF ...)
1199 construct. REF can be the same symbol
1200 in the first argument of the corresponding
1201 (let REF ...) construct, or it can be a
1202 submatch number. It matches the referenced
1203 submatch.
1205 The REFs are associated with explicitly named submatches starting
1206 from 1. Multiple occurrences of the same REF refer to the same
1207 submatch.
1209 If a case matches, the match data is modified as usual so you can
1210 use it in the case body, but you still have to pass the correct
1211 string as argument to `match-string'."
1212 (let* ((vars ())
1213 (rx-constituents
1214 `((let
1215 ,(lambda (form)
1216 (rx-check form)
1217 (let ((var (cadr form)))
1218 (cl-check-type var symbol)
1219 (let ((i (or (cl-position var vars :test #'eq)
1220 (prog1 (length vars)
1221 (setq vars `(,@vars ,var))))))
1222 (rx-form `(submatch-n ,(1+ i) ,@(cddr form))))))
1223 1 nil)
1224 (backref
1225 ,(lambda (form)
1226 (rx-check form)
1227 (rx-backref
1228 `(backref ,(let ((var (cadr form)))
1229 (if (integerp var) var
1230 (1+ (cl-position var vars :test #'eq)))))))
1232 ,(lambda (var)
1233 (cond ((integerp var) (rx-check-backref var))
1234 ((memq var vars) t)
1235 (t (error "rx `backref' variable must be one of %s: %s"
1236 vars var)))))
1237 ,@rx-constituents))
1238 (regexp (rx-to-string `(seq ,@regexps) :no-group)))
1239 `(and (pred (string-match ,regexp))
1240 ,@(cl-loop for i from 1
1241 for var in vars
1242 collect `(app (match-string ,i) ,var)))))
1244 ;; ;; sregex.el replacement
1246 ;; ;;;###autoload (provide 'sregex)
1247 ;; ;;;###autoload (autoload 'sregex "rx")
1248 ;; (defalias 'sregex 'rx-to-string)
1249 ;; ;;;###autoload (autoload 'sregexq "rx" nil nil 'macro)
1250 ;; (defalias 'sregexq 'rx)
1252 (provide 'rx)
1254 ;;; rx.el ends here