[Tex/LaTex] Fanciest way to include Mathematica code in LaTeX

formattingwolfram-mathematica

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

\documentclass[a4paper,11pt]{article}
\usepackage{kerkis}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage[pdftex]{graphicx}
\usepackage{xcolor}

\begin{document}
\begin{align}
\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}
\end{align}

\setlength{\unitlength}{1cm}
\begin{picture}(15,5)
\color{blue}
\put(-1,0){\line(0,1){5}}
\put(0,1.5){\includegraphics[scale=0.8]{math}}
\put(-1,0){\line(1,0){15}}
\put(14,0){\line(0,1){5}}
\put(-1,5){\line(1,0){15}}
\end{picture}

\end{document}

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]

Best Answer

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:

\documentclass{article}

\usepackage[margin=2cm]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{mmacells}


\mmaDefineMathReplacement[≤]{<=}{\leq}
\mmaDefineMathReplacement[≥]{>=}{\geq}
\mmaDefineMathReplacement[≠]{!=}{\neq}
\mmaDefineMathReplacement[→]{->}{\to}[2]
\mmaDefineMathReplacement[⧴]{:>}{:\hspace{-.2em}\to}[2]
\mmaDefineMathReplacement{∉}{\notin}
\mmaDefineMathReplacement{∞}{\infty}
\mmaDefineMathReplacement{𝕕}{\mathbbm{d}}


\mmaSet{
  morefv={gobble=2},
  linklocaluri=mma/symbol/definition:#1,
  morecellgraphics={yoffset=1.9ex}
}


\begin{document}

Input from question with output from my Mathematica version.
Input is in input form, it can be copied and pasted to Mathematica.
\begin{mmaCell}[functionlocal=y]{Code}
  Integrate[{y^(-3)*(1-(a/y)^2)^(-2)},{y,r,Infinity}]
\end{mmaCell}
\begin{mmaCell}{Output}
  \{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]\}
\end{mmaCell}

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.
\begin{mmaCell}[index=3,functionlocal=y]{Input}
  \mmaSubSupM{\int}{r}{∞}\{\mmaFrac{1}{\mmaSup{y}{3}\mmaSup{\big(1-\mmaSup{\big(\mmaFrac{a}{y}\big)}{2}\big)}{2}}\}𝕕y
\end{mmaCell}


More features:
\begin{mmaCell}[
  moredefined=f,
  functionlocal=a,
  local=b,
  pattern={x_,x},
  excessargument=n,
  linkbuiltin=List
]{Code}
  (* A (* nested *) comment. *)
  Block[{a=3},a+2]
  f[x_]:=2x+1 
  Module[{b=c},
      Print["a string \" with double quotes inside ", b/d];
      b+1
  ]
  f[z]//FullForm
  Sin[m,n]
  List[1,List[2,3]]; (* Links to documentation. *)
\end{mmaCell}
\begin{mmaCell}{Output}
  5
\end{mmaCell}
\begin{mmaCell}{Print}
  a string " with double quotes inside \mmaFrac{c}{d}
\end{mmaCell}
\begin{mmaCell}[addtoindex=1]{Output}
  1+c
\end{mmaCell}
\begin{mmaCell}[form=FullForm]{Output}
  Plus[1,Times[2,z]]
\end{mmaCell}
\begin{mmaCell}[messagelink={message/General/argx}]{Message}
  Sin::argx: Sin called with 2 arguments; 1 argument is expected. >>
\end{mmaCell}
\begin{mmaCell}{Output}
  Sin[m,n]
\end{mmaCell}
\begin{mmaCell}{Output}
  \{1,\{2,3\}\}
\end{mmaCell}
Graphics mixed with code:
\begin{mmaCell}{Code}
  a Graphics[{Green,Disk[]},ImageSize->50]/2
\end{mmaCell}
% You need greenDisk.pdf file for this to work.
% \begin{mmaCell}[moregraphics={moreig={scale=.7}}]{Output}
%   \mmaFrac{a \mmaGraphics{greenDisk}}{2}
% \end{mmaCell}
\begin{mmaCell}{Code}
  (* Different roles of one symbol. *)
  x;
  _x;
  \mmaDef{x_};
  \mmaPat{x_}->2x;
  \mmaPat{x_}:>2\mmaPat{x};
  f[\mmaPat{x_}]=2x;
  f[\mmaPat{x_}]:=2\mmaPat{x};
  Block[{\mmaFnc{x}},2\mmaFnc{x}];
  Module[{\mmaLoc{x}},2\mmaLoc{x}];
  \mmaUnd{Module}; (* undefined Module symbol *)
  \mmaLnB{Module}; (* Module symbol with link to documentation *)
  Sin[x\mmaExc{,x}];
\end{mmaCell}
\begin{mmaCell}[addtoindex=11]{Input}
  (* 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}}
\end{mmaCell}
\begin{mmaCell}{Input}
  (* Replacements for infix operators in "Input" cells. *)
  x>=y; x<=y; x!=y; x->y; x:>y;
\end{mmaCell}
\begin{mmaCell}{Code}
  (* No replacement in "Code" cells. *)
  x>=y; x<=y; x!=y; x->y; x:>y;
\end{mmaCell}
\begin{mmaCell}[label={(\mmaCellIndex)custom}]{Code}
  (* Cell with custom label. *)
\end{mmaCell}
\begin{mmaCell}{Input}
  \mmaLnT{x}=2;(* labeled definition of x *)
\end{mmaCell}
\begin{mmaCell}{Input}
  \mmaLnL{x}(* usage of x with link to its definition *)
\end{mmaCell}

Implemented syntax elements:
\begin{mmaCell}[
  defined=defined,
  undefined=undefined,
  functionlocal=functionlocal,
  local=local,
  pattern=pattern,
  localconflict=localconflict,
  globalconflict=globalconflict,
  excessargument=excessargument,
  unknownoption=unknownoption,
  unwantedassignment=unwantedassignment,
  shadowing=shadowing,
  syntaxerror=syntaxerror,
  emphasizedsyntaxerror=emphasizedsyntaxerror,
  formattingerror=formattingerror,
]{Code}
  \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 *)
\end{mmaCell}

Inline cell: \mmaInlineCell[functionlocal=a]{Code}{Module[{a=5}, a]}.
Formatted inline cell:
\mmaInlineCell[pattern={x_,x}]{Input}{f[x_]:=\mmaFrac{\mmaSup{x}{2}}{5}}
\subsubsection*{
  Inline cell inside macro argument:
  \mmaInlineCellNonVerb[functionlocal=x]{Code}{Solve[\mmaSqrt{x}==y,x]}
}

\end{document}

Unicode

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.

\documentclass{article}
\usepackage{mmacells}
\begin{document}

\begin{mmaCell}{Input}
\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}\)}}
\end{mmaCell}

\end{document}

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.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{mmacells}
\begin{document}

\mmaDefineMathReplacement{±}{\pm}
\mmaDefineMathReplacement{α}{\alpha}
\mmaDefineMathReplacement{β}{\beta}
\mmaDefineMathReplacement{γ}{\gamma}

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

\end{document}

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.

\documentclass{article}
\usepackage{fontspec}
\usepackage{mmacells}

\setmainfont{FreeSerif}
\setmonofont{FreeMono}

\mmaSet{uselistings=false}

\begin{document}

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

\end{document}

result of xelatex with Unicode

Related Question