GNU TeXmacsUser manualReferenceAboutEnglish
Connections, the output parser and the life of a session

1.The connection resource

1.1.Data structure

A connection is a resource in the sense of

Kernel/Abstractions/resource.hpp

: a global object which is registered under a name when it is created and which can be retrieved from anywhere by constructing connection (name). The name of a connection is lan-ses, where lan is the name of the plug-in (the value of prog-language in a session) and ses the name of the session (the value of prog-session, default unless the user chose another session). The structure is private to

System/Link/connection.cpp

:

RESOURCE(connection);
struct connection_rep: rep<connection> {
  string  name;          // name of the pipe type
  string  session;       // name of the session
  tree    info;          // startup information tree
  tm_link ln;            // the underlying link
  int     status;        // status of the connection
  int     prev_status;   // last notified status
  bool    forced_eval;   // forced input evaluation without call backs
  bool    cmdline_eval;  // command line style evaluation
  bool    request_eval;  // request style evaluation
  texmacs_input tm_out;  // texmacs input handler for output from child
  texmacs_input tm_err;  // texmacs input handler for errors from child
  …
};

The field info is the launcher description returned by the Scheme function connection-info (for instance (tuple "pipe" "tm_maxima")), ln is the link which actually talks to the extern program, and tm_out and tm_err are the parsers for its standard output and standard error.

Resources are never destroyed. Once created, a connection lives until TeXmacs exits, and stopping a session only stops its link; restarting the session restarts the same link object. A new connection_rep (with a new link) is only created by connection_start if the launcher description changed in the meantime, for instance after reinit-plugin-cache. In that case the new object simply replaces the old one in the resource table.

1.2.Status

The status constants are defined in

System/Link/tm_link.hpp

:

Constant Value Meaning
CONNECTION_DEAD 0 the link is not alive
CONNECTION_DYING 1 the link was interrupted or stopped while output was expected
WAITING_FOR_INPUT 2 the program is idle: the last request is complete
WAITING_FOR_OUTPUT 3 a request was sent and its output is not complete yet

The value CONNECTION_DYING is internal: both connection_status (the Scheme function connection-status) and the notifications to Scheme report it as WAITING_FOR_OUTPUT. Conversely, connection_status reports CONNECTION_DEAD whenever the link is not alive, regardless of the field status. Seen from Scheme, the status is therefore 0 (dead), 2 (idle) or 3 (busy). The status changes as follows:

The field prev_status holds the last status which was reported to Scheme; connection_notify_status only calls connection-notify-status when the status changed since.

1.3.Creation and start

The entry point is connection_start, called from Scheme as (connection-start lan ses):

string
connection_start (string name, string session, bool again) {
  if (!connection_declared (name))
    return "Error: connection " * name * " has not been declared";
  connection con= connection (name * "-" * session);
  tree t= connection_info (name, session);
  if (is_nil (con) || con->info != t) {
    if (is_tuple (t, "cmdline")) {
      tm_link ln= make_cmdline_link (name);
      con= tm_new<connection_rep> (name, session, ln);
      con->cmdline_eval= true;
    }
    if (is_tuple (t, "request")) { … make_request_link … }
    if (is_tuple (t, "pipe", 1)) {
      tm_link ln= make_pipe_link (t[1]->label);
      con= tm_new<connection_rep> (name, session, ln);
    }
    else if (is_tuple (t, "dynlink", 3)) { … make_dynamic_link … }
    con->info= t;
  }
  return con->start (again);
}

The functions connection_declared, connection_info and connection_handlers are thin wrappers around the Scheme functions connection-defined?, connection-info and connection-get-handlers of

tm-plugins.scm

, which are described in connection tables and predicates. Notice that the result of connection_handlers is cached in a static table on first use, so that handlers which are declared later (after a re-detection of the plug-ins) are not taken into account until TeXmacs is restarted.

The method connection_rep::start then starts the link if necessary, resets the two parsers (bof), installs the call-back through which the link signals new data, and handles a few special cases:

string
connection_rep::start (bool again) {
  string message;
  if (ln->alive) {
    message= "Continuation of '" * name * "' session";
    status = WAITING_FOR_INPUT;
  }
  else {
    message= ln->start ();
    tm_out = texmacs_input ("output");
    tm_err = texmacs_input ("error");
    status = WAITING_FOR_OUTPUT;
    if (again && (message == "ok")) {
      beep ();
      (void) connection_retrieve (name, session);
    }
  }
  tm_out->bof ();
  tm_err->bof ();
  ln->set_command (command (connection_callback, this));
  if (name == "dynlink") {
    this->listen ();
    status = WAITING_FOR_OUTPUT;
  }
  if (message == "cmdline") { … status= WAITING_FOR_INPUT; … }
  if (message == "request") { … status= WAITING_FOR_INPUT; … }
  return message;
}

