本人没有什么贡献,就不投稿了。
使用:
python <filename>.py --help查看用法。
Code(By ChatGPT)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
cpp_to_katex.py
Convert C++ source code into a KaTeX-friendly Markdown display block.
Default palette: Monaco / VS Code Light+ on white background.
Usage:
python3 cpp_to_katex.py main.cpp -o main_katex.md
cat main.cpp | python3 cpp_to_katex.py - > main_katex.md
The generated KaTeX intentionally avoids fragile array preambles like @{...}.
It only uses \begin{array}{r l}, \textcolor, \texttt, and \hspace.
"""
from __future__ import annotations
import argparse
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple
# Monaco / VS Code Light+ inspired palette.
# You can edit these without touching the lexer.
THEMES: Dict[str, Dict[str, str]] = {
"monaco": {
"plain": "#000000",
"line": "#237893",
"keyword": "#0000ff",
"type": "#267f99",
"preproc": "#af00db",
"string": "#a31515",
"number": "#098658",
"comment": "#008000",
"constant": "#001080",
"builtin": "#795e26",
},
# A slightly softer version. Use: --theme soft
"soft": {
"plain": "#1f2328",
"line": "#57606a",
"keyword": "#0550ae",
"type": "#116329",
"preproc": "#8250df",
"string": "#953800",
"number": "#116329",
"comment": "#6e7781",
"constant": "#0a3069",
"builtin": "#6639ba",
},
}
KEYWORDS = {
"alignas", "alignof", "and", "and_eq", "asm", "bitand", "bitor", "break",
"case", "catch", "class", "compl", "concept", "const", "consteval", "constexpr",
"constinit", "const_cast", "continue", "co_await", "co_return", "co_yield",
"decltype", "default", "delete", "do", "dynamic_cast", "else", "enum", "explicit",
"export", "extern", "final", "for", "friend", "goto", "if", "inline", "mutable",
"namespace", "new", "noexcept", "not", "not_eq", "operator", "or", "or_eq",
"override", "private", "protected", "public", "register", "reinterpret_cast",
"requires", "return", "sizeof", "static", "static_assert", "static_cast", "struct",
"switch", "template", "this", "thread_local", "throw", "try", "typedef", "typeid",
"typename", "union", "using", "virtual", "volatile", "while", "xor", "xor_eq",
}
TYPE_WORDS = {
"auto", "bool", "char", "char8_t", "char16_t", "char32_t", "double", "float",
"int", "long", "short", "signed", "unsigned", "void", "wchar_t", "__int128",
"int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t",
"uint64_t", "size_t", "ptrdiff_t", "string", "vector", "pair", "tuple", "array",
"deque", "queue", "priority_queue", "stack", "set", "multiset", "map", "multimap",
"unordered_set", "unordered_map", "bitset", "list", "optional", "variant",
}
CONSTANTS = {
"true", "false", "nullptr", "NULL", "EOF", "stdin", "stdout", "stderr",
"cin", "cout", "cerr", "clog", "endl", "numeric_limits",
}
BUILTINS = {
"__builtin_popcount", "__builtin_popcountll", "__builtin_ctz", "__builtin_ctzll",
"__builtin_clz", "__builtin_clzll", "__builtin_mul_overflow", "__gcd",
"lower_bound", "upper_bound", "sort", "unique", "reverse", "rotate", "min", "max",
"swap", "abs", "gcd", "lcm", "emplace_back", "push_back", "make_pair",
}
IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
NUMBER_RE = re.compile(
r"""
(?:0[xX][0-9A-Fa-f']+(?:[uUlL]*)?)
| (?:0[bB][01']+(?:[uUlL]*)?)
| (?:(?:\d[\d']*)(?:\.\d[\d']*)?(?:[eE][+-]?\d[\d']*)?|(?:\.\d[\d']+(?:[eE][+-]?\d[\d']*)?))(?:[fFlLuU]*)
""",
re.VERBOSE,
)
@dataclass
class Segment:
style: str
text: str
@dataclass
class LexState:
block_comment: bool = False
raw_string_delim: Optional[str] = None
def read_text(path: str) -> str:
if path == "-":
return sys.stdin.read()
return Path(path).read_text(encoding="utf-8")
def emit(segs: List[Segment], style: str, text: str) -> None:
if not text:
return
if segs and segs[-1].style == style:
segs[-1].text += text
else:
segs.append(Segment(style, text))
def consume_quoted(line: str, start: int, quote: str) -> int:
"""Return first index after a normal C/C++ string or char literal on one line."""
i = start + 1
n = len(line)
escaped = False
while i < n:
ch = line[i]
if escaped:
escaped = False
i += 1
continue
if ch == "\\":
escaped = True
i += 1
continue
i += 1
if ch == quote:
break
return i
def try_raw_string_start(line: str, i: int) -> Optional[Tuple[str, int]]:
"""
Recognize C++ raw string start R"delim(.
Return (delimiter, index_after_start) or None.
"""
if i + 1 >= len(line) or line[i] != "R" or line[i + 1] != '"':
return None
j = i + 2
while j < len(line) and line[j] != "(":
# C++ raw string delimiters cannot contain spaces, parens, backslash.
if line[j].isspace() or line[j] in "\\)":
return None
j += 1
if j >= len(line):
return None
return line[i + 2 : j], j + 1
def lex_code_part(line: str, state: LexState) -> Tuple[List[Segment], LexState]:
segs: List[Segment] = []
i, n = 0, len(line)
while i < n:
if state.raw_string_delim is not None:
end_pat = ")" + state.raw_string_delim + '"'
j = line.find(end_pat, i)
if j == -1:
emit(segs, "string", line[i:])
i = n
else:
emit(segs, "string", line[i : j + len(end_pat)])
i = j + len(end_pat)
state.raw_string_delim = None
continue
if state.block_comment:
j = line.find("*/", i)
if j == -1:
emit(segs, "comment", line[i:])
i = n
else:
emit(segs, "comment", line[i : j + 2])
i = j + 2
state.block_comment = False
continue
ch = line[i]
# Whitespace.
if ch.isspace():
j = i + 1
while j < n and line[j].isspace():
j += 1
emit(segs, "plain", line[i:j])
i = j
continue
# Comments.
if line.startswith("//", i):
emit(segs, "comment", line[i:])
break
if line.startswith("/*", i):
j = line.find("*/", i + 2)
if j == -1:
emit(segs, "comment", line[i:])
state.block_comment = True
break
emit(segs, "comment", line[i : j + 2])
i = j + 2
continue
# Raw string.
raw = try_raw_string_start(line, i)
if raw is not None:
delim, after_start = raw
end_pat = ")" + delim + '"'
j = line.find(end_pat, after_start)
if j == -1:
emit(segs, "string", line[i:])
state.raw_string_delim = delim
break
emit(segs, "string", line[i : j + len(end_pat)])
i = j + len(end_pat)
continue
# Normal string or char literal.
if ch == '"' or ch == "'":
j = consume_quoted(line, i, ch)
emit(segs, "string", line[i:j])
i = j
continue
# Number.
m = NUMBER_RE.match(line, i)
if m is not None:
emit(segs, "number", m.group(0))
i = m.end()
continue
# Identifier / keyword.
m = IDENT_RE.match(line, i)
if m is not None:
word = m.group(0)
if word in TYPE_WORDS:
style = "type"
elif word in KEYWORDS:
style = "keyword"
elif word in CONSTANTS:
style = "constant"
elif word in BUILTINS or word.startswith("__builtin_"):
style = "builtin"
else:
style = "plain"
emit(segs, style, word)
i = m.end()
continue
# Punctuation / operators.
emit(segs, "plain", ch)
i += 1
return segs, state
def lex_preprocessor_line(line: str, state: LexState) -> Tuple[List[Segment], LexState]:
"""Highlight #directive, then lex the rest normally."""
segs: List[Segment] = []
m = re.match(r"(\s*)(#\s*[A-Za-z_][A-Za-z0-9_]*)(.*)$", line)
if not m:
return lex_code_part(line, state)
leading, directive, rest = m.groups()
emit(segs, "plain", leading)
emit(segs, "preproc", directive)
# Common #include <...> / "..." case.
if directive.replace(" ", "") == "#include":
rest_m = re.match(r"(\s*)(<[^>]*>|\"(?:\\.|[^\"])*\")(.*)$", rest)
if rest_m:
emit(segs, "plain", rest_m.group(1))
emit(segs, "string", rest_m.group(2))
tail, state = lex_code_part(rest_m.group(3), state)
segs.extend(tail)
return segs, state
tail, state = lex_code_part(rest, state)
segs.extend(tail)
return segs, state
def lex_cpp(code: str, tab_width: int = 4) -> List[List[Segment]]:
# split('\n') preserves a final empty line only when the source ends with \n;
# for code display it is usually cleaner to drop exactly that final empty line.
lines = code.expandtabs(tab_width).split("\n")
if lines and lines[-1] == "":
lines.pop()
state = LexState()
result: List[List[Segment]] = []
for line in lines:
if not state.block_comment and state.raw_string_delim is None and line.lstrip().startswith("#"):
segs, state = lex_preprocessor_line(line, state)
else:
segs, state = lex_code_part(line, state)
result.append(segs)
return result
def tex_escape_texttt(s: str) -> str:
"""Escape text so it can be placed inside \texttt{...} in KaTeX."""
out: List[str] = []
for ch in s:
if ch == "\\":
out.append(r"\textbackslash{}")
elif ch == "{":
out.append(r"\{")
elif ch == "}":
out.append(r"\}")
elif ch == "#":
out.append(r"\#")
elif ch == "$":
out.append(r"\$")
elif ch == "%":
out.append(r"\%")
elif ch == "&":
out.append(r"\&")
elif ch == "_":
out.append(r"\_")
elif ch == "^":
out.append(r"\textasciicircum{}")
elif ch == "~":
out.append(r"\textasciitilde{}")
else:
out.append(ch)
return "".join(out)
def hspace(count: int, space_em: float) -> str:
amount = count * space_em
# Avoid ugly 2.0800000000000001 in output.
text = f"{amount:.4f}".rstrip("0").rstrip(".")
if text == "":
text = "0"
return rf"\hspace{{{text}em}}"
def color_wrap(style: str, body: str, colors: Dict[str, str], always_color: bool = False) -> str:
color = colors.get(style, colors["plain"])
if always_color or style != "plain":
return rf"\textcolor{{{color}}}{{{body}}}"
return body
def render_segment(seg: Segment, colors: Dict[str, str], space_em: float, always_color: bool) -> str:
parts: List[str] = []
buf: List[str] = []
spaces = 0
def flush_text() -> None:
nonlocal buf
if buf:
raw = "".join(buf)
body = rf"\texttt{{{tex_escape_texttt(raw)}}}"
parts.append(color_wrap(seg.style, body, colors, always_color=always_color))
buf = []
def flush_spaces() -> None:
nonlocal spaces
if spaces:
parts.append(hspace(spaces, space_em))
spaces = 0
for ch in seg.text:
if ch == " ":
flush_text()
spaces += 1
else:
flush_spaces()
buf.append(ch)
flush_text()
flush_spaces()
return "".join(parts)
def render_line(segs: List[Segment], colors: Dict[str, str], space_em: float, always_color: bool) -> str:
if not segs:
return r"{}"
rendered = "".join(render_segment(seg, colors, space_em, always_color) for seg in segs)
return rendered if rendered else r"{}"
def build_katex(
lexed_lines: List[List[Segment]],
*,
colors: Dict[str, str],
line_numbers: bool = True,
start_line: int = 1,
size: str = "small",
arraystretch: float = 1.22,
row_gap_em: float = 0.06,
space_em: float = 0.52,
always_color_plain: bool = False,
fenced_math: bool = False,
comment_header: bool = True,
) -> str:
if size not in {"tiny", "scriptsize", "footnotesize", "small", "normalsize", "large"}:
raise ValueError(f"unsupported size: {size}")
lines: List[str] = []
if comment_header:
lines.append("<!-- generated by cpp_to_katex.py; KaTeX-compatible, plain array columns -->")
lines.append("")
open_delim, close_delim = ("```math", "```") if fenced_math else ("$$", "$$")
lines.append(open_delim)
lines.append(rf"\{size}")
lines.append(rf"\def\arraystretch{{{arraystretch}}}")
if line_numbers:
lines.append(r"\begin{array}{r l}")
for idx, segs in enumerate(lexed_lines):
line_no = str(start_line + idx)
ln = rf"\textcolor{{{colors['line']}}}{{\texttt{{{line_no}}}}}"
code = render_line(segs, colors, space_em, always_color_plain)
row = f"{ln} & {code}"
if idx + 1 < len(lexed_lines):
row += rf" \\[{row_gap_em}em]"
lines.append(row)
lines.append(r"\end{array}")
else:
lines.append(r"\begin{array}{l}")
for idx, segs in enumerate(lexed_lines):
code = render_line(segs, colors, space_em, always_color_plain)
row = code
if idx + 1 < len(lexed_lines):
row += rf" \\[{row_gap_em}em]"
lines.append(row)
lines.append(r"\end{array}")
lines.append(close_delim)
lines.append("")
return "\n".join(lines)
def parse_args(argv: Optional[Iterable[str]] = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Convert C++ source into a KaTeX Markdown block with Monaco-like syntax colors."
)
parser.add_argument("input", help="input .cpp file, or '-' for stdin")
parser.add_argument("-o", "--output", help="output Markdown file; default: stdout")
parser.add_argument("--theme", choices=sorted(THEMES.keys()), default="monaco")
parser.add_argument("--no-line-number", action="store_true", help="omit line numbers")
parser.add_argument("--start-line", type=int, default=1, help="first displayed line number")
parser.add_argument("--size", default="small", choices=["tiny", "scriptsize", "footnotesize", "small", "normalsize", "large"])
parser.add_argument("--arraystretch", type=float, default=1.22, help="KaTeX array row-height multiplier")
parser.add_argument("--row-gap-em", type=float, default=0.06, help="extra gap after each row, in em")
parser.add_argument("--space-em", type=float, default=0.52, help="width of one source-code space, in em")
parser.add_argument("--tab-width", type=int, default=4, help="tab expansion width")
parser.add_argument("--fenced-math", action="store_true", help="use ```math fence instead of $$ display math")
parser.add_argument("--always-color-plain", action="store_true", help="wrap plain text in black \\textcolor too")
parser.add_argument("--no-header", action="store_true", help="do not add an HTML comment header")
return parser.parse_args(argv)
def main(argv: Optional[Iterable[str]] = None) -> int:
args = parse_args(argv)
code = read_text(args.input)
lexed = lex_cpp(code, tab_width=args.tab_width)
md = build_katex(
lexed,
colors=THEMES[args.theme],
line_numbers=not args.no_line_number,
start_line=args.start_line,
size=args.size,
arraystretch=args.arraystretch,
row_gap_em=args.row_gap_em,
space_em=args.space_em,
always_color_plain=args.always_color_plain,
fenced_math=args.fenced_math,
comment_header=not args.no_header,
)
if args.output:
Path(args.output).write_text(md, encoding="utf-8")
else:
sys.stdout.write(md)
return 0
if __name__ == "__main__":
raise SystemExit(main())