#
# Operations for HTML manipulation in Text widgets.
#

# The following functions work on HTML anchors, returning an index or "" if
# unsuccessful.

proc th_anchor_begin {w index} {
  set i1 [$w search -backward -- "<a " "$index +1c" 1.0]
  set i2 [$w search -backward -- "<A " "$index +1c" 1.0]
  if {$i1 == ""} {return $i2} ; if {$i2 == ""} {return $i1}
  if {[$w compare $i1 < $i2]} {return $i2} else {return $i1}
}

proc th_anchor_end {w index} {
  set i1 [$w search -forward -- "</a>" "$index -4c" end]
  set i2 [$w search -forward -- "</A>" "$index -4c" end]
  if {$i1 == ""} {
    if {$i2 == ""} {return ""} else {return "$i2 +4c"}
  } elseif {$i2 == ""} {return "$i1 +4c"
  } elseif {[$w compare $i1 > $i2]} {return "$i2 +4c"} else {return "$i1 +4c"}
}

proc th_anchor_next {w index} {
  set i1 [$w search -forward -- "<a " "$index+1c" end]
  set i2 [$w search -forward -- "<A " "$index+1c" end]
  if {$i1 == ""} {return $i2} ; if {$i2 == ""} {return $i1}
  if {[$w compare $i1 > $i2]} {return $i2} else {return $i1}
}

proc th_anchor_prev {w index} {
  if {[set begin [th_anchor_begin $w $index]] == ""} {return ""}
  if {[$w compare $begin != $index]} {return $begin 
  } else {return [th_anchor_begin $w "$index -1c"]
}}

# The following functions are similar, except they work on HTML markups.

proc th_markup_begin {w index} {
  if {[$w compare $index >= "end-1c"]} {set index "end-2c"}
  return [$w search -backward -- "<" "$index +1c" 1.0]
}

proc th_markup_end {w index} {
  set i1 [$w search -forward -- ">" "$index -1c" end]
  if {$i1 == ""} {return ""} else {return "$i1 +1c"}
}

proc th_markup_next {w index} {
  return [$w search -forward -- "<" "$index+1c" end]
}

proc th_markup_prev {w index} {
  if {[set begin [th_markup_begin $w $index]] == ""} {return ""}
  if {[$w compare $begin != $index]} {return $begin 
  } else {return [th_markup_begin $w "$index -1c"]
}}

