flexablelib 3.3.0__tar.gz → 3.3.1__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 (103) hide show
  1. {flexablelib-3.3.0 → flexablelib-3.3.1}/CHANGELOG.md +31 -0
  2. {flexablelib-3.3.0 → flexablelib-3.3.1}/PKG-INFO +7 -7
  3. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/cells.py +2 -1
  4. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/layout.py +24 -7
  5. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/readers.py +13 -0
  6. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/table.py +57 -13
  7. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/text_width.py +37 -2
  8. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib.egg-info/PKG-INFO +7 -7
  9. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib.egg-info/SOURCES.txt +5 -0
  10. flexablelib-3.3.1/flexablelib.egg-info/requires.txt +26 -0
  11. {flexablelib-3.3.0 → flexablelib-3.3.1}/package.json +1 -1
  12. flexablelib-3.3.1/tests/test_v331_formats.py +141 -0
  13. flexablelib-3.3.1/tests/test_v331_panel_width.py +85 -0
  14. flexablelib-3.3.1/tests/test_v331_readers_bom.py +45 -0
  15. flexablelib-3.3.1/tests/test_v331_readers_edges.py +99 -0
  16. flexablelib-3.3.1/tests/test_v331_tabs.py +154 -0
  17. flexablelib-3.3.0/flexablelib.egg-info/requires.txt +0 -26
  18. {flexablelib-3.3.0 → flexablelib-3.3.1}/.coveragerc +0 -0
  19. {flexablelib-3.3.0 → flexablelib-3.3.1}/LICENSE +0 -0
  20. {flexablelib-3.3.0 → flexablelib-3.3.1}/MANIFEST.in +0 -0
  21. {flexablelib-3.3.0 → flexablelib-3.3.1}/README.md +0 -0
  22. {flexablelib-3.3.0 → flexablelib-3.3.1}/examples/admin.py +0 -0
  23. {flexablelib-3.3.0 → flexablelib-3.3.1}/examples/dashboard.py +0 -0
  24. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/__init__.py +0 -0
  25. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/_frames.py +0 -0
  26. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/_legacy/__init__.py +0 -0
  27. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/_legacy/screen.py +0 -0
  28. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/_legacy/widgets.py +0 -0
  29. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/_speedups.c +0 -0
  30. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/_width_tables.h +0 -0
  31. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/box_topology.py +0 -0
  32. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/colors.py +0 -0
  33. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/columns.py +0 -0
  34. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/fast.py +0 -0
  35. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/merges.py +0 -0
  36. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/options.py +0 -0
  37. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/py.typed +0 -0
  38. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/screen.py +0 -0
  39. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/style_compositions.py +0 -0
  40. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/table_strings.py +0 -0
  41. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/utils.py +0 -0
  42. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/widgets.py +0 -0
  43. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib/writers.py +0 -0
  44. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib.egg-info/dependency_links.txt +0 -0
  45. {flexablelib-3.3.0 → flexablelib-3.3.1}/flexablelib.egg-info/top_level.txt +0 -0
  46. {flexablelib-3.3.0 → flexablelib-3.3.1}/pytest.ini +0 -0
  47. {flexablelib-3.3.0 → flexablelib-3.3.1}/setup.cfg +0 -0
  48. {flexablelib-3.3.0 → flexablelib-3.3.1}/setup.py +0 -0
  49. {flexablelib-3.3.0 → flexablelib-3.3.1}/style_examples.md +0 -0
  50. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/conftest.py +0 -0
  51. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/helpers.py +0 -0
  52. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_align_indicators.py +0 -0
  53. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_box_topology.py +0 -0
  54. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_cells.py +0 -0
  55. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_columns.py +0 -0
  56. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_excel.py +0 -0
  57. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_features.py +0 -0
  58. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_issues.py +0 -0
  59. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_merge_edge_matrix.py +0 -0
  60. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_merge_fill.py +0 -0
  61. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_merges.py +0 -0
  62. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_public_api_edges.py +0 -0
  63. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_readme_examples.py +0 -0
  64. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_stress_matrix.py +0 -0
  65. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_style_line_widths.py +0 -0
  66. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_styles.py +0 -0
  67. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_text_width.py +0 -0
  68. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_two_pass_measurement.py +0 -0
  69. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_upstream_issues.py +0 -0
  70. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v2021_fixes.py +0 -0
  71. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v210_rows_copy.py +0 -0
  72. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v2110_fixes.py +0 -0
  73. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v211_fixes.py +0 -0
  74. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v213_features.py +0 -0
  75. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v214_features.py +0 -0
  76. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v215_features.py +0 -0
  77. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v216_features.py +0 -0
  78. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v217_features.py +0 -0
  79. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v218_features.py +0 -0
  80. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v219_coverage.py +0 -0
  81. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v219_fixes.py +0 -0
  82. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v220_exports.py +0 -0
  83. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v221_fixes.py +0 -0
  84. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v222_fixes.py +0 -0
  85. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v223_fixes.py +0 -0
  86. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v224_fixes.py +0 -0
  87. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v230_none.py +0 -0
  88. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v231_fixes.py +0 -0
  89. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v232_merge_ansi.py +0 -0
  90. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v300_style_names.py +0 -0
  91. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v310_layout.py +0 -0
  92. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v320_tui.py +0 -0
  93. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v330_components.py +0 -0
  94. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v330_frames.py +0 -0
  95. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v330_layout.py +0 -0
  96. {flexablelib-3.3.0 → flexablelib-3.3.1}/tests/test_v330_tui.py +0 -0
  97. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/bench_frames.py +0 -0
  98. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/benchmark.py +0 -0
  99. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/generate_width_tables.py +0 -0
  100. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/readme_gallery.py +0 -0
  101. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/stress_matrix.py +0 -0
  102. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/style_examples.py +0 -0
  103. {flexablelib-3.3.0 → flexablelib-3.3.1}/tools/text_to_png.py +0 -0
