[Tex/LaTex] Left align text in the listings package

listings

I want the text to be "left aligned" in MS Word jargon, in the listings.

Please see the snip below. Notice the amount of white space before and after the word "first" are different. I do not want the extra white space after "first".

enter image description here

Below is the code that produces this:

\documentclass[]{article}
\usepackage{listings}
\begin{document}

\begin{figure}[h!]
\lstset{
    language=Python,
    numberstyle=\tiny,
    deletekeywords={from,in,and},
    morekeywords={function,Algorithm,algorithm, then,do},
    mathescape=true,
    numbers=left,
    xleftmargin=.04\textwidth,
    breaklines=true,
    flexiblecolumns=true
}
\begin{lstlisting}
            Z = Y(from 1 to rand(1, Size(P(j))) # from the first till a random value

\end{lstlisting}
\caption{figure caption}
\label{fig1}
\end{figure}

\end{document}

Best Answer

You need columns=fullflexible

\documentclass[]{article}
\usepackage{listings}
\begin{document}

\begin{figure}[h!]
\lstset{
    language=Python,
    numberstyle=\tiny,
    deletekeywords={from,in,and},
    morekeywords={function,Algorithm,algorithm, then,do},
    mathescape=true,
    numbers=left,
    xleftmargin=.04\textwidth,
    breaklines=true,
    columns=fullflexible,
    flexiblecolumns=true,
}
\begin{lstlisting}
            Z = Y(from 1 to rand(1, Size(P(j))) # from the first till a random value

\end{lstlisting}
\caption{figure caption}
\label{fig1}
\end{figure}

\end{document}
Related Question