Version 16 of How many lines in a text widget?

Updated 2007-05-03 21:01:53 by Duoas

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
    }