0

How can I match the values for the keys (org mode attributes) #+label OR #+name?

Example: Using get-labels () I got fig:foo. Nice.

How can I get fig:bar as well?

#+label: fig:foo
#+name: fig:bar

While this one works for #+label:

(re-search-forward "#\\+label: \\([a-zA-z0-9:-]*\\)" (point-max) t)

This one fails i.e. matches only #+name:

(re-search-forward "#\\+label:\\|#\\+name: \\([a-zA-z0-9:-]*\\)" (point-max) t)

Used here

(defun get-labels ()
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (let ((matches '()))
      (while (re-search-forward "#\\+label: \\([a-zA-z0-9:-]*\\)" (point-max) t)
        (add-to-list 'matches (match-string-no-properties 1) t))
      matches)))

.

# -*- mode: snippet -*-
# --
cref:${1:$$(yas-choose-value (get-labels))} $0
jjk
  • 734
  • 4
  • 18
  • https://emacs.stackexchange.com/tags/elisp/info – Drew Mar 01 '22 at 22:57
  • "#\\+label:\\|#\\+name: \\([a-zA-z0-9:-]*\\)" is either "#\\+label:" or "#\\+name: \\([a-zA-z0-9:-]*\\)". Is that what you meant to match? – phils Mar 04 '22 at 14:48
  • @phils get-labels() should return fig:bar as well. Currently it only returns fig:foo – jjk Mar 04 '22 at 18:06
  • 1
    I highly, highly recommend that you spend some time with M-x re-builder and experiment with the various kinds of regexp syntax to get your head around them. Read the regexp sub-sections under (emacs)Search and test the various things to see how they work. Spending a bit of time doing this should clarify things for you enormously. Also take note of https://emacs.stackexchange.com/q/5568/454. – phils Mar 04 '22 at 23:12

1 Answers1

3

You need to use \(...\|...\) for grouping:

"#\\+\\(label\\|name\\): \\([a-zA-z0-9:-]*\\)"

E.g., C-j (eval-print-last-sexp) after (get-labels) inserts ("name" "label"):

(defun get-labels ()
  (interactive)
  (let ((matches '()))
    (save-excursion
      (while (re-search-forward "#\\+\\(label\\|name\\): \\([a-zA-z0-9:-]*\\)" (point-max) t)
        (push (match-string-no-properties 1) matches)))
    (delete-dups matches)))
(get-labels)
#+label: fig:foo
#+name: fig:bar

PS. You should never use add-to-list for a let-bound variables.

sds
  • 6,104
  • 22
  • 39