API
This section describes the low-level API of the parser and the generator. You will only need it if you implement your own macros, or if you want to access parts of the result and keep processing them.
The latex.js package exports:
parse()andSyntaxError: the parserHtmlGenerator, the HTML generator, and its abstract base classGeneratorLaTeXJSComponentanddefineLaTeXJSComponent(): the web component- the TypeScript types
HtmlOptions(the options ofHtmlGenerator) andHyphenator(a function that inserts soft hyphens into a text) resetSvgIds(): resets the counter for the ids of the SVG elements that thepictureenvironment creates, so that translating the same document again gives the same ids (useful in tests)
Parser
parse(latex, options)
This function parses the given input LaTeX document and returns a generator that creates the output document.
Arguments:
latex<string>: the LaTeX source documentoptions<Object>:generator: an instance ofHtmlGeneratorgrammarSource(optional): a name for the source, e.g. its file name; errors report it inlocation.source
Returns the HtmlGenerator instance.
class: SyntaxError
parse() throws a SyntaxError (a subclass of the built-in SyntaxError) if the document cannot be translated: for actual syntax errors as well as for errors that macros report, like unknown macros or environments, or a missing argument. Its properties:
message<string>: e.g.unknown macro: \foolocation<Object>: where the error happened:startandend, each withline,column(both 1-based) andoffset(0-based), andsource, thegrammarSourcegiven toparse()expectedandfound: what the parser expected and what it found instead;nullif a macro reported the error
error.format([{ source, text }]) returns a message that shows the line of the error; source has to match the grammarSource, text is the LaTeX source:
Error: unknown macro: \foo
--> doc.tex:2:25
|
2 | \begin{itemize}\item a \foo\end{itemize}
| ^^^class: HtmlGenerator
CTOR: new HtmlGenerator(options)
Create a new HTML generator. options is an optional <Object> that can have the following properties:
documentClass<string>: the document class to use for a document without preamble (default:"article")CustomMacros<constructor>: a class with additional macros, see Custom Macroshyphenate<boolean|function>:true(default) hyphenates using the bundled English patterns,falsedisables hyphenation. For other languages, pass a function that inserts soft hyphens, e.g.hyphenateSyncfrom the hyphen package:import { hyphenateSync } from 'hyphen/de'styles<Array<string>>: URLs of additional CSS stylesheets; relative URLs are resolved like the ones of the LaTeX.js stylesheets (seestylesAndScripts())precision<number>: the number of decimal places of lengths in the output (default:3)
htmlGenerator.reset()
Reset the generator. Needs to be called before the generator is used for creating a second document: parsing another document without a reset fails, e.g. with the error "Two \documentclass commands...".
htmlGenerator.htmlDocument(baseURL)
Returns the full DOM HTMLDocument representation of the LaTeX source, including <head> and <body>. This is meant to be used as its own standalone webpage or in an <iframe>.
baseURL will be used as base for the scripts and stylesheets; if omitted, the base will be window.location.href or, if not available, scripts and stylesheets will have relative URLs.
To serialize it, use '<!DOCTYPE html>' + htmlGenerator.htmlDocument().documentElement.outerHTML. outerHTML doesn't include the doctype, but without it, browsers render the page in quirks mode, with wrong font sizes: class names ignore the case then, so \large, \Large, and \LARGE would all have the same size.
htmlGenerator.stylesAndScripts(baseURL)
Returns a DocumentFragment with the <link> and <script> elements the document needs: the KaTeX stylesheet, the stylesheets of the document class and the packages, the styles from the options, and js/base.js. This usually is part of the <head> element.
If baseURL is given, the files will be referenced with absolute URLs, otherwise with relative URLs.
htmlGenerator.domFragment()
Returns the DOM DocumentFragment of the document: the text body (<div class="body">) and the margin notes, if there are any. This does not include the scripts and stylesheets and is meant for testing and low-level embedding.
htmlGenerator.applyLengthsAndGeometryToDom(element)
Sets the font size and the page geometry (text width and margins) of the document as CSS variables in the style of element. htmlDocument() does this for its <html> element, and the web component for itself. When you use domFragment(), call it for an element that contains the fragment, e.g. document.documentElement.
htmlGenerator.documentTitle
The title of the document as plain text, as set by \maketitle, or "untitled" if there was no \maketitle. htmlDocument() uses it as <title>.
class: Generator
Generator is the abstract base class of HtmlGenerator. It holds the state of the document (groups, fonts, counters, lengths, labels, ...), and it is the API that macros use to create output and to change that state: a class with macros gets the generator in its constructor, see Custom Macros. These are its most important methods:
Creating output
create(kind, children, classes): an element of the given kind, with the given children (a node or an array of nodes) and CSS classes (a string). The kinds are"inline"and"block"(in HTML:<span>and<div>),"par","linebreak", the sectioning kinds"part"to"subparagraph", kinds for lists, title and abstract, and"verb"and"verbatim"; seeElementsinsrc/generator/elements.ts.createText(text): a text node with the current font attributes, hyphenatedcreateVerbatim(text): verbatim text like\verb: an element in typewriter font, without hyphenation, and of the current font attributes only with the sizecreateFragment(...nodes): a fragment of the given nodes or arrays of nodescreateLink(url, children),createImage(width, height, url)macro(name, args): the output of another macro, e.g.this.g.macro("LaTeX")
Groups and fonts
enterGroup(copyAttrs),exitGroup(): like{and}; font changes last until the end of the current group. By default, text created in the group only gets the font attributes set in the group itself: a macro's result gets the current attributes frommacro()anyway, so they aren't repeated inside it. WithcopyAttrs = true, the text also gets the attributes of the enclosing groups, as in{...}in the text and in environments, whose output nobody adds them to.setFontFamily(family):"rm","sf"or"tt"setFontWeight(weight):"md"or"bf"setFontShape(shape):"up","it","sl"or"sc";"em"toggles between italic and uprightsetFontSize(size):"tiny","scriptsize","footnotesize","small","normalsize","large","Large","LARGE","huge"or"Huge"fontFamily(),fontWeight(),fontShape(),fontSize(),textDecoration(): the value that was set in the current group, or that the group copied from its parent;undefinedif the one of the surrounding text still appliessetAlignment(alignment):"centering","raggedright"or"raggedleft"
Counters and lengths
newCounter(name, parent): creates a counter that is reset whenever the optional counterparentis stepped;\the<name>shows its value in arabic numerals unless a macrothe<name>is definedcounter(name),setCounter(name, value),stepCounter(name)arabic(n),roman(n),Roman(n),alph(n),Alph(n): a number formatted like\arabicetc.newLength(name),length(name),setLength(name, length): lengths areLengthobjects, like the parsed arguments of typel
References
refCounter(counter, id): makes the counter the one that the next\labelrefers to; withoutid, it returns a new anchor element to put into the outputsetLabel(name),ref(name): like\labeland\ref
Errors
error(message): reports an error; while parsing, it is thrown as aSyntaxErrorwith the current position in the source