Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs Lisp: can the same regexp match two different patterns with same number of groupings?

Tags:

regex

emacs

elisp

I've started writing Emacs scripts according to directions given at http://www.emacswiki.org/emacs/EmacsScripts, which basically say that your scripts should start with:

:;exec emacs --script "$0" $@ 

Now I'd like to customize auto-mode-interpreter-regexp' accordingly, to make Emacs scripts automatically loaded withemacs-lisp-mode'.

The original `auto-mode-interpreter-regexp' was meant to match:

#! /bin/bash
#! /usr/bin/env perl

and so on, and thus it was this one:

"\\(?:#![   ]?\\([^     \n]*/bin/env[   ]\\)?\\([^  \n]+\\)\\)"

I tried adding the new regexp as an alternative:

(setq auto-mode-interpreter-regexp
   (concat ;; match "#! /bin/bash", "#! /usr/bin/env perl", etc.
           "\\(?:#![    ]?\\([^     \n]*/bin/env[   ]\\)?\\([^  \n]+\\)\\)"
           ;; or
           "\\|"
           ;; match ":;exec emacs "
           "\\(?::;[    ]?\\(exec\\)[   ]+\\([^     \n]+\\)[    ]*\\)"))

but this one, while matching the whole string, failed to capture its submatches, especially the second one which is needed to detect the interpreter. Thus, I've mixed the regexp to match both headers at the same time:

(setq auto-mode-interpreter-regexp
    (concat ;; match "#!" or ":;"
            "\\(?:#!\\|:;\\)"
            ;; optional spaces
            "[  ]?"
            ;; match "/bin/bash", "/usr/bin/env" or "exec" 
            "\\(\\[^    \n]*/bin/env[   ]\\|exec[   ]\\)?"
            ;; match interpreter
            "\\([^  \n]+\\)"))

Could I have done better? Thank you.

like image 336
Eleno Avatar asked Feb 02 '12 23:02

Eleno


1 Answers

Regexp in Emacs supports the use of "explicitly numbered group" construct to assign a group number to any submatch. See Elisp Manual 34.3.1.3 Backslash Constructs in Regular Expressions.

The syntax is ‘(?num: ... )’, where num is the chosen group number.

like image 190
huaiyuan Avatar answered Oct 04 '22 00:10

huaiyuan