satz 0.1.0__py3-none-any.whl

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.
satz/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """satz - a small LaTeX-like markup language with a Python backend.
2
+
3
+ source text --(parser)--> nodes
4
+ --(pass 1: command functions)--> Document structure
5
+ --(pass 2: renderer)--> PDF
6
+
7
+ For package authors, everything needed is importable from here:
8
+
9
+ from satz import command, restyle, Run, text
10
+ """
11
+
12
+ from .build import Context, build
13
+ from .commands import COMMANDS, command
14
+ from .document import Document, Geometry
15
+ from .errors import CommandError, CompileError, ParseError
16
+ from .inline import InlineStyle, MathRun, Run, plain, restyle, text
17
+ from .parser import parse
18
+ from .render import OPTIONS, STYLES, Style, render
19
+
20
+ __all__ = ["build", "parse", "render", "command", "COMMANDS", "Context",
21
+ "Document", "Geometry", "Style", "STYLES", "OPTIONS",
22
+ "Run", "MathRun", "InlineStyle", "restyle", "text", "plain",
23
+ "CompileError", "ParseError", "CommandError"]
24
+ __version__ = "0.1.0"
satz/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """python -m satz content.tex"""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
satz/build.py ADDED
@@ -0,0 +1,146 @@
1
+ """PASS 1 - walk the parsed nodes and build the document structure.
2
+
3
+ Nothing is drawn here. Consecutive text, math and inline commands are
4
+ collected into paragraphs; block commands end the current paragraph.
5
+ """
6
+
7
+ import os
8
+ from typing import List
9
+
10
+ from . import mathrender
11
+ from .commands import COMMANDS, CommandSpec
12
+ from .document import Document, Equation, Paragraph, parse_length
13
+ from .errors import CommandError
14
+ from .inline import Inline, MathRun, Run, is_blank
15
+ from .parser import Command, Math, ParBreak, Text, parse, unescape
16
+
17
+
18
+ class Context:
19
+ """What a command function receives as its first argument."""
20
+
21
+ def __init__(self, doc: Document, base_dir: str):
22
+ self.doc = doc
23
+ self.base_dir = base_dir
24
+ self.line = 0 # line of the command being executed
25
+ self.arg_line = 0 # line where its first argument starts
26
+
27
+ # -- for command authors ---------------------------------------------
28
+ def add(self, block):
29
+ return self.doc.add(block)
30
+
31
+ def content(self, raw: str, line: int = None) -> List[Inline]:
32
+ """Parse a string as formatted inline content."""
33
+ return to_inlines(parse(raw, line or self.arg_line or self.line), self)
34
+
35
+ def path(self, p: str) -> str:
36
+ return p if os.path.isabs(p) else os.path.join(self.base_dir, p)
37
+
38
+ def length(self, s: str) -> float:
39
+ try:
40
+ return parse_length(s)
41
+ except ValueError:
42
+ self.error(f"not a length: {s!r} (examples: 12pt, 3mm, 0.5cm)")
43
+
44
+ def check_math(self, src: str, line: int = None):
45
+ try:
46
+ mathrender.measure(src, 10)
47
+ except mathrender.MathError as exc:
48
+ raise CommandError(str(exc), line or self.line) from None
49
+
50
+ def error(self, message: str, line: int = None):
51
+ raise CommandError(message, line or self.line)
52
+
53
+
54
+ def _lookup(node: Command) -> CommandSpec:
55
+ spec = COMMANDS.get(node.name)
56
+ if spec is None:
57
+ raise CommandError(f"unknown command \\{node.name} (run 'satz "
58
+ f"--commands' for the list)", node.line)
59
+ n = len(node.args)
60
+ if not spec.min_args <= n <= spec.max_args:
61
+ raise CommandError(f"\\{node.name} takes {spec.min_args}"
62
+ f"{'' if spec.min_args == spec.max_args else f'-{spec.max_args}'}"
63
+ f" argument(s), got {n}. Usage: {spec.signature()}", node.line)
64
+ return spec
65
+
66
+
67
+ def call(ctx: Context, node: Command):
68
+ spec = _lookup(node)
69
+ saved = ctx.line, ctx.arg_line
70
+ ctx.line = node.line
71
+ ctx.arg_line = node.arg_lines[0] if node.arg_lines else node.line
72
+ try:
73
+ args = []
74
+ for raw, kind, line in zip(node.args, spec.argtypes, node.arg_lines):
75
+ if kind == "content":
76
+ args.append(to_inlines(parse(raw, line), ctx))
77
+ elif kind == "text":
78
+ args.append(" ".join(unescape(raw).split()))
79
+ else:
80
+ args.append(raw)
81
+ ctx.line = node.line
82
+ result = spec.fn(ctx, *args)
83
+ finally:
84
+ ctx.line, ctx.arg_line = saved
85
+ if spec.inline:
86
+ if result is None:
87
+ return []
88
+ if isinstance(result, str):
89
+ return [Run(result)]
90
+ if isinstance(result, (Run, MathRun)):
91
+ return [result]
92
+ return list(result)
93
+ return None
94
+
95
+
96
+ def to_inlines(nodes, ctx: Context) -> List[Inline]:
97
+ out: List[Inline] = []
98
+ for node in nodes:
99
+ if isinstance(node, Text):
100
+ out.append(Run(node.text))
101
+ elif isinstance(node, ParBreak):
102
+ out.append(Run(" "))
103
+ elif isinstance(node, Math):
104
+ if node.display:
105
+ raise CommandError("display math $$...$$ cannot be used inside an argument",
106
+ node.line)
107
+ ctx.check_math(node.src, node.line)
108
+ out.append(MathRun(node.src, line=node.line))
109
+ elif isinstance(node, Command):
110
+ if not _lookup(node).inline:
111
+ raise CommandError(f"\\{node.name} is a block command and cannot be "
112
+ f"used inside an argument", node.line)
113
+ out.extend(call(ctx, node))
114
+ return out
115
+
116
+
117
+ def build(source: str, base_dir: str = ".", doc: Document = None) -> Document:
118
+ doc = doc if doc is not None else Document()
119
+ ctx = Context(doc, base_dir)
120
+ para: List[Inline] = []
121
+
122
+ def flush():
123
+ if para and not is_blank(para):
124
+ doc.add(Paragraph(list(para)))
125
+ para.clear()
126
+
127
+ for node in parse(source):
128
+ if isinstance(node, ParBreak):
129
+ flush()
130
+ elif isinstance(node, Text):
131
+ para.append(Run(node.text))
132
+ elif isinstance(node, Math):
133
+ ctx.check_math(node.src, node.line)
134
+ if node.display:
135
+ flush()
136
+ doc.add(Equation(node.src, None))
137
+ else:
138
+ para.append(MathRun(node.src, line=node.line))
139
+ elif isinstance(node, Command):
140
+ if _lookup(node).inline:
141
+ para.extend(call(ctx, node))
142
+ else:
143
+ flush()
144
+ call(ctx, node)
145
+ flush()
146
+ return doc
satz/cli.py ADDED
@@ -0,0 +1,69 @@
1
+ """Command line interface - installed as the `satz` command.
2
+
3
+ satz content.tex
4
+ satz content.tex -o out.pdf
5
+ satz content.tex --dump # show the structure from pass 1
6
+ satz --commands # list all commands
7
+
8
+ Without installing: python -m satz content.tex
9
+ """
10
+
11
+ import argparse
12
+ import os
13
+ import sys
14
+
15
+ from . import COMMANDS, CompileError, __version__, build, render
16
+
17
+
18
+ def list_commands():
19
+ seen = {}
20
+ for name, spec in sorted(COMMANDS.items()):
21
+ seen.setdefault(id(spec), (spec, []))[1].append(name)
22
+ for spec, names in sorted(seen.values(), key=lambda v: v[0].name):
23
+ aliases = [n for n in names if n != spec.name]
24
+ kind = "inline" if spec.inline else "block "
25
+ extra = f" (also: {', '.join(chr(92) + a for a in aliases)})" if aliases else ""
26
+ print(f" {kind} {spec.signature()}{extra}")
27
+
28
+
29
+ def main(argv=None):
30
+ ap = argparse.ArgumentParser(prog="satz", description="compile satz markup to PDF")
31
+ ap.add_argument("--version", action="version", version=f"satz {__version__}")
32
+ ap.add_argument("source", nargs="?", help="input file")
33
+ ap.add_argument("-o", "--output", help="output PDF (default: same name .pdf)")
34
+ ap.add_argument("--dump", action="store_true", help="print the pass-1 structure and exit")
35
+ ap.add_argument("--commands", action="store_true", help="list all commands and exit")
36
+ args = ap.parse_args(argv)
37
+
38
+ if args.commands:
39
+ list_commands()
40
+ return 0
41
+ if not args.source:
42
+ ap.error("no source file given")
43
+
44
+ with open(args.source, encoding="utf-8") as fh:
45
+ source = fh.read()
46
+ base_dir = os.path.dirname(os.path.abspath(args.source))
47
+
48
+ try: # ---- pass 1
49
+ doc = build(source, base_dir=base_dir)
50
+ except CompileError as exc:
51
+ print(f"{args.source}:{exc.line or '?'}: error: {exc.message}", file=sys.stderr)
52
+ if exc.line:
53
+ lines = source.splitlines()
54
+ if 0 < exc.line <= len(lines):
55
+ print(f" {exc.line} | {lines[exc.line - 1]}", file=sys.stderr)
56
+ return 1
57
+
58
+ if args.dump:
59
+ print(doc.dump())
60
+ return 0
61
+
62
+ out = args.output or os.path.splitext(args.source)[0] + ".pdf"
63
+ render(doc, out) # ---- pass 2
64
+ print(f"{args.source} -> {out} ({len(doc.blocks)} blocks)")
65
+ return 0
66
+
67
+
68
+ if __name__ == "__main__":
69
+ raise SystemExit(main())
satz/commands.py ADDED
@@ -0,0 +1,410 @@
1
+ r"""Command registry and the built-in commands.
2
+
3
+ A markup command is a Python function registered under a name. Its
4
+ argument types tell the compiler how to prepare each {argument}:
5
+
6
+ content formatted text -> list of inline runs (may contain \bold, $x$, ...)
7
+ text plain string -> escapes resolved, whitespace collapsed
8
+ raw verbatim string -> untouched (table bodies, math, code)
9
+ ...? trailing '?' marks an optional argument
10
+
11
+ Inline commands (inline=True) return runs that flow inside a paragraph.
12
+ Block commands add blocks to the document with ctx.add(...).
13
+
14
+ @command("bold", "content", inline=True)
15
+ def bold(ctx, body):
16
+ return restyle(body, bold=True)
17
+ """
18
+
19
+ import csv
20
+ import os
21
+ import re
22
+ from dataclasses import dataclass
23
+ from typing import Callable, Dict, List, Tuple
24
+
25
+ from reportlab.lib import colors
26
+
27
+ from .document import (PAPER_SIZES, Equation, Figure, Heading, ListBlock,
28
+ PageBreak, Table, parse_length)
29
+ from .errors import CommandError
30
+ from .inline import Run, restyle
31
+
32
+ ARG_TYPES = ("content", "text", "raw")
33
+
34
+
35
+ @dataclass
36
+ class CommandSpec:
37
+ name: str
38
+ fn: Callable
39
+ argtypes: Tuple[str, ...]
40
+ optional: Tuple[bool, ...]
41
+ inline: bool
42
+
43
+ @property
44
+ def min_args(self):
45
+ return self.optional.count(False)
46
+
47
+ @property
48
+ def max_args(self):
49
+ return len(self.argtypes)
50
+
51
+ def signature(self):
52
+ parts = [f"{{{t}}}" if not o else f"[{{{t}}}]"
53
+ for t, o in zip(self.argtypes, self.optional)]
54
+ return f"\\{self.name}" + "".join(parts)
55
+
56
+
57
+ COMMANDS: Dict[str, CommandSpec] = {}
58
+
59
+
60
+ def command(name: str, *argtypes: str, inline: bool = False, aliases=()):
61
+ """Decorator: bind markup command(s) to a Python function."""
62
+ types, optional = [], []
63
+ for t in argtypes:
64
+ opt = t.endswith("?")
65
+ t = t.rstrip("?")
66
+ if t not in ARG_TYPES:
67
+ raise ValueError(f"{name}: unknown argument type {t!r}, use one of {ARG_TYPES}")
68
+ if optional and optional[-1] and not opt:
69
+ raise ValueError(f"{name}: optional arguments must come last")
70
+ types.append(t)
71
+ optional.append(opt)
72
+
73
+ def decorator(fn):
74
+ spec = CommandSpec(name, fn, tuple(types), tuple(optional), inline)
75
+ for n in (name, *aliases):
76
+ COMMANDS[n] = spec
77
+ return fn
78
+ return decorator
79
+
80
+
81
+ # ==========================================================================
82
+ # inline formatting
83
+ # ==========================================================================
84
+
85
+ @command("bold", "content", inline=True, aliases=("textbf",))
86
+ def cmd_bold(ctx, body):
87
+ return restyle(body, bold=True)
88
+
89
+
90
+ @command("italic", "content", inline=True, aliases=("textit", "emph"))
91
+ def cmd_italic(ctx, body):
92
+ return restyle(body, italic=True)
93
+
94
+
95
+ @command("mono", "content", inline=True, aliases=("texttt", "code"))
96
+ def cmd_mono(ctx, body):
97
+ return restyle(body, family="mono")
98
+
99
+
100
+ @command("sans", "content", inline=True, aliases=("textsf",))
101
+ def cmd_sans(ctx, body):
102
+ return restyle(body, family="sans")
103
+
104
+
105
+ @command("underline", "content", inline=True)
106
+ def cmd_underline(ctx, body):
107
+ return restyle(body, underline=True)
108
+
109
+
110
+ @command("sup", "content", inline=True, aliases=("textsuperscript",))
111
+ def cmd_sup(ctx, body):
112
+ return restyle(body, scale=0.7, rise=0.35)
113
+
114
+
115
+ @command("sub", "content", inline=True, aliases=("textsubscript",))
116
+ def cmd_sub(ctx, body):
117
+ return restyle(body, scale=0.7, rise=-0.15)
118
+
119
+
120
+ @command("small", "content", inline=True)
121
+ def cmd_small(ctx, body):
122
+ return restyle(body, scale=0.85)
123
+
124
+
125
+ @command("large", "content", inline=True)
126
+ def cmd_large(ctx, body):
127
+ return restyle(body, scale=1.2)
128
+
129
+
130
+ @command("size", "text", "content", inline=True)
131
+ def cmd_size(ctx, size, body):
132
+ r"""\size{14pt}{text} - absolute font size."""
133
+ return restyle(body, size=ctx.length(size))
134
+
135
+
136
+ @command("color", "text", "content", inline=True)
137
+ def cmd_color(ctx, name, body):
138
+ r"""\color{red}{text} \color{#1f77b4}{text}"""
139
+ try:
140
+ colors.toColor(name)
141
+ except ValueError:
142
+ ctx.error(f"\\color: unknown colour {name!r} (use a name like 'red' or '#RRGGBB')")
143
+ return restyle(body, color=name)
144
+
145
+
146
+ @command("letterspacing", "text", "content", inline=True, aliases=("tracking",))
147
+ def cmd_letterspacing(ctx, amount, body):
148
+ r"""\letterspacing{1pt}{SPACED} - extra space between letters."""
149
+ return restyle(body, tracking=ctx.length(amount))
150
+
151
+
152
+ @command("font", "text", "content", inline=True)
153
+ def cmd_font(ctx, family, body):
154
+ r"""\font{sans}{text} - any family registered in fonts.py."""
155
+ from . import fonts
156
+ if family not in fonts.families():
157
+ ctx.error(f"\\font: unknown family {family!r} (known: {', '.join(fonts.families())})")
158
+ return restyle(body, family=family)
159
+
160
+
161
+ # ==========================================================================
162
+ # document setup
163
+ # ==========================================================================
164
+
165
+ @command("title", "content")
166
+ def cmd_title(ctx, body):
167
+ ctx.doc.title = body
168
+
169
+
170
+ @command("author", "content")
171
+ def cmd_author(ctx, body):
172
+ ctx.doc.author = body
173
+
174
+
175
+ @command("date", "content")
176
+ def cmd_date(ctx, body):
177
+ ctx.doc.date = body
178
+
179
+
180
+ @command("use", "text")
181
+ def cmd_use(ctx, name):
182
+ r"""\use{si} - load a package (a Python module that registers commands)."""
183
+ from .packages import load
184
+ load(name, ctx)
185
+
186
+
187
+ @command("geometry", "text", "text?")
188
+ def cmd_geometry(ctx, *args):
189
+ r"""\geometry{a4, margin=25mm} \geometry{a4}{25mm}
190
+ \geometry{a5, landscape, left=30mm, right=20mm, top=25mm, bottom=25mm}"""
191
+ g = ctx.doc.geometry
192
+ items = [p.strip() for arg in args for p in arg.split(",") if p.strip()]
193
+ for item in items:
194
+ key, _, value = item.partition("=")
195
+ key, value = key.strip().lower(), value.strip()
196
+ try:
197
+ if not value:
198
+ if key in PAPER_SIZES:
199
+ g.paper = key
200
+ elif key in ("landscape", "portrait"):
201
+ g.landscape = key == "landscape"
202
+ else:
203
+ g.left = g.right = g.top = g.bottom = parse_length(key)
204
+ elif key in ("paper", "papersize", "paperformat"):
205
+ if value.lower() not in PAPER_SIZES:
206
+ ctx.error(f"\\geometry: unknown paper {value!r} "
207
+ f"(known: {', '.join(sorted(PAPER_SIZES))})")
208
+ g.paper = value.lower()
209
+ elif key == "margin":
210
+ g.left = g.right = g.top = g.bottom = parse_length(value)
211
+ elif key in ("left", "right", "top", "bottom"):
212
+ setattr(g, key, parse_length(value))
213
+ elif key == "orientation":
214
+ g.landscape = value.lower() == "landscape"
215
+ else:
216
+ ctx.error(f"\\geometry: unknown option {key!r}")
217
+ except ValueError:
218
+ ctx.error(f"\\geometry: don't understand {item!r}")
219
+
220
+
221
+ # ==========================================================================
222
+ # structure
223
+ # ==========================================================================
224
+
225
+ @command("chapter", "content")
226
+ def cmd_chapter(ctx, title):
227
+ ctx.add(Heading(0, title, ctx.doc.next_number("chapter")))
228
+
229
+
230
+ @command("section", "content")
231
+ def cmd_section(ctx, title):
232
+ ctx.add(Heading(1, title, ctx.doc.next_number("section")))
233
+
234
+
235
+ @command("subsection", "content")
236
+ def cmd_subsection(ctx, title):
237
+ ctx.add(Heading(2, title, ctx.doc.next_number("subsection")))
238
+
239
+
240
+ @command("newpage", aliases=("pagebreak",))
241
+ def cmd_newpage(ctx):
242
+ ctx.add(PageBreak())
243
+
244
+
245
+ # ==========================================================================
246
+ # figures, equations, lists
247
+ # ==========================================================================
248
+
249
+ @command("figure", "text", "content?")
250
+ def cmd_figure(ctx, path, caption=None):
251
+ r"""\figure{plot.png} \figure{plot.png}{Caption text.}"""
252
+ ctx.add(Figure(ctx.path(path), ctx.doc.next_number("figure"), caption))
253
+
254
+
255
+ @command("equation", "raw")
256
+ def cmd_equation(ctx, src):
257
+ r"""\equation{ E = m c^2 } - numbered display equation. $$ ... $$ is unnumbered."""
258
+ src = " ".join(src.split())
259
+ ctx.check_math(src)
260
+ ctx.add(Equation(src, ctx.doc.next_number("equation")))
261
+
262
+
263
+ _ITEM_RE = re.compile(r"^(?:[-*•]|\d+[.)])\s+(.*)$")
264
+
265
+
266
+ def _list_items(ctx, raw):
267
+ items = [] # [text, line]
268
+ for k, ln in enumerate(raw.split("\n")):
269
+ s = ln.strip()
270
+ if not s or s.startswith("%"):
271
+ continue
272
+ m = _ITEM_RE.match(s)
273
+ if m:
274
+ items.append([m.group(1), ctx.arg_line + k])
275
+ elif items:
276
+ items[-1][0] += "\n" + s
277
+ else:
278
+ ctx.error("list items must start with '- ' (or '1. ')", ctx.arg_line + k)
279
+ return [ctx.content(t, line) for t, line in items]
280
+
281
+
282
+ @command("list", "raw", aliases=("itemize",))
283
+ def cmd_list(ctx, body):
284
+ r"""\list{
285
+ - first item
286
+ - second item, \bold{formatted}
287
+ }"""
288
+ ctx.add(ListBlock(_list_items(ctx, body), ordered=False))
289
+
290
+
291
+ @command("numlist", "raw", aliases=("enumerate",))
292
+ def cmd_numlist(ctx, body):
293
+ ctx.add(ListBlock(_list_items(ctx, body), ordered=True))
294
+
295
+
296
+ # ==========================================================================
297
+ # tables
298
+ # ==========================================================================
299
+
300
+ _RULE_CELL = re.compile(r"^\s*:?-{2,}:?\s*$")
301
+
302
+
303
+ def _split_row(line: str) -> List[str]:
304
+ """Split on unescaped '|' that are not inside $math$."""
305
+ cells, cur, in_math, i = [], [], False, 0
306
+ while i < len(line):
307
+ c = line[i]
308
+ if c == "\\" and i + 1 < len(line):
309
+ cur.append(line[i:i + 2])
310
+ i += 2
311
+ continue
312
+ if c == "$":
313
+ in_math = not in_math
314
+ if c == "|" and not in_math:
315
+ cells.append("".join(cur))
316
+ cur = []
317
+ else:
318
+ cur.append(c)
319
+ i += 1
320
+ cells.append("".join(cur))
321
+ s = line.strip()
322
+ if s.startswith("|"):
323
+ cells = cells[1:]
324
+ if s.endswith("|") and not s.endswith("\\|"):
325
+ cells = cells[:-1]
326
+ return cells
327
+
328
+
329
+ def _alignment(rule_cell: str) -> str:
330
+ s = rule_cell.strip()
331
+ if s.startswith(":") and s.endswith(":"):
332
+ return "center"
333
+ return "right" if s.endswith(":") else "left"
334
+
335
+
336
+ def _finish_table(ctx, header, body, align, caption):
337
+ ncols = max([len(r) for r in header + body] + [len(align), 1])
338
+ pad = lambda row: row + [[] for _ in range(ncols - len(row))]
339
+ header = [pad([restyle(cell, bold=True) for cell in row]) for row in header]
340
+ body = [pad(row) for row in body]
341
+ align = list(align) + ["left"] * (ncols - len(align))
342
+ ctx.add(Table(header, body, align, ctx.doc.next_number("table"), caption))
343
+
344
+
345
+ @command("table", "raw", "content?")
346
+ def cmd_table(ctx, body, caption=None):
347
+ r"""Rows are lines, cells are separated by |, a rule line marks the header:
348
+
349
+ \table{
350
+ | Quantity | Symbol | Value |
351
+ |-----------|:------:|------:|
352
+ | Mass | $m$ | 1.2 |
353
+ }{Caption.}
354
+
355
+ :--- left, :---: centred, ---: right aligned.
356
+ """
357
+ header, rows, align = [], [], []
358
+ for k, ln in enumerate(body.split("\n")):
359
+ if not ln.strip() or ln.strip().startswith("%"):
360
+ continue
361
+ cells = _split_row(ln)
362
+ if cells and all(_RULE_CELL.match(c) for c in cells):
363
+ if not header and rows:
364
+ header, rows = rows, []
365
+ align = [_alignment(c) for c in cells]
366
+ continue
367
+ line = ctx.arg_line + k
368
+ rows.append([ctx.content(c.strip(), line) for c in cells])
369
+ if not header and not rows:
370
+ ctx.error("\\table: empty table")
371
+ _finish_table(ctx, header, rows, align, caption)
372
+
373
+
374
+ def _is_number(s: str) -> bool:
375
+ try:
376
+ float(s.strip().replace(",", "."))
377
+ return True
378
+ except ValueError:
379
+ return False
380
+
381
+
382
+ @command("csvtable", "text", "content?")
383
+ def cmd_csvtable(ctx, path, caption=None):
384
+ r"""\csvtable{data.csv}{Caption.} - first row is the header; numeric
385
+ columns are right aligned. Delimiter (, ; tab) is detected."""
386
+ full = ctx.path(path)
387
+ if not os.path.exists(full):
388
+ ctx.error(f"\\csvtable: file not found: {path}")
389
+ with open(full, newline="", encoding="utf-8-sig") as fh:
390
+ sample = fh.read(4096)
391
+ fh.seek(0)
392
+ try:
393
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
394
+ except csv.Error:
395
+ dialect = csv.excel
396
+ rows = [r for r in csv.reader(fh, dialect) if any(c.strip() for c in r)]
397
+ if not rows:
398
+ ctx.error(f"\\csvtable: {path} is empty")
399
+ head, data = rows[0], rows[1:]
400
+ ncols = max(len(r) for r in rows)
401
+ align = []
402
+ for j in range(ncols):
403
+ col = [r[j] for r in data if j < len(r) and r[j].strip()]
404
+ align.append("right" if col and all(_is_number(v) for v in col) else "left")
405
+ header = [[ctx.content(h.strip()) for h in head]] # header may use markup
406
+ def cell(c):
407
+ c = c.strip()
408
+ return [Run("\u2212" + c[1:] if c.startswith("-") and _is_number(c) else c)]
409
+ body = [[cell(c) for c in r] for r in data] # data is plain text
410
+ _finish_table(ctx, header, body, align, caption)