#!/usr/local/bin/wish -f
#!/bin/sh
# exec wish -f "$0" "$@"
#
# TKEDIT
set       Version 2.0.0
#
# Text Editor using TCL-TK
#
# Author:  Rainer Kowallik
#          kowallik@ifh.de
#
# Procs and Variables for external use
#
# procs for cursor Movement
#
# proc NextChar 
# proc PrevChar
# proc EndOfWord 
# proc BeginOfWord
# proc EndOfLine
# proc BeginOfLine
# proc NextLine 
# proc PrevLine
# proc NextScreen
# proc PrevScreen
# proc TopOfFile
# proc BottomOfFile
#
# procs for File I/O
#
# proc SaveTo <filename>
# proc loadFile <filename>
# proc OpenNew
# proc IncludeFile <filename>
# proc SaveClip
# proc CrLf2Lf
# proc Cr2Lf
# proc SaveCrLf
# proc SaveCr
# proc CheckAndQuit
#
# procs for Edit
#
# proc MarkBegin
# proc MarkEnd
# proc CopyToClip
# proc CutToClip
# proc PasteFromClip
# proc DelToEOW
# proc DelWord
# proc DelToEOL
# proc DelToBOL
# proc DelLine
# proc DelSelect
# proc DelSpace
# proc JoinLines
# proc Capitalize
# proc LowerCase
# proc DoIndent
# proc YankLine
# proc DoTab
#
# procs for Search / Replace
#
# proc AskGotoLine
# proc GotoLine
# proc AskSearchString
# proc SearchNext
# proc SearchPrev
# proc MatchBracket
# proc AskReplaceString
# proc ReplaceNext
# proc ReplaceAll
# proc InsertText
# proc InsertTextAt
# proc DeleteTextAt
#
# Variables:
#
# ThisFileName   
# SearchString  
# ReplaceString 
# Result         
# AWin         
#

#
# Patching tkedit for wish4.0 (tcl7.4b4 and tk4.0b4)
#

proc OldStyleSelect { } {
   global tk_version tk_priv
   if {$tk_version >= 4.0} {
      bind Text <1> {
          set tk_priv(selectMode) char
          %W mark set insert @%x,%y
          %W mark set anchor insert
          if {[lindex [%W config -state] 4] == "normal"} {focus %W}
          DoService 0
      }
      bind Text <Double-1> {
          set tk_priv(selectMode) word
          %W mark set insert "@%x,%y wordstart"
          tk_textSelectTo %W insert
      }
      bind Text <Triple-1> {
          set tk_priv(selectMode) line
          %W mark set insert "@%x,%y linestart"
          tk_textSelectTo %W insert
      }
      bind Text <B1-Motion> {tk_textSelectTo %W @%x,%y}
      bind Text <Shift-1> {
          tk_textResetAnchor %W @%x,%y
          tk_textSelectTo %W @%x,%y
      }
      bind Text <Shift-B1-Motion> {tk_textSelectTo %W @%x,%y}
   }
}

proc NewStyleSelect { } {
   global tk_version
   if {$tk_version >= 4.0} {
      bind Text <1> {
          tkTextButton1 %W %x %y
          DoService 0
      }
      bind Text <B1-Motion> {
          set tkPriv(x) %x
          set tkPriv(y) %y
          tkTextSelectTo %W %x %y
      }
      bind Text <Double-1> {
          set tkPriv(selectMode) word
          tkTextSelectTo %W %x %y
          catch {%W mark set insert sel.first}
      }
      bind Text <Triple-1> {
          set tkPriv(selectMode) line
          tkTextSelectTo %W %x %y
          catch {%W mark set insert sel.first}
      }
      bind Text <Shift-1> {
          tkTextResetAnchor %W @%x,%y
          set tkPriv(selectMode) char
          tkTextSelectTo %W %x %y
      }
   }
}

proc SetSelectStyle { } {
   global XPrefOldSelect
   if {$XPrefOldSelect == 1} {
      OldStyleSelect
   } else {
      NewStyleSelect
   }
}
if {$tk_version >= 4.0} {
bind Entry <ButtonRelease-2> {}
bind Entry <Left> {}
bind Entry <Right> {}

bind Text <Control-a> {}
bind Text <Control-b> {}
bind Text <Control-c> {}
bind Text <Control-d> {}
bind Text <Control-e> {}
bind Text <Control-f> {}
bind Text <Control-g> {}
bind Text <Control-h> {}
bind Text <Control-i> {}
bind Text <Control-j> {}
bind Text <Control-k> {}
bind Text <Control-l> {}
bind Text <Control-m> {}
bind Text <Control-n> {}
bind Text <Control-o> {}
bind Text <Control-p> {}
bind Text <Control-q> {}
bind Text <Control-r> {}
bind Text <Control-s> {}
bind Text <Control-t> {}
bind Text <Control-u> {}
bind Text <Control-v> {}
bind Text <Control-w> {}
bind Text <Control-x> {}
bind Text <Control-y> {}
bind Text <Control-z> {}

bind Text <1> {tkTextButton1 %W %x %y}
bind Text <2> {}
bind Text <ButtonRelease-2> {}
bind Text <3> {}
bind Text <Double-1> {}
bind Text <Triple-1> {}
bind Text <Left> {}
bind Text <Right> {}
bind Text <Up> {}
bind Text <Down> {}
bind Text <Shift-Left> {}
bind Text <Shift-Right> {}
bind Text <Shift-Up> {}
bind Text <Shift-Down> {}
bind Text <Control-Left> {}
bind Text <Control-Right> {}
bind Text <Control-Up> {}
bind Text <Control-Down> {}

bind Text <M-Shift-Left> {}
bind Text <M-Shift-Right> {}
bind Text <M-Shift-Up> {}
bind Text <M-Shift-Down> {}
bind Text <M-Control-Left> {}
bind Text <M-Control-Right> {}
bind Text <M-Control-Up> {}
bind Text <M-Control-Down> {}

bind Text <Prior> {}
bind Text <Next> {}
bind Text <Home> {}
bind Text <End> {}
bind all <Tab> {}
bind Text <Tab> {}
bind all <Shift-Tab> {}
bind Text <Shift-Tab> {}
bind Text <Control-Tab> {}
bind Text <Control-comma> {}
bind Text <Control-period> {}
bind Text <Control-equal> {}
bind Text <Control-slash> {}
bind Text <Return> {}
bind Text <Delete> {}
bind Text <space> {}
bind Text <BackSpace> {}
bind Text <Control-space> {}
bind Text <Select> {}
bind Text <Control-backslash> {}

proc tk_textSelectTo {w index} {
    global tk_priv

    if [catch {$w index anchor}] {
	$w mark set anchor $index
    }
    case $tk_priv(selectMode) {
	char {
	    if [$w compare $index < anchor] {
		set first $index
		set last anchor
	    } else {
		set first anchor
		set last [$w index $index+1c]
	    }
	}
	word {
	    if [$w compare $index < anchor] {
		set first [$w index "$index wordstart"]
		set last [$w index "anchor wordend"]
	    } else {
		set first [$w index "anchor wordstart"]
		set last [$w index "$index wordend"]
	    }
	}
	line {
	    if [$w compare $index < anchor] {
		set first [$w index "$index linestart"]
		set last [$w index "anchor lineend + 1c"]
	    } else {
		set first [$w index "anchor linestart"]
		set last [$w index "$index lineend + 1c"]
	    }
	}
    }
    $w tag remove sel 0.0 $first
    $w tag add sel $first $last
    $w tag remove sel $last end
    $w mark set sel.first $first
    $w mark set sel.last $last
}
proc tk_textResetAnchor {w index} {
    global tk_priv
    if {[$w tag ranges sel] == ""} {
	set tk_priv(selectMode) char
	$w mark set anchor $index
	return
    }
    if [tk_textIndexCloser $w $index sel.first sel.last] {
	if {$tk_priv(selectMode) == "char"} {
	    $w mark set anchor sel.last
	} else {
	    $w mark set anchor sel.last-1c
	}
    } else {
	$w mark set anchor sel.first
    }
}
proc tk_textIndexCloser {w a b c} {
    set a [$w index $a]
    set b [$w index $b]
    set c [$w index $c]
    if [$w compare $a <= $b] {
	return 1
    }
    if [$w compare $a >= $c] {
	return 0
    }
    scan $a "%d.%d" lineA chA
    scan $b "%d.%d" lineB chB
    scan $c "%d.%d" lineC chC
    if {$chC == 0} {
	incr lineC -1
	set chC [string length [$w get $lineC.0 $lineC.end]]
    }
    if {$lineB != $lineC} {
	return [expr {($lineA-$lineB) < ($lineC-$lineA)}]
    }
    return [expr {($chA-$chB) < ($chC-$chA)}]
}

}


#
# Starting with procedures which will be used from ".tkedit"
#
proc SetFont font {
   global FontSize FontName NoWin
   set FontName $font
   if {!$NoWin} {
      .text configure -font "${font}--*-${FontSize}-*-*-*-*-iso8859-*"
      .textv configure -font "${font}--*-${FontSize}-*-*-*-*-iso8859-*"
   }
}

proc NewFontSize size {
   global FontSize FontName NoWin
   set FontSize $size
   if {!$NoWin} {
      .text configure -font "${FontName}--*-${size}-*-*-*-*-iso8859-*"
      .textv configure -font "${FontName}--*-${size}-*-*-*-*-iso8859-*"
   }
}

proc GetColorSelect___ {var val} {
   global TempName MyAdress
   
   exec rm -f $TempName
   eval "exec ColorSelect 2>/dev/null >$TempName \
          -cmd \"send $MyAdress SetRGBX\" -var $var $val &"
   set f [open $TempName r]
   set flag 1
   while {$flag} {
      set rgb [read $f 80]
      puts stdout "[eof $f] $rgb"
      if {[string length $rgb] > 0} {
         set flag 0
         regsub \x0a $rgb "" rgb
      }
      DoService 0
      update
      after 500
   }
   gets $f rgb
   close $f
   exec rm -f $TempName
puts stdout "returned $rgb"
   return $rgb
}

proc GetColorSelect {var val} {
   global TempName UseSend MyAdress
   
   if {!$UseSend} {
      set rgb [eval "exec ColorSelect 2>/dev/null $val"]
      return $rgb
   } else {
   eval "exec ColorSelect 2>/dev/null >/dev/null \
          -cmd \"send $MyAdress SetRGBX\" -var $var $val &"
      return $val
   }
}

proc SetRGB var {
   upvar $var x
   set rgb [GetColorSelect $var $x]
   if {[string index $rgb 0] != "#"} return
   set x $rgb
   UpdateRGB
}

