puToTex function

String puToTex(
  1. String input
)

Converts the argument of \pu (a physical quantity) to TeX: 123 kJ/mol → 123\,\mathrm{kJ}/\mathrm{mol}, 1.2e3 m/s → 1.2\cdot 10^{3}\,\mathrm{m}/\mathrm{s}.

As mhchem documents: e and *10^ give a centred dot, E, x10^ and ×10^ a cross; digits right after a unit are its power (mol-1, m2); // sets the units as a fraction (kJ//mol).

Implementation

String puToTex(String input) {
  final m = RegExp(
    r'^\s*([-+−]?\d+(?:[.,]\d+)?(?:\(\d+\))?)(?:\s*(e|E|\*\s*10\^|[x×]\s*10\^)\s*([-+−]?\d+))?',
  ).firstMatch(input);
  if (m == null) return _unitsOrFraction(input.trim());
  final b = StringBuffer(m[1]!.replaceAll(',', '{,}'));
  if (m[3] != null) {
    final dot = m[2] == 'e' || m[2]!.startsWith('*');
    b.write('${dot ? r'\cdot' : r'\times'} 10^{${m[3]}}');
  }
  final rest = input.substring(m.end).trim();
  if (rest.isNotEmpty) b.write('\\,${_unitsOrFraction(rest)}');
  return b.toString();
}