Example #1
0
    def _identify_code_tabs(self, block_str):

        text = FencedCodeTabsPreprocessor._filter_content(block_str)

        while True:
            m = self.FENCE_BLOCK_REGEX.search(text)
            if m:

                first_line = text[m.start():].split('\n')[0]

                kwargs = {}
                for param, regex in PARAM_REGEXES.items():
                    param_m = regex.search(first_line)
                    if param_m:
                        if param_m.group(param):
                            kwargs[param] = param_m.group(param)
                        elif (not param_m.group(param) is None) and param in PARAM_DEFAULTS:
                            kwargs[param] = PARAM_DEFAULTS[param]
                        else:
                            raise Exception("{} needs an argument within \n{}".format(param, first_line))

                lang = ''
                label = ''

                if m.group('lang') and m.group('lang') not in PARAM_REGEXES:
                    lang = m.group('lang')
                    label = lang[0:1].capitalize() + lang[1:]

                if kwargs.get('fct_label'):
                    label =  kwargs.get('fct_label')

                if self.codehilite_conf:
                    highliter = CodeHilite(
                        m.group('code'),
                        linenums=self.codehilite_conf['linenums'][0],
                        guess_lang=self.codehilite_conf['guess_lang'][0],
                        css_class=self.codehilite_conf['css_class'][0],
                        style=self.codehilite_conf['pygments_style'][0],
                        lang=(m.group('lang') or None),
                        noclasses=self.codehilite_conf['noclasses'][0],
                        hl_lines=parse_hl_lines(kwargs.get('hl_lines'))
                    )

                    code = highliter.hilite()
                else:
                    code = self.TAB_ITEM_BODY_WRAP_ESCAPE % (lang,
                                                             self._escape(m.group('code')))

                self.tab_items.append(FencedCodeTabs(label, lang, code))

                placeholder = self.tab_item_placeholder.format(len(self.tab_items) - 1)

                text = "{}\n{}\n{}".format(text[:m.start()],
                                           placeholder,
                                           text[m.end():])

            else:
                break

        return text
Example #2
0
    def format_code(self, lang: str, text: str) -> str:
        if lang:
            langclass = LANG_TAG.format(lang)
        else:
            langclass = ''

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.md.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        # If config is not empty, then the codehighlite extension
        # is enabled, so we call it to highlite the code
        if self.codehilite_conf:
            highliter = CodeHilite(
                text,
                linenums=self.codehilite_conf['linenums'][0],
                guess_lang=self.codehilite_conf['guess_lang'][0],
                css_class=self.codehilite_conf['css_class'][0],
                style=self.codehilite_conf['pygments_style'][0],
                use_pygments=self.codehilite_conf['use_pygments'][0],
                lang=(lang or None),
                noclasses=self.codehilite_conf['noclasses'][0])

            code = highliter.hilite()
        else:
            code = CODE_WRAP.format(langclass, self._escape(text))

        # To support our "view in playground" feature, the frontend
        # needs to know what Pygments language was used for
        # highlighting this code block.  We record this in a data
        # attribute attached to the outer `pre` element.
        # Unfortunately, the pygments API doesn't offer a way to add
        # this, so we need to do it in a post-processing step.
        if lang:
            parsed_code = etree.HTML(code)
            div_tag = parsed_code[0][0]

            # For the value of our data element, we get the lexer
            # subclass name instead of directly using the language,
            # since that canonicalizes aliases (Eg: `js` and
            # `javascript` will be mapped to `JavaScript`).
            try:
                code_language = get_lexer_by_name(lang).name
            except ClassNotFound:
                # If there isn't a Pygments lexer by this name, we
                # still tag it with the user's data-code-language
                # value, since this allows hooking up a "playground"
                # for custom "languages" that aren't known to Pygments.
                code_language = lang

            div_tag.attrib['data-code-language'] = code_language
            # lxml implicitly converts tags like <span></span> into <span/>.
            # Specifying method="c14n" when converting to string prevents that.
            code = etree.tostring(div_tag, method="c14n").decode()
        return code
