我如何才能像图片中那样将行代码居中并编号?是否有可以在 lstlisting 环境中运行的命令?非常感谢
答案1
这里我使用了我的numberedblock
包,它允许引用带标签的代码块。我使用括号而不是括号,以免与公式编号混淆。使用其内置宏和环境,只能执行固定缩进的代码块。但是,通过使用一些额外的代码,可以实现居中。
\documentclass{article}
\usepackage{numberedblock,lipsum,stackengine}
\setstackEOL{\\}
\setstackgap{L}{\normalbaselineskip}
\setlength\maxblocklabelsize{0in}
\setlength\blockindent{.2in}
\renewcommand\blocklabel[1]{\llap{[\textit{\arabic{#1}}]}}
\begin{document}
\lipsum[1]
as enthalpy\ldots from the old pressure
\begin{numVblock}[\nbVlabel{cd:a}]
For fixed indent code
Can be verbatim &^%\\
solve(UEqn == - fvc::grad(p));
\end{numVblock}
\setlength\blockindent{0in}
\begin{verbbox}
For centered code
Can be verbatim &^%\\
solve(UEqn == - fvc::grad(p));
\end{verbbox}
\nbVlabel{cd:b}\numblock{\makebox[\textwidth]{\theverbbox}}
In code blocks~\ref{cd:a} and \ref{cd:b}, \lipsum[2]
\end{document}
答案2
使用escapeinside
选项:
\documentclass{article}
\usepackage{listings}
\lstset{basicstyle=\ttfamily,escapeinside=`'}
\newcounter{cnt}
\newcommand\Label[1]{\hfill\refstepcounter{cnt}(\thecnt)\label{#1}}
\begin{document}
\begin{lstlisting}
solve(UEqn == - fvc::grad(p)); `\Label{foo}'
\end{lstlisting}
\begin{lstlisting}
solve(UEqn == - fvc::grad(p)); `\Label{bar}'
\end{lstlisting}
also seen in \ref{foo} and \ref{bar} \ldots
\end{document}
答案3
您希望它居中并使用计数器来计算方程式,因此最简单的方法是使用并以所需的格式equation
将其写入里面:\hbox
\documentclass{article}
\usepackage{amsmath}
\usepackage{listings}
\lstset{basicstyle=\ttfamily}
\begin{document}
some test text and some more text and some more text and some more text and some more text and some more text and some more text and some more text
\begin{equation}
\hbox{\lstinline!solve(UEqn == - fvc::grad(p));!}
\end{equation}
some test text and some more text and some more text and some more text and some more text and some more text and some more text and some more text
\end{document}