Пример #1
0
def _finalize(doc):
    logging.debug("Finalize doc!")
    hdr_inc = "header-includes"
    # Add header-includes if necessary
    if "header-includes" not in doc.metadata:
        if doc.get_metadata("output.beamer_presentation.includes") is None:
            logging.debug("No 'header-includes' nor `includes` ? Created 'header-includes'!")
            doc.metadata[hdr_inc] = pf.MetaList()
        else:
            logging.ERROR("Found 'includes'! SAD THINK")
            exit(1)

    # Convert header-includes to MetaList if necessary

    logging.debug("Append background packages to `header-includes`")

    if not isinstance(doc.metadata[hdr_inc], pf.MetaList):
        logging.debug("The '" + hdr_inc + "' is not a list? Converted!")
        doc.metadata[hdr_inc] = pf.MetaList(doc.metadata[hdr_inc])

    frmt = doc.format
    if doc.format in ("latex", "beamer"):
        frmt = "latex"

    if doc.format in ("tex", "latex", "beamer"):
        doc.metadata[hdr_inc].append(
            pf.MetaInlines(pf.RawInline("\\usepackage{xspace}", frmt))
        )
        doc.metadata[hdr_inc].append(
            pf.MetaInlines(pf.RawInline("\\usepackage{trimclip}", frmt))
        )
Пример #2
0
def finalize(doc):
    """Adds the pgfplots and caption packages to the header-includes if needed.
    """
    if doc.plot_found:
        pgfplots_inline = pf.MetaInlines(pf.RawInline(
            r'''%
\makeatletter
\@ifpackageloaded{pgfplots}{}{\usepackage{pgfplots}}
\makeatother
\usepgfplotslibrary{groupplots}
''', format='tex'))
        try:
            doc.metadata['header-includes'].append(pgfplots_inline)
        except KeyError:
            doc.metadata['header-includes'] = pf.MetaList(pgfplots_inline)

    if doc.caption_found:
        caption_inline = pf.MetaInlines(pf.RawInline(
            r'''%
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\@ifpackageloaded{cleveref}{}{\usepackage{cleveref}}
\@ifundefined{codelisting}{%
    \DeclareCaptionType{codelisting}[Code Listing][List of Code Listings]
    \crefname{codelisting}{code listing}{code listings}
    \Crefname{codelisting}{Code Listing}{Code Listings}
    \captionsetup[codelisting]{position=bottom}
}{}
\makeatother
''', format='tex'))
        try:
            doc.metadata['header-includes'].append(caption_inline)
        except KeyError:
            doc.metadata['header-includes'] = pf.MetaList(caption_inline)
Пример #3
0
def _finalize(doc):
    logging.debug("Finalize doc!")
    hdr_inc = "header-includes"
    # Add header-includes if necessary
    if "header-includes" not in doc.metadata:
        if doc.get_metadata("output.beamer_presentation.includes") is None:
            logging.debug(
                "No 'header-includes' nor `includes` ? Created 'header-includes'!"
            )
            doc.metadata["header-includes"] = pf.MetaList()
        else:
            logging.ERROR("Found 'includes'! SAD THING!")
            exit(1)

    # Convert header-includes to MetaList if necessary

    logging.debug("Append background packages to `header-includes`")

    if not isinstance(doc.metadata[hdr_inc], pf.MetaList):
        logging.debug("The '" + hdr_inc + "' is not a list? Converted!")
        doc.metadata[hdr_inc] = pf.MetaList(doc.metadata[hdr_inc])

    doc.metadata[hdr_inc].append(
        pf.MetaInlines(
            pf.RawInline(
                "\\usepackage[pages=some,placement=center,scale=3,angle=45,color=red!55]{background}",
                "latex")))