Example #3
0
    def format_code(self, lang, text):
        # type: (Text, Text) -> Text
        if lang:
            langclass = LANG_TAG % (lang, )
        else:
            langclass = ''

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        # If config is not empty, then the codehighlite extension
        # is enabled, so we call it to highlite the code
        if self.codehilite_conf:
            highliter = CodeHilite(
                text,
                linenums=self.codehilite_conf['linenums'][0],
                guess_lang=self.codehilite_conf['guess_lang'][0],
                css_class=self.codehilite_conf['css_class'][0],
                style=self.codehilite_conf['pygments_style'][0],
                use_pygments=self.codehilite_conf['use_pygments'][0],
                lang=(lang or None),
                noclasses=self.codehilite_conf['noclasses'][0])

            code = highliter.hilite()
        else:
            code = CODE_WRAP % (langclass, self._escape(text))

        return code
Example #4
0
    def assertOutputEquals(self, source, expected, **options):
        """
        Test that source code block results in the expected output with given options.
        """

        output = CodeHilite(source, **options).hilite()
        self.assertMultiLineEqual(output.strip(), expected)
    def run(self, lines):
        """ Match and store Fenced Code Blocks in the HtmlStash. """

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.md.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)
        while 1:
            m = self.FENCED_BLOCK_RE.search(text)

            if m:
                lang = ''
                wrap_tag = ''
                wrap_class = ''
                if m.group('lang'):
                    lang = self.LANG_TAG % m.group('lang')

                if m.group('wrap_tag'):
                    wrap_tag = m.group('wrap_tag')

                if m.group('wrap_class'):
                    wrap_class = m.group('wrap_class')

                # If config is not empty, then the codehighlite extension
                # is enabled, so we call it to highlight the code
                if self.codehilite_conf:
                    highliter = CodeHilite(
                        m.group('code'),
                        linenums=self.codehilite_conf['linenums'][0],
                        guess_lang=self.codehilite_conf['guess_lang'][0],
                        css_class=self.codehilite_conf['css_class'][0],
                        style=self.codehilite_conf['pygments_style'][0],
                        use_pygments=self.codehilite_conf['use_pygments'][0],
                        lang=(m.group('lang') or None),
                        noclasses=self.codehilite_conf['noclasses'][0],
                        hl_lines=parse_hl_lines(m.group('hl_lines')))

                    code = highliter.hilite()
                else:
                    code = self.CODE_WRAP % (lang, self._escape(
                        m.group('code')))

                placeholder = self.md.htmlStash.store(code)

                text = '{}\n<div class="ez-code-example">{}</div> \n {}\n{}'\
                    .format(text[:m.start()], m.group('code'), placeholder, text[m.end():])

                if wrap_tag and wrap_class:
                    text = '<%s class="%s">\n%s\n</%s>' % (
                        wrap_tag, wrap_class, text, wrap_tag)

            else:
                break
        return text.split("\n")
Example #6
0
    def format_code(self, lang, text):
        # type: (Text, Text) -> Text
        if lang:
            langclass = LANG_TAG % (lang,)
        else:
            langclass = ''

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        # If config is not empty, then the codehighlite extension
        # is enabled, so we call it to highlite the code
        if self.codehilite_conf:
            highliter = CodeHilite(text,
                                   linenums=self.codehilite_conf['linenums'][0],
                                   guess_lang=self.codehilite_conf['guess_lang'][0],
                                   css_class=self.codehilite_conf['css_class'][0],
                                   style=self.codehilite_conf['pygments_style'][0],
                                   use_pygments=self.codehilite_conf['use_pygments'][0],
                                   lang=(lang or None),
                                   noclasses=self.codehilite_conf['noclasses'][0])

            code = highliter.hilite()
        else:
            code = CODE_WRAP % (langclass, self._escape(text))

        return code
