#!/usr/bin/wish

# If Typewriter is running just open the files
if {[regexp Typewriter [winfo interps]]} {
	for {set i 0} {$i < $argc} {incr i} {
		if {[file isfile [file join [pwd] [lindex $argv $i]]]} { 
			catch {send Typewriter [list file.open -file [file join [pwd] [lindex $argv $i]]]}
		}
	}
	exit
}

# Set the path to the library
set LIB_DIR [file dirname [info script]]/tt_lib
lappend auto_path $LIB_DIR
source $LIB_DIR/options.tcl


####
# Bind usual function to keys.
#
bind Text <Control-Key-v> {tk_textPaste %W}
bind Text <Control-Delete> {    
	if {[%W tag nextrange sel 1.0 end] != ""} {
		%W delete sel.first sel.last
    } else {
		%W delete insert [tkTextNextWord %W insert]
		%W see insert
  	}
}
bind Text <Control-BackSpace> {    
	if {[%W tag nextrange sel 1.0 end] != ""} {
		%W delete sel.first sel.last
    } else {
		%W delete [tkTextPrevPos %W insert tcl_startOfPreviousWord] insert
		%W see insert
  	}
}



#####
# functions.bind
#
# This procedure is called every time a new typewriter window is created, and
# set the accelerator keys.
#
proc functions.bind {win} {
	bind $win <Control-KeyPress-g> "edit.goto; break"
    bind $win <Control-KeyPress-n> "file.new; break"
    bind $win <Control-KeyPress-o> "file.open; break" 
    bind $win <Control-KeyPress-q> "file.quit; break"
	bind $win <Control-KeyPress-f> "edit.find_and_replace; break"
    bind $win <Control-KeyPress-s> "file.save; break"
    bind $win <Control-KeyPress-u> "file.close; break"
	bind $win <Control-KeyPress-z> "undo; break"
	bind $win <Alt-KeyPress-z>     "redo; break"
    bind $win <Alt-KeyPress-s>     "file.save_as; break"
}



#####
# Install wm hints 
#
wm title . "Typewriter"
wm geometry . +10+20
wm resizable . 1 0
wm protocol . WM_DELETE_WINDOW "file.quit"

tk appname Typewriter

# Show program information
label .l1 -text Typewriter -width 15 -font "Lucidatypewriter 24"
pack .l1 -fill x -expand yes
label .l2 -text "The Tcl/Tk editor" -font "Helvetica 10"
pack .l2 -fill x -expand yes

menu.init
trace variable topWindow w menu.update
set topWindow ""

functions.bind .
# Show the app main window before and other window
update

# Parse command line parameters
for {set i 0} {$i < $argc} {incr i} {
	if {[file isfile [file join [pwd] [lindex $argv $i]]]} { 
		catch {file.open -file [file join [pwd] [lindex $argv $i]]}
	}
}

