4

Consider the following code:

\documentclass{beamer}
\usepackage{listings}

\begin{document}

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

\end{document}

enter image description here

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.

6
  • 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
  • Did my answer help you? – jub0bs Apr 7 '14 at 17:08
  • 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
4

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?

enter image description here

\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}
int add
int !*add*!
\end{lstlisting}
\end{frame}

\end{document}
2
  • 1
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.