Updated 2012-09-25 21:36:53 by AK

EKB I wanted the feature (in many popular programmer's editors) of maintaining the indentation when I hit the "Enter" (or "Return") key to go to a new line. Here's what I came up with:
    proc handleEnterKey {w} {
        # First, delete the current selection
        if {[$w tag nextrange sel 1.0] != ""} {
            $w delete sel.first sel.last

        # Find the whitespace at the start of the current line
        set startl [$w index "insert linestart"]
        set endl [lindex [split $startl "."] 0].end
        regexp {^([ \t]*)} [$w get $startl $endl] -> ws

        # Create a newline, insert whitespace
        $w insert [$w index insert] "\n$ws"
        # If necessary, scroll the view so cursor is visible
        $w see [$w index insert]

    text .some.text.widget

    bind .some.text.widget <Return> {
        handleEnterKey %W
        # break, since we've already handled the Return

See also auto-indent