예제 #1
0
파일: pygments.py 프로젝트: pkdevbox/trac
    def process_request(self, req):
        style = req.args['style']
        try:
            style_cls = get_style_by_name(style)
        except ValueError as e:
            raise HTTPNotFound(e)

        parts = style_cls.__module__.split('.')
        filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
        mtime = datetime.fromtimestamp(os.path.getmtime(filename), localtz)
        last_modified = http_date(mtime)
        if last_modified == req.get_header('If-Modified-Since'):
            req.send_response(304)
            req.end_headers()
            return

        formatter = HtmlFormatter(style=style_cls)
        content = u'\n\n'.join([
            formatter.get_style_defs('div.code pre'),
            formatter.get_style_defs('table.code td')
        ]).encode('utf-8')

        req.send_response(200)
        req.send_header('Content-Type', 'text/css; charset=utf-8')
        req.send_header('Last-Modified', last_modified)
        req.send_header('Content-Length', len(content))
        req.write(content)
예제 #2
0
    def process_request(self, req):
        style = req.args['style']
        try:
            style_cls = get_style_by_name(style)
        except ValueError as e:
            raise HTTPNotFound(e)

        parts = style_cls.__module__.split('.')
        filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
        mtime = datetime.fromtimestamp(os.path.getmtime(filename), localtz)
        last_modified = http_date(mtime)
        if last_modified == req.get_header('If-Modified-Since'):
            req.send_response(304)
            req.end_headers()
            return

        formatter = HtmlFormatter(style=style_cls)
        content = u'\n\n'.join([
            formatter.get_style_defs('div.code pre'),
            formatter.get_style_defs('table.code td')
        ]).encode('utf-8')

        req.send_response(200)
        req.send_header('Content-Type', 'text/css; charset=utf-8')
        req.send_header('Last-Modified', last_modified)
        req.send_header('Content-Length', len(content))
        req.write(content)
예제 #3
0
파일: models.py 프로젝트: mrJayson/lmsunsw
    def render_code(self):
        formatter = HtmlFormatter(style='default', nowrap=True, classprefix='code%s-' % self.pk)
        html = highlight(self.code, get_lexer_by_name(self.syntax), formatter)
        css = formatter.get_style_defs()

        # Included in a DIV, so the next item will be displayed below.
        return _('<div class="code"><style type="text/css">%(css)s</style>\n<pre>%(html)s</pre></div>\n') % {'css':css, 'html':html}
예제 #4
0
    def make_report(self):
        """Makes a html report in the dir where logs are stored."""
        if self.execution_stats is None:
            raise Exception('First run the executor')

        if os.environ.get('DISPLAY', '') == '':
            LOGGER.info('No display found, using non-interactive Agg backend')
            plt.switch_backend('Agg')

        dependency_graph = self._create_dependency_graph()
        task_descriptions = self._get_task_descriptions()

        formatter = HtmlFormatter(linenos=True)
        task_source = self._render_task_source(formatter)
        execution_stats = self._render_execution_errors(formatter)

        template = self._get_template()

        html = template.render(dependency_graph=dependency_graph,
                               task_descriptions=task_descriptions,
                               task_source=task_source,
                               execution_stats=execution_stats,
                               execution_logs=self.execution_logs,
                               code_css=formatter.get_style_defs())

        if not os.path.isdir(self.report_folder):
            os.mkdir(self.report_folder)

        with open(self._get_report_filename(), 'w') as fout:
            fout.write(html)

        return html
예제 #5
0
class PygmentHighlighting:
    def __init__(self, options):
        self.logger = Logger(options.verbose)
        self.formatter = None
        try:
            from pygments.formatters.html import HtmlFormatter
            self.formatter = HtmlFormatter(nowrap=True)
        except ImportError as e:  # pragma: no cover
            self.logger.warn("No syntax highlighting available: {}".format(
                str(e)))

    def get_css(self):
        if self.formatter is None:  # pragma: no cover
            return ''
        return "\n\n/* pygments syntax highlighting */\n" + self.formatter.get_style_defs(
        )

    # Set the lexer for the given filename. Return true if a lexer is found
    def highlighter_for_file(self, filename):
        if self.formatter is None:  # pragma: no cover
            return NullHighlighting.highlighter_for_file(filename)

        import pygments
        from pygments.lexers import get_lexer_for_filename
        from jinja2 import Markup
        try:
            lexer = get_lexer_for_filename(filename, None, stripnl=False)
            return lambda code: [
                Markup(line.rstrip()) for line in pygments.highlight(
                    code, lexer, self.formatter).split("\n")
            ]
        except pygments.util.ClassNotFound:  # pragma: no cover
            return NullHighlighting.highlighter_for_file(filename)
