flexablelib 2.0.13__tar.gz → 2.0.14__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {flexablelib-2.0.13 → flexablelib-2.0.14}/CHANGELOG.md +19 -0
  2. {flexablelib-2.0.13/flexablelib.egg-info → flexablelib-2.0.14}/PKG-INFO +1 -1
  3. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/cells.py +58 -58
  4. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/table.py +346 -2
  5. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/writers.py +131 -0
  6. {flexablelib-2.0.13 → flexablelib-2.0.14/flexablelib.egg-info}/PKG-INFO +1 -1
  7. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib.egg-info/SOURCES.txt +1 -0
  8. {flexablelib-2.0.13 → flexablelib-2.0.14}/package.json +1 -1
  9. flexablelib-2.0.14/tests/test_v214_features.py +105 -0
  10. {flexablelib-2.0.13 → flexablelib-2.0.14}/LICENSE +0 -0
  11. {flexablelib-2.0.13 → flexablelib-2.0.14}/MANIFEST.in +0 -0
  12. {flexablelib-2.0.13 → flexablelib-2.0.14}/README.md +0 -0
  13. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/__init__.py +0 -0
  14. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/_speedups.c +0 -0
  15. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/_width_tables.h +0 -0
  16. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/colors.py +0 -0
  17. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/columns.py +0 -0
  18. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/fast.py +0 -0
  19. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/merges.py +0 -0
  20. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/options.py +0 -0
  21. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/readers.py +0 -0
  22. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/style_compositions.py +0 -0
  23. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/table_strings.py +0 -0
  24. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/text_width.py +0 -0
  25. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib/utils.py +0 -0
  26. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib.egg-info/dependency_links.txt +0 -0
  27. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib.egg-info/requires.txt +0 -0
  28. {flexablelib-2.0.13 → flexablelib-2.0.14}/flexablelib.egg-info/top_level.txt +0 -0
  29. {flexablelib-2.0.13 → flexablelib-2.0.14}/setup.cfg +0 -0
  30. {flexablelib-2.0.13 → flexablelib-2.0.14}/setup.py +0 -0
  31. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_cells.py +0 -0
  32. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_columns.py +0 -0
  33. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_excel.py +0 -0
  34. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_features.py +0 -0
  35. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_issues.py +0 -0
  36. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_merge_edge_matrix.py +0 -0
  37. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_merges.py +0 -0
  38. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_readme_examples.py +0 -0
  39. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_styles.py +0 -0
  40. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_text_width.py +0 -0
  41. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_two_pass_measurement.py +0 -0
  42. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_upstream_issues.py +0 -0
  43. {flexablelib-2.0.13 → flexablelib-2.0.14}/tests/test_v213_features.py +0 -0
  44. {flexablelib-2.0.13 → flexablelib-2.0.14}/tools/benchmark.py +0 -0
  45. {flexablelib-2.0.13 → flexablelib-2.0.14}/tools/generate_width_tables.py +0 -0
@@ -2,6 +2,25 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [2.0.14] - 2026-10-28
6
+
7
+ ### Added
8
+ - ``Table.valign`` / ``col_valign`` / ``cell_valign``: vertical cell alignment
9
+ ``t`` / ``m`` / ``b`` inside multi-line rows (texttable-style).
10
+ - ``Table.panel`` + ``Table.shadow``: outer frame (rounded/sharp/ascii/double/heavy)
11
+ and optional drop-shadow (tabled Panel / Spectre style).
12
+ - Export writers: ``to_rst()``, ``to_asciidoc()``, ``to_latex()``.
13
+ - ``Table.transpose()`` / ``rotate()``: swap rows and columns for display.
14
+ - ``Table.paginate(page_length=...)``: list of composed page strings with
15
+ headers repeated (PrettyTable / go-pretty).
16
+ - Nested subtables: a cell whose value is a ``Table`` is composed into a
17
+ multiline cell (minimal useful nesting).
18
+
19
+ ### Notes
20
+ - Column percent-width constraints (F10) remain covered by existing
21
+ ``column_min_width`` / ``column_max_width``; no API change.
22
+ - Streaming / incremental print (F13) deferred.
23
+
5
24
  ## [2.0.13] - 2026-10-28
6
25
 
7
26
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 2.0.13
3
+ Version: 2.0.14
4
4
  Summary: Flexible console and HTML tables for Python
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Download-URL:
@@ -408,81 +408,81 @@ def __zip_sub_rows(row: Union[list, tuple]) -> tuple:
408
408
  only_sub_row = row[0]
409
409
  return only_sub_row
410
410
 
