#
# Code for doing query or global replacements in Text widgets
#

# Called the first time a replace operation is requested
proc th_Text_replace_setup {w} {
  global TH
  eval $w tag configure was_replaced $TH(Replace,Tag)
  set TH(Replace,All,$w) {}
  set TH(Replace,Marks,$w) {}
}

# Does one replacement.
proc th_Text_replace_one {w} {
  global TH auto_index
  set search $TH(Search,Select,[winfo class $w])
  set new_string [[th_frame $w].replace.e get]

  if {[catch "$w get $search.first $search.last" old_stuff]} {return}
  $w delete $search.first $search.last
  $w insert insert $new_string ; incr TH(Replace,Count,$w)
  $w tag add was_replaced "insert -[string length $new_string] c" insert
  $w tag raise was_replaced
  set TH(Modified,$w) 1
  if {([info procs th_Text_register_undoable_cmd] != "") || \
     ([lsearch [array names auto_index] th_Text_register_undoable_cmd] >= 0)} {
    set m1 [th_gensym] ; set m2 [th_gensym]
    $w mark set $m1 "insert -[string length $new_string] chars"
    $w mark set $m2 insert
    $w mark gravity $m1 left
    $w mark gravity $m2 right
    set replacement [list $m1 $m2 $old_stuff]
    lappend TH(Replace,All,$w) $replacement
    lappend TH(Replace,Marks,$w) $m1 $m2
}}

# Shuts down replacement.
proc th_Text_replace_exit {w} {
  global TH auto_index
  $w tag remove was_replaced 1.0 end
  set f [th_frame $w]
  if {([info procs th_Text_register_undoable_cmd] != "") || \
     ([lsearch [array names auto_index] th_Text_register_undoable_cmd] >= 0)} {
    if {![catch "set TH(Replace,All,$w)"] &&
	![catch "set TH(Replace,Marks,$w)"] && $TH(Replace,Count,$w)} {
      th_Text_register_undoable_cmd $w [list th_Text_undo_replacements $w \
$TH(Replace,All,$w)] "Replace [$f.search.e get] with [$f.replace.e get]" \
	$TH(Replace,Marks,$w)
}}}

# Undoes the replacements passed in.
proc th_Text_undo_replacements {w replacements} {
  foreach replacement $replacements {
    $w delete [lindex $replacement 0] [lindex $replacement 1]
    $w insert [lindex $replacement 0] [lindex $replacement 2]
}}