예제 #6
0
    def pretty(self, args, cell):
        """pretty-print the robot text"""
        tidier = Tidy()

        with tempfile.TemporaryDirectory() as td:
            tdp = Path(td)
            it = tdp / "ugly.robot"
            it.write_text(cell, **ENC)
            tidier.inplace(str(it))
            cell = it.read_text(**ENC)

        lexer = RobotFrameworkLexer()
        formatter = HtmlFormatter(cssclass=self.PRETTY_CLASS, style=args.style)
        css = formatter.get_style_defs(f".{self.PRETTY_CLASS}")
        highlighted = highlight(cell, lexer, formatter)
        html = HTML(f"""
            <ul><li>
            <details>
                <summary>Formatted Robot Code</summary>
                <style>{css}</style>{highlighted}
            </details>
            </li></ul>
        """)

        return html
예제 #7
0
def notebook_fileprinter(file, lexer="YAML"):
    """Print the code from file/BytesIO  to notebook cell with syntax highlighting.

    Parameters
    ----------
    file
        filename or ``BytesIO`` buffer of ASDF file
    lexer
        Syntax style to use

    """
    from IPython.display import HTML
    from pygments import highlight
    from pygments.formatters.html import HtmlFormatter
    from pygments.lexers import get_lexer_by_name, get_lexer_for_filename

    if isinstance(file, BytesIO):
        lexer = get_lexer_by_name(lexer)
    elif Path(file).suffix == ".asdf":
        lexer = get_lexer_by_name("YAML")
    else:
        lexer = get_lexer_for_filename(file)

    code = get_yaml_header(file)
    formatter = HtmlFormatter()
    return HTML('<style type="text/css">{}</style>{}'.format(
        formatter.get_style_defs(".highlight"),
        highlight(code, lexer, formatter),
    ))
예제 #8
0
파일: model.py 프로젝트: ADFD/adfd
 def _bbcodeAsHtml(self):
     style = get_style_by_name('igor')
     formatter = HtmlFormatter(style=style)
     lexer = get_lexer_by_name("bbcode", stripall=True)
     css = formatter.get_style_defs()
     txt = highlight(self._bbcode, lexer, HtmlFormatter())
     return "<style>%s</style>\n%s" % (css, txt)
예제 #9
0
def code():
    try:
        code = request.form['code']
        stylename = request.form['style']
        lang = request.form['lang']
    except:
        code = ''
        stylename = 'igor'
        lang = 'python'

    if stylename == '' or stylename is None or stylename == '代码高亮':
        stylename = 'igor'
    if lang == '' or lang is None:
        lang = 'python'

    style_list = get_all_styles()
    style = get_style_by_name(stylename)
    if code:
        lexer = get_lexer_by_name(lang)
        formatter = HtmlFormatter(style=style,
                                  cssclass='syntax',
                                  linenos=False)
        highlightcode = highlight(code, lexer, formatter)
        highlightcss = formatter.get_style_defs('.syntax pre')
    else:
        highlightcode = ''
        highlightcss = ''

    return render_template('code.html',
                           code=code,
                           highlightcss=highlightcss,
                           highlightcode=highlightcode,
                           style_list=style_list,
                           style=stylename,
                           lang=lang)
예제 #10
0
 def prev_view_code(self, code, laugange):
     htmlFormatter = HtmlFormatter()
     lexer = CppLexer()
     if laugange == "Cpp":
         lexer = CppLexer()
     elif laugange == "CSharp":
         lexer = CSharpLexer()
     codeDiv = highlight(code, lexer, htmlFormatter)
     codeCss = htmlFormatter.get_style_defs(".highlight")
     #
     html = """
     <html>
         <head>
             <style type="text/css">
             %s
             </style>
         </head>
         <body>
         %s
         </body>
     </html>
     """ % (codeCss, codeDiv)
     self.webView.setHtml(html)
     self.setStyleSheet(codeCss)
     # 输出文件测试验证
     # ff = open('test.html', 'w')
     # ff.write(html)
     # ff.close()
     pass
