Techniques to restore cursor position within Notepad++ file
I wrote an NppExec script that saves the cursor position within the current file, then performs a bunch of commands (some of which may delete lines within the file), then finally restores the cursor position.
The code basically looks like:
// get caret position & anchor
sci_sendmsg SCI_GETCURRENTPOS
set local pos = $(MSG_RESULT)
sci_sendmsg SCI_GETANCHOR
set local anchor = $(MSG_RESULT)
sci_sendmsg SCI_GETFIRSTVISIBLELINE
set local firstvisibleline = $(MSG_RESULT)
... commands to modify file ...
// set caret position & anchor
sci_sendmsg SCI_SETSEL $(anchor) $(pos)
sci_sendmsg SCI_SETFIRSTVISIBLELINE $(firstvisibleline)
Until recently, this worked well. But recently, the cursor does not return to its original position. I'm thinking this could be because some lines within the file (even if nowhere near the cursor) have been deleted by the script.
Questions:
- Given the details provided above, should this be working?
- If not, would a reasonable way to return the cursor to its original position within the file be to simply insert a small unique string, perform the desired commands, then search for the unique string, and then finally delete that string from the file?
- Can you think of a better way to accomplish this goal?
If the technique proposed in question 2 is a good idea, what's the best way to insert text into an open file at the current cursor position (actually, I'm curious either way)? I tried SCI_SENDMSG SCI_INSERTTEXT(-1,TeStStRiNg) and SCI_SENDMSG SCI_INSERTTEXT(-1,"TeStStRiNg"), but neither worked. It's easy to call a Notepad++ macro to accomplish this, but I'm thinking there must be a more straightforward method.
The technique described in the Manual "4.6.11. Clone current document to new editor pane" works for me. It uses SCI_SETSEL and SCI_SETFIRSTVISIBLELINE in the same way as you do.
As for SCI_INSERTTEXT, the correct syntax is
sci_sendmsg SCI_INSERTTEXT -1 "Some text"
To insert multi-line text, one may use e.g.
set local s ~ strunescape 123\n456\n789
sci_sendmsg SCI_INSERTTEXT -1 "$(s)"
The syntax of sci_sendmsg can be seen by executing
help sci_sendmsg
Thanks for your reply.
The technique described in the Manual "4.6.11. Clone current document to new editor pane" works for me. It uses
SCI_SETSELandSCI_SETFIRSTVISIBLELINEin the same way as you do.
It works for me, too, except if lines in the file are programmatically removed above the cursor's position (in the ... commands to modify file ... section). Should it work even if lines within the file are being programmatically removed between getting the pos and anchor values and then using them to set the cursor position?
...As for
SCI_INSERTTEXT, the correct syntax issci_sendmsg SCI_INSERTTEXT -1 "Some text"
Ah, thanks. The parens were the problem. Easy to fix.
To insert multi-line text, one may use e.g.
set local s ~ strunescape 123\n456\n789 sci_sendmsg SCI_INSERTTEXT -1 "$(s)"
That's a helpful example. Thank you.