3

MWE

\documentclass{article}

\usepackage{listings}
\usepackage{lmodern}

\lstset{
  language=C,
  basicstyle=\ttfamily,
  commentstyle=\rmfamily
}

\begin{document}
\begin{lstlisting}
int a; // a number
int b; // another number
// ...
int sum = add(a, b); // their sum
\end{lstlisting}
\begin{lstlisting}[columns=fullflexible]
int a; // a number
int b; // another number
// ...
int sum = add(a, b); // their sum
\end{lstlisting}
\end{document}

I'd like to sort of merge these two styles:

  • fixed column alignment for code (or anything not a comment)
  • fullflexible column alignment for comments
2
  • 2
    What about not using fixed altogether? The monospaced font for the code part already ensures column alignment; expanding the interletter space just makes for difficult reading. – egreg Feb 24 '15 at 18:25
  • @egreg I'm not guaranteed the author will want to use monospace code – Sean Allred Feb 24 '15 at 18:51
9

It seems that it's possible, adding \lst@column@fullflexible to the commentstyle.

So, with

\makeatletter
\let\commentfullflexible\lst@column@fullflexible
\makeatother

define your \lstset as

\lstset{
  language=C,
  basicstyle=\ttfamily,
  commentstyle=\rmfamily\commentfullflexible
}

MWE:

\documentclass{article}

\usepackage{listings}
\usepackage{lmodern}

\makeatletter
\let\commentfullflexible\lst@column@fullflexible
\makeatother

\begin{document}

\lstset{
  language=C,
  basicstyle=\ttfamily,
  commentstyle=\rmfamily
}

\begin{lstlisting}[caption={Normal comments}]
int a; // a number
int b; // another number
// ...
int sum = add(a, b); // their sum
\end{lstlisting}

\lstset{
  language=C,
  basicstyle=\ttfamily,
  commentstyle=\rmfamily\commentfullflexible
}

\begin{lstlisting}[caption={Fullflexible comments}]
int a; // a number
int b; // another number
// ...
int sum = add(a, b); // their sum
\end{lstlisting}
\end{document} 

Output:

enter image description here

1
  • Thanks! This answers the question, but I do personally wonder if there's a way to keep the // teletype – but that's not in the scope of this question :) But for those who might want this, I would define \commentfullflexible to perhaps somehow parse the // comment with a low-level \def (or expl3 equivalent), setting the // in basicstyle. If I come up with a good answer, I'll ask a separate Q and self-answer (unless anyone else is curious enough to beat me to the punch). – Sean Allred Feb 24 '15 at 19:00

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.