예제 #11
0
def render_code(instance, style_name="default"):
    # Some interesting options in the HtmlFormatter:
    # - nowrap       -> no wrap inside <pre>
    # - classprefix  -> prefix for the classnames
    # - noclasses    -> all inline styles.
    #
    # To get_style_defs(), you can pass a selector prefix.
    #
    style = styles.get_style_by_name(style_name)
    formatter = HtmlFormatter(
        linenos=instance.linenumbers,
        style=style,
        nowrap=True,
        classprefix="code%s-" % instance.pk,
    )
    html = highlight(instance.code, get_lexer_by_name(instance.language), formatter)
    css = formatter.get_style_defs()

    # Included in a DIV, so the next item will be displayed below.
    return (
        '<div class="code"><style type="text/css">'
        + css
        + "</style>\n<pre>"
        + html
        + "</pre></div>\n"
    )
예제 #12
0
파일: util.py 프로젝트: BAMWelDX/weldx
def notebook_fileprinter(file: types_path_and_file_like, lexer="YAML"):
    """Print the code from file/BytesIO to notebook cell with syntax highlighting.

    Parameters
    ----------
    file :
        filename or file-like object pointing towards / containing an ASDF file.
    lexer :
        Syntax style to use

    """
    from IPython.display import HTML
    from pygments import highlight
    from pygments.formatters.html import HtmlFormatter
    from pygments.lexers import get_lexer_by_name, get_lexer_for_filename

    if isinstance(file, types_file_like.__args__):
        lexer = get_lexer_by_name(lexer)
    elif Path(file).suffix == ".asdf":
        lexer = get_lexer_by_name("YAML")
    else:
        lexer = get_lexer_for_filename(file)

    code = get_yaml_header(file, parse=False)
    formatter = HtmlFormatter()
    return HTML('<style type="text/css">{}</style>{}'.format(
        formatter.get_style_defs(".highlight"),
        highlight(code, lexer, formatter),
    ))
예제 #13
0
def highlight_paste(paste, hl_lines):
    '''Use pygments to syntax highlight a paste, returns by the way the CSS'''
    lexer = get_lexer_by_name(paste.hl_alias)
    formatter = HtmlFormatter(linenos=True, cssclass='source', hl_lines=hl_lines)
    return (
        highlight(paste.content, lexer, formatter),
        formatter.get_style_defs('.source')
    )
예제 #14
0
def home():
    readme = open("README.md", 'r', encoding="utf-8")
    md_template = markdown(readme.read(), extensions=["fenced_code"])
    formatter = HtmlFormatter(style="emacs", full=True, cssclass="codehilite")
    css_string = formatter.get_style_defs()
    md_css_string = "<style>" + css_string + "</style>"
    md_template = md_css_string + md_template
    return md_template
예제 #15
0
파일: main.py 프로젝트: GabrielC101/PPaste
def highlight_paste(paste, hl_lines):
    '''Use pygments to syntax highlight a paste, returns by the way the CSS'''
    lexer = get_lexer_by_name(paste.hl_alias)
    formatter = HtmlFormatter(linenos=True, cssclass='source', hl_lines=hl_lines)
    return (
        highlight(paste.content, lexer, formatter),
        formatter.get_style_defs('.source')
    )
예제 #16
0
 def style_defs(cls):
     """
     Return the CSS style definitions required
     by the formatted snippet.
     """
     formatter = HtmlFormatter()
     formatter.style.highlight_color = cls.VIOLATION_COLOR
     return formatter.get_style_defs()
예제 #17
0
 def pretty_typeform(self, obj):
     formatter = HtmlFormatter(style='colorful')
     data = json.dumps(obj.user_flow_action.flow.context,
                       indent=2,
                       ensure_ascii=False)
     response = highlight(data.encode('utf-8'), JsonLexer(), formatter)
     style = "<style>" + formatter.get_style_defs() + "</style><br>"
     return mark_safe(style + response)
예제 #18
0
 def style_defs(cls):
     """
     Return the CSS style definitions required
     by the formatted snippet.
     """
     formatter = HtmlFormatter()
     formatter.style.highlight_color = cls.VIOLATION_COLOR
     return formatter.get_style_defs()
