答案1
以下是基于这个帖子。
\documentclass{article}
\usepackage{tikz}
\usepackage{listings}
\usetikzlibrary{calc}
\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\begin{document}
\begin{lstlisting}[escapechar= !]
!\tikzmark{x1}!int gilligan(int j){
int marmot(int i){ do something really cool !\tikzmark{x4}!
int duck(int k){
!\tikzmark{x2}!cout<< i; !\tikzmark{x5}!
}
!\tikzmark{x3}! }
!\tikzmark{x6}!} !\tikz[overlay,remember picture]{\draw[fill=gray](x1.south)--([yshift=1pt]x2.west)--(x3.south)--cycle;}!
\end{lstlisting}
\tikz[overlay,remember picture]{%
\draw[fill=gray]([xshift=4pt]x6.south)--([xshift=8pt]x2.south)--(x5|-x2.south)--(x4.south)--(x4|-x6.south)
--cycle;}
\end{document}
我不确定阴影区域应该离代码有多近,但这可以调整。我还放了一个 Ti钾清单内的 Z 图片,因为你需要它如果代码跨越多页。
更新:如果你能提到你得到了一个非常好的答案关于相关问题。是的,也可以使用那里使用的方法。
\documentclass{article} % from https://tex.stackexchange.com/a/419865/121799
%\url{https://tex.stackexchange.com/q/419759/86}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\newcounter{tmlistings}
\newcounter{newtmlistings}
\newcommand\makenode[2]{%
\tikz[baseline=0pt, remember picture] { \node[fill=gray!50,thick,rounded corners,anchor=base,#1/.try] (listings-\the\value{tmlistings}) {#2}; }%
\stepcounter{tmlistings}%
}
\newcommand\makenewnode[2]{%
\tikz[baseline=0pt, remember picture] { \node[inner
sep=0pt,anchor=base,#1/.try] (newlistings-\the\value{newtmlistings}) {#2}; }%
\stepcounter{newtmlistings}%
% \typeout{\thenewtmlistings}
}
% \tikzset{
% keyword/.style={
% fill=gray!75,
% draw=black
% }
% }
\lstset{
keywordstyle=\makenewnode{keyword},
stringstyle=\makenewnode{string},
identifierstyle=\makenewnode{identifier},
}
\begin{document}
\begin{lstlisting}[language=c,escapechar=!]
int gilligan (int j) {
for (int i = 1; i < j; i++) {
if (i % 2 == 0) {
cout << i
}
}
}!\makenewnode{keyword}{\strut}!
\end{lstlisting}
\begin{tikzpicture}[remember picture,overlay]
% \foreach \i [evaluate={\j=int(\i+1)}] in {0,...,12}
% {\draw (newlistings-\i)node[left]{\i} --(newlistings-\j); }
\draw[fill=gray] (newlistings-0.south west) -- ([xshift=-4pt]newlistings-12.west)
-- (newlistings-14.north-| newlistings-0.south west) -- cycle;
\draw[fill=gray] (newlistings-14.south) -- ([yshift=-2pt]newlistings-12.south)
-- ([xshift=1.1cm,yshift=-2pt]newlistings-12.south east)
-- ([xshift=1.3cm,yshift=-2pt]newlistings-9.south east)
-- ([xshift=1.3cm,yshift=-2pt]newlistings-9.south east |- newlistings-14.south)
-- cycle;
\end{tikzpicture}
\end{document}