How to get currently visible Line #s

I’m trying to get the line numbers of the first and last visible lines in the editor, based on the current scroll.

I’ve looked at all of these answers so far:

but they all refer to deprecated APIs and don’t seem to have any info that is currently useful.
Accidentally asked this in a github issue and got an answer that left me with more questions than I had before: How to get currently visible lines · Issue #919 · codemirror/dev · GitHub

My code is currently this:

    const rect = editor.getBoundingClientRect();
    const topVisibleLineBlock = editor.lineBlockAtHeight(rect.top);
    const bottomVisibleLineBlock = editor.lineBlockAtHeight(rect.bottom);

    // Look up the line blocks in editor.viewState.viewportLines ...

I’m pretty sure that this is the wrong way to do this, because when I scroll around the values returned by the calls to editor.lineBlockAtHeight() don’t change.

I’m also not sure if editor.viewState.viewportLines is the right place to look up the line blocks to get line #s, or what I should be comparing to do that lookup…

1 Like

Here is a minimal example of the issue I’m hitting: Try CodeMirror

If you scroll around, the top and bottom visible blocks won’t change. What am I missing?

lineBlockAtHeight doesn’t take a screen position, but a position relative to the top of the document. Pass rect.top - editor.documentTop etc.

Thanks. I can get lineBlocks now, but can’t figure out where to look them up to get line #s.
viewportLineBlocks doesn’t have the line number as part of the values, and it doesn’t have all the lines so I can’t use the index either.

Is there another structure somewhere that has all the lines, and I can compare on from?
Or do I need to get the original document, manually split it on newlines myself and do the comparison there?

You want view.state.doc.lineAt(N).number, probably.

Thanks, that should be what I need