Version 1 of handling of ANSI terminals using Expect

Updated 2003-08-25 07:08:59

There are a lot of network devices not supporting a raw mode but only ansi mode. To remove the ANSI sequences use:

  proc un_ansi {data} {
    set txt {}
    while {[string length ${data}]} {
      set match { }
      switch -regexp -- ${data} {
        {^\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]} {
             regexp -- {^\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]} ${data} match
             append txt "\n"
           }
        {^(.+?)\x1b} {
             regexp -- {^(.+?)\x1b} ${data} UNUSED match
             # handle special escape sequences
             regsub -all -- {\\([\\\[\]])} ${match} {\1} raw_match
             append txt ${raw_match}
           }
        {^\x1b} {
             # do nothing
           }
        default {
             set match ${data}
             append txt ${match}
           }
       }
       set data [string range ${data} [string length ${match}] end]
   }

   regsub -all -- "\t+" ${txt} { } txt
   regsub -all -- " +" ${txt} { } txt
   regsub -all -nocase -- "\n+" [string trim ${txt}] "\n" txt
   return ${txt}
  }