# How to convert the symbol $d$ in Integrate into $\mathrm{d}$?

I used

TeXForm[HoldForm[Integrate[x^2, {x, 1, 2}]]]


to convert the integral

$$\int_1^2 x^2 \, dx$$ How to get $$\int_1^2 x^2 \, \mathrm{d}x ?$$

-

Here's an approach using string replacement:

dIfy[str_] := CopyToClipboard@OutputForm@
StringReplace["$" <> ToString[str] <> "$", "dx" -> "\\mathrm{d}x"];

tex = TeXForm[HoldForm[Integrate[x^2, {x, 1, 2}]]];
dIfy[tex]


$$\int_1^2 x^2 \, \mathrm{d}x$$

Per VF1's suggestion, here is an improved version:

dIfy[str_] := CopyToClipboard@OutputForm@
StringReplace["$" <> ToString[str] <> "$",
"d" ~~ x_ :> "\\mathrm{d}" <> x];


The problem of course is that this matches any d, so clearly this string approach isn't going to be the ideal for general usage. At least not without some involved string patterns.

Edit. Implementing luyuwuli's suggestion:

SetAttributes[dIfy, HoldFirst];
dIfy[int : Integrate[_, varsSpec__]] := Module[{vars, strform},
vars = ToString[If[ListQ[#], First[#], #]] & /@ {varsSpec};
strform = ToString[TeXForm[HoldForm[int]]];

CopyToClipboard@
OutputForm["$" <> StringReplace[strform, ("d" ~~ # -> "\\mathrm{d}" <> # &) /@ vars] <> "$"]]

dIfy[Integrate[z x^2 + y^2, {x, -1, 1}, {y, -1, 1}, z]]


$$\int _{-1}^1\int _{-1}^1\int \left(z x^2+y^2\right)\mathrm{d}z\mathrm{d}y\mathrm{d}x$$

For educational purposes, here's the first version I made. It works the same while being less coherent, but it shows a typical use-case for Fold:

repl1[str_, sym_] := StringReplace[str, "d" <> sym -> "\\mathrm{d}" <> sym];

SetAttributes[dIfy, HoldFirst];
dIfy[int : Integrate[_, varsSpec__]] := Module[{vars, strform},
vars = ToString[If[ListQ[#], First[#], #]] & /@ {varsSpec};
strform = ToString[TeXForm[HoldForm[int]]];
CopyToClipboard@OutputForm["$" <> Fold[repl1, strform, vars] <> "$"]];

-
Perhaps "d"~~x_ :> "\\mathrm{d}"<>x would be a more suitable replacement rule? – VF1 May 6 '13 at 3:58
@amr "\, d" is only seen in the one-dimensional integral. For the multi-dimensional situation, Mathematica will output something like:\int _1^2\int _1^2x y^2dydx – luyuwuli May 6 '13 at 4:35
@luyuwuli d'oh! fixed – amr May 6 '13 at 4:52
I don't understand, my computer doesn't run. – minthao_2011 May 6 '13 at 5:08
@amr Actually I'm thinking how to deal with even more general situations. i.e. If one variable in the integrand has name with letter d like "det", after running your code, "det" will be wrapped by \text{}. In order to deal with the most general situation, I have an idea that before changing the integral to TexForm, we have to extract the actual integral parameter first(in this case "x"), then change the expression to string, then replace the "d". But temporarily I don't know how to do that. Wish you can make it:) – luyuwuli May 6 '13 at 5:11