(十三)Latex自定义命令和环境

<1>自定义命令

\documentclass{ctexart}
% \newcommand-定义命令
% 命令只能由字母组成,不能以\end开头
% \newcommand<命令>[<参数个数>][<首参数默认值>]{<具体定义>}
\newcommand\PRC{People's Republic of \emph{China}}

% \newcommand也可以使用参数
% 参数个数可以从1到9,使用时用#1,#2,#3,#4...#9
\newcommand\loves[2]{#1 喜欢 #2}
\newcommand\hateby[2]{#2 不受 #1 喜欢}
% newcommand的参数也可以有默认值
%指定参数个数的同时指定了首个参数的默认值,那么这个命令的第一个参数就可以成为可选参数(要使用中括号指定)
\newcommand\love[3][喜欢]{#2#1#3}

% renewcommand-重定义命令,只能作用于已有命令
% 与\newcomamd 命令作用和用法相同,但只能用于已有命令
% \renewcommand<命令>[<首参数默认值>]{<具体定义>}
\renewcommand\abstractname{内容简介}  %\abstractname封装在abstarct环境中,是已经存在的命令

\begin{document}
 \PRC
 
 \loves{}{}
 
 \hateby{}{萝卜}
 
 \love{猫儿}{鱼儿}
 
 \love[最爱]{猫儿}{鱼儿}
 
 \begin{abstract}
  这是一段摘要
 \end{abstract}
\end{document}

在这里插入图片描述
<2>自定义环境

\documentclass{ctexart}
% 定义和重定义环境
% \newenvironment{<环境名称>}[<参数个数>][<首参数默认值>]{<环境前定义>}{<环境后定义>}
% \renewenvironment{<环境名称>}[<参数个数>][<首参数默认值>]{<环境前定义>}{<环境后定义>}
% 为book类中定义摘要(abstract)环境
\newenvironment{myabstract}[1][摘要]
{\small                                     %字号
 \begin{center}\bfseries #1\end{center}  %参数居中粗体
 \begin{quotation}}       %环境前定义
 {\end{quotation}}        %环境后定义
 
 % 环境参数只有<环境前定义>可以使用参数
%<环境后定义>中不能再使用环境参数,如果需要,可以先把前面得到的参数保存再一个命令,在后面使用:
% 也就是说环境参数要经过环境前定义处理后才能被环境后定义使用
\newenvironment{Quotation}[1]
{\newcommand\quotesource{#1} \begin{quotation}}               
{\par\hfill ---《\textit{\quotesource}》 \end{quotation}}

\begin{document}
 \begin{myabstract}[我的摘要]
  这是自定义的摘要环境
 \end{myabstract}
%使用新定义的环境
 \begin{Quotation}{易$\cdot$乾}
  初九,潜龙勿用。
 \end{Quotation}
  
\end{document}

在这里插入图片描述

发布了23 篇原创文章 · 获赞 2 · 访问量 632

猜你喜欢

转载自blog.csdn.net/weixin_44378835/article/details/104203772
今日推荐