Debian Codegraph @

cloud_sptheme/ext/table_styling.py

raw symbols SCIP
1 """cloud_sptheme.ext.table_styling -- add directives for styling tables"""
2 #=============================================================================
3 # imports
4 #=============================================================================
5 # core
6 from cloud_sptheme.utils import PY3
7 if PY3:
8 from itertools import zip_longest as izip_longest
9 else:
10 # FIXME: not present in py25
11 from itertools import izip_longest
12 import os
13 # site
14 from docutils import nodes
15 from docutils.parsers.rst import directives
16 from docutils.parsers.rst.directives.tables import RSTTable
17 from sphinx.builders.html import StandaloneHTMLBuilder
18 try:
19 # sphinx 1.5 has it's own RSTTable, inherit from that if available.
20 from sphinx.directives.patches import RSTTable
21 except ImportError:
22 pass
23 # pkg
24 from cloud_sptheme import __version__
25 from cloud_sptheme import _root_dir, is_cloud_theme
26 from cloud_sptheme.utils import add_static_file
27 # local
28 __all__ = [
29 "setup",
30 ]
31
32 #=============================================================================
33 # constants
34 #=============================================================================
35
36 # name of key controlling whether css file is included
37 EMBED_KEY = "table_styling_embed_css"
38
39 # name of key controlling css class name
40 CLASS_KEY = "table_styling_class"
41
42 # name of key controlling css class name
43 TABLE_DEFAULT_ALIGN_KEY = "table_styling_default_align"
44
45 #=============================================================================
46 # field option parsers
47 #=============================================================================
48 def _split_argument_list(argument):
49 if "," in argument:
50 return argument.split(",")
51 else:
52 return argument.split()
53
54 def _parse_argument_map(argument, argmap, param):
55 args = _split_argument_list(argument)
56 if len(args) == 1 and all(c in argmap for c in args[0]):
57 args = args[0]
58 def norm(arg):
59 try:
60 return argmap[arg]
61 except KeyError:
62 raise ValueError("invalid %s: %r" % (param, arg))
63 return [norm(arg) for arg in args]
64
65
66 #: list of css classes from cloud.css_t which affect table alignment.
67 #: if any of these are present, TABLE_DEFAULT_ALIGN_KEY will be suppressed.
68 _cloud_table_align_classes = set(["centered"])
69
70 _alignment_map = dict(
71 l="left",
72 r="right",
73 c="center",
74 j="justify",
75 left="left",
76 right="right",
77 center="center",
78 centered="center", # compat alias
79 justify="justify",
80 justified="justify", # compat alias
81 )
82
83 def alignment_list(argument):
84 """convert into list of alignment options.
85 raise ``ValueError`` if no args found, or invalid strings.
86 """
87 return _parse_argument_map(argument, _alignment_map, "alignment")
88
89 _bool_map = {"true": True, "t": True,
90 "yes": True, "y": True,
91 "false": False, "f": False,
92 "no": False, "n": False,
93 }
94
95 def bool_list(argument):
96 """convert to list of true/false values"""
97 return _parse_argument_map(argument, _bool_map, "boolean value")
98
99 def class_option_list(argument):
100 """convert to list of list of classes"""
101 args = _split_argument_list(argument)
102 return [directives.class_option(arg) for arg in args]
103
104 _divider_map = {
105 "0": "no",
106 "1": "single",
107 "2": "double",
108 "none": "no",
109 "single": "single",
110 "double": "double",
111 }
112
113 def divider_list(argument):
114 return _parse_argument_map(argument, _divider_map, "divider style")
115
116 #=============================================================================
117 # replacement for table directive
118 #=============================================================================
119
120 class ExtendedRSTTable(RSTTable):
121 # TODO: could have this auto-generate tabularcolumns directive for latex,
122 # based on alignment, dividers, and wrapping settings:
123 # |,|| for dividers
124 # l,c,r - align, nowrap
125 # L,C,R,J - align, wrap
126 # XXX: how to handle widths for tabularcolumns?
127
128 option_spec = RSTTable.option_spec.copy()
129 option_spec.update({
130 # class, name already present
131 'header-columns': directives.nonnegative_int,
132 # TODO: column-widths: support limited set of units (em/in/%)
133 # expressable under both css & latex
134 'widths': directives.positive_int_list,
135 'column-alignment': alignment_list,
136 'header-alignment': alignment_list,
137 'column-wrapping': bool_list,
138 'column-classes': class_option_list,
139 'column-dividers': divider_list,
140 })
141
142 @property
143 def config(self):
144 """
145 custom hack to get config object easily
146 """
147 return self.state.document.settings.env.config
148
149 def run(self):
150 result = RSTTable.run(self)
151 if result and isinstance(result[0], nodes.table):
152 self._update_table_classes(result[0])
153 return result
154
155 def _update_table_classes(self, table):
156 # add global "table_styling_class"
157 assert isinstance(table, nodes.table)
158 config = self.config
159 classes = getattr(config, CLASS_KEY)
160 if classes:
161 for cls in classes.split():
162 table['classes'].append(cls)
163
164 self._update_table_alignment(table)
165
166 # figure out how many header rows & columns
167 options = self.options
168 header_cols = options.get("header-columns") or 0
169 widths = options.get("widths")
170
171 # Parse column options into list of ColumnOptions records.
172 # If any option is short, it will be padded with ``None`` values
173 # to match the longest list.
174 EMPTY = ()
175 opts = tuple(izip_longest(
176 options.get("column-alignment", EMPTY),
177 options.get("header-alignment", EMPTY),
178 options.get("column-wrapping", EMPTY),
179 options.get("column-classes", EMPTY),
180 options.get("column-dividers", EMPTY),
181 ))
182 NULL_OPTIONS = [None] * 5
183
184 # try to find "tgroup" node holding thead/tbody etc
185 def locate(cls):
186 for child in table.children:
187 if isinstance(child, cls):
188 return child
189 return None
190 tgroup = locate(nodes.tgroup)
191 if not tgroup:
192 return
193
194 # loop through content of 'tgroup' node --
195 # should be 0+ 'colspec' nodes, 0-1 thead node, and 0-1 tbody nodes.
196 # NOTE: using 'cgroup_idx' as hack to track colgroup index
197 cgroup_idx = 0
198 for child in tgroup:
199 # handle colspec entry (corresponding to COLGROUP)
200 # set group width & mark "header" columns
201 if isinstance(child, nodes.colspec):
202 if widths and cgroup_idx < len(widths):
203 child['colwidth'] = widths[cgroup_idx]
204 if cgroup_idx < header_cols:
205 child['stub'] = 1
206 cgroup_idx += 1
207 continue
208
209 # otherwise have thead / tbody --
210 # loop through each row in child, adding classes as appropriate
211 assert isinstance(child, (nodes.thead, nodes.tbody))
212 for row in child.children:
213
214 # check if we're in a header
215 is_header_row = isinstance(child, nodes.thead)
216
217 # Add alignment and wrap classes to each column (would add to
218 # colspec instead, but html doesn't inherit much from colgroup)
219 # We iterate trough the list of table cells in the row while
220 # maintaining the column format index in parallel
221 assert isinstance(row, nodes.row)
222 colidx = 0 # visible idx, to account for colspans
223 prev_col_classes = None
224 for idx, col in enumerate(row):
225
226 # get align/wrap options for column
227 try:
228 col_opts = opts[colidx]
229 except IndexError:
230 col_opts = NULL_OPTIONS
231 align, header_align, wrap, clist, divider = col_opts
232
233 # let header values override defaults
234 if is_header_row:
235 align = header_align
236 if align is None:
237 align = "left"
238
239 # add alignment / wrapping classes for column
240 assert isinstance(col, nodes.entry)
241 classes = col['classes']
242 if align:
243 classes.append(align + "-align")
244 if wrap is False:
245 classes.append("nowrap")
246 if clist:
247 classes.extend(clist)
248
249 if divider:
250 # add divider class for left side of this column,
251 classes.append(divider + "-left-divider")
252
253 # same divider type to right side of previous column,
254 # so that css can bind to either.
255 if prev_col_classes is not None:
256 prev_col_classes.append(divider + "-right-divider")
257
258 # update prev_col_classes for next pass
259 prev_col_classes = classes
260
261 # Now it's the time to advance the column format index.
262 # If we have a cell spans across the columns, we add the
263 # value of 'morecols', so we get the proper right divider
264 # for the current cell and the proper format index for the
265 # next loop iteration
266 colidx += 1 + col.get("morecols", 0)
267
268 # add divider to right side of last column
269 if prev_col_classes and colidx < len(opts):
270 align, header_align, wrap, clist, divider = opts[colidx]
271 if divider:
272 prev_col_classes.append(divider + "-right-divider")
273
274 def _update_table_alignment(self, table):
275 """
276 custom method to help with table alignment --
277 add default alignment, UNLESS one of cloud's table alignment directives is present
278 """
279 config = self.config
280
281 # debug hack
282 # print("table: classes=%r attrs=%r default=%r" % (table["classes"], table.attributes, getattr(config, TABLE_DEFAULT_ALIGN_KEY)))
283
284 # don't do anything if :align: directive present
285 align = table.attributes.get("align")
286 if align:
287 # TODO: would like to patch things so could pass in "fullwidth" here.
288 return
289
290 # don't do anything if cloud.css alignment-related rst-class is present
291 for_cloud = is_cloud_theme(config.html_theme)
292 if for_cloud and _cloud_table_align_classes.intersection(table["classes"]):
293 return
294
295 # apply default alignment
296 align = getattr(config, TABLE_DEFAULT_ALIGN_KEY)
297 if align:
298 table.attributes["align"] = align
299
300 #=============================================================================
301 # patch builder to copy css file (if needed)
302 #=============================================================================
303
304 css_path = os.path.join(_root_dir, "ext", "static", "table_styling.css")
305
306 def prepare_builder(app):
307 # make sure needed css styling gets included when building html
308 builder = app.builder
309 if not isinstance(builder, StandaloneHTMLBuilder):
310 return
311 if not getattr(app.config, EMBED_KEY):
312 return
313
314 # add custom css stylesheet
315 add_static_file(builder, css_path, stylesheet=True)
316
317 #=============================================================================
318 # register extension
319 #=============================================================================
320 def setup(app):
321 # whether it will embed raw css
322 app.add_config_value(EMBED_KEY, True, "html")
323
324 # default class to add to all styled tables
325 app.add_config_value(CLASS_KEY, "styled-table", "html")
326
327 # set default value for :align: directive
328 # (sphinx 2.0 forces "center" as the default)
329 app.add_config_value(TABLE_DEFAULT_ALIGN_KEY, "", "html")
330
331 # HACK: sphinx (>= 1.5) issues warning about replacing RSTTable.
332 # we know that's happening, so pop it out of registry first.
333 # (but ONLY if what's there wasn't already patched)
334 directive_map = directives._directives
335 if directive_map.get("table") is RSTTable:
336 directive_map.pop("table")
337
338 # replace existing table directive with custom one
339 app.add_directive("table", ExtendedRSTTable)
340
341 # add extra resources
342 app.connect("builder-inited", prepare_builder)
343
344 # identifies the version of our extension
345 return {'version': __version__}
346
347 #=============================================================================
348 # eof
349 #=============================================================================