Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
editor.set_selection behavior
-
This code below works great using editorial. It will select text on given positions and scroll the page to the selected text.
import editor # assuming the text >= 910 editor.set_selection(900,910)
However, if I run that code using pythonista the page only stay still and not scrolling automatically
Is there any other way to scroll the page automatically to cursor position or selected text in pythonista?
-
The trick is that you must use
replace_text
which causes the editor to scroll.
You can replace a zero length range with '', so as not to actually change anything.It is difficult to accurately control exactly where the cursor will be placed. The logic works differently depending on whether the old position is above or below the selection, and by how much, and how close you are to the top,and bottom of the buffer. For instance, if the selection is on the current screen, the screen might not scroll at all. If you are scrolling ahead, usually the cursor will end up at the very bottom of the screen.
You can get fancy and first force a scroll to the very top of the buffer, then scroll past by an extra N lines, so that you get some context, but then you need to count lines, and make sure you don't try to scroll past the end of the buffer, etc. also, when first loading the file, you have to wait until the file is fully loaded, and there is no way to check that.
In editmenu/Tabs, here is the solution we used to restore the previous saved selection, and scroll to that spot, after a file was loaded:
def setsel(sel): # keep trying to move the cursor while the file might be loading while editor.get_selection()[0] < sel[0]: editor.replace_text(sel[0],sel[0],'') editor.replace_text(sel[0]+400,sel[0]+400,'') time.sleep(0.25) editor.set_selection(*sel) ui.delay(setsel,1.0)
The ui.delay was used to give the file some time to load, then called the setsel function, which keeps trying to move the cursor, and check when it was successful. If the file was already open, you should replace text first at 0,0 to ensure consistent results when you are below vs above the selection.
-
@JonB, wow thank you so much, case solved 😇
import editor # assuming the text >= 910 editor.replace_text(900,900,'') editor.set_selection(900,910)
Thank you so much for providing answer and bonus information.