Example #7
0
    def run(self, lines):
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True
        text = '\n'.join(lines)
        while 1:
            m = FENCED_BLOCK_RE.search(text)
            if m:
                lang = ''
                if m.group('lang'):
                    lang = LANG_TAG % m.group('lang')
                if self.codehilite_conf:
                    highliter = CodeHilite(
                        m.group('code'),
                        linenos=self.codehilite_conf['force_linenos'][0],
                        guess_lang=self.codehilite_conf['guess_lang'][0],
                        css_class=self.codehilite_conf['css_class'][0],
                        style=self.codehilite_conf['pygments_style'][0],
                        lang=m.group('lang') or None,
                        noclasses=self.codehilite_conf['noclasses'][0])
                    code = highliter.hilite()
                else:
                    code = CODE_WRAP % (lang, self._escape(m.group('code')))
                placeholder = self.markdown.htmlStash.store(code, safe=True)
                text = '%s\n%s\n%s' % (text[:m.start()], placeholder,
                                       text[m.end():])
            else:
                break

        return text.split('\n')
Example #8
0
    def hilite(self):
        if not self.filename:
            return CodeHilite.hilite(self)

        self.src = self.src.strip('\n')

        if self.lang is None:
            self._parseHeader()
        if pygments and self.use_pygments:
            try:
                lexer = get_lexer_by_name(self.lang)
            except ValueError:
                try:
                    if self.guess_lang:
                        lexer = guess_lexer(self.src)
                    else:
                        lexer = get_lexer_by_name('text')
                except ValueError:
                    lexer = get_lexer_by_name('text')
            formatter = get_formatter_by_name(
                'html',
                linenos=self.linenums,
                cssclass=self.css_class,
                style=self.style,
                noclasses=self.noclasses,
                hl_lines=self.hl_lines,
                wrapcode=True,
                filename=self.filename,
            )
            return highlight(self.src, lexer, formatter)

        return CodeHilite.hilite(self)
Example #9
0
    def format_code(self, lang: str, text: str) -> str:
        if lang:
            langclass = LANG_TAG.format(lang)
        else:
            langclass = ""

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.md.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        # If config is not empty, then the codehighlite extension
        # is enabled, so we call it to highlite the code
        if self.codehilite_conf:
            highliter = CodeHilite(
                text,
                linenums=self.codehilite_conf["linenums"][0],
                guess_lang=self.codehilite_conf["guess_lang"][0],
                css_class=self.codehilite_conf["css_class"][0],
                style=self.codehilite_conf["pygments_style"][0],
                use_pygments=self.codehilite_conf["use_pygments"][0],
                lang=(lang or None),
                noclasses=self.codehilite_conf["noclasses"][0],
            )

            code = highliter.hilite().rstrip("\n")
        else:
            code = CODE_WRAP.format(langclass, self._escape(text))

        # To support our "view in playground" feature, the frontend
        # needs to know what Pygments language was used for
        # highlighting this code block.  We record this in a data
        # attribute attached to the outer `pre` element.
        # Unfortunately, the pygments API doesn't offer a way to add
        # this, so we need to do it in a post-processing step.
        if lang:
            div_tag = lxml.html.fromstring(code)

            # For the value of our data element, we get the lexer
            # subclass name instead of directly using the language,
            # since that canonicalizes aliases (Eg: `js` and
            # `javascript` will be mapped to `JavaScript`).
            try:
                code_language = get_lexer_by_name(lang).name
            except ClassNotFound:
                # If there isn't a Pygments lexer by this name, we
                # still tag it with the user's data-code-language
                # value, since this allows hooking up a "playground"
                # for custom "languages" that aren't known to Pygments.
                code_language = lang

            div_tag.attrib["data-code-language"] = code_language
            code = lxml.html.tostring(div_tag, encoding="unicode")
        return code
Example #10
0
    def __init__(self, filename='', **args4base):
        # if _:
        #     raise TypeError("__init__() expected a keyword argument only")

        CodeHilite.__init__(self, **args4base)
        #print(self.noclasses)
        #print(args4base['noclasses'])
        #raise KeyboardInterrupt()
        self.filename = filename
