marklas 0.4.2__tar.gz → 0.4.4__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.4.2
3
+ Version: 0.4.4
4
4
  Summary: Bidirectional converter between GitHub Flavored Markdown and Atlassian Document Format
5
5
  Author: byExist
6
6
  Author-email: byExist <jongbeom.kwon@gmail.com>
@@ -136,11 +136,11 @@ restored_adf = to_adf(markdown) # push back — structure preserved
136
136
 
137
137
  Markdown is significantly more compact than ADF JSON — critical for LLM-based workflows where every token counts.
138
138
 
139
- | Format | Tokens | Bytes |
140
- | --- | --- | --- |
141
- | ADF JSON | 89,374 | 523 KB |
142
- | Markdown | 21,798 | 49 KB |
143
- | **Reduction** | **4.1x** | **10.6x** |
139
+ | | ADF JSON | Markdown (annotated) | Markdown (plain) |
140
+ | --- | --- | --- | --- |
141
+ | Tokens | 102,706 | 33,343 | 12,454 |
142
+ | Bytes | 625 KB | 99 KB | 38 KB |
143
+ | **Reduction** | — | **3.1x / 6.3x** | **8.2x / 16.5x** |
144
144
 
145
145
  *Measured on a real Confluence page using GPT-4o tokenizer (tiktoken).*
146
146
 
@@ -117,11 +117,11 @@ restored_adf = to_adf(markdown) # push back — structure preserved
117
117
 
118
118
  Markdown is significantly more compact than ADF JSON — critical for LLM-based workflows where every token counts.
119
119
 
120
- | Format | Tokens | Bytes |
121
- | --- | --- | --- |
122
- | ADF JSON | 89,374 | 523 KB |
123
- | Markdown | 21,798 | 49 KB |
124
- | **Reduction** | **4.1x** | **10.6x** |
120
+ | | ADF JSON | Markdown (annotated) | Markdown (plain) |
121
+ | --- | --- | --- | --- |
122
+ | Tokens | 102,706 | 33,343 | 12,454 |
123
+ | Bytes | 625 KB | 99 KB | 38 KB |
124
+ | **Reduction** | — | **3.1x / 6.3x** | **8.2x / 16.5x** |
125
125
 
126
126
  *Measured on a real Confluence page using GPT-4o tokenizer (tiktoken).*
127
127
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "marklas"
3
- version = "0.4.2"
3
+ version = "0.4.4"
4
4
  description = "Bidirectional converter between GitHub Flavored Markdown and Atlassian Document Format"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -29,3 +29,8 @@ addopts = ["--import-mode=importlib"]
29
29
  [build-system]
30
30
  requires = ["uv_build>=0.9.21,<0.10.0"]
31
31
  build-backend = "uv_build"
32
+
33
+ [dependency-groups]
34
+ dev = [
35
+ "pre-commit>=4.5.1",
36
+ ]
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import re
7
+ import textwrap
7
8
  from typing import Any, Literal, cast
8
9
 
9
10
  import mistune
@@ -21,6 +22,7 @@ _tokenize = mistune.create_markdown(
21
22
  renderer="ast",
22
23
  plugins=["table", "strikethrough", "task_lists"],
23
24
  )
25
+ _inline_parser = _tokenize.inline
24
26
 
25
27
 
26
28
  # ---------------------------------------------------------------------------
@@ -112,11 +114,9 @@ def _split_block_html(raw: str) -> list[dict[str, Any]] | None:
112
114
  if parsed:
113
115
  synthetic_tokens.append({"type": "inline_html", "raw": part})
114
116
  else:
115
- inner_tokens = cast(list[dict[str, Any]], _tokenize(part))
116
- for tok in inner_tokens:
117
- if tok["type"] == "paragraph":
118
- children = cast(list[dict[str, Any]], tok.get("children", []))
119
- synthetic_tokens.extend(children)
117
+ state = _inline_parser.state_cls(env={})
118
+ state.src = part
119
+ synthetic_tokens.extend(_inline_parser.parse(state))
120
120
 
121
121
  if not synthetic_tokens:
122
122
  return None
@@ -268,7 +268,7 @@ def _parse_block(token: dict[str, Any]) -> blocks.Block | None:
268
268
  case "bodiedSyncBlock":
269
269
  return _parse_annotated_bodied_sync_block(token)
270
270
  case "blank_line":
271
- return blocks.Paragraph(children=[])
271
+ return None
272
272
  case "block_html":
273
273
  return None
274
274
  case _:
@@ -294,6 +294,7 @@ def _parse_code_block(token: dict[str, Any]) -> blocks.CodeBlock:
294
294
  code = token.get("raw", "")
295
295
  if code.endswith("\n"):
296
296
  code = code[:-1]
