![]() |
Adding a language, performance and pitfalls | ![]() |
This section walks through the addition of a hypothetical language lua with the generic highlighter prog_language_rep, which requires no C++ changes. The file names follow the conventions of the existing languages of the code plugin; all code shown is an example to be adapted, not existing code.
Create src/plugins/code/progs/lua-lang.scm. The module name must be (lua-lang), since prog_language_rep loads it with (use-modules (lua-lang)), and the file must be found by prog_lang_exists (here: in $TEXMACS_PATH/plugins/code/progs/ after installation).
(texmacs-module (lua-lang)
(:use (prog default-lang)))
(tm-define (parser-feature lan key)
(:require (and (== lan "lua") (== key "keyword")))
‘(,(string->symbol key)
(constant "true" "false" "nil")
(declare_function "function")
(keyword "local" "end" "in" "and" "or" "not")
(keyword_conditional "if" "then" "else" "elseif" "for" "while"
"do" "repeat" "until" "break")
(keyword_control "return" "goto")))
(tm-define (parser-feature lan key)
(:require (and (== lan "lua") (== key "operator")))
‘(,(string->symbol key)
(operator "+" "-" "*" "/" "%" "^" "#" ".."
"==" "~=" "<=" ">=" "<" ">" "=")
(operator_field "." ":")
(operator_openclose "{" "[" "(" ")" "]" "}")))
(tm-define (parser-feature lan key)
(:require (and (== lan "lua") (== key "number")))
‘(,(string->symbol key)
(bool_features "prefix_0x" "sci_notation")))
(tm-define (parser-feature lan key)
(:require (and (== lan "lua") (== key "string")))
‘(,(string->symbol key)
(bool_features "hex_with_8_bits")
(escape_sequences "\\" "\"" "'" "a" "b" "f" "n" "r" "t" "v")))
(tm-define (parser-feature lan key)
(:require (and (== lan "lua") (== key "comment")))
‘(,(string->symbol key)
(inline "--")))
(define (notify-lua-syntax var val)
(syntax-read-preferences "lua"))
(define-preferences
("syntax:lua:comment" "brown" notify-lua-syntax)
("syntax:lua:keyword" "#309090" notify-lua-syntax)) |
Note that the word operators and, or and not are declared as keywords rather than operators: operators are matched before keywords and without regard to word boundaries (see the pitfalls below). Lua block comments --[[ … ]] cannot be expressed; only /* … */ is supported for multi-line comments.
prog_language only builds a prog_language_rep if the format exists. Declare it next to the other formats of the plugin in
src/plugins/code/progs/code-format.scm
:
(define-format lua
(:name "Lua source code")
(:suffix "lua"))
(define (texmacs->lua x . opts)
(texmacs->verbatim x (acons "texmacs->verbatim:encoding" "SourceCode" '())))
(define (lua->texmacs x . opts)
(code->texmacs x))
(define (lua-snippet->texmacs x . opts)
(code-snippet->texmacs x))
(converter texmacs-tree lua-document (:function texmacs->lua))
(converter lua-document texmacs-tree (:function lua->texmacs))
(converter texmacs-tree lua-snippet (:function texmacs->lua))
(converter lua-snippet texmacs-tree (:function lua-snippet->texmacs)) |
and add lua to the corresponding line of
init-texmacs.scm
:
(lazy-format (code-format) cpp julia scala java json csv lua) |
With the format in place, opening a .lua file gives a buffer in programming mode with prog-language set to lua (attach_subformat), and the snippet converters are used by copy and paste in programming mode.
Add an inline and a block macro to
src/TeXmacs/packages/environment/env-program.ts
:
<assign|lua-lang|<macro|body|<with|mode|prog|prog-language|lua|font-family|rm|body>>> <assign|lua-code|<macro|body|<pseudo-code|<lua-lang|body>>>> |
(in the existing file, the block macros are written in block form). Then register the tags in the groups inline-code-tag and block-code-tag of
text/text-drd.scm
, so that generic editing functions recognize them as code, and add entries ("Lua" (make 'lua-lang)) and ("Lua" (make 'lua-code)) to code-menu in
text/text-menu.scm
.
Add mode predicates to
kernel/texmacs/tm-modes.scm
:
(in-lua% (== (get-env "prog-language") "lua"))
(in-prog-lua% #t in-prog% in-lua%) |
Create prog/lua-edit.scm and add (prog lua-edit) to the :use list of
prog/prog-kbd.scm
:
(texmacs-module (prog lua-edit)
(:use (prog prog-edit)))
(tm-define (program-compute-indentation doc row col)
(:mode in-prog-lua?)
(if (<= row 0) 0
(let* ((r (or (program-row (- row 1)) ""))
(i (string-get-indent r))
(tr (tm-string-trim r)))
(if (or (string-ends? tr "then") (string-ends? tr "do")
(string-prefix? "function" tr))
(+ i (get-tabstop))
i))))
(tm-define (notify-cursor-moved status)
(:require prog-highlight-brackets?)
(:mode in-prog-lua?)
(select-brackets-after-movement "([{" ")]}" "\\"))
(kbd-map
(:mode in-prog-lua?)
("(" (bracket-open "(" ")" "\\"))
(")" (bracket-close "(" ")" "\\"))
("\"" (bracket-open "\"" "\"" "\\"))) |
After rebuilding and installing (the plugin files and packages are copied by the build), evaluate (format? "lua") in a Scheme session: it must return #t. Insert a lua-code block and type some code; if nothing is colored, the language most probably fell back to verb_language_rep. Enabling (debug-set "parser" #t) before the language is first used prints the configuration of the string and preprocessor parsers on the debugging console. Remember that the language object, and hence the result of the format test, is cached for the whole session: restart TeXmacs after changing the definitions.
A user can also provide a language without modifying TeXmacs, as a plugin in $TEXMACS_HOME_PATH/plugins/lua/progs/: the file lua-lang.scm there is found by prog_lang_exists, and the plugin initialization must declare the format with define-format and define the markup in a style package of the plugin.
If the generic highlighter is not expressive enough (other string delimiters, nested comments, context dependent coloring, colors that follow themes), write a C++ class derived from abstract_language_rep as for
cpp_language.cpp
: declare it in
System/Language/impl_language.hpp
, implement advance, get_hyphens, hyphenate and get_color, and add a test for its name to prog_language before the generic case. The sources of
System/Language/
are collected by a glob in
src/CMakeLists.txt
, so it suffices to re-run CMake. Return names of environment variables from get_color to obtain theme-aware colors.
Highlighting happens during typesetting, so its cost is paid for every line which is (re)typeset. The typesetter only re-typesets modified paragraphs, and every line of a program is a paragraph, so editing usually costs little; the cost matters when a long file is typeset as a whole (loading, changing the style or the page width, zooming).
Caching of language objects. prog_language is a hash-table lookup after the first call; the expensive construction (loading the Scheme module, evaluating parser-feature six times) happens once per language and session. The environment only calls prog_language when mode or prog-language changes.
Caching of colors. Decoded colors are cached per language in color_decoding. The Scheme highlighter caches the result of defined? for every symbol in colored.
Per-token rescanning. For each token, prog_language_rep::get_color scans the line from its beginning for an inline comment start, and in_comment may scan the current line and all previous lines up to the nearest /*, and then following lines up to a */. The C++ highlighter re-parses the line from the start for every token as well. The cost of a line is therefore at least quadratic in its length, and, in a long file with few comments, each token may cause a scan over many lines.
Operator and string tables. operator_parser_rep and string_parser_rep iterate over all their entries at every position where they are tried; very large operator tables are slow.
Packrat highlighting. The packrat mechanism parses the whole document with the start symbol, but stores the results in highlight observers and only re-parses the range of lines which lost their highlighting after a modification.
The following list is based on reading the current code; it is meant to help developers interpret surprising colors.
Two different language mechanisms coexist. A language name may be handled by a hard-wired C++ class, by the generic prog_language_rep, or by the fallback. In particular
cpp-lang.scm
does not influence the highlighting of C++, and languages with a -lang.scm file but without a format (currently javascript, dot, octave) are not highlighted.
Cached decisions. Once prog_language has created an object for a name, it is used for the rest of the session. A parser-feature or format defined later is ignored.
Keywords. keyword_parser_rep reads a run of ASCII letters. Keywords containing digits, underscores or spaces (for instance wchar_t, __debug__ or abstract type) never match, and the letter prefix of an identifier is colored if it is a keyword: in for_each, the part for is colored as a keyword.
Word operators. Operators are tried before keywords and identifiers and without checking word boundaries. With
python-lang.scm
, which lists and, or and not as operators, the beginning of identifiers like order or notify is colored as an operator.
Unknown color classes. A group name not known to encode_color is drawn in the syntax:lan:none color, red by default (for instance operator_decoration).
Comments and strings. The inline comment test in prog_language_rep::get_color does not know about strings, so that a # inside a Python string turns the rest of the line into a comment. Multi-line comments are always C style. The detection of multi-line comments only works when the lines are the direct string children of a document in the edited tree; it fails in inline code and for lines containing markup. It is also heuristic: a line such as /* a */ x = 1; followed, somewhere below, by a line containing */ has its code colored as a comment.
Stale colors across lines. Inserting or removing /* or */ changes the color of other lines, but only the modified line is re-typeset; the other lines are updated when they are typeset again.
State shared across strings. The string parser of a language object keeps its state between calls. An unterminated string literal therefore continues into the next string typeset with the same language, which may belong to another line, another code block or even another document, depending on the typesetting order.
Escape sequences. In escaped_char_parser_rep, escape sequences of more than one character (such as newline in
python-lang.scm
and
julia-lang.scm
) advance one character too little, and octal escapes are never recognized because can_parse does not test for them.
Variable names versus macros. The names returned by get_color are looked up with env->provides. If a package defines a macro with the same name, its value is not a color. For example,
utilities/comment.ts
defines a macro comment-color, which shadows the variable used for comments in Scheme and C++ code.
Markup names.
environment/env-program.ts
first defines java, python, julia, scala, r, scilab and fortran as names of languages, and then redefines them as inline code macros with one argument; only the second definitions are effective. In documentation, use scheme and c++ for the names, which are not overridden. The groups in
text/text-drd.scm
mention inline tags octave, javascript and json, whereas the macros are called octave-lang, javascript-lang and json-lang.
Editing is separate from highlighting. Bracket matching and indentation work on raw characters and know nothing about strings and comments (see the FIXME in
prog/python-edit.scm
). For languages without an overload of program-compute-indentation, such as C++, pressing return resets the indentation of the new line to zero.