我正在用不同的 leftskip 排版文字(文字的某些部分向右縮排)。
由於某種原因,預設情況下列表不會考慮 leftskip。然而它有一個有趣的 xleftmargin 屬性。當給定明確的值時,它可以充分工作,例如。 2公分。
但是,我似乎無法將其設定為等於 \leftskip。我嘗試了不同的變化,包括
\documentclass{article}
\usepackage{listings}
\setlength{\leftskip}{5cm}
\begin{document}
totototo
\begin{lstlisting}[xleftmargin={\the\leftskip}]
def example_function():
print("Hello, world!")
\end{lstlisting}
\end{document}
但無濟於事。我該說什麼 ?在 MWE 中我可以只使用5cm
,但實際上, \leftskip 並不總是相同的。
答案1
分配一個在其工作\leftskip
之前設定的新長度;lstlisting
那我們可以用它作為 的值xleftmargin
。
\documentclass{article}
\usepackage{listings}
\newlength{\keepleftskip}
\AtBeginEnvironment{lstlisting}{\setlength{\keepleftskip}{\leftskip}}
\lstset{xleftmargin=\keepleftskip}
\begin{document}
\noindent
totototo
\begin{lstlisting}
def example_function():
print("Hello, world!")
\end{lstlisting}
\setlength{\leftskip}{5cm}
\noindent
totototo
\begin{lstlisting}
def example_function():
print("Hello, world!")
\end{lstlisting}
\setlength{\leftskip}{1cm}
\noindent
totototo
\begin{lstlisting}
def example_function():
print("Hello, world!")
\end{lstlisting}
\end{document}
答案2
正如 Ulrike Fischer 在她的評論中指出的那樣,\leftskip
被重置\begin{lstlisting}
。
我能得到的最接近的是創建具有相同值的第二個長度暫存器並使用該暫存器。這意味著您每次更改時都必須更新該暫存器\leftskip
:
\documentclass{article}
\usepackage{listings}
\newlength{\leftskiphack}
\begin{document}
\setlength{\leftskip}{5cm}
\setlength{\leftskiphack}{\leftskip}
totototo
\begin{lstlisting}[xleftmargin=\the\leftskiphack]
def example_function():
print("Hello, world!")
\end{lstlisting}
\setlength{\leftskip}{8cm}
\setlength{\leftskiphack}{\leftskip}
totototo
\begin{lstlisting}[xleftmargin=\the\leftskiphack]
def example_function():
print("Hello, world!")
\end{lstlisting}
\end{document}