297
+ code = textwrap.dedent(code)
297
298
  info = token.get("attrs", {}).get("info", "")
298
299
  language = info or None
299
300
  return blocks.CodeBlock(code=code, language=language)
@@ -330,8 +331,14 @@ def _parse_list(token: dict[str, Any]) -> blocks.BulletList | blocks.OrderedList
330
331
  def _parse_list_item_children(
331
332
  item_token: dict[str, Any], tight: bool
332
333
  ) -> list[blocks.Block]:
334
+ matched = _match_block_annotations(item_token.get("children", []))
333
335
  children: list[blocks.Block] = []
334
- for child in item_token.get("children", []):
336
+ for child in matched:
337
+ if child.get("_annotated"):
338
+ node = _parse_block(child)
339
+ if node is not None:
340
+ children.append(node)
341
+ continue
335
342
  match child["type"]:
336
343
  case "paragraph":
337
344
  children.append(_parse_paragraph(child))
@@ -346,6 +353,14 @@ def _parse_list_item_children(
346
353
  children.append(_parse_list(child))
347
354
  case "thematic_break":
348
355
  children.append(_parse_thematic_break())
356
+ case "blank_line":
357
+ pass
358
+ case "block_html":
359
+ inline_children = _split_block_html(child["raw"])
360
+ if inline_children is not None:
361
+ inls = _parse_inlines(inline_children)
362
+ if inls:
363
+ children.append(blocks.Paragraph(children=inls))
349
364
  case _:
350
365
  raise ValueError(f"Unknown list item child type: {child['type']}")
351
366
  return children
@@ -539,19 +554,36 @@ def _parse_annotated_layout_column(token: dict[str, Any]) -> blocks.LayoutColumn
539
554
  # ---------------------------------------------------------------------------
540
555
 
541
556
 
557
+ def _br_to_linebreak(tok: dict[str, Any]) -> dict[str, Any]:
558
+ if tok.get("type") == "inline_html" and tok["raw"].strip().lower() in (
559
+ "<br>",
560
+ "<br/>",
561
+ "<br />",
562
+ ):
563
+ return {"type": "linebreak"}
564
+ return tok
565
+
566
+
542
567
  def _parse_cell_blocks(tokens: list[dict[str, Any]]) -> list[blocks.Block]:
543
568
  """Parse table cell inline tokens into blocks.
544
569
 
545
570
  Uses annotation matching to group tokens, then dispatches each group.
546
571
  Unannotated tokens become Paragraph (plain GFM).
547
572
  """
548
- matched = _match_cell_annotations(tokens)
573
+ # Rewrite <br> inline_html → linebreak before annotation matching so that
574
+ # HardBreak survives inside annotated paragraph children.
575
+ rewritten = [_br_to_linebreak(t) for t in tokens]
576
+ matched = _match_cell_annotations(rewritten)
549
577
  result: list[blocks.Block] = []
550
578
  loose: list[dict[str, Any]] = []
551
579
 
552
580
  def _flush_loose() -> None:
553
581
  if not loose:
554
582
  return
583
+ # linebreak-only loose tokens are block separators — skip them
584
+ if all(t.get("type") == "linebreak" for t in loose):
585
+ loose.clear()
586
+ return
555
587
  children = _parse_inlines(loose)
556
588
  if children:
557
589
  result.append(blocks.Paragraph(children=children))
@@ -810,7 +842,15 @@ def _parse_inlines(tokens: list[dict[str, Any]]) -> list[inlines.Inline]:
810
842
  for token in matched:
811
843
  node = _parse_inline(token)
812
844
  if node is not None:
813
- result.append(node)
845
+ # Merge adjacent Text nodes (mistune may split e.g. "[" separately)
846
+ if (
847
+ isinstance(node, inlines.Text)
848
+ and result
849
+ and isinstance(result[-1], inlines.Text)
850
+ ):
851
+ result[-1] = inlines.Text(text=result[-1].text + node.text)
852
+ else:
853
+ result.append(node)
814
854
  return result
815
855
 
816
856
 
@@ -1036,7 +1076,6 @@ def _build_media(d: dict[str, Any]) -> blocks.Media:
1036
1076
  )
1037
1077
 
1038
1078
 
1039
-
1040
1079
  # ---------------------------------------------------------------------------
1041
1080
  # Helpers
1042
1081
  # ---------------------------------------------------------------------------
@@ -1211,12 +1250,10 @@ def _inner_tokens_to_text(tokens: list[dict[str, Any]]) -> str:
1211
1250
  for tok in tokens:
1212
1251
  if tok["type"] == "text":
1213
1252
  parts.append(tok["raw"])
1253
+ elif tok["type"] == "linebreak":
1254
+ parts.append("<br>")
1214
1255
  elif tok["type"] == "inline_html":
