Version 4 of tk_textPaste

Updated 2009-10-28 15:27:32 by wdb

tk_textPaste window

Pastes the contents of the clipboard to the insertion point in a text widget window. Deletes the current selection (except on X11).

This function is documented with text.


This command is called in response to the receipt of a <<Paste>> event.


The actual proc is defined as:

 proc ::tk_textPaste w {
   global tcl_platform
   if {![catch {::tk::GetSelection $w CLIPBOARD} sel]} {
     set oldSeparator [$w cget -autoseparators]
     if { $oldSeparator } {
       $w configure -autoseparators 0
       $w edit separator
     }
     if {[string compare [tk windowingsystem] "x11"]} {
       catch { $w delete sel.first sel.last }
     }
     $w insert insert $sel
     if { $oldSeparator } {
       $w edit separator
       $w configure -autoseparators 1
     }
   }
 }

which doesn't take into account the possibility of having multiple ranges with the sel tag. Here's a more complete version:

 proc ::tk_textPaste w {
   global tcl_platform
   array set range {}
   if { [catch {$w tag ranges sel} ranges] } { return }
   foreach {first last} $ranges {
     set range($first) $last
     puts "set range($first) \[$last\]"
   }

   if { [catch {::tk::GetSelection $w CLIPBOARD} sel] } { return }

   set oldSeparator [$w cget -autoseparators]
   if { $oldSeparator } {
     $w configure -autoseparators 0
     $w edit separator
   }
   if { ![string equal [tk windowingsystem] "x11"] } {
     foreach first [lsort -decreasing [array names range]] {
       $w delete $first $range($first)
     }
   }
   $w insert insert $sel
   if { $oldSeparator } {
     $w edit separator
     $w configure -autoseparators 1
   }
 }

See also:


Tk syntax help - Category Command - Category String Processing


WHD - 2009-10-27 12:19:49

Two questions:

  • Why doesn't tk_textPaste delete the selection on X11? That might have been standard behavior at one time, but it certainly isn't standard behavior now.
  • Regarding the "fixed" version above that allows the "sel" tag to have multiple ranges...why would it?

wdb Separate selection areas are imaginamble if a text widget is programmed like OOo Write. -- O my unix machine, I am annoyed of non-deleting the selection on pasting, so here my slightly shorter version where multiple sel ranges are deleted in reverse order:

proc tk_textPaste w {
  global tcl_platform
  if {!catch {::tk::GetSelection $w CLIPBOARD} sel} then {
    set oldSeparator $w cget -autoseparators
    if {$oldSeparator} then {
      $w configure -autoseparators 0
      $w edit separator
    }
    foreach {to from} [lreverse [$w tag ranges sel] {
      $w delete $from $to
    }
    $w insert insert $sel
    if {$oldSeparator} then {
      $w edit separator
      $w configure -autoseparators 1
    }
  }
}