# Use Custom LaTeX Macros to Boost Your Writing Productivity

URL: https://www.cesarsotovalero.net/blog/use-custom-latex-macros-to-boost-your-writing-productivity.html
Date: 2021-05-28
Author: César Soto Valero
Tags: latex
Summary: In this blog post, I describe how I use LaTeX macros to boost my writing productivity by automating repetitive tasks such as formatting and number computations. I explain how to create custom commands for common tasks like abbreviations, author notes, formatting and computing numbers, percentages, and ratios, as well as embedding small bar charts within documents. This post also demonstrates how to execute Python scripts within LaTeX documents, offering a powerful way to dynamically update content and automate parts of the writing process.

If you ever use [LaTeX](https://en.wikipedia.org/wiki/LaTeX) to write your research papers or technical reports, then you should know how useful and powerful this tool is.
Let me just mention three well-known benefits of using LaTeX: 1) beautiful typeset output (especially when dealing with mathematical notations); 2) consistent handling of references and bibliography (thanks to [BibTeX](http://www.bibtex.org/); 3) separation of content and style, meaning that all you need to write is plain text (also true for tables and figures, thanks to [TikZ](https://en.wikipedia.org/wiki/PGF/TikZ)).
LaTeX has a powerful markup language for document creation.
One of the best and often misleading advantages of using this language is that it allows the creation of [custom macros](https://en.wikibooks.org/wiki/LaTeX/Macros).
These are user-defined commands that allows avoiding typing repetitive LaTeX commands (e.g., formatting strings or numbers) and even perform live computations (e.g., calculating numeric expression).
Let me show you how it works!

![A slow snail crawling at Djurgården in Stockholm (he doesn't use LaTeX macros)](https://www.cesarsotovalero.net/img/posts/2021/snail.jpg)

_© A slow snail crawling at Djurgården in Stockholm (he doesn't use LaTeX macros, obviously)_

# Creating a Simple User Custom Command

To add a custom command in your document, use `\newcommand{\name}[num]{definition}`.
The following commands are examples that allow simplifying the use of some common English abbreviations:

```latex
% Load required package

\usepackage{xspace}

% Create custom user defined commands

\newcommand{\ie}{i.e.\@\xspace}
\newcommand{\aka}{a.k.a.\@\xspace}
\newcommand{\eg}{e.g.\@\xspace}
\newcommand{\etal}{et al.\@\xspace}
\newcommand{\wrt}{w.r.t.\@\xspace}
```

Once added in your document, you just need to type `\ie` and the text `i.e.` will be printed in your document.
Note that you need to use `\@\xspace` to indicate that a white space follows the displayed text.

# Inserting Author Notes

I often find very useful defining the `\cesar` and `\todo` commands in all my documents to create quick author notes and remarks in my documents.  The following code defines these commands, which are very useful when inserting notes (e.g., `\cesar{refine this sentence}`):

```latex
% Load required packages

\usepackage{xspace}
\usepackage{ifthen}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{amsmath,amssymb}
\usepackage[inline]{enumitem}

% Code for creating comments

\newboolean{showcomments}
\setboolean{showcomments}{true}
\ifthenelse{\boolean{showcomments}}
{\newcommand{\mynote}[2]{
  \fbox{\bfseries\sffamily\scriptsize#1}
  {\small
  $\blacktriangleright$
  \textsf{\textcolor{red}{{\em #2}\bf}}
  $\blacktriangleleft$}}
}

% Create custom user defined command for author notes

\newcommand{
  \cesar}[1]{\mynote{Cesar}{#1}
}

% Create custom user defined command for `TODO` notes

\newcommand*\badge[1]{
  \colorbox{red}{\color{white}#1}
}
\newcommand{\todo}[1]{
  \noindent\textbf{\badge{TODO}} {\color{red}#1}
  \GenericWarning{}{LaTeX Warning: TODO: #1}
}
```

For example, the `\cesar{An author note}` produces ![Comand](https://www.cesarsotovalero.net/img/posts/2021/authornote.png), whereas `\todo{A todo note}` produces ![Comand](https://www.cesarsotovalero.net/img/posts/2021/todonote.png).

# Formatting Numbers

You can use the `numprint` and `fp` packages to create your own commands to format numeric values.
The following example creates a `\np` command to print numeric values in math mode, nicely formatted, and rounded by two decimal digits.

```latex
% Load required packages

\usepackage{xspace}
\usepackage{fp}
\usepackage[autolanguage]{numprint}

% Create custom user defined command for author notes

\newcommand*\np[2][z]{
  %\textcolor{red}{
  \ifx z#1
    \nprounddigits{2}$\numprint{#2}$
  \else
    \nprounddigits{2}$\numprint[#1]{#2}$
  \fi\xspace
}
```

Now, for example, you can use `\np{22.324}` to print `22.32`, or `\np{22.324}{\%}` to print `22.32%`.

# Computing Numbers

You can create numeric variables using `\def`.
This is very handy since you can keep all the values in your document in the same place.
Furthermore, you can use `\FPeval` to compute values based on these variables.
With `\FPeval`, your document will lively update every time you update some value.
The following is a basic example:

```latex
\def\nbX{42}
\def\nbY{42}
\FPeval{nbSum}{round(\nbX + \nbY, 0)}
```

In this example, using `\nbSum` prints the value `84` in the document.

# Handling Percentages

If you use percentages in your document, you can calculate a percentage directly based on two variables: a number and the total. The following `\ShowPercentage` command calculates rates based on two variables.

```latex
% Load required packages

\usepackage{xspace}
\usepackage{fp}
\usepackage[autolanguage]{numprint}

% Create custom user defined command for author notes

\newcommand{\ShowPercentage}[2]{
  \FPeval\percentage{round(#1/#2*100,0)}
  \FPeval\percentageOneDecimal{round(#1/#2*100,2)}
  \ifnum \percentage=0
    {\np[\%]{0}}
  \else
    \ifnum \percentage<1
      {$<$\np[\%]{0.1}}
    \else
      {\np[\%]{\FPprint{percentageOneDecimal}}}
    \fi
  \fi
  \xspace
}
```

For example, `\ShowPercentage{1221}{20023}` prints `6.10%`.
Note that a percentage rounded to 0 will be presented as `<1%`

# Handling Ratios

Sometimes percentages are hard to read (e.g., when the numerator and denominator are large numbers).
In such cases, you can present ratios instead.
For example, to say that `4` is two times larger that `2`.
The following `\Ratio` command calculates based based on two variables.

```latex
% Create custom user defined command for printing ratios

\newcommand{\Ratio}[2]{
  \FPeval\percentage{round(#2/#1,1)}
  \FPeval\percentageOneDecimal{round(#2/#1,1)}
  \np[\times]{\FPprint{percentageOneDecimal}}
  \xspace
}
```

For the previous example, it prints: `2x`.

# Embedding Small Barcharts

A nice way to compare percentages in a graphical manner (especially in tables), is by embedding small barchart plots within them. The following `\ChartSmall` commands does the trick for you:

```latex
% Load required packages

\usepackage{xspace}
\usepackage{fp}
\usepackage[autolanguage]{numprint}
\usepackage{xcolor}

% Create custom user defined command for author notes

\newlength\BARSIZE \setlength\BARSIZE{0.5cm}
\newcommand{\inlinechart}[2]{
  \FPeval{\BLACKBARSIZE}{#1/#2}\textcolor{black!80}{\rule{\BLACKBARSIZE\BARSIZE}{1.6ex}}
  \FPeval{\BLACKBARSIZE}{1 - (#1/#2)}\textcolor{black!10}{\rule{\BLACKBARSIZE\BARSIZE}{1.6ex}}
}
\newcommand*\ChartSmall[3][v]{
  \ifx q#1
    \np{#2}/\np{#3}(\ShowPercentage{#2}{#3})
  \else
    \ifx p#1
      \np{#2}(\ShowPercentage{#2}{#3})\else
    \ifx c#1
      \inlinechart{#2}{#3}
    \else
      \np{#2}
    \ifx r#1
      /\np{#3}
  \fi
  \hspace*{0.5ex}(\ShowPercentage{#2}{#3})
  \inlinechart{#2}{#3}
  \xspace
\fi\fi\fi
}
```

Note that you can use this command in three different flavors:
- `\ChartSmall[x]{80}{155}` produces ![Comand](https://www.cesarsotovalero.net/img/posts/2021/smallshart1.png)
- `\ChartSmall[q]{80}{155}` produces ![Comand](https://www.cesarsotovalero.net/img/posts/2021/smallshart2.png)
- `\ChartSmall[p]{80}{155}` produces ![Comand](https://www.cesarsotovalero.net/img/posts/2021/smallshart3.png)

# Executing Python Scripts in a LaTeX Document

You can leverage the computational capabilities of the Python programming language to compute values or automatize the creation of a LaTeX document.
Here is an example, credited to [this answer](https://tex.stackexchange.com/questions/598403/can-i-execute-python-code-inside-latex) on StackExchange.

```latex
\documentclass{article}
\begin{filecontents*}{zz.py}
print("one")
print("two")
\end{filecontents*}

\usepackage{color}
\begin{document}

\input{|python mypy.py}

\hrule

\input{|python zz.py}
\end{document}
```

Here is file `mypy.py` called within the LaTeX document:

```python
print("\\section{The First}\n")
print("Some colours:\n\n")
clr=['red','blue','green']
for c in clr:
  print("\n\\textcolor{" + c + "}{" + c +"}\n")
```

The output is as following:

# IMAGE

![Python code executed in a LaTeX document](https://www.cesarsotovalero.net/img/posts/2021/python_executed_in_latex_document.png)

_The figure shows a working example of Python code embedded in a LaTeX file in Overleaf._

# Conclusion

LaTeX is not only an awesome tool to create beautiful documents.
It also provides packages to format and compute numeric values as variables.
I've used all the custom commands presented in this post to ease the writing process of [my research papers](https://www.cesarsotovalero.net/publications).
Since then, dealing with numeric values and percentages has never been easier.
