Mapytex/mapytex/calculus/API/renders.py
Bertrand Benjamin 78ce8f767a
All checks were successful
continuous-integration/drone/push Build is passing
Fix: fraction rendering
2021-09-25 18:05:05 +02:00

73 lines
1.7 KiB
Python

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Expression
"""
from ..core import tree2txt, tree2tex
class Render(object):
""" Object which render Expression or token """
def __init__(self, default="txt"):
self._default = default
self._render = default
self.renders = {}
def register_render(self, name, func, attribute):
""" register a render """
try:
self.renders[name]
except KeyError:
self.renders[name] = {"name": name, "func": func, "attribute": attribute}
else:
raise ValueError("This render name already exists")
@property
def render_name(self):
return self._render
@property
def render(self):
return self.renders[self._render]
def __call__(self, mo_tree, tmp_render=''):
if tmp_render:
r = self.renders[tmp_render]
else:
r = self.render
try:
return r["func"](mo_tree)
except ValueError:
pass
try:
return getattr(mo_tree, r["attribute"])
except AttributeError:
return str(mo_tree)
def set_render(self, render):
""" Define the render """
if render in self.renders.keys():
self._render = render
else:
raise ValueError("This render does not exists")
render = Render()
render.register_render("txt", tree2txt, "__txt__")
render.register_render("tex", tree2tex, "__tex__")
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del