如何改变 lstset 中 html 标签的颜色?

如何改变 lstset 中 html 标签的颜色?

我有一段代码:"></li></a><script>alert(123);</script>我想使用 \lstset 来着色(即 => HTML 标签如“li”“a”“script”将是 dkblue 颜色)。我使用“listings”包和 \lstset 扩展,如下所示:

\lstset{
language        = html,
basicstyle      = \small\ttfamily,
keywordstyle    = \color{dkblue},
stringstyle     = \color{red},
identifierstyle = \color{dkgreen},
commentstyle    = \color{gray},
emph            =[1]{html},
emphstyle       =[1]\color{black},
emph            =[2]{if,and,or,else},
emphstyle       =[2]\color{dkyellow}}

问题在于,在其余代码之前放置“>”会阻止 LaTeX 将代码解释为 HTML。有人有解决方案吗?

答案1

您的代码片段颜色正确:它以 a 开头",因此它是一个字符串。

一个快速而肮脏的(实际上不是很快但相当肮脏)解决方案是从lstlisting没有字符串分隔符的情况下复制 html 驱动程序,然后添加您自己的首选项:

\documentclass{article}
\usepackage{listings,xcolor}
\definecolor{dkgreen}{rgb}{0,.6,0}
\definecolor{dkblue}{rgb}{0,0,.6}
\definecolor{dkyellow}{cmyk}{0,0,.8,.3}
\lstdefinelanguage{nohtml}{
  morekeywords={A,ABBR,ACRONYM,ADDRESS,APPLET,AREA,B,BASE,BASEFONT,%
      BDO,BIG,BLOCKQUOTE,BODY,BR,BUTTON,CAPTION,CENTER,CITE,CODE,COL,%
      COLGROUP,DD,DEL,DFN,DIR,DIV,DL,DOCTYPE,DT,EM,FIELDSET,FONT,FORM,%
      FRAME,FRAMESET,HEAD,HR,H1,H2,H3,H4,H5,H6,HTML,I,IFRAME,IMG,INPUT,%
      INS,ISINDEX,KBD,LABEL,LEGEND,LH,LI,LINK,LISTING,MAP,META,MENU,%
      NOFRAMES,NOSCRIPT,OBJECT,OPTGROUP,OPTION,P,PARAM,PLAINTEXT,PRE,%
      OL,Q,S,SAMP,SCRIPT,SELECT,SMALL,SPAN,STRIKE,STRING,STRONG,STYLE,%
      SUB,SUP,TABLE,TBODY,TD,TEXTAREA,TFOOT,TH,THEAD,TITLE,TR,TT,U,UL,%
      VAR,XMP,%
      accesskey,action,align,alink,alt,archive,axis,background,bgcolor,%
      border,cellpadding,cellspacing,charset,checked,cite,class,classid,%
      code,codebase,codetype,color,cols,colspan,content,coords,data,%
      datetime,defer,disabled,dir,event,error,for,frameborder,headers,%
      height,href,hreflang,hspace,http-equiv,id,ismap,label,lang,link,%
      longdesc,marginwidth,marginheight,maxlength,media,method,multiple,%
      name,nohref,noresize,noshade,nowrap,onblur,onchange,onclick,%
      ondblclick,onfocus,onkeydown,onkeypress,onkeyup,onload,onmousedown,%
      profile,readonly,onmousemove,onmouseout,onmouseover,onmouseup,%
      onselect,onunload,rel,rev,rows,rowspan,scheme,scope,scrolling,%
      selected,shape,size,src,standby,style,tabindex,text,title,type,%
      units,usemap,valign,value,valuetype,vlink,vspace,width,xmlns},%
   tag=**[s]<>,%
   sensitive=f,%
    basicstyle      = \small\ttfamily,
    keywordstyle    = \color{dkblue},
    stringstyle     = \color{red},
    identifierstyle = \color{dkgreen},
    commentstyle    = \color{gray},
    emph            =[1]{html},
    emphstyle       =[1]\color{black},
    emph            =[2]{if,and,or,else},
    emphstyle       =[2]\color{dkyellow}
}
\begin{document}
\begin{lstlisting}[language=nohtml]
"></li></a><script>alert(123);</script>
\end{lstlisting}
\end{document}

结果:

在此处输入图片描述

该解决方案的一个优点是,对于其他格式良好的 html,您仍然可以使用默认html定义(带有字符串)。

相关内容