Packages
How to Create Custom Commands in LaTeX
Custom commands (macros) let you avoid repetition and make your documents easier to maintain. Define a command once in the preamble and use it throughout your document—if you need to change it later, update it in one place.
Basic \newcommand
Define a simple command that expands to fixed text or formatting:
% In the preamble:
\newcommand{\eg}{e.g.,\@}
\newcommand{\ie}{i.e.,\@}
\newcommand{\R}{\mathbb{R}}
% In the document:
The set of real numbers is $\R$.
We observed several species, \eg cats and dogs.Output: \R expands to the blackboard-bold R, and \eg produces 'e.g.' with correct spacing.
Commands with Arguments
Use [number] to specify how many arguments your command takes. Reference them with #1, #2, etc.:
% Command with 1 argument
\newcommand{\keyword}[1]{\textbf{\textit{#1}}}
% Command with 2 arguments
\newcommand{\highlight}[2]{\colorbox{#1}{\textcolor{white}{#2}}}
% Command with an optional argument (default value in [])
\newcommand{\note}[2][Note]{\textbf{#1:} #2}
% Usage:
\keyword{machine learning}
\highlight{blue}{Important}
\note{This is a default note.}
\note[Warning]{This is a warning.}Output: keyword produces bold-italic text; highlight creates colored boxes; note has an optional label.
Renewing Existing Commands
Use \renewcommand to override an existing LaTeX command. Be careful—this changes behavior globally.
% Change how \emph behaves (default is italic)
\renewcommand{\emph}[1]{\textbf{#1}}
% Now \emph produces bold instead of italic:
This is \emph{emphasized} text.
% Override the abstract title
\renewcommand{\abstractname}{Executive Summary}Output: \emph now renders bold text; the abstract section is titled 'Executive Summary'.
Custom Environments
Use \newenvironment to create reusable blocks with begin/end code:
% Define a custom environment
\newenvironment{important}
{\begin{center}\bfseries\large} % begin code
{\end{center}} % end code
% More practical: a "note" box
\usepackage{tcolorbox}
\newenvironment{notebox}
{\begin{tcolorbox}[colback=yellow!10, colframe=yellow!50!black, title=Note]}
{\end{tcolorbox}}
% Usage:
\begin{important}
This text is centered, bold, and large.
\end{important}
\begin{notebox}
Remember to cite your sources.
\end{notebox}Output: Custom environments produce styled blocks that you can reuse throughout the document.
💡 Tips
- •Always define commands in the preamble (before \begin{document})
- •Prefix personal commands with a unique letter to avoid conflicts (e.g., \myR instead of \R)
- •Use \providecommand instead of \newcommand to define a command only if it doesn't already exist
- •For complex macros with conditional logic, look into xparse and \NewDocumentCommand
Try This in Bibby AI
Write LaTeX faster with AI auto-complete and instant compilation.
Start Writing Free