| 287 | return r" \\ ".join(parts) |
| 288 | |
| 289 | def replace_command_balanced(tex: str, cmd: str, new_line: str) -> str: |
| 290 | m = re.search(rf"\\{cmd}\b", tex) |
| 291 | if not m: return tex |
| 292 | i = m.end() |
| 293 | if i < len(tex) and tex[i] == '[': |
| 294 | depth = 1; i += 1 |
| 295 | while i < len(tex) and depth: |
| 296 | if tex[i] == '[': depth += 1 |
| 297 | elif tex[i] == ']': depth -= 1 |
| 298 | i += 1 |
| 299 | while i < len(tex) and tex[i].isspace(): i += 1 |
| 300 | if i >= len(tex) or tex[i] != '{': return tex |
| 301 | start = m.start(); j = i; depth = 0; end = None |
| 302 | while j < len(tex): |
| 303 | if tex[j] == '{': depth += 1 |
| 304 | elif tex[j] == '}': |
| 305 | depth -= 1 |
| 306 | if depth == 0: end = j; break |
| 307 | j += 1 |
| 308 | if end is None: return tex |
| 309 | return tex[:start] + new_line + tex[end+1:] |
| 310 | |
| 311 | def format_content_to_latex(content: str) -> str: |
| 312 | """格式化正文内容,自动修复 LaTeX 命令""" |