Definitions
LaTeX has support for making new commands of many different kinds.

\newcommand & \renewcommand
Synopses, one of (three regular forms, three starred forms):

\newcommand{\cmd}{defn}
\newcommand{\cmd}[nargs]{defn}
\newcommand{\cmd}[nargs][optargdefault]{defn}
\newcommand*{\cmd}{defn}
\newcommand*{\cmd}[nargs]{defn}
\newcommand*{\cmd}[nargs][optargdefault]{defn}

or the same six possibilities with \renewcommand instead of \newcommand:

\renewcommand{\cmd}{defn}
\renewcommand{\cmd}[nargs]{defn}
\renewcommand{\cmd}[nargs][optargdefault]{defn}
\renewcommand*{\cmd}{defn}
\renewcommand*{\cmd}[nargs]{defn}
\renewcommand*{\cmd}[nargs][optargdefault]{defn}

Define or redefine a command (see also \DeclareRobustCommand in Class and package commands).
The starred form of these two forbids the arguments from containing multiple paragraphs of text (i.e., a \par token; in plain TeX terms: the commands are not \long). With the default form, arguments can be multiple paragraphs.
These are the parameters (examples follow):
cmd 	Required; \cmd is the command name. It must begin with a backslash, \, and must not begin with the four character string \end. For \newcommand, it must not be already defined. For \renewcommand, this name must already be defined.
nargs 	Optional; an integer from 0 to 9, specifying the number of arguments that the command takes, including any optional argument. Omitting this argument is the same as specifying 0, meaning that the command has no arguments. If you redefine a command, the new version can have a different number of arguments than the old version.
optargdefault 	 Optional; if this argument is present then the first argument of \cmd is optional, with default value optargdefault (which may be the empty string). If optargdefault is not present then \cmd does not take an optional argument.
That is, if \cmd is called with a following argument in square brackets, as in \cmd[optval]{...}..., then within defn the parameter #1 is set to optval. On the other hand, if \cmd is called without following square brackets then within defn the parameter #1 is set to optargdefault. In either case, the required arguments start with #2.
Omitting [optargdefault] from the definition is entirely different from giving the square brackets with empty contents, as in []. The former says the command being defined takes no optional argument, so #1 is the first required argument (if nargs ≥ 1); the latter sets the optional argument #1 to the empty string as the default, if no optional argument was given in the call.
Similarly, omitting [optval] from a call is also entirely different from giving the square brackets with empty contents. The former sets #1 to the value of optval (assuming the command was defined to take an optional argument); the latter sets #1 to the empty string, just as with any other value.
If a command is not defined to take an optional argument, but is called with an optional argument, the results are unpredictable: there may be a LaTeX error, there may be incorrect typeset output, or both.
defn 	 Required; the text to be substituted for every occurrence of \cmd. The parameters #1, #2, …, #nargs are replaced by the values supplied when the command is called (or by optargdefault in the case of an optional argument not specified in the call, as just explained).
TeX ignores blanks in the source following a control word (see Control sequences), as in ‘\cmd ’. If you want a space there, one solution is to type {} after the command (‘\cmd{} ’), and another solution is to use an explicit control space (‘\cmd\ ’).
A simple example of defining a new command: \newcommand{\RS}{Robin Smith} results in \RS being replaced by the longer text. Redefining an existing command is similar: \renewcommand{\qedsymbol}{{\small QED}}.
If you use \newcommand and the command name has already been used then you get something like ‘LaTeX Error: Command \fred already defined. Or name \end... illegal, see p.192 of the manual’. Similarly, If you use \renewcommand and the command name has not been defined then you get something like ‘LaTeX Error: \hank undefined’.
Here the first definition creates a command with no arguments, and the second, a command with one required argument:

\newcommand{\student}{Ms~O'Leary}
\newcommand{\defref}[1]{Definition~\ref{#1}}

Use the first as in I highly recommend \student{} to you. The second has a variable argument, so that \defref{def:basis} expands to Definition~\ref{def:basis}, which ultimately expands to something like ‘Definition~3.14’.
Similarly, but with two required arguments: \newcommand{\nbym}[2]{$#1 \times #2$} is invoked as \nbym{2}{k}.
This example has an optional argument.

\newcommand{\salutation}[1][Sir or Madam]{Dear #1:}

Then \salutation gives ‘Dear Sir or Madam:’ while \salutation[John] gives ‘Dear John:’. And \salutation[] gives ‘Dear :’.
This example has an optional argument and two required arguments.

\newcommand{\lawyers}[3][company]{#2, #3, and~#1}
I employ \lawyers[Howe]{Dewey}{Cheatem}.

The output is ‘I employ Dewey, Cheatem, and Howe.’. The optional argument, Howe, is associated with #1, while Dewey and Cheatem are associated with #2 and #3. Because of the optional argument, \lawyers{Dewey}{Cheatem} will give the output ‘I employ Dewey, Cheatem, and company.’.
The braces around defn do not define a group, that is, they do not delimit the scope of the result of expanding defn. For example, with \newcommand{\shipname}[1]{\it #1}, in this sentence,

The \shipname{Monitor} met the \shipname{Merrimac}.

the words ‘met the’, and the period, would incorrectly be in italics. The solution is to put another pair of braces inside the definition: \newcommand{\shipname}[1]{{\it #1}}.

Control sequence, control word and control symbol
When reading input TeX converts the stream of read characters into a sequence of tokens. When TeX sees a backslash \, it will handle the following characters in a special way in order to make a control sequence token.
The control sequences fall into two categories:
control word, when the control sequence is gathered from a \ followed by at least one ASCII letter (A-Z and a-z), followed by at least one non-letter.
control symbol, when the control sequence is gathered from a \ followed by one non-letter character.
The sequence of characters so found after the \ is also called the control sequence name.
Blanks after a control word are ignored and do not produce any whitespace in the output (see \newcommand & \renewcommand and \(SPACE)).
Just as the \relax command does nothing, the following input will simply print ‘Hello!’ :

Hel\relax&#160;&#160;&#160;
&#160;&#160;&#160;lo!

This is because blanks after \relax, including the newline, are ignored, and blanks at the beginning of a line are also ignored (see Leading blanks).

\providecommand
Synopses, one of:

\providecommand{\cmd}{defn}
\providecommand{\cmd}[nargs]{defn}
\providecommand{\cmd}[nargs][optargdefault]{defn}
\providecommand*{\cmd}{defn}
\providecommand*{\cmd}[nargs]{defn}
\providecommand*{\cmd}[nargs][optargdefault]{defn}

Defines a command, as long as no command of this name already exists. If no command of this name already exists then this has the same effect as \newcommand. If a command of this name already exists then this definition does nothing. This is particularly useful in a file that may be loaded more than once, such as a style file. See \newcommand & \renewcommand, for the description of the arguments.
This example

\providecommand{\myaffiliation}{Saint Michael's College}
\providecommand{\myaffiliation}{Lyc\'ee Henri IV}
From \myaffiliation.

outputs ‘From Saint Michael's College.’. Unlike \newcommand, the repeated use of \providecommand to (try to) define \myaffiliation does not give an error.

\makeatletter & \makeatother
Synopsis:

\makeatletter
  ... definition of commands with @ in their name ..
\makeatother

Use this pair when you redefine LaTeX commands that are named with an at-sign character ‘@’. The \makeatletter declaration makes the at-sign character have the category code of a letter, code 11. The \makeatother declaration sets the category code of the at-sign to code 12, its default value.
As TeX reads characters, it assigns each one a category code, or catcode. For instance, it assigns the backslash character ‘\’ the catcode 0. Command names consist of a category 0 character, ordinarily backslash, followed by letters, category 11 characters (except that a command name can also consist of a category 0 character followed by a single non-letter symbol).
LaTeX’s source code has the convention that some commands use @ in their name. These commands are mainly intended for package or class writers. The convention prevents authors who are just using a package or class from accidentally replacing such a command with one of their own, because by default the at-sign has catcode 12.
Use the pair \makeatletter and \makeatother inside a .tex file, typically in the preamble, when you are defining or redefining commands named with @, by having them surround your definition. Don’t use these inside .sty or .cls files since the \usepackage and \documentclass commands already arrange that the at-sign has the character code of a letter, catcode 11.
For a comprehensive list of macros with an at-sign in their names see https://ctan.org/pkg/macros2e.
In this example the class file has a command \thesis@universityname that the user wants to change. These three lines should go in the preamble, before the \begin{document}.

\makeatletter
\renewcommand{\thesis@universityname}{Saint Michael's College}
\makeatother

\@ifstar
Synopsis:

\newcommand{\mycmd}{\@ifstar{\mycmd@star}{\mycmd@nostar}}
\newcommand{\mycmd@nostar}[nostar-num-args]{nostar-body} 
\newcommand{\mycmd@star}[star-num-args]{star-body}

Many standard LaTeX environments or commands have a variant with the same name but ending with a star character *, an asterisk. Examples are the table and table* environments and the \section and \section* commands.
When defining environments, following this pattern is straightforward because \newenvironment and \renewenvironment allow the environment name to contain a star. So you just have to write \newenvironment{myenv} or \newenvironment{myenv*} and continue the definition as usual. For commands the situation is more complex as the star not being a letter cannot be part of the command name. As in the synopsis above, there will be a user-called command, given above as \mycmd, which peeks ahead to see if it is followed by a star. For instance, LaTeX does not really have a \section* command; instead, the \section command peeks ahead. This command does not accept arguments but instead expands to one of two commands that do accept arguments. In the synopsis these two are \mycmd@nostar and \mycmd@star. They could take the same number of arguments or a different number, or no arguments at all. As always, in a LaTeX document a command using an at-sign @ in its name must be enclosed inside a \makeatletter ... \makeatother block (see \makeatletter & \makeatother).
This example of \@ifstar defines the command \ciel and a variant \ciel*. Both have one required argument. A call to \ciel{blue} will return "not starry blue sky" while \ciel*{night} will return "starry night sky".

\makeatletter
\newcommand*{\ciel@unstarred}[1]{not starry #1 sky}
\newcommand*{\ciel@starred}[1]{starry #1 sky}
\newcommand*{\ciel}{\@ifstar{\ciel@starred}{\ciel@unstarred}}
\makeatother

In the next example, the starred variant takes a different number of arguments than the unstarred one. With this definition, Agent 007’s ``My name is \agentsecret*{Bond}, \agentsecret{James}{Bond}.'' is equivalent to entering the commands ``My name is \textsc{Bond}, \textit{James} textsc{Bond}.''

\newcommand*{\agentsecret@unstarred}[2]{\textit{#1} \textsc{#2}}
\newcommand*{\agentsecret@starred}[1]{\textsc{#1}}
\newcommand*{\agentsecret}{%
  \@ifstar{\agentsecret@starred}{\agentsecret@unstarred}}

After a command name, a star is handled similarly to an optional argument. (This differs from environment names in which the star is part of the name itself and as such could be in any position.) Thus, it is technically possible to put any number of spaces between the command and the star. Thus \agentsecret*{Bond} and \agentsecret&#160;*{Bond} are equivalent. However, the standard practice is not to insert any such spaces.
There are two alternative ways to accomplish the work of \@ifstar. (1) The suffix package allows the construct \newcommand\mycommand{unstarred-variant} followed by \WithSuffix\newcommand\mycommand*{starred-variant}. (2) LaTeX provides the xparse package, which allows this code:

\NewDocumentCommand\foo{s}{\IfBooleanTF#1
  {starred-variant}%
  {unstarred-variant}% 
  }

\newcounter: Allocating a counter
Synopsis, one of:

\newcounter{countername}
\newcounter{countername}[supercounter]

Globally defines a new counter named countername and initialize it to zero (see Counters).
The name countername must consist of letters only. It does not begin with a backslash. This name must not already be in use by another counter.
When you use the optional argument [supercounter] then the counter countername will be reset to zero whenever supercounter is incremented. For example, ordinarily subsection is numbered within section so that any time you increment section, either with \stepcounter (see \stepcounter) or \refstepcounter (see \refstepcounter), then LaTeX will reset subsection to zero.
This example

\newcounter{asuper}  \setcounter{asuper}{1}
\newcounter{asub}[asuper] \setcounter{asub}{3}   % Note `asuper'
The value of asuper is \arabic{asuper} and of asub is \arabic{asub}.
\stepcounter{asuper}
Now asuper is \arabic{asuper} while asub is \arabic{asub}.

produces ‘The value of asuper is 1 and that of asub is 3’ and ‘Now asuper is 2 while asub is 0’.
If the counter already exists, for instance by entering asuper twice, then you get something like ‘LaTeX Error: Command \c@asuper already defined. Or name \end... illegal, see p.192 of the manual.’.
If you use the optional argument then the super counter must already exist. Entering \newcounter{jh}[lh] when lh is not a defined counter will get you ‘LaTeX Error: No counter 'lh' defined.’

\newlength
Synopsis:

\newlength{\len}

Allocate a new length register (see Lengths). The required argument \len has to be a control sequence (see Control sequences), and as such must begin with a backslash, \ under normal circumstances. The new register holds rubber lengths such as 72.27pt or 1in plus.2in minus.1in (a LaTeX length register is what plain TeX calls a skip register). The initial value is zero. The control sequence \len must not be already defined.
An example:

\newlength{\graphichgt}

If you forget the backslash then you get ‘Missing control sequence inserted’. If the control sequence already exists then you get something like ‘LaTeX Error: Command \graphichgt already defined. Or name \end... illegal, see p.192 of the manual’.

\newsavebox
Synopsis:

\newsavebox{\cmd}

Define \cmd, the string consisting of a backslash followed by cmd, to refer to a new bin for storing material. These bins hold material that has been typeset, to use multiple times or to measure or manipulate (see Boxes). The bin name \cmd is required, must start with a backslash, \, and must not already be a defined command. This command is fragile (see \protect).
This allocates a bin and then puts typeset material into it.

\newsavebox{\logobox}
\savebox{\logobox}{LoGo}
Our logo is \usebox{\logobox}.

The output is ‘Our logo is LoGo’.
If there is an already defined bin then you get something like ‘LaTeX Error: Command \logobox already defined. Or name \end... illegal, see p.192 of the manual’.
The allocation of a box is global.

\newenvironment & \renewenvironment
Synopses, one of:

\newenvironment{env}{begdef}{enddef}
\newenvironment{env}[nargs]{begdef}{enddef}
\newenvironment{env}[nargs][optargdefault]{begdef}{enddef}
\newenvironment*{env}{begdef}{enddef}
\newenvironment*{env}[nargs]{begdef}{enddef}
\newenvironment*{env}[nargs][optargdefault]{begdef}{enddef}

or one of these.

\renewenvironment{env}{begdef}{enddef}
\renewenvironment{env}[nargs]{begdef}{enddef}
\renewenvironment{env}[nargs][optargdefault]{begdef}{enddef}
\renewenvironment*{env}{begdef}{enddef}
\renewenvironment*{env}[nargs]{begdef}{enddef}
\renewenvironment*{env}[nargs][optargdefault]{begdef}{enddef}

Define or redefine the environment env, that is, create the construct \begin{env} ... body ... \end{env}.
The starred form of these commands requires that the arguments not contain multiple paragraphs of text. However, the body of these environments can contain multiple paragraphs.
env 	Required; the environment name. It consists only of letters or the * character, and thus does not begin with backslash, \. It must not begin with the string end. For \newenvironment, the name env must not be the name of an already existing environment, and also the command \env must be undefined. For \renewenvironment, env must be the name of an existing environment.
nargs 	Optional; an integer from 0 to 9 denoting the number of arguments of that the environment takes. When you use the environment these arguments appear after the \begin, as in \begin{env}{arg1} ... {argn}. Omitting this is equivalent to setting it to 0; the environment will have no arguments. When redefining an environment, the new version can have a different number of arguments than the old version.
optargdefault 	Optional; if this is present then the first argument of the defined environment is optional, with default value optargdefault (which may be the empty string). If this is not in the definition then the environment does not take an optional argument.
That is, when optargdefault is present in the definition of the environment then you can start the environment with square brackets, as in \begin{env}[optval]{...} ... \end{env}. In this case, within begdefn the parameter #1 is set to the value of optval. If you call \begin{env} without square brackets, then within begdefn the parameter #1 is set to the value of the default optargdefault. In either case, any required arguments start with #2.
Omitting [myval] in the call is different than having the square brackets with no contents, as in []. The former results in #1 expanding to optargdefault; the latter results in #1 expanding to the empty string.
begdef 	Required; the text expanded at every occurrence of \begin{env}. Within begdef, the parameters #1, #2, ... #nargs, are replaced by the values that you supply when you call the environment; see the examples below.
enddef 	Required; the text expanded at every occurrence of \end{env}. This may not contain any parameters, that is, you cannot use #1, #2, etc., here (but see the final example below).
All environments, that is to say the begdef code, the environment body, and the enddef code, are processed within a group. Thus, in the first example below, the effect of the \small is limited to the quote and does not extend to material following the environment.
If you try to define an environment and the name has already been used then you get something like ‘LaTeX Error: Command \fred already defined. Or name \end... illegal, see p.192 of the manual’. If you try to redefine an environment and the name has not yet been used then you get something like ‘LaTeX Error: Environment hank undefined.’.
This example gives an environment like LaTeX’s quotation except that it will be set in smaller type.

\newenvironment{smallquote}{%
  \small\begin{quotation}
}{%
  \end{quotation}
}

This has an argument, which is set in boldface at the start of a paragraph.

\newenvironment{point}[1]{%
  \noindent\textbf{#1}
}{%
}

This one shows the use of a optional argument; it gives a quotation environment that cites the author.

\newenvironment{citequote}[1][Shakespeare]{%
  \begin{quotation}
  \noindent\textit{#1}: 
}{%
  \end{quotation}
}

The author’s name is optional, and defaults to ‘Shakespeare’. In the document, use the environment like this.

\begin{citequote}[Lincoln]
  ...
\end{citequote}

The final example shows how to save the value of an argument to use in enddef, in this case in a box (see \sbox & \savebox).

\newsavebox{\quoteauthor}
\newenvironment{citequote}[1][Shakespeare]{%
  \sbox\quoteauthor{#1}%
  \begin{quotation} 
}{%
  \hspace{1em plus 1fill}---\usebox{\quoteauthor}
  \end{quotation}
}

\newtheorem
Synopses:

\newtheorem{name}{title}
\newtheorem{name}{title}[numbered_within]
\newtheorem{name}[numbered_like]{title}

Define a new theorem-like environment. You can specify one of numbered_within and numbered_like, or neither, but not both.
The first form, \newtheorem{name}{title}, creates an environment that will be labelled with title; see the first example below.
The second form, \newtheorem{name}{title}[numbered_within], creates an environment whose counter is subordinate to the existing counter numbered_within, so this counter will be reset when numbered_within is reset. See the second example below.
The third form \newtheorem{name}[numbered_like]{title}, with optional argument between the two required arguments, creates an environment whose counter will share the previously defined counter numbered_like. See the third example.
This command creates a counter named name. In addition, unless the optional argument numbered_like is used, inside of the theorem-like environment the current \ref value will be that of \thenumbered_within (see \ref).
This declaration is global. It is fragile (see \protect).
Arguments:
name 	The name of the environment. It is a string of letters. It must not begin with a backslash, \. It must not be the name of an existing environment, and the command name \name must not already be defined.
title 	The text to be printed at the beginning of the environment, before the number. For example, ‘Theorem’.
numbered_within 	Optional; the name of an already defined counter, usually a sectional unit such as chapter or section. When the numbered_within counter is reset then the name environment’s counter will also be reset.
If this optional argument is not used then the command \thename is set to \arabic{name}.
numbered_like 	Optional; the name of an already defined theorem-like environment. The new environment will be numbered in sequence with numbered_like.
Without any optional arguments the environments are numbered sequentially. The example below has a declaration in the preamble that results in ‘Definition 1’ and ‘Definition 2’ in the output.

\newtheorem{defn}{Definition}
\begin{document}
\section{...}
\begin{defn}
  First def 
\end{defn}

\section{...}
\begin{defn}
  Second def
\end{defn}

This example has the same document body as the prior one. But here \newtheorem’s optional argument numbered_within is given as section, so the output is like ‘Definition 1.1’ and ‘Definition 2.1’.

\newtheorem{defn}{Definition}[section]
\begin{document}
\section{...}
\begin{defn}
  First def 
\end{defn}

\section{...}
\begin{defn}
  Second def
\end{defn}

In the next example there are two declarations in the preamble, the second of which calls for the new thm environment to use the same counter as defn. It gives ‘Definition 1.1’, followed by ‘Theorem 2.1’ and ‘Definition 2.2’.

\newtheorem{defn}{Definition}[section]
\newtheorem{thm}[defn]{Theorem}
\begin{document}
\section{...}
\begin{defn}
  First def 
\end{defn}

\section{...}
\begin{thm}
  First thm
\end{thm}

\begin{defn}
  Second def
\end{defn}

\newfont
This command is obsolete. This description is here only to help with old documents. New documents should define fonts in families through the New Font Selection Scheme which allows you to, for example, associate a boldface with a roman (see Fonts).
Synopsis:

\newfont{\cmd}{font description}

Define a command \cmd that will change the current font. The control sequence must not already be defined. It must begin with a backslash, \.
The font description consists of a fontname and an optional at clause. LaTeX will look on your system for a file named fontname.tfm. The at clause can have the form either at dimen or scaled factor, where a factor of ‘1000’ means no scaling. For LaTeX’s purposes, all this does is scale all the character and other font dimensions relative to the font’s design size, which is a value defined in the .tfm file.
This defines two equivalent fonts and typesets a few characters in each.

\newfont{\testfontat}{cmb10 at 11pt}
\newfont{\testfontscaled}{cmb10 scaled 1100}
\testfontat abc
\testfontscaled abc

\protect
All LaTeX commands are either fragile or robust. A fragile command can break when it is used in the argument to certain other commands, typically those that write material to the table of contents, the cross-reference file, etc. To prevent fragile commands from causing errors, one solution is to precede them with the command \protect.
For example, when LaTeX runs the \section{section name} command it writes the section name text to the .aux auxiliary file, moving it there for use elsewhere in the document such as in the table of contents. Such an argument that is used in multiple places is referred to as a moving argument. A command is fragile if it can expand during this process into invalid TeX code. Some examples of moving arguments are those that appear in the \caption{...} command (see figure), in the \thanks{...} command (see \maketitle), and in @-expressions in the tabular and array environments (see tabular).
If you get strange errors from commands used in moving arguments, try preceding it with \protect. Each fragile command must be protected with their own \protect.
Although usually a \protect command doesn’t hurt, length commands such as \parindent should not be preceded by a \protect command (see Lengths. Nor can a \protect command be used in the argument to \addtocounter or \setcounter command (see \setcounter and \addtocounter. These commands are already robust.
As of the October 2019 release of LaTeX (https://www.latex-project.org/news/latex2e-news/ltnews30.pdf), most commands that had been previously fragile were fixed to be robust. For example, any command taking an optional argument, such as \root or \raisebox, was fragile, but is now robust. Similarly, \(...\) math was fragile and is now robust ($...$ has always been robust).
Perhaps the most commonly used remaining fragile command is \verb; for example,

\begin{figure}
  ...
  \caption{This \verb|\command| causes an error.}
\end{figure}

Adding \protect does not help here. It’s usually feasible to rewrite the caption (or section heading or whatever) to use \texttt, often the simplest solution.
Alternatively, to use \verb, you can apply the \cprotect command from cprotect package (https://ctan.org/pkg/cprotect) to the \caption:

\cprotect\caption{This \verb|\command| is ok with \verb|\cprotect|.}

\cprotect also allows use of \begin...\end environments in moving arguments, where they are normally not allowed, via a similar prefix command \cprotEnv.

\ignorespaces & \ignorespacesafterend
Synopsis:

\ignorespaces

or

\ignorespacesafterend

Both commands cause LaTeX to ignore blanks (that is, characters of catcode 10 such as space or tabulation) after the end of the command up to the first box or non-blank character. The first is a primitive command of TeX, and the second is LaTeX-specific.
The \ignorespaces is often used when defining commands via \newcommand, or \newenvironment, or \def. The example below illustrates. It allows a user to show the points values for quiz questions in the margin but it is inconvenient because, as shown in the enumerate list, users must not put any space between the command and the question text.

\newcommand{\points}[1]{\makebox[0pt]{\makebox[10em][l]{#1~pts}}
\begin{enumerate} 
  \item\points{10}no extra space output here
  \item\points{15} extra space between the number and the `extra'
\end{enumerate}

The solution is to change to this.

\newcommand{\points}[1]{%
  \makebox[0pt]{\makebox[10em][l]{#1~pts}}\ignorespaces}

A second example shows blanks being removed from the front of text. The commands below allow a user to uniformly attach a title to names. But, as given, if a title accidentally starts with a space then \fullname will reproduce that.

\newcommand{\honorific}[1]{\def\honorific{#1}} % remember title
\newcommand{\fullname}[1]{\honorific~#1}       % put title before name

\begin{tabular}{|l|}
\honorific{Mr/Ms}  \fullname{Jones} \\  % no extra space here
\honorific{ Mr/Ms} \fullname{Jones}     % extra space before title
\end{tabular}

To fix this, change to \newcommand{\fullname}[1]{\ignorespaces\honorific~#1}.
The \ignorespaces is also often used in a \newenvironment at the end of the begin clause, as in \begin{newenvironment}{env name}{... \ignorespaces}{...}.
To strip blanks off the end of an environment use \ignorespacesafterend. An example is that this will show a much larger vertical space between the first and second environments than between the second and third.

\newenvironment{eq}{\begin{equation}}{\end{equation}}
\begin{eq}
e=mc^2
\end{eq}
\begin{equation}
F=ma
\end{equation}
\begin{equation}
E=IR
\end{equation}

Putting a comment character % immediately after the \end{eq} will make the vertical space disappear, but that is inconvenient. The solution is to change to \newenvironment{eq}{\begin{equation}}{\end{equation}\ignorespacesafterend}.

xspace package
This is an add-on package, not part of core LaTeX. Synopsis:

\usepackage{xspace}
  ...
\newcommand{...}{...\xspace}

The \xspace macro, when used at the end of a command definition, adds a space unless the command is followed by certain punctuation characters.
After a control sequence that is a control word (see Control sequences, as opposed to control symbols such as \$), TeX gobbles blank characters. Thus, in the first sentence below, the output has ‘Vermont’ placed snugly against the period, without any intervening space, despite the space in the input.

\newcommand{\VT}{Vermont}
Our college is in \VT .
\VT{} summers are nice.

But because of the gobbling, the second sentence needs the empty curly braces or else there would be no space separating ‘Vermont’ from ‘summers’. (Many authors instead use a backslash-space \ for this. See \(SPACE).)
The xspace package provides \xspace. It is for writing commands which are designed to be used mainly in text. It must be placed at the very end of the definition of these commands. It inserts a space after that command unless what immediately follows is in a list of exceptions. In this example, the empty braces are not needed.

\newcommand{\VT}{Vermont\xspace}
Our college is in \VT .
\VT summers are nice.

The default exception list contains the characters ,.'/?;:!~-), the open curly brace and the backslash-space command discussed above, and the commands \footnote or \footnotemark. You can add to that list as with \xspaceaddexceptions{\myfni \myfnii} which adds \myfni and \myfnii to the list; and you can remove from that list as with \xspaceremoveexception{!}.
A comment: many experts prefer not to use \xspace. Putting it in a definition means that the command will usually get the spacing right. But it isn’t easy to predict when to enter empty braces because \xspace will get it wrong, such as when it is followed by another command, and so \xspace can make editing material harder and more error-prone than instead of always inserting the empty braces.

Class and package commands
These are commands designed to help writers of classes or packages.

\AtBeginDvi & \AtEndDvi
Synopsis:

\AtBeginDvi{code}
\AtEndDvi{code}

\AtBeginDvi saves, in a box register, code to be executed at the beginning of the shipout of the first page of the document. Despite the name, it applies to DVI, PDF, and XDV output. It fills the shipout/firstpage hook; new code should use that hook directly.
Similarly, \AtEndDvi (previously available only with the atenddvi package) is code executed when finalizing the main output document.

\AtEndOfClass & \AtEndOfPackage
Synopses:

\AtEndOfClass{code}
\AtEndOfPackage{code}

Hooks to insert code to be executed when LaTeX finishes processing the current class resp. package.
These hooks can be used multiple times; each code segment will be executed in the order called. Many packages and classes use these commands.
See also \AtBeginDocument.

\CheckCommand
Synopsis:

\CheckCommand{cmd}[num][default]{definition}
\CheckCommand* (same parameters)

Like \newcommand (see \newcommand & \renewcommand) but does not define cmd; instead it checks that the current definition of cmd is exactly as given by definition and is or is not \long as expected. A long command is a command that accepts \par within an argument.
With the unstarred version of \CheckCommand, cmd is expected to be \long; with the starred version, cmd must not be \long
\CheckCommand raises an error when the check fails. This allows you to check before you start redefining cmd yourself that no other package has already redefined this command.

\ClassError and \PackageError and other messages
Produce error, warning, and informational messages for classes:
\ClassError{class name}{error-text}{help-text} 	\ClassWarning{class name}{warning-text} 	\ClassWarningNoLine{class name}{warning-text} 	\ClassNote{class name}{note-text} 	\ClassNoteNoLine{class name}{note-text} 	\ClassInfo{class name}{log-text} 	
and the same for packages:
\PackageError{package name}{error-text}{help-text} 	\PackageWarning{package name}{warning-text} 	\PackageWarningNoLine{package name}{warning-text} 	\PackageNote{package name}{note-text} 	\PackageNoteNoLine{package name}{note-text} 	\PackageInfo{package name}{log-text} 	
For \ClassError and \PackageError the message is error-text, followed by TeX’s ‘?’ error prompt. If the user then asks for help by typing h, they see help-text.
The four Warning commands write warning-text on the terminal and log file (with no error prompt), prefixed by the text ‘Warning:’.
The four Note commands also write the note-text to the terminal and log file, without the ‘Warning:’ prefix.
The NoLine versions omit the number of the input line generating the message, while the other versions do show that number.
The two Info commands write log-text only in the transcript file and not to the terminal.
To format the messages, including the help-text: use \protect to stop a command from expanding, get a line break with \MessageBreak, and get a space with \space where a space character is ignored, most commonly after a command.
LaTeX appends a period to the messages.

\CurrentOption
Expands to the name of the option currently being processed. This can only be used within the code argument of either \DeclareOption or \DeclareOption*.

\DeclareOption
Synopsis:

\DeclareOption{option}{code}
\DeclareOption*{option}{code}

Define an option a user can include in their \documentclass command. For example, a class smcmemo could have an option logo allowing users to put the institutional logo on the first page. The document would start with \documentclass[logo]{smcmemo}. To enable this, the class file must contain \DeclareOption{logo}{code} (and later, \ProcessOptions).
If you request an option that has not been declared, by default this will produce a warning like Unused global option(s): [badoption]. This can be changed by using \DeclareOption*{code}, which executes code for any unknown option.
For example, many classes extend an existing class, using code such as \LoadClass{article} (see \LoadClass). In this case, it makes sense to pass any otherwise-unknown options to the underlying class, like this:

\DeclareOption*{%
  \PassOptionsToClass{\CurrentOption}{article}%
}

As another example, our class smcmemo might allow users to keep lists of memo recipients in external files, so the user could invoke \documentclass[math]{smcmemo} and it will read the file math.memo. This code inputs the file if it exists, while if it doesn’t, the option is passed to the article class:

\DeclareOption*{\InputIfFileExists{\CurrentOption.memo}
  {}{%
  \PassOptionsToClass{\CurrentOption}{article}}}

\DeclareRobustCommand
Synopsis:

\DeclareRobustCommand{cmd}[num][default]{definition}
\DeclareRobustCommand* (same parameters

\DeclareRobustCommand and its starred form are generally like \newcommand and \newcommand* (see \newcommand & \renewcommand), with the addition that they define a so-called robust command, even if some code within the definition is fragile. (For a discussion of robust and fragile commands, see \protect.)
Also unlike \newcommand, these do not give an error if macro cmd already exists; instead, a log message is put into the transcript file if a command is redefined. Thus, \DeclareRobustCommand can be used to define new robust commands or to redefine existing commands, making them robust.
The starred form, \DeclareRobustCommand*, disallows the arguments from containing multiple paragraphs, just like the starred form of \newcommand and \renewcommand. The meaning of the arguments is the same.
Commands defined this way are a bit less efficient than those defined using \newcommand so unless the command’s data is fragile and the command is used within a moving argument, use \newcommand.
Related to this, the etoolbox package offers three commands and their starred forms: \newrobustcmd(*) \renewrobustcmd(*), and \providerobustcmd(*). They are similar to \newcommand, \renewcommand, and \providecommand and their own starred forms, but define a robust cmd. They have two possible advantages compared to \DeclareRobustCommand:
They use the low-level e-TeX protection mechanism rather than the higher-level LaTeX \protect mechanism, so they do not incur the slight loss of performance mentioned above, and
They make the same distinction between \new…, \renew…, and \provide…, as the standard commands. That is, they do not just write a log message when you redefine cmd that already exists; you need to use either \renew… or \provide…, or you get an error. This may or may not be a benefit.

\ExecuteOptions
Synopsis:

\ExecuteOptions{option-list}

For each option option in option-list, in order, this command executes the command \ds@option. If this command is not defined then that option is silently ignored.
This can be used to provide a default option list before \ProcessOptions. For example, if in a class file you want the default to be 11pt fonts then you could specify \ExecuteOptions{11pt}\ProcessOptions\relax.

\IfFileExists & \InputIfFileExists
Synopses:

\IfFileExists{filename}{true-code}{false-code}
\InputIfFileExists{filename}{true-code}{false-code}

\IfFileExists executes true-code if LaTeX finds the file filename or false-code otherwise. In the first case it executing true-code and then inputs the file. Thus the command

\IfFileExists{img.pdf}{%
  \includegraphics{img.pdf}}
  {\typeout{!! img.pdf not found}

will include the graphic img.pdf if it is found and otherwise give a warning.
This command looks for the file in all search paths that LaTeX uses, not only in the current directory. To look only in the current directory do something like \IfFileExists{./filename}{true-code}{false-code}. If you ask for a filename without a .tex extension then LaTeX will first look for the file by appending the .tex; for more on how LaTeX handles file extensions see \input.
\InputIfFileExists is similar, but, as the name states, automatically \inputs filename if it exists. The true-code is executed just before the \input; if the file doesn’t exist, the false-code is executed. An example:

\InputIfFileExists{mypkg.cfg}
  {\PackageInfo{Loading mypkg.cfg for configuration information}}
  {\PackageInfo{No mypkg.cfg found}}

\LoadClass & \LoadClassWithOptions
Synopses:

\LoadClass[options-list]{class-name}[release-date]
\LoadClassWithOptions{class-name}[release-date]

Load a class, as with \documentclass[options-list]{class-name}[release-date]. An example: \LoadClass[twoside]{article}.
The options-list, if present, is a comma-separated list. The release-date is also optional. If present it must have the form YYYY/MM/DD.
If you request release-date and the date of the package installed on your system is earlier, then you get a warning on the screen and in the log like this:

You have requested, on input line 4, version `2038/01/19' of
document class article, but only version `2014/09/29 v1.4h
Standard LaTeX document class' is available.

The command version \LoadClassWithOptions uses the list of options for the current class. This means it ignores any options passed to it via \PassOptionsToClass. This is a convenience command that lets you build classes on existing ones, such as the standard article class, without having to track which options were passed.

\NeedsTeXFormat
Synopsis:

\NeedsTeXFormat{format}[format-date]

Specifies the format that this class must be run under. Often issued as the first line of a class file, and most often used as: \NeedsTeXFormat{LaTeX2e}. When a document using that class is processed, the format being run must exactly match the format name given, including case. If it does not match then execution stops with an error like ‘This file needs format `LaTeX2e' but this is `plain'.’.
To require a version of the format that you know to have certain features, include the optional format-date on which those features were implemented. If present, it must be in the form YYYY/MM/DD. If the format version installed on your system is earlier than format date then you get a warning like this.

You have requested release `2038/01/20' of LaTeX, but only
release `2016/02/01' is available.

\OptionNotUsed
Adds the current option to the list of unused options. Can only be used within the code argument of either \DeclareOption or \DeclareOption*.

\PassOptionsToClass & \PassOptionsToPackage
Synopses:

\PassOptionsToClass{options}{clsname}
\PassOptionsToPackage{option}{pkgname}

Adds the options in the comma-separated list options to the options used by any future \RequirePackage or \usepackage command for the class clsname or the package pkgname, respectively.
The reason for these commands is that although you may load a package any number of times with no options, if you can specify options only the first time you load the package. Loading a package with options more than once will get you an error like Option clash for package foo.. LaTeX throws an error even if there is no conflict between the options.
If your own code is bringing in a package twice then you can combine the calls; for example, replacing the two

\RequirePackage[landscape]{geometry}
\RequirePackage[margins=1in]{geometry}

with the single command

\RequirePackage[landscape,margins=1in]{geometry}

However, suppose you are loading firstpkg and inside that package it loads secondpkg, and you need secondpkg to be loaded with option draft. Then before load the first package you must tell LaTeX about the desired options for the second package, like this:

\PassOptionsToPackage{draft}{secondpkg}
\RequirePackage{firstpkg}

If firstpkg.sty loads an option in conflict with what you want then you may have to alter its source, or yours.
These commands are useful for general users as well as class and package writers. For instance, suppose a user wants to load the graphicx package with the option draft and also wants to use a class foo that loads the graphicx package, but without that option. The user could start their LaTeX file with \PassOptionsToPackage{draft}{graphicx} \documentclass{foo}.

\ProcessOptions
Synopsis:

\ProcessOptions\@options
\ProcessOptions*\@options

Execute the code for each option that the user has invoked. Invoke it in the class file as \ProcessOptions\relax (because of the existence of the starred version, described below).
Options come in two types. Local options have been specified for this particular package in \usepackage[options], \RequirePackage[options], or the options argument of \PassOptionsToPackage{options}. Global options are those given by the class user in \documentclass[options]. If an option is specified both locally and globally then it is local.
When \ProcessOptions is called for a package pkg.sty, the following happens:
For each option option so far declared with \DeclareOption, \ProcessOptions looks to see if that option is either global or local for pkg. If so, then it executes the declared code. This is done in the order in which these options were given in pkg.sty.
For each remaining local option, it executes the command \ds@option if it has been defined somewhere (other than by a \DeclareOption); otherwise, it executes the default option code given in \DeclareOption*. If no default option code has been declared then it gives an error message. This is done in the order in which these options were specified.
When \ProcessOptions is called for a class it works in the same way except that all options are local, and the default code for \DeclareOption* is \OptionNotUsed rather than an error.
The starred version \ProcessOptions* executes the options in the order specified in the calling commands, rather than in the order of declaration in the class or package. For a package, this means that the global options are processed first.

\ProvidesClass & \ProvidesPackage
Synopses:

\ProvidesClass{clsname}[release-date [info-text]]
\ProvidesPackage{pkgname}[release-date [info-text]]

Identifies the class or package being defined, printing a message to the screen and the log file.
When you load a class or package, for example with \documentclass{smcmemo} or \usepackage{test}, LaTeX inputs a file (smcmemo.cls and test.sty, respectively). If the name of the file does not match the class or package name declared in it then you get a warning. Thus, if you invoke \documentclass{smcmemo}, and the file smcmemo.cls has the statement \ProvidesClass{foo} then you get a warning like You have requested document class `smcmemo', but the document class provides 'foo'. This warning does not prevent LaTeX from processing the rest of the class file normally.
If you include the optional argument then you must include a date, before any spaces, of the form YYYY/MM/DD. The rest of the optional argument is free-form, although it traditionally identifies the class. It is written to the screen during compilation and to the log file. Thus, if your file smcmemo.cls contains the line \ProvidesClass{smcmemo}[2008/06/01 v1.0 SMC memo class] and your document’s first line is \documentclass{smcmemo} then you will see Document Class: smcmemo 2008/06/01 v1.0 SMC memo class.
The date in the optional argument allows class and package users to ask to be warned if the version of the class or package is earlier than release date. For instance, a user could enter \documentclass{smcmemo}[2018/10/12] or \usepackage{foo}[[2017/07/07]] to require a class or package with certain features by specifying that it must be released no earlier than the given date. Perhaps more importantly, the date serves as documentation of the last release. (In practice, package users rarely include a date, and class users almost never do.)

\ProvidesFile
Synopsis:

\ProvidesFile{filename}[info-text]

Declare a file other than the main class and package files, such as a configuration or font definition file. It writes the given information to the log file, essentially like \ProvidesClass and \ProvidesPackage (see the previous section).
For example:

\ProvidesFile{smcmemo.cfg}[2017/10/12 config file for smcmemo.cls]

writes this into the log:

File: smcmemo.cfg 2017/10/12 config file for smcmemo.cls

\RequirePackage & \RequirePackageWithOptions
Synopsis:

\RequirePackage[option-list]{pkgname}[release-date]
\RequirePackageWithOptions{pkgname}[release-date]

Load a package, like the command \usepackage (see Additional packages). An example: \RequirePackage[landscape,margin=1in]{geometry}
The initial optional argument option-list, if present, must be a comma-separated list. The trailing optional argument release-date, if present, must have the form YYYY/MM/DD. If the release date of the package as installed on your system is earlier than release-date then you get a warning like ‘You have requested, on input line 9, version `2017/07/03' of package jhtest, but only version `2000/01/01' is available’.
The \RequirePackageWithOptions variant uses the list of options for the current class. This means it ignores any options passed to it via \PassOptionsToClass. This is a convenience command to allow easily building classes on existing ones without having to track which options were passed.
The difference between \usepackage and \RequirePackage is small. The \usepackage command is intended to be used in documents, while \RequirePackage is intended for package and class files. The most significant difference in practice is that \RequirePackage can be used in a document before the \documentclass command, while \usepackage gives an error there. The most common need for this nowadays is for the \DocumentMetadata command (see \DocumentMetadata).
The LaTeX development team strongly recommends use of these and related commands over plain TeX’s \input; see the Class Guide (https://ctan.org/pkg/clsguide).