Issue with cursor positioning

I created this keyboard action to function as a “smart tab” so that then the tab key is pressed:

  • If there is no selection, the tab gets prepended to the current line instead of at the cursor position
  • If multiple links are selected, tab is prepended to each line
  • Cursor position (or selection start and end) is retained relative to the content

This works in all cases I’ve found except when the selected line has only list markdown and no other text, i.e. prepended with "- "

In that case the cursor always gets inserted one character to the left of where it should be.

I’m pretty sure this used to work but it’s been a while so I don’t remember how long since it was working.

Here’s the script

const list_re = /(^\t*[-*+] )/gm;

// grab state
let [lnStart, lnLen] = editor.getSelectedLineRange();
let lnText = editor.getTextInRange(lnStart, lnLen);
let [selStart, selLen] = editor.getSelectedRange();

let indent_lines = (l) => {
    let lines;
    if (l.match(list_re)) {
        lines = l.replace(list_re, "\t$1");
    } else {
        lines = l.replace(/^/gm,"\t");
    return lines;

let originalCursorPos = selStart;

let tabbed_text = indent_lines(lnText);
editor.setTextInRange(lnStart, lnLen, tabbed_text);

// Adjust cursor position based on indentation level
let indentationLevel =\S|$/);
let cursorPos = originalCursorPos + indentationLevel;

Can anyone help?

This sounds like the same goal as the default “Indent” action that ships in the “Editing” action group - that is also available in the directory. You might start with that example.

I think you’ve got a few cases here where it might not work out right. You also are not adjusting the length of the selection, and making some assumptions that won’t work out in multi-line selection (like that some of the tabs you add might not before the original cursoe position)

1 Like

Thanks Greg, that’s much better than mine. Now I just have to forget how much time I put into writing an action when it had already been done.