#!/usr/bin/tclsh
# Usage: tkread [-w]
#        -w rewrap lines
#
# TODO:
# - justify text (not simple; see http://wiki.tcl.tk/1774)
# - add a basic search function
# - add function to type 30g to scroll 30% through an article

set fontsize 20
set colour #333333
set inverted 0

package require Tk
wm title . "read"

proc rewrap {text} {
	set wrapped [regsub -all {\n([^\n])} $text { \1}]
	set spaced [regsub -all {  *} $wrapped { }]
	set better [regsub -all {\n *} $spaced "\n"]
	set better [regsub -all {\n} $better "\n\n"]
	return [regsub -all {\n\n\n} $better "\n"]
}

proc changeFontSize {change} {
	global fontsize
	set newsize [expr $fontsize $change]
	if {$newsize > 0} {
		set fontsize $newsize
		.t configure -font "Times $fontsize" -padx [expr $fontsize * 2]
	}
}

proc invertColours {} {
	global inverted colour
	if {$inverted} {
		set inverted 0
		.t configure -bg white -fg $colour
		. configure -bg white
	} else {
		set inverted 1
		.t configure -bg $colour -fg white
		. configure -bg $colour
	}
}

proc scroll {dir amount} {
	.t yview scroll $dir $amount
	set percent [expr [lindex [.t yview] 1] * 100]
	set rough [regsub {\..*} $percent {}]
	wm title . "read $rough%"
}

. configure -bg white
text .t -font "Times $fontsize" -wrap word -width 60 -padx [expr $fontsize * 2] -bd -1 -bg white -fg $colour
pack .t -expand yes -fill y
set text [read stdin]
if { $::argc > 0 && [lindex $::argv 0] == "-w" } {
	set text [rewrap $text]
}
.t insert end $text
.t configure -state disabled ;# disable cursor

bind . <Up> {scroll -1 unit}
bind . <k> {scroll -1 unit}
bind . <Down> {scroll 1 unit}
bind . <j> {scroll 1 unit}
bind . <Prior> {scroll -1 page}
bind . <Shift-space> {scroll -1 page}
bind . <Left> {scroll -1 page}
bind . <b> {scroll -1 page}
bind . <K> {scroll -1 page}
bind . <Next> {scroll 1 page}
bind . <space> {scroll 1 page}
bind . <Right> {scroll 1 page}
bind . <J> {scroll 1 page}
bind . <Home> {.t yview moveto 0}
bind . <End> {.t yview moveto 1}
bind . <equal> {changeFontSize +5}
bind . <minus> {changeFontSize -5}
bind . <plus> {changeFontSize +1}
bind . <underscore> {changeFontSize -1}
bind . <v> {invertColours}
bind . <q> {exit}
