我正在使用listings
包来显示源代码,并希望重新格式化编号以使用oldstylenums
。使用时出现问题microtype
,因为它会为列表中的每一行代码抛出错误,如下所示
Argument of \MT@res@a has an extra }. import
Paragraph ended before \MT@res@a was complete. import
Extra \else. import
- 禁用
microtype
会使 LaTeX 编译。 - 不重新格式化编号会使 LaTeX 编译。
- 禁用
hyperref
会使 LaTeX 编译。
有没有办法重新格式化数字而不会出现错误microtype
,也不会禁用两个基本包之一microtype
和hyperref
我的文档?
这是我最小的、无法运行的示例。执行上述任何一点都可以使其运行。
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
% Disabling the below makes it compile
\usepackage{microtype}
\usepackage{listings}
\lstset{upquote=true}
\lstdefinestyle{PythonStyle}{
language=Python,
commentstyle=\itshape,
basicstyle=\footnotesize\ttfamily,
breaklines=true,
numbers=left,
numberstyle=\ttfamily\scriptsize,
tabsize=4,
numbersep=20pt, % separation between numbers and listing
basewidth=0.5em, % the width of each character in the listing
}
% Disabling the below makes it compile
\renewcommand*\thelstnumber{\oldstylenums{\arabic{lstnumber}}} % nicer numbering
% Disabling the below makes it compile
\usepackage[colorlinks=true, pdfusetitle]{hyperref}
\begin{document}
\section{Section}
We are at page \pageref{sec:here}.\label{sec:here}
\begin{lstlisting}[style=PythonStyle]
import numpy as np
# this is a comment
a = np.sqrt(2)
if a > 2:
print("Interesting")
\end{lstlisting}
\end{document}
答案1
感谢 Ulrike Fischer 的上述评论。因此,我发现可行的解决方案是在样式调用之外定义数字函数:
\newcommand\epicNumbers[1]{\oldstylenums{#1}}
然后在lstdefinestyle
调用中调用该函数,如下所示:
\lstdefinestyle{PythonStyle}{
language=Python,
...,
numberstyle=\ttfamily\scriptsize\color[rgb]{0.5,0.5,1.0}\epicNumbers,
...,
}
完整的工作文件是这样的:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{microtype}
\usepackage{listings}
\newcommand\epicNumbers[1]{\oldstylenums{#1}} % this line is new
\lstset{upquote=true}
\lstdefinestyle{PythonStyle}{
language=Python,
commentstyle=\itshape,
basicstyle=\footnotesize\ttfamily,
breaklines=true,
numbers=left,
numberstyle=\ttfamily\scriptsize\epicNumbers, % call the new number style
tabsize=4,
numbersep=20pt,
basewidth=0.5em,
}
\usepackage[colorlinks=true, pdfusetitle]{hyperref}
\begin{document}
\section{Section}
We are at page \pageref{sec:here}.\label{sec:here}
\begin{lstlisting}[style=PythonStyle]
import numpy as np
# this is a comment
a = np.sqrt(2)
if a > 2:
print("Interesting")
\end{lstlisting}
\end{document}