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)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Use the 'pygments' library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(force_insert=False, force_update=False, using=None, update_fields=None)
def trans(content, type, style, suffix): print(type, style, suffix) if not suffix: lexer = get_lexer_by_name(type) else: try: lexer = get_lexer_for_filename(suffix) except: lexer = get_lexer_by_name(type) # 指定风格 formatter = HtmlFormatter(style=style) # 获取html html = highlight(content, lexer, formatter) return html
def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.prog_lang) line_no = "table" if self.line_no else False options = {"title": self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=line_no, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """ 利用pygments,创建高亮的html文本呈现code块,然后再保存 """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
def save(self, *args, **kwargs): # new """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.description, lexer, formatter) super(Task, self).save(*args, **kwargs)
def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.language) # linenos = self.linenos and 'table' or False linenos = 'table' if self.linenos else False # options = self.title and {'title': self.title} or {} options = {'title': self.title} if self.title else {} formatter = HtmlFormatter( style=self.style, linenos=linenos, full=True, **options, ) self.highlighted = highlight(self.code, lexer, formatter) super().save(*args, **kwargs)
def detail_json_formatted(self): # with JSON field, no need to do .loads data = json.dumps(json.loads(self.params), 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) return mark_safe( '<textarea rows="15" cols="120" readonly>%s</textarea>' % data)
def create_highlighted_text(text, lexer_name='text', style='friendly', title=None): lexer = get_lexer_by_name(lexer_name) # linenos = 'table' if self.linenos else False linenos = False options = {'title': title} if title else {} formatter = HtmlFormatter(style=style, linenos=linenos, full=True, **options) highlighted = highlight(text, lexer, formatter) return highlighted
def save(self, *args, **kwargs): """ 使用‘pygments’库去创建一个高亮的html表示的代码片段 :return: """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and "table" or False options = self.title and {"title": self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """ code snippet의 하이라이팅을 생성하기 위해 pygments 라이브러리를 사용한다 """ lexer = get_lexer_by_name(self.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
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 }
def blockcode(self, text, lang): if not lang: return '\n<pre><code>{}</code></pre>\n'.format(text.strip()) try: lexer = get_lexer_by_name(lang, stripall=True) except ClassNotFound: lexer = None if lexer: formatter = HtmlFormatter(linenos='inline') return highlight(text, lexer, formatter) # default return '\n<pre><code>{}</code></pre>\n'.format(text.strip())
def save(self, *args, **kwargs): """ use pygments lib to create a highlighted html representation of the code snippet """ lexer = get_lexer_by_name(self.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
def html(self): """ Return an HTML representation of the snippet. """ formatter = HtmlFormatter( cssclass=self.DIV_CSS_CLASS, linenos=True, linenostart=self._start_line, hl_lines=self._shift_lines(self._violation_lines, self._start_line), lineanchors=self._src_filename, ) return pygments.format(self.src_tokens(), formatter)
def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.name) boardingid = 'table' if self.boardingid else False options = {'title': self.name} if self.name else {} formatter = HtmlFormatter(style=self.name, boardingid=boardingid, full=True, **options) self.highlighted = highlight(self.contact, lexer, formatter) super(passengers, self).save(*args, **kwargs)
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)
def html(self): # TODO: section tags for each section and subsection out = HTML() out.start_tag("article") for block in self.blocks: if block.content_type is None: out.element("p", html=Text(" ".join(block.lines)).html) elif block.content_type in (Heading, HorizontalRule): for line in block.lines: out.write_html(line.html) elif block.content_type is Literal: source = "".join(line.line for line in block.lines) lang, _, metadata = block.metadata.partition(" ") try: lexer = get_lexer_by_name(lang) except ClassNotFound: lexer = None if lexer is None: out.start_tag("pre") out.write_text(source) out.end_tag("pre") else: out.write_raw(highlight(source, lexer, HtmlFormatter())) elif block.content_type is Quote: out.start_tag("blockquote") for line in block.lines: out.write_html(line.html) out.end_tag("blockquote") elif block.content_type is ListItem: level = 0 for line in block.lines: while level > line.level: out.end_tag() level -= 1 while level < line.level: out.start_tag(line.list_tag(level)) level += 1 out.write_html(line.html) while level: out.end_tag() level -= 1 elif block.content_type is TableRow: out.start_tag("table") for line in block.lines: out.write_html(line.html) out.end_tag("table") out.element("footer") out.end_tag("article") return out.html
def upload_file_remote(dest_file: Path, ext: str, file_path: Path, zip_flag, plain, in_file, ppb_path_on_host, ppb_target_host, metadata: dict) -> None: """ dest_file: destination filename + extension (example: 77a80349869f.png) ext: file extension, like dest_file.suffix file_path: path to input file. """ with tempfile.TemporaryDirectory() as tmpdirname: send_metadata(dest_file, metadata, ppb_path_on_host, ppb_target_host, tmpdirname) tempfile_path = os.path.join(tmpdirname, in_file) if zip_flag: zip_command = f'zip -r {tempfile_path} {file_path}' log.info(zip_command) os.system(zip_command) file_path = tempfile_path elif not plain and not check_extension( ext, { *IMAGE_EXTENSIONS, *VIDEO_EXTENSIONS, *COMPRESSION_EXTENSIONS, '', 'pdf' }): with open(file_path, mode='r') as c: code = c.read() with open(tempfile_path, mode='w') as f: if ext == '.log': lexer = BashLexer() else: try: lexer = guess_lexer_for_filename(file_path, c) except Exception as e: print(e) try: highlight(code, lexer, HtmlFormatter(linenos=True, full=True), outfile=f) except: # if pygments fails to find a lexer, continue without highlighting tempfile_path = file_path lexer = None file_path = tempfile_path log.info(f'Highlighted {file_path} with lexer {lexer}.') rsync_command = f'rsync -avP {file_path} {ppb_target_host}:{ppb_path_on_host}/{dest_file}' log.info(rsync_command) os.system(rsync_command)
def save(self, *args, **kwargs): """使用`pygments`库创建一个高亮显示的HTML表示代码段。""" lexer = get_lexer_by_name(self.language) """ linenos = (True and 'table') or False => or 前的语句为True,所以不执行 or 后的语句 => linenos = 'table' linenos = (False and 'table') or False => or 前的语句为False,所以执行 or 后的语句 => linenos = False """ linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super().save(*args, **kwargs)
def highlightCode(self, code, language): #converting the html to platin td = QTextDocument() td.setHtml(code) print("the plain text is here : " + td.toPlainText()) codeLexer = get_lexer_by_name(language) f = open("highlightTest.html", 'wb') #fi = open("highlightTest.png",'wb') #style = get_style_by_name("native") formatter = HtmlFormatter(full=True, noclasses=True, encoding="UTF-8") #imgFormater = ImageFormatter() result = highlight(td.toPlainText(), codeLexer, formatter) td.setHtml(result.decode("UTF-8")) print(td.toHtml()) return td.toHtml()
def save(self, *args, **kwargs): """ `pygments` 라이브러리를 사용하여 하이라이트된 코드를 만든다. """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter( style=self.style, linenos=linenos, full=True, **options, ) self.highlighted = highlight(self.code, lexer, formatter) super().save(*args, **kwargs)
def save(self, *args, **kwargs): """ Use the 'pygments' library to create a highlighted HTML representation of the code snippet pygments 라이브러리를 사용하여, 하이라이트 된 코드의 HTML 텍스트를 생성 """ lexer = get_lexer_by_name(self.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) # overriding save method so that the highlighed field is added super(Snippet, self).save(*args, **kwargs)
def format_code_for_display(concept_key, lang): """ Returns the formatted HTML formatted syntax-highlighted text for a concept key (from a meta language file) and a language :param concept_key: name of the key to format :param lang: language to format it (in meta language/syntax highlighter format) :return: string with code with applied HTML formatting """ if lang.concept_unknown( concept_key) or lang.concept_code(concept_key) is None: return "Unknown" if lang.concept_implemented(concept_key): return highlight(lang.concept_code(concept_key), get_lexer_by_name(lang.key, startinline=True), HtmlFormatter()) return None
def pygmentize(code, linenos=False, tofile=False, outputfile=''): style = 'colorful' defstyles = 'overflow:auto;width:auto;' formatter = HtmlFormatter(style=style, linenos=False, noclasses=True, cssclass='', cssstyles=defstyles + get_default_style(), prestyles='margin: 0') html = highlight(code, JavaLexer(), formatter) if linenos: html = insert_line_numbers(html) html = "<!-- Rapport généré avec TPGen -->" + html return html
def __init__(self, query, highlightFormat: str = "html"): ''' construct me for the given query and highlightFormat Args: query(Query): the query to do the syntax highlighting for highlightFormat(str): the highlight format to be used ''' self.query = query self.highlightFormat = highlightFormat self.lexer = get_lexer_by_name(self.query.lang) if self.highlightFormat == "html": self.formatter = HtmlFormatter() elif self.highlightFormat == "latex": self.formatter = LatexFormatter()
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 syntax_highlight(file): code = file.path.read_text() try: lexer = get_lexer_for_mimetype(file.client_mimetype) except ClassNotFound: try: lexer = guess_lexer(code) except ClassNotFound: lexer = TextLexer() return highlight( code, lexer, HtmlFormatter(linenos="table", anchorlinenos=True, lineanchors="line"), )