proc SetRGBX {var rgb} {

   if {[string index $rgb 0] != "#"} return
   upvar $var x
      set ndigit [string length $rgb]
      switch $ndigit {
         7 { set x $rgb }
         13 {
               scan $rgb "#%2x%2x%2x%2x%2x%2x" r rd g gd b bd
               set x [format #%02x%02x%02x $r $g $b]
           }
      }
   UpdateRGB
   DoService 0
   update
}

proc UpdateRGB { } {
   global XPrefHotBgRGB XPrefHotFgRGB XPrefMainBack XPrefMenuBack \
          XPrefEntBack XPrefButtonBack XPrefFoundRGB XPrefPasteRGB \
          XPrefMatchRGB BackgroundRGB ForegroundRGB tk_version

catch {.bufhot.win configure -bg $XPrefHotBgRGB}
catch {.lsehot.win configure -bg $XPrefHotBgRGB}
catch {.bufhot.win configure -fg $XPrefHotFgRGB}
catch {.lsehot.win configure -fg $XPrefHotFgRGB}
foreach x [info commands .mBar*] {$x configure -background $XPrefMenuBack}
foreach x ".row1 .c1 .c2 .c5 .c6 .c7 .rc1 .rc2 .row2 [info commands .label*]" \
         {$x configure -background $XPrefMainBack}
if {$tk_version < 4.0} {
   foreach x ".scrolly .scrollvy" {$x configure -fg $XPrefMainBack}
}
foreach x "searchstring replacestring actfile linenr columnnr bytes" {
      .$x configure -background $XPrefEntBack}
foreach x "searchstringup searchstringdown searchfirst searchnext searchprev \
           casesense pattern replacestringup replacestringdown replacenext \
           replacerange replaceend replaceall autoindent protect " {
      .$x configure -background $XPrefButtonBack}
foreach x ".text .textv" {
   $x tag configure found -background $XPrefFoundRGB
   $x tag configure paste -background $XPrefPasteRGB
   $x tag configure match -background $XPrefMatchRGB
}
update
SetRGB_bg $BackgroundRGB
SetRGB_fg $ForegroundRGB
}

proc SetRGB_bg rgb {
   global BackgroundRGB NoWin
   if { $rgb == -1 } {
      set rgb [GetColorSelect BackgroundRGB $BackgroundRGB]
      if {[string index $rgb 0] != "#"} return
   }
   set BackgroundRGB $rgb
   if {!$NoWin} {
      .text configure  -background $rgb
      .textv configure  -background $rgb
   }
}

proc SetRGB_fg rgb {
   global ForegroundRGB NoWin
   if { $rgb == -1 } {
      set rgb [GetColorSelect ForegroundRGB $ForegroundRGB] 
      if {[string index $rgb 0] != "#"} return
   }
   set ForegroundRGB $rgb
   if {!$NoWin} {
      .text configure  -foreground $rgb
      .textv configure  -foreground $rgb
   }
}

proc SetWinGeom {width height} {
   global NoWin WinWidth WinHeight
   
   set WinWidth $width
   set WinHeight $height
   if {!$NoWin} {
      .text configure -width $width -height $height
   }
}
#
# Now initialize Variables before starting ".tkedit"
#
set NoWin 1
set TempName "/tmp/tkedit.[exec whoami]"
set FontName "-Adobe-Courier-Medium-R-Normal"
set FontSize "140"
set BackgroundRGB "#ffffff"
set ForegroundRGB "#000000"
set XPrefHotBgRGB "#e0e0e0"
set XPrefHotFgRGB "#000000"
set WinWidth 80
set WinHeight 24
set EnaSplitYN 1
set XPrefXKillOnBS 0
set DimFocusOutYN 1
set AutoSaveYN 1
set AutoBackupYN 1
set TabDistance 3
set AutoNewLine 80
set AutoIndentYN 1
set HiddenBytes 0
set XPrefFollowViewYN 1
set XPrefOldSelect 1
set XPrefCPAttrYN 1
set XPrefScrollBarX 0
set XPrefAutoSavePrefs 1
for {set i 1} {$i <= 60} {incr i} {
    set MacF($i) ""
}
set PollFunctions "NoAction"

proc DefaultColor x {
   global XPrefMainBack XPrefMenuBack XPrefEntBack XPrefButtonBack \
          XPrefPasteRGB XPrefFoundRGB XPrefMatchRGB XPrefBorderW
   switch $x {
      1 {
         set XPrefMainBack "#c0c0c0"
         set XPrefMenuBack "#d0d0d0"
         set XPrefEntBack "#f5d5ff"
         set XPrefButtonBack "#c1c8e9"
         set XPrefPasteRGB "#a0a0ff"
         set XPrefFoundRGB "#ffa0a0"
         set XPrefMatchRGB "#a0ffa0"
         set XPrefBorderW 1
      }
      2 {
         set XPrefMainBack "#c2e3d5"
         set XPrefMenuBack "#d9e7e1"
         set XPrefEntBack "#d9e3df"
         set XPrefButtonBack "#97e2d6"
         set XPrefPasteRGB "#a0a0ff"
         set XPrefFoundRGB "#ffa0a0"
         set XPrefMatchRGB "#a0ffa0"
         set XPrefBorderW 1
      }
      3 {
         set XPrefMainBack "#f9e6c7"
         set XPrefMenuBack "#f9e6c7"
         set XPrefEntBack "#f9e6c7"
         set XPrefButtonBack "#f9e6c7"
         set XPrefPasteRGB "#a0a0ff"
         set XPrefFoundRGB "#ffa0a0"
         set XPrefMatchRGB "#a0ffa0"
         set XPrefBorderW 1
      }
   }
}

DefaultColor 1

set MinDelay 50
set MaxDelay 500
set DynIncr 30

#
# Now read Configuration ".tkedit"
#
set CWD [pwd] ; cd
if {[file exists ".tkedit"]} {
   source ".tkedit"
}
cd $CWD
set FontString "${FontName}--*-${FontSize}-*-*-*-*-iso8859-*"
SetSelectStyle
#
# Build up editor widgets
#
frame .mBar -relief raised -bd 2 -background $XPrefMenuBack
pack .mBar -side top -fill x

#
# Search / Replace Quick Panel
#

frame .row1 -background $XPrefMainBack
pack .row1 -side top -expand 0 -fill x
frame .c1 -background $XPrefMainBack
frame .c2 -background $XPrefMainBack
frame .c5 -background $XPrefMainBack
frame .c6 -background $XPrefMainBack
frame .c7 -background $XPrefMainBack
for {set i 8} {$i < 56} {incr i} {frame .c$i}

pack .c1 -side left -in .row1 -expand 1 -fill x
pack .c2 -side left -in .row1 -after .c1 -expand 0
pack .c5 -side left -in .row1 -after .c2 -expand 1 -fill x
pack .c6 .c7 -side left -in .row1 -after .c5 -expand 0
frame .rc1 -background $XPrefMainBack
frame .rc2 -background $XPrefMainBack

label .labelsearch -text "Search For" -background $XPrefMainBack
entry .searchstring -width 16 -relief sunken -bd 2 -textvariable SearchString \
      -bg $XPrefEntBack -borderwidth $XPrefBorderW
button .searchstringup -text "^" -command SearchStringUp \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .searchstringdown -text "v" -command SearchStringDown \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .searchfirst -text "First" -command {DoCmd "^YSearchFirst"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .searchnext -text "Next" -command {DoCmd "^YSearchNext"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .searchprev -text "Prev" -command {DoCmd "^YSearchPrev"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
checkbutton .casesense -text "Case" -variable SearchCaseYN \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
checkbutton .pattern -text "RExp" -variable SearchPatternYN \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW

pack .labelsearch .casesense .pattern .searchfirst .searchnext .searchprev \
      -side left -in .rc1 -expand 0
pack .rc1 .searchstring -side top -in .c1 -expand 1 -fill x
pack .searchstringup .searchstringdown -side top -in .c2 -expand 0

label .labelreplace -text "Replace With" -background $XPrefMainBack
entry .replacestring -width 16 -relief sunken -bd 2 \
      -textvariable ReplaceString -bg $XPrefEntBack -borderwidth $XPrefBorderW
button .replacestringup -text "^" -command ReplaceStringUp \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .replacestringdown -text "v" -command ReplaceStringDown \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .replacenext -text "Next" -command {DoCmd "^YReplaceNext"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .replacerange -text "Range" -command {DoCmd "^YReplaceRange"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .replaceend -text "End" -command {DoCmd "^YReplaceEnd"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
button .replaceall -text "All" -command {DoCmd "^YReplaceAll"} \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW

pack .labelreplace .replacenext .replacerange .replaceend .replaceall \
         -side left -in .rc2 -fill  x
pack .rc2 .replacestring -side top -in .c5 -expand 1 -fill x
pack .replacestringup .replacestringdown -side top -in .c6 -expand 0

#
# Bindings for search / replace text boxes
#
bind .searchstring <Return> {
   set DelayedCMD "NoAction"
   StackUp $SearchString SearchStackPtr SearchStack
   SearchNext
}
bind .searchstring <2> {set SearchString "[GetXSelect]"}
bind .searchstring <Control-k> {set SearchString "" ; update}
bind .searchstring <Up> {SearchStringUp}
bind .searchstring <Down> {SearchStringDown}
bind .searchstring <Left> {EntryCursor .searchstring -1}
bind .searchstring <Right> {EntryCursor .searchstring 1}
bind .replacestring <Return> {
   set DelayedCMD "NoAction"
   StackUp $ReplaceString ReplaceStackPtr ReplaceStack
   ReplaceNext
}
bind .replacestring <2> {set ReplaceString "[GetXSelect]"}
bind .replacestring <Control-k> {set ReplaceString "" ; update}
bind .replacestring <Up> {ReplaceStringUp}
bind .replacestring <Down> {ReplaceStringDown}
bind .replacestring <Left> {EntryCursor .replacestring -1}
bind .replacestring <Right> {EntryCursor .replacestring 1}
#
# Continue with Quick Panel
#
checkbutton .autoindent -text "Indent" -variable AutoIndentYN \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
checkbutton .protect -text "RdOnly" -variable ProtectYN -command DoChmod \
      -padx 0 -pady 0 -background $XPrefButtonBack -borderwidth $XPrefBorderW
pack .autoindent .protect -side top -in .c7 -fill x -padx 2m

#
# Text (Main Editor) widget and scrollbar and spec. Gadgets
#
frame .row2 -background $XPrefMainBack
pack .row2 -side top -after .row1 -expand 0 -fill x

button .close -text "Close" -padx 0 -pady 0 -command {DoCmd "^YCheckAndClose"}
entry .actfile -width 30 -relief sunken -bd 2 -textvariable ThisFileName \
      -bg $XPrefEntBack  -borderwidth $XPrefBorderW
label .labelline -text "line #" -background $XPrefMainBack
entry .linenr -width 6 -relief sunken -bd 2 -textvariable LineNumber \
      -bg $XPrefEntBack  -borderwidth $XPrefBorderW
label .labelcolumn -text "," -background $XPrefMainBack
entry .columnnr -width 3 -relief sunken -bd 2 -textvariable ColumnNumber \
      -bg $XPrefEntBack  -borderwidth $XPrefBorderW
label .labelbyte -text "bytes:" -background $XPrefMainBack
entry .bytes -width 8 -relief sunken -bd 2 -textvariable NumBytes \
      -bg $XPrefEntBack  -borderwidth $XPrefBorderW

pack .close -in .row2 -side left
pack .actfile -in .row2 -side left -after .close -expand 1 -fill x
pack .labelline .linenr .labelcolumn .columnnr .labelbyte .bytes \
      -side left -after .actfile -in .row2 -expand 0

bind .linenr <Return> {set DelayedCMD "NoAction" ; GotoLine}
bind .linenr <2> {set LineNumber "[GetXSelect]"}
bind .linenr <Control-k> {set LineNumber "" ; update}
bind .linenr <Left> {EntryCursor .linenr -1}
bind .linenr <Right> {EntryCursor .linenr 1}

bind .columnnr <Return> {GotoLine}
bind .columnnr <2> {set ColumnNumber "[GetXSelect]"}
bind .columnnr <Control-k> {set ColumnNumber "" ; update}
bind .columnnr <Left> {EntryCursor .columnnr -1}
bind .columnnr <Right> {EntryCursor .columnnr 1}

bind .actfile <FocusIn> {set OldName $ThisFileName}
bind .actfile <FocusOut> {set ThisFileName $OldName}
bind .actfile <Return> {
   set tmp $OldName
   set OldName $ThisFileName
   DoRenameBuffer $tmp $ThisFileName
   }
bind .actfile <2> {set ThisFileName "[GetXSelect]"}
bind .actfile <Control-k> {set ThisFileName "" ; update}
bind .actfile <Up> {set ThisFileName $OldName ; CycleBuffer}
bind .actfile <Down> {set ThisFileName $OldName ; CycleBuffer}
bind .actfile <Left> {EntryCursor .actfile -1}
bind .actfile <Right> {EntryCursor .actfile 1}

bind .bytes <FocusIn> {set OldBytes $NumBytes}
bind .bytes <Return> {GotoByte}
bind .bytes <2> {set NumBytes "[GetXSelect]"}
bind .bytes <Control-k> {set NumBytes "" ; update}
bind .bytes <Left> {EntryCursor .bytes -1}
bind .bytes <Right> {EntryCursor .bytes 1}

frame .ctextv
text .textv -relief raised -bd 2 \
         -width $WinWidth -height $WinHeight \
         -font $FontString \
         -background $BackgroundRGB \
         -foreground $ForegroundRGB \
         -selectbackground #b2dfee \
         -selectforeground black \
         -yscrollcommand ".scrollvy set" -setgrid 0

frame .ctext
pack .ctext -side top -after .row2 -expand 1 -fill both
text .text -relief raised -bd 2 \
         -width $WinWidth -height $WinHeight \
         -font $FontString \
         -background $BackgroundRGB \
         -foreground $ForegroundRGB \
         -selectbackground #b2dfee \
         -selectforeground black \
         -yscrollcommand ".scrolly set" -setgrid 1

if {$tk_version >= 4.0} {
         .text configure -xscrollcommand ".scrollx set"
#         .textv configure -xscrollcommand ".scrollx set"
}

scrollbar .scrolly -command "DoScrollY .text yview"
scrollbar .scrollvy -command "DoScrollY .textv yview"
scrollbar .scrollx -orient horizontal -command "DoScrollX"

#
# remove the highlight border for tk_4.x
#
if {$tk_version >= 4.0} {
foreach x "searchstring replacestring actfile linenr columnnr bytes" {
      .$x configure -highlightthickness 0}
foreach x "searchstringup searchstringdown searchfirst searchnext searchprev \
           casesense pattern replacestringup replacestringdown replacenext \
           replacerange replaceend replaceall autoindent protect " {
      .$x configure -highlightthickness 0}
}

wm minsize . 10 2

pack .scrolly -in .ctext -side right -fill y
pack .text -in .ctext -side bottom -expand 1 -fill both

.text mark set found1 1.0
.text mark set found2 1.0
.text mark set pastebeg 1.0
.text mark set pasteend 1.0
.text mark set match1 1.0
.text mark set match2 1.0
.text mark set last1 1.0
.text mark set last2 1.0
.text mark set markpos1 1.0
.text mark set markpos2 1.0
.text mark set markpos3 1.0
.text mark set markpos4 1.0
.text mark set insertv 1.0

#
# bindings for main editor window
#
proc binded {key cmd} {
   bind .text $key $cmd
   bind .textv $key $cmd
}

bind .text <FocusIn> {FocusIn .text}
bind .textv <FocusIn> {FocusIn .textv}
bind .text <FocusOut> {FocusOut .text}
bind .textv <FocusOut> {FocusOut .textv}
bind . <FocusOut> {FocusGone}

binded <3> {ClearMarks ; set Cancel 1}

if {$tk_version < 4.0} {
   binded <Double-1> {
       set tk_priv(selectMode) word
       tk_textSelectTo $AWin @%x,%y
       BeginOfWord
   }
   binded <Triple-1> {
       set tk_priv(selectMode) line
       tk_textSelectTo $AWin @%x,%y
       BeginOfLine
   }
} else {
   bind Text <KeyPress> { }
   binded <Any-Key> {if {"%A" != "\{\}"} {InsertText "%A"}}
   binded <Double-1> {
       set tkPriv(selectMode) word
       tkTextSelectTo %W %x %y
       %W mark set insert "insert wordstart"
   }
   binded <Triple-1> {
       set tkPriv(selectMode) line
       tkTextSelectTo %W %x %y
       %W mark set insert "insert linestart"
   }
}

binded <Return> {DoCmd ^j}
binded <BackSpace> {DoCmd ^h}
binded <Control-h> {DoCmd ^h}
binded <Delete> {DoCmd ^h}
binded <Tab> {DoCmd ^|}
binded <2> {DoCmd ^v}
binded <space> {DoSpace}
#
# Menu Shortcuts
#
binded <Control-a> {DoCmd ^a}
binded <Control-b> {DoCmd ^b}
binded <Control-c> {DoCmd ^c}
binded <Control-d> {DoCmd ^d}
binded <Control-e> {DoCmd ^e}
binded <Control-f> {DoCmd ^f}
binded <Control-g> {DoCmd ^g}
binded <Control-h> {DoCmd ^h}
binded <Control-i> {DoCmd ^i}
binded <Control-j> {DoCmd ^j}
binded <Control-k> {DoCmd ^k}
binded <Control-l> {DoCmd ^l}
binded <Control-m> {DoCmd ^m}
binded <Control-n> {DoCmd ^n}
binded <Control-o> {DoCmd ^o}
binded <Control-O> {DoCmd "^YOpenNew"}
binded <Control-p> {DoCmd ^p}
binded <Control-q> {DoCmd ^q}
binded <Control-r> {DoCmd ^r}
binded <Control-s> {DoCmd ^s}
binded <Control-t> {DoCmd ^t}
binded <Control-u> {DoCmd ^u}
binded <Control-v> {DoCmd ^v}
binded <Control-w> {DoCmd ^w}
binded <Control-x> {DoCmd ^x}
binded <Control-y> {DoCmd ^y}
binded <Control-z> {DoCmd "^z"}
binded <Control-Tab> {DoCmd "^YBackTab"}
binded <Shift-Tab> {DoCmd "^YCycleBuffer"}
binded <Control-greater> {DoCmd ^>}
binded <Control-less> {DoCmd ^<}
binded <Control-space> {DoCmd ^@}
binded <Control-minus> {DoCmd "^YJoinLines"}
binded <Escape> {Record 0}
binded <Control-bracketleft> {Record 0}
binded <Control-F1> {DoCmd "^YMarkPos 1"}
binded <Control-F2> {DoCmd "^YMarkPos 2"}
binded <Control-F3> {DoCmd "^YMarkPos 3"}
binded <Control-F4> {DoCmd "^YMarkPos 4"}
binded <Control-Key-0> {DoCmd ^0}
binded <Control-Key-1> {DoCmd ^1}
binded <Control-Key-2> {DoCmd ^2}
binded <Control-Key-3> {DoCmd ^3}
binded <Control-Key-4> {DoCmd ^4}
binded <Control-Key-5> {DoCmd ^5}
binded <Control-Key-6> {DoCmd ^6}
binded <Control-Key-7> {DoCmd ^7}
binded <Control-Key-8> {DoCmd ^8}
binded <Control-Key-9> {DoCmd ^9}
binded <Control-Key-period> {DoCmd ^.}
binded <Control-Key-comma> {DoCmd ^YDelToEOW}
binded <Control-Key-slash> {DoCmd ^/}
binded <Control-Key-equal> {DoCmd ^=}
#
# Cursor Movement
#
binded <Right> {DoCmd ^R}
binded <Left> {DoCmd ^L}
binded <Up> {DoCmd ^U}
binded <Down> {DoCmd ^D}
binded <Control-Up> {DoCmd ^T}
binded <Control-Down> {DoCmd ^B}
binded <Control-Left> {DoCmd ^A}
binded <Control-Right> {DoCmd ^Z}
binded <Shift-Up> {PrevScreen}
binded <Shift-Down> {NextScreen}
binded <Shift-Right> {DoCmd ^O}
binded <Shift-Left> {DoCmd ^W}

binded <M-Control-Up> {DoCmd ^T}
binded <M-Control-Down> {DoCmd ^B}
binded <M-Control-Left> {DoCmd ^A}
binded <M-Control-Right> {DoCmd ^Z}
binded <M-Shift-Up> {PrevScreen}
binded <M-Shift-Down> {NextScreen}
binded <M-Shift-Right> {DoCmd ^O}
binded <M-Shift-Left> {DoCmd ^W}


#
# Macro Keys
#

binded <F1> {DoCmd "^YPlayMac 1"}
binded <F2> {DoCmd "^YPlayMac 2"}
binded <F3> {DoCmd "^YPlayMac 3"}
binded <F4> {DoCmd "^YPlayMac 4"}
binded <F5> {DoCmd "^YPlayMac 5"}
binded <F6> {DoCmd "^YPlayMac 6"}
binded <F7> {DoCmd "^YPlayMac 7"}
binded <F8> {DoCmd "^YPlayMac 8"}
binded <F9> {DoCmd "^YPlayMac 9"}
binded <F10> {DoCmd "^YPlayMac 10"}
binded <F11> {DoCmd "^YPlayMac 11"}
binded <F12> {DoCmd "^YPlayMac 12"}
binded <F13> {DoCmd "^YPlayMac 13"}
binded <F14> {DoCmd "^YPlayMac 14"}
binded <F15> {DoCmd "^YPlayMac 15"}
binded <F16> {DoCmd "^YPlayMac 16"}
binded <F17> {DoCmd "^YPlayMac 17"}
binded <F18> {DoCmd "^YPlayMac 18"}
binded <F19> {DoCmd "^YPlayMac 19"}
binded <F20> {DoCmd "^YPlayMac 20"}
#
binded <KP_F1> {DoCmd "^YPlayMac 21"}
binded <KP_F2> {DoCmd "^YPlayMac 22"}
binded <KP_F3> {DoCmd "^YPlayMac 23"}
binded <KP_F4> {DoCmd "^YPlayMac 24"}
binded <KP_Equal> {DoCmd "^YPlayMac 25"}
binded <KP_Add> {DoCmd "^YPlayMac 26"}
binded <KP_Subtract> {DoCmd "^YPlayMac 27"}
binded <KP_Multiply> {DoCmd "^YPlayMac 28"}
binded <KP_Divide> {DoCmd "^YPlayMac 29"}
#
binded <KP_0> {DoCmd "^YPlayMac 30"}
binded <KP_1> {DoCmd "^YPlayMac 31"}
binded <KP_2> {DoCmd "^YPlayMac 32"}
binded <KP_3> {DoCmd "^YPlayMac 33"}
binded <KP_4> {DoCmd "^YPlayMac 34"}
binded <KP_5> {DoCmd "^YPlayMac 35"}
binded <KP_6> {DoCmd "^YPlayMac 36"}
binded <KP_7> {DoCmd "^YPlayMac 37"}
binded <KP_8> {DoCmd "^YPlayMac 38"}
binded <KP_9> {DoCmd "^YPlayMac 39"}
#
binded <KP_Enter> {DoCmd "^YPlayMac 40"}
binded <KP_Decimal> {DoCmd "^YPlayMac 41"}
binded <KP_Separator> {DoCmd "^YPlayMac 42"}
#
binded <Select> {DoCmd "^YPlayMac 43"}
binded <Find> {DoCmd "^YPlayMac 44"}
binded <Help> {DoCmd "^YPlayMac 45"}
binded <Undo> {DoCmd "^YPlayMac 46"}
binded <Redo> {DoCmd "^YPlayMac 47"}
binded <Home> {DoCmd "^YPlayMac 48"}
binded <Begin> {DoCmd "^YPlayMac 49"}
binded <End> {DoCmd "^YPlayMac 50"}
binded <Prior> {DoCmd "^YPlayMac 51"}
binded <Next> {DoCmd "^YPlayMac 52"}
binded <Execute> {DoCmd "^YPlayMac 53"}
binded <Insert> {DoCmd "^YPlayMac 54"}
binded <Cancel> {DoCmd "^YPlayMac 55"}
binded <Break> {DoCmd "^YPlayMac 56"}
binded <Print> {DoCmd "^YPlayMac 57"}
# binded <Delete> {DoCmd "^YPlayMac 58"}

#
# initialize Menus
#
# FILE Menus
#
menubutton .mBar.file -text File \
		-menu .mBar.file.m -background $XPrefMenuBack
menu .mBar.file.m -background $XPrefMenuBack
.mBar.file.m add command -label "Launcher" -command {DoCmd "^YLaunchFileSelect"}
.mBar.file.m add command -label "Open \[ctrl-o\]" -underline 0 \
        -command {DoCmd ^o}
.mBar.file.m add command -label "Open New \[ctrl-shift-o\]" \
        -command {DoCmd "^YOpenNew"}
.mBar.file.m add command -label "New Buffer \[ctrl-f\]" -underline 6\
  -command {DoCmd ^f ; set DelayedCMD "focus .actfile"}
.mBar.file.m add cascade -label "Reload" \
        -menu .mBar.file.m.reload
.mBar.file.m add separator
.mBar.file.m add command -label "Write \[ctrl-w\]" -underline 0 \
        -command {DoCmd ^w}
.mBar.file.m add command -label "Save As \[ctrl-a\]" -underline 5 \
        -command {DoCmd ^a}
.mBar.file.m add cascade -label "chmod" -menu .mBar.file.m.chmod
.mBar.file.m add cascade -label "convert" -menu .mBar.file.m.convert
.mBar.file.m add cascade -label "Export to" -menu .mBar.file.m.export
.mBar.file.m add separator
.mBar.file.m add command -label "Include File" \
        -command {DoCmd "^YIncludeAFile"}
.mBar.file.m add command -label "Include Column" \
        -command {DoCmd "^YIncludeAColumn"}
.mBar.file.m add separator
.mBar.file.m add command -label "Save Clip" \
        -command {DoCmd "^YSaveClip"}
.mBar.file.m add command -label "Print Buffer" \
        -command {DoCmd "^YPrintBuffer"}
.mBar.file.m add separator
.mBar.file.m add command -label "Quit \[ctrl-q\]" -underline 0 \
        -command {DoCmd ^q}
#
menu .mBar.file.m.chmod -background $XPrefMenuBack
.mBar.file.m.chmod add command -label "make Writable" \
	-command {exec chmod +w $ThisFileName}
.mBar.file.m.chmod add command -label "make Executable" \
	-command {exec chmod a+x $ThisFileName}
#
menu .mBar.file.m.convert -background $XPrefMenuBack
.mBar.file.m.convert add command -label "BS Remove (man)" \
        -command CVTBS
.mBar.file.m.convert add command -label "0x09 -> spaces%8" \
        -command CVTTabs
.mBar.file.m.convert add command -label "CR/LF -> LF" \
        -command CrLf2Lf
.mBar.file.m.convert add command -label "CR -> LF" \
        -command Cr2Lf
menu .mBar.file.m.export -background $XPrefMenuBack
.mBar.file.m.export add command -label "MS-DOSe (CR/LF)" \
        -command SaveCrLf
.mBar.file.m.export add command -label "OS-9 (CR)" \
        -command SaveCr
menu .mBar.file.m.reload -background $XPrefMenuBack
.mBar.file.m.reload add command -label "Last Saved" \
        -command {loadFile $ThisFileName}
.mBar.file.m.reload add command -label "Last Autosave" \
        -command {loadFile "$ThisFileName~"}
.mBar.file.m.reload add command -label "Last Backup" \
        -command {loadFile $ThisFileName.tkbak}
#
# Edit Menu
#
menubutton .mBar.edit -text Edit \
                -menu .mBar.edit.m -background $XPrefMenuBack
menu .mBar.edit.m -background $XPrefMenuBack
.mBar.edit.m add command -label "Limited Undo \[ctrl-u\]" -underline 8 \
               -command {DoCmd ^u}
.mBar.edit.m add command -label "Delete Char \[ctrl-=\]" \
                -command {DoCmd ^=}
.mBar.edit.m add command -label "Kill Word End\[ctrl-,\]"\
                -command {DoCmd "^YDelToEOW"}
.mBar.edit.m add command -label "Kill Word \[ctrl-d\]" -underline 8\
                -command {DoCmd ^d}
.mBar.edit.m add command -label "Kill Line \[ctrl-k\]" -underline 0\
                -command {DoCmd ^k}
.mBar.edit.m add command -label "Kill To EOL \[ctrl-.]" \
                -command {DoCmd ^.}
.mBar.edit.m add command -label "Kill To BOL \[ctrl-/]" \
                -command {DoCmd ^/}
.mBar.edit.m add command -label "Kill X-Select \[ctrl-x]" \
                -command {DoCmd ^x}
.mBar.edit.m add command -label "Kill Spaces \[ctrl-space]" \
                -command {DoCmd ^@}        
.mBar.edit.m add command -label "Join Lines \[ctrl-minus]" \
                -command {DoCmd "^YJoinLines"}        
.mBar.edit.m add command -label "Yank (unkill) \[ctrl-y\]" -underline 0\
                -command {DoCmd ^y}
.mBar.edit.m add command -label "Indent \[ctrl-i\]" -underline 0\
                -command {DoCmd ^i}
.mBar.edit.m add command -label "BackTab \[ctrl-Tab\]" \
                -command {DoCmd "^YBackTab"}
.mBar.edit.m add command -label "Capitalize  \[ctrl->\]" \
                -command {DoCmd ^>}
.mBar.edit.m add command -label "Lower Case  \[ctrl-<\]" \
                -command {DoCmd ^<}
#
# Cut / Paste Menu
#
menubutton .mBar.cut -text "Cut/Paste" \
               -menu .mBar.cut.m -background $XPrefMenuBack
menu .mBar.cut.m -background $XPrefMenuBack
.mBar.cut.m add command -label "Mark Begin \[ctrl-b\]" -underline 5\
                -command {DoCmd ^b}
.mBar.cut.m add command -label "Mark Columnar \[ctrl-t\]" \
                -command {DoCmd ^t}
.mBar.cut.m add command -label "Mark End (Copy) \[ctrl-e\]" -underline 5\
                -command {DoCmd ^e}
.mBar.cut.m add command -label "Cut \[ctrl-c\]" -underline 0\
                -command {DoCmd ^c}
.mBar.cut.m add command -label "Paste \[ctrl-v\]" \
                -command {DoCmd ^v}
.mBar.cut.m add separator
.mBar.cut.m add cascade -label "Store Clip" \
                -menu .mBar.cut.m.store
.mBar.cut.m add cascade -label "Restore Clip" \
                -menu .mBar.cut.m.restore
.mBar.cut.m add command -label "Clear Marks \[Right-Button\]" \
                -command {DoCmd "^YClearMarks"}
menu .mBar.cut.m.store -background $XPrefMenuBack
.mBar.cut.m.store add command -label "Store to 1" \
                -command {DoCmd "^YStoClip 1"}
.mBar.cut.m.store add command -label "Store to 2" \
                -command {DoCmd "^YStoClip 2"}
.mBar.cut.m.store add command -label "Store to 3" \
                -command {DoCmd "^YStoClip 3"}
.mBar.cut.m.store add command -label "Store to 4" \
                -command {DoCmd "^YStoClip 4"}
menu .mBar.cut.m.restore -background $XPrefMenuBack
.mBar.cut.m.restore add command -label "Restore from 1" \
                -command {DoCmd "^YRclClip 1"}
.mBar.cut.m.restore add command -label "Restore from 2" \
                -command {DoCmd "^YRclClip 2"}
.mBar.cut.m.restore add command -label "Restore from 3" \
                -command {DoCmd "^YRclClip 3"}
.mBar.cut.m.restore add command -label "Restore from 4" \
                -command {DoCmd "^YRclClip 4"}

#
# Search / Replace / Goto Menu
#
menubutton .mBar.search -text "Goto/Find" \
                -menu .mBar.search.m -background $XPrefMenuBack
menu .mBar.search.m -background $XPrefMenuBack
.mBar.search.m add command -label "Goto Line \[ctrl-g\]" -underline 0\
    -command {DoCmd ^g ; set DelayedCMD "focus .linenr"}
.mBar.search.m add command -label "Goto Top \[ctrl-up\]" \
                -command {DoCmd ^T}
.mBar.search.m add command -label "Goto Bottom \[ctrl-down\]" \
                -command {DoCmd ^B}
.mBar.search.m add command -label "Next Screen \[shift-down\]" \
                -command NextScreen
.mBar.search.m add command -label "Prev Screen \[shift-up\]" \
                -command PrevScreen
.mBar.search.m add separator
.mBar.search.m add command -label "Search \[ctrl-s\]" -underline 0\
   -command {DoCmd ^s ; set DelayedCMD "focus .searchstring"}
.mBar.search.m add command -label "Search Next \[ctrl-n\]" -underline 7\
                -command {DoCmd ^n}
.mBar.search.m add command -label "Search Prev. \[ctrl-p\]" -underline 7\
                -command {DoCmd ^p}
.mBar.search.m add checkbutton -label "Case Sensitive"\
                -variable SearchCaseYN
.mBar.search.m add checkbutton -label "Pattern"\
                -variable SearchPatternYN
.mBar.search.m add command -label "Replace \[ctrl-r\]" -underline 0\
   -command {DoCmd ^r ; set DelayedCMD "focus .replacestring"}
.mBar.search.m add command -label "Replace Next \[ctrl-l\]" -underline 3\
                -command {DoCmd ^l}
.mBar.search.m add command -label "Replace Range" \
                -command ReplaceRange
.mBar.search.m add command -label "Replace All" \
                -command ReplaceAll
.mBar.search.m add separator
.mBar.search.m add command -label "Match (\{\[\]\}) \[ctrl-m\]" -underline 0\
                -command {DoCmd ^m}
.mBar.search.m add cascade -label "Mark Position" \
                -menu .mBar.search.m.markpos
.mBar.search.m add cascade -label "Goto Position" \
                -menu .mBar.search.m.gotopos
menu .mBar.search.m.markpos -background $XPrefMenuBack
.mBar.search.m.markpos add command -label "Mark 1   \[ctrl-F1\]" \
                -command {DoCmd "^YMarkPos 1"}
.mBar.search.m.markpos add command -label "Mark 2   \[ctrl-F2\]" \
                -command {DoCmd "^YMarkPos 2"}
.mBar.search.m.markpos add command -label "Mark 3   \[ctrl-F3\]" \
                -command {DoCmd "^YMarkPos 3"}
.mBar.search.m.markpos add command -label "Mark 4   \[ctrl-F4\]" \
                -command {DoCmd "^YMarkPos 4"}
menu .mBar.search.m.gotopos -background $XPrefMenuBack
.mBar.search.m.gotopos add command -label "Goto 1   \[ctrl-1\]" \
                -command {DoCmd ^1}
.mBar.search.m.gotopos add command -label "Goto 2   \[ctrl-2\]" \
                -command {DoCmd ^2}
.mBar.search.m.gotopos add command -label "Goto 3   \[ctrl-3\]" \
                -command {DoCmd ^3}
.mBar.search.m.gotopos add command -label "Goto 4   \[ctrl-4\]" \
                -command {DoCmd ^4}
.mBar.search.m.gotopos add command -label "Range Begin \[ctrl-5\]" \
                -command {DoCmd ^5}
.mBar.search.m.gotopos add command -label "Range End \[ctrl-6\]" \
                -command {DoCmd ^6}
.mBar.search.m.gotopos add command -label "Primary View \[ctrl-7\]" \
                -command {DoCmd ^7}
.mBar.search.m.gotopos add command -label "Secondary View \[ctrl-8\]" \
                -command {DoCmd ^8}
.mBar.search.m.gotopos add command -label "Last postion \[ctrl-0\]" \
                -command {DoCmd ^0}
.mBar.search.m.gotopos add command -label "Last Search \[ctrl-9\]" \
                -command {DoCmd ^9}
#
# Preferences Menus
#
menubutton .mBar.prefs -text Preferences\
                -menu .mBar.prefs.m -background $XPrefMenuBack
menu .mBar.prefs.m -background $XPrefMenuBack
.mBar.prefs.m add command -label "Save Preferences" \
                -command SavePrefs
.mBar.prefs.m add checkbutton -label "Pref-Autosave" \
                -variable XPrefAutoSavePrefs
.mBar.prefs.m add cascade -label "Font Type" \
                -menu .mBar.prefs.m.font
.mBar.prefs.m add cascade -label "Font Size" \
                -menu .mBar.prefs.m.size
.mBar.prefs.m add cascade -label "Colors" \
                -menu .mBar.prefs.m.color
.mBar.prefs.m add cascade -label "Default Colors" \
                -menu .mBar.prefs.m.defcolor
.mBar.prefs.m add checkbutton -label "Enable split/undo" \
                -variable EnaSplitYN -command ClearView
.mBar.prefs.m add checkbutton -label "X-Kill on BS/DEL" \
                -variable XPrefXKillOnBS
.mBar.prefs.m add checkbutton -label "Dim FocusOut" \
                -variable DimFocusOutYN
.mBar.prefs.m add checkbutton -label "Old Style Select" \
                -variable XPrefOldSelect -command SetSelectStyle
.mBar.prefs.m add checkbutton -label "Ins. follow View" \
                -variable XPrefFollowViewYN
.mBar.prefs.m add checkbutton -label "Copy Attributes" \
                -variable XPrefCPAttrYN
.mBar.prefs.m add checkbutton -label "Scrollbar-X" \
                -variable XPrefScrollBarX -command SwitchXscroll
.mBar.prefs.m add checkbutton -label "Autosave"\
                -variable AutoSaveYN
.mBar.prefs.m add checkbutton -label "AutoBackup"\
                -variable AutoBackupYN
.mBar.prefs.m add cascade -label "Tabs"\
                -menu .mBar.prefs.m.tabs
.mBar.prefs.m add cascade -label "AutoNewLine"\
                -menu .mBar.prefs.m.autonl
#
menu .mBar.prefs.m.font -background $XPrefMenuBack
.mBar.prefs.m.font add command -label "Helvetica Medium" \
                -command {DoCmd "^YSetFont -Adobe-Helvetica-Medium-R-Normal"}
.mBar.prefs.m.font add command -label "Helvetica Bold" \
                -command {DoCmd "^YSetFont -Adobe-Helvetica-Bold-R-Normal"}
.mBar.prefs.m.font add command -label "Courier Medium" \
                -command {DoCmd "^YSetFont -Adobe-Courier-Medium-R-Normal"}
.mBar.prefs.m.font add command -label "Courier Bold" \
                -command {DoCmd "^YSetFont -Adobe-Courier-Bold-R-Normal"}
.mBar.prefs.m.font add command -label "Times Medium" \
                -command {DoCmd "^YSetFont -Adobe-Times-Medium-R-Normal"}
.mBar.prefs.m.font add command -label "Times Bold" \
                -command {DoCmd "^YSetFont -Adobe-Times-Bold-R-Normal"}
.mBar.prefs.m.font add command -label "Fixed Medium" \
                -command {DoCmd "^YSetFont -Misc-Fixed-Medium-R-Normal"}
.mBar.prefs.m.font add command -label "Fixed Bold" \
                -command {DoCmd "^YSetFont -Misc-Fixed-Bold-R-Normal"}
#
menu .mBar.prefs.m.size -background $XPrefMenuBack
.mBar.prefs.m.size add command -label "80" -command {DoCmd "^YNewFontSize 80"}
.mBar.prefs.m.size add command -label "90" -command {DoCmd "^YNewFontSize 90"}
.mBar.prefs.m.size add command -label "100" -command {DoCmd "^YNewFontSize 100"}
.mBar.prefs.m.size add command -label "120" -command {DoCmd "^YNewFontSize 120"}
.mBar.prefs.m.size add command -label "140" -command {DoCmd "^YNewFontSize 140"}
.mBar.prefs.m.size add command -label "180" -command {DoCmd "^YNewFontSize 180"}
.mBar.prefs.m.size add command -label "240" -command {DoCmd "^YNewFontSize 240"}
#
menu .mBar.prefs.m.color -background $XPrefMenuBack
.mBar.prefs.m.color add checkbutton -label "Use send" \
                -variable UseSend
set UseSend 0
.mBar.prefs.m.color add separator
.mBar.prefs.m.color add command -label "Edit Background" \
                -command {SetRGB_bg -1}
.mBar.prefs.m.color add command -label "Edit Foreground" \
                -command {SetRGB_fg -1}
.mBar.prefs.m.color add command -label "HotList Back" \
                -command {SetRGB XPrefHotBgRGB}
.mBar.prefs.m.color add command -label "HotList Fore" \
                -command {SetRGB XPrefHotFgRGB}
.mBar.prefs.m.color add command -label "Panel Back" \
                -command {SetRGB XPrefMainBack}
.mBar.prefs.m.color add command -label "Menu Back" \
                -command {SetRGB XPrefMenuBack}
.mBar.prefs.m.color add command -label "Button Back" \
                -command {SetRGB XPrefButtonBack}
.mBar.prefs.m.color add command -label "Entry Back" \
                -command {SetRGB XPrefEntBack}
.mBar.prefs.m.color add separator
.mBar.prefs.m.color add command -label "Found" \
                -command {SetRGB XPrefFoundRGB}
.mBar.prefs.m.color add command -label "Paste" \
                -command {SetRGB XPrefPasteRGB}
.mBar.prefs.m.color add command -label "Match" \
                -command {SetRGB XPrefMatchRGB}
.mBar.prefs.m.color add separator
#
menu .mBar.prefs.m.defcolor -background $XPrefMenuBack
.mBar.prefs.m.defcolor add command -label "grey/blue/violett" \
                -command {DefaultColor 1 ; UpdateRGB}
.mBar.prefs.m.defcolor add command -label "Green" \
                -command {DefaultColor 2 ; UpdateRGB}
.mBar.prefs.m.defcolor add command -label "Original" \
                -command {DefaultColor 3 ; UpdateRGB}
#
menu .mBar.prefs.m.tabs -background $XPrefMenuBack
.mBar.prefs.m.tabs add radiobutton -label "Char 0x09"\
                -value 0 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 2"\
                -value 2 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 3"\
                -value 3 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 4"\
                -value 4 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 5"\
                -value 5 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 6"\
                -value 6 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 7"\
                -value 7 -variable TabDistance
.mBar.prefs.m.tabs add radiobutton -label "Spaces % 8"\
                -value 8 -variable TabDistance

menu .mBar.prefs.m.autonl -background $XPrefMenuBack
.mBar.prefs.m.autonl add radiobutton -label "No AutoNewLine"\
                -value 0 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "60 char"\
                -value 60 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "70 char"\
                -value 70 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "FORTRAN"\
                -value 72 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "80 char"\
                -value 80 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "90 char"\
                -value 90 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "100 char"\
                -value 100 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "110 char"\
                -value 110 -variable AutoNewLine
.mBar.prefs.m.autonl add radiobutton -label "120 char"\
                -value 120 -variable AutoNewLine

#
# Macro Menu
# will be filled from directory $HOME/tkedit-macros
#
menubutton .mBar.macro -text Macro \
                -menu .mBar.macro.m -background $XPrefMenuBack
menu .mBar.macro.m -background $XPrefMenuBack
.mBar.macro.m add command -label "Call External" \
                -command {DoCmd "^YMacroExternal"}
.mBar.macro.m add command -label "Copy Macro" \
                -command {MacroCopy}                
.mBar.macro.m add command -label "Load Startup" \
                -command {MacroAddStart}                
.mBar.macro.m add command -label "Remove Startup" \
                -command {MacroRemove}                
.mBar.macro.m add separator
.mBar.macro.m add command -label "README !" \
                -command {MacroWarning}
.mBar.macro.m add cascade -label "F-Keys 1-20" \
                -menu .mBar.macro.m.fkey
.mBar.macro.m add cascade -label "Keypad Keys" \
                -menu .mBar.macro.m.keypad
.mBar.macro.m add cascade -label "Other Keys" \
                -menu .mBar.macro.m.other
.mBar.macro.m add command -label "Append Selected text" \
                -command {
       set MacF($MacroActive) "$MacF($MacroActive)[selection get]"
       set RecMacTextPos [$AWin index insert]
                         }
.mBar.macro.m add command -label "Append External Macro" \
                -command {
       set f [eval "exec $FileSelect"]
       if {[string length $f] > 0} {
          set MacF($MacroActive) "$MacF($MacroActive)^X$f"
       }
                         }
.mBar.macro.m add command -label "Record END \[esc\]" \
                -command {Record 0}

menu .mBar.macro.m.fkey -background $XPrefMenuBack
.mBar.macro.m.fkey add command -label "Record F1" \
                -command {Record 1}
.mBar.macro.m.fkey add command -label "Record F2" \
                -command {Record 2}
.mBar.macro.m.fkey add command -label "Record F3" \
                -command {Record 3}
.mBar.macro.m.fkey add command -label "Record F4" \
                -command {Record 4}
.mBar.macro.m.fkey add command -label "Record F5" \
                -command {Record 5}
.mBar.macro.m.fkey add command -label "Record F6" \
                -command {Record 6}
.mBar.macro.m.fkey add command -label "Record F7" \
                -command {Record 7}
.mBar.macro.m.fkey add command -label "Record F8" \
                -command {Record 8}
.mBar.macro.m.fkey add command -label "Record F9" \
                -command {Record 9}
.mBar.macro.m.fkey add command -label "Record F10" \
                -command {Record 10}
.mBar.macro.m.fkey add command -label "Record F11" \
                -command {Record 11}
.mBar.macro.m.fkey add command -label "Record F12" \
                -command {Record 12}
.mBar.macro.m.fkey add command -label "Record F13" \
                -command {Record 13}
.mBar.macro.m.fkey add command -label "Record F14" \
                -command {Record 14}
.mBar.macro.m.fkey add command -label "Record F15" \
                -command {Record 15}
.mBar.macro.m.fkey add command -label "Record F16" \
                -command {Record 16}
.mBar.macro.m.fkey add command -label "Record F17" \
                -command {Record 17}
.mBar.macro.m.fkey add command -label "Record F18" \
                -command {Record 18}
.mBar.macro.m.fkey add command -label "Record F19" \
                -command {Record 19}
.mBar.macro.m.fkey add command -label "Record F20" \
                -command {Record 20}

menu .mBar.macro.m.keypad -background $XPrefMenuBack
.mBar.macro.m.keypad add command -label "Record PF1" \
                -command {Record 21}
.mBar.macro.m.keypad add command -label "Record PF2" \
                -command {Record 22}
.mBar.macro.m.keypad add command -label "Record PF3" \
                -command {Record 23}
.mBar.macro.m.keypad add command -label "Record PF4" \
                -command {Record 24}
.mBar.macro.m.keypad add command -label "Record Equal" \
                -command {Record 25}
.mBar.macro.m.keypad add command -label "Record Add" \
                -command {Record 26}
.mBar.macro.m.keypad add command -label "Record Subtract" \
                -command {Record 27}
.mBar.macro.m.keypad add command -label "Record Multiply" \
                -command {Record 28}
.mBar.macro.m.keypad add command -label "Record Divide" \
                -command {Record 29}
.mBar.macro.m.keypad add command -label "Record 0" \
                -command {Record 30}
.mBar.macro.m.keypad add command -label "Record 1" \
                -command {Record 31}
.mBar.macro.m.keypad add command -label "Record 2" \
                -command {Record 32}
.mBar.macro.m.keypad add command -label "Record 3" \
                -command {Record 33}
.mBar.macro.m.keypad add command -label "Record 4" \
                -command {Record 34}
.mBar.macro.m.keypad add command -label "Record 5" \
                -command {Record 35}
.mBar.macro.m.keypad add command -label "Record 6" \
                -command {Record 36}
.mBar.macro.m.keypad add command -label "Record 7" \
                -command {Record 37}
.mBar.macro.m.keypad add command -label "Record 8" \
                -command {Record 38}
.mBar.macro.m.keypad add command -label "Record 9" \
                -command {Record 39}
.mBar.macro.m.keypad add command -label "Record Enter" \
                -command {Record 40}
.mBar.macro.m.keypad add command -label "Record Decimal" \
                -command {Record 41}
.mBar.macro.m.keypad add command -label "Record Separator" \
                -command {Record 42}

menu .mBar.macro.m.other -background $XPrefMenuBack
.mBar.macro.m.other add command -label "Record Select" \
                -command {Record 43}
.mBar.macro.m.other add command -label "Record Find" \
                -command {Record 44}
.mBar.macro.m.other add command -label "Record Help" \
                -command {Record 45}
.mBar.macro.m.other add command -label "Record Undo" \
                -command {Record 46}
.mBar.macro.m.other add command -label "Record Redo" \
                -command {Record 47}
.mBar.macro.m.other add command -label "Record Home" \
                -command {Record 48}
.mBar.macro.m.other add command -label "Record Begin" \
                -command {Record 49}
.mBar.macro.m.other add command -label "Record End" \
                -command {Record 50}
.mBar.macro.m.other add command -label "Record Prior" \
                -command {Record 51}
.mBar.macro.m.other add command -label "Record Next" \
                -command {Record 52}
.mBar.macro.m.other add command -label "Execute/Do/Run" \
                -command {Record 53}
.mBar.macro.m.other add command -label "Record Insert" \
                -command {Record 54}
.mBar.macro.m.other add command -label "Record Cancel" \
                -command {Record 55}
.mBar.macro.m.other add command -label "Record Break" \
                -command {Record 56}
.mBar.macro.m.other add command -label "Record Print" \
                -command {Record 57}
# .mBar.macro.m.other add command -label "Record Delete" \
#                 -command {Record 58}
#
# Buffer Menu
#
menubutton .mBar.buffer -text Buffer -menu .mBar.buffer.m \
      -background $XPrefMenuBack
menu .mBar.buffer.m -background $XPrefMenuBack
.mBar.buffer.m add command -label "Cycle Buffer \[shift-Tab\]" \
                  -command {DoCmd "^YCycleBuffer"} \
                  -background white
.mBar.buffer.m add command -label "Close Buffer \[ctrl-z\]" \
                  -command {DoCmd ^z} \
                  -background white
.mBar.buffer.m add command -label "Rename Buffer" \
                  -command {set DelayedCMD "focus .actfile"} \
                  -background white
.mBar.buffer.m add command -label "Launch Buffer" \
                  -command {DoCmd "^YLaunchBuffer"} 
.mBar.buffer.m add separator
.mBar.buffer.m add command -label "Actual Hotlist" \
                  -command {DoCmd "^YBufMakeHotlist"} \
                  -background "#ffe0e0"
.mBar.buffer.m add separator
#
# LSE Menu
#
menubutton .mBar.lse -text "Language" -menu .mBar.lse.m \
      -background $XPrefMenuBack
menu .mBar.lse.m -background $XPrefMenuBack
.mBar.lse.m add cascade -label "Language" -menu .mBar.lse.m.lang
.mBar.lse.m add cascade -label "C" -menu .mBar.lse.m.c
.mBar.lse.m add cascade -label "FORTRAN" -menu .mBar.lse.m.ftn
.mBar.lse.m add cascade -label "TCL" -menu .mBar.lse.m.tcl
.mBar.lse.m add command -label "Make HotList" \
               -command {DoCmd "^YMakeHotList"}
.mBar.lse.m add command -label "Goto Declar." \
               -command {DoCmd "^YGotoDeclar"}

menu .mBar.lse.m.c -background $XPrefMenuBack
.mBar.lse.m.c add command -label "C-Comment" \
               -command {DoCmd "^YCComment"}
.mBar.lse.m.c add command -label "C-Uncomment" \
               -command {DoCmd "^YCUncomment"}
.mBar.lse.m.c add command -label "Frame Range" \
               -command {DoCmd "^YFrameRangeC"}
.mBar.lse.m.c add command -label "Remove Frame" \
               -command {DoCmd "^YRemoveFrameC"}
#
menu .mBar.lse.m.ftn -background $XPrefMenuBack
#
menu .mBar.lse.m.tcl -background $XPrefMenuBack
.mBar.lse.m.tcl add command -label "Frame Range" \
               -command {DoCmd "^YFrameRangeTCL"}
.mBar.lse.m.tcl add command -label "Remove Frame" \
               -command {DoCmd "^YRemoveFrameTCL"}
#
menu .mBar.lse.m.lang -background $XPrefMenuBack
.mBar.lse.m.lang add radiobutton -label "Unknown"\
                -value "Unknown" -variable FileType
.mBar.lse.m.lang add radiobutton -label "SHELL"\
                -value "SHELL" -variable FileType
.mBar.lse.m.lang add radiobutton -label "CSH"\
                -value "CSH" -variable FileType
.mBar.lse.m.lang add radiobutton -label "TCL"\
                -value "TCL" -variable FileType
.mBar.lse.m.lang add radiobutton -label "PERL"\
                -value "PERL" -variable FileType

#
# Miscellaneus Menu
#
menubutton .mBar.misc -text "Misc." -menu .mBar.misc.m \
       -background $XPrefMenuBack
menu .mBar.misc.m -background $XPrefMenuBack
.mBar.misc.m add command -label "Version $Version" \
            -command Commercial -background white
.mBar.misc.m add command -label "Rainer Kowallik" \
            -command Commercial -background white
.mBar.misc.m add command -label "kowallik@ifh.de" \
            -command Commercial -background white
.mBar.misc.m add command -label "Check Send" \
            -command {DoCmd "^YDoCheckSend"}
.mBar.misc.m add command -label "Run Update" \
            -command {DoCmd "^YDoUpdate"}
.mBar.misc.m add command -label "EvalClip" \
               -command {DoCmd "^YEvalClip"}
.mBar.misc.m add command -label "Split View" \
               -command {DoCmd "^YSplitView"}
.mBar.misc.m add command -label "Close View" \
               -command {DoCmd "^YCloseView"}
.mBar.misc.m add command -label "Repeat Key" \
               -command {DoCmd "^!RepeatKey"}
.mBar.misc.m add command -label "Rpt.K. Range" \
               -command {DoCmd "^YRepeatKeyRange"}
.mBar.misc.m add cascade -label "Shell" -menu .mBar.misc.m.shell
.mBar.misc.m add cascade -label "Extract" -menu .mBar.misc.m.extract

menu .mBar.misc.m.shell -background $XPrefMenuBack
.mBar.misc.m.shell add command -label "Execute command" \
               -command {DoCmd "^YShellExecute"}
.mBar.misc.m.shell add command -label "Copy Back" \
               -command {DoCmd "^YShellCopy"}
.mBar.misc.m.shell add command -label "Close Window" \
               -command {DoCmd "^YShellClose"}

menu .mBar.misc.m.extract -background $XPrefMenuBack
.mBar.misc.m.extract add command -label "extract search" \
               -command {DoCmd "^YExtractSearch"}
.mBar.misc.m.extract add command -label "Copy Back" \
               -command {DoCmd "^YExtractCopy"}
.mBar.misc.m.extract add command -label "Goto Line" \
               -command {DoCmd "^YExtractGoto"}
.mBar.misc.m.extract add command -label "Close Window" \
               -command {DoCmd "^YExtractClose"}

#
# Help Menu
#
menubutton .mBar.help -text Help -menu .mBar.help.m -background $XPrefMenuBack
menu .mBar.help.m -background $XPrefMenuBack
.mBar.help.m add command -label "Mouse Buttons" \
               -command {SearchHelp "Mouse Buttons:"}
.mBar.help.m add command -label "Moving Cursor" \
               -command {SearchHelp "Cursor movement:"}
.mBar.help.m add command -label "Simple Editing" \
               -command {SearchHelp "Editing:"}
.mBar.help.m add command -label "Search/Replace" \
               -command {SearchHelp "Search and Replace:"}
.mBar.help.m add command -label "Cut and Paste" \
               -command {SearchHelp "Paste Buffers:"}
.mBar.help.m add command -label "Text Markers" \
               -command {SearchHelp "Textmarkers:"}
.mBar.help.m add command -label "Macro Recording" \
               -command {SearchHelp "Function Key Macros:"}
.mBar.help.m add command -label "External macros" \
               -command {SearchHelp "External macros:"}
.mBar.help.m add command -label "Startup Macros" \
               -command {SearchHelp "Startup macros:"}
.mBar.help.m add command -label "Extract Search" \
               -command {SearchHelp "Extract_Search Feature:"}
.mBar.help.m add command -label "Language Menu" \
               -command {SearchHelp "Language Menu Features:"}
.mBar.help.m add command -label "Multiple Buffers" \
               -command {SearchHelp "Multiple Buffers:"}
.mBar.help.m add command -label "The Close Button" \
               -command {SearchHelp "The Status Indicator/Close Button:"}
.mBar.help.m add command -label "Split Views" \
               -command {SearchHelp "Split Views:"}
.mBar.help.m add command -label "Preferences" \
               -command {SearchHelp "Preferences:"}
.mBar.help.m add command -label "Converting Text" \
               -command {SearchHelp "Converting Text:"}
.mBar.help.m add command -label "Repeat Key" \
               -command {SearchHelp "Repeat Key Feature:"}
.mBar.help.m add command -label "More / Less" \
               -command {SearchHelp "More / Less Feature:"}
.mBar.help.m add command -label "Startup Files" \
               -command {SearchHelp "Startup files:"}
.mBar.help.m add command -label "Cmd.line options" \
               -command {SearchHelp "Command line options:"}
.mBar.help.m add command -label "BW-Monitor" \
               -command {SearchHelp "BW_Terminal.startup"}
.mBar.help.m add command -label "Bugs" \
               -command {SearchHelp "Known Bugs to Version $Version:"}
.mBar.help.m add command -label "Whats New" \
   -command {MacHelp "REVISIONLIST.tkedit" "Changes in Version $Version:"}
.mBar.help.m add command -label "README/UPDATE" \
               -command {SearchHelp "Startup Macros:"}
.mBar.help.m add command -label "micro tkedit" \
               -command {SearchHelp "tkedit light or tke:"}
#
# Macro Help
#
menubutton .mBar.machelp -text Macro_Help -menu .mBar.machelp.m \
      -background $XPrefMenuBack
menu .mBar.machelp.m -background $XPrefMenuBack
.mBar.machelp.m add command -label "Available Macros" \
               -command {MacHelp "AvailableMacros.txt" ""}
.mBar.machelp.m add command -label "How to write" \
               -command {MacHelp "writing_macros.txt" ""}

pack .mBar.file .mBar.edit .mBar.cut .mBar.search .mBar.prefs .mBar.macro \
             .mBar.buffer .mBar.lse .mBar.misc .mBar.help .mBar.machelp\
             -side left -expand 1
tk_menuBar .mBar .mBar.file .mBar.edit .mBar.cut .mBar.search .mBar.prefs \
    .mBar.macro .mBar.buffer .mBar.lse .mBar.misc .mBar.help .mBar.machelp

#
# window focus routines
#
proc FocusOut win {
   global AWin LWin
   
   StoreXSelect
   set w ".text"
   if {$win == ".text" } {set w ".textv"}
   CopyText $win $w
   set LWin $win
}

proc FocusGone { } {
   DimWin .text
   DimWin .textv
}

proc DimWin win {
   global BackgroundRGB ForegroundRGB DimFocusOutYN
   
   if {($BackgroundRGB != -1) && ($DimFocusOutYN == 1)} {
      scan $BackgroundRGB "#%2x%2x%2x" r g b
      set r [expr $r >> 1]
      set g [expr $g >> 1]
      set b [expr $b >> 1]
      if {$r < 0} {set r 0}
      if {$g < 0} {set g 0}
      if {$b < 0} {set b 0}
      set rgb [format "#%2.2x%2.2x%2.2x" $r $g $b]
      $win configure -background $rgb
   }
}


#
# queue handling
#

proc AddAfterCMD function {
   global DoAfterCMD
   set DoAfterCMD "$DoAfterCMD ; $function"
}

proc RemoveAfterCMD function {
   global DoAfterCMD
   regsub " ; $function" $DoAfterCMD "" DoAfterCMD
}
 
proc AddBeforeCMD function {
   global DoBeforeCMD
   set DoBeforeCMD "$DoBeforeCMD ; $function"
}

proc RemoveBeforeCMD function {
   global DoBeforeCMD
   regsub " ; $function" $DoBeforeCMD "" DoBeforeCMD
}

proc AddPoll function {
   global PollFunctions
   set PollFunctions "$PollFunctions ; $function"
}

proc RemovePoll function {
   global PollFunctions
   regsub " ; $function" $PollFunctions "" PollFunctions
}

proc AddNewLine function {
   global DoNewLineCMD
   set DoNewLineCMD "$DoNewLineCMD; $function"
}

proc RemoveNewLine function {
   global DoNewLineCMD
   regsub " ; $function" $DoNewLineCMD "" DoNewLineCMD
}


proc AddSave function {
   global SaveFunctions
   set SaveFunctions "$SaveFunctions ; $function"
}

proc RemoveSave function {
   global SaveFunctions
   regsub " ; $function" $SaveFunctions "" SaveFunctions
}

#
# Procedures that build up the editor
#
proc CycleBuffer { } {
   global ThisFileName BufferStoT BufferStoM BufferStoS BufferStoP

   set n [lsearch [array names BufferStoT] $ThisFileName]
   set m [array size BufferStoT]
   incr n
   if { $n >= $m } {set n 0}   
   set file [lindex [array names BufferStoT] $n]
   ChangeBuffer $file
}

proc NewBuffer file {
   global AWin LWin ModifyStatus AutoSaveStatus ProtectYN ThisFileName \
          SaveFirstTime NumBytes HiddenBytes DelayedCMD Usage FileType\
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU BufferStoV \
          BufferStoF BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
          BufferSto5 BufferSto6 BufferSto7 BufferSto8 \
          BufferStoRet BufferStoTab BufferStoSpc BufferStoView BufferStoH\
          ExtReturnCMD ExtTabCMD ExtSpaceCMD

   ChangeBuffer ""
   set x ".mBar.buffer.m add command -label $file "
   set x "$x -command {ChangeBuffer $file}"
   uplevel $x
   .text delete 1.0 end
   set ModifyStatus 0; set AutoSaveStatus 0 ; set SaveFirstTime 1
   set HiddenBytes 0
   set BufferStoT($file) " "
   set BufferStoM($file) $ModifyStatus
   set BufferStoH($file) $HiddenBytes
   set BufferStoS($file) $AutoSaveStatus
   set BufferStoP($file) 1.0
   set BufferStoU($file) "File"
   set BufferStoF($file) "Unknown"
   set BufferStoV($file) 1.0
   set BufferSto1($file) 1.0
   set BufferSto2($file) 1.0
   set BufferSto3($file) 1.0
   set BufferSto4($file) 1.0
   set BufferSto5($file) 1.0
   set BufferSto6($file) 1.0
   set BufferSto7($file) 1.0
   set BufferSto8($file) 1.0
   set BufferStoRet($file) "InsertReturn"
   set BufferStoTab($file) "InsertTab"
   set BufferStoSpc($file) "InsertSpace"
   set BufferStoView($file) 0
   set ExtReturnCMD "InsertReturn"
   set ExtTabCMD "InsertTab"
   set ExtSpaceCMD "InsertSpace"
   set DelayedCMD "NoAction"
   set Usage "File"
   set FileType "Unknown"

   CopyText .text .textv
   focus .actfile
   set ThisFileName $file
   BufUpdateHotlist
   DoService 1
}

proc ChangeBuffer BufferName {
   global AWin LWin ModifyStatus AutoSaveStatus ProtectYN ThisFileName OldName\
          SaveFirstTime NumBytes HiddenBytes Usage FileType\
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU BufferStoV \
          BufferStoF BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
          BufferSto5 BufferSto6 BufferSto7 BufferSto8 \
          BufferStoRet BufferStoTab BufferStoSpc BufferStoView BufferStoH\
          ExtReturnCMD ExtTabCMD ExtSpaceCMD

   StoreXSelect
   StoreAttributes $ThisFileName
   if { $NumBytes > 1 } {
      set BufferStoT($ThisFileName) "[$AWin get 1.0 end]"
      set BufferStoM($ThisFileName) $ModifyStatus
      set BufferStoS($ThisFileName) $AutoSaveStatus
      set BufferStoH($ThisFileName) $HiddenBytes
      set BufferStoP($ThisFileName) "[$AWin index insert]"
      set BufferStoV($ThisFileName) "[$AWin index insertv]"
      set BufferStoU($ThisFileName) $Usage
      set BufferStoF($ThisFileName) $FileType
      set BufferSto1($ThisFileName) [$AWin index markpos1]
      set BufferSto2($ThisFileName) [$AWin index markpos2]
      set BufferSto3($ThisFileName) [$AWin index markpos3]
      set BufferSto4($ThisFileName) [$AWin index markpos4]
      set BufferSto5($ThisFileName) [$AWin index pastebeg]
      set BufferSto6($ThisFileName) [$AWin index pasteend]
      set BufferSto7($ThisFileName) [$AWin index found1]
      set BufferSto8($ThisFileName) [$AWin index last2]
      set BufferStoRet($ThisFileName) $ExtReturnCMD
      set BufferStoTab($ThisFileName) $ExtTabCMD
      set BufferStoSpc($ThisFileName) $ExtSpaceCMD
      set BufferStoView($ThisFileName) $ProtectYN
      }
   .text delete 1.0 end
   if {$BufferName == ""} return
   .text insert end "$BufferStoT($BufferName)"
   set ThisFileName $BufferName
   set OldName $BufferName
   .text mark set insert "$BufferStoP($BufferName)"
   .text mark set insertv "$BufferStoV($BufferName)"
   set Usage $BufferStoU($BufferName)
   set FileType $BufferStoF($BufferName)
   set ExtReturnCMD $BufferStoRet($BufferName)
   set ExtTabCMD $BufferStoTab($BufferName)
   set ExtSpaceCMD $BufferStoSpc($BufferName)
   set ProtectYN $BufferStoView($BufferName)
   DoService 1
   set ModifyStatus $BufferStoM($BufferName)
   set HiddenBytes $BufferStoH($BufferName)
   set AutoSaveStatus $BufferStoS($BufferName)
   .text yview -pickplace insert
   .text mark set markpos1 "$BufferSto1($BufferName)"
   .text mark set markpos2 "$BufferSto2($BufferName)"
   .text mark set markpos3 "$BufferSto3($BufferName)"
   .text mark set markpos4 "$BufferSto4($BufferName)"
   .text mark set pastebeg "$BufferSto5($BufferName)"
   .text mark set pasteend "$BufferSto6($BufferName)"
   .text mark set found1 "$BufferSto7($BufferName)"
   .text mark set last2 "$BufferSto8($BufferName)"
   CopyText .text .textv
   RecallAttributes $BufferName
   GetFileType
   DoService 0  
}

proc BufMakeHotlist { } {
   global AWin ThisFileName BufferStoT

   set names "[array names BufferStoT]"
   set h 0
   set w 10
   foreach i "$names" {
      set l [string length $i]
      if {$l > $w} {set w $l}
      incr h
   }
   BufOpenHotWin $h $w
   foreach i "$names" {
      .bufhot.win insert end "$i\n"
   }
}

proc BufUpdateHotlist { } {
   global AWin ThisFileName BufferStoT BufHotIsOpen

   if {$BufHotIsOpen == 0} { return }
   .bufhot.win delete 1.0 end
   set names "[array names BufferStoT]"
   foreach i "$names" {
      .bufhot.win insert end "$i\n"
   }
}

proc StoreAttributes {name} {
   global AWin XPrefCPAttrYN
   if {$XPrefCPAttrYN < 1} {return}
   StoreAttributes_ $name $AWin
}

proc RecallAttributes {name} {
   global SplitOnYN XPrefCPAttrYN
   if {$XPrefCPAttrYN < 1} {return}
   RecallAttributes_ $name .text
   if {$SplitOnYN == 1} {
      RecallAttributes_ $name .textv
   }
}

proc StoreAttributes_ {name buf} {
   global Attributes

   set namelist [$buf tag names]
   set Attributes($name) "$namelist"
   foreach j "$namelist" {
      set i 1.0
      set x ""
      while { 1 == 1} {
         set n [$buf tag nextrange $j $i]
         if {$n == ""} {break}
         set k [lindex $n 0]
         set i [lindex $n 1]
         set x "$x $k $i"
      }
      set Attributes($name,$j) "$x"
   }
}

proc RecallAttributes_ {name buf} {
   global Attributes tk_version

   if {[catch {set namelist "$Attributes($name)"}]} {return}
   foreach j "$namelist" {
      set x "$Attributes($name,$j)"
      if {$tk_version >= 4.0} {
         if {$x != ""} {eval "$buf tag add $j $x"}
      } else {
         set n [llength $x]
         set s 0
         set e 1
         while {1 == 1} {
            if {$x != ""} {eval "$buf tag add $j [lrange $x $s $e]"}
            incr s 2
            incr e 2
            if {$e > $n} break
         }
      }
   }
}

proc GetFileType { } {
   global FileTypes FileType ThisFileName AWin
   
   catch {if {$FileType != "Unknown"} return}
   set x [file extension $ThisFileName]
   if {[info exists FileTypes($x)]} {
      set FileType $FileTypes($x)
   } else {
      if {[$AWin get 1.0 1.2] == "#!"} {
         set x [$AWin get 1.0 "1.0 lineend"]
         if {[string first "perl" $x] >= 0} {set FileType "PERL" ; return}
         if {[string first "/bin/sh" $x] >= 0} {set FileType "SHELL" ; return}
         if {[string first "ksh" $x] >= 0} {set FileType "SHELL" ; return}
         if {[string first "wish" $x] >= 0} {set FileType "TCL" ; return}
         if {[string first "csh" $x] >= 0} {set FileType "CSH" ; return}
         set FileType "TCL"
      }
   }
}

proc LaunchFileSelect { } {
   global TempName UseSend MyAdress
   
   eval "exec FileSelect 2>/dev/null >/dev/null \
          -cmd1 \"Add to tkedit\" \"send $MyAdress loadFile %\" \
          -cmd2 \"New tkedit\" \"exec tkedit % \&\" &"
}

proc loadFile file {
   global AWin LWin ModifyStatus AutoSaveStatus ProtectYN ThisFileName \
          SaveFirstTime NumBytes HiddenBytes Usage FileType \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU BufferStoV  \
          BufferStoF BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
          BufferSto5 BufferSto6 BufferSto7 BufferSto8 \
          BufferStoRet BufferStoTab BufferStoSpc BufferStoView BufferStoH\
          ExtReturnCMD ExtTabCMD ExtSpaceCMD TempName

   ChangeBuffer ""
   set ProtectYN 0

   set flg 0
   if {[string first ":" $file] > 1} {
      eval "exec rcp $file $TempName"
      set flg 1
      set merk "$file"
      set file "$TempName"
   }
   if {[file exists "$file~"]} {
      set erg [tk_dialog .err "Notice" "Backup File exists" warning -1 \
               "Load $file" "Load Backup"]
      if {$erg == 1} {set file "$file~"}
   }
   if {[file exists $file]} {
      if {![file writable $file]} {set ProtectYN 1}
      set f [open $file]
      while {![eof $f]} {
         .text insert end [read $f 8192]
      }
      close $f
   }
   if $flg {
      exec rm -f $TempName
      set file $merk
   }
   set x ".mBar.buffer.m add command -label $file "
   set x "$x -command {ChangeBuffer $file}"
   uplevel $x
   set ThisFileName $file
   set ModifyStatus 0; set AutoSaveStatus 0 ; set SaveFirstTime 1
   set HiddenBytes 0
   DoService 1
   set BufferStoT($file) " "
   set BufferStoM($file) $ModifyStatus
   set BufferStoH($file) $HiddenBytes
   set BufferStoS($file) $AutoSaveStatus
   set BufferStoP($file) 1.0
   set BufferStoV($file) 1.0
   set BufferStoU($file) "File"
   set BufferStoF($file) "Unknown"
   set BufferSto1($file) 1.0
   set BufferSto2($file) 1.0
   set BufferSto3($file) 1.0
   set BufferSto4($file) 1.0
   set BufferSto5($file) 1.0
   set BufferSto6($file) 1.0
   set BufferSto7($file) 1.0
   set BufferSto8($file) 1.0
   set BufferStoRet($file) "InsertReturn"
   set BufferStoTab($file) "InsertTab"
   set BufferStoSpc($file) "InsertSpace"
   set BufferStoView($file) $ProtectYN
   set ExtReturnCMD "InsertReturn"
   set ExtTabCMD "InsertTab"
   set ExtSpaceCMD "InsertSpace"
   set DelayedCMD "NoAction"
   set Usage "File"
   set FileType "Unknown"
   TopOfFile
   CopyText .text .textv
   BufUpdateHotlist
   GetFileType
}

proc CheckFile file {
   global BufferStoT
   return [info exists BufferStoT($file)]
}
proc LoadAFile { } {
   global ThisFileName FileSelect
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] > 0} {
      if {[CheckFile $fnam]} {
         set erg [tk_dialog .err "tkedit error" "Allready Loaded" warning -1 \
         OVERWRITE CANCEL]
         if {$erg == 0} {
            ChangeBuffer $fnam ; CloseThis
         } else {return}
      }
      loadFile $fnam
   }
}

proc DoChmod { } {
   global ThisFileName ProtectYN
   
   if {!$ProtectYN} {
      if {![file writable $ThisFileName]} {exec chmod +w $ThisFileName}
   }
}

proc SaveTo_ {fnam} {
   global AWin LWin TempName Text_To_Save SaveFunctions

   SyncText

   set flg 0
   if {[string first ":" "$fnam"] > 1} {
      set merk $fnam
      set fnam "$TempName"
      set flg 1
   }

   set f [open $fnam w]
   set Text_To_Save [$AWin get 1.0 end]
   scan [$AWin index end] %d numLines
   eval $SaveFunctions
   puts -nonewline $f $Text_To_Save
   close $f
   
   if $flg {
      eval "exec rcp $TempName $merk"
      exec rm -f $TempName
   }
}

proc SaveTo fnam {
   global ThisFileName ModifyStatus AutoSaveStatus AutoSaveYN Usage
   SaveTo_ $fnam
   set ModifyStatus 0; set AutoSaveStatus 0
   set Usage "File"
   DoService 1
   if {$AutoSaveYN} {
      exec rm -f "${ThisFileName}~"
   }      
}

proc SaveThis { } {
   global ThisFileName ProtectYN AutoBackupYN SaveFirstTime FileSelect
   if {$ProtectYN} {
      tk_dialog .err "tkedit error" "View Only" warning -1 OK
      return
   }
   if {$ThisFileName == "NewBuffer"} {
      set ThisFileName [eval "exec $FileSelect"]
   }
   if {$AutoBackupYN && $SaveFirstTime} {
      set SaveFirstTime 0
      catch {exec cp $ThisFileName $ThisFileName.tkbak}
   }
   SaveTo $ThisFileName
   DoService 1
}

proc SaveAs { } {
   global ThisFileName FileSelect
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] > 0} {
      SaveTo $fnam
   }
}

proc AutoSave {ms} {
   global ThisFileName ProtectYN AutoSaveYN AutoSaveStatus AutoSaveCnt Usage
   if {$ProtectYN} return
   if {$Usage != "File"} return
   if {$AutoSaveYN && $AutoSaveStatus} {
      set AutoSaveCnt [expr $AutoSaveCnt + $ms]
      if {$AutoSaveCnt < 60000} return
      set AutoSaveCnt 0
      if {![catch {SaveTo_ "${ThisFileName}~"}]} { set AutoSaveStatus 0 }
   }     
}


proc SavePrefs { } {
   global FontSize FontName BackgroundRGB ForegroundRGB \
          SearchCaseYN SearchPatternYN AutoIndentYN AutoSaveYN MacF \
          TabDistance AutoBackupYN AutoNewLine EnaSplitYN DimFocusOutYN
          
   set cwd [pwd] ; cd
   set f [open ".tkedit" w]
   puts $f "SetFont $FontName"
   puts $f "NewFontSize $FontSize"
   puts $f "set EnaSplitYN $EnaSplitYN"
   puts $f "set DimFocusOutYN $DimFocusOutYN"
   puts $f "set SearchCaseYN $SearchCaseYN"
   puts $f "set SearchPatternYN $SearchPatternYN"
   puts $f "set AutoIndentYN $AutoIndentYN"
   puts $f "set AutoSaveYN $AutoSaveYN"
   puts $f "set AutoBackupYN $AutoBackupYN"
   puts $f "set TabDistance $TabDistance"
   puts $f "set AutoNewLine $AutoNewLine"
   for {set i 1} {$i <= 60} {incr i} {
      if {"$MacF($i)" != ""} {
         puts $f "set MacF($i) \"$MacF($i)\""
      }
   }
   if {$BackgroundRGB != -1} {puts $f "SetRGB_bg $BackgroundRGB"}
   if {$ForegroundRGB != -1} {puts $f "SetRGB_fg $ForegroundRGB"}
   puts $f "SetWinGeom [GetWinWidth] [GetWinHeight]"
   foreach Var  [info globals "XPref*"] {
      upvar #0 $Var tmp
      puts $f "set $Var \"$tmp\""
   }
   close $f
   cd $cwd
}

proc ReadConfig { } {
   global CWD
   
   set f [file tail [info script]]
   if {$f != "tke"} {
      set x $CWD
      uplevel ReadConfig2
      set CWD $x
   } else {
      .mBar.file.m add command -label "Exec Startup" \
             -command {DoCmd "^YReadConfig2"}
   }
   cd $CWD
}

proc ReadConfig2 { } {
   global CWD Version
   
   set CWD [pwd] ; cd
   set f [file tail [info script]]
   if {$f == "tke"} {
      .mBar.file.m delete "Exec Startup"
   }
   if {[file exists ".tkeditrc"]} {
      uplevel {source ".tkeditrc"}
   }
   if {[file isdirectory "tkedit_macros"] == 0} {DoUpdate}
   if {[file isdirectory "tkedit_macros"]} {
      cd "tkedit_macros"
      if {[file exists $Version] == 0} { DoUpdate }
      set allfiles ""
      catch {set allfiles [glob *.startup]}
      foreach i $allfiles {
         set x "uplevel \{source $i\}"
         if {[file exists $i]} {
            eval $x
         }
      }
   }
   cd $CWD
}

proc DoUpdate { } {
   global CWD env Version

   set tmp [pwd]
   cd $CWD
   regsub -all "\:" $env(PATH) " " s
   set l [llength $s]
   for {set i 0} {$i < $l} {incr i} {
      set f "[lindex $s $i]/tkedit_storage/update.tcl"
      if {[file exists $f] != 0} {
         source $f
         break
      }
   }
   cd $tmp
}

proc DoCheckSend { } {
   global CWD env Version
   
   regsub -all "\:" $env(PATH) " " s
   set l [llength $s]
   for {set i 0} {$i < $l} {incr i} {
      set f "[lindex $s $i]/tkedit_storage/CheckSend.tcl"
      if {[file exists $f] != 0} {
         catch {eval "exec wish -f $f &"}
         break
      }
   }
}

proc LaunchBuffer { } {
   global AWin ThisFileName MyAdress

   SaveThis
   eval "exec tkedit $ThisFileName -exit \
      \"send $MyAdress loadFile $ThisFileName\" &"
   CloseThis
}

proc OpenNew { } {
   global FileSelect
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] > 0} {
      exec tkedit $fnam &
   }
}
proc IncludeFile file {
   global  AWin LWin
   
	set f [open $file r]
	while {![eof $f]} {
		InsertText [read $f 1000]
	}
	close $f
        $AWin yview -pickplace insert
}
proc IncludeAFile { } {
   global FileSelect
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] > 0} {IncludeFile $fnam}
}
proc IncludeAColumn { } {
   global FileSelect
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] > 0} {
      set buf \x11\n
      set f [open $fnam r]
      while {![eof $f]} {
         set buf "$buf[read $f 1000]"
      }
      ToPaste "$buf"
      PasteFromClip
   }
}

