Skip to content

Instantly share code, notes, and snippets.

@ClementGre
Last active April 5, 2024 22:21
Show Gist options
  • Save ClementGre/38be531cc7fbfc8a6d1398f739d0198b to your computer and use it in GitHub Desktop.
Save ClementGre/38be531cc7fbfc8a6d1398f739d0198b to your computer and use it in GitHub Desktop.
A Latex command that converts any non formatted unit, e.g. Kg.m2.s-1 into a beautifully formatted Latex $\textrm{Kg}\cdot\textrm{m}^2\cdot\textrm{s}^{-2}}$.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Units Latexizer by Clément Grennerat %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Actions:
% "deg" is replaced by °C
% Letters [A-Za-z] are put into textrm{}
% Numbers and minus are superscripted
% Dots are replaced by \cdot
\ExplSyntaxOn
\NewDocumentCommand{\formatUnit}{m}
{
\tl_set:Nn \l_tmpa_tl { #1 }
\regex_replace_all:nnN { (deg) } { ^\c{circ} C } \l_tmpa_tl
\regex_replace_all:nnN { ([A-Za-z]+) } { \c{textrm}\cB\{ \1 \cE\} } \l_tmpa_tl
\regex_replace_all:nnN { ([0-9-]+) } { ^{\1} } \l_tmpa_tl
\regex_replace_all:nnN { (\.) } { \c{cdot} } \l_tmpa_tl
\tl_use:N \l_tmpa_tl
}
\ExplSyntaxOff
% Command for auto-completion and text mode support
\renewcommand{\u}[1]{
\ifmmode \ \formatUnit{#1} \else $\formatUnit{#1}$ \fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment