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
4
  • emacs.stackexchange.com/tags/elisp/info
    – Drew
    Commented Mar 1, 2022 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
    Commented Mar 4, 2022 at 14:48
  • @phils get-labels() should return fig:bar as well. Currently it only returns fig:foo
    – jjk
    Commented Mar 4, 2022 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 emacs.stackexchange.com/q/5568/454.
    – phils
    Commented Mar 4, 2022 at 23:12

1 Answer 1

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.

4
  • I only got name or NAME returned. No values from any attribute i.e. +#name or +#label
    – jjk
    Commented Mar 4, 2022 at 14:27
  • @jjk: WFM, please see the code
    – sds
    Commented Mar 4, 2022 at 18:57
  • Now yasnippet returns all keys but I need the values
    – jjk
    Commented Mar 4, 2022 at 20:59
  • So replace (match-string-no-properties 1) with (match-string-no-properties 2)
    – sds
    Commented Mar 4, 2022 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.