예제 #19
0
    def process_request(self, req):
        # settings panel
        if not 'style' in req.args:
            req._no_pygments_stylesheet = True
            styles = list(get_all_styles())
            styles.sort(lambda a, b: cmp(a.lower(), b.lower()))

            if req.method == 'POST':
                style = req.args.get('new_style')
                if style and style in styles:
                    req.session['pygments_style'] = style

            output = self._highlight('html', self.EXAMPLE, False)
            req.hdf['output'] = Markup(output)
            req.hdf['current'] = req.session.get('pygments_style',
                                                 self.default_style)
            req.hdf['styles'] = styles
            req.hdf['pygments_path'] = self.env.href.pygments()
            return 'pygments_settings.cs', None

        # provide stylesheet
        else:
            style = req.args['style']

            parts = style.__module__.split('.')
            filename = resource_filename('.'.join(parts[:-1]),
                                         parts[-1] + '.py')
            mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
            last_modified = http_date(time.mktime(mtime.timetuple()))
            if last_modified == req.get_header('If-Modified-Since'):
                req.send_response(304)
                req.end_headers()
                return

            formatter = HtmlFormatter(style=style)
            content = u'\n\n'.join([
                formatter.get_style_defs('div.code pre'),
                formatter.get_style_defs('table.code td')
            ]).encode('utf-8')

            req.send_response(200)
            req.send_header('Content-Type', 'text/css; charset=utf-8')
            req.send_header('Last-Modified', last_modified)
            req.send_header('Content-Length', len(content))
            req.write(content)
예제 #20
0
    def nice_ping_response(self, instance):
        # Convert the data to sorted, indented JSON
        response = json.dumps(instance.ping_response, indent=2)
        formatter = HtmlFormatter(style='colorful')
        response = highlight(response, JsonLexer(), formatter)
        style = "<style>" + formatter.get_style_defs() + "</style><br>"

        # Safe the output
        return mark_safe(style + response)
예제 #21
0
    def process_request(self, req):
        # settings panel
        if not 'style' in req.args:
            req._no_pygments_stylesheet = True
            styles = list(get_all_styles())
            styles.sort(lambda a, b: cmp(a.lower(), b.lower()))

            if req.method == 'POST':
                style = req.args.get('new_style')
                if style and style in styles:
                    req.session['pygments_style'] = style

            output = self._highlight('html', self.EXAMPLE, False)
            req.hdf['output'] = Markup(output)
            req.hdf['current'] = req.session.get('pygments_style',
                                                 self.default_style)
            req.hdf['styles'] = styles
            req.hdf['pygments_path'] = self.env.href.pygments()
            return 'pygments_settings.cs', None

        # provide stylesheet
        else:
            style = req.args['style']

            parts = style.__module__.split('.')
            filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
            mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
            last_modified = http_date(time.mktime(mtime.timetuple()))
            if last_modified == req.get_header('If-Modified-Since'):
                req.send_response(304)
                req.end_headers()
                return

            formatter = HtmlFormatter(style=style)
            content = u'\n\n'.join([
                formatter.get_style_defs('div.code pre'),
                formatter.get_style_defs('table.code td')
            ]).encode('utf-8')

            req.send_response(200)
            req.send_header('Content-Type', 'text/css; charset=utf-8')
            req.send_header('Last-Modified', last_modified)
            req.send_header('Content-Length', len(content))
            req.write(content)
예제 #22
0
 def code_highlight(self, para):
     first_line = para.split('\n', 1)[0]
     first_line = '#!' + first_line.replace('`', '')
     lexer = guess_lexer(first_line)
     formatter = HtmlFormatter(linenos=False, cssclass="highlight")
     code = '\n'.join(para.split('\n')[1:-2])
     html = '<div id="scoped-content"><style type="text/css">' + formatter.get_style_defs('.highlight') + '</style>'
     html += highlight(code, lexer, formatter)
     html += '</div>'
     return html
예제 #23
0
    def render(self, name, value, attrs=None, renderer=None):
        formatter = HtmlFormatter(style='colorful')
        formatted_json = highlight(json.dumps(json.loads(value), sort_keys=True, indent=2),
                                   JsonLexer(), formatter)

        context = self.get_context(name, value, attrs)
        context['json'] = mark_safe(formatted_json)
        context['style'] = mark_safe("<style>" + formatter.get_style_defs() + "</style>")
        template = Template(self.tpl)
        return template.render(Context(context))
