1

I would like to hide some parts of a lstlisting code and change it into a white rectangle (for example) for my students. Besides, under a boolean condition, I would like to come back to the version without the gaps.

With texts it is easy by using the package dashundergaps, but it doesn't work with lstlisting.

\documentclass[a4paper,10pt,table]{book}
\usepackage{ifthen}
\usepackage{listings}
\begin{document}
    \begin{lstlisting}
        answer=[]#How to hide this line ?
        def myqyestion():
            return answer
    \end{lstlisting} 
\end{document}
siracusa
  • 13,411
jowe_19
  • 939

1 Answers1

2

I tried this solution (from How can I hide (or blur) some code in a listing?):

    \documentclass{article}
    \usepackage{ifthen}
    \usepackage{tikz} %to be used with package below:
    \usepackage[confidentiel]{optional}
    \newlength\heightconf
    \newlength\widthconf

    \usepackage[confidentiel]{optional}

    \newcommand\troualgo{}

    \newboolean{etu}
    \setboolean{etu}{false}

    \ifetu
    \renewcommand\troualgo[1]{%
    \opt{confidentiel}{%
     \settoheight{\heightconf}{#1}%
     \settowidth{\widthconf}{#1}%
     \tikz{\node[inner sep=0pt,rectangle,draw,anchor=base,textheight=\heightconf,textwidth=\widthconf,fill=white]{};}}
    \opt{libre}{#1}}
    \fi

    \usepackage{listings}
    \lstset{escapechar=\£}
    \lstdefinestyle{python}{language=Python,basicstyle=\small\ttfamily,xleftmargin=0.3em,keywordstyle=\color{red}\bfseries\underbar,commentstyle=\color{blue},stringstyle=\ttfamily,showstringspaces=false,numbers=left,numberstyle=\itshape\bfseries\footnotesize,aboveskip=0.35cm,belowskip=0.5cm,backgroundcolor =\color{white},columns=[l]flexible,escapechar=\£}

    %starting document 
    \begin{document}

    \begin{lstlisting}[style=python]
    for i in range(1,3):
        a=b
        £\troualgo{b=c;}£
        c=d
        £\troualgo{print(c);}£
    \end{lstlisting}

    \end{document}
jowe_19
  • 939