proc ToPaste text {
   global env
   set f [open $env(HOME)/.pastebuffer w]
   puts -nonewline $f "$text"
   close $f
}

proc FromPaste { } {
   global env
   set x ""
   set f [open $env(HOME)/.pastebuffer]
   while {![eof $f]} {
      set x "$x[read $f 1000]"
   }   
   close $f
   return $x
}

proc StoreXSelect { } {
   global LastXSelect
   
   set t ""
   catch {set t [selection get TARGETS]}
   if {[lsearch $t STRING] >= 0} {
      catch {set LastXSelect [selection get STRING]}
   }   
}

proc GetXSelect { } {
   global LastXSelect
   
   if {[catch {set s [selection get STRING]}]} {
      set s $LastXSelect
   }
   return "$s"
}

proc XSelectToMark { } {
   global AWin
   
   set t ""
   set s ""
   catch {set t [selection get TARGETS]}
   if {[lsearch $t STRING] >= 0} {
      catch {$AWin mark set pastebeg sel.first}
      catch {$AWin mark set pasteend sel.last}
      return 1
   }
   return 0
}

proc SaveClip { } {
   global  MarkActive FileSelect
   
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] > 0} {
   
      set f [open $fnam w]
      set t ""
      catch {set t [selection get TARGETS]}
      if {[lsearch $t STRING] >= 0} {
         puts $f [GetXSelect]
      } else {
         set buf "[FromPaste]"
         if {[string index $buf 0] == "\x11"} {
            set buf [string range "$buf" 2 end]
         }
         puts $f "$buf"
      }
      close $f
   }
}

