pyltk/pyltk/tabular.py

95 lines
2.6 KiB
Python

# -*- encoding: utf-8 -*-
from .element import element
class row_element(element):
""" Class representing a row of a tabular element. """
def __init__(self, columns, parent, label=None,
wrapper=False, endline=False):
super().__init__(parent, columns, label=label)
self.wrapper = wrapper
self.endline = endline
def content(self):
wp = str
if self.wrapper:
cw = 1/len(self.childrens)
wp = lambda c: str(self.wrapper(c, width=cw))
out = ' & '.join(map(wp, self.childrens))
if self.endline:
out += '\\\\'
return out
class hline_element(row_element):
def __init__(self, parent=None):
super().__init__([], parent)
def content(self):
return '\\hline'
# instance of hline element
hline = hline_element()
class tabular(element):
""" Class representing a latex tabular. """
templates = {
'content': """\\begin{{tabular}}{{{columns}}}
{inner}
\\end{{tabular}}"""
}
def __init__(self, parent=None, rows=[], columns=None,
autowrap=False, label=None):
""" Create a tabular with given rows and column specification.
Parameters:
- rows Rows for the tabular (list of list or list of string).
- columns String representing columns options.
"""
super().__init__(parent, label=label)
self.columns = columns
self.autowrap = autowrap
for row in rows:
self.addrow(row)
def addhline(self):
""" Add a hline to the current tabular element. """
self.addrow(hline_element(self), False)
def addrow(self, row, wrap=None):
""" Add a row to the tabular.
Parameters:
- row Array or string (array will be joined with ' & ').
- wrap Can contains a wrapper element (typically a resizebox) for
the cell of the row.
"""
if not isinstance(row, row_element):
row = row_element(row, parent=self)
if wrap is None:
wrap = self.autowrap
row.wrapper = wrap
if self.childrens:
last = self.childrens[-1]
if isinstance(last, row_element):
last.endline = True
self.add(row)
def addrows(self, rows):
""" Add multiple rows to the tabular (see addrow). """
for row in rows:
self.addrow(row)
def content(self):
return self.fmt().format('content', {
'columns': self.columns,
'inner': super().content()
})