@@ -89,27 +89,27 @@ def format_units_unicode(udict):
8989def format_units_latex (udict ,font = 'mathrm' ,mult = r'\cdot' ,paren = False ):
9090 '''
9191 Replace the units string provided with an equivalent latex string.
92-
92+
9393 Division (a/b) will be replaced by \f rac{a}{b}.
94-
94+
9595 Exponentiation (m**2) will be replaced with superscripts (m^{2})
96-
97- The latex is set with the font argument, and the default is the normal,
98- non-italicized font mathrm. Other useful options include 'mathnormal',
96+
97+ The latex is set with the font argument, and the default is the normal,
98+ non-italicized font mathrm. Other useful options include 'mathnormal',
9999 'mathit', 'mathsf', and 'mathtt'.
100-
100+
101101 Multiplication (*) are replaced with the symbol specified by the mult argument.
102102 By default this is the latex \cdot symbol. Other useful
103103 options may be '' or '*'.
104-
104+
105105 If paren=True, encapsulate the string in '\left(' and '\r ight)'
106-
106+
107107 The result of format_units_latex is encapsulated in $. This allows the result
108108 to be used directly in Latex in normal text mode, or in Matplotlib text via the
109109 MathText feature.
110-
110+
111111 Restrictions:
112- This routine will not put CompoundUnits into a fractional form.
112+ This routine will not put CompoundUnits into a fractional form.
113113 '''
114114 res = format_units (udict )
115115 if res .startswith ('(' ) and res .endswith (')' ):
@@ -128,3 +128,36 @@ def format_units_latex(udict,font='mathrm',mult=r'\cdot',paren=False):
128128 res = r'\left(%s\right)' % res
129129 res = r'$\%s{%s}$' % (font ,res )
130130 return res
131+
132+
133+ def format_units_html (udict ,font = '%s' ,mult = r'⋅' ,paren = False ):
134+ '''
135+ Replace the units string provided with an equivalent html string.
136+
137+ Exponentiation (m**2) will be replaced with superscripts (m<sup>2</sup>})
138+
139+ No formating is done, change `font` argument to e.g.:
140+ '<span style="color: #0000a0">%s</span>' to have text be colored blue.
141+
142+ Multiplication (*) are replaced with the symbol specified by the mult
143+ argument. By default this is the latex ⋅ symbol. Other useful options
144+ may be '' or '*'.
145+
146+ If paren=True, encapsulate the string in '(' and ')'
147+
148+ '''
149+ res = format_units (udict )
150+ if res .startswith ('(' ) and res .endswith (')' ):
151+ # Compound Unit
152+ compound = True
153+ else :
154+ # Not a compound unit
155+ compound = False
156+ # Replace exponentiation (**exp) with ^{exp}
157+ res = re .sub (r'\*{2,2}(?P<exp>\d+)' ,r'<sup>\g<exp></sup>' ,res )
158+ # Remove multiplication signs
159+ res = re .sub (r'\*' ,mult ,res )
160+ if paren and not compound :
161+ res = '(%s)' % res
162+ res = font % res
163+ return res
0 commit comments