Definitions of Commands and Environments

Definitions of Commands and Environments #

Author: Erhua

Keywords: commands, environments

In this section, we will discuss the definitions of commands and environments in LaTeX.

In LaTeX, macros are divided into two categories: commands and environments.

Commands #

Defining a New Command: \newcommand #

\newcommand<new command (with \)>(number of arguments)[default value for the first argument]{specific command definition}
\documentclass[]{article}
\usepackage[heading=true]{ctex} % Be sure to set heading to true, otherwise ctexset cannot be used
\usepackage[left = 30mm,right = 30mm]{geometry}
\newCJKfontfamily\qingsong{FZQKBYSJW--GB1-0}
\newcommand\jinse{\qingsong 锦瑟}
\newcommand\js[3][锦瑟]{#3#1#2}
\begin{document}
\jinse \jinse \par
\js{无端}{五十弦}
\end{document}

Redefining an Existing Command: \renewcommand #

\renewcommand<existing command>(number of arguments)[default value for the first argument]{specific command definition}
The maximum number of arguments is 9, and the parameters are represented as #1~#9 in the command definition.

Environments #

\newenvironment{name of environment}(number of arguments)[default value for the first argument]{content before environment}{content after environment}
The content in "content before environment" will be processed before the text contained in this environment, while the content in "content after environment" will be processed when the \end{name} command is encountered.
The maximum number of arguments is 9, and the parameters are represented as #1~#9 in the command definition.
% When using default argument values
\newenvironment{shengming}[1][Declaration]{
	\begin{center}#1\end{center}
	\begin{center}
}{\end{center}}
------
\begin{shengming}
锦瑟无端五十弦,一弦一柱思华年
\end{shengming}

% When using custom argument values
\setCJKfamilyfont{qingsong}{FZQKBYSJW--GB1-0}
------
\newenvironment{shengming}[1]{
	\begin{center}#1\end{center}
	\begin{center}
}{\end{center}}
------
\CJKfamily{qingsong}
\begin{shengming}{I declare}
锦瑟无端五十弦,一弦一柱思华年
\end{shengming}

You cannot reference arguments in the "after" content, so you need to find a way to do it in the "before" content.
\newenvironment{zhuyi}[1][Attention]{
	\newcommand\zy{#1}
	\textbf{\zy}\hfill
}{\hfill \textbf{\zy}}
------
\begin{zhuyi}
锦瑟无端五十弦,一弦一柱思华年
\end{zhuyi}

Therefore, custom commands and environments are very important. By encapsulating font, font size, indentation, alignment, spacing, and other content with custom commands and environments, the structure of the document can be clearer. In large documents, the defined commands and environments are usually placed in separate files.