
\chapter{Using GNU TeXmacs as an interface}

\TeXmacs\ currently supports a very simple interface for
communicating with extern programs.
Although this interface has to be improved in many ways in the future,
it is typically possible to evaluate commands of an extern computer
algebra system inside a ``\TeXmacs-session'',
and display the results in a nice, graphical way.
It is also possible to evaluate shell commands and
\scheme\ programs inside such sessions.

\section{Sessions}

A session can be started from the \submenu{Insert}{session} menu.
A session consists of a sequence of input and output environments and
possible text between them. When pressing \key{return} inside
an input environment of a session, the text inside the environment
is evaluated and the result is displayed in an output environment.

Now each session environment takes two arguments: the programming
language and a name for the session. All input to be evaluated is
redirected to the package which implements the programming languages
and the session name is passed as an extra argument.

It is possible to redefine the screen layout of sessions as follows.
For each session in programming language `p', you then have to modify
the environments `input-p' and `output-p' which respectively
correspond to the layout of the input and the output.
The first argument to `input-p' is the prompt for the input.

It is possible to give sessions a name (the default name being ``default''):
by clicking on \subsubmenu{Insert}{session}{other},
one both has to enter a session type and a session name.
Different sessions which have the same type and the same name share
correspond to one instance of the application being executed.
Consequently, such sessions share a common environment.
By using different session names, one may concurrently launch
several instances of the same application.

When entering a command in a session, the application attempts
to execute it. Several commands may be launched concurrently
in the same document, but the output will only be active in
the session where the cursor is and at the place of the cursor.
Therefore, we recommend to use different buffers for parallel
executions. Executions may be interrupted from the iconbar.
it is also possible to disconnect (close) the application;
in that case no further commands can be executed in
the corresponding session.

\subsection{Shell sessions}

In a `shell' session it is possible to evaluate shell commands.
All input and output is verbatim. No particular command-line
utilities (such as completion mechanisms) have been implemented yet.
The output of the shell command is displayed gradually as
the program executes.

\subsection{Scheme sessions}

