[Tex/LaTex] How to instruct listings package to correctly handle SQL comments in external source files

commentslistings

The listings in SQL containing -- style comments come across as −− when pasted from PDF (if lmodern is used, otherwise as ??). I looked at these answers but do not see how I could use them with the listings (which I mostly load from the external files (if that matters): How do I prevent LaTeX from creating en-dash and em-dash?

\documentclass[11pt,letterpaper]{memoir}
\usepackage{lmodern}
\usepackage{listings}
\lstloadlanguages{SQL}

\lstset {
    frameround=fttt
    ,language=SQL
    ,numbers=left
    ,breaklines=true
    ,showstringspaces=false
    ,columns=flexible
    ,keepspaces=true
}

\begin{document}

\begin{lstlisting}
select 1
-- This is just a comment
select 2
\end{lstlisting}

\end{document}

The results look as follows in Sql Studio after pasting from PDF (third line is what they should look like):

enter image description here

EDIT:

I tried using the method proposed in listings package changes hyphens to minus signs and it worked fine for just the common SQL comment lines (ex: -- This is a comment), but it had a side effect on the output listings, where the field names are separated from data with the lines containing multiple dashes:

field1
--------------
1.33333333

These have an extra space after the first 2 dashes and look as follows:

enter image description here

MWE with the linked suggestion implemented:

\documentclass[11pt,letterpaper]{memoir}
\usepackage{listings}

\makeatletter
\lst@CCPutMacro\lst@ProcessOther {"2D}{\lst@ttfamily{-{}}{-{}}}
\@empty\z@\@empty
\makeatother

\lstset {
    frameround=fttt
    ,language=SQL
    ,breaklines=true
    ,columns=flexible
}

\begin{document}

\begin{lstlisting}
field1
--------------
1.3333333

field1    field2
--------- --------------
9.66667   9.66667
\end{lstlisting}

\end{document}

Best Answer

The source of problem with the uneven spacing is the columns=flexible option: with it listings tries to reinsert missing space after each "block" of input, in your case after two -- as they consist of a block due to the comment definition. As the hyphen is a bit smaller then the default column width of 0.45em, you get an space.

There are various ways to get around the problem:

Make the default width of a flexible column smaller:

\begin{lstlisting}[caption={extra spaces},label={lst:sp},nolol=true,numbers=none,%
                   basewidth={0.6em,0.37em}
                   ]

Make the hyphen larger:

\lst@CCPutMacro\lst@ProcessOther {"2D}{\lst@ttfamily{-{}}{{\Large-}{}}}
\@empty\z@\@empty

or put it in a larger box:

\lst@CCPutMacro\lst@ProcessOther {"2D}{\lst@ttfamily{-{}}{\makebox[0.45em]{-}{}}}
\@empty\z@\@empty