Python pygments.util.ClassNotFound() Examples

The following are 30 code examples of pygments.util.ClassNotFound(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygments.util , or try the search function .
Example #1
Source File: mistune_markdown.py    From Django-blog with MIT License 6 votes vote down vote up
def block_code(self, code, lang=None):
        """Rendering block level code. ``pre > code``.

        :param code: text content of the code block.
        :param lang: language of the given code.
        """
        code = code.rstrip('\n')  # 去掉尾部的换行符
        # 如果没有lang, 就返回代码块
        if not lang:
            code = mistune.escape(code)
            return '<pre><code>%s\n</code></pre>\n' % code

        # 给代码加上高亮  例如: lang='python'的话
        # ```python
        #   print('666')
        # ```
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except ClassNotFound:
            # 如果lang是不合法, 没有匹配到, 就设置为python
            lexer = get_lexer_by_name('python', stripall=True)
        formatter = html.HtmlFormatter()  # linenos=True
        return highlight(code, lexer, formatter) 
Example #2
Source File: __init__.py    From pigaios with GNU General Public License v3.0 6 votes vote down vote up
def get_formatter_for_filename(fn, **options):
    """Lookup and instantiate a formatter by filename pattern.

    Raises ClassNotFound if not found.
    """
    fn = basename(fn)
    for modname, name, _, filenames, _ in itervalues(FORMATTERS):
        for filename in filenames:
            if _fn_matches(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name](**options)
    for cls in find_plugin_formatters():
        for filename in cls.filenames:
            if _fn_matches(fn, filename):
                return cls(**options)
    raise ClassNotFound("no formatter found for file name %r" % fn) 
Example #3
Source File: pygments_sh.py    From Turing with MIT License 6 votes vote down vote up
def set_lexer_from_filename(self, filename):
        """
        Change the lexer based on the filename (actually only the extension is
        needed)

        :param filename: Filename or extension
        """
        self._lexer = None
        if filename.endswith("~"):
            filename = filename[0:len(filename) - 1]
        try:
            self._lexer = get_lexer_for_filename(filename)
        except (ClassNotFound, ImportError):
            print('class not found for url', filename)
            try:
                m = mimetypes.guess_type(filename)
                print(m)
                self._lexer = get_lexer_for_mimetype(m[0])
            except (ClassNotFound, IndexError, ImportError):
                self._lexer = get_lexer_for_mimetype('text/plain')
        if self._lexer is None:
            _logger().warning('failed to get lexer from filename: %s, using '
                              'plain text instead...', filename)
            self._lexer = TextLexer() 
Example #4
Source File: __init__.py    From pigaios with GNU General Public License v3.0 6 votes vote down vote up
def get_lexer_by_name(_alias, **options):
    """Get a lexer by an alias.

    Raises ClassNotFound if not found.
    """
    if not _alias:
        raise ClassNotFound('no lexer for alias %r found' % _alias)

    # lookup builtin lexers
    for module_name, name, aliases, _, _ in itervalues(LEXERS):
        if _alias.lower() in aliases:
            if name not in _lexer_cache:
                _load_lexers(module_name)
            return _lexer_cache[name](**options)
    # continue with lexers from setuptools entrypoints
    for cls in find_plugin_lexers():
        if _alias in cls.aliases:
            return cls(**options)
    raise ClassNotFound('no lexer for alias %r found' % _alias) 
Example #5
Source File: __init__.py    From pigaios with GNU General Public License v3.0 6 votes vote down vote up
def guess_lexer(_text, **options):
    """Guess a lexer by strong distinctions in the text (eg, shebang)."""

    # try to get a vim modeline first
    ft = get_filetype_from_buffer(_text)

    if ft is not None:
        try:
            return get_lexer_by_name(ft, **options)
        except ClassNotFound:
            pass

    best_lexer = [0.0, None]
    for lexer in _iter_lexerclasses():
        rv = lexer.analyse_text(_text)
        if rv == 1.0:
            return lexer(**options)
        if rv > best_lexer[0]:
            best_lexer[:] = (rv, lexer)
    if not best_lexer[0] or best_lexer[1] is None:
        raise ClassNotFound('no lexer matching the text found')
    return best_lexer[1](**options) 
Example #6
Source File: __init__.py    From pigaios with GNU General Public License v3.0 6 votes vote down vote up
def get_style_by_name(name):
    if name in STYLE_MAP:
        mod, cls = STYLE_MAP[name].split('::')
        builtin = "yes"
    else:
        for found_name, style in find_plugin_styles():
            if name == found_name:
                return style
        # perhaps it got dropped into our styles package
        builtin = ""
        mod = name
        cls = name.title() + "Style"

    try:
        mod = __import__('pygments.styles.' + mod, None, None, [cls])
    except ImportError:
        raise ClassNotFound("Could not find style module %r" % mod +
                         (builtin and ", though it should be builtin") + ".")
    try:
        return getattr(mod, cls)
    except AttributeError:
        raise ClassNotFound("Could not find style class %r in style module." % cls) 
Example #7
Source File: pygments_sh.py    From Turing with MIT License 6 votes vote down vote up
def _update_style(self):
        """ Sets the style to the specified Pygments style.
        """
        try:
            self._style = get_style_by_name(self._pygments_style)
        except ClassNotFound:
            # unknown style, also happen with plugins style when used from a
            # frozen app.
            if self._pygments_style == 'qt':
                from pyqode.core.styles import QtStyle
                self._style = QtStyle
            elif self._pygments_style == 'darcula':
                from pyqode.core.styles import DarculaStyle
                self._style = DarculaStyle
            else:
                self._style = get_style_by_name('default')
                self._pygments_style = 'default'
        self._clear_caches() 
Example #8
Source File: pygments.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_filename(
        cls, filename: str, sync_from_start: FilterOrBool = True
    ) -> "Lexer":
        """
        Create a `Lexer` from a filename.
        """
        # Inline imports: the Pygments dependency is optional!
        from pygments.util import ClassNotFound
        from pygments.lexers import get_lexer_for_filename

        try:
            pygments_lexer = get_lexer_for_filename(filename)
        except ClassNotFound:
            return SimpleLexer()
        else:
            return cls(pygments_lexer.__class__, sync_from_start=sync_from_start) 
Example #9
Source File: __init__.py    From komodo-wakatime with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def find_lexer_class_by_name(_alias):
    """Lookup a lexer class by alias.

    Like `get_lexer_by_name`, but does not instantiate the class.

    .. versionadded:: 2.2
    """
    if not _alias:
        raise ClassNotFound('no lexer for alias %r found' % _alias)
    # lookup builtin lexers
    for module_name, name, aliases, _, _ in itervalues(LEXERS):
        if _alias.lower() in aliases:
            if name not in _lexer_cache:
                _load_lexers(module_name)
            return _lexer_cache[name]
    # continue with lexers from setuptools entrypoints
    for cls in find_plugin_lexers():
        if _alias.lower() in cls.aliases:
            return cls
    raise ClassNotFound('no lexer for alias %r found' % _alias) 
Example #10
Source File: __init__.py    From komodo-wakatime with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_style_by_name(name):
    if name in STYLE_MAP:
        mod, cls = STYLE_MAP[name].split('::')
        builtin = "yes"
    else:
        for found_name, style in find_plugin_styles():
            if name == found_name:
                return style
        # perhaps it got dropped into our styles package
        builtin = ""
        mod = name
        cls = name.title() + "Style"

    try:
        mod = __import__('pygments.styles.' + mod, None, None, [cls])
    except ImportError:
        raise ClassNotFound("Could not find style module %r" % mod +
                         (builtin and ", though it should be builtin") + ".")
    try:
        return getattr(mod, cls)
    except AttributeError:
        raise ClassNotFound("Could not find style class %r in style module." % cls) 
Example #11
Source File: __init__.py    From komodo-wakatime with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_formatter_for_filename(fn, **options):
    """Lookup and instantiate a formatter by filename pattern.

    Raises ClassNotFound if not found.
    """
    fn = basename(fn)
    for modname, name, _, filenames, _ in itervalues(FORMATTERS):
        for filename in filenames:
            if _fn_matches(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name](**options)
    for cls in find_plugin_formatters():
        for filename in cls.filenames:
            if _fn_matches(fn, filename):
                return cls(**options)
    raise ClassNotFound("no formatter found for file name %r" % fn) 
Example #12
Source File: snippets.py    From diff_cover with Apache License 2.0 6 votes vote down vote up
def _parse_src(cls, src_contents, src_filename):
        """
        Return a stream of `(token_type, value)` tuples
        parsed from `src_contents` (str)

        Uses `src_filename` to guess the type of file
        so it can highlight syntax correctly.
        """

        # Parse the source into tokens
        try:
            lexer = guess_lexer_for_filename(src_filename, src_contents)
        except ClassNotFound:
            lexer = TextLexer()

        # Ensure that we don't strip newlines from
        # the source file when lexing.
        lexer.stripnl = False

        return pygments.lex(src_contents, lexer) 
Example #13
Source File: pygments_sh.py    From Turing with MIT License 6 votes vote down vote up
def set_mime_type(self, mime_type):
        """
        Update the highlighter lexer based on a mime type.

        :param mime_type: mime type of the new lexer to setup.
        """
        try:
            self.set_lexer_from_mime_type(mime_type)
        except ClassNotFound:
            _logger().exception('failed to get lexer from mimetype')
            self._lexer = TextLexer()
            return False
        except ImportError:
            # import error while loading some pygments plugins, the editor
            # should not crash
            _logger().warning('failed to get lexer from mimetype (%s)' %
                              mime_type)
            self._lexer = TextLexer()
            return False
        else:
            return True 
Example #14
Source File: syntax_highlighter.py    From Turing with MIT License 6 votes vote down vote up
def __init__(self, style):
        """
        :param style: name of the pygments style to load
        """
        self._name = style
        self._brushes = {}
        #: Dictionary of formats colors (keys are the same as for
        #: :attr:`pyqode.core.api.COLOR_SCHEME_KEYS`
        self.formats = {}
        try:
            style = get_style_by_name(style)
        except ClassNotFound:
            if style == 'darcula':
                from pyqode.core.styles.darcula import DarculaStyle
                style = DarculaStyle
            else:
                from pyqode.core.styles.qt import QtStyle
                style = QtStyle
        self._load_formats_from_style(style) 
Example #15
Source File: textfmts.py    From pigaios with GNU General Public License v3.0 6 votes vote down vote up
def content_callback(self, match):
        content_type = getattr(self, 'content_type', None)
        content = match.group()
        offset = match.start()
        if content_type:
            from pygments.lexers import get_lexer_for_mimetype
            possible_lexer_mimetypes = [content_type]
            if '+' in content_type:
                # application/calendar+xml can be treated as application/xml
                # if there's not a better match.
                general_type = re.sub(r'^(.*)/.*\+(.*)$', r'\1/\2',
                                      content_type)
                possible_lexer_mimetypes.append(general_type)

            for i in possible_lexer_mimetypes:
                try:
                    lexer = get_lexer_for_mimetype(i)
                except ClassNotFound:
                    pass
                else:
                    for idx, token, value in lexer.get_tokens_unprocessed(content):
                        yield offset + idx, token, value
                    return
        yield offset, Text, content 
Example #16
Source File: pgstyle.py    From pgcli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native").styles

    for token in cli_style:
        if token.startswith("Token."):
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error("Unhandled style / class name: %s", token)

    class OutputStyle(PygmentsStyle):
        default_style = ""
        styles = style

    return OutputStyle 
Example #17
Source File: __init__.py    From pySINDy with MIT License 6 votes vote down vote up
def get_formatter_for_filename(fn, **options):
    """Lookup and instantiate a formatter by filename pattern.

    Raises ClassNotFound if not found.
    """
    fn = basename(fn)
    for modname, name, _, filenames, _ in itervalues(FORMATTERS):
        for filename in filenames:
            if _fn_matches(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name](**options)
    for cls in find_plugin_formatters():
        for filename in cls.filenames:
            if _fn_matches(fn, filename):
                return cls(**options)
    raise ClassNotFound("no formatter found for file name %r" % fn) 
Example #18
Source File: __init__.py    From pySINDy with MIT License 6 votes vote down vote up
def get_style_by_name(name):
    if name in STYLE_MAP:
        mod, cls = STYLE_MAP[name].split('::')
        builtin = "yes"
    else:
        for found_name, style in find_plugin_styles():
            if name == found_name:
                return style
        # perhaps it got dropped into our styles package
        builtin = ""
        mod = name
        cls = name.title() + "Style"

    try:
        mod = __import__('pygments.styles.' + mod, None, None, [cls])
    except ImportError:
        raise ClassNotFound("Could not find style module %r" % mod +
                         (builtin and ", though it should be builtin") + ".")
    try:
        return getattr(mod, cls)
    except AttributeError:
        raise ClassNotFound("Could not find style class %r in style module." % cls) 
Example #19
Source File: __init__.py    From pySINDy with MIT License 6 votes vote down vote up
def find_lexer_class_by_name(_alias):
    """Lookup a lexer class by alias.

    Like `get_lexer_by_name`, but does not instantiate the class.

    .. versionadded:: 2.2
    """
    if not _alias:
        raise ClassNotFound('no lexer for alias %r found' % _alias)
    # lookup builtin lexers
    for module_name, name, aliases, _, _ in itervalues(LEXERS):
        if _alias.lower() in aliases:
            if name not in _lexer_cache:
                _load_lexers(module_name)
            return _lexer_cache[name]
    # continue with lexers from setuptools entrypoints
    for cls in find_plugin_lexers():
        if _alias.lower() in cls.aliases:
            return cls
    raise ClassNotFound('no lexer for alias %r found' % _alias) 
Example #20
Source File: textfmts.py    From pygments with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def content_callback(self, match):
        content_type = getattr(self, 'content_type', None)
        content = match.group()
        offset = match.start()
        if content_type:
            from pygments.lexers import get_lexer_for_mimetype
            possible_lexer_mimetypes = [content_type]
            if '+' in content_type:
                # application/calendar+xml can be treated as application/xml
                # if there's not a better match.
                general_type = re.sub(r'^(.*)/.*\+(.*)$', r'\1/\2',
                                      content_type)
                possible_lexer_mimetypes.append(general_type)

            for i in possible_lexer_mimetypes:
                try:
                    lexer = get_lexer_for_mimetype(i)
                except ClassNotFound:
                    pass
                else:
                    for idx, token, value in lexer.get_tokens_unprocessed(content):
                        yield offset + idx, token, value
                    return
        yield offset, Text, content 
Example #21
Source File: __init__.py    From pySINDy with MIT License 6 votes vote down vote up
def guess_lexer(_text, **options):
    """Guess a lexer by strong distinctions in the text (eg, shebang)."""

    # try to get a vim modeline first
    ft = get_filetype_from_buffer(_text)

    if ft is not None:
        try:
            return get_lexer_by_name(ft, **options)
        except ClassNotFound:
            pass

    best_lexer = [0.0, None]
    for lexer in _iter_lexerclasses():
        rv = lexer.analyse_text(_text)
        if rv == 1.0:
            return lexer(**options)
        if rv > best_lexer[0]:
            best_lexer[:] = (rv, lexer)
    if not best_lexer[0] or best_lexer[1] is None:
        raise ClassNotFound('no lexer matching the text found')
    return best_lexer[1](**options) 
Example #22
Source File: textfmts.py    From pySINDy with MIT License 6 votes vote down vote up
def content_callback(self, match):
        content_type = getattr(self, 'content_type', None)
        content = match.group()
        offset = match.start()
        if content_type:
            from pygments.lexers import get_lexer_for_mimetype
            possible_lexer_mimetypes = [content_type]
            if '+' in content_type:
                # application/calendar+xml can be treated as application/xml
                # if there's not a better match.
                general_type = re.sub(r'^(.*)/.*\+(.*)$', r'\1/\2',
                                      content_type)
                possible_lexer_mimetypes.append(general_type)

            for i in possible_lexer_mimetypes:
                try:
                    lexer = get_lexer_for_mimetype(i)
                except ClassNotFound:
                    pass
                else:
                    for idx, token, value in lexer.get_tokens_unprocessed(content):
                        yield offset + idx, token, value
                    return
        yield offset, Text, content 
Example #23
Source File: jupyter_widget.py    From pySINDy with MIT License 6 votes vote down vote up
def _handle_kernel_info_reply(self, rep):
        """Handle kernel info replies."""
        content = rep['content']
        language_name = content['language_info']['name']
        pygments_lexer = content['language_info'].get('pygments_lexer', '')

        try:
            # Other kernels with pygments_lexer info will have to be
            # added here by hand.
            if pygments_lexer == 'ipython3':
                lexer = IPython3Lexer()
            elif pygments_lexer == 'ipython2':
                lexer = IPythonLexer()
            else:
                lexer = get_lexer_by_name(language_name)
            self._highlighter._lexer = lexer
        except ClassNotFound:
            pass

        self.kernel_banner = content.get('banner', '')
        if self._starting:
            # finish handling started channels
            self._starting = False
            super(JupyterWidget, self)._started_channels() 
Example #24
Source File: clistyle.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native").styles

    for token in cli_style:
        if token.startswith("Token."):
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error("Unhandled style / class name: %s", token)

    class OutputStyle(PygmentsStyle):
        default_style = ""
        styles = style

    return OutputStyle 
Example #25
Source File: operations.py    From wordinserter with MIT License 6 votes vote down vote up
def highlighted_operations(self):
        from pygments.lexers import get_lexer_by_name
        from pygments.util import ClassNotFound
        from pygments import highlight
        from pygments.formatters import get_formatter_by_name
        from wordinserter import parse
        import warnings

        try:
            formatter = get_formatter_by_name("html")
            lexer = get_lexer_by_name(self.highlight)
        except ClassNotFound:
            warnings.warn("Lexer {0} or formatter html not found, not highlighting".format(self.highlight))
            return None

        formatter.noclasses = True

        highlighted_code = highlight(self.text, lexer=lexer, formatter=formatter)
        return parse(highlighted_code, parser="html") 
Example #26
Source File: httpdomain.py    From couchdb-documentation with Apache License 2.0 6 votes vote down vote up
def content_callback(self, match):
        content_type = getattr(self, "content_type", None)
        content = match.group()
        offset = match.start()
        if content_type:
            from pygments.lexers import get_lexer_for_mimetype

            try:
                lexer = get_lexer_for_mimetype(content_type)
            except ClassNotFound:
                pass
            else:
                for idx, token, value in lexer.get_tokens_unprocessed(content):
                    yield offset + idx, token, value
                return
        yield offset, Text, content 
Example #27
Source File: __init__.py    From pygments with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def find_lexer_class_by_name(_alias):
    """Lookup a lexer class by alias.

    Like `get_lexer_by_name`, but does not instantiate the class.

    .. versionadded:: 2.2
    """
    if not _alias:
        raise ClassNotFound('no lexer for alias %r found' % _alias)
    # lookup builtin lexers
    for module_name, name, aliases, _, _ in LEXERS.values():
        if _alias.lower() in aliases:
            if name not in _lexer_cache:
                _load_lexers(module_name)
            return _lexer_cache[name]
    # continue with lexers from setuptools entrypoints
    for cls in find_plugin_lexers():
        if _alias.lower() in cls.aliases:
            return cls
    raise ClassNotFound('no lexer for alias %r found' % _alias) 
Example #28
Source File: __init__.py    From pygments with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_style_by_name(name):
    if name in STYLE_MAP:
        mod, cls = STYLE_MAP[name].split('::')
        builtin = "yes"
    else:
        for found_name, style in find_plugin_styles():
            if name == found_name:
                return style
        # perhaps it got dropped into our styles package
        builtin = ""
        mod = name
        cls = name.title() + "Style"

    try:
        mod = __import__('pygments.styles.' + mod, None, None, [cls])
    except ImportError:
        raise ClassNotFound("Could not find style module %r" % mod +
                         (builtin and ", though it should be builtin") + ".")
    try:
        return getattr(mod, cls)
    except AttributeError:
        raise ClassNotFound("Could not find style class %r in style module." % cls) 
Example #29
Source File: __init__.py    From pygments with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_formatter_for_filename(fn, **options):
    """Lookup and instantiate a formatter by filename pattern.

    Raises ClassNotFound if not found.
    """
    fn = basename(fn)
    for modname, name, _, filenames, _ in FORMATTERS.values():
        for filename in filenames:
            if _fn_matches(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name](**options)
    for cls in find_plugin_formatters():
        for filename in cls.filenames:
            if _fn_matches(fn, filename):
                return cls(**options)
    raise ClassNotFound("no formatter found for file name %r" % fn) 
Example #30
Source File: clistyle.py    From athenacli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native').styles

    for token in cli_style:
        if token.startswith('Token.'):
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error('Unhandled style / class name: %s', token)
        
        class OutputStyle(PygmentsStyle):
            default_style = ""
            styles = style
        
        return OutputStyle