1

If the point is on a link on org mode, how can I copy the link (complete link, including url and description) directly into the kill ring without marking the whole link, killing it and yanking it again?

1
  • I presume you want to copy it into the kill ring so that you can yank it elsewhere? – NickD Jan 28 at 2:17
4

Here is an implementation using the Org mode parser in org-element.el as mentioned in my comment to Firmin Martin's answer:

(defun ndk/link-fast-copy ()
   (interactive)
   (let* ((context (org-element-context))
          (type (org-element-type context))
          (beg (org-element-property :begin context))
          (end (org-element-property :end context)))
     (when (eq type 'link)
      (copy-region-as-kill beg end))))

(define-key org-mode-map (kbd "C-c z") #'ndk/link-fast-copy)

I prefer it because it uses the Org mode parser, not ad-hoc regular expressions which are difficult to understand and error-prone. Also, there is some checking that I'm actually in the context of the link and if not the function does nothing.

To be sure, the parser uses regexps underneath the covers for its lexical analysis, but they are presumably well-tested and robust enough that I, as a user, do not have to worry about their correctness.

1
  • Great, thanks a lot! – student Jan 28 at 21:08
1

Try this function. Constraint: you should be positioned after "[[".

(defun my/org-link-copy-at-point ()
  (interactive)
  (save-excursion
    (let* ((ol-regex "\\[\\[.*?:.*?\\]\\(\\[.*?\\]\\)?\\]")
       (beg (re-search-backward "\\[\\["))
       (end (re-search-forward ol-regex))
       (link-string (buffer-substring-no-properties (match-beginning 0) (match-end 0)))) 
      (kill-new link-string)
      (message "Org link %s is copied." link-string))))

2
  • My objection to this is that in order to figure out whether it's right, I need to understand the regexp (that's one of the problems with using regexps). Org mode has a parser to deal with this kind of problem: it's in org-element.el and there is (developer) documentation for it on Worg. I would recommend that you use that, rather than reinventing the wheel. It does have some disadvantages: it is slower than doing it by hand and it too might have bugs (although they tend to be widely seen and therefore quickly fixed). But it is a standard foundation on which one can build. – NickD Jan 28 at 14:45
  • @NickD Indeed! Thanks for the comment. – Firmin Martin Jan 28 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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