marklas 0.7.2__tar.gz → 0.8.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: marklas
3
- Version: 0.7.2
3
+ Version: 0.8.0
4
4
  Summary: Bidirectional converter between GitHub Flavored Markdown and Atlassian Document Format
5
5
  Keywords: markdown,adf,atlassian,jira,confluence,converter,atlassian-document-format
6
6
  Author: byExist
@@ -153,15 +153,15 @@ Markdown is significantly more compact than ADF JSON — critical for LLM-based
153
153
 
154
154
  | | ADF JSON | Markdown | Markdown (plain) |
155
155
  | --- | --- | --- | --- |
156
- | Tokens | 243,217 | 76,332 | 47,794 |
157
- | **Reduction** | — | **3.2x** | **5.1x** |
156
+ | Tokens | 2,173,468 | 858,970 | 560,765 |
157
+ | **Reduction** | — | **2.5x** | **3.9x** |
158
158
 
159
- *Measured on 7 real Confluence pages (pretty-printed JSON) using GPT-4o tokenizer (tiktoken).*
159
+ *Measured on 204 real Confluence pages (compact JSON) using GPT-4o tokenizer (tiktoken).*
160
160
 
161
161
  ## Documentation
162
162
 
163
- - [Mapping Reference](docs/mapping.md) — how each ADF node maps to Markdown
164
- - [LLM Editing Guide](docs/llm-guide.md) — guide for LLMs editing marklas output
163
+ - [Format Reference](docs/format.md) — how each ADF node maps to Markdown
164
+ - [Editing Skill](docs/editing.md) — rules for LLM agents editing marklas output
165
165
 
166
166
  ## Development
167
167
 
@@ -126,15 +126,15 @@ Markdown is significantly more compact than ADF JSON — critical for LLM-based
126
126
 
127
127
  | | ADF JSON | Markdown | Markdown (plain) |
128
128
  | --- | --- | --- | --- |
129
- | Tokens | 243,217 | 76,332 | 47,794 |
130
- | **Reduction** | — | **3.2x** | **5.1x** |
129
+ | Tokens | 2,173,468 | 858,970 | 560,765 |
130
+ | **Reduction** | — | **2.5x** | **3.9x** |
131
131
 
132
- *Measured on 7 real Confluence pages (pretty-printed JSON) using GPT-4o tokenizer (tiktoken).*
132
+ *Measured on 204 real Confluence pages (compact JSON) using GPT-4o tokenizer (tiktoken).*
133
133
 
134
134
  ## Documentation
135
135
 
136
- - [Mapping Reference](docs/mapping.md) — how each ADF node maps to Markdown
137
- - [LLM Editing Guide](docs/llm-guide.md) — guide for LLMs editing marklas output
136
+ - [Format Reference](docs/format.md) — how each ADF node maps to Markdown
137
+ - [Editing Skill](docs/editing.md) — rules for LLM agents editing marklas output
138
138
 
139
139
  ## Development
140
140
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "marklas"
3
- version = "0.7.2"
3
+ version = "0.8.0"
4
4
  description = "Bidirectional converter between GitHub Flavored Markdown and Atlassian Document Format"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -53,4 +53,5 @@ build-backend = "uv_build"
53
53
  [dependency-groups]
54
54
  dev = [
55
55
  "pre-commit>=4.5.1",
56
+ "tiktoken>=0.13.0",
56
57
  ]
@@ -214,13 +214,79 @@ def _parse_list_item(node: dict[str, Any]) -> ast.ListItem:
214
214
 
215
215
  def _parse_table(node: dict[str, Any]) -> ast.Table:
216
216
  attrs = _get_attrs(node)
