Prompt to prepend text at line or lines

I have a Drafts Syntax that changes the text colour of lines that begin with a certain characters. But instead of having to manually place the cursor and navigate the iPhone keyboard to find the specific key that I want, I’d like to speed up my workflow with a prompt action.

Is this something that is easy to achieve and can you point me in the right direction please?

Here is what I want to achieve:

Start with these 5 predefined tokens
("? ", "_ ", "• ", "- ", "x ").

Then, I want to create a prompt that will look at the current line that the cursor is on or currently selected lines and show my predefined tokens as options in the prompt allowing me to select one of them.

If any of these predefined tokens do already exist at the beginning of the selected line or at the beginning of any of the selected lines, replace that token with the token that was just chosen in the prompt.

And if any of the predefined tokens do not already exist at the beginning of any of the lines, then go ahead and insert the selected token at the beginning of the selected line(s).

Update: All sorted. I’ve managed to cobble something together that seems to do what I want for now.

// Add prefix or suffix to the selected lines.
var [oldStart, oldLen] = editor.getSelectedRange();
var [start, len] = editor.getSelectedLineRange();

var lineText = editor.getTextInRange(start, len);
if (lineText.endsWith("\n")) { // trailing LF doesn't count
	lineText = lineText.slice(0, -1);
	len -= 1;
}

// Prepare the prompt and get the text from the user.
var p = Prompt.create();
p.addSegmentedControl("prefix", "", ["- ", "• ", "? ", "_ ", "X "],"- ")
p.addButton("Add");
p.addButton("Remove");

var didSelect = p.show();

if (didSelect) { // make the changes
	// Get the affixes
	let prefix = p.fieldValues["prefix"];
	
	// Edit the selected lines.
	let lines = lineText.split('\n');
	
	if (p.buttonPressed == "Add") {
		lines.forEach((line, i) => lines[i] = prefix + line);
	}
	else { // remove
		if (prefix != "") {
			let preLen = prefix.length;
			lines.forEach(function(line, i) {
				if (line.slice(0, preLen) == prefix) {
					lines[i] = line.slice(preLen);
				}
			});
		}
	}
	
	// Replace the text in the editor and select it.
	let replacement = lines.join('\n')
	editor.setTextInRange(start, len, replacement);
	// editor.setSelectedRange(start, replacement.length);
	editor.activate();
}
else { // put selection back
	editor.setSelectedRange(oldStart, oldLen);
	editor.activate();
}
2 Likes