Posted to tcl by kbk at Sun Aug 03 22:06:37 GMT 2008view pretty

#----------------------------------------------------------------------
#
# backslashify --
#
#	Converts a UTF-8 string to a plain ASCII one with escapes.
#
# Parameters:
#	string -- String to convert
#
# Results:
#	Returns the converted string
#
# Side effects:
#	None.
#
#----------------------------------------------------------------------

proc backslashify { string } {

    set retval {}
    foreach char [split $string {}] {
	scan $char %c ccode
	if { $ccode >= 0x0020 && $ccode < 0x007f
	     && $char ne "\"" && $char ne "'"
	     && $char ne "\{" && $char ne "\}" && $char ne "\["
	     && $char ne "\]" && $char ne "\\" && $char ne "\$" } {
	    append retval $char
	} elseif {$ccode < 0x100} {
	    append retval \\ [format %03o $ccode]
	} else {
	    append retval \\u [format %04x $ccode]
	}
    }
    return $retval
}