Version 2 of line numbers in text widget

Updated 2008-03-18 11:41:41 by suchenwi

Richard Suchenwirth 2008-03-18 - The following codelet allows to display line numbers in a text widget. Note that they are just literally inserted at beginnings of lines, so if you do copy & paste of multiple lines, best toggle line number display off.

proc linenums {w} {
    if [llength [$w tag ranges linenum]] {
        foreach {from to} [$w tag ranges linenum] {
            $w delete $from $to
        }
    } else {
        set lastline [expr int([$w index "end - 1 c"])]
        for {set i 1} {$i <= $lastline} {incr i} {
            $w insert $i.0 [format "%5d " $i] linenum
        }
    }    
}

Test and demo - the source file itself is displayed, line numbers on/off are toggled with F1:

proc readfile filename {
    set f [open $filename]
    return [read $f][close $f]
}

pack [text .t]
.t tag configure linenum -background yellow
.t insert 1.0 [readfile [info script]]
bind .t <F1> {linenums %W}