# Canvas chapter

# Bindings for canvas Text items

proc CanvasEditBind { c } {
	bind $c <Button-1> {
		focus %W
		if {[%W find overlapping [expr %x-2] [expr %y-2] \
				[expr %x+2] [expr %y+2]] == {}} {
			%W focus {}
		}
	}
	$c bind text <Button-1> {
		%W focus current
		%W icursor current @%x,%y
		%W select from current @%x,%y
	}
	$c bind text <B1-Motion> {
		%W select to current @%x,%y
	}
	$c bind text <Delete> {
		if {[%W select item] != {}} {
			%W dchars [%W select item] sel.first sel.last
		} elseif {[%W focus] != {}} {
			%W dchars [%W focus] insert
		}
	}
	$c bind text <Control-d> {
		if {[%W focus] != {}} {
			%W dchars [%W focus] insert
		}
	}
	$c bind text <Control-h> {
		if {[%W select item] != {}} {
			%W dchars [%W select item] sel.first sel.last
		} elseif {[%W focus] != {}} {
			set _t [%W focus]
			%W icursor $_t [expr [%W index $_t insert]-1]
			%W dchars $_t insert
			unset _t
		}
	}
	$c bind text <BackSpace> [$c bind text <Control-h>]

	$c bind text <Control-Delete> {
		%W delete current
	}
	$c bind text <Return> {
		%W insert current insert \n
	}
	$c bind text <Any-Key> {
		%W insert current insert %A
	}
	bind $c <Button-2> {
		if {[catch {selection get} _s] == 0} {
			if {[%W focus] != {}} {
			    %W insert [%W focus] insert $_s
			} else {
			    %W create text %x %y -text $_s -anchor nw -tag text
			}
			unset _s
		}
	}
	$c bind text <Key-Right> {
		%W icursor current [expr [%W index current insert]+1]
	}
	$c bind text <Control-f> [$c bind text <Key-Right>]
	$c bind text <Key-Left> {
		%W icursor current [expr [%W index current insert]-1]
	}
	$c bind text <Control-b> [$c bind text <Key-Left>]
}
if [info exists c] {
    CanvasEditBind $c
    $c create text 50 50 -text "Hello there" -tag text
}
