86 lines
2.1 KiB
Python
86 lines
2.1 KiB
Python
# -*- encoding: utf-8 -*-
|
|
|
|
from .formatter import formatter
|
|
|
|
from collections import Iterable
|
|
|
|
|
|
class element:
|
|
|
|
""" Class representing a latex element. """
|
|
|
|
# Joiner for childrens
|
|
sep = '\n'
|
|
|
|
# Automatically add label after element if present
|
|
autolabel = True
|
|
|
|
def __init__(self, parent=None, childrens=[], label=None):
|
|
self.parent = parent
|
|
if childrens is None:
|
|
childrens = []
|
|
if not isinstance(childrens, Iterable):
|
|
childrens = [childrens]
|
|
self.childrens = []
|
|
self.add(childrens)
|
|
self.label = label
|
|
|
|
def add(self, childrens):
|
|
if not isinstance(childrens, Iterable):
|
|
childrens = [childrens]
|
|
for child in childrens:
|
|
if not isinstance(child, element):
|
|
child = wrapper_element(child, self)
|
|
try:
|
|
child.parent.remove(child)
|
|
except:
|
|
pass
|
|
child.parent = self
|
|
self.childrens.append(child)
|
|
|
|
def content(self):
|
|
return self.sep.join(map(str, self.childrens))
|
|
|
|
def fmt(self):
|
|
return formatter(self.templates)
|
|
|
|
def format_options(self, options):
|
|
if not options:
|
|
return ''
|
|
opts = []
|
|
for k, v in options.items():
|
|
opts.append('{key} = {{{value}}}'.format(key=k, value=v))
|
|
return self.fmt().format('options', {
|
|
'content': ', '.join(opts)
|
|
})
|
|
|
|
def format_label(self, label):
|
|
if not label:
|
|
return ''
|
|
return '\\label{{{}}}'.format(label)
|
|
|
|
def __str__(self):
|
|
out = self.content().strip()
|
|
if self.autolabel:
|
|
out += self.format_label(self.label)
|
|
return out
|
|
|
|
|
|
class wrapper_element(element):
|
|
|
|
""" Wrapper for standard python types working as latex elements. """
|
|
|
|
escape_list = ['_', '#', '%']
|
|
|
|
def __init__(self, data, parent):
|
|
super().__init__(parent=parent)
|
|
self.data = data
|
|
|
|
def escape(self, s):
|
|
for e in self.escape_list:
|
|
s = s.replace(e, '\\' + e)
|
|
return s
|
|
|
|
def content(self):
|
|
return self.escape(str(self.data))
|