예제 #24
0
 def diff_prettified(self):
     response = json.loads(self.difference)
     response = json.dumps(response,
                           sort_keys=True,
                           indent=1,
                           ensure_ascii=False).replace('&oacute;', "ó")
     response = response[:10000]
     formatter = HtmlFormatter(style='colorful', lineseparator="<br>")
     response = highlight(response, JsonLexer(), formatter)
     style = "<style>" + formatter.get_style_defs() + "</style>"
     return mark_safe(style + response)
예제 #25
0
 def get(self, paste_id):
     try:
         aid = b64.num_decode(paste_id)
         paste = Paste.get_by_id(aid)
         content, lang = paste.content, paste.type
         formatter = HtmlFormatter()
         self.response.out.write(template.render("paste.html", {'css': formatter.get_style_defs('.highlight'),
                                                                'paste': highlight(content, get_lexer_by_name(lang), formatter)}))
     except Exception:
         self.response.set_status(404)
         self.response.out.write(template.render("404.html", {}))
예제 #26
0
def render_json(data):
    data = custom_sort(data)
    if hasattr(data, "get"):
        data = data.get("json") or data.get("text")
    text = json.dumps(data, sort_keys=False, indent=2)
    formatter = HtmlFormatter(style="monokai",
                              cssclass="metadata",
                              wrapcode=False)
    text = highlight(text, JsonLdLexer(), formatter)
    style = "<style>" + formatter.get_style_defs() + "</style>"
    text = (style + bleach.linkify(text)).strip()
    return mark_safe(text)
예제 #27
0
def highlight_code(code):
    # TODO: refactor this into a code cell model to support multiple languages
    """
    Creates html and css for python code highlighting.
    :param code: The python code to highlight
    :return: A dictionary with html code and css styling
    """
    lexer = PythonLexer()
    formatter = HtmlFormatter()
    code_html = highlight(code, lexer, formatter)
    code_css = formatter.get_style_defs()
    return code_html, code_css
class codeStyle():
    def __init__(self, style='native'):
        self.style = style
        self.formatter = HtmlFormatter(style=style)

    def get_css(self):
        css = self.formatter.get_style_defs('.highlight')
        return css

    def translate_code(self, code, language):
        lexer = get_lexer_by_name(language)
        html = highlight(code, lexer, self.formatter)
        return html
예제 #29
0
파일: admin.py 프로젝트: jank0s/nat64check
    def admin_nat64_data(self, measurement):
        response = yaml.dump(measurement.nat64_data)

        # Get the Pygments formatter
        formatter = HtmlFormatter(style='colorful')

        # Highlight the data
        response = highlight(response, YamlLexer(), formatter)

        # Get the stylesheet
        style = "<style>" + formatter.get_style_defs() + "</style><br>"

        # Safe the output
        return mark_safe(style + response)
예제 #30
0
def test_executing_style_defs():
    style = style_with_executing_node("native", "bg:#ffff00")
    formatter = HtmlFormatter(style=style)
    style_defs = formatter.get_style_defs()

    expected = """
    .c { color: #999999; font-style: italic }
    .err { color: #a61717; background-color: #e3d2d2 }
    .c-ExecutingNode { color: #999999; font-style: italic; background-color: #ffff00 }
    .err-ExecutingNode { color: #a61717; background-color: #ffff00 }
    """.strip().splitlines()

    for line in expected:
        assert line.strip() in style_defs
예제 #31
0
    def render_code(self):
        formatter = HtmlFormatter(style='default',
                                  nowrap=True,
                                  classprefix='code%s-' % self.pk)
        html = highlight(self.code, get_lexer_by_name(self.syntax), formatter)
        css = formatter.get_style_defs()

        # Included in a DIV, so the next item will be displayed below.
        return _(
            '<div class="code"><style type="text/css">%(css)s</style>\n<pre>%(html)s</pre></div>\n'
        ) % {
            'css': css,
            'html': html
        }
