How to use the pygments.formatters.HtmlFormatter function in Pygments

To help you get started, we’ve selected a few Pygments examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github windelbouwman / ppci-mirror / tools / analyze_c_code.py View on Github external
'NameLocationtyp',
            file=f)
        for func in functions:
            tagname = get_tag(func.location.filename)
            name = '<a href="#{2}-{1}">{0}</a>'.format(func.name, func.location.row, tagname)
            print(
                '{0}{1}{2}'.format(
                    name, '', ''),
                file=f)

        print('', file=f)
        print('<h1>Files</h1>', file=f)

        for source_filename, source_code, ast in asts:
            tagname = get_tag(source_filename)
            formatter = HtmlFormatter(lineanchors=tagname, linenos='inline')
            print('<h2>{}</h2>'.format(source_filename), file=f)
            print('', file=f)
            print(
                '',
                file=f)
            for decl in ast.declarations:
                if isinstance(decl, declarations.VariableDeclaration):
                    tp = 'var'
                elif isinstance(decl, declarations.FunctionDeclaration):
                    tp = 'func'
                else:
                    tp = 'other'

                tp += str(decl.storage_class)

                if source_filename == decl.location.filename:<table><tbody><tr><th>Name</th><th>Location</th><th>typ</th></tr></tbody></table>
github CenterForOpenScience / osf.io / mfr / renderer / code / __init__.py View on Github external
def _render(self, file_pointer, url):
        formatter = pygments.formatters.HtmlFormatter()
        content = file_pointer.read()
        try:
            lexer = pygments.lexers.guess_lexer_for_filename(
                file_pointer.name, content
            )
        except ClassNotFound:
            lexer = pygments.lexers.guess_lexer(content)
        highlight = pygments.highlight(content, lexer, formatter)
        link = 'href="{}/code/css/style.css" /&gt;'.format(self.STATIC_PATH)
        return '
github chrissimpkins / codeface / scripts / old_scripts / render_AK.py View on Github external
help = "background color and opacity" )
parser.add_argument( "-p", "--pad", default = 4, type = int,
                     help = "padding in pixels around image" )
parser.add_argument( "-x", "--width", default = 0, type = int,
                     help = "minimum width of image to generate" )
parser.add_argument( "-y", "--height", default = 0, type = int,
                     help = "minimum height of image to generate" )
args = parser.parse_args()

# Read sample text in (may be utf-8) and optionally syntax highlight it
# with Pygments.  The markup will be adapted for Pango.

with codecs.open( args.text, encoding = "utf-8" ) as source:
    text = source.read().strip( "\n" )
lexer = pygments.lexers.get_lexer_by_name( args.lang )
formatter = pygments.formatters.HtmlFormatter(
    noclasses = True,
    nowrap = True,
    style = args.style )
text = pygments.highlight( text, lexer, formatter )
text = re.sub( "style=\"color: (#[0-9A-Fa-f]{6})(?:; )?",
               "foreground=\"\\1\" style=\"", text )
if args.regular:
    text = re.sub( "style=\"font-weight: bold(?:; )?",
                   "style=\"", text )
    text = re.sub( "style=\"font-style: italic(?:; )?",
                   "style=\"", text )
else:
    text = re.sub( "style=\"font-weight: bold(?:; )?",
                   "weight=\"bold\" style=\"", text )
    text = re.sub( "style=\"font-style: italic(?:; )?",
                   "style=\"italic\" style=\"", text )
github pengutronix / flamingo / flamingo / plugins / rst / pygments.py View on Github external
def run(self):
            try:
                if self.arguments:
                    lexer = get_lexer_by_name(self.arguments[0])

                else:
                    lexer = guess_lexer('\n'.join(self.content))

            except (ClassNotFound, IndexError):
                lexer = get_lexer_by_name('text')

            formatter = HtmlFormatter()
            content = highlight('\n'.join(self.content), lexer, formatter)

            # find template
            template = self.options.get(
                'template', context.settings.DEFAULT_CODE_BLOCK_TEMPLATE)

            node_content = context.templating_engine.render(
                template,
                {
                    'context': context,
                    'content': content,
                    'license': self.options.get('license', ''),
                },
                handle_exceptions=False,
            )