proc EvalClip { } {
   global  MarkActive
   
      set t ""
      catch {set t [selection get TARGETS]}
      if {[lsearch $t STRING] >= 0} {
         set cmd "[GetXSelect]"
      } else {
         set cmd "[FromPaste]"
      }
      uplevel $cmd
}

proc CVTBS { } {
   global AWin LWin
   
   SyncText
   set oldins [$AWin index insert]
   regsub -all ".\x08" "[$AWin get 1.0 end]" "" s
   DeleteTextAt "1.0" end
   InsertTextAt "1.0" "$s"
   $AWin mark set insert "$oldins"
   $AWin yview -pickplace insert   
}

proc CVTTabs { } {
   global AWin LWin TabDistance SearchString Result Cancel
   
   SyncText
   set oldins [$AWin index insert]
   set oldsearch $SearchString
   set oldtab $TabDistance

   set SearchString "\x09"
   set TabDistance 8
   $AWin mark set insert 1.0
   
   set Cancel 0
   while {1} {
      SearchNext
      if {!$Result} break
      if {$Cancel} break
      delete
      DoTab
   }

   set SearchString $oldsearch
   set TabDistance $oldtab
   $AWin mark set insert "$oldins"
   $AWin yview -pickplace insert   
}

proc CrLf2Lf { } {
   global AWin LWin
   scan [$AWin index end] %d numLines
   for {set i 1} {$i < $numLines} {incr i} {
      set s [$AWin get $i.0 "$i.0 lineend"]
      regsub -all \x0d $s "" z
      regsub -all \x84 $z \xe4 s
      regsub -all \x94 $s \xf6 z
      regsub -all \x81 $z \xfc s
      regsub -all \x98 $s \xc4 z
      regsub -all \x9e $z \xd6 s
      regsub -all \x9f $s \xdc z
      regsub -all \xfe $z \xdf s
      DeleteTextAt "$i.0" "$i.0 lineend"
      InsertTextAt "$i.0" "$s"
   }
}
proc Cr2Lf { } {
   global AWin LWin Cancel
   set Cancel 0
   $AWin mark set tmp insert
   $AWin mark set insert 1.0
   while {0 == 0} {
      $AWin mark set  $d
      if {[$AWin compare insert == end]} break
      if {$Cancel} break
      set x [$AWin get insert]
      if {$x == \x0d} {update; DeleteCharAt insert ; InsertText "\n"}
   }
   $AWin mark set insert tmp
}
proc SaveCrLf { } {
   global AWin LWin FileSelect

   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] == 0} return
   set f [open $fnam w]
   scan [$AWin index end] %d numLines
   for {set i 1} {$i < $numLines} {incr i} {
      set z [$AWin get $i.0 "$i.0 lineend"]
      regsub -all \xe4 $z \x84 s
      regsub -all \xf6 $s \x94 z
      regsub -all \xfc $z \x81 s
      regsub -all \xc4 $s \x98 z
      regsub -all \xd6 $z \x9e s
      regsub -all \xdc $s \x9f z
      regsub -all \xdf $z \xfe s
      puts $f "${s}\x0d"
   }
   close $f
}
proc SaveCr { } {
   global AWin LWin FileSelect
   set fnam [eval "exec $FileSelect"]
   if {[string length $fnam] == 0} return
   set f [open $fnam w]
   scan [$AWin index end] %d numLines
   for {set i 1} {$i < $numLines} {incr i} {
      set s [$AWin get $i.0 "$i.0 lineend"]
      puts -nonewline $f "${s}\x0d"
   }
   close $f
}

