Subject: Re: bug#6384: Teach rx explicitly numbered submatches

From: Lennart Borgman <[email-masked]>
Date: Wed, 9 Jun 2010 20:19:52 +0200

On Wed, Jun 9, 2010 at 8:16 PM, Stefan Monnier <[email-masked]> wrote:
>> Explicitly numbered groups are of the form
>
>>   \(?nn:...\)
>
>> Here is a patch for it. Someone with good lisp fu might check it.
>
> I see an elisp file, not  apatch.  Can you resend it as a patch, please?

Ah, wrote the wrong buffer ... ;-)

Here it is, it is very small.
=== modified file 'lisp/emacs-lisp/rx.el'
--- trunk/lisp/emacs-lisp/rx.el	2010-01-13 08:35:10 +0000
+++ patched/lisp/emacs-lisp/rx.el	2010-06-09 17:18:56 +0000
@@ -132,6 +132,7 @@
     (>=			. (rx->= 2 nil))   ; SRE
     (**			. (rx-** 2 nil))   ; SRE
     (submatch		. (rx-submatch 1 nil)) ; SRE
+    (submatch-n		. (rx-submatch-n 2 nil))
     (group		. submatch)
     (zero-or-more	. (rx-kleene 1 nil))
     (one-or-more	. (rx-kleene 1 nil))
@@ -674,6 +675,19 @@
             (mapconcat (lambda (re) (rx-form re ':)) (cdr form) nil))
           "\\)"))
 
+(defun rx-submatch-n (form)
+  "Parse and produce code from FORM, which is `(submatch-n ...)'."
+  (unless (and (integerp (nth 1 form))
+               (> (nth 1 form) 0))
+    (error "rx `submatch-n' requires positive integer first arg"))
+  (concat "\\(\?"
+          (format "%d:" (nth 1 form))
+          (if (= 3 (length form))
+              ;; Only one sub-form.
+              (rx-form (caddr form))
+            ;; Several sub-forms implicitly concatenated.
+            (mapconcat (lambda (re) (rx-form re ':)) (cddr form) nil))
+          "\\)"))
 
 (defun rx-backref (form)
   "Parse and produce code from FORM, which is `(backref N)'."