You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jupyter中添加同时兼容Markdown与nbconvert的\newcommand?

Dual-Working \newcommand for Jupyter Notebook (Live + PDF Export)

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:: latex directive 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 \mycustomcmd in math cells will render exactly how you defined it.
  • PDF export: nbconvert pulls out the content inside the raw:: latex block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:18:12