This question is inspired by this question: How to convert the symbol $d$ in Integrate into $\mathrm{d}$?.

Although it’s not a big problem, the TeXForm can be modified manually to “standard” form, I’m curious why Mathematica’s TeXForm won’t change the differential d to $\mathrm{d}$ automatically.

There are some detailed situations to pay attention to.

  • The integrand or the integration argument may contain some variables having letter “d”(Such as: det, adcda, etc.) or even “d” itself.(Although it’s ugly to do so.)

  • Mathematica will automatically change alpha to $\alpha$.

  • Single-character symbol names are given in italic font, while multiple character names are given in roman font.

I’ve written some lines of codes to do this. But I think the code is ugly and can’t handle the situation with integration argument’s name exactly “d”. Here is my code.

cTeXForm[expr_, arg__] := Module[{
  (*temp saves the original TeXForm*)
  temp = ToString@TeXForm@HoldForm[Integrate[expr, arg]],
 (*var saves the integration argument and reverse the order to keep up with the integral symbol*)
  var = ToString /@ TeXForm /@ Reverse@(Flatten /@ ({#} & /@ {arg}))[[;; , 1]], pos, range, betweenQ, loc},
  (*locate the position of differential d*)
  pos = StringPosition[temp, "d"][[;; , 1]];
  range = StringPosition[temp, var];
  betweenQ[n_] := Catch@(Scan[If[#[[1]] <= n <= #[[2]], Throw[0], n] &, range];Throw[1]);
  loc = {#, #} & /@ 
  Pick[pos, betweenQ[#] & /@ pos, 1][[-Length@var ;; -1]] ;
  (*replace and output*)
  CopyToClipboard@OutputForm@StringReplacePart[temp, "\\mathrm{d}", loc]]

Here is the test (although no beautiful):

cTeXForm[x^2 alpha d baded, {x, 1, 2}, {alpha, 2, 3},baded]

And here is the output of my code

$$\int _1^2\int _2^3\int \alpha \text{baded} d x^2\mathrm{d}\text{baded}\mathrm{d}\alpha \mathrm{d}x$$

So the question is how to precisely change the differential d to $\mathrm{d}$? Are there any other ways to do this? (RegularExpression, rule-based replacement etc. I’m not familiar with these.)

Any advice about the string manipulation or using TeXForm is welcomed.


1 Answer 1


I think I've found an answer to my own question.

Bypassing the difficulties of replacing d to $\mathrm{d}$, the following code constructs the intended TeX-form directly.

SetAttributes[integralTeXForm, HoldAll]
integralTeXForm[expr_, arg__] := Module[{temp, var, add},
  add = If[Length@# == 3, "_" <> #[[2]] <> "^" <> #[[3]] <> " ", ""] &;
  temp = ToString@TeXForm@HoldForm[expr];
  var = Map[ToString@TeXForm@# &, Reverse@(Flatten /@ ({#} & /@ {arg})), {2}];
  CopyToClipboard@Fold["\\int " <> add[#2] <> #1 <> "\\,\\mathrm{d}" <> #2[[1]]&, temp, var]

And the code above can also maintain the order of variables in the integrand.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.