# Clipboard cut, copy and paste features.
# Rick Smereka, Copyright (C) 2004-2005.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, get a copy via the Internet at
# http://gnu.org/copyleft/gpl.html or write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA

# You can contact the author via email at rsmereka@future-lab.com

# Initial tcl version. Feb/2004, Rick Smereka
# This version based on code in the book 'Graphical Applications with
# Tcl & Tk' second edition by Eric Foster-Johnson.
proc cut_text {textwidget} {
   # Cut text from text widget to clipboard. Returns nothing.
   # get the owner of the current selection (if any)
   set owner [selection own]

   if {$owner == $textwidget} {
      #clear clipboard
      clipboard clear

      catch {
         # obtain the selection and append it to the clipboard
         set text [selection get]
         clipboard append $text

         # delete selected text
         $owner delete sel.first sel.last
         focus $textwidget
      }
   }
}

proc copy_text {textwidget} {
   # Copy text from text widget to clipboard. Returns nothing.
   # get the owner of the current selection (if any)
   set owner [selection own]

   if {$owner == $textwidget} {
      # clear clipboard
      clipboard clear

      catch {
         # append the current selection to the clipboard
         clipboard append [selection get]
      }
   }
}

proc paste_text {textwidget} {
   # Paste text from clipboard to text widget. Text is pasted at the
   # current cursor position if no text is selected. If text is selected,
   # the pasted text from the clipboard replaces it. Returns nothing.
   catch {
      # get text from clipboard
      set clip [selection get -selection CLIPBOARD]
   }

   # default location to insert data
   set idx [$textwidget index insert]

   # get the owner of the current selection (if any)
   set owner [selection own]

   if {$owner == $textwidget} {
      catch {
         # save index where selection starts
         set idx [$owner index sel.first]

         # delete selection
         $textwidget delete sel.first sel.last
      }
   }

   catch {
      # paste by inserting text from clipboard into text widget
      $textwidget insert $idx $clip
      focus $textwidget
   }
}
