-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
1452 lines (1173 loc) · 55.8 KB
/
script.py
File metadata and controls
1452 lines (1173 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import json
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
import re
import hashlib
import tempfile
import os
import urllib.request
import urllib.parse
def get_root() -> Path:
if getattr(sys, 'frozen', False):
return Path(sys._MEIPASS)
return Path(__file__).parent.resolve()
ROOT = get_root()
PLACEHOLDERS = [
"@@TITLE@@",
"@@SUBTITLE@@",
"@@SUBMITTEDTO@@",
"@@AUTHORS@@",
"@@DATE@@",
"@@INPUT_FILE@@",
"@@TITLE_TEMPLATE@@",
"@@ENABLE_CONTENT_PAGE@@",
"@@TOC_DEPTH@@",
"@@ENABLE_PAGE_CREDITS@@",
"@@ENABLE_FOOTNOTES_AT_END@@",
"@@ENABLE_FOOTNOTES_AS_COMMENTS@@",
"@@ENABLE_THATS_ALL_PAGE@@",
"@@HEADING_NUMBERING@@",
"@@UNIVERSITY@@",
"@@DEPARTMENT@@",
]
IMAGE_EXTS = {
".png",
".jpg",
".jpeg",
".gif",
".pdf",
".svg",
".eps",
".bmp",
".webp",
}
LATEX_LOG_LEVEL = "SILENT"
class BuildError(Exception):
pass
class Logger:
"""Colored console logging utility with single-line overwriting."""
COLORS = {
"INFO": "\033[94m",
"SUCCESS": "\033[92m",
"WARNING": "\033[93m",
"ERROR": "\033[91m",
"RESET": "\033[0m",
}
_last_length = 0
@classmethod
def _print(cls, msg: str, persist: bool = False):
"""Print message, optionally overwriting previous line."""
padding = max(0, cls._last_length - len(msg))
padded_msg = msg + " " * padding
cls._last_length = len(msg)
if persist:
print(f"\r{padded_msg}")
cls._last_length = 0
else:
print(f"\r{padded_msg}", end="", flush=True)
@classmethod
def info(cls, msg: str, persist: bool = False):
cls._print(f"{cls.COLORS['INFO']}[INFO]{cls.COLORS['RESET']} {msg}", persist)
@classmethod
def success(cls, msg: str, persist: bool = True):
cls._print(f"{cls.COLORS['SUCCESS']}[SUCCESS]{cls.COLORS['RESET']} {msg}", persist)
@classmethod
def warning(cls, msg: str, persist: bool = True):
cls._print(f"{cls.COLORS['WARNING']}[WARNING]{cls.COLORS['RESET']} {msg}", persist)
@classmethod
def error(cls, msg: str, persist: bool = True):
cls._print(f"{cls.COLORS['ERROR']}[ERROR]{cls.COLORS['RESET']} {msg}", persist)
def load_or_create_metadata(md_dir: Path, md_base: str) -> dict:
def is_similar_json(s1: dict, s2: dict, except_keys: set) -> bool:
"""Check if two JSON objects have the same keys with matching data types."""
s1_filtered = {k: v for k, v in s1.items() if k not in except_keys}
s2_filtered = {k: v for k, v in s2.items() if k not in except_keys}
if s1_filtered.keys() != s2_filtered.keys():
return False
for key in s1_filtered.keys():
if type(s1_filtered[key]) != type(s2_filtered[key]):
return False
return True
def load_json_file(path: Path) -> dict:
"""Safely load JSON from file."""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def get_current_date() -> str:
"""Get current date in the required format."""
return datetime.now().strftime("%B %d, %Y")
def write_metadata_with_date(data: dict, path: Path) -> None:
"""Write metadata JSON file with current date."""
data["date"] = get_current_date()
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
def update_compatible_fields(target: dict, source: dict | None) -> None:
"""Update target dict with compatible fields from source."""
if source is not None:
target.update({k: v for k, v in source.items() if k in target and type(v) == type(target[k])})
"""Load metadata JSON file, creating default if missing."""
meta_path = md_dir / f"{md_base}.json"
json_file = load_json_file(ROOT / "default.json")
if not meta_path.exists():
parent_default_path = ROOT.parent / "default.json"
if parent_default_path.exists():
try:
modified_default = load_json_file(parent_default_path)
except json.JSONDecodeError:
Logger.error(f"Invalid JSON in {parent_default_path}. Using default.")
modified_default = None
if is_similar_json(json_file, modified_default, except_keys={"date"}):
json_file = modified_default
else:
update_compatible_fields(json_file, modified_default)
with open(parent_default_path, "w", encoding="utf-8") as f:
json.dump(json_file, f, indent=2)
write_metadata_with_date(json_file, meta_path)
Logger.warning(f"Created {md_base}.json")
else:
try:
json_file_in_dir = load_json_file(meta_path)
except json.JSONDecodeError:
Logger.error(f"Invalid JSON in {md_base}.json. Recreating from default.")
write_metadata_with_date(json_file, meta_path)
return json_file
if not is_similar_json(json_file, json_file_in_dir, except_keys={"date"}):
update_compatible_fields(json_file, json_file_in_dir)
write_metadata_with_date(json_file, meta_path)
Logger.warning(f"Updated {md_base}.json to match expected structure")
return load_json_file(meta_path)
def build_authors(meta: dict) -> str:
"""Build LaTeX table rows for authors from metadata."""
authors = meta.get("submittedby") or []
if not isinstance(authors, list):
return ""
lines: list[str] = []
for i, a in enumerate(authors):
name = str(a.get("name", ""))
roll = str(a.get("roll", ""))
if i > 0:
lines.append(r"\noalign{\vspace{0.3cm}}")
lines.append(f"Name: & {name} \\\\")
lines.append(f"Reg\\#: & {roll} \\\\")
if not lines:
return ""
return "\n".join(lines)
def replace_placeholders(md_path: Path, tex_path: Path, meta: dict):
"""Replace template placeholders with metadata values."""
content = tex_path.read_text(encoding="utf-8")
authors_block = build_authors(meta)
to_value = meta.get("submittedto", "")
# Map string template names to numeric values for LaTeX
title_template_map = {
"no-title": 0,
"university-title": 1,
"header-title": 2,
"separate-page-title": 3,
}
title_template_value = meta.get("titleTemplate", "no-title")
# Support both old numeric format and new string format for backward compatibility
if isinstance(title_template_value, int):
title_template = title_template_value
if title_template < 0 or title_template > 3:
title_template = 0
else:
title_template = title_template_map.get(title_template_value, 0)
title_template_cmd = f"\\renewcommand{{\\titleTemplate}}{{{title_template}}}"
enable_content = bool(meta.get("enableContentPage"))
content_page_toggle = "\\enablecontentpagetrue" if enable_content else "\\enablecontentpagefalse"
toc_depth = int(meta.get("tocDepth", 3))
if toc_depth < 1 or toc_depth > 6:
toc_depth = 3
toc_depth_cmd = f"\\setcounter{{tocdepth}}{{{toc_depth}}}"
enable_credits = bool(meta.get("enablePageCredits", False))
page_credits_toggle = "\\enablepagecreditstrue" if enable_credits else "\\enablepagecreditsfalse"
enable_footnotes_at_end = bool(meta.get("moveFootnotesToEnd"))
footnotes_at_end_toggle = "\\enablefootnotesatendtrue" if enable_footnotes_at_end else "\\enablefootnotesatendfalse"
enable_footnotes_as_comments = bool(meta.get("footnotesAsComments"))
footnotes_as_comments_toggle = "\\enablefootnotesascommentstrue" if enable_footnotes_as_comments else "\\enablefootnotesascommentsfalse"
enable_thats_all = bool(meta.get("enableThatsAllPage"))
thats_all_toggle = "\\enablethatsalltrue" if enable_thats_all else "\\enablethatsallfalse"
heading_numbering = bool(meta.get("headingNumbering", False))
heading_numbering_toggle = "" if heading_numbering else "\\suppressnumbering"
mapping = {
"@@TITLE@@": meta.get("title", ""),
"@@SUBTITLE@@": meta.get("subtitle", ""),
"@@SUBMITTEDTO@@": to_value,
"@@AUTHORS@@": authors_block,
"@@DATE@@": meta.get("date", ""),
"@@INPUT_FILE@@": md_path.name,
"@@TITLE_TEMPLATE@@": title_template_cmd,
"@@ENABLE_CONTENT_PAGE@@": content_page_toggle,
"@@TOC_DEPTH@@": toc_depth_cmd,
"@@ENABLE_PAGE_CREDITS@@": page_credits_toggle,
"@@ENABLE_FOOTNOTES_AT_END@@": footnotes_at_end_toggle,
"@@ENABLE_FOOTNOTES_AS_COMMENTS@@": footnotes_as_comments_toggle,
"@@ENABLE_THATS_ALL_PAGE@@": thats_all_toggle,
"@@HEADING_NUMBERING@@": heading_numbering_toggle,
"@@UNIVERSITY@@": meta.get("university", ""),
"@@DEPARTMENT@@": meta.get("department", ""),
}
for ph in PLACEHOLDERS:
val = mapping.get(ph, "")
content = content.replace(ph, val)
tex_path.write_text(content, encoding="utf-8")
def run_lualatex(build_dir: Path):
env = os.environ.copy()
texmf = ROOT / "texmf"
if texmf.exists():
env["TEXMFHOME"] = str(texmf)
cmd = [
"lualatex",
"--shell-escape",
"-synctex=1",
"-interaction=nonstopmode",
"-file-line-error",
"template.tex",
]
try:
Logger.info(f"Compiling into PDF...", persist=False)
proc = subprocess.run(
cmd,
cwd=build_dir,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
check=False,
)
except FileNotFoundError as e:
raise BuildError("lualatex not found") from e
final_returncode = proc.returncode
output = proc.stdout
if LATEX_LOG_LEVEL == "DEBUG":
print(output)
pdf_path = build_dir / "template.pdf"
produced = pdf_path.exists()
return final_returncode, produced, pdf_path
def find_markdown_images(md_path: Path) -> list[Path]:
text = md_path.read_text(encoding="utf-8", errors="ignore")
candidates: set[str] = set()
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
# 
raw = m.group(1).strip()
if raw.startswith("<") and raw.endswith(">"):
raw = raw[1:-1]
if (raw.startswith('"') and raw.endswith('"')) or (raw.startswith("'") and raw.endswith("'")):
raw = raw[1:-1]
if " " in raw and not any(raw.startswith(q) for q in ('"', "'")):
raw = raw.split(" ")[0]
candidates.add(raw)
for m in re.finditer(r'<img[^>]*?src=["\']([^"\']+)["\']', text, re.IGNORECASE):
# <img src="path" ...>
candidates.add(m.group(1).strip())
for m in re.finditer(r"^\s*\[[^\]]+\]:\s*(\S+)", text, re.MULTILINE):
# [label]: path
target = m.group(1).strip()
candidates.add(target)
paths: list[Path] = []
for c in candidates:
if not c or "://" in c or c.startswith("data:") or c.startswith("#"):
continue
p = (md_path.parent / c).resolve()
if p.exists() and p.suffix.lower() in IMAGE_EXTS:
paths.append(p)
return paths
def download_remote_images_from_markdown(md_content: str, build_dir: Path) -> str:
"""Download remote images referenced in markdown and replace URLs with local paths."""
images_dir = build_dir / "images"
images_dir.mkdir(exist_ok=True)
def download_and_replace_url(match):
url = match.group(2).strip()
if not ("http://" in url or "https://" in url):
return match.group(0)
try:
clean_url = url.split("?")[0] if "?" in url else url
filename = Path(urllib.parse.urlparse(clean_url).path).name
if not filename or "." not in filename:
filename = "image_" + hashlib.md5(url.encode()).hexdigest()[:8] + ".jpg"
local_path = images_dir / filename
if not local_path.exists():
Logger.info(f"Downloading: {filename}", persist=False)
urllib.request.urlretrieve(url, local_path)
relative_path = f"images/{filename}"
return f""
except Exception as e:
Logger.warning(f"Failed to download image: {e}")
return match.group(0)
return re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", download_and_replace_url, md_content)
def convert_markdown_footnotes_to_latex(content: str, use_comments: bool = False) -> str:
content, protected_blocks = protect_code_and_math_blocks(content)
footnote_defs = {}
def extract_definition(match):
label = match.group(1)
content = match.group(2).strip()
footnote_defs[label] = content
return ""
content = re.sub(r"^\[(\^[^\]]+)\]:\s*(.+?)(?=\n\s*\n|\n\s*\[|\Z)", extract_definition, content, flags=re.MULTILINE | re.DOTALL)
if use_comments:
def replace_inline(match):
footnote_content = match.group(1)
return f"\\todoComment{{{footnote_content}}}"
content = re.sub(r"\^\[([^\]]+)\]", replace_inline, content)
def replace_reference(match):
label = match.group(1)
if label in footnote_defs:
footnote_content = footnote_defs[label]
return f"\\todoComment{{{footnote_content}}}"
return match.group(0)
content = re.sub(r"\[(\^[^\]]+)\]", replace_reference, content)
else:
def replace_inline(match):
footnote_content = match.group(1)
return f"\\footnote{{{footnote_content}}}"
content = re.sub(r"\^\[([^\]]+)\]", replace_inline, content)
def replace_reference(match):
label = match.group(1)
if label in footnote_defs:
footnote_content = footnote_defs[label]
return f"\\footnote{{{footnote_content}}}"
return match.group(0)
content = re.sub(r"\[(\^[^\]]+)\]", replace_reference, content)
content = restore_protected_blocks(content, protected_blocks)
return content
def escape_latex_url(url: str) -> str:
"""Escapes characters in a URL for LaTeX."""
# The hyperref package is smart, but & and % are still issues.
# It's generally safer to escape them.
return url.replace("&", r"\&").replace("%", r"\%")
def escape_signs(content: str, to_escape: list[str]) -> str:
"""Escape special characters while protecting code blocks, raw latex blocks, and URLs."""
protected_blocks = []
def protect_and_store(match):
placeholder = f"__PROTECTED_BLOCK_{len(protected_blocks)}__"
protected_blocks.append(match.group(0))
return placeholder
# Protect blocks where no escaping should happen
content = re.sub(r"````+.*?````+", protect_and_store, content, flags=re.DOTALL)
content = re.sub(r"```.*?```", protect_and_store, content, flags=re.DOTALL)
content = re.sub(r"`[^`\n]+`", protect_and_store, content)
content = re.sub(r"\$\$.*?\$\$", protect_and_store, content, flags=re.DOTALL)
content = re.sub(r"\$[^$\n]+\$", protect_and_store, content)
# For markdown links, escape the URL part separately
def protect_and_escape_link_url(match):
link_text = match.group(1)
url = match.group(2)
escaped_url = escape_latex_url(url)
placeholder = f"__PROTECTED_BLOCK_{len(protected_blocks)}__"
protected_blocks.append(escaped_url)
return f"[{link_text}]({placeholder})"
content = re.sub(r"\[([^\]]*)\]\(([^)]+)\)", protect_and_escape_link_url, content)
# Protect raw URLs that are not in markdown links
def protect_and_escape_raw_url(match):
url = match.group(1)
escaped_url = escape_latex_url(url)
placeholder = f"__PROTECTED_BLOCK_{len(protected_blocks)}__"
protected_blocks.append(escaped_url)
return placeholder
content = re.sub(r"\b(https?://[^\s<>\"')]+)", protect_and_escape_raw_url, content)
# Now, escape the characters in the rest of the content
for sign in to_escape:
content = content.replace(sign, f"\\{sign}")
# Restore all protected blocks
for i, block in enumerate(protected_blocks):
content = content.replace(f"__PROTECTED_BLOCK_{i}__", block, 1)
return content
def normalize_language_identifiers(content: str) -> str:
lang_map = {
"jsonc": "json",
"tsx": "typescript",
"jsx": "javascript",
"vue": "html",
"svelte": "html",
"astro": "html",
}
for unsupported, supported in lang_map.items():
content = re.sub(rf"```{unsupported}\b", f"```{supported}", content)
return content
def process_code_blocks(content: str, build_dir: Path) -> str:
lines = content.split("\n")
processed_lines = []
in_code_block = False
code_block_lines = []
header = ""
opening_fence = ""
for line in lines:
if not in_code_block:
match = re.match(r"^(\s*)(`{3,})(.*)", line)
if match:
in_code_block = True
opening_fence = match.group(2)
header = match.group(3).strip()
else:
processed_lines.append(line)
else:
if line.strip().startswith(opening_fence) and len(line.strip()) >= len(opening_fence):
in_code_block = False
code_content = "\n".join(code_block_lines)
lang_match = re.match(r"(\w+)", header)
lang = lang_match.group(1) if lang_match else "text"
if lang == "mermaid":
original_block = f"{opening_fence}{header}\n{code_content}\n{line.strip()}"
processed_lines.append(original_block)
else:
clean_code_content = code_content
code_hash = hashlib.md5(clean_code_content.encode("utf-8")).hexdigest()
code_dir = build_dir / "_code_build"
code_dir.mkdir(exist_ok=True)
code_filepath = code_dir / code_hash
code_filepath.write_text(clean_code_content, encoding="utf-8")
highlight_match = re.search(r"\.highlightlines=([\d,-]+)", header)
if highlight_match:
line_spec = highlight_match.group(1)
minted_options = f"breaklines,breakanywhere,linenos=false,highlightcolor=codeHighlightBg,highlightlines={{{line_spec}}}"
else:
minted_options = "breaklines,breakanywhere,linenos=false,highlightcolor=codeHighlightBg"
pygments_lang = lang
if lang == "text" or not lang:
top_padding = "5pt"
show_label = "false"
else:
top_padding = "20pt"
show_label = "true"
latex_command = f"""
\\begin{{tcolorbox}}[
enhanced, colback=black!3, colframe=black!10, boxrule=0.5pt, arc=3pt,
left=5pt, right=5pt, top={top_padding}, bottom=5pt, breakable,
overlay={{\\ifstrequal{{{show_label}}}{{true}}{{\\node[anchor=north east, font=\\scriptsize\\ttfamily, text=black!50, fill=black!7, rounded corners=1pt] at ([xshift=-5pt,yshift=-5pt]frame.north east) {{{lang}}};}}{{}} }}
]
\\inputminted[{minted_options}]{{{pygments_lang if pygments_lang else 'text'}}}{{_code_build/{code_hash}}}
\\end{{tcolorbox}}"""
raw_latex_block = f"```{{=latex}}\n{latex_command}\n```"
processed_lines.append(raw_latex_block)
code_block_lines = []
header = ""
opening_fence = ""
else:
code_block_lines.append(line)
if in_code_block:
processed_lines.append(opening_fence + header)
processed_lines.extend(code_block_lines)
return "\n".join(processed_lines)
def find_mmdc_command():
"""Return path to mermaid-cli (mmdc) if available in PATH."""
candidates = ["mmdc"]
if os.name == "nt":
candidates.insert(0, "mmdc.cmd")
for cmd in candidates:
found = shutil.which(cmd)
if found:
return found
return None
def process_mermaid_diagrams(content: str, build_dir: Path) -> str:
if "```mermaid" not in content:
return content
protected_blocks = []
def store_non_mermaid_block(match):
protected_blocks.append(match.group(0))
return f"__PROTECTED_CODE_BLOCK_{len(protected_blocks)-1}__"
content = re.sub(r"````+.*?````+", store_non_mermaid_block, content, flags=re.DOTALL)
mmdc_cmd = find_mmdc_command()
if mmdc_cmd is None:
Logger.warning("Mermaid-cli not found. Install with: npm install -g @mermaid-js/mermaid-cli")
def mermaid_to_text(match):
mermaid_code = match.group(1).strip()
return f"```text\n{mermaid_code}\n```"
pattern = r"```mermaid\n(.*?)\n```"
content = re.sub(pattern, mermaid_to_text, content, flags=re.DOTALL)
for i, block in enumerate(protected_blocks):
content = content.replace(f"__PROTECTED_CODE_BLOCK_{i}__", block)
return content
total_diagrams = len(re.findall(r"```mermaid\n(.*?)\n```", content, flags=re.DOTALL))
if total_diagrams > 0:
Logger.info(f"Processing {total_diagrams} Mermaid diagram(s)...", persist=False)
diagram_counter = 0
def replace_mermaid_block(match):
nonlocal diagram_counter
diagram_counter += 1
mermaid_code = match.group(1).strip()
diagram_hash = hashlib.md5(mermaid_code.encode("utf-8")).hexdigest()[:12]
image_name = f"mermaid_{diagram_hash}.pdf"
image_path = build_dir / image_name
if not image_path.exists():
try:
with tempfile.NamedTemporaryFile(mode="w", suffix=".mmd", delete=False, encoding="utf-8") as temp_file:
temp_file.write(mermaid_code)
temp_mmd_path = Path(temp_file.name)
config_content = {"theme": "neutral", "themeVariables": {"background": "#ffffff", "primaryColor": "#ffffff"}}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8") as config_file:
json.dump(config_content, config_file, indent=2)
temp_config_path = Path(config_file.name)
cmd = [
mmdc_cmd,
"-i",
str(temp_mmd_path),
"-o",
str(image_path),
"-t",
"neutral",
"-b",
"white",
"-c",
str(temp_config_path),
"--pdfFit",
]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
temp_mmd_path.unlink()
temp_config_path.unlink()
if result.returncode != 0 or not image_path.exists():
Logger.warning(f"Failed {diagram_counter}/{total_diagrams}")
return f"```text\n{mermaid_code}\n```"
else:
Logger.info(f"Generated {diagram_counter}/{total_diagrams}", persist=False)
except Exception:
Logger.warning(f"Error {diagram_counter}/{total_diagrams}")
return f"```text\n{mermaid_code}\n```"
else:
Logger.info(f"Cached {diagram_counter}/{total_diagrams}", persist=False)
return f""
pattern = r"```mermaid\n(.*?)\n```"
processed_content = re.sub(pattern, replace_mermaid_block, content, flags=re.DOTALL)
for i, block in enumerate(protected_blocks):
processed_content = processed_content.replace(f"__PROTECTED_CODE_BLOCK_{i}__", block)
return processed_content
def process_keyboard_shortcuts(content: str) -> str:
"""Convert [[KEY]] and [[KEY1] + [KEY2]] syntax to LaTeX keyboard shortcut commands."""
content, protected_blocks = protect_code_and_math_blocks(content)
def convert_shortcut(match):
captured = match.group(1)
shortcut_content = "[" + captured + "]"
parts = re.findall(r"\[([^\]]+)\]|(\s*\+\s*)", shortcut_content)
latex_parts = []
for key, separator in parts:
if key:
latex_parts.append(f"\\kbdkey{{{key}}}")
elif separator:
latex_parts.append("\\kbdplus")
joined_latex = "".join(latex_parts)
return f"\\kbdshortcut{{{joined_latex}}}"
content = re.sub(r"\[\[(.*?)\]\]", convert_shortcut, content)
content = restore_protected_blocks(content, protected_blocks)
return content
def process_container_blocks(content: str) -> str:
"""Convert container-style blocks (alerts, alignment, boxes) to LaTeX environments with proper nesting support."""
content, protected_blocks = protect_code_and_math_blocks(content)
container_types = {
"note": "mdalertnote",
"tip": "mdalerttip",
"important": "mdalertimportant",
"warning": "mdalertwarning",
"caution": "mdalertcaution",
"center": "mdcenter",
"right": "mdright",
"box": "mdbox",
}
lines = content.split("\n")
processed_lines = []
i = 0
alert_counter = 0
while i < len(lines):
line = lines[i]
match = re.match(r"^(\s*):::\s*(note|tip|important|warning|caution|center|right|box)\s*$", line, re.IGNORECASE)
if match:
indent = match.group(1)
alert_type = match.group(2).lower()
latex_env = container_types[alert_type]
alert_id = alert_counter
alert_counter += 1
alert_lines = []
i += 1
nesting_level = 1
while i < len(lines) and nesting_level > 0:
current_line = lines[i]
if re.match(r"^(\s*):::\s*(note|tip|important|warning|caution|center|right|box)\s*$", current_line, re.IGNORECASE):
nesting_level += 1
if current_line.startswith(indent) and len(current_line) > len(indent):
clean_line = current_line[len(indent) :]
elif current_line.strip() == "":
clean_line = ""
else:
clean_line = current_line
alert_lines.append(clean_line)
elif re.match(r"^(\s*):::\s*$", current_line):
nesting_level -= 1
if nesting_level > 0:
if current_line.startswith(indent) and len(current_line) > len(indent):
clean_line = current_line[len(indent) :]
elif current_line.strip() == "":
clean_line = ""
else:
clean_line = current_line
alert_lines.append(clean_line)
else:
if current_line.startswith(indent) and len(current_line) > len(indent):
clean_line = current_line[len(indent) :]
elif current_line.strip() == "":
clean_line = ""
else:
clean_line = current_line
alert_lines.append(clean_line)
i += 1
while alert_lines and alert_lines[-1].strip() == "":
alert_lines.pop()
alert_content = "\n".join(alert_lines)
processed_alert_content = process_container_blocks(alert_content) # Recursive call
processed_alert_lines = processed_alert_content.split("\n") if processed_alert_content else []
processed_lines.append(f"{indent}__ALERT_BEGIN_{alert_id}_{latex_env}__")
processed_lines.append("")
for alert_line in processed_alert_lines:
processed_lines.append(f"{indent}{alert_line}")
processed_lines.append("")
processed_lines.append(f"{indent}__ALERT_END_{alert_id}_{latex_env}__")
else:
processed_lines.append(line)
i += 1
result = "\n".join(processed_lines)
result = restore_protected_blocks(result, protected_blocks)
return result
def post_process_alerts(content: str) -> str:
"""Convert alert placeholders to raw LaTeX blocks after markdown processing."""
content, protected_blocks = protect_code_and_math_blocks(content)
def replace_begin(match):
env_name = match.group(1)
return f"\\begin{{{env_name}}}"
def replace_end(match):
env_name = match.group(1)
return f"\\end{{{env_name}}}"
content = re.sub(r"__ALERT_BEGIN_\d+_([a-z]+)__", replace_begin, content)
content = re.sub(r"__ALERT_END_\d+_([a-z]+)__", replace_end, content)
content = restore_protected_blocks(content, protected_blocks)
return content
def protect_code_and_math_blocks(content: str) -> tuple[str, list[str]]:
"""Temporarily replace code blocks and math blocks with placeholders."""
protected_blocks = []
def store_protected_block(match):
protected_blocks.append(match.group(0))
return f"__PROTECTED_PLACEHOLDER_{len(protected_blocks)-1}__"
content = re.sub(r"````+.*?````+", store_protected_block, content, flags=re.DOTALL)
content = re.sub(r"```.*?```", store_protected_block, content, flags=re.DOTALL)
content = re.sub(r"`[^`\n]*`", store_protected_block, content)
content = re.sub(r"\$\$.*?\$\$", store_protected_block, content, flags=re.DOTALL)
content = re.sub(r"\$[^$\n]*\$", store_protected_block, content)
return content, protected_blocks
def restore_protected_blocks(content: str, protected_blocks: list[str]) -> str:
"""Restore protected blocks from placeholders."""
for i, protected_block in enumerate(protected_blocks):
content = content.replace(f"__PROTECTED_PLACEHOLDER_{i}__", protected_block)
return content
def process_emojis(content: str) -> str:
"""Convert emoji characters in content to LaTeX \\emoji{shortcode} using emoji-table.def mapping."""
content, protected_blocks = protect_code_and_math_blocks(content)
if not hasattr(process_emojis, "_emoji_map"):
emoji_map = {}
emoji_table_path = subprocess.check_output(["kpsewhich", "emoji-table.def"], text=True).strip()
if emoji_table_path and os.path.exists(emoji_table_path):
with open(emoji_table_path, encoding="utf-8") as f:
data = f.read()
pattern = r"\\__emoji_def:nnnnn\s*{([^}]*)}\s*{([^}]*)}"
for m in re.findall(pattern, data):
hex_seq, shortcode = m
chars = []
for cp in re.findall(r"\^+([0-9a-fA-F]+)", hex_seq):
chars.append(chr(int(cp, 16)))
emoji = "".join(chars)
emoji_map[emoji] = shortcode
process_emojis._emoji_map = emoji_map
else:
emoji_map = process_emojis._emoji_map
def replace_emoji(match):
emoji = match.group(0)
shortcode = emoji_map.get(emoji)
if shortcode:
return f"\\emoji{{{shortcode}}}"
return emoji
if emoji_map:
emoji_regex = re.compile("|".join(re.escape(e) for e in sorted(emoji_map, key=len, reverse=True)))
content = emoji_regex.sub(replace_emoji, content)
content = restore_protected_blocks(content, protected_blocks)
return content
def apply_markdown_formatting_math_safe(content: str) -> str:
"""Apply markdown formatting while protecting LaTeX math blocks and code blocks."""
content, protected_blocks = protect_code_and_math_blocks(content)
content = re.sub(r"(?<=\s)==([^=]+)==(?=\s|[.,!?:;\'\"\)\]\}]|\Z)", r"\\mdhighlight{\1}", content)
content = re.sub(r"(?<=\s)~~([^~]+)~~(?=\s|[.,!?:;\'\"\)\]\}]|\Z)", r"\\mdstrikethrough{\1}", content)
content = re.sub(r"(?<=\s)--([^-]+)--(?=\s|[.,!?:;\'\"\)\]\}]|\Z)", r"\\underline{\1}", content)
content = re.sub(r"(?<=\s)\^\^([^\^]+)\^\^(?=\s|[.,!?:;\'\"\)\]\}]|\Z)", r"\\textsc{\1}", content)
content = re.sub(r"\^([^\^]+)\^", r"\\textsuperscript{\1}", content)
content = re.sub(r"~([^~]+)~", r"\\textsubscript{\1}", content)
content = restore_protected_blocks(content, protected_blocks)
return content
def convert_svg_to_pdf(svg_path: Path, pdf_path: Path) -> bool:
"""Convert an SVG file to PDF using svglib+reportlab. Returns True on success."""
try:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF
drawing = svg2rlg(str(svg_path))
if drawing is None:
Logger.warning(f"svglib could not parse {svg_path}")
return False
renderPDF.drawToFile(drawing, str(pdf_path), fmt="PDF")
return True
except ImportError:
Logger.warning("svglib/reportlab not installed – SVG images will not render. " "Install with: pip install svglib reportlab")
return False
except Exception as e:
Logger.warning(f"SVG-to-PDF conversion failed for {svg_path}: {e}")
return False
def rewrite_svg_refs_to_pdf(md_content: str) -> str:
"""Replace .svg image references with .pdf so LaTeX can include them."""
md_content = re.sub(
r'(!\[[^\]]*\]\([^)]*)\.svg(\s*(?:"[^"]*")?\s*\))',
r"\1.pdf\2",
md_content,
)
md_content = re.sub(
r'(<img[^>]*?src=["\'])([^"\']*)(\.svg)(["\'])',
r"\1\2.pdf\4",
md_content,
flags=re.IGNORECASE,
)
return md_content
def copy_image_assets(md_path: Path, build_dir: Path, root_md_dir: Path):
images = find_markdown_images(md_path)
if not images:
return
for img in images:
try:
rel = img.relative_to(root_md_dir)
except ValueError:
rel = Path(img.name)
# Convert SVGs to PDF for LaTeX compatibility
if img.suffix.lower() == ".svg":
pdf_rel = rel.with_suffix(".pdf")
dest = build_dir / pdf_rel
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists():
if not convert_svg_to_pdf(img, dest):
Logger.error(f"Failed to convert SVG {img}")
else:
dest = build_dir / rel
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists():
try:
shutil.copy(img, dest)
except Exception as e:
Logger.error(f"Failed to copy image {img}: {e}")
def process_executable_blocks(content: str, build_dir: Path, source_dir: Path = None) -> str:
"""Execute code blocks with property-based control for multiple languages.
Syntax: ```lang {.execute .show-code .show-output .no-cache .format=png}
Properties:
- .execute: Marks the block for execution.
- .show-code: Displays the source code.
- .hide-code: Hides the source code.
- .show-output: Displays the execution output.
- .hide-output: Hides the execution output.
- .cache / .no-cache: Controls caching of execution results.
- .format=png|pdf: Sets plot output format (default: pdf, Python only).
"""
EXECUTION_CONFIG = {
"python": {
"command": ["python"],
"extension": "py",
"plot_check": lambda code: ("plt.show()" in code or "plt.subplots(" in code or "plt.plot(" in code or "plt.bar(" in code or "plt.scatter(" in code or "plt.hist(" in code or "plt.figure(" in code),
"plot_code": "\nimport matplotlib.pyplot as plt\nplt.savefig(r'{plot_path}', format='{format}', bbox_inches='tight'{dpi_param})\nplt.close()",
"plot_formats": ["pdf", "png"],
"default_format": "pdf",
"persistent": True, # Enable persistent state for Python
},
"javascript": {"command": ["node"], "extension": "js"},
"powershell": {"command": ["powershell", "-File"], "extension": "ps1"},
"bash": {"command": ["bash"], "extension": "sh"},
}
# Try to use IPython for persistent Python execution
python_namespace = {} # Shared namespace for Python blocks
try:
from IPython.terminal.embed import InteractiveShellEmbed
python_shell = InteractiveShellEmbed()
python_shell.run_cell("import sys; import io", silent=True)
except ImportError:
python_shell = None # Use simple exec-based persistence
supported_langs = "|".join(EXECUTION_CONFIG.keys())
pattern = rf"```({supported_langs})\s+{{([^}}]+)}}\n(.*?)\n```"
protected_blocks = []
def store_protected_block(match):
protected_blocks.append(match.group(0))
return f"__PROTECTED_EXEC_BLOCK_{len(protected_blocks)-1}__"