def format(self, format: Literal['html', 'shell']) -> str: stack = traceback.format_exception(*self.exc_info) # remove the fist element in the trace which refers to this file # (element 0 is the standard "Traceback (most recent call last):" message, hence removing element 1) stack.pop(1) tb = ''.join(stack) if format == 'html': h = pyg_highlight(tb, lexer=tb_lexer, formatter=html_formatter).rstrip('\n') return Markup(f'<span class="highlight">{h}</span>') else: return pyg_highlight(tb, lexer=tb_lexer, formatter=shell_formatter).rstrip('\n')
def highlight(src, syntax="python"): # type: (t.Text, t.Text) -> t.Text """Apply syntax highlighting. Only available if pygments is installed.""" if syntax == "xml": src = " " * 80 + src src = textwrap.dedent(src).strip() if not config.color: return src try: from pygments import highlight as pyg_highlight from pygments.lexers import PythonLexer, XmlLexer, RstLexer from pygments.formatters.terminal import TerminalFormatter except ImportError: return src else: if syntax == "python": lexer = PythonLexer() elif syntax == "xml": lexer = XmlLexer() elif syntax == "rst": lexer = RstLexer() else: raise ValueError("Unknown syntax {!r}".format(syntax)) return pyg_highlight(src, lexer, TerminalFormatter()).strip() # type: ignore
def highlight_code(format: str, code: str) -> Markup: try: lexer = get_lexer_by_name(format, stripall=True) except ClassNotFound: lexer = None if lexer: h = pyg_highlight(code, lexer=lexer, formatter=html_formatter).strip('\n') return Markup(f'<span class="highlight">{h}</span>') else: return Markup(f'<span class="raw">{escape_html(code)}</span>')
def highlight(text, lexer="diff", formatter="terminal"): """Highlight text with pygments Returns text untouched if colour output is not enabled :param str text: Text to highlight :param str lexer: Jinja lexer to use :param str formatter: :rtype: ``str`` :return: Syntax highlighted output, when possible """ if utils.T.is_a_tty: lexer = get_lexer_by_name(lexer) formatter = get_formatter_by_name(formatter) return pyg_highlight(text, lexer, formatter) else: return text
def render_highlighted(paste, lexer=None): text = False if paste.lexer == 'detect': lexer = guess_lexer(paste.code) #guess lexer tries to determine a lexer from the source text else: lexer = get_lexer_by_name(paste.lexer) #Get lexer object from lexer list if not lexer: lexer = get_lexer_by_name("text") text = True formatter = HtmlFormatter(linenos='table', style="monokai") highlighted = pyg_highlight(paste.code, lexer, formatter) #Highlight styles = '' if not text: styles = formatter.get_style_defs() highlighted = highlighted.replace('\t', '<span class="tabmargin"></span><span class="tabspan">\t</span>') print highlighted return highlighted, styles, lexer.name
def highlight(text, lexer='diff', formatter='terminal'): """Highlight text highlighted using ``pygments``. Returns text untouched if colour output is not enabled See: :pypi:`Pygments` Args: text (str): Text to highlight lexer (str): Jinja lexer to use formatter (str): Jinja formatter to use Returns: str: Syntax highlighted output, when possible """ if sys.stdout.isatty(): lexer = get_lexer_by_name(lexer) formatter = get_formatter_by_name(formatter) return pyg_highlight(text, lexer, formatter) else: return text
def highlight(__text: str, lexer: Optional[str] = 'diff', formatter: Optional[str] = 'terminal') -> str: """Highlight text with pygments. Returns text untouched if colour output is not enabled Args: __text: Text to highlight lexer: Jinja lexer to use formatter: Jinja formatter to use Returns: Syntax highlighted output, when possible """ if sys.stdout.isatty(): lexer = get_lexer_by_name(lexer) formatter = get_formatter_by_name(formatter) return pyg_highlight(__text, lexer, formatter) else: return __text
def highlight(__text: str, *, lexer: str = 'diff', formatter: str = 'terminal') -> str: """Highlight text highlighted using ``pygments``. Returns text untouched if colour output is not enabled. See also: :pypi:`Pygments` Args: __text: Text to highlight lexer: Jinja lexer to use formatter: Jinja formatter to use Returns: Syntax highlighted output, when possible """ if sys.stdout.isatty(): lexer = get_lexer_by_name(lexer) formatter = get_formatter_by_name(formatter) __text = pyg_highlight(__text, lexer, formatter) return __text
def highlight(source, sections, preserve_paths=True, outdir=None): if not outdir: raise TypeError("Missing the required 'outdir' keyword argument.") language = get_language(source) divider_text = "\n" + language["symbol"] + "DIVIDER\n" divider_html = re.compile(r'\n*<span class="c[1]?">'+ language["symbol"] + 'DIVIDER</span>\n*') output = pyg_highlight(divider_text.join(section["code"] for section in sections), lexers.get_lexer_by_name(language["lexer"]), formatters.HtmlFormatter(nowrap=True)) fragments = re.split(divider_html, output) for i, tp in enumerate(zip(sections, fragments)): section, fragment = tp section["code_html"] = "<div class='highlight'><pre>{0}</pre></div>".format(fragment) try: docs_text = unicode(section["doc"]) except UnicodeError: docs_text = unicode(section["doc"].decode('utf-8')) section["docs_html"] = markdown(inspect.cleandoc(docs_text), ['extra']) section["num"] = i
def _to_html(things, highlight): result = [] textify_html = lambda s: textify(s, 'html') for thing in things: if isinstance(thing, Code): code = str(thing) if highlight: try: lexer = get_lexer_by_name(thing.language, stripall=True) except ClassNotFound: lexer = guess_lexer(code) formatter = HtmlFormatter(style=get_style_by_name('emacs'), linenos=True, cssclass='highlight') text = pyg_highlight(code, lexer, formatter) else: text = '<pre>%s</pre>' % code result.append(text) elif isinstance(thing, DefinitionList): result.append('<dl>') result.extend(_to_html(thing.things, highlight)) result.append('</dl>') elif isinstance(thing, DefinitionItem): result.append('<dt>%s</dt>' % textify_html(thing.term)) result.append('<dd>%s</dd>' % textify_html(thing.description)) elif isinstance(thing, Header): args = { 'level': thing.level, 'text': textify_html(thing)} text = '<h%(level)d>%(text)s</h%(level)d>' % args result.append(text) elif isinstance(thing, List): tag = 'ol' if thing.ordered else 'ul' result.append('<%s>' % tag) result.extend(_to_html(thing.things, highlight)) result.append('</%s>' % tag) elif isinstance(thing, ListItem): if thing.things: result.append('<li>%s' % textify_html(thing)) result.extend(_to_html(thing.things, highlight)) result.append('</li>') else: text = '<li>%s</li>' % textify_html(thing) result.append(text) elif isinstance(thing, Paragraph): lines = (textify_html(line) for line in thing.lines) text = '<p>%s</p>' % ' '.join(lines) result.append(text) elif isinstance(thing, Table): result.append('<table>') result.extend(_to_html(thing.things, highlight)) result.append('</table>') elif isinstance(thing, TableRow): tag = 'th' if thing.is_header else 'td' fmt = '</%(tag)s><%(tag)s>' % {'tag': tag} args = { 'tag': tag, 'text': fmt.join(textify_html(col) for col in thing.cols) } text = '<%(tag)s>%(text)s</%(tag)s>' % args result.append('<tr>') result.append(text) result.append('</tr>') return result