def render(self, context): code = self.code.resolve(context) lang = self.lang.resolve(context) lexer = get_lexer_by_name(PYGMENT_LANGUAGE_NAMES.get(lang, lang)) lexer.add_filter(VisibleWhitespaceFilter(tabsize=4)) formatter = HtmlFormatter(style="colorful") return highlight(code, lexer, formatter).replace("\n", "<br/>")
def setUp(self): self.log_printer = ListLogPrinter() self.console_printer = ConsolePrinter(print_colored=False) self.no_color = not self.console_printer.print_colored self.file_diff_dict = {} self.section = Section('t') self.local_bears = OrderedDict([('default', [SomelocalBear]), ('test', [SomelocalBear])]) self.global_bears = OrderedDict([('default', [SomeglobalBear]), ('test', [SomeglobalBear])]) self.old_open_editor_applicable = OpenEditorAction.is_applicable OpenEditorAction.is_applicable = staticmethod( lambda *args: 'OpenEditorAction cannot be applied') self.old_apply_patch_applicable = ApplyPatchAction.is_applicable ApplyPatchAction.is_applicable = staticmethod( lambda *args: 'ApplyPatchAction cannot be applied') self.lexer = TextLexer() self.lexer.add_filter( VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=SpacingHelper.DEFAULT_TAB_WIDTH)) patcher = patch('coalib.results.result_actions.OpenEditorAction.' 'subprocess') self.addCleanup(patcher.stop) patcher.start()
def python_prettify(code, style): lexer = PythonLexer() lexer.add_filter(VisibleWhitespaceFilter(spaces=" ")) pretty_code = highlight( code, lexer, HtmlFormatter( linenos=style, linenostart=0)) # print(pretty_code) return format_html('{}', mark_safe(pretty_code))
def __enter__(self): new_filters = list(self._orig_filters) new_filters.append( VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize)) self._lexer.filters = new_filters self._lexer.tabsize = 0 return self._lexer
def print_lines(console_printer, file_dict, sourcerange): """ Prints the lines between the current and the result line. If needed they will be shortened. :param console_printer: Object to print messages on the console. :param file_dict: A dictionary containing all files as values with filenames as key. :param sourcerange: The SourceRange object referring to the related lines to print. """ no_color = not console_printer.print_colored for i in range(sourcerange.start.line, sourcerange.end.line + 1): # Print affected file's line number in the sidebar. console_printer.print(format_lines(lines='', line_nr=i, symbol='['), color=FILE_LINES_COLOR, end='') line = file_dict[sourcerange.file][i - 1].rstrip('\n') try: lexer = get_lexer_for_filename(sourcerange.file) except ClassNotFound: lexer = TextLexer() lexer.add_filter( VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=SpacingHelper.DEFAULT_TAB_WIDTH)) # highlight() combines lexer and formatter to output a ``str`` # object. printed_chars = 0 if i == sourcerange.start.line and sourcerange.start.column: console_printer.print(highlight_text( no_color, line[:sourcerange.start.column - 1], BackgroundMessageStyle, lexer), end='') printed_chars = sourcerange.start.column - 1 if i == sourcerange.end.line and sourcerange.end.column: console_printer.print(highlight_text( no_color, line[printed_chars:sourcerange.end.column - 1], BackgroundSourceRangeStyle, lexer), end='') console_printer.print(highlight_text( no_color, line[sourcerange.end.column - 1:], BackgroundSourceRangeStyle, lexer), end='') console_printer.print('') else: console_printer.print(highlight_text(no_color, line[printed_chars:], BackgroundMessageStyle, lexer), end='') console_printer.print('')
def html_diff(diff, linenos='inline'): """Display diff as HTML""" if diff is None: return difflexer = DiffLexer() # Do not give whitespaces the special Whitespace token type as this # prevents the html formatter from picking up on trailing whitespaces in # the diff. difflexer.add_filter(VisibleWhitespaceFilter(wstokentype=False, tabs=True)) return highlight( diff, difflexer, HtmlFormatter(linenos=linenos, noclasses=True, style="diffstyle"))
def parse(self, parser): parser.stream.next() args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) lng_name = args[0].name body = parser.parse_statements(['name:endhighlight'], drop_needle=True) origin_str = body[0].nodes[0].data lexer = get_lexer_by_name(lng_name) lexer.filters.append(VisibleWhitespaceFilter()) result = highlight(origin_str, lexer, HtmlFormatter()) body[0].nodes[0].data = result return body
def setUp(self): self.log_printer = LogPrinter(ConsolePrinter(print_colored=False)) self.console_printer = ConsolePrinter(print_colored=False) self.file_diff_dict = {} self.section = Section("t") self.local_bears = OrderedDict([("default", [SomelocalBear]), ("test", [SomelocalBear])]) self.global_bears = OrderedDict([("default", [SomeglobalBear]), ("test", [SomeglobalBear])]) self.old_open_editor_applicable = OpenEditorAction.is_applicable OpenEditorAction.is_applicable = staticmethod(lambda *args: False) self.old_apply_patch_applicable = ApplyPatchAction.is_applicable ApplyPatchAction.is_applicable = staticmethod(lambda *args: False) self.lexer = TextLexer() self.lexer.add_filter( VisibleWhitespaceFilter(spaces="•", tabs=True, tabsize=SpacingHelper.DEFAULT_TAB_WIDTH))
from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import TerminalFormatter from pygments.filters import VisibleWhitespaceFilter code = """ for i in range(1, 11): \tprint("Hello world!") if x and y: print("yes") if x or y: \tprint("dunno") """ print(highlight(code, PythonLexer(), TerminalFormatter())) print("-----------------------") lexer = PythonLexer() lexer.add_filter(VisibleWhitespaceFilter(tabs=True)) print(highlight(code, lexer, TerminalFormatter()))
if pre.parent.name == 'div': pclass = pre.parent.get('class') if pclass and \ ('highlight' in pclass or \ 'hilighttable' in pclass or \ 'output_text' in pclass): continue # highlighting with pygments if ('createCanvas' in pre.string) or ('this.' in pre.string): lexer = get_lexer_by_name('js') lexer.tabsize = 2 elif ('self.' in pre.string): lexer = get_lexer_by_name('py') lexer.tabsize = 2 else: lexer = guess_lexer(pre.string) lexer.tabsize = 2 lexer.add_filter(VisibleWhitespaceFilter(tabsize=2)) code = highlight(pre.string.rstrip(), lexer, html_formatter) new_tag = pre.replace_with(code) # create the final html string. # formatter None is used to preserve # the html < and > signs rendered = soup.prettify(formatter=None) with open(output_file, 'w') as ofile: ofile.write(rendered)