def pygmentize(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value lexer = None for klass in classes: if klass == "commonlisp": klass = "lisp" try: lexer = get_lexer_by_name(klass) break except: pass if lexer is None: try: lexer = guess_lexer(code) except: lexer = TextLexer() if format == "html5": format = "html" if format == "html": formatter = get_formatter_by_name(format) \ .__class__(cssclass="highlight " + klass) else: formatter = get_formatter_by_name(format) return RawBlock(format, highlight(code, lexer, formatter))
def onMenuCodeStyleChanged(self, label, checked): if not label: return self.settings.setValue('pygments', label) pygments_rst_path = os.path.join( __home_data_path__, 'themes', 'reStructuredText', 'pygments.css') pygments_md_path = os.path.join( __home_data_path__, 'themes', 'Markdown', 'pygments.css') comment = """ /* * +---------------+ * | pygment style | * +---------------+ */\n""" with open(pygments_rst_path, 'wb') as f: f.write(toBytes(comment)) if label != 'null': formatter = get_formatter_by_name('html', style=label) f.write(toBytes(formatter.get_style_defs('pre.code'))) with open(pygments_md_path, 'wb') as f: f.write(toBytes(comment)) if label != 'null': formatter = get_formatter_by_name('html', style=label) f.write(toBytes(formatter.get_style_defs('.codehilite'))) self.previewCurrentText() self.showMessage( self.tr('pygments change: %s' % label))
def serve_language_css(style): try: fmt = formatters.get_formatter_by_name('html', style=style) except: util.log.warn('Style "%s" cannot be found, falling back to default' % (style, )) fmt = formatters.get_formatter_by_name('html') bottle.response.content_type = 'text/css' return fmt.get_style_defs(['.pygmentized'])
def get_pygment_style(style, css_class='codehilite'): """Get the specified pygments sytle CSS.""" try: # Try and request pygments to generate it text = get_formatter_by_name('html', style=style).get_style_defs('.' + css_class) except Exception: # Try and request pygments to generate default text = get_formatter_by_name('html', style="default").get_style_defs('.' + css_class) return '<style>\n%s\n</style>\n' % text if text is not None else ""
def serve_language_css(style): try: fmt = formatters.get_formatter_by_name('html', style=style) except: util.log.warn( 'Style "%s" cannot be found, falling back to default' % (style,) ) fmt = formatters.get_formatter_by_name('html') bottle.response.content_type = 'text/css' return fmt.get_style_defs(['.pygmentized'])
def get_pygment_style(style, css_class='codehilite'): """Get the specified pygments sytle CSS.""" try: # Try and request pygments to generate it text = get_formatter_by_name( 'html', style=style).get_style_defs('.' + css_class) except Exception: # Try and request pygments to generate default text = get_formatter_by_name( 'html', style="default").get_style_defs('.' + css_class) return '<style>\n%s\n</style>\n' % text if text is not None else ""
def setUpClass(cls): root_path = os.path.dirname(os.path.dirname(__file__)) lexer_filename = os.path.join(root_path, 'pybemolle', 'lexers.py') cls.lexer = load_lexer_from_file(lexer_filename, 'BemolleLexer') cls.formatter = get_formatter_by_name('html', style='bemolle', noclasses=True)
def output_json(json): click.secho( highlight( _format_response(json), lexers.get_lexer_by_name("json"), formatters.get_formatter_by_name("terminal"), ))
def render(self, value, context): src = value['code'].strip('\n') lang = value['language'] lexer = get_lexer_by_name(lang) formatter = get_formatter_by_name( 'html', linenos=None, cssclass='codehilite', style='default', noclasses=False, ) return mark_safe(highlight(src, lexer, formatter)) # class MarkDownBlock(blocks.TextBlock): # """ MarkDown Block """ # # class Meta: # icon = 'code' # # def render_basic(self, value): # md = markdown( # value, # [ # 'markdown.extensions.fenced_code', # 'codehilite', # ], # ) # return mark_safe(md)
def hljsx(code): lexer = get_lexer_by_name('jsx') formatter = get_formatter_by_name('html') hl = highlight(code, lexer, formatter) if isinstance(hl, str): return hl return hl.encode('utf-8')
def make_highlight(language, fontsize, style, inp, line_width) -> None: """ Highlight code for keynote.app from clipboard and save result to clipboard. STYLE Style for code FONTSIZE Font size to use LANGUAGE Programming language of source code INP What is the source of code LINE-WIDTH python only. Format code to fit width """ lexer = get_lexer_by_name(language) click.echo(f"Using lexer {lexer}") code = (pyperclip.paste() if inp == "clipboard" else click.edit( text=pyperclip.paste(), extension=lexer.filenames[0][1:])) if language == "python": code = black.format_str(code, mode=black.Mode(line_length=line_width)) click.echo( f"Got code from clipboard that starts with {click.style(code[:20], fg='blue')}..." ) res = highlight( code, lexer, get_formatter_by_name("rtf", style=get_style_by_name(style), fontsize=fontsize), ) click.echo("Highlighted") pyperclip.copy(res) click.echo("Done!")
def _visit_source(self, node): lexer = get_lexer_by_name(node["language"]) formatter = get_formatter_by_name("html") src = "\n".join([i["value"] for i in node["code"]]) highlighted_src = highlight(src, lexer, formatter) highlighted_src_lines = highlighted_src.split("\n") callouts = {} for linenum, callout in node["callouts"].items(): callout_name, callout_text = callout highlighted_src_lines[linenum] = "{line} {callout}".format( line=highlighted_src_lines[linenum], callout=self._render("callout", name=callout_name), ) callouts[callout_name] = callout_text highlighted_src = "\n".join(highlighted_src_lines) callouts_list = [(self._render("callout", name=name), text) for name, text in callouts.items()] return { "code": highlighted_src, "language": node["language"], "callouts": callouts_list, "title": self.visit(node["title"]), }
def pygmentize(key, value, format, meta): if key == 'CodeBlock': #LOG("key : {}\n value : {}\n format : {}\n meta : {}\n\n\n".format(key, value, format, meta)) [[ident, classes, keyvals], code] = value lexer = None for klass in classes: try: lexer = get_lexer_by_name(klass) break except: pass if lexer is None: try: lexer = guess_lexer(code) except: lexer = TextLexer() options = {} if ('numberLines' in value[0][1]): options['linenos'] = 'table' return [ RawBlock( format, highlight(code, lexer, get_formatter_by_name(format, **options))) ]
def render(self, value): src = value["code"].strip("\n") lang = value["language"] lexer = get_lexer_by_name(lang) formatter = get_formatter_by_name("html", linenos=None, cssclass="codehilite", style="default", noclasses=False) return mark_safe(highlight(src, lexer, formatter))
def get_printer(mode='auto'): """ Generate printer function. :param mode: string: always, never or auto :return: """ def printer(data): print(data) if mode in ('auto', 'always'): try: from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import get_formatter_by_name if mode == 'always' or sys.stdout.isatty(): lexer = get_lexer_by_name('json') formatter = get_formatter_by_name('terminal256') def printer(data): print(highlight(data, lexer, formatter), end='', file=sys.stdout) except ImportError as e: if mode == 'always': import warnings warnings.warn('No pygments module available, cannot colorize output') return printer
def process_request(json_data): log.debug('Processing: path: %s\n%s:%s' % (json_data['fullPath'], json_data['action'], json_data['language'])) try: code = json_data['code'] fmter = get_formatter_by_name(json_data['outformat'], linenos = json_data['linenos'], lineanchors = json_data['lineanchors']) fmter.encoding = json_data['encoding'] lexer = get_lexer_by_name(json_data['language']) return highlight(code, lexer, fmter) except ValueError as err: log.error(err) return ''' <h1><a href="http://pygments.org">Pygments</a> failed to highlight this file</h1> <div>You should consider filing a bug report or provide a bug fix to help the community ;)</div> <div> The Error was: <pre>%s</pre> </div> <div> The code that was parsed is: <pre>%s</pre> </div> ''' % (err, code)
def get_context(self, value, parent_context=None): context = super().get_context(value, parent_context=parent_context) src = value.get('code') or '' src = src.strip('\n') lang = value.get('language') or '' line_numbers = value['line_numbers'] if lang: lexer = get_lexer_by_name(lang) else: lexer = guess_lexer(src) formatter = get_formatter_by_name( 'html', linenos=line_numbers, cssclass='codehilite', style='default', noclasses=False, ) context.update({ 'filename': value.get('filename'), 'display_filename': value.get('display_filename'), 'language': value.get('lang'), 'code': mark_safe(highlight(src, lexer, formatter)) }) return context
def highlight(content, lexer_name, formatter): try: lexer = get_lexer_by_name(lexer_name) except ClassNotFound: if lexer_name != '': return "No such lexer.", 400 if formatter and formatter != 'html': formatter = get_formatter_by_name(formatter) else: formatter = HtmlFormatter(linenos='table', anchorlinenos=True, lineanchors='L', linespans='L') if lexer_name == '': tokens = ((Token.Text, '{}\n'.format(c.decode('utf-8'))) for c in content.splitlines()) content = _format(tokens, formatter) else: content = _highlight(content, lexer, formatter) if not isinstance(formatter, HtmlFormatter): return content template = render_template("generic.html", cc='container-fluid', content=content, **style_args()) return template
def format(self, code, language): if language == "": lexer = guess_lexer(code) else: lexer = get_lexer_by_name(language) formatter = get_formatter_by_name(self.formatname) return highlight(code, lexer, formatter)
def highlight(sections, language, preserve_paths=True, outdir=None): """ Highlights a single chunk of code using the **Pygments** module, and runs the text of its corresponding comment through **Markdown**. We process the entire file in a single call to Pygments by inserting little marker comments between each section and then splitting the result string wherever our markers occur. """ if not outdir: raise TypeError("Missing the required 'outdir' keyword argument.") output = pygments.highlight( language["divider_text"].join(section["code_text"].rstrip() for section in sections), language["lexer"], formatters.get_formatter_by_name("html")) output = output.replace(highlight_start, "").replace(highlight_end, "") fragments = re.split(language["divider_html"], output) for i, section in enumerate(sections): section["code_html"] = highlight_start + \ shift(fragments, "") + highlight_end try: docs_text = unicode(section["docs_text"]) except UnicodeError: docs_text = unicode(section["docs_text"].decode('utf-8')) except NameError: docs_text = section['docs_text'] section["docs_html"] = markdown( preprocess(docs_text, preserve_paths=preserve_paths, outdir=outdir)) section["num"] = i return sections
def ConvertCodeToHtml(self, code): from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import get_formatter_by_name lexer = get_lexer_by_name('python') formatter = get_formatter_by_name('html', noclasses=True) return highlight(code, lexer, formatter)
def __init__(self, fmt=None, datefmt=None, style='%', options=None, pygments_lexer='postgres-console', pygments_formatter="terminal256", pygments_style="default"): ''' Args: fmt: (str): The logging.Formatter format string datefmt (str): The logging.Formatter date format string style (str): The logging.Formatter format string type options (dict): Dict of options to pass to sqlparse.format() pygments_lexer (str): The name of the pygments lexer to use. Examples include: 'postgres-console', 'postgres', 'rql', 'sql', 'sqlite3', 'mysql', 'plpgsql', 'tsql' pygments_formatter (str): The name of the pygments formatter to use. Examples include: 'terminal256', 'terminal', 'terminal16m', 'text' pygments_style (str): The name of the pygments formatter style to use. ''' super(DjangoDbSqlColorFormatter, self).__init__(fmt=fmt, datefmt=datefmt, style=style) self.options = options or {'reindent': True, 'keyword_case': 'upper'} # postgres-console, postgres, rql, sql, sqlite3, mysql, plpgsql, tsql self._lexer = get_lexer_by_name(pygments_lexer) pygments_style = get_style_by_name(pygments_style) # terminal256, terminal, terminal16m, text self._formatter = get_formatter_by_name(pygments_formatter, style=pygments_style)
def highlight(sections, language, preserve_paths=True, outdir=None): """ Highlights a single chunk of code using the **Pygments** module, and runs the text of its corresponding comment through **Markdown**. We process the entire file in a single call to Pygments by inserting little marker comments between each section and then splitting the result string wherever our markers occur. """ if not outdir: raise TypeError("Missing the required 'outdir' keyword argument.") output = pygments.highlight(language["divider_text"].join(section["code_text"].rstrip() for section in sections), language["lexer"], formatters.get_formatter_by_name("html")) output = output.replace(highlight_start, "").replace(highlight_end, "") fragments = re.split(language["divider_html"], output) for i, section in enumerate(sections): section["code_html"] = highlight_start + \ shift(fragments, "") + highlight_end try: docs_text = unicode(section["docs_text"]) except UnicodeError: docs_text = unicode(section["docs_text"].decode('utf-8')) except NameError: docs_text = section['docs_text'] section["docs_html"] = markdown(preprocess(docs_text, preserve_paths=preserve_paths, outdir=outdir)) section["num"] = i return sections
def pretty(ob, lexer=None): """ Return a pretty console text representation of 'ob'. If 'ob' is something else than plain text, specify it in 'lexer'. If 'ob' is not string, Json lexer is assumed. Command line switches can be used to control highlighting and style. """ if lexer is None: if isinstance(ob, basestring): lexer = 'text' else: lexer = 'json' if lexer == 'json': ob = json.dumps(ob, indent=4, sort_keys=True) if got_pygments: lexerob = get_lexer_by_name(lexer) formatter = get_formatter_by_name(PRETTY_FORMATTER, style=PRETTY_STYLE) #from pygments.filters import * #lexerob.add_filter(VisibleWhitespaceFilter()) ret = highlight(ob, lexerob, formatter) else: ret = ob return ret.rstrip()
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)
def command(title, version, output): config = [{ "theme": "", "prefix": ".highlight", "style": "default" }, { "theme": "materials-dark", "prefix": ".materials-dark .highlight", "style": "stata-dark" }, { "theme": "materials-light", "prefix": ".materials-light .highlight", "style": "stata-light" }] with open(output, "w") as printcss: print(f"/* {title} version {version}", file=printcss) print(" *", file=printcss) print(" * This is pygments.css. This file is generated with Pygments.", file=printcss) print(" *", file=printcss) print(" * See https://xsltng.docbook.org/", file=printcss) print(" *", file=printcss) print(" */", file=printcss) for theme in config: parsed_opts = {"style": theme["style"]} formatter = get_formatter_by_name("html", **parsed_opts) print(formatter.get_style_defs(theme["prefix"]), file=printcss)
def create_code_css(): from pygments.formatters import get_formatter_by_name formatter = get_formatter_by_name('html', style=kw["code_color_scheme"]) utils.makedirs(os.path.dirname(code_css_path)) with codecs.open(code_css_path, 'wb+', 'utf8') as outf: outf.write(formatter.get_style_defs(kw["code.css_selectors"])) outf.write(kw["code.css_close"])
def create_code_css(): from pygments.formatters import get_formatter_by_name formatter = get_formatter_by_name('html', style=kw["code_color_scheme"]) utils.makedirs(os.path.dirname(code_css_path)) with codecs.open(code_css_path, 'wb+', 'utf8') as outf: outf.write(formatter.get_style_defs('pre.code')) outf.write("table.codetable { width: 100%;} td.linenos {text-align: right; width: 4em;}")
def get_formatter_by_name(alias, **options): """Gets a formatter instance from its name or alias. This mimics the behavior of ``pygments.formatters.get_formatter_by_name()``. """ if CACHE is None: load_or_build() names = CACHE["formatters"]["names"] if alias in names: modname, clsname = names[alias] mod = importlib.import_module(modname) cls = getattr(mod, clsname) formatter = cls(**options) else: # couldn't find formatter in cache, fallback to the hard way import inspect from pygments.formatters import get_formatter_by_name formatter = get_formatter_by_name(alias, **options) # add this filename to the cache for future use cls = type(formatter) mod = inspect.getmodule(cls) names[alias] = (mod.__name__, cls.__name__) write_cache(cache_filename()) return formatter
def get_printer(mode='auto'): """ Generate printer function. :param mode: string: always, never or auto :return: """ def printer(data): print(data) if mode in ('auto', 'always'): try: from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import get_formatter_by_name if mode == 'always' or sys.stdout.isatty(): lexer = get_lexer_by_name('json') formatter = get_formatter_by_name('terminal256') def printer(data): print(highlight(data, lexer, formatter), end='', file=sys.stdout) except ImportError as e: if mode == 'always': import warnings warnings.warn( 'No pygments module available, cannot colorize output') return printer
def diff_revs(wiki, user, rev, raw=False): diff = wiki.scm.diff(path=None, rev1=rev, rev2=None) if not raw: lexer = get_lexer_by_name('diff') formatter = get_formatter_by_name('html') diff = highlight(diff, lexer, formatter) return {'diff': diff, 'disp_rev': rev}
def exec(self): """処理を実行します。""" # -------------------------------------------------------------------------------- # pygments の基本的な使い方 # - http://pygments.org/ # # pygments を利用する場合、必要なオブジェクトは以下の3つ # - コード: ハイライト表示対象のコード # - 解析器(lexer): コードを解析するためのオブジェクト # - フォーマッタ: 最終的な出力を担当するオブジェクト # # lexer と formatter は、各実装クラスを直接つかってもいいが # 以下のヘルパー関数を使用しても取得できる # - pygments.lexers.get_lexer_by_name() # - 例えば、言語が python の場合は、"python" or "python3" となる # - http://pygments.org/docs/lexers/ # - pygments.formatters.get_formatter_by_name() # - 例えば、HTMLで出力したい場合は "html" となる # - http://pygments.org/docs/formatters/ # - HtmlFormatterは便利だが、残念な事にHTML4形式で現状出力されてしまう。 # # 必要なオブジェクトが揃ったら、後は pygments.highlight() に渡すと # 整形データが取得できる # -------------------------------------------------------------------------------- code = """\ def hello(): print('world') results = [] for x in range(10): ressults.append(i for i in x) """ lexer = get_lexer_by_name('python3') formatter = get_formatter_by_name('html', linenos=True, full=True, encoding='utf-8') # formatter に対して, 共通パラメータ [encoding] を指定した場合 # 結果として受け取るデータの型は、bytes になる。指定していない場合、str となる。 # HtmlFormatter にて encoding を指定しない場合、 charset の値が None となることに注意。 html = highlight(code, lexer, formatter) if hasattr(html, 'decode'): html = html.decode('utf-8') pr('pygments.html', html) file_path = (pathlib.Path.home() / 'pygments_test.html').as_posix() with open(file_path, 'w') as out_fp: out_fp.write(html) preserve_file = True try: if sys.platform == 'win32': cmd = shlex.split(f'cmd /C start {file_path}') else: cmd = shlex.split(f'open {file_path}') subprocess.check_call(cmd, shell=False) finally: if not preserve_file: os.unlink(file_path)
def hilite(self): """ Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with css to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">). returns : A string of html. """ 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') lang = lexer.aliases[0] formatter = get_formatter_by_name('html', linenos=self.linenums, cssclass=self.css_class, style=self.style, noclasses=self.noclasses, hl_lines=self.hl_lines) hilited_html = highlight(self.src, lexer, formatter) if self.wrap_by_lang and self.lang: return '<div class="%(class)s-%(lang)s">%(html)s</div>\n' % { 'class': self.css_class, 'lang': self.lang.replace('+', '-'), 'html': hilited_html, } else: return hilited_html else: # just escape and build markup usable by JS highlighting libs txt = self.src.replace('&', '&') txt = txt.replace('<', '<') txt = txt.replace('>', '>') txt = txt.replace('"', '"') classes = [] if self.lang: classes.append('language-%s' % self.lang) if self.linenums: classes.append('linenums') class_str = '' if classes: class_str = ' class="%s"' % ' '.join(classes) return '<pre class="%s"><code%s>%s</code></pre>\n' % \ (self.css_class, class_str, txt)
def traceback_code(self, task): formatter = get_formatter_by_name('html') if sys.version_info.major == 3: lexer = get_lexer_by_name('py3tb') else: lexer = get_lexer_by_name('pytb') style = formatter.get_style_defs('.highlight') return mark_safe('<style>{}</style><br/>{}'.format(style, highlight(task.traceback, lexer, formatter)))
def get_css(style: str, classname: str) -> Optional[str]: try: fmter = get_formatter_by_name(_FORMAT, style=style) except ClassNotFound: return None css = fmter.get_style_defs(f".{classname}") assert isinstance(css, str) return css
def _determine_formatter(style="default", colors=None, debug=False): colors = colors or _get_term_color_support() if debug: sys.stderr.write("Detected support for %s colors\n" % colors) if colors == 256: fmt_options = {'style': style} elif style in ('light', 'dark'): fmt_options = {'bg': style} else: fmt_options = {'bg': 'dark'} fmt_alias = 'terminal256' if colors == 256 else 'terminal' try: return get_formatter_by_name(fmt_alias, **fmt_options) except ClassNotFound as ex: if debug: sys.stderr.write(str(ex) + "\n") return get_formatter_by_name(fmt_alias)
def post(self): language=self.request.get('language') code=self.request.get('code') try: lexer = get_lexer_by_name(language, stripall=True) formatter = get_formatter_by_name('html', linenos=True, cssclass='pygmy') except ClassNotFound, e: self.render_error(500, { 'error' : e })
def create_code_css(): from pygments.formatters import get_formatter_by_name formatter = get_formatter_by_name("html", style=kw["code_color_scheme"]) utils.makedirs(os.path.dirname(code_css_path)) with codecs.open(code_css_path, "wb+", "utf8") as outf: outf.write(formatter.get_style_defs(["pre.code", "div.code pre"])) outf.write("\ntable.codetable { width: 100%;} td.linenos {text-align: right; width: 4em;}\n")
def highlight(context, body, syntax, format='html'): """Looks up the appropriate Pygments lexer for a given syntax and uses it to format the passed body. """ lexer = get_lexer_by_name(syntax) formatter = get_formatter_by_name(format) return pygments.highlight(body, lexer, formatter)
def create_code_css(): from pygments.formatters import get_formatter_by_name formatter = get_formatter_by_name('html', style=kw["code_color_scheme"]) utils.makedirs(os.path.dirname(code_css_path)) with io.open(code_css_path, 'w+', encoding='utf8') as outf: outf.write(kw["code.css_head"]) outf.write(formatter.get_style_defs(kw["code.css_selectors"])) outf.write(kw["code.css_close"])
def get_pygments_style(): try: from pygments.formatters import get_formatter_by_name except ImportError: return {} fmt = get_formatter_by_name('html', style='trac') return {'text/css': '/* Pygments */\n\n' + fmt.get_style_defs('.highlight')}
def colorprint(data, output_format="yaml"): """ Colorized print for either a yaml or a json document given as argument """ lexer = lexers.get_lexer_by_name(output_format) formatter = formatters.get_formatter_by_name("256") formatter.__init__(style=get_style_by_name('emacs')) colored = highlight(str(data, 'UTF-8'), lexer, formatter) sys.stdout.write(colored)
def pprn(format: str, theme: str, filename: Optional[PurePath], text: str) -> str: style = get_style_by_name(theme) formatter = get_formatter_by_name(format, style=style) lexer = _get_lexer(filename, text) pretty = highlight(text, lexer=lexer, formatter=formatter) return cast(str, pretty)
def format_HTML(filepath): with open(filepath, 'r') as file_to_read: data = file_to_read.read() lexer_object = guess_lexer_for_filename(filepath, data) pyg_formatter = get_formatter_by_name('html', linenos='table', style='monokai') return highlight(data, lexer_object, pyg_formatter)
def pygments_style(style): try: string = get_formatter_by_name('html', style=style).get_style_defs('.highlight') except ClassNotFound: logger.warning('Unknown Pygments style %s', style) string = '/* nothing */' return string
def test_get_formatters(): # test that the formatters functions work x = formatters.get_formatter_by_name("html", opt="val") assert isinstance(x, formatters.HtmlFormatter) assert x.options["opt"] == "val" x = formatters.get_formatter_for_filename("a.html", opt="val") assert isinstance(x, formatters.HtmlFormatter) assert x.options["opt"] == "val"
def get_text(self, node, **options): if options.get('plain'): return node.content formatter_name = options.get('formatter_name') if formatter_name: from pygments import highlight from pygments.formatters import get_formatter_by_name formatter = get_formatter_by_name(formatter_name) return highlight(node.content, node.lexer, formatter) return node.content
def higlight_code(text): try: from pygments.lexers import get_lexer_by_name from pygments.formatters import get_formatter_by_name from pygments.styles import ClassNotFound except ImportError: return text language = 'python' lexer = get_lexer_by_name(language) if not lexer: return text try: formatter = get_formatter_by_name('terminal256', style='alan') except ClassNotFound: formatter = get_formatter_by_name('terminal256', style='monokai') if not formatter: return text import pygments return pygments.highlight(text, lexer, formatter)
def onCodeStyleChanged(self, label, checked): self.pygments = label self.settings.setValue('pygments', self.pygments) pygments_style_path = os.path.join( __home_data_path__, 'themes', 'pygments.css') with open(pygments_style_path, 'wb') as f: if self.pygments != 'null': formatter = get_formatter_by_name('html', style=self.pygments) f.write(toBytes(formatter.get_style_defs('pre.code'))) self.previewCurrentText()
def formatter(self): colors = _get_term_color_support() if self.debug: sys.stderr.write("Detected support for %s colors\n" % colors) if colors == 256: fmt_options = {'style': self.style} elif self.style in ('light', 'dark'): fmt_options = {'bg': self.style} else: fmt_options = {'bg': 'dark'} from pygments.formatters import get_formatter_by_name import pygments.util fmt_alias = 'terminal256' if colors == 256 else 'terminal' try: return get_formatter_by_name(fmt_alias, **fmt_options) except pygments.util.ClassNotFound as ex: if self.debug: sys.stderr.write(str(ex) + "\n") return get_formatter_by_name(fmt_alias)
def highlight_code(code, lang): code = cleanup_code(code) try: lexer = get_lexer_by_name(lang, stripall=False) except ClassNotFound: logger.warning('Unknown Pygments language %s', lang) lexer = guess_lexer(code) return highlight(code, lexer, get_formatter_by_name('html'))
def __initialize(cls): """Initialize the object if needed""" if cls.formatter is None: name = Config.get("core.color", Formatter.NO_COLOR) if name == "auto": name = "terminal256" cls.formatter = get_formatter_by_name(name, style=OutputStyle, encoding=Formatter.ENCODING)
def raw_format(cls, tokens): """Format the given list of tokens as a simple string (no color) :param tokens: the input list of token to format :type tokens: tuple[Token, str] :rtype: str """ formatter = get_formatter_by_name(Formatter.NO_COLOR, encoding=Formatter.ENCODING) return pygments.format(tokens, formatter)
def highlight(code, lang='python'): """ Highlights source in the given programming language. """ formatter = get_formatter_by_name('html') try: lexer = get_lexer_by_name(lang) except ClassNotFound: lexer = get_lexer_by_name('python') return Markup(pygments_highlight(code, lexer, formatter))
def test_get_formatters(self): a = self.assert_ ae = self.assertEquals # test that the formatters functions work x = formatters.get_formatter_by_name("html", opt="val") a(isinstance(x, formatters.HtmlFormatter)) ae(x.options["opt"], "val") x = formatters.get_formatter_for_filename("a.html", opt="val") a(isinstance(x, formatters.HtmlFormatter)) ae(x.options["opt"], "val")