使用箭头指向特定的代码块并为关键字分配背景颜色

使用箭头指向特定的代码块并为关键字分配背景颜色

如何为某些单词和标点符号指定背景颜色?我希望它像下图这样: 在此处输入图片描述

这是我的代码:

\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}

相关内容