GNU TeXmacsUser manualReferenceAboutEnglish
Exporting to LaTeX

1.The stages of the export

When the user exports a buffer to LaTeX, the following stages are traversed. The first stages are written in C++, the main conversion and the serialization in Scheme.

  1. buffer_export (

    Texmacs/Data/new_buffer.cpp

    ) attaches the current view to the document (attribute view) and calls export_tree, which calls tree_to_generic with the format latex-document. The converter graph selects the converter from texmacs-stree to latex-document, implemented by conservative-texmacs->latex, that is by the C++ function conservative_texmacs_to_latex.

  2. conservative_texmacs_to_latex (

    Data/Convert/Tex/conservative_totex.cpp

    ) checks whether the document was itself imported from LaTeX with source tracking; if so, unchanged parts of the original LaTeX source are reused (see source tracking and conservative conversion). Otherwise, or after this preparation, it calls tracked_texmacs_to_latex (

    tracked_totex.cpp

    ).

  3. tracked_texmacs_to_latex first calls latex_expand, which retrieves the view from the view attribute and calls edit_typeset_rep::exec_latex on the body. This expands the TeXmacs macros which have no LaTeX counterpart (see below). Then it calls tree_to_latex_document, which calls the Scheme function texmacs->latex-document from

    convert/latex/init-latex.scm

    , possibly several times when source tracking is enabled.

  4. texmacs->latex-document converts the tree into an stree, calls texmacs->latex (

    convert/latex/tmtex.scm

    ) to obtain a LaTeX stree, and serializes it with serialize-latex (

    convert/latex/texout.scm

    ).

Snippets (copying a selection as LaTeX) skip the C++ stages and go directly through texmacs->latex and serialize-latex (converters texmacs-stree \(\rightarrow\) latex-stree \(\rightarrow\) latex-snippet).

2.Macro expansion before the conversion

LaTeX does not know most TeXmacs macros. Instead of implementing a LaTeX counterpart for each of them, the exporter can let the TeXmacs evaluator expand them in the environment of the document, using the style files and packages of the document. This is done by

tree edit_typeset_rep::exec_latex (tree t, path p)
(expand macros unknown to the LaTeX converter)

Implemented in

Edit/Editor/edit_typeset.cpp

and accessible from Scheme as latex-expand. Nothing is done unless one of the preferences "texmacs->latex:expand-macros" or "texmacs->latex:expand-user-macros" is "on". Otherwise the environment at the start of the document is computed (typeset_exec_until), patched with the result of the Scheme function tmtex-env-patch, and the body is evaluated with exec. Before patching, every variable tmlatex-name of the environment replaces the variable name (function prefix_specific): a style file may thus provide LaTeX-specific variants of its macros, just as it may provide tmhtml- variants for the HTML export. When user macros are not expanded, a hide-preamble at the start of the document is evaluated separately so that the user's definitions survive.

The patch returned by tmtex-env-patch (end of

tmtex.scm

) is a collection of identity macros (xmacro "x" (eval-args "x")), which protect a tag from expansion while still evaluating its arguments. Protected are:

with the exception of the tags listed in tmtex-always-expand (for instance the rendering macros of theorems, algorithms, exercises and the tags of the tmdoc style), which are always expanded. All other macros, in particular the ones which only appear inside the definitions of other macros, are expanded by the evaluator. As a consequence, a macro of a style file which is used directly in the document and which has no handler in the converter is not expanded: it is exported as a LaTeX command with the same name (see the default rule below), which has to be defined by the user on the LaTeX side.

3.The LaTeX stree

The result of texmacs->latex is a Scheme expression in which ordinary lists (cmd arg1 … argn) stand for the LaTeX command \cmd{arg1}…{argn}, strings stand for LaTeX text, and a number of special labels starting with ! stand for other constructs. The serializer texout in

convert/latex/texout.scm

recognizes the following labels:

(!file body styles needs init preamble)

A complete document; serialized by texout-file, which writes the \documentclass, the \usepackage commands, the language, the TeXmacs macro definitions and the user's preamble. needs is a list of three lists: the languages, the colors and the color maps which were used.

!document, !paragraph, !concat, !append

Vertical concatenation (paragraphs separated by blank lines), lines inside a paragraph, horizontal concatenation, and plain juxtaposition.

((!begin env arg …) body)

An environment \begin{env}{arg}…body\end{env}; !begin* is a variant without line breaks.

(!option x)

An optional argument [x] of the enclosing command.

!math, !eqn

Inline math $…$ and display math \[…\].

!sub, !sup

Subscripts and superscripts.

!group

A group {…}.

!table, !row

The contents of a tabular environment.

!verb, !verbatim, !verbatim*

Verbatim text.

!symbol, !widechar

A symbol command and a non-ASCII character.

!nbsp, !nbhyph, !newline, !nextline, !linefeed, !indent, !unindent

Spacing and layout of the output.

!arg

A macro parameter #n (in macro definitions).

!comment, !preamble, !ignore, !annotate

Comments, verbatim preamble material, ignored material and transparent annotations.

!invariant, !marker

Verbatim LaTeX source reused by the conservative converter, and the source tracking markers {\btm{…}} and {\etm{…}}.

!file-name

The name of a file, as in includegraphics, written as it is.

Any other list is serialized as a command application by texout-apply. The serializer writes into the output buffer of

convert/tools/output.scm

(output-text, output-verbatim, output-lf, etc.), which takes care of indentation and line breaking; serialize-latex returns the accumulated string via output-produce.

4.The main converter

4.1.Entry point

(texmacs->latex x opts)
(convert a TeXmacs stree into a LaTeX stree)

If x is a complete file (tmfile?), the body, the style, the language, the initial environment and the attachments are extracted and assembled into (!file body style lan init att path). The global variables tmtex-style and tmtex-packages are set from the style, style-specific modules are imported (import-tmtex-styles), the hooks tmtex-style-init and tmtex-style-preprocess are called and the function recurses on the !file expression. Otherwise, equation numbers are normalized (tmtm-eqnumber->nonumber), brackets are matched (tmtm-match-brackets), the options are decoded (tmtex-initialize), the tree is pre-processed by tmpre-produce (

convert/tools/tmpre.scm

) and converted by tmtex. Finally, if the option "texmacs->latex:use-macros" is off, the LaTeX macros introduced by TeXmacs are expanded in place by latex-expand-macros; for MathJax (option "texmacs->latex:mathjax", only set by the HTML exporter) the result is cleaned up by latex-mathjax-pre and latex-mathjax.

The handler of !file is tmtex-file. It separates the preamble of the document (macro definitions and the contents of hide-preamble, see tmtex-filter-preamble) from the body, converts the TeXmacs style into a LaTeX document class with tmtex-transform-style (e.g. generic, tmarticle and tmdoc become article, book and tmbook become book; other styles are kept only if "texmacs->latex:replace-style" is off), determines whether user macros are mainly used in text or in math mode (init-mode-stats), and converts the definitions with tmtex-pre and the body with tmtex. The result is the !file stree described above.

4.2.Dispatching

The converter proper is the function tmtex: strings are converted by tmtex-string, compound trees by tmtex-apply:

(define (tmtex-apply key args)
  (let ((n (length args))
        (r (or (ahash-ref tmtex-dynamic key)
               (logic-ref tmtex-methods% key))))
    …
    (cond ((== r 'environment)
           (tmtex-std-env (symbol->string key) args))
          (r (r args))
          (else
            (let ((p (logic-ref tmtex-tmstyle% key)))
              (cond ((and p (or (= (cadr p) -1) (= (cadr p) n)))
                     ((car p) (symbol->string key) args))
                    …
                    (else (tmtex-function key args))))))))

There are thus four levels of dispatch.

  1. The hash table tmtex-dynamic, filled during the conversion by tmtex-new-theorem: theorem-like environments declared in the document are exported as LaTeX environments.

  2. The logical table tmtex-methods%, which is the union of tmtex-primitives% (the TeXmacs primitives: concat, frac, with, table, image, etc.) and tmtex-extra-methods% (a few extra tags such as wide-float and the marginal notes). These tables are declared with logic-dispatcher, which is logic-table with the implementations unquoted, so that the table stores procedures; see logical programming extensions. The handlers take the list of (unconverted) arguments.

  3. The logical table tmtex-tmstyle%, for the tags defined in the standard style files (sectioning, theorems, lists, size changes, code, citations, etc.). Each entry is a pair (handler arity), where the arity -1 accepts any number of arguments; the handler is called with the tag name (a string) and the arguments. The arity -2 is used for handlers which take the whole tree.

  4. Fallbacks: a tag whose last argument is a table or tformat is converted into a table environment with tmtex-table-apply, and any other tag is converted by tmtex-function into a LaTeX command whose name is computed by tmtex-var-name: non-alphanumeric characters are dropped, digits are spelled out (my-tag2 becomes \mytagtwo), and names which would clash with short TeX or LaTeX commands (the group tmtex-protected%, which contains for instance a, it and em) get the prefix tm.

Many handlers are tiny. For instance the logical markup strong, em, name, etc. is handled by

(define (tmtex-modifier s l)
  (tex-apply (string->symbol (string-append "tm" s)) (tmtex (car l))))

which produces \tmstrong{…}. The function tex-apply wraps the application in a group in text mode, and tex-math-apply wraps it in \ensuremath outside math mode.

4.3.The conversion environment

The converter keeps a small environment tmtex-env (a hash table of stacks) with the functions tmtex-env-set, tmtex-env-reset and tmtex-env-assign. The most important variable is "mode", which decides whether strings are converted as text or as math (tmtex-math-mode?). with is handled by tmtex-with, which pushes the variable and looks up a LaTeX command in the tables tex-with-cmd% (text, e.g. font-series bold gives \tmtextbf), tex-with-cmd-math% (math fonts, e.g. math-font cal gives \mathcal) and tex-assign-cmd% (declarations such as \bfseries); paragraph parameters, languages and colors have dedicated handlers (tmtex-make-parmod, tmtex-make-lang, tmtex-make-color).

4.4.Style-specific conversions

The behavior of the converter depends on the TeXmacs style of the document. The modes declared by texmacs-modes at the top of

tmtex.scm

(elsevier-style%, acm-style%, ams-style%, revtex-style%, springer-style%, ieee-style%, beamer-style%, natbib-package%, …) test tmtex-style and tmtex-packages. The modules

tmtex-acm.scm

,

tmtex-ams.scm

, etc. are imported by import-tmtex-styles and redefine some functions with tm-define and the :mode option (see function definition and contextual overloading). For instance

tmtex-ams.scm

contains

(tm-define (tmtex-transform-style x)
  (:mode ams-style?) x)

(tm-define (tmtex-provided-packages)
  (:mode ams-style?)
  '("amsmath"))

Tags whose conversion depends on the style (title and abstract metadata, equation, bibliography, …) are declared with the macro tmtex-style-dependent, which defines a default implementation and adds the corresponding entry to tmtex-tmstyle%; a style module only needs to overload the function, e.g. tmtex-doc-title or tmtex-make-doc-data. Other hooks are tmtex-style-init, tmtex-style-preprocess, tmtex-postprocess, tmtex-postprocess-body, tmtex-provided-packages (packages already loaded by the document class) and latex-extra-preamble.

5.Macros and the preamble

5.1.LaTeX macros introduced by TeXmacs

Many TeXmacs tags are exported to LaTeX commands which do not exist in standard LaTeX, such as \tmstrong, \tmop, \tmtextbf, or environments such as tmindent. Their definitions are kept in smart tables (

utils/library/smart-table.scm

) in

convert/latex/latex-define.scm

:

latex-texmacs-macro

Macro bodies, written as LaTeX strees in which the integers 1, 2, … denote the arguments, e.g. (tmstrong (textbf 1)). The special forms (!recurse x) and (!translate s) expand a nested macro and translate a string into the document language.

latex-texmacs-environment

Environment bodies, where --- stands for the body of the environment.

latex-texmacs-preamble, latex-texmacs-env-preamble

Arbitrary preamble material needed for a command resp. environment.

The arity of these macros is declared in

latex-texmacs-drd.scm

(groups latex-texmacs-0%, latex-texmacs-1%, …, latex-texmacs-environment-0%, etc., which feed latex-texmacs-arity%). Entries of a smart table may be conditional;

latex-overload.scm

uses this to change definitions according to the LaTeX document class or packages, for instance

(smart-table latex-texmacs-macro
  (:require (latex-depends? "amsthm"))
  (qed #f))

The preamble is computed by latex-preamble in

latex-tools.scm

, called from texout-file. It returns the document class options, the \usepackage lines, the page size settings and the macro definitions:

If the option "texmacs->latex:use-macros" is off, no definitions are written: latex-expand-macros substitutes the macro bodies directly into the document, which yields a self-contained but less readable LaTeX file.

5.2.User macros

Macro definitions in the document ((assign "name" (macro …)) in the body or in a hide-preamble) are converted by tmtex-assign into \newcommand (or \providecommand if the name is a known LaTeX command), with arg replaced by #1, #2, … (tmtex-args). Since LaTeX commands are either text or math commands, tmtex-pre uses the statistics of init-mode-stats to convert the body in the mode in which the macro is mostly used, and protects it with \text or \ensuremath if it is used in both modes (mode-protect). If "texmacs->latex:expand-user-macros" is on, the definitions are not exported and the macros are expanded by exec_latex instead.

6.Text, symbols and encodings

Strings are converted by tmtex-string, which splits them into characters and TeXmacs symbols <…> and dispatches to tmtex-text-list or tmtex-math-list according to the mode. Special characters (#$%&_{}) are escaped, the Cork ligature characters (quotes, dashes) are written as TeX ligatures, and in math mode sequences of letters which form a known operator (latex-operator%) become \sin, \log, …, while other multi-letter sequences are wrapped in \tmop.

Symbols are handled by tmtex-token-sub: a few special cases are listed in latex-special-symbols% and latex-text-symbols%, the prefixes up-, bbb-, cal-, frak-, b- are mapped to \mathrm, \mathbb, \mathcal, \mathfrak, \tmmathbf, Unicode characters <#XXXX> become !widechar, and other symbols become the LaTeX command with the same name (hyphens removed) provided that it occurs in the symbol table latex-symbol% (

latex-symbol-drd.scm

and

latex-texmacs-drd.scm

). Unknown symbols are reported on the console (non converted symbol) and exported as \nonconverted{…}.

The option "texmacs->latex:encoding" selects how non-ASCII characters are written:

"ascii" (default)

Characters are converted to TeX commands (string-convert from "UTF-8" to "LaTeX" in output-tex); fontenc is loaded when needed for Cyrillic or extended Latin characters.

"cork"

Characters are output in the Cork encoding and made active with \catcode definitions in the preamble.

"utf-8"

Characters are output in UTF-8 and \usepackage[utf8]{inputenc} is added. This encoding is forced for Chinese, Japanese and Korean documents (tmtex-cjk-document?), which also use the CJK package.

The language of the document gives rise to a babel package option; language changes inside the document are handled by tmtex-make-lang.

7.Mathematics

Formulas are converted in the mode "math": math and (with "mode" "math" …) produce !math, equation* produces !eqn, equation the equation environment, and the equation arrays (eqnarray*, align, …) array or tabular constructions through tmtex-eqnarray and tmtex-table-apply. Before the conversion, tmtm-match-brackets matches large brackets; the handlers tmtex-left, tmtex-mid, tmtex-right and tmtex-big produce \left, \middle, \right and big operators, and pre-brackets turns large brackets back into ordinary ones where this is possible. Scripts are converted to !sub and !sup, frac to \frac, sqrt to \sqrt, wide accents by tmtex-wide and tmtex-wide-star. The semantic math markup (math-ordinary, math-relation, …) is mapped to \mathord, \mathrel, etc.

Tables are converted by tmtex-table-apply with the help of the table parser of

convert/tools/old-tmtable.scm

. The table tmtex-table-props% gives, for each tabular macro (tabular, matrix, choice, …), the material to put before and after, the default alignment and whether borders are used.

8.Images and graphics

image is handled by tmtex-image. A linked image in a format which LaTeX can include (eps, pdf, png, jpg) is included with \includegraphics; other images are converted into a .pdf or .eps file (according to the preference "native pdf") with convert-to-file. Sizes are translated into \resizebox or \scalebox.

TeXmacs graphics (graphics), draw-over, draw-under, trees and the content of (specific "image" …) have no LaTeX counterpart; they are typeset by TeXmacs itself into a picture file by tmtex-eps, which calls print-snippet and computes the bounding box so that the picture is aligned on the baseline (\raisebox around \includegraphics). The picture files are named base-n.pdf (or .eps) next to the target file, where base is the name of current-save-target without the suffix (tmtex-eps-names). When a conversion writes no file (e.g. for snippets, or the formulas for MathJax in an HTML file), loose-image-names puts the pictures in the temporary folder under an absolute name; a copy to the clipboard keeps them next to the document, or else in $TEXMACS_HOME_PATH/system/images, as image-hash.

9.Bibliographies, citations and indexes

cite and its variants are exported as \cite, or as the natbib commands when the package cite-author-year is used (mode natbib-package%). bibliography is handled by tmtex-bib and tmtex-biblio: by default the bibliography which was generated in TeXmacs is exported as a thebibliography environment with \bibitem entries; if the option "texmacs->latex:indirect-bib" is on, the commands \bibliographystyle and \bibliography are written instead, so that BibTeX has to be run on the LaTeX side. Labels and references become \label, \ref and \pageref; the-index becomes \printindex (and \makeindex is added to the preamble), the table of contents \tableofcontents; glossaries have dedicated handlers.

10.Options

The options of the converters from texmacs-stree to latex-stree and to latex-document are declared in

init-latex.scm

and appear in the menu tab Convert (sub-tab LaTeX) of the preferences dialog. Some are passed in the option list of the converter, some are read directly as preferences.

Option Default Effect
texmacs->latex:replace-style on Map unknown styles to article.
texmacs->latex:expand-macros on Expand macros with exec_latex.
texmacs->latex:expand-user-macros off Expand user macros instead of exporting them.
texmacs->latex:indirect-bib off Use \bibliography.
texmacs->latex:use-macros on Define TeXmacs macros in the preamble.
texmacs->latex:encoding ascii ascii, cork or utf-8.
texmacs->latex:source-tracking off Add source tracking information.
texmacs->latex:conservative on Reuse the original LaTeX source.
texmacs->latex:transparent-source-tracking on Check that markers do not change the output.
texmacs->latex:attach-tracking-info on See below.

Table 1. Options of the LaTeX export.

"texmacs->latex:expand-macros", "texmacs->latex:source-tracking", "texmacs->latex:conservative" and "texmacs->latex:transparent-source-tracking" are read with get_preference in C++, and "texmacs->latex:expand-user-macros" is read with get-preference in tmtex-file and tmtex-env-patch; for these options, a value passed explicitly to convert has no effect. The other options are read from the option list by tmtex-initialize. The preference "texmacs->latex:attach-tracking-info" appears in the preferences dialog, but is not read anywhere in the conversion code of this version; likewise

init-latex.scm

declares a preference "texmacs->latex:transparent-tracking" which is not used.

11.How to add support for a new tag

Suppose that a style file defines a macro my-note with one argument, which should become \mynote{…} in LaTeX, with a definition in the preamble.

  1. Without any work, the default rule already produces \mynote{…}, provided that the tag occurs literally in the document (so that tmtex-env-patch protects it from expansion), but the generated file does not define \mynote.

  2. To provide a definition, add an entry to the smart table latex-texmacs-macro in

    latex-define.scm

    , e.g. (mynote (footnote 1)), and declare its arity by adding mynote to latex-texmacs-1% in

    latex-texmacs-drd.scm

    . If the definition requires a package, add an entry to latex-needs% in

    latex-drd.scm

    .

  3. If the conversion is not a plain renaming, add an entry to tmtex-tmstyle% in

    tmtex.scm

    , for instance (my-note (,tmtex-my-note 1)), with a handler (define (tmtex-my-note s l) …) which receives the tag name and the list of unconverted arguments and returns a LaTeX stree; use tmtex to convert the arguments. For a new primitive, add an entry to tmtex-primitives% instead (the handler then only receives the arguments).

  4. If the tag must be expanded by TeXmacs before the export (because its LaTeX rendering is too hard), add its name to tmtex-always-expand, or give it a tmlatex-my-note variant in the style file.

  5. For the import in the other direction, see importing LaTeX: the command \mynote is recognized as a TeXmacs extension because it belongs to latex-texmacs%, and a rule converting it back has to be added to latex_command_to_tree.

12.Testing and debugging

13.Known limitations

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".