proc CheckAndQuit { } {
   global ModifyStatus AutoSaveStatus ProtectYN ThisFileName Usage\
       SaveFirstTime NumBytes XPrefAutoSavePrefs \
       BufferStoT BufferStoM BufferStoS BufferStoP

   set flag 0
   if {$Usage == "File"} {set flag $ModifyStatus}
   foreach i [array names BufferStoM] {
      if {$Usage == "File"} { set flag [expr $flag + $BufferStoM($i)]}
   }
   if {$flag == 0} {
      PrepareExit ; exit
   } else {
      set erg [tk_dialog .err "tkedit error" "File Not Saved" warning -1 \
                CONTINUE QUIT]
      if {$erg == 1} {PrepareExit ; exit}
   }
}

proc CheckAndClose { } {
   global ModifyStatus ThisFileName Usage

   if {$Usage == "More"} {CloseThis; return}
   if {$Usage == "Shell"} {CloseThis; return}
   if {$Usage == "All"} {CloseThis; return}
   if {$Usage == "Help"} {CloseThis; return}
   if {$ModifyStatus == 0} {
      CloseThis
   } else {
      set erg [tk_dialog .err "tkedit error" "File Not Saved" warning -1 \
                CONTINUE SAVE+CLOSE CLOSE]
      if {$erg == 2} {CloseThis}
      if {$erg == 1} {SaveThis ; CheckAndClose}
   }
}

proc CloseThis { } {
   global ModifyStatus AutoSaveStatus ProtectYN ThisFileName \
       SaveFirstTime NumBytes HiddenBytes Usage FileType \
       BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU BufferStoV \
       BufferStoF BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
       BufferSto5 BufferSto6 BufferSto7 BufferSto8  \
       BufferStoRet BufferStoTab BufferStoSpc BufferStoView BufferStoH\
       ExtReturnCMD ExtTabCMD ExtSpaceCMD



   unset BufferStoT($ThisFileName)
   unset BufferStoM($ThisFileName)
   unset BufferStoH($ThisFileName)
   unset BufferStoS($ThisFileName)
   unset BufferStoP($ThisFileName)
   unset BufferStoU($ThisFileName)
   unset BufferStoF($ThisFileName)
   unset BufferStoV($ThisFileName)
   unset BufferSto1($ThisFileName)
   unset BufferSto2($ThisFileName)
   unset BufferSto3($ThisFileName)
   unset BufferSto4($ThisFileName)
   unset BufferSto5($ThisFileName)
   unset BufferSto6($ThisFileName)
   unset BufferSto7($ThisFileName)
   unset BufferSto8($ThisFileName)
   unset BufferStoRet($ThisFileName)
   unset BufferStoTab($ThisFileName)
   unset BufferStoSpc($ThisFileName)
   unset BufferStoView($ThisFileName)
   .text delete 1.0 end
   .textv delete 1.0 end
   set NumBytes 0
   set HiddenBytes 0
   .mBar.buffer.m delete $ThisFileName
   BufUpdateHotlist
   set file [lindex [array names BufferStoT] 0]
   if {[string length $file] > 0} {
      ChangeBuffer $file
   } else {
      PrepareExit
      exit
   }
}

proc PrintBuffer { } {
   global AWin PrintCMD
   
   set f [open "| $PrintCMD" w]
   puts $f [$AWin get 1.0 end]
   close $f
}

#
# Procs for complex command execution in Emacs or Xedit style
#

proc ShellExecute { } {
   global AWin ThisFileName ExtReturnCMD OldReturnCMD Usage LastActiveBuffer \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU\
          BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
          BufferSto5 BufferSto6 BufferSto7 BufferSto8
          
   if {$Usage != "Shell"} {set LastActiveBuffer $ThisFileName}
   if {[lsearch [array names BufferStoT] "__Shell_Output"] > 0} {
      RenameBuffer "__Shell_Output" "__Shell_Input"
      ChangeBuffer "__Shell_Input"
      DeleteTextAt "1.0" end
   } else {
      NewBuffer "__Shell_Input"
      set Usage "Shell"
   }
   set ThisFileName "__Shell_Input"
   set OldReturnCMD $ExtReturnCMD
   set ExtReturnCMD "ShellExecuteCMD"
   focus $AWin
}

proc ShellExecuteCMD { } {
   global AWin ExtReturnCMD OldReturnCMD Usage ThisFileName LastActiveBuffer \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU\
          BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
          BufferSto5 BufferSto6 BufferSto7 BufferSto8
          
   set ExtReturnCMD $OldReturnCMD
   
   exec rm -f __cmdout
   set cmd "[string trim [$AWin get 1.0 end]] > __cmdout"
   
   DeleteTextAt "1.0" end
   if {[string index $cmd 0] == "|"} {
      exec rm -f __cmdin
      set f [open "__cmdin" w]
      puts $f $BufferStoT($LastActiveBuffer)
      close $f
      set cmd "cat __cmdin | [string range $cmd 1 end]"
      set err [catch {eval exec $cmd}]
      exec rm -f __cmdin
   } else {
      set err [catch {eval exec $cmd}]
   }
   if {$err} {
      $AWin insert insert "COMMAND >$cmd< RETURNED ERROR"
   } else {
      set f [open "__cmdout" r]
      while {![eof $f]} {
         InsertTextAt end [read $f 1000]
      }
      close $f
   }
   exec rm -f __cmdout
   RenameBuffer "__Shell_Input" "__Shell_Output"
   set ThisFileName "__Shell_Output"
}

proc ShellCopy { } {
   global AWin LastActiveBuffer Usage BufferStoT
   
   if {$Usage != "Shell"} {
      tk_dialog .err "tkedit error" "Not in Shell Buffer" warning -1 OK
      return
   } else {
      ChangeBuffer $LastActiveBuffer
      SyncText
      DeleteTextAt "1.0" end
      InsertText "$BufferStoT(__Shell_Output)"
   }
}

proc ShellClose { } {
   global LastActiveBuffer
   
   ChangeBuffer "__Shell_Output"
   CloseThis
   ChangeBuffer $LastActiveBuffer
}


proc ExtractSearch { } {
   global AWin ThisFileName ExtReturnCMD OldReturnCMD Usage LastActiveBuffer \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU\
          ExtractedLines SearchString Result Cancel

   if {[string length $SearchString] < 1} {
      tk_dialog .err "tkedit error" "Need Search String" warning -1 OK
      return
   }
   if {$Usage != "All"} {set LastActiveBuffer $ThisFileName}
   if {[lsearch [array names BufferStoT] "Extract_Search"] >= 0} {
      ChangeBuffer "Extract_Search"
      DeleteTextAt "1.0" end
   } else {
      NewBuffer "Extract_Search"
      set Usage "AllX"
   }
   ChangeBuffer $LastActiveBuffer
   
   set p [$AWin index insert]
   $AWin mark set insert 1.0
   set Cancel 0
   set n 0
   while {!$Cancel} {
      SearchNext
      if {!$Result} break
      scan  [$AWin index insert] "%d.%d" l dummy
      set ExtractedLines($n) $l
      set txt($n) [$AWin get $l.0 "$l.0 lineend"]
      incr n
      EndOfLine
      DoBusy 5
   }
   $AWin mark set insert $p
   if {$Cancel} {ExtractClose ; return}
   ChangeBuffer "Extract_Search"
   for {set i 0} {$i < $n} {incr i} {$AWin insert insert "$txt($i)\n"}
   $AWin mark set insert 1.0
   set Usage "All"
   set ThisFileName "Extract_Search"
   set OldReturnCMD $ExtReturnCMD
   set ExtReturnCMD "ExtractGoto"
   DoService 1
}


proc ExtractClose { } {
   global LastActiveBuffer
   
   ChangeBuffer "Extract_Search"
   CloseThis
   ChangeBuffer $LastActiveBuffer
}

proc ExtractCopy { } {
   global AWin ThisFileName ExtReturnCMD OldReturnCMD Usage LastActiveBuffer \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU\
          ExtractedLines SearchString Result Cancel
          
   if {$Usage != "All"} {
      tk_dialog .err "tkedit error" "Not in Extract Buffer" warning -1 OK
      return
   } else {
      ChangeBuffer $LastActiveBuffer
      SyncText
      DoService 0
      set ll [array size ExtractedLines]
      for {set n 0} {$n < $ll} {incr n} {
         set i $ExtractedLines($n)
         DeleteTextAt "$i.0" "$i.0 lineend"
         set s "[lindex [split $BufferStoT(Extract_Search) "\n"] $n]"
         if {[string index $s 0] == ""} {
            set j [expr $i + 1]
            DeleteTextAt "$i.0" "$j.0"
            RenumXX "-" 1 ExtractedLines
         } else {
            InsertTextAt $i.0 $s
         }
      }
      DoService 0
   }
}

proc ExtractGoto { } {
   global AWin ThisFileName ExtReturnCMD OldReturnCMD Usage LastActiveBuffer \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU \
          ExtractedLines SearchString Result Cancel

   if {$Usage != "All"} {
      tk_dialog .err "tkedit error" "Not in Extract Buffer" warning -1 OK
      return
   } else {
      scan [$AWin index insert] "%d.%d" l c
      set l [expr $l - 1]
      set l $ExtractedLines($l)
      ChangeBuffer $LastActiveBuffer
      $AWin mark set insert $l.0
      $AWin yview -pickplace insert
   }
}

proc LSEOpenHotWin LSE_HotWin {
   global FontString env AWin XPrefHotBgRGB XPrefHotFgRGB
   
   catch {destroy $LSE_HotWin}
   toplevel $LSE_HotWin -class Dialog
   frame $LSE_HotWin.top -relief raised -bd 1
   pack $LSE_HotWin.top -side top -expand 1 -fill both
   frame $LSE_HotWin.bot -relief raised -bd 1
   pack $LSE_HotWin.bot -side bottom
   text $LSE_HotWin.win -width 20 -height 20 -font $FontString \
         -background $XPrefHotBgRGB -foreground $XPrefHotFgRGB \
         -yscrollcommand "$LSE_HotWin.scroll set" -wrap none  -setgrid 1
   pack $LSE_HotWin.win -in $LSE_HotWin.top -side left -expand 1 -fill both
   scrollbar $LSE_HotWin.scroll -command "$LSE_HotWin.win yview"
   pack $LSE_HotWin.scroll -in $LSE_HotWin.top -side right -fill y
   set cmd \
"button $LSE_HotWin.quit -text Dismiss -width 10 -command {destroy $LSE_HotWin}"
   eval $cmd
   pack $LSE_HotWin.quit -in $LSE_HotWin.bot -side left
   wm maxsize $LSE_HotWin 100 100
   wm minsize $LSE_HotWin 10 2
   bind $LSE_HotWin.win <1> {
      global AWin LSELines

       %W mark set insert @%x,%y
      set t [string range %W 8 12]
      set f [string range %W 14 end]
      set l [expr [string length $f] - 5]
      regsub -all "\[\*\]" [string range $f 0 $l] "." f
#       scan [%W index insert] "%d.%d" l c
       set l [file rootname [%W index insert]]
       ChangeBuffer $f
       catch {$AWin mark set insert [lindex $LSELines($t,$f) [expr $l - 1]].0}
       $AWin yview -pickplace insert
   }
   bind $LSE_HotWin.win <B1-Motion> { }
   bind $LSE_HotWin.win <2> { }
   bind $LSE_HotWin.win <3> { }
   bind $LSE_HotWin.win <Double-1> { }
   bind $LSE_HotWin.win <Triple-1> { }
}

proc LSEClose { } {
   global LSEFrom
   
   ChangeBuffer "LSE"
   CloseThis
   ChangeBuffer $LSEFrom
}

proc LSECopy { } {
   global AWin ThisFileName ExtReturnCMD OldReturnCMD Usage \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU\
          LSELines SearchString Result Cancel HiddenBytes LSEFrom LSEwhat
          
   if {$Usage != "LSE"} {
      tk_dialog .err "tkedit error" "Not in LSE Buffer" warning -1 OK
      return
   } else {
      ChangeBuffer $LSEFrom
      if {$HiddenBytes != 0} {LSE_Expand_All}
      SyncText
      DoService 0
      set ll [llength $LSELines($LSEwhat,$ThisFileName)]
      for {set n 0} {$n < $ll} {incr n} {
         set i [lindex $LSELines($LSEwhat,$ThisFileName) $n]
         DeleteTextAt "$i.0" "$i.0 lineend"
         InsertTextAt "$i.0" [lindex [split $BufferStoT(LSE) "\n"] $n]
      }
      DoService 0
   }
}

proc LSEGoto { } {
   global AWin ThisFileName ExtReturnCMD OldReturnCMD Usage \
          BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU\
          LSELines SearchString Result Cancel LSEFrom LSEwhat

   if {$Usage != "LSE"} {
      tk_dialog .err "tkedit error" "Not in LSE Buffer" warning -1 OK
      return
   } else {
      scan [$AWin index insert] "%d.%d" l c
      set l [lindex $LSELines($LSEwhat,$LSEFrom) [expr $l - 1]]
      ChangeBuffer $LSEFrom
      $AWin mark set insert $l.0
      $AWin yview -pickplace insert
   }
}

proc RenumX {op nl} {
   global AWin ThisFileName ExtractedLines LSELines
          
   RenumXX $op $nl ExtractedLines
   RenumXY $op $nl LSELines
}

proc RenumXX {op nl array} {
   upvar $array a
   global AWin

   if {[catch {set m [array size a]}]} return
      scan [$AWin index insert] "%d.%d" l c
      if {"$op" == "+"} {set l [expr $l - $nl]}
      for {set i 0} {$i < $m} {incr i} {
         if {$a($i) > $l} {
            set a($i) [expr $a($i) $op $nl]
         }
      }
}

proc RenumXY {op nl array} {
   upvar $array a
   global AWin ThisFileName

   if {[catch {set anames [array names a]}]} {return}

   scan [$AWin index insert] "%d.%d" l c
   if {"$op" == "+"} {set l [expr $l - $nl]}
   foreach j $anames {
      set lines "$a($j)"
      set erg ""
      foreach i $lines {
         if {$i >= $l} {
            set erg "$erg [expr $i $op $nl]"
         } else {
            set erg "$erg $i"
         }
      }
      set a($j) "$erg"
   }
}

