iTranslated by AI
How to Instantly Generate LaTeX Code for Chemical Structures
How to Instantly Generate TeX Code for Chemical Structures
Introduction
LaTeX (hereinafter TeX) is a document creation system preferred by students and researchers in physics and mathematics, but once you get used to it, it is also a far more powerful tool for chemistry and biology than Word.
However, when you try to write chemical structures or reaction mechanisms in a report, you hit a major wall:
- "There are no clean images of the target structural formula online."
- "I don't have a license for paid software like ChemDraw."
While you can draw beautiful structures with code using the LaTeX chemfig package, it is difficult to write complex structures from scratch. That is why today I will introduce a tool called mol2chemfig. Using this, you can perform the magical time-saving feat of "searching for a molecule by ID from a web database and instantly converting it into TeX code."
I will explain how to dramatically streamline the creation of physical chemistry and organic chemistry reports.
What You Will Learn in This Article
- How to draw beautiful chemical structures with a few lines of code.
- Techniques for converting existing structural formulas into TeX code in one go.
Recommended Environment
In this article, I recommend using VS Code (Visual Studio Code) as your editor.
Since mol2chemfig is a tool that uses Python to convert files and requires running commands on your computer, VS Code allows you to execute the conversion command (mol2chemfig ...) directly below the editor window, making your work more efficient.
Steps to Set Up the Environment
If you do not have an environment set up yet, please prepare it using the following steps:
- Install TeX Live (The TeX core)
- Install VS Code (The editor)
- Install Python (To run the conversion tool)
- Install the VS Code extension "LaTeX Workshop"
- Edit the configuration file (settings.json)
For specific installation methods, the following articles are helpful:
LaTeX Environment Setup (VSCode + LuaLaTeX)
LaTeX Environment Setup in VSCode
TeX File Configuration (Preamble)
First, we configure the beginning (preamble) of the TeX file. I use article because it is more stable for reference settings (like BibLaTeX). Also, while I am using Lualatex, other engines will work fine as well.
\documentclass[a4paper]{article}
% --- Basic Packages ---
\usepackage{luatexja} % Japanese support
\usepackage{chemfig} % Main package for drawing chemical structures
\usepackage{mol2chemfig} % Necessary to run code converted by mol2chemfig
1 Basic Writing Style for chemfig
From here, I will briefly explain how to actually write code in chemfig to draw chemical structures. If you learn the following basic rules, you can quickly draw simple molecules.
1.1 How to Write Linear Compounds
The basics are "bond types," "angles," and "branching."
1.1.1 Bonds and Angles
- Single bonds are represented by
-, double bonds by=, and triple bonds by~. - Angles are specified using
[:angle]. The angle increases counterclockwise from the horizontal direction on the page. Using an integer[n]specifies an angle of (45×n) degrees.[2]extends the bond in the 90-degree direction (straight up), and[-2]extends it in the -90-degree direction (straight down). - You can also omit the bonding atoms.
Example
\chemfig{C-[:30]C=[:-30]C-[:30]C} % With carbon atoms
\qquad % Space
\chemfig{-[:30]=[:-30]-[:30]} % Skeleton only
Output Result:

1.1.2 Branching Structures
- Branching structures can be displayed by enclosing the desired substituent in parentheses immediately after the atom in the main chain where you want to attach it. This structure can also be used in a nested manner.
- In
C - C - C, where(-[2]A(-B)-[2]D)is added to the middle C atom, it creates an upward skeletonA-[2]Dafter making the main chain, then attaches the substituent(-B)toA.
As an example, let's write acetone. As an aside, since you can specify the bond length multiplier after the angle, like[angle, bond length multiplier], you can make it look more realistic by shortening the C=O bond length.
Example:
\chemfig{CH_3 - CH (-[2] A (-B) -[2] D) - CH_3}
\qquad
\chemfig{-[:30](=[2,0.8]O)-[:-30]} % Shortening C=O bond length to 0.8x standard
Output Result:

1.2 How to Write Cyclic Compounds
Cyclic compounds can be drawn by specifying the number of vertices of a regular polygon and the type of bonds. The atom before the * is placed at the bottom-left and drawn counterclockwise. The way to attach substituents is the same as in linear compounds. Naturally, skeleton display is also possible.
Example:
\chemfig{A*6(-B=C-D(-[:30]OH)=E-F=)} % Counterclockwise from A
\qquad
\chemfig{HN*5(-=-N=-)} % Counterclockwise from N of NH
Output Result:

1.3 Other Commands
This section is for those who are interested or want to know about more detailed expressions. You can skip this part if you like.
1.3.1 Wedge Notation
> and < represent bonds protruding from the page, while >: and <: represent bonds on the back side of the page.
Example:
\chemfig{A -[:30]C(<[:-60]E)( <:[:-15]B)-[2]D}
\qquad
\chemfig{*6(--(<:[:-30,0.7])-( <[:30]OH)---)}
Output Result:

1.3.2 Charges and Lone Pairs
The methods for displaying atomic charges or lone pairs on oxygen or nitrogen atoms are as follows. Detailed option descriptions are omitted, but you can write + marks or lone pairs using \charge{angle = \symbol}{atom}. Regarding lone pairs, imagine rotating the : around the atom. Making + or - into \scriptstyle results in a smaller, more aesthetically pleasing size.
Example
\chemfig{CH_3 - \charge{90=\:}{O}H} % Rotate : by 90 degrees
\qquad
\chemfig{H-\charge{45=$\scriptstyle+$}{O}(-[2]H)-H}
Output Result:

