--- library/text.tcl +++ library/text.tcl @@ -489,25 +489,63 @@ # between characters to the given coordinates and returns the index # of the character just after the boundary. # +# The boundary is kept out of grapheme clusters. A cluster (a base +# character plus its combining marks, e.g. the nikkud and teamim of +# pointed Hebrew, or a ZWJ emoji sequence) occupies a single position +# on screen although it spans several indices; when the half-width +# test below splits inside such a cluster, each pointer movement can +# oscillate between those indices and the mouse selection "dances" +# while dragging. Snapping the boundary to the edge of the cluster, +# using the ICU-based tk::startOfCluster / tk::endOfCluster commands +# (UAX #29 extended grapheme clusters), makes the selection visually +# stable for every writing system, not just Hebrew. +# # Arguments: # w - The text window. # x - X-coordinate within the window. # y - Y-coordinate within the window. proc ::tk::TextClosestGap {w x y} { set pos [$w index @$x,$y] set bbox [$w bbox $pos] if {$bbox eq ""} { return $pos } # The check on y coord of the line bbox with dlineinfo is to fix # [a9cf210a42] to properly handle selecting and moving the mouse # out of the widget. # The bbox of a newline extends to the right edge of the widget, and # the gap after it is on the next line. [13aabdb3c1] - if {$y < [lindex [$w dlineinfo $pos] 1] || - $x - [lindex $bbox 0] < [lindex $bbox 2]/2 || - [$w get $pos] eq "\n"} { + if {$y < [lindex [$w dlineinfo $pos] 1] || [$w get $pos] eq "\n"} { return $pos } + # Keep the boundary out of grapheme clusters. This is only possible + # when libicu was found at start-up (see generic/tkIcu.c); without + # it the behavior below is unchanged. + if {[llength [info commands ::tk::startOfCluster]]} { + # $cend is the first cluster boundary after $pos, so the cluster + # [$cstart, $cend) is the one containing $pos. When $pos is itself + # a cluster boundary, $cstart == $pos and we fall through to the + # historical behavior. + set cend [TextNextPos $w $pos tk::endOfCluster] + if {[$w compare $cend != $pos]} { + set cstart [TextPrevPos $w $cend tk::startOfCluster] + if {[$w compare $cstart != $pos]} { + # $pos is strictly inside a cluster: apply the half-width + # test to the base character of the cluster, and return the + # nearest cluster edge. + set bb [$w bbox $cstart] + if {$bb eq ""} { + set bb $bbox + } + if {$x - [lindex $bb 0] < [lindex $bb 2]/2} { + return $cstart + } + return $cend + } + } + } + if {$x - [lindex $bbox 0] < [lindex $bbox 2]/2} { return $pos } $w index "$pos + 1 char" }