github sqlalchemy / sqlalchemy / doc / build / builder / builders.py View on Github external
for ttype, value in apply_filters(tokensource, [StripDocTestFilter()]):
            if ttype in Token.Sql:
                for t, v in HtmlFormatter._format_lines(self, iter(buf)):
                    yield t, v
                buf = []

                if ttype is Token.Sql:
                    yield 1, "<div class="show_sql">%s</div>" % re.sub(r'(?:[{stop}|\n]*)$', '', value)
                elif ttype is Token.Sql.Link:
                    yield 1, "<a class="sql_link" href="#">sql</a>"
                elif ttype is Token.Sql.Popup:
                    yield 1, "<div class="popup_sql">%s</div>" % re.sub(r'(?:[{stop}|\n]*)$', '', value)
            else:
                buf.append((ttype, value))

        for t, v in _strip_trailing_whitespace(HtmlFormatter._format_lines(self, iter(buf))):
            yield t, v
github kylewm / redwind / scripts / update_static_resources.py View on Github external
import requests
import pygments.formatters
import shutil

#['fruity', 'perldoc', 'trac', 'native', 'autumn', 'emacs', 'vs',
#'rrt', 'colorful', 'monokai', 'pastie', 'default', 'borland',
#'manni', 'vim', 'bw', 'friendly', 'tango', 'murphy']
PYGMENTS_STYLE = 'tango'
pygments_css = (pygments.formatters.HtmlFormatter(style=PYGMENTS_STYLE)
                .get_style_defs('.codehilite'))
with open('redwind/skeletal/static/css/pygments.css', 'w') as f:
    f.write(pygments_css)


def curl(url, file):
    response = requests.get(url, stream=True)
    with open(file, 'wb') as f:
        shutil.copyfileobj(response.raw, f)
        del response


for s in [ 60, 76, 114, 152 ]:
    curl('http://www.gravatar.com/avatar/767447312a2f39bec228c3925e3edf74?s={}'.format(s),
         'redwind/skeletal/static/img/users/kyle{}.jpg'.format(s))
github flexxui / flexx / docs / scripts / pyscriptexample.py View on Github external
def my_highlight(code):
    return highlight(code, PythonLexer(), HtmlFormatter())
github brosner / oebfare / oebfare_project / apps / blog / templatetags / blog_utils.py View on Github external
def pygments_directive(name, arguments, options, content, lineno,
                       content_offset, block_text, state, state_machine):
    try:
        lexer = get_lexer_by_name(arguments[0])
    except (ValueError, IndexError):
        # no lexer found - use the text one instead of an exception
        lexer = TextLexer()
    parsed = highlight(u"\n".join(content), lexer, HtmlFormatter())
    return [nodes.raw("", parsed, format="html")]
pygments_directive.arguments = (0, 1, False)
github merengue-cms / merengueproj / merengueproj / merengue / apps / debug_toolbar / panels / sql.py View on Github external
def reformat_sql(sql):
    sql = sql.replace('`,`', '`, `')
    sql = sql.replace('SELECT ', 'SELECT\n\t')
    sql = sql.replace('` FROM ', '`\nFROM\n\t')
    sql = sql.replace('` WHERE ', '`\nWHERE\n\t')
    sql = sql.replace('` INNER JOIN ', '`\nINNER JOIN\n\t')
    sql = sql.replace('` OUTER JOIN ', '`\nOUTER JOIN\n\t')
    sql = sql.replace(' ORDER BY ', '\nORDER BY\n\t')
    # Use Pygments to highlight SQL if it's available
    try:
        from pygments import highlight
        from pygments.lexers import SqlLexer
        from pygments.formatters import HtmlFormatter
        sql = highlight(sql, SqlLexer(), HtmlFormatter())
    except ImportError:
        pass
    return sql
github kovidgoyal / calibre / src / calibre / ebooks / markdown / extensions / codehilite.py View on Github external
if self.lang is None:
            self._getLang()

        if pygments:
            try:
                lexer = get_lexer_by_name(self.lang)
            except ValueError:
                try:
                    if self.guess_lang:
                        lexer = guess_lexer(self.src)
                    else:
                        lexer = TextLexer()
                except ValueError:
                    lexer = TextLexer()
            formatter = HtmlFormatter(linenos=self.linenums,
                                      cssclass=self.css_class,
                                      style=self.style,
                                      noclasses=self.noclasses)
            return highlight(self.src, lexer, formatter)
        else:
            # just escape and build markup usable by JS highlighting libs
            txt = self.src.replace('&amp;', '&amp;')
            txt = txt.replace('&lt;', '&lt;')
            txt = txt.replace('&gt;', '&gt;')
            txt = txt.replace('"', '"')
            classes = []
            if self.lang:
                classes.append('language-%s' % self.lang)
            if self.linenums:
                classes.append('linenums')
            class_str = ''