The following elisp function will take a link around the current point as recognised by org-bracket-link-regexp
, so either [[Link][Description]]
or [[Link]]
, and replace it by Description
in the first case or Link
in the second case.
New version: for org 9.3 or newer (also added save-excursion
as in the answer of @Chris)
(defun afs/org-replace-link-by-link-description ()
"Replace an org link by its description or if empty its address"
(interactive)
(if (org-in-regexp org-link-bracket-re 1)
(save-excursion
(let ((remove (list (match-beginning 0) (match-end 0)))
(description
(if (match-end 2)
(org-match-string-no-properties 2)
(org-match-string-no-properties 1))))
(apply 'delete-region remove)
(insert description)))))
Alternatively the following elisp function will do such a replacement on all links in the buffer or region:
(defun afs/org-replace-all-links-by-description (&optional start end)
"Find all org links and replace by their descriptions."
(interactive
(if (use-region-p) (list (region-beginning) (region-end))
(list (point-min) (point-max))))
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(while (re-search-forward org-link-bracket-re nil t)
(replace-match (match-string-no-properties
(if (match-end 2) 2 1)))))))
The above is for org 9.4, where org-match-string-no-properities
has been obseleted in favour of match-string-no-properties
.
Old version: before org 9.3
(defun afs/org-replace-link-by-link-description ()
"Replace an org link by its description or if empty its address"
(interactive)
(if (org-in-regexp org-bracket-link-regexp 1)
(let ((remove (list (match-beginning 0) (match-end 0)))
(description (if (match-end 3)
(org-match-string-no-properties 3)
(org-match-string-no-properties 1))))
(apply 'delete-region remove)
(insert description))))
In org version 9.3 org-bracket-link-regexp
was obsoleted, but aliased to the new org-link-bracket-re
. The new regexp is documented in ol.el
as
org-link-bracket-re
(rx (seq "[["
;; URI part: match group 1.
(group
(one-or-more
(or (not (any "[]\\"))
(and "\\" (zero-or-more "\\\\") (any "[]"))
(and (one-or-more "\\") (not (any "[]"))))))
"]"
;; Description (optional): match group 2.
(opt "[" (group (+? anything)) "]")
"]"))
so the second group now matches the description of the link if present.
C-c C-l
and deleting the existing link works.