import re

#
# This file shows how to create a custom template system.
#
# A template is a function that reads the template from a file and writes the
# expanded template to a file.
#

def underscore_replace(cfget, fd_in, fd_out):
    """
    Replace values represented as _SECTION_KEY_
    """
    # Complex regexp to avoid replacing inside words (like "_bar_" in
    # "foo_bar_baz")
    RE_LINE = re.compile(r"(?:^|(?<=\W))_(\w+(?:_\w+)*)_(?=\W|$)")

    def subst(mo):
        "Provides the value to substitute for a key"
        vals = mo.group(1).split("_", 1)
        if len(vals) == 1:
            query = mo.group(1)
        else:
            query = "/".join(vals)
        return cfget.query(query)

    # Filter all input lines through re.sub
    for line in fd_in:
        fd_out.write(RE_LINE.sub(subst, line))

def init(cfget):
    """
    This function is called by cfget when it loads this file as a plugin.

    The parameter 'cfget' is the main cfget engine, to which we can attach
    parsers, template engines and dump functions.
    """

    # Add the new template engine. The name is used in --template=NAME
    cfget.add_templater("underscores", underscore_replace)
