alvin alexander

LaTeX example: How to create your own commands with ‘newcommand’

LaTeX question: Can you show a simple example of creating your own LaTeX command?

Here is an example LaTeX file where I'm experimenting with various newcommand and renewcommand capabilities. The file actually contains six LaTeX examples, and in each step I add one more LaTeX feature that is a little harder than the previous step.

In the last several examples I start passing parameters into my LaTeX commands. After that, I start using the "html" package (html.sty) and the "ifthen" package (ifthen.sty) to do some if/then decision-making in my last several newcommand/renewcommand examples.

LaTeX example program

Without any further ado, here is the LaTeX example code:

I hope these examples on creating your own LaTeX commands helps with your own LaTeX document work.

Help keep this website running!

  • LaTeX HTML package - control your output
  • LaTeX if then examples (LaTeX ifthen package)
  • LaTeX FAQ Site
  • LaTeX example document - description lists and tables
  • LaTeX example document using htmlonly, latexonly, and image

books by alvin

  • If I have died, please call ...
  • No thoughts in my mind, just peace
  • Book: Learn Functional Programming The Fast Way! (FP for OOP developers)
  • Functional Programming, Simplified (a best-selling FP book)
  • Scala 3 modules: How to build modular systems

LaTeX/Macros

Documents produced with the commands you have learned up to this point will look acceptable to a large audience. While they are not fancy-looking, they obey all the established rules of good typesetting, which will make them easy to read and pleasant to look at. However, there are situations where LaTeX does not provide a command or environment that matches your needs, or the output produced by some existing command may not meet your requirements.

In this chapter, we will try to give some hints on how to teach LaTeX new tricks and how to make it produce output that looks different from what is provided by default.

LaTeX is a fairly high-level language compared to Plain TeX and thus is more limited. The next chapter will focus on Plain TeX and will explain advanced techniques for programming.

  • 1.1 DeclareRobustCommand
  • 2.1 Extra space
  • 2.2 Declare commands within new environment
  • 2.3 Environment contents as a macro argument
  • 3 Extending the number of arguments
  • 4 Arithmetic
  • 5 Conditionals
  • 8 LaTeX Hooks
  • 9 Command-line LaTeX
  • 10 Notes and References

New commands [ edit | edit source ]

To add your own commands, use the

command. Basically, the command requires two arguments: the name of the command you want to create (preceded by a backslash), and the definition of the command. Note that the command name can but need not be enclosed in braces, as you like. The num argument in square brackets is optional and specifies the number of arguments the new command takes (up to 9 are possible). If missing it defaults to 0, i.e. no argument allowed.

The following two examples should help you to get the idea. The first example defines a new command called \wbal that will print “The Wikibook about LaTeX”. Such a command could come in handy if you had to write the title of this book over and over again.

The next example illustrates how to define a new command that takes one argument. The #1 tag gets replaced by the argument you specify. If you wanted to use more than one argument, use #2 and so on, these arguments are added in an extra set of brackets.

Name your new command \wbalTwo and not \wbal 2 as digits cannot be used to name macros — invalid characters will error out at compile-time.

LaTeX will not allow you to create a new command that would overwrite an existing one. But there is a special command in case you explicitly want this: \renewcommand . It uses the same syntax as the \newcommand command.

In certain cases you might also want to use the \providecommand command. It works like \newcommand , but if the command is already defined, LaTeX will silently ignore the new command.

With LaTex2e, it is also possible to add a default parameter to a command with the following syntax:

If the default parameter of \newcommand is present, then the first of the number of arguments specified by num is optional with a default value of default ; if absent, then all of the arguments are required.

{\displaystyle {\vec {a}}}

and write your vectors inside the new \myvec { ... } command. You can call it as you wish, but you'd better choose a short name because you will probably write it very often. Then, if you change your mind and you want your vectors to look differently you just have to change the definition of your \myvec { ... } . Use this approach whenever you can: this will save you a lot of time and increase the consistency of your document.

DeclareRobustCommand [ edit | edit source ]

Some commands are fragile , that is they fail in some environments. If a macro works in body text but not in (for example) a figure caption, it's worth trying to replace the \newcommand { \MyCommand } ... declaration with \DeclareRobustCommand { \MyCommand } ... in the preamble. This is especially true for macros which, when expanded, produce text that is written to a .aux file.

New command to work in both paragraph and math mode

Suppose you want to declare some variable which you want to use in paragraph as well as in math mode. It can be achieved with the help of \ensuremath command in Latex2e as follows

Space after the \newcommand

It is a common problem to having nonconforming spacing after a newly defined command.

Consider : "The momentum is calculated using p= mv." Note there is no space after the formula.

On the other hand "The formula p=mv calculates the momentum.", have space after the formula.

For this spacing problem one may use xspace package which will automatically decide if there should be any space after it or not.

New environments [ edit | edit source ]

Just as with the \newcommand command, there is a command to create your own environments. The \newenvironment command uses the following syntax:

Again \newenvironment can have an optional argument. When the \begin { name } command (which starts the environment) is encountered, the material specified in the before argument is processed before the text in the environment gets processed. The material in the after argument gets processed when the \end { name } command (which ends the environment) is encountered.

