Hung-Yi's LogoHung-Yi’s Journal

Easily Copy an Org-mode URL

Emacs doesn't have a built in function to copy the URL of a hyperlink in Org-mode. This function will let you do just that.

I’m sharing a simple function to copy/kill/yank the URL of an Org-mode link at the cursor/point within Emacs. It handles plain URLs too: ones that don’t have the square bracket delimiters or a description.

It’s been useful when I want the URL of a link other than for browsing, for example to paste into a terminal or a messaging app.

(defun my-org-retrieve-url-from-point ()
  "Copies the URL from an org link at the point"
  (let ((plain-url (url-get-url-at-point)))
    (if plain-url
          (kill-new plain-url)
          (message (concat "Copied: " plain-url)))
      (let* ((link-info (assoc :link (org-context)))
             (text (when link-info
                      (or (cadr link-info) (point-min))
                      (or (caddr link-info) (point-max))))))
        (if (not text)
            (error "Oops! Point isn't in an org link")
          (string-match org-link-bracket-re text)
          (let ((url (substring text (match-beginning 1) (match-end 1))))
            (kill-new url)
            (message (concat "Copied: " url))))))))

In Doom Emacs I’ve bound it to SPC m l y for convenience:

(use-package! org
  (map! :map org-mode-map
        (:prefix ("l" . "links")
         "y" #'my-org-retrieve-url-from-point)))