2 mol2chemfig
As you can see, creating complex molecules is very difficult, and even with AI, you ultimately have to make manual adjustments for a clean output. Therefore, I will introduce the installation of mol2chemfig, an external Python tool that can generate code for any complex molecule in an instant.
2.1 How to Install mol2chemfig
The official mol2chemfig is no longer maintained (it was for Python 2) and will not run in the current environment (Python 3).
Therefore, I will install an unofficial version modified to support Python 3 directly from GitHub.
2.1.1 Installation Command
Enter and execute the following command in the VS Code terminal in a single line.
(Uses the git command)
For Mac:
pip3 install git+https://github.com/Augus1999/mol2chemfigPy3.git
For Windows:
First, Git must be installed.
(If an error occurs when you type git --version in the command prompt, please install Git for Windows)
Once ready, execute the following command:
pip install git+https://github.com/Augus1999/mol2chemfigPy3.git
⚠️ What to do if errors occur during installation? (Troubleshooting)
Q1. "pip: command not found" or "pip is not recognized as an internal command..." appears.
A. Python is not installed correctly, or its PATH is not set.
Restart the Python installer and make sure to check the "Add Python to PATH" (or Add Python 3.x to PATH) checkbox on the first installation screen before reinstalling.
Without this, VS Code cannot find Python.
Q2. "git: command not found" appears.
A. Git is not installed.
This installation method uses the git command.
- Windows: Download and install Git for Windows.
-
Mac: Typing
gitin the terminal may automatically prompt you to install it. Please follow the instructions.
Q3. "error: externally-managed-environment" appears (Mac).
A. This is a Mac security restriction.
Add --break-system-packages to the end of the command and execute it again. Since mol2chemfig is unlikely to interfere with other Python-based apps, please proceed by ignoring this restriction.
pip3 install git+https://github.com/Augus1999/mol2chemfigPy3.git --break-system-packages
Verification of Installation
mol2chemfig --version
If this displays mol2chemfig version 1.6.0, the installation was successful.
2.2 Preparation on the LaTeX Side (Only Once)
mol2chemfig output code sometimes contains specialized commands. To prevent errors, register the configuration file (mol2chemfig.sty) to your TeX system. If you cannot perform this operation, use it without adding \usepackage{mol2chemfig} in the preamble.
By doing this, you will be able to use \usepackage{mol2chemfig} regardless of which folder you are writing your report in.
Since placing it in the same location as every .tex file is troublesome, I will install it in the common TeX library folder so that it is "set once and usable for reports in any folder."
2.2.2 For Mac / Linux
Copy and execute the following command in the terminal.
It automatically downloads the file from the official archive (CTAN) and places it where the system can recognize it. This allows you to use mol2chemfig in any directory just like an official package.
mkdir -p ~/Library/texmf/tex/latex/mol2chemfig
Download and save the file from the official site
curl -L -o ~/Library/texmf/tex/latex/mol2chemfig/mol2chemfig.sty http://mirrors.ctan.org/graphics/mol2chemfig/latex/mol2chemfig.sty
2.2.3 For Windows
Since it is complicated via command, create folders via Explorer.
Open C:\Users\(Your User Name).
Create a new folder named texmf (if it already exists, leave it as is).
Inside it, create folders sequentially: tex → latex → mol2chemfig.
Save the mol2chemfig.sty downloaded from CTAN inside the final folder.
2.3 Usage
2.3.1 Preamble
Just add \usepackage{mol2chemfig} in the same way as an official package.
2.3.2 Searching for PubChem ID
As an example, let's search for ethanol in the PubChem database.

The CID (Compound ID) is found to be 702.
2.3.3 Conversion to chemfig Code
- Open the
.texfile where you want to display the compound in VS Code. - Open the terminal at the bottom of the screen.
Type the command in the terminal as follows. It means the following:
mol2chemfig -w -y delete -i pubchem 702
-
-w: Fetch information from the web -
-y delete: Remove hydrogen from hydrocarbons -
-i pubchem 702: Structure of the compound with CID 702
Then, code like\chemfig{...}will be displayed in the terminal.
2.3.4 Compilation
Copy and paste this into your TeX file and compile it to display the chemical structure of ethanol.
If you run the command in the terminal without -y delete, a structure displaying all hydrogen atoms bonded to carbon will be displayed.
The left shows the carbon skeleton, and the right shows the structure with all hydrogens displayed.

With this, you can easily write any compound listed in the database. If you don't like the bond length or angle, you can adjust it using the methods shown above.
2.3.5 Adjustments
Substituted benzenes take up space, so it may be better to rotate them to an appropriate orientation. In such cases, you can rotate them by -a angle when converting in the terminal. Taking phenol as an example:
mol2chemfig -w -y delete -i pubchem 996
mol2chemfig -a -90 -w -y delete -i pubchem 996 % -90 degree rotation
The left is the original, and the right is the code compiled after a -90 degree rotation.

Conclusion
Once you install mol2chemfig, you can display chemical structures without stress. Regardless of your field, please give it a try. Thank you for reading to the end!
References
I would like to express my gratitude to the following articles for being very helpful during writing.
Discussion