@@ -2,6 +2,37 @@
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
+ ## [3.3.1] - 2026-11-12
6
+
7
+ ### Fixed
8
+ - Tabs no longer push tables and cards past their width. A tab measures
9
+ nothing, so a cell holding one was sized and wrapped as narrower than the
10
+ spaces it became: the table came out wider than ``max_width`` (or
11
+ ``render(width)``), and in card mode the raw tab displaced the frame.
12
+ Cells are expanded before they are measured, headers are trimmed on their
13
+ expanded width with ``overflow='truncate'``, and ``wrap_to_width`` expands
14
+ tabs itself, so cards, grids, widgets and components get it too.
15
+ - A newline in a card title, or in a title set into a border
16
+ (``title_position='border'``), split the frame in two; the title now
17
+ goes on one line. Multi-line table titles and captions are aligned line
18
+ by line instead of only the first line.
19
+ - ``max_width`` now counts the ``panel`` (two columns) and ``shadow``
20
+ (one): squeezing, ``expand_to_window`` and ``too_narrow_message`` sized
21
+ the columns for the full width and then drew the panel outside it.
22
+ - ``from_csv`` and ``from_markdown`` drop a leading UTF-8 byte-order mark
23
+ (Excel's "CSV UTF-8"): it was kept as the first character of the first
24
+ header, and a Markdown table gained an extra empty column.
25
+ - A brace format template (``custom_format={'price': '{:,.2f}'}``,
26
+ ``float_format='$ {:,.2f}'``) no longer aborts the whole render on a text
27
+ cell in the column; the cell prints as it is, as it already did with a
28
+ plain spec. A template that needs more than one value raises a
29
+ ``ValueError`` that says so.
30
+
31
+ ### Added
32
+ - ``flexablelib.text_width.expand_tabs(text, tabsize=8)``: tab expansion
33
+ that counts terminal columns (wide characters two, escape sequences
34
+ none).
35
+
5
36
  ## [3.3.0] - 2026-11-12
6
37
 
7
38
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 3.3.0
3
+ Version: 3.3.1
4
4
  Summary: Fast, dependency-free terminal tables for Python: 54 border styles, ANSI colors, cell merges, decimal alignment, width fitting, and CSV/Markdown/HTML/Excel/LaTeX I/O.
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Author: Benjamin Ramirez
@@ -46,18 +46,18 @@ Requires-Dist: openpyxl>=3.0; extra == "excel"
46
46
  Provides-Extra: html
47
47
  Requires-Dist: lxml>=4.0; extra == "html"
48
48
  Provides-Extra: tui
49
- Requires-Dist: flexablelib-tui==3.3.0; extra == "tui"
49
+ Requires-Dist: flexablelib-tui==3.3.1; extra == "tui"
50
50
  Provides-Extra: components
51
- Requires-Dist: flexablelib-components==3.3.0; extra == "components"
51
+ Requires-Dist: flexablelib-components==3.3.1; extra == "components"
52
52
  Provides-Extra: speed
53
- Requires-Dist: flexablelib-speedups==3.3.0; extra == "speed"
53
+ Requires-Dist: flexablelib-speedups==3.3.1; extra == "speed"
54
54
  Provides-Extra: all
55
55
  Requires-Dist: pandas>=1.0; extra == "all"
56
56
  Requires-Dist: openpyxl>=3.0; extra == "all"
57
57
  Requires-Dist: lxml>=4.0; extra == "all"
58
- Requires-Dist: flexablelib-tui==3.3.0; extra == "all"
59
- Requires-Dist: flexablelib-components==3.3.0; extra == "all"
60
- Requires-Dist: flexablelib-speedups==3.3.0; extra == "all"
58
+ Requires-Dist: flexablelib-tui==3.3.1; extra == "all"
59
+ Requires-Dist: flexablelib-components==3.3.1; extra == "all"
60
+ Requires-Dist: flexablelib-speedups==3.3.1; extra == "all"
61
61
  Dynamic: author
62
62
  Dynamic: author-email
63
63
  Dynamic: classifier
@@ -1,6 +1,7 @@
1
1
  """ CELL WRAPPING AND ADJUSTMENT """
2
2
 
3
3
  from .fast import pad_to_width, visible_width
4
+ from .text_width import expand_tabs
4
5
  from .utils import is_some_instance
5
6
  from .options import FLT_FILTER, INT_FILTER
6
7
 
@@ -532,7 +533,7 @@ def __wrap_cell(cell: Any) -> Union[List[str], Any]:
532
533
  if cell != '':
533
534
  # If the cell is not empty,
534
535
  # apply the str method splitlines
535
- return cell.expandtabs(TAB_SIZE).splitlines()
536
+ return expand_tabs(cell, TAB_SIZE).splitlines()
536
537
  else:
537
538
  # Return a list with empty string in case of empty cell.
538
539
  return ['']
@@ -32,6 +32,7 @@ from .style_compositions import (
32
32
  DEPRECATED_STYLE_NAMES,
33
33
  )
34
34
  from .text_width import (
35
+ expand_tabs,
35
36
  pad_to_width,
36
37
  strip_ansi,
37
38
  tokenize,
@@ -80,7 +81,7 @@ def render_width(width=None):
80
81
 
81
82
 
82
83
  def _block_width(text):
83
- return max(_fx.widths_of(text.split('\n')), default=0)
84
+ return max(_fx.widths_of(expand_tabs(text).split('\n')), default=0)
84
85
 
85
86
 
86
87
  # +---------------------------------------------------------------------------+
@@ -178,6 +179,19 @@ def _splice(line, start, end, replacement):
178
179
  return ''.join(before) + replacement + kept + ''.join(after)
179
180
 
180
181
 
182
+ def _one_line(text):
183
+ """
184
+ A label that must fit on one line: tabs expanded, line breaks as spaces.
185
+
186
+ Titles go into a border line, where a newline would break the frame in two
187
+ and a tab (which measures nothing) would push the corner out of place.
188
+ """
189
+ text = expand_tabs(str(text))
190
+ if '\n' in text or '\r' in text:
191
+ text = ' '.join(part for part in re.split(r'\r\n|\r|\n', text))
192
+ return text
193
+
194
+
181
195
  def inset_label(line, label, align='c', glyph=None, label_prefix='',
182
196
  border_prefix=''):
183
197
  """
@@ -191,6 +205,7 @@ def inset_label(line, label, align='c', glyph=None, label_prefix='',
191
205
  ``label_prefix`` colours the label; ``border_prefix`` is the SGR the
192
206
  border was drawn with, reopened after the label.
193
207
  """
208
+ label = _one_line(label)
194
209
  plain = strip_ansi(line)
195
210
  if not plain.strip():
196
211
  return None
@@ -601,7 +616,7 @@ class Card(object):
601
616
  _panel_overhead(self.panel, self.shadow))
602
617
 
603
618
  def _label_width(self):
604
- return max((_fx.visible_width(strip_ansi(l)) for l, _ in self.__fields),
619
+ return max((_block_width(strip_ansi(l)) for l, _ in self.__fields),
605
620
  default=0)
606
621
 
607
622
  def _value_text(self, value):
@@ -617,7 +632,8 @@ class Card(object):
617
632
  inner = 0
618
633
  if self.title:
619
634
  extra = 4 if self._title_in_border() else 0
620
- inner = max(inner, _fx.visible_width(self.title) + extra -
635
+ title = _one_line(self.title) if extra else self.title
636
+ inner = max(inner, _block_width(expand_tabs(title)) + extra -
621
637
  2 * self._padding() * (1 if extra else 0))
622
638
  for text in (self.subtitle, self.footer):
623
639
  if text:
@@ -636,7 +652,7 @@ class Card(object):
636
652
  for _, v in self.__fields)
637
653
  inner = max(inner, label_w + gap + value_w)
638
654
  else:
639
- tile = max(max(_fx.visible_width(l), _block_width(
655
+ tile = max(max(_block_width(l), _block_width(
640
656
  self._value_text(v))) for l, v in self.__fields)
641
657
  inner = max(inner, cols * tile + (cols - 1) * gap)
642
658
  if self.body is not None:
@@ -794,7 +810,7 @@ class Card(object):
794
810
  cols = self.field_columns
795
811
  if cols == 'auto':
796
812
  # As many tiles per row as fit at their natural width.
797
- tile = max(max(_fx.visible_width(l), _block_width(
813
+ tile = max(max(_block_width(l), _block_width(
798
814
  self._value_text(v))) for l, v in fields)
799
815
  cols = max(1, (content_w + gap) // (tile + gap))
800
816
  cols = min(cols, len(fields))
@@ -942,7 +958,7 @@ class Card(object):
942
958
  if top is not None:
943
959
  drawn = paint(top)
944
960
  if title_in_border:
945
- label = self.title
961
+ label = _one_line(self.title)
946
962
  room = inner - 4
947
963
  if _fx.visible_width(label) > room:
948
964
  label = _fx.truncate(label, max(1, room), '…')
@@ -953,7 +969,8 @@ class Card(object):
953
969
  if set_in is None:
954
970
  # Not even a short label fits: draw it as a first line.
955
971
  sections.insert(0, ('head', [self._content(
956
- painter, self.title, self.title_color, content_w,
972
+ painter, _one_line(self.title), self.title_color,
973
+ content_w,
957
974
  pad, fill, _align(self.title_align))]))
958
975
  else:
959
976
  drawn = set_in
@@ -170,6 +170,9 @@ def _csv_reader_kwargs(delimiter=',', dialect=None, quoting=None,
170
170
  return kwargs
171
171
 
172
172
 
173
+ _BOM = '\ufeff'
174
+
175
+
173
176
  def from_csv(table_class, source, parse_numbers: bool = True,
174
177
  has_header: bool = True, delimiter: str = ',',
175
178
  encoding: str = 'utf-8', dialect=None, quoting=None,
@@ -207,6 +210,12 @@ def from_csv(table_class, source, parse_numbers: bool = True,
207
210
  with open(source, 'r', newline='', encoding=encoding) as handle:
208
211
  rows = [row for row in _csv.reader(handle, **reader_kwargs)]
209
212
 
213
+ if rows and rows[0] and rows[0][0].startswith(_BOM):
214
+ # Excel and Notepad save UTF-8 CSV with a byte-order mark, which
215
+ # ``encoding='utf-8'`` keeps as the first character of the first
216
+ # header: ``table.headers[0] == '\ufeffName'`` and lookups by 'Name'
217
+ # failed.
218
+ rows[0][0] = rows[0][0][len(_BOM):]
210
219
  if not rows:
211
220
  return table_class(**options)
212
221
  if has_header:
@@ -596,6 +605,10 @@ def from_markdown(table_class, source, parse_numbers: bool = True, **options):
596
605
  else:
597
606
  text = source.decode('utf-8') if isinstance(source, bytes) else str(source)
598
607
 
608
+ # A byte-order mark is not whitespace to str.strip(), and left in place
609
+ # it hid the header row's leading pipe.
610
+ if text.startswith(_BOM):
611
+ text = text[len(_BOM):]
599
612
  lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
600
613
  rows_raw = []
601
614
  for ln in lines:
@@ -30,7 +30,7 @@ from .columns import (
30
30
  ALIGNMENTS_PER_TYPE as type_alignments
31
31
  )
32
32
  from .fast import truncate_to_width, visible_width, wrap_to_width
33
- from .text_width import strip_ansi
33
+ from .text_width import expand_tabs, strip_ansi
34
34
  from .table_strings import (
35
35
  _get_separators,
36
36
  _get_data_rows,
@@ -59,6 +59,7 @@ from .options import (
59
59
  INVISIBLE_SEPARATOR,
60
60
  )
61
61
  from .cells import (
62
+ TAB_SIZE,
62
63
  _wrap_rows,
63
64
  _zip_wrapped_rows
64
65
  )
@@ -423,10 +424,12 @@ class Table(object):
423
424
  whole multi-line string at once turned ``'a\\nbb'`` into ``'...'``.
424
425
  A cell that already fits is returned unchanged, type included.
425
426
  """
426
- text = str(piece)
427
+ text = expand_tabs(str(piece), TAB_SIZE)
427
428
  lines = text.split('\n')
428
429
  if all(visible_width(line) <= new_width for line in lines):
429
430
  return piece
431
+ # Trim the expanded lines: a tab measures nothing, so trimming the
432
+ # raw text let it through as fitting when it did not.
430
433
  return '\n'.join(cls.__trim_with_sign(line, new_width) for line in lines)
431
434
 
432
435
  @staticmethod
@@ -2101,6 +2104,20 @@ class Table(object):
2101
2104
  console_columns, _ = get_window_size()
2102
2105
  return console_columns
2103
2106
 
2107
+ def __body_width(self) -> int:
2108
+ """
2109
+ Width left for the table itself once the panel and shadow are drawn.
2110
+
2111
+ The panel adds a column each side and the shadow one more on the
2112
+ right, all outside the frame the columns are sized for; leaving them
2113
+ out made a panelled table two columns wider than ``max_width``.
2114
+ """
2115
+ return max(1, self.__available_width() - self.__chrome_width())
2116
+
2117
+ def __chrome_width(self) -> int:
2118
+ """Columns the panel and shadow add around the table."""
2119
+ return (2 if self.__panel else 0) + (1 if self.__shadow else 0)
2120
+
2104
2121
  def __minimum_table_width(self) -> int:
2105
2122
  """
2106
2123
  Narrowest the table could possibly be rendered.
@@ -2998,7 +3015,7 @@ class Table(object):
2998
3015
  # illegible, if the caller asked to be told -- issue #14.
2999
3016
  if self.__too_narrow_message is not None:
3000
3017
  available = self.__available_width()
3001
- needed = self.__minimum_table_width()
3018
+ needed = self.__minimum_table_width() + self.__chrome_width()
3002
3019
  if needed > available:
3003
3020
  return self.__too_narrow_message.format(
3004
3021
  needed=needed, available=available
@@ -3144,7 +3161,7 @@ class Table(object):
3144
3161
  """
3145
3162
  adjust = False
3146
3163
  difference = 0
3147
- available = self.__available_width()
3164
+ available = self.__body_width()
3148
3165
  if available < table_width:
3149
3166
  difference = (table_width - available) + 1
3150
3167
  adjust = True
@@ -3538,7 +3555,19 @@ class Table(object):
3538
3555
  if not isinstance(fmt, str):
3539
3556
  return value
3540
3557
  if '{' in fmt:
3541
- return fmt.format(value)
3558
+ try:
3559
+ return fmt.format(value)
3560
+ except (TypeError, ValueError):
3561
+ # A value the template cannot format (text in a number
3562
+ # column, say) prints as it is, as it does with a plain spec;
3563
+ # it used to abort the whole render.
3564
+ return value
3565
+ except (IndexError, KeyError) as error:
3566
+ raise ValueError(
3567
+ 'format {0!r} needs more than the one value it is given '
3568
+ '(use {{}} or {{0}}, e.g. "{{:,.2f}}"): {1}'.format(
3569
+ fmt, error)
3570
+ ) from None
3542
3571
  if '%' in fmt and fmt != '%':
3543
3572
  try:
3544
3573
  return fmt % value
@@ -3790,7 +3819,7 @@ class Table(object):
3790
3819
 
3791
3820
  def __expand_columns_to_window(self, table_width):
3792
3821
  """Distribute spare horizontal space across user columns."""
3793
- available = self.__available_width()
3822
+ available = self.__body_width()
3794
3823
  spare = available - table_width
3795
3824
  if spare <= 0:
3796
3825
  return False
@@ -4009,9 +4038,15 @@ class Table(object):
4009
4038
  for column_i, header in enumerate(headers):
4010
4039
  if column_i >= len(row):
4011
4040
  continue
4012
- rows[row_i][column_i] = self.__format_display_value(
4041
+ shown = self.__format_display_value(
4013
4042
  row[column_i], header, column_i
4014
4043
  )
4044
+ if isinstance(shown, str) and '\t' in shown:
4045
+ # Expand before anything measures or wraps the cell: a
4046
+ # tab measures nothing, so a column sized around it came
4047
+ # out narrower than the spaces it later turned into.
4048
+ shown = expand_tabs(shown, TAB_SIZE)
4049
+ rows[row_i][column_i] = shown
4015
4050
  # rows_with_i has the index at 0.
4016
4051
  with_i_i = column_i + 1
4017
4052
  if with_i_i < len(rows_with_i[row_i]):
@@ -4609,6 +4644,12 @@ class Table(object):
4609
4644
 
4610
4645
  def __aligned_label(self, text, table_width, spec=None):
4611
4646
  """Place ``text`` left/centre/right over ``table_width`` columns."""
4647
+ text = expand_tabs(str(text), TAB_SIZE)
4648
+ if '\n' in text:
4649
+ # Every line is placed on its own; aligning the block as a whole
4650
+ # left the lines after the first at column 0.
4651
+ return '\n'.join(self.__aligned_label(line, table_width, spec)
4652
+ for line in text.split('\n'))
4612
4653
  if spec and self.__colors_active:
4613
4654
  text = colorize(text, spec)
4614
4655
  width = visible_width(text)
@@ -4766,12 +4807,15 @@ class Table(object):
4766
4807
  if not self.__caption or self.__caption_position == 'border':
4767
4808
  return None
4768
4809
  table_width = drawn_width or self.__get_string_table_width()
4769
- caption = self.__caption
4770
- caption_width = visible_width(caption)
4771
- if caption_width >= table_width:
4772
- return caption
4773
- left = (table_width - caption_width) // 2
4774
- return (' ' * left) + caption
4810
+ lines = []
4811
+ for caption in expand_tabs(self.__caption, TAB_SIZE).split('\n'):
4812
+ caption_width = visible_width(caption)
4813
+ if caption_width >= table_width:
4814
+ lines.append(caption)
4815
+ else:
4816
+ left = (table_width - caption_width) // 2
4817
+ lines.append((' ' * left) + caption)
4818
+ return '\n'.join(lines)
4775
4819
 
4776
4820
  def __apply_table_align(self, table_string):
4777
4821
  """Pad every line so the table sits left, centre or right."""
@@ -175,6 +175,38 @@ def visible_width(text: str) -> int:
175
175
  return sum(width for _, width in measured_clusters(strip_ansi(text)))
176
176
 
177
177
 
178
+ def expand_tabs(text: str, tabsize: int = 8) -> str:
179
+ """
180
+ Replace every tab with the spaces that reach the next tab stop.
181
+
182
+ Unlike `str.expandtabs`, the column is counted in terminal columns: escape
183
+ sequences take none and wide characters take two, so `'漢\tx'` puts `x` at
184
+ column 8 just as a terminal would, and a coloured cell expands the same as
185
+ a plain one. Each line restarts at column 0.
186
+ """
187
+ if '\t' not in text:
188
+ return text
189
+ size = max(int(tabsize), 1)
190
+ out = []
191
+ column = 0
192
+ for kind, token in tokenize(text):
193
+ if kind == 'ansi':
194
+ out.append(token)
195
+ continue
196
+ for cluster, width in measured_clusters(token):
197
+ if cluster == '\t':
198
+ step = size - column % size
199
+ out.append(' ' * step)
200
+ column += step
201
+ elif cluster in ('\n', '\r'):
202
+ out.append(cluster)
203
+ column = 0
204
+ else:
205
+ out.append(cluster)
206
+ column += width
207
+ return ''.join(out)
208
+
209
+
178
210
  def tokenize(text: str) -> Iterator[Tuple[str, str]]:
179
211
  """
180
212
  Split into ('ansi', sequence) and ('text', run) pairs, in order.
@@ -382,7 +414,10 @@ def wrap_to_width(text: str, width: int) -> List[str]:
382
414
  line ends with a sequence still active, that line is closed with a reset and
383
415
  the sequence is reopened on the next, so colour survives the break intact.
384
416
 
385
- Existing newlines are honoured as hard breaks.
417
+ Existing newlines are honoured as hard breaks, and tabs are expanded to
418
+ the next 8-column stop first (see `expand_tabs`): a tab measures nothing,
419
+ so a line holding one used to pass as fitting and then overflow by however
420
+ far the terminal moved the cursor.
386
421
 
387
422
  `width` below 1 is treated as 1. A zero or negative width would otherwise
388
423
  loop forever on wide characters, which is tabulate #399.
@@ -393,7 +428,7 @@ def wrap_to_width(text: str, width: int) -> List[str]:
393
428
  return ['']
394
429
 
395
430
  lines = []
396
- for hard_line in text.split('\n'):
431
+ for hard_line in expand_tabs(text).split('\n'):
397
432
  lines.extend(_wrap_single_line(hard_line, width))
398
433
  return lines
399
434
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 3.3.0
3
+ Version: 3.3.1
4
4
  Summary: Fast, dependency-free terminal tables for Python: 54 border styles, ANSI colors, cell merges, decimal alignment, width fitting, and CSV/Markdown/HTML/Excel/LaTeX I/O.
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Author: Benjamin Ramirez
@@ -46,18 +46,18 @@ Requires-Dist: openpyxl>=3.0; extra == "excel"
46
46
  Provides-Extra: html
47
47
  Requires-Dist: lxml>=4.0; extra == "html"
48
48
  Provides-Extra: tui
49
- Requires-Dist: flexablelib-tui==3.3.0; extra == "tui"
49
+ Requires-Dist: flexablelib-tui==3.3.1; extra == "tui"
50
50
  Provides-Extra: components
51
- Requires-Dist: flexablelib-components==3.3.0; extra == "components"
51
+ Requires-Dist: flexablelib-components==3.3.1; extra == "components"
52
52
  Provides-Extra: speed
53
- Requires-Dist: flexablelib-speedups==3.3.0; extra == "speed"
53
+ Requires-Dist: flexablelib-speedups==3.3.1; extra == "speed"
54
54
  Provides-Extra: all
55
55
  Requires-Dist: pandas>=1.0; extra == "all"
56
56
  Requires-Dist: openpyxl>=3.0; extra == "all"
57
57
  Requires-Dist: lxml>=4.0; extra == "all"
58
- Requires-Dist: flexablelib-tui==3.3.0; extra == "all"
59
- Requires-Dist: flexablelib-components==3.3.0; extra == "all"
60
- Requires-Dist: flexablelib-speedups==3.3.0; extra == "all"
58
+ Requires-Dist: flexablelib-tui==3.3.1; extra == "all"
59
+ Requires-Dist: flexablelib-components==3.3.1; extra == "all"
60
+ Requires-Dist: flexablelib-speedups==3.3.1; extra == "all"
61
61
  Dynamic: author
62
62
  Dynamic: author-email
63
63
  Dynamic: classifier
@@ -87,6 +87,11 @@ tests/test_v330_components.py
87
87
  tests/test_v330_frames.py
88
88
  tests/test_v330_layout.py
89
89
  tests/test_v330_tui.py
90
+ tests/test_v331_formats.py
91
+ tests/test_v331_panel_width.py
92
+ tests/test_v331_readers_bom.py
93
+ tests/test_v331_readers_edges.py
94
+ tests/test_v331_tabs.py
90
95
  tools/bench_frames.py
91
96
  tools/benchmark.py
92
97
  tools/generate_width_tables.py
@@ -0,0 +1,26 @@
1
+
2
+ [all]
3
+ pandas>=1.0
4
+ openpyxl>=3.0
5
+ lxml>=4.0
6
+ flexablelib-tui==3.3.1
7
+ flexablelib-components==3.3.1
8
+ flexablelib-speedups==3.3.1
9
+
10
+ [components]
11
+ flexablelib-components==3.3.1
12
+
13
+ [excel]
14
+ openpyxl>=3.0
15
+
16
+ [html]
17
+ lxml>=4.0
18
+
19
+ [pandas]
20
+ pandas>=1.0
21
+
22
+ [speed]
23
+ flexablelib-speedups==3.3.1
24
+
25
+ [tui]
26
+ flexablelib-tui==3.3.1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flexablelib",
3
- "version": "3.3.0",
3
+ "version": "3.3.1",
4
4
  "private": true,
5
5
  "description": "Flexible console and HTML tables for Python: styles, merges, colors, widths, decimal alignment.",
6
6
  "repository": {
@@ -0,0 +1,141 @@
1
+ """
2
+ Format templates on cells they cannot format, and the Excel number formats
3
+ the terminal formats translate to.
4
+ """
5
+
6
+ import io
7
+
8
+ import pytest
9
+
10
+ from flexablelib import Table
11
+
12
+
13
+ def _plain(table):
14
+ table.use_colors = False
15
+ return table.compose()
16
+
17
+
18
+ # -- brace templates -----------------------------------------------------------
19
+
20
+ def test_brace_template_leaves_text_cells_alone():
21
+ # A plain spec already did; the template aborted the whole render.
22
+ for spec in ('{:,.2f}', ',.2f', '%.2f'):
23
+ table = Table(rows=[[1234.5], ['n/a'], [None]], headers=['p'])
24
+ table.custom_format = {'p': spec}
25
+ out = _plain(table)
26
+ assert '1,234.50' in out or '1234.50' in out
27
+ assert 'n/a' in out
28
+
29
+
30
+ def test_brace_template_through_float_format_and_exports():
31
+ table = Table(rows=[[1.5, 'x'], ['-', 'y']], headers=['n', 's'])
32
+ table.float_format = '$ {:,.2f}'
33
+ assert '$ 1.50' in _plain(table)
34
+ assert table.to_records(formatted=True)[1]['n'] == '-'
35
+ assert '$ 1.50' in table.to_csv()
36
+
37
+
38
+ @pytest.mark.parametrize('spec', ['{:.2f} {:.1f}', '{name}', '{1}'])
39
+ def test_brace_template_wanting_more_values_says_so(spec):
40
+ table = Table(rows=[[1.5]], headers=['n'])
41
+ table.float_format = spec
42
+ with pytest.raises(ValueError, match='one value'):
43
+ table.compose()
44
+
45
+
46
+ def test_escaped_braces_are_literal():
47
+ table = Table(rows=[[2.0]], headers=['n'])
48
+ table.float_format = '{} {{unit}}'
49
+ assert '2.0 {unit}' in _plain(table)
50
+
51
+
52
+ # -- Excel number formats ---------------------------------------------------
53
+
54
+ openpyxl = pytest.importorskip('openpyxl')
55
+
56
+
57
+ def _excel_formats(tmp_path, **settings):
58
+ table = Table(rows=[[1234, 1234.5, 'x']], headers=['i', 'f', 's'])
59
+ for name, value in settings.items():
60
+ setattr(table, name, value)
61
+ path = str(tmp_path / 'out.xlsx')
62
+ table.to_excel(path)
63
+ sheet = openpyxl.load_workbook(path).active
64
+ return sheet['A2'].number_format, sheet['B2'].number_format
65
+
66
+
67
+ @pytest.mark.parametrize('settings, expected', [
68
+ (dict(int_format=',', float_format='.3e'), ('#,##0', '0.000E+00')),
69
+ (dict(int_format='n', float_format=','), ('0', '#,##0.##########')),
70
+ (dict(int_format='E'), ('0.000000E+00', 'General')),
71
+ (dict(float_format='.0%'), ('General', '0%')),
72
+ (dict(int_format='{0:,d}', float_format='$ {:,.0f} MXN'),
73
+ ('#,##0', '"$ "#,##0" MXN"')),
74
+ (dict(custom_format={'i': ',d', 1: '.1f'}), ('#,##0', '0.0')),
75
+ (dict(leading_zeros=5), ('00000', 'General')),
76
+ ])
77
+ def test_excel_formats_match_the_terminal(tmp_path, settings, expected):
78
+ assert _excel_formats(tmp_path, **settings) == expected
79
+
80
+
81
+ @pytest.mark.parametrize('settings', [
82
+ dict(float_format='.2n'), # precision with 'n': no equivalent
83
+ dict(int_format='{:x}'), # hex has no number format
84
+ dict(float_format='d'), # 'd' does not apply to a float
85
+ dict(int_format='05d'), # zero padding through a width
86
+ dict(float_format=lambda v: str(v)), # callables stay General
87
+ dict(float_format='{} and {{x}}'), # not a single-field template
88
+ dict(float_format='n'), # plain 'n' on a float
89
+ ])
90
+ def test_excel_falls_back_to_general(tmp_path, settings):
91
+ formats = _excel_formats(tmp_path, **settings)
92
+ assert 'General' in formats
93
+ key = 'int_format' if 'int_format' in settings else 'float_format'
94
+ assert formats[0 if key == 'int_format' else 1] == 'General'
95
+
96
+
97
+ # -- HTML ----------------------------------------------------------------------
98
+
99
+ def _merged_html(**colors):
100
+ table = Table(rows=[['a', 'b'], ['c', 'd']], headers=['x', 'y'])
101
+ table.merge_cells(0, 0, 1, 0)
102
+ for name, value in colors.items():
103
+ setattr(table, name, value)
104
+ return table.to_html()
105
+
106
+
107
+ def test_html_merge_inherits_row_colour():
108
+ html = _merged_html(row_colors={0: 'red'})
109
+ cell = html[html.index('rowspan="2"'):].split('>')[0]
110
+ assert 'color:' in cell
111
+
112
+
113
+ def test_html_merge_inherits_column_colour():
114
+ plain = _merged_html()
115
+ coloured = _merged_html(column_colors={'x': 'blue'})
116
+ cell = coloured[coloured.index('rowspan="2"'):].split('>')[0]
117
+ assert 'color:' in cell
118
+ assert cell != plain[plain.index('rowspan="2"'):].split('>')[0]
119
+
120
+
121
+ def test_html_writes_to_a_handle_and_a_path(tmp_path):
122
+ table = Table(rows=[['a']], headers=['h'])
123
+ handle = io.StringIO()
124
+ assert table.to_html(handle) is None
125
+ assert handle.getvalue() == table.to_html()
126
+ path = tmp_path / 'out.html'
127
+ assert table.to_html(str(path)) is None
128
+ assert path.read_text(encoding='utf-8') == table.to_html()
129
+
130
+
131
+ def test_merged_html_writes_to_a_handle_and_a_path(tmp_path):
132
+ table = Table(rows=[['a', 'b'], ['c', 'd']], headers=['x', 'y'])
133
+ table.merge_cells(0, 0, 1, 0)
134
+ expected = table.to_html()
135
+ assert 'rowspan="2"' in expected
136
+ handle = io.StringIO()
137
+ assert table.to_html(handle) is None
138
+ assert handle.getvalue() == expected
139
+ path = tmp_path / 'merged.html'
140
+ assert table.to_html(str(path)) is None
141
+ assert path.read_text(encoding='utf-8') == expected