In a `\scheme' session you can evaluate {\sc Guile}/{\scheme} programs.
The input should be verbatim text. The input is evaluated and
the result is displayed. No gradual output mechanism has been
implemented yet for {\scheme} session.

\subsection{Pari sessions}

I order to use \pari\ inside \TeXmacs, you should first make sure that
you downloaded a version newer than \pari-2.1.0 from
\begin{verbatim}
    ftp://megrez.math.u-bordeaux.fr/pub/pari
\end{verbatim}
In order to determine the version of an already installed
\pari-system, type ¤gp --version¤.

\section{Link your own system to TeXmacs}

Assume that you have written a computer algebra system
(or some other scientific program which requires mathematical
input and output), and that you want a graphical interface
for your program. In order to link your system to \TeXmacs,
you have to options:
\begin{enumerate}
  \item Link your system to {\TeXmacs} via pipes.
  \item Link your system as a dynamically linked library.
\end{enumerate}
The first option is usually easier to implement, more robust and
provides gradual output; the second option is faster.
Let us now describe the steps you have to go through
for each of these two options. You may also choose to
customize an easy example provided with {\TeXmacs},
as explained in the last subsection.

\subsection{Connections via pipes}

\begin{enumerate}
  \item Create a special command line option for your program
        which allows it to recognize that it has been called by {\TeXmacs}.
        All communication between {\TeXmacs} and your application
        will pass through standard input and output.
  \item Include a line of the form
\begin{verbatim}
    (connection-declare "name" "shell-cmd")
\end{verbatim}
        in your personal initialization file ¤Init.scm¤.
        Here ¤name¤ must be the name of your package and
        ¤shell-cmd¤ the shell command to launch it
        (including special command line options).
        You should also include a command
\begin{verbatim}
    (connection-format "name" "input-format" "output-format")
\end{verbatim}
        if your input and output is not merely verbatim text.
        More details about the available data formats can
        be found in the next section.
  \item Add a command like
\begin{verbatim}
    (set! session-menu (menu-merge session-menu
      '(("name" (make-session "name")))))
\end{verbatim}
        to your personal initialization file ¤Init.scm¤,
        in order to be able to start a \TeXmacs-session
        from the \submenu{Insert}{session} menu,
        in which you can evaluate expressions of your language.
        You may also redefine the keyboard for your such sessions.
  \item Create a style file in which you provide
        the input and output environments `input-name' and
        `output-name' for your system.
  \item If everything works well, and you wish to make it possible
        for others to use your system inside
        the official \TeXmacs\ distribution,
	then contact me at
\begin{verbatim}
    TeXmacs@math.u-psud.fr
\end{verbatim}
	I will take care of the inclusion of the necessary
	initialization commands for your package in
	the \TeXmacs\ ¤Init.scm¤ file and your input and
        output styles in the ¤program.ts¤ file.
\end{enumerate}

\subsection{Connections via dynamically linked libraries}

\begin{enumerate}
  \item Modify the architecture of your system in such a way that
        the main part of it can be linked as a shared library;
        your binary should typically become a very small program,
        which handles verbatim input and output,
        and which is linked with your shared library at runtime.
  \item Copy the include file ¤$TEXMACS_PATH/include/TeXmacs.h¤ %$
        into the include directory of your system's source and
        write the input/output routines as required by the last
        TeXmacs communication protocol as explained below.
  \item Include a line of the form
\begin{verbatim}
    (package-declare "name" "libname.so" "get_name_package" "init")
\end{verbatim}
        in your personal initialization file ¤Init.scm¤.
        Here ¤name¤ must be the name of your package, ¤libname.so¤
        the corresponding shared library, ¤get_name_package¤
        the function, which will be called by \TeXmacs\ in order
        to link your system to \TeXmacs, and ¤init¤
        some initialization string for your package.
  \item Follow the same steps 3, 4 and 5 as above.
\end{enumerate}

\subsection{Customizing an easy example}

The best way to get started with implementing your own link to {\TeXmacs}
is to take a look at the sample ``computer algebra system'' ¤mycas¤,
which can be found in the directory ¤$TEXMACS_PATH/misc/mycas¤. %$
The file ¤mycas.cc¤ contains a very simple program which can be interfaced
with {\TeXmacs}. In order to test the program, you should first
compile it using
\begin{verbatim}
    g++ mycas.cc -o mycas
\end{verbatim}
Next, you should move ¤mycas¤ to some location in your path,
so that it will automatically be recognized when launching {\TeXmacs}.

At a second stage, you may analyze the way how ¤mycas¤ works,
and mimick the communication protocol for your own system.
When you think that you are done, you may first replace
the executable ¤mycas¤ with a symbolic link to the main binary
of your system, so that you can test your system under the name ``mycas''.
If everything works fine, then you may finally customize the initialization,
menu and style files as explained above.

\section{Communication via pipes}

By default, all input from the application and
all output to the application is verbatim.
When including a command like
\begin{verbatim}
    (connection-format "name" "input-format" "output-format")
\end{verbatim}
in your personal initialization file,
it is possible to use other data formats with more semantics.
Currently, we provide only ¤verbatim¤ as an input data format
for your application and ¤verbatim¤, ¤scheme¤, ¤latex¤, ¤html¤, ¤ps¤
and ¤generic¤ as output data formats. The ¤scheme¤ format
is used to transmit {\TeXmacs} trees, using the scheme syntax.

We recommend the use of ¤generic¤ as the output format,
because you may access to all other data formats via this format and
it allows a clean specification of the start and the end of
a data package. More precisely, the ¤generic¤ output format
comes with three special control characters
\begin{verbatim}
    #define DATA_BEGIN   ((char) 2)
    #define DATA_END     ((char) 5)
    #define DATA_ESCAPE  ((char) 27)
\end{verbatim}
Any data package which is send from the application to {\TeXmacs}
should start with ¤DATA_BEGIN¤ and with a matching ¤DATA_END¤.
After ¤DATA_BEGIN¤, you should send the particular data format
of your package, followed by the ¤':'¤ character. 

Moreover, the ¤DATA_BEGIN¤/¤DATA_END¤ may be used recursively
inside your data package. The ¤DATA_ESCAPE¤ character followed by
any other character $c$ is used to produce $c$, even if
$c$ is one of the three control characters.
The following C++-program illustrates the use of
the ¤generic¤ output format.
\begin{verbatim}
    #include <stdio.h>
    #include <string.h>
    #include <iostream.h>

    #define DATA_BEGIN   ((char) 2)
    #define DATA_END     ((char) 5)
    #define DATA_ESCAPE  ((char) 27)

    int
    main () {
      cout << DATA_BEGIN << "verbatim:";
      cout << "Welcome to my package\n";
      cout << DATA_END;
      fflush (stdout);
      while (1) {
        char buffer[100];
        cin >> buffer;
        if (strcmp (buffer, "quit") == 0) break;
        cout << DATA_BEGIN << "verbatim:";
        cout << "You typed " << buffer << "\n";
        cout << "And now a LaTeX formula: ";
        cout << DATA_BEGIN << "latex:";
        cout << "$x^2+y^2=z^2$";
        cout << DATA_END;
        cout << DATA_END;
        fflush (stdout);
      }
      return 0;
    }
\end{verbatim}
In the case of communication by pipes,
the output maybe redirected to several ``channels'',
the ¤output¤ channel being the default one.
The ¤prompt¤ channel allows you to specify a prompt and
the ¤input¤ channel to specify a default value for the next input.
For instance, in order to use ¤Hello] ¤ as a prompt,
you should include the following code just before the final ¤DATA_END¤:
\begin{verbatim}
    cout << DATA_BEGIN << "channel:prompt" << DATA_END;
    cout << "Hello] ";
\end{verbatim}

\section{The TeXmacs communication protocol}

The {\TeXmacs} communication protocol is used for
linking libraries dynamically to {\TeXmacs}.
The file ¤$TEXMACS_PATH/include/TeXmacs.h¤ contains %$
the declarations of all data structures and functions used by the protocol.
Actually, we foresee a succession of different protocols.
Each of these protocols have the abstract data structures
¤TeXmacs_exports¤ and ¤package_exports¤ in common,
with information about the versions of the protocol,
\TeXmacs\ and your package.

The $n$-th concrete version of the communication protocol
should provide two data structures ¤TeXmacs_exports_n¤ and
¤package_exports_n¤. The first structure contains all routines and
data of \TeXmacs, which may be necessary for the package.
The second structure contains all routines and data
of your package, which should be visible inside \TeXmacs.

In order to link your system to \TeXmacs, you have to implement a function
\begin{verbatim}
    package_exports* get_my_package (int version);
\end{verbatim}
This function takes the highest \TeXmacs\ communication protocol
supported by your \TeXmacs\ system on input. It should return
a pointer to an instance of a concrete structure ¤package_exports_n¤,
where ¤n¤ is inferior or equal to ¤version¤.

\subsection{Version 1 of the TeXmacs communication protocol}

In the first version of the TeXmacs communication protocol,
your package should export an instance of the following data structure:
\begin{verbatim}
    typedef struct package_exports_1 {
      char* version_protocol; /* "TeXmacs communication protocol 1" */
      char* version_package;
      char* (*install) (TeXmacs_exports_1* TM, char* options, char** errors);
      char* (*evaluate) (char* what, char* session, char** errors);
      char* (*execute) (char* what, char* session, char** errors);
    } package_exports_1;
\end{verbatim}
The string ¤version_protocol¤ should contain
¤"TeXmacs communication protocol 1"¤ and
the string ¤version_package¤ the version of your package.

The routine ¤install¤ will be called once by
\TeXmacs\ in order to initialize your system with options ¤options¤.
It communicates the routines exported by
\TeXmacs\ to your system in the form of ¤TM¤.
The routine should return a status message like
\begin{verbatim}
    "my-package.version successfully linked to TeXmacs"
\end{verbatim}
If installation failed, then you should return ¤NULL¤ and
¤*errors¤ should contain an error message.
Both ¤what¤ and the returned string have a special format,
in which it is possible to encode arbitrary \TeXmacs\ documents.
This format will be explained in the next section.

The routine ¤evaluate¤ is used to evaluate the expression ¤what¤
inside a \TeXmacs-session with name ¤session¤. It should return
the evaluation of ¤what¤ or ¤NULL¤ if an error occurred.
¤*errors¤ either contains one or more warning messages
or an error message, if the evaluation failed. The command
\begin{verbatim}
    (package-format "name" "input-format" "output-format")
\end{verbatim}
is used in order to specify the input and output formats
for evaluations, in a similar way as in the case of pipes.

The routine ¤execute¤ has a similar specification as ¤evaluate¤,
except that it is not used for the evaluation of expressions
inside a \TeXmacs-session, but rather for other communication
purposes between \TeXmacs\ and your package.

\begin{remark}
  All strings returned by the routines ¤install¤, ¤evaluate¤ and
  ¤execute¤, as well as all warning and error messages should
  be allocated using ¤malloc¤. They will be freed by
  \TeXmacs\ using ¤free¤.
\end{remark}

The first version of the \TeXmacs\ communication protocol also
requires \TeXmacs\ to export an instance of the data structure
\begin{verbatim}
    typedef struct TeXmacs_exports_1 {
      char* version_protocol; /* "TeXmacs communication protocol 1" */
      char* version_TeXmacs;
    } TeXmacs_exports_1;
\end{verbatim}
The string ¤version_protocol¤ contains the version
¤"TeXmacs communication protocol 1"¤ of the protocol and
¤version_TeXmacs¤ the current version of TeXmacs.

\section{Further features}

In the case when you connected your system to {\TeXmacs} using pipes,
you may use a few other facilities. First of all, you may directly
execute {\TeXmacs} commands when outputting from your system
by incorporating pieces of code of the form
\begin{verbatim}
    [DATA_BEGIN]command:scheme-program[DATA_END]
\end{verbatim}
in your output. Inversily, when your cursor is inside a session
of your system, you may use the scheme command
\begin{verbatim}
    (extern-exec cas-command)
\end{verbatim}
in order to execute a command of your system.
