# Centralize an \includegraphics within a \def

This question is prompted by an answer I was giving here, in which I used \includegraphics{...} within a \def definition, in order to include graphics in an in-line context.

Question: How do I go about centralising the included graphic, when using in-line, without resorting to manual ways like \hspace{}? I tried with \centering, but that has no effect. I've added fbox in the example below to make it more apparent.

\documentclass{article}
\usepackage{graphicx,keystroke,scalerel}
\renewcommand{\fboxsep}{0pt}
\def\abcd{%
{\centering \fbox{\scalerel*{\includegraphics{example-image-a}}{X}}}
}

\begin{document}
This is an in-line graphic \fbox{\keystroke{\abcd}}.

This is an in-line graphic \fbox{\abcd} with some space on either side.
\end{document}


ps. I was using it in \keystroke{...} from the keystroke package, but the problem is more general, and can be described without the keystroke package. However, please do address this in your answer if it is any different from the case without using keystroke, as I would like to improve on my answer there.

• You are adding an extra space to the right; use % after }. Apr 17 '17 at 4:06
• Oh darn, I gotta be more careful with this in the future. you can leave an answer and I'll accept it.
– Troy
Apr 17 '17 at 4:10
• \centering is doing nothing in your example, but it isn't clear what you want it to do, \fbox fits closely around its content so there is nothing to centre? Apr 17 '17 at 7:56
• @DavidCarlisle You're right, I was intending for the \centering to somehow apply to the \keystroke, not so much centering it in the fbox itself.
– Troy
Apr 17 '17 at 8:08

As noted by others, there are several problems. Stray spaces were creeping in, because lines inside a macro definition were not ended in a %. Also, \centering has no relevance outside of TeX's paragraph setting mechanism, which does not apply inside an \fbox. Finally, \fboxsep is a length, not a definition, and so should be set as such. In TeX, that would be \fboxsep=0pt\relax, while in LaTeX, one can preferably use \setlength{\fboxsep}{0pt}.

\documentclass{article}
\usepackage{graphicx,keystroke,scalerel}
\setlength{\fboxsep}{0pt}
\newcommand\abcd{\fbox{\scalerel*{\includegraphics{example-image-a}}{X}}}
\begin{document}
This is an in-line graphic \fbox{\keystroke{\abcd}}.

This is an in-line graphic \fbox{\abcd} with some space on either side.
\end{document}


• Please, also fix \renewcommand{\fboxsep}{0pt}, which should be \setlength{\fboxsep}{0pt}. Jun 21 '17 at 13:13
• @egreg Ack!! I didn't see that! Jun 21 '17 at 13:16
• Simpler than loading scalerel: \includegraphics[height=\fontcharht\fontX]{example-image-a}`. Jun 21 '17 at 13:20
• @egreg Geez...if I could downvote my answer, I would! Jun 21 '17 at 13:24