Source

shinypress / shinypress / merge.py

Full commit
import traceback
import codecs
import os

from shinypress.handlers import handlers
from shinypress.themes import themes

from shinypress.latex import render_pdf

# TODO: use something nicer?
def warning(line_no, msg):
    print 'Warning (line %s): %s' % (line_no, msg)

def read_presentation(filename):
    lines = codecs.open(filename, 'rU', 'utf-8')

    # FIXME: hack to ensure relative paths work
    old = os.getcwd()
    new = os.path.dirname(filename)
    if new:
        os.chdir(new)

    content = []
    extras = []

    for i, line in enumerate(lines):
        line = line.strip()
        if not line or line.startswith('#') or line.startswith('//'):
            continue

        handler, filename = line.split(':', 1)
        handler = handler.strip()
        filename = filename.strip()

        # handle included files
        # FIXME: no recursion detection! :)
        if handler == 'include':
            c, e = read_presentation(filename)
            content.extend(c)
            extras.extend(e)
            continue

        if handler not in handlers:
            warning(i, 'Undefined handler: %s' % handler)
            continue

        handler_func = handlers[handler]
        try:
            c, e = handler_func(filename)
        except Exception, e:
            tb = traceback.format_exc()
            warning(i, 'Caught exception, traceback follows:\n%s' % (tb,))
        else:
            content.append((c, handler))
            extras.extend(e)

    os.chdir(old)
    return content, extras

# thing for reading the presentation format
class Presentation(object):
    def __init__(self, filename, theme):
        self.theme = theme
        self.content, self.extras = read_presentation(filename)

    def render_pdf(self):
        source, extras = self.theme.render(self.content)
        extras.extend(self.extras)
        return render_pdf(source, extras)