Listings lstdefinestyle not work with custom defined command

key-valuelistings

I defined a new command named '\showLineNo', and used in '\lstdefinestyle', got an error:

Package Listings Error: Numbers none unknown. \lstset{style=customstyleone}

sample code:

\documentclass{article}
\RequirePackage{listings}

\def\showLineNo{none}

\lstdefinestyle{customstyleone}{
    numbers=\showLineNo,
    numbersep=5pt
}
\lstset{style=customstyleone}

\begin{document}
\begin{lstlisting}[language=Python, caption=python code example]
    def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable
\end{lstlisting}
\end{document}

but work as follow:

\documentclass{article}
\RequirePackage{listings}

\lstdefinestyle{customstyleone}{
    numbers=none,
    numbersep=5pt
}
\lstset{style=customstyleone}

\begin{document}
\begin{lstlisting}[language=Python, caption=python code example]
    def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable
\end{lstlisting}
\end{document}

How can I use custom command pass to lstdefinestyle?

Best Answer

The listings package uses a mechanism which doesn't expand the value of the numbers key to search for the valid values (while the error recovery does expand the value). Hence your usage with a macro holding the value for numbers doesn't work like that.

We could however define an alternative key (if it doesn't exist yet) which expands its value and passes it to the numbers key. You could consider the following a small hack, as we play with listings keyval-namespace (or an extension?).

\documentclass{article}
\RequirePackage{listings}

\def\showLineNo{none}

\makeatletter
\@ifundefined{KV@lst@numbers-expanded}
  {%
    \define@key{lst}{numbers-expanded}
      {\expandafter\KV@lst@numbers\expanded{{#1}}}%
  }
  {\GenericError{}{key numbers-expanded already defined}{}}
\makeatother
\lstdefinestyle{customstyleone}{
    numbers-expanded=\showLineNo,
    numbersep=5pt
}
\lstset{style=customstyleone}

\begin{document}
\begin{lstlisting}[language=Python, caption=python code example]
    def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable
\end{lstlisting}
\end{document}
Related Question