GNU TeXmacsUser manualReferenceAboutEnglish
From a code environment to colored text

1.Where programming mode comes from

Programming mode is entered in three ways.

Code markup

The package

environment/env-program.ts

defines one inline macro per language, which simply changes the mode, the language and the font family:

<assign|python|<macro|body|<with|mode|prog|prog-language|python|font-family|rm|body>>>

The inline macros are scm, cpp, java, python, julia, scala, r, scilab, fortran, shell, mmx (Mathemagix), dot-lang, javascript-lang, json-lang, octave-lang and minimal. For each of them there is a block variant (scm-code, cpp-code, python-code, dot-code, json-code, mmx-code, …) which wraps the inline macro inside pseudo-code, itself defined via render-code (no indentation of the first line, no separation between paragraphs, padding above and below). The Scheme groups inline-code-tag and block-code-tag in

text/text-drd.scm

list these tags, and the menu code-menu in

text/text-menu.scm

(shown as the submenu “Program”) offers them to the user.

Sessions

In

compute/session.ts

the macro session sets prog-language to the name of the plugin (python, maxima, …) and input and output switch to prog mode. Session input is therefore highlighted with the language of the plugin, if that language is known (otherwise the fallback language is used, see below). Similarly,

compute/scripts.ts

typesets script input in programming mode with prog-language set to the scripting language.

Source files

When a file in a programming format is loaded, the function attach_subformat (

Texmacs/Data/new_buffer.cpp

) sets the initial environment of the buffer to mode=prog and prog-language=format, and selects the style code (

src/TeXmacs/styles/test/code.ts

). This happens only if the format exists and either a format-lang.scm file is found (prog_lang_exists) or the format is one of mathemagix, scilab or scheme.

The default values are set in

Typeset/Env/env_default.cpp

: prog-language is scheme and prog-scripts is none. The fonts used in programming mode are controlled by prog-font, prog-font-family, prog-font-series and prog-font-shape, and prog-session holds the name of the current session. All these variable names are declared in

Data/Drd/vars.cpp

(PROG_LANGUAGE, PROG_SCRIPTS, …). Note that prog-scripts is only used by the scripting markup in

compute/scripts.ts

; it plays no role in highlighting.

2.Selecting the language object

The typesetting environment edit_env_rep (

Typeset/env.hpp

) holds the current language in its member language lan, together with the integer mode (1 for text, 2 for math, 3 for programs, 0 otherwise) and an integer hl_lan which is used by packrat based highlighting. In

Typeset/Env/env_semantics.cpp

, the variable prog-language has the type Env_Language and mode has the type Env_Mode; whenever one of them changes, update_language is called:

void
edit_env_rep::update_language () {
  switch (mode) {
  case 0:
  case 1:
    lan= text_language (get_string (LANGUAGE));
    break;
  case 2:
    lan= math_language (get_string (MATH_LANGUAGE));
    break;
  case 3:
    lan= prog_language (get_string (PROG_LANGUAGE));
    break;
  }
  hl_lan= lan->hl_lan;
}

The editor uses the same rules in edit_typeset_rep::get_env_language (

Edit/Editor/edit_typeset.cpp

) to obtain the language at the cursor.

3.The language registry

The class language is a resource (macro RESOURCE in

Kernel/Abstractions/resource.hpp

): every language_rep has a name res_name, and its constructor registers the object in the static table language::instances. Language objects are not destroyed in practice; they are shared by all documents, views and typesetters for the whole session.

language prog_language (string s)
(language object for a programming language)

Returns the cached object if language::instances already contains s. Otherwise it creates one, using the following rules in this order:

bool prog_lang_exists (string s)
(is there a language definition file?)

Returns true if a file s-lang.scm exists in one of $TEXMACS_PATH/progs/prog/, $TEXMACS_PATH/plugins/s/progs/, $TEXMACS_PATH/plugins/code/progs/, $TEXMACS_HOME_PATH/plugins/s/progs/ or $TEXMACS_HOME_PATH/plugins/code/progs/.

