Late to the party (and my first post here, by the way), but I think this might be useful to others too. The accepted answer works perfectly when yanking inside emacs again, but the actual text copied to the system clipboard is still the full org-mode syntax. I wanted something that could copy a link out of both org-mode and emacs. Use cases: I've been doing a lot of web dev lately, and I often use multiple browsers. Only one of them can be the default for the C-c c-o
shortcut, and sometimes I want to open a link in a non-default one. Also, pasting links to coworkers on Slack, et cetera.
Long story short, I've come up with this solution by mixing and matching the accepted answer:
(defun my-org-export-url ()
(interactive)
(let* ((link-info (assoc :link (org-context)))
(text (when link-info
(buffer-substring-no-properties (or (cadr link-info) (point-min))
(or (caddr link-info) (point-max))))))
(if (not text)
(error "Not in org link")
(string-match org-bracket-link-regexp text)
(kill-new (substring text (match-beginning 1) (match-end 1))))))
This will copy to the clipboard the link only part of an org-mode link.
In fact, I have integrated both the previous answer's solution and this new function inside my .emacs
, each with its own keybinding. Full code here:
(defun my-yank-org-link (text)
(if (derived-mode-p 'org-mode)
(insert text)
(string-match org-bracket-link-regexp text)
(insert (substring text (match-beginning 1) (match-end 1)))))
(defun my-org-copy-smart-url ()
(interactive)
(let* ((link-info (assoc :link (org-context)))
(text (when link-info
(buffer-substring-no-properties (or (cadr link-info) (point-min))
(or (caddr link-info) (point-max))))))
(if (not text)
(error "Not in org link")
(add-text-properties 0 (length text) '(yank-handler (my-yank-org-link)) text)
(kill-new text))))
(global-set-key (kbd "C-c c") 'my-org-copy-smart-url)
(defun my-org-export-url ()
(interactive)
(let* ((link-info (assoc :link (org-context)))
(text (when link-info
(buffer-substring-no-properties (or (cadr link-info) (point-min))
(or (caddr link-info) (point-max))))))
(if (not text)
(error "Not in org link")
(string-match org-bracket-link-regexp text)
(kill-new (substring text (match-beginning 1) (match-end 1))))))
(global-set-key (kbd "C-c e") 'my-org-export-url)
I've chosen the C-c e
and C-c c
keybindings because they are good mnemonics for e
xport and c
opy and they are unused in org-mode. They also somehow fit with the already existing keybinding C-c C-o
for o
pening links.