I am trying to include a Mathematica code in LaTeX. To obtain the Mathematica code I just exported notebook as PDF. I didn't like the way it was included in my TEX code so I just thought of adding a box around picture so as to make it a bit more fancy. It's not yet there but it's better than nothing. The code used is


\nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=-    \int_r^\infty \!     \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}     \dfrac{\alpha^3}{y^3}\left(1-    \dfrac{\alpha^2}    {y^2}\right)^{-2}\,\mathrm{d}y\\
=&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3     \underbrace{\int_r^\infty     \! y^{-3} \left(1-\dfrac{\alpha^2}    {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI}



My output is

Any ideas on how to include Mathematica code in a more aesthetically way?

Edit:At first I used package listing but the problem was the fraction and the fact that I don't know how to include in a convenient way In[1] and Out[1]

  • Did you give a try with ctan.org/pkg/listings Nov 29, 2012 at 7:24
  • @texlearner: Thank you very much for your comment. I did actually but the problem is that the fraction in the answer is exported as a/b which is something I would like to avoid!
    – Thanos
    Nov 29, 2012 at 7:46
  • You could use mathescape - i'll extend my answer to that.
    – Ronny
    Nov 29, 2012 at 7:47
  • 1
    @Jubobs Where are thou?
    – percusse
    Feb 5, 2015 at 0:11

4 Answers 4


I know this question is old and surely OP doesn't need it anymore, but recently I had similar problem and I think my solution answers the question.

First thing to note is that in Mathematica FrontEnd cells can have arbitrary styles. Each styles appearance is customizable by a stylesheet. With default stylesheet even most basic cell styles i.e. Input and Output look different.

In cells with some styles (e.g Input or Code) code syntax is colored, this can be achieved using already mentioned in other answers listings package.

Cells with some styles (e.g. Input, Output or Print) by default use, so called StandardForm, which allows embedding of complicated formatting (fractions, superscripts etc.) inside code. This was partially solved in other answers by using mathescape functionality of listings package. Problem with this solution is that mathescape "completely escapes" to TeX. Since one can't nest listings environments/commands, I don't see a way to treat parts of escaped content again as code (e.g. typeset it verbatim) using listings only.

To achieve such functionality one can use Verbatim environment from fancyvrb package. By setting proper commandchars we can embed, for example, \frac command inside code, in such way that frac's arguments are typeset verbatim. Downside of fancyvrb is that it doesn't offer automatic syntax coloring. Fortunately listings has special interface to fancyvrb that allows combining of reading code by fancyvrb and typesetting it by listings.

Below I present usage of my mmacells package, which implements solution based on fancyvrb + listings approach, with some additional features like customizable cell styles, automatic cell labels etc.

There's also corresponding Mathematica package: CellsToTeX, that automatically exports Mathematica code to TeX code compatible with mmacells. Mathematica package is described in detail in answer to "How best to embed various cell groups into a latex project?" question on Mathematica Stack Exchange.

Usage example

Print screen of result: Mathematica cells in pdf

TeX code:







Input from question with output from my Mathematica version.
Input is in input form, it can be copied and pasted to Mathematica.
  \{ConditionalExpression[-\mmaFrac{1}{2 (\mmaSup{a}{2} - \mmaSup{r}{2})},
     Im[r] Re[a] ≠ Im[a] Re[r] || ((a + r > 0 || a + r ∉ Reals) &&
       ((Re[a] < r && Im[a] == 0) || a - r ∉ Reals)) || r ∉ Reals]\}

For comparison, same cells obtained by including PDFs exported from Mathematica:
% You need inCell.pdf and outCell.pdf files for this to work.
% \mmaCellGraphics{Input}{inCell}
% \mmaCellGraphics[yoffset=3.5ex]{Output}{outCell}

Same input expression, but in standard form (as if it was inputted using math assistant). Note that syntax coloring still works.

More features:
  (* A (* nested *) comment. *)
      Print["a string \" with double quotes inside ", b/d];
  List[1,List[2,3]]; (* Links to documentation. *)
  a string " with double quotes inside \mmaFrac{c}{d}
  Sin::argx: Sin called with 2 arguments; 1 argument is expected. >>
Graphics mixed with code:
  a Graphics[{Green,Disk[]},ImageSize->50]/2
% You need greenDisk.pdf file for this to work.
% \begin{mmaCell}[moregraphics={moreig={scale=.7}}]{Output}
%   \mmaFrac{a \mmaGraphics{greenDisk}}{2}
% \end{mmaCell}
  (* Different roles of one symbol. *)
  \mmaUnd{Module}; (* undefined Module symbol *)
  \mmaLnB{Module}; (* Module symbol with link to documentation *)
  (* Nesting of "formatting boxes" *)
  \mmaSup{a}{\mmaSup{a}{a}} \mmaSub{a}{\mmaSub{a}{a}} \mmaSubSup{a}{\mmaSubSup{a}{a}{a}}{\mmaSubSup{a}{a}{a}} \mmaUnder{a}{\mmaUnder{a}{a}} \mmaOver{a}{\mmaOver{a}{a}} \mmaUnderOver{a}{\mmaUnderOver{a}{a}{a}}{\mmaUnderOver{a}{a}{a}} \mmaFrac{a}{\mmaFrac{a}{\mmaFrac{a}{a}}} \mmaSqrt{\mmaSqrt{a}} \mmaRadical{a}{\mmaRadical{a}{a}}
  (* Replacements for infix operators in "Input" cells. *)
  x>=y; x<=y; x!=y; x->y; x:>y;
  (* No replacement in "Code" cells. *)
  x>=y; x<=y; x!=y; x->y; x:>y;
  (* Cell with custom label. *)
  \mmaLnT{x}=2;(* labeled definition of x *)
  \mmaLnL{x}(* usage of x with link to its definition *)

Implemented syntax elements:
  \mmaDef{Def} defined (*  defined symbol *)
  \mmaUnd{Und} undefined (* UndefinedSymbol *)
  \mmaFnc{Fnc} functionlocal (* FunctionLocalVariable *)
  \mmaLoc{Loc} local (* LocalVariable *)
  \mmaPat{Pat} pattern (* PatternVariable *)
  \mmaLCn{LCn} localconflict (* LocalScopeConflict *)
  \mmaGCn{GCn} globalconflict (* GlobalToLocalScopeConflict *)
  \mmaExc{Exc} excessargument (* ExcessArgument *)
  \mmaOpt{Opt} unknownoption (* UnknownOption *)
  \mmaAsg{Asg} unwantedassignment (* UnwantedAssignment *)
  \mmaShd{Shd} shadowing (* SymbolShadowing *)
  \mmaSnt{Snt} syntaxerror (* SyntaxError *)
  \mmaEmp{Emp} emphasizedsyntaxerror (* EmphasizedSyntaxError *)
  \mmaFmt{Fmt} formattingerror (* FormattingError *)

Inline cell: \mmaInlineCell[functionlocal=a]{Code}{Module[{a=5}, a]}.
Formatted inline cell:
  Inline cell inside macro argument:



There are three strategies of handling Unicode supported by mmacells. Code for all of them can be automatically generated by CellsToTeX Mathematica package.

1. No Unicode

Don't use Unicode at all, use appropriate TeX commands instead. This approach works in all engines.

listings package doesn't color elements provided by escaped commands, so they need to be wrapped with appropriate annotations.


\mmaSub{x}{1} == \mmaFrac{-\mmaUnd{\(\pmb{\beta}\)} \(\pmb{\pm}\) \mmaSqrt{\mmaSup{\mmaUnd{\(\pmb{\beta}\)}}{2} - 4 \mmaUnd{\(\pmb{\alpha}\)} \mmaUnd{\(\pmb{\gamma}\)}}}{2 \mmaUnd{\(\pmb{\alpha}\)}}


result of pdfLaTeX with Unicode

2. Unicode input

Use Unicode characters in input and automatically convert them to appropriate TeX commands by using \mmaDefineMathReplacement. This approach works in pdfTeX engine.

Replacements are implemented using listings literate option, so are "excluded" from automatic coloring, and identifiers containing Unicode characters need to be wrapped with appropriate annotations. Whether replacements will be used is controlled by mathreplacements option. By default Code cells don't use replacements (mathreplacements=none), Input cells use bold replacements (mathreplacements=bols) i.e. will use given command wrapped with math delimiters and \pmb, Output, Print and Message cells use "light" replacements (mathreplacements=light) i.e. will will use given command wrapped with math delimiters.



\mmaSub{x}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}}


