为什么我的源代码列表中单词之间的间距这么大?

为什么我的源代码列表中单词之间的间距这么大?

我使用以下代码列出我的 Java 代码,但单词之间似乎有太多空格。我该怎么办?

% source code listing
\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}

\usepackage{caption}

% citation style
\usepackage{apacite}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}

\begin{document}
\begin{lstlisting}[label=some-code,caption=bind to service call]
bindService(new Intent(this, Recognizer.class), recConnection, Context.BIND_AUTO_CREATE);
\end{lstlisting}
\end{document}

这是我得到的快照。代码未完全显示,并且功能中的空间太宽bindService

在此处输入图片描述

答案1

如果您设置,columns=flexible则空格不会拉伸太多。您还应该允许换行,但只能在空格处换行。最后,最好说明listings设置的语言是 Java:

示例输出

\documentclass{article}
% source code listing
\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}

\usepackage{caption}

% citation style
\usepackage{apacite}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}

\lstset{language=java,columns=flexible,breaklines=true,breakatwhitespace=true}

\begin{document}

\begin{lstlisting}[label=some-code,caption=Bind to service call]
bindService(new Intent(this, Recognizer.class), recConnection, Context.BIND_AUTO_CREATE);
\end{lstlisting}

\end{document}

答案2

如果要保留列对齐,但要减少字符间距,请将选项设置basewidth为较小的值:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor} % for setting colors

% set the default code style
\lstset{
    language=C++,
    frame=tb, % draw a frame at the top and bottom of the code block
    tabsize=4, % tab space width
    showstringspaces=false, % don't mark spaces in strings
    numbers=left, % display line numbers on the left
    commentstyle=\color{green}, % comment color
    keywordstyle=\color{blue}, % keyword color
    stringstyle=\color{red}, % string color
    basicstyle=\footnotesize\ttfamily,
    basewidth = {.48em}
}

\begin{document}

\begin{lstlisting}[caption={C++ code using listings}]
#include <iostream>
int main() {
    // print hello to the console
    std::cout << "Hello, world!" << std::endl;
    return 0;
}
\end{lstlisting}

\end{document}

使用列表的 C++ 代码

答案3

您必须使用breaklines=true以便将线分成两条。

\documentclass{article}
% source code listing
\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}

\usepackage{caption}

% citation style
\usepackage{apacite}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}

\begin{document}
\begin{lstlisting}[breaklines=true,label=some-code,caption=bind to service call]     %% <---here
bindService(new Intent(this, Recognizer.class), recConnection, Context.BIND_AUTO_CREATE);
\end{lstlisting}
\end{document}

在此处输入图片描述

相关内容