Search code examples
pythonwxpythonscintilla

wxPython styledtextctrl: How to get number of visible lines with word wrapping enabled?


I am trying to determine the number of lines displayed on the screen in a wxPython styledtextctrl with word wrapping enabled.

I have seen several answers to visible lines here:

wxPython - StyledTextCtrl get currently visible lines

Get visible lines in Scintilla.NET component

The second one if for C# but since the base is still scintilla I thought it was relevant.

The problem with these solutions is while they give the lines, they do so assuming that word wrapping is not enabled. If it is enabled, and some of the lines are wrapped, then the following scintilla function returns the value if wrapping were not enabled:

LinesOnScreen()

So my question is is there any way to get the number of lines on the screen given that word wrapping is enabled?


Solution

  • I assume what you want is the number of document lines, rather than the number of display lines. So if wrapping is enabled, the former will be less than the latter if any lines are wrapped.

    As you've already discovered, LinesOnScreen() will give the number of visible display lines. But there is currently no built-in facility to get the number of visible document lines, so it will need to be calculated.

    A complete solution could be quite complex, especially if you need to take into account things like line-folding and annotations. But a very basic solution would go something like this:

        index = editor.GetFirstVisibleLine()
        lines = editor.LinesOnScreen() + index
        count = 0
        while index < lines:
            index += editor.WrapCount(index)
            count += 1
    

    But note that this does not attempt to deal with partial lines at the top and bottom of the screen (which is left as an exercise for the reader).