The command installed with tm_link_rep::set_command is stored in the field feed_cmd of the link. Whenever the link has new data, it (or the polling code, see links and the event loop) applies this command, which calls the static function connection_callback and hence connection_rep::listen.

The argument again is only set by connection_get, the helper of the synchronous evaluation functions: when a connection is started implicitly by connection_eval, TeXmacs beeps and swallows the banner synchronously. The special treatment of the plug-in named dynlink is discussed in known issues.

1.4.Writing, reading and listening

Input is sent by connection_write. The variant taking a tree, which is the one behind connection-write, first converts the tree into a string by calling (plugin-serialize lan t); the variant taking a string is exposed as connection-write-string and is used for special commands. In both cases connection_rep::write writes the string on the input channel of the link, resets both parsers and marks the connection as busy.

Output is processed by connection_rep::listen, the heart of the connection layer:

void
connection_rep::listen () {
  if (forced_eval) return;
  connection_notify_status (this);
  if (status != CONNECTION_DEAD) {
    if (cmdline_eval || request_eval) ln->listen (1);
    read (LINK_ERR);
    connection_notify (this, "error", tm_err->get ("error"));
    read (LINK_OUT);
    connection_notify (this, "output", tm_out->get ("output"));
    connection_notify (this, "prompt", tm_out->get ("prompt"));
    connection_notify (this, "input", tm_out->get ("input"));
    tree t= connection_handlers (name);
    for (int i=0; i<N(t); i++) {
      tree doc= tm_out->get (t[i][0]->label);
      if (doc != "") call (t[i][1]->label, doc);
      doc= tm_err->get (t[i][0]->label);
      if (doc != "") call (t[i][1]->label, doc);
    }
  }
  connection_notify_status (this);
}

The method connection_rep::read takes all the bytes which the link has buffered for the given channel (tm_link_rep::read) and feeds them one by one to the corresponding parser using texmacs_input_rep::put. The parser accumulates the converted trees per channel; get removes and returns the accumulated document of a channel, or the empty string if there is nothing new. Finally, connection_notify calls

(connection-notify lan ses channel tree)

for every non-empty channel, and connection_notify_status calls (connection-notify-status lan ses status) if the status changed.

Three consequences of this code are worth noticing. First, the standard error is always processed before the standard output, so the relative order of error and normal output produced during one polling interval is lost. Secondly, the channels are always notified in the order error, output, prompt, input, followed by the custom channels declared with :handler; the custom handlers are called with a single argument (the tree) and bypass the request queue. Thirdly, the status is notified both before and after the output, so that a status change to 2 (end of output) always reaches Scheme after the corresponding output.

The flag forced_eval is set by connection_retrieve during synchronous evaluations, so that output which is read by the synchronous loop is not concurrently consumed by an asynchronous call-back.

2.The output parser

2.1.State

The class texmacs_input_rep, declared in

Data/Convert/Generic/input.hpp

, turns a stream of bytes into documents. One instance is created for the standard output (with type equal to "output") and one for the standard error (type equal to "error"); the type is the default channel.

struct texmacs_input_rep: concrete_struct {
  string type;                  // default value for channel below
  int    status;                // status of parser
  string buf;                   // input buffer
  string format;                // current input format
  int    mode;                  // corresponding input mode
  string channel;               // current output channel
  tree   stack;                 // stack for nested blocks
  bool   ignore_verb;           // hack to enable completion with some plugins
  hashmap<string,tree> docs;    // output for each channel
  …
};

The stack is a linked list of triples tuple (format, channel, stack), terminated by the empty string. The mode is an integer code which is computed from the format by texmacs_input_rep::get_mode and selects the flushing routine.

2.2.The state machine

The method put processes one character and returns true when the character completed the outermost block, that is, when the program is ready for new input:

bool
texmacs_input_rep::put (char c) {
  bool block_done= false;
  switch (status) {
  case STATUS_NORMAL:
    if (c == DATA_ESCAPE) status= STATUS_ESCAPE;
    else if (c == DATA_BEGIN) { flush (true); status= STATUS_BEGIN; }
    else if (c == DATA_ABORT && (format == "verbatim" || format == "utf8")
             && buf == "") ignore_verb= true;
    else if (c == DATA_END) {
      flush (true);
      end ();
      block_done= (stack == "");
      ignore_verb= (ignore_verb && stack != "");
    }
    else buf << c;
    break;
  case STATUS_ESCAPE:
    buf << c; status= STATUS_NORMAL; break;
  case STATUS_BEGIN:
    if (c == ':') { begin_mode (buf); buf= ""; status= STATUS_NORMAL; }
    else if (c == '#') { begin_channel (buf); buf= ""; status= STATUS_NORMAL; }
    else buf << c;
    break;
  }
  if (status == STATUS_NORMAL) flush ();
  return block_done;
}

After a DATA_BEGIN, the characters up to the first : or # are collected as the name of a format or channel. begin_mode pushes the current format and channel on the stack and switches the format; begin_channel pushes them and switches the channel (and empties the documents of the prompt and input channels, so that only the last prompt counts). A DATA_END forces a flush in the current format and pops the stack with end. A DATA_END with an empty stack (that is, without a matching DATA_BEGIN) also counts as the end of the output.

Before each block, and after each ordinary character, the buffer is flushed: flush (true) always converts the whole buffer, while flush () lets the current format decide whether enough text is available. As an exception, text on the error channel inside a block is only flushed when forced, that is, at the end of the block.

2.3.Conversion of the formats

The flushing routines and the conversions they perform are:

Format Routine Flushed when Conversion
verbatim verbatim_flush newline verbatim_to_tree (buf, false, "auto")
utf8 utf8_flush newline utf8_to_cork, then verbatim_to_tree
latex latex_flush empty line generic_to_tree (buf, "latex-snippet")
html html_flush </P> generic_to_tree with "html-snippet", wrapped in html-text
scheme scheme_flush end of block simplify_correct (scheme_to_tree (buf))
math math_flush end of block string->object, cas->stree, tm->tree, wrapped in WITH mode math
ps ps_flush end of block IMAGE with RAW_DATA
file file_flush end of block file loaded with load_string, then image_flush
command command_flush end of block eval of (begin buf)
channel channel_flush end of block replaces the channel saved on top of the stack
any format? xformat_flush end of block generic_to_tree (buf, format * "-snippet")
cmdline-name cmdline_flush end of output (connection-result name "default" buf)
request-name request_flush end of output same as cmdline_flush

Unknown formats fall back to verbatim. Since the command format evaluates arbitrary Scheme code, a plug-in has full control over the editor; this is by design (see sending commands to TeXmacs), but it means that the output of untrusted programs should never be piped into a session. The method ispell_flush is declared in

input.hpp

but has no implementation and no mode.

2.4.Accumulating the output

Every flushing routine passes its result to texmacs_input_rep::write, which appends it to the document of the current channel in docs. If the new tree is not a document, it is first wrapped into one. Its first paragraph is concatenated with the last paragraph of the accumulated document (so that output arriving in several pieces without newline ends up in the same paragraph), and its remaining paragraphs are appended.

The method bof is called whenever a new request starts: it resets the format to verbatim (except for the cmdline-name and request-name formats, which are sticky), the channel to the default channel, and clears the document of the default channel. The method eof forces a final flush when the link died.

The prompt is an ordinary channel: the program sends DATA_BEGIN prompt# … DATA_END (or, in the legacy syntax, DATA_BEGIN channel:prompt DATA_END, which works by overwriting the channel which end will restore), and the session layer decides what to do with it.

3.The request queue

3.1.Requests and call-backs

All asynchronous traffic with a connection goes through the queue of the pair (lan, ses) in

utils/plugins/plugin-eval.scm

. A request is a list whose head is a list of five elements

((do notify next cancel author) . args)

where args is specific to the client: for sessions it is (in out next opts), as built by session-encode, where out and next are tree pointers to the output of the evaluated field and to the next input field; for silent evaluations it is (in out err return opts), as built by silent-encode. The call-backs are invoked as (do lan ses), (notify lan ses channel tree), (next lan ses) and (cancel lan ses dead?), and always operate on the request at the head of the queue ((car (pending-ref lan ses))).

The author is a fresh number obtained with new-author when the request is queued. plugin-feed registers it with start-slave (which calls archiver_rep::start_slave in

Data/History/archiver.cpp

), and the notifications run inside with-author, which temporarily switches the current author and commits the changes. This way, the modifications which the asynchronous output makes to the document are attributed to the request in the undo history rather than mixed with the edits which the user makes in the meantime.

3.2.The scheduler

The queue is driven by four functions:

(plugin-feed lan ses do notify next cancel args)
(enqueue a request)

Append a request to the queue and call plugin-do if the queue was empty. Requests queued while another one is being processed wait until the latter is complete.

(plugin-do lan ses)
(process the head of the queue)

If the head is a start request (its first argument is :start), call plugin-start if the connection is dead, and plugin-next otherwise. For :cmdline and :request plug-ins, call the do call-back directly. If the connection is dead, push a silent start request in front of the queue and process it first; its output (the banner) is discarded. Otherwise call the do call-back, which usually calls plugin-write.

(plugin-next lan ses)
(request complete)

Call the next call-back of the head, remove it from the queue and process the following request.

(plugin-cancel lan ses dead?)
(cancel all requests)

Call the cancel call-back of every request in the queue and empty it.

The notifications from C++ are dispatched as follows. connection-notify passes the tree to the notify call-back of the head of the queue (output on a connection with an empty queue is dropped), and records trees on the prompt channel in the table plugin-prompts, from which plugin-prompt later takes the prompt of new input fields. connection-notify-status reacts to the status: 2 calls plugin-next; 0 forgets the prompt and the timing and calls plugin-cancel with dead? set to #t, except for :cmdline and :request plug-ins, for which 0 is the normal end of a request and calls plugin-next. The status 3 is ignored.

The function plugin-write records the starting time of the request (for plugin-timing) and sends the request: a tree of the form (command string) is sent verbatim with connection-write-string, anything else is serialized with connection-write. For the scheme language, it schedules a delayed evaluation with scheme-eval which simulates the notifications of a real connection.

4.The life of a session

This section follows a session from its creation to its end. The functions are in

dynamic/session-edit.scm

unless stated otherwise.

4.1.Creating the session

Insert\(\rightarrow\)Session\(\rightarrow\)Name calls (make-session lan ses), which inserts

(session lan ses (document (output (document "")) (input prompt (document ""))))

(with input-text or input-math instead of input according to the preferences), adds the style package lan.ts if it exists, and calls

