Find and print all known escape codes in a string,
        using get_known_codes.
517346
def list_known_codes(s, unique=True, rgb_mode=False):
    
    total = 0
    for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
        total += 1
        print(codedesc)
    plural = 'code' if total == 1 else 'codes'
    codetype = ' unique' if unique else ''
    print('\nFound {}{} escape {}.'.format(total, codetype, plural))
    return 0 if total > 0 else 1
766275
def parse_keys(string,
                with_spaces = False,
                with_tabs = False,
                with_newlines = False,
                modifiers = None):
    ""

    keys = []
    if not modifiers:
        modifiers = []
    index = 0
    while index < len(string):

        c = string[index]
        index += 1
        # check if one of CTRL, SHIFT, ALT has been pressed
        if c in MODIFIERS.keys():
            modifier = MODIFIERS[c]
            # remember that we are currently modified
            modifiers.append(modifier)
            # hold down the modifier key
            keys.append(VirtualKeyAction(modifier, up = False))
            if DEBUG:
                print("MODS+", modifiers)
            continue

        # Apply modifiers over a bunch of characters (not just one!)
        elif c == "(":
            # find the end of the bracketed text
            end_pos = string.find(")", index)
            if end_pos == -1:
                raise KeySequenceError('`)` not found')
            keys.extend(
                parse_keys(string[index:end_pos], modifiers = modifiers))
            index = end_pos + 1

        # Escape or named key
        elif c == "{":
            # We start searching from index + 1 to account for the case {}}
            end_pos = string.find("}", index + 1)
            if end_pos == -1:
                raise KeySequenceError('`}` not found')

            code = string[index:end_pos]
            index = end_pos + 1
            keys.extend(handle_code(code))

        # unmatched ")"
        elif c == ')':
            raise KeySequenceError('`)` should be preceeded by `(`')

        # unmatched "}"
        elif c == '}':
            raise KeySequenceError('`}` should be preceeded by `{`')

        # so it is a normal character
        else:
            # don't output white space unless flags to output have been set
            if (c == ' ' and not with_spaces or
                c == '\t' and not with_tabs or
                c == '\n' and not with_newlines):
                continue

            # output nuewline
            if c in ('~', '\n'):
                keys.append(VirtualKeyAction(CODES["ENTER"]))

            # safest are the virtual keys - so if our key is a virtual key
            # use a VirtualKeyAction
            #if ord(c) in CODE_NAMES:
            #    keys.append(VirtualKeyAction(ord(c)))

            elif modifiers:
                keys.append(EscapedKeyAction(c))

            else:
                keys.append(KeyAction(c))

        # as we have handled the text - release the modifiers
        while modifiers:
            if DEBUG:
                print("MODS-", modifiers)
            keys.append(VirtualKeyAction(modifiers.pop(), down = False))

    # just in case there were any modifiers left pressed - release them
    while modifiers:
        keys.append(VirtualKeyAction(modifiers.pop(), down = False))

    return keys
137836
def _escape_markdown_literals(string):
    
    literals = list("\\`*_{}[]()<>#+-.!:|")
    escape = lambda c: '\\' + c if c in literals else c
    return "".join(map(escape, string))
486376
def decompose_code(code):
    
    code = "%-6s" % code
    ind1 = code[3:4]
    if ind1 == " ": ind1 = "_"
    ind2 = code[4:5]
    if ind2 == " ": ind2 = "_"
    subcode = code[5:6]
    if subcode == " ": subcode = None
    return (code[0:3], ind1, ind2, subcode)
1217987
def _escape(value):
        
        value = str(value)
        for char, escaped in {' ': '\ ', ',': '\,', '"': '\"'}.items():
            value = value.replace(char, escaped)
        return value
1043691
def _context_string(context):
    """"""
    msg = 'Code block context:\n            '
    lines = ['Selective arithmetic coding bypass:  {0}',
             'Reset context probabilities on coding pass boundaries:  {1}',
             'Termination on each coding pass:  {2}',
             'Vertically stripe causal context:  {3}',
             'Predictable termination:  {4}',
             'Segmentation symbols:  {5}']
    msg += '\n            '.join(lines)
    msg = msg.format(((context & 0x01) > 0),
                     ((context & 0x02) > 0),
                     ((context & 0x04) > 0),
                     ((context & 0x08) > 0),
                     ((context & 0x10) > 0),
                     ((context & 0x20) > 0))
    return msg
153136
def Escape(self, string="", **_):
    """"""
    # Translate special escapes:
    self.stack[-1] += self.STRING_ESCAPES.get(string, string)
