Here's a LuaLaTeX-based solution. It works with numeric exponents with any number of digits, not just either 1 or 2 digits. It can also handle the presence of an optional sign symbol (-
or +
) at the start of the exponent.

In case you're curious about what the code does: (a) It sets up a Lua function, called fix_expo
, which scans lines of input and replaces all instances of ^
followed by possibly some whitespace, followed by the pattern "optional -
or +
symbol, followed by possibly some whitespace, followed by 1 or more digits" with ^{<pattern>}
. (b) The LaTeX macro \FixExpo
assigns the Lua function to LuaTeX's process_input_buffer
callback. This callback operates at a very early stage, before TeX starts its regular input processing.
Should you need to terminate operation of this function for some reason, simply issue the directive \UnfixExpo
. To reactivate the function, simply run \FixExpo
again.
It's straightforward to add some overhead code that ensures that the Lua function fix_expo
does not operate inside verbatim
-like environments. (Or, if your document doesn't contain too many verbatim-like environments, simply execute \UnfixExpo
and \FixExpo
, respectively, before and after such environments.)
% !TeX program = lualatex
\documentclass{article}
%% Lua-side code:
\usepackage{luacode}
\begin{luacode}
function fix_expo( s )
return ( s:gsub ( "%^%s-([%-%+]?%s-%d+)", "^{%1}" ) )
end
\end{luacode}
% LaTeX-side code: Macros '\FixExpo' and '\UnfixExpo'
\newcommand\FixExpo{\directlua{
luatexbase.add_to_callback ( "process_input_buffer" , fix_expo , "fix_expo")}}
\newcommand\UnfixExpo{\directlua{
luatexbase.remove_from_callback ( "process_input_buffer" , "fix_expo")}}
% Activate the Lua function by default:
\AtBeginDocument{\FixExpo}
\begin{document}
$2^0+2^1+\dots+2 ^ 31=2 ^ 32-1 \ne 2^ 387 $
$x ^ 5555 - y ^ 6666
=z^77777$
$x^-100+x^-10+x^-1+x^0+x^+1+x^+10+x ^ + 100$
\end{document}
^{2}
etc. – user31729 Jun 7 '17 at 7:37x^n
is x^{n}` but what do you wantx^max
to be, orx^my^n
? – David Carlisle Jun 7 '17 at 7:52