# Copyright (C) 1999 - Martin Strauss - under terms of GPL
###############################################################################
# line breaking
proc Line_breaking {E START END} {
global line_breaking_chars
set imax [lindex [split [$E index "$START.0 lineend"] "."] 1]
set spaces ""
for {set i 0} {$i<=$imax} {incr i} {
 if {[string compare [$E get $START.$i] " "] == 0} {set spaces "$spaces "} {break}
}
for {set i $START} {$i<=$END} {incr i} {
 if {[lindex [split [$E index "$i.0 lineend"] "."] 1] > 80} {
  set pos [$E search -backwards -- " " $i.$line_breaking_chars "$i.0"]
  if {[lindex [split $pos "."] 0] == $i} {
   if {[string compare [$E get "$pos + 1c"] "\n"] !=0} {
    $E insert "$pos + 1c" "\n$spaces"
    incr END
   }
  }
 }
}
}
proc Line_unbreaking {E START END} {
for {set i $START} {$i<=$END} {incr i} {
 if {[string compare [$E get "$i.0 lineend - 1c"] " "] ==0} {
  if {[string length [$E get "$i.0+1l" "$i.1+1l"]] !=0} {
   while {[string compare [$E get "$i.0 lineend+1c"] " "] == 0} {
    $E delete "$i.0 lineend+1c"
   }
   $E delete "$i.0 lineend"
   incr i -1
   incr END -1
  }
 }
}
}
proc Line_breaking_switch {E KEY} {
switch $KEY all {
 Line_breaking_switch $E unall
 Line_breaking $E 1 [lindex [split [$E index end] "."]  0]
} unall {
 Line_unbreaking $E 1 [lindex [split [$E index end] "."]  0]
} section {
 Line_breaking_switch $E unsection
 set pos1 [lindex [split [$E search -backwards -regexp -- "^$" insert 1.0] "."]  0]
 set pos2 [lindex [split [$E search -regexp -- "^$" insert end] "."]  0]
 if {$pos1 == ""} {set pos1 1}
 if {$pos2 == ""} {set pos2 [lindex [split [$E index end] "."]  0]}
 Line_breaking $E $pos1 $pos2
} unsection {
 set pos1 [lindex [split [$E search -backwards -regexp -- "^$" insert 1.0] "."]  0]
 set pos2 [lindex [split [$E search -regexp -- "^$" insert end] "."]  0]
 if {$pos1 == ""} {set pos1 1}
 if {$pos2 == ""} {set pos2 [lindex [split [$E index end] "."]  0]}
 Line_unbreaking $E $pos1 $pos2
} line {
 Line_breaking_switch $E unline
 set ksp [lindex [split [$E index {insert linestart}] "."] 0]
 if {$ksp != ""} {
  Line_breaking $E $ksp $ksp
 }
} unline {
 set pos1 [expr [lindex [split [$E search -backwards -regexp -- "\[^ \]$" insert 1.0] "."]  0] +1]
 set pos2 [lindex [split [$E search -regexp -- "\[^ \]$" insert end] "."]  0]
 if {$pos1 == ""} {set pos1 1}
 if {$pos2 == ""} {set pos2 [lindex [split [$E index end] "."]  0]}
 Line_unbreaking $E $pos1 $pos2
}
}