# Problems with spacing in lstlisting with escaped code

Consider the following code:

\documentclass{beamer}
\usepackage{listings}

\begin{document}

\begin{frame}[fragile]{title}
\begin{lstlisting}[escapeinside={!*}{*!},]
\end{lstlisting}
\end{frame}

\end{document}


As you can see, the spacing (or the font) in the word inside the escaped code changes. How can I make it to look the same?

I need to change specific parts inside the listing, but the spacing inconsistencies is a problem.

• If the alignment structure of the code allows it, I prefer option columns=flexible that sets the spacing more naturally and solves the issue for this instance. However "escaping" means being outside the listings column alignment. Another option could be keyword highlighting and similar. – Heiko Oberdiek Apr 4 '14 at 19:56
• Do you want to highglight only the second "add"? Not the first one? – jub0bs Apr 4 '14 at 20:39
• The problem is that the spacing is changing. I put both to illustrate the problem. Imagine that in a normal usage, the changed part will be surrounded by code, and it will look strange. – adn Apr 4 '14 at 21:07
• Yes, sorry I got some trouble applying it as I had a custom style. But after a while I made it work. Sorry that I forgot to accept it. :) – adn Apr 7 '14 at 20:44

In case what you want to highlight is part of the code, my suggestion would be, not to define !* and *! as escape-to-LaTeX delimiters, but to simply define them as "invisible" delimiters that highlight their content in red, instead. That way, you don't get any discrepancy in column alignment between the normal code and the highlighted code. See my MWE below.

In case the highlighted bit is not code, then I don't think you should concern yourself about such a discrepancy in column alignment. For instance, have a look at the bottom screenshot on this answer; do you find anything shocking?

\documentclass{beamer}

\usepackage{listings}

% Definition of custom delimiters
% (the i' means the delimiters themselves don't get printed)
\lstset{moredelim=[is][\color{red}]{!*}{*!}}

\begin{document}

\begin{frame}[fragile]{title}
\begin{lstlisting}

• I see that you did good amount of digging into listings and code production. Good work. Hope we will get more (like matlab-pretty) :) – user11232 Apr 5 '14 at 0:02
• @HarishKumar I still wouldn't claim that I know the listings source code well; it's pretty intricate. But once I release matlab-prettifier officially, I might do other similar things with listings`, if there is a need. – jub0bs Apr 5 '14 at 11:27