411
- def _wrap_rows(headers: Union[list, tuple],
412
- data: Union[List[Union[list, tuple]], Tuple[Union[list, tuple]]]
411
+
412
+ def _normalize_valign(code) -> str:
413
+ """Map caller codes to ``t`` / ``m`` / ``b`` (default top)."""
414
+ if code is None:
415
+ return 't'
416
+ key = str(code).strip().lower()
417
+ if key in ('t', 'top'):
418
+ return 't'
419
+ if key in ('m', 'middle', 'c', 'center', 'centre'):
420
+ return 'm'
421
+ if key in ('b', 'bottom'):
422
+ return 'b'
423
+ raise ValueError(
424
+ "valign must be one of 't'/'m'/'b' (or top/middle/bottom), got {!r}"
425
+ .format(code)
426
+ )
427
+
428
+
429
+ def _wrap_rows(headers: Union[list, tuple],
430
+ data: Union[List[Union[list, tuple]], Tuple[Union[list, tuple]]],
431
+ header_valigns=None,
432
+ row_valigns=None,
413
433
  ) -> Tuple[list, list]:
414
434
  """
415
435
  Wraps the rows and headers of the table if
416
- any new line characters are present::
417
-
418
- _wrap_rows(headers=['a', 'b\\nc'], data=[['a', 'b\\nc'], ['c', 'd']])
419
-
420
- Results in:
436
+ any new line characters are present.
421
437
 
422
- >>> ([['a', 'b'], ['', 'c']], [[['a', 'b'], ['', 'c']], [['c', 'd']]])
423
- >>> | ^ ^ | | ^ ^ | | |
424
- >>> # sub-row sub-row sub-row sub-row no sub-rows
425
- >>> #<-------wrapped-------> <-------wrapped-------> <not wrapped>
438
+ ``header_valigns`` / ``row_valigns`` optionally shift short cells inside
439
+ the tallest cell of that row (``t`` / ``m`` / ``b``). ``row_valigns`` is
440
+ a sequence parallel to ``data``; each entry is a sequence of codes, one
441
+ per cell (or ``None`` for top).
426
442
  """
427
- # If no headers are provided, return None.
428
443
  wrapped_headers = None
429
-
444
+
430
445
  there_are_headers = headers is not None and is_some_instance(headers, list, tuple)
431
446
  if there_are_headers:
432
- # If there are headers, wrap them.
433
- wrapped_headers = __wrap_single_row(headers)
434
-
435
- # Wrap each row.
436
- # If no new line characters are present, data is returned as it is.
437
- wrapped_data = list(map(__wrap_single_row, data))
447
+ wrapped_headers = __wrap_single_row(headers, header_valigns)
448
+
449
+ if row_valigns is None:
450
+ wrapped_data = [__wrap_single_row(row) for row in data]
451
+ else:
452
+ wrapped_data = []
453
+ for row_i, row in enumerate(data):
454
+ valigns = row_valigns[row_i] if row_i < len(row_valigns) else None
455
+ wrapped_data.append(__wrap_single_row(row, valigns))
438
456
 
439
457
  return wrapped_headers, wrapped_data
440
458
 
441
459
 
442
- def __wrap_single_row(row: Union[list, tuple]) -> list:
460
+ def __wrap_single_row(row: Union[list, tuple], valigns=None) -> list:
443
461
  """
444
- Will split every cell that has an new line character.
445
- The splitted cell generates a new sub-row, and every other
446
- cell that doesn't have a new line character will be adjusted::
462
+ Split cells on newlines and pad short cells vertically.
447
463
 
448
- __wrap_single_row(['a', 'b\\nc'])
449
-
450
- Results in:
451
-
452
- >>> [['a', 'b'], ['', 'c']]
453
- >>> ^
454
- >>> # Blank space to adjust the cell.
464
+ Default valign is top (blank lines under the content). Pass ``valigns``
465
+ as a parallel list of ``t`` / ``m`` / ``b`` to middle- or bottom-align.
455
466
  """
456
- # Split in lines if any new line characters are present.
457
467
  splitted_cells = list(map(__wrap_cell, row))
458
-
459
- # Get the quantity of sub-rows calculating the max length of
460
- # all of the splitted (or not) cells.
461
468
  quantity_of_sub_rows = max([len(x) for x in splitted_cells])
462
-
463
- # Create blank sub-rows each one having the same quantity of
464
- # cells as the original row.
465
- sub_rows = [['' for x in range(len(row))]
469
+ sub_rows = [['' for x in range(len(row))]
466
470
  for _ in range(quantity_of_sub_rows)]
467
-
468
- # Fill the sub-rows with the splitted cells.
469
- #
470
- # [['a'], ['b', 'c']] <-- splitted_cells
471
- # ^ ^ ^
472
- # sbr0 sbr0 sbr1
473
- # <cell0> <--cell1-->
474
- #
475
- # [['a', 'b'], ['', 'c']] <-- sub_rows (being filled)
476
- # ^ ^ ^ ^
477
- # [0][0] [0][1] ^ [1][1] <-- sub_rows[sub_row][cell]
478
- # [0][0] [1][0] ^ [1][1] <-- splitted_cells[cell][sub-row]
479
- # ^
480
- # There's no second sub-row in the first cell,
481
- # so it's just left empty
482
- #
471
+
483
472
  for cell in range(len(splitted_cells)):
484
- for sub_row in range(len(splitted_cells[cell])):
485
- sub_rows[sub_row][cell] = splitted_cells[cell][sub_row]
473
+ parts = splitted_cells[cell]
474
+ height = len(parts)
475
+ code = 't'
476
+ if valigns is not None and cell < len(valigns) and valigns[cell] is not None:
477
+ code = _normalize_valign(valigns[cell])
478
+ if code == 'b':
479
+ start = quantity_of_sub_rows - height
480
+ elif code == 'm':
481
+ start = (quantity_of_sub_rows - height) // 2
482
+ else:
483
+ start = 0
484
+ for sub_row in range(height):
485
+ sub_rows[start + sub_row][cell] = parts[sub_row]
486
486
 
487
487
  return sub_rows
488
488
 
@@ -492,8 +492,8 @@ def __wrap_cell(cell: Any) -> Union[List[str], Any]:
492
492
  Split in lines a cell if it has a new line character::
493
493
 
494
494
  'a' -> ['a']
495
- 'a\\nb' -> ['a', 'b']
496
- 'a\\tb' -> ['a b']
495
+ 'a\nb' -> ['a', 'b']
496
+ 'a\tb' -> ['a b']
497
497
  '' -> ['']
498
498
  123 -> [123]
499
499
  None -> [None]
@@ -819,6 +819,13 @@ class Table(object):
819
819
  self.__cell_padding = None
820
820
  # 'wrap' | 'truncate' | None (None defers to auto_wrap bool).
821
821
  self.__overflow = None
822
+ # Vertical cell align: 't'/'m'/'b' default, plus per-column / per-cell maps.
823
+ self.__valign = 't'
824
+ self.__col_valign = None
825
+ self.__cell_valign = {}
826
+ # Outer panel frame (tabled/Spectre style) + optional shadow.
827
+ self.__panel = False
828
+ self.__shadow = False
822
829
  # Row indexes after which a horizontal rule is forced.
823
830
  self.__dividers = set()
824
831
  # Sort / filter applied to the display copy, not to stored data.
@@ -1455,6 +1462,47 @@ class Table(object):
1455
1462
  """
1456
1463
  return self.__overflow
1457
1464
 
1465
+ @property
1466
+ def valign(self):
1467
+ """
1468
+ Default vertical cell alignment inside a multi-line row: ``'t'``,
1469
+ ``'m'``, or ``'b'`` (texttable-style). Overridden by
1470
+ :attr:`col_valign` and :attr:`cell_valign`.
1471
+ """
1472
+ return self.__valign
1473
+
1474
+ @property
1475
+ def col_valign(self):
1476
+ """
1477
+ Per-column vertical alignment: a code, list/tuple of codes, or
1478
+ ``{header_or_index: code}``.
1479
+ """
1480
+ return self.__col_valign
1481
+
1482
+ @property
1483
+ def cell_valign(self):
1484
+ """
1485
+ Per-cell vertical alignment map ``{(row, col): 't'|'m'|'b'}``.
1486
+ ``col`` may be a header name or 0-based index.
1487
+ """
1488
+ return self.__cell_valign
1489
+
1490
+ @property
1491
+ def panel(self):
1492
+ """
1493
+ When true (or a box style name), wrap the composed table in an outer
1494
+ frame. Inspired by tabled Panel / Spectre Panel.
1495
+ """
1496
+ return self.__panel
1497
+
1498
+ @property
1499
+ def shadow(self):
1500
+ """
1501
+ When true (or a character), draw a drop-shadow on the right and
1502
+ bottom of the composed table (or of the panel, when both are set).
1503
+ """
1504
+ return self.__shadow
1505
+
1458
1506
  @property
1459
1507
  def sort_by(self):
1460
1508
  """
@@ -1799,6 +1847,60 @@ class Table(object):
1799
1847
  self.__overflow = 'truncate' if value == 'ellipsis' else value
1800
1848
  self.__auto_wrap_table = self.__overflow == 'wrap'
1801
1849
 
1850
+ @valign.setter
1851
+ def valign(self, value):
1852
+ from .cells import _normalize_valign
1853
+ self.__valign = _normalize_valign(value)
1854
+
1855
+ @col_valign.setter
1856
+ def col_valign(self, value):
1857
+ if value is None:
1858
+ self.__col_valign = None
1859
+ return
1860
+ from .cells import _normalize_valign
1861
+ if isinstance(value, dict):
1862
+ self.__col_valign = {
1863
+ key: _normalize_valign(code) for key, code in value.items()
1864
+ }
1865
+ elif is_some_instance(value, list, tuple):
1866
+ self.__col_valign = [_normalize_valign(code) for code in value]
1867
+ else:
1868
+ self.__col_valign = _normalize_valign(value)
1869
+
1870
+ @cell_valign.setter
1871
+ def cell_valign(self, value):
1872
+ if value is None:
1873
+ self.__cell_valign = {}
1874
+ return
1875
+ if not isinstance(value, dict):
1876
+ raise TypeError('cell_valign must be a dict of (row, col) -> code')
1877
+ from .cells import _normalize_valign
1878
+ self.__cell_valign = {
1879
+ key: _normalize_valign(code) for key, code in value.items()
1880
+ }
1881
+
1882
+ @panel.setter
1883
+ def panel(self, value):
1884
+ if value is None or value is False:
1885
+ self.__panel = False
1886
+ return
1887
+ if value is True:
1888
+ self.__panel = True
1889
+ return
1890
+ # Named box style: store the string so the renderer can pick glyphs.
1891
+ self.__panel = str(value)
1892
+
1893
+ @shadow.setter
1894
+ def shadow(self, value):
1895
+ if value is None or value is False:
1896
+ self.__shadow = False
1897
+ return
1898
+ if value is True:
1899
+ self.__shadow = True
1900
+ return
1901
+ # Custom shadow glyph (one visible character preferred).
1902
+ self.__shadow = str(value) if str(value) else True
1903
+
1802
1904
  @sort_by.setter
1803
1905
  def sort_by(self, value):
1804
1906
  self.__sort_by = value
@@ -3472,6 +3574,10 @@ class Table(object):
3472
3574
  formatted = self.__apply_format_spec(value, self.__float_format)
3473
3575
  else:
3474
3576
  formatted = value
3577
+ elif isinstance(value, Table):
3578
+ # Minimal nested subtable: compose the child into a multiline cell.
3579
+ # Child panel/shadow still apply; avoid cycles by not wrapping self.
3580
+ formatted = value.compose()
3475
3581
  else:
3476
3582
  formatted = value
3477
3583
 
@@ -3962,9 +4068,17 @@ class Table(object):
3962
4068
  semi_processed_columns = self.__semi_processed_columns
3963
4069
  processed_columns = self.__processed_columns
3964
4070
 
4071
+ # Fitting can hand back a one-shot zip(); materialise before any
4072
+ # pass that walks the rows (valign resolution would otherwise empty it).
4073
+ rows = list(rows) if rows is not None else []
4074
+ header_valigns, row_valigns = self.__valigns_for_wrap(
4075
+ headers, rows
4076
+ )
3965
4077
  wrapped_headers, wrapped_rows = _wrap_rows(
3966
- headers,
3967
- rows
4078
+ headers,
4079
+ rows,
4080
+ header_valigns=header_valigns,
4081
+ row_valigns=row_valigns,
3968
4082
  )
3969
4083
  transformed_columns, transformed_headers = _zip_wrapped_rows(
3970
4084
  wrapped_headers,
@@ -4224,6 +4338,7 @@ class Table(object):
4224
4338
  if self.__border_texts:
4225
4339
  table_string = self.__apply_vertical_border_texts(table_string)
4226
4340
 
4341
+ table_string = self.__apply_panel_and_shadow(table_string)
4227
4342
  return self.__apply_table_align(table_string)
4228
4343
 
4229
4344
  def __join_body_rows(self, body_rows, body_line, separator_line,
@@ -4298,6 +4413,132 @@ class Table(object):
4298
4413
  left = (table_width - title_width) // 2
4299
4414
  return (' ' * left) + title
4300
4415
 
4416
+
4417
+ def __valign_for_cell(self, row_index, header, column_i):
4418
+ """Resolve t/m/b for one body cell (cell > column > default)."""
4419
+ from .cells import _normalize_valign
4420
+ cell_map = self.__cell_valign or {}
4421
+ if cell_map:
4422
+ for key in ((row_index, header), (row_index, column_i)):
4423
+ if key in cell_map:
4424
+ return _normalize_valign(cell_map[key])
4425
+ per = self.__col_valign
4426
+ if per is not None:
4427
+ if isinstance(per, dict):
4428
+ if header in per:
4429
+ return _normalize_valign(per[header])
4430
+ if column_i in per:
4431
+ return _normalize_valign(per[column_i])
4432
+ elif is_some_instance(per, list, tuple):
4433
+ if column_i is not None and column_i < len(per):
4434
+ return _normalize_valign(per[column_i])
4435
+ else:
4436
+ return _normalize_valign(per)
4437
+ return _normalize_valign(self.__valign)
4438
+
4439
+ def __valigns_for_wrap(self, headers, rows):
4440
+ """Build header_valigns and per-row body valign lists for ``_wrap_rows``."""
4441
+ from .cells import _normalize_valign
4442
+ default = _normalize_valign(self.__valign)
4443
+ n = len(headers) if headers is not None else 0
4444
+ # Headers follow column valign (no per-cell header map).
4445
+ header_valigns = []
4446
+ for column_i, header in enumerate(headers or []):
4447
+ user_i = None if (self.__show_index and column_i == 0) else (
4448
+ column_i - 1 if self.__show_index else column_i
4449
+ )
4450
+ if self.__show_index and column_i == 0:
4451
+ header_valigns.append(default)
4452
+ continue
4453
+ header_valigns.append(
4454
+ self.__valign_for_cell(-1, header, user_i)
4455
+ if user_i is not None else default
4456
+ )
4457
+ # Force header-only resolution without cell_valign row hits:
4458
+ # __valign_for_cell with row -1 won't match normal cell keys.
4459
+ row_valigns = []
4460
+ for row_i, row in enumerate(rows or []):
4461
+ codes = []
4462
+ for column_i in range(len(row)):
4463
+ if self.__show_index:
4464
+ if column_i == 0:
4465
+ codes.append(default)
4466
+ continue
4467
+ header = headers[column_i] if column_i < n else ''
4468
+ user_i = column_i - 1
4469
+ else:
4470
+ header = headers[column_i] if column_i < n else ''
4471
+ user_i = column_i
4472
+ codes.append(self.__valign_for_cell(row_i, header, user_i))
4473
+ row_valigns.append(codes)
4474
+ # Only pay the cost when something is not top.
4475
+ needs = (
4476
+ default != 't'
4477
+ or self.__col_valign is not None
4478
+ or bool(self.__cell_valign)
4479
+ )
4480
+ if not needs:
4481
+ return None, None
4482
+ return header_valigns, row_valigns
4483
+
4484
+ def __apply_panel_and_shadow(self, table_string):
4485
+ """Wrap the finished table in an optional outer panel and/or shadow."""
4486
+ if not table_string:
4487
+ return table_string
4488
+ out = table_string
4489
+ if self.__panel:
4490
+ out = self.__wrap_panel(out)
4491
+ if self.__shadow:
4492
+ out = self.__apply_shadow(out)
4493
+ return out
4494
+
4495
+ def __panel_glyphs(self):
4496
+ """Box-drawing glyphs for the outer panel frame."""
4497
+ name = 'rounded'
4498
+ if isinstance(self.__panel, str) and self.__panel not in ('True', 'true', '1'):
4499
+ name = self.__panel.lower()
4500
+ presets = {
4501
+ 'rounded': ('╭', '─', '╮', '│', '╰', '╯'),
4502
+ 'sharp': ('┌', '─', '┐', '│', '└', '┘'),
4503
+ 'ascii': ('+', '-', '+', '|', '+', '+'),
4504
+ 'double': ('╔', '═', '╗', '║', '╚', '╝'),
4505
+ 'heavy': ('┏', '━', '┓', '┃', '┗', '┛'),
4506
+ }
4507
+ return presets.get(name, presets['rounded'])
4508
+
4509
+ def __wrap_panel(self, table_string):
4510
+ tl, hz, tr, vt, bl, br = self.__panel_glyphs()
4511
+ lines = table_string.splitlines()
4512
+ width = max((visible_width(line) for line in lines), default=0)
4513
+ padded = []
4514
+ for line in lines:
4515
+ pad = width - visible_width(line)
4516
+ padded.append(line + (' ' * pad))
4517
+ top = tl + (hz * width) + tr
4518
+ bottom = bl + (hz * width) + br
4519
+ body = [vt + line + vt for line in padded]
4520
+ return chr(10).join([top] + body + [bottom])
4521
+
4522
+ def __apply_shadow(self, table_string):
4523
+ glyph = '░'
4524
+ if isinstance(self.__shadow, str) and self.__shadow not in ('True', 'true', '1'):
4525
+ glyph = self.__shadow[:1] or '░'
4526
+ lines = table_string.splitlines()
4527
+ width = max((visible_width(line) for line in lines), default=0)
4528
+ out = []
4529
+ for i, line in enumerate(lines):
4530
+ pad = width - visible_width(line)
4531
+ body = line + (' ' * pad)
4532
+ # First line: no right-edge shadow (Spectre-style); later lines get it,
4533
+ # plus a bottom shadow row.
4534
+ if i == 0:
4535
+ out.append(body + ' ')
4536
+ else:
4537
+ out.append(body + glyph)
4538
+ out.append(' ' + (glyph * width))
4539
+ return chr(10).join(out)
4540
+
4541
+
4301
4542
  def __caption_line(self, column_widths_list, table_with_i):
4302
4543
  """Centre the caption under the full table width, if any."""
4303
4544
  if not self.__caption:
@@ -4838,6 +5079,94 @@ class Table(object):
4838
5079
  # +-----------------------------------------------------------------------------+
4839
5080
  # start +------------------------+ DATA WRITING +------------------------+ start
4840
5081
 
5082
+ def transpose(self, **options):
5083
+ """
5084
+ Return a new table with rows and columns swapped (display rotate).
5085
+
5086
+ The first column of the result is the original header names; remaining
5087
+ columns are ``row0`` … ``rowN`` holding the original cells. Style and
5088
+ most display options are copied when not overridden in ``options``.
5089
+ """
5090
+ headers = list(self.headers)
5091
+ # Pull raw stored rows (not the composed display copy).
5092
+ rows = []
5093
+ n = self.row_count
5094
+ for row_i in range(n):
5095
+ row = []
5096
+ for header in headers:
5097
+ col = self.__columns.get(header, [])
5098
+ row.append(col[row_i] if row_i < len(col) else self.__missing_value)
5099
+ rows.append(row)
5100
+ new_headers = ['field'] + ['row{}'.format(i) for i in range(len(rows))]
5101
+ new_rows = []
5102
+ for col_i, header in enumerate(headers):
5103
+ new_rows.append(
5104
+ [header] + [rows[r][col_i] if col_i < len(rows[r]) else ''
5105
+ for r in range(len(rows))]
5106
+ )
5107
+ style = options.pop('style_name', self.style_name)
5108
+ out = type(self).from_records(
5109
+ new_rows, headers=new_headers, style_name=style, **options
5110
+ )
5111
+ return out
5112
+
5113
+ def rotate(self, **options):
5114
+ """Alias of :meth:`transpose` (tabled naming)."""
5115
+ return self.transpose(**options)
5116
+
5117
+ def paginate(self, page_length=20):
5118
+ """
5119
+ Split the table into composed string pages of ``page_length`` body rows.
5120
+
5121
+ Each page is a full table (headers/title/caption/panel repeated).
5122
+ Returns a list of strings. ``page_length`` must be >= 1.
5123
+ Inspired by PrettyTable ``paginate`` / go-pretty.
5124
+ """
5125
+ page_length = int(page_length)
5126
+ if page_length < 1:
5127
+ raise ValueError('page_length must be >= 1')
5128
+ headers = list(self.headers)
5129
+ n = self.row_count
5130
+ if n == 0:
5131
+ return [self.compose()]
5132
+ pages = []
5133
+ for start in range(0, n, page_length):
5134
+ end = min(start + page_length, n)
5135
+ slice_rows = []
5136
+ for row_i in range(start, end):
5137
+ row = []
5138
+ for header in headers:
5139
+ col = self.__columns.get(header, [])
5140
+ row.append(col[row_i] if row_i < len(col) else self.__missing_value)
5141
+ slice_rows.append(row)
5142
+ page = type(self).from_records(
5143
+ slice_rows, headers=headers, style_name=self.style_name,
5144
+ missing_val=self.__missing_value,
5145
+ )
5146
+ # Copy common display settings so pages look like the parent.
5147
+ for attr in (
5148
+ 'title', 'caption', 'show_headers', 'show_index', 'header_color',
5149
+ 'border_color', 'use_colors', 'zebra', 'footer_rows', 'footer_color',
5150
+ 'cell_padding', 'overflow', 'auto_wrap', 'valign', 'col_valign',
5151
+ 'panel', 'shadow', 'col_alignment', 'header_align', 'max_width',
5152
+ 'column_min_width', 'column_max_width', 'table_align',
5153
+ ):
5154
+ try:
5155
+ setattr(page, attr, getattr(self, attr))
5156
+ except Exception:
5157
+ pass
5158
+ if self.__cell_colors:
5159
+ # Remap absolute row indexes into the page's local indexes.
5160
+ remapped = {}
5161
+ for (r, c), spec in self.__cell_colors.items():
5162
+ if isinstance(r, int) and start <= r < end:
5163
+ remapped[(r - start, c)] = spec
5164
+ if remapped:
5165
+ page.cell_colors = remapped
5166
+ pages.append(page.compose())
5167
+ return pages
5168
+
5169
+
4841
5170
  @classmethod
4842
5171
  def from_markdown(cls, source, parse_numbers=True, **options):
4843
5172
  """
@@ -4875,6 +5204,21 @@ class Table(object):
4875
5204
  from .writers import to_markdown
4876
5205
  return to_markdown(self, include_index, align)
4877
5206
 
5207
+ def to_rst(self, include_index=False):
5208
+ """Render as a reStructuredText grid table."""
5209
+ from .writers import to_rst
5210
+ return to_rst(self, include_index)
5211
+
5212
+ def to_asciidoc(self, include_index=False):
5213
+ """Render as an AsciiDoc table (``|===`` style)."""
5214
+ from .writers import to_asciidoc
5215
+ return to_asciidoc(self, include_index)
5216
+
5217
+ def to_latex(self, include_index=False):
5218
+ """Render as a LaTeX ``tabular`` environment."""
5219
+ from .writers import to_latex
5220
+ return to_latex(self, include_index)
5221
+
4878
5222
  def to_html(self, target=None, title='Table', paginate=25,
4879
5223
  include_index=False, searchable=True, encoding='utf-8'):
4880
5224
  """
@@ -715,3 +715,134 @@ def to_excel(table, path, sheet_name: str = 'Sheet1',
715
715
  top_left.font = _Font(color=fg, bold='bold' in str(spec).lower())
716
716
 
717
717
  workbook.save(path)
718
+
719
+
720
+ def to_rst(table, include_index: bool = False) -> str:
721
+ """
722
+ Write a reStructuredText grid table.
723
+
724
+ Uses ``+---+`` / ``|`` grid syntax so column alignment survives docutils.
725
+ Newlines inside cells become spaces (RST grid cells are single-line).
726
+ """
727
+ from .fast import visible_width, pad_to_width
728
+
729
+ headers, rows = _table_data(table, include_index)
730
+ if not headers:
731
+ return ''
732
+
733
+ def cell(value):
734
+ return _plain(value).replace('\n', ' ')
735
+
736
+ header_texts = [cell(h) for h in headers]
737
+ row_texts = [[cell(v) for v in row] for row in rows]
738
+ widths = [
739
+ max(
740
+ [visible_width(header_texts[i])]
741
+ + [visible_width(row[i]) for row in row_texts if i < len(row)]
742
+ + [1]
743
+ )
744
+ for i in range(len(header_texts))
745
+ ]
746
+
747
+ def rule(char='-'):
748
+ return '+' + '+'.join(char * (w + 2) for w in widths) + '+'
749
+
750
+ def line(cells):
751
+ parts = [
752
+ ' ' + pad_to_width(text, widths[i], 'l') + ' '
753
+ for i, text in enumerate(cells)
754
+ ]
755
+ return '|' + '|'.join(parts) + '|'
756
+
757
+ out = [rule('-'), line(header_texts), rule('=')]
758
+ for row in row_texts:
759
+ out.append(line(row))
760
+ out.append(rule('-'))
761
+ return '\n'.join(out)
762
+
763
+
764
+ def to_asciidoc(table, include_index: bool = False) -> str:
765
+ """
766
+ Write an AsciiDoc table (``|===`` delimited).
767
+
768
+ Column widths are left to the AsciiDoc processor; cells with newlines are
769
+ flattened to spaces so a single logical row stays one source line.
770
+ """
771
+ headers, rows = _table_data(table, include_index)
772
+ if not headers:
773
+ return ''
774
+
775
+ def cell(value):
776
+ return _plain(value).replace('|', '\\|').replace('\n', ' ')
777
+
778
+ lines = ['|===', '| ' + ' | '.join(cell(h) for h in headers)]
779
+ for row in rows:
780
+ lines.append('| ' + ' | '.join(cell(v) for v in row))
781
+ lines.append('|===')
782
+ return '\n'.join(lines)
783
+
784
+
785
+ def to_latex(table, include_index: bool = False) -> str:
786
+ """
787
+ Write a LaTeX ``tabular`` environment.
788
+
789
+ Alignment letters follow the table's column alignments when available
790
+ (``l`` / ``c`` / ``r``); otherwise every column is left-aligned. Special
791
+ TeX characters in cells are escaped.
792
+ """
793
+ headers, rows = _table_data(table, include_index)
794
+ if not headers:
795
+ return ''
796
+
797
+ def escape_tex(value):
798
+ text = _plain(value).replace('\n', ' ')
799
+ out = []
800
+ for ch in text:
801
+ if ch == '\\':
802
+ out.append(r'\textbackslash{}')
803
+ elif ch == '&':
804
+ out.append(r'\&')
805
+ elif ch == '%':
806
+ out.append(r'\%')
807
+ elif ch == '$':
808
+ out.append(r'\$')
809
+ elif ch == '#':
810
+ out.append(r'\#')
811
+ elif ch == '_':
812
+ out.append(r'\_')
813
+ elif ch == '{':
814
+ out.append(r'\{')
815
+ elif ch == '}':
816
+ out.append(r'\}')
817
+ elif ch == '~':
818
+ out.append(r'\textasciitilde{}')
819
+ elif ch == '^':
820
+ out.append(r'\textasciicircum{}')
821
+ else:
822
+ out.append(ch)
823
+ return ''.join(out)
824
+
825
+ aligns = []
826
+ for i, header in enumerate(headers):
827
+ code = 'l'
828
+ try:
829
+ values = [row[i] for row in rows if i < len(row)]
830
+ code = _markdown_alignment(table, header, i, values)
831
+ except Exception:
832
+ code = 'l'
833
+ if code not in ('l', 'c', 'r'):
834
+ code = 'l'
835
+ aligns.append(code)
836
+
837
+ colspec = ''.join(aligns)
838
+ lines = [
839
+ r'\begin{tabular}{' + colspec + '}',
840
+ r'\hline',
841
+ ' & '.join(escape_tex(h) for h in headers) + r' \\',
842
+ r'\hline',
843
+ ]
844
+ for row in rows:
845
+ lines.append(' & '.join(escape_tex(v) for v in row) + r' \\')
846
+ lines.append(r'\hline')
847
+ lines.append(r'\end{tabular}')
848
+ return '\n'.join(lines)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 2.0.13
3
+ Version: 2.0.14
4
4
  Summary: Flexible console and HTML tables for Python
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Download-URL:
@@ -39,5 +39,6 @@ tests/test_text_width.py
39
39
  tests/test_two_pass_measurement.py
40
40
  tests/test_upstream_issues.py
41
41
  tests/test_v213_features.py
42
+ tests/test_v214_features.py
42
43
  tools/benchmark.py
43
44
  tools/generate_width_tables.py
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flexablelib",
3
- "version": "2.0.13",
3
+ "version": "2.0.14",
4
4
  "description": "Flexible console and HTML tables for Python: styles, merges, colors, widths, decimal alignment.",
5
5
  "main": "__init__.py",
6
6
  "scripts": {
@@ -0,0 +1,105 @@
1
+ """Features shipped in 2.0.14 (valign, panel/shadow, writers, transpose, paginate, nested)."""
2
+ import re
3
+ import pytest
4
+ from flexablelib.table import Table
5
+
6
+
7
+ def bare(text: str) -> str:
8
+ return re.sub(r'\x1b\[[0-9;]*m', '', text)
9
+
10
+
11
+ def test_valign_top_middle_bottom():
12
+ t = Table.from_records(
13
+ [['hi', 'a\nb\nc']],
14
+ headers=['L', 'R'],
15
+ style_name='rounded',
16
+ )
17
+ top = bare(t.compose())
18
+ assert re.search(r'│ hi │ a │', top)
19
+ t.col_valign = {'L': 'b'}
20
+ bottom = bare(t.compose())
21
+ assert re.search(r'│ hi │ c │', bottom)
22
+ t.col_valign = {'L': 'm'}
23
+ mid = bare(t.compose())
24
+ assert re.search(r'│ hi │ b │', mid)
25
+
26
+
27
+ def test_valign_rejects_bad_code():
28
+ t = Table.from_records([[1]], headers=['A'])
29
+ with pytest.raises(ValueError):
30
+ t.valign = 'sideways'
31
+
32
+
33
+ def test_panel_and_shadow():
34
+ t = Table.from_records([['a', 1]], headers=['X', 'Y'], style_name='sharp')
35
+ t.panel = True
36
+ out = bare(t.compose())
37
+ assert out.splitlines()[0].startswith('╭')
38
+ assert out.splitlines()[-1].startswith('╰')
39
+ t.shadow = True
40
+ shadowed = bare(t.compose())
41
+ assert '░' in shadowed
42
+
43
+
44
+ def test_panel_ascii_style():
45
+ t = Table.from_records([['a']], headers=['X'], style_name='ascii')
46
+ t.panel = 'ascii'
47
+ out = bare(t.compose())
48
+ assert out.splitlines()[0].startswith('+')
49
+
50
+
51
+ def test_to_rst_asciidoc_latex():
52
+ t = Table.from_records([['a', 1], ['b', 2]], headers=['X', 'Y'])
53
+ rst = t.to_rst()
54
+ assert '+===' in rst or '+=' in rst
55
+ assert '| X |' in rst or '| X ' in rst
56
+ adoc = t.to_asciidoc()
57
+ assert adoc.startswith('|===')
58
+ assert '| X | Y' in adoc
59
+ tex = t.to_latex()
60
+ assert r'\begin{tabular}' in tex
61
+ assert r'\end{tabular}' in tex
62
+ assert 'X & Y' in tex
63
+
64
+
65
+ def test_transpose_and_rotate_alias():
66
+ t = Table.from_records([['a', 1], ['b', 2]], headers=['X', 'Y'], style_name='sharp')
67
+ rotated = t.transpose()
68
+ assert rotated.headers[0] == 'field'
69
+ assert 'row0' in rotated.headers
70
+ assert rotated.columns['field'] == ['X', 'Y']
71
+ assert t.rotate().columns['field'] == ['X', 'Y']
72
+
73
+
74
+ def test_paginate_pages():
75
+ t = Table.from_records(
76
+ [[f'r{i}', i] for i in range(5)],
77
+ headers=['N', 'V'],
78
+ style_name='simple',
79
+ )
80
+ pages = t.paginate(2)
81
+ assert len(pages) == 3
82
+ assert 'r0' in bare(pages[0]) and 'r1' in bare(pages[0])
83
+ assert 'r4' in bare(pages[2])
84
+ with pytest.raises(ValueError):
85
+ t.paginate(0)
86
+
87
+
88
+ def test_nested_subtable_in_cell():
89
+ inner = Table.from_records([[1, 2]], headers=['a', 'b'], style_name='ascii')
90
+ outer = Table.from_records(
91
+ [['cell', inner]], headers=['k', 'v'], style_name='rounded'
92
+ )
93
+ out = bare(outer.compose())
94
+ assert 'cell' in out
95
+ assert '| a | b |' in out or 'a' in out
96
+ assert '1' in out and '2' in out
97
+
98
+
99
+ def test_column_min_max_still_covered():
100
+ """F10: percent constraints deferred; min/max already ship."""
101
+ t = Table.from_records([['hello world', 1]], headers=['A', 'B'])
102
+ t.column_max_width = {'A': 5}
103
+ t.overflow = 'truncate'
104
+ out = bare(t.compose())
105
+ assert 'he' in out and 'world' not in out
File without changes
File without changes
File without changes
File without changes
File without changes