> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/field-specific/02-chemistry-formulae.md).

# Chemistry formulae

This article highlights two LaTeX packages designed for typesetting chemical content and documentation:

* [chemfig](https://www.ctan.org/pkg/chemfig): a package to [draw structural formulae of molecules](#using-chemfig-to-draw-molecules-structural-formulae)
* [mhchem](https://ctan.org/pkg/mhchem): a package to [typeset chemical formulae and equations](#using-mhchem-to-typeset-chemical-formulae-and-equations)

## Using chemfig to draw molecules (structural formulae)

Drawing a molecule consists mainly of connecting groups of atoms with lines. Simple linear formulae can be easily drawn using the `chemfig` package, as shown in the following example:

```latex
\documentclass{article}
\usepackage{chemfig}
\begin{document}

\section{Introduction}
Writing chemical formulae with chemfig is straightforward.

\chemfig{A=B}
\end{document}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Chemfig+example+1\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Csection%7BIntroduction%7D%0AWriting+chemical+formulae+with+chemfig+is+straightforward.%0A%0A%5Cchemfig%7BA%3DB%7D%0A%5Cend%7Bdocument%7D)

The following image shows the output produced by the example above:

![A basic chemfig example](/files/7FFfC8q5iI01lgSDCHa9)

The package is imported by `\usepackage{chemfig}` in the preamble. The command `\chemfig{A=B}` the draws the molecule. The symbol `=` determines the type of bond. See the [reference guide](#reference-guide) for a list of bond types.

### Angles

There are several ways to define angles between bonds in molecules.

```latex
To define chemical formulae you can use units that define the angles

\chemfig{A-[1]B-[7]C}

Absolute angles

\chemfig{A-[:50]B-[:-25]C}

Relative angles

\chemfig{A-[::50]B-[::-25]C}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Chemfig+example+2\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0ATo+define+chemical+formulae+you+can+use+units+that+define+the+angles%0A%0A%5Cchemfig%7BA-%5B1%5DB-%5B7%5DC%7D%0A%0AAbsolute+angles%0A%0A%5Cchemfig%7BA-%5B%3A50%5DB-%5B%3A-25%5DC%7D%0A%0ARelative+angles%0A%0A%5Cchemfig%7BA-%5B%3A%3A50%5DB-%5B%3A%3A-25%5DC%7D%0A%5Cend%7Bdocument%7D)

The following image shows the output produced by the example above:

![Chemfig2OLV2.png](/files/lBDcqaDjT59JUqDTV8zw)

Each one of the three commands in the example above uses a different method to determine the angle between bonds.

* `default units`: In the command `\chemfig{A-[1]B-[7]C}` the parameters inside brackets set the angle in special units, each unit equals 45°. Hence in the example the angles are 45° and 315°.
* `absolute units`: The angles can be set in absolute units, in the command `\chemfig{A-[:50]B-[:-25]C}` the parameter inside the brackets represent the angle, in degrees, measured from the horizontal baseline. Negative angles are allowed.
* `relative angles`: In the third example `\chemfig{A-[::50]B-[::-25]C}` the angles are measured from the previous bond, instead of the baseline.

### Rings

The example below presents the syntax to draw regular polygons:

```latex
Regular polygons:

\chemfig{A*5(-B=C-D-E=)}

Incomplete rings are also possible:

\chemfig{A*5(-B=C-D)}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Chemfig+example+3\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0ARegular+polygons%3A%0A%0A%5Cchemfig%7BA%2A5%28-B%3DC-D-E%3D%29%7D%0A%0AIncomplete+rings+are+also+possible%3A%0A%0A%5Cchemfig%7BA%2A5%28-B%3DC-D%29%7D%0A%5Cend%7Bdocument%7D)

The following image shows the output produced by the example above:

![Chemfig3OLV2.png](/files/3WUy8SAJoMHkNAgLLcLU)

The syntax of the command `\chemfig{A*5(-B=C-D-E=)}` is explained below:

* `A`: This is the first atom, the rest of the atoms will be drawn from here
* `*5`: Number of sides of the polygon
* `(-B=C-D-E=)`: The rest of the atoms and bonds. If not enough are passed to complete the polygon, an incomplete ring will be drawn.

There is an additional parameter that can be passed to this command: a double asterisk. For instance, if `**5` is set instead of `*5` a circle is drawn inside the polygon.

#### Connected rings

The next example draws the chemical structure of caffeine:

```latex
\documentclass{article}
\usepackage{chemfig}
\begin{document}
\section{I need caffeine.}

\chemfig{*6((=O)-N(-)-(*5(-N=-N(-)-))=-(=O)-N(-)-)}
\end{document}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Drawing+caffeine+using+chemfig\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csection%7BI+need+caffeine.%7D%0A%0A%5Cchemfig%7B%2A6%28%28%3DO%29-N%28-%29-%28%2A5%28-N%3D-N%28-%29-%29%29%3D-%28%3DO%29-N%28-%29-%29%7D%0A%5Cend%7Bdocument%7D)

