#
# String completion for Canvas widgets
#


# Canvas replacement / completion

proc th_Canvas_undoable_completion_replace {w i new_string} {
  global auto_index
  if {([info procs th_Canvas_register_undoable_cmd] != "") || \
    ([lsearch [array names auto_index] th_Canvas_register_undoable_cmd] >= 0)} {
    th_Canvas_register_undoable_cmd $w $i "Completion"
  }
  if {([info procs th_Canvas_replace] != "") || \
     ([lsearch [array names auto_index] th_Canvas_replace] >= 0)} {
    th_Canvas_replace $w $i $new_string
  } else {
    set delta [expr [string length $new_string] - [string length [lindex [$w itemconfigure $i -text] 4]]]

    set new_index [expr [$w index $i insert] + $delta]
    $w dchars $i 0 end
    $w insert $i 0 $new_string
    $w icursor $i $new_index
}}

# Does completion to the string in an entry binding.
# Beeps unless exact completion was made.
proc th_Canvas_complete {w possibilities {function filter_completions}} {
  if {[catch "$w index [set i [$w focus]] insert"]} {bell ; return}
  if {[$w index $i insert] == 0} {return 0}

  set new_string [th_Misc_complete [lindex [$w itemconfigure $i -text] 4] $possibilities $function]
  if {$new_string != ""} {th_Canvas_undoable_completion_replace $w $i $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_Canvas_complete_multiple {w completion_list} { 
  if {[catch "$w index [set i [$w focus]] insert"]} {bell ; return}

  set index [expr [$w index $i insert] - 1]
  set text [lindex [$w itemconfigure $i -text] 4]
  set prev_char [string index $text $index]
  if {([string first $prev_char " \n\t"] >= 0) || ($index == -1)} {return 0}

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

# Shows list of completions, letting user pick one.
proc th_Canvas_completion_dialog {w} {
  if {[catch "$w index [set i [$w focus]] insert"]} {bell ; return}

  global TH
  set view [$w index $i insert]
  set new_string [th_Misc_completion_dialog $view]
  if {$new_string != ""} {
    set text [lindex [$w itemconfigure $i -text] 4]
    th_Canvas_undoable_completion_replace $w $i "[string range $text 0 \
	[expr $TH(Completion,Index) - 1]]$new_string[string range $text \
		[$w index $i insert] end]"
}}