1215
- raw = tok["raw"].strip()
1216
- if raw.lower() == "<br>":
1217
- parts.append("<br>")
1218
- else:
1219
- parts.append(raw)
1256
+ parts.append(tok["raw"].strip())
1220
1257
  elif tok["type"] == "codespan":
1221
1258
  parts.append(tok["raw"])
1222
1259
  else:
@@ -12,14 +12,6 @@ from marklas.nodes import blocks, inlines
12
12
  _annotate_ctx: ContextVar[bool] = ContextVar("annotate", default=True)
13
13
 
14
14
 
15
- class UnknownNodeError(Exception):
16
- """Raised when a render dispatch encounters an unrecognized AST node."""
17
-
18
- def __init__(self, node: object) -> None:
19
- super().__init__(f"Unknown node: {type(node).__name__}")
20
- self.node = node
21
-
22
-
23
15
  def render(doc: blocks.Document, *, annotate: bool = True) -> str:
24
16
  token = _annotate_ctx.set(annotate)
25
17
  try:
@@ -123,7 +115,7 @@ def _render_block(node: blocks.Block) -> str:
123
115
  case blocks.BodiedSyncBlock():
124
116
  return _render_bodied_sync_block(node)
125
117
  case _:
126
- raise UnknownNodeError(node)
118
+ raise ValueError(f"Unknown node: {type(node).__name__}")
127
119
 
128
120
 
129
121
  def _render_paragraph(node: blocks.Paragraph) -> str:
@@ -135,6 +127,8 @@ def _render_paragraph(node: blocks.Paragraph) -> str:
135
127
  align=node.alignment,
136
128
  indentation=node.indentation,
137
129
  )
130
+ if not content and _annotate_ctx.get():
131
+ return _annotate_block(node, content)
138
132
  return content
139
133
 
140
134
 
@@ -187,11 +181,23 @@ def _render_ordered_list(node: blocks.OrderedList) -> str:
187
181
  return sep.join(items)
188
182
 
189
183
 
184
+ def _is_whitespace_only_paragraph(node: blocks.Block) -> bool:
185
+ return (
186
+ isinstance(node, blocks.Paragraph)
187
+ and all(
188
+ isinstance(c, inlines.Text) and not c.text.strip() for c in node.children
189
+ )
190
+ and len(node.children) > 0
191
+ )
192
+
193
+
190
194
  def _render_list_item_body(children: list[blocks.Block], tight: bool) -> str:
191
195
  if tight and len(children) == 1 and isinstance(children[0], blocks.Paragraph):
192
196
  return _render_inlines(children[0].children)
193
197
  parts: list[str] = []
194
198
  for child in children:
199
+ if _is_whitespace_only_paragraph(child):
200
+ continue
195
201
  rendered = _render_block(child)
196
202
  parts.append(rendered)
197
203
  body = "\n\n".join(parts)
@@ -250,8 +256,19 @@ def _render_table_row(row: list[blocks.TableCell], col_count: int) -> str:
250
256
 
251
257
 
252
258
  def _render_table_cell(cell: blocks.TableCell) -> str:
259
+ parts = [_render_cell_block(c) for c in cell.children]
253
260
  sep = "" if _annotate_ctx.get() else "<br>"
254
- return sep.join(_render_cell_block(c) for c in cell.children)
261
+ return _escape_cell_pipe(sep.join(parts))
262
+
263
+
264
+ def _escape_cell_pipe(text: str) -> str:
265
+ """Escape unescaped ``|`` inside rendered table-cell content.
266
+
267
+ Pipe characters that act as GFM column delimiters are added by the
268
+ row-level renderer, so any ``|`` produced by cell-block rendering must
269
+ be escaped to avoid breaking the column count.
270
+ """
271
+ return text.replace("|", "\\|")
255
272
 
256
273
 
257
274
  def _collect_table_attrs(node: blocks.Table) -> dict[str, Any]:
@@ -460,7 +477,7 @@ def _render_cell_block(node: blocks.Block) -> str:
460
477
  case blocks.BodiedSyncBlock():
461
478
  return _render_cell_bodied_sync_block(node)
462
479
  case _:
463
- raise UnknownNodeError(node)
480
+ raise ValueError(f"Unknown node: {type(node).__name__}")
464
481
 
465
482
 
466
483
  def _render_cell_inlines(nodes: list[inlines.Inline]) -> str:
@@ -682,7 +699,7 @@ def _render_inline(node: inlines.Inline) -> str:
682
699
  case inlines.InlineExtension():
683
700
  return _extension_fallback(node.raw)
684
701
  case _:
685
- raise UnknownNodeError(node)
702
+ raise ValueError(f"Unknown node: {type(node).__name__}")
686
703
 
687
704
 
688
705
  def _render_link(node: inlines.Link) -> str:
File without changes
File without changes
File without changes