예제 #32
0
    def make_report(self, include_logs: bool = True):
        """Makes a html report and saves it into the same folder where logs are stored."""
        if self.eoexecutor.execution_results is None:
            raise RuntimeError(
                "Cannot produce a report without running the executor first, check EOExecutor.run method"
            )

        if os.environ.get("DISPLAY", "") == "":
            plt.switch_backend("Agg")

        try:
            dependency_graph = self._create_dependency_graph()
        except graphviz.backend.ExecutableNotFound as ex:
            dependency_graph = None
            warnings.warn(
                f"{ex}.\nPlease install the system package 'graphviz' (in addition to the python package) to have "
                "the dependency graph in the final report!",
                EOUserWarning,
            )

        formatter = HtmlFormatter(linenos=True)

        template = self._get_template()

        execution_log_filenames = [fs.path.basename(log_path) for log_path in self.eoexecutor.get_log_paths()]
        if self.eoexecutor.save_logs:
            execution_logs = self.eoexecutor.read_logs() if include_logs else None
        else:
            execution_logs = ["No logs saved"] * len(self.eoexecutor.execution_kwargs)

        html = template.render(
            title=f"Report {self._format_datetime(self.eoexecutor.start_time)}",
            dependency_graph=dependency_graph,
            general_stats=self.eoexecutor.general_stats,
            exception_stats=self._get_exception_stats(),
            task_descriptions=self._get_node_descriptions(),
            task_sources=self._render_task_sources(formatter),
            execution_results=self.eoexecutor.execution_results,
            execution_tracebacks=self._render_execution_tracebacks(formatter),
            execution_logs=execution_logs,
            execution_log_filenames=execution_log_filenames,
            execution_names=self.eoexecutor.execution_names,
            code_css=formatter.get_style_defs(),
        )

        self.eoexecutor.filesystem.makedirs(self.eoexecutor.report_folder, recreate=True)

        with self.eoexecutor.filesystem.open(self.eoexecutor.get_report_path(full_path=False), "w") as file_handle:
            file_handle.write(html)
예제 #33
0
def export():
    if not os.path.exists(PYGMENTS_PATH):
        os.makedirs(PYGMENTS_PATH)

    styles = list(get_all_styles())

    for style in styles:
        print('Generating CSS for %s' % style)

        opts = {
            'style': style,
            'noclasses': False,
            'nobackground': False,
        }

        path = os.path.join(PYGMENTS_PATH, '%s.css' % style)
        formatter = HtmlFormatter(**opts)
        md_css = formatter.get_style_defs('.highlight')
        rst_css = formatter.get_style_defs('.literal-block')

        with open(path, 'w+') as f:
            f.write(md_css)
            f.write('\n')
            f.write(rst_css)
예제 #34
0
def export():
    if not os.path.exists(PYGMENTS_PATH):
        os.makedirs(PYGMENTS_PATH)

    styles = list(get_all_styles())

    for style in styles:
        print("Generating CSS for %s" % style)

        opts = {
            "style": style,
            "noclasses": False,
            "nobackground": False,
        }

        path = os.path.join(PYGMENTS_PATH, "%s.css" % style)
        formatter = HtmlFormatter(**opts)
        md_css = formatter.get_style_defs(".highlight")
        rst_css = formatter.get_style_defs(".literal-block")

        with open(path, "w+") as f:
            f.write(md_css)
            f.write("\n")
            f.write(rst_css)
예제 #35
0
    def nice_web_response(self, instance):
        # Convert the data to sorted, indented JSON
        data = copy(instance.web_response)
        if data:
            if 'image' in data:
                del data['image']
            if 'resources' in data:
                del data['resources']
        response = json.dumps(data, indent=2)
        formatter = HtmlFormatter(style='colorful')
        response = highlight(response, JsonLexer(), formatter)
        style = "<style>" + formatter.get_style_defs() + "</style><br>"

        # Safe the output
        return mark_safe(style + response)
def render_code(instance, style_name='default'):
    # Some interesting options in the HtmlFormatter:
    # - nowrap       -> no wrap inside <pre>
    # - classprefix  -> prefix for the classnames
    # - noclasses    -> all inline styles.
    #
    # To get_style_defs(), you can pass a selector prefix.
    #
    style = styles.get_style_by_name(style_name)
    formatter = HtmlFormatter(linenos=instance.linenumbers, style=style, nowrap=True, classprefix='code%s-' % instance.pk)
    html = highlight(instance.code, get_lexer_by_name(instance.language), formatter)
    css = formatter.get_style_defs()

    # Included in a DIV, so the next item will be displayed below.
    return '<div class="code"><style type="text/css">' + css + '</style>\n<pre>' + html + '</pre></div>\n'
