April 14, 2020 at 1:56 PM by Dr. Drang
A week or two ago, this question from TDK_SA90 (my favorite cassette for taping albums) popped up on the Drafts forum. What TDK wanted was a Drafts action that would
append or prepend inserted text, and also, have it act on only selected lines in the draft - all lines if no selection made.
I already had an action that would add line numbers to selected text (or the entire draft if nothing was selected), and I had worked through the logic of the Drafts
getSelectedLineRange function, so this seemed like both a simple extension of what I’d already done and an action I’d use myself.
I wanted the action to work like BBEdit’scommand in the menu, which allows you to add or remove text from either the beginning or end of every selected line.
The action’s user interface is a little different, but I think it’s easy to understand.
Lines 3–15 work out which lines are going to prefixed or suffixed. If any text is selected, those lines—extending out to the beginning of the first line and the end of the last line—will be edited. If no text is selected, then the entire draft will be edited. There’s a bit of trickiness when the selection ends with a linefeed character; that detail is covered in my post on lines and Drafts.
Lines 17–23 define the prompt you see above. The commands for the Prompt class are defined in the Drafts documentation.
Line 25 displays the prompt and, if the user didn’t cancel, sets
didSelect to true and fills the various fields of the
p variable that was defined in Line 18.
If the user canceled, Lines 64–65 are executed. These ensure that focus goes back to the draft (it was lost when the prompt appeared) and that whatever selection was active before the prompt is restored.
Lines 28—61 are the meat of the script. Line 33 splits the selected lines into an array of strings, one for each line. If the user tapped the
lines array and adds text to the beginning and end of each line. If the user tapped the Remove button, things are a more complicated.
If the user entered any prefix text, Lines 39–46 look for that text at the front of each selected line and delete it if it’s there. If the prefix text isn’t there, the line is left alone. If the user didn’t enter any prefix text, this entire set of lines is skipped.
Lines 47–54 do basically the same thing for suffix text.
Finally, Lines 58–61, replace the text in the draft with the lines that have just been editing, adjusts the selection, and restores focus to the draft.
replace command for some of this, it’s because prefixes and suffixes are anchored to the beginnings and ends of strings, and the only way I know to do that with
replace is to use regular expressions with
$. That would mean the text the user enters at the prompt would be interpreted as a regular expression, which can be annoying if the prefix or suffix text contains characters that have special meaning in a regular expression.