Mapytex/mapytex/calculus/API/renders.py

69 lines
1.6 KiB
Python
Raw Normal View History

#! /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
2020-12-15 14:37:27 +00:00
class Render(object):
""" Object which render Expression or token """
2019-05-14 04:55:56 +00:00
2020-12-15 14:37:27 +00:00
def __init__(self, default="txt"):
self._default = default
self._render = default
self.renders = {}
2018-09-20 16:38:49 +00:00
2020-12-15 14:37:27 +00:00
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")
2020-12-15 14:37:27 +00:00
@property
def render(self):
return self.renders[self._render]
2019-05-14 04:55:56 +00:00
2020-12-15 14:37:27 +00:00
def __call__(self, mo_tree, tmp_render=''):
if tmp_render:
r = self.renders[tmp_render]
else:
r = self.render
2018-09-20 16:38:49 +00:00
2020-12-15 14:37:27 +00:00
try:
return r["func"](mo_tree)
except ValueError:
pass
2020-12-15 14:37:27 +00:00
try:
return getattr(mo_tree, r["attribute"])
except AttributeError:
return str(mo_tree)
2019-05-14 04:55:56 +00:00
2020-12-15 14:37:27 +00:00
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