Пример #4
0
def finalize(doc):
    # Add header-includes if necessary
    if 'header-includes' not in doc.metadata:
        doc.metadata['header-includes'] = pf.MetaList()
    # Convert header-includes to MetaList if necessary
    elif not isinstance(doc.metadata['header-includes'], pf.MetaList):
        doc.metadata['header-includes'] = pf.MetaList(
            doc.metadata['header-includes'])

    # Add usefull LaTexPackage
    doc.metadata['header-includes'].append(
        pf.MetaInlines(pf.RawInline('\\usepackage{pstricks}', 'tex')))
    doc.metadata['header-includes'].append(
        pf.MetaInlines(pf.RawInline('\\usepackage{pst-barcode}', 'tex')))
Пример #5
0
def builtin2meta(val):
    if isinstance(val, bool):
        return pf.MetaBool(val)
    elif isinstance(val, (float, int)):
        return pf.MetaString(str(val))
    elif isinstance(val, string_types):
        return pf.MetaString(val)
    elif isinstance(val, list):
        return pf.MetaList(*[builtin2meta(x) for x in val])
    elif isinstance(val, dict):
        return pf.MetaMap(*[(k, builtin2meta(v)) for k, v in val.items()])
    elif isinstance(val, pf.Block):
        return pf.MetaBlocks(val)
    elif isinstance(val, pf.Inline):
        return pf.MetaInlines(val)
    elif isinstance(
            val,
        (
            pf.MetaBool,
            pf.MetaString,
            pf.MetaValue,
            pf.MetaList,
            pf.MetaMap,
            pf.MetaBlocks,
            pf.MetaInlines,
        ),
    ):
        return val

    raise TypeError("unknown type: {} (type: {})".format(val, type(val)))
Пример #6
0
def masthead(doc):
    """Generate the masthead based on the metadata
    """
    if doc.format != "html":
        return

    avatar = "<a href='{0}/' class='site-avatar'><img src='{1}' /></a>"
    name = "<h1 class='site-name'><a href='{0}/'>{1}</a></h1>"
    desc = "<p class='site-description'>{0}</p>"
    metadata = doc.get_metadata()
    url = metadata.get("url", "")
    nav = "<a href='{0}/{1}'>{2}</a>"
    author = doc.get_metadata("author")
    if isinstance(author, (list, tuple)):
        author = author[0]

    masthead = [
        "", "<div class='wrapper-masthead'>", "\t<div class='container'>",
        "\t\t<header class='masthead clearfix'>",
        "\t\t\t" + avatar.format(url, metadata.get("avatar", "")),
        "\t\t\t<div class='site-info'>", "\t\t\t\t" + name.format(url, author),
        "\t\t\t\t" + desc.format(metadata.get("description", "")),
        "\t\t\t</div>", "\t\t\t<nav>",
        "\t\t\t" + nav.format(url, "website/index.html", "Home"),
        "\t\t\t" + nav.format(url, "website/about.html", "About"),
        "\t\t\t" + nav.format(url, "website/blog/index.html", "Blog"),
        "\t\t\t" + nav.format(url, "website/fun/index.html", "Fun"),
        "\t\t\t" + nav.format(url, "resume/index.html", "Resume"),
        "\t\t\t</nav>", "\t\t</header>", "\t</div>", "</div>",
        "<div id='main' role='main' class='container'>"
    ]
    doc.metadata["include-before"] = panflute.MetaList(
        *doc.get_metadata("include-before", ()),
        panflute.RawBlock("\n".join(masthead), format="html"))
Пример #7
0
def finalize(doc):
    if doc.format == 'latex':
        # tex = [r'\usepackage[toc]{glossaries}', '\makeglossaries']
        tex = []
        for acronym, definition in doc.acronyms.items():
            tex_acronym = TEMPLATE_NEWACRONYM.safe_substitute(acronym=acronym, definition=definition)
            tex.append(tex_acronym)
        tex = [pf.MetaInlines(pf.RawInline(line, format='latex')) for line in tex]
        tex = pf.MetaList(*tex)
        doc.metadata['acronyms'] = tex
