listings 确实会突出显示所有关键字

listings 确实会突出显示所有关键字

我正在尝试在我正在编写的报告中包含 AMPL 语法突出显示。

我尝试过使用 listings 包

\documentclass[12pt]{report}

%Packages

\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb}
\usepackage{geometry}
\usepackage{color}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{sectsty}
\usepackage[squaren,Gray]{SIunits}
\usepackage[french]{babel}
\usepackage{listings}
\geometry{hmargin=2.5cm,vmargin=2cm}
\usepackage{fancyhdr}
\pagestyle{fancy}
%\definecolor{bdx}{rgb}{0.682, 0.145, 0.451}
\definecolor{bdx}{rgb}{0.674, 0.152, 0.451}

\sectionfont{\centering\color{bdx}}
\subsectionfont{\color{bdx}}
\subsubsectionfont{\centering}
\renewcommand{\thesection}{\Roman{section}.}
\renewcommand{\thesubsection}{\arabic{subsection} - }
\renewcommand{\headrulewidth}{0pt}

%Page de titre
\setcounter{tocdepth}{2}
\title{\color{bdx}{\textbf{Test}}
\author{John D}
\date{\today}

% Default fixed font does not support bold face
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{12} % for bold
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12}  % for normal

\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}
\definecolor{deepgrey}{rgb}{0.25,0.25,0.25}



% AMPL style for highlighting

\lstdefinelanguage{ampl}
{
keywords={}
}

\newcommand\amplstyle{\lstset{
language=ampl,
backgroundcolor=\color{white},
basicstyle=\ttm,
emph={subject to, minimize, reset},          % Custom highlighting
otherkeywords={set,param,var,arc,integer,minimize,maximize,subject,to,node,sum,in,Current,complements,integer,solve_result_num,IN,contains,less,suffix,INOUT,default,logical,sum,Infinity,dimen,max,symbolic
,Initial,div,min,table,LOCAL,else,option,then,OUT,environ,setof     ,union,all,exists,shell_exitcodeuntil,binary,forall,solve_exitcodewhile     ,by,if,solve_messagewithin,check,in,solve_result},             % Add keywords here
keywordstyle=\small\ttb\color{deepblue},
emphstyle=\small\ttb\color{deepred},    % Custom highlighting style
morestring=[b]",
stringstyle=\color{deepgreen},
commentstyle=\ttm\color{deepgrey},
frame=tb,                         % Any extra options here
showstringspaces=false            % 
}}


% AMPL environment
\lstnewenvironment{ampl}[1][]
{
\amplstyle
\lstset{#1}
}
{}

% AMPL for external files
\newcommand\amplexternal[2][]{{
\amplstyle
\lstinputlisting[#1]{#2}}}

% AMPL for inline
\newcommand\amplinline[1]{{\amplstyle\lstinline!#1!}}

我尝试打印出来:

\begin{ampl}
set A;
reset;
option solver gurobi;
var j >= 0;
minimize cost;
subject to bob : 
    "But why ?"
\end{ampl}

但这并不能正确地突出显示单词,它似乎进入了第一次识别。例如,“reset”应该被强调,但没有,而子字符串“set”被突出显示。

我该如何解决这个问题?

答案1

您正在使用otherkeywords选项添加更多关键字,但这是错误的。otherkeywords应该用于添加包含以下内容的关键字其他符号,即除字母或数字之外的通常不会出现在标识符中的字符。

使用正确的选项后,morekeywords您会得到正确的结果:

\newcommand\amplstyle{\lstset{
    ...
    emph={subject to, minimize, reset},          % Custom highlighting
    morekeywords={set,param,var, ...},           % Add keywords here
    ...
}}

在此处输入图片描述

相关内容