Example #11
0
    def format_code(self, lang: str, text: str) -> str:
        if lang:
            langclass = LANG_TAG.format(lang)
        else:
            langclass = ''

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.md.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        # If config is not empty, then the codehighlite extension
        # is enabled, so we call it to highlite the code
        if self.codehilite_conf:
            highliter = CodeHilite(text,
                                   linenums=self.codehilite_conf['linenums'][0],
                                   guess_lang=self.codehilite_conf['guess_lang'][0],
                                   css_class=self.codehilite_conf['css_class'][0],
                                   style=self.codehilite_conf['pygments_style'][0],
                                   use_pygments=self.codehilite_conf['use_pygments'][0],
                                   lang=(lang or None),
                                   noclasses=self.codehilite_conf['noclasses'][0])

            code = highliter.hilite()
        else:
            code = CODE_WRAP.format(langclass, self._escape(text))

        # In order to display a "view-in-playground" option in the frontend,
        # we need to know the language used in the codeblock. We tweak the HTML
        # CodeHilite generates to add this language as a data-attribute.
        if lang:
            parsed_code = etree.HTML(code)
            div_tag = parsed_code[0][0]
            # We get the lexer subclass name instead of directly processing the lang, to avoid
            # different tags being generated for each of the lang's alias. Eg: `js` and `javascript`
            # would now be mapped to `JavaScript`. In case no lexer with that alias is found, we
            # return back the text, wrapped in a data-codehilite tag.
            try:
                lexer_subclass_name = get_lexer_by_name(lang).name
            except ClassNotFound:
                lexer_subclass_name = lang
            div_tag.attrib['data-codehilite-language'] = lexer_subclass_name
            # Lxml implicitly converts tags like <span></span> into <span/>
            # specifying method="c14n" when converting to string, prevents that.
            code = etree.tostring(div_tag, method="c14n").decode()
        return code
Example #12
0
    def run(self, lines):
        """ Match and store Fenced Code Blocks in the HtmlStash. """

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.md.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)
        while 1:
            m = self.FENCED_BLOCK_RE.search(text)
            if m:
                lang = ''
                if m.group('lang'):
                    lang = self.LANG_TAG % m.group('lang')
                print(f"lang is {lang}")
                if 'mermaid' in lang:
                    code = f"<div class=\"mermaid\">{m.group('code')}</div>"
                    print(code)
                else:
                    # If config is not empty, then the codehighlite extension
                    # is enabled, so we call it to highlight the code
                    if self.codehilite_conf:
                        highliter = CodeHilite(
                            m.group('code'),
                            linenums=self.codehilite_conf['linenums'][0],
                            guess_lang=self.codehilite_conf['guess_lang'][0],
                            css_class=self.codehilite_conf['css_class'][0],
                            style=self.codehilite_conf['pygments_style'][0],
                            use_pygments=self.codehilite_conf['use_pygments']
                            [0],
                            lang=(m.group('lang') or None),
                            noclasses=self.codehilite_conf['noclasses'][0],
                            hl_lines=parse_hl_lines(m.group('hl_lines')))

                        code = highliter.hilite()
                    else:
                        code = self.CODE_WRAP % (lang,
                                                 self._escape(m.group('code')))

                placeholder = self.md.htmlStash.store(code)
                text = '%s\n%s\n%s' % (text[:m.start()], placeholder,
                                       text[m.end():])
            else:
                break
        return text.split("\n")
Example #13
0
def highlight(code, config, tab_length, lang=None):
    code = CodeHilite(
        code,
        linenums=config['linenums'],
        guess_lang=config['guess_lang'],
        css_class=config['css_class'],
        style=config['pygments_style'],
        noclasses=config['noclasses'],
        tab_length=tab_length,
        use_pygments=config['use_pygments'],
        lang=lang,
    )
    html = code.hilite()
    html = """<div class="codehilite-wrap">{}</div>""".format(html)
    return html
Example #14
0
    def _highlite_code(self, lang, code, options):
        if self.codehilite_config:
            highliter = CodeHilite(
                code,
                linenums=self.codehilite_config['linenums'][0],
                guess_lang=self.codehilite_config['guess_lang'][0],
                css_class=self.codehilite_config['css_class'][0],
                style=self.codehilite_config['pygments_style'][0],
                lang=(lang or None),
                noclasses=self.codehilite_config['noclasses'][0],
                hl_lines=parse_hl_lines(options['hl_lines'])
            )
            return highliter.hilite()

        return '<pre><code class="{}">{}</code></pre>'.format(lang, util.escape(code))