proc MakeHotList { } {
   global ExtHotListCMD FileType
   if {$FileType == "Unknown"} {
      tk_dialog .err "Notice" \
         "FileType is Unknown\nPlease set language manually" \
         warning -1 "OK"
      return
   }
   if {[info exists ExtHotListCMD($FileType)]} {eval $ExtHotListCMD($FileType)}
}

proc GotoDeclar { } {
   global ExtGotoCMD FileType
   if {$FileType == "Unknown"} {
      tk_dialog .err "Notice" \
         "FileType is Unknown\nPlease set language manually" \
         warning -1 "OK"
      return
   }
   if {[info exists ExtGotoCMD($FileType)]} {eval $ExtGotoCMD($FileType)}
}
#
# Cursor Movement
#
proc NextChar { } {
   global AWin LWin
   $AWin mark set insert "insert + 1 chars"
   $AWin yview -pickplace insert
   DoService 0
}
proc PrevChar { } {
   global AWin LWin
   $AWin mark set insert "insert - 1 chars"
   $AWin yview -pickplace insert
   DoService 0
}

proc EndOfWord { } {
   global AWin LWin
   
   set end [$AWin index end]
   while {[$AWin get insert] <= " "} {
      if {[$AWin index insert] == $end} break
      $AWin mark set insert "insert + 1 chars"
   }
   
   $AWin mark set insert "insert wordend"
   $AWin yview -pickplace insert
   DoService 0
}
proc BeginOfWord { } {
   global AWin LWin

   $AWin mark set insert "insert - 1 chars"
   while {[$AWin get insert] <= " "} {
      if {[$AWin index insert] == 1.0} break
      $AWin mark set insert "insert - 1 chars"
   }
   $AWin mark set insert "insert wordstart"
   $AWin yview -pickplace insert
   DoService 0
}
proc EndOfLine { } {
   global AWin LWin

   $AWin mark set insert "insert lineend"
   $AWin yview -pickplace insert   
   DoService 0
}
proc BeginOfLine { } {
   global AWin LWin

   $AWin mark set insert "insert linestart"
   $AWin yview -pickplace insert   
   DoService 0
}

proc NextLine { } {
   global AWin LWin
   $AWin mark set insert "insert + 1 line"
   $AWin yview -pickplace insert
   DoService 0
}
proc PrevLine { } {
   global AWin LWin
   $AWin mark set insert "insert - 1 line"
   $AWin yview -pickplace insert
   DoService 0
}
proc NextScreen { } {
   global AWin LWin
   set height [GetWinHeight]
   set p [$AWin index insert]
   set np [expr $p + ${height}.0]
   $AWin mark set insert "$np"
   $AWin yview -pickplace insert
   DoService 0
}
proc PrevScreen { } {
   global AWin LWin
   set height [GetWinHeight]
   set p [$AWin index insert]
   set np [expr $p - ${height}.0]
   $AWin mark set insert "$np"
   $AWin yview -pickplace insert
   DoService 0
}

proc TopOfFile { } {
   global AWin LWin
   $AWin mark set last1 insert
   $AWin mark set insert "1.0"
   $AWin yview -pickplace insert
   DoService 0
}
proc BottomOfFile { } {
   global AWin LWin
   $AWin mark set last1 insert
   $AWin mark set insert end
   $AWin yview -pickplace insert
   DoService 0
}
proc MarkPos n {
   global AWin LWin
   $AWin mark set markpos$n insert
}
proc GotoPos n {
   global AWin LWin
   $AWin mark set last2 last1
   $AWin mark set last1 insert
   switch $n {
      5 {$AWin mark set insert pastebeg}
      6 {$AWin mark set insert pasteend}
      9 {$AWin mark set insert found1}
      0 {$AWin mark set insert last2}
      default {$AWin mark set insert markpos$n}
   }
   $AWin yview -pickplace insert
}

proc DoReturn { } {
   global AWin LWin AutoIndentYN ExtReturnCMD ExtReturn FileType
   
   eval $ExtReturnCMD
   if {[info exists ExtReturn($FileType)]} {eval $ExtReturn($FileType)}
}

proc InsertReturn { } {
   global AWin LWin AutoIndentYN ExtReturnCMD
   
   InsertText "\n"
   GetLineNumber
   if {$AutoIndentYN} {DoIndent}
   $AWin yview -pickplace insert
   RenumX "+" 1
   SyncText
}

proc DoTab { } {
   global AWin LWin TabDistance ExtTabCMD ExtTab FileType
   
   eval $ExtTabCMD
   if {[info exists ExtTab($FileType)]} {eval $ExtTab($FileType)}
}

proc InsertTab { } {
   global  AWin LWin TabDistance
   scan [$AWin index insert] %d.%d l c
   switch $TabDistance {
      0 {InsertText "\x09"}
      default {
         set c [expr $c % $TabDistance]
         set t ""
         for {set i $c} {$i < $TabDistance} {incr i} {
            set t "$t "
         }
         InsertText "$t"
      }
   }
}

proc BackTab { } {
   global  AWin LWin TabDistance
   scan [$AWin index insert] %d.%d l c
   switch $TabDistance {
      0 {backspace}
      default {
         set c [expr $c % $TabDistance]
         if {$c == 0} {set c $TabDistance}
         for {set i 0} {$i < $c} {incr i} { backspace }
      }
   }
}

proc StrLen str {
   regsub -all "\x09" "$str" "        " x
   return [string length "$x"]
}

proc DoSpace { } {
   global AWin LWin AutoNewLine AutoIndentYN ExtSpaceCMD DoAfterCMD \
          DoBeforeCMD ExtSpace FileType ExtAfter
   
   eval $DoBeforeCMD
   eval $ExtSpaceCMD
   if {[info exists ExtSpace($FileType)]} {eval $ExtSpace($FileType)}
   eval $DoAfterCMD
}

proc InsertSpace { } {
   global  AWin LWin AutoNewLine AutoIndentYN
   InsertText " "
   if {$AutoNewLine > 0} {
      scan [$AWin index insert] %d.%d l c
      if {$c > $AutoNewLine} {
         set x [$AWin get "insert linestart" "insert - 1 char"]
         set c [string last " " "$x"]
         $AWin mark set tmp "insert linestart + $c char"
         DeleteCharAt tmp
         InsertTextAt tmp "\n"
         GetLineNumber
         if {$AutoIndentYN} {
    if {[regexp -indices "\[^\x20\x09\]" [$AWin get $l.0 "$l.0 lineend"] c]} {
            set x [lindex $c 0]
            set s [$AWin get $l.0 $l.$x]
            }
            InsertTextAt tmp "$s"
         }
         $AWin yview -pickplace insert
         RenumX "+" 1
         SyncText
         if {$AutoNewLine == 72} {
            incr l
            InsertTextAt $l.5 "+"
         }
      }
   }
   $AWin yview -pickplace insert
}
#
# Procs for the EDIT Menu
#
proc backspace {} {
    global  AWin LWin XPrefXKillOnBS
    if {$XPrefXKillOnBS} {
      if {[DelSelect]} return
    }
    scan [$AWin index insert] "%d.%d" l c
    DeleteTextAt "insert - 1 chars" insert
    $AWin yview -pickplace insert
    GetLineNumber
    if {$c == 0} {RenumX "-" 1}
}
proc delete {} {
    global  AWin LWin XPrefXKillOnBS
    if {$XPrefXKillOnBS} {
      if {[DelSelect]} return
    }
    DeleteCharAt insert
    $AWin yview -pickplace insert
    GetLineNumber
}
proc MarkBegin { } {
    global AWin LWin  MarkActive
    ClearMarks
    $AWin mark set pastebeg insert
    $AWin tag add paste pastebeg insert
    set MarkActive 1
}

proc MarkColumnar { } {
    global AWin LWin  MarkActive
    ClearMarks
    $AWin mark set pastebeg insert
    $AWin tag add paste pastebeg insert
    set MarkActive 2
}

proc MarkEnd { } {
    global AWin LWin  MarkActive XPrefPasteRGB
    
    switch $MarkActive {
    0 {CopyToClip}
    1 {
         $AWin mark set pasteend insert
         $AWin tag delete paste
         $AWin tag add paste pastebeg pasteend
         $AWin tag configure paste -background $XPrefPasteRGB
         ToPaste "[$AWin get pastebeg pasteend]"
      }
    2 {
         set buf \x11\n
         scan [$AWin index pastebeg] "%d.%d" l1 c1
         scan [$AWin index insert] "%d.%d" l2 c2
         $AWin tag delete paste
         for {set l $l1} {$l <= $l2} {incr l} {
            set s "[$AWin get $l.$c1 $l.$c2]"
            if {[string last "\n" $s] < 0} {
               set s "$s\n"
            }
            set buf "$buf$s"
         }
         ToPaste "$buf"
      }
    }
    set MarkActive 0
}
proc CopyToClip { } {
   global 1
   set t ""
   catch {set t [selection get TARGETS]}
   if {[lsearch $t STRING] >= 0} {
      ToPaste [GetXSelect]
   }
}
proc CutToClip { } {
   global AWin LWin MarkActive
   SyncText
   scan [$AWin index insert] %d lastl
   switch $MarkActive {
    0 {
         set t ""
         catch {set t [selection get TARGETS]}
         if {[lsearch $t STRING] >= 0} {
            ToPaste [GetXSelect]
            DelSelect
         }
      }
    1 {
         $AWin mark set pasteend insert
         $AWin tag add paste pastebeg pasteend
         ToPaste "[$AWin get pastebeg pasteend]"
         DeleteTextAt pastebeg pasteend
      }
    2 {
         set buf \x11\n
         scan [$AWin index pastebeg] "%d.%d" l1 c1
         scan [$AWin index insert] "%d.%d" l2 c2
         $AWin tag delete paste
         for {set l $l1} {$l <= $l2} {incr l} {
            set s "[$AWin get $l.$c1 $l.$c2]"
            if {[string last "\n" $s] < 0} {
               set s "$s\n"
               DeleteTextAt "$l.$c1" "$l.$c2"
            } else {
               DeleteTextAt "$l.$c1" "$l.[expr $c1 + [string length $s] - 1]"
            }
            set buf "$buf$s"
         }
         ToPaste "$buf"
      }
   }
   set MarkActive 0
   scan [$AWin index insert] %d l
   set x [expr $lastl - $l]
   RenumX "-" $x
}

proc PasteFromClip { } {
   global AWin LWin MarkActive

   SyncText
   scan [$AWin index insert] %d lastl
   set t ""
   catch {set t [selection get TARGETS]}
   if {[lsearch $t STRING] >= 0} {
      InsertText [GetXSelect]
   } else {
      set buf "[FromPaste]"
      if {[string index $buf 0] == "\x11"} {
         scan [$AWin index insert] "%d.%d" l1 c1
         scan [$AWin index end] "%d.%d" ll lc
         set bl [string length $buf]
         set i 2
         while {1} {
            set n $i
            while {1} {
               set s "[string index "$buf" $n]"
               if {$s == "\n"} break
               incr n
               if {$n > $bl} break
            }
            if {$n > $bl} break
            set n [expr $n - 1]
            set s [string range "$buf" $i $n]
            set sl [string length [$AWin get $l1.0 "$l1.0 lineend"]]
            while {$sl < $c1} {InsertTextAt "$l1.$sl" " "; incr sl}
            InsertTextAt "$l1.$c1" "$s"
            incr n ; incr n
            set i $n
            incr l1
            if {$l1 > $ll} {InsertTextAt end "\n"}
         }
      } else {
         InsertText "$buf"
      }
   }
   $AWin yview -pickplace insert
   scan [$AWin index insert] %d l
   set x [expr $l - $lastl]
   RenumX "+" $x
}
proc StoClip n {
   global  PasteSto
   set PasteSto($n) [FromPaste]
}
proc RclClip n {
   global  PasteSto
   ToPaste "$PasteSto($n)"
}
proc DelToEOW { } {
   global AWin LWin YankBuffer
   SyncText
   
   set  YankBuffer [$AWin get insert "insert wordend"]
   DeleteTextAt "insert" "insert wordend"
}
proc DelWord { } {
   global AWin LWin YankBuffer
   SyncText
   
   set  YankBuffer [$AWin get "insert wordstart" "insert wordend"]
   DeleteTextAt "insert wordstart" "insert wordend"
}
proc DelLine { } {
   global AWin LWin YankBuffer Usage
   
   switch $Usage {
     "All"  {
               scan [$AWin index insert] %d l
               InsertTextAt "$l.0" ""
               NextLine ; BeginOfLine
            }
     "File" {
               SyncText
   set YankBuffer [$AWin get "insert linestart" "insert lineend + 1 char"]
   DeleteTextAt "insert linestart" "insert lineend + 1 char"
               update
               RenumX "-" 1
            }
  "default" {return}
  }
}
proc DelToEOL { } {
   global AWin LWin YankBuffer
   SyncText
   scan [$AWin index insert] %d.%d l c
   set x [string length [$AWin get $l.0 "$l.0 lineend"]]
   set YankBuffer [$AWin get insert $l.$x]
   set c [expr $c + [string length "$YankBuffer"]]
   DeleteTextAt insert "$l.$c"
}
proc DelToBOL { } {
   global AWin LWin YankBuffer
   SyncText
   scan [$AWin index insert] %d l
   set YankBuffer [$AWin get $l.0 insert]
   DeleteTextAt "$l.0" insert
}

proc DelSpace { } {
   global AWin LWin
   
   $AWin mark set tmp insert
   while {[set c [$AWin get tmp]] <= " "} {
      if {$c == "\n"} break
      $AWin mark set tmp "tmp + 1 chars"
   }
   DeleteTextAt insert tmp
}

proc JoinLines { } {
   global AWin LWin 
   BeginOfLine; NextLine ; backspace ; DelSpace
   InsertText " "
   RenumX "-" 1
}

proc DelSelect { } {
   global AWin LWin YankBuffer
   SyncText
   set t ""
   set s ""
   catch {set t [selection get TARGETS]}
   if {[lsearch $t STRING] >= 0} {
      set YankBuffer [$AWin get sel.first sel.last]
      DeleteTextAt "sel.first" "sel.last"
      selection clear $AWin
      set nl [expr [llength [split "$YankBuffer" "\n"]] - 1]
      if {[string first "\n" "$YankBuffer"] >= 0} {RenumX "-" $nl}
      return 1
   }
   return 0
}

proc Capitalize { } {
   global AWin YankBuffer
   
   DelWord
   set YankBuffer [string toupper $YankBuffer]
   InsertText "$YankBuffer"
}
proc LowerCase { } {
   global AWin YankBuffer
   
   DelWord
   set YankBuffer [string tolower $YankBuffer]
   InsertText "$YankBuffer"
}

proc CComment { } {
   global AWin
   
   scan "[$AWin index insert]" "%d.%d" l c
   InsertTextAt "$l.0" "/* "
   set x [string length [$AWin get $l.0 "$l.0 lineend"]]
   InsertTextAt "$l.$x" " */"
}

proc CUncomment { } {
   global AWin SearchString SearchCaseYN SearchPatternYN ReplaceString Result
   
   set ts $SearchString
   set tc $SearchCaseYN
   set tp $SearchPatternYN
   set tr $ReplaceString

   set SearchCaseYN 1
   set SearchPatternYN 0
   set SearchString "*/"
   set ReplaceString ""

   ReplaceNext
   if {[$AWin get "found1 - 1 chars" found1] == " "} {
      DeleteTextAt "found1 - 1 chars" found1
   }  
   
   set SearchString "/*"
   
   SearchPrev
   ReplaceNext
   if {[$AWin get found1 "found1 + 1 chars"] == " "} {
      DeleteTextAt found1 "found1 + 1 chars"
   }

   set SearchString $ts
   set ReplaceString $tr
   set SearchCaseYN $tc
   set SearchPatternYN $tp
}

proc FrameRangeC { } {
   global AWin
   
   SyncText
   XSelectToMark
   set p [$AWin index insert]
   scan [$AWin index pastebeg] %d pbeg 
   scan [$AWin index pasteend] %d pend
   set maxlen 5
   for {set l $pbeg} {$l < $pend} {incr l} {
      set x [StrLen [$AWin get $l.0 "$l.0 lineend"]]
      if {$x > $maxlen} {set maxlen $x} 
   }
   set maxlen [expr $maxlen + 3]
   $AWin mark set insert $pbeg.0
   InsertText "/*"
   set t ""
   for {set i 0} {$i < $maxlen} {incr i} { set t "${t}*" }
   InsertText "${t}\n"
   incr pbeg ; incr pend ;
   for {set l $pbeg} {$l < $pend} {incr l} {
      set x "* [$AWin get $l.0 "$l.0 lineend"]"
      set lx [StrLen $x]
      for {set i $lx} {$i < $maxlen} {incr i} {set x "$x "}
      set x "$x *"
      DeleteTextAt "$l.0" "$l.0 lineend"
      InsertTextAt "$l.0" "$x"
   }
   $AWin mark set insert $pend.0
   set t ""
   for {set i 0} {$i < $maxlen} {incr i} { set t "${t}*" }
   set t "${t}*/"
   InsertText "${t}\n"
   ClearMarks
}

proc FrameRangeTCL { } {
   global AWin
   
   SyncText
   XSelectToMark
   set p [$AWin index insert]
   scan [$AWin index pastebeg] %d pbeg 
   scan [$AWin index pasteend] %d pend
   set maxlen 5
   for {set l $pbeg} {$l < $pend} {incr l} {
      set x [StrLen [$AWin get $l.0 "$l.0 lineend"]]
      if {$x > $maxlen} {set maxlen $x} 
   }
   $AWin mark set insert $pbeg.0
   set maxlen [expr $maxlen + 2]
   set t ""
   for {set i -2} {$i < $maxlen} {incr i} { set t "${t}#" }
   InsertText "${t}\n"
   incr pbeg ; incr pend ;
   for {set l $pbeg} {$l < $pend} {incr l} {
      set x "# [$AWin get $l.0 "$l.0 lineend"]"
      set lx [StrLen $x]
      for {set i $lx} {$i < $maxlen} {incr i} {set x "$x "}
      set x "$x #"
      DeleteTextAt "$l.0" "$l.0 lineend"
      InsertTextAt "$l.0" "$x"
   }
   $AWin mark set insert $pend.0
   set t ""
   for {set i -2} {$i < $maxlen} {incr i} { set t "${t}#" }
   InsertText "${t}\n"
   ClearMarks
}

proc RemoveFrameTCL { } {
   global AWin SearchString SearchCaseYN SearchPatternYN ReplaceString \
          Result EnaSplitYN
   
   SyncText
   
   set ts $SearchString
   set tc $SearchCaseYN
   set tp $SearchPatternYN
   set m $EnaSplitYN

   set EnaSplitYN 0
   set SearchCaseYN 1
   set SearchPatternYN 0
   set SearchString "###"
   SearchPrev
   if {$Result > 0} {
      DelLine
      while {1} {
         BeginOfLine
         set s [$AWin get insert "insert lineend"]
         if {[string index "$s" 0] != "#"} {break}
         set l [string length "$s"]
         set s [string range "$s" 2 [expr $l - 2]]
         if {[string index "$s" 0] == "#"} {
            DelLine
            break
         }
         DeleteTextAt insert "insert lineend"
         InsertText [string trimright $s]
         NextLine
      }
   }
   set SearchString $ts
   set SearchCaseYN $tc
   set SearchPatternYN $tp
   set EnaSplitYN $m
}

proc RemoveFrameC { } {
   global AWin SearchString SearchCaseYN SearchPatternYN ReplaceString \
          Result EnaSplitYN
   
   SyncText
   
   set ts $SearchString
   set tc $SearchCaseYN
   set tp $SearchPatternYN
   set m $EnaSplitYN

   set EnaSplitYN 0
   set SearchCaseYN 1
   set SearchPatternYN 0
   set SearchString "/*"
   SearchPrev
   if {$Result} {
      DelLine
      while {1} {
         BeginOfLine
         set s [$AWin get insert "insert lineend"]
         set l [string length "$s"]
         if {[string index "$s" [expr $l - 1]] == "/"} {
            DelLine
            break
         }
         if {[string index "$s" 0] != "*"} {break}
         set s [string range "$s" 2 [expr $l - 2]]
         DeleteTextAt insert "insert lineend"
         InsertText [string trimright $s]
         NextLine
      }
   }
   set SearchString $ts
   set SearchCaseYN $tc
   set SearchPatternYN $tp
   set EnaSplitYN $m
}


proc DoIndent { } {
   global AWin LWin
   set p [$AWin index insert]
   set np [expr $p - 1.0]
   set s ""
   if {[regexp -indices "\[^\x20\x09\]" [$AWin get $np "$np lineend"] c]} {
      set x [lindex $c 0]
      set s [$AWin get $np "$np + $x char"]
   }
   InsertText "$s"
}
proc YankLine { } {
   global AWin LWin YankBuffer
   SyncText
   InsertText "$YankBuffer"
   update
   if {[string first "\n" "$YankBuffer"] >= 0} {RenumX "+" 1}
}
proc ClearMarks { } {
   global AWin LWin
   $AWin tag delete found paste match
   selection clear $AWin
}
#
# procs for Search / Replace
#
proc AskGotoLine { } {
   global LineNumber ColumnNumber DelayedCMD
   
   set ColumnNumber 0
   focus .linenr
   .linenr delete 0 end
}

proc GotoLine { } {
   global AWin LWin LineNumber ColumnNumber
   $AWin mark set last1 insert
   GotoLC "${LineNumber}.${ColumnNumber}"
   $AWin yview -pickplace insert
   focus $AWin
}

proc GotoLC LC {
   global AWin
   $AWin mark set insert $LC
}

proc GotoByte { } {
   global AWin LWin LineNumber ColumnNumber NumBytes OldBytes
   
   set gb $NumBytes
   set NumBytes $OldBytes
   $AWin mark set insert "1.0 + $gb char"
   $AWin yview -pickplace insert
   focus $AWin
}