(session-feed lan ses :start banner-document input-field '())

The output before the first input field will receive the banner. session-feed replaces its content by script-busy (which is rendered as a busy indicator) and enqueues the request.

4.2.Starting the program

Since the first argument is :start, plugin-do calls plugin-start, and hence connection_start, which creates the connection and its link and starts the link: for a pipe, a process is launched. The status is now WAITING_FOR_OUTPUT.

The program prints its banner followed by a prompt, for instance

DATA_BEGIN verbatim:Welcome to MyCAS 1.0
DATA_BEGIN prompt#> DATA_END
DATA_END

(without the spaces after DATA_BEGIN). At the next poll, the link has data and connection_rep::listen runs. The banner is delivered on the output channel to session-notify, which inserts it into the banner output with session-output (in front of the script-busy tag); the prompt is delivered on the prompt channel and becomes the prompt of the input field if this is the last pending request and the field is still empty. When the outermost DATA_END has been parsed, the status becomes WAITING_FOR_INPUT, connection-notify-status calls plugin-next, and session-next removes the script-busy tag (and the whole output if it stayed empty).

If the connection was already alive (for instance a second session with the same name in another document), plugin-do calls plugin-next immediately and the empty banner is removed.

4.3.Evaluating an input field

When the user presses ↩ in an input field, kbd-enter is called. If multi-line input is active, a newline is inserted. If the plug-in supports :test-input-done, the special command (input-done? string) is first sent through plugin-command and the input is only evaluated if the answer is not #f. Otherwise session-evaluate calls field-process-input, which

  1. checks that the language is known (session-ready?);

  2. turns the input into an unfolded-io with an empty output (field-insert-output);

  3. finds the next input field, or creates a new one with the current prompt (field-create);

  4. calls session-feed with the input (as a Scheme tree), the output and the next field, and moves the cursor to the next field.

session-feed preprocesses the input (plugin-preprocess, which converts mathematical input if :math-input is among the options), sets the output to (document (script-busy)), and enqueues the request. When the request reaches the head of the queue, session-do checks that the output and the next field are still at their place in the document (session-coherent?; the user may have deleted them in the meantime), copies the current prompt into the evaluated field, and calls plugin-write. Empty inputs are skipped, except for the r plug-in.

Several fields can be evaluated in a row (session-evaluate-all, session-evaluate-above, session-evaluate-below): they are simply queued, and each one is sent when the previous one is complete.

4.4.Receiving the output

Output is inserted incrementally. Each call to connection_rep::listen delivers what the parser converted so far: for verbatim output, all complete lines. session-output inserts the paragraphs of the received document before the trailing script-busy tag (and before a trailing errput), and session-errput inserts error output into an errput tag, creating it if needed. A tree received on the input channel becomes the content of the next input field, provided that no other request is pending.

When the output is complete, the status changes to 2 and session-next replaces the script-busy tag by a timing tag (if timings were requested with Show timings in the output options of the session, and the evaluation took at least one millisecond) or removes it, removes the output if it is empty, and releases the tree pointers.

4.5.Interrupting

Interrupt execution calls plugin-interrupt. If the connection is busy, connection_interrupt calls tm_link_rep::interrupt (which sends SIGINT to the program, see links), sets the status to CONNECTION_DYING and calls connection_rep::listen. On the Scheme side, all pending requests are cancelled: their script-busy tags become script-interrupted.

The program is expected to react to SIGINT by terminating its current output with DATA_END. Until it does, the connection is reported as busy (status 3). Notice that the requests are cancelled on the Scheme side immediately, while the program may still be producing output. If the user evaluates a new field before the program has closed the interrupted output, the new request is written to the program right away (since the status is not 0), and the late output and the DATA_END of the interrupted computation are attributed to the new request.

4.6.Stopping and restarting

Close session calls plugin-stop, hence connection_stop, which stops the link (for pipes: termination of the process) and calls connection_rep::listen. The link being dead, connection_rep::read flushes the parsers (eof) and sets the status to CONNECTION_DEAD; the resulting notification of status 0 cancels the pending requests with dead? set to #t, which replaces their busy tags by script-dead. The same happens when the program exits or crashes on its own: the link sees an end of file on the standard output of the program.

There is no explicit restart. The next evaluation in a dead session finds the status 0 in plugin-do, which inserts a silent start request in front of it: the connection is started again with the same link object, the new banner is discarded, and the evaluation proceeds as usual.

4.7.Several sessions

Each pair (lan, ses) has its own connection, queue, prompt and author, and for pipes its own process. The names of the sessions are chosen by the user (Insert\(\rightarrow\)Session\(\rightarrow\)Other) or are the variants declared by the plug-in; a session name of the form variant:suffix uses the launcher of variant (see connection-info), which allows several independent sessions of the same variant. Conversely, several session tags with the same language and session name, in the same or in different documents, share a single connection and a single queue; this is how Split session works. The dynamic environment variables prog-language and prog-session, set by the session macro, tell the editing commands which connection the cursor is in.

5.Synchronous evaluation

The function connection_eval (the Scheme function connection-eval, used by plugin-eval) bypasses the request queue:

tree
connection_eval (string name, string session, tree t) {
  connection con= connection_get (name, session);
  if (is_nil (con)) return "";
  connection_write (name, session, t);
  return connection_retrieve (name, session);
}

connection_get starts the connection if it does not exist yet, with again set to true so that the banner is read and discarded. connection_retrieve then loops until the status is WAITING_FOR_INPUT: with forced_eval set, it calls perform_select (except in Qt builds, where the Qt pipe link reads directly from the process in its read method), reads the output channel with connection_read and accumulates the result in a document. Only the default output channel is returned; error output is not.

This loop runs in the main thread and does not return to the event loop, so the user interface is frozen until the program has answered, and there is no timeout. Since it bypasses the request queue, plugin-eval should not be used on a connection which has asynchronous requests in progress. connection_cmd is the same for special commands: it formats the command with format-command and unwraps a single-paragraph result.

6.Command line and request connections

The connections of plug-ins configured with :cmdline or :request (such as the ai plug-in) follow a different pattern: there is no long-lived process, and each request is run separately.

  1. At start, cmdline_link_rep::start (resp. request_link_rep::start) returns the message "cmdline" (resp. "request"), and connection_rep::start switches the output parser to the format cmdline-name (resp. request-name) and reports the connection as idle at once.

  2. For each request, the link calls back the Scheme function (connection-cmdline name "default" input) (resp. connection-request), which applies the cmd-fun (resp. request-fun) of the plug-in to obtain a shell command (resp. a request description), and launches it. For command line links, newlines in the input are replaced by spaces.

  3. The output is only made available when the command has terminated: cmdline_link_rep::read returns nothing while the link is alive. When it dies, connection_rep::read calls eof, which flushes the whole output through cmdline_flush and (connection-result name "default" output), that is, through the result-fun of the plug-in, and the status becomes 0. For these plug-ins, connection-notify-status treats 0 as the end of the request.

The string "default" passed as the second argument is a constant: the session name is not passed to the plug-in functions.

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