Пример #8
0
 def __add_header_includes(doc):
     # Add header-includes if necessary
     if "header-includes" not in doc.metadata:
         if doc.get_metadata("output.beamer_presentation.includes") is None:
             logging.info(
                 "No 'header-includes' nor `includes` ? Created 'header-includes'!"
             )
             doc.metadata[hdr_inc] = pf.MetaList()
         else:
             logging.ERROR("Found 'includes'! SAD THING!")
             exit(1)
     return doc
Пример #9
0
def finalize(doc):
    if doc.format == 'latex':
        tex = [r'\makeglossaries']
        for acronym, definition in doc.acronyms.items():
            tex_acronym = TEMPLATE_NEWACRONYM.safe_substitute(
                acronym=acronym, definition=definition)
            tex.append(tex_acronym)

        tex = [
            pf.MetaInlines(pf.RawInline(line, format='latex')) for line in tex
        ]
        tex = pf.MetaList(*tex)
        if 'header-includes' in doc.metadata:
            doc.metadata['header-includes'].content.extend(tex)
        else:
            doc.metadata['header-includes'] = tex
Пример #10
0
def footer(doc):
    """Generate the footer for the HTML version
    """
    if doc.format != "html" or "footer-links" not in doc.metadata:
        return

    links = doc.get_metadata("footer-links", [])
    # panflute.debug(_root + ":footer: links {0}".format(links))
    keys = (
        ("email", "mailto: {0}"),
        ("github", "https://github.com/{0}"),
        ("linkedin", "https://linkedin.com/in/{0}"),
        ("stackoverflow", "https://stackoverflow.com/users/{0}"),
    )
    href = "<a href='{0}'><img src='static/svg-icons/{1}.svg'/></a>"
    logos = [
        href.format(url.format(links[key]), key) for key, url in keys
        if links.get(key, False)
    ]

    # panflute.debug(logos)
    year = datetime.date.today().year
    author = doc.get_metadata("author")
    if isinstance(author, (list, tuple)):
        author = author[0]

    # Build up the footer for each page to include the logos and the
    # copy right notice.
    footer = "\n" \
           + "\n</div>" \
           + "\n<div class='wrapper-footer'>" \
           + "\n\t<div class='container'>" \
           + "\n\t\t<footer class='footer'>" \
           + "\n\t\t\t".join([""] + logos) \
           + "\n\t\t\t<div>" \
           + "&#169; Copyright {0}, {1}".format(year, author) \
           + ("" if author[-1] == "." else ".") + "  Created using " \
           + "<a href='https://scons.org'>SCons</a> and " \
           + "<a href='https://pandoc.org'>Pandoc</a>" \
           + "\n\t\t\t</div>" \
           + "\n\t\t</footer>" \
           + "\n\t</div>" \
           + "\n</div>" \
           + "\n"
    doc.metadata["include-after"] = panflute.MetaList(
        *doc.get_metadata("include-after", ()),
        panflute.RawBlock(footer, format="html"))
Пример #11
0
def finalize(doc):
    if doc.format == 'latex':
        tex = [r'\makeglossaries']
        for _, values in doc.abbrs.items():
            tex_acronym = DEFINE_ABBREVIATION.render(**values)
            tex.append(tex_acronym)

        for _, values in doc.glsentries.items():
            tex_acronym = DEFINE_GLOSSARY_ENTRY.render(**values)
            tex.append(tex_acronym)

        tex = [
            pf.MetaInlines(pf.RawInline(line, format='latex')) for line in tex
        ]
        tex = pf.MetaList(*tex)
        if 'header-includes' in doc.metadata:
            doc.metadata['header-includes'].content.extend(tex)
        else:
            doc.metadata['header-includes'] = tex
