Script: Fix transclusion links pointing to deleted document(s)

In a recent thread, the point of transclusion links pointing to invalid (i.e. no longer existing) documents was raised.

The following (JavaScript) is a proof of concept/suggestion of how to handle these links. It uses a fixed UUID for demonstration purposes. In real life, one would probably have that script as part of a smart rule that is triggered on move to trash and accesses the UUID of the document that is trashed.

The code then replaces all transclusion links referring to this UUID with a red link saying “Document missing”. This, again, is just illustrating the approach. In real life, one would use the commented out app.search() call instead of app.selectedRecords(). Note: search will only find the UUIDs in a link if the hidden preference IndexRawMarkdownSource needs to be set. Afterwards, you have to rebuild the database.

(() => {
  const app = Application("DEVONthink 3")
  const UUID = "8770B7C0-248C-45BA-AFDA-95FE61E6537A";
  const link = `x-devonthink-item://${UUID}`;
  const records = app.selectedRecords(); /* app.search(`text:${UUID}`); */
  const regularExpr = new RegExp(`({{${link}}}|!\\[\\[${link}\\]\\])`,'g');
  records.forEach(r => {
    const txt = r.plainText();
    r.plainText = txt.replaceAll(regularExpr,`[Document ${UUID} missing](${link} style="color: red")`);
  })
})()
4 Likes