예제 #37
0
    def detail_json_formatted(self):

        # dump the json with indentation set

        # example for detail_text TextField
        json_obj = json.loads(self.detail_json)
        data = json.dumps(json_obj, indent=2)

        # format it with pygments and highlight it
        formatter = HtmlFormatter(style='colorful')
        response = highlight(data, JsonLexer(), formatter)

        # include the style sheet
        style = "<style>" + formatter.get_style_defs() + "</style><br/>"

        return mark_safe(style + response)
    def export(
        source_file: SourceFile,
        document_tree,
        traceability_index: TraceabilityIndex,
        link_renderer,
    ):
        output = ""

        template = SourceFileViewHTMLGenerator.env.get_template(
            "source_file_view/source_file_view.jinja.html")

        with open(source_file.full_path) as f:
            source_file_lines = f.readlines()

        markup_renderer = MarkupRenderer()

        html_formatter = HtmlFormatter()
        pygmented_source_file_content = highlight("".join(source_file_lines),
                                                  PythonLexer(),
                                                  html_formatter)

        # Ugly hack to split content into lines: Cutting off:
        # <div class="highlight"><pre> and </pre></div>
        # TODO: Implement proper splitting.
        assert pygmented_source_file_content.startswith(
            '<div class="highlight"><pre>')
        assert pygmented_source_file_content.endswith(
            "</pre></div>\n"), f"{pygmented_source_file_content}"
        pygmented_source_file_content = pygmented_source_file_content[
            28:len(pygmented_source_file_content) - 13]
        pygmented_source_file_lines = pygmented_source_file_content.split("\n")
        if pygmented_source_file_lines[-1] == "":
            pygmented_source_file_lines.pop()

        pygments_styles = html_formatter.get_style_defs(".highlight")
        output += template.render(
            source_file=source_file,
            source_file_lines=source_file_lines,
            pygments_styles=pygments_styles,
            source_file_content=pygmented_source_file_lines,
            traceability_index=traceability_index,
            link_renderer=link_renderer,
            renderer=markup_renderer,
            document_type=DocumentType.document(),
        )
        return output
예제 #39
0
def dump(nb, fp, nb_name):
    doc = Document(title=nb_name)
    langinfo = nb.metadata.get('language_info', {})
    lexer_name = langinfo.get('pygments_lexer', langinfo.get('name', None))
    lexer = _get_pygments_lexer(lexer_name)
    formatter = HtmlFormatter()
    pygments_styles = Style(formatter.get_style_defs())
    doc.append_head(pygments_styles)
    metadata_et = Script(script=json.dumps(nb.metadata))
    metadata_et.id = "nb_metadata"
    metadata_et.set_attribute('type', 'application/json')
    doc.append_head(metadata_et)
    doc.append_body(NotebookElement(nb, lexer, formatter))

    for fragment in doc:
        #print(repr(fragment))
        fp.write(fragment)
예제 #40
0
def export():
    if not os.path.exists(PYGMENTS_PATH):
        os.makedirs(PYGMENTS_PATH)

    styles = list(get_all_styles())

    for style in styles:
        print("Generating CSS for %s" % style)

        opts = {"style": style}

        path = os.path.join(PYGMENTS_PATH, "%s.css" % style)
        formatter = HtmlFormatter(**opts)
        css_content = formatter.get_style_defs()
        # little fix because pelican doesn't append background color.
        css_content = css_content.replace(".hll", ".highlight")

        with open(path, "w") as f:
            f.write(css_content)
예제 #41
0
파일: generate.py 프로젝트: nrjones8/blog
def export():
    if not os.path.exists(PYGMENTS_PATH):
        os.makedirs(PYGMENTS_PATH)

    styles = list(get_all_styles())

    for style in styles:
        print('Generating CSS for %s' % style)

        opts = {
            'style': style,
            'noclasses': False,
            'nobackground': False,
        }

        path = os.path.join(PYGMENTS_PATH, '%s.css' % style)
        formatter = HtmlFormatter(**opts)
        css_content = formatter.get_style_defs('.highlight')

        with open(path, 'w') as f:
            f.write(css_content)