[Tex/LaTex] Escapeinside in lstinputlisting

listings

The defined escapeinside sequence does not work within the lstinputlisting.

At first, I defined the escapeinside as follow:

\lstset{
        basicstyle=\ttfamily,
        numbers=left,
        numberstyle=\tiny, 
        numbersep=5pt,
        frame=single,
        % start delimiter: (*, end delimiter: *)
        escapeinside={(*}{*)},  
        gobble=8,
        captionpos=b,
        aboveskip=15pt,
        belowskip=-0.5 \baselineskip,
        breaklines=true
    } 

As the code snippets are relatively large, I include them by using lstinputlisting:

\lstinputlisting[
    label=lst:my_code_sample,
    caption={My caption.},
    language=python]
{code/my_code_sample.py}

Then I tried to insert a line reference into my_code_sample.py by including a label within the defined escape sequence:

def do_something(self, attack_name: str):
    """
    A short description of the method comes here.
    """
    # Load attack class
    attack_module = importlib.import_module(attack_name) (*\label{testtest}*)
    attack_class = getattr(attack_module, attack_name)

But instead of creating the label, LaTeX shows the error:

File ended while scanning use of \lst@BOLGobble@.

Is the lstinputlisting not compatible with the escapeinside command?

Best Answer

It works flawlessly if I remove the gobble=8 option.

\begin{filecontents*}{\jobname.py}
def do_something(self, attack_name: str):
    """
    A short description of the method comes here.
    """
    # Load attack class
    attack_module = importlib.import_module(attack_name) (*\label{testtest}*)
    attack_class = getattr(attack_module, attack_name)
\end{filecontents*}

\documentclass{article}
\usepackage{listings}

\lstset{
  basicstyle=\ttfamily,
  numbers=left,
  numberstyle=\tiny, 
  numbersep=5pt,
  frame=single,
  % start delimiter: (*, end delimiter: *)
  escapeinside={(*}{*)},  
%  gobble=8,
  captionpos=b,
  aboveskip=15pt,
  belowskip=-0.5 \baselineskip,
  breaklines=true,
}

\begin{document}

\begin{lstlisting}[language=python]
def do_something(self, attack_name: str):
    """
    A short description of the method comes here.
    """
    # Load attack class
    attack_module = importlib.import_module(attack_name) (*\label{test}*)
    attack_class = getattr(attack_module, attack_name)
\end{lstlisting}

\lstinputlisting[
    label=lst:my_code_sample,
    caption={My caption.},
    language=python
]{\jobname.py}

\end{document}

Here's the .aux file, which shows the label is set:

\relax 
\newlabel{test}{{6}{1}}
\newlabel{lst:my_code_sample}{{1}{1}}
\@writefile{lol}{\contentsline {lstlisting}{\numberline {1}My caption.}{1}}
\newlabel{testtest}{{6}{1}}

enter image description here

Related Question