def __init__(self, source=None): PwebTexPygmentsFormatter.__init__(self, source) from pygments.formatters import LatexFormatter x = LatexFormatter() self.header = ("""\\documentclass[a4paper,11pt,final]{article} \\usepackage{fancyvrb, color, graphicx, hyperref, ,amsmath, url} \\usepackage{palatino} \\usepackage[a4paper,text={16.5cm,25.2cm},centering]{geometry} \\hypersetup { pdfauthor = {Pweave}, pdftitle={Published from %s}, colorlinks=TRUE, linkcolor=black, citecolor=blue, urlcolor=blue } \\setlength{\parindent}{0pt} \\setlength{\parskip}{1.2ex} %% fix for pandoc 1.14 \\providecommand{\\tightlist}{%% \\setlength{\\itemsep}{0pt}\\setlength{\\parskip}{0pt}} %s """) % (self.source, x.get_style_defs()) self.footer = r"\end{document}"
def process(self): if self.output.lower() == 'latex': formatter = LatexFormatter( linenos=True if self.linenos else False, linenostart=self.linenostart if self.linenostart else 1, ) elif self.output.lower() == 'html': formatter = HtmlFormatter( linenos=self.linenos if self.linenos else False, linenostart=self.linenostart if self.linenostart else 1, noclasses=True if self.noclasses else False, ) else: # THROW ERROR pass if self.language: lexer = get_lexer_by_name(self.language) elif self.content: lexer = guess_lexer(self.content) else:pass if self.output == 'latex' and self.preamble: return '\usepackage{fancyvrb}\n\usepackage{color}\n\usepackage[latin1]{inputenc}\n' +\ formatter.get_style_defs() elif self.output == 'html' and self.preamble: return formatter.get_style_defs() else: pass return highlight(self.content, lexer, formatter)
def test_valid_output(self): fp = open(TESTFILE) try: tokensource = list(PythonLexer().get_tokens(fp.read())) finally: fp.close() fmt = LatexFormatter(full=True, encoding='latin1') handle, pathname = tempfile.mkstemp('.tex') # place all output files in /tmp too old_wd = os.getcwd() os.chdir(os.path.dirname(pathname)) tfile = os.fdopen(handle, 'wb') fmt.format(tokensource, tfile) tfile.close() try: import subprocess po = subprocess.Popen(['latex', '-interaction=nonstopmode', pathname], stdout=subprocess.PIPE) ret = po.wait() output = po.stdout.read() po.stdout.close() except OSError: # latex not available pass else: if ret: print output self.assertFalse(ret, 'latex run reported errors') os.unlink(pathname) os.chdir(old_wd)
def test_valid_output(self): tokensource = list(PythonLexer().get_tokens(file( os.path.join(testdir, testfile)).read())) fmt = LatexFormatter(full=True) handle, pathname = tempfile.mkstemp('.tex') # place all output files in /tmp too old_wd = os.getcwd() os.chdir(os.path.dirname(pathname)) tfile = os.fdopen(handle, 'w+b') fmt.format(tokensource, tfile) tfile.close() try: try: import subprocess ret = subprocess.Popen(['latex', '-interaction=nonstopmode', pathname], stdout=subprocess.PIPE).wait() except ImportError: # Python 2.3 - no subprocess module ret = os.popen('latex -interaction=nonstopmode "%s"' % pathname).close() if ret == 32512: raise OSError # not found except OSError: # latex not available pass else: self.failIf(ret, 'latex run reported errors') os.unlink(pathname) os.chdir(old_wd)
def process_note(notefile): fn = LatexClass(notefile) fn.parse_note(); formatter = LatexFormatter() defs = formatter.get_style_defs() out = fn.template['article'].replace('~article.title', fn.title).replace('~article.content', (fn.note).encode('utf-8')).replace('~article.defs', str(defs)).replace('~article.date', str(fn.date)) with open(notefile.split('.')[0] + '.tex', "w") as fout: fout.write(out)
def latex_syntax_highlight(body, language='text', verboptions=("frame=single,framerule=0.2pt," "framesep=5pt,xleftmargin=15pt")): from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import LatexFormatter lexer = get_lexer_by_name(language) formatter = LatexFormatter(linenos=True, verboptions=verboptions) return "{}\n{}".format(formatter.get_style_defs(), highlight(body, lexer, formatter))
def latex_syntax_highlight_file(filename, language='text', verboptions=("frame=single,framerule=0.2pt," "framesep=5pt,xleftmargin=15pt")): with open(filename.strip()) as f: body = f.read() from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import LatexFormatter lexer = get_lexer_by_name(language) formatter = LatexFormatter(linenos=True, verboptions=verboptions) return "{}\n{}".format(formatter.get_style_defs(), highlight(body, lexer, formatter).replace('[[', '[{}[').replace(']]', ']{}]'))
def latex_output(filenames, outfile, style, fontpkg, pagebreak): if not outfile: outfile = "output.tex" lines_wrapped = 0 formatter = LatexFormatter(linenos=False, style=style) output = open(outfile, "w") output.write(latex_preamble % fontpkg) output.write(formatter.get_style_defs()) for filename in filenames: output.write("\\hrule\n") output.write("\\section*{" + filename + "}\n") lexer = get_lexer_for_filename(filename) F = open(filename, "r") result = highlight(F.read(), lexer, formatter, output) F.close() if pagebreak: output.write("\\pagebreak") output.write("\end{document}") if lines_wrapped > 0: print "(wrapped " + str(lines_wrapped) + " lines)" output.close()
def code(title): """ Return syntax highlighted LaTeX. """ filename = title.split(' ')[1] try: lexer = get_lexer_for_filename(filename) except: lexer = get_lexer_by_name('text') f = open(filename, 'r') code = highlight(f.read(), lexer, LatexFormatter()) f.close() out = "\n\\begin{frame}[fragile,t]" out += "\n\t\\frametitle{Code: \"%s\"}" % filename out += code out += "\n\end{frame}" return out
def preprocess(self, nb, resources): """Preprocessing to apply on each notebook. Parameters ---------- nb : NotebookNode Notebook being converted resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. """ # Generate Pygments definitions for Latex from pygments.formatters import LatexFormatter resources.setdefault("latex", {}) resources["latex"].setdefault( "pygments_definitions", LatexFormatter(style=self.style).get_style_defs()) resources["latex"].setdefault("pygments_style_name", self.style) return nb, resources
def highlight_code(text, lang): """Syntax-highlight source code using Pygments. :Parameters: text The code to be formatted. lang The language of the source code. :Returns: A LaTeX formatted representation of the source code. """ # Preconditions & preparation: from pygments import highlight from pygments.formatters import LatexFormatter lexer = get_lexer(text, lang) if not lexer: return text lexer.add_filter('whitespace', tabsize=3, tabs=' ') return highlight(text, lexer, LatexFormatter(tabsize=3))
def setup(app): # Directives: app.add_directive('robot-source', SourceDirective) app.add_directive('robot-settings', SettingsDirective) app.add_directive('robot-variables', VariablesDirective) app.add_directive('robot-tests', TestCasesDirective) app.add_directive('robot-keywords', KeywordsDirective) # BBB: app.add_directive('robot_source', SourceDirective) app.add_directive('robot_settings', SettingsDirective) app.add_directive('robot_variables', VariablesDirective) app.add_directive('robot_tests', TestCasesDirective) app.add_directive('robot_keywords', KeywordsDirective) # LaTeX-support: if 'preamble' not in app.config.latex_elements: app.config.latex_elements['preamble'] = '' app.config.latex_elements['preamble'] += '''\ \\usepackage{fancyvrb} \\usepackage{color} ''' + LatexFormatter().get_style_defs()
def main(): """ Función principal del script. """ if len(sys.argv) != 2: print 'Usage: {0} <input-file>'.format(os.path.basename(sys.argv[0])) else: input_file = os.path.abspath(sys.argv[1]) if input_file.endswith('.py'): lexer = PythonLexer() elif input_file.endswith('.c') or input_file.endswith('.h'): lexer = CLexer() elif input_file.endswith('.tiger') or input_file.endswith('.tig'): lexer = TigerLexer() else: print 'Error: Invalid input file. Only C, Python and Tiger programs accepted.' sys.exit() dot_index = -len(input_file) + input_file.rfind('.') output_file = '%s.tex' % input_file[:dot_index] with codecs.open(input_file, encoding='utf-8') as input: with codecs.open(output_file, mode='w', encoding='utf-8') as output: highlight(input.read(), lexer, LatexFormatter(), output)
def processFile(f): #lines = open(sys.argv[1]).readlines() lines = open(f).readlines() startVerb = False for l in lines: if (not ('!!>' in l)): if (startVerb == False): #print('\\begin{Verbatim}[commandchars=\\\\\{\\},frame=single]') print(STRVERBSTART) startVerb = True str1 = highlight(l, FortranLexer(), LatexFormatter()).split('\n') Nlen = len(str1) for il in range(1, Nlen - 2): if str1[il] != '': print(str1[il]) else: if (startVerb == True): print('\\end{Verbatim}') startVerb = False print(l.replace('!!>', '').strip()) if (startVerb == True): print('\\end{Verbatim}') startVerb = False
import pygments from pygments.token import Error, STANDARD_TYPES, Name, Operator from pygments.filters import Filter, TokenMergeFilter, NameHighlightFilter from pygments.formatters import HtmlFormatter, LatexFormatter # pylint: disable=no-name-in-module from dominate import tags from dominate.util import raw as dom_raw from .pygments_lexer import CoqLexer from .pygments_style import TangoSubtleStyle LEXER = CoqLexer(ensurenl=False) # pylint: disable=no-member LEXER.add_filter(TokenMergeFilter()) HTML_FORMATTER = HtmlFormatter(nobackground=True, nowrap=True, style=TangoSubtleStyle) LATEX_FORMATTER = LatexFormatter(nobackground=True, nowrap=True, style=TangoSubtleStyle) WHITESPACE_RE = re.compile(r"\A(\s*)(.*?)(\s*)\Z", re.DOTALL) def add_tokens(tokens): """Register additional `tokens` to add custom syntax highlighting. `tokens` should be a dictionary, whose keys indicate a type of token and whose values are lists of strings to highlight with that token type. This is particularly useful to highlight custom tactics or symbols. For example, if your code defines a tactic ``map_eq`` to decide map equalities, and two tactics ``map_simplify`` and ``map_subst`` to simplify map expressions, you might write the following: >>> add_tokens({ ... 'tacn-solve': ['map_eq'],
def build_pygments_macros(filename): from pygments.formatters import LatexFormatter text = LatexFormatter().get_style_defs() with open(filename, "w") as f: f.write(text) f.write('\n')
def __init__(self, document): LaTeXTranslator.__init__(self, document) self.organization = None #used for Beamer title and possibly #header/footer. Set from docinfo # record the the settings for codeblocks self.cb_use_pygments = document.settings.cb_use_pygments self.cb_replace_tabs = document.settings.cb_replace_tabs self.cb_default_lang = document.settings.cb_default_lang self.head_prefix = [ x for x in self.head_prefix if ('{typearea}' not in x) ] #hyperref_posn = [i for i in range (len (self.head_prefix)) # if ('{hyperref}' in self.head_prefix[i])] hyperref_posn = index(self.head_prefix, lambda x: '{hyperref}\n' in x) if (hyperref_posn is None): self.head_prefix.extend(['\\usepackage{hyperref}\n']) #self.head_prefix[hyperref_posn[0]] = '\\usepackage{hyperref}\n' self.head_prefix.extend([ '\\definecolor{rrblitbackground}{rgb}{0.55, 0.3, 0.1}\n', '\\newenvironment{rtbliteral}{\n', '\\begin{ttfamily}\n', '\\color{rrblitbackground}\n', '}{\n', '\\end{ttfamily}\n', '}\n', ]) if (self.cb_use_pygments): #from pygments.formatters import LatexFormatter #fmtr = LatexFormatter() self.head_prefix.extend([ '\\usepackage{fancyvrb}\n', '\\usepackage{color}\n', #LatexFormatter().get_style_defs(), ]) # set appropriate header options for theming theme = document.settings.theme if theme: self.head_prefix.append('\\usetheme{%s}\n' % theme) # set appropriate header options for note display shownotes = document.settings.shownotes if shownotes == SHOWNOTES_TRUE: shownotes = SHOWNOTES_RIGHT use_pgfpages = True if (shownotes == SHOWNOTES_FALSE): option_str = 'hide notes' use_pgfpages = False elif (shownotes == SHOWNOTES_ONLY): option_str = 'show only notes' else: if (shownotes == SHOWNOTES_LEFT): notes_posn = 'left' elif (shownotes in SHOWNOTES_RIGHT): notes_posn = 'right' elif (shownotes == SHOWNOTES_TOP): notes_posn = 'top' elif (shownotes == SHOWNOTES_BOTTOM): notes_posn = 'bottom' else: # TODO: better error handling assert False, "unrecognised option for shownotes '%s'" % shownotes option_str = 'show notes on second screen=%s' % notes_posn if use_pgfpages: self.head_prefix.append('\\usepackage{pgfpages}\n') self.head_prefix.append('\\setbeameroption{%s}\n' % option_str) if (self.cb_use_pygments): from pygments.formatters import LatexFormatter fmtr = LatexFormatter() self.head_prefix.extend([ LatexFormatter().get_style_defs(), ]) self.overlay_bullets = string_to_bool(document.settings.overlaybullets, False) self.fragile_default = string_to_bool( document.settings.fragile_default, True) #using a False default because #True is the actual default. If you are trying to pass in a value #and I can't determine what you really meant, I am assuming you #want something other than the actual default. self.centerfigs = string_to_bool(document.settings.centerfigs, False) #same reasoning as above self.in_columnset = False self.in_column = False self.in_note = False self.frame_level = 0 # this fixes the hardcoded section titles in docutils 0.4 self.d_class = DocumentClass('article')
def format(self, tokensource, outfile): LatexFormatter.format(self, self._filter_tokens(tokensource), outfile)
# documents`_. from docutils import nodes from docutils.parsers.rst import directives from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import LatexFormatter #pygments_formatter = LatexFormatter(option='wrap', # #linenos=True, # style="fruity", # full=False) pygments_formatter = LatexFormatter( linenos=False, encoding='utf-8', verboptions= "frame=lines,framerule=2pt,fontfamily=courier,fontsize=\\small,label={[source code begin]source code end}" ) #pygments_formatter.full = True 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: # no lexer found - use the text one instead of an exception lexer = get_lexer_by_name('text') parsed = highlight(u'\n'.join(content), lexer, pygments_formatter) return [nodes.raw('', parsed, format='latex')]
\\documentclass[a4paper]{article} \\usepackage{fancyvrb} \\usepackage{xcolor}\n\n \\definecolor{mygray}{rgb}{0.95,0.95,0.95} \\usepackage{mdframed} \\BeforeBeginEnvironment{Verbatim}{\\begin{mdframed}[backgroundcolor=mygray]} \\AfterEndEnvironment{Verbatim}{\\end{mdframed}} ''' MIDLINE = ''' \\begin{document} ''' print(PRELINE) print( LatexFormatter().get_style_defs() ) print(MIDLINE) #STRVERBSTART = ''' #\\begin{Verbatim}[commandchars=\\\\\{\},codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8}] #''' STRVERBSTART = ''' \\begin{Verbatim}[commandchars=\\\\\{\}]''' startVerb = False for l in lines: if( not ('!!>' in l) ): if( startVerb==False ): #print('\\begin{Verbatim}[commandchars=\\\\\{\\},frame=single]')
# Set to True if you want inline CSS styles instead of classes INLINESTYLES = False try: import locale locale.setlocale(locale.LC_ALL, '') except: pass # set up Pygments from pygments.formatters import LatexFormatter # The default formatter DEFAULT = LatexFormatter() # Add name -> formatter pairs for every variant you want to use VARIANTS = { # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), } from docutils import nodes from docutils.parsers.rst import directives from pygments import highlight from pygments.lexers import get_lexer_by_name, TextLexer def pygments_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine):
def build_formatter(args): """ Construct the formatter according to provided arguments. """ return LatexFormatter(style=args.style)
def rst2tex(in_path, out_path): options.mkdir_p(out_path) for file in glob.glob(os.path.join(in_path, '*')): if os.path.isdir(file): copytree(file, out_path) else: shutil.copy(file, out_path) base_dir = os.path.dirname(__file__) scipy_status = os.path.join(base_dir, '_static/status.sty') shutil.copy(scipy_status, out_path) scipy_style = os.path.join(base_dir, '_static/scipy.sty') shutil.copy(scipy_style, out_path) preamble = r'''\usepackage{scipy}''' # Add the LaTeX commands required by Pygments to do syntax highlighting pygments = None try: import pygments except ImportError: import warnings warnings.warn( RuntimeWarning('Could not import Pygments. ' 'Syntax highlighting will fail.')) if pygments: from pygments.formatters import LatexFormatter from writer.sphinx_highlight import SphinxStyle preamble += LatexFormatter(style=SphinxStyle).get_style_defs() settings = { 'documentclass': 'wlpeerj', 'use_verbatim_when_possible': True, 'use_latex_citations': True, 'latex_preamble': preamble, 'documentoptions': 'fleqn,12pt', 'halt_level': 3, # 2: warn; 3: error; 4: severe } try: rst, = glob.glob(os.path.join(in_path, '*.rst')) except ValueError: raise RuntimeError("Found more than one input .rst--not sure which " "one to use.") content = header + open(rst, 'r').read() tex = dc.publish_string(source=content, writer=writer, settings_overrides=settings) tex = tex.replace('subsection{', 'section*{') # remove incorrect \labels texlines = tex.split('\n') texlines = filter(lambda x: not x.startswith(r' \label{'), texlines) tex = '\n'.join(texlines) tex_file = os.path.join(out_path, 'paper.tex') with open(tex_file, 'w') as f: f.write(tex)
if __name__ == '__main__': import pytex __package__ = 'pytex.util' # @ReservedAssignment @UnusedImport import traceback import sys from pygments import highlight from pygments.lexers import PythonLexer # @UnresolvedImport from pygments.formatters import LatexFormatter # @UnresolvedImport from .text import print_capture from .rawtex import tex_document PYGMENTS_DEFS = LatexFormatter().get_style_defs().strip() def render_error(etype=None, evalue=None, tb=None, as_document=False): r'''Renders the last traceback as LaTeX code. The resulting code uses pygments for syntax highlighting. If no traceback object is given, the last traceback is used. Example ------- >>> try: ... 1/0 ... except: ... print(render_error()) #doctest: +ELLIPSIS \makeatletter... \begin{Verbatim}[commandchars=\\\{\}] \PY{n}{Traceback}... \end{Verbatim}
def _generate_pygments_latex_def(self): return LatexFormatter().get_style_defs()
def highlight2latex(src, lang='ipython'): """ Return a syntax-highlighted version of the input source as latex output. """ from pygments.formatters import LatexFormatter return pygment_highlight(src, LatexFormatter(), lang)
def test_others_work(self): """check other formatters don't crash""" highlight(self.code, Python3Lexer(), LatexFormatter(style=MyStyle)) highlight(self.code, Python3Lexer(), HtmlFormatter(style=MyStyle))
def create_tex_file(filenames, working_dir): all_files = glob(join(escape(working_dir), '**', '*'), recursive=True) relevant_files = list(filter(lambda x: basename(x) in filenames, all_files)) if not relevant_files: return None, None else: print(f"Found files: {relevant_files}") scoring = create_grading(relevant_files) print(scoring) pprint(scoring.file_points) formatter = LatexFormatter(style='friendly', title="This is a title", linenos=True, escapeinside="xx", titel="This is a title", verboptions="fontsize=\\scriptsize") doctext = [] doctext.append(r'''\documentclass[10pt]{article} \usepackage{geometry} \geometry{ a4paper, right=10mm, bottom=15mm, left=10mm, top=10mm, } \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{minted} \setlength{\parindent}{0cm} \renewcommand{\familydefault}{\sfdefault} ''') doctext.append(formatter.get_style_defs()) doctext.append(r""" \begin{document}""") doctext.append( jinja2.Template(r""" \section*{Scoring} {% for file, scoring in file_points.items() %} \paragraph{ {{file}}: {{scoring.scored_points}} / {{scoring.max_points}} } \begin{itemize} {% for task in scoring.tasks %} \item {{ task[0] }}: {{task[1]}} / {{task[2]}} {% endfor %} \end{itemize} {% endfor %} \paragraph{ Total: {{scored_points}} / {{total_points}} } """).render(scoring.__dict__)) for filename in relevant_files: with open(filename, 'r', encoding="utf-8", errors="ignore") as f: code = f.read() doctext.append(f"\\section*{{{basename(filename)}}}") doctext.append(highlight(code, CustomJavaLexer(), formatter)) doctext.append(r"\end{document}") return '\n'.join(doctext), scoring
def __init__(self, document): LaTeXTranslator.__init__(self, document) # Used for Beamer title and possibly header/footer. Set from docinfo # record the settings for codeblocks. self.organization = None self.cb_use_pygments = document.settings.cb_use_pygments self.cb_replace_tabs = document.settings.cb_replace_tabs self.cb_default_lang = document.settings.cb_default_lang self.head_prefix = [ x for x in self.head_prefix if '{typearea}' not in x ] self.head_prefix.extend([ '\\definecolor{rrblitbackground}{rgb}{0.55, 0.3, 0.1}\n', '\\newenvironment{rtbliteral}{\n', '\\begin{ttfamily}\n', '\\color{rrblitbackground}\n', '}{\n', '\\end{ttfamily}\n', '}\n', ]) if self.cb_use_pygments: self.head_prefix.extend([ '\\usepackage{fancyvrb}\n', '\\usepackage{color}\n', ]) # set appropriate header options for theming theme = document.settings.theme if theme: self.head_prefix.append('\\usetheme{%s}\n' % theme) set_header_options(self.head_prefix, document.settings.shownotes) if self.cb_use_pygments: from pygments.formatters import LatexFormatter self.head_prefix.extend([ LatexFormatter().get_style_defs(), ]) self.overlay_bullets = string_to_bool(document.settings.overlaybullets, False) self.fragile_default = string_to_bool( document.settings.fragile_default, True) self.shortauthor = document.settings.shortauthor self.shorttitle = document.settings.shorttitle # using a False default because # True is the actual default. If you are trying to pass in a value # and I can't determine what you really meant, I am assuming you # want something other than the actual default. self.centerfigs = string_to_bool(document.settings.centerfigs, False) # same reasoning as above self.in_columnset = False self.in_column = False self.in_note = False self.frame_level = 0 # this fixes the hardcoded section titles in docutils 0.4 self.d_class = DocumentClass('article') self.admonition_alert_type = None
def rst2tex(in_path, out_path): options.mkdir_p(out_path) for file in glob.glob(os.path.join(in_path, '*')): shutil.copy(file, out_path) base_dir = os.path.dirname(__file__) scipy_status = os.path.join(base_dir, '_static/status.sty') shutil.copy(scipy_status, out_path) scipy_style = os.path.join(base_dir, '_static/scipy.sty') shutil.copy(scipy_style, out_path) preamble = r'''\pdfoutput=1 \usepackage{scipy}''' # Add the LaTeX commands required by Pygments to do syntax highlighting pygments = None try: import pygments except ImportError: import warnings warnings.warn( RuntimeWarning('Could not import Pygments. ' 'Syntax highlighting will fail.')) if pygments: from pygments.formatters import LatexFormatter from writer.sphinx_highlight import SphinxStyle preamble += LatexFormatter(style=SphinxStyle).get_style_defs() settings = { 'documentclass': 'IEEEtran', 'use_verbatim_when_possible': True, 'use_latex_citations': True, 'latex_preamble': preamble, 'documentoptions': 'letterpaper,compsoc,twoside', 'halt_level': 3, # 2: warn; 3: error; 4: severe 'sectnum_xform': False, 'sectnum_depth': 3, } try: rst, = glob.glob(os.path.join(in_path, '*.rst')) except ValueError: raise RuntimeError("Found more than one input .rst--not sure which " "one to use.") content = header + open(rst, 'r').read() tex = dc.publish_string(source=content, writer=writer, settings_overrides=settings) stats_file = os.path.join(out_path, 'paper_stats.json') d = options.cfg2dict(stats_file) d.update(writer.document.stats) arxiv_path = os.path.join(in_path, 'arxiv.json') if os.path.exists(arxiv_path): arxiv = options.cfg2dict(arxiv_path) else: arxiv = {'arxiv_identifier': None} d.update(arxiv) options.dict2cfg(d, stats_file) tex_file = os.path.join(out_path, 'paper.tex') with open(tex_file, 'w') as f: f.write(tex)
def generate_sty(self, style='default'): formatter = LatexFormatter(style=style) return formatter.get_style_defs()
def test_others_work(): """Check other formatters don't crash.""" highlight(CODE, Python3Lexer(), LatexFormatter(style=MyStyle)) highlight(CODE, Python3Lexer(), HtmlFormatter(style=MyStyle))
def _repr_latex_(self): from pygments import highlight from pygments.formatters import LatexFormatter return highlight(self.data, self._get_lexer(), LatexFormatter())
def rst2tex(in_path, out_path): dir_util.copy_tree(in_path, out_path) base_dir = os.path.dirname(__file__) out_file = shutil.copy(status_file, out_path) os.rename(out_file, os.path.join(out_path, 'status.sty')) scipy_style = os.path.join(base_dir, '_static/scipy.sty') shutil.copy(scipy_style, out_path) preamble = u'''\\usepackage{scipy}''' # Add the LaTeX commands required by Pygments to do syntax highlighting pygments = None try: import pygments except ImportError: import warnings warnings.warn( RuntimeWarning('Could not import Pygments. ' 'Syntax highlighting will fail.')) if pygments: from pygments.formatters import LatexFormatter from writer.sphinx_highlight import SphinxStyle preamble += LatexFormatter(style=SphinxStyle).get_style_defs() settings = { 'documentclass': 'IEEEtran', 'use_verbatim_when_possible': True, 'use_latex_citations': True, 'latex_preamble': preamble, 'documentoptions': 'letterpaper,compsoc,twoside', 'halt_level': 3, # 2: warn; 3: error; 4: severe } try: rst, = glob.glob(os.path.join(in_path, '*.rst')) except ValueError: raise RuntimeError("Found more than one input .rst--not sure which " "one to use.") with io.open(rst, mode='r', encoding='utf-8') as f: content = header + f.read() tex = dc.publish_string(source=content, writer=writer, settings_overrides=settings) stats_file = os.path.join(out_path, 'paper_stats.json') d = options.cfg2dict(stats_file) try: d.update(writer.document.stats) options.dict2cfg(d, stats_file) except AttributeError: print("Error: no paper configuration found") tex_file = os.path.join(out_path, 'paper.tex') with io.open(tex_file, mode='wb') as f: try: tex = tex.encode('utf-8') except (AttributeError, UnicodeDecodeError): pass f.write(tex)
for token in tokens: if token.startswith("}"): active.remove(token[1:]) else: if "JCB{" in l: vis = 0 if "}JCB" in l: vis = 1 return dict([(k, "".join(unindent(v))) for (k, v) in d.items()]) sources = """ termdriver-helloworld termdriver-counter1 termdriver-counter2 termdriver-color1 """ for fn in sources.split(): code = Clean(open("samples/%s.ino" % fn)) for (tag, body) in code.items(): hh = open("%s-%s.inc" % (fn, tag), "w") hh.write(highlight(body, CppLexer(), LatexFormatter())) hh.close() if __name__ == "__main__": for f in sources.split(): ino = open("samples/" + f + ".ino", "rt").read() m = highlight(ino, CppLexer(), LatexFormatter()) open("code/" + f + ".inc", "wt").write(m)
def makeFormatter(verboptions='', nolinenos=False): return LatexFormatter( verboptions=verboptions.replace('!', '\\'), linenos = not nolinenos, style=CustomStyle, )
# Add the LaTeX commands required by Pygments to do syntax highlighting try: import pygments except ImportError: import warnings warnings.warn(RuntimeWarning('Could not import Pygments. ' 'Syntax highlighting will fail.')) pygments = None if pygments: from pygments.formatters import LatexFormatter from sphinx_highlight import SphinxStyle preamble += LatexFormatter(style=SphinxStyle).get_style_defs() settings = {'documentclass': 'IEEEtran', 'use_verbatim_when_possible': True, 'use_latex_citations': True, 'latex_preamble': preamble, 'documentoptions': 'letterpaper,compsoc,twoside'} try: rst, = glob.glob(os.path.join(in_path, '*.rst')) except ValueError: raise RuntimeError("Found more than one input .rst--not sure which one to use.") content = open(rst, 'r').read()
def pygments_sty(self): formatter = LatexFormatter(style=self.setting('style')) return formatter.get_style_defs()