Пример #12
0
def _finalize(doc):
    hdr_inc = "header-includes"

    def __add_header_includes(doc):
        # Add header-includes if necessary
        if "header-includes" not in doc.metadata:
            if doc.get_metadata("output.beamer_presentation.includes") is None:
                logging.info(
                    "No 'header-includes' nor `includes` ? Created 'header-includes'!"
                )
                doc.metadata[hdr_inc] = pf.MetaList()
            else:
                logging.ERROR("Found 'includes'! SAD THING!")
                exit(1)
        return doc

    def __append_header_includes(rawstr, frmt):
        logging.debug(f"Append line '{rawstr}' to `header-includes`")
        if not rawstr in doc.get_metadata("header-includes"):
            doc.metadata[hdr_inc].append(
                pf.MetaInlines(pf.RawInline(rawstr, frmt)))

    logging.debug("Finalize doc!")

    doc = __add_header_includes(doc)
    # Convert header-includes to MetaList if necessary

    logging.debug("Append background packages to `header-includes`")

    if not isinstance(doc.metadata[hdr_inc], pf.MetaList):
        logging.info(f"The '{hdr_inc}' is not a list? Converted!")
        doc.metadata[hdr_inc] = pf.MetaList(doc.metadata[hdr_inc])

    if doc.format in LATEX_LIKE:
        __append_header_includes(
            r"\usepackage{xspace}  % added by typography.py!", "latex")
        __append_header_includes(
            r"\usepackage{trimclip}  % added by typography.py!", "latex")
Пример #13
0
#!/usr/bin/env python3
"""
Add abstract to pdf files.
"""

__author__ = "Benjamin Grange"

import copy

import panflute as pf

abstract = pf.MetaList()
in_abstract = False


def code_filter(elem, doc):
    global abstract
    global in_abstract

    if isinstance(elem, pf.Header):
        in_abstract = False
        if elem.identifier == "abstract":
            nodes = elem.parent.content
            within = False
            for n in iter(nodes):
                if isinstance(n, pf.Header) and n.identifier == "abstract":
                    within = True
                    continue
                if isinstance(n, pf.Header) and n.identifier == "endabstract":
                    break
                if within:
Пример #14
0
def prepare(doc):
    doc.exercisecount = 0  ## Added attribute!!
    doc.inside_exercise = False
    doc.questioncount = 0  ## Added attribute!!
    doc.inside_question = False
    doc.column_count = 0
    doc.columns_width = Dimension("600pt")
    doc.columns_sep = Dimension("0cm")
    doc.columns_to_patch = []
    doc.prev_column = None
    doc.enable_traditional_tables = False
    doc.disable_columns = True
    doc.custom_counters = {}

    #print >> sys.stderr, doc.format
    if doc.api_version == (1, 17, 0, 4):
        doc.disable_columns = False

    doc.pandoc_columns = doc.get_metadata('pandoc_columns',
                                          default=False,
                                          builtin=True)
    tables = doc.get_metadata('traditional-tables',
                              default=False,
                              builtin=True)
    doc.autounderlined = doc.get_metadata(
        'autounderlined', default=False, builtin=True) and latex_format(
            doc.format)
    framed_on = doc.get_metadata('includeframed', default=True,
                                 builtin=True) and latex_format(doc.format)
    doc.embed_pdfnotes = doc.get_metadata(
        'embed_pdfnotes', default=False,
        builtin=True) and doc.format == "beamer"
    doc.note_counter = 1

    if tables:
        doc.enable_traditional_tables = tables

    if doc.format == "latex" or doc.format == "beamer":

        if 'header-includes' in doc.metadata:
            includes = doc.metadata['header-includes']
        else:
            includes = pf.MetaList([])
            doc.metadata['header-includes'] = includes
        cont = includes.content
        ## TIKZ
        cont.append(pf.MetaInlines(pf.RawInline('\n\\usepackage{tikz}',
                                                'tex')))
        cont.append(
            pf.MetaInlines(
                pf.RawInline(
                    '\n\\usetikzlibrary{calc,backgrounds,arrows,shapes,matrix,fit,patterns,trees,positioning,decorations.pathreplacing,automata}',
                    'tex')))
        cont.append(
            pf.MetaInlines(pf.RawInline('\n\\usepackage{standalone}', 'tex')))
        cont.append(
            pf.MetaInlines(pf.RawInline('\n\\usepackage{color}', 'tex')))
        #Shaded enviroments
        if framed_on:
            cont.append(
                pf.MetaInlines(
                    pf.RawInline('\n\\usepackage{framed,color}', 'tex')))
            cont.append(
                pf.MetaInlines(
                    pf.RawInline('\n\\definecolor{shadecolor}{gray}{0.9}',
                                 'tex')))
            cont.append(
                pf.MetaInlines(
                    pf.RawInline('\n\\definecolor{gray}{rgb}{0.5,0.5,0.5}',
                                 'tex')))
            cont.append(
                pf.MetaInlines(pf.RawInline('\n\\usepackage{framed}', 'tex')))
