'write text at current cursor position and interpret color escapes.
return the number of characters written.'

def write_color(self, text, attr=None):

    if isinstance(attr, AnsiState):
        defaultstate = attr
    elif (attr is None):
        attr = self.defaultstate.copy()
    else:
        defaultstate = AnsiState()
        defaultstate.winattr = attr
        attr = defaultstate
    chunks = terminal_escape.split(text)
    n = 0
    res = []
    for chunk in chunks:
        m = escape_parts.match(chunk)
        if m:
            parts = m.group(1).split(u';')
            if ((len(parts) == 1) and (parts[0] == u'0')):
                attr = self.defaultstate.copy()
                continue
            for part in parts:
                if (part == u'0'):
                    attr = self.defaultstate.copy()
                    attr.bold = False
                elif (part == u'7'):
                    attr.inverse = True
                elif (part == u'1'):
                    attr.bold = True
                elif ((len(part) == 2) and (u'30' <= part <= u'37')):
                    attr.color = trtable[(int(part) - 30)]
                elif ((len(part) == 2) and (u'40' <= part <= u'47')):
                    attr.backgroundcolor = trtable[(int(part) - 40)]
            continue
        n += len(chunk)
        if True:
            res.append((attr.copy(), chunk))
    return (n, res)
