latex.js

repository·master·Indexed 21 days ago

https://github.com/michael-brade/latex.js

A JavaScript-based translator that converts LaTeX source code into HTML5 using a PEG.js parser. It aims for high compatibility and precision with LaTeX syntax, utilizing accompanying CSS to make the HTML output resemble traditional LaTeX. The library provides a CLI for console translation and an extensible API allowing users to implement custom LaTeX macros using JavaScript.

Tokens
12.4K
Snippets
49
Records
61
Agent score
71%

What's inside latex.js

  1. Overview of latex.js

    master

    latex.js is a LaTeX to HTML5 translator written in JavaScript using a PEG.js parser. It is designed to be uncompromisingly exact and compatible with LaTeX, ensuring that the generated HTML output is precise. The accompanying CSS is designed to make the HTML output resemble standard LaTeX output.

    For an interactive way to test LaTeX snippets, you can use the latex.js playground.

  2. Understand the limitations of LaTeX to HTML translation

    master

    When using latex.js, be aware of several architectural and language-level limitations that affect how your LaTeX source is rendered:

    Parsing and Macro Limitations

    • No Intermediate AST: Because the project does not yet use an intermediate Abstract Syntax Tree (AST), conditional expressions in TeX are not supported.
    • Macro Support: Deprecated macros (e.g., eqnarray, \it, \sl) and most plain TeX macros are not implemented. Only standard LaTeX syntax and catcodes are assumed.
    • No Macro Definitions: You cannot define new macros using \def within the LaTeX source. The parser only supports expanding existing macros.
    • Incomplete Snippets: Every macro must return a complete document (fragment) node; partial or incomplete LaTeX snippets are currently unsupported.
    • Package Support: Native LaTeX packages and documentclasses cannot be loaded. To use functionality from a package, you must implement those macros directly in JavaScript.
  3. How LaTeX.js architecture works

    master

    The translation process follows a specific pipeline:

    1. Parsing: A PEG parser (defined in src/latex-parser.pegjs) parses the <latex/> code.
    2. Generation: As the parser runs, it calls generator functions. The generator manages the state, including the stack, lengths, counters, fonts, and references.
    3. Macro Execution: The generator uses the Macros class to execute macros encountered during parsing.
    4. DOM Construction: Both the parser and the macros build the resulting HTML DOM tree by calling HtmlGenerator functions.

    Key source files for the translation engine include:

    • Parser: src/latex-parser.pegjs
    • Generator: src/generator.ls and src/html-generator.ls
    • Macros/DocumentClasses: src/latex.ltx.ls, src/symbols.ls, and files in src/documentclasses/*.ls
    • Packages: src/packages/*.ls
  4. Identify non-translatable TeX features in HTML/CSS

    master

    Certain TeX features cannot be accurately translated to HTML/CSS due to the fundamental differences between TeX's layout engine and the web model:

    Layout and Spacing

    • Whitespace Handling: TeX's ability to remove specific whitespace from the beginning/end of lines (including special characters like \ or ~) is not fully possible in HTML.
    • Glue: Horizontal glue (\hfill) and vertical glue cannot be emulated in HTML (except within boxes of fixed height).
    • Negative VSpace: Using \vspace{} with a negative value inside a paragraph (horizontal mode) is not supported.
    • Box Depth: TeX boxes have a specific 'depth' below the baseline. CSS boxes only recognize height, which can cause minor visual discrepancies in baseline alignment.

    Pagination

    • Pagebreaks: Since HTML is a continuous flow document, any macros related to pagebreaks will be ignored.
  5. Extend <latex/>.js with custom macros

    master
    The library is designed for extensibility. You can add new LaTeX macros using JavaScript. This is often a more efficient way to implement specific functionalities compared to standard LaTeX, as you can leverage the combination of JavaScript and CSS for styling and behavior.
  6. Build and test the LaTeX.js repository

    master

    To develop on the LaTeX.js source, clone the repository and follow these steps:

    Setup and Testing

    npm install
    npm run build   # or devbuild
    npm test

    Note: To verify CSS screenshots, you must have ImageMagick installed. The project uses puppeteer with Chromium to take screenshots.

    Documentation and Playground To build the documentation website and the interactive playground:

    npm run docs
    npm install
    npm run build
    npm test
  7. Define custom LaTeX macros in JavaScript

    master

    You can extend <latex/>.js by defining a custom class containing your macros and passing it to the HtmlGenerator constructor via the CustomMacros property in the options object.

    If you define macros in an external file for use with the CLI, the file must either be named exactly like the class or use a default export.

    var generator = new latexjs.HtmlGenerator({
      CustomMacros: (function() {
        var args      = CustomMacros.args = {},
            prototype = CustomMacros.prototype;
    
        function CustomMacros(generator) {
          this.g = generator;
        }
    
        // Define the 'bf' macro
        args['bf'] = ['HV']
        prototype['bf'] = function() {
          this.g.setFontWeight('bf')
        };
    
        return CustomMacros;
      })()
    });
  8. Use latex.js as a Library

    master

    For maximum control over the translation process, use latex.js as a library in your project. The architecture is divided into a parser and a generator. Currently, only an HtmlGenerator is available.

    Installation

    npm install --save-prod latex.js

    Basic Usage Pattern

    1. Import the parser and the HtmlGenerator.
    2. Parse the LaTeX source.
    3. Use the generator to translate the parsed content into HTML.

    Note: The HtmlGenerator accepts an options object for configuration.

  9. Implement custom LaTeX macros in JavaScript

    master

    Because latex.js uses a PEG parser that treats LaTeX as a context-free language, it cannot support TeX's Turing-complete macro system (including \def or dynamic scoping).

    If you need a macro that is not provided by the library or is part of a specific LaTeX package, you must reimplement the macro directly in JavaScript to circumvent the parsing limitations.

  10. Install latex.js for CLI or library usage

    master

    You can install latex.js either as a global command-line tool or as a dependency in your JavaScript project.

    Global CLI Installation

    To use latex.js directly from your terminal, install it globally using npm:

    npm install -g latex.js

    Library Installation

    To use latex.js as a module within your own application, add it to your project's production dependencies:

    npm install --save-prod latex.js