Example #15
0
def highlight(code, config, tab_length, lang=None):
    code = CodeHilite(
        code,
        linenums=config['linenums'],
        guess_lang=config['guess_lang'],
        css_class=config['css_class'],
        style=config['pygments_style'],
        noclasses=config['noclasses'],
        tab_length=tab_length,
        use_pygments=config['use_pygments'],
        lang=lang,
    )
    html = code.hilite()
    html = """<div class="codehilite-wrap">{}</div>""".format(html)
    return html
Example #16
0
    def run(self, lines):
        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)
        while 1:
            m = QUALIFIED_FENCED_BLOCK_RE.search(text)
            if m:
                qualifies = m.group('qualifies') or ''
                qualifies = filter(None, qualifies.split('\n'))
                code = m.group('code')
                qualifier_list = QualifierList(qualifies)
                code = qualifier_list.mark(code)

                # If config is not empty, then the codehighlite extension
                # is enabled, so we call it to highlite the code
                if self.codehilite_conf and m.group('lang'):
                    highliter = CodeHilite(code,
                            linenums=self.codehilite_conf['linenums'][0],
                            guess_lang=self.codehilite_conf['guess_lang'][0],
                            css_class=self.codehilite_conf['css_class'][0],
                            style=self.codehilite_conf['pygments_style'][0],
                            lang=(m.group('lang') or None),
                            noclasses=self.codehilite_conf['noclasses'][0])

                    code = highliter.hilite()
                else:
                    lang = ''
                    if m.group('lang'):
                        lang = LANG_TAG % m.group('lang')

                    code = CODE_WRAP % (lang, self._escape(code))

                code = qualifier_list.qualify(code)

                placeholder = self.markdown.htmlStash.store(code, safe=True)
                text = '%s\n%s\n%s'% (text[:m.start()], placeholder, text[m.end():])
            else:
                break
        return text.split("\n")
Example #17
0
    def run(self, lines):
        """ Match and store Fenced Code Blocks in the HtmlStash. """

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)
        while 1:
            m = FENCED_BLOCK_RE.search(text)
            if m:
                lang = ''
                if m.group('lang'):
                    lang = LANG_TAG % m.group('lang')

                # If config is not empty, then the codehighlite extension
                # is enabled, so we call it to highlite the code
                if self.codehilite_conf:
                    highliter = CodeHilite(
                        m.group('code'),
                        linenos=self.codehilite_conf['force_linenos'][0],
                        guess_lang=self.codehilite_conf['guess_lang'][0],
                        css_class=self.codehilite_conf['css_class'][0],
                        style=self.codehilite_conf['pygments_style'][0],
                        lang=(m.group('lang') or None),
                        noclasses=self.codehilite_conf['noclasses'][0])

                    code = highliter.hilite()
                else:
                    code = CODE_WRAP % (lang, self._escape(m.group('code')))

                placeholder = self.markdown.htmlStash.store(code, safe=True)
                text = '%s\n%s\n%s' % (text[:m.start()], placeholder,
                                       text[m.end():])
            else:
                break
        return text.split("\n")
Example #18
0
    def run(self, lines):
        """ Match and store Fenced Code Blocks in the HtmlStash. """

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)
        while 1:
            m = FENCED_BLOCK_RE.search(text)
            if m:
                lang = ""
                if m.group("lang"):
                    lang = LANG_TAG % m.group("lang")

                # If config is not empty, then the codehighlite extension
                # is enabled, so we call it to highlite the code
                if self.codehilite_conf:
                    highliter = CodeHilite(
                        m.group("code"),
                        linenos=self.codehilite_conf["force_linenos"],
                        guess_lang=self.codehilite_conf["guess_lang"],
                        css_class=self.codehilite_conf["css_class"],
                        style=self.codehilite_conf["pygments_style"],
                        lang=(m.group("lang") or None),
                        noclasses=self.codehilite_conf["noclasses"],
                    )

                    code = highliter.hilite()
                else:
                    code = CODE_WRAP % (lang, self._escape(m.group("code")))

                placeholder = self.markdown.htmlStash.store(code, safe=True)
                text = "%s\n%s\n%s" % (text[: m.start()], placeholder, text[m.end() :])
            else:
                break
        return text.split("\n")
