
我需要為原始程式碼範例建立環境。我希望它看起來像這樣:
程式碼範例:
------------------------------------------------
# 這是程式碼範例
迴聲“你好”
------------------------------------------------
問題是,我不知道如何強制它自動轉義特殊字元(尤其是散列),這樣使用者就不必每次想要寫入散列時都鍵入反斜線。
我的程式碼
\def\terminalText#1\end{\hspace*{2em}\texttt{#1}\\\end}
\newenvironment{codeExample}{
\vspace*{1.5em}
\noindent
Code example:\\
\hspace*{1.3em}\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}\\
\terminalText}
{\hspace*{1.3em}\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}}
這段程式碼運作良好,直到我想在環境中寫入任何特殊字符,然後我收到此錯誤:
! Paragraph ended before \terminalText was complete.
verbatim
根據問題,我甚至嘗試為環境製作某種包裝逐字可以與新環境定義一起使用嗎?,但它給了我這個錯誤:
! LaTeX Error: \begin{codeExample} on input line 535 ended by \end{verbatim}.
我的第二個代碼
\newenvironment{codeExample}{
\vspace*{1.5em}
\noindent
Code Example:\\
\hspace*{1.3em}\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}\\
\verbatim
}
{%
\endverbatim
\hspace*{1.3em}\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}}
答案1
使用verbatim
包,第二個範例的程式碼可以開箱即用(如果dashrule
也包含包)
\documentclass{article}
\usepackage{verbatim}
\usepackage{dashrule}
\newenvironment{codeExample}{
\vspace*{1.5em}
\noindent
Code Example:\\
\hspace*{1.3em}
\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}
\verbatim
}
{%
\endverbatim
\hspace*{1.3em}
\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}
}
\begin{document}
\begin{codeExample}
# This is the code example
echo 'Hello'
\end{codeExample}
\end{document}
請考慮將listings
package 作為排版程式碼範例的「更好」和更簡潔的方式。
編輯tcolorbox
這是一個包含列表輸出的範例。
\documentclass{article}
\usepackage{verbatim}
\usepackage{dashrule}
\usepackage[most]{tcolorbox}
\newenvironment{codeExample}{
\vspace*{1.5em}
\noindent
Code Example:\\
\hspace*{1.3em}
\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}
\verbatim
}
{%
\endverbatim
\hspace*{1.3em}
\hdashrule[0.5ex]{435pt}{0.9pt}{1.5mm}
}
\newtcblisting[auto counter]{codeex}[1][]{%
arc=0pt,
auto outer arc,
colbacktitle=yellow,
coltitle=black,
title={Code Example \thetcbcounter},
listing options={language=bash},
listing only,
lowerbox=ignored,
before upper=\hdashrule[0.5ex]{\textwidth}{0.9pt}{1.5mm},
after upper=\hdashrule[0.5ex]{\textwidth}{0.9pt}{1.5mm}
#1
}
\begin{document}
\begin{codeExample}
# This is the code example
echo 'Hello'
\end{codeExample}
\begin{codeex}
echo 'Hello'
\end{codeex}
\end{document}