proc AskSearchString { } {
   global DelayedCMD
   
   focus .searchstring ; 
   .searchstring delete 0 end
}
proc MarkFound indices {
   global AWin LWin XPrefFoundRGB
  $AWin mark set found1 "last + [lindex $indices 0] chars"
  $AWin mark set found2 "last + [expr [lindex $indices 1] + 1] chars"
  $AWin mark set insert found1
  $AWin tag add found found1 found2
  $AWin tag configure found -background $XPrefFoundRGB
}

proc SearchFirst { } {
   global AWin Result
   
   set opos [$AWin index insert]
   $AWin mark set insert 1.1
   SearchNext
   if {!$Result} {$AWin mark set insert $opos}
   $AWin yview -pickplace insert
}

proc SearchNext { } {
   global AWin LWin SearchString LineNumber SearchCaseYN \
               SearchPatternYN Result
   set Result 0
   if {$SearchCaseYN} {
      set SearchFor $SearchString
   } else {
      set SearchFor "[string tolower "$SearchString"]"
   }
   set xl [string length $SearchFor]
   if {$xl > 0} {set xl [expr $xl - 1]}
   $AWin mark set last "insert + 1 char"
   if {[$AWin index insert] == 1.0} {
      scan [$AWin index found2] %d.%d l c
      set c [expr $c - 1]
      if {($c != $xl) || ($l != 1)} {
         $AWin mark set last 1.0
      }
   }
   $AWin tag delete found
   scan [$AWin index insert] %d.%d line char
   scan [$AWin index end] %d numLines
   if {$SearchCaseYN} {
      set s "[$AWin get last end]"
   } else {
      set s "[string tolower [$AWin get last end]]"
   }
   if {$SearchPatternYN} {
      if {[regexp -indices "$SearchFor" "$s" indices]} {
         MarkFound $indices
         set Result 1
      }
   } else {
      set x [string first "$SearchFor" "$s"]
      if {$x >= 0} {
         MarkFound "$x [expr $x + $xl]"
         set Result 1
      }
   }
   $AWin yview -pickplace insert
   focus $AWin
   GetLineNumber
}


proc SearchPrev { } {
   global AWin LWin SearchString LineNumber SearchCaseYN SearchPatternYN \
          Result
          
   if {$SearchCaseYN} {
      set SearchFor $SearchString
   } else {
      set SearchFor [string tolower "$SearchString"]
   }
   set Result 0
   set xl [string length $SearchFor]
   if {$xl > 0} {set xl [expr $xl - 1]}
   $AWin mark set last1 insert
   $AWin tag delete found
   scan [$AWin index insert] %d.%d line char
   set numLines $line
   for {set i $line} {$i > 0} {set i [expr $i - 1]} {
      $AWin mark set last $i.0
      if {$line == $i} {
         set z [$AWin get last $i.$char]
      } else {
         set z [$AWin get last "last lineend"]
      }
      if {$SearchCaseYN} {
         set s $z
      } else {
         set s "[string tolower $z]"
      }
      if {$SearchPatternYN} {
         if {[regexp -indices $SearchFor $s indices]} {
            set Result 1
            MarkFound $indices ; break
         }
      } else {
         set x [string last $SearchFor $s]
         if {$x >= 0} {
            set Result 1
            MarkFound "$x [expr $x + $xl]" ; break
         }
      }
   }
   $AWin yview -pickplace insert
   focus $AWin
   GetLineNumber
}
proc MatchBracket { } {
   global AWin LWin Cancel
   
   $AWin tag delete match
   set c [$AWin get insert]
   switch $c {
      "("  {MatchBracketFWD "(" ")"}
      "\{" {MatchBracketFWD "\{" "\}"}
      "\[" {MatchBracketFWD "\[" "\]"}
      ")"  {MatchBracketBWD ")" "("}
      "\}" {MatchBracketBWD "\}" "\{"}
      "\]" {MatchBracketBWD "\]" "\["}
   }
}

proc MatchBracketBWD {c y} {
   global AWin LWin Cancel XPrefMatchRGB

   $AWin mark set match2 "insert + 1 char"
   $AWin mark set match1 match2
   set Cancel 0
   set i 1
   while {!$Cancel} {
      set i [string last $y [$AWin get 1.0 "match1 - 1 char"]]
      if {$i <= 0} {set i 1 ; break}
      incr i
      $AWin mark set match1 "1.0 + $i char"
      set s [$AWin get match1 insert]
      set i [string last $c $s]
      if {$i >= 0} {
         $AWin mark set insert "match1 + $i char"
      } else {
         $AWin mark set match1 "match1 - 1 char"
         $AWin mark set insert match2
         $AWin tag add match match1 match2
         $AWin tag configure match -background $XPrefMatchRGB
         $AWin mark set insert match1
         break
      }
      DoBusy 10
   }
   if {($i >= 0) || ($Cancel)} {$AWin mark set insert "match2 - 1 char"}
   $AWin yview -pickplace insert
}

proc MatchBracketFWD {c y} {
   global AWin LWin Cancel XPrefMatchRGB

   $AWin mark set match1 insert
   $AWin mark set match2 "match1 + 1 char"
   $AWin mark set insert match2
   set Cancel 0
   set i 1
   while {!$Cancel} {
      set i [string first $y [$AWin get match2 end]]
      incr i
      if {$i <= 0} {set i 1 ; break}
      $AWin mark set match2 "match2 + $i char"
      set s [$AWin get insert match2]
      set i [string first $c $s]
      if {$i >= 0} {
         incr i
         $AWin mark set insert "insert + $i char"
      } else {
         $AWin mark set insert "match2 - 1 char"
         $AWin tag add match match1 match2
         $AWin tag configure match -background $XPrefMatchRGB
         break
      }
      DoBusy 10
   }
   if {($i >= 0) || ($Cancel)} {$AWin mark set insert match1}
   $AWin yview -pickplace insert
}

proc AskReplaceString { } {
   global DelayedCMD
   
   focus .replacestring ;
   .replacestring delete 0 end
}
proc DoReplace xl {
   global AWin LWin SearchString ReplaceString Result \
          SearchPatternYN SearchCaseYN XPrefFoundRGB

   if {$Result} {
      if {$SearchPatternYN} {
         set s "[$AWin get found1 found2]"
         if {$SearchCaseYN} {
            regsub $SearchString "$s" $ReplaceString z
         } else {
            regsub -nocase $SearchString "$s" $ReplaceString z
         }
         ReplaceTextAt found1 found2 $z
         set xl [string length "$z"]
      } else {
         ReplaceTextAt found1 found2 $ReplaceString
      }
      $AWin mark set found1 "insert - $xl char"
      $AWin mark set found2 insert
      $AWin tag add found found1 found2
      $AWin tag configure found -background $XPrefFoundRGB
   }
}

proc ReplaceNext { } {
   global AWin LWin SearchString ReplaceString Result
   
   SyncText
   set xl [string length $ReplaceString]
   if {[$AWin index insert] != 1.0} {
      PrevChar
      SearchNext
   }
   DoReplace $xl
   $AWin yview -pickplace insert
   focus $AWin
}
proc ReplaceRange { } {
   global AWin LWin SearchString ReplaceString Result Cancel

   SyncText
   XSelectToMark
   set Cancel 0
   set xl [string length $ReplaceString]
   $AWin mark set tmp insert
   $AWin mark set insert pastebeg
   while {1} {
      update
      if {$Cancel} break
      SearchNext
      if {[$AWin compare insert >= pasteend]} break
      DoReplace $xl
      if {!$Result} break
      DoBusy 5
   }
   if {$Cancel} {LimitedUndo}
   $AWin tag delete found
   $AWin mark set insert tmp
   $AWin yview -pickplace insert
   focus $AWin
}

proc ReplaceAll { } {
   global AWin LWin SearchString ReplaceString Result Cancel

   set opos [$AWin index insert]
   $AWin mark set insert 1.0
   ReplaceEnd
   if {(!$Result)|($Cancel)} {$AWin mark set insert $opos}
   $AWin yview -pickplace insert
}
proc ReplaceEnd { } {
   global AWin LWin SearchString ReplaceString Result Cancel 

   SyncText
   set Cancel 0
   set xl [string length $ReplaceString]
   $AWin mark set tmp insert
   focus $AWin
   while {1} {
      if {$Cancel} break
      SearchNext
      DoReplace $xl
      if {!$Result} break
      DoBusy 5
   }
   if {$Cancel} {LimitedUndo}
   $AWin mark set insert tmp
   $AWin yview -pickplace insert
   focus $AWin
}
proc SearchStringUp { } {
   global SearchString SearchStackPtr SearchStack
   set SearchString "[StackGet -1 $SearchString SearchStackPtr SearchStack]"
}
proc SearchStringDown { } {
   global SearchString SearchStackPtr SearchStack
   set SearchString "[StackGet 1 $SearchString SearchStackPtr SearchStack]"
}
proc ReplaceStringUp { } {
   global ReplaceString ReplaceStackPtr ReplaceStack
   set ReplaceString "[StackGet -1 $ReplaceString ReplaceStackPtr ReplaceStack]"
}
proc ReplaceStringDown { } {
   global ReplaceString ReplaceStackPtr ReplaceStack
   set ReplaceString "[StackGet 1 $ReplaceString ReplaceStackPtr ReplaceStack]"
}

proc DoRenameBuffer {OldName NewName} {
   global ThisFileName
   set ThisFileName $OldName
   RenameBuffer $ThisFileName $NewName
}

proc RenameBuffer {OldName NewName} {
   global ThisFileName ModifyStatus AutoSaveStatus SaveFirstTime \
       ProtectYN AWin Usage FileType HiddenBytes\
       BufferStoT BufferStoM BufferStoS BufferStoP BufferStoU BufferStoV \
       BufferStoF BufferSto1 BufferSto2 BufferSto3 BufferSto4 \
       BufferSto5 BufferSto6 BufferSto7 BufferSto8 \
       BufferStoRet BufferStoTab BufferStoSpc BufferStoView BufferStoH\
       ExtReturnCMD ExtTabCMD ExtSpaceCMD DelayedCMD

   if {$OldName == $NewName} return
   foreach i [array names BufferStoT] {
      if {$NewName == $i} {
         ChangeBuffer $i
         update
         CloseThis
         update
         ChangeBuffer $OldName
         update
      }
   }

   unset BufferStoT($OldName)
   unset BufferStoM($OldName)
   unset BufferStoH($OldName)
   unset BufferStoS($OldName)
   unset BufferStoP($OldName)
   unset BufferStoU($OldName)
   unset BufferStoF($OldName)
   unset BufferStoV($OldName)
   unset BufferSto1($OldName)
   unset BufferSto2($OldName)
   unset BufferSto3($OldName)
   unset BufferSto4($OldName)
   unset BufferSto5($OldName)
   unset BufferSto6($OldName)
   unset BufferSto7($OldName)
   unset BufferSto8($OldName)
   unset BufferStoRet($OldName)
   unset BufferStoTab($OldName)
   unset BufferStoSpc($OldName)
   unset BufferStoView($OldName)
   .mBar.buffer.m delete $OldName
   
   set x ".mBar.buffer.m add command -label $NewName "
   set x "$x -command {ChangeBuffer $NewName}"
   uplevel $x

   set BufferStoT($NewName) "[$AWin get 1.0 end]"
   set BufferStoM($NewName) $ModifyStatus
   set BufferStoH($NewName) $HiddenBytes
   set BufferStoS($NewName) $AutoSaveStatus
   set BufferStoP($NewName) "[$AWin index insert]"
   set BufferStoU($NewName) $Usage
   set BufferStoF($NewName) $FileType
   set BufferStoV($NewName) "[$AWin index insertv]"
   set BufferSto1($NewName) [$AWin index markpos1]
   set BufferSto2($NewName) [$AWin index markpos2]
   set BufferSto3($NewName) [$AWin index markpos3]
   set BufferSto4($NewName) [$AWin index markpos4]
   set BufferSto5($NewName) [$AWin index pastebeg]
   set BufferSto6($NewName) [$AWin index pasteend]
   set BufferSto7($NewName) [$AWin index found1]
   set BufferSto8($NewName) [$AWin index last2]
   set BufferStoRet($NewName) $ExtReturnCMD
   set BufferStoTab($NewName) $ExtTabCMD
   set BufferStoSpc($NewName) $ExtSpaceCMD
   set BufferStoView($NewName) $ProtectYN
   
   if {"$ThisFileName" == "$OldName"} {set ThisFileName "$NewName"}
   
   focus $AWin
   BufUpdateHotlist
}

proc StackUp {cmpstr ptr stack} {
   upvar $ptr p
   upvar $stack s
   for {set i 0} {$i < $p} {incr i} {
      if {[string match $cmpstr $s($i)]} {
         set x [expr $p - 1]
         for {set j $i} {$j < $x} {incr j} {
            set k [expr $j + 1]
            set s($j) $s($k)
         }
      }
   }
   set s($p) $cmpstr
   incr p
}

proc StackGet {dir cmpstr ptr stack} {
   upvar $ptr p
   upvar $stack s
   for {set i 0} {$i < $p} {incr i} {
      if {[string match $cmpstr $s($i)]} break
   }
   set i [expr $i + $dir]
   set k [expr $p - 1]
   if {$i > $k} {set i $k}
   if {$i < 0} {set i 0}
   set erg ""
   catch {set erg $s($i)}
   return $erg
}

proc InsertText text {
   global  AWin
   $AWin insert insert "$text"
}
proc InsertTextAt {pos text}  {
   global  AWin
   $AWin insert $pos "$text"
}
proc DeleteTextAt {p1 p2} {
   global AWin
   
   $AWin delete $p1 $p2
}
proc DeleteCharAt pos {
   global AWin
   
   $AWin delete $pos
}

proc ReplaceTextAt {p1 p2 text} {
   global AWin
   
   $AWin delete $p1 $p2
   $AWin insert $p1 "$text"
}

#
# Procedures for Split View
#
proc SplitView { } {
   global BackgroundRGB ForegroundRGB FontSize FontName SplitOnYN EnaSplitYN
   
   if {$SplitOnYN == 1} return
   set EnaSplitYN 1
   set height [GetWinHeight]
   set newh [expr $height >> 1]
   .text configure -height $newh -setgrid 1
   pack .ctextv -side bottom -expand 1 -fill both
   pack .scrollvy -in .ctextv -side right -fill y
   pack .textv -in .ctextv -side bottom -expand 1 -fill both
   .textv configure -height $newh -setgrid 1
   if {$BackgroundRGB != -1} {.textv configure -background $BackgroundRGB}
   if {$ForegroundRGB != -1} {.textv configure -foreground $ForegroundRGB}
   .textv configure -font "${FontName}--*-${FontSize}-*"
   .text mark set insertv 1.0
   CopyText .text .textv
   .textv mark set insert 1.0
   set SplitOnYN 1
   FocusIn .text
}

proc CloseView { } {
   global DelayedCMD SplitOnYN EnaSplitYN AutoSaveCnt AutoSaveStatus
   if {$SplitOnYN != 1} {return}
   
   set DelayedCMD "CloseViewDLD"
}

proc CloseViewDLD { } {
   global DelayedCMD SplitOnYN AutoSaveCnt AutoSaveStatus ThisFileName
   
   SyncText
# Since "CloseView" sometimes crashes, make at least a Backup copy....
   if {$AutoSaveStatus} {
      set AutoSaveCnt 0; set AutoSaveStatus 0
      SaveTo_ "${ThisFileName}~"
   }
# Now continue with closing the window
   set f [focus]
   if {$f == ".textv"} {CopyText .textv .text}
   FocusIn .text
   set DelayedCMD "CloseViewDLD2"
}

proc CloseViewDLD2 { } {
   global SplitOnYN EnaSplitYN AutoSaveCnt AutoSaveStatus ThisFileName

   .textv configure -height 0 -setgrid 0
   pack forget .scrollvy
   pack forget .textv
   pack forget .ctextv
   set SplitOnYN 0
   set height [GetWinHeight]
   set newh [expr $height << 1]
   .text configure -height $newh -setgrid 1
}

proc ClearView {} {
   global EnaSplitYN SplitOnYN
   
   if {$EnaSplitYN != 1} return
   CloseView
   .textv delete 1.0 end
}

proc CopyText {t1 t2} {
   global SplitOnYN EnaSplitYN ThisFileName

   if {$EnaSplitYN != 1} return
   $t2 delete 1.0 end
   $t2 insert insert [$t1 get 1.0 end]
   $t2 mark set found1 [$t1 index found1]
   $t2 mark set found2 [$t1 index found2]
   $t2 mark set pastebeg [$t1 index pastebeg]
   $t2 mark set pasteend [$t1 index pasteend]
   $t2 mark set match1 [$t1 index match1]
   $t2 mark set match2 [$t1 index match2]
   $t2 mark set last1 [$t1 index last1]
   $t2 mark set last2 [$t1 index last2]
   $t2 mark set markpos1 [$t1 index markpos1]
   $t2 mark set markpos2 [$t1 index markpos2]
   $t2 mark set markpos3 [$t1 index markpos3]
   $t2 mark set markpos4 [$t1 index markpos4]
   $t2 mark set insertv [$t1 index insert]
   if {$SplitOnYN == 1} {
      $t2 mark set insert [$t1 index insertv]
      $t2 yview -pickplace insert
      set tmp ""
      catch { set tmp [$t1 tag ranges sel] }
      StoreAttributes_ $ThisFileName $t1
      RecallAttributes_ $ThisFileName $t2
      if {$tmp != ""} {eval "$t1 tag add sel $tmp"}
   }
}

proc SyncText { } {
   global AWin LWin EnaSplitYN

   if {$EnaSplitYN != 1} return
   StoreXSelect
   set w ".text"
   if {$AWin == ".text" } {set w ".textv"}
   CopyText $AWin $w
}

proc LimitedUndo { } {
   global AWin LWin EnaSplitYN
   
   if {$EnaSplitYN != 1} return
   set p [$AWin index insert]
   set w ".text"
   if {$AWin == ".text" } {set w ".textv"}
   CopyText $w $AWin
   $AWin mark set insert $p
   $AWin yview -pickplace insert
}

proc SwitchView win {
   global AWin LWin EnaSplitYN DelayedCMD SplitOnYN
   
   if {$SplitOnYN == 0} {
      SplitView
   } else {
      focus $win
      set  DelayedCMD "focus $win"     
   }
}

proc FocusIn win {
   global AWin LWin BackgroundRGB ForegroundRGB UpdateInterval MinDelay
   
   set w ".text"
   if {$win == ".text" } {set w ".textv"}
   $win mark set insertv [$w index insert]
   if {$BackgroundRGB != -1} {
      $win configure -background $BackgroundRGB
      DimWin $w
   }
#    if {"$LWin" != "$win"} {
#       CopyText $LWin win
#    }
   $win yview -pickplace insert
   set AWin $win
   focus $AWin
   set UpdateInterval $MinDelay
}

#
# Utilities:
#
proc GetWinHeight { } {
#   scan [wm  geometry .] %dx%d width height
   scan [.text configure -height] "-height height Height %d %d" dummy height
   return $height
}

proc GetWinWidth { } {
#   scan [wm  geometry .] %dx%d width height
   scan [.text configure -width] "-width width Width %d %d" dummy width
   return $width
}

proc MacroWarning { } {
   tk_dialog .err "Please:" \
   "Do not move the cursor with the mouse \nduring macro recording" \
   warning -1 OK
}

proc MacText { } {
   global MacroActive AWin MacF RecMacTextPos
   
   if {$MacroActive == 0} {ClearMarks ; set Cancel 1 ; return}
   set MacF($MacroActive) "$MacF($MacroActive)[$AWin get $RecMacTextPos insert]"
}

proc Record n {
   global MacroActive MacF AWin RecMacTextPos LastCommand Cancel

   if {$n > 0} {
      set MacF($n) ""
      set RecMacTextPos [$AWin index insert]
   } else {
      MacText
      set Cancel 1
      set LastCommand "^YClearMarks"
   }
   set MacroActive $n
}

proc DoCmd c {
   global MacroActive MacF AWin RecMacTextPos LastCommand FileType \
          DoAfterCMD DoBeforeCMD UpdateInterval MinDelay FlagDirect ExtAfter

   set FlagDirect 1
   if {$LastCommand == ""} {
      set LastCommand "$c"
      return
   }
   eval $DoBeforeCMD
   if {$MacroActive > 0} {
      MacText
      set MacF($MacroActive) "$MacF($MacroActive)$c"
      ExecCmds "$c"
      set RecMacTextPos [$AWin index insert]
   } else {
      ExecCmds "$c"
   }
   eval $DoAfterCMD
   set UpdateInterval $MinDelay
}

proc PlayMac n {
   global MacroActive MacF FlagDirect
   
   set FlagDirect 0
   ExecCmds "$MacF($n)"
}