result of pdfLaTeX with Unicode

3. Unicode input and output

Use Unicode characters in input and rely on appropriate glyphs of used fonts. This approach works in Unicode-aware engines.

Since listings does not support Unicode, it needs to be switched off using uselistings=false option. With listings switched off no automatic coloring occurs, so all identifiers, also those not containing Unicode characters, need to be wrapped with appropriate annotations.





\mmaSub{\mmaUnd{x}}{1} == \mmaFrac{-\mmaUnd{β} ± \mmaSqrt{\mmaSup{\mmaUnd{β}}{2} - 4 \mmaUnd{α} \mmaUnd{γ}}}{2 \mmaUnd{α}}


result of xelatex with Unicode

  • 4
    This is a really nice solution! Will you upload mmacells to CTAN? Nov 25, 2015 at 12:20
  • 2
    @HenriMenke I planned to upload it, to CTAN, after adding documentation, but I don't know when I'll have time to do it.
    – jkuczm
    Nov 25, 2015 at 22:53
  • 2
    @Abby Sure, just use functionlocal={x,y} option.
    – jkuczm
    Mar 23, 2017 at 16:09
  • 1
    @M.R. You can use fv option to pass formatcom key, with font changing commands, to Verbatim environment, on which mmaCell is based. Font changing commands depend on used engine. So something like \mmaSet{fv={formatcom*=\fontfamily{...}\selectfont}} for pdfTeX, or \mmaSet{fv={formatcom*=\setmonofont{...}\ttfamily}} for XeTeX, or LuaTeX, where dots should be replaced with appropriate font name.
    – jkuczm
    Apr 6, 2017 at 22:46
  • 1
    @Dominique You could use tcolorbox as shown in issue 21.
    – jkuczm
    Aug 29, 2017 at 14:47