The optional num and default arguments are used the same way as in the \newcommand command. LaTeX makes sure that you do not define an environment that already exists. If you ever want to change an existing environment, you can use the \renewenvironment command. It uses the same syntax as the \newenvironment command.

The example below illustrates the usage of the \newenvironment command:

Extra space [ edit | edit source ]

When creating a new environment you may easily get bitten by extra spaces creeping in, which can potentially have fatal effects. One example is when you want to create a title environment which suppresses its own indentation as well as the one on the following paragraph. The \ignorespaces command in the begin block of the environment will make it ignore any space after executing the begin block. The end block is a bit more tricky as special processing occurs at the end of an environment. With the \ignorespacesafterend LaTeX will issue an \ignorespaces after the special ‘end’ processing has occurred.

Also, if you're still having problems with extra space being appended at the end of your environment when using the \input for external source, make sure there is no space between the beginning, sourcing, and end of the environment, such as:

Declare commands within new environment [ edit | edit source ]

New commands can be declared within newenvironment. Commands declared within the newenvironment refer to their arguments by doubling the # character. In the following example, a new environment is declared along with a nested command:

If, by mistake, the arguments passed to the \topics macro are defined with a single # character, the following error message will be thrown:

Environment contents as a macro argument [ edit | edit source ]

Some commands (for example, \verb , \textbf , and \fcolorbox ) expect the text to be modified to be passed as an argument, and thus cannot be placed in the "header" or "footer" of an environment definition. In some cases, a workaround is a corresponding environment, such as \begin { verbatim } ... \end { verbatim } for \verb . When no corresponding environment exists, an alternative is the environ package, which places the environment contents inside the local macro \BODY . In the following example, the makebold environment bolds its contents:

Extending the number of arguments [ edit | edit source ]

The xkeyval packages will let you define key/value options for commands.

The package is quite complete and documentation is exhaustive. We recommend that package developers read it. [1]

Let's provide a simple example [1] :

Arithmetic [ edit | edit source ]

LaTeX can manipulate numbers.

The calc package provides the common infix notation.

For high-precision computations, you can use the fp [2] package.

Conditionals [ edit | edit source ]

LaTeX can use conditionals thanks to the ifthen package.

FYI: For newer projects e-TeX is recommended [3] , available in LaTeX from etoolbox . See section 3.6 of their manual.

Following a short example, a bool that switches its state every time it is used. [4]

Loops [ edit | edit source ]

The PGF/TikZ extension provides the \foreach command.

If you are only using \foreach and not drawing graphics, you may instead use the pgffor package directly.

Alternatively you can check out the multido package.

Strings [ edit | edit source ]

xstring provides a lot of features. From CTAN:

  • testing a string’s contents
  • extracting substrings
  • substitution of substrings
  • string length
  • position of a substring
  • number of recurrences of a substring

LaTeX Hooks [ edit | edit source ]

LaTeX provides two hooks:

  • \AtBeginDocument will let you specify a set of commands that will be executed when \begin { document } is met.
  • \AtEndDocument does the same for \end { document } .

This gives you some more flexibility for macros. It can be useful to override settings that get executed after the preamble. These hooks can be called several times. The commands will be executed in the order they were set.

For instance, let's replace the page numbers with oldstylenums:

There are also hooks for classes and packages. See Creating Packages .

Command-line LaTeX [ edit | edit source ]

If you work on a Unix-like OS, you might be using Makefiles or any kind of script to build your LaTeX projects. In that connection it might be interesting to produce different versions of the same document by calling LaTeX with command-line parameters. If you add the following structure to your document:

Now you can call LaTeX like this:

First the command \blackandwhite gets defined and then the actual file is read with input. By setting \blackandwhite to false the color version of the document would be produced.

Notes and References [ edit | edit source ]

  • ↑ tex.stackexchange.com
  • ↑ ctan.mackichan.com
  • ↑ https://tex.stackexchange.com/questions/13866/why-is-the-ifthen-package-obsolete
  • ↑ https://tex.stackexchange.com/a/232059/37907

defining latex commands

  • Requests for expansion

Navigation menu

Latex Tutorial

How to use ‘\newcommand’ in LaTeX?

The \newcommand command in LaTeX allows you to define your custom commands . Replacing long or frequently used text snippets with a shorter, easier-to-remember command can save you time and effort. This guide will walk you through the basics of \newcommand and its various features.

What is ‘\newcommand’?

\newcommand is a LaTeX macro that lets you create a new command with a specific definition. This definition can be:

  • Text: You can define your command to insert a specific text block automatically.
  • LaTeX code: You can define your command to execute a sequence of LaTeX commands. This can be useful for frequently used formatting patterns or complex expressions.
  • Parameters: Your command can take optional or mandatory arguments, allowing for dynamic content based on the provided input.

How to use \newcommand?

Basic syntax.

The basic syntax for \newcommand is as follows:

\newcommand : This is the command that tells LaTeX you want to define a new command.

commandname : This is the name of your new command. It should start with a backslash ( \ ), followed by a combination of lowercase and/or uppercase letters, or alternatively, a backslash followed by a single non-letter symbol. Choose a unique name for your command.

numargs : The number of arguments your command takes. It can take any integer values from 1 to 9. If not included, the command will be devoid of any arguments. ( optional )

option : If this condition exists, the initial argument becomes optional, with a default value specified at this point. In the absence of this condition, all arguments are mandatory. ( optional )

definition : This is the actual content of your command. It can be text, LaTeX code, or a combination of both. You can use the # symbol followed by the argument number (e.g., #1 , #2 , and so on) to refer to the arguments within the definition.

Where to write this command?

If you want your command to be available throughout the document, define it in the preamble (before \begin{document} ).

Let’s create a simple command that formats a person’s name in bold:

  • \person : The name of the command.
  • [1] : The command takes one argument.
  • \textbf{#1} : The definition makes the argument bold.

Now you can use your \person command in the document:

\newcommand in latex example 1

Let’s look at another example.

\newcommand in latex example 2

Multiple Arguments in ‘\newcommand’

You can define commands with multiple arguments. For example,

Now, look at the above command’s usage with two arguments in an example.

\newcommand in latex example 3

Let’s look at an example in which it defines a command to format a fraction with specific spacing.

This command takes two arguments ( #1 and #2 ) and formats them as a fraction with a small space between the numerator and denominator.

\newcommand in latex example 5

  • Choose clear and concise command names: Use easily recognizable names and reflect the command’s purpose.
  • Use arguments effectively: Define arguments for commands that require specific information or variation.
  • Document your commands: Add comments explaining your custom commands for future reference.
  • Use \newcommand strategically to target repetitive tasks and complex formatting.
  • You can use \renewcommand to redefine an existing command, including those defined by LaTeX. Be cautious, as it can break your document if used incorrectly.

That’s a basic guide to using \newcommand in LaTeX . By harnessing the potential of \newcommand , you transform LaTeX from a mere typesetting tool into a personal workspace customized to your needs. So, unleash your creativity, define shortcuts, and ease document creation.

Related posts:

  • Is LaTeX a programming language?
  • Is LaTeX better than Word?
  • Is LaTeX slower than Word?
  • LaTeX Document Classes: A Comprehensive Guide
  • LaTeX Input File (Preamble and Body)
  • \input vs. \include: What’s the Difference?
  • What is an ‘Environment’ in LaTeX?
  • Mastering Font Size in LaTeX: A Comprehensive Guide
  • Table vs. Tabular Environment in LaTeX
  • LaTeX Special Characters (+Printing Commands)

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

web analytics

These are the 100 most frequent LaTeX commands

Many writefull users write in latex - using writefull for overleaf to proofread and revise their work. for this analysis, we parsed 300k papers from arxiv to explore what latex commands are used most often in research writing..

Our analysis

We downloaded 300,000 papers from arXiv.org, parsed these to extract the LaTeX commands, then listed these by frequency.

The sheet below shows the 100 most frequently used LaTeX commands - the list further down shows their % share and definitions.

It’s not surprising that the commands \begin and \end are most common - these appear throughout any research text to indicate environments. Many commands reveal common practices in scientific writing, like citing sources ( \cite ), reporting math ( \frac , \alpha ), cross-referencing ( \ref , \label ), and referencing ( \bibitem ). Other frequent commands are used to control formatting ( \bf , \rm ).

defining latex commands

See how many of these commands you tend to use, and if there may be commands you didn’t know about. Or, if you’re new to LaTeX, why not use this overview to master the most useful commands first? To help you get started, we’re defining these 100 commands below.

The 100 most frequent LaTeX commands

1. \end (6.0%) \end{environment} ends an environment begun by \begin{environment}

2. \begin (6.0%) \begin{environment} begins an environment. It is followed by the assorted environments, and is always paired with \end{environment}.

3. \ref (5.0%) \ref{text} is the section number in which \label{text} occurs.

4. \frac (4.9%) \frac{numerator}{denominator} produces a fraction in math environments.

5. \cite (4.5%) \cite[subcit]{ref} produces a reference, in square brackets, to a bibliographic item created with \bibitem{ref}. Optionally, a sub-citation 'subcit' can be inserted in the entry.

6. \label (3.8%) \label{text} provides a reference point that is accessed with \ref{text} or \pageref{text}.

7. \bibitem (3.8%) \bibitem{ref} text creates a bibliography entry text, numbers it, and labels it with reference label ref.

8. \bf (3.3%) \bf switches to bold face type.

9. \right (3.1%) \right* (where * is a delimiter) must be paired with '\left*' (not necessarily using the same delimiter). '.' acts as a null delimiter (math mode).

10. \left (3.1%) \left* (where * is a delimiter) must be paired with '\right*' (not necessarily using the same delimiter). '.' acts as a null delimiter (math mode).

11. \rm (1.6%) \rm switches to Roman type.

12. \alpha (1.6%) \alpha is α (math mode).

13. \mu (1.6%) \mu is µ (math mode).

14. \newcommand (1.5%) \newcommand{\cs}[narg]{def} defines a new control sequence '\cs' with definition 'def'. Optionally, 'narg' is the number of arguments, indicated in def as #1, #2, etc.

15. \def (1.5%) \def lets you define your own commands.

16. \it (1.4%) \it switches to italic type.

17. \pi (1.4%) \pi is π. \Pi is Π (math mode).

18. \sigma (1.1%) \sigma is σ. \Sigma is Σ (math mode).

19. \sum (1.1%) \sum is ∑ (math mode).

20. \lambda (1.0%) \lambda is λ. \Lambda is Λ (math mode).

21. \beta (1.0%) \beta is β (math mode).

22. \nu (0.9%) \nu is ν (math mode).

23. \partial (0.9%) \partial is ∂ (math mode).

24. \int (0.9%) \int is ∫ (math mode).

25. \delta (0.9%) \delta is δ. \Delta is ∆ (math mode).

26. \rho (0.9%) \rho is ρ (math mode).

27. \phi (0.9%) \phi is φ. \Phi is Φ (math mode).

28. \gamma (0.9%) \gamma is γ. \Gamma is Γ (math mode).

29. \omega (0.9%) \omega is ω. \Omega is Ω (math mode).

30. \caption (0.9%) \caption[loftitle]{text} creates a numbered caption in a figure or table environment. Optional 'loftitle' contains entry for the list of figures if different from 'text'.

31. \over (0.9%) \over can be used to produce fractions in math environments.

32. \bibinfo (0.9%) \bibinfo is used to tag the bibliography with the field information from the original entry in the BibTEX database.

33. \nonumber (0.8%) \nonumber is used in an eqnarray environment to suppress equation numbering.

34. \bar (0.8%) \bar puts a macron over a letter (math mode).

35. \sqrt (0.8%) \sqrt produces a squared root, for example, \sqrt[3]{arg}. The root ([3]) is optional.

36. \theta (0.8%) \theta is θ. \Theta is Θ (math mode).

37. \tau (0.8%) \tau is τ (math mode).

38. \em (0.8%) \em toggles between roman and italic fonts for emphasis.

39. \rangle (0.8%) \rangle is ⟩ (math mode).

40. \hat (0.7%) \hat makes a circumflex: ˆ (math mode).

41. \tilde (0.7%) \tilde makes a tilde: ˜ (math mode).

42. \cal (0.7%) \cal produces calligraphic letters (math mode).

43. \section (0.7%) \section[toctitle]{text} begins a new section, automatically headed and numbered. Optional 'toctitle' contains entry for the table of contents if different from 'text'. \section*{text} begins a section, prints a title, but doesn’t include a number or make a table of contents entry.

44. \hline (0.7%) \hline draws a horizontal line across all columns of a tabular or array environment.

45. \mbox (0.6%) \mbox{text} places text into a horizontal box.

46. \item (0.6%) \item[text] indicates a list entry. text is optional, used in description environment.

47. \psi (0.6%) \psi is ψ. \Psi is Ψ (math mode).

48. \includegraphics (0.6%) \includegraphics inserts an image.

49. \vec (0.6%) \vec puts a vector over a letter (math mode).

50. \langle (0.6%) \langle is ⟨ (math mode).

51. \epsilon (0.6%) \epsilon is ϵ (math mode).

52. \textbf (0.6%) \textbf makes text bold.

53. \eta (0.5%) \eta is η (math mode).

54. \put (0.5%) \put(x,y){stuff} is the basic picture-drawing command. (x,y) is the reference point, the meaning of which varies for different 'stuff'. 'stuff' may be anything that goes in an \mbox.

55. \cdot (0.5%) \cdot is · (math mode).

56. \in (0.5%) \in is ∈ (math mode).

57. \xi (0.5%) \xi is ξ. \Xi is Ξ (math mode).

58. \infty (0.5%) \infty is ∞ (math mode).

59. \quad (0.5%) A \quad is a space equal to the current font size.

60. \subsection (0.5%) \subsection[toctitle]{text}, \subsubsection[toctitle]{text} begin new subsections, automatically headed and numbered. Optional 'toctitle' contains entry for the table of contents if different from 'text'. \subsection*{text}, \subsubsection*{text} begin subsections, but suppress section number and table of contents entry.

61. \mathcal (0.5%) \mathcal is used to turn on math calligraphic font for uppercase letters and digits.

62. \author (0.5%) \author{names} declares author(s) for the \maketitle command.

63. \times (0.5%) \times is × (math mode).

64. \emph (0.5%) \emph is used to emphasize text, usually with italics.

65. \bibnamefont (0.5%) \bibnamefont is used for user-defined font commands to present author names in bibliographies.

66. \mathbf (0.4%) \mathbf is used to present math in bold font.

67. \prime (0.4%) \prime is ′ (math mode).

68. \be (0.4%) \be is used as an abbreviation for '\begin{equation}'.

69. \mathrm (0.4%) \mathrm is used to turn on roman typestyle for uppercase and lowercase letters.

70. \ee (0.4%) \ee is used as an abbreviation for '\end{equation}'.

71. \vspace (0.4%) \vspace{len} leaves a vertical space of dimension 'len'.

72. \pm (0.4%) \pm is ± (math mode).

73. \chi (0.4%) \chi is χ (math mode).

74. \usepackage (0.4%) \usepackage is used in the preamble of a document to import a package.

75. \bibfnamefont (0.4%) \bibnamefont is used for user-defined font commands to present (first) names in bibliographies.

76. \ell (0.3%) \ell is ℓ (math mode).

77. \text (0.3%) \text is used to add normal text in math mode.

78. \qquad (0.3%) A \qquad gives twice the amount of \quad, and \quad is a space equal to the current font size).

79. \noindent (0.3%) \noindent suppresses indentation of first line of paragraph.

80. \to (0.3%) \to is → (math mode).

81. \varphi (0.3%) \varphi is ϕ (math mode).

82. \hspace (0.3%) \hspace{len} leaves a horizontal space of dimension 'len'.

83. \leq (0.3%) \leq is ≤ (math mode).

84. \cos (0.3%) \cos is cos (math mode).

85. \eqref (0.3%) \eqref is used to provide cross-references to equations.

86. \overline (0.3%) \overline{text} produces an overline on 'text' (math mode).

87. \sin (0.3%) \sin is sin (math mode).

88. \kappa (0.3%) \kappa is κ (math mode).

89. \hbox (0.3%) \hbox is used to treat contents as text.

90. \rightarrow (0.3%) \rightarrow is →. \Rightarrow is ⇒ (math mode).

91. \varepsilon (0.3%) \varepsilon is ε (math mode).

92. \textit (0.3%) \textit is used to produce text-mode material in italics within a mathematical expression.

93. \dagger (0.3%) \dagger is † (math mode).

94. \affiliation (0.3%) \affiliation{text} presents author affiliation information.

95. \big (0.3%) \big is used to set a (larger) size for brackets and parentheses.

96. \otimes (0.2%) \otimes is ⊗ (math mode).

97. \equiv (0.2%) \equiv is ≡ (math mode).

98. \zeta (0.2%) \zeta is ζ (math mode).

99. \dot (0.2%) \dot makes a dot over a letter: ˙ (math mode).

100. \ln (0.2%) \ln is ln (math mode).

Reference: Most of the above definitions were drawn from this useful source [pdf] ).

About the author

Hilde is Chief Applied Linguist at Writefull.

defining latex commands

Extending LaTeX

This lesson shows how you can extend LaTeX to your needs and change its layout further by using packages and definitions. It also shows how you can define your own commands.

After having declared a class, in the preamble you can modify functionality in LaTeX by adding one or more packages . These can

Changing how LaTeX works

The LaTeX ‘kernel’ (the core of LaTeX) is rather limited in user customisation, and so some add-on packages deal with very common ideas. The first is to change how LaTeX deals with language-specific typesetting (hyphenation, punctuation, quotations, localisation, etc.). Different languages have different rules, so it’s important to tell LaTeX which one to use. This is handled by the babel package.

Try un-commenting the (clearly misleading) line to load babel and see the effect. (The standard hyphenation rules are US English.)

The babel package does a lot more than hyphenation, depending on the language involved; we’ve given some more details if you need them.

Changing design

It’s useful to be able to adjust some aspects of design independent of the document class. The most obvious one are the page margins. We’ve just used the geometry package in the example above, but let’s now have an example specifically about margins.

You should see the effect here compared to not loading geometry .

Adding new functionality

One of LaTeX’s strengths is that you can choose from thousands of packages, including ones for writing mathematical text, for hyperlinking, for sophisticated capabilities with color, etc. We will see some more common packages in later lessons.

Defining commands

Sometimes you need a command specific to your document, either some functionality not found in the available packages or simply a command to enter a common expression that is used multiple times.

The following example shows a command to produce keywords with a specific style applied.

In the definition [1] denotes the number of arguments (here one) and #1 denotes the first argument that is supplied ( apples or oranges in this example). You may have up to nine arguments, but it is usually best to have just one argument, or sometimes none at all.

Defining commands does not just reduce the typing required to produce a document. It helps to separate out the styling information. If it is decided to use a different style for keywords, rather than having to edit the entire document, you simply need to use a different definition. Here we load the xcolor package to provide colors, and use blue in place of bold in the formatting.

Beware that defining too many commands or defining commands with multiple arguments may make the document source harder to understand as it is using an unfamiliar syntax. The ability to define document-specific commands should be used with care.

Try out writing some text in other European languages and see how babel affects hyphenation: you can probably find some text on the internet, and guess the right options.

Try altering the margins in the geometry example. You can set the individual top , bottom , left and right margins separately using a comma-separated list.

Try loading the lipsum package and then add the command \lipsum to your document. Can you guess why this package is useful for making examples?

Try altering the definition of \kw to achieve a different style.

No Search Results

  • Environments

LaTeX environments are used to apply specific typesetting effect(s) to a section of your document’s content. This article explains how to use existing environments and define new ones.

  • 1 Introduction
  • 2 Environments
  • 3.1 Defining simple environments
  • 3.2 Defining environments which take arguments
  • 3.3.1 Some notes
  • 4 Redefining existing environments
  • 5 Further reading

Introduction

An environment starts with \begin{name} and ends with \end{name} :

where “ name ” is the name of the environment being used—such as the following example using “ center ” to format (center) a paragraph of text:

 Open this example in Overleaf.

This example produces the following output:

Image showing the center alignment

The following example uses the tabular environment to typeset a small table. tabular takes an additional argument { c c c } which defines the alignment of the cells—see the Tables article for more information.

Example of the tabular environment

Some environments accept optional arguments which are usually passed inside brackets ( [...] ).

Defining a new environment

To define a new environment use the \newenvironment command which has the general form:

  • name is the name of this user-defined argument;
  • numarg is the number of arguments, from 1 to 9, this environment accepts. If [numarg] is omitted then the environment does not accept any arguments—such as the boxed environment defined in the next example ;
  • optarg_default makes the first argument optional and provides a default value—i.e., it is the value used if an optional argument value is not provided;
  • begin_def is LaTeX code executed when the environment starts (opens), i.e., when you write \begin{name} . Within this code you can use arguments accepted by the environment—note that the optional argument is #1 and the remaining arguments are accessed using #2 to #numarg;
  • end_def is LaTeX code executed when the environment ends (closes); i.e., when you write \end{name} . You cannot use any of the arguments within this code section.

Defining simple environments

In this first example, we define the boxed environment which does not take any arguments. It draws a box around text contained within the environment:

Demonstrating a custom LaTeX environment

If we compare our definition of boxed with the general form of \newenvironment we can see:

  • name is boxed ;
  • neither [numarg] or [optarg_default] are provided because this environment does not take any arguments;
  • begin_def is the LaTeX code—provided between a pair of braces {...} —which is executed when the environment starts (opens):
  • end_def is the LaTeX code—provided between a pair of braces {...} —which is executed when the environment stops (closes):

In the example, begin_def starts a center environment and within that a tabular environment is opened to draw vertical lines and a horizontal line around the text we place in the environment. end_def draws another horizontal line then closes the tabular and center environments.

Defining environments which take arguments

Let’s enhance the previous example to do the following:

  • use an optional argument to typeset a title. If a title is not provided, use the default value This is a box ;
  • use a second argument which contains material to typeset ahead of the text we provide within the environment itself.

So we have 2 arguments:

  • the first (argument 1) is optional;
  • the second (argument 2) is not.

This means numarg =2.

We can use the following definition of our updated boxed environment:

This enhanced version differs from the original in the following ways:

  • [numarg] is present and has the value 2;
  • [optarg_default] is also present, making the first argument optional with a default value This is a box .

The following example demonstrates some uses of our upgraded boxed environment:

Environment with an optional parameter

Numbered environments

Numbered environments can be created either manually or directly with the command \newtheorem , as demonstrated by the following example:

 Open this example in Overleaf

Example showing user-defined numbered environments

  • incremented by 1 by using \refstepcounter{example} within the environment definition;
  • reset every time a new \section{...} is started;
  • a variable whose current value can be typeset using \theexample . See the article about counters to learn more.
  • the name of the new environment: SampleEnv in our example;
  • the text to be printed in bold at the beginning of the line: Sample Environment in our example;
  • an optional parameter which determines when the counter is reset; and if it’s used the counter gets preceded by that reset counter’s value: section in our example.

The amsthm package , along with amsmath , provide useful extra definitions alongside \newtheorem ; see Theorems and proofs for further details.

Redefining existing environments

Environments can be redefined using \renewenvironment whose syntax is the same as \newenvironment —see the section Defining a new environment for an explanation of the various parameters:

The next example redefines the itemize environment—this is only an example to illustrate the process, it should not be considered within a real document. The new itemize environment no longer produces a bulleted list; instead, it centres and emphasizes (italicizes) the text within it (using the \em command).

Example with a redefined itemize environment

Further reading

For more information see:

  • Understanding packages and class files
  • Writing your own package
  • Writing your own class
  • Lengths in LaTeX
  • Using colours in LaTeX
  • Page size and margins
  • List of packages and class files
  • The not so short introduction to L a T e X 2 ε
  • LaTeX/Creating_Packages on WikiBooks
  • Documentation Home
  • Learn LaTeX in 30 minutes

Overleaf guides

  • Creating a document in Overleaf
  • Uploading a project
  • Copying a project
  • Creating a project from a template
  • Using the Overleaf project menu
  • Including images in Overleaf
  • Exporting your work from Overleaf
  • Working offline in Overleaf
  • Using Track Changes in Overleaf
  • Using bibliographies in Overleaf
  • Sharing your work with others
  • Using the History feature
  • Debugging Compilation timeout errors
  • How-to guides
  • Guide to Overleaf’s premium features

LaTeX Basics

  • Creating your first LaTeX document
  • Choosing a LaTeX Compiler
  • Paragraphs and new lines
  • Bold, italics and underlining

Mathematics

  • Mathematical expressions
  • Subscripts and superscripts
  • Brackets and Parentheses
  • Fractions and Binomials
  • Aligning equations
  • Spacing in math mode
  • Integrals, sums and limits
  • Display style in math mode
  • List of Greek letters and math symbols
  • Mathematical fonts
  • Using the Symbol Palette in Overleaf

Figures and tables

  • Inserting Images
  • Positioning Images and Tables
  • Lists of Tables and Figures
  • Drawing Diagrams Directly in LaTeX
  • TikZ package