Example #19
0
    def run(self, lines):
        """ Match and store Octo Code Blocks in the HtmlStash. """

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)
        while 1:
            m = INCLUDE_CODE_RE.search(text)
            if m:
                lang = ''
                if m.group('lang'):
                    lang = LANG_TAG % m.group('lang')
                code_path=os.path.join(os.getcwd(),'static/downloads/code',m.group('path'))
                code = open(code_path,'r').read()
                # If config is not empty, then the codehighlite extension
                # is enabled, so we call it to highlite the code
                if self.codehilite_conf:
                    highliter = CodeHilite(code,
                            linenums=self.codehilite_conf['linenums'][0],
                            guess_lang=self.codehilite_conf['guess_lang'][0],
                            css_class=self.codehilite_conf['css_class'][0],
                            style=self.codehilite_conf['pygments_style'][0],
                            lang=(m.group('lang') or None),
                            noclasses=self.codehilite_conf['noclasses'][0])

                    code = highliter.hilite()
                else:
                    code = CODE_WRAP % (lang, self._escape(code))

                placeholder = self.markdown.htmlStash.store(code, safe=True)
                text = '%s\n%s\n%s'% (text[:m.start()], placeholder, text[m.end():])
            else:
                break
        return text.split("\n")
Example #20
0
 def run(self, root):
     """ Find code blocks and store in htmlStash. """
     blocks = root.iter('pre')
     for block in blocks:
         if len(block) == 1 and block[0].tag == 'code':
             code = CodeHilite(block[0].text,
                               linenums=self.config['linenums'],
                               guess_lang=self.config['guess_lang'],
                               css_class=self.config['css_class'],
                               style=self.config['pygments_style'],
                               noclasses=self.config['noclasses'],
                               tab_length=self.markdown.tab_length,
                               use_pygments=self.config['use_pygments'])
             html = code.hilite()
             html = """<div class="codehilite-wrap">{}</div>""".format(html)
             placeholder = self.markdown.htmlStash.store(html, safe=True)
             # Clear codeblock in etree instance
             block.clear()
             # Change to p element which will later
             # be removed when inserting raw html
             block.tag = 'p'
             block.text = placeholder
Example #21
0
    def format_code(self, lang: str, text: str) -> str:
        if not lang:
            try:
                lang = self.md.zulip_realm.default_code_block_language
            except AttributeError:
                pass
        lang = remap_language(lang)
        if lang:
            langclass = LANG_TAG % (lang, )
        else:
            langclass = ''

        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        # If config is not empty, then the codehighlite extension
        # is enabled, so we call it to highlite the code
        if self.codehilite_conf:
            highliter = CodeHilite(
                text,
                linenums=self.codehilite_conf['linenums'][0],
                guess_lang=self.codehilite_conf['guess_lang'][0],
                css_class=self.codehilite_conf['css_class'][0],
                style=self.codehilite_conf['pygments_style'][0],
                use_pygments=self.codehilite_conf['use_pygments'][0],
                lang=(lang or None),
                noclasses=self.codehilite_conf['noclasses'][0])

            code = highliter.hilite()
        else:
            code = CODE_WRAP % (langclass, self._escape(text))

        return code
