Version 23 of How many lines in a text widget?

Updated 2012-08-07 01:51:52 by AMG

If we need to incrementally work through the lines of a text widget we can obtain the content size in terms of lines and characters using:

pathName index end

This will, however return a value such as '5.5', ie. five lines '.' and five characters. If we just need the lines, and not the characters, (eg. in an incremented loop) then the following proc is always handy.

#---------------
# return actual number of lines in a text widget
#---------------
proc _lines {t} {
    return [expr [lindex [split [$t index end] .] 0] -1]
}

you can avoid the math by doing [$t index end-1c]...

#---------------
# test it
#---------------
proc demo {} {
    catch {console show}
    pack [text .txt]
    .txt insert end "1\n2\n3\n4\n5"
    puts [_lines .txt]

    for {set i 1} {$i <= [_lines .txt]} {incr i} {
        puts [.txt get $i.0 "$i.0 lineend"]
    }
}

demo

Duoas: Sometimes all you want to know is how many lines there are visible in the text window. It took me a while to figure this out so I'll post the solution here (it is actually very simple). This does not account for -wrap.

proc text.vlines text {
    set  begin   [lindex [split [$text index @0,0]         .] 0]
    set  end     [lindex [split [$text index @65535,65535] .] 0]
    set  vlines  $end
    incr vlines -$begin
    incr vlines
    return $vlines
}

MG July 21 2012 - How can you find the indexes of the visible characters in the text widget? I want to bind to a text widget so that, when it's resized, it moves to put the last line that was visible before on screen (default behaviour keeps the first line visible on screen instead), but can't find out which line that is.


AMG: It's as easy as [$win count -lines 1.0 end].