How to find the current line?

If I use selectedRanges it gives me information like [1915, 1916] instead of the line number which is 72

The TextEditor selectedRange is showing selected characters. Have you tried feeding this Range to the getLineRangeForRange method?


Sadly that doesn’t gives what I want.

On line 10 I get

console.log(editor.selectedRange) - [123, 124]
console.log(editor.getLineRangeForRange(editor.selectedRange)) - [83, 124]

I want just the number 10…

Edit: The following kind of works but it seems to hacky

var hackRange = new Range(0, editor.selectedRange.end-1)

var selectedText = editor.getTextInRange(hackRange);
var currentLineNumber = selectedText.split(/\r\n|\r|\n/).length;

There should be a more easy wait to get the current line number/row and some cases the column

That’s pretty much what I was going to suggest:

let newlines =
    .getTextInRange(new Range(0, editor.selectedRange.end))
    .match(/\n/g) || [];
console.log(`Line: ${newlines.length + 1}`);

I don’t see a convenience method either.

1 Like

Does that gives the correct line for you? For me it shows one line more than the correct one… for example at line number 79 it prints 80. Thats why I subtracted 1 from the range.

I saw the correct line number. I didn’t try with line endings besides macOS/Unix LF. Also, my test code ran on text entry, not a text selection (a selection might have included the line ending of current line for you).

We currently have an outstanding API feature request for direct access to line and column information. We hope to get to this soon!


I just saw this today — and it’s awesome to know that Panic’s addressing this!! — but, in the meantime, you could do the end-of-line checking more conveniently with .eol, a document property which should correctly identify whatever end-of-line character is being used on the current document.

Kudos to the ever-amazing @apexskier for using that nifty feature on his own extensions!

1 Like