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 1001 1002 1003 1004
|
""" Markdown 到 HTML 转换工具
功能: - 将 Markdown 文件转换为 HTML 文件 - 自动生成目录(TOC) - 支持语法高亮(需要 Pygments) - 支持递归处理目录 - 保持源文件目录结构
使用方式: # 转换单个文件 python parsedown.py -f input.md
# 转换单个文件并指定输出 python parsedown.py -f input.md -o output.html
# 转换目录下所有 .md 文件(递归处理子目录) python parsedown.py -d ./docs
# 转换目录并指定输出目录 python parsedown.py -d ./docs -o ./html
参数说明: -f, --file FILE 指定要转换的 markdown 文件 -d, --dir DIR 指定要转换的目录(递归处理子目录) -o, --output OUTPUT 指定输出目录或文件路径 -h, --help 显示帮助信息
依赖: - markdown>=3.5.0 - pymdown-extensions>=10.0(用于 Mermaid 图表支持) - pygments>=2.16.0(可选,用于代码高亮)
示例: python parsedown.py -f README.md python parsedown.py -f README.md -o docs/index.html python parsedown.py -d ./markdown_files python parsedown.py -d ./markdown_files -o ./html_output """
import markdown import argparse from pathlib import Path
def mermaid_formatter(source, language, css_class, options, md, **kwargs): return f'<pre class="mermaid">{source}</pre>'
class Parsedown: def __init__(self): self.extensions = [ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', 'markdown.extensions.tables', 'markdown.extensions.attr_list', 'markdown.extensions.def_list', 'markdown.extensions.abbr', 'markdown.extensions.footnotes', 'markdown.extensions.md_in_html', 'pymdownx.superfences', ] self.extension_configs = { 'markdown.extensions.toc': { 'permalink': True, 'permalink_title': '链接到此标题', 'baselevel': 1, 'toc_depth': 6, }, 'markdown.extensions.codehilite': { 'lin_css_class': 'lineno', }, 'pymdownx.superfences': { 'custom_fences': [ { 'name': 'mermaid', 'class': 'mermaid', 'format': mermaid_formatter, } ] }, } def text(self, markdown_text): md = markdown.Markdown( extensions=self.extensions, extension_configs=self.extension_configs ) html = md.convert(markdown_text) toc_html = md.toc return html, toc_html
def get_html_template(): return '''<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{title}</title> <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script> <script> mermaid.initialize({{ startOnLoad: true, theme: 'default', themeVariables: {{ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }} }}); </script> <style> * {{ margin: 0; padding: 0; box-sizing: border-box; }} body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; line-height: 1.6; background: #f5f5f5; padding: 20px; }} .container {{ max-width: 900px; margin: 0 auto; background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }} .content {{ line-height: 1.8; }} .content h1, .content h2, .content h3, .content h4, .content h5, .content h6 {{ margin-top: 24px; margin-bottom: 16px; font-weight: 600; }} .content h1 {{ font-size: 2em; border-bottom: 1px solid #eee; padding-bottom: 10px; }} .content h2 {{ font-size: 1.5em; }} .content h3 {{ font-size: 1.25em; }} .content p {{ margin-bottom: 16px; }} .content code {{ background: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; font-size: 0.9em; }} .content pre {{ background: #f4f4f4; padding: 16px; border-radius: 6px; overflow-x: auto; margin-bottom: 16px; }} .content pre code {{ background: transparent; padding: 0; }} .codehilite {{ background: #f4f4f4; padding: 16px; border-radius: 6px; overflow-x: auto; margin-bottom: 16px; }} .codehilite pre {{ background: transparent; padding: 0; margin: 0; }} .codehilite code {{ background: transparent; padding: 0; font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; font-size: 0.9em; line-height: 1.5; }} .codehilite .k {{ color: #000080; font-weight: bold; }} .codehilite .kt {{ color: #000080; font-weight: bold; }} .codehilite .kd {{ color: #000080; font-weight: bold; }} .codehilite .kn {{ color: #000080; font-weight: bold; }} .codehilite .kp {{ color: #000080; font-weight: bold; }} .codehilite .kr {{ color: #000080; font-weight: bold; }} .codehilite .nf {{ color: #0000FF; }} .codehilite .nc {{ color: #0000FF; }} .codehilite .nn {{ color: #0000FF; }} .codehilite .nb {{ color: #008000; }} .codehilite .bp {{ color: #008000; }} .codehilite .s {{ color: #BA2121; }} .codehilite .s1 {{ color: #BA2121; }} .codehilite .s2 {{ color: #BA2121; }} .codehilite .sd {{ color: #BA2121; font-style: italic; }} .codehilite .se {{ color: #BA2121; }} .codehilite .sh {{ color: #BA2121; }} .codehilite .si {{ color: #BA2121; }} .codehilite .sx {{ color: #BA2121; }} .codehilite .sr {{ color: #BA2121; }} .codehilite .ss {{ color: #19177C; }} .codehilite .sc {{ color: #BA2121; }} .codehilite .m {{ color: #666666; }} .codehilite .mf {{ color: #666666; }} .codehilite .mh {{ color: #666666; }} .codehilite .mi {{ color: #666666; }} .codehilite .mo {{ color: #666666; }} .codehilite .il {{ color: #666666; }} .codehilite .c {{ color: #408080; font-style: italic; }} .codehilite .cm {{ color: #408080; font-style: italic; }} .codehilite .cp {{ color: #BC7A00; }} .codehilite .c1 {{ color: #408080; font-style: italic; }} .codehilite .cs {{ color: #408080; font-style: italic; }} .codehilite .kc {{ color: #008000; font-weight: bold; }} .codehilite .o {{ color: #666666; }} .codehilite .ow {{ color: #AA22FF; font-weight: bold; }} .codehilite .p {{ color: #666666; }} .codehilite .w {{ color: #bbbbbb; }} .codehilite .ch {{ color: #008000; }} .codehilite .gh {{ color: #000080; font-weight: bold; }} .codehilite .gu {{ color: #800080; font-weight: bold; }} .codehilite .gt {{ color: #0044DD; }} .codehilite .gi {{ color: #008000; }} .codehilite .go {{ color: #888888; }} .codehilite .gp {{ color: #000080; font-weight: bold; }} .codehilite .gs {{ color: #888888; font-weight: bold; }} .codehilite .gr {{ color: #FF0000; }} .codehilite .ge {{ color: #FF0000; font-style: italic; }} .codehilite .gd {{ color: #A00000; }} .codehilite .ni {{ color: #999999; font-weight: bold; }} .codehilite .ne {{ color: #D2413A; font-weight: bold; }} .codehilite .na {{ color: #7D9029; }} .codehilite .nt {{ color: #000080; font-weight: bold; }} .codehilite .nd {{ color: #A2F; }} .codehilite .no {{ color: #880000; }} .codehilite .nv {{ color: #19177C; }} .codehilite .vc {{ color: #19177C; }} .codehilite .vg {{ color: #19177C; }} .codehilite .vi {{ color: #19177C; }} .codehilite .vm {{ color: #19177C; }} .mermaid-wrapper {{ position: relative; background: #f8f9fa; padding: 20px; border-radius: 6px; margin: 16px 0; text-align: center; overflow-x: auto; }} .mermaid-wrapper .mermaid {{ background: transparent; padding: 0; margin: 0; }} .mermaid-fullscreen-btn {{ position: absolute; top: 8px; right: 8px; width: 32px; height: 32px; border: none; background: rgba(0, 0, 0, 0.08); border-radius: 6px; cursor: pointer; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.2s, background 0.2s; z-index: 1; }} .mermaid-wrapper:hover .mermaid-fullscreen-btn {{ opacity: 1; }} .mermaid-fullscreen-btn:hover {{ background: rgba(0, 0, 0, 0.15); }} .mermaid-fullscreen-btn svg {{ width: 18px; height: 18px; color: #555; }} .mermaid-overlay {{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 10000; display: flex; flex-direction: column; align-items: center; justify-content: center; opacity: 0; visibility: hidden; transition: opacity 0.3s, visibility 0.3s; }} .mermaid-overlay.active {{ opacity: 1; visibility: visible; }} .mermaid-overlay-header {{ position: absolute; top: 0; left: 0; right: 0; display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; background: rgba(0, 0, 0, 0.3); z-index: 1; }} .mermaid-overlay-title {{ color: #ccc; font-size: 14px; }} .mermaid-overlay-controls {{ display: flex; gap: 8px; align-items: center; }} .mermaid-overlay-btn {{ width: 36px; height: 36px; border: 1px solid rgba(255, 255, 255, 0.3); background: rgba(255, 255, 255, 0.1); border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 18px; transition: background 0.2s; }} .mermaid-overlay-btn:hover {{ background: rgba(255, 255, 255, 0.2); }} .mermaid-overlay-btn.close-btn {{ border-color: rgba(255, 100, 100, 0.5); background: rgba(255, 100, 100, 0.15); font-size: 20px; }} .mermaid-overlay-btn.close-btn:hover {{ background: rgba(255, 100, 100, 0.3); }} .mermaid-overlay-body {{ flex: 1; display: flex; align-items: center; justify-content: center; width: 100%; overflow: hidden; cursor: grab; padding: 70px 24px 24px; }} .mermaid-overlay-body.dragging {{ cursor: grabbing; }} .mermaid-overlay-body svg {{ max-width: none !important; max-height: none !important; transition: none; background: #fff; border-radius: 4px; }} .mermaid-zoom-indicator {{ position: absolute; bottom: 20px; right: 24px; color: rgba(255, 255, 255, 0.5); font-size: 13px; pointer-events: none; }} .content ul, .content ol {{ margin-left: 24px; margin-bottom: 16px; }} .content blockquote {{ border-left: 4px solid #ddd; padding-left: 16px; color: #666; margin: 16px 0; }} .content a {{ color: #0066cc; text-decoration: none; }} .content a:hover {{ text-decoration: underline; }} .content table {{ border-collapse: collapse; width: 100%; margin-bottom: 16px; }} .content table th, .content table td {{ border: 1px solid #ddd; padding: 8px 12px; text-align: left; }} .content table th {{ background: #f4f4f4; font-weight: 600; }} .toc {{ background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 30px; border: 1px solid #e9ecef; }} .toc-header {{ display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }} .toc-title {{ font-size: 18px; font-weight: 600; color: #333; margin: 0; }} .toc-toggle {{ background: none; border: none; color: #0066cc; cursor: pointer; font-size: 14px; padding: 4px 8px; border-radius: 4px; transition: background 0.2s; }} .toc-toggle:hover {{ background: #e9ecef; }} .toc-content {{ display: block; }} .toc-content.collapsed {{ display: none; }} .toc ul {{ list-style: none; padding-left: 0; }} .toc ul ul {{ padding-left: 20px; }} .toc li {{ margin: 8px 0; }} .toc a {{ color: #0066cc; text-decoration: none; }} .toc a:hover {{ text-decoration: underline; }} .toc .toc-h1 {{ font-weight: 500; }} .toc .toc-h2 {{ font-weight: 400; }} .toc .toc-h3 {{ font-weight: 400; font-size: 0.95em; }} .toc .toc-h4 {{ font-weight: 400; font-size: 0.9em; }} .toc .toc-h5 {{ font-weight: 400; font-size: 0.85em; }} .toc .toc-h6 {{ font-weight: 400; font-size: 0.8em; }} .toc-h2 .toc-h2 {{ padding-left: 10px; }} .toc-h3 .toc-h3 {{ padding-left: 10px; }} .toc-h4 .toc-h4 {{ padding-left: 10px; }} .toc-h5 .toc-h5 {{ padding-left: 10px; }} .toc-h6 .toc-h6 {{ padding-left: 10px; }} .floating-actions {{ position: fixed; bottom: 30px; right: 30px; display: flex; flex-direction: column; gap: 12px; }} .floating-btn {{ width: 50px; height: 50px; border-radius: 50%; background: #0066cc; color: #fff; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(0,102,204,0.3); transition: all 0.3s; text-decoration: none; }} .floating-btn:hover {{ background: #0052a3; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0,102,204,0.4); }} .floating-btn svg {{ width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; }} @media (max-width: 768px) {{ .floating-actions {{ display: none; }} .container {{ padding: 15px; }} }} </style> <script> function toggleToc() {{ var tocContent = document.getElementById('toc-content'); var toggleBtn = document.getElementById('toc-toggle'); if (tocContent.classList.contains('collapsed')) {{ tocContent.classList.remove('collapsed'); toggleBtn.textContent = '收起'; }} else {{ tocContent.classList.add('collapsed'); toggleBtn.textContent = '展开'; }} }} </script> <script> var mermaidOverlayState = {{ scale: 1, translateX: 0, translateY: 0, isDragging: false, startX: 0, startY: 0, lastTranslateX: 0, lastTranslateY: 0, svgClone: null }};
function initMermaidFullscreen() {{ var mermaidElements = document.querySelectorAll('.mermaid'); mermaidElements.forEach(function(el) {{ if (el.closest('.mermaid-wrapper')) return; var wrapper = document.createElement('div'); wrapper.className = 'mermaid-wrapper'; var btn = document.createElement('button'); btn.className = 'mermaid-fullscreen-btn'; btn.title = '全屏查看'; btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"></path><path d="M21 8V5a2 2 0 0 0-2-2h-3"></path><path d="M3 16v3a2 2 0 0 0 2 2h3"></path><path d="M16 21h3a2 2 0 0 0 2-2v-3"></path></svg>'; btn.addEventListener('click', function(e) {{ e.stopPropagation(); openMermaidFullscreen(wrapper); }}); el.parentNode.insertBefore(wrapper, el); wrapper.appendChild(el); wrapper.appendChild(btn); }}); }}
function openMermaidFullscreen(wrapper) {{ var existing = document.getElementById('mermaid-overlay'); if (existing) existing.remove();
var overlay = document.createElement('div'); overlay.id = 'mermaid-overlay'; overlay.className = 'mermaid-overlay';
var header = document.createElement('div'); header.className = 'mermaid-overlay-header';
var title = document.createElement('span'); title.className = 'mermaid-overlay-title'; title.textContent = 'Mermaid 图表 \u2014 滚轮缩放 \u00B7 拖拽移动 \u00B7 ESC 退出';
var controls = document.createElement('div'); controls.className = 'mermaid-overlay-controls';
var zoomInBtn = document.createElement('button'); zoomInBtn.className = 'mermaid-overlay-btn'; zoomInBtn.innerHTML = '+'; zoomInBtn.title = '放大'; zoomInBtn.addEventListener('click', function(e) {{ e.stopPropagation(); mermaidZoom(0.2); }});
var zoomOutBtn = document.createElement('button'); zoomOutBtn.className = 'mermaid-overlay-btn'; zoomOutBtn.innerHTML = '\u2212'; zoomOutBtn.title = '缩小'; zoomOutBtn.addEventListener('click', function(e) {{ e.stopPropagation(); mermaidZoom(-0.2); }});
var resetBtn = document.createElement('button'); resetBtn.className = 'mermaid-overlay-btn'; resetBtn.innerHTML = '\u21BA'; resetBtn.title = '重置'; resetBtn.addEventListener('click', function(e) {{ e.stopPropagation(); mermaidResetView(); }});
var closeBtn = document.createElement('button'); closeBtn.className = 'mermaid-overlay-btn close-btn'; closeBtn.innerHTML = '\u2715'; closeBtn.title = '关闭 (ESC)'; closeBtn.addEventListener('click', function(e) {{ e.stopPropagation(); closeMermaidFullscreen(); }});
controls.appendChild(zoomInBtn); controls.appendChild(zoomOutBtn); controls.appendChild(resetBtn); controls.appendChild(closeBtn); header.appendChild(title); header.appendChild(controls);
var body = document.createElement('div'); body.className = 'mermaid-overlay-body';
var svgEl = wrapper.querySelector('svg'); if (svgEl) {{ var clone = svgEl.cloneNode(true); mermaidOverlayState.svgClone = clone; body.appendChild(clone); }} else {{ var preEl = wrapper.querySelector('.mermaid'); if (preEl) {{ var clone = preEl.cloneNode(true); mermaidOverlayState.svgClone = clone; body.appendChild(clone); }} }}
var zoomIndicator = document.createElement('div'); zoomIndicator.className = 'mermaid-zoom-indicator'; zoomIndicator.id = 'mermaid-zoom-indicator'; zoomIndicator.textContent = '100%';
overlay.appendChild(header); overlay.appendChild(body); overlay.appendChild(zoomIndicator);
overlay.addEventListener('click', function(e) {{ if (e.target === overlay || e.target === body) {{ closeMermaidFullscreen(); }} }});
document.body.appendChild(overlay); document.body.style.overflow = 'hidden';
mermaidOverlayState.scale = 1; mermaidOverlayState.translateX = 0; mermaidOverlayState.translateY = 0; updateMermaidTransform();
requestAnimationFrame(function() {{ overlay.classList.add('active'); }});
body.addEventListener('wheel', mermaidWheelHandler, {{ passive: false }}); body.addEventListener('mousedown', mermaidDragStart); body.addEventListener('touchstart', mermaidTouchStart, {{ passive: false }}); document.addEventListener('mousemove', mermaidDragMove); document.addEventListener('mouseup', mermaidDragEnd); document.addEventListener('touchmove', mermaidTouchMove, {{ passive: false }}); document.addEventListener('touchend', mermaidTouchEnd); document.addEventListener('keydown', mermaidEscHandler); }}
function closeMermaidFullscreen() {{ var overlay = document.getElementById('mermaid-overlay'); if (!overlay) return; overlay.classList.remove('active'); document.body.style.overflow = ''; var body = overlay.querySelector('.mermaid-overlay-body'); if (body) {{ body.removeEventListener('wheel', mermaidWheelHandler); body.removeEventListener('mousedown', mermaidDragStart); body.removeEventListener('touchstart', mermaidTouchStart); }} document.removeEventListener('mousemove', mermaidDragMove); document.removeEventListener('mouseup', mermaidDragEnd); document.removeEventListener('touchmove', mermaidTouchMove); document.removeEventListener('touchend', mermaidTouchEnd); document.removeEventListener('keydown', mermaidEscHandler); setTimeout(function() {{ if (overlay.parentNode) overlay.remove(); }}, 300); mermaidOverlayState.svgClone = null; }}
function mermaidZoom(delta) {{ var newScale = mermaidOverlayState.scale + delta; newScale = Math.max(0.1, Math.min(5, newScale)); mermaidOverlayState.scale = newScale; updateMermaidTransform(); }}
function mermaidResetView() {{ mermaidOverlayState.scale = 1; mermaidOverlayState.translateX = 0; mermaidOverlayState.translateY = 0; updateMermaidTransform(); }}
function updateMermaidTransform() {{ if (!mermaidOverlayState.svgClone) return; var s = mermaidOverlayState.scale; var tx = mermaidOverlayState.translateX; var ty = mermaidOverlayState.translateY; mermaidOverlayState.svgClone.style.transform = 'translate(' + tx + 'px, ' + ty + 'px) scale(' + s + ')'; mermaidOverlayState.svgClone.style.transformOrigin = 'center center'; var indicator = document.getElementById('mermaid-zoom-indicator'); if (indicator) {{ indicator.textContent = Math.round(s * 100) + '%'; }} }}
function mermaidWheelHandler(e) {{ e.preventDefault(); var delta = e.deltaY > 0 ? -0.1 : 0.1; mermaidZoom(delta); }}
function mermaidDragStart(e) {{ if (e.target.closest('.mermaid-overlay-header')) return; mermaidOverlayState.isDragging = true; mermaidOverlayState.startX = e.clientX; mermaidOverlayState.startY = e.clientY; mermaidOverlayState.lastTranslateX = mermaidOverlayState.translateX; mermaidOverlayState.lastTranslateY = mermaidOverlayState.translateY; var body = document.querySelector('.mermaid-overlay-body'); if (body) body.classList.add('dragging'); }}
function mermaidDragMove(e) {{ if (!mermaidOverlayState.isDragging) return; var dx = e.clientX - mermaidOverlayState.startX; var dy = e.clientY - mermaidOverlayState.startY; mermaidOverlayState.translateX = mermaidOverlayState.lastTranslateX + dx; mermaidOverlayState.translateY = mermaidOverlayState.lastTranslateY + dy; updateMermaidTransform(); }}
function mermaidDragEnd() {{ mermaidOverlayState.isDragging = false; var body = document.querySelector('.mermaid-overlay-body'); if (body) body.classList.remove('dragging'); }}
function mermaidTouchStart(e) {{ if (e.touches.length === 1) {{ if (e.target.closest('.mermaid-overlay-header')) return; e.preventDefault(); mermaidOverlayState.isDragging = true; mermaidOverlayState.startX = e.touches[0].clientX; mermaidOverlayState.startY = e.touches[0].clientY; mermaidOverlayState.lastTranslateX = mermaidOverlayState.translateX; mermaidOverlayState.lastTranslateY = mermaidOverlayState.translateY; }} }}
function mermaidTouchMove(e) {{ if (!mermaidOverlayState.isDragging || e.touches.length !== 1) return; e.preventDefault(); var dx = e.touches[0].clientX - mermaidOverlayState.startX; var dy = e.touches[0].clientY - mermaidOverlayState.startY; mermaidOverlayState.translateX = mermaidOverlayState.lastTranslateX + dx; mermaidOverlayState.translateY = mermaidOverlayState.lastTranslateY + dy; updateMermaidTransform(); }}
function mermaidTouchEnd() {{ mermaidOverlayState.isDragging = false; }}
function mermaidEscHandler(e) {{ if (e.key === 'Escape') {{ closeMermaidFullscreen(); }} }}
(function() {{ var initialized = false; var observer = new MutationObserver(function() {{ if (initialized) return; var svgElements = document.querySelectorAll('.mermaid svg, .mermaid[data-processed]'); if (svgElements.length > 0) {{ initialized = true; observer.disconnect(); setTimeout(function() {{ initMermaidFullscreen(); }}, 100); }} }}); observer.observe(document.documentElement, {{ childList: true, subtree: true }}); }})(); </script> </head> <body> <div class="container"> {toc} <div class="content"> {content} </div> <div class="floating-actions"> <button class="floating-btn" onclick="window.scrollTo({{top: 0, behavior: 'smooth'}})" title="回到顶部"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <polyline points="18 15 12 9 6 15"></polyline> </svg> </button> </div> </div> </body> </html>'''
def parse_front_matter(markdown_content): lines = markdown_content.split('\n') if not lines or not lines[0].strip() == '---': return None, markdown_content front_matter = [] content_lines = [] in_front_matter = True front_matter_count = 0 for line in lines: if in_front_matter: if line.strip() == '---': front_matter_count += 1 if front_matter_count == 2: in_front_matter = False continue front_matter.append(line) else: content_lines.append(line) if front_matter_count < 2: return None, markdown_content content_text = '\n'.join(content_lines) front_matter_dict = {} for line in front_matter: if ':' in line: key, value = line.split(':', 1) key = key.strip() value = value.strip() front_matter_dict[key] = value return front_matter_dict, content_text
def convert_markdown_to_html(input_path, output_path=None): input_path = Path(input_path) if not input_path.exists(): print(f"错误: 文件不存在 - {input_path}") return False if input_path.suffix != '.md': print(f"错误: 文件不是 .md 格式 - {input_path}") return False if output_path is None: output_path = input_path.with_suffix('.html') else: output_path = Path(output_path) if output_path.is_dir(): output_path = output_path / input_path.with_suffix('.html').name try: with open(input_path, 'r', encoding='utf-8') as f: markdown_content = f.read() front_matter, content = parse_front_matter(markdown_content) parsedown = Parsedown() html_content, toc_html = parsedown.text(content) title = input_path.stem if front_matter and 'title' in front_matter: title = front_matter['title'] toc_section = '' if toc_html.strip(): toc_section = f'<div class="toc"><div class="toc-header"><h3 class="toc-title">目录</h3><button class="toc-toggle" id="toc-toggle" onclick="toggleToc()">收起</button></div><div class="toc-content" id="toc-content">{toc_html}</div></div>' template = get_html_template() full_html = template.format( title=title, toc=toc_section, content=html_content ) output_path.parent.mkdir(parents=True, exist_ok=True) with open(output_path, 'w', encoding='utf-8') as f: f.write(full_html) print(f"成功: {input_path} -> {output_path}") return True except Exception as e: print(f"错误: 转换失败 {input_path} - {e}") return False
def process_directory(input_dir, output_dir=None): input_dir = Path(input_dir) if not input_dir.exists() or not input_dir.is_dir(): print(f"错误: 目录不存在 - {input_dir}") return False if output_dir is None: output_dir = input_dir else: output_dir = Path(output_dir) success_count = 0 total_count = 0 for md_file in input_dir.rglob('*.md'): total_count += 1 relative_path = md_file.relative_to(input_dir) output_file = output_dir / relative_path.with_suffix('.html') if convert_markdown_to_html(md_file, output_file): success_count += 1 print(f"\n转换完成: {success_count}/{total_count} 个文件成功") return success_count == total_count
def main(): parser = argparse.ArgumentParser( description='Markdown 到 HTML 转换工具,支持目录和目录生成', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' 示例: # 转换单个文件 python parsedown.py -f input.md # 转换单个文件并指定输出 python parsedown.py -f input.md -o output.html # 转换目录下所有 .md 文件 python parsedown.py -d ./docs # 转换目录并指定输出目录 python parsedown.py -d ./docs -o ./html ''' ) parser.add_argument( '-f', '--file', type=str, help='指定要转换的 markdown 文件' ) parser.add_argument( '-d', '--dir', type=str, help='指定要转换的目录(递归处理子目录)' ) parser.add_argument( '-o', '--output', type=str, help='指定输出目录或文件路径' ) args = parser.parse_args() if not args.file and not args.dir: parser.print_help() return 1 if args.file and args.dir: print("错误: 不能同时指定文件和目录") return 1 if args.file: success = convert_markdown_to_html(args.file, args.output) return 0 if success else 1 if args.dir: success = process_directory(args.dir, args.output) return 0 if success else 1 return 0
if __name__ == '__main__': exit(main())
|