DEV Community

Willem van den Ende
Willem van den Ende

Posted on

How to replace an org-mode link by its description

Table of Contents

  1. Problem
  2. Solution
  3. Epilogue

Problem

Before turning a note into a blog post, I want to remove some of the org-mode links that are internal to my notes. There did not appear to be a way to do this out of the box. The answers I found on emacs stackexchange used regular expressions or deleted a space after the link.

I used a fair number of tabs to cobble up a solution, so I thought it would be worth sharing.

org-delete-link by a throw-away account almost worked, and uses org-modes’ Abstract Syntax Three through the org-element api. User Timm correctly pointed out a space after the link would also be deleted.

Solution

I prefer Andrew Swann’s name for the function, so here is my fixed mashup:

 (defun org-replace-link-by-link-description () "Remove the link part of an org-mode link at point and keep only the description" (interactive) (let ((elem (org-element-context))) (if (eq (car elem) 'link) (let* ((content-begin (org-element-property :contents-begin elem)) (content-end (org-element-property :contents-end elem)) (link-begin (org-element-property :begin elem)) (link-end (org-element-property :end elem))) (if (and content-begin content-end) (let ((content (buffer-substring-no-properties content-begin content-end))) (delete-region link-begin (- link-end 1)) (insert content))))))) 
Enter fullscreen mode Exit fullscreen mode

Subtract one from link-end and it works. This is the fixed line:

 (delete-region link-begin (- link-end 1)) 
Enter fullscreen mode Exit fullscreen mode

Original question on emacs stackexchange: in org-mode, how to remove a link?

Epilogue

Why do I want this? I want to publish only some of my org-roam notes. Org-roam notes are like private wiki-pages. It also allows (with a bookmarklet) to clip webpages to their own org-roam note. At the top of the note, there is a roamkey that then contains the url of the page. I want to export my org-roam notes to markdown. Links should be to orignal webpages, instead of my private clippings with notes.

This is a baby step in the right direction.

FYI macs is perfectly usable without writing any code, using a distribution like Doom Emacs (my current) or Spacemacs (my previous). This is the first time in six years of regular emacs use that I’m writing a non-trivial amount of code for it.

Top comments (0)