Example #1
0
def links_append():
    """Add Markdown links table to Markdown files."""
    if "links" not in ivy.site.config:
        return

    with open(ivy.site.config["links"], "r") as reader:
        links = yaml.safe_load(reader)
    util.make_config("links", links)

    links_table = "\n".join(f'[{entry["key"]}]: {entry["url"]}'
                            for entry in links)

    def visitor(node):
        if _needs_links(node):
            node.text += "\n\n" + links_table

    ivy.nodes.root().walk(visitor)
Example #2
0
def _flatten_tables(collected):
    """Convert collected table information to flat lookup table."""
    major = util.make_major()
    tables = util.make_config("tables")
    for fileslug in collected:
        if fileslug in major:
            for (i, entry) in enumerate(collected[fileslug]):
                entry.number = (str(major[fileslug]), str(i + 1))
                tables[entry.slug] = entry
Example #3
0
def collect():
    """Collect information by parsing shortcodes."""
    parser = shortcodes.Parser(inherit_globals=False, ignore_unknown=True)
    parser.register(_process_index, "i", "/i")
    index = util.make_config("index")
    ivy.nodes.root().walk(lambda node: parser.parse(node.text, {
        "node": node,
        "index": index
    }))
def bib_ref(pargs, kwargs, node):
    """Handle [% b "key1,key2" %] biblography reference shortcodes."""
    if len(pargs) == 0:
        util.fail(f"Empty 'b' shortcode in {node.filepath}")

    citations = util.make_config("citations")
    citations |= set(pargs)

    keys = [f'<a href="@root/bibliography/#{k}">{k}</a>' for k in pargs]
    return f"[{', '.join(keys)}]"
Example #5
0
def glossary_ref(pargs, kwargs, node, content):
    """Handle [% g slug %]text[% /g %] glossary reference shortcodes."""
    if len(pargs) != 1:
        util.fail(f"Badly-formatted 'g' shortcode {pargs} in {node.filepath}")

    definitions = util.make_config("definitions")
    slug = pargs[0]
    definitions.add(slug)

    return (
        f'<a class="glossref" href="@root/glossary/#{slug}" markdown="1">{content}</a>'
    )
Example #6
0
def glossary(pargs, kwargs, node):
    """Convert glossary to Markdown."""
    if "glossary" not in ivy.site.config:
        return '<p class="warning">No glossary specified.</p>'
    if "lang" not in ivy.site.config:
        return '<p class="warning">No language specified.</p>'

    with open(ivy.site.config["glossary"], "r") as reader:
        glossary = yaml.safe_load(reader) or {}
    lang = ivy.site.config["lang"]

    try:
        glossary.sort(key=lambda x: x[lang]["term"].lower())
    except KeyError as exc:
        util.fail(
            f"Glossary entry or entries missing key, term, or {lang}: {exc}.")

    util.make_config("glossary", glossary)

    lookup = {entry["key"]: entry[lang]["term"] for entry in glossary}
    result = "\n\n".join(
        _as_markdown(lookup, lang, entry) for entry in glossary)
    return result
Example #7
0
def excerpt(pargs, kwargs, node):
    """Handle a file inclusion, possibly excerpting."""
    # Error checking.
    if pargs:
        util.fail(
            f"Badly-formatted excerpt shortcode with {pargs} in {node.filepath}"
        )

    # Handle by cases.
    inclusions = util.make_config("inclusions")
    if ("pat" in kwargs) and ("fill" in kwargs):
        return _multi(inclusions, node, **kwargs)
    elif "file" not in kwargs:
        util.fail(
            f"Badly-formatted excerpt shortcode with {kwargs} in {node.filepath}"
        )
    elif ("keep" in kwargs) and ("omit" in kwargs):
        return _keep_omit(inclusions, node, **kwargs)
    elif "keep" in kwargs:
        return _keep(inclusions, node, **kwargs)
    elif "omit" in kwargs:
        return _omit(inclusions, node, **kwargs)
    else:
        return _file(inclusions, node, **kwargs)
Example #8
0
def _flatten_headings(collected):
    """Create flat cross-reference table."""
    headings = util.make_config("headings")
    for group in collected.values():
        for entry in group:
            headings[entry.slug] = entry
    if (bib_filename := ivy.site.config.get("bibliography", None)) is None:
        return '<p class="warning">No bibliography specified.</p>'
    if (bib_style := ivy.site.config.get("bibliography_style", None)) is None:
        return '<p class="warning">No bibliography style specified.</p>'

    # Set up Pybtex.
    html = find_plugin("pybtex.backends", "html")()
    style = find_plugin("pybtex.style.formatting", bib_style)()

    # Format a single bibliography entry.
    def _format(key, body):
        return f'<dt id="{key}">{key}</dt>\n<dd>{body}</dd>'

    # Load and save bibliography.
    bib = parse_file(bib_filename)
    util.make_config("bibliography", {k for k in bib.entries.keys()})

    # Generate HTML.
    formatted = style.format_bibliography(bib)
    entries = [
        _format(entry.key, entry.text.render(html)) for entry in formatted
    ]
    return '<dl class="bibliography">\n\n' + "\n\n".join(entries) + "\n\n</dl>"


@ivy.events.register(ivy.events.Event.EXIT)
def check():
    if (citations := util.get_config("citations")) is None:
        return
    if (bibliography := util.get_config("bibliography")) is None:
        return