proc ExecCmds m {
   global AWin MacroActive DelayedCMD FlagDirect
   
   set l [string length "$m"]
   for {set i 0} {$i < $l} {incr i} {
      set c [string index $m $i]
      if {$c == "^"} {
         incr i
         set c [string index $m $i]
         switch "$c" {
            a {SaveAs}
            b {MarkBegin}
            c {CutToClip}
            d {DelWord}
            e {MarkEnd}
            f {NewBuffer "NewBuffer"}
            g {AskGotoLine}
            h {backspace}
            i {DoIndent}
            j {DoReturn}
            k {DelLine}
            l {ReplaceNext}
            m {MatchBracket}
            n {SearchNext}
            o {LoadAFile}
            p {SearchPrev}
            q {CheckAndQuit}
            r {AskReplaceString}
            s {AskSearchString}
            t {MarkColumnar}
            u {LimitedUndo}
            v {PasteFromClip}
            w {SaveThis}
            x {DelSelect}
            y {YankLine}
            z {CheckAndClose}
            @ {DelSpace}
            > {Capitalize}
            < {LowerCase}
            0 {GotoPos 0}
            1 {GotoPos 1}
            2 {GotoPos 2}
            3 {GotoPos 3}
            4 {GotoPos 4}
            5 {GotoPos 5}
            6 {GotoPos 6}
            7 {SwitchView .text}
            8 {SwitchView .textv}
            9 {GotoPos 9}
            R {NextChar}
            L {PrevChar}
            U {PrevLine}
            D {NextLine}
            T {TopOfFile}
            B {BottomOfFile}
            A {BeginOfLine}
            Z {EndOfLine}
            O {EndOfWord}
            W {BeginOfWord}
            | {DoTab}
            . {DelToEOL}
            / {DelToBOL}
            = {delete}
            X {
                set s ""
                while {$i < $l} {
                   incr i
                   set c [string index $m $i]
                   if {$c <= " "} break
                   if {$c == "^"} {set i [expr $i - 1] ; break}
                   set s "$s$c"
                }
                source $s
              }
            Y {
                set s ""
                while {$i < $l} {
                   incr i
                   set c [string index $m $i]
                   if {$c < " "} break
                   if {$c == "^"} {set i [expr $i - 1] ; break}
                   set s "$s$c"
                }
                uplevel $s
              }
            ! {
                set s ""
                while {$i < $l} {
                   incr i
                   set c [string index $m $i]
                   if {$c < " "} break
                   if {$c == "^"} {set i [expr $i - 1] ; break}
                   set s "$s$c"
                }
                if {!$FlagDirect} {
                   uplevel $s
                } else {
                   set DelayedCMD $s
                }
              }
         }
      } else {
         InsertText "$c"
      }
   }
}

proc GetValue Preset {
   global AWin ThisFileName OldName Ready DelayedCMD

   set GETVnam $ThisFileName
   set Ready 0
   set ThisFileName $Preset
   bind .actfile <Return> {set Ready 1}
   focus .actfile
   while {!$Ready} {
      update
      after 200
   }
   set x $ThisFileName
   set ThisFileName $GETVnam
   set OldName $GETVnam
   bind .actfile <Return> {
      set tmp $OldName
      set OldName $ThisFileName
      DoRenameBuffer $tmp $ThisFileName
   }
   focus $AWin
   return $x
}

proc RepeatKey { } {
   global AWin ThisFileName OldName LastCommand DelayedCMD \
          RPTK_ins RPTK_nr

   set RPTK_nr [GetValue ""]
   set LastCommand ""
   set RPTK_ins [$AWin index insert]
   SyncText
   XSelectToMark
   set DelayedCMD "RepeatKeyXX"
}

proc RepeatKeyRange { } {
   global AWin RPTK_nam LastCommand DelayedCMD RPTK_ins RPTK_nr

   set RPTK_nr "range"
   set LastCommand ""
   set RPTK_ins [$AWin index insert]
   SyncText
   XSelectToMark
   set DelayedCMD "RepeatKeyXX"
}

proc RepeatKeyXX { } {
   global AWin ThisFileName LastCommand DelayedCMD RPTK_ins RPTK_nr \
          Result Cancel EnaSplitYN

   set ins [$AWin index insert]
   if {$LastCommand != ""} {
      set cmd "$LastCommand"
      set Cancel 0
      set msplit $EnaSplitYN
      set EnaSplitYN 0
      if {$RPTK_nr == "all"} {
         set RPTK_nr 99999
         $AWin mark set insert 1.0
      }
      if {$RPTK_nr == "end"} {
         set RPTK_nr 99999
      }
      if {$RPTK_nr == "range"} {
         set RPTK_nr 99998
         $AWin mark set insert pastebeg
         scan [$AWin index pasteend] "%d.%d" endr endc
      }
      scan [$AWin index end] %d endl
      for {set i 1} {$i <= $RPTK_nr} {incr i} {
         switch $RPTK_nr {
            99999 {
               scan [$AWin index insert] "%d.%d" l c
               if {$l >= $endl} {break}
            }
            99998 {
               if {[$AWin compare insert >= pasteend]} {break}
            }
         }
         ExecCmds "$cmd"
         DoBusy 10
         if {$Cancel} {break}
      }
      set EnaSplitYN $msplit
      if {$Cancel} {LimitedUndo}
      return
   }
   if {$RPTK_ins != $ins} {
      set c [$AWin get $RPTK_ins $ins]
      if {($RPTK_nr == "end") || ($RPTK_nr == "all") || ($RPTK_nr == "range")} {
         tk_dialog .err "tkedit error" "Only Number allowed !" warning -1 OK
         return
      }
      set Cancel 0
      for {set i 1} {$i < $RPTK_nr} {incr i} {
         InsertText "$c"
         DoBusy 10
         if {$Cancel} {break}
      }
      if {$Cancel} {LimitedUndo}
      set LastCommand "$c"
      return
   }
   set DelayedCMD "RepeatKeyXX"
}

proc EvalExtAfter { } {
   global ExtAfter FileType
   if {[info exists ExtAfter($FileType)]} {eval $ExtAfter($FileType)}
}

proc EvalExtNewLine { } {
   global ExtNewLine FileType
   if {[info exists ExtNewLine($FileType)]} {eval $ExtNewLine($FileType)}
}

proc NoAction { } {
   return
}

proc NotImplementedYet { } {
   tk_dialog .err "tkedit error" "Not Implemented Yet" warning -1 OK
}

proc Commercial { } {
   tk_dialog .err "Commercial:" "\
Have you also tried tkdir ?\n \
A directory Utility with support\n \
for Workstation Clusters.\n \
Available now at:\n \
ftp.ifh.de:/pub/unix/tcl/code/tkdir-i.j.k.tar.Z" questhead -1 OK
}

proc BufOpenHotWin {height width} {
   global FontString env AWin BufHotIsOpen XPrefHotBgRGB XPrefHotFgRGB

   catch {destroy .bufhot}
   toplevel .bufhot -class Dialog
   frame .bufhot.top -relief raised -bd 1
   pack .bufhot.top -side top -expand 1 -fill both
   frame .bufhot.bot -relief raised -bd 1
   pack .bufhot.bot -side bottom
   text .bufhot.win -width $width -height $height -font $FontString \
         -background $XPrefHotBgRGB -foreground $XPrefHotFgRGB \
         -yscrollcommand ".bufhot.scroll set" -wrap none -setgrid 1
   pack .bufhot.win -in .bufhot.top -side left -expand 1 -fill both
   scrollbar .bufhot.scroll -command ".bufhot.win yview"
   pack .bufhot.scroll -in .bufhot.top -side right -fill y
   button .bufhot.quit -text "Dismiss" -width 10 -command {
      destroy .bufhot
      set BufHotIsOpen 0
   }
   pack .bufhot.quit -in .bufhot.bot -side left
   wm maxsize .bufhot 100 100
   wm minsize .bufhot 10 1
   bind .bufhot.win <1> {
       %W mark set insert @%x,%y
       set name [%W get "insert linestart" "insert lineend"]
       if {[string length $name] > 0} {ChangeBuffer $name}
   }
   bind .bufhot.win <B1-Motion> { }
   bind .bufhot.win <2> { }
   bind .bufhot.win <3> { }
   bind .bufhot.win <Double-1> { }
   bind .bufhot.win <Triple-1> { }
   set BufHotIsOpen 1
}

proc LoadHelp file {
   global env BufferStoT Usage
   
   if {[lsearch [array names BufferStoT] "__Help__"] < 0} {
      regsub -all "\:" $env(PATH) " " s
      set l [llength $s]
      for {set i 0} {$i < $l} {incr i} {
         set f "[lindex $s $i]/tkedit_storage/$file"
         if {[file exists $f]} {
            loadFile $f
            RenameBuffer $f "__Help__"
            break
         }
      }
   } else {
      ChangeBuffer "__Help__"
   }
   set Usage "Help"
}

proc SearchHelp str {
   global AWin SearchString SearchCaseYN SearchPatternYN BufferStoT
   
   set lastsearch $SearchString
   set lastsearchcase $SearchCaseYN
   set lastsearchpatt $SearchPatternYN

   LoadHelp "tkedit.txt"
   TopOfFile
   set SearchString "$str"
   set SearchPatternYN 0
   set SearchCaseYN 0
   SearchNext
   set SearchString $lastsearch
   set SearchCaseYN $lastsearchcase
   set SearchPatternYN $lastsearchpatt
}

proc MacHelp {file str} {
   global env AWin Usage SearchString SearchCaseYN SearchPatternYN BufferStoT
   
   set lastsearch $SearchString
   set lastsearchcase $SearchCaseYN
   set lastsearchpatt $SearchPatternYN

   LoadHelp $file
   TopOfFile
   set SearchString "$str"
   set SearchPatternYN 0
   set SearchCaseYN 0
   SearchNext
   set SearchString $lastsearch
   set SearchCaseYN $lastsearchcase
   set SearchPatternYN $lastsearchpatt
}

proc MacroExternal { } {
   global env FileSelect
   
   set fnam ""
   regsub -all "\:" $env(PATH) " " s
   set l [llength $s]
   if {[file isdirectory "~/tkedit_macros"] != 0} {
     set fnam [eval "exec $FileSelect -dir $env(HOME)/tkedit_macros"]
   } else {
      for {set i 0} {$i < $l} {incr i} {
         set f "[lindex $s $i]/tkedit_storage"
         if {[file isdirectory $f]} {
            set fnam [eval "exec $FileSelect -dir $f"]
            break
         }
      }
   }
   if {[string length $fnam] > 0} {
      source $fnam
   }
}

proc MacroAddStart { } {
   global env FileSelect
   
   set fnam ""
   regsub -all "\:" $env(PATH) " " s
   set l [llength $s]
   for {set i 0} {$i < $l} {incr i} {
      set f "[lindex $s $i]/tkedit_storage"
      if {[file isdirectory $f]} {
         set fnam [eval "exec $FileSelect -dir $f -patt *.startup"]
         break
      }
    }
   if {[string length $fnam] > 0} {
      if {[file isdirectory "~/tkedit_macros"] == 0} {
         exec mkdir "$env(HOME)/tkedit_macros"
      }
      set s [file tail $fnam]
      exec cp "$fnam" "$env(HOME)/tkedit_macros/$s"
      set x "uplevel \{source $fnam\}"
      eval $x
   }
}

proc MacroRemove { } {
   global env FileSelect
   
   set fnam ""
   set f "$env(HOME)/tkedit_macros"
   set fnam [eval "exec $FileSelect -dir $f"]
   if {[string length $fnam] > 0} {
      exec rm "$fnam"
      set x "unload_[file rootname [file tail $fnam]]"
      catch {uplevel $x}
   }
}

proc MacroCopy { } {
   global env FileSelect
   
   set fnam ""
   regsub -all "\:" $env(PATH) " " s
   set l [llength $s]
   for {set i 0} {$i < $l} {incr i} {
      set f "[lindex $s $i]/tkedit_storage"
      if {[file isdirectory $f]} {
         set fnam [eval "exec $FileSelect -dir $f"]
         break
      }
    }
   if {[string length $fnam] > 0} {
      if {[file isdirectory "~/tkedit_macros"] == 0} {
         exec mkdir "$env(HOME)/tkedit_macros"
      }
      set s [file tail $fnam]
      exec cp "$fnam" "$env(HOME)/tkedit_macros/$s"
   }
}

proc EntryCursor {w dir} {
   set x [$w index insert]
   set x [expr $x + $dir]
   $w icursor $x
}

proc DoScrollY {args} {
   global XPrefFollowViewYN
   
   eval $args
   set win [lindex $args 0]
   focus $win
   if $XPrefFollowViewYN {
      $win mark set insert [$win index @1,1]
   }
}

proc DoScrollX {args} {
   eval .text xview $args
   eval .textv xview $args
}

proc SwitchXscroll { } {
   global XPrefScrollBarX
   
   if {$XPrefScrollBarX} {
      pack .scrollx -in .ctext -side bottom -before .text -fill x -pady 0
      .text configure -wrap none
      .textv configure -wrap none
   } else {
      .text configure -wrap char
      .textv configure -wrap char
      pack forget .scrollx
   }
}

proc DoBusy intervall {
   global AWin BusyCnt
   
   if {$BusyCnt > $intervall} {
      set BusyCnt 0
      $AWin yview -pickplace insert
      update
   }
   incr BusyCnt
}

proc GetLineNumber { } {
   global AWin LWin LineNumber ColumnNumber ExtractedLines LSELines Usage \
          ThisFileName LSEFrom LSEwhat DoNewLineCMD
   
   switch $Usage {
      "All" {
            scan [$AWin index insert] "%d.%d" l c
            set l [expr $l - 1]
            set ll [array size ExtractedLines]
            if {$l < $ll} {set l $ExtractedLines($l)}
            set LineNumber $l
            set ColumnNumber $c
      }
      "LSE" {
            scan [$AWin index insert] "%d.%d" l c
            set l [expr $l - 1]
            if {[catch {set ll [llength $LSELines($LSEwhat,$LSEFrom)]}]} {set ll 0}
            if {$l < $ll} {set l [lindex $LSELines($LSEwhat,$LSEFrom) $l]}
            set LineNumber $l
            set ColumnNumber $c
      }
      default {
         set f [focus]
         if {($f != ".linenr") && ($f != ".columnnr")} {
            scan [$AWin index insert] %d.%d LineNumber ColumnNumber
            eval $DoNewLineCMD
         }
      }
   }
}
proc GetBytes { } {
   global AWin LWin NumBytes HiddenBytes Usage LastInsert LastEnd \
   UpdateInterval MinDelay
   set i [$AWin index insert]
   set e [$AWin index end]
   if {($e == $LastEnd) && ($i == $LastInsert)} return
   set LastEnd $e
   set LastInsert $i
   set UpdateInterval $MinDelay
   switch $Usage {
      default {
         set f [focus]
         if {$f != ".bytes"} {
            set NumBytes [expr [string length [$AWin get 1.0 end]] \
                  + $HiddenBytes]
         }
      }
   }
}
proc DoService flag {
   global AWin NumBytes LastBytes ModifyStatus AutoSaveStatus Usage DelayedCMD\
          MacroActive MarkActive ProtectYN ThisFileName LastL LastC\
          FSgreenCMD FSredCMD FSamberCMD FSblueCMD FSvioletCMD \
          UpdateInterval MinDelay XPrefPasteRGB

   if {[tell stdin] < 0} {
      if {$ThisFileName == "NewBuffer"} {
         RenameBuffer $ThisFileName "__stdin"
         set ThisFileName "__stdin"
         set Usage "More"
         focus $AWin
         $AWin mark set insert 1.0
         $AWin yview -pickplace 1.0
         update
      }
      if {$ThisFileName == "__stdin"} {
         regsub -all ".\x08" "[read stdin 32768]" "" s
         set ProtectYN 1
         InsertTextAt end "$s"
      }
   }
   set FSdoCMD "$FSgreenCMD"
   GetLineNumber
   GetBytes
   if {$flag == 1} {
      set ModifyStatus 0
   } else {
      if {$NumBytes != $LastBytes} {
         set ModifyStatus 1
         set AutoSaveStatus 1
         set UpdateInterval $MinDelay
      }
      if {$ModifyStatus == 1} {
         set FSdoCMD "$FSredCMD"
         if {$AutoSaveStatus == 0} {set FSdoCMD "$FSamberCMD"}
      }
   }
   switch $Usage {
      "More" {
         set LastBytes $NumBytes
         set ModifyStatus 0
         set AutoSaveStatus 0
      }
      "Shell" {
         set NumBytes $LastBytes
         set ModifyStatus 0
         set AutoSaveStatus 0
         set FSdoCMD "$FSgreenCMD"
      }
   }
   switch $MarkActive {
    1 {
         set FSdoCMD "$FSvioletCMD"
         $AWin tag delete paste
         $AWin mark set pasteend insert
         $AWin tag add paste pastebeg pasteend
         $AWin tag configure paste -background $XPrefPasteRGB
      }
    2 {
         set FSdoCMD "$FSvioletCMD"
         scan [$AWin index pastebeg] "%d.%d" l1 c1
         scan [$AWin index insert] "%d.%d" l2 c2
         $AWin tag delete paste
         for {set l $l1} {$l <= $l2} {incr l} {
            $AWin tag add paste $l.$c1 $l.$c2
            $AWin tag configure paste -background $XPrefPasteRGB
         }
         set LastC $c2
         set LastL $l2
      }
   }
   if {$MacroActive > 0} {set FSdoCMD "$FSblueCMD"}
   eval $FSdoCMD
   if {$DelayedCMD != "NoAction"} {
      set cmd "$DelayedCMD"
      set DelayedCMD "NoAction"
      uplevel "$cmd"
   }
   set LastBytes $NumBytes
}

proc PrepareExit { } {
   global QuitFlag DoOnExit XPrefAutoSavePrefs
   
   AllowDestroy
   if {$XPrefAutoSavePrefs} {SavePrefs}
   set QuitFlag 1
   catch {eval $DoOnExit}
}

proc AllowDestroy { } {
   foreach i [info commands .*] {
      bind $i <Destroy> { }
   }
}
proc ForbidDestroy { } {
   foreach i [info commands .*] {
      bind $i <Destroy> {DoNotDestroy %W}
   }
}
proc DoNotDestroy win {

      tk_dialog .err "Notice" \
"Please do not press this Button again\n \
Diesen Knopf bitte nicht mehr drcken\n\n \
Please select QUIT from the FILE-menu" \
 warning -1 "Ich war's nicht"

   tkeditMainLoop
}

#
# Main Loop
#

proc tkeditMainLoop { } {
global UpdateInterval DynIncr MaxDelay PollFunctions QuitFlag

   DoService 1
   focus .text
   GetLineNumber

   update
   set j 0
   set k 0
   
   while { 1 == 1 } {
      if {($UpdateInterval < 200) || ($k > 4)} {
         DoService 0
         AutoSave $j
         set k 0
      }
      incr k
      set UpdateInterval [expr $UpdateInterval + ($UpdateInterval / $DynIncr)]
      if {$UpdateInterval > $MaxDelay} {set UpdateInterval $MaxDelay}
   
      set j 0
      while {$j < 1000} {
         eval $PollFunctions
         update
         after $UpdateInterval
         set j [expr $j + $UpdateInterval]
         if {$QuitFlag} break
      }
      if {$QuitFlag} break
   }
}   

#
# post processing
#

ForbidDestroy
set QuitFlag 0
set FileType "Unknown"
set BufHotIsOpen 0
set FSgreenCMD ".close configure -background #00ff00"
set FSredCMD ".close configure -background #ff0000"
set FSamberCMD ".close configure -background #ffa000"
set FSvioletCMD ".close configure -background #ff00ff"
set FSblueCMD ".close configure -background #0000ff"
set AutoSaveStatus 0
set AutoSaveCnt 0
set MacroActive 0
set MarkActive 0
set SearchStackPtr 0
set ReplaceStackPtr 0
set SaveFirstTime 1
set YankBuffer ""
set AWin .text
set LWin .text
set SplitOnYN 0
set LastL 1
set LastC 0
set ExtReturnCMD "InsertReturn"
set ExtTabCMD "InsertTab"
set ExtSpaceCMD "InsertSpace"
set DelayedCMD "NoAction"
set LastCommand "NoAction"
set DoAfterCMD "EvalExtAfter"
set DoBeforeCMD "NoAction"
set DoNewLineCMD "EvalExtNewLine"
set SaveFunctions "NoAction"
set DoOnExit "NoAction"
set Usage "File"
set LastBytes 0
set LastInsert 0.0
set LastEnd 0.0
set BusyCnt 0
set PrintCMD "lpr"
set NoWin 0
set FileSelect "FileSelect 2>/dev/null"
set UpdateInterval $MinDelay
set MyAdress "tkedit"
if {$tk_version >= 4.0} {set MyAdress [tk appname]}

update

set flag 0
if {$argc > 0} {
   set i 0
   while {$i < $argc} {
      set f [lindex $argv $i]
#
# - start code Raul Barral Tamayo 
#
      update
      # here, it must avoid to load the following option
      if {[string index $f 0] == "-"} { 
        incr i 2
        if { $f == "-ro" } { incr i "-1" }
        continue
      }; # continue because it could be files between options :-)

      # it must avoid to load a directory
      if { ![ file isdirectory $f ] } { loadFile $f }
#
# - End Code Raul Barral Tamayo
#
      set flag 1
      incr i
   }
} 
if {$flag == 0} { NewBuffer "NewBuffer" }

$AWin mark set insert 1.0
# $AWin yview -pickplace insert


set flag 0
for {set i 0} {$i < $argc} {incr i} {
   if {[lindex $argv $i] == "-do"} {
      incr i
      set f [lindex $argv $i]
      if {[string length $f] > 0} {source $f}
      set flag 1
   }
}
if {$flag == 0} { ReadConfig }
GetFileType

set i [lsearch $argv "-pos"]
if {$i > 0} {
   incr i
   set x [lindex $argv $i]
   .text mark set insert $x
   .text yview -pickplace insert
}

set i [lsearch $argv "-search"]
if {$i > 0} {
   incr i
   set SearchString [lindex $argv $i]
   SearchNext 
}

set i [lsearch $argv "-width"]
if {$i > 0} {
   incr i
   set x [lindex $argv $i]
   .text configure -width $x
}

set i [lsearch $argv "-height"]
if {$i > 0} {
   incr i
   set x [lindex $argv $i]
   .text configure -height $x
}

set i [lsearch $argv "-bg"]
if {$i > 0} {
   incr i
   set x [lindex $argv $i]
   SetRGB_bg $x
}

set i [lsearch $argv "-fg"]
if {$i > 0} {
   incr i
   set x [lindex $argv $i]
   SetRGB_fg $x
}

set i [lsearch $argv "-cmd"]
if {$i > 0} {
   incr i
   set x [lindex $argv $i]
   eval $x
}

set i [lsearch $argv "-exit"]
if {$i > 0} {
   incr i
   set DoOnExit  [lindex $argv $i]
}
   
set i [lsearch $argv "-ro"]
if {$i > 0} {
   set ProtectYN 1
}

#
# Now load System administrators configuration for Dynamic Update Rates
#
if {[file exists /etc/tkedit.cfg]} {
   source "/etc/tkedit.cfg"   
}

wm iconname . $ThisFileName

tkeditMainLoop