References and Citations

  • Bibliography management with bibtex
  • Bibliography management with natbib
  • Bibliography management with biblatex
  • Bibtex bibliography styles
  • Natbib bibliography styles
  • Natbib citation styles
  • Biblatex bibliography styles
  • Biblatex citation styles
  • Multilingual typesetting on Overleaf using polyglossia and fontspec
  • Multilingual typesetting on Overleaf using babel and fontspec
  • International language support
  • Quotations and quotation marks

Document structure

  • Sections and chapters
  • Table of contents
  • Cross referencing sections, equations and floats
  • Nomenclatures
  • Management in a large project
  • Multi-file LaTeX projects
  • Lengths in L a T e X
  • Headers and footers
  • Page numbering
  • Paragraph formatting
  • Line breaks and blank spaces
  • Text alignment
  • Single sided and double sided documents
  • Multiple columns
  • Code listing
  • Code Highlighting with minted
  • Margin notes
  • Font sizes, families, and styles
  • Font typefaces
  • Supporting modern fonts with X Ǝ L a T e X

Presentations

Field specific.

  • Theorems and proofs
  • Chemistry formulae
  • Feynman diagrams
  • Molecular orbital diagrams
  • Chess notation
  • Knitting patterns
  • CircuiTikz package
  • Pgfplots package
  • Typesetting exams in LaTeX
  • Attribute Value Matrices

Class files

Advanced tex/latex.

  • In-depth technical articles on TeX/LaTeX

Have you checked our knowledge base ?

Message sent! Our team will review it and reply by email.

The TeX FAQ

Frequently Asked Question List for TeX

Programming

Transcribing latex command definitions.

At several places in this FAQ, questions are answered in terms of how to program a LaTeX macro. Sometimes, these macros might also help users of Plain TeX or other packages; this answer attempts to provide a rough-and-ready guide to transcribing such macro definitions for use in other packages.

The reason LaTeX has commands that replace \def , is that there’s a general philosophy within LaTeX that the user should be protected from himself: the user has different commands according to whether the command to be defined exists ( \renewcommand ) or not ( \newcommand ), and if its status proves not as the user expected, an error is reported. A third definition command, \providecommand , only defines if the target is not already defined; LaTeX has no direct equivalent of \def , which ignores the present state of the command. The final command of this sort is \DeclareRobustCommand , which creates a command which is “robust” (i.e., will not expand if subjected to LaTeX “protected expansion”); from the Plain TeX user’s point of view, \DeclareRobustCommand should be treated as a non-checking version of \newcommand .

LaTeX commands are, by default, defined \long ; an optional * between the \newcommand and its (other) arguments specifies that the command is not to be defined \long . The * is detected by a command ifstar which uses \futurelet to switch between two branches, and gobbles the * : LaTeX users are encouraged to think of the * as part of the command name.

LaTeX’s checks for unknown command are done by \ifx comparison of a \csname construction with \relax ; since the command name argument is the desired control sequence name, this proves a little long-winded. Since #1 is the requisite argument, we have:

( \@gobble simply throws away its argument).

The arguments of a LaTeX command are specified by two optional arguments to the defining command: a count of arguments (0–9: if the count is 0, the optional count argument may be omitted), and a default value for the first argument, if the defined command’s first argument is to be optional. So:

In the last case, \foo may be called as \foo{goodbye} , which is equivalent to \foo[boo]{goodbye} (employing the default value given for the first argument), or as \foo[hello]{goodbye} (with an explicit first argument).

Coding of commands with optional arguments is exemplified by the coding of the last \foo above:

FAQ ID: Q-cvtlatex Tags:  macros

IMAGES

  1. A Beginner's Guide to LATEX

    defining latex commands

  2. [Tex/LaTex] Most useful/important (La)TeX commands/environments

    defining latex commands

  3. what is latex

    defining latex commands

  4. what is latex

    defining latex commands

  5. LaTeX Basics with Chart Studio

    defining latex commands

  6. Product: The Ultimate LaTeX Reference Guide

    defining latex commands

VIDEO

  1. Latex 01

  2. Latex Purchase Regrets Episode 2

  3. This is my latex# collection#latex tutorial#

  4. Quick Guide to Latex

  5. Work in Latex

  6. LaTex

