]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/rx.el
Add 2012 to FSF copyright years for Emacs files
[gnu-emacs] / lisp / emacs-lisp / rx.el
1 ;;; rx.el --- sexp notation for regular expressions
2
3 ;; Copyright (C) 2001-2012 Free Software Foundation, Inc.
4
5 ;; Author: Gerd Moellmann <gerd@gnu.org>
6 ;; Maintainer: FSF
7 ;; Keywords: strings, regexps, extensions
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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/>.
23
24 ;;; Commentary:
25
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 :-).
32
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.
36
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.
48
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.
54 ;;
55 ;; Some examples of string regexps and their sexp counterparts:
56 ;;
57 ;; "^[a-z]*"
58 ;; (rx (and line-start (0+ (in "a-z"))))
59 ;;
60 ;; "\n[^ \t]"
61 ;; (rx (and "\n" (not blank))), or
62 ;; (rx (and "\n" (not (any " \t"))))
63 ;;
64 ;; "\\*\\*\\* EOOH \\*\\*\\*\n"
65 ;; (rx "*** EOOH ***\n")
66 ;;
67 ;; "\\<\\(catch\\|finally\\)\\>[^_]"
68 ;; (rx (and word-start (submatch (or "catch" "finally")) word-end
69 ;; (not (any ?_))))
70 ;;
71 ;; "[ \t\n]*:\\([^:]+\\|$\\)"
72 ;; (rx (and (zero-or-more (in " \t\n")) ":"
73 ;; (submatch (or line-end (one-or-more (not (any ?:)))))))
74 ;;
75 ;; "^content-transfer-encoding:\\(\n?[\t ]\\)*quoted-printable\\(\n?[\t ]\\)*"
76 ;; (rx (and line-start
77 ;; "content-transfer-encoding:"
78 ;; (+ (? ?\n)) blank
79 ;; "quoted-printable"
80 ;; (+ (? ?\n)) blank))
81 ;;
82 ;; (concat "^\\(?:" something-else "\\)")
83 ;; (rx (and line-start (eval something-else))), statically or
84 ;; (rx-to-string '(and line-start ,something-else)), dynamically.
85 ;;
86 ;; (regexp-opt '(STRING1 STRING2 ...))
87 ;; (rx (or STRING1 STRING2 ...)), or in other words, `or' automatically
88 ;; calls `regexp-opt' as needed.
89 ;;
90 ;; "^;;\\s-*\n\\|^\n"
91 ;; (rx (or (and line-start ";;" (0+ space) ?\n)
92 ;; (and line-start ?\n)))
93 ;;
94 ;; "\\$[I]d: [^ ]+ \\([^ ]+\\) "
95 ;; (rx (and "$Id: "
96 ;; (1+ (not (in " ")))
97 ;; " "
98 ;; (submatch (1+ (not (in " "))))
99 ;; " "))
100 ;;
101 ;; "\\\\\\\\\\[\\w+"
102 ;; (rx (and ?\\ ?\\ ?\[ (1+ word)))
103 ;;
104 ;; etc.
105
106 ;;; History:
107 ;;
108
109 ;;; Code:
110
111 (defconst rx-constituents
112 '((and . (rx-and 1 nil))
113 (seq . and) ; SRE
114 (: . and) ; SRE
115 (sequence . and) ; sregex
116 (or . (rx-or 1 nil))
117 (| . or) ; SRE
118 (not-newline . ".")
119 (nonl . not-newline) ; SRE
120 (anything . (rx-anything 0 nil))
121 (any . (rx-any 1 nil rx-check-any)) ; inconsistent with SRE
122 (any . ".") ; sregex
123 (in . any)
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
139 (\?? . zero-or-one)
140 (* . zero-or-more) ; SRE
141 (*? . zero-or-more)
142 (0+ . zero-or-more)
143 (+ . one-or-more) ; SRE
144 (+? . one-or-more)
145 (1+ . one-or-more)
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))
151 (line-start . "^")
152 (bol . line-start) ; SRE
153 (line-end . "$")
154 (eol . line-end) ; SRE
155 (string-start . "\\`")
156 (bos . string-start) ; SRE
157 (bot . string-start) ; sregex
158 (string-end . "\\'")
159 (eos . string-end) ; SRE
160 (eot . string-end) ; sregex
161 (buffer-start . "\\`")
162 (buffer-end . "\\'")
163 (point . "\\=")
164 (word-start . "\\<")
165 (bow . word-start) ; SRE
166 (word-end . "\\>")
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
180 (num . 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.")
221
222
223 (defconst rx-syntax
224 '((whitespace . ?-)
225 (punctuation . ?.)
226 (word . ?w)
227 (symbol . ?_)
228 (open-parenthesis . ?\()
229 (close-parenthesis . ?\))
230 (expression-prefix . ?\')
231 (string-quote . ?\")
232 (paired-delimiter . ?$)
233 (escape . ?\\)
234 (character-quote . ?/)
235 (comment-start . ?<)
236 (comment-end . ?>)
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.")
244
245
246 (defconst rx-categories
247 '((consonant . ?0)
248 (base-vowel . ?1)
249 (upper-diacritical-mark . ?2)
250 (lower-diacritical-mark . ?3)
251 (tone-mark . ?4)
252 (symbol . ?5)
253 (digit . ?6)
254 (vowel-modifying-diacritical-mark . ?7)
255 (vowel-sign . ?8)
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 . ?^)
268 (ascii . ?a)
269 (arabic . ?b)
270 (chinese . ?c)
271 (ethiopic . ?e)
272 (greek . ?g)
273 (korean . ?h)
274 (indian . ?i)
275 (japanese . ?j)
276 (japanese-katakana . ?k)
277 (latin . ?l)
278 (lao . ?o)
279 (tibetan . ?q)
280 (japanese-roman . ?r)
281 (thai . ?t)
282 (vietnamese . ?v)
283 (hebrew . ?w)
284 (cyrillic . ?y)
285 (can-break . ?|))
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.")
291
292
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.")
296
297
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 '\??)))
307 (let (old-op)
308 (while (and (not (null op)) (symbolp op))
309 (setq old-op 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.
314 (let ((new-op
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))))))
319 op)
320
321
322 (defun rx-check (form)
323 "Check FORM according to its car's parsing info."
324 (unless (listp form)
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))
332 (< nargs min-args))
333 (error "rx form `%s' requires at least %d args"
334 (car form) min-args))
335 (when (and (not (null max-args))
336 (> nargs 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))))))
344
345
346 (defun rx-group-if (regexp group)
347 "Put shy groups around REGEXP if seemingly necessary when GROUP
348 is non-nil."
349 (cond
350 ;; for some repetition
351 ((eq group '*) (if (rx-atomic-p regexp) (setq group nil)))
352 ;; for concatenation
353 ((eq group ':)
354 (if (rx-atomic-p
355 (if (string-match
356 "\\(?:[?*+]\\??\\|\\\\{[0-9]*,?[0-9]*\\\\}\\)\\'" regexp)
357 (substring regexp 0 (match-beginning 0))
358 regexp))
359 (setq group nil)))
360 ;; for OR
361 ((eq group '|) (setq group nil))
362 ;; do anyway
363 ((eq group t))
364 ((rx-atomic-p regexp t) (setq group nil)))
365 (if group
366 (concat "\\(?:" regexp "\\)")
367 regexp))
368
369
370 (defvar rx-parent)
371 ;; dynamically bound in some functions.
372
373
374 (defun rx-and (form)
375 "Parse and produce code from FORM.
376 FORM is of the form `(and FORM1 ...)'."
377 (rx-check form)
378 (rx-group-if
379 (mapconcat (lambda (x) (rx-form x ':)) (cdr form) nil)
380 (and (memq rx-parent '(* t)) rx-parent)))
381
382
383 (defun rx-or (form)
384 "Parse and produce code from FORM, which is `(or FORM1 ...)'."
385 (rx-check form)
386 (rx-group-if
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)))
391
392
393 (defun rx-anything (form)
394 "Match any character."
395 (if (consp form)
396 (error "rx `anything' syntax error: %s" form))
397 (rx-or (list 'or 'not-newline ?\n)))
398
399
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."
403 (let (m)
404 (cond
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)))))
414 ranges))
415
416
417 (defun rx-any-condense-range (args)
418 "Condense by side effect ARGS as range for Rx `any'."
419 (let (str
420 l)
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))
425 (t (push e l))))
426 args)
427 ;; condense overlapped ranges in L
428 (let ((tail (setq l (sort l #'car-less-than-car)))
429 d)
430 (while (setq d (cdr tail))
431 (if (>= (cdar tail) (1- (caar d)))
432 (progn
433 (setcdr (car tail) (max (cdar tail) (cdar d)))
434 (setcdr tail (cdr d)))
435 (setq tail d))))
436 ;; Separate small ranges to single number, and delete dups.
437 (nconc
438 (apply #'nconc
439 (mapcar (lambda (e)
440 (cond
441 ((= (car e) (cdr e)) (list (car e)))
442 ((= (1+ (car e)) (cdr e)) (list (car e) (cdr e)))
443 ((list e))))
444 l))
445 (delete-dups str))))
446
447
448 (defun rx-check-any-string (str)
449 "Check string argument STR for Rx `any'."
450 (let ((i 0)
451 c1 c2 l)
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))
457 (setq l (nconc
458 l
459 (append (substring str i (match-beginning 0)) nil))))
460 ;; range
461 (setq i (match-end 0)
462 c1 (aref str (match-beginning 0))
463 c2 (aref str (1- i)))
464 (cond
465 ((< c1 c2) (setq l (nconc l (list (cons c1 c2)))))
466 ((= c1 c2) (setq l (nconc l (list c1))))))
467 ;; rest?
468 (if (< i (length str))
469 (setq l (nconc l (append (substring str i) nil))))
470 l))
471
472
473 (defun rx-check-any (arg)
474 "Check arg ARG for Rx `any'."
475 (cond
476 ((integerp arg) (list arg))
477 ((symbolp arg)
478 (let ((translation (condition-case nil
479 (rx-form arg)
480 (error 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)))
486 (list arg))
487 ((stringp arg) (rx-check-any-string arg))
488 ((error
489 "rx `any' requires string, character, char pair or char class args"))))
490
491
492 (defun rx-any (form)
493 "Parse and produce code from FORM, which is `(any ARG ...)'.
494 ARG is optional."
495 (rx-check form)
496 (let* ((args (rx-any-condense-range
497 (apply
498 #'nconc
499 (mapcar #'rx-check-any (cdr form)))))
500 m
501 s)
502 (cond
503 ;; single close bracket
504 ;; => "[]...-]" or "[]...--.]"
505 ((memq ?\] args)
506 ;; set ] at the beginning
507 (setq args (cons ?\] (delq ?\] args)))
508 ;; set - at the end
509 (if (or (memq ?- args) (assq ?- args))
510 (setq args (nconc (rx-any-delete-from-range ?- args)
511 (list ?-)))))
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)
518 ;; to the end
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
524 ;; => "[]...-]"
525 ((setq m (rassq ?\] args))
526 ;; set ] at the beginning
527 (setq args (cons ?\] (rx-any-delete-from-range ?\] args)))
528 ;; set - at the end
529 (if (or (memq ?- args) (assq ?- args))
530 (setq args (nconc (rx-any-delete-from-range ?- args)
531 (list ?-)))))
532 ;; {no close bracket appears}
533 ;;
534 ;; bring single bar to the beginning
535 ((memq ?- args)
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))))
540 ;;
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)
546 (list ?^))))))
547 ;; some 1-char?
548 (if (and (null (cdr args)) (numberp (car args))
549 (or (= 1 (length
550 (setq s (regexp-quote (string (car args))))))
551 (and (equal (car args) ?^) ;; unnecessary predicate?
552 (null (eq rx-parent '!)))))
553 s
554 (concat "["
555 (mapconcat
556 (lambda (e) (cond
557 ((numberp e) (string e))
558 ((consp 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))))
566 (e)))
567 args
568 nil)
569 "]"))))
570
571
572 (defun rx-check-not (arg)
573 "Check arg ARG for Rx `not'."
574 (unless (or (and (symbolp arg)
575 (string-match "\\`\\[\\[:[-a-z]+:\\]\\]\\'"
576 (condition-case nil
577 (rx-form arg)
578 (error ""))))
579 (eq arg 'word-boundary)
580 (and (consp arg)
581 (memq (car arg) '(not any in syntax category))))
582 (error "rx `not' syntax error: %s" arg))
583 t)
584
585
586 (defun rx-not (form)
587 "Parse and produce code from FORM. FORM is `(not ...)'."
588 (rx-check form)
589 (let ((result (rx-form (cadr form) '!))
590 case-fold-search)
591 (cond ((string-match "\\`\\[^" result)
592 (cond
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)))
605 (t
606 (concat "[^" result "]")))))
607
608
609 (defun rx-not-char (form)
610 "Parse and produce code from FORM. FORM is `(not-char ...)'."
611 (rx-check form)
612 (rx-not `(not (in ,@(cdr form)))))
613
614
615 (defun rx-not-syntax (form)
616 "Parse and produce code from FORM. FORM is `(not-syntax SYNTAX)'."
617 (rx-check form)
618 (rx-not `(not (syntax ,@(cdr form)))))
619
620
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)
629 form
630 (let ((form (copy-sequence form)))
631 (setcdr (nthcdr skip form) (list (cons 'and tail)))
632 form))))
633
634
635 (defun rx-= (form)
636 "Parse and produce code from FORM `(= N ...)'."
637 (rx-check form)
638 (setq form (rx-trans-forms form 1))
639 (unless (and (integerp (nth 1 form))
640 (> (nth 1 form) 0))
641 (error "rx `=' requires positive integer first arg"))
642 (format "%s\\{%d\\}" (rx-form (nth 2 form) '*) (nth 1 form)))
643
644
645 (defun rx->= (form)
646 "Parse and produce code from FORM `(>= N ...)'."
647 (rx-check form)
648 (setq form (rx-trans-forms form 1))
649 (unless (and (integerp (nth 1 form))
650 (> (nth 1 form) 0))
651 (error "rx `>=' requires positive integer first arg"))
652 (format "%s\\{%d,\\}" (rx-form (nth 2 form) '*) (nth 1 form)))
653
654
655 (defun rx-** (form)
656 "Parse and produce code from FORM `(** N M ...)'."
657 (rx-check form)
658 (rx-form (cons 'repeat (cdr (rx-trans-forms form 2))) '*))
659
660
661 (defun rx-repeat (form)
662 "Parse and produce code from FORM.
663 FORM is either `(repeat N FORM1)' or `(repeat N M FORMS...)'."
664 (rx-check form)
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))
671 (> (nth 1 form) 0))
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)))
675 (< (nth 2 form) 0)
676 (not (integerp (nth 1 form)))
677 (< (nth 1 form) 0)
678 (< (nth 2 form) (nth 1 form)))
679 (error "rx `repeat' range error"))
680 (t
681 (format "%s\\{%d,%d\\}" (rx-form (nth 3 form) '*)
682 (nth 1 form) (nth 2 form)))))
683
684
685 (defun rx-submatch (form)
686 "Parse and produce code from FORM, which is `(submatch ...)'."
687 (concat "\\("
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))
693 "\\)"))
694
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))
704 "\\)")))
705
706 (defun rx-backref (form)
707 "Parse and produce code from FORM, which is `(backref N)'."
708 (rx-check form)
709 (format "\\%d" (nth 1 form)))
710
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)))
715
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'
723 is non-nil."
724 (rx-check form)
725 (setq form (rx-trans-forms form))
726 (let ((suffix (cond ((memq (car form) '(* + ?\s)) "")
727 ((memq (car form) '(*? +? ??)) "?")
728 (rx-greedy-flag "")
729 (t "?")))
730 (op (cond ((memq (car form) '(* *? 0+ zero-or-more)) "*")
731 ((memq (car form) '(+ +? 1+ one-or-more)) "+")
732 (t "?"))))
733 (rx-group-if
734 (concat (rx-form (cadr form) '*) op suffix)
735 (and (memq rx-parent '(t *)) rx-parent))))
736
737
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.
744
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;
751
752 a group or shy group: \\(...\\)
753 a character class: [...]
754 a single character: a
755
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)))
763 (cond
764 ((<= l 1))
765 ((= l 2) (= (aref r 0) ?\\))
766 ((= l 3) (string-match "\\`\\(?:\\\\[cCsS_]\\|\\[[^^]\\]\\)" r))
767 ((null lax)
768 (cond
769 ((string-match "\\`\\[^?\]?\\(?:\\[:[a-z]+:]\\|[^\]]\\)*\\]\\'" r))
770 ((string-match "\\`\\\\(\\(?:[^\\]\\|\\\\[^\)]\\)*\\\\)\\'" r)))))))
771
772
773 (defun rx-syntax (form)
774 "Parse and produce code from FORM, which is `(syntax SYMBOL)'."
775 (rx-check form)
776 (let* ((sym (cadr form))
777 (syntax (cdr (assq sym rx-syntax))))
778 (unless syntax
779 ;; Try sregex compatibility.
780 (cond
781 ((characterp sym) (setq syntax sym))
782 ((symbolp sym)
783 (let ((name (symbol-name sym)))
784 (if (= 1 (length name))
785 (setq syntax (aref name 0))))))
786 (unless syntax
787 (error "Unknown rx syntax `%s'" sym)))
788 (format "\\s%c" syntax)))
789
790
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))
796 t)
797
798
799 (defun rx-category (form)
800 "Parse and produce code from FORM, which is `(category SYMBOL)'."
801 (rx-check form)
802 (let ((char (if (integerp (cadr form))
803 (cadr form)
804 (cdr (assq (cadr form) rx-categories)))))
805 (format "\\c%c" char)))
806
807
808 (defun rx-eval (form)
809 "Parse and produce code from FORM, which is `(eval FORM)'."
810 (rx-check form)
811 (rx-form (eval (cadr form)) rx-parent))
812
813
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."
819 (rx-check form)
820 (let ((rx-greedy-flag (eq (car form) 'maximal-match)))
821 (rx-form (cadr form) rx-parent)))
822
823
824 (defun rx-regexp (form)
825 "Parse and produce code from FORM, which is `(regexp STRING)'."
826 (rx-check form)
827 (rx-group-if (cadr form) rx-parent))
828
829
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."
835 (if (stringp form)
836 (rx-group-if (regexp-quote form)
837 (if (and (eq rx-parent '*) (< 1 (length form)))
838 rx-parent))
839 (cond ((integerp form)
840 (regexp-quote (char-to-string form)))
841 ((symbolp form)
842 (let ((info (rx-info form nil)))
843 (cond ((stringp info)
844 info)
845 ((null info)
846 (error "Unknown rx form `%s'" form))
847 (t
848 (funcall (nth 0 info) form)))))
849 ((consp form)
850 (let ((info (rx-info (car form) 'head)))
851 (unless (consp info)
852 (error "Unknown rx form `%s'" (car form)))
853 (funcall (nth 0 info) form)))
854 (t
855 (error "rx syntax error at `%s'" form)))))
856
857
858 ;;;###autoload
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)))
864
865
866 ;;;###autoload
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.
870
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.
874
875 The following are valid subforms of regular expressions in sexp
876 notation.
877
878 STRING
879 matches string STRING literally.
880
881 CHAR
882 matches character CHAR literally.
883
884 `not-newline', `nonl'
885 matches any character except a newline.
886
887 `anything'
888 matches any character
889
890 `(any SET ...)'
891 `(in SET ...)'
892 `(char SET ...)'
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)'.
896
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.
901
902 `(not (any SET ...))'
903 matches any character not in SET ...
904
905 `line-start', `bol'
906 matches the empty string, but only at the beginning of a line
907 in the text being matched
908
909 `line-end', `eol'
910 is similar to `line-start' but matches only at the end of a line
911
912 `string-start', `bos', `bot'
913 matches the empty string, but only at the beginning of the
914 string being matched against.
915
916 `string-end', `eos', `eot'
917 matches the empty string, but only at the end of the
918 string being matched against.
919
920 `buffer-start'
921 matches the empty string, but only at the beginning of the
922 buffer being matched against. Actually equivalent to `string-start'.
923
924 `buffer-end'
925 matches the empty string, but only at the end of the
926 buffer being matched against. Actually equivalent to `string-end'.
927
928 `point'
929 matches the empty string, but only at point.
930
931 `word-start', `bow'
932 matches the empty string, but only at the beginning of a word.
933
934 `word-end', `eow'
935 matches the empty string, but only at the end of a word.
936
937 `word-boundary'
938 matches the empty string, but only at the beginning or end of a
939 word.
940
941 `(not word-boundary)'
942 `not-word-boundary'
943 matches the empty string, but not at the beginning or end of a
944 word.
945
946 `symbol-start'
947 matches the empty string, but only at the beginning of a symbol.
948
949 `symbol-end'
950 matches the empty string, but only at the end of a symbol.
951
952 `digit', `numeric', `num'
953 matches 0 through 9.
954
955 `control', `cntrl'
956 matches ASCII control characters.
957
958 `hex-digit', `hex', `xdigit'
959 matches 0 through 9, a through f and A through F.
960
961 `blank'
962 matches space and tab only.
963
964 `graphic', `graph'
965 matches graphic characters--everything except ASCII control chars,
966 space, and DEL.
967
968 `printing', `print'
969 matches printing characters--everything except ASCII control chars
970 and DEL.
971
972 `alphanumeric', `alnum'
973 matches letters and digits. (But at present, for multibyte characters,
974 it matches anything that has word syntax.)
975
976 `letter', `alphabetic', `alpha'
977 matches letters. (But at present, for multibyte characters,
978 it matches anything that has word syntax.)
979
980 `ascii'
981 matches ASCII (unibyte) characters.
982
983 `nonascii'
984 matches non-ASCII (multibyte) characters.
985
986 `lower', `lower-case'
987 matches anything lower-case.
988
989 `upper', `upper-case'
990 matches anything upper-case.
991
992 `punctuation', `punct'
993 matches punctuation. (But at present, for multibyte characters,
994 it matches anything that has non-word syntax.)
995
996 `space', `whitespace', `white'
997 matches anything that has whitespace syntax.
998
999 `word', `wordchar'
1000 matches anything that has word syntax.
1001
1002 `not-wordchar'
1003 matches anything that has non-word syntax.
1004
1005 `(syntax 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.'.
1009
1010 `whitespace' (\\s- in string notation)
1011 `punctuation' (\\s.)
1012 `word' (\\sw)
1013 `symbol' (\\s_)
1014 `open-parenthesis' (\\s()
1015 `close-parenthesis' (\\s))
1016 `expression-prefix' (\\s')
1017 `string-quote' (\\s\")
1018 `paired-delimiter' (\\s$)
1019 `escape' (\\s\\)
1020 `character-quote' (\\s/)
1021 `comment-start' (\\s<)
1022 `comment-end' (\\s>)
1023 `string-delimiter' (\\s|)
1024 `comment-delimiter' (\\s!)
1025
1026 `(not (syntax SYNTAX))'
1027 matches a character that doesn't have syntax SYNTAX.
1028
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.
1032
1033 `consonant' (\\c0 in string notation)
1034 `base-vowel' (\\c1)
1035 `upper-diacritical-mark' (\\c2)
1036 `lower-diacritical-mark' (\\c3)
1037 `tone-mark' (\\c4)
1038 `symbol' (\\c5)
1039 `digit' (\\c6)
1040 `vowel-modifying-diacritical-mark' (\\c7)
1041 `vowel-sign' (\\c8)
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^)
1054 `ascii' (\\ca)
1055 `arabic' (\\cb)
1056 `chinese' (\\cc)
1057 `ethiopic' (\\ce)
1058 `greek' (\\cg)
1059 `korean' (\\ch)
1060 `indian' (\\ci)
1061 `japanese' (\\cj)
1062 `japanese-katakana' (\\ck)
1063 `latin' (\\cl)
1064 `lao' (\\co)
1065 `tibetan' (\\cq)
1066 `japanese-roman' (\\cr)
1067 `thai' (\\ct)
1068 `vietnamese' (\\cv)
1069 `hebrew' (\\cw)
1070 `cyrillic' (\\cy)
1071 `can-break' (\\c|)
1072
1073 `(not (category CATEGORY))'
1074 matches a character that doesn't have category CATEGORY.
1075
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.
1081
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'.
1086
1087 `(submatch-n N SEXP1 SEXP2 ...)'
1088 `(group-n N SEXP1 SEXP2 ...)'
1089 like `group', but make it an explicitly-numbered group with
1090 group number N.
1091
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
1096 regular expression.
1097
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.
1103
1104 `(maximal-match SEXP)'
1105 produce a greedy regexp for SEXP. This is the default.
1106
1107 Below, `SEXP ...' represents a sequence of regexp forms, treated as if
1108 enclosed in `(and ...)'.
1109
1110 `(zero-or-more SEXP ...)'
1111 `(0+ SEXP ...)'
1112 matches zero or more occurrences of what SEXP ... matches.
1113
1114 `(* SEXP ...)'
1115 like `zero-or-more', but always produces a greedy regexp, independent
1116 of `rx-greedy-flag'.
1117
1118 `(*? SEXP ...)'
1119 like `zero-or-more', but always produces a non-greedy regexp,
1120 independent of `rx-greedy-flag'.
1121
1122 `(one-or-more SEXP ...)'
1123 `(1+ SEXP ...)'
1124 matches one or more occurrences of SEXP ...
1125
1126 `(+ SEXP ...)'
1127 like `one-or-more', but always produces a greedy regexp.
1128
1129 `(+? SEXP ...)'
1130 like `one-or-more', but always produces a non-greedy regexp.
1131
1132 `(zero-or-one SEXP ...)'
1133 `(optional SEXP ...)'
1134 `(opt SEXP ...)'
1135 matches zero or one occurrences of A.
1136
1137 `(? SEXP ...)'
1138 like `zero-or-one', but always produces a greedy regexp.
1139
1140 `(?? SEXP ...)'
1141 like `zero-or-one', but always produces a non-greedy regexp.
1142
1143 `(repeat N SEXP)'
1144 `(= N SEXP ...)'
1145 matches N occurrences.
1146
1147 `(>= N SEXP ...)'
1148 matches N or more occurrences.
1149
1150 `(repeat N M SEXP)'
1151 `(** N M SEXP ...)'
1152 matches N to M occurrences.
1153
1154 `(backref N)'
1155 matches what was matched previously by submatch N.
1156
1157 `(eval FORM)'
1158 evaluate FORM and insert result. If result is a string,
1159 `regexp-quote' it.
1160
1161 `(regexp REGEXP)'
1162 include REGEXP in string notation in the result."
1163 (cond ((null regexps)
1164 (error "No regexp"))
1165 ((cdr regexps)
1166 (rx-to-string `(and ,@regexps) t))
1167 (t
1168 (rx-to-string (car regexps) t))))
1169 \f
1170 ;; ;; sregex.el replacement
1171
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)
1177 \f
1178 (provide 'rx)
1179
1180 ;;; rx.el ends here