GNU TeXmacsUser manualReferenceAboutEnglish
Importing LaTeX

1.Overview

The import of LaTeX is almost entirely written in C++, in the directory

Data/Convert/Tex

. The Scheme side only declares the converters (

convert/latex/init-latex.scm

) and provides the tables which describe the LaTeX commands (

convert/latex/latex-command-drd.scm

,

latex-symbol-drd.scm

,

latex-texmacs-drd.scm

,

latex-drd.scm

). A complete LaTeX document is imported by

(tm-define (latex-document->texmacs x . opts)
  (if (list-1? opts) (set! opts (car opts)))
  (with as-pic (== (get-preference "latex->texmacs:fallback-on-pictures") "on")
    (conservative-latex->texmacs x as-pic)))

The C++ function conservative_latex_to_texmacs and the function tracked_latex_to_texmacs which it calls implement the source tracking and conservative import described in source tracking and conservative conversion. When these features are disabled (the default), they reduce to

tree latex_document_to_tree (string s, bool as_pic)
(import a complete LaTeX document)

Defined in

fromtex_post.cpp

. Opens a new layer of the command tables (see below), parses the document with parse_latex_document (s, true, as_pic), renders the parts which must be imported as pictures (latex_fallback_on_pictures, only if as_pic), converts the parsed LaTeX with latex_to_tree and closes the layer.

Snippets (pasting LaTeX) are imported by parse-latex followed by latex->texmacs, that is parse_latex and latex_to_tree. The whole import thus consists of two phases: the parser, which turns the string into parsed LaTeX, and the converter, which turns parsed LaTeX into a TeXmacs tree. Both phases need to know the type and the arity of the LaTeX commands.

2.Knowledge about LaTeX commands

The type and arity of a command are obtained with

string latex_type  (string cmd);
int    latex_arity (string cmd);

declared in

Tex/convert_tex.hpp

and implemented in

inittex.cpp

. The argument is the command with its backslash, and environments are represented as \begin-name and \end-name. These functions first look into the hash maps command_type and command_arity (and command_def for the definitions), which contain the commands defined by the document being parsed, and otherwise call the Scheme functions latex-type and latex-arity of

latex-drd.scm

(the results are cached by hashfunc objects). The three maps are rel_hashmap objects: they are extended at the beginning of a parse and merged or shortened at the end, so that definitions do not leak from one import to the next.

latex-type returns one of the following strings, according to the logical group in which the command occurs:

"command"

Ordinary commands (latex-command%, with arities from latex-command-0%, latex-command-1%, …; the groups latex-command-1*% etc. contain commands with an optional argument).

"symbol", "big-symbol"

Symbols (

latex-symbol-drd.scm

, including the symbols of amssymb, stmaryrd, wasysym, upgreek, …), converted into the TeXmacs symbol with the same name.

"modifier"

Font and paragraph declarations and commands such as \bf, \textbf, \centering.

"environment", "math-environment", "enunciation", "list"

Environments; math environments switch the parser to math mode, enunciations are theorem-like environments.

"length", "counter", "name"

Lengths, counters and names (such as \LaTeX).

"operator", "control"

Operators such as \sin and control commands.

"ignore"

Commands which are dropped (latex-ignore%: \relax, \sloppy, …).

"as-picture"

Commands and environments which are rendered as pictures (latex-as-pic%: pspicture, tikzpicture, \xymatrix).

"texmacs"

The extra commands which the TeXmacs exporter introduces (latex-texmacs%, e.g. \tmstrong); this allows a round trip of exported documents.

"undefined"

Unknown commands.

The parser adds its own types for commands defined in the document: "user" (macros defined by \def or \newcommand), "enunciation" (environments declared by \newtheorem), "length" (declared by \newlength), and internal types such as "side-effect!", "begin-end!", "defined-env!" and "replace" for definitions which are substituted during the parse. A negative arity means that the first argument is optional.

3.The parser

3.1.Pre-processing

tree parse_latex (string s, bool change, bool as_pic)
(parse a LaTeX string)

Defined at the end of

parsetex.cpp

. Converts line endings (dos_to_better), detects the language from the babel options (get_latex_language) and the input encoding from inputenc (get_latex_encoding, latex_encoding_to_iconv), converts the string to UTF-8 (with a heuristic western_to_utf8 when no encoding is declared), converts LaTeX accent commands into characters, runs a latex_parser and converts the accented characters back to the internal Cork encoding (accented_to_Cork). If a language was found, the result is wrapped into (!language tree lan). parse_latex_document wraps the result into (!file tree).

latex_parser::parse (string s, int change) first cuts the source at strategic places (before \begin{document}, sectioning commands, \newcommand, \def at brace depth zero), so that an error in one part does not spoil the rest. While cutting, it removes the block of macro definitions written by the TeXmacs exporter (between %%%%%%%%%% Start TeXmacs macros and %%%%%%%%%% End TeXmacs macros) and inlines the files loaded by \input, \include and \usepackage when they can be found relative to the current file (see get_file_focus), except for a list of well-known packages (skip_expansion) whose commands are known to the tables anyway.

3.2.Parsed LaTeX

The pieces are parsed by the recursive descent methods of latex_parser: parse (text up to a stop string), parse_backslash, parse_command, parse_unknown, parse_symbol, parse_length, parse_verbatim and so on. The result is a C++ tree with the following conventions:

The parser keeps the current mode in the pseudo-entry command_type ("!mode") ("text" or "math"), which matters for the arguments of commands such as \text (is_text_argument).

3.3.Definitions in the document

When the parser meets \def, \newcommand, \renewcommand, \providecommand, \DeclareMathOperator (all normalized to \def), \newenvironment, \newtheorem, \newlength, etc., it records the type, arity and body of the new command in command_type, command_arity and command_def, so that later occurrences are parsed with the right number of arguments. The definitions themselves are kept in the tree and later become TeXmacs macro definitions in the preamble of the imported document. Only special definitions are substituted during the parse: shortcuts for \begin/\end, definitions with side effects, and (when importing as pictures) definitions whose body must be rendered as a picture.

3.4.Pictures

If the preference "latex->texmacs:fallback-on-pictures" is on, commands and environments of type "as-picture" are stored as (tuple "\latex_preview" name source). After parsing, latex_fallback_on_pictures (

fromtex.cpp

) merges the beginning and end of environments, calls latex_preview (

Plugins/LaTeX_Preview/latex_preview.cpp

), which runs LaTeX on the fragments together with the preamble of the document, and replaces them by picture-mixed trees containing both the picture and the original source.

4.From parsed LaTeX to TeXmacs

4.1.The stages

The driver is latex_to_tree (tree t) in

fromtex_post.cpp

. Abridged, it reads

tree t1= kill_space_invaders (t0);
…
tree t2= is_document? filter_preamble (t1): t1;
tree t3= parsed_latex_to_tree (t2);
tree t4= finalize_document (t3);
tree t5= is_document? finalize_preamble (t4, style): t4;
tree t6= handle_matches (t5);
…
tree t7= upgrade_tex (t6);
tree t8= finalize_floats (t7);
tree t9= finalize_misc (t8);
…
tree t10= finalize_textm (t9);
tree t11= drd_correct (std_drd, t10);
…
tree t13= latex_correct (t12);
tree t14= guess_missing (t13);
tree t15= postprocess_metadata (t14);
kill_space_invaders

Removes spaces and newlines which TeX would ignore (

fromtex.cpp

).

filter_preamble

Moves the preamble into a hide-preamble environment, keeps the document class, and collects the title, authors and abstract with collect_metadata (

metadata.cpp

), which has variants for the classes of various publishers (

metadata-acm.cpp

,

metadata-ams.cpp

,

metadata-elsevier.cpp

,

metadata-ieee.cpp

,

metadata-revtex.cpp

,

metadata-springer.cpp

).

parsed_latex_to_tree

The main translation, see below.

finalize_document, finalize_layout

Builds the paragraph structure (make_paragraphs): blank lines become paragraph breaks, and display environments, lists and sections are put in separate paragraphs. Also handles algorithms (finalize_algorithms) and matrices (finalize_pmatrix).

finalize_preamble

Determines the style from \documentclass, drops \usepackage, converts \bibliography (loading the .bbl file next to the source if it exists) and drops redefinitions of standard theorem environments.

handle_matches

Matches the flat begin/end pairs into environments, closing and reopening environments which are improperly nested.

upgrade_tex

A selection of the upgrade routines of

Data/Convert/Texmacs/upgradetm.cpp

which turn the old-style markup (apply, begin, set/reset, …) produced so far into modern TeXmacs markup.

finalize_floats, finalize_misc, finalize_textm

Floats and captions, hyperlinks and various clean-ups (sections and labels, nested with, vertical space).

drd_correct, latex_correct, simplify_correct

Corrections with respect to the DRD and the conventions for math.

guess_missing, postprocess_metadata

Adds missing definitions and structures the metadata (doc-data, doc-author, …) with

metadata_post.cpp

.

For a complete document, the result is assembled into a TeXmacs file whose style is the LaTeX class if a TeXmacs style with this name exists (and generic otherwise), followed by the package std-latex (except for a few classes) and by cite-author-year if natbib was detected. The language and a font for Chinese, Taiwanese and Russian are stored in the initial environment.

4.2.The translation of commands

parsed_latex_to_tree (abbreviated l2e in

fromtex.cpp

) dispatches on the shape of the tree: strings are passed to latex_symbol_to_tree, concat nodes to latex_concat_to_tree (which also deals with font declarations whose scope extends to the end of the group) and tuples to latex_command_to_tree.

latex_symbol_to_tree handles commands without arguments: special characters, the commands of type "symbol" (converted to the TeXmacs symbol <name>, with a few exceptions such as \lnot and the upgreek letters), nullary modifiers (\bf, \centering, …) which become set nodes, and so on.

latex_command_to_tree is a long sequence of tests of the form

if (is_tuple (t, "\\frac", 2)) return tree (FRAC, l2e (t[1]), l2e (t[2]));
if (is_tuple (t, "\\sqrt*", 2)) return tree (SQRT, l2e (t[2]), l2e (t[1]));
…
// Start TeXmacs specific markup
if (is_tuple (t, "\\tmstrong", 1)) return tree (APPLY, "strong", l2e (t[1]));

The arguments are converted recursively with l2e; arguments which must be kept as text use parsed_text_to_tree (t2e) and string_arg. Commands which are not handled explicitly fall through to the end of the function, where (tuple "\cmd" args) becomes (apply "cmd" args) and environments become begin nodes; upgrade_tex later turns these into ordinary TeXmacs tags. An unknown LaTeX command \foo{x} thus gives the tag foo with one argument, which is displayed in red if no macro foo is defined. Packages which are often used by journals, such as the theorem environments or algorithm2e, have dedicated code.

5.LaTeX class and style files

The format latex-class (suffixes ltx, sty, cls) is imported by latex_class_document_to_tree (

fromcls.cpp

). It sets the flag textm_class_flag (which makes the parser accept length assignments in TeX syntax), imports the file as a document and filters the result with latex_class_filter into a TeXmacs style file.

6.Options

"latex->texmacs:fallback-on-pictures" (default "on")

Import the constructs of type "as-picture" as pictures (requires a working LaTeX installation).

"latex->texmacs:source-tracking", "latex->texmacs:conservative", "latex->texmacs:transparent-source-tracking" (default "off")

See source tracking and conservative conversion.

All these options are read with get-preference or get_preference; the option list passed to the converter is ignored by latex-document->texmacs.

7.How to add support for a new command

  1. Declare the command in the tables, so that the parser reads the right number of arguments: add it to the appropriate group of

    latex-command-drd.scm

    (e.g. latex-command-2% for a command with two arguments, latex-command-1*% for one argument plus an optional one, latex-environment-0% for an environment), or to

    latex-symbol-drd.scm

    for a symbol. If the corresponding TeXmacs symbol has the same name, nothing else is needed for symbols.

  2. Add a rule to latex_command_to_tree in

    fromtex.cpp

    which builds the TeXmacs tree, e.g.

    if (is_tuple (t, "\\mycmd", 2))
      return compound ("my-tag", l2e (t[1]), l2e (t[2]));

    Without such a rule, the command is imported as a tag with the same name (without backslash), which may be sufficient if a macro with this name is defined in a style package.

  3. If the command introduces a block structure (an environment which should be a separate paragraph), check the lists of block environments in

    fromtex.cpp

    and

    fromtex_post.cpp

    (is_block_environnement, finalize_layout).

  4. For commands which the TeXmacs exporter itself produces, add them to

    latex-texmacs-drd.scm

    and convert them back in the section Start TeXmacs specific markup of latex_command_to_tree.

8.Testing

9.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".