As is often the case, as I use Drafts I find things that I need to do and write a script to fix it for me! In this case, I have a habit of planning to add links later in my text, but find it a pain to go through the whole article to find them and the find function is too darn manual for me. There were already a few actions in the Actions Directory, but they didn’t quite work the way I wanted them to. If you haven’t guessed where this is going yet: I wrote my own!

This action using the Script function in Drafts, and some good old regular expressions. The code itself can be broken down into eight steps:

  1. Get the contents of the Draft.
  2. Create the regular expression.
  3. Parse the contents of the Draft with the regular expression to get a list of matches
  4. Create a prompt
  5. Add each match to the prompt
  6. Show the prompt
  7. Go through each match again and replace it (within the whole content) with the information provided through the prompt.
  8. Update the draft.
let content = draft.content; //get the content of the draft

let pattern = /\[[^\]]+]\(\)/g; //build the regex

let matches = content.match(pattern); //find all the empty links

//create the prompt
let p = Prompt.create();
p.title = "Missing Links";

//add each empty link to the prompt
matches.forEach(function (match, index){
    p.addTextField(index, match.replace('[', '').replace(']()', ''), "");
});

//show the prompt
p.addButton("OK");
let didSelect = p.show();

//if the prompt wasn't cancelled
if (didSelect) {
    if (p.buttonPressed == "OK") {
        //go through each empty link and replace it with the updated information
        Object.keys(p.fieldValues).forEach(function (index) {
            content = content.replace(matches[index], matches[index].replace('()', '('+p.fieldValues[index]+')'))
        });
    }
}

//update the draft
draft.content = content;
draft.update();

The idea is I can run this at the end of writing, deal with all my links in one prompt, and get on with things. It’s the kind of action I’ll include as a step in other actions to make sure I don’t accidentally post empty links!

Get it from the action directory</a