关键字颜色不正确

关键字颜色不正确

我正在使用该listings包来展示一些代码。

这是我的 Latex 文档:

\documentclass{article}
\usepackage{listings}
\usepackage{color}
\usepackage[table]{xcolor}

% CUSTOMIZATIONS
\definecolor{t1}{HTML}{C32024}
\definecolor{t2}{HTML}{141543}
\definecolor{t3}{HTML}{1052A6}
\definecolor{t4}{HTML}{06B0E6}

\definecolor{g1}{HTML}{CFCFCF}
\definecolor{g2}{HTML}{ADADAD}

\lstset{ %
    backgroundcolor=\color{white},
    basicstyle=\footnotesize\ttfamily,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    commentstyle=\color{mygreen},
    deletekeywords={...},
    escapeinside={\%*}{*)},
    extendedchars=true,
    keepspaces=true,
    keywordstyle=\color{blue},
    otherkeywords={AND,OR,NOT,FOR,IF,RETURN,TO,THEN,ELSE,WHILE,DO},
    numbers=left,
    numbersep=5pt,
    numberstyle=\tiny\color{g1},
    rulecolor=\color{black},
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    stepnumber=1,
    stringstyle=\color{mymauve},
    tabsize=2,
    title=\lstname
}

    \begin{document}
    \begin{lstlisting}
    int MaxSeqSum(int N, A[])
        maxsum = 0
        sum = 0
        i = 1
        FOR j = i TO N
            IF (sum + A[j] > 0) THEN
                sum = sum + A[j]
            ELSE
                sum = 0
                i = j+1
            IF (maxsum < sum) THEN
                maxsum = sum
                max_start = i
                max_end = j
    \end{lstlisting}
    \end{document}

我希望看到所有指定的关键字都是蓝色的,但事实是,例如,FOR只有半色,也许代码中存在一些冲突导致只有子字符串OR是蓝色。

我该如何修复它?

答案1

不要通过 定义关键字otherkeywords,而是通过 定义它们keywords

在此处输入图片描述

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\definecolor{g1}{HTML}{CFCFCF}

\lstset{ %
  backgroundcolor=\color{white},
  basicstyle=\footnotesize\ttfamily,
  breakatwhitespace=false,
  breaklines=true,
  captionpos=b,
  commentstyle=\color{mygreen},
  deletekeywords={...},
  escapeinside={\%*}{*)},
  extendedchars=true,
  keepspaces=true,
  keywordstyle=\color{blue},
  keywords={AND,OR,NOT,FOR,IF,RETURN,TO,THEN,ELSE,WHILE,DO},
  numbers=left,
  numbersep=5pt,
  numberstyle=\tiny\color{g1},
  rulecolor=\color{black},
  showspaces=false,
  showstringspaces=false,
  showtabs=false,
  stepnumber=1,
  stringstyle=\color{mymauve},
  tabsize=2,
  title=\lstname
}

\begin{document}

\begin{lstlisting}
int MaxSeqSum(int N, A[])
    maxsum = 0
    sum = 0
    i = 1
    FOR j = i TO N
        IF (sum + A[j] > 0) THEN
            sum = sum + A[j]
        ELSE
            sum = 0
            i = j+1
        IF (maxsum < sum) THEN
            maxsum = sum
            max_start = i
            max_end = j
\end{lstlisting}

\end{document}

相关内容