send special characters

Stefan Finzel

Now and then there is the need to handle special characters like CTRL-C e.g. to send special command sequences to devices using expect. To keep this in a more readable form this proc is useful.

As the representation of the characters is not common two formats are supported, e.g. <>TAB<> and >TAB< will both result in an tabulator character.

# ------------------------------------------------------------------------------

proc sendchar {cmds} {
    # --------------------------------------------------------------------------
    # translate character representation
    # --------------------------------------------------------------------------
    set chars ""
    foreach cmd ${cmds} {
        switch -glob -- [string toupper ${cmd}] {
            {>CTRL\+?<} {
                    # CTRL+A ... CTRL+Z
                    if {[scan [string index ${cmd} 5] %c cmd]} {
                        append chars "[format %c [expr {${cmd} - 64}]]"
                    }
                }
            {>RIGHT<} {
                    append chars "\x1b[C"
                }
            {>LEFT<} {
                    append chars "\x1b[D"
                }
            {>UP<} {
                    append chars "\x1b[A"
                }
            {>DOWN<} {
                    append chars "\x1b[B"
                }
            {>ESC<} {
                    append chars "\x1b"
                }
            {>RETURN<} {
                    append chars "\r"
                }
            {>TAB<} {
                    append chars "\t"
                }
            {>SPACE<} {
                    append chars " "
                }
            {<*>} {
                    regexp -- {<(.*)>} ${cmd} {} cmd
                    if {[string match {>*<} ${cmd}]} {
                        append chars [sendchar ${cmd}]
                    } else {
                        append chars ${cmd}
                    }
                }
            default {
                    puts stderr "invalid modifier\t'${cmd}'"
                }
        }
    }
    return ${chars}
}

FW: The formatting was broken here, I fixed it based on my best guess.


See also: