Skip to content
github-actions[bot] edited this page Nov 25, 2026 · 1 revision

SaTeX: Static Analysis for (La)TeX and Friends

An abstract interpreter for (La)TeX and related engines. It expands macros, executes primitives and tracks catcode changes and recursion. It keeps track of context and of each path through conditionals. It does not typeset the document. It lints documents (with quick-fixes, and finds unused or missing macros), slices them, analyzes their performance, jumps to definitions and lists package options with what they govern.

SaTeX demo: version, summary, lint, explain, slice, query, kernel timings and the Vim language server

The documentation at https://eagleoutice.github.io/satex-analyzer/ covers the assumed concrete TeX/eTeX semantics, the linting rules, all supported queries and the configuration.

The first runs of satex are slow because it reads, interprets and caches the (La)TeX kernel and the packages it loads. Later runs use the cache.


SaTeX is actively developed by Florian Sihler (contact me at: florian.sihler@uni-ulm.de) under the MIT License. Contributions are welcome (see CONTRIBUTING.md).

The development and initial Rust codebase is strongly assisted by Claude Code, working from architecture descriptions and TeX semantics. Its design is inspired by flowR, a static analyzer for R. SaTeX neither uses nor requires flowR. It is still work in progress. Please avoid AI-only contributions. The humans who submit code are responsible for it.


Install

Prebuilt binaries for Linux and macOS (x86-64 and ARM64) and Windows (x86-64) are attached to every release. The changelog lists what changed. With Rust installed, cargo install satex-analyzer installs the satex command. cargo install --git https://github.com/EagleoutIce/satex-analyzer installs the latest version from the repository. To build from source:

cargo build --release
./target/release/satex --help

With Docker, ghcr.io/eagleoutice/satex holds satex and TeX Live (LaTeX with the recommended packages and fonts, latexmk). The interpreted kernel is built into the image, about 420 MB in all. Mount the project as the working directory:

docker run --rm -v "$PWD:/work" ghcr.io/eagleoutice/satex lint -f main.tex
docker run --rm -p 2087:2087 -v "$PWD:/work" ghcr.io/eagleoutice/satex lsp --host 0.0.0.0 --port 2087

The second line serves the language server over TCP. docker build -t satex . builds the image from the repository. --build-arg TEX_PACKAGES=texlive-full installs every TeX Live package, at about 5 GB more.

Shell completion: after installing, run satex completions install once. It adds the hook to the startup file of your shell (bash, zsh or fish). satex completions <shell> prints the script for bash, zsh, fish, elvish or powershell. Query names and --set keys complete from the program itself. See the command line page.

source <(satex completions bash)   # bash: add to ~/.bashrc

zsh and fish are on the command line page.

Current version: 0.2.7. satex --version also lists the plugins included in this build and the configuration in effect:

$ satex --version
satex 0.2.7
https://github.com/EagleoutIce/satex-analyzer

plugins: 48 in 11 kinds
  provider            3  texlive, miktex, tectonic
  platform            3  linux, macos, windows
  engine              4  tex, pdftex, luatex, xetex
  kernel              4  latex2e, plain, context, none
  output              4  pdf, dvi, ps, html
  build system        5  latexmk, make, tectonic, arara, l3build
  tools               7  biber, bibtex, makeindex, xindy, makeglossaries, dvips, ps2pdf
  magic comments      3  % !TeX, % !BIB, % arara:
… 17 more lines omitted
Full satex --help output
$ satex --help
Static analyzer for TeX and LaTeX

Usage: satex [OPTIONS] [COMMAND]

Commands:
  query         Run a query.  `satex query --list` names them all
  lint          Context-sensitive lints for the input file. `--all` includes libraries
  summary       What the document and every file it loads contribute
  scope         Control sequences visible at a position, for completion
  explain       What a control sequence means and where it comes from
  slice         Slice the document around a control sequence, environment or position: a compilable reconstruction of the main file by default
  controls      Everything a switch, option or conditional governs.  Without a name, the switches and options in effect.  Several names answer in one table, each row's `for` column saying which one it answers
  dependencies  The program dependence graph (data dependencies plus control dependencies) as DOT or JSON
  trace         The execution trace, step by step
  cache         The interpreted LaTeX2e kernel and the package caches.  Without a further command, prints their status
  compile       Build the document with its build system (arara directives, a Tectonic.toml, latexmk, or the engine) and explain each error and warning the log reports by what the analysis found there.  The build runs the project's own code and build files, so build only projects you trust
  install       Install the packages the document loads that this machine does not have.  Asks first, never elevates, and is never run by `lint --fix`
  tokens        The token stream the mouth produces
  completions   Print the shell completion script: bash, zsh, fish, elvish or powershell.  Values complete from the running binary.  `install [bash|zsh|fish]` registers it in that shell's startup file. Without a shell, it does so in every shell installed or in use
  lsp           A Language Server Protocol server: a thin facade over the queries and lints above, driven by `initialize`/`didOpen`/`didChange` instead of one-shot arguments.  Stdio by default, `--port` switches to TCP
  gui           The browser playground on this machine: opens it on the project in DIR, with the TeX packages installed here, the native language server and the local TeX for the PDF. Edits are saved to the files
  new           A new project in DIR: a provider template (`--list` names them) or another project's files (`--from`). The template's class comes from the TeX installation, or from its provider over HTTPS into the cache (`templates:` in satex.yaml). Then a run reads the new main file and reports the class or style and its version. Nothing in an archive runs
  help          Print this message or the help of the given subcommand(s)

Options:
  -V, --version
          The version, the plugins this build offers, and the configuration in effect here

  -h, --help
          Print help (see a summary with '-h')

Input:
  -f, --file <FILE>
          The document to read, `-` for stdin. Without it, satex reads what is piped in, else each root document in the current directory

      --config <FILE>
          An extra config file, merged on top of every discovered satex.yaml (built-in defaults, the global config, the ones from the filesystem root down to the document's directory)

      --no-config
          Ignore every satex.yaml, discovered or named with --config. Only built-in defaults and `--set` apply

      --profile <NAME>
          Which defaults to apply (usually auto-detected): document, package, class, literate or plain

      --set <PATH=VALUE>
          Overrides an option of `satex.yaml` by its dotted path, the value written as there: `--set limits.memory=8GiB --set load.inputs=false`. `PATH+` appends to a list: `--set lint_off+=[unused-label]`. Repeatable. The flags below win over it

      --no-packages
          Do not load packages. Analyze the document and the kernel only

      --no-classes
          Do not load the document class

      --inject <TEXT>
          Text read at `--at` as if it stood there in the file, such as `\mymacro{x}`: every command then sees what it does in the state the document has there. The file on disk is not changed

      --at <[FILE:]LINE[:COL]>
          Where `--inject` puts its text. The main file without FILE, the start of the line without COL

Limits:
      --max-steps <N>
          Stop the interpreter after this many expansion steps

      --max-memory <SIZE>
          What this run may hold at once, as written by `ulimit`: 512M, 4GiB, 0 for no limit

      --threads <N>
          Threads used for program discovery

Output:
  -v, --verbose...
          Report progress: files read (-v), every 100k tokens (-vv), every expansion (-vvv)

      --format <FORMAT>
          Output format. A command given one it cannot print names the ones it can

          Possible values:
          - text:     Aligned table for a terminal, with color and links
          - compact:  A short text view. For `satex trace`: what each call of the main file expands to and each conditional's outcome, at most 8 lines
          - json:     One JSON array of objects, one object per record
          - csv:      Comma-separated, one record per line
          - markdown: A Markdown table, for a report or a pull request
          - dot:      Graphviz, for `satex dependencies`
          - github:   GitHub Actions annotations
          - sarif:    SARIF 2.1.0, for code scanning
          - lsp:      Language Server Protocol diagnostics and quick-fix code actions
          - texlog:   A LaTeX log, for editors that read only that (TeXstudio)
          
          [default: text]

      --color <COLOR>
          When to color the output

          Possible values:
          - auto:   Color when stdout is a terminal, off otherwise
          - always: Color even when stdout is not a terminal, for example when piped
          - never:  Never color the output
          
          [default: auto]

      --links
          Turn on terminal hyperlinks from names to their source position, even when auto-detection would leave them off

      --no-links
          Turn off terminal hyperlinks, even when auto-detection would turn them on

      --stats
          Print one line of resource accounting (files, tokens, memory, time) to stderr after the run

      --timings
          Print a per-phase timing breakdown to stderr after the run

      --stats-json
          Print the accounting of `--stats` and `--timings` as one JSON object to stderr after the run

Linting

Context-sensitive diagnostics: undefined names, duplicates, dead code and misused conditionals.

$ satex lint -f samples/paper.tex
correctness (1)

  ▲ C018 unguarded-recursion (1)
    paper.tex:24:13  \recurse names itself in its replacement text with no conditional to stop it. Nothing expands it,
                     so this is read off the text
      24 │ \newcommand{\recurse}[1]{#1\recurse{#1}}
         │             ^^^^^^^^
         = hint: add the test that ends the recursion

style (10)

  ● S033 inconsistent-precision (1)
    paper.tex:70:16  numeric column 2 mixes 1 to 2 decimal places: give every number one precision
      70 │     Ours     & 0.92  \\
         │                ^
         = hint: round them by hand, or let siunitx `S` round with `round-mode = places`

  ● S037 numbers-not-aligned (1)
    paper.tex:70:16  numeric column 2 is set `c`: align its decimal separators with siunitx `S`, or at least use `r`
      70 │     Ours     & 0.92  \\
         │                ^
         = hint: add `\usepackage{siunitx}`, set column 2 as `S` and brace its header: `{Score}`

  ● S040 primitive-tex-command (1)
… 50 more lines omitted
List all rules alongside a description with --rules
$ satex lint --rules
severity  category     number  code                              message                                             
error     correctness  C001    already-defined                   command already defined                             
error     correctness  C043    assertion-refuted                 assertion fails                                     
error     correctness  C002    bibtex-command-under-biblatex     BibTeX command under biblatex                       
error     correctness  C003    build-bibliography-disabled       build never runs BibTeX or biber                    
error     correctness  C004    build-command-placeholders        engine command lacks %S or %O                       
error     correctness  C005    build-engine-mismatch             build uses the wrong engine or output               
error     correctness  C006    build-shell-escape-missing        build forbids needed shell escape                   
error     correctness  C007    caused-library-error              package error caused by the document                
error     correctness  C025    environment-mismatch              wrong environment closed                            
error     correctness  C046    invalid-directive                 unreadable satex directive                          
error     correctness  C066    malformed-bibliography-entry      entry breaks the database's grammar                 
error     correctness  C008    math-still-open                   math mode left open                                 
error     correctness  C055    metadata-after-class              DocumentMetadata after documentclass                
error     correctness  C047    missing-end                       document has no end                                 
error     correctness  C009    missing-graphic                   image missing for this output                       
error     correctness  C010    new-redefines                     declaration redefines a command                     
error     correctness  C011    not-defined                       renewing an undefined command                       
error     correctness  C012    option-clash                      package loaded with clashing options                
error     correctness  C013    raised-error                      TeX error in the document                           
error     correctness  C014    undefined-color                   color used before it is defined                     
error     correctness  C015    undefined-control-sequence        undefined command                                   
error     correctness  C016    undefined-environment             undefined environment                               
error     correctness  C017    undefined-glossary-entry          glossary entry never declared                       
error     correctness  C018    unguarded-recursion               recursion that never stops                          
warning   correctness  C052    bibliography-entry-missing-field  cited entry lacks a required field                  
warning   correctness  C071    broken-bibliography-crossref      crossref to no entry, or to an earlier one          
warning   correctness  C019    build-missing-custom-dependency   glossary files have no latexmk rule                 
warning   correctness  C020    catcode-escapes-group             category code change outlives its group             
warning   correctness  C069    conflicting-bibliography-fields   fields that exclude each other                      
warning   correctness  C021    conflicting-color-definition      color name defined twice                            
warning   correctness  C022    delimiter-not-followed            \left or \right before a brace                      
warning   correctness  C023    duplicate-bibliography-entry      key declared twice                                  
warning   correctness  C067    duplicate-bibliography-field      field given twice in one entry                      
warning   correctness  C050    duplicate-bibliography-load       database loaded twice                               
warning   correctness  C051    duplicate-bibliography-work       one work under two keys                             
warning   correctness  C024    duplicate-label                   label defined twice                                 
warning   correctness  C026    expl-syntax-left-on               ExplSyntaxOn never turned off                       
warning   correctness  C027    expl3-constant-set                expl3 constant set again                            
warning   correctness  C028    expl3-signature-mismatch          expl3 argument signature mismatch                   
warning   correctness  C057    graphic-without-alt               graphic without alternative text                    
warning   correctness  C029    ignored-verbatim-tail             text lost after verbatim end                        
warning   correctness  C068    invalid-bibliography-field-value  value is not what the field takes                   
warning   correctness  C030    math-script-braces                script needs braces                                 
warning   correctness  C065    missing-bibliography              citations without a bibliography                    
warning   correctness  C031    missing-dependency                package missing from the dependency file            
warning   correctness  C063    misspelled-magic-comment          misspelled magic comment                            
warning   correctness  C064    package-call-error                a package command fails on some call                
warning   correctness  C061    package-load-order                package overrides an earlier one                    
warning   correctness  C058    pdfua-without-title               PDF/UA without a title                              
warning   correctness  C054    reference-name-mismatch           name does not match the label                       
warning   correctness  C056    tagging-incompatible-package      package incompatible with tagging                   
warning   correctness  C060    tagging-unsupported-engine        engine does not support tagging                     
warning   correctness  C059    tagging-without-language          tagging without a language                          
warning   correctness  C032    unbalanced-brackets               unbalanced brackets                                 
warning   correctness  C033    unbalanced-color-stack            unbalanced color stack                              
warning   correctness  C034    unbalanced-pdf-content            unclosed PDF literal                                
warning   correctness  C053    undefined-bibliography-string     undefined @string constant                          
warning   correctness  C035    undefined-citation                citation key not in the bibliography                
warning   correctness  C048    undefined-cref-format             cleveref has no name for this label                 
warning   correctness  C036    undefined-optional-content        unknown optional content group                      
warning   correctness  C037    undefined-reference               reference to an undefined label                     
warning   correctness  C038    uninstalled-package               package not installed                               
warning   correctness  C070    unknown-bibliography-entry-type   entry type the style does not define                
warning   correctness  C049    unknown-code-language             unknown listings language                           
warning   correctness  C062    unknown-package-name              package name misspelled                             
warning   correctness  C039    unresolved-file                   file not installed                                  
info      correctness  C045    assumption-made                   document assumes a condition                        
info      correctness  C040    expected-load                     file read before a package it expects               
info      correctness  C041    math-mode-mismatch                math delimiter in the wrong mode                    
info      correctness  C042    unintended-escape                 command followed by escaped punctuation             
hint      correctness  C044    assertion-proved                  assertion always holds                              
warning   security     X001    build-shell-escape-unneeded       build allows unused shell escape                    
warning   security     X002    shell-escape                      document runs a program                             
warning   style        S001    accent-on-dotted-letter           accent on a dotted i or j                           
warning   style        S002    command-terminated-space          space eaten after a command                         
warning   style        S003    dimension-times                   x instead of a times sign                           
warning   style        S004    double-space                      double space                                        
warning   style        S060    doubled-punctuation               doubled punctuation                                 
warning   style        S005    ellipsis-dots                     three periods, not an ellipsis                      
warning   style        S054    et-al                             et al. spelled by hand                              
warning   style        S006    expl3-scope                       expl3 scope prefix mismatch                         
warning   style        S007    expl3-type                        expl3 type suffix mismatch                          
warning   style        S008    group-local-definition            definition lost when its group closes               
warning   style        S067    low-contrast-color                text color with too little contrast                 
warning   style        S009    math-operator-name                operator name in math italic                        
warning   style        S010    missing-italic-correction         missing italic correction                           
warning   style        S011    missing-nonbreaking-space         missing tie before a reference                      
warning   style        S063    overfull-box                      hbox too wide for its width                         
warning   style        S062    overfull-line                     line wider than the text block                      
warning   style        S012    parenthesis-spacing               parenthesis takes the wrong space                   
warning   style        S013    quote-direction                   quotation mark points the wrong way                 
warning   style        S061    sentence-capital                  sentence starts lowercase                           
warning   style        S014    sentence-spacing                  wrong space after a period                          
warning   style        S015    space-before-command              line may break before a mark                        
warning   style        S016    space-before-punctuation          space before punctuation                            
warning   style        S017    stray-italic-correction           stray italic correction                             
warning   style        S018    unknown-suppress-code             suppression names no rule                           
warning   style        S019    user-pattern                      matches a project pattern                           
warning   style        S064    wider-than-line                   box wider than its lines                            
warning   style        S020    wrong-dash                        wrong dash length                                   
warning   style        S021    wrong-quote-character             wrong character used as a quote                     
warning   style        S022    zero-italic-correction            useless italic correction                           
info      style        S059    bare-reference                    reference without a name                            
info      style        S023    build-bibliography-unneeded       build runs BibTeX without a bibliography            
info      style        S024    build-engine-options              engine command lacks file:line or SyncTeX           
info      style        S025    build-unused-custom-dependency    unused latexmk dependency                           
info      style        S053    clones                            repeated block of source                            
info      style        S026    comment-marker                    TODO marker in a comment                            
info      style        S027    computer-modern-in-t1             T1 text relies on cm-super                          
info      style        S028    csquotes-available                hand-set quotes, csquotes not loaded                
info      style        S029    dead-definition                   definition replaced before use                      
info      style        S030    duplicate-color-value             two names for one color                             
info      style        S031    duplicate-package                 package loaded twice                                
info      style        S032    hand-set-quantity                 hand-set number and unit                            
info      style        S052    hand-written-author               author name typed before a citation                 
info      style        S051    hand-written-reference            number typed after a reference name                 
info      style        S069    ignored-bibliography-field        field the style never reads of this type            
info      style        S033    inconsistent-precision            different decimals in a column                      
info      style        S068    indistinct-colors                 colors alike with color blindness                   
info      style        S057    itemize-described                 labelled items in an itemize                        
info      style        S056    itemize-numbered                  numbered items in an itemize                        
info      style        S034    math-punctuation                  punctuation on the wrong side of a formula          
info      style        S035    math-shift-dollars                $$ instead of \[                                    
info      style        S036    microtype-available               microtype not loaded                                
info      style        S037    numbers-not-aligned               numbers not aligned                                 
info      style        S038    ot1-font-encoding                 accents built with \accent in OT1                   
info      style        S058    package-successor                 package has a successor                             
info      style        S039    prefer-cleveref                   hand-written name before a reference                
info      style        S040    primitive-tex-command             plain TeX primitive in LaTeX                        
info      style        S041    quote-ligature                    quotes run together                                 
info      style        S042    quote-punctuation                 punctuation inside the quote                        
info      style        S066    redundant-package-load            package loaded already                              
info      style        S070    spelled-out-macro                 word typed out that a command of the document sets  
info      style        S043    stray-space                       space from a line end in a macro                    
info      style        S044    table-rules                       vertical rules or hline in a table                  
info      style        S065    tagged-math-without-mathml        formulas without MathML                             
info      style        S055    uncited-bibliography-entry        database entry never cited                          
info      style        S045    unit-in-cells                     unit repeated in every cell                         
info      style        S046    unreferenced-numbered-display     numbered display never referenced                   
info      style        S047    unused-bibitem                    bibitem never cited                                 
info      style        S048    unused-color                      color never used                                    
info      style        S049    unused-definition                 macro never used                                    
info      style        S050    unused-label                      label never referenced                              
error     performance  P001    package-after-preamble            package loaded after the preamble                   
info      performance  P002    includeonly-available             parts built whole                                   
info      performance  P003    preamble-cost                     slow preamble                                       
info      performance  P004    recursive-macro                   recursive macro                                     
info      performance  P005    unused-dependency                 unused entry in the dependency file                 
info      performance  P006    unused-package                    unused package                                      
error     precision    A003    unread-document                   document not fully read                             
info      precision    A001    analysis-imprecision              analysis had to widen                               
info      precision    A002    assertion-unknown                 assertion not decided                               
Explain one rule with --explain
$ satex lint --explain unguarded-recursion
C018 unguarded-recursion  correctness / error / since 0.1.0
recursion that never stops

The run saw the macro's expansion reach the macro again, could not see the
recursion end, and found no conditional (no `\if…`, `\else` or `\fi`) to
end it, in any macro of the cycle or in one their replacement texts name.  A
macro nothing expands is judged by the names its replacement text holds, and
it calls a name only where the name stands to be expanded: not inside braces,
not as the target of a definition or after `\string`, and not as a quark
(`\def\q{\q}`, compared and never expanded).  A real run expands until
TeX runs out of memory:
`TeX capacity exceeded, sorry [main memory size]`.

Fix by adding the test that stops it, or by removing the self-reference.

Findings marked [fix] are repaired by satex lint --fix, those marked [unsafe fix] by --fix --unsafe-fixes (these could theoretically change the resulting document). You can use --diff to show the specific edits. See quick-fixes.

For CI, output formats include --format github (GitHub Actions annotations) and --format sarif (code scanning).

Show the GitHub Actions with --format github
$ satex lint -f samples/paper.tex --format github
::warning file=samples/paper.tex,line=24,col=13,title=C018 unguarded-recursion::\recurse names itself in its replacement text with no conditional to stop it. Nothing expands it, so this is read off the text
::notice file=samples/paper.tex,line=76,col=1,title=S050 unused-label::label `sec:conclusion` is never referenced
::notice file=samples/paper.tex,line=42,col=1,title=S050 unused-label::label `sec:method` is never referenced
::notice file=samples/paper.tex,line=22,col=1,title=S040 primitive-tex-command::`\csname` is plain TeX. Here it uses a control sequence by name
::notice file=samples/preamble.tex,line=1,col=1,title=S049 unused-definition::\hello is never used
::notice file=samples/paper.tex,line=14,col=1,title=S049 unused-definition::\WeirdMore is never used
… 5 more lines omitted

Comprehension

These commands explain existing documents and their macros.

Explaining Macros

With explain you can ask SaTeX what a specific macro does. explain may list multiple meanings of a macro if they differ (e.g. in the LaTeX document). Use --all to obtain lists every definition and --at to ask at a specific place in the document: preamble, document, LINE, FILE:LINE or after:PACKAGE.

Explain the \usepackage macro
$ satex explain -f samples/paper.tex '\usepackage'
\usepackage @ latex.ltx:18619:25
  tag            alias
  when           preamble
  context        outside environments
  effective      \usepackage[1]{2}[3]
  signature      omo
  roles          #2 package
  types          #1 options, #2 package (.sty), #3 date, at least
  takes          1-3
  uses           4 times, in this run
  by             \let
  does           Loads packages.
  documentation  The LaTeX2e sources, [source2e](https://ctan.org/pkg/source2e)
  expands        \@fileswithoptions
  body           \@fileswithoptions \@pkgextension 
  reference      https://texdoc.org/serve/source2e/0
  file           /usr/local/texlive/YYYY/texmf-dist/tex/latex/base/latex.ltx:18619

\usepackage @ latex.ltx:9521:22
  tag            alias
  when           document
  context        outside environments
  effective      \usepackage
  error          LaTeX Error: Can be used only in preamble.
  roles          #1 package
  types          #1 package (.sty)
  takes          0
  uses           0 times, in this run
  by             \let
  does           Loads packages.
  documentation  The LaTeX2e sources, [source2e](https://ctan.org/pkg/source2e)
  may_expand     \@fileswithoptions
  body           \@latex@error {Can be used only in preamble}\@eha 
  reference      https://texdoc.org/serve/source2e/0
  file           /usr/local/texlive/YYYY/texmf-dist/tex/latex/base/latex.ltx:9521
Explain a user-defined macro --at document
$ satex explain -f samples/paper.tex '\norm'
\norm @ paper.tex:12:13
  tag         macro
  context     outside environments
  effective   \norm{1}
  signature   m
  takes       1
  uses        1 time, in this run
  by          \newcommand
  expands     \left, \lVert, \right
  may_expand  \hat
  body        \left \lVert #1\right \rVert 
  file        samples/paper.tex:12

See the explain section of the queries page, and signatures for what the signature keys mean.

Document Summaries

A document summary shows the commands, dependencies, and metadata of a document.

What the document contains with summary
$ satex summary -f samples/paper.tex
paper.tex
  identified LaTeX2e document, class article [2025/01/22 v1.4n Standard LaTeX document class][11pt]
  title A Sample Document for saTeX
  author satex Test Suite
  engine pdflatex (build configuration)
  provider texlive (TeX 3.141592653 (TeX Live 2026)) (detected)
  platform linux (this machine)
  kernel latex2e (default)
… 28 more lines omitted

Explore Package Options and Feature Flags

The controls command shows the switches and options a package or class defines, and what each governs. You can also use query options to see what keys an environment's optional argument takes.

Switches and options, and what each one governs, with controls
$ satex controls -f samples/paper.tex
tag     name       count  value                                  governs  file           
option  article           11pt                                            paper.tex      @ paper.tex:1:1
switch  \ifdraft          false                                  213      paper.tex      @ paper.tex:3:7
offers  amsmath    15     alignedleftspaceno, alignedleftspace…           amsmath.sty    @ amsmath.sty:45:16
… 9 more lines omitted
The keys an environment's optional argument takes with query options
$ satex query options -f samples/paper.tex --for itemize
Slice the document around a name, position or query with slice

A compilable document by default. --where EXPR slices to every occurrence or definition a query accepts (--where 'kind=begin-environment and key=figure' for every figure), --list prints the matching records instead, and --out DIR writes the slice out as its own small project.

$ satex slice -f samples/paper.tex '\ifdraft'
\begin{filecontents*}[overwrite]{mypackage.sty}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mypackage}[2024/01/01 v1.0 Sample package for satex]

\RequirePackage{xcolor}

… 58 more lines omitted
What is visible at a position, for completion, with scope
$ satex scope -f samples/paper.tex --at 20:1
tag          name                           effecti…  does      file                
macro        \Weird                         \Weird …            paper.tex           @ paper.tex:16:1
macro        \WeirdMore                     \WeirdM…            paper.tex           @ paper.tex:14:1
… 10265 more lines omitted

Performance

Shows what a build costs: which packages and files dominate, and what to do about it.

$ satex lint -f samples/paper.tex --filter 'category=performance'
performance (1)

  ● P003 preamble-cost (1)
    paper.tex:26:1  4 packages requested directly, 275 files read, 82% of the tokens the build takes
      26 │ \begin{document}
         │ ^^^^^^
… 6 more lines omitted

--timings breaks the time down per phase and file, --stats sums up counts and wall time. Both measure the run itself and change between runs. The kernel and the packages are interpreted once and cached. satex cache build prepares the packages in cache.index ahead of time.

The cached kernel with cache
$ satex cache
cache ~/.cache/satex
  kernel     /usr/local/texlive/YYYY/texmf-dist/tex/latex/base/latex.ltx · 197.8k definitions · cached
  pruned     63 caches, 72.3 MiB: no build can use them, or past limits.cache_size
  packages   418 stored, 954.0 MiB
… 2 more lines omitted

Queries

Structured facts for other tools. See the queries wiki page for more details.

The commands a document defines itself, without packages and without internal @ names:

$ satex query definitions -f samples/paper.tex --filter 'origin=document and not package~. and not name~@'
tag     name         paramet…  comment                               body      file          
switch  \ifdraft                                                               paper.tex     @ paper.tex:3:7
switch  \drafttrue                                                   \let \i…  paper.tex     @ paper.tex:3:7
switch  \draftfalse                                                  \let \i…  paper.tex     @ paper.tex:3:7
macro   \hello                                                       world     preamble.tex  @ preamble.tex:1:1
macro   \highlight   #1        Standard single-argument macros.      \textbf…  paper.tex     @ paper.tex:11:13
macro   \norm        #1                                              \left \…  paper.tex     @ paper.tex:12:13
macro   \WeirdMore   super #…                                         #1       paper.tex     @ paper.tex:14:1
… 2 more lines omitted
List all queries with --list
$ satex query --list
name              about                                                                                                 
calls             which control sequences each macro's body invokes                                                     
catcodes          explicit \catcode assignments the document makes                                                      
definitions       every macro, environment and register the document or its packages define                             
dependencies      files, packages and classes read, and what loaded each                                                
dependency-graph  the dependency graph between files and packages as records                                            
diagnostics       what satex noticed while interpreting, apart from lint rules                                          
distribution      the detected TeX installation, version and searched trees                                             
expansions        how often each macro was expanded during the run                                                      
exports           the names installed packages define, each with the package or library to load                         
files             every file read, in the order it was opened                                                           
gaps              constructs the run could not interpret, grouped by cause                                              
letters           where a punctuation character becomes a letter or stops being one: what names are typeable where      
occurrences       package banners, passed options and other one-off events                                              
options           the keys an environment or command's optional argument accepts                                        
pgfkeys           pgfkeys defined at the end of the run and what each does                                              
plugins           what each plugin chose for this run, and why                                                          
previews          arrow tips and patterns the run declared, drawn by TeX                                                
produces          where a given text can come from, expanded or not                                                     
project           document class, engine and build settings detected or assumed                                         
recursion         macros that call themselves, directly or through others                                               
side-effects      definitions and assignments a macro makes when called                                                 
tagging           PDF tagging: whether it is on, the standard, language, title and each package's status                
trace             every step: macro expansions, primitives run, changes made (only with `trace: true`, or use `satex …  
type-plugins      the editor's type plugins: the types each triggers on and its features                                
typeset           the text the document typesets, one row per paragraph                                                 
Several queries over one analysis with --request
{
  "file": "samples/mypackage.sty",
  "queries": [
    {"type": "explain", "names": ["\\mybox"]},
    {"type": "controls", "names": ["my@draft"]},
    {"type": "options", "name": "mybanner"}
  ]
}

satex query --request FILE (or - for stdin) answers each in order, as one JSON array. A config object overrides settings as --set does.

Every step of the run with trace
$ satex trace -f samples/paper.tex
index   step         name                        detail    arguments       file           
678     expand       \documentclass                                        paper.tex      @ paper.tex:1:1
8412    open-file    \article                    /usr/lo…                  paper.tex      @ paper.tex:1:1
10261   expand       \par                                                  paper.tex      @ paper.tex:2:1
10268   expand       \newif                                \ifdraft        paper.tex      @ paper.tex:3:1
… 185 more lines omitted
The token stream with tokens
$ satex tokens -f samples/paper.tex
kind  name            detail  
cs    \documentclass          @ 1:1
char  [               cat 12  @ 1:15
char  1               cat 12  @ 1:16
char  1               cat 12  @ 1:17
… 1210 more lines omitted

Every command prints text by default. You can use --format json, csv or markdown whenever it prints rows. Some formats like github, sarif and lsp may be specific to commands like lint.

Editor integration

satex lsp runs a Language Server: diagnostics, hover, definitions, references, completion, document symbols and quick fixes, all backed by the commands above. Stdio by default, --port/--host for TCP. See the LSP wiki page for the protocol details and Neovim setup, and the VS Code and IntelliJ pages for those editors.

satex gui [DIR] opens the browser playground on a project of your computer: its files, the TeX packages installed there, the native language server and your TeX for the PDF. Edits are saved to the files. See the playground on your machine.

Configuration

SaTeX merges its built-in defaults, your global ~/.config/satex/satex.yaml, every satex.yaml from the filesystem root down to the document, --config FILE, and --set PATH=VALUE, each overriding the one before. satex --version lists what was used. Plugins detect the installation, engine, output and build system (latexmk, make, l3build, …). TeX, e-TeX, pdfTeX and LaTeX2e are modeled in full. XeTeX, LuaTeX and ConTeXt are experimental. See the configuration wiki page. The command line page gives the rules every command shares: input, config, output and exit codes.

How it works

SaTeX has no abstract syntax tree in the classical sense and is not syntax-guided. When analyzing TeX a token's meaning depends on category codes and on what earlier macros did, so the token stream only exists while the document runs. SaTeX follows an expansion-guided approach instead using TeX's machine (mouth, gullet, stomach, save stack).

Concretely:

  • State. Meanings of control sequences, category codes, register values and the save stack, are tracked during the analysis. A value SaTeX cannot decide while running is unknown, and that spreads to everything computed from it.
  • Transfer. Every primitive has the effect associated with the concrete TeX/eTeX semantics.
  • Branching. We analyze every branch of a conditional if the test is not deterministic. This also applies transitively to macro-expansions.
  • Termination. Recursive expansion that could go on forever is cut short by approximating it, within the budgets in limits.

Gaps

Use satex query gaps -f <document> to get details on noted issues SaTeX has with analyzing the document (and its dependencies). The challenges page shows what makes TeX hard to analyze.

Related Work

There are various preexisting analysis approaches for TeX, albeit none offer full support for macro expansion, catcode manipulations, build-systems, and the like. However, based on your need, you may find the following useful:

  • Featherweight TeX is a formal model of TeX's macro system, aimed at parser correctness (rather than analyzing real documents).
  • Tylax converts between LaTeX and Typst with support for basic macro expansion.
  • unravel steps through TeX's expansion as a debugger, but runs one concrete execution for this.
  • TexLab is a language server that gives editor features from a syntax tree, without expanding macros.
  • unified-latex parses LaTeX into a syntax tree for transformation, and does not expand macros in general.
  • ChkTeX is a token-level linter for typographic and style mistakes (it does not expand macros). The chktex coverage table lists its 49 warnings and the satex rule for each.

Clone this wiki locally