1 ;;; rx.el --- sexp notation for regular expressions
3 ;; Copyright (C) 2001-2011 Free Software Foundation, Inc.
5 ;; Author: Gerd Moellmann <gerd@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 <http://www.gnu.org/licenses/>.
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 Shivers' attempted definitive SRE notation
39 ;; <URL:http://www.ai.mit.edu/~/shivers/sre.txt>. SRE forms not
40 ;; catered for include: dsm, uncase, w/case, w/nocase, ,@<exp>,
41 ;; ,<exp>, (word ...), word+, posix-string, and character class forms.
42 ;; Some forms are inconsistent with SRE, either for historical reasons
43 ;; or because of the implementation -- simple translation into Emacs
44 ;; regexp strings. These include: any, word. Also, case-sensitivity
45 ;; and greediness are controlled by variables external to the regexp,
46 ;; and you need to feed the forms to the `posix-' functions to get
47 ;; SRE's POSIX semantics. There are probably more difficulties.
49 ;; Rx translates a sexp notation for regular expressions into the
50 ;; usual string notation. The translation can be done at compile-time
51 ;; by using the `rx' macro. It can be done at run-time by calling
52 ;; function `rx-to-string'. See the documentation of `rx' for a
53 ;; complete description of the sexp notation.
55 ;; Some examples of string regexps and their sexp counterparts:
58 ;; (rx (and line-start (0+ (in "a-z"))))
61 ;; (rx (and "\n" (not blank))), or
62 ;; (rx (and "\n" (not (any " \t"))))
64 ;; "\\*\\*\\* EOOH \\*\\*\\*\n"
65 ;; (rx "*** EOOH ***\n")
67 ;; "\\<\\(catch\\|finally\\)\\>[^_]"
68 ;; (rx (and word-start (submatch (or "catch" "finally")) word-end
71 ;; "[ \t\n]*:\\([^:]+\\|$\\)"
72 ;; (rx (and (zero-or-more (in " \t\n")) ":"
73 ;; (submatch (or line-end (one-or-more (not (any ?:)))))))
75 ;; "^content-transfer-encoding:\\(\n?[\t ]\\)*quoted-printable\\(\n?[\t ]\\)*"
76 ;; (rx (and line-start
77 ;; "content-transfer-encoding:"
80 ;; (+ (? ?\n)) blank))
82 ;; (concat "^\\(?:" something-else "\\)")
83 ;; (rx (and line-start (eval something-else))), statically or
84 ;; (rx-to-string '(and line-start ,something-else)), dynamically.
86 ;; (regexp-opt '(STRING1 STRING2 ...))
87 ;; (rx (or STRING1 STRING2 ...)), or in other words, `or' automatically
88 ;; calls `regexp-opt' as needed.
91 ;; (rx (or (and line-start ";;" (0+ space) ?\n)
92 ;; (and line-start ?\n)))
94 ;; "\\$[I]d: [^ ]+ \\([^ ]+\\) "
96 ;; (1+ (not (in " ")))
98 ;; (submatch (1+ (not (in " "))))
102 ;; (rx (and ?\\ ?\\ ?\[ (1+ word)))
111 (defconst rx-constituents
112 '((and .
(rx-and 1 nil
))
115 (sequence . and
) ; sregex
119 (nonl . not-newline
) ; SRE
120 (anything .
(rx-anything 0 nil
))
121 (any .
(rx-any 1 nil rx-check-any
)) ; inconsistent with SRE
124 (char . any
) ; sregex
125 (not-char .
(rx-not-char 1 nil rx-check-any
)) ; sregex
126 (not .
(rx-not 1 1 rx-check-not
))
127 (repeat .
(rx-repeat 2 nil
))
128 (= .
(rx-= 2 nil
)) ; SRE
129 (>= .
(rx->= 2 nil
)) ; SRE
130 (** .
(rx-** 2 nil
)) ; SRE
131 (submatch .
(rx-submatch 1 nil
)) ; SRE
132 (group . submatch
) ; sregex
133 (submatch-n .
(rx-submatch-n 2 nil
))
134 (group-n . submatch-n
)
135 (zero-or-more .
(rx-kleene 1 nil
))
136 (one-or-more .
(rx-kleene 1 nil
))
137 (zero-or-one .
(rx-kleene 1 nil
))
138 (\? . zero-or-one
) ; SRE
140 (* . zero-or-more
) ; SRE
143 (+ . one-or-more
) ; SRE
146 (optional . zero-or-one
)
147 (opt . zero-or-one
) ; sregex
148 (minimal-match .
(rx-greedy 1 1))
149 (maximal-match .
(rx-greedy 1 1))
150 (backref .
(rx-backref 1 1 rx-check-backref
))
152 (bol . line-start
) ; SRE
154 (eol . line-end
) ; SRE
155 (string-start .
"\\`")
156 (bos . string-start
) ; SRE
157 (bot . string-start
) ; sregex
159 (eos . string-end
) ; SRE
160 (eot . string-end
) ; sregex
161 (buffer-start .
"\\`")
165 (bow . word-start
) ; SRE
167 (eow . word-end
) ; SRE
168 (word-boundary .
"\\b")
169 (not-word-boundary .
"\\B") ; sregex
170 (symbol-start .
"\\_<")
171 (symbol-end .
"\\_>")
172 (syntax .
(rx-syntax 1 1))
173 (not-syntax .
(rx-not-syntax 1 1)) ; sregex
174 (category .
(rx-category 1 1 rx-check-category
))
175 (eval .
(rx-eval 1 1))
176 (regexp .
(rx-regexp 1 1 stringp
))
177 (regex . regexp
) ; sregex
178 (digit .
"[[:digit:]]")
179 (numeric . digit
) ; SRE
181 (control .
"[[:cntrl:]]") ; SRE
182 (cntrl . control
) ; SRE
183 (hex-digit .
"[[:xdigit:]]") ; SRE
184 (hex . hex-digit
) ; SRE
185 (xdigit . hex-digit
) ; SRE
186 (blank .
"[[:blank:]]") ; SRE
187 (graphic .
"[[:graph:]]") ; SRE
188 (graph . graphic
) ; SRE
189 (printing .
"[[:print:]]") ; SRE
190 (print . printing
) ; SRE
191 (alphanumeric .
"[[:alnum:]]") ; SRE
192 (alnum . alphanumeric
) ; SRE
193 (letter .
"[[:alpha:]]")
194 (alphabetic . letter
) ; SRE
195 (alpha . letter
) ; SRE
196 (ascii .
"[[:ascii:]]") ; SRE
197 (nonascii .
"[[:nonascii:]]")
198 (lower .
"[[:lower:]]") ; SRE
199 (lower-case . lower
) ; SRE
200 (punctuation .
"[[:punct:]]") ; SRE
201 (punct . punctuation
) ; SRE
202 (space .
"[[:space:]]") ; SRE
203 (whitespace . space
) ; SRE
204 (white . space
) ; SRE
205 (upper .
"[[:upper:]]") ; SRE
206 (upper-case . upper
) ; SRE
207 (word .
"[[:word:]]") ; inconsistent with SRE
208 (wordchar . word
) ; sregex
209 (not-wordchar .
"\\W"))
210 "Alist of sexp form regexp constituents.
211 Each element of the alist has the form (SYMBOL . DEFN).
212 SYMBOL is a valid constituent of sexp regular expressions.
213 If DEFN is a string, SYMBOL is translated into DEFN.
214 If DEFN is a symbol, use the definition of DEFN, recursively.
215 Otherwise, DEFN must be a list (FUNCTION MIN-ARGS MAX-ARGS PREDICATE).
216 FUNCTION is used to produce code for SYMBOL. MIN-ARGS and MAX-ARGS
217 are the minimum and maximum number of arguments the function-form
218 sexp constituent SYMBOL may have in sexp regular expressions.
219 MAX-ARGS nil means no limit. PREDICATE, if specified, means that
220 all arguments must satisfy PREDICATE.")
228 (open-parenthesis . ?\
()
229 (close-parenthesis . ?\
))
230 (expression-prefix . ?
\')
232 (paired-delimiter . ?$
)
234 (character-quote . ?
/)
237 (string-delimiter . ?|
)
238 (comment-delimiter . ?
!))
239 "Alist mapping Rx syntax symbols to syntax characters.
240 Each entry has the form (SYMBOL . CHAR), where SYMBOL is a valid
241 symbol in `(syntax SYMBOL)', and CHAR is the syntax character
242 corresponding to SYMBOL, as it would be used with \\s or \\S in
243 regular expressions.")
246 (defconst rx-categories
249 (upper-diacritical-mark . ?
2)
250 (lower-diacritical-mark . ?
3)
254 (vowel-modifying-diacritical-mark . ?
7)
256 (semivowel-lower . ?
9)
257 (not-at-end-of-line . ?
<)
258 (not-at-beginning-of-line . ?
>)
259 (alpha-numeric-two-byte . ?A
)
260 (chinse-two-byte . ?C
)
261 (greek-two-byte . ?G
)
262 (japanese-hiragana-two-byte . ?H
)
263 (indian-two-byte . ?I
)
264 (japanese-katakana-two-byte . ?K
)
265 (korean-hangul-two-byte . ?N
)
266 (cyrillic-two-byte . ?Y
)
267 (combining-diacritic . ?^
)
276 (japanese-katakana . ?k
)
280 (japanese-roman . ?r
)
286 "Alist mapping symbols to category characters.
287 Each entry has the form (SYMBOL . CHAR), where SYMBOL is a valid
288 symbol in `(category SYMBOL)', and CHAR is the category character
289 corresponding to SYMBOL, as it would be used with `\\c' or `\\C' in
290 regular expression strings.")
293 (defvar rx-greedy-flag t
294 "Non-nil means produce greedy regular expressions for `zero-or-one',
295 `zero-or-more', and `one-or-more'. Dynamically bound.")
298 (defun rx-info (op head
)
299 "Return parsing/code generation info for OP.
300 If OP is the space character ASCII 32, return info for the symbol `?'.
301 If OP is the character `?', return info for the symbol `??'.
302 See also `rx-constituents'.
303 If HEAD is non-nil, then OP is the head of a sexp, otherwise it's
304 a standalone symbol."
305 (cond ((eq op ?
) (setq op
'\?))
306 ((eq op ??
) (setq op
'\??
)))
308 (while (and (not (null op
)) (symbolp op
))
310 (setq op
(cdr (assq op rx-constituents
)))
311 (when (if head
(stringp op
) (consp op
))
312 ;; We found something but of the wrong kind. Let's look for an
313 ;; alternate definition for the other case.
315 (cdr (assq old-op
(cdr (memq (assq old-op rx-constituents
)
316 rx-constituents
))))))
317 (if (and new-op
(not (if head
(stringp new-op
) (consp new-op
))))
318 (setq op new-op
))))))
322 (defun rx-check (form)
323 "Check FORM according to its car's parsing info."
325 (error "rx `%s' needs argument(s)" form
))
326 (let* ((rx (rx-info (car form
) 'head
))
327 (nargs (1- (length form
)))
328 (min-args (nth 1 rx
))
329 (max-args (nth 2 rx
))
330 (type-pred (nth 3 rx
)))
331 (when (and (not (null min-args
))
333 (error "rx form `%s' requires at least %d args"
334 (car form
) min-args
))
335 (when (and (not (null max-args
))
337 (error "rx form `%s' accepts at most %d args"
338 (car form
) max-args
))
339 (when (not (null type-pred
))
340 (dolist (sub-form (cdr form
))
341 (unless (funcall type-pred sub-form
)
342 (error "rx form `%s' requires args satisfying `%s'"
343 (car form
) type-pred
))))))
346 (defun rx-group-if (regexp group
)
347 "Put shy groups around REGEXP if seemingly necessary when GROUP
350 ;; for some repetition
351 ((eq group
'*) (if (rx-atomic-p regexp
) (setq group nil
)))
356 "\\(?:[?*+]\\??\\|\\\\{[0-9]*,?[0-9]*\\\\}\\)\\'" regexp
)
357 (substring regexp
0 (match-beginning 0))
361 ((eq group
'|
) (setq group nil
))
364 ((rx-atomic-p regexp t
) (setq group nil
)))
366 (concat "\\(?:" regexp
"\\)")
371 ;; dynamically bound in some functions.
375 "Parse and produce code from FORM.
376 FORM is of the form `(and FORM1 ...)'."
379 (mapconcat (lambda (x) (rx-form x
':)) (cdr form
) nil
)
380 (and (memq rx-parent
'(* t
)) rx-parent
)))
384 "Parse and produce code from FORM, which is `(or FORM1 ...)'."
387 (if (memq nil
(mapcar 'stringp
(cdr form
)))
388 (mapconcat (lambda (x) (rx-form x
'|
)) (cdr form
) "\\|")
389 (regexp-opt (cdr form
)))
390 (and (memq rx-parent
'(: * t
)) rx-parent
)))
393 (defun rx-anything (form)
394 "Match any character."
396 (error "rx `anythng' syntax error: %s" form
))
397 (rx-or (list 'or
'not-newline ?
\n)))
400 (defun rx-any-delete-from-range (char ranges
)
401 "Delete by side effect character CHAR from RANGES.
402 Only both edges of each range is checked."
405 ((memq char ranges
) (setq ranges
(delq char ranges
)))
406 ((setq m
(assq char ranges
))
407 (if (eq (1+ char
) (cdr m
))
408 (setcar (memq m ranges
) (1+ char
))
409 (setcar m
(1+ char
))))
410 ((setq m
(rassq char ranges
))
411 (if (eq (1- char
) (car m
))
412 (setcar (memq m ranges
) (1- char
))
413 (setcdr m
(1- char
)))))
417 (defun rx-any-condense-range (args)
418 "Condense by side effect ARGS as range for Rx `any'."
421 ;; set STR list of all strings
422 ;; set L list of all ranges
423 (mapc (lambda (e) (cond ((stringp e
) (push e str
))
424 ((numberp e
) (push (cons e e
) l
))
427 ;; condense overlapped ranges in L
428 (let ((tail (setq l
(sort l
#'car-less-than-car
)))
430 (while (setq d
(cdr tail
))
431 (if (>= (cdar tail
) (1- (caar d
)))
433 (setcdr (car tail
) (max (cdar tail
) (cdar d
)))
434 (setcdr tail
(cdr d
)))
436 ;; Separate small ranges to single number, and delete dups.
441 ((= (car e
) (cdr e
)) (list (car e
)))
442 ((= (1+ (car e
)) (cdr e
)) (list (car e
) (cdr e
)))
448 (defun rx-check-any-string (str)
449 "Check string argument STR for Rx `any'."
452 (if (= 0 (length str
))
453 (error "String arg for Rx `any' must not be empty"))
454 (while (string-match ".-." str i
)
455 ;; string before range: convert it to characters
456 (if (< i
(match-beginning 0))
459 (append (substring str i
(match-beginning 0)) nil
))))
461 (setq i
(match-end 0)
462 c1
(aref str
(match-beginning 0))
463 c2
(aref str
(1- i
)))
465 ((< c1 c2
) (setq l
(nconc l
(list (cons c1 c2
)))))
466 ((= c1 c2
) (setq l
(nconc l
(list c1
))))))
468 (if (< i
(length str
))
469 (setq l
(nconc l
(append (substring str i
) nil
))))
473 (defun rx-check-any (arg)
474 "Check arg ARG for Rx `any'."
476 ((integerp arg
) (list arg
))
478 (let ((translation (condition-case nil
481 (if (or (null translation
)
482 (null (string-match "\\`\\[\\[:[-a-z]+:\\]\\]\\'" translation
)))
483 (error "Invalid char class `%s' in Rx `any'" arg
))
484 (list (substring translation
1 -
1)))) ; strip outer brackets
485 ((and (integerp (car-safe arg
)) (integerp (cdr-safe arg
)))
487 ((stringp arg
) (rx-check-any-string arg
))
489 "rx `any' requires string, character, char pair or char class args"))))
493 "Parse and produce code from FORM, which is `(any ARG ...)'.
496 (let* ((args (rx-any-condense-range
499 (mapcar #'rx-check-any
(cdr form
)))))
503 ;; single close bracket
504 ;; => "[]...-]" or "[]...--.]"
506 ;; set ] at the beginning
507 (setq args
(cons ?\
] (delq ?\
] args
)))
509 (if (or (memq ?- args
) (assq ?- args
))
510 (setq args
(nconc (rx-any-delete-from-range ?- args
)
512 ;; close bracket starts a range
513 ;; => "[]-....-]" or "[]-.--....]"
514 ((setq m
(assq ?\
] args
))
515 ;; bring it to the beginning
516 (setq args
(cons m
(delq m args
)))
517 (cond ((memq ?- args
)
519 (setq args
(nconc (delq ?- args
) (list ?-
))))
520 ((setq m
(assq ?- args
))
521 ;; next to the bracket's range, make the second range
522 (setcdr args
(cons m
(delq m args
))))))
523 ;; bracket in the end range
525 ((setq m
(rassq ?\
] args
))
526 ;; set ] at the beginning
527 (setq args
(cons ?\
] (rx-any-delete-from-range ?\
] args
)))
529 (if (or (memq ?- args
) (assq ?- args
))
530 (setq args
(nconc (rx-any-delete-from-range ?- args
)
532 ;; {no close bracket appears}
534 ;; bring single bar to the beginning
536 (setq args
(cons ?-
(delq ?- args
))))
537 ;; bar start a range, bring it to the beginning
538 ((setq m
(assq ?- args
))
539 (setq args
(cons m
(delq m args
))))
541 ;; hat at the beginning?
542 ((or (eq (car args
) ?^
) (eq (car-safe (car args
)) ?^
))
543 (setq args
(if (cdr args
)
544 `(,(cadr args
) ,(car args
) ,@(cddr args
))
545 (nconc (rx-any-delete-from-range ?^ args
)
548 (if (and (null (cdr args
)) (numberp (car args
))
550 (setq s
(regexp-quote (string (car args
))))))
551 (and (equal (car args
) ?^
) ;; unnecessary predicate?
552 (null (eq rx-parent
'!)))))
557 ((numberp e
) (string e
))
559 (if (and (= (1+ (car e
)) (cdr e
))
560 ;; rx-any-condense-range should
561 ;; prevent this case from happening.
562 (null (memq (car e
) '(?\
] ?-
)))
563 (null (memq (cdr e
) '(?\
] ?-
))))
564 (string (car e
) (cdr e
))
565 (string (car e
) ?-
(cdr e
))))
572 (defun rx-check-not (arg)
573 "Check arg ARG for Rx `not'."
574 (unless (or (and (symbolp arg
)
575 (string-match "\\`\\[\\[:[-a-z]+:\\]\\]\\'"
579 (eq arg
'word-boundary
)
581 (memq (car arg
) '(not any in syntax category
))))
582 (error "rx `not' syntax error: %s" arg
))
587 "Parse and produce code from FORM. FORM is `(not ...)'."
589 (let ((result (rx-form (cadr form
) '!))
591 (cond ((string-match "\\`\\[^" result
)
593 ((equal result
"[^]") "[^^]")
594 ((and (= (length result
) 4) (null (eq rx-parent
'!)))
595 (regexp-quote (substring result
2 3)))
596 ((concat "[" (substring result
2)))))
597 ((eq ?\
[ (aref result
0))
598 (concat "[^" (substring result
1)))
599 ((string-match "\\`\\\\[scbw]" result
)
600 (concat (upcase (substring result
0 2))
601 (substring result
2)))
602 ((string-match "\\`\\\\[SCBW]" result
)
603 (concat (downcase (substring result
0 2))
604 (substring result
2)))
606 (concat "[^" result
"]")))))
609 (defun rx-not-char (form)
610 "Parse and produce code from FORM. FORM is `(not-char ...)'."
612 (rx-not `(not (in ,@(cdr form
)))))
615 (defun rx-not-syntax (form)
616 "Parse and produce code from FORM. FORM is `(not-syntax SYNTAX)'."
618 (rx-not `(not (syntax ,@(cdr form
)))))
621 (defun rx-trans-forms (form &optional skip
)
622 "If FORM's length is greater than two, transform it to length two.
623 A form (HEAD REST ...) becomes (HEAD (and REST ...)).
624 If SKIP is non-nil, allow that number of items after the head, i.e.
625 `(= N REST ...)' becomes `(= N (and REST ...))' if SKIP is 1."
626 (unless skip
(setq skip
0))
627 (let ((tail (nthcdr (1+ skip
) form
)))
628 (if (= (length tail
) 1)
630 (let ((form (copy-sequence form
)))
631 (setcdr (nthcdr skip form
) (list (cons 'and tail
)))
636 "Parse and produce code from FORM `(= N ...)'."
638 (setq form
(rx-trans-forms form
1))
639 (unless (and (integerp (nth 1 form
))
641 (error "rx `=' requires positive integer first arg"))
642 (format "%s\\{%d\\}" (rx-form (nth 2 form
) '*) (nth 1 form
)))
646 "Parse and produce code from FORM `(>= N ...)'."
648 (setq form
(rx-trans-forms form
1))
649 (unless (and (integerp (nth 1 form
))
651 (error "rx `>=' requires positive integer first arg"))
652 (format "%s\\{%d,\\}" (rx-form (nth 2 form
) '*) (nth 1 form
)))
656 "Parse and produce code from FORM `(** N M ...)'."
658 (rx-form (cons 'repeat
(cdr (rx-trans-forms form
2))) '*))
661 (defun rx-repeat (form)
662 "Parse and produce code from FORM.
663 FORM is either `(repeat N FORM1)' or `(repeat N M FORMS...)'."
665 (if (> (length form
) 4)
666 (setq form
(rx-trans-forms form
2)))
667 (if (null (nth 2 form
))
668 (setq form
(cons (nth 0 form
) (cons (nth 1 form
) (nthcdr 3 form
)))))
669 (cond ((= (length form
) 3)
670 (unless (and (integerp (nth 1 form
))
672 (error "rx `repeat' requires positive integer first arg"))
673 (format "%s\\{%d\\}" (rx-form (nth 2 form
) '*) (nth 1 form
)))
674 ((or (not (integerp (nth 2 form
)))
676 (not (integerp (nth 1 form
)))
678 (< (nth 2 form
) (nth 1 form
)))
679 (error "rx `repeat' range error"))
681 (format "%s\\{%d,%d\\}" (rx-form (nth 3 form
) '*)
682 (nth 1 form
) (nth 2 form
)))))
685 (defun rx-submatch (form)
686 "Parse and produce code from FORM, which is `(submatch ...)'."
688 (if (= 2 (length form
))
689 ;; Only one sub-form.
690 (rx-form (cadr form
))
691 ;; Several sub-forms implicitly concatenated.
692 (mapconcat (lambda (re) (rx-form re
':)) (cdr form
) nil
))
695 (defun rx-submatch-n (form)
696 "Parse and produce code from FORM, which is `(submatch-n N ...)'."
697 (let ((n (nth 1 form
)))
698 (concat "\\(?" (number-to-string n
) ":"
699 (if (= 3 (length form
))
700 ;; Only one sub-form.
701 (rx-form (nth 2 form
))
702 ;; Several sub-forms implicitly concatenated.
703 (mapconcat (lambda (re) (rx-form re
':)) (cddr form
) nil
))
706 (defun rx-backref (form)
707 "Parse and produce code from FORM, which is `(backref N)'."
709 (format "\\%d" (nth 1 form
)))
711 (defun rx-check-backref (arg)
712 "Check arg ARG for Rx `backref'."
713 (or (and (integerp arg
) (>= arg
1) (<= arg
9))
714 (error "rx `backref' requires numeric 1<=arg<=9: %s" arg
)))
716 (defun rx-kleene (form)
717 "Parse and produce code from FORM.
718 FORM is `(OP FORM1)', where OP is one of the `zero-or-one',
719 `zero-or-more' etc. operators.
720 If OP is one of `*', `+', `?', produce a greedy regexp.
721 If OP is one of `*?', `+?', `??', produce a non-greedy regexp.
722 If OP is anything else, produce a greedy regexp if `rx-greedy-flag'
725 (setq form
(rx-trans-forms form
))
726 (let ((suffix (cond ((memq (car form
) '(* + ?\s
)) "")
727 ((memq (car form
) '(*?
+? ??
)) "?")
730 (op (cond ((memq (car form
) '(* *?
0+ zero-or-more
)) "*")
731 ((memq (car form
) '(+ +?
1+ one-or-more
)) "+")
734 (concat (rx-form (cadr form
) '*) op suffix
)
735 (and (memq rx-parent
'(t *)) rx-parent
))))
738 (defun rx-atomic-p (r &optional lax
)
739 "Return non-nil if regexp string R is atomic.
740 An atomic regexp R is one such that a suffix operator
741 appended to R will apply to all of R. For example, \"a\"
742 \"[abc]\" and \"\\(ab\\|ab*c\\)\" are atomic and \"ab\",
743 \"[ab]c\", and \"ab\\|ab*c\" are not atomic.
745 This function may return false negatives, but it will not
746 return false positives. It is nevertheless useful in
747 situations where an efficiency shortcut can be taken only if a
748 regexp is atomic. The function can be improved to detect
749 more cases of atomic regexps. Presently, this function
750 detects the following categories of atomic regexp;
752 a group or shy group: \\(...\\)
753 a character class: [...]
754 a single character: a
756 On the other hand, false negatives will be returned for
757 regexps that are atomic but end in operators, such as
758 \"a+\". I think these are rare. Probably such cases could
759 be detected without much effort. A guarantee of no false
760 negatives would require a theoretic specification of the set
761 of all atomic regexps."
762 (let ((l (length r
)))
765 ((= l
2) (= (aref r
0) ?
\\))
766 ((= l
3) (string-match "\\`\\(?:\\\\[cCsS_]\\|\\[[^^]\\]\\)" r
))
769 ((string-match "\\`\\[^?\]?\\(?:\\[:[a-z]+:]\\|[^\]]\\)*\\]\\'" r
))
770 ((string-match "\\`\\\\(\\(?:[^\\]\\|\\\\[^\)]\\)*\\\\)\\'" r
)))))))
773 (defun rx-syntax (form)
774 "Parse and produce code from FORM, which is `(syntax SYMBOL)'."
776 (let* ((sym (cadr form
))
777 (syntax (cdr (assq sym rx-syntax
))))
779 ;; Try sregex compatibility.
781 ((characterp sym
) (setq syntax sym
))
783 (let ((name (symbol-name sym
)))
784 (if (= 1 (length name
))
785 (setq syntax
(aref name
0))))))
787 (error "Unknown rx syntax `%s'" sym
)))
788 (format "\\s%c" syntax
)))
791 (defun rx-check-category (form)
792 "Check the argument FORM of a `(category FORM)'."
793 (unless (or (integerp form
)
794 (cdr (assq form rx-categories
)))
795 (error "Unknown category `%s'" form
))
799 (defun rx-category (form)
800 "Parse and produce code from FORM, which is `(category SYMBOL)'."
802 (let ((char (if (integerp (cadr form
))
804 (cdr (assq (cadr form
) rx-categories
)))))
805 (format "\\c%c" char
)))
808 (defun rx-eval (form)
809 "Parse and produce code from FORM, which is `(eval FORM)'."
811 (rx-form (eval (cadr form
)) rx-parent
))
814 (defun rx-greedy (form)
815 "Parse and produce code from FORM.
816 If FORM is '(minimal-match FORM1)', non-greedy versions of `*',
817 `+', and `?' operators will be used in FORM1. If FORM is
818 '(maximal-match FORM1)', greedy operators will be used."
820 (let ((rx-greedy-flag (eq (car form
) 'maximal-match
)))
821 (rx-form (cadr form
) rx-parent
)))
824 (defun rx-regexp (form)
825 "Parse and produce code from FORM, which is `(regexp STRING)'."
827 (rx-group-if (cadr form
) rx-parent
))
830 (defun rx-form (form &optional rx-parent
)
831 "Parse and produce code for regular expression FORM.
832 FORM is a regular expression in sexp form.
833 RX-PARENT shows which type of expression calls and controls putting of
834 shy groups around the result and some more in other functions."
836 (rx-group-if (regexp-quote form
)
837 (if (and (eq rx-parent
'*) (< 1 (length form
)))
839 (cond ((integerp form
)
840 (regexp-quote (char-to-string form
)))
842 (let ((info (rx-info form nil
)))
843 (cond ((stringp info
)
846 (error "Unknown rx form `%s'" form
))
848 (funcall (nth 0 info
) form
)))))
850 (let ((info (rx-info (car form
) 'head
)))
852 (error "Unknown rx form `%s'" (car form
)))
853 (funcall (nth 0 info
) form
)))
855 (error "rx syntax error at `%s'" form
)))))
859 (defun rx-to-string (form &optional no-group
)
860 "Parse and produce code for regular expression FORM.
861 FORM is a regular expression in sexp form.
862 NO-GROUP non-nil means don't put shy groups around the result."
863 (rx-group-if (rx-form form
) (null no-group
)))
867 (defmacro rx
(&rest regexps
)
868 "Translate regular expressions REGEXPS in sexp form to a regexp string.
869 REGEXPS is a non-empty sequence of forms of the sort listed below.
871 Note that `rx' is a Lisp macro; when used in a Lisp program being
872 compiled, the translation is performed by the compiler.
873 See `rx-to-string' for how to do such a translation at run-time.
875 The following are valid subforms of regular expressions in sexp
879 matches string STRING literally.
882 matches character CHAR literally.
884 `not-newline', `nonl'
885 matches any character except a newline.
888 matches any character
893 matches any character in SET .... SET may be a character or string.
894 Ranges of characters can be specified as `A-Z' in strings.
895 Ranges may also be specified as conses like `(?A . ?Z)'.
897 SET may also be the name of a character class: `digit',
898 `control', `hex-digit', `blank', `graph', `print', `alnum',
899 `alpha', `ascii', `nonascii', `lower', `punct', `space', `upper',
900 `word', or one of their synonyms.
902 `(not (any SET ...))'
903 matches any character not in SET ...
906 matches the empty string, but only at the beginning of a line
907 in the text being matched
910 is similar to `line-start' but matches only at the end of a line
912 `string-start', `bos', `bot'
913 matches the empty string, but only at the beginning of the
914 string being matched against.
916 `string-end', `eos', `eot'
917 matches the empty string, but only at the end of the
918 string being matched against.
921 matches the empty string, but only at the beginning of the
922 buffer being matched against. Actually equivalent to `string-start'.
925 matches the empty string, but only at the end of the
926 buffer being matched against. Actually equivalent to `string-end'.
929 matches the empty string, but only at point.
932 matches the empty string, but only at the beginning of a word.
935 matches the empty string, but only at the end of a word.
938 matches the empty string, but only at the beginning or end of a
941 `(not word-boundary)'
943 matches the empty string, but not at the beginning or end of a
947 matches the empty string, but only at the beginning of a symbol.
950 matches the empty string, but only at the end of a symbol.
952 `digit', `numeric', `num'
956 matches ASCII control characters.
958 `hex-digit', `hex', `xdigit'
959 matches 0 through 9, a through f and A through F.
962 matches space and tab only.
965 matches graphic characters--everything except ASCII control chars,
969 matches printing characters--everything except ASCII control chars
972 `alphanumeric', `alnum'
973 matches letters and digits. (But at present, for multibyte characters,
974 it matches anything that has word syntax.)
976 `letter', `alphabetic', `alpha'
977 matches letters. (But at present, for multibyte characters,
978 it matches anything that has word syntax.)
981 matches ASCII (unibyte) characters.
984 matches non-ASCII (multibyte) characters.
986 `lower', `lower-case'
987 matches anything lower-case.
989 `upper', `upper-case'
990 matches anything upper-case.
992 `punctuation', `punct'
993 matches punctuation. (But at present, for multibyte characters,
994 it matches anything that has non-word syntax.)
996 `space', `whitespace', `white'
997 matches anything that has whitespace syntax.
1000 matches anything that has word syntax.
1003 matches anything that has non-word syntax.
1006 matches a character with syntax SYNTAX. SYNTAX must be one
1007 of the following symbols, or a symbol corresponding to the syntax
1008 character, e.g. `\\.' for `\\s.'.
1010 `whitespace' (\\s- in string notation)
1011 `punctuation' (\\s.)
1014 `open-parenthesis' (\\s()
1015 `close-parenthesis' (\\s))
1016 `expression-prefix' (\\s')
1017 `string-quote' (\\s\")
1018 `paired-delimiter' (\\s$)
1020 `character-quote' (\\s/)
1021 `comment-start' (\\s<)
1022 `comment-end' (\\s>)
1023 `string-delimiter' (\\s|)
1024 `comment-delimiter' (\\s!)
1026 `(not (syntax SYNTAX))'
1027 matches a character that doesn't have syntax SYNTAX.
1029 `(category CATEGORY)'
1030 matches a character with category CATEGORY. CATEGORY must be
1031 either a character to use for C, or one of the following symbols.
1033 `consonant' (\\c0 in string notation)
1035 `upper-diacritical-mark' (\\c2)
1036 `lower-diacritical-mark' (\\c3)
1040 `vowel-modifying-diacritical-mark' (\\c7)
1042 `semivowel-lower' (\\c9)
1043 `not-at-end-of-line' (\\c<)
1044 `not-at-beginning-of-line' (\\c>)
1045 `alpha-numeric-two-byte' (\\cA)
1046 `chinse-two-byte' (\\cC)
1047 `greek-two-byte' (\\cG)
1048 `japanese-hiragana-two-byte' (\\cH)
1049 `indian-tow-byte' (\\cI)
1050 `japanese-katakana-two-byte' (\\cK)
1051 `korean-hangul-two-byte' (\\cN)
1052 `cyrillic-two-byte' (\\cY)
1053 `combining-diacritic' (\\c^)
1062 `japanese-katakana' (\\ck)
1066 `japanese-roman' (\\cr)
1073 `(not (category CATEGORY))'
1074 matches a character that doesn't have category CATEGORY.
1076 `(and SEXP1 SEXP2 ...)'
1077 `(: SEXP1 SEXP2 ...)'
1078 `(seq SEXP1 SEXP2 ...)'
1079 `(sequence SEXP1 SEXP2 ...)'
1080 matches what SEXP1 matches, followed by what SEXP2 matches, etc.
1082 `(submatch SEXP1 SEXP2 ...)'
1083 `(group SEXP1 SEXP2 ...)'
1084 like `and', but makes the match accessible with `match-end',
1085 `match-beginning', and `match-string'.
1087 `(submatch-n N SEXP1 SEXP2 ...)'
1088 `(group-n N SEXP1 SEXP2 ...)'
1089 like `group', but make it an explicitly-numbered group with
1092 `(or SEXP1 SEXP2 ...)'
1093 `(| SEXP1 SEXP2 ...)'
1094 matches anything that matches SEXP1 or SEXP2, etc. If all
1095 args are strings, use `regexp-opt' to optimize the resulting
1098 `(minimal-match SEXP)'
1099 produce a non-greedy regexp for SEXP. Normally, regexps matching
1100 zero or more occurrences of something are \"greedy\" in that they
1101 match as much as they can, as long as the overall regexp can
1102 still match. A non-greedy regexp matches as little as possible.
1104 `(maximal-match SEXP)'
1105 produce a greedy regexp for SEXP. This is the default.
1107 Below, `SEXP ...' represents a sequence of regexp forms, treated as if
1108 enclosed in `(and ...)'.
1110 `(zero-or-more SEXP ...)'
1112 matches zero or more occurrences of what SEXP ... matches.
1115 like `zero-or-more', but always produces a greedy regexp, independent
1116 of `rx-greedy-flag'.
1119 like `zero-or-more', but always produces a non-greedy regexp,
1120 independent of `rx-greedy-flag'.
1122 `(one-or-more SEXP ...)'
1124 matches one or more occurrences of SEXP ...
1127 like `one-or-more', but always produces a greedy regexp.
1130 like `one-or-more', but always produces a non-greedy regexp.
1132 `(zero-or-one SEXP ...)'
1133 `(optional SEXP ...)'
1135 matches zero or one occurrences of A.
1138 like `zero-or-one', but always produces a greedy regexp.
1141 like `zero-or-one', but always produces a non-greedy regexp.
1145 matches N occurrences.
1148 matches N or more occurrences.
1152 matches N to M occurrences.
1155 matches what was matched previously by submatch N.
1158 evaluate FORM and insert result. If result is a string,
1162 include REGEXP in string notation in the result."
1163 (cond ((null regexps
)
1164 (error "No regexp"))
1166 (rx-to-string `(and ,@regexps
) t
))
1168 (rx-to-string (car regexps
) t
))))
1170 ;; ;; sregex.el replacement
1172 ;; ;;;###autoload (provide 'sregex)
1173 ;; ;;;###autoload (autoload 'sregex "rx")
1174 ;; (defalias 'sregex 'rx-to-string)
1175 ;; ;;;###autoload (autoload 'sregexq "rx" nil nil 'macro)
1176 ;; (defalias 'sregexq 'rx)