val_latex 0.1.1
val_latex: ^0.1.1 copied to clipboard
LaTeX math typesetting in pure Dart: a TeX parser, macros, TeX layout with line breaking and right-to-left math, OpenType math fonts, and speech output.
example/example.dart
// Parses LaTeX math, lays it out, and reads the result.
//
// dart run example/example.dart
import 'package:val_latex/val_latex.dart';
void main() {
// Parse: never throws; problems become diagnostics.
final result = parseLatex(r'x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}');
print('Diagnostics: ${result.diagnostics.length}');
// Lay out with TeX's rules and the bundled Latin Modern Math font.
// Sizes are in em: multiply by the font size for pixels.
final layout = layoutFormula(result);
print(
'Size: ${layout.width.toStringAsFixed(2)} × '
'${(layout.height + layout.depth).toStringAsFixed(2)} em',
);
print('Display items to draw: ${layout.items.length}');
// Break a long formula to a width, in display style.
final wrapped = renderLatex(
r'\sum_{k=1}^{n} k^2 = \frac{n(n+1)(2n+1)}{6} = 1 + 4 + 9 + \cdots + n^2',
layoutOptions: const LayoutOptions(displayMode: true, maxWidth: 10),
);
print('Lines at 10 em: ${wrapped.lineCount}');
// Unfinished input, as an LLM streams it, renders as far as it goes.
final partial = parseLatex(r'\frac{a}{');
print('Incomplete: ${partial.incomplete}');
// Spoken form, for screen readers.
print('Speech: ${toSpeech(result)}');
// Normalised LaTeX back.
print('LaTeX: ${toLatex(result)}');
}