Sunday, April 22, 2012

Substring markup

I find the Tcl string map subcommand very useful and use it quite extensively in text manipulation. Here's an example of where I wanted to highlight substrings within a piece of text using pango markup.

# test-substring-markup.tcl
exec tclsh "$0" "$@"
package require Gnocl

# search for str2 in str1, then add pango markup formatting
proc markup_substring {str1 str2 format} {
    # add necessary quote marks around property values
    set format [string map [list = =\" { } {" }] "$format "]
    set str3 "<span $format>$str2</span>" ;#"
    return [string map [list $str2 $str3] $str1 ]

set lab [gnocl::label]
gnocl::window -child $lab -setSize 0.25

# set string text
set str "how now brown cow"

# markup first word
set str [markup_substring $str brown "foreground=red weight=bold background=yellow"]

# cascaded markup is possible but, problems will happen if the search string matches the markup statements.
set str [markup_substring $str cow "foreground=white underline=double background=black"]

$lab configure -text $str

No comments: