解决latex在使用lstlisting环境时的Undefined control sequence.错误

  错误描述,如题,Undefined control sequence. \begin{lstlisting},查了不少的资料,起始就是一句话,缺了宏包的导入。先看代码:

\documentclass[11pt,a4paper]{ctexart}
\usepackage{listings}
%插入代码要引入的宏包
\author{gsc}
\title{sample}
\lstset{
    columns = fixed,       
    basicstyle = \linespread{1.2} \ttfamily,             % 设置行距,字体
    %numbers = left,                                      % 在左侧显示行号
    numberstyle = \tiny \color{gray},                    % 设定行号格式
    keywordstyle = \bfseries \color[RGB]{240,40,255},    % 设定关键字颜色
    numberstyle = \footnotesize \color{darkgray},           
    commentstyle = \color[RGB]{0,96,96},                 % 设置代码注释的格式
    stringstyle = \color[RGB]{128,128,0},                % 设置字符串格式
    frame = single,                                      % 不显示背景边框
    backgroundcolor = \color[RGB]{205,245,244},          % 设定背景颜色
    showstringspaces = false,                            % 不显示字符串中的空格
    language=Tex                                         % 设置语言
}

\begin{document}
\begin{lstlisting}[language=tex]
\begin{document}
    坚持使用\LaTeX ,你会爱不释手!
\end{document}
\end{lstlisting}
    坚持使用\LaTeX ,你会爱不释手!    
\end{document}

编译时就会出现各种问题,后来就添加了一行导入宏包\usepackage{xcolor},就解决了问题,记录下来。

正确代码:

\documentclass[11pt,a4paper]{ctexart}
\usepackage{xcolor}
\usepackage{listings}
%插入代码要引入的宏包
\author{gsc}
\title{sample}
\lstset{
    columns = fixed,       
    basicstyle = \linespread{1.2} \ttfamily,             % 设置行距,字体
    %numbers = left,                                      % 在左侧显示行号
    numberstyle = \tiny \color{gray},                    % 设定行号格式
    keywordstyle = \bfseries \color[RGB]{240,40,255},    % 设定关键字颜色
    numberstyle = \footnotesize \color{darkgray},           
    commentstyle = \color[RGB]{0,96,96},                 % 设置代码注释的格式
    stringstyle = \color[RGB]{128,128,0},                % 设置字符串格式
    frame = single,                                      % 不显示背景边框
    backgroundcolor = \color[RGB]{205,245,244},          % 设定背景颜色
    showstringspaces = false,                            % 不显示字符串中的空格
    language=Tex                                         % 设置语言
}

\begin{document}
\begin{lstlisting}[language=tex]
\begin{document}
    坚持使用\LaTeX ,你会爱不释手!
\end{document}
\end{lstlisting}
    坚持使用\LaTeX ,你会爱不释手!    
\end{document}

搞定了在latex中展示latex代码

posted @ 2024-01-20 21:48  叕叒双又  阅读(264)  评论(0编辑  收藏  举报