217
- return ast.Table(
218
- content=[_parse_table_row(r) for r in node.get("content", [])],
217
+ raw_rows = cast(list[dict[str, Any]], node.get("content", []))
218
+ table = ast.Table(
219
+ content=[_parse_table_row(r) for r in raw_rows],
219
220
  display_mode=attrs.get("displayMode"),
220
221
  is_number_column_enabled=attrs.get("isNumberColumnEnabled"),
221
222
  layout=attrs.get("layout"),
222
223
  width=attrs.get("width"),
223
224
  )
225
+ # Order matters: consolidate first (raw cells still align 1:1 with ast
226
+ # cells), then equalize (which mutates ast cell colspans).
227
+ table.colwidths = _consolidate_colwidths(table, raw_rows)
228
+ _equalize_row_widths(table)
229
+ return table
230
+
231
+
232
+ def _consolidate_colwidths(
233
+ table: ast.Table, raw_rows: list[dict[str, Any]]
234
+ ) -> list[float] | None:
235
+ """Collapse per-cell `attrs.colwidth` into one width per grid column.
236
+
237
+ ADF stores colwidth on each cell, but it's semantically a column
238
+ property (every cell sharing a column has the same width in any
239
+ sane table). Walk the grid via ``Table.iter_cells`` and read each
240
+ cell's raw colwidth from the parallel raw_rows array; record the
241
+ first non-zero width seen per column.
242
+ """
243
+ col_to_width: dict[int, float] = {}
244
+ for r, c, ci, cell in table.iter_cells():
245
+ raw_cells = cast(list[dict[str, Any]], raw_rows[r].get("content", []))
246
+ raw_attrs = cast(dict[str, Any], raw_cells[ci].get("attrs") or {})
247
+ raw_cw = raw_attrs.get("colwidth")
248
+ if not isinstance(raw_cw, list):
249
+ continue
250
+ cs = cell.colspan or 1
251
+ for i, w in enumerate(cast(list[Any], raw_cw[:cs])):
252
+ col = c + i
253
+ if col not in col_to_width and isinstance(w, (int, float)) and w > 0:
254
+ col_to_width[col] = float(w)
255
+ if not col_to_width:
256
+ return None
257
+ max_col = max(col_to_width) + 1
258
+ return [col_to_width.get(i, 0.0) for i in range(max_col)]
259
+
260
+
261
+ def _equalize_row_widths(table: ast.Table) -> None:
262
+ """Make every row span the same number of columns.
263
+
264
+ ADF allows rows with different total cell widths — Confluence simply
265
+ extends the last visible cell's colspan to fill the gap at render
266
+ time. Without this normalization, our md → ADF round-trip would
267
+ instead insert explicit empty cells, changing the row's cell count.
268
+ Make the implicit colspan explicit at parse time so the cell count
269
+ survives the round-trip.
270
+
271
+ This is the *sparse → semi-dense* half of the round-trip pair; the
272
+ inverse step (dense → sparse) lives in
273
+ ``marklas.md.parser.block._sparsify_rows`` and drops the padding
274
+ cells GFM rendering inserts at rowspan-occupied slots.
275
+ """
276
+ rows = table.content
277
+ if not rows:
278
+ return
279
+ row_widths = [0] * len(rows)
280
+ for r, c, _ci, cell in table.iter_cells():
281
+ end = c + (cell.colspan or 1)
282
+ if end > row_widths[r]:
283
+ row_widths[r] = end
284
+ target = max(row_widths, default=0)
285
+ for r, row in enumerate(rows):
286
+ if row_widths[r] < target and row.content:
287
+ deficit = target - row_widths[r]
288
+ last = row.content[-1]
289
+ last.colspan = (last.colspan or 1) + deficit
224
290
 
225
291
 
226
292
  def _parse_table_row(node: dict[str, Any]) -> ast.TableRow:
@@ -236,7 +302,6 @@ def _parse_table_cell(node: dict[str, Any]) -> ast.TableCell | ast.TableHeader:
236
302
  ),
237
303
  colspan=attrs.get("colspan"),
238
304
  rowspan=attrs.get("rowspan"),
239
- colwidth=attrs.get("colwidth"),
240
305
  background=attrs.get("background"),
241
306
  )
242
307
 
@@ -494,7 +559,31 @@ def _resolve_emoji_text(text: str | None, emoji_id: str | None) -> str | None:
494
559
 
