lstlisting:如何對齊突出顯示的程式碼

lstlisting:如何對齊突出顯示的程式碼

我想定義幾個新命令來突出顯示我的程式碼部分(這實際上是用於追蹤轉儲,而不是用於程式語言)。

我的問題是我似乎無法使彩色文字與清單文字正確對齊。請參閱“Hello worlds”。

我嘗試添加\ttfamily新的命令定義,但沒有幫助。也嘗試了不同的字體大小,我相信彩色和非彩色文字字體的大小相同,所以我認為這不是問題。

\documentclass{article}

\usepackage{listings}
\lstset{
  basicstyle=\ttfamily\large,
  breakatwhitespace=false,
  breaklines=true,
  escapeinside={\%*}{*},
}

\usepackage{color}
\definecolor{mycolorGreenOne}{rgb}{0, 0.7, 0}
\newcommand*{\listingsHigh}[1]{\textcolor{red}{#1}}
\newcommand*{\LighthighOne}{\color{cyan}}

\begin{document}
\begin{lstlisting}
My text: %*\LighthighOne Hello world!* Goodbye!
My text: Hello world! Goodbye!
My text: %*\listingsHigh{Hello world!}* Goodbye!
\end{lstlisting}
\end{document}

答案1

解決了問題!我補充道:columns=fullflexible

我應該提到的是,文檔中對 fullflexible 的描述對於我來說似乎與實際所做的事情違反直覺。這是因為它似乎表明固定保持列“對齊”,而靈活“破壞”列以確保尊重原始字體對齊。然而,fixed不工作但fullflexible確實有效。如果有人願意解釋為什麼我會很感激。

請參閱第 2.10 節:清單 pdf

\documentclass{article}

\usepackage{listings}
\lstset{
  basicstyle=\ttfamily\large,
  breakatwhitespace=false,
  breaklines=true,
  escapeinside={\%*}{*},
  columns=fullflexible
}

\usepackage{color}
\definecolor{mycolorGreenOne}{rgb}{0, 0.7, 0}
\newcommand*{\listingsHigh}[1]{\textcolor{red}{#1}}
\newcommand*{\LighthighOne}{\color{cyan}}

\begin{document}
\begin{lstlisting}
My text: %*\LighthighOne Hello world!* Goodbye!
My text: Hello world! Goodbye!
My text: %*\listingsHigh{Hello world!}* Goodbye!
\end{lstlisting}
\end{document}

相關內容