為什麼 \noindent 在這裡不能正常運作?

為什麼 \noindent 在這裡不能正常運作?

我定義了一個新環境,類似(但不等於)listings

\documentclass{ltxdoc}
\usepackage{lipsum}
\newenvironment{lines}
{\par\begingroup\nobreak
\vspace{3pt}\parindent0pt\hrule\kern5pt
\nobreak\obeylines\everypar{\strut}\endgroup}
{\par\begingroup\nobreak
\vspace{3pt}\parindent0pt\hrule\kern5pt
\nobreak\obeylines\everypar{\strut}\endgroup%
\noindent%
}
\begin{document}
\lipsum[1]
\begin{lines}
Some nifty code and stuffz
\end{lines}
\lipsum[2]
\end{document}

為什麼我\noindent在文字之前保留一個小空格?我錯過了什麼?

答案1

如果你使用,\noindent你幾乎總是會遇到這種行為。空格是從環境後面的行尾開始排版的詞間空格。

您可以透過使用來避免這個問題\ignorespacesafterend,但這只是掩蓋裂縫。錯誤是使用\noindent過早啟動了水平模式,這就是為什麼行尾被排版為空格的原因。 LaTeX 環境從不這樣做。您應該使用定義環境,trivlist然後環境將以垂直模式結束,但如果後面沒有空行,縮排將被抑制(實際上是使用刪除\lastbox而不是不使用新增\noindent。)

像這樣,調整長度以適應。

在此輸入影像描述

\documentclass{ltxdoc}
\usepackage{lipsum}
\newenvironment{linez}
 {\trivlist\nopagebreak
  \parindent0pt
  \vspace{3pt}%
  \hrule
  \vspace{-3pt}%
  \item\relax\obeylines}
 {\par
  \nopagebreak
  \vspace{3pt}%
  \hrule
  \vspace{3pt}%
  \endtrivlist}

\begin{document}
\lipsum[1]
\begin{linez}
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
\end{linez}
\lipsum[2]
\end{document}

答案2

你丟失了\ignorespacesafterend,但定義不起作用\obeylines,因為你將它包含在一個群組中,並且它的效果在以下位置消失\endgroup

\documentclass{ltxdoc}
\usepackage{lipsum}
\newenvironment{linez}
 {\par\nopagebreak
  \vspace{3pt}
  \parindent0pt
  \hrule\kern5pt
  \obeylines}
 {\par
  \nopagebreak
  \vspace{3pt}
  \hrule\kern5pt
  \noindent\ignorespacesafterend}

\begin{document}
\lipsum[1]
\begin{linez}
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
\end{linez}
\lipsum[2]
\end{document}

在此輸入影像描述

相關內容