Sublime Forum

How to check if cursor is at the end of the line?

#1

I’m beginnig to learn architecture of st plugin. And I don’t know how approach to take to this issue. It should be fast without getting contents of the line.
What is the function to get line length in which cursor exists. And second how to get cursor position, that is line number and column number ?

0 Likes

#2

Have you seen sublimetext.com/docs/3/api_reference.html ?

Look at the line() function in the API docs. Something like this:

rg = view.line( view.sel()[0] )
length_of_rg = rg.b - rg.a

Hmm. It seems that the line function seems to ignore indentation (whitespace at the beginning of the line). I’m not sure what the best alternative is if this is an issue for you.

Hope this helps,
Alex

0 Likes

#3

will be a better code, since rg.a can be larger than rg.b.

0 Likes

#4

@randy3k You’re right, of course :smile:

0 Likes

#5

In ST3, I suppose the fastest way is:

is_cursor_at_the_end_of_the_line = view.classify(view.sel()[0].a) & sublime.CLASS_LINE_END != 0
0 Likes

#6

The actual “cursor” for a selection is sel.b, not sel.a: view.sel()[0].b

This matters if you do an area selection.

I also urge you to iterate over the cursors and do proper multiple cursor support in your plugins instead of hard-coding view.sel()[0].

0 Likes

#7

[quote=“lunixbochs”]The actual “cursor” for a selection is sel.b, not sel.a: view.sel()[0].b

This matters if you do an area selection.
[/quote]

This is not correct, as randy3k said just above. The “cursor” is at region.end().

0 Likes

#8

Wrong. region.end() gives you the side of the region closest to the end of the buffer. region.b is the cursor.

To demonstrate, open a view in sublime, make a few lines, then drag select from the end of the view to the beginning. Your “cursor” (the blinking dot) will be at the beginning of the view, while the selection will span to the end of the view.

Open the console and run this:

print(view.size(), view.sel()[0].b, view.sel()[0].end())

view.size() will equal region.end() and not region.b.

region.end() is only accurate when you do selections toward the end of the view, and wrong when you do selections toward the beginning of the view.

You should also be careful of using (region.begin(), region.end()) to save and restore cursor state, as you will potentially reverse the selection (like using abs() on a negative number).

0 Likes

#9

Oh, wow, sorry. I got mixed up. Thanks!

0 Likes