![]() |
Internals of the TeXmacs file system | ![]() |
The TeXmacs file system (tmfs) is a virtual file system whose documents do not live on disk, but are produced on demand by Scheme code. Any URL starting with tmfs:// belongs to it. The implementation is split between two layers:
The C++ file layer (
System/Classes/url.cpp
,
System/Files/file.cpp
,
System/Files/web_files.cpp
) recognizes tmfs URLs and, instead of accessing the disk, calls a small number of Scheme entry points: tmfs-load, tmfs-save, tmfs-permission?, tmfs-format, tmfs-title and tmfs-can-autosave?.
The Scheme module
kernel/texmacs/tm-file-system.scm
implements these entry points by dispatching on the class of the URL (its first component) to handlers registered by other modules, with default behaviors for missing handlers. Some further operations (dates, removal, autosave, masters) are only used from Scheme, mainly by
texmacs/texmacs/tm-files.scm
.
Since all file operations of TeXmacs go through the same C++ routines (load_string, save_string, is_of_type, …), a tmfs document can be loaded into a buffer, saved, included, linked to or used as an image just like an ordinary file. The paths in this document are relative to
src/src/
for C++ files and to
src/TeXmacs/progs/
for Scheme files.
TeXmacs represents URLs as trees (see the URL system). When a string is converted into a URL, the generic constructor url_general in
System/Classes/url.cpp
checks for known protocol prefixes. For tmfs:// it calls
static url
url_tmfs (string name) {
url u= url_get_name (name);
return url_root ("tmfs") * u;
} |
so that tmfs://help/normal/tm/doc/main/man-manual.en.tm becomes the concatenation of the root tmfs with the names help, normal, tm, … Nothing else is interpreted: query strings such as type=module&what=doc.apidoc are simply parts of names. The following predicates are declared in
System/Classes/url.hpp
:
Whether u is the root tmfs itself.
Whether u is a tmfs URL (or an alternative of such URLs). Exported to Scheme as url-rooted-tmfs?.
Whether u is a tmfs URL whose class is sub_protocol. Exported to Scheme as url-rooted-tmfs-protocol?. For instance,
Texmacs/Window/tm_dialogue.cpp
uses is_rooted_tmfs (buf, "part") to recognize partial documents.
tmfs URLs count as rooted URLs: relative names can be completed against them (complete in
System/Classes/url.cpp
accepts them in the same way as web URLs), which is how relative hyperlinks and images inside a generated document can work. When the directory of a tmfs document is not meaningful, a master should be provided (see below).
On the Scheme side, an URL (or its string form) is split by tmfs-decompose-name into a class and a name:
(define-public (tmfs-decompose-name name)
(if (url? name) (set! name (url->unix name)))
(if (string-starts? name "tmfs://") (set! name (string-drop name 7)))
(with i (string-index name #\/)
(list (if i (substring name 0 i) "file")
(if i (substring name (+ i 1) (string-length name)) name)))) |
The class is the first component; the name is the rest of the string, which is passed verbatim to the handlers. If there is no slash, the class defaults to "file". Classes are strings in the handler table, although lazy-tmfs-handler takes symbols.
How the name is structured is up to each handler. Two conventions are supported by helper functions in
kernel/texmacs/tm-file-system.scm
:
A name of the form var1=val1&var2=val2 is converted into an association list by query->list and back by list->query; query-ref looks up a single variable. The only escaping performed is the replacement of colons by %3A. Used by apidoc and grep.
A name made of components separated by slashes is handled with tmfs-pair?, tmfs-car, tmfs-cdr, tmfs->list and list->tmfs, which work on strings in the same way as car and cdr on lists. Most handlers use this convention, typically with a few leading parameters followed by an embedded file name.
Many handlers work on an existing file: the history or a revision of a file, a part of a document, the comments of a buffer, etc. The file is then embedded at the end of the name by url->tmfs-string and recovered with tmfs-string->url. The encoding prefixes the path with a pseudo protocol:
A file under $TEXMACS_PATH, given relatively to it. For instance tm/doc/main/man-manual.en.tm.
An absolute file name without its leading slash, as in file/home/joe/paper.tm. On Windows the colon after the drive letter is removed (strip-colon), as in file/c/Users/joe/paper.tm.
A relative file name.
A web URL or another tmfs URL, without the ://. For instance the tmfs string of tmfs://help/normal/x.tm is tmfs/help/normal/x.tm.
Strings which do not start with one of these prefixes are interpreted by tmfs-string->url as paths relative to the root directory. A typical constructor thus reads
(tm-define (tmfs-url-commit root rev)
(string-append "tmfs://commit/" rev "/" (url->tmfs-string root))) |
and the corresponding load handler decomposes its name with (tmfs-car name) (the revision) and (tmfs-string->url (tmfs-cdr name)) (the file).
File tests are implemented by is_of_type (url name, string filter) in
System/Files/file.cpp
, where filter is a string of letters. For tmfs URLs:
d (directory), l (link) and x (executable) always fail.
r calls (tmfs-permission? name "read") and w calls (tmfs-permission? name "write").
All other letters, in particular f (regular file), are ignored and therefore succeed.
Since exists is implemented as a resolution with the filter "r", url-exists? on a tmfs URL is the same as asking for read permission; the load handler is not called. file_size returns -1 and last_modified returns the smallest possible date for tmfs URLs; on the Scheme side,
texmacs/texmacs/tm-files.scm
redefines url-last-modified and url-newer? so that they use tmfs-date instead. file_format calls tmfs-format instead of guessing the format from the suffix.
Reading a file always goes through resolution and concretization, which maps a resolved URL to a local file name. For tmfs URLs, concretize_url in
System/Classes/url.cpp
calls get_from_server in
System/Files/web_files.cpp
:
url
get_from_server (url u) {
if (!is_rooted_tmfs (u)) return url_none ();
url res= get_cache (u);
if (!is_none (res)) return res;
string name= as_string (u);
if (ends (name, "~") || ends (name, "#")) {
if (!is_rooted_tmfs (name)) return url_none ();
if (!as_bool (call ("tmfs-can-autosave?", unglue (u, 1))))
return url_none ();
}
string r= as_string (call ("tmfs-load", object (name)));
if (r == "") return url_none ();
url tmp= url_temp (string (".") * suffix (name));
(void) save_string (tmp, r, true);
return tmp;
} |
In other words, the string returned by tmfs-load is written to a fresh temporary file with the same suffix, and load_string then reads this file as usual. Several consequences follow:
An empty result means failure: the URL cannot be concretized and loading fails.
The result is not cached (the call to set_cache is commented out, because handlers which fill their buffers in a delayed fashion would be cached as empty files). The load handler is therefore called each time the document is read.
Any code which needs a local copy of a file (images, inclusions, make_file in
System/Files/make_file.cpp
with the command CMD_GET_FROM_SERVER) works for tmfs too. As a special case, make_file first looks for tmfs://artwork/… files in $TEXMACS_HOME_PATH/misc.
save_string checks is_rooted_tmfs first and, for tmfs URLs, calls save_to_server, which passes the URL and the string to tmfs-save. save_to_server always reports success, so errors must be signalled by the save handler itself (for instance with set-message). append_string is not supported: it stops TeXmacs with the fatal error file not appendable.
From get_from_server; returns the serialized document.
From save_to_server.
From is_of_type, with kind equal to "read" or "write".
From file_format.
From get_from_server, for autosave names ending with ~ or #.
From propose_title in
Texmacs/Data/new_buffer.cpp
.
The complete path followed when the user opens tmfs://help/normal/tm/doc/main/man-manual.en.tm is as follows.
load-buffer (
texmacs/texmacs/tm-files.scm
) checks permissions with url-test?: the tests "f" and "r" end up in tmfs-permission?.
buffer-load calls buffer_load in
Texmacs/Data/new_buffer.cpp
, which determines the format with file_format (hence tmfs-format, by default "stm") and calls import_tree.
import_tree resolves the URL with the filter "fr" and calls load_string, which concretizes it via get_from_server and therefore tmfs-load.
tmfs-load finds the load handler of the class and calls it on the name. If the handler returns a (document …) tree rather than a string, it is converted with texmacs->stm into the stm format (Scheme representation of TeXmacs trees); any other result which is not a string is serialized with object->tmstring.
import_loaded_tree parses the string according to the format and the buffer is filled with set_buffer_tree. The buffer title is computed by propose_title, which calls tmfs-title.
Finally, load-buffer-open in
tm-files.scm
asks for (tmfs-master name) and, if it differs from the name, makes it the master of the buffer with buffer-set-master.
Handlers which (re)generate documents on request are usually opened with load-document or revert-buffer-revert. The latter reloads the buffer even if it already exists, which is the natural way to refresh generated content such as a version history or a search result.
save-buffer first checks with url-test? that the URL is writable, which invokes the permission handler with "write"; without write permission it displays You do not have write access for …. Then buffer_save exports the buffer in the format returned by file_format and calls save_string. On the Scheme side, tmfs-save converts the string back into a Scheme tree before calling the handler:
(define-public (tmfs-save u what)
(with (class name) (tmfs-decompose-name u)
(lazy-tmfs-force class)
(cond ((ahash-ref tmfs-handler-table (cons class 'save)) =>
(lambda (handler)
(handler name (convert what "stm-document" "texmacs-stree"))))
(else ((ahash-ref tmfs-handler-table (cons #t 'save)) u what))))) |
After a successful save_string, the buffer is marked as saved.
A load handler must return immediately. Handlers whose contents come from a remote server, such as those of the remote file system in
client/client-tmfs.scm
, therefore send a request, return a placeholder document, and replace the contents of the buffer when the answer arrives:
(tm-define (buffer-set-stm u doc)
(with t (tree-import-loaded-from-object doc u)
(buffer-set u t)
(buffer-pretend-saved u))) |
The same technique may be used for any computation which takes time.
Handlers are stored in the hash table tmfs-handler-table, indexed by pairs (class . action), where class is a string (or #t for the default handlers) and action one of the symbols load, save, autosave, remove, wrap, date, title, permission?, master and format. The function (tmfs-handler class action handle) adds an entry; the macros tmfs-load-handler and friends are shorthands which convert the class symbol into a string and build the lambda:
(define-public-macro (tmfs-load-handler head . body)
(with (type what) head
‘(tmfs-handler ,(symbol->string type) 'load
(lambda (,what) ,@body)))) |
Each public operation first calls lazy-tmfs-force on the class, which loads the module registered with lazy-tmfs-handler the first time the class is used, and then looks up the handler.
Calls the load handler of the class, or the default one, which returns a document saying Invalid tmfs document. A string result is returned as is, a (document …) tree is converted with texmacs->stm, and any other result is serialized with object->tmstring.
Calls the save handler with the name and the document as a Scheme tree. The default handler does nothing.
Calls the title handler with the name and the document. Without a title handler, the title is the complete URL.
Names ending with ~ or # (autosave files) are only accessible if the autosave handler accepts them. Otherwise the permission? handler of the class decides. Without such a handler: if the URL wraps a file (see below), the permissions of that file are used; if the class has a load handler, only "read" is granted; otherwise the default handler grants "read" only.
Calls the master handler, or returns the URL itself.
Calls the format handler, or returns "stm".
Calls the wrap handler, or returns #f.
Call the handler of the class; the defaults apply url-last-modified and url-remove to the wrapped file, if any.
Calls the autosave handler with the name and a suffix ("~" or "#"), which should return the URL where the autosave copy is stored, or #f if autosaving is not supported. The default handler supports autosaving only for wrapped files.
Returns #t if the class has no load handler.
Notice that, except for load, the default handlers (those registered for the class #t) are called with the complete URL rather than the name. The default master and format handlers are never used: tmfs-master and tmfs-format directly return the URL and "stm".
A wrap handler declares that a tmfs document is merely a different view on an ordinary file. For instance, the part handler returns the file the part is taken from. The wrapped file is used by the default handlers for permissions, dates, removal and autosave, and by buffer-last-save in
tm-files.scm
, which asks the buffer of the wrapped file, if it is open, for its last save time.
tm-files.scm
redefines url-autosave so that, for tmfs URLs, the autosave location is obtained from tmfs-autosave. The remote file system, for example, stores the autosave copies of remote files in the local backup directory:
(tmfs-autosave-handler (remote-file name suf)
(url-backup (url-glue name suf))) |
When recovering, get_from_server refuses to load URLs ending with ~ or # unless tmfs-can-autosave? holds for the original URL.
Buffers are identified by URLs: an ordinary file buffer is named by its file URL, a generated buffer by its tmfs URL. New documents which have not been saved yet get a no_name_…tm name in $TEXMACS_HOME_PATH/texts/scratch (see is_scratch in
System/Files/file.cpp
). There is no special tmfs://buffer/… scheme. The buffer layer itself is described in the TeXmacs server and in the buffer API.
The title of a buffer is computed by propose_title in
Texmacs/Data/new_buffer.cpp
. For tmfs buffers it is the result of tmfs-title; if several buffers would get the same title, a number is appended, as in Help - Title (2).
Views and windows are also identified by tmfs URLs, but these URLs are mere identifiers: there are no handlers for them and they cannot be loaded.
A view is named tmfs://view/nr/buffer by abstract_view in
Texmacs/Data/new_view.cpp
, where nr is a counter specific to the buffer and buffer encodes the name of the buffer: here/ followed by the path for relative names, default followed by the absolute path for local files, and otherwise the protocol, a slash and the rest of the URL. For instance the first view of /home/joe/paper.tm is tmfs://view/1/default/home/joe/paper.tm. concrete_view decodes such names.
A window is named tmfs://window/nr by create_window_id in
Texmacs/Data/new_window.cpp
, with a global counter starting at 1.
From Scheme, these identifiers are manipulated with the functions of the view API and the window API. This is why the classes view and window must not be used for handlers.
Every buffer has a master URL, returned by buffer-get-master (or buffer-master for the current buffer), which is used instead of the buffer name to resolve relative links and to navigate. Normally the master is the buffer itself; load-buffer-open replaces it by the result of tmfs-master for tmfs buffers. Some generators set the master explicitly instead; for example version-show-history in
version/version-tmfs.scm
makes the history buffer point to the file whose history is shown. The C++ predicate is_aux_buffer (
Texmacs/Data/new_buffer.cpp
) considers a buffer as auxiliary as soon as its master differs from its name.
Many dialogs and side tools of TeXmacs edit small documents in buffers of the class aux, defined in
kernel/texmacs/tm-file-system.scm
. Their contents are not generated, but stored in the Scheme table aux-buffers, and their masters in aux-masters:
(tmfs-load-handler (aux name)
(or (ahash-ref aux-buffers name)
‘(document
(TeXmacs ,(texmacs-version))
(style (tuple "generic"))
(body (document "")))))
(tmfs-title-handler (aux name doc)
name)
(tmfs-master-handler (aux name)
(or (ahash-ref aux-masters name)
(unix->url (string-append "tmfs://aux/" name)))) |
(aux-name aux) returns the URL tmfs://aux/ followed by the string aux, aux-set-document and aux-set-master set the contents and the master, and open-auxiliary in
tm-files.scm
combines them and switches to the auxiliary buffer; the macro with-aux evaluates some code with an auxiliary buffer holding a given file. The title of an auxiliary buffer is its name.
Examples of auxiliary buffers are tmfs://aux/search and tmfs://aux/replace (
generic/search-widgets.scm
), tmfs://aux/spell (
generic/spell-widgets.scm
), tmfs://aux/latex-source (
convert/latex/tmtex-widgets.scm
) and tmfs://aux/macro-editor (
source/macro-widgets.scm
). On the C++ side, embedded_name in
Texmacs/Window/tm_window.cpp
names the buffers of embedded editor widgets tmfs://aux/TeXmacs-input-nr, and edit_interface_rep::is_embedded_widget recognizes such widgets by the prefix tmfs://aux/. When the current buffer is auxiliary (but not a part buffer), interactive commands ask their questions in a popup rather than in the footer (
Texmacs/Window/tm_dialogue.cpp
).
When a file is imported from a format different from its natural one,
tm-files.scm
opens it as tmfs://import/format/file, where file is the output of url->tmfs-string. The import handler converts the file with tree-import and completes the result with tmfs-document; its title is the file name followed by the format.
The client/server infrastructure of TeXmacs exposes files stored on a TeXmacs server as tmfs://remote-file/… and tmfs://remote-dir/… URLs (see the catalogue). The client handlers in
client/client-tmfs.scm
forward loading and saving to Scheme services such as remote-file-load and remote-file-save, implemented on the server by
server/server-tmfs.scm
, which stores the files in a repository under $TEXMACS_HOME_PATH/server and keeps their metadata in a database. The server side itself does not define any tmfs handler. These mechanisms are described in collaborative editing.
When calling tmfs-handler directly, the class must be a string: (tmfs-handler "foo" 'load …). A symbol would never be found.
Handlers receive the name without the class and without tmfs://; tmfs-car and tmfs-cdr return #f when there is no slash in their argument.
A load handler returning the empty string makes loading fail. Return an empty document instead.
The load handler is called each time the document is read, not only when a buffer is created; make it fast, or cache results yourself.
Without a permission handler, the document is read-only; the save handler is then never called.
Errors during saving are not propagated to the C++ layer.
lazy-tmfs-handler only registers the listed classes. The handlers remote-dir, chat, live or fontdbg, for example, are not registered lazily and are only available once their modules have been loaded for another reason.