我有如下内容:
\documentclass{article}
\usepackage{listings}
\lstnewenvironment{shellsession}[1][]
{\lstset{language=bash,
basicstyle=\small\ttfamily,
numbers=none,
#1
}}
{}
\begin{document}
\begin{shellsession}
first line
second line
third line
\end{shellsession}
\end{document}
这给了我以下输出:
这并不奇怪,但我想知道是否有办法在每行前面添加一个字符。为了清楚起见,我希望得到的输出是
$ first line
$ second line
$ third line
答案1
您可以通过名为 的钩子在每一行“真实”内容(即不是由listings
选项创建的行breaklines
)前添加一些内容。listings
EveryPar
请注意,由于钩子是全局的,如果您使用多种语言排版代码,但只想将内容添加到这些语言子集(此处只有一种)的列表行中listings
,则必须采取一些预防措施。listings
bash
另外,请注意,如果不采取任何对策,例如
listings
的gobble
选项(参见listings
手动的)- 马丁·沙勒的
lstautogobble
包裹,或 - 我的实验
lstautodedent
包裹,
您的环境中存在的任何缩进listing
都将在输出中排版;这可能最终将您的列表“推”到右侧,这是不可取的。
\documentclass{article}
\usepackage{listings}
\makeatletter
% define custom macro that expands to the language name
% (for comparison purposes)
\newcommand\langname@bash{}
\def\langname@bash{bash}
% define custom prompt
\newcommand\prompt@bash{\$\ }
% define a macro (initially empty) and insert it at the beginning
% of every paragraph
\newcommand\addedToEveryPar@bash{}
\lst@AddToHook{EveryPar}{\addedToEveryPar@bash}
% redefine the macro by the custom prompt, but only if the language in use
% be `bash'
\lst@AddToHook{PreInit}{%
\ifx\lst@language\langname@bash%
\let\addedToEveryPar@bash\prompt@bash%
\fi
}
\makeatother
\lstnewenvironment{shellsession}[1][]
{\lstset{language=bash,
basicstyle=\small\ttfamily,
numbers=none,
#1
}}
{}
\begin{document}
\begin{shellsession}
first line
second line
third line
\end{shellsession}
% just to check that your prompt doesn't find its way into unrelated language...
% (code taken from http://stackoverflow.com/a/14560801/2541573)
\begin{lstlisting}[language=Python, basicstyle=\ttfamily]
def memo(f):
cache = {}
def memoized(n):
nonlocal cache
if n not in cache:
cache[n] = f(n)
return cache[n]
return memoized
\end{lstlisting}
\end{document}