format_exists (

Data/Convert/Generic/generic.cpp

) calls the Scheme predicate format? (

kernel/texmacs/tm-convert.scm

), which is true when the format was declared with define-format. The formats of the programming languages are declared lazily in

init-texmacs.scm

:

(lazy-format (prog prog-format) scheme)
(lazy-format (code-format) cpp julia scala java json csv)
(lazy-format (mathemagix-format) mathemagix)
(lazy-format (caas-format) caas)
(lazy-format (python-format) python)
(lazy-format (scilab-format) scilab)

The modules (code-format) and (python-format) live in the plugins code and python. Hence a language gets the generic highlighter only if both a format and a -lang.scm file exist. For instance python, java, scala, julia, json and csv use prog_language_rep, whereas, in the current sources, there is no define-format for javascript, dot or octave, although their -lang.scm files exist in the code and octave plugins.

4.The class language_rep

The abstract interface is shared with text and mathematics (

System/Language/language.hpp

):

struct language_rep: rep<language> {
  string lan_name;  // name of the language
  int hl_lan;
  static hashmap<string,int> color_encoding;
  hashmap<int,string> color_decoding;
    language_rep (string s);
  virtual text_property advance (tree t, int& pos) = 0;
  virtual array<int> get_hyphens (string s) = 0;
  virtual void hyphenate (string s, int after, string& l, string& r) = 0;
  virtual string get_group (string s);
  virtual array<string> get_members (string s);
  virtual void highlight (tree t);
  virtual string get_color (tree t, int start, int end);
};
text_property advance (tree t, int& pos)
(lexical scanner)

Advances pos over the next token of the string t->label and returns a pointer to a text_property_rep, which tells the typesetter how much space and which line breaking penalties to put around the token. Programming languages return &tp_space_rep for a blank and &tp_normal_rep for everything else; these global objects are defined in

language.cpp

and declared extern in

impl_language.hpp

. The argument is a tree rather than a string so that implementations may find the position of the line in the document (see the section on multi-line comments in the next chapter).

string get_color (tree t, int start, int end)
(color of a token)

