We must remember to use HoldPattern
to prevent evaluation of D[...]
expression used on left hand side of definition. To make D
formatting general we need some preprocessing of variable specification arguments to count total order of derivative.
Import@"https://raw.githubusercontent.com/jkuczm/MathematicaTeXUtilities/master/NoInstall.m"
Unprotect@D;
Format[HoldPattern@D[f_, vars__, OptionsPattern[]], TeXForm] := Module[{n = 0, v},
v = Replace[HoldComplete@vars, {
{x_, i_, ___} /; (n += i; True) :> HoldForm@HoldForm[x]^i,
x_ /; (n++; True) :> HoldForm@HoldForm[x]
}, {1}];
TeXDelimited[
"\\frac{" <> ToString[TeXVerbatim@"\\mathrm{d}"^n, TeXForm] <> "}{",
Sequence @@ v,
"} " <> ToString[Unevaluated@f, TeXForm],
"BodyConverter" -> ("\\mathrm{d}" <> ToString[#, TeXForm]&),
"BodySeparator" -> " \\, ",
"DelimSeparator" -> ""
]
]
Protect@D;
Basic example:
D[f[x], x] // HoldForm // TeXForm
(* \frac{\mathrm{d}}{\mathrm{d}x} f(x) *)
$\frac{\mathrm{d}}{\mathrm{d}x} f(x)$
Complicated example with variables with assigned values to test potential evaluation leaks:
x = 10; y = 20; f = Plus;
D[f[x, y, z], {x, n}, y, {z, 2 + m}] // HoldForm // TeXForm
ClearAll[x, y, f]
(* \frac{\mathrm{d}^{3+m+n}}{\mathrm{d}x^n \, \mathrm{d}y \, \mathrm{d}z^{2+m}} f(x,y,z) *)
$\frac{\mathrm{d}^{3+m+n}}{\mathrm{d}x^n \, \mathrm{d}y \, \mathrm{d}z^{2+m}} f(x,y,z)$
For Integrate
we must make sure that our custom format value takes precedence over built-in formatting, so we move it to beginning of FormatValues
. Here I'll limit custom formatting to indefinite integrals with up to four variables, but of course more general rules can be defined.
Unprotect@Integrate;
Format[Integrate[fun_, vars : Repeated[_Symbol, {1, 4}]], TeXForm] := With[
{v = HoldForm /@ HoldForm /@ HoldComplete@vars},
TeXDelimited[
"\\" <> StringRepeat["i", Length@v] <> "nt",
Unevaluated@fun,
Sequence @@ v,
"",
"DelimSeparator" -> " ",
"BodySeparator" -> " \\, \\mathrm{d}"
]
]
(* Move TeXForm format to begining of FormatValues so they take precedence over existing ones. *)
FormatValues@Integrate = Join[#@False, #@True]&@GroupBy[FormatValues@Integrate, FreeQ@TeXForm];
Protect@Integrate;
Basic example:
Integrate[f[x], x] // TeXForm
(* \int f(x) \, \mathrm{d}x *)
$\int f(x) \, \mathrm{d}x$
Complicated example with variables with assigned values to test potential evaluation leaks:
x = 10; y = 20; f = Plus;
Integrate[f[x, y, z], x, y, z] // HoldForm // TeXForm
ClearAll[x, y, f]
(* \iiint f(x,y,z) \, \mathrm{d}x \, \mathrm{d}y \, \mathrm{d}z *)
$\iiint f(x,y,z) \, \mathrm{d}x \, \mathrm{d}y \, \mathrm{d}z$
Nothing happened
, do you mean that after tryingTeXForm
again, it looked exactly the same? $\endgroup$