495
560
 
496
561
  def _parse_inlines(nodes: list[dict[str, Any]]) -> list[ast.Inline]:
497
- return [n for node in nodes if (n := _parse_inline(node)) is not None]
562
+ """Parse inline nodes, splitting text on ``\\n`` into text + HardBreak.
563
+
564
+ ADF's schema defines ``hardBreak.attrs.text`` as the literal ``"\\n"``,
565
+ so a ``\\n`` character inside a text node is canonically a hard line
566
+ break. Split here so downstream code sees one canonical shape: text
567
+ nodes never contain ``\\n``, and visual line breaks are always
568
+ ``ast.HardBreak`` nodes.
569
+ """
570
+ result: list[ast.Inline] = []
571
+ for node in nodes:
572
+ if node.get("type") == "text":
573
+ text = node.get("text", "")
574
+ if "\n" in text:
575
+ marks = _parse_marks(node.get("marks", []))
576
+ segments = text.split("\n")
577
+ for i, seg in enumerate(segments):
578
+ if i > 0:
579
+ result.append(ast.HardBreak())
580
+ if seg:
581
+ result.append(ast.Text(text=seg, marks=list(marks)))
582
+ continue
583
+ n = _parse_inline(node)
584
+ if n is not None:
585
+ result.append(n)
586
+ return result
498
587
 
499
588
 
500
589
  def _parse_inline(node: dict[str, Any]) -> ast.Inline | None:
@@ -17,7 +17,7 @@ def render(doc: ast.Doc) -> dict[str, Any]:
17
17
  return {
18
18
  "type": "doc",
19
19
  "version": doc.version,
20
- "content": _render_children(doc.content, _render_block),
20
+ "content": _render_children(doc.content, render_block),
21
21
  }
22
22
 
23
23
 
@@ -120,7 +120,7 @@ def _render_marks(marks: Sequence[ast.Mark]) -> list[dict[str, Any]]:
120
120
  # ── Block dispatch ───────────────────────────────────────────────────────────
121
121
 
122
122
 
123
- def _render_block(node: ast.Node) -> dict[str, Any] | None:
123
+ def render_block(node: ast.Node) -> dict[str, Any] | None:
124
124
  """Dispatch a block node. Accepts Node because it serves multiple content contexts."""
125
125
  match node:
126
126
  case ast.Paragraph():
@@ -130,7 +130,7 @@ def _render_block(node: ast.Node) -> dict[str, Any] | None:
130
130
  case ast.CodeBlock():
131
131
  return _render_code_block(node)
132
132
  case ast.Blockquote():
133
- return _render_blockquote(node)
133
+ return render_blockquote(node)
134
134
  case ast.BulletList():
135
135
  return _render_bullet_list(node)
136
136
  case ast.OrderedList():
@@ -150,7 +150,7 @@ def _render_block(node: ast.Node) -> dict[str, Any] | None:
150
150
  case ast.MediaGroup():
151
151
  return _render_media_group(node)
152
152
  case ast.BlockCard():
153
- return _render_block_card(node)
153
+ return render_block_card(node)
154
154
  case ast.EmbedCard():
155
155
  return _render_embed_card(node)
156
156
  case ast.TaskList():
@@ -206,10 +206,10 @@ def _render_code_block(node: ast.CodeBlock) -> dict[str, Any]:
206
206
  return _with_marks(result, node.marks)
207
207
 
208
208
 
209
- def _render_blockquote(node: ast.Blockquote) -> dict[str, Any]:
209
+ def render_blockquote(node: ast.Blockquote) -> dict[str, Any]:
210
210
  return {
211
211
  "type": "blockquote",
212
- "content": _render_children(node.content, _render_block),
212
+ "content": _render_children(node.content, render_block),
213
213
  }
214
214
 
215
215
 
@@ -225,7 +225,7 @@ def _render_ordered_list(node: ast.OrderedList) -> dict[str, Any]:
225
225
  "type": "orderedList",
