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?

editor.getLineRangeForRange(editor.selectedRange)

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 =
  editor
    .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!

5 Likes

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!

2 Likes

Is 2023 and looking at the documentation there still no means to easily get the line number from a range. Move a cursor to a line number. Move the cursor to a row/col or set the selection using row, col.

Is there anything new?

Here’s the code I use for getting the line & column number of the cursor position:

  const text = editor.document.getTextInRange(new Range(0, editor.document.length))
  const cursorPosition = editor.selectedRange.start
  const lines = text.slice(0, cursorPosition).split('\n')
  const line = lines.length
  const column = lines.slice(-1)[0].length + 1

I wonder if we (the community) should make an open source JS library of useful functions for Nova extension authors?

1 Like