1097761
def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]:
    
    codes = get_code_indices(s)
    if not codes:
        # This function is not for non-escape-code stuff, but okay.
        return {i: c for i, c in enumerate(s)}

    indices = {}
    for codeindex in sorted(codes):
        code = codes[codeindex]
        if codeindex == 0:
            indices[codeindex] = code
            continue
        # Grab characters before codeindex.
        start = max(indices or {0: ''}, key=int)
        startcode = indices.get(start, '')
        startlen = start + len(startcode)
        indices.update({i: s[i] for i in range(startlen, codeindex)})
        indices[codeindex] = code

    if not indices:
        return {i: c for i, c in enumerate(s)}
    lastindex = max(indices, key=int)
    lastitem = indices[lastindex]
    start = lastindex + len(lastitem)
    textlen = len(s)
    if start < (textlen - 1):
        # Grab chars after last code.
        indices.update({i: s[i] for i in range(start, textlen)})
    return indices
1330919
def extract_value(self, string, key, inline_code=True):
        
        regex = r'\* ' + key + ': '
        if inline_code:
            regex = regex + '``(.*)``'
        else:
            regex = regex + '(.*)'
        value = re.findall(regex, string)
        if value:
            return value[0].replace('``', '')
        else:
            return False
268090
def _escape(self, msg):
        
        escaped = ''	
        for c in msg: 
            escaped += c
            if c == '"':
                escaped += '"'
        return escaped
1281808
def find_matches(text):
    
    """
    path = os.path.expanduser(text)
    if os.path.isdir(path) and not path.endswith('/'):
        return [ text + '/' ]

    pattern = path + '*'
    is_implicit_cwd = not (path.startswith('/') or path.startswith('./'))
    if is_implicit_cwd:
        pattern = './' + pattern
    rawlist = glob.glob(pattern)
    ret = []
    for fname in rawlist:
        if is_implicit_cwd:
            fname = fname[2:]
        if os.path.isdir(fname):
            ret.append(fname + '/')
        else:
            ret.append(fname)
    return ret
248500
def string(s):
    
    ret = ['"']
    for c in s:
        if ' ' <= c < '\x7f':
            if c == "'" or c == '"' or c == '\\':
                ret.append('\\')
            ret.append(c)
            continue
        elif c <= '\x7f':
            if c in ('\r', '\n', '\t'):
                # unicode-escape produces bytes
                ret.append(c.encode('unicode-escape').decode("ascii"))
                continue
        i = ord(c)
        ret.append('\\u')
        ret.append('%x' % (i >> 12))
        ret.append('%x' % ((i >> 8) & 0x0f))
        ret.append('%x' % ((i >> 4) & 0x0f))
        ret.append('%x' % (i & 0x0f))
    ret.append('"')
    return ''.join(ret)
429834
def _escaped(self):
        

        chars = self._token_info['chars']
        count = len(chars)

        # prev char is escape, keep going
        if count and chars[count - 1] == self.ESCAPE:
            chars.pop()  # swallow escape char
            return True
        else:
            return False
1028919
def _escape_str(value):
        

        if isinstance(value, int):
            return "%d" % value
        value = value.replace("\\", r'\\')
        for i, j in ts3_escape.items():
            value = value.replace(i, j)
        return value
571574
def _get_keycodes():
    
    try:
        return _key_cache.pop()
    except IndexError:
        pass
    result = []
    terminators = 'ABCDFHPQRS~'
    with TerminalContext():
        code = get_ord()
        result.append(code)
        if code == 27:
            with TimerContext(0.1) as timer:
                code = get_ord()
            if not timer.timed_out:
                result.append(code)
                result.append(get_ord())
                if 64 < result[-1] < 69:
                    pass
                elif result[1] == 91:
                    while True:
                        code = get_ord()
                        result.append(code)
                        if chr(code) in terminators:
                            break
    return tuple(result)
1277473
def find_prototypes(code):
    

    prots = []
    lines = code.split('\n')
    for line in lines:
        m = re.match("\s*" + re_func_prot, line)
        if m is not None:
            rtype, name, args = m.groups()[:3]
            if args == 'void' or args.strip() == '':
                args = []
            else:
                args = [tuple(arg.strip().split(' '))
                        for arg in args.split(',')]
            prots.append((name, args, rtype))

    return prots
493614
def p_encaps_list_string(p):
    ''
    if p[1] == '':
        p[0] = p[2].decode('string_escape')
    else:
        p[0] = ast.BinaryOp('.', p[1], p[2].decode('string_escape'),
                            lineno=p.lineno(2))