I need to set subscripts and superscripts automatically in mathematical equations in roman font style for a book publication. I do not want to apply \mathrm{...} to each subscript or superscript separately.

can't you just replace _ by ^ and \sb by \sp ?
– David CarlisleJul 19 '17 at 7:47

I assume you never raise to the power of a variable, and instead only use descriptive superscripts in your field? Because in $x \mathrm{e}^{\mathrm{x}}$ the two xs are different entities, while in $x \mathrm{e}^x$ they're not.
– Chris HJul 19 '17 at 8:53

1

Correct, I only use descriptive superscripts.
– christiankralJul 19 '17 at 9:52

I really hope this is because it's a book about a field that only uses descriptive text superscripts rather than powers. I've come across this but can;t recall what uses it.
– Chris HJul 19 '17 at 8:56

@egreg, thanks a lot for your solution. It works very well for me.
– christiankralJul 19 '17 at 9:54

The (German) publisher insists on roman subscripts and superscripts. So the only choice I have is to either manually re-format (some older) LaTeX code use this trick to globally change the format.
– christiankralJul 19 '17 at 9:58

2

@christiankral If the publisher tells me that $x_{n}$ must have the “n” in upright type, I tell them they don't know about mathematics. Of course, this depends on what the subscripts/superscripts contain.
– egregJul 19 '17 at 10:50

Here's a LuaLaTeX-based solution. It doesn't change the catcodes of _ and ^. Instead, it sets up a Lua function and assigns it to the process_input_buffer callback; that way, all instances of _{...} and ^{...} are converted to _{\mathrm{...}} and ^{\mathrm{...}}, respectively, before LaTeX even starts its usual processing.

Whitespace between _/^ and the material enclosed in curly braces is OK. However, the presence of the curly braces is significant: the Lua function will not modify the appearance of y^x and x_n, say.