# How can I consistently adjust kerning within and outside of subscripts?

I want to define a macro that shows an array access in a language like in C or Java.

My first try looked like this:

\newcommand{\accessI}[2]{#1\left[#2\right]}
$\accessI{a}{i}$


I didn't like this because the kerning of the brackets didn't seem right (they should be closer, imho). The kerning can be easily fixed with \mkern.

\newcommand{\accessII}[2]{#1\mkern-3mu\left[#2\right]}
$\accessII{a}{i}$


This looks great, but when I use terms like this in a subscript, the kerning looks bad again (this time the brackets are too close).

$A_{\accessII{a}{i}}$


I'm now looking for either

• a command like \mkern that is context-dependent (i.e. that shrinks the adjustments when used in a subscript) or
• a way to tell in which context the macro is used so that I can use different \mkern-calls in the \accessII macro

The excessive amount of space around \left[ i\right] is there by design. If you want to avoid this design feature, I'd like to suggest that you make use of either the mleftright package and its \mleft and \mright macros or the mathtools package and its \DeclarePairedDelimiter macro. In the following example, these ideas are used to create user-level macros called \accessII and \accessIII, respectively.

\documentclass{article}

\usepackage{mathtools}  % for \DeclarePairedDelimiter macro
\DeclarePairedDelimiter\brackets\lbrack\rbrack

\usepackage{mleftright} % for \mleft and \mright macros

\newcommand{\accessII}[2]{#1\mleft[#2\mright]}  % good
\newcommand{\accessIII}[2]{#1\brackets*{#2}}    % equally good

\begin{document}
$\accessI{a}{i} \quad \accessII{a}{i} \quad \accessIII{a}{i} \quad A_{\accessII{a}{i}} \quad A_{\accessIII{a}{i}}$
\end{document}


I marked Mico's answer as correct because it solved my specific problem, but if anyone needs to do something similar that is not related to parentheses, they can (as I have learned in the mean time) use the \mathchoice macro that is explained elsewhere on on the TeX stack exchange (What is \mathchoice?). For the problem at hand one could for example define

\newcommand{\accessIV}[2]{#1
\mathchoice{\mkern-3mu}{\mkern-3mu}{\mkern-1.5mu}{\mkern-2mu}
\left[#2\right]}


To have different kerning in different positions:

$\accessIV{a}{i}$
$A_{\accessIV{a}{i}}$
$A_{a_{\accessIV{a}{i}}}$


• This solution may take care of the excess-whitespace issue between a and [i], but it does not fix the excessive amount of whitespace that \accessIV ends up inserting between [i] and a subsequent character, say, . ("period") if TeX is in \displaystyle or \textstyle math mode. E.g., do compare the outputs of \accessIV and the \mleft/\mright approach in expressions such as $\displaystyle \accessIV{a}{i}. \quad a\mleft[i\mright].$ and $\textstyle \accessIV{a}{i}. \quad a\mleft[i\mright].$.
– Mico
Aug 28, 2022 at 10:27