Version 2 of Balancing Open and Close Quotes in a TK text widget.

Updated 2007-11-14 21:02:42 by dkf

WJG (04/11/07) Here's the gnocl::text equivalent. Those who already use gnocl may be aware that the current release has no text bindings for either the widget or tags. I use a development version which has the appropriate bindings. For those who are interested, before the next official release occurs, send me an email and I can forward details.


#---------------
# gncolBalanceQuotes.tcl
#---------------
# William J Giddings
# 04/11/07
#---------------
# Enable context sensitive quotations.
# If the input quote mark is preceded by a printable character,
# then closequote otherwise openquote!
#
#---------------
# Notes:
# This is not "smart" and so does attempt to ballance quote marks.
# The swap is made on the KeyRelease event so the swap will only
# effect the final quote if a key repeat event occurs.
#---------------

#!/bin/sh \
exec tclsh  "$0" "$@"

package require Gnocl     ;# Tcl-Gtk+ bindings

#---------------
# w    text widget into which the substition is to be made
# c    character currently inserted
#
# Codes:
#         single openquote   `   \u2018
#                closequote  '   \u2019
#         double openquote   "   \u201C
#                closequote  "   \u201D
#
#         '      quoteright
#         #      quotedbl
#---------------

proc balanceQuotes {w c} {
    #get the preceding character
    set idx [ $w getCursor ]
    set str [ $w get cursor-1 ]
    if {$str == "" || [string is space $str] || $str == "\u2018" || $str == "\u201C" } {
        set str " "
    }

    # if the last code entered was '
    if {$c == "quoteright" } {
        $w erase cursor
        if {$str == " "} {
            # openquote
            $w insert cursor "\u2018"
        } else  {
            # closequote
            $w insert cursor "\u2019"
        }
    }

    # or, if was "
    if {$c == "quotedbl" } {
        $w erase cursor
        if {$str == " "} {
            # openquote
            $w insert cursor "\u201C"
        } else  {
            # closequote
            $w insert cursor "\u201D"
        }
    }
}

#---------------
# Demo
#---------------
set txt [gnocl::text -baseFont {Sans 25} \
        -onKeyRelease {balanceQuotes %w %K}]
gnocl::window -title BalanceQuotes \
        -child $txt \
        -onDestroy exit \
        -width 250