Пример #15
0
def prepare(doc):
	##Load defaults	
	lang_dict={}
	lang_dict["lang1"]="SP"
	lang_dict["lang2"]="EN"
	lang_avail=["SP","EN"]
	lang_id=1 ## Fits

	lang1=doc.get_metadata('lang1')
	lang2=doc.get_metadata('lang2')

	## See if the user specified languages other than default 
	if lang1!=None:
		lang_dict["lang1"]=lang1
		lang_avail[0]=lang1
	if lang2!=None:
		lang_dict["lang2"]=lang2
		lang_avail[1]=lang2

	## Check user's choice 
	lang_enabled=doc.get_metadata('lang_enabled')

	if lang_enabled!=None:
		if lang_enabled=="1":
			doc.lang_str=lang_dict["lang1"]
			doc.lang_id=1
		elif lang_enabled=="2":
			doc.lang_str=lang_dict["lang2"]
			doc.lang_id=2
		else:	
			try:
				idx=lang_avail.index(lang_enabled)
			except:
				print(lang_enabled,"key not found in lang list", file=sys.stderr)
				exit(1)
			doc.lang_str=lang_enabled
			doc.lang_id=idx+1		
	else:
		doc.lang_str=lang_avail[0]	
		doc.lang_id=1


	## Tags to include/exclude stuff
	doc.include_begin="BEGIN-"+doc.lang_str
	doc.include_end="END-"+doc.lang_str

	if doc.lang_id==1:
		tag=lang_dict["lang2"]
	else:
		tag=lang_dict["lang1"]


	## Define some variables automatically (pandoc-crossref bridge code)
	default_vars(doc)

	## Deal with variable translation
	dual_vars(doc)

	doc.exclude_begin="BEGIN-"+tag
	doc.exclude_end="END-"+tag

	## Internal parameter
	doc.remove_component=False

	## Include for tex
	### IMPORTANT NOTICE: if the -H option of pandoc is used in the
	### Command line, then this will not take any effect whatsoever
	if doc.format=="latex" or doc.format=="beamer":

		if 'header-includes' in doc.metadata:
			includes=doc.metadata['header-includes']
			#pf.debug(type(includes))
			
		else:
			includes=pf.MetaList([])
			doc.metadata['header-includes']=includes
		cont=includes.content

		#for c in includes.content:
		#	pf.debug(c)
		#return

		cont.append(pf.MetaInlines(pf.RawInline('\n\\usepackage{comment}','tex')))

		cont.append(pf.MetaInlines(pf.RawInline('\n\\includecomment{in'+doc.lang_str+'}','tex')))
		cont.append(pf.MetaInlines(pf.RawInline('\n\\excludecomment{in'+tag+'}','tex')))
		cont.append(pf.MetaInlines(pf.RawInline('\n\\newcommand{\\dtext}[2]{#'+str(doc.lang_id)+'}','tex')))
		cont.append(pf.MetaInlines(pf.RawInline('\n\\newcommand{\\dcode}[2]{\\textcolor{NavyBlue}{#'+str(doc.lang_id)+'}}','tex')))
		cont.append(pf.MetaInlines(pf.RawInline('\n\\usepackage{tikz}','tex')))
		cont.append(pf.MetaInlines(pf.RawInline('\n\\usetikzlibrary{calc,backgrounds,arrows,shapes,matrix,fit,patterns,trees,positioning,decorations.pathreplacing,automata}','tex')))