Returns a color specification for the token t->label (start, end) or the empty string for the default color. The specification is either the name of an environment variable (like keyword-color) or a color (like dark green or #309090). The default implementation returns "".

void highlight (tree t)
(packrat highlighting)

If hl_lan is nonzero and t does not yet carry highlighting information for this language, runs the packrat highlighter packrat_highlight (res_name, "Main", t). This is called by concater_rep::typeset for every subtree before it is typeset, as long as env->hl_lan != 0.

For programming languages, get_hyphens and hyphenate are trivial: only a position directly after a - followed by a letter is a (discouraged) break point, so long lines of code are essentially never hyphenated.

5.The concrete language classes

prog_language_rep

The generic highlighter (

prog_language.cpp

). It derives from abstract_language_rep, which owns one instance of each parser of Data/Parser/, and is configured at construction time from the Scheme function parser-feature. Its colors come from the preference based color decoding (see colors, preferences and themes). Used for Python, Java, Scala, Julia, JSON, CSV and any new language added in the recommended way.

scheme_language_rep

A small hand-written scanner for Scheme (

scheme_language.cpp

). Tokens are delimited by spaces and parentheses. get_color scans back at most 1000 characters on the current line to detect comments and strings, colors numbers, strings, keywords (:foo) and the symbols listed in highlight-any, and asks Scheme whether other symbols are defined? (the answer is cached in the member colored). The keyword list highlight-any is read from

tm-mode.el

, the Emacs mode for TeXmacs Scheme code, by the module

utils/misc/tm-keywords.scm

. The returned colors are names of environment variables (comment-color, string-color, number-color, alt-keyword-color, alt-constant-color, defined-color).

cpp_language_rep

A hand-written highlighter for C and C++ (

cpp_language.cpp

) with built-in tables of keywords, types and constants, support for preprocessor lines (the test for continuation lines, end_preprocessing, looks for a trailing / rather than a backslash) and C-style comments spanning several lines. It returns environment variable names. Note that, although

plugins/code/progs/cpp-lang.scm

contains a complete parser-feature description for cpp, the dispatcher prog_language never uses it, since cpp is matched earlier.

mathemagix_language_rep, r_language_rep

Hand-written highlighters (

mathemagix_language.cpp

,

r_language.cpp

). The former returns environment variable names, plus a fixed color COLOR_MARKUP for markup; the latter mostly returns literal colors such as #8020c0 or dark green.

scilab_language_rep, fortran_language_rep

Hand-written highlighters (

scilab_language.cpp

,

fortran_language.cpp

) which, like prog_language_rep, use decode_color and thus the preferences syntax:scilab:* and syntax:fortran:*.

verb_language_rep

The fallback (

verb_language.cpp

). It splits the text at spaces and at the characters -, /, \, , and ?, which become allowed line breaks. Its constructor sets hl_lan= packrat_abbreviation (res_name, "Main"), so that if a packrat grammar with the same name as the language and a symbol Main exists, the text is highlighted according to that grammar; otherwise no colors are produced. The test language minimal (

language/minimal.scm

, markup minimal) works in this way.

Text and mathematics use other subclasses (

text_language.cpp

,

math_language.cpp

), which are outside the scope of this chapter.

6.Typesetting a string in programming mode

The entry point for atomic trees is concater_rep::typeset (

Typeset/Concat/concater.cpp

):

if (env->hl_lan != 0)
  env->lan->highlight (t);

if (is_atomic (t)) {
  if      (env->mode == 1) typeset_text_string (t, ip, 0, N(t->label));
  else if (env->mode == 2) typeset_math_string (t, ip, 0, N(t->label));
  else if (env->mode == 3) typeset_prog_string (t, ip, 0, N(t->label));
  else                      typeset_text_string (t, ip, 0, N(t->label));
  return;
}

The same dispatch occurs in concater_rep::typeset_range (

Typeset/Concat/concat_macro.cpp

), which typesets a substring [i1, i2) of a string; this is why typeset_prog_string receives the whole tree together with a start and an end position. The core loop is (abridged):

void
concater_rep::typeset_prog_string (tree t, path ip, int pos, int end) {
  array<space> spc_tab= env->fn->get_normal_spacing (env->spacing_policy);
  string s= t->label;
  int    start;
  do {
    start= pos;
    text_property tp= env->lan->advance (t, pos);
    if (pos > end) pos= end;
    if ((pos-start == 1) && (s[start]==' ')) { // spaces
      …
    }
    else { // strings
      penalty_max (tp->pen_before);
      PRINT_SPACE (tp->spc_before)
      string color= env->lan->get_color (t, start, pos);
      string content= s (start, pos);
      typeset_colored_substring (content, ip, start, color);
      penalty_min (tp->pen_after);
      PRINT_SPACE (tp->spc_after)
    }
  } while (pos<end);
}

Two properties of this loop matter for language implementors:

The color specification is resolved by:

void
concater_rep::typeset_colored_substring
  (string s, path ip, int pos, string col)
{
  color c;
  if (col == "")
    c= apply_alpha (env->pen->get_color (), env->alpha);
  else if (env->provides (col)) {
    tree t= env->read (col);
    if (t == "") c= apply_alpha (env->pen->get_color (), env->alpha);
    else c= named_color (as_string (t), env->alpha);
  }
  else c= named_color (col, env->alpha);
  box b= text_box (ip, pos, s, env->fn, c);
  a << line_item (STRING_ITEM, OP_TEXT, b, HYPH_INVALID, env->lan);
}

An empty specification, or an environment variable whose value is empty (by default operator-color and misc-lexeme-color), means “use the current text color”. Since the color is looked up in the environment at typesetting time, colors given as variable names follow the current theme and any with in the document, whereas literal colors do not.

The resulting line items are ordinary text boxes; line breaking, cursor movement and selections work exactly as for text (see the chapters on the typesetter and on boxes).

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