226
226
  "content": [_render_list_item(i) for i in node.content],
227
227
  }
228
- if node.order is not None and node.order != 1:
228
+ if node.order is not None:
229
229
  result["attrs"] = {"order": node.order}
230
230
  return result
231
231
 
@@ -237,7 +237,7 @@ def _render_rule() -> dict[str, Any]:
237
237
  def _render_list_item(node: ast.ListItem) -> dict[str, Any]:
238
238
  return {
239
239
  "type": "listItem",
240
- "content": _render_children(node.content, _render_block),
240
+ "content": _render_children(node.content, render_block),
241
241
  }
242
242
 
243
243
 
@@ -245,9 +245,10 @@ def _render_list_item(node: ast.ListItem) -> dict[str, Any]:
245
245
 
246
246
 
247
247
  def _render_table(node: ast.Table) -> dict[str, Any]:
248
+ rendered_rows = [_render_table_row(r) for r in node.content]
248
249
  result: dict[str, Any] = {
249
250
  "type": "table",
250
- "content": [_render_table_row(r) for r in node.content],
251
+ "content": rendered_rows,
251
252
  }
252
253
  attrs = _omit_none(
253
254
  {
@@ -259,9 +260,36 @@ def _render_table(node: ast.Table) -> dict[str, Any]:
259
260
  )
260
261
  if attrs:
261
262
  result["attrs"] = attrs
263
+ # Distribute the AST's column-major widths back onto each cell where
264
+ # the ADF spec stores it. Using the grid walker keeps cell-vs-column
265
+ # alignment correct under colspan/rowspan.
266
+ if node.colwidths:
267
+ _distribute_colwidths(node, rendered_rows)
262
268
  return result
263
269
 
264
270
 
271
+ def _distribute_colwidths(
272
+ table: ast.Table, rendered_rows: list[dict[str, Any]]
273
+ ) -> None:
274
+ """Spread `table.colwidths` (column-major) back onto each rendered cell.
275
+
276
+ The ast carries a single width-per-column array; the ADF spec wants it
277
+ stored per cell. Use the grid walker to map each cell to its column
278
+ range and attach the slice to the parallel rendered dict.
279
+ """
280
+ widths = table.colwidths or []
281
+ if not widths:
282
+ return
283
+ for r, c, ci, cell in table.iter_cells():
284
+ cs = cell.colspan or 1
285
+ slice_ = widths[c : c + cs]
286
+ if not slice_ or not any(w > 0 for w in slice_):
287
+ continue
288
+ rendered_cell = rendered_rows[r]["content"][ci]
289
+ attrs = rendered_cell.setdefault("attrs", {})
290
+ attrs["colwidth"] = slice_
291
+
292
+
265
293
  def _render_table_row(node: ast.TableRow) -> dict[str, Any]:
266
294
  return {
267
295
  "type": "tableRow",
@@ -273,13 +301,12 @@ def _render_table_cell(node: ast.TableCell | ast.TableHeader) -> dict[str, Any]:
273
301
  cell_type = "tableHeader" if isinstance(node, ast.TableHeader) else "tableCell"
274
302
  result: dict[str, Any] = {
275
303
  "type": cell_type,
276
- "content": _render_children(node.content, _render_block),
304
+ "content": _render_children(node.content, render_block),
277
305
  }
278
306
  attrs = _omit_none(
279
307
  {
280
308
  "colspan": node.colspan,
281
309
  "rowspan": node.rowspan,
282
- "colwidth": node.colwidth,
283
310
  "background": node.background,
284
311
  }
285
312
  )
@@ -304,14 +331,14 @@ def _render_panel(node: ast.Panel) -> dict[str, Any]:
304
331
  return {
305
332
  "type": "panel",
306
333
  "attrs": attrs,
307
- "content": _render_children(node.content, _render_block),
334
+ "content": _render_children(node.content, render_block),
308
335
  }
309
336
 
310
337
 
311
338
  def _render_expand(node: ast.Expand) -> dict[str, Any]:
312
339
  result: dict[str, Any] = {
313
340
  "type": "expand",
314
- "content": _render_children(node.content, _render_block),
341
+ "content": _render_children(node.content, render_block),
315
342
  }
316
343
  if node.title:
317
344
  result["attrs"] = {"title": node.title}
@@ -322,7 +349,7 @@ def _render_nested_expand(node: ast.NestedExpand) -> dict[str, Any]:
322
349
  result: dict[str, Any] = {
323
350
  "type": "nestedExpand",
324
351
  "attrs": {},
325
- "content": _render_children(node.content, _render_block),
352
+ "content": _render_children(node.content, render_block),
326
353
  }
327
354
  if node.title:
328
355
  result["attrs"]["title"] = node.title
@@ -373,7 +400,7 @@ def _render_media_group(node: ast.MediaGroup) -> dict[str, Any]:
373
400
  return {"type": "mediaGroup", "content": [_render_media(m) for m in node.content]}
374
401
 
375
402
 
376
- def _render_block_card(node: ast.BlockCard) -> dict[str, Any]:
403
+ def render_block_card(node: ast.BlockCard) -> dict[str, Any]:
377
404
  attrs = _omit_none(
378
405
  {
379
406
  "url": node.url,
@@ -421,7 +448,7 @@ def _render_task_item(node: ast.TaskItem | ast.BlockTaskItem) -> dict[str, Any]:
421
448
  if isinstance(node, ast.TaskItem):
422
449
  content = _render_inlines(node.content)
423
450
  else:
424
- content = _render_children(node.content, _render_block)
451
+ content = _render_children(node.content, render_block)
425
452
  if content:
426
453
  result["content"] = content
427
454
  return result
@@ -458,7 +485,7 @@ def _render_layout_column(node: ast.LayoutColumn) -> dict[str, Any]:
458
485
  return {
459
486
  "type": "layoutColumn",
460
487
  "attrs": {"width": node.width},
461
- "content": _render_children(node.content, _render_block),
488
+ "content": _render_children(node.content, render_block),
462
489
  }
463
490
 
464
491
 
@@ -489,7 +516,7 @@ def _render_bodied_extension(node: ast.BodiedExtension) -> dict[str, Any]:
489
516
  result: dict[str, Any] = {
490
517
  "type": "bodiedExtension",
491
518
  "attrs": attrs,
492
- "content": _render_children(node.content, _render_block),
519
+ "content": _render_children(node.content, render_block),
493
520
  }
494
521
  return _with_marks(result, node.marks)
495
522
 
@@ -506,7 +533,7 @@ def _render_bodied_sync_block(node: ast.BodiedSyncBlock) -> dict[str, Any]:
506
533
  result: dict[str, Any] = {
507
534
  "type": "bodiedSyncBlock",
508
535
  "attrs": {"resourceId": node.resource_id},
509
- "content": _render_children(node.content, _render_block),
536
+ "content": _render_children(node.content, render_block),
510
537
  }
511
538
  return _with_marks(result, node.marks)
512
539
 
@@ -554,7 +581,7 @@ def _render_text(node: ast.Text) -> dict[str, Any]:
554
581
 
555
582
 
556
583
  def _render_hard_break() -> dict[str, Any]:
557
- return {"type": "hardBreak", "attrs": {"text": "\n"}}
584
+ return {"type": "hardBreak"}
558
585
 
559
586
 
560
587
  def _render_mention(node: ast.Mention) -> dict[str, Any]:
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from collections.abc import Sequence
3
+ from collections.abc import Iterator, Sequence
4
4
  from dataclasses import dataclass, field
5
5
  from typing import Any, Literal, TypeAlias, Union
6
6
 
@@ -119,7 +119,6 @@ class Text(Node):
119
119
 
120
120
  @dataclass
121
121
  class HardBreak(Node):
122
- # text: str | None = None # always "\n", injected by ADF renderer
123
122
  pass
124
123
 
125
124
 
@@ -312,7 +311,6 @@ class TableCell(Node):
312
311
  content: Sequence[TableCellContent]
313
312
  colspan: int | None = None
314
313
  rowspan: int | None = None
315
- colwidth: list[int] | None = None
316
314
  background: str | None = None
317
315
 
318
316
 
@@ -336,8 +334,48 @@ class Table(Node):
336
334
  | None
337
335
  ) = None
338
336
  width: float | None = None
337
+ # Column widths in the order of the grid columns (one entry per column,
338
+ # not per cell). ADF stores width on each cell's `attrs.colwidth`, but
339
+ # the value is semantically a column-level property — same column → same
340
+ # width — and we consolidate it here so the model reflects that.
341
+ colwidths: list[float] | None = None
339
342
  # marks: Sequence[FragmentMark] — FragmentMark itself is commented out
340
343
 
344
+ def iter_cells(
345
+ self,
346
+ ) -> Iterator[tuple[int, int, int, TableCell | TableHeader]]:
347
+ """Walk each cell with its grid position and index within the row.
348
+
349
+ Tuple shape: ``(row_index, col_index, cell_index, cell)``.
350
+
351
+ - ``row_index`` / ``col_index`` — visual grid position, accounting
352
+ for any prior row's ``rowspan`` that claims a slot in this row.
353
+ - ``cell_index`` — index inside ``row.content`` (sequential ADF order,
354
+ ignoring grid layout).
355
+
356
+ Both indices are needed: ``col_index`` tells you *what column* this
357
+ cell occupies (for colwidth distribution); ``cell_index`` finds the
358
+ corresponding rendered/raw cell dict in a parallel structure.
359
+ """
360
+ rows = self.content
361
+ num_rows = len(rows)
362
+ occupied: set[tuple[int, int]] = set()
363
+ for r, row in enumerate(rows):
364
+ c = 0
365
+ for ci, cell in enumerate(row.content):
366
+ while (r, c) in occupied:
367
+ c += 1
368
+ yield r, c, ci, cell
369
+ cs = cell.colspan or 1
370
+ rs = cell.rowspan or 1
371
+ for dr in range(rs):
372
+ rr = r + dr
373
+ if rr >= num_rows:
374
+ break
375
+ for dc in range(cs):
376
+ occupied.add((rr, c + dc))
377
+ c += cs
378
+
341
379
 
342
380
  @dataclass
343
381
  class Panel(Node):
@@ -0,0 +1,44 @@
1
+ """Markdown → ADF AST parser.
2
+
3
+ Pipeline:
4
+
5
+ md string
6
+ │
7
+ ▼ normalize.tokenize (mistune → list[dict])
8
+ raw token stream
9
+ │
10
+ ▼ normalize.normalize_blocks (pair block_html → IR)
11
+ Token stream (HtmlPaired | HtmlVoid | mistune dict)
12
+ │
13
+ ▼ block.dispatch_blocks (yield ast.Node per token)
14
+ ast.Node stream
15
+ │
16
+ ▼ ir.collect + ir.is_doc (narrow to ast.DocContent)
17
+ list[ast.DocContent]
18
+ │
19
+ ▼ ast.Doc(content=...)
20
+ ast.Doc
21
+
22
+ Each stage is its own module:
23
+ - ir.py: dataclasses, container schemas, predicates, helpers
24
+ - normalize.py: tokenization + HTML tag parsing + paired matching
25
+ - inline.py: inline dispatch + per-node inline builders
26
+ - block.py: block dispatch + per-node block builders + cell sub-system
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from marklas import ast
32
+
33
+ from .block import dispatch_blocks
34
+ from .ir import collect, is_doc
35
+ from .normalize import normalize_blocks, tokenize
36
+
37
+
38
+ def parse(md: str) -> ast.Doc:
39
+ """Parse a Markdown string (with marklas HTML extensions) to an ADF AST Doc."""
40
+ tokens = normalize_blocks(tokenize(md))
41
+ return ast.Doc(content=collect(dispatch_blocks(tokens), is_doc))
42
+
43
+
44
+ __all__ = ["parse"]