LaTeX command with superscript and subscript

I inherited the command below from another user

\newcommand{\den}[2][]{%
\mbox{$\llbracket$\bfseries #2$\rrbracket^{#1}$}%
}


This allows the use of \den with an optional superscript. As such, either \den{word} or \den[1]{word} can be used.

How can I also add an argument for subscript, so that I can either leave out all arguments or include both arguments? For example, these should all be legal:

\den{word}
\den[][i]{word}
\den[a][i]{word}


With xparse it's easy to add several optional arguments.

\documentclass{article}
\usepackage{xparse} % for the main command
\usepackage{stmaryrd} % for the brackets

\NewDocumentCommand{\den}{oom}{%
$\llbracket \mbox{\bfseries#3} \rrbracket \IfValueT{#2}{_{#2}} \IfValueT{#1}{^{#1}}$%
}

\begin{document}

\den{word}

\den[a]{word}

\den[a][i]{word}

\den[][i]{word}

\end{document}


A different implementation with a key-value syntax:

\documentclass{article}
\usepackage{xparse} % for the main command
\usepackage{stmaryrd} % for the brackets

\ExplSyntaxOn
\NewDocumentCommand{\den}{O{}m}
{
$\keys_set:nn { adamg/den } { #1 } \llbracket \mbox{\bfseries#2} \rrbracket \tl_if_empty:NF \l_adamg_den_sub_tl { \tl_if_empty:NT \l_adamg_den_sup_tl { \sp{} } \sb{\l_adamg_den_sub_tl} } \tl_if_empty:NF \l_adamg_den_sup_tl { \sp{\l_adamg_den_sup_tl} }$
}
{
}
\ExplSyntaxOff

\begin{document}

\den{word}

\den[sup=a]{word}

\den[sup=a,sub=i]{word}

\den[sub=i]{word}

\end{document}

• Thanks! What's the advantage of the second one? – Adam_G May 2 '17 at 23:27
• @Adam_G You don't care whether sub comes before or after sup, for instance. And you don't risk to forget the empty optional argument if you only want the subscript. – egreg May 2 '17 at 23:28