#!/usr/bin/env python # -*- coding: utf-8 -*- """Template for .tex generation settings and utilities""" from jinja2 import Environment, FileSystemLoader, ChoiceLoader, PackageLoader, \ TemplateNotFound, nodes from jinja2.ext import Extension from jinja2.meta import find_referenced_templates as find_templates import codecs import os import re import json from songbook_core import errors _LATEX_SUBS = ( (re.compile(r'\\'), r'\\textbackslash'), (re.compile(r'([{}_#%&$])'), r'\\\1'), (re.compile(r'~'), r'\~{}'), (re.compile(r'\^'), r'\^{}'), (re.compile(r'"'), r"''"), (re.compile(r'\.\.\.+'), r'\\ldots'), ) _VARIABLE_REGEXP = re.compile(r""" \(\*\ *variables\ *\*\) # Match (* variables *) ( # Match and capture the following: (?: # Start of non-capturing group, used to match a single character (?! # only if it's impossible to match the following: \(\*\ * # - a literal (* (?: # Inner non-capturing group, used for the following alternation: variables # - Either match the word variables | # or endvariables # - the word endvariables ) # End of inner non-capturing group \ *\*\) # - a literal *) ) # End of negative lookahead assertion . # Match any single character )* # Repeat as often as possible ) # End of capturing group 1 \(\*\ *endvariables\ *\*\) # until (* endvariables *) is matched.""", re.VERBOSE|re.DOTALL) class VariablesExtension(Extension): """Extension to jinja2 to silently ignore variable block. Instead, they are parsed by this module. """ tags = set(['variables']) def parse(self, parser): parser.stream.next() parser.parse_statements( end_tokens=['name:endvariables'], drop_needle=True, ) return nodes.Const("") def _escape_tex(value): '''Escape TeX special characters''' newval = value for pattern, replacement in _LATEX_SUBS: newval = pattern.sub(replacement, newval) return newval class TexRenderer(object): """Render a template to a LaTeX file.""" def __init__(self, template, datadir, lang): '''Start a new jinja2 environment for .tex creation. Arguments: - template: name of the template to use. - datadir: location of the data directory (which max contain file /templates/