# How to define a macro in a Jupyter cell?

Hi!

I want to define a macro in a Markdown text cell of a Jupyter notebook. But it seems that we cannot define it.

For example, I want to define a macro which formats vectors. The code in the cell is:

\newcommand{\vect}[1]{{\mathbf{\boldsymbol{{#1}}}}}

This is the vector $\vect{x}$.


The rendering is shows the “newcommand” statement, and I do not want that.

A possible way to define a macro in a Jupyter cell is to put a dollar in front of and after the macro.

$\newcommand{\vect}[1]{{\mathbf{\boldsymbol{{#1}}}}}$
This is the vector $\vect{x}$.


and the rendering is:

This is the trick used at Latex macros in Jupyter (iPython) notebook not rendered by github, but the topic is slightly different.

Is this a correct way to solve this?

Best regards,

Michaël

PS

Michael,

In a jupyter notebook markdown cell I can enter a new LaTex command like:

$\newcommand{\partials}[2]{\dfrac{\partial #1}{\partial #2}}$

and then use it as:

$$\partials{L’}{q_j}$$.

In the notebook, the newcommand line will be hidden and the use of the \partials command works as expected. It displays a nice partial derivative.

BUT when I download the notebook as PDF via LaTex I get an error:

! Undefined control sequence.
l.537 [\partials
{L’}{q_j}]
?
! Emergency stop.

I can work around the error by downloading to TeX, opening the file in an editor (say GNOME LaTeX), and manually moving the line:

$$\newcommand{\partials}[2]{\dfrac{\partial #1}{\partial #2}}$$

from the document body up into the preamble and deleting the unneeded $$and$$. I can then save the tex file and compile to get a correct display in the PDF document. A workaround that complex isn’t much of a workaround.


\vskip-\parskip
\vskip-\baselineskip

</div>


Apparently you only issue the \newcommand and \require statements once, Otherwise you get a LaTeX compile error.

So we have tricks that work in Jupyter notebook and Jupyter lab. They are unfortunately not the same tricks, so you cannot edit the same ipynb in both tools and get the same results. This sounds like a work-around (which is good) but not a full solution.

Is there a good place to document this so other folks will not have to dig it out in bits and pieces?

1 Like