Get a Pygments Lexer given a filename.
339564
def find_lexer_for_filename(filename):
    
    filename = filename or ''
    root, ext = os.path.splitext(filename)
    if ext in custom_extension_lexer_mapping:
        lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])
    else:
        try:
            lexer = get_lexer_for_filename(filename)
        except Exception:
            return TextLexer()
    return lexer
1055423
def rst(filename):
    '''
    
    '''
    content = codecs.open(filename, encoding='utf-8').read()
    for regex, replacement in PYPI_RST_FILTERS:
        content = re.sub(regex, replacement, content)
    return content
999900
def gen_filename_completions(self, word, filenames):
        
        if not word:
            return filenames
        else:
            trie = pygtrie.CharTrie()
            for filename in filenames:
                trie[filename] = filename
            return trie.iterkeys(prefix=word)
187216
def getsourcefile(object):
    """"""
    filename = getfile(object)
    if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
1094137
def get(cls, filename):
        
        path = os.path.join(SparkFiles.getRootDirectory(), filename)
        return os.path.abspath(path)
722107
def get_all_lexers():
    
    for item in itervalues(LEXERS):
        yield item[1:]
    for lexer in find_plugin_lexers():
        yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes
1354113
def _handle_codeblock(self, match):
        
        from pygments.lexers import get_lexer_by_name

        # section header
        yield match.start(1), String        , match.group(1)
        yield match.start(2), String        , match.group(2)
        yield match.start(3), Text          , match.group(3)

        # lookup lexer if wanted and existing
        lexer = None
        if self.handlecodeblocks:
            try:
                lexer = get_lexer_by_name( match.group(2).strip() )
            except ClassNotFound:
                pass
        code = match.group(4)

        # no lexer for this language. handle it like it was a code block
        if lexer is None:
            yield match.start(4), String, code
            return

        for item in do_insertions([], lexer.get_tokens_unprocessed(code)):
            yield item

        yield match.start(5), String        , match.group(5)
588609
def lex_document(self, document):
        
        location = self.editor_buffer.location

        if location:
            if self.editor_buffer.in_file_explorer_mode:
                return PygmentsLexer(DirectoryListingLexer, sync_from_start=False).lex_document(document)

            return PygmentsLexer.from_filename(location, sync_from_start=False).lex_document(document)

        return SimpleLexer().lex_document(document)
963066
def from_file(filename, mime=False):
    "
    m = _get_magic_type(mime)
    return m.from_file(filename)
1112318
def punify_filename(filename):
    
    path, extension = splitext(filename)
    return path.encode('punycode').decode('utf8') + extension
897729
def filename_to_str(self, filename):
        '''
        
        '''
        if filename.__class__ != str:
            if not IS_PY3K:
                filename = filename.encode(file_system_encoding)
            else:
                raise AssertionError('Expected to have str on Python 3. Found: %s (%s)' % (filename, filename.__class__))
        return filename
391692
def lexer(self):
        

        try:
            lexer = lexers.guess_lexer_for_filename(self.name, self.content, stripnl=False)
        except lexers.ClassNotFound:
            lexer = lexers.TextLexer(stripnl=False)
        # returns first alias
        return lexer
812734
def decode_filename(filename):
    """"""
    if isinstance(filename, unicode):
        return filename

    return filename.decode(sys.getfilesystemencoding())
1295113
def _tokenize(self, source, name, filename=None, state=None):
        
        source = self.preprocess(source, name, filename)
        stream = self.lexer.tokenize(source, name, filename, state)
        for ext in self.iter_extensions():
            stream = ext.filter_stream(stream)
            if not isinstance(stream, TokenStream):
                stream = TokenStream(stream, name, filename)
        return stream
380091
def detect_encoding(filename):
    """"""
    try:
        with open(filename, 'rb') as input_file:
            from lib2to3.pgen2 import tokenize as lib2to3_tokenize
            encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]

            # Check for correctness of encoding.
            with open_with_encoding(filename, encoding) as input_file:
                input_file.read()

        return encoding
    except (SyntaxError, LookupError, UnicodeDecodeError):
        return 'latin-1'