Example #22
0
 def run(self, root):
     """ Find code blocks and store in htmlStash. """
     blocks = root.iter('pre')
     for block in blocks:
         if len(block) == 1 and block[0].tag == 'code':
             code = CodeHilite(
                 block[0].text,
                 linenums=self.config['linenums'],
                 guess_lang=self.config['guess_lang'],
                 css_class=self.config['css_class'],
                 style=self.config['pygments_style'],
                 noclasses=self.config['noclasses'],
                 tab_length=self.markdown.tab_length,
                 use_pygments=self.config['use_pygments']
             )
             html = code.hilite()
             html = """<div class="codehilite-wrap">{}</div>""".format(html)
             placeholder = self.markdown.htmlStash.store(html, safe=True)
             # Clear codeblock in etree instance
             block.clear()
             # Change to p element which will later
             # be removed when inserting raw html
             block.tag = 'p'
             block.text = placeholder
    def highlight(self, source, language):
        """
        Syntax highlight the code block.

        If config is not empty, then the codehlite extension
        is enabled, so we call into it to highlight the code.
        """
        if self.codehilite_conf:
            code = CodeHilite(
                source,
                linenums=self.codehilite_conf['linenums'][0],
                guess_lang=self.codehilite_conf['guess_lang'][0],
                css_class=self.codehilite_conf['css_class'][0],
                style=self.codehilite_conf['pygments_style'][0],
                lang=language,
                noclasses=self.codehilite_conf['noclasses'][0],
                hl_lines=parse_hl_lines(self.hl_lines),
                use_pygments=self.codehilite_conf['use_pygments'][0]).hilite()
        else:
            lang = self.CLASS_ATTR % language if language else ''
            code = self.CODE_WRAP % (lang, _escape(source))
        return code
Example #24
0
    def __init__(self, *_, **args4base):
        if _:
            raise TypeError("__init__() expected a keyword argument only")

        CodeHilite.__init__(self, **args4base)
Example #25
0
 def hilite(self):
     return CodeHilite.hilite(self)
    def run(self, lines):
        # Check for code hilite extension
        if not self.checked_for_codehilite:
            for ext in self.markdown.registeredExtensions:
                if isinstance(ext, CodeHiliteExtension):
                    self.codehilite_conf = ext.config
                    break

            self.checked_for_codehilite = True

        text = "\n".join(lines)

        example_counter = 0

        while 1:
            m = QUALIFIED_FENCED_BLOCK_RE.search(text)
            if m:
                # ```cpp example みたいに書かれていたらサンプルコードとして扱う
                is_example = m.group('lang_meta') and ('example' in m.group('lang_meta').strip().split())

                qualifies = m.group('qualifies') or ''
                qualifies = qualifies + self.global_qualify_list
                qualifies = filter(None, qualifies.split('\n'))
                code = _removeIndent(*m.group('code', 'indent'))

                # サンプルコードだったら、self.markdown の中にコードの情報と ID を入れておく
                if is_example:
                    example_id = hashlib.sha1(str(example_counter) + code.encode('utf-8')).hexdigest()
                    self.markdown._example_codes.append({"id": example_id, "code": code})
                    example_counter += 1

                qualifier_list = QualifierList(qualifies)
                code = qualifier_list.mark(code)

                # If config is not empty, then the codehighlite extension
                # is enabled, so we call it to highlite the code
                if self.codehilite_conf and m.group('lang'):
                    highliter = CodeHilite(
                        code,
                        linenums=self.codehilite_conf['linenums'][0],
                        guess_lang=self.codehilite_conf['guess_lang'][0],
                        css_class=self.codehilite_conf['css_class'][0],
                        style=self.codehilite_conf['pygments_style'][0],
                        lang=(m.group('lang') or None),
                        noclasses=self.codehilite_conf['noclasses'][0])

                    code = highliter.hilite()
                    # サンプルコードだったら <div id="..." class="yata"> で囲む
                    if is_example:
                        code = '<div id="%s" class="yata">%s</div>' % (example_id, code)
                else:
                    lang = ''
                    if m.group('lang'):
                        lang = LANG_TAG % m.group('lang')

                    code = CODE_WRAP % (lang, _escape(code))

                code = qualifier_list.qualify(code)

                placeholder = self.markdown.htmlStash.store(code, safe=True)
                text = '%s\n%s\n%s' % (text[:m.start()], placeholder, text[m.end():])
            else:
                break
        return text.split("\n")