![]() |
The typesetting environment | ![]() |
The typesetting environment is an object of class edit_env, a reference-counted pointer to an edit_env_rep (
Typeset/env.hpp
). Each editor owns exactly one environment (the member env of edit_typeset_rep), which is shared by the typesetter of that editor (typesetter_rep::env) and by all its bridges and concaters. Temporary environments are also created for computing the environment of a style (compute_env_and_drd, see below) and in a few other places.
The most important data members are:
A reference to the data relation descriptor of the buffer (the member drd of editor_rep). The environment uses it for drd-props and for accessibility tests, and the DRD is in turn largely computed from the macros of the environment; see the data relation descriptor.
(private) The current values of all variables. Macros are ordinary values of the form (macro x1 … xn body), (xmacro x body) or (func …).
(private) The old values of variables written with the monitored write methods since the last local_start. It is used by bridges to compute and cache the net effect of a paragraph on the environment.
The stack of macro argument frames. The head of the list binds the parameters of the innermost macro which is being expanded to the corresponding argument trees.
A parallel stack which binds the same parameters to the inverse paths of the argument trees in the source document (or to a decoration path, when the argument is not part of the document).
A reference to the global table default_var_type which assigns an Env_* category to each built-in variable (see update below).
The master file of the buffer, the file currently being typeset (which differs inside an include) and whether that file is trusted for the execution of extern scripts.
References to the tables of labels, auxiliary data and attachments of the buffer (or of the project), which are read and written by primitives like set-binding and get-binding.
Information collected while typesetting, such as missing references or loci.
The remaining members (fn, pen, lan, mode, index_level, page_width, point_style, …) are C++ caches of the values of certain environment variables, which the typesetter reads directly for speed. They are kept up to date by the update methods.
The member src (a hashmap<string,path> initialized to a decoration path) is declared but does not appear to be used anywhere else in the code.
tree read (string s)
read returns the current value of s (or UNINIT if s is undefined) and provides tests whether s is defined. The helpers get_bool, get_int, get_double, get_string, get_length, get_vspace and get_color convert the value; note that they return a default value (false, 0, "") when the value is a compound tree, and that they do not evaluate the value.
void write (string s, tree t)
void write_update (string s, tree t)
void monitored_write (string s, tree t)
The _update variants call update (s) after writing, so that the C++ caches are recomputed. The monitored_ variants first record the old value of s in back (using hashmap::write_back, which only records the first old value), so that the change can be undone or cached by the enclosing bridge. None of these methods evaluates t.
Evaluates t with exec and, if the result differs from the current value, stores it in a monitored way and calls update (s). This is the implementation of the assign primitive.
tree local_begin (string s, tree t)
local_begin writes t into s, updates and returns the old value, which must later be restored with local_end. This is the idiom used by the typesetter itself for temporary changes such as the script level (local_begin_script) or the extents of a box (local_begin_extents). Such changes are not monitored.
void update (string s)
update (s) dispatches on var_type[s]: for Env_User and Env_Fixed nothing happens; for Env_Font, Env_Font_Size the font fn is recomputed by update_font; for Env_Mode the mode, language and font are recomputed; for Env_Color, Env_Page, Env_Frame and so on the corresponding update_* method is called. update () recomputes all caches. The table default_var_type is filled by initialize_default_var_type in
env_semantics.cpp
; all variables which are not listed there, and in particular all macros and user variables, are of category Env_User.
When you add a new built-in environment variable whose value must be cached in a C++ field of edit_env_rep, you have to declare its name in
Data/Drd/vars.hpp
and
vars.cpp
, give it a default value in initialize_default_env (
env_default.cpp
), assign it a category in initialize_default_var_type and handle that category in both update methods.
Variables in TeXmacs are dynamically scoped. There is a single environment, which is modified while the typesetter or the evaluator traverses the document, and every tree sees the values which were current at the moment it is processed:
with evaluates the new values, writes them with write_update, processes its body and then restores the old values in reverse order (edit_env_rep::exec_with, concater_rep::typeset_with, bridge_with_rep::my_typeset).
assign changes the value for the remainder of the traversal. There is no automatic restoration at the end of a macro body or of a paragraph: an assignment inside a macro remains visible after the macro application, and an assignment in one paragraph is visible in all following paragraphs. This is how counters and style definitions work.
A macro body is expanded in the environment of the call site, not of the definition site: (macro "x" (value "font-size")) yields the font size at the place where the macro is used.
Macro parameters are not environment variables. They are bound in a separate stack of frames (macro_arg), and arg always looks in the innermost frame only (see the evaluator).
Because assign has global effect, the typesetter needs to know how each paragraph changes the environment, in order to be able to skip paragraphs which do not need to be re-typeset. This is implemented by the monitored writes and by three methods of edit_env_rep, which are called by bridge_rep::typeset (
Typeset/Bridge/bridge.cpp
) around the typesetting of a bridge:
hashmap<string,tree> prev_back (UNINIT);
…
env->local_start (prev_back);
my_typeset (desired_status);
env->local_update (ttt->old_patch, changes);
env->local_end (prev_back); |
local_start saves the current back table and starts a fresh one; during my_typeset, every monitored write records the original value of the variable in back. local_update computes from back and the current env the table changes of the new values of all variables which were modified (invert (back, env)), and updates the typesetter's old_patch. local_end merges the recorded old values into the saved outer table, so that the outer bridge also sees the changes. The next time the bridge is found to be valid, the typesetter does not re-typeset it but simply replays its changes with monitored_patch_env (changes).
Only writes which are meant to persist must be monitored: assign and exec_until_* use monitored writes, whereas with, whose effect is undone at the end, uses plain write_update during typesetting. When you write C++ code which changes the environment in a persistent way, use a monitored write, or cached paragraphs will not reproduce the change.
The global table default_env is filled once by initialize_default_env in
Typeset/Env/env_default.cpp
. It contains the default values of all built-in variables (as strings or trees), and also a few built-in macros, for instance
tree identity_m (MACRO, "x", tree (ARG, "x"));
tree tabular_m (MACRO, "x", tree (TFORMAT, tree (ARG, "x")));
…
env (IDENTITY) = identity_m; // identity macro
env (TABULAR) = tabular_m; // tabular macro |
The constructor of edit_env_rep copies default_env, calls style_init_env (which reads dpi, page flexibility and the first page number and resets back) and update (). write_default_env resets the whole environment to a copy of default_env. The built-in variables are documented for users in built-in environment variables.
Lengths are strings such as 2cm, 1.5fn or 0.5par, or trees of the form (tmlen def) or (tmlen min def max) whose entries are numbers of internal units (SI). The conversion is done by as_tmlen in
Typeset/Env/env_length.cpp
:
parse_length (s (start, n), len, unit);
if (unit == "error" || is_empty (unit)) {
return tree (TMLEN, "0");
} else {
return tmlen_times (len, as_tmlen (exec (compound (unit * "-length"))));
} |
In other words, a unit u is the value of the tag u-length. For the standard units this is a built-in primitive (cm-length is evaluated by exec_cm_length, fn-length by exec_fn_length, etc.), which uses the cached C++ fields of the environment (such as inch, magn_len or the metrics of the current font fn). Since exec expands macros, a style file can define new units by defining macros, for instance (assign "foo-length" (macro "3mm")); this is also why lengths like par or pag depend on the environment in which they are evaluated. as_length returns the default value of the tmlen as an SI; the variants as_hspace and as_vspace keep the stretchability. Length arithmetic (tmlen_plus, tmlen_times, tmlen_over, …) is used by the arithmetic primitives plus, times and so on when their arguments are lengths. See also TeXmacs lengths.
The initial environment of a buffer is computed from its style (the style tuple of the document) and from its initial environment (the initial collection). This happens in
Edit/Editor/edit_typeset.cpp
:
void
edit_typeset_rep::typeset_preamble () {
env->write_default_env ();
typeset_style_use_cache (the_style);
env->update ();
env->read_env (stydef);
env->patch_env (init);
env->update ();
env->read_env (pre);
drd->heuristic_init (pre);
} |
The environment after loading the style is saved in stydef, the environment after adding the initial values in pre. Finally the DRD is refined heuristically using the macros in pre. Before every typesetting pass, typeset_prepare resets the environment to pre:
env->write_default_env ();
env->patch_env (pre);
env->style_init_env ();
env->update (); |
so that assignments made in the body of the document during the previous pass do not leak into the next one.
typeset_style_use_cache first calls preprocess_style (
Data/Document/new_style.cpp
), which turns an atomic style into a tuple and replaces each package name p by the absolute name of a file p.ts found in the directory of the document or one of its ancestors, if there is such a file (this allows documents to override standard packages locally). It then looks up the style in a two-level cache (style_get_cache): an in-memory table, and files in $TEXMACS_HOME_PATH/system/cache whose names are derived from the style tuple. The cache stores, for each style tuple, the resulting environment and the local part of the DRD (drd_info_rep::get_locals).
On a cache miss, get_style_env and get_style_drd call compute_env_and_drd, which
creates a fresh drd_info named none which inherits from std_drd, and a fresh edit_env with dummy reference tables;
evaluates (use-package p1 … pn) in that environment;
reads back the resulting environment with read_env and runs drd_info_rep::heuristic_init on it;
stores both in the style_data_rep tables style_cached and drd_cached.
A table style_busy protects against styles which (directly or indirectly) require themselves. edit_env_rep::exec_use_package is the workhorse: it resolves each package in $TEXMACS_STYLE_PATH (and in the directory of the document), parses it, extracts the body and evaluates it with exec after applying filter_style, which strips the style-with, style-only, active and inactive tags used for the presentation of style sources. Since a style file is just a document whose body consists of assign statements (and nested use-package, use-module, drd-props …), evaluating it fills the environment with the macros it defines. Note that it is evaluated, not typeset.
Finally use_modules evaluates the Scheme modules listed in the variable THE_MODULES (the-modules), which is extended by every use-module primitive (edit_env_rep::exec_use_module).
The style caches are cleared by style_invalidate_cache, called by tm_server_rep::style_clear_cache (Scheme function style-clear-cache), which also removes the cache files and re-initializes the styles of all views. If you change a .ts file during development and nothing happens, this is the cache at work.
Rewritten by with_package_definitions (
Texmacs/Data/new_buffer.cpp
) into a with which binds all variables assigned at the top level of the package (loaded with load_style_tree, cached in style_tree_cache). Nested packages and non-assign statements are ignored, as the FIXME there admits.
The included document is loaded by load_inclusion (cached in document_inclusions) and typeset in place, with cur_file_name and secure temporarily set according to the included file (concater_rep::typeset_include, bridge_rewrite_rep::my_typeset).
Many editing routines need the value of an environment variable at the cursor position or at some other path, for instance to know whether the cursor is in math mode. This is computed by edit_typeset_rep::typeset_exec_until (path p), which caches the results per path in the table cur (up to 25 entries). The public accessors get_env_value, get_env_string, defined_at_cursor and get_full_env are built on it.
There are two strategies:
The exact strategy calls exec_until (ttt, p / rp) (
Typeset/Bridge/typesetter.cpp
), which delegates to the bridges; valid bridges replay their cached changes and invalid ones call the partial evaluator edit_env_rep::exec_until described in the evaluator.
When enable_fastenv is set (from the preference fast environments through the Scheme function set-fast-environments), a much cheaper approximation is used: descending along the path, it only executes top-level assign statements and preambles (restricted_exec), handles table formats (table_descend) and, for any other tag, applies the environment which the DRD associates to the child through drd_info_rep::get_env_child. Macro bodies are not traversed; only the environment changes which the DRD heuristics could infer from the macro definitions are taken into account.
In source mode (outside the preamble), define_style_macros in addition writes all top-level macro definitions of the document into the environment. The variant var_texmacs_exec (the Scheme function texmacs-exec*) evaluates a tree in the environment at the cursor, whereas texmacs_exec (texmacs-exec) uses the current state of the environment.