868711
def get_parser():
    
    desc = Colors.LIGHTBLUE + textwrap.dedent(
        '''\
        Welcome to
                      _                           _                            _
           __ _ _   _| |_ ___      _ __  _   _   | |_ ___  _ __ _ __ ___ _ __ | |_
          / _` | | | | __/ _ \    | '_ \| | | |  | __/ _ \| '__| '__/ _ \ '_ \| __|
         | (_| | |_| | || (_) |   | |_) | |_| |  | || (_) | |  | | |  __/ | | | |_
          \__,_|\__,_|\__\___/____| .__/ \__, |___\__\___/|_|  |_|  \___|_| |_|\__|
                            |_____|_|    |___/_____|

        ------------------------------------
          auto_py_torrent is an automated tool for download files by obtaining
        torrents or magnets that are in different provided pages that the
        user can choose.

          Its goal is to make it easier for users to find the files they want
        and download them instantly.

          An auto_py_torrent command is provided in which the user can
        currently choose between two modes, best_rated and list mode, then it
        selects one of the torrent tracking pages for multimedia content and
        finally enter the text of what you want to download.
        ------------------------------------
        ''') + Colors.ENDC
    usage_info = Colors.LGREEN + textwrap.dedent(
        '''\

        Use "%(prog)s --help" for more information.
        Examples:
            use "%(prog)s MODE SELECTED_PAGE STRING_TO_SEARCH # generic.
            use "%(prog)s 0 0 "The simpsons" # best rated.
            use "%(prog)s 1 0 "The simpsons" # list rated.

        Mode options:
            0: best_rated. # Download the most rated file.
            1: list. # Get a list, and select one of them.

        Page list options:
            0: torrent project.
            1: the pirate bay.
            2: 1337x.
            3: eztv.
            4: limetorrents.
            5: isohunt.
        ''') + Colors.ENDC
    epi = Colors.LIGHTPURPLE + textwrap.dedent(
        '''\
        -> Thanks for using auto_py_torrent!
        ''') + Colors.ENDC

    # Parent and only parser.
    parser = argparse.ArgumentParser(
        add_help=True,
        formatter_class=argparse.RawTextHelpFormatter,
        usage=usage_info,
        description=desc,
        epilog=epi)
    parser.add_argument('mode', action='store',
                        choices=range(len(MODES)),
                        type=int,
                        help='Select mode of file download.\n'
                             '    e.g: 0(rated) or 1(list).')
    parser.add_argument('torr_page', action='store',
                        choices=range(len(TORRENTS)),
                        type=int,
                        help='Select tracking page to download from.\n'
                             '    e.g: 0 to .. ' + str(len(TORRENTS)-1) + '.')
    parser.add_argument('str_search', action='store',
                        type=str,
                        help='Input torrent string to search.\n'
                             '    e.g: "String search"')
    return(parser)
765772
def highlight_text(text, lexer_name='python', **kwargs):
    
    """
    # Resolve extensions to languages
    lexer_name = {
        'py': 'python',
        'h': 'cpp',
        'cpp': 'cpp',
        'c': 'cpp',
    }.get(lexer_name.replace('.', ''), lexer_name)
    if lexer_name in ['red', 'yellow', 'blue', 'green']:
        # hack for coloring
        return color_text(text, lexer_name)
    import utool as ut
    if ENABLE_COLORS:
        try:
            import pygments
            import pygments.lexers
            import pygments.formatters
            #from pygments import highlight
            #from pygments.lexers import get_lexer_by_name
            #from pygments.formatters import TerminalFormatter
            #if ut.WIN32:
            #    assert False
            #    #formater = pygments.formatters.terminal256.Terminal256Formatter()
            #    import pygments.formatters.terminal256
            #    formater = pygments.formatters.terminal256.Terminal256Formatter()
            #else:
            import pygments.formatters.terminal
            formater = pygments.formatters.terminal.TerminalFormatter(bg='dark')
            lexer = pygments.lexers.get_lexer_by_name(lexer_name, **kwargs)
            return pygments.highlight(text, lexer, formater)
        except Exception:
            if ut.SUPER_STRICT:
                raise
            return text
    return text