Search code examples
latexlistings

Comment in listings environment


When I write my code in listings environment and try writing "comment" as comment, I see this in my pdf:

breaking#breakingcomment

I want to have a simple comment as "#comment" I don't know why and don't know how to do to resolve the problem. This is my start declaration:

\lstdefinelanguage{Python}
{
  morekeywords={from, import, def, return},
  morecomment=[l]{\#},
  morestring=[b]",
  alsodigit={-},
  alsoletter={&}
}

\lstdefinestyle{custompython}{
    language=Python,
    frame=tlrb,
    aboveskip=3mm,
    belowskip=5mm,
    backgroundcolor=\color{gray},
    showstringspaces=true,
    columns=flexible,
    basicstyle={\small\ttfamily},
    numbers=left,
    numberstyle=\tiny\color{orange}\ttfamily,
    numbersep=5pt,
    keywordstyle=\color{Green},
    commentstyle=\color{orange},
    stringstyle=\color{purple},
    commentstyle=\small\color{red}\ttfamily
    breaklines=false,
    breakatwhitespace=true
    tabsize=5
}

And this is what I write inside listings environment:

\begin{lstlisting}[language=Python, style=custompython, label=code:source, caption = Code]

sers_ind, q, re = 4, 0.7, 1
srcx, srcy = 0, 0
ammasso = lens #comment
sorgente = serSource

\end{lstlisting}

Solution

  • You are missing the , after the commentstyle key:

    \documentclass{article}
    
    \usepackage{listings}
    \usepackage{xcolor}
    
    \lstdefinelanguage{Python}
    {
      morekeywords={from, import, def, return},
      comment=[l]{\#},
      morestring=[b]",
      alsodigit={-},
      alsoletter={&},
    }
    
    \lstdefinestyle{custompython}{
        language=Python,
        frame=tlrb,
        aboveskip=3mm,
        belowskip=5mm,
        backgroundcolor=\color{gray},
        showstringspaces=true,
        columns=flexible,
        basicstyle={\small\ttfamily},
        numbers=left,
        numberstyle=\tiny\color{orange}\ttfamily,
        numbersep=5pt,
        keywordstyle=\color{Green},
        commentstyle=\color{orange},
        stringstyle=\color{purple},
        commentstyle=\small\color{red}\ttfamily,
        breaklines=false,
        breakatwhitespace=true,
        tabsize=5
    }
    
    
    \begin{document}
    
    \begin{lstlisting}[language=Python, style=custompython, label=code:source, caption = Code]
    
    sers_ind, q, re = 4, 0.7, 1
    srcx, srcy = 0, 0
    ammasso = lens #comment
    sorgente = serSource
    
    \end{lstlisting}
    
    
    \end{document}
    

    enter image description here