我正在使用该listings
包,包括使用\begin{lstlistings}
和使用\lstinputlisting
命令。现在,我想显示某些语言的列表语言。假设我有以下代码:
\documentclass[a4paper, 12pt, hidelinks]{report}
\usepackage[british]{babel}
\usepackage{listings, xcolor}
\lstdefinelanguage{Toml}{
comment = [l]{\#},
keywords = {true, false},
morestring = [b]{"}
}
\lstset{
tabsize = 2,
frame = tb,
breaklines = true,
numbers = left,
numbersep = 5pt,
numberstyle = \color{white!30!black}\scriptsize,
stepnumber = 1,
basicstyle = \footnotesize\ttfamily,
commentstyle={\color{green!50!black}\ttfamily},
keywordstyle = {\bfseries\color{purple}}, % keywords
keywordstyle = [2]{\itshape\color{blue}}, % traits
keywordstyle = [3]{\color{blue}}, % primitive types
keywordstyle = [4]{\color{blue}}, % type and value ctors
keywordstyle = [5]{\color{purple!50!blue}}, % macros
stringstyle = \color{green!45!blue},
aboveskip = \baselineskip,
showstringspaces = false
}
\begin{document}
\begin{lstlisting}[language=Toml]
[package]
name = "foobar"
\end{lstlisting}
\end{document}
我希望字符串TOML
以小灰色字母写在第一条水平线下方的右上角。
如果可能的话,我只想针对某些语言启用此功能。
答案1
一个解决方案是使用tcolorbox
。
编辑:同时使用环境(如lstlisting
)和命令(如lstinputlisting
)。
\documentclass[a4paper, 12pt, hidelinks]{report}
\usepackage[british]{babel}
\usepackage{listings, xcolor}
\usepackage[listings,skins]{tcolorbox}
\lstdefinelanguage{Toml}{
comment = [l]{\#},
keywords = {true, false},
morestring = [b]{"}
}
\lstset{
tabsize = 2,
frame = tb,
breaklines = true,
numbers = left,
numbersep = 5pt,
numberstyle = \color{white!30!black}\scriptsize,
stepnumber = 1,
basicstyle = \footnotesize\ttfamily,
commentstyle={\color{green!50!black}\ttfamily},
keywordstyle = {\bfseries\color{purple}}, % keywords
keywordstyle = [2]{\itshape\color{blue}}, % traits
keywordstyle = [3]{\color{blue}}, % primitive types
keywordstyle = [4]{\color{blue}}, % type and value ctors
keywordstyle = [5]{\color{purple!50!blue}}, % macros
stringstyle = \color{green!45!blue},
aboveskip = \baselineskip,
showstringspaces = false
}
\newtcblisting{mylisting}[1]{%
enhanced,
listing only,
title={\texttt{#1}},
attach boxed title to top right,
listing options={language=#1}
}
\newtcbinputlisting{\myinputlisting}[2][]{%
listing file={#2},
enhanced,
listing only,
title={\scriptsize\texttt{#1}},
attach boxed title to top right={yshift=-\tcboxedtitleheight/2},
listing options={language={#1}},
coltitle=black,
colbacktitle=gray!10
}
\begin{document}
\begin{lstlisting}[language=Toml]
[package]
name = "foobar"
\end{lstlisting}
\begin{mylisting}{Toml}
[package]
name = "foobar"
\end{mylisting}
\begin{filecontents*}{code.toml}
[package]
name = "foobar"
\end{filecontents*}
\myinputlisting[Toml]{code.toml} % <-- replace code.toml with your file
\end{document}