Updated 2015-09-02 21:03:39 by pooryorick

WJG 2006-04-15: The standard Tcl string command does allow the formatting of titles, however, it only capitalizes the first letter of the word. What if want to create a title from a whole string or a selection from within a text widget? The following code segment may help. Based upon English usage, it will scan each word of the selection and then determine whether or not to capitalize the first letter. In short, it will capitalize anything except those words in an exception list. Such words are ones that are by custom left in lower case; typically conjuctions, common verbs and prepostions. Any way, have a play..
proc case:title {} {
    set w [selection own]

    set first [$w index sel.first]
    set a [$w get sel.first sel.last]
    foreach word $a {
        #ignore certain words
        switch  -- $word {
            if -
            for -
            of -
            the -
            that -
            this -
            have -
            is -
            be -
            are -
            have -
            has -
            had -
            a -
            as -
            to -
            or -
            in -
            on -
            an -
            at -
            with -
            you -
            your -
            and { }
            default {
                # append word to output string
                set word [string totitle $word]
                }
        }
        append b "$word "
        }
        $w delete sel.first sel.last
        # trim away whitespace
        set b [string trimright $b]
        set b [string trimright $b .]
        # make sure initial is always capital
        set b [string totitle $b 0 0]
        $w insert $first $b
    }

proc demo {} {
    console show
    puts [string totitle "how now brown cow"]
    pack [button .but -text Title -command case:title] -side top -anchor nw
    pack [text .txt] -fill both -side top -anchor nw
}

demo


[Category Example String Processing]