如何在Jupyter中添加同时兼容Markdown与nbconvert的\newcommand?
Got it, so you want a \newcommand that works both when you're using the notebook live (MathJax renders it properly) AND when you export to PDF via nbconvert? Here's a straightforward combined trick that fixes both issues at once:
First, drop the MathJax-friendly command in a Markdown cell (this makes it active in the notebook immediately):
$\newcommand{\mycustomcmd}{\textbf{My Fancy Command}}$This line won't show up as visible output, but MathJax will register the command for every math cell that comes after it in the notebook.
Next, in that same Markdown cell, add a nbconvert-specific raw LaTeX block wrapped in HTML comments. This ensures the command gets added to the .tex file when you export to PDF:
<!-- raw:: latex --> \newcommand{\mycustomcmd}{\textbf{My Fancy Command}} <!-- endraw -->The comments keep this block hidden in the notebook's rendered view, but nbconvert will spot the
raw:: latexdirective and inject the command straight into the LaTeX preamble during export.
Quick breakdown of why this works:
- Live notebook: The
$\newcommand{...}$is parsed by MathJax, so any later use of\mycustomcmdin math cells will render exactly how you defined it. - PDF export: nbconvert pulls out the content inside the
raw:: latexblock and adds it to the generated .tex file—so when LaTeX compiles the PDF, it recognizes the command just like any other native LaTeX definition.
Pro tip: Keep the command definition identical in both spots to avoid weird inconsistencies between the live notebook and the exported PDF!
内容的提问来源于stack exchange,提问作者weymouth