The following graphic shows the output produced by the caffeine example:

![A drawing of the caffeine molecule produced using the chemfig LaTeX package](/files/HH8pX8K57yW5MqlaaZlP)

### Branches

Chemical formulae are not always linear, branched formulae are actually the most common type. Below an example on how to create them.

```latex
Branched molecule \vspace{.5cm}

\chemfig{H-C(-[2]H)(-[6]H)-C(=[1]O)-[7]H}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Chemfig+example+4\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0ABranched+molecule+%5Cvspace%7B.5cm%7D%0A%0A%5Cchemfig%7BH-C%28-%5B2%5DH%29%28-%5B6%5DH%29-C%28%3D%5B1%5DO%29-%5B7%5DH%7D%0A%5Cend%7Bdocument%7D)

The following image shows the output produced by the example above:

![Chemfig4OLV2.png](/files/c4ULFbLTEe0Fq74qclav)

Branches in each node are created by adding formulas inside parentheses. For instance, the code

```latex
C(-[2]H)(-[6]H)
```

creates two branches in "C", one with a 2 units angle (90°) and other with a 6 units angle (270°).

Branches can also be added to rings:

```latex
Branched ring
\vspace{.5cm}

\chemfig{A*6(-B=C(-CH_3)-D-E-F(=G)=)}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Chemfig+example+5\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0ABranched+ring%0A%5Cvspace%7B.5cm%7D%0A%0A%5Cchemfig%7BA%2A6%28-B%3DC%28-CH_3%29-D-E-F%28%3DG%29%3D%29%7D%0A%5Cend%7Bdocument%7D)

The following image shows the output produced by the example above:

![Chemfig5OLV2.png](/files/gcg6662kw2uJQcR4iANj)

The syntax is similar, using parentheses a branch can be attached to a node (atom). For instance

```latex
F(=G)
```

attaches a branch to the node "F". More complex examples can be created using nested branches and even attaching rings as branches.

### Customizing the formulae

Several parameters such as colors and the node separation can be changed, also additional text to describe the formula can be added.

```latex
{\huge
    \setchemfig{atom sep=2em,bond style={line width=1pt,red,dash pattern=on 2pt off 2pt}}
    \chemname
    {\chemfig{H-C(-[2]H)(-[6]H)-C(=[1]O)-[7]H}}
    {Acetaldehyde}
}
```

[Open this `chemfig` example in Overleaf](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Chemfig+example+6\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Bchemfig%7D%0A%5Cbegin%7Bdocument%7D%0A%7B%5Chuge+%0A++++%5Csetchemfig%7Batom+sep%3D2em%2Cbond+style%3D%7Bline+width%3D1pt%2Cred%2Cdash+pattern%3Don+2pt+off+2pt%7D%7D++%0A++++%5Cchemname%0A++++%7B%5Cchemfig%7BH-C%28-%5B2%5DH%29%28-%5B6%5DH%29-C%28%3D%5B1%5DO%29-%5B7%5DH%7D%7D++++%0A++++%7BAcetaldehyde%7D%0A%7D%0A%5Cend%7Bdocument%7D)

The following image shows the output produced by the example above:

![Drawing Acetaldehyde in LaTeX using the chemfig package](/files/8S8lcmy0nPdUVpu9Swud)

There are two new commands here:

* `\setchemfig{}`: This command is used to configure settings for drawing chemical structures.
* `\chem``name{}{}` : The first parameter in this command is a `chemfig` formula, the second one is some text that will be printed below the formula. In the example, the text is "Acetaldehyde".

Notice also that the font used is `huge`. You can use any other [font size](/latex/fonts/01-font-sizes-families-and-styles.md) and the formula will be scaled accordingly.

### Reference guide (chemfig)

**Bond types**

| Bond type         | code                | output                                    |
| ----------------- | ------------------- | ----------------------------------------- |
| single            | `\chemfig{O - H}`   | ![Bond1.png](/files/jcpP7Cd57gzGJPDef6Aq) |
| double            | `\chemfig{O = H}`   | ![Bond2.png](/files/Rrc1qWiiFnkifBxoYRQs) |
| triple            | `\chemfig{O ~ H}`   | ![Bond3.png](/files/eKRemOme34RI6Mh5U0zA) |
| plain right cram  | `\chemfig{O > H}`   | ![Bond4.png](/files/RdArskRLrFEFzDWgzOVF) |
| plain left cram   | `\chemfig{O < H}`   | ![Bond5.png](/files/NKfm3kJtm6hSe5dGG3H9) |
| dashed right cram | `\chemfig{O >: H}`  | ![Bond6.png](/files/PHDLGGQXYIoLl9tutcre) |
| dashed left cram  | `\chemfig{O <: H}`  | ![Bond7.png](/files/NW0AzBg1gNgcLYwdY8Lp) |
| hollow right cram | `\chemfig{O >\| H}` | ![Bond8.png](/files/UQUtqi2p3osqdmoD9Pds) |
| hollow left cram  | `\chemfig{O <\| H}` | ![Bond9.png](/files/R3dR7nIgp7qe67E2ERqM) |

## Using mhchem to typeset chemical formulae and equations

The `mhchem` package’s versatile `\ce` command, which is [supported by Overleaf’s Visual Editor preview](#visual-editors-preview-of-chemical-formulae-and-equations), enables typesetting of chemical formulae and equations; for example, writing `\ce{H2O}` typesets $$\text{H}\_2\text{O}$$, the chemical formula for water.

* **Note**: Recent versions of the `mhchem` package can [increase the time needed for your project to compile](/latex/knowledge-base/038-fixing-and-preventing-compile-timeouts.md#mhchemtimeout). Switching to the [`chemformula` package](https://ctan.org/pkg/chemformula?lang=en), and using its `\ch` command, can decrease compilation time but the `\ch` command is not currently previewed by Visual Editor.

### How to load the mhchem package

To use the latest version of `mhchem`, currently version 4, add the following line to your document preamble:

```latex
\usepackage[version=4]{mhchem}
```

This loads `mhchem` with its default styles for formatting chemical formulae and equations. To change those defaults you can either use `mhchem` package options or the `\mhchemoptions` command. For example, to change the text mode font to sans serif and draw arrows using PGF/Ti*k*Z, you can load `mhchem` using

```latex
\usepackage[version=4,arrows=pgf-filled,textfontname=sffamily]{mhchem}
```

or you can use the `\mhchemoptions` command within your document

```latex
\mhchemoptions{arrows=pgf-filled,textfontname=sffamily}
```

The [`mhchem` package documentation](http://mirrors.ctan.org/macros/latex/contrib/mhchem/mhchem.pdf) provides further guidance on configuring `mhchem`, together with numerous examples of chemical formulae and equations, a few of which we reproduce here to help you get started. Note the use of space characters within more complex input to the `\ce` command. Those spaces are required to help `mhchem` correctly parse your chemical formulae and equations; omitting them can trigger the error [Unexpected input character](#the-unexpected-input-character-mhchem-error).

### Some examples

The following Overleaf project loads `mhchem` using three package options:

* `arrows=pgf-filled`: draws filled arrows using PGF
* `textfontname=sffamily`: outside of math mode, chemical formulae and equations are typeset using using the default sans serif font
* `mathfontname=mathsf`: in math mode use a sans serif font

The `\ce` command is used to typeset a range of examples.

```latex
\documentclass{article}
%Load mhchem using some package options
\usepackage[version=4,arrows=pgf-filled,
textfontname=sffamily,
mathfontname=mathsf]{mhchem}
\begin{document}
\subsection*{Simple molecules}

\begin{itemize}
\item Water: \verb|\ce{H2O}|, \ce{H2O}
\item Benzene: \verb|\ce{C6H6}|, \ce{C6H6}
\item Hydrogen peroxide: \verb|\ce{H2O2}|, \ce{H2O2}
\item Acetic acid: \verb|\ce{C2H4O2}|, \ce{C2H4O2}
\item Glucose: \verb|\ce{C6H12O6}|, \ce{C6H12O6}
\end{itemize}

\subsection*{Chemical equations}

Two basic examples:

\begin{itemize}
\item \verb|\ce{2H2 + O2 -> 2H2O}| typesets \ce{2H2 + O2 -> 2H2O}
\item \verb|\ce{CO2 + C -> 2 CO}| typesets \ce{CO2 + C -> 2 CO}
\end{itemize}

\subsection*{A more complex example}

Writing \verb|\ce{Hg^2+ ->[I-] HgI2 ->[I-] [Hg^{II}I4]^2-}| typesets this:\vskip10pt
\noindent \ce{Hg^2+ ->[I-] HgI2 ->[I-] [Hg^{II}I4]^2-}.

\subsection*{A math mode example}

Chemical expressions can be typeset using math mode commands such as \verb|\frac|. \vskip10pt

\noindent Writing \verb|\[K=\frac{[\ce{Hg^2+}][\ce{Hg}]}{[\ce{Hg2^2+}]}\]| produces this:

\[K=\frac{[\ce{Hg^2+}][\ce{Hg}]}{[\ce{Hg2^2+}]}\]
\end{document}
```

[Open this `mhchem` example in Overleaf.](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=mhchem+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%25Load+mhchem+using+some+package+options%0A%5Cusepackage%5Bversion%3D4%2Carrows%3Dpgf-filled%2C%0Atextfontname%3Dsffamily%2C%0Amathfontname%3Dmathsf%5D%7Bmhchem%7D%0A%5Cbegin%7Bdocument%7D%0A%5Csubsection%2A%7BSimple+molecules%7D%0A%0A%5Cbegin%7Bitemize%7D%0A%5Citem+Water%3A+%5Cverb%7C%5Cce%7BH2O%7D%7C%2C+%5Cce%7BH2O%7D%0A%5Citem+Benzene%3A+%5Cverb%7C%5Cce%7BC6H6%7D%7C%2C+%5Cce%7BC6H6%7D%0A%5Citem+Hydrogen+peroxide%3A+%5Cverb%7C%5Cce%7BH2O2%7D%7C%2C+%5Cce%7BH2O2%7D%0A%5Citem+Acetic+acid%3A+%5Cverb%7C%5Cce%7BC2H4O2%7D%7C%2C+%5Cce%7BC2H4O2%7D%0A%5Citem+Glucose%3A+%5Cverb%7C%5Cce%7BC6H12O6%7D%7C%2C+%5Cce%7BC6H12O6%7D%0A%5Cend%7Bitemize%7D%0A%0A%5Csubsection%2A%7BChemical+equations%7D%0A%0ATwo+basic+examples%3A%0A%0A%5Cbegin%7Bitemize%7D%0A%5Citem+%5Cverb%7C%5Cce%7B2H2+%2B+O2+-%3E+2H2O%7D%7C+typesets+%5Cce%7B2H2+%2B+O2+-%3E+2H2O%7D%0A%5Citem+%5Cverb%7C%5Cce%7BCO2+%2B+C+-%3E+2+CO%7D%7C+typesets+%5Cce%7BCO2+%2B+C+-%3E+2+CO%7D%0A%5Cend%7Bitemize%7D%0A%0A%5Csubsection%2A%7BA+more+complex+example%7D%0A%0AWriting+%5Cverb%7C%5Cce%7BHg%5E2%2B+-%3E%5BI-%5D+HgI2+-%3E%5BI-%5D+%5BHg%5E%7BII%7DI4%5D%5E2-%7D%7C+typesets+this%3A%5Cvskip10pt%0A%5Cnoindent+%5Cce%7BHg%5E2%2B+-%3E%5BI-%5D+HgI2+-%3E%5BI-%5D+%5BHg%5E%7BII%7DI4%5D%5E2-%7D.%0A%0A%5Csubsection%2A%7BA+math+mode+example%7D%0A%0AChemical+expressions+can+be+typeset+using+math+mode+commands+such+as+%5Cverb%7C%5Cfrac%7C.+%5Cvskip10pt%0A%0A%5Cnoindent+Writing+%5Cverb%7C%5C%5BK%3D%5Cfrac%7B%5B%5Cce%7BHg%5E2%2B%7D%5D%5B%5Cce%7BHg%7D%5D%7D%7B%5B%5Cce%7BHg2%5E2%2B%7D%5D%7D%5C%5D%7C+produces+this%3A%0A%0A%5C%5BK%3D%5Cfrac%7B%5B%5Cce%7BHg%5E2%2B%7D%5D%5B%5Cce%7BHg%7D%5D%7D%7B%5B%5Cce%7BHg2%5E2%2B%7D%5D%7D%5C%5D%0A%5Cend%7Bdocument%7D)

This project produces the following output:

![Graphic showing mhchem examples](/files/DH2rkO02cxEDOO4mJEJV)

The [`mhchem` package documentation](http://mirrors.ctan.org/macros/latex/contrib/mhchem/mhchem.pdf) is well worth reading because it contains numerous examples of chemical formulae and equations in addition to information on package options and configuration.

### Visual Editor’s preview of chemical formulae and equations

Overleaf’s Visual Editor provides a preview of chemical formulae and equations typeset by the `\ce` command, as demonstrated in the following video clip:

{% embed url="<https://videos.ctfassets.net/nrgyaltdicpt/38RMpDdTIkwBhVo4Jh2s28/aac834f5d7f2676133f884e1c6b3d0cb/VisualEditorchem.mp4>" %}

### The “Unexpected input character” mhchem error

The `mhchem` package error **`Assertion failed: Unexpected input character`** often results from missing spaces in the `\ce` command input—spaces are essential for `mhchem` to accurately parse the more complex chemical expressions. This error can arise when copying and pasting examples from PDF documents, where spaces may not be accurately replicated.

The following example demonstrates this error:

```latex
\ce{CO2+C->2CO}
```

[Open this **error-generating** `mhchem` example in Overleaf.](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=mhchem+errors+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bversion%3D4%5D%7Bmhchem%7D+%0A%5Cbegin%7Bdocument%7D%0A%5Cce%7BCO2%2BC-%3E2CO%7D%0A%5Cend%7Bdocument%7D)

As a minimum, we need to put a space between the `C` and the `->` ; however, that approach might still not be sufficient to typeset our desired expression. With all spaces added correctly, it looks like this:

```latex
\ce{CO2 + C -> 2 CO}
```

[Open this corrected `mhchem` example in Overleaf.](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=mhchem+corrected+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bversion%3D4%5D%7Bmhchem%7D+%0A%5Cbegin%7Bdocument%7D%0A%5Cce%7BCO2+%2B+C+-%3E+2+CO%7D%0A%5Cend%7Bdocument%7D)

This project produces the following output:

![](/files/gW7zP98tpoCH1gE2QO4o)

## Further reading

For more information see

* [Molecular orbital diagrams](/latex/field-specific/04-molecular-orbital-diagrams.md)
* [Feynman diagrams](/latex/field-specific/03-feynman-diagrams.md)
* [TikZ package](/latex/figures-and-tables/05-tikz-package.md)
* [Inserting Images](/latex/more-topics/27-inserting-images.md)
* [List of Greek letters and math symbols](/latex/mathematics/11-list-of-greek-letters-and-math-symbols.md)
* [The **chemfig** package documentation](http://www.ctan.org/pkg/chemfig)
* [The **tikz/pgf** package documentation](http://www.ctan.org/pkg/pgf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/field-specific/02-chemistry-formulae.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