You could use listings together with xcolor to include the code, for example with this MWE



  \begin{lstlisting}[language=Mathematica,caption={Example code}]

You would obtain something like Code example image

and by changing the \lstset even adapt the colors to look more Mathematicaish. You could then also use external code files and something like \lstinputlisting{yourfile.m} to include them. This is what i prefer, because then you could just (ok in Mathematica working on one cell) code the stuff you want and change the code. Due to the input it is then automatically the most recent version of your code example.

Edit 1 The OP requested to use Math symbols and fractions in his code:

One way to do that is, to add mathescape to the lstset as a further key. Then at any $ in the code the mode is switched to mathmode and one can type simply math. Then one could change the code line to


to obtain Second Code with math though i think it is not that nice to read (because there's still ^2 in the code and other non-LaTeX-set formulae. Finally my remark above won't work anymore, this code would - of course - not be able to run in Mathematica anymore.

  • 1
    Thank you very much for your answer! The first thing I did was to use listings but if you see in my figure the answer contains a fraction which uses a horizontal line to separate numerator from denominator. If I use listings the result is something like a/b, with a slash instead of a horizontal line, that is... Another issue I am facing is the fact that I want to include In[1] and Out[1]. If I use listings those "keywords",which are different from actual keywords, are printed as part of the code...
    – Thanos
    Nov 29, 2012 at 7:50
  • Another issue I am facing is the fact that I want to include In[1] and Out[1]. If I use listings those "keywords",which are different from actual keywords, are printed as part of the code...
    – Thanos
    Nov 29, 2012 at 7:55
  • I'll think about that, but that's a tricky one. To Obtain In[1] instead of 1 (the number now printed as line number) would be possible i think, but alternating them (with Out[...]) is challenging.
    – Ronny
    Nov 29, 2012 at 7:56
  • @You are right about that, so I will edit my question in order to provide the information I forgot to include.
    – Thanos
    Nov 29, 2012 at 8:02
  • @Ronny, is there a way to make the comments in my code look grey in the latex file, instead of black? I want to make them easy to be distinguished from the rest of the code... Nov 27, 2014 at 11:05

Another way to include mathematica packages into latex is to use this package mma.sty

by Manuel Kauers. With


in the preamble one can do a lot. I find it really amazing. I normally enclose it in mdframed environment which I think is pretty cool. See the image below:


There are also example on how one can use the package in the style file mma.sty.


As requested by @KevinO'Bryant, I have added a MWE which produces the two images above.


% For mathematica session
 innerlinewidth=0.5pt, innerleftmargin=10pt,%
 innerrightmargin=10pt, innertopmargin=10pt,%
 innerbottommargin=10pt, roundcorner=5pt,
 singleextra={\path (P) -- node[minimum height=.6cm,overlay,draw,fill=white, rounded corners,very thick] {\bf Mathematica Session} (O|-P);}

  \In |Command|[|arg|_1,1+1] \\
  \Out \mathrm{x^2+9} \\
  \In |quit| \\
  \Warning{name} something in text mode  \\
  \In |Print|["test"];\\
  \Print test\\
  \In |Quit| \\
  \Out {\rm
  \{ \{-6,\ \sqrt{2},\ \sqrt{3},\ k,\ 1 + n \},\ \{ \{k + n,\ 2 + k + n,\ -2\},\ \{ k + n,\ 5 + k + n,\ -5 \},\ \{2 + k + n,\ 5 + k + n,\ -3 \}  \} \} 
  } \\

 \In {\mathrm{\bf f = \{ \sqrt{2}(\bc{n}+1)^{2}(\bc{n}+\bc{k}),\ 6 (\bc{n}+1) (-\bc{k} - \bc{n} - 2) \bc{k},\ \sqrt{-3}(\bc{k} + \bc{n} + 5)\};}} \\ 
 \In {\mathrm{\bf tower = \Big\{ \{\bc{k}, 1, 1 \},\ \Big\{\bc{h}, 1, \frac{1}{\bc{k} + 1} \Big\},\ \Big\{\bc{b}, \frac{\bc{n}-\bc{k}}{\bc{k}+1}, 0 \Big\} \Big\} ;}}\\
 \In {\mathrm{\bf ShiftPrimeEquivalentFactors[f,\ tower]}}\\
 \Out { 
  \{ \{-6,\ \sqrt{2},\ \sqrt{3},\ k,\ 1 + n \},\ \{ \{k + n,\ 2 + k + n,\ -2\},\ \{ k + n,\ 5 + k + n,\ -5 \},\ \{2 + k + n,\ 5 + k + n,\ -3 \}  \} \} 

  • 2
    That is pretty cool. Mind sharing a MWE? Jun 14, 2016 at 6:29
  • 3
    @KevinO'Bryant: I added a MWE as you requested.
    – wisedoe
    Jun 15, 2016 at 4:11

Using the listings package, it is possible to get math mode in the mathematica code. You need to add the mathescape option on the listings environment definition, and manually place the math delimiters in the listing. I realise that this may be impractical if you want to insert a lot of code.

I hope the following code makes my meaning clear.





\nonumber W_{r\rightarrow\infty}=&-\int_{r}^{\infty}\!F\,\mathrm{d}y=-    \int_r^\infty \!     \dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}     \dfrac{\alpha^3}{y^3}\left(1-    \dfrac{\alpha^2}    {y^2}\right)^{-2}\,\mathrm{d}y\\
=&-\dfrac{1}{4\pi \epsilon_0} \dfrac{q^2}{\alpha^2}\alpha^3     \underbrace{\int_r^\infty     \! y^{-3} \left(1-\dfrac{\alpha^2}    {y^2}\right)^{-2} \,\mathrm{d}y}_{I} \label{eq:WcondI}


In[1]:= Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}]
Out[1]= {ConditionalExpression[$\displaystyle-\frac{1}{2(a^2-r^2)}$, Im[r] 
Re[a] $\neq$ Im[a] Re[r] || (( $a+r>0$ || $a+r \notin $ Reals) && ($a<r$ || 
$a-r \notin$ Reals) || $r\notin$ Reals )]}




Note that I formatted the output manually. Here is the result: result

  • Adding the ` Out[]` and In[] is of course easier, than the idea i just thought about, namely tweaking the numbering of the listing.
    – Ronny
    Nov 29, 2012 at 8:04
  • @Ronny Oops! I didn't see that you already mentioned the use of mathescape, sorry about that.
    – guillem
    Nov 29, 2012 at 8:17
  • Actually i added that, when the OP mentioned that in his first comment below the Introduction, though i was too lazy to type the Output myself in math, i was a little faster with that additional edit than your post ;)
    – Ronny
    Nov 29, 2012 at 10:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .