#
# String completion for Entry widgets
#


# Entry replacement / completion

proc th_Entry_undoable_completion_replace {w new_string} {
  global auto_index
  if {([info procs th_Entry_register_undoable_cmd] != "") || \
     ([lsearch [array names auto_index] th_Entry_register_undoable_cmd] >= 0)} {
    th_Entry_register_undoable_cmd $w "Completion"
  }
  if {([info procs th_Entry_replace] != "") || \
     ([lsearch [array names auto_index] th_Entry_replace] >= 0)} {
    th_Entry_replace $w $new_string
  } else {
    set delta [expr [string length $new_string] - [string length [$w get]]]
    set new_index [expr [$w index insert] + $delta]
    set view [$w index @0]
    $w delete 0 end
    $w insert 0 $new_string
    $w icursor $new_index
    $w xview $view
}}

# Does completion to the string in an entry binding.
# Beeps unless exact completion was made.
proc th_Entry_complete {w possibilities {function filter_completions}} {
  if {[$w index insert] == 0} {return 0}
  set new_string [th_Misc_complete [$w get] $possibilities $function]
  if {$new_string != ""} {th_Entry_undoable_completion_replace $w $new_string}
  return 1
}

# Does completion to the substring in an entry binding before the insert cursor.
# Beeps unless completion was made and no message exists.
proc th_Entry_complete_multiple {w completion_list} { 
  set index [expr [$w index insert] - 1]
  set prev_char [string index [$w get] $index]
  if {([string first $prev_char " \n\t"] >= 0) || ($index == -1)} {return 0}

  set head [string range [$w get] 0 $index]
  set tail [string range [$w get] [$w index insert] end]
  set new_string [th_Misc_complete_multiple $head $completion_list]
  if {$new_string != ""} {
    th_Entry_undoable_completion_replace $w "$new_string$tail"
  }
  return 1
}

# Shows list of completions, letting user pick one.
proc th_Entry_completion_dialog {w} {
  global TH
  set view [$w index insert]
  set new_string [th_Misc_completion_dialog $view]
  if {$new_string != ""} {
    th_Entry_undoable_completion_replace $w "[string  range [$w get] 0 \
	[expr $TH(Completion,Index) - 1]]$new_string[string range [$w get] \
		[$w index insert] end]"
}}
