Closed vsht closed 7 years ago
Due to some peculiarities of listings
- fancyvrb
interface, explicit newlines can't be used inside formatting commands like \mmaFrac
. So you need to either get rid of those newlines, or switch off listings
(for Print
cell uselistings=false
should have no negative effects).
Following code should work:
\documentclass[12pt]{article}
\usepackage{mmacells}
\begin{document}
\begin{mmaCell}{Print}
\mmaFrac{\mmaSub{\(\alpha\)}{s} (\mmaSub{C}{F}-\mmaFrac{\mmaSub{C}{A}}{2}) (\mmaFrac{1}{\mmaSub{\(\varepsilon\)}{IR}}+\mmaFrac{q2 (-\mmaFrac{1}{3\mmaSub{\(\varepsilon\)}{IR}}+\mmaFrac{1}{3} log(\mmaFrac{m}{\(\mu\)})-\mmaFrac{1}{8})}{\mmaSup{m}{2}}-\mmaFrac{3}{2} log(\mmaFrac{m}{\(\mu\)})+\mmaFrac{1}{2\mmaSub{\(\varepsilon\)}{UV}}+1)}{\(\pi\)}
\end{mmaCell}
\begin{mmaCell}[uselistings=false]{Print}
\mmaFrac{\mmaSub{\(\alpha\)}{s} (\mmaSub{C}{F}-\mmaFrac{\mmaSub{C}{A}}{2}) (\mmaFrac{1}{\mmaSub{\(\varepsilon\)}{IR}}+\mmaFrac{q2 (-\mmaFrac{1}{3
\mmaSub{\(\varepsilon\)}{IR}}+\mmaFrac{1}{3} log(\mmaFrac{m}{\(\mu\)})-\mmaFrac{1}{8})}{\mmaSup{m}{2}}-\mmaFrac{3}{2} log(\mmaFrac{m}{\(\mu\)})+\mmaFrac{1}{2
\mmaSub{\(\varepsilon\)}{UV}}+1)}{\(\pi\)}
\end{mmaCell}
\end{document}
CellsToTeX
package itself doesn't add those newlines. Mathematica might add them when you copy its output to clipboard, or export it to a file.
I see, thanks for the explanation.
Well, of course I can get rid of the newlines via StringReplace
, e.g. (quick hacky code)
str2 = StringReplace[
str, {"\\begin{mmaCell}{Output}" ~~ ShortestMatch[x___] ~~
"\\end{mmaCell}" :>
"\\begin{mmaCell}{Output}\n" <> StringReplace[x, "\n" -> ""] <>
"\n\\end{mmaCell}\n",
"\\begin{mmaCell}{Print}" ~~ ShortestMatch[x___] ~~
"\\end{mmaCell}" :>
"\\begin{mmaCell}{Print}\n" <> StringReplace[x, "\n" -> ""] <>
"\n\\end{mmaCell}\n"}];
However, there still seem to be issues. For example, out of
abelianVertex =
FCFAConvert[
FCPrepareFAAmp[
CreateFeynAmp[DiagramExtract[diagsVertex, 1],
Truncated -> False, PreFactor -> -1]],
IncomingMomenta -> {p1, q}, OutgoingMomenta -> {p2},
LoopMomenta -> {l}, UndoChiralSplittings -> True,
DropSumOver -> True, List -> False,
FinalSubstitutions -> {SMP["m_u"] -> m, q -> p2 - p1,
Pair[Momentum[Polarization[___], ___], ___] :> 1},
ChangeDimension -> D, SMP -> True] // Contract // SUNSimplify //
ReplaceAll[#, SUNTF[{x__}, __] :> SUNT[x]] & //
SUNSimplify[#, Explicit -> True] &
I get
\begin{mmaCell}[addtoindex=5,moredefined={abelianVertex, FCFAConvert, FCPrepareFAAmp, CreateFeynAmp, DiagramExtract, diagsVertex, Truncated, PreFactor,
IncomingMomenta, OutgoingMomenta, LoopMomenta, UndoChiralSplittings, DropSumOver, FinalSubstitutions, SMP, Pair, Momentum, Polarization, ChangeDimension,
Contract, SUNSimplify, SUNTF, SUNT, Explicit},morepattern={#, x__, x}]{Input}
abelianVertex=FCFAConvert[FCPrepareFAAmp[CreateFeynAmp[DiagramExtract[diagsVertex,1], Truncated -> False,PreFactor\(\pmb{\to}\)-1]],
IncomingMomenta\(\pmb{\to}\)\{p1,q\},OutgoingMomenta\(\pmb{\to}\)\{p2\},LoopMomenta\(\pmb{\to}\)\{l\},UndoChiralSplittings\(\pmb{\to}\)True,DropSumOver\(\pmb{\to}\)True,List\(\pmb{\to}\)False,FinalSubstitutions\(\pmb{\to}\)\{SMP["m_u"]\(\pmb{\to}\)m,q\(\pmb{\to}\)p2-p1,Pair[Momentum[Polarization[___],___],___]:>1\},ChangeDimension\(\pmb{\to}\)D,SMP\(\pmb{\to}\)True]//Contract//SUNSimplify//ReplaceAll[#,SUNTF[\{x__\},__]\(\pmb{:\to}\)SUNT[x]]&//SUNSimplify[#,Explicit\(\pmb{\to}\)True]&
\end{mmaCell}
The generates
! Illegal parameter number in definition of \lst@temp.
unless I remove morepattern={#, x__, x}
by hand.
So what is the purpose of morepattern
here and is it safe to get rid of it via StringReplace?
Well, of course I can get rid of the newlines via
StringReplace
...
Those newlines shouldn't be there in the first place. Could you show full Mathematica code that results in string with newlines in formatting commands?
... unless I remove
morepattern={#, x__, x}
by hand. So what is the purpose ofmorepattern
here and is it safe to get rid of it via StringReplace?
The fact that non-escaped #
appears in morepattern
option is a bug.
The purpose of morepattern
option is to add identifiers that should be styled as "pattern variables" i.e. oblique, light green.
A quick hack, fixing this bug, is patching CellsToTeX
InternaloptionValueToTeX
:
Module[{inside},
CellsToTeX`Internal`optionValueToTeX[val_] /; Not@TrueQ@inside :=
Block[{inside = True},
StringReplace[CellsToTeX`Internal`optionValueToTeX[val], "#" -> "\\#"]
]
]
Those newlines shouldn't be there in the first place. Could you show full Mathematica code that results in string with newlines in formatting commands?
Sure, but it is a bit complicated...
So first you need to install FeynCalc
Import["https://raw.githubusercontent.com/FeynCalc/feyncalc/master/install.m"] InstallFeynCalc[InstallFeynCalcDevelopmentVersion -> True]
Then FeynHelpers
Import["https://raw.githubusercontent.com/FeynCalc/feynhelpers/master/install.m"] InstallFeynHelpers[]
Then extract QCDBGF.zip to .Mathematica/Applications/eynCalc/FeynArts/Models
and finally run
code.nb.zip on a fresh kernel.
By the way, the since the sections cannot be handled by MathematicaCellsToTeX, may be it would be good to have them filtered out automatically. The code I was using at the end is
nbObj = NotebookOpen["/home/vs/Dokumente/Work/code.nb"]
CurrentValue[nbObj, CellLabelAutoDelete] = False;
SelectionMove[nbObj, All, Notebook];
SelectionEvaluate[nbObj, Before];
SetOptions[CellToTeX, "CurrentCellIndex" -> Automatic];
nbConv = NotebookGet[nbObj] /.
Cell[x___, "Section", y___] :> Unevaluated@Sequence[] /.
cell : Cell[_, __] :> Cell[CellToTeX[cell], "Final"];
str = ExportString[nbConv, "TeX", "FullDocument" -> False,
"ConversionRules" -> {"Final" -> Identity}];
str2 = StringReplace[str, {
"\\begin{mmaCell}" ~~ ShortestMatch[t___] ~~ "{Output}" ~~
ShortestMatch[x___] ~~ "\\end{mmaCell}" :>
"\\begin{mmaCell}" <> t <> "{Output}\n" <>
StringReplace[x, "\n" -> ""] <> "\n\\end{mmaCell}\n",
"\\begin{mmaCell}" ~~ ShortestMatch[t___] ~~ "{Print}" ~~
ShortestMatch[x___] ~~ "\\end{mmaCell}" :>
"\\begin{mmaCell}" <> t <> "{Print}\n" <>
StringReplace[x, "\n" -> ""] <> "\n\\end{mmaCell}\n"}] //
StringReplace[#, {"morepattern={" ~~ ShortestMatch[___] ~~ "}" ->
""}] &;
Export[FileNameJoin[{NotebookDirectory[], "code.tex"}], str2]
I've converted one of cells from code.nb.zip
:
tmpCell =
Cell[BoxData[
FormBox[FractionBox[
RowBox[{SubscriptBox["\[Alpha]", "s"], " ",
RowBox[{"(",
RowBox[{SubscriptBox["C", "F"], "-",
FractionBox[SubscriptBox["C", "A"], "2"]}], ")"}], " ",
RowBox[{"(",
RowBox[{FractionBox["1",
SubscriptBox["\[CurlyEpsilon]", "IR"]], "+",
FractionBox[
RowBox[{"q2", " ",
RowBox[{"(",
RowBox[{RowBox[{"-",
FractionBox["1",
RowBox[{"3", " ",
SubscriptBox["\[CurlyEpsilon]", "IR"]}]]}], "+",
RowBox[{FractionBox["1", "3"], " ",
RowBox[{"log", "(", FractionBox["m", "\[Mu]"],
")"}]}], "-", FractionBox["1", "8"]}], ")"}]}],
SuperscriptBox["m", "2"]], "-",
RowBox[{FractionBox["3", "2"], " ",
RowBox[{"log", "(", FractionBox["m", "\[Mu]"], ")"}]}],
"+", FractionBox["1",
RowBox[{"2", " ",
SubscriptBox["\[CurlyEpsilon]", "UV"]}]], "+", "1"}],
")"}]}], "\[Pi]"], TraditionalForm]], "Output"];
tmpCell // CellPrint
tmpCell // CellToTeX
(*
\begin{mmaCell}{Output}
\mmaFrac{\mmaSub{\(\alpha\)}{s} (\mmaSub{C}{F}-\mmaFrac{\mmaSub{C}{A}}{2}) (\mmaFrac{1}{\mmaSub{\(\varepsilon\)}{IR}}+\mmaFrac{q2 (-\mmaFrac{1}{3 \mmaSub{\(\varepsilon\)}{IR}}+\mmaFrac{1}{3} log(\mmaFrac{m}{\(\mu\)})-\mmaFrac{1}{8})}{\mmaSup{m}{2}}-\mmaFrac{3}{2} log(\mmaFrac{m}{\(\mu\)})+\mmaFrac{1}{2 \mmaSub{\(\varepsilon\)}{UV}}+1)}{\(\pi\)}
\end{mmaCell}
*)
As can be seen in FullForm
:
tmpCell // CellToTeX // FullForm
(*"\\begin{mmaCell}{Output}\n \\mmaFrac{\\mmaSub{\\(\\alpha\\)}{s} (\\mmaSub{C}{F}-\\mmaFrac{\\mmaSub{C}{A}}{2}) (\\mmaFrac{1}{\\mmaSub{\\(\\varepsilon\\)}{IR}}+\\mmaFrac{q2 (-\\mmaFrac{1}{3 \\mmaSub{\\(\\varepsilon\\)}{IR}}+\\mmaFrac{1}{3} log(\\mmaFrac{m}{\\(\\mu\\)})-\\mmaFrac{1}{8})}{\\mmaSup{m}{2}}-\\mmaFrac{3}{2} log(\\mmaFrac{m}{\\(\\mu\\)})+\\mmaFrac{1}{2 \\mmaSub{\\(\\varepsilon\\)}{UV}}+1)}{\\(\\pi\\)}\n\\end{mmaCell}"*)
only newlines in the string are those after \\begin{mmaCell}{Output}
and before \\end{mmaCell}
, there are no newlines inside formatting commands.
Compilation of returned TeX code gives following pdf, without any errors:
Honestly, I don't know what goes wrong here. I attach an example, if you are interested to debug it: here pdflatex simply freezes.
With StringReplace and your patch I can get TeX code that compiles fine and this is all that I need for the moment. example.zip
Problem is in built-in TeX export, specifically in System
ConvertTeXDump
cleanUpFilefunction that adds newline to first tab or space after 144 characters in each line. We can
Block` it for duration of relevant export.
... since the sections cannot be handled by MathematicaCellsToTeX, may be it would be good to have them filtered out automatically.
We can convert, with CellToTeX
, supported cells, and leave other cells alone, so that they will be converted by built-in TeX export. Pattern matching supported cell styles is stored in CellsToTeX
Configuration$supportedCellStyles
.
So putting everything together, we can do:
(* Fix bug in optionValueToTeX. *)
Module[{inside},
CellsToTeX`Internal`optionValueToTeX[val_] /; Not@TrueQ@inside :=
Block[{inside = True},
StringReplace[CellsToTeX`Internal`optionValueToTeX[val], "#" -> "\\#"]
]
]
(* Size of notebook window affects boxes representing fractions. *)
nbObj = NotebookOpen["code.nb", WindowSize -> Medium]
CurrentValue[nbObj, CellLabelAutoDelete] = False;
SelectionMove[nbObj, All, Notebook];
SelectionEvaluate[nbObj, Before];
SetOptions[CellToTeX, "CurrentCellIndex" -> Automatic];
(* Use CellToTeX only on supported cell styles listed in $supportedCellStyles. *)
nbConv = NotebookGet[nbObj] /.
cell : Cell[_, CellsToTeX`Configuration`$supportedCellStyles, __] :>
Cell[CellToTeX[cell], "Final"];
(* Add preamble setting default gobble option and turning on line breaking from listings. *)
nbConv = Insert[nbConv,
Cell[CellsToTeXPreamble["TeXOptions" -> {"morelst" -> {"breaklines" -> True}}], "Final"],
{1, 1}
];
(* Disable cleanUpFile - a function adding newlines on whitespace,
after 144 characters in a line. *)
Block[{System`Convert`TeXDump`cleanUpFile},
Export[
FileNameJoin[{NotebookDirectory[], "code.tex"}], nbConv, "TeXFragment",
"ConversionRules" -> {"Final" -> Identity}
]
]
Thanks, this works nicely :)
Unfortunately, I found another example (actually much more simple than code.nb
), where already the conversion fails (for some reason GitHub won't accept my upload, so I used my university web space):
http://users.ph.tum.de/ga57tah/example2.zip
Here already the conversion fails with
CellsToTeXException::unsupported: Box: TemplateSlotSequence[1,] is not one of supported: {RowBox[_List],(StyleBox|ButtonBox|InterpretationBox|FormBox|TagBox)\[InvisibleApplication](_,___),TemplateBox[_,_,___],SubscriptBox[\[Integral],_,OptionsPattern[]],<<9>>,HoldPattern[SqrtBox[Repeated[_,{1}],OptionsPattern[]]],HoldPattern[RadicalBox[Repeated[_,{2}],OptionsPattern[]]],_String}. Exception occurred in CellsToTeX
ConfigurationboxesToTeXProcessor({<<1>>}).
...
The output is created with Package-X, available from http://packagex.hepforge.org/
Those are just unsupported boxes. Of course ultimately all boxes should be supported, but support will be added incrementally. Which boxes are supported is governed by "BoxRules"
processor option, with default values, for formatted cells, stored in $boxesToFormattedTeX
. One can add transformation rules for relevant boxes with something like:
PrependTo[$ContextPath, "CellsToTeX`Configuration`"];
$boxesToFormattedTeX = Join[{
TooltipBox[contents_, ___] :> makeString[contents],
GridBox[rows : {{_} ..}, ___] :> StringJoin@Riffle[makeString /@ rows[[All, 1]], "\n"],
PaneSelectorBox[rules_, Verbatim[Dynamic][x_, ___] | x_, ___] :>
makeString@Replace[x, rules]
}, $boxesToFormattedTeX]
Appearance of TemplateSlotSequence
is slightly different problem that can be fixed by evaluating:
BoxForm`$UseTemplateSlotSequenceForRow = False
before evaluation of converted notebook.
Also Block[{System
ConvertTeXDump
cleanUpFile}, ...]works provided that
SystemConvert
TeXDump` context was loaded before evaluating this
Blockexpression, it can be ensured by a "dummy" TeX export:
ExportString["", "TeXFragment"];`.
There will still be some Part::partw
warnings. They originate in strange way in which Package-X is installed, its symbols are somehow invisible for Language
ExtendedDefinitionfunction, which is used by
SyntaxAnnotationspackage to determine whether symbol is defined. I'll adapt `SyntaxAnnotations
to take into account this situation.
Those are just unsupported boxes. Of course ultimately all boxes should be supported, but support will be added incrementally.
I see. This is fine, of course. After all it is your hobby project. I got the point that one can add new boxes by hand. BTW, GridBox can be also of the form GridBox[{{__}},___]
as in this FIRE output
fire.nb.zip. But your code works with two tiny changes
PrependTo[$ContextPath, "CellsToTeX`Configuration`"];
$boxesToFormattedTeX =
Join[{TooltipBox[contents_, ___] :> makeString[contents],
GridBox[rows : {{__}}, ___] :>
StringJoin@Riffle[makeString /@ rows, "\n"],
PaneSelectorBox[rules_, Verbatim[Dynamic][x_, ___] | x_, ___] :>
makeString@Replace[x, rules]}, $boxesToFormattedTeX];
There will still be some Part::partw warnings. They originate in strange way in which Package-X is installed, its symbols are somehow invisible for Language
ExtendedDefinition function, which is used by SyntaxAnnotations
package to determine whether symbol is defined. I'll adapt SyntaxAnnotations` to take into account this situation.
This is because the author of Package-X uses Locked
, Protected
and ReadProtected
to prevent people from looking at the source code.
I have just one question left concerning the LaTeX part. Is there a simple way to make brackets adapt their size depending on the input in between? \left
and \right
obviously do not work, because mmaCell
is not a math environment. Normally I would not bother, but the brackets in
really do not look so good, when compared to the original
Thanks a lot for all your help, I really appreciate it!
I have just one question left concerning the LaTeX part. Is there a simple way to make brackets adapt their size depending on the input in between? \left and \right obviously do not work, because mmaCell is not a math environment.
Nevermind, I got it with
% Bracketed FractionBox
\NewDocumentCommand \mmaFracBr { m m } {\ensuremath{\left ( \frac{\text{#1}}{\text{#2}} \right )}}
Running StringReplace on the output TeX will do the job.
Thanks so much for all the tricks and fixes.
Thanks for the feedback. Bug with non-escaped #
is fixed and those 3 additional boxes are supported in v0.2.1.
As to auto-sizing of brackets, this is a bit difficult to do robustly in TeX verbatim environment.
This package started as more "code" oriented. Of course in Mathematica there's no clear distinction between "code" and "mathematical expressions", but all those output cells in TraditionalForm
seems to belong more to the latter category. Maybe for output cells consider using ordinary TeXForm
which sometimes can do a better job in converting "mathematical expressions" to TeX, or use PDFs for output cells as described in "Example of customization" section of my M.SE answer, but quality of Mathematica PDF export is very version dependent.
I have a non-verbatim variant of conversion on my TODO list. It will use math mode instead of verbatim environment on the TeX side, but implementing it will take some time.
Hi, the following tex file
fails to compile, by freezing pdflatex:
$pdflatex test.tex
after this line the CPU load goes crazy without any visible progress.
The code was obtained from the following cell
I'm on Fedora 23, 64-bit with TeX Live 2014 from the standard repository and Mathematica 11. Am I doing something wrong here?
Cheers, Vladyslav