jkuczm / MathematicaCellsToTeX

Convert Mathematica cells to TeX, retaining formatting.
Other
57 stars 10 forks source link

freeze on compiling with pdflatex for a particular code snippet #20

Closed vsht closed 7 years ago

vsht commented 7 years ago

Hi, the following tex file

\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}

\end{document}

fails to compile, by freezing pdflatex: $pdflatex test.tex

This is pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2014) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./test.tex
LaTeX2e <2011/06/27>
Babel <3.9k> and hyphenation patterns for 8 languages loaded.
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size12.clo)) (./mmacells.sty
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/expl3.sty
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3names.sty
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3bootstrap.sty))
(/usr/share/texlive/texmf-dist/tex/latex/etex-pkg/etex.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3basics.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3expan.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3tl.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3seq.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3int.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3quark.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3prg.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3clist.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3token.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3prop.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3msg.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3file.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3skip.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3keys.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3fp.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3box.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3coffins.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3color.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3luatex.sty)
(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3candidates.sty)
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ifpdf.sty))
(/usr/share/texlive/texmf-dist/tex/latex/l3packages/xparse/xparse.sty)
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty
For additional information on amsmath, use the `?' option.
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty))
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty)
(/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty))
(/usr/share/texlive/texmf-dist/tex/latex/bbm-macros/bbm.sty)
(/usr/share/texlive/texmf-dist/tex/latex/xcolor/xcolor.sty
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/color.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/pdftex-def/pdftex.def
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/infwarerr.sty)
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ltxcmds.sty)))
(/usr/share/texlive/texmf-dist/tex/latex/fancyvrb/fancyvrb.sty
Style option: `fancyvrb' v2.7a, with DG/SPQR fixes, and firstline=lastline fix 
<2008/02/07> (tvz) (/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty
)) (/usr/share/texlive/texmf-dist/tex/latex/listings/listings.sty
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstmisc.sty)
(/usr/share/texlive/texmf-dist/tex/latex/listings/listings.cfg))
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/graphics.cfg)))
(/usr/share/texlive/texmf-dist/tex/latex/hyperref/hyperref.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/hobsub-hyperref.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/hobsub-generic.sty))
(/usr/share/texlive/texmf-dist/tex/generic/ifxetex/ifxetex.sty)
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/auxhook.sty)
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/kvoptions.sty)
(/usr/share/texlive/texmf-dist/tex/latex/hyperref/pd1enc.def)
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/hyperref.cfg)
(/usr/share/texlive/texmf-dist/tex/latex/url/url.sty))

Package hyperref Message: Driver (autodetected): hpdftex.

(/usr/share/texlive/texmf-dist/tex/latex/hyperref/hpdftex.def
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/rerunfilecheck.sty))
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstmisc.sty)) (./test.aux)
(/usr/share/texlive/texmf-dist/tex/context/base/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
) (/usr/share/texlive/texmf-dist/tex/latex/oberdiek/epstopdf-base.sty
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/grfext.sty)
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg))
(/usr/share/texlive/texmf-dist/tex/latex/hyperref/nameref.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/gettitlestring.sty))
(./test.out) (./test.out)
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstlang1.sty)
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstlang1.sty)
(/usr/share/texlive/texmf-dist/tex/latex/listings/lstlang1.sty)

after this line the CPU load goes crazy without any visible progress.

The code was obtained from the following cell

Cell[BoxData[
 RowBox[{"F1V", "=", 
  RowBox[{
   RowBox[{"(", 
    RowBox[{
     RowBox[{"SMP", "[", "\"\<alpha_s\>\"", "]"}], "/", "Pi"}], ")"}], 
   RowBox[{"(", 
    RowBox[{"CF", "-", 
     RowBox[{
      RowBox[{"1", "/", "2"}], " ", "CA"}]}], ")"}], 
   RowBox[{"(", 
    RowBox[{
     RowBox[{"1", "/", 
      RowBox[{"(", 
       RowBox[{"2", "EpsilonUV"}], ")"}]}], "+", 
     RowBox[{"1", "/", "EpsilonIR"}], "+", "1", "-", 
     RowBox[{
      RowBox[{"3", "/", "2"}], 
      RowBox[{"Log", "[", 
       RowBox[{"m", "/", "ScaleMu"}], "]"}]}], "+", "\[IndentingNewLine]", 
     RowBox[{
      RowBox[{"q2", "/", 
       RowBox[{"m", "^", "2"}]}], 
      RowBox[{"(", 
       RowBox[{
        RowBox[{
         RowBox[{"-", "1"}], "/", 
         RowBox[{"(", 
          RowBox[{"3", "EpsilonIR"}], ")"}]}], "-", 
        RowBox[{"1", "/", "8"}], "+", 
        RowBox[{
         RowBox[{"1", "/", "3"}], 
         RowBox[{"Log", "[", 
          RowBox[{"m", "/", "ScaleMu"}], "]"}]}]}], ")"}]}]}], ")"}]}]}]], "Input",
 CellLabel->"In[10]:="]

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

jkuczm commented 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.

vsht commented 7 years ago

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?

jkuczm commented 7 years ago

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?

jkuczm commented 7 years ago

... 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?

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 CellsToTeXInternaloptionValueToTeX:

Module[{inside},
    CellsToTeX`Internal`optionValueToTeX[val_] /; Not@TrueQ@inside :=
        Block[{inside = True},
            StringReplace[CellsToTeX`Internal`optionValueToTeX[val], "#" -> "\\#"]
        ]
]
vsht commented 7 years ago

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.

vsht commented 7 years ago

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]
jkuczm commented 7 years ago

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}
*)

MMA code

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: pdf screenshot

vsht commented 7 years ago

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

jkuczm commented 7 years ago

Problem is in built-in TeX export, specifically in SystemConvertTeXDumpcleanUpFilefunction that adds newline to first tab or space after 144 characters in each line. We canBlock` 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 CellsToTeXConfiguration$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}
    ]
]
vsht commented 7 years ago

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 CellsToTeXConfigurationboxesToTeXProcessor({<<1>>}). ... The output is created with Package-X, available from http://packagex.hepforge.org/

jkuczm commented 7 years ago

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[{SystemConvertTeXDumpcleanUpFile}, ...]works provided thatSystemConvertTeXDump` context was loaded before evaluating thisBlockexpression, 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 LanguageExtendedDefinitionfunction, which is used bySyntaxAnnotationspackage to determine whether symbol is defined. I'll adapt `SyntaxAnnotations to take into account this situation.

vsht commented 7 years ago

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 LanguageExtendedDefinition 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 bildschirmfoto von 2016-10-20 12-05-05 really do not look so good, when compared to the original bildschirmfoto von 2016-10-20 12-08-14

Thanks a lot for all your help, I really appreciate it!

vsht commented 7 years ago

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.

jkuczm commented 7 years ago

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.