Return to original cursor position after replacing string?

Hello,

I am building an extension that auto timestamps on save. Everything works, but it always jumps to the top of the page after it is finished.

Is there a way to stay in place when after the replace is complete?

The extension takes the current document’s code and searches for a regex match, which it then replaces with new value.

Thanks.

Hi yabdab. You could try using the TextEditorEdit replace method instead of the TextEdit replace method.

https://docs.nova.app/api-reference/text-editor-edit/#replacerange-text-format

As per the docs:

Replaces text in the the provided Range with a new text string. This method differs from insert() in that it will not move the cursor.

Failing that, it may be necessary to store the initial cursor position then set the cursor position again using the TextEditor scrollToPosition method once the replace operation is complete.

https://docs.nova.app/api-reference/text-editor/#scrolltopositionposition

Hope this helps. Good luck!

Jason

1 Like

@jason Thanks for the reply.

I have the replace part wired already :grin:

What would be the easiest way to obtain the current cursor position before I trigger the replace function? Is there a func in the API that will do this? TIA

Nevermind, looks like this will give me what I need to scroll to…

const cursorPosition = editor.selectedRange.end;

and then …

editor.scrollToPosition(cursorPosition);
2 Likes

I have found that scrollToPosition is kinda jerky (FOUC) when the replace occurs. I would like it to appear like nothing happens and the code just stays in place.

I have been studying the Prettier extension, which replaces all the content in document with newly formatted code, and it is clean. I will continue to play around with it, but if anyone knows the trick, then please let me(us) know. :wink:

2 Likes