Skip to content

Commit

Permalink
Added a tabularx environment, added a new column type to
Browse files Browse the repository at this point in the history
count table width from (X)
  • Loading branch information
Vladimir Gorovikov committed Jul 14, 2016
1 parent 6792f97 commit 1cdbb5d
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 8 deletions.
2 changes: 1 addition & 1 deletion pylatex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .package import Package
from .section import Section, Subsection, Subsubsection
from .table import Table, MultiColumn, MultiRow, Tabular, Tabu, LongTable, \
LongTabu, ColoredTable, LongColoredTable
LongTabu, ColoredTable, LongColoredTable, Tabularx, Column
from .tikz import TikZ, Axis, Plot
from .figure import Figure, SubFigure, StandAloneGraphic
from .lists import Enumerate, Itemize, Description
Expand Down
61 changes: 56 additions & 5 deletions pylatex/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
import re


# The letters used to count the table width
COLUMN_LETTERS = ['l', 'c', 'r', 'p', 'm', 'b', 'X']


def _get_table_width(table_spec):
"""Calculate the width of a table based on its spec.
Expand All @@ -31,13 +35,15 @@ def _get_table_width(table_spec):
The width of a table which uses the specification supplied.
"""

column_letters = ['l', 'c', 'r', 'p', 'm', 'b']

# Remove things like {\bfseries}
cleaner_spec = re.sub(r'{[^}]*}', '', table_spec)

# Remove X[] in tabu environments so they dont interfere with column count
for l in COLUMN_LETTERS:
cleaner_spec = re.sub(r'X\[[^X]*' + l + r'\]', l, cleaner_spec)
spec_counter = Counter(cleaner_spec)

return sum(spec_counter[l] for l in column_letters)
return sum(spec_counter[l] for l in COLUMN_LETTERS)


class Tabular(Environment):
Expand All @@ -49,7 +55,7 @@ class Tabular(Environment):
}

def __init__(self, table_spec, data=None, pos=None, *, row_height=None,
col_space=None, **kwargs):
col_space=None, arguments=None, **kwargs):
"""
Args
----
Expand All @@ -62,6 +68,8 @@ def __init__(self, table_spec, data=None, pos=None, *, row_height=None,
row height
col_space: str
Specifies the spacing between table columns
arguments: str or `list`
The arguments to append to the table
References
----------
Expand All @@ -72,8 +80,17 @@ def __init__(self, table_spec, data=None, pos=None, *, row_height=None,
self.row_height = row_height
self.col_space = col_space

# Append the table_spec to the arguments list
if arguments is not None:
if isinstance(arguments, str):
arguments = [arguments]
else:
arguments = []

arguments.append(table_spec)

super().__init__(data=data, options=pos,
arguments=table_spec, **kwargs)
arguments=arguments, **kwargs)

def dumps(self):
r"""Turn the Latex Object into a string in Latex format."""
Expand Down Expand Up @@ -170,6 +187,12 @@ def add_row(self, cells, *, escape=None, mapper=None, strict=True):
mapper=mapper) + NoEscape(r'\\'))


class Tabularx(Tabular):
"""A class that represents a tabularx environment."""

packages = [Package('tabularx')]


class MultiColumn(Container):
"""A class that represents a multicolumn inside of a table."""

Expand Down Expand Up @@ -347,3 +370,31 @@ class LongColoredTable(ColoredTable, LongTabu):
"""Class representing a longtabu with colored rows."""

_latex_name = "longtabu"


class Column(UnsafeCommand):
"""A class representing a new column type."""

_repr_attributes_mapping = {
'name': 'arguments',
'base': 'arguments',
'modifications': 'arguments'
}

def __init__(self, name, base, modifications):
"""
Args
----
name: str
The name of the new column type
base: str
The name of the base column type
modifications: str
The modifications made to the column type
"""

COLUMN_LETTERS.append(name)

modified = r">{%s\arraybackslash}%s" % (modifications, base)

super().__init__(command="newcolumntype", arguments=[name, modified])
13 changes: 11 additions & 2 deletions tests/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@
Package, TikZ, Axis, Plot, Itemize, Enumerate, Description, MultiColumn, \
MultiRow, Command, Matrix, VectorName, Quantity, TableRowSizeError, \
LongTable, ColoredTable, Position, FlushLeft, FlushRight, Center, \
MiniPage, TextBlock, PageStyle, Head, Foot, StandAloneGraphic
MiniPage, TextBlock, PageStyle, Head, Foot, StandAloneGraphic, Tabularx, \
Column
from pylatex.utils import escape_latex, fix_filename, dumps_list, bold, \
italic, verbatim, center, flush_left, flush_right, huge, header1, \
header2, small1, small2, text_color, page_break, new_line, line_break, \
horizontal_fill, vertical_skip, horizontal_skip, display_page_number, \
text_box
text_box, NoEscape

matplotlib.use('Agg') # Not to use X server. For TravisCI.
import matplotlib.pyplot as pyplot # noqa
Expand Down Expand Up @@ -101,6 +102,10 @@ def test_table():

repr(t)

# TabularX
tabularx = Tabularx(table_spec='X X X', arguments=NoEscape(r"\textwidth"))
tabularx.add_row(["test1", "test2", "test3"])

# Long Table
longtable = LongTable(table_spec='c c c')
longtable.add_row(["test", "test2", "test3"])
Expand All @@ -110,6 +115,10 @@ def test_table():
coloredtable = ColoredTable(table_spec='X[c] X[c]')
coloredtable.add_row(["test", "test2"], color="gray", mapper=bold)

# Column
column = Column("R", "X", r"\raggedleft")
repr(column)


def test_command():
c = Command(command='documentclass', arguments=None, options=None,
Expand Down

0 comments on commit 1cdbb5d

Please sign in to comment.