![]() |
Importing LaTeX | ![]() |
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
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.
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:
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).
Symbols (
latex-symbol-drd.scm
, including the symbols of amssymb, stmaryrd, wasysym, upgreek, …), converted into the TeXmacs symbol with the same name.
Font and paragraph declarations and commands such as \bf, \textbf, \centering.
Environments; math environments switch the parser to math mode, enunciations are theorem-like environments.
Lengths, counters and names (such as \LaTeX).
Operators such as \sin and control commands.
Commands which are dropped (latex-ignore%: \relax, \sloppy, …).
Commands and environments which are rendered as pictures (latex-as-pic%: pspicture, tikzpicture, \xymatrix).
The extra commands which the TeXmacs exporter introduces (latex-texmacs%, e.g. \tmstrong); this allows a round trip of exported documents.
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.
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.
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:
Text is a string; a sequence is a concat.
A command application is a tuple whose first child is the name of the command with its backslash, followed by the arguments: \frac{1}{2} becomes (tuple "\frac" "1" "2"). The parser reads as many arguments as given by latex_arity. If an optional argument is present, it is stored as the first argument and a star is appended to the name: \sqrt[3]{x} becomes (tuple "\sqrt*" "3" "x").
Environments are not nested: \begin{proof} and \end{proof} become (tuple "\begin-proof") and (tuple "\end-proof") in the flow; matching is done afterwards.
Subscripts and superscripts become \<sub> and \<sup> applications, math shifts $ and $$ become \begin-math / \end-math and \begin-displaymath / \end-displaymath pairs.
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).
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.
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.
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); |
Removes spaces and newlines which TeX would ignore (
fromtex.cpp
).
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
).
The main translation, see below.
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).
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.
Matches the flat begin/end pairs into environments, closing and reopening environments which are improperly nested.
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.
Floats and captions, hyperlinks and various clean-ups (sections and labels, nested with, vertical space).
Corrections with respect to the DRD and the conventions for math.
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.
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.
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.
Import the constructs of type "as-picture" as pictures (requires a working LaTeX installation).
All these options are read with get-preference or get_preference; the option list passed to the converter is ignored by latex-document->texmacs.
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.
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.
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).
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.
Open a .tex file with File\(\rightarrow\)Import\(\rightarrow\)LaTeX or paste a LaTeX snippet (Edit\(\rightarrow\)Paste from\(\rightarrow\)LaTeX).
In a Scheme session, (latex->texmacs (parse-latex "$\\frac{1}{2}$")) shows the result for a snippet; (parse-latex s) alone shows the parsed LaTeX, which is usually the first thing to check when an import goes wrong.
The commented cout statements in latex_to_tree print the tree after each stage.
The idempotence tests of
convert/latex/test-tmtex.scm
((test-tmtex)) also exercise the import.
LaTeX is a programming language; the importer only understands the commands in its tables, user definitions of a reasonable form and some packages. Low-level TeX programming (\catcode, conditionals, \expandafter, …) is not interpreted.
Included files are only expanded when they are found relative to the imported file.
Errors in the source are not reported; the parser tries to recover heuristically, which can produce unexpected results.
Layout-oriented constructs (explicit spacing, boxes, tabular tricks) are often imported in a simplified form; see also the user documentation limitations of the current LaTeX converter.