Beginner JavaScript Insert Position Question

I’ve been working through the various examples in the action directory and have managed to make the script do what I want, but in a less than elegant manner. I’m hoping some kind soul can point me in the right direction for the final cleanup, or point me to some good documentation on learning JavaScript for drafts.

The goal here is I have created a keyboard with the different stores that I shop at. I want to run down my shopping list and tag each item with what store I will get it at. Then, I have a final button which sends the list to reminders.

Currently if I position at the end of each line, I can insert the tag just fine. What I would like to accomplish is to be able to have the cursor anywhere in the line, and still insert the tag at EOL. I would also like to set the cursor position to the next line. Pretty sure I can figure that part out of I can figure out how to set the initial insert position to the end of whatever line I am on.

Here is the existing keyboard action script and thanks to the kind souls.

let loc = editor.getSelectedRange()[0],
  store = " #aldi";
editor.setTextInRange(loc, 0, store);
editor.setSelectedRange(loc + 6, 0);

The Editor object has a helpful method for this… getSelectedLineRange() which returns extends the current cursor selection (or position, if no selection) to return the location of the start of the line, and the length. This allows you to locate the end of the line to do the insertion, something like:

let store = " #aldi";
let [loc, len] = editor.getSelectedLineRange();
// loc is not the index of the first character in the line
// len is the length of the line.
// this should put your text at the end of the line
editor.setTextInRange(loc+len, 0, store);
// now move cursor to end
editor.setSelectedRange(loc+len+1, 0);

Actually it inserts at the start of the next line which I assume means it is including the new line in getSelectedLineRange. I should be able to figure that out though. Thanks.

Just to be fully pedantic, you’re right that the second value returned from getSelectedLineRange includes the newline character at the end of the line, but that’s only true if there is a trailing newline. The very last line of the draft won’t have one, so to check for that edge case, you have to do something like this:

let store = " #aldi";

// put tag at end of current line
let [loc, len] = editor.getSelectedLineRange();
if (editor.getTextInRange(loc+len-1, 1) == '\n') {
editor.setTextInRange(loc+len, 0, store);

// move cursor to new end of line
editor.setSelectedRange(loc+len+store.length, 0);

Thanks, Doc. I tend not to test my example on the forum, I’m afraid.

Hello! Thanks for this wonderful solution. I’m curious, how might one adapt this to apply the tag to each line in a draft? I tried to add this code into a for loop but the #aldi tag is added several times to end to of the draft and not the end of each line.

Thanks for taking time to answer!