COMMENTS

  1. Defining your own commands

    Creating a document in Overleaf. Uploading a project. Copying a project. Creating a project from a template. Using the Overleaf project menu. Including images in Overleaf. Exporting your work from Overleaf. Working offline in Overleaf. Using Track Changes in Overleaf.

  2. Commands

    Most LaTeX commands are simple words preceded by a special character, usually \, the backslash character. Let's look at some examples: \documentclass{ article } \begin{ document } In a document there are different types of \textbf{ commands } that define the way the elements are displayed. This

  3. How to create new commands with multiple arguments?

    56 I'd like to create a new command \add that accepts 2 arguments, called entity and title. In other words, the command should look like this: \add {entity} {title}. The output should have the following form: \textit {entity} ' {title}'. So if I, for example, type \add {article} {LaTeX} the result should be article 'LaTeX'. How can I do this?

  4. LaTeX example: How to create your own commands with 'newcommand'

    The file actually contains six LaTeX examples, and in each step I add one more LaTeX feature that is a little harder than the previous step. In the last several examples I start passing parameters into my LaTeX commands. After that, I start using the "html" package (html.sty) and the "ifthen" package (ifthen.sty) to do some if/then decision ...

  5. LaTeX/Macros

    LaTeX provides two hooks: \AtBeginDocument will let you specify a set of commands that will be executed when \begin{ document } is met. \AtEndDocument does the same for \end{ document }. This gives you some more flexibility for macros. It can be useful to override settings that get executed after the preamble.

  6. The definitions of LaTeX commands

    The definitions of LaTeX commands There are several reasons to want to know the definitions of LaTeX commands: from the simplest "idle curiosity", to the pressing need to patch something to make it "work the way you want it". None of these are pure motives, but knowledge and expertise seldom arrive through the purest of motives.

  7. How to Define New Commands and Operators

    In this video, we show how to define commands and operators. This video series is a LaTeX tutorial for beginners. It includes the basic idea of LaTeX and how...

  8. Defining LaTeX commands within other commands

    LaTeX command definition is significantly different from the TeX primitive form discussed in an earlier question about definitions within macros. In most ways, the LaTeX situation is simpler (at least in part because it imposes more restrictions on the user); however, defining a command within a command still requires some care.

  9. How to use 'newcommand' in LaTeX?

    Tips. Choose clear and concise command names: Use easily recognizable names and reflect the command's purpose. Use arguments effectively: Define arguments for commands that require specific information or variation. Document your commands: Add comments explaining your custom commands for future reference. Use \newcommand strategically to target repetitive tasks and complex formatting.

  10. Commands defined with * options

    Commands defined with * options. LaTeX commands commonly have "versions" defined with an asterisk tagged onto their name: for example \newcommand and \newcommand* (the former defines a \long version of the command). The simple-minded way for a user to write such a command involves use of the ifthen package: This does the trick, for ...

  11. These are the 100 most frequent LaTeX commands

    These are the 100 most frequent LaTeX commands Many Writefull users write in LaTeX - using Writefull for Overleaf to proofread and revise their work. For this analysis, we parsed 300K papers from arXiv to explore what LaTeX commands are used most often in research writing. Our analysis

  12. How to define a new command?

    1 Answer. The syntax should look like this. In a \newcommand declaration, you use [1] to indicate a mandatory argument, [2] to indicate two arguments, and so on, and then refer to them as #1 and #2 in the command text. \newcommand is often better than \def, as it will issue a warning if the command is already defined; if you know it's defined ...

  13. Define your own commands in LaTeX

    LaTeX: https://www.latex-project.orgTexmaker (LaTeX editor): https://www.xm1math.net/texmakerWikibooks LaTeX tutorial: https://en.wikibooks.org/wiki/LaTeXFor...

  14. macros

    8 Which of the following declarations is preferred when defining new textual macro's in latex \newcommand* {\dosomething} [1] {\textbf {#1}} versus \newcommand* {\dosomething} {\textbf} textbf is just used as an example. I know that the latter construction is not allowed if used inside a group e.g.

  15. Extending LaTeX using packages and definitions

    Extending LaTeX. This lesson shows how you can extend LaTeX to your needs and change its layout further by using packages and definitions. It also shows how you can define your own commands. After having declared a class, in the preamble you can modify functionality in LaTeX by adding one or more packages. These can.

  16. Commands and environments

    LaTeX documents behaviour can be controlled by using specific command. Typical command structure is as following: \commandname [optional argument] {main argument} Note, that all commands must be proceeded by the backslash mark and the main argument must be included inside {..} pair. Some commands have more than one arguments, for example:

  17. Environments

    Defining a new environment. To define a new environment use the \newenvironment command which has the general form: \newenvironment{name}[numarg][optarg_default]{begin_def}{end_def} numarg is the number of arguments, from 1 to 9, this environment accepts. If [numarg] is omitted then the environment does not accept any arguments—such as the ...

  18. How to define a command that defines another command?

    5 I have a command defined with xparse that looks like this: \NewDocumentCommand {\ME} {sogd<>} {\added [id=ME,remark= {#1}] {#2}} (for the full code see Passing complicated argument patterns to a new command) Now, I want this to be defined through another command, something like

  19. Introduction to Macros in Latex

    LaTeX is a free software package created in 1985 by the American computer scientist Leslie Lamport as a new version of the TeX typesetting system. It provides a set of powerful tools for creating professional-looking documents. One feature that makes LaTeX stand out is the use of macros. Macros are predefined commands that allow us to automate ...

  20. Defining commands/abbreviations that contain numbers

    macros - Defining commands/abbreviations that contain numbers - TeX - LaTeX Stack Exchange Defining commands/abbreviations that contain numbers Ask Question Asked 13 years, 1 month ago Modified 1 month ago Viewed 45k times 118 I tend to use \newcommand to define macros for symbols I use often, e.g. \newcommand {\hankel} {H^ { (1)}_0}.

  21. Transcribing LaTeX command definitions

    (@gobble simply throws away its argument). The arguments of a LaTeX command are specified by two optional arguments to the defining command: a count of arguments (0-9: if the count is 0, the optional count argument may be omitted), and a default value for the first argument, if the defined command's first argument is to be optional.