class Dumb: name = 'dumb' def insert(self, s): assert self.i <= len(self.outc) if self.i == len(self.outc): self.outc.append(s) else: self.outc[self.i] = s self.i += 1 def do_backspace(self): self.i = max(0, self.i - 1) def do_tab(self): self.insert(' ') def do_newline(self): self.outs += ''.join(self.outc) + '\n' self.i = 0 self.outc = [] def do_careturn(self): self.i = 0 def do_esc(self, c): pass def do_delete(self): if self.i < len(self.outc): del self.outc[self.i] def handle_ctl(self, c): n = ord(c) if n == 8: self.do_backspace() elif n == 9: self.do_tab() elif n == 10: self.do_newline() elif n == 13: self.do_careturn() elif n == 27: self.do_esc(c) elif n == 127: self.do_delete() def handle_print(self, c): self.insert(c) def handle_8bit(self, c): pass def handle(self, c): n = ord(c) assert n >= 0 and n < 256 if n <= 27 or n == 127: self.handle_ctl(c) elif n < 127: self.handle_print(c) else: self.handle_8bit(c) def filter(self, s): self.i = 0 self.outc = [] self.outs = "" for c in s: self.handle(c) return self.outs + ''.join(self.outc) class XTerm(Dumb): name = 'xterm' ansi_colors = { '\033[30m': '[B:d]', '\033[30;0m': '[B:d]', '\033[30;1m': '[B:d:*]', '\033[31m': '[r:d]', '\033[31;0m': '[r:d]', '\033[31;1m': '[r:d:*]', '\033[32m': '[g:d]', '\033[32;0m': '[g:d]', '\033[32;1m': '[g:d:*]', '\033[33m': '[y:d]', '\033[33;0m': '[y:d]', '\033[33;1m': '[y:d:*]', '\033[34m': '[b:d]', '\033[34;0m': '[b:d]', '\033[34;1m': '[b:d:*]', '\033[35m': '[m:d]', '\033[35;0m': '[m:d]', '\033[35;1m': '[m:d:*]', '\033[36m': '[c:d]', '\033[36;0m': '[c:d]', '\033[36;1m': '[c:d:*]', '\033[37m': '[w:d]', '\033[37;0m': '[w:d]', '\033[37;1m': '[w:d:*]', '\033[39m': '[d:d]', '\033[39;0m': '[d:d]', '\033[39;1m': '[d:d:*]', } def filter(self, s): self.meta = [] return Dumb.filter(self, s) def do_esc(self, c): self.meta.append(c) def handle(self, c): if self.meta: self.meta.append(c) if c == 'm': s = ''.join(self.meta) if s in self.ansi_colors: #self.insert(self.ansi_colors[s]) pass self.meta = [] else: Dumb.handle(self, c)