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

# Called for the first replace. (called from the search routines).
proc th_Misc_replace_setup {w binding_list} {
  global TH
  set rf "[th_frame $w].replace"
  set sf "[th_frame $w].search"

  lappend TH(Completions,$rf.e) "th_word_replace $w {}"

  foreach binding "OK Cancel $binding_list" {
    th_bind $rf.e $binding [th_bind $sf.e $binding]
  }
  th_bind $rf.e Replace_One "th_Misc_replace_one $w ; break"
  th_bind $rf.e Replace_All "th_Misc_replace_all $w ; break"

  destroy $rf.l
  menubutton $rf.l -text "Change to:" -menu $rf.l.m
  pack $rf.l -side left -before $rf.e
  menu $rf.l.m
  foreach binding $binding_list {
    $rf.l.m add command -label [lindex $TH(Menuentry,$binding) 0] \
	-accel [lindex $TH(Binding,$binding) 0] \
	-underline [lindex $TH(Menuentry,$binding) 1] \
	-command [th_bind $rf.e $binding]
  }
  set class [winfo class $w]
  if {([info procs th_[set class]_replace_setup] != "") || \
     ([lsearch [array names auto_index] th_[set class]_replace_setup] >= 0)} {
    th_[set class]_replace_setup $w
}}

# Sets up the replacement routines for w. Binding_list is the set of search
# bindings that should be duplicated in the replacement entry.
proc th_Misc_replace {w clear_flag binding_list} {
  if {[winfo exists "[th_frame $w].replace.e"]} {set setup 0} else {set setup 1}
  set rf [th_show_entry $w replace]
  if $setup {th_Misc_replace_setup $w $binding_list}
  if $clear_flag {$rf.e delete 0 end}

  set sf "[winfo parent $rf].search"
  global TH auto_index
  set TH(Replace,Width,$w) [$sf.e cget -width]
  if {[set width [string length [$sf.e get]]] > 10} {set width 10}
  $sf.e configure -width $width
  set TH(Replace,Count,$w) 0
  return ""
}

proc th_Misc_replace_one {w} {
  th_[winfo class $w]_replace_one $w
  th_Misc_find $w [[th_frame $w].search.e get] 1
}

proc th_Misc_replace_all {w} {
  th_[winfo class $w]_replace_one $w
  set se "[th_frame $w].search.e"
  set re "[th_frame $w].replace.e"
  set old_string [$se get]
  while {[th_Misc_find $w $old_string 1]} { th_[winfo class $w]_replace_one $w }
  th_Misc_search_exit $w
  $se delete 0 end
  $se insert 0 [$re get]
}

# Shuts down replacee.
proc th_Misc_replace_exit {w} {
  th_hide_entry $w replace
  global TH auto_index
  set f [th_frame $w]
  $f.search.e configure -width $TH(Replace,Width,$w)

  set class [winfo class $w]
  if {([info procs th_[set class]_replace_exit] != "") || \
     ([lsearch [array names auto_index] th_[set class]_replace_exit] >= 0)} {
    th_[set class]_replace_exit $w
  }
  if $TH(Replace,Count,$w) {
    th_flash_label $w -text "Replaced $TH(Replace,Count,$w) occurrences."
    set TH(Replace,Count,$w) 0
  }
}
