Script: Fix upwards relative image links (../) in Markdown

DT does not support upward relative image links in Markdown documents like this one:
[Alt-Text](../group/image.png). The reasoning for that is sound (see the documentation). However, one can fix Markdown documents with a simple JavaScript script. As shown, it works with the currently selected files, but it can be easily modified to work in a smart rule, too.

(() => {
  const app = Application("DEVONthink 3");
  const selection = app.selectedRecords();
  /* Use only markdown records from current selection and loop over them */
  selection.filter(r => r.type() === "markdown").forEach(r => {
    /* Get the text of the record */
    const txt = r.plainText();
    /* Get the full path to the location group */
    const location = r.location();
    /* Get the full path up to the location group */
    const parent = location.replace(/(.*\/).*\//,"$1");
    /* Replace all occurences of ".." in links by "parent" */
    r.plainText = txt.replaceAll(/\(\.\.\//g,`(${parent}`);
    })
})()

The approach is straightforward, using regular expressions to replace .. in links by the absolute path to the parent group.
Note This might not always give the desired result if the Markdown documents belong to different groups. However, directly after importing them this shouldn’t occur.

1 Like