Estilo numérico personalizado para linhas \ref'ed em um ambiente de listagem

Estilo numérico personalizado para linhas \ref'ed em um ambiente de listagem

Considere o seguinte MWE:

\documentclass{article}

\usepackage{tikz}

\usepackage{listings}

\lstset{%
  basicstyle =\ttfamily,
  language = Python,
  keywordstyle = \bfseries,
  commentstyle = \itshape,
  numbers = left,
  numberstyle = \tiny\sffamily,
  escapechar = |,
  gobble = 2,
}

\begin{document}

\begin{lstlisting}
  import numpy as np
  from matplotlib import pyplot as plt

  t = np.linspace(0, 1, 100) |\label{that-line}|
  plt.plot(t, t**2)
  plt.show() |\label{that-other-line}|
\end{lstlisting}

Please see line~\ref{that-line} and line~\ref{that-other-line}.

\end{document}

A saída atual é:

saída de listagem

Gostaria que os números correspondentes às linhas editadas \ref(portanto, as linhas 4 e 6 no meu MWE) tivessem um estilo específico (por exemplo, digitado dentro de um quadrado ou círculo, de preferência tikzcódigo arbitrário). Por exemplo:

com círculos

Responder1

Uma adaptação da minha resposta emComo adicionar símbolos de círculo numerados referíveis às listagens de código?:

\documentclass{article}

\usepackage{tikz}

\usepackage{listings}

\usepackage{circledsteps}
\pgfkeys{/csteps/outer color=orange}

\lstset{%
  basicstyle =\ttfamily,
  language = Python,
  keywordstyle = \bfseries,
  commentstyle = \itshape,
  numbers = left,
  numberstyle = \tiny\sffamily,
  escapechar = |,
  gobble = 2,
}
\makeatletter
\newcommand*\CircleNext{%
  \lst@AddToHook{OnNewLine}{%
   \def\thelstnumber{\Circled{\arabic{lstnumber}}\hskip-2.1pt}}%
}
\def\circlabel#1{
  \lst@AddToHook{OnNewLine}{%
   \def\thelstnumber{\arabic{lstnumber}}}%
  \label{#1}%
}
\makeatother
\begin{document}

\begin{lstlisting}
  import numpy as np
  from matplotlib import pyplot as plt
  |\CircleNext|
  t = np.linspace(0, 1, 100) |\circlabel{that-line}|
  plt.plot(t, t**2)|\CircleNext|
  plt.show() |\circlabel{that-other-line}|
\end{lstlisting}

Please see line~\ref{that-line} and line~\ref{that-other-line}.

\end{document}

insira a descrição da imagem aqui


Abaixo uma variante que não precisa dos \CircleNextcomandos. Funciona escrevendo um rótulo extra que consiste no formato listing number-line number. Em vez de um OnNewLinegancho para listagens, agora o comando \thelstnumber(que imprime o número da linha para cada linha) é modificado para verificar se o rótulo da listagem atual e da linha atual existe ou não. Se o rótulo existir, o número será circulado (na próxima execução).

Infelizmente, \thelstnumbertambém é gravado no arquivo .aux como o texto do rótulo que é lido por \ref. Para evitar números circulados no texto principal, uma solução é redefinir temporariamente \thelstnumberpara ser apenas o número ao escrever o \label.

O resto do código é escrituração para criar e incrementar o contador de listagens que é utilizado na nova etiqueta.

Código:

\documentclass{article}
\usepackage{tikz}
\newcounter{lstprefix}
\setcounter{lstprefix}{0}
\usepackage{listings}
\AddToHook{env/lstlisting/before}{\stepcounter{lstprefix}}

\usepackage{circledsteps}
\pgfkeys{/csteps/outer color=orange}

\lstset{%
  basicstyle =\ttfamily,
  language = Python,
  keywordstyle = \bfseries,
  commentstyle = \itshape,
  numbers = left,
  numberstyle = \tiny\sffamily,
  escapechar = |,
  gobble = 2,
}
\makeatletter
\def\thelstnumber{%
\ifcsname r@lst\thelstprefix-\arabic{lstnumber}\endcsname%
\Circled{\arabic{lstnumber}}\hskip-2.1pt%
\else%
\arabic{lstnumber}%
\fi%
}
\def\circlabel#1{
  {\def\thelstnumber{\arabic{lstnumber}}\label{#1}}%
  \label{lst\thelstprefix-\arabic{lstnumber}}%
}
\makeatother
\begin{document}

\begin{lstlisting}
  import numpy as np
  from matplotlib import pyplot as plt
  
  t = np.linspace(0, 1, 100) |\circlabel{that-line}|
  plt.plot(t, t**2)
  plt.show() |\circlabel{that-other-line}|
\end{lstlisting}

Please see line~\ref{that-line} and line~\ref{that-other-line}.

\begin{lstlisting}
  import numpy as np
  from matplotlib import pyplot as plt |\circlabel{import-line}|
  
  t = np.linspace(0, 1, 100)
  plt.plot(t, t**2)
  plt.show()
\end{lstlisting}
See also line \ref{import-line}.
\end{document}

Isso cria o seguinte arquivo .aux:

\relax 
\newlabel{that-line}{{4}{1}}
\newlabel{lst1-4}{{\Circled {4}\hskip -2.1pt}{1}}
\newlabel{that-other-line}{{6}{1}}
\newlabel{lst1-6}{{\Circled {6}\hskip -2.1pt}{1}}
\newlabel{import-line}{{2}{1}}
\newlabel{lst2-2}{{\Circled {2}\hskip -2.1pt}{1}}
\gdef \@abspage@last{1}

informação relacionada