button-lock icon indicating copy to clipboard operation
button-lock copied to clipboard

Using regexp groups in the action

Open jkitchin opened this issue 6 years ago • 2 comments

I find myself doing something like this a lot lately. I have a regexp with some groups in it that match text I want to make a button of, but in the action I only need to use part of the text. For example below will make a #hashtag into a button, but in the action I only need the "hashtag", e.g. to open the hashtag on Twitter or something.

;; The hashtag is in group 1.
(setq hashtag-regexp "\\(^\\|[[:space:]]\\|\\s(\\)\\(?2:#\\(?1:[[:alnum:]]*\\)\\)")

(button-lock-set-button
 hashtag-regexp
 (lambda ()
   (interactive)
   (goto-char (1- (previous-single-property-change (point) 'button-lock)))
   (save-match-data
     (looking-at hashtag-regexp)
     (message (match-string-no-properties 1))))
 :grouping 2
 :additional-property 'button-lock
 :face (list 'link)
 :help-echo "Click me to open the hashtag.")

The most robust way I have found so far is via property searching to get to the beginning of the match, and then "look at it" again. Is this the right approach to doing this?

jkitchin avatar Mar 03 '18 20:03 jkitchin