![使用箭头指向特定的代码块并为关键字分配背景颜色](https://linux22.com/image/464740/%E4%BD%BF%E7%94%A8%E7%AE%AD%E5%A4%B4%E6%8C%87%E5%90%91%E7%89%B9%E5%AE%9A%E7%9A%84%E4%BB%A3%E7%A0%81%E5%9D%97%E5%B9%B6%E4%B8%BA%E5%85%B3%E9%94%AE%E5%AD%97%E5%88%86%E9%85%8D%E8%83%8C%E6%99%AF%E9%A2%9C%E8%89%B2.png)
这是我的代码:
\documentclass[a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\usepackage{listings}
\usepackage{xcolor}
\def\tikzmark#1{\tikz[remember picture,overlay]\node[yshift=2pt](#1){};}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
escapeinside={*}{*},
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
\usepackage[absolute,overlay]{textpos}
\newcommand\PlaceText[3]{%
\begin{textblock*}{10in}(#1,#2) %% change width of box from 10in as you wish
#3
\end{textblock*}
}%
\begin{document}
\begin{lstlisting}[language=Python]
# Here is the function:
def hello():*\tikzmark{A}*
print("Hello together!")
# Main:
hello() *\tikzmark{B}*
hello() *\tikzmark{C}*
hello() *\tikzmark{D}*
\end{lstlisting}
\tikzset{Empharrow/.style={dashed,red,thick,->,arrows={-Triangle[width=3pt]}}}
\begin{tikzpicture}[remember picture,overlay]
\draw[Empharrow](D)--+(7cm,0)|-(A);
\draw[Empharrow](C)--+(6cm,0)|-(A);
\draw[Empharrow](B)--+(5.5cm,0)|-(A);
\end{tikzpicture}
\PlaceText{100mm}{60mm}{The \texttt{hello()} function is called here}
\end{document}
输出:
有没有更优雅的方法?尽管如此,我主要关心的是代码中某些单词的背景颜色。
答案1
也许你正在寻找这个:
在这种情况下,您只需tikzpicture
像下面这样编辑,然后删除您的PlaceText
行。
其余一切都很好。
\begin{tikzpicture}[remember picture,overlay]
\draw[Empharrow](D)--+(7cm,0)|-(A.north east)node[pos=0.25,right,text width=4cm]{The \texttt{hello()} function\\is called here};
\draw[Empharrow](C)--+(6cm,0)|-(A);
\draw[Empharrow](B)--+(5.5cm,0)|-(A.south east);
\end{tikzpicture}