Table of Contents
- Language Files
- 1. What a language file is for
- 2. Parsing a language in a program
- 3. The file format
- 4. [language]: the name, the files and the blocks
- 5. [lexical]: how the text is cut into tokens
- Names
- Comments
- Strings
- Characters and numbers
- Regular expressions, quote operators and variables
- Directives, attributes and other tokens
- Markup and documents
- 6. [lines], [words], [symbols] and [editing]
- [lines]: lines by their first characters
- [words]: the words of each class
- [symbols]: simple definition patterns
- [editing]
- 7. Blocks and folding
- 8. Embedded languages
- 9. Styles
- 10. Rules the lexer always follows
- 11. C and C++
Language Files
Kami has no list of languages built into it, apart from C and C++. It learns each language from a language file: a plain text file that says which files are in the language, how to cut its text into tokens, which words it has, how it makes blocks and how to find its declarations. This page explains how a program parses a language file and chooses the language of a file, the format of the file, and every key of every section. The [grammar] section and the keys that only a grammar uses have a page of their own, Grammars. Unryu ships 86 language files, and its manual describes them from a user's side.
1. What a language file is for
A language file is text. language_parse() turns it into a Language, a plain struct that holds every setting of the file. Kami never reads a language file from the disk itself, so a program can keep its language files where it likes, ship them inside itself, or hand them to a sandboxed process. The parts of the struct are used by different calls:
One parsed Language serves every call. The lexer always runs first; the model and the folds read its tokens. Nothing here draws anything: a program gives each style a color.
2. Parsing a language in a program
| Call | What it does |
|---|---|
language_parse(&language, text, id) |
Parses one language file. id is the language's id, normally the file's name without .lang ("python"); it is also its name until a name key sets one. A key or section that Kami does not know is ignored, and a value that is not valid leaves the default, so a file with a mistake never makes the call fail. A [grammar] that cannot be compiled leaves language.grammar NULL and says why in language.grammar_problem. Returns 0, or -1 when out of memory. Free the language with language_free(). |
language_set_parse(&set, text) |
Parses several language files in one text, for a file that embeds other languages. Each file starts with a line %%language ID; a text whose first line is not such a line starts with a file whose id is main. The first language of the set is the language of the text being read, the others are the languages it embeds. Free the set with language_set_free(). |
language_set_find(&set, word, length) |
The language of a set that a word names, such as the word after a Markdown code fence: the word is compared, in any case, with each language's id, then with each name, then with each language's extensions. NULL when none matches. |
language_builtin("c"), language_builtin("cpp") |
Kami's own C and C++ languages, parsed once from the files built into Kami, the first time they are asked for. lexer_run() uses them. language_builtin_text() gives the text of those files. |
language_match(&language, path, first_line) |
How well a language fits a file: 3 when its filenames list holds the file's whole name, 2 for one of its extensions or a filenames pattern, 1 when the file's #! line names one of its shebangs, 0 for none. first_line may be NULL. |
language_detect_score(&language, text, length) |
How many of the language's detect words appear in the first 4 KB of a text. When two languages fit a file equally well, the one with the higher score is the better guess. |
To choose the language of a file, call language_match() for every language and take the highest result; break a tie with language_detect_score(), and if that ties too, with any rule the program likes (Unryu takes the language whose name sorts first). These are the details of the match:
- The whole name is the part of the path after the last
/. It is compared with each word offilenamesexactly; case matters. - The extension is the text after the last dot of the name. It is compared with each word of
extensions, and case matters (Candcare different extensions). An extension with a dot in it (pyx.in) can never match: use afilenamespattern such as*.pyx.ininstead. - A word of
filenameswith*or?in it is a pattern (Makefile.*,.bash_*,*rc), matched as the shell matches a file name, and counts as much as an extension. - For
#!, only the program's own name counts:#!/usr/bin/python3and#!/usr/bin/env python3both namepython3, andenv -Sis understood too. - A detect word counts once, wherever it appears in the first 4 KB, even inside another word, and case matters.
3. The file format
A language file is a plain text file in sections, like an INI file:
- A line
[name]starts a section. The sections are[language],[lexical],[lines],[words],[symbols],[grammar]and[editing]. The names[markup]and[markdown]are also accepted and mean the same as[lexical]. Keys in a section of another name, and keys before the first section, are ignored. - Every other line is
key = value. The key ends at the first=(an equals sign with a space on each side), or at the first=when there is none, so a key in[lines]may itself hold=. Spaces around the key and the value are dropped. A line with no=is ignored. - A line that starts with
;is a comment, and so is a line that starts with#, except in[lines], where#can be a line prefix. Blank lines are ignored. ([grammar]has rules of its own: see Grammars.) - A key with an empty value is the same as a key that is not there: it keeps the default. So a file can list every key, most of them empty, as Unryu's files do.
- A list is separated by spaces:
extensions = py pyw pyi. To put a space inside one item, write the item in double quotes:"( "is Forth's comment opener, with its space. A lone", or""", is just that text. - A yes-or-no key is on with
trueoryes(in any case) or1, and off with anything else. - A key that takes one character takes its value when the value is exactly one character long;
none, an empty value or a longer value means no character. - A key that takes characters (such as
variable-prefixesorregex-flags) takes each character of its value, with spaces dropped:$ @ %and$@%are the same. - Most keys may be written again, and a second line replaces the first. The marker and word lists add up instead: each line adds its items to the list. These are the lists of
[lexical]markers (line-comment,string,operatorsand the like), the block-word lists of[language](block-start,block-endand the like), and[words]. Some keys hold one entry per line and "may come again": each line adds one more entry (oneblock-commentline for each kind of block comment). The tables below say which keys these are.extensions,filenames,shebangs,detect, thelayout-keys,operator-characters,soft-keywords,conditional-wordsand every key that takes characters are replaced by a second line. - Key and section names are written in lower case, as shown on this page. Markers, words and patterns are compared with the text exactly, unless the language sets
case-sensitive = false.
These limits apply; what goes past them is dropped:
| What | Limit | Constant |
|---|---|---|
| Markers in one list (comments, strings, prefixes ...) | 24 | LANGUAGE_LIST_MAX |
Entries of a key that may come again (block-comment, embed ...) |
24 | LANGUAGE_LIST_MAX |
| Operators | 320 | LANGUAGE_OPERATORS_MAX |
| The length of one marker | 15 bytes | LANGUAGE_MARKER_MAX (16, with the NUL) |
[symbols] patterns, and words in one pattern besides NAME |
32, and 6 | LANGUAGE_SYMBOLS_MAX, LANGUAGE_PATTERN_MAX |
[lines] rules |
24 | LANGUAGE_LIST_MAX |
block-rule lines, and the words of one rule's test |
32, and 10 | LANGUAGE_BLOCK_RULES_MAX, LANGUAGE_BLOCK_WORDS_MAX |
| The id and the name | 63 bytes each | |
extensions, filenames; shebangs, detect |
511 bytes; 255 bytes |
A small complete example
This is a whole language file for a made-up language, Tiny. With it, Kami colors .tiny files, finds their functions and variables, folds their blocks, checks their syntax and links each name to its definition. Every key it leaves out keeps its default.
; Tiny: a small example language
[language]
name = Tiny
extensions = tiny
shebangs = tiny
engine = generic
blocks = keywords
block-start = func if while
block-end = end
layout = lines
layout-ignore-in = (
[lexical]
line-comment = #
string = "
escape = \
number-separator = _
operators = == != <= >= = + - * / < > , ( )
[words]
keyword = func if while end return var
constant = true false nil
builtin = print
[symbols]
function = func NAME
variable = var NAME
[grammar]
file = @many(statement) END
statement = function / declaration / if_stmt / while_stmt / return_stmt / expression NEWLINE
function = "func" NAME:function @body("(" parameters? ")" NEWLINE @many(statement, "end") "end") NEWLINE
parameters = NAME:parameter ("," NAME:parameter)*
declaration = "var" NAME:variable "=" expression NEWLINE
if_stmt = "if" expression NEWLINE @block(@many(statement, "end")) "end" NEWLINE
while_stmt = "while" expression NEWLINE @block(@many(statement, "end")) "end" NEWLINE
return_stmt = "return" expression? NEWLINE
expression = operand (OP operand)*
operand = NUMBER / STRING / "true" / "false" / "nil" / call / NAME:use / "(" expression ")"
call = NAME:use "(" (expression ("," expression)*)? ")"
[editing]
comment-toggle = "# "
With it, this file is valid. The model has the symbols countdown, n and i, and each later i and n names its definition:
# Count down from a number.
func countdown(n)
var i = n
while i > 0
print(i, "left")
i = i - 1
end
return nil
end
countdown(1_000)
An Example Program reads this language and this file in a program.
4. [language]: the name, the files and the blocks
| Key | What it does |
|---|---|
name |
The name for people. Default: the id. |
extensions |
File name endings, without the dot, separated by spaces. Case matters. |
filenames |
Whole file names (Makefile, .bashrc), or patterns with * (any text) and ? (any one character), such as Makefile.* or *rc. |
shebangs |
The program names that a #! first line may give: python python3. |
detect |
Words that, found in the first 4 KB of a file, decide between two languages that claim the same ending (language_detect_score()). |
engine |
generic (the default), c or c++. It says what should read the tokens after the lexer. Kami's calls do not choose by it: a program calls semantic_build() for a language whose engine is c or c++, and language_symbols_build() for the others. The lexer reads it too: with c++ it sets LEXER_CPLUSPLUS in the lexer's options, and with generic a number ends before a dot that a letter follows, unless the letter is an exponent letter (3.times is the number 3 and then .times), and before two dots (0..5 is a range). With c and c++ a number is a preprocessing number, kept whole as the C standard says: 1..2 is one number there. Use c or c++ only for languages that are C or C++ underneath. |
blocks |
How the language makes blocks: braces (the default), indent, keywords or none. See Blocks and folding. |
block-start |
With blocks = keywords: words that open a block when they start a statement (if, def, while). A list. |
block-open |
Words that open a block wherever they are (do, function). A list. |
block-end |
Words that close a block (end, until). A list. |
block-endless |
Openers that have no closer when their name is followed by =, like Ruby's one-line def area = width * height. A list. |
block-join |
Words that continue the block above instead of opening a new one: Ada's begin after procedure P is. A list. |
block-join-to |
The openers that a block-join word continues, once each (Ada: procedure function package task protected entry declare). A list. |
block-rule |
A block word, a test and the test's words: when the block word really opens or closes a block. May come again. See Blocks and folding. |
statements |
lines: a statement ends at the end of its line, unless the line ends with the line-continuation character or the next line starts with it (Fortran, FreeBASIC). Otherwise a statement ends at a ;. This decides where a block-rule looks. |
continuation-column |
For fixed-form languages: a column, counted from 1, where any character other than a space or 0, after blank columns, joins the line to the line before it (Fortran 77: 6). The grammar uses it. |
pairs |
The pairs besides brackets that language_pairs() finds (Braces): any of quotes comments interpolation tags angles keywords conditionals text (Language.pair_kinds, a bit for each LanguagePairKind). |
keyword-pair |
An opening word and its closing word, for a language whose blocks are not keywords: the shell's if fi. Several openers may share a closer. May come again (Language.keyword_pairs). |
named-pair |
An opening command and its closing one whose { } names must match: LaTeX's \begin \end. May come again (Language.named_pairs). |
text-pairs |
Opening and closing characters in turn, paired in prose: « » “ ” (Language.text_pairs). |
void-tags |
Elements that have no end tag (Language.void_tags). |
optional-end-tags |
Elements whose end tag may be left out: they close with their parent (Language.optional_end_tags). |
The other keys of [language] are explained on Grammars: layout and the keys that start with layout-, soft-keywords, split-operators, self-words, class-scope, sigil-free-names, loose-strings and assign-scope matter only for a language with a grammar, while operator-characters, underscore-operators, dotted-operators, digit-names and continuation-in-strings change how the lexer cuts tokens in any language.
5. [lexical]: how the text is cut into tokens
The [lexical] keys describe the language's tokens. Where two kinds of token could start at the same place, the longest opener wins among comments, strings, characters, heredocs and delimited strings, and between openers of the same length a comment wins over a string: Python's ''' opens a multi-line string, not two strings, and C's /* is a comment, not a division. Some tokens are tried before these, whatever their length: variables by sigil or by delimiters, command substitutions, hash-colors and number-prefixes numbers. Lua's long brackets and Swift's #" win only over an opener of one character. Keys marked "a list" add up over several lines.
Names
| Key | What it does |
|---|---|
identifier-start |
The characters a name can start with: ranges such as A-Z, single characters such as _ $ (each character of such a word counts), and unicode for every byte of a non-ASCII character. Default: A-Z a-z _ unicode. |
identifier-part |
The characters a name can go on with. Default: A-Z a-z 0-9 _ unicode. |
identifier-escapes |
Escapes that a name may contain, such as C's \u and \U. A list. |
case-sensitive |
false: words, names, line-comment markers, delimited-string openers and operators match in any case (SQL, Pascal, Fortran). Other markers (block comments, string delimiters, [lines] prefixes) are still compared exactly. Default: true. Set it before the [words] section, because words are stored as they are read. |
unicode-spaces |
true: Unicode space characters (no-break space, em space and so on) are white space. A name ends at such a character in every language; without this key the character itself is not skipped as white space. |
uppercase-style |
A style for names that start with a capital letter (Erlang: variable, Haskell: type). Words of [words] keep their own class. With variable, a name that starts with _ (and is longer than _) is a variable too. |
name-prefix |
A prefix and a style: a name that is none of the language's words and starts with the prefix gets the style (CSS: name-prefix = -- variable makes --accent a variable). May come again. |
backtick-names |
true: `a name` in backquotes is one name (Swift, Kotlin, Scala). |
Comments
| Key | What it does |
|---|---|
line-comment |
Markers of a comment that runs to the end of the line: //, #, --. A marker can be a word, such as Batch's REM. A list. |
block-comment |
An opener and its closer: /* */. May come again. |
nested-comments |
true: a block comment may hold another one (Rust, Haskell). |
doc-comment |
Openers that make a comment documentation (/** /*! /// //!): it gets the comment-doc or comment-line-doc style. A comment no longer than its opener and closer (/**/) is not documentation. A list. |
directive-comment |
Openers that make a comment a directive, with the preprocessor style: Pascal's {$, Haskell's {-#. A list. |
comment-at-word-start |
true: a line comment opens only where a word may start, so in a shell a#b is one word. |
line-block-comment |
An opener and a closer that must each start a line (after any indentation); the rest of that line belongs to the comment: Ruby's =begin and =end, Perl's =head1 ... =cut, Matlab's %{ and %}. The closer EOF means the comment runs to the end of the file. May come again. |
line-block-open-end |
true: such a comment may run to the end of the file without its closer (Perl's POD), with no fault. Without it, such a comment runs to the end of the file too, but is marked TOKEN_FLAG_UNTERMINATED. |
comment-column |
A column, counted from 1, where one of the column-comments characters makes the whole line a comment (Fortran 77: 1). |
column-comments |
Those characters (Fortran 77: C c * !). |
shebang-comment |
true: a #! first line is a comment. |
comment-strings |
true: a " string (or a tagged `{id |
literate |
true: the file is prose with code in it, as in Literate CoffeeScript. Prose starts at a line that is not indented, or that starts a list item, and runs to the next blank line; it is a comment. An indented line outside prose is code. |
comment-definition |
Words that, in this order inside a colon definition : NAME ... ;, make NAME a word that skips the rest of its line. Forth: SOURCE >IN !, so after : ~ SOURCE >IN ! Y ! ; the word ~ starts a line comment in that file. |
name-definition |
The same for a word that takes the next word as a name; alternatives are separated by ` |
name-words |
Words after which the next word, up to a blank, is a name whatever it holds. Forth: ' ['] POSTPONE [CHAR], so POSTPONE ." starts no string. A list. |
Strings
| Key | What it does |
|---|---|
string |
Delimiters of strings on one line: " '. The same delimiter opens and closes, and escapes apply. A list. |
raw-string |
Delimiters of one-line strings with no escapes. A list. |
multiline-string |
Delimiters of strings that may span lines: """ '''. A list. |
delimited-string |
An opener, its closer, and flags: C#'s @" " raw multiline doubling, Forth's ." ". The flags are raw (no escapes), multiline, doubling (a doubled closer inside is one character), escapes (a backslash escapes, whatever escape says), tag (an id may stand between the two characters of the opener, and the closer must hold the same id: OCaml's `{id |
string-prefixes |
Words that may stand right before a string and are part of it: Python's f b u r, C's u8 L. A list. |
raw-prefixes |
Those prefixes that make the string raw: r R. A list. |
any-string-prefix |
true: any name right before a " is the string's prefix (Julia: doc"x"). A prefix that is not in string-prefixes makes the string raw, with no interpolation. |
cpp-raw-prefixes |
Prefixes of C++ raw strings, R"tag( ... )tag": R u8R LR uR UR. A list. |
hash-raw-prefixes |
Prefixes of Rust raw strings, r#" ... "# with any number of #: r br. A list. |
hash-raw-strings |
true: #" ... "# with no prefix (Swift). |
long-brackets |
true: Lua's long strings [[ ]] and [==[ ]==]. |
long-bracket-comment |
A marker that turns a long bracket into a comment: Lua's --, for --[[ ... ]]. |
string-doubling |
true: a delimiter written twice inside a string stands for one (SQL and Pascal's 'it''s'). |
string-at-word-start |
true: a string opens only where a word may start (Tcl: a"b is one word). |
closer-takes-run |
true: a closer of more than one character also ends a longer run of its character (Nim: """a"""" ends after the last quote). |
smart-quotes |
true: a typographic quote also ends a string that a plain quote opened (PowerShell). A typographic quote does not open a string. |
heredoc |
Heredoc openers: << <<- <<~ <<<. The word after the opener ends the heredoc on a line of its own. The word may be quoted ('EOF', "EOF") or come after the escape (\EOF); 'EOF' and \EOF turn interpolation off. With <<~ and <<< the end word may be indented. The body's tokens get TOKEN_FLAG_HEREDOC. A list. |
heredoc-joined |
true: the heredoc word must follow the opener with no space (Ruby, so that class << self is no heredoc). With it, <<- also ends at an indented word. |
case-patterns |
A shell's case: the word that opens it, the word before the patterns, the word that closes it, then the words that end an item (case in esac ;; ;& ;;&). The ) after a pattern has no (, so it is not a bracket: brace matching and the ghosts ignore it. A pattern that opens with ( pairs as usual. |
command-embed |
A command, a language id, then how the command's code argument is found. A single-quoted argument that is the code is colored in that language, and its brackets pair. first: the first argument that is not an option (awk '{ print }'). after and options: the argument after one of them (perl -e, also -ne). skip and options: options that take a value, which is not the code; --arg:2 takes two. none and options: with one of them the code is in a file, so no argument is code (awk -f prog.awk). The command may follow env, sudo, xargs and settings such as LC_ALL=C, and may be a path. May come again. Shell has command-embed = awk awk first skip -F -v none -f --file and rules for sed, perl, python, ruby, node and jq. |
interpolation |
A string delimiter, an opener and a closer: code inside strings of that delimiter (" ${ }, Python's " { }). The code is lexed as code. An opener of one character written twice ({{) is a plain brace, not code. May come again. |
interpolation-prefixes |
Only strings with one of these prefixes interpolate (Python's f, Scala's s). Empty: every string of the delimiter does. A list. |
interpolation-variable |
A string delimiter and a sigil: $name inside such strings is a variable (" $). May come again. |
interpolation-format |
A character that, inside interpolated code, starts a format specification with fields of its own (Python's : in f"{x:{width}}"). |
escape |
The escape character, usually \. Default: none. |
escape-braces |
Letters after the escape whose { } belongs to the escape: Python's N for \N{NAME}. |
escape-in-code |
true: the escape quotes the next character outside strings too (the shell's \;). |
raw-escaped-quote |
true: in a raw string, the escape before the delimiter keeps the string open (Python's r'\''). |
Characters and numbers
| Key | What it does |
|---|---|
character |
Delimiters of character constants: '. A list. |
character-prefix |
Prefixes that, with one character after them, make a character constant: Erlang and Smalltalk's $a, Ruby's ?a. A prefix that ends in \ also takes a name (Lisp's #\space). A character given by its number after the escape is one character too ($\x41), and the character can be any UTF-8 character. A list. |
numbered-character |
A character that, with digits after it, is a character constant: Pascal's #13, and #$0D in hexadecimal. |
tick-style |
A style for a ' followed by a name that is not a character constant: Rust's lifetimes 'a (label), Ada's attributes 'First. A ' that starts no character constant is an operator when a space, a tab or an opening bracket follows it, or when it comes right after a name or a ) (Ada's T'(...)). |
number-separator |
A separator between digits: _, or C++'s '. |
number-characters |
More characters a number may hold: Ada's # in 16#FF#. |
number-prefixes |
Characters that start a number before its digits: Pascal's $FF, %1010, &17. A base letter H, O or B (in either case) may follow the prefix, when a hexadecimal digit follows it (BASIC's &HFF). |
exponent-letters |
Letters that may follow a number's dot as its exponent (Fortran: dD for 1.D13). Empty: e E. |
tick-numbers |
true: a ' and a base letter continue a number (Verilog's 4'b1010). |
hash-colors |
true: #fff and #ff8000 are numbers (CSS, configuration files). |
Regular expressions, quote operators and variables
| Key | What it does |
|---|---|
regex |
The delimiter of a regular expression literal, usually /. A regex opens only where a value may stand (after an operator other than ++, -- and ', an opening bracket or a regex-after word), and only when it closes on its line (or regex-multiline is on), so a / b stays a division. |
regex-flags |
Letters that may follow a regex: gimsuy. |
regex-after |
Words after which a regex may stand: return typeof. In a language with jsx, also words after which an element may stand. A list. |
regex-multiline |
true: a regex may span lines (Ruby's /x). |
regex-after-space |
true: after a name, a space and then a / with no space after it opens a regex (CoffeeScript: f /re/). |
quote-operators |
Words that start a string with any delimiter: Perl's q qq qw. A list. |
quote-in-quotes |
true: the delimiters of a quote operator's string sit inside quotes: Oracle's q'[ ... ]'. |
regex-operators |
Words that start a regex with any delimiter: Perl's m qr. A list. |
substitution-operators |
Words that start two parts with any delimiter: Perl's s tr y. A list. |
percent-literals |
% and a letter that start a string with any delimiter, where a value may stand: Ruby's %w %q %Q %i. A list. |
percent-regexes |
The same for a regex: Ruby's %r. A list. |
operand-at-line-start |
true: the first token of a line may be a value (a regex, a %w[]), because a statement starts there (Ruby). |
variable-prefixes |
Sigils: a sigil and a name are a variable ($ @ %). |
variable-specials |
Characters a sigil may stand before on their own: $? $# $1. Inside a string, a special digit takes all the digits after it ("$10"); in code it is one character ($10 is $1 and 0). |
variable-braces |
An opener and a closer: ${name} is one variable. The opener's first character must be one of the variable-prefixes. May come again. |
variable-delimiters |
An opener and a closer around a name: Batch's %name%. May come again. |
command-substitution |
An opener and a closer around code: the shell's $( ). The code inside is lexed as code. The opener's first character must be one of the variable-prefixes. May come again. |
quote-transpose |
true: a ' right after a value is an operator (Matlab's transpose). |
Directives, attributes and other tokens
| Key | What it does |
|---|---|
directive |
A character that, at the start of a line, makes the line a directive (C's #). Its tokens get TOKEN_FLAG_DIRECTIVE, and the character itself is a TOKEN_HASH. |
directive-first-column |
true: a directive starts only where its character is the very first character of the line (Haskell: #ifdef in column 1 is the C preprocessor). |
directive-word-prefix |
A character that, with a word after it, is a directive anywhere: Verilog's `define. |
header-words |
Words after which, in a directive, <...> is a header name (include import). A list. |
conditional-words |
The words of conditional code after the directive character, in the order if, else-if, else, end. Each position can list alternatives separated by ` |
conditional-in-line |
true: a conditional mark ends after its condition, and the rest of the line is code (Haxe: x = #if flash 1 #else 2 #end;). |
line-continuation |
A character that, at the end of a line, continues the line (a directive or a statement): \, Fortran's &. |
line-splice |
A character that, with a line end after it, vanishes everywhere, even inside a token (C's \). |
trigraphs |
true: C's trigraphs ??= and the rest are always read. (For C, LEXER_TRIGRAPHS turns them on for one call.) |
digraph |
An alternative spelling and the standard token: <% {. The token gets the standard token's kind and TOKEN_FLAG_DIGRAPH. May come again. |
less-colon-colon |
true: <:: is < and :: unless : or > follows (C++). |
attribute-prefix |
Characters that, with a word after them, make an attribute: @name. In CSS, # . make #id and .class. |
attribute-where-operand |
true: the prefix makes an attribute only where a value may stand, so Python's a @ b is an operator. |
attribute-brackets |
An opener and a closer of a whole attribute token: Rust's #[ ]. May come again. |
macro-suffix |
A character that, after a word, makes a macro call: Rust's name!. |
symbol-prefix |
A character that, with a word after it, makes a constant: Ruby and Lisp's :name. Not right after a name or a closing bracket, so Julia's a[1]:b stays a range. |
symbol-operators |
Operators that are symbols after the symbol-prefix, and :name=: Ruby's [] []= <=> == + -@. A list. |
full-stop |
true: a . followed by a space ends a statement rather than a number (Smalltalk's 1000.). |
operators |
The language's operators. Kami tries the longest first, whatever their order in the list. ( ) [ ] { } ; are tokens of their own even when they are not listed, but a longer listed operator that starts with one of them wins (((, ;;), and is an operator. A list of up to 320. |
Markup and documents
| Key | What it does |
|---|---|
markup |
true: the file is markup (HTML, XML): tags, attribute names and values, entities, comments, CDATA and declarations, with text between them. |
jsx |
true: <tag ...> where a value may stand is an element, with its tags, attributes, {code} and text (JSX in JavaScript and TSX, E4X, XML literals in Scala). Type arguments can follow a tag's name (TSX). |
markdown |
true: the file is a document with headings, fenced and indented code, quotes, lists, rules, code spans, emphasis, strong text and links. Every such language also knows a fence's language word, the quote kinds [!NOTE], task boxes [ ] and [x], and reference labels. With no inline key (that is, Markdown itself) Kami also knows front matter (YAML between --- lines, or +++ lines for TOML, at the very start), HTML blocks and tags, $math$ and $$ blocks, tables, ~~deleted~~, ==marked==, ^sup^, ~sub~, a link's text, address and title apart, footnotes, entities and escapes. |
lines-only |
true: a line that no [lines] rule takes is plain text with no tokens (Diff). |
code-region |
An opener and a closer around the language's own code inside markup: PHP's <?php ?>. May come again. |
embed |
A tag and the id of the language inside it: script javascript. May come again. See Embedded languages. |
fence-languages |
true: the word after a code fence (or in AsciiDoc's [source,python]) names the language of the block. |
block-fence |
A marker and a style: a line that is just the marker opens a block that runs to the next such line (AsciiDoc: ---- code, //// comment). May come again. |
inline |
A marker and a style: text between two of the markers on one line gets the style (** strong, ` code). May come again. With no inline line, Markdown's own rules apply. |
setext-headings |
The characters of a line that underlines the heading above it, or none. Default: = -. |
indented-code |
true: a line indented by four spaces after a blank line is code. Default: true. |
literal-after |
A marker (reStructuredText's ::). A line that ends with it opens a code block of the lines indented deeper under it. If the marker is followed by one word that names a language (.. code-block:: python), the block is lexed in that language; a word that names no language opens no block. |
6. [lines], [words], [symbols] and [editing]
[lines]: lines by their first characters
Each key is a prefix and its value a style: a line that starts with the prefix is one token of that style. Diff uses + = inserted, - = deleted and @@ = changed. The longest prefix that matches wins. Spaces around a key are dropped, so a prefix that ends with a space has to be written in double quotes ("== " = heading), and so does a prefix that starts with ;, which would otherwise start a comment: ";" = comment-line. A # is no comment in this section, so # can be a prefix as it is. A value that is not a style name is ignored, and so is a key of 16 bytes or more.
[words]: the words of each class
Each key is a style and its value a list of words: keyword = if else while, type = int float, constant = true false, builtin = print len. Any style name from the list of styles can be a key. A key that is not a style name is ignored. Lines add up, and a word listed twice keeps one of its classes. language_word_style() looks a word up.
The classes matter beyond highlighting: a keyword can never be a NAME in a grammar (see soft-keywords), and a keyword, type or constant is never declared by a [symbols] pattern. A builtin can be declared, so a file may assign to it (Make's CC := cc).
[symbols]: simple definition patterns
A language without a grammar finds its definitions with patterns. A language with a grammar keeps its patterns too: language_symbols_build() uses them when the grammar gives up on a file. Each key is a kind, and each value a pattern of words around the word NAME; every line adds a pattern.
[symbols]
function = def NAME
function = async def NAME
class = class NAME
variable = ^ NAME =
not-after = end
| Part | Meaning |
|---|---|
| the key | The kind of definition, and the SemanticKind it gives: variable (SEMANTIC_VARIABLE), function and method (SEMANTIC_FUNCTION), type (SEMANTIC_TYPEDEF), class, struct, namespace and module (SEMANTIC_TAG), constant (SEMANTIC_ENUMERATOR), label (SEMANTIC_LABEL), macro (SEMANTIC_MACRO), member and field (SEMANTIC_MEMBER). |
NAME |
The name being defined. A pattern must have exactly one NAME and at least one other word, or it is ignored. |
| a word | That exact token: def, =, : (in any case when the language sets case-sensitive = false). |
* |
Any name that is not a keyword, a constant or a preprocessor word, and is not on a directive line, such as a type: variable = * NAME ;. |
(...), [...] |
A whole group in parentheses or square brackets. |
'*' |
A word in single quotes is that word itself, for words that mean something in patterns (Nim's export mark '*'). |
^ |
Before NAME only: what follows starts its line (Batch's :label). |
$ |
After NAME only: what comes before ends its line. |
not-after |
Words after which no pattern defines anything on the same line: end, so Fortran's end subroutine foo does not define foo again. A list. |
A pattern that starts with NAME matches only at the start of a line, so in a Makefile echo a: b inside a recipe is not a target. In function TSquare.Area, TSquare only qualifies the name: a pattern function NAME does not define TSquare, and only a pattern with * . NAME defines Area. The model of other languages says how the definitions are nested and how uses are found.
[editing]
Kami only keeps these keys, for the program:
| Key | What it holds |
|---|---|
comment-toggle |
What an editor puts before a line to comment it out (Language.comment_toggle, at most 15 bytes). Use quotes to keep a space at the end: comment-toggle = "# ". An editor may fall back on the first line-comment marker when it is empty, as Unryu does. |
indent-after |
Characters that, at the end of a line, should make the next line one level deeper (Language.indent_after; Python's :). |
import-words, import-separator, import-files |
How the language brings in another file, for an editor that follows imports (Language.import_words, import_separator, import_files): the words (import from), the character between a module's parts (.), and the files a module can be with {} for its path ({}.py {}/__init__.py). |
unicode-escape |
How the language writes a character in a string, for an editor that turns characters into escapes (Language.unicode_escape): a form up to U+FFFF and one past it, where %4 and %8 are that many hex digits and % as few as needed (C: \u%4 \U%8); utf16 as the second form means a surrogate pair of the first (Java). |
semicolon-after |
Words, separated by spaces, whose { } block ends with a ; (Language.semicolon_after, at most 63 bytes). C has struct union enum and C++ adds class. An editor that closes a { by itself can then type }; after struct point {, as Unryu does. |
spelling |
What a spelling checker reads of the language (Language.spelling, a LanguageSpelling), which language_spelling_ranges() gives as runs of the text: code (the default) for comments and the strings that have a space in them; prose for all of the text but its code spans, links, tags, entities, commands, numbers and operators (Markdown, LaTeX); markup for comments, strings with a space, and the text between the tags (HTML, XML); none for nothing (a diff, JSON). |
7. Blocks and folding
The blocks key says how the language makes blocks. In a language without a grammar, blocks decide which definition holds which (a method inside its class), and they give the folds: language_indent_folds() for indent and language_keyword_folds() for keywords (see Folds). A language with a grammar takes its scopes and blocks from the grammar instead. blocks has no effect on brace pairing.
| Value | A definition's block is | Languages |
|---|---|---|
braces |
The { } after the definition's name, past any ( ) and [ ] and before a ;. A line at the same indentation that starts with a word is the next statement, so Go's package main gets no block. |
C, Java, JavaScript, Rust, Go ... |
indent |
The deeper lines under the definition's line (blank lines inside belong to it). Lines inside an open bracket continue the line above and make no block of their own. | Python, YAML, Nim ... |
keywords |
From an opening word to the closing word that matches it. | Ruby, Lua, Julia, Matlab, Pascal, Verilog, Ada, Fortran, VHDL, SQL ... |
none |
There are no blocks; definitions are flat. | COBOL, Assembly, configuration files, documents ... |
Keyword blocks
With blocks = keywords, a block-start word opens a block only at the start of a statement, so Ruby's x if y opens no block. A block-open word opens a block anywhere. A closer inside brackets closes only a block opened inside the same brackets, so Matlab's a(end) closes nothing. An opener that is still open when its bracket closes had no closer and is dropped (Ada's (if a then b else c)). A block word on a directive line is not a block word. A block-endless word followed by its name and = opens no block. A block-join word does not open a block when the open block came from a block-join-to word that it has not joined yet, so procedure P is ... begin ... end P; is one block. A block-open word on the line of a block-start word that is still open opens no second block (while x do). A block word right after . or : is a name (a.end). A word right after a closer on its line is part of the closer (end if). An opener followed by ; opens nothing (Pascal's forward TShape = class;).
A block-rule line is a block word, a test and the test's words. The rule decides whether the word opens or closes a block at a given place; when a word has several rules, each must allow it. In the test's words, 0 stands for any number and " for any string. The word's statement starts at the word and ends at a ; or at a bracket that closes outside it; with statements = lines, it also ends at the end of the line. A rule with an unknown test is ignored.
| Test | The word counts | Example |
|---|---|---|
alone |
Only when it is alone on its line. | SQL: declare alone |
not-alone |
Only when more follows on its line. | FreeBASIC: end not-alone |
next-not |
Not when the next token is one of the words. | Fortran: do next-not 0 |
not-after |
Not right after one of the words, on the same line. | FreeBASIC: sub not-after declare exit as |
line-not |
Not on a line that starts with one of the words. | VHDL: generate line-not elsif else |
ends |
Only when its statement ends with one of the words. | Fortran: if ends then |
has |
Only when its statement holds one of the words, outside brackets. | Ada: procedure has is |
has-not |
Not when its statement holds one of the words. | VHDL: component has-not map |
after-not |
Not when the first of the words, in its statement, is followed by one of the others. | Ada: package after-not is new separate |
group |
Only when its statement is the word and one ( ) group. |
Fortran: where group |
8. Embedded languages
Some files hold code in other languages. Kami lexes that code with the other language's own file. To make that possible, the program puts the file's language and every language it may embed into one text, each after a line %%language ID, parses it with language_set_parse(), and lexes with language_lex_set(). When the set does not hold the language, its text is not lexed as code: inside markup it stays markup text, and a code fence or front matter is one token of the code or preprocessor style.
| Where | How the other language is found in the set |
|---|---|
HTML's <script> and <style> |
embed = script javascript and embed = style css: the tag name (in any case) and the language id. |
| PHP in HTML | code-region = <?php ?>: the language's own code between the markers, markup outside them. |
| A Markdown code fence | fence-languages = true: the word after ``` or ~~~ is looked up with language_set_find() (id, then name, then extensions, in any case). A fence in no language of the set gets the code style. |
| Markdown front matter | YAML between --- lines at the very start, lexed with the set's yaml language; +++ lines give TOML, lexed with a toml language when the set has one. |
| HTML in Markdown | HTML blocks and tags in a Markdown file, lexed with the set's html language. |
| An AsciiDoc listing | [source,python] on the line above a block-fence of style code. |
| A reStructuredText block | literal-after = ::: .. code-block:: python, then the indented lines. |
| A command's code in a shell script | command-embed = awk awk first ...: a single-quoted argument that is the command's code (awk '{ print $1 }', sed -e '...') is lexed with the set's language of that id. Its tokens have TOKEN_FLAG_EMBEDDED, as has the closing quote, so the shell's grammar sees the opening quote alone as the string. |
| String interpolation, command substitution | interpolation and command-substitution: the code between the markers, in the same language. |
Embedding is limited to 64 levels, so no file can exhaust the stack.
9. Styles
Every token gets one style, a LanguageStyle. A style's name can be a key in [words], a value in [lines], uppercase-style, tick-style, name-prefix, block-fence and inline, and a <style> term in a grammar. language_style_name() and language_style_from_name() turn a style into its name and back.
| Name | Constant | Given to |
|---|---|---|
default |
LANGUAGE_STYLE_DEFAULT |
Text with no other style. |
comment |
LANGUAGE_STYLE_COMMENT |
A block comment. |
comment-line |
LANGUAGE_STYLE_COMMENT_LINE |
A line comment. |
comment-doc |
LANGUAGE_STYLE_COMMENT_DOC |
A block comment that starts with a doc-comment opener. |
comment-line-doc |
LANGUAGE_STYLE_COMMENT_LINE_DOC |
A line comment that starts with a doc-comment opener. |
number |
LANGUAGE_STYLE_NUMBER |
A number. |
string |
LANGUAGE_STYLE_STRING |
A string, a heredoc, a header name; in Markdown, a link's address. |
character |
LANGUAGE_STYLE_CHARACTER |
A character constant; in Markdown, an escape. |
keyword |
LANGUAGE_STYLE_KEYWORD |
A [words] keyword; in Markdown, a task box and a quote kind. |
type |
LANGUAGE_STYLE_TYPE |
A [words] type. |
constant |
LANGUAGE_STYLE_CONSTANT |
A [words] constant, a symbol (:name); in Markdown, a done task, ^sup^ and ~sub~. |
builtin |
LANGUAGE_STYLE_BUILTIN |
A [words] builtin. |
attribute |
LANGUAGE_STYLE_ATTRIBUTE |
@name, #[...], a markup attribute's name; in Markdown, a fence's language and a link's title. |
preprocessor |
LANGUAGE_STYLE_PREPROCESSOR |
A directive; in Markdown, front matter. |
operator |
LANGUAGE_STYLE_OPERATOR |
An operator or punctuation. |
brace |
LANGUAGE_STYLE_BRACE |
{ } ( ) [ ]. |
identifier |
LANGUAGE_STYLE_IDENTIFIER |
Any other name. |
regex |
LANGUAGE_STYLE_REGEX |
A regex literal; in Markdown, math. |
variable |
LANGUAGE_STYLE_VARIABLE |
A name with its sigil: $x, @x, %x%. |
label |
LANGUAGE_STYLE_LABEL |
A tick name with tick-style = label, a label line; in Markdown, a link label and a footnote. |
macro |
LANGUAGE_STYLE_MACRO |
A macro call: name!. |
tag |
LANGUAGE_STYLE_TAG |
A markup tag with its < > </ />. |
entity |
LANGUAGE_STYLE_ENTITY |
&, . |
heading |
LANGUAGE_STYLE_HEADING |
A document heading. |
emphasis |
LANGUAGE_STYLE_EMPHASIS |
*emphasis*. |
strong |
LANGUAGE_STYLE_STRONG |
**strong**. |
link |
LANGUAGE_STYLE_LINK |
A link's text, <url>. |
code |
LANGUAGE_STYLE_CODE |
`code`, a fenced block in no known language, CDATA. |
inserted |
LANGUAGE_STYLE_INSERTED |
A diff's added line. |
deleted |
LANGUAGE_STYLE_DELETED |
A diff's removed line, ~~struck~~ text. |
changed |
LANGUAGE_STYLE_CHANGED |
A diff's @@ and file lines; in Markdown, ==marked== text. |
10. Rules the lexer always follows
These rules apply to every language and need no key:
- A UTF-8 byte order mark at the start of the text is not part of it.
- A non-ASCII character listed in
operatorsis an operator, even where names can contain any letter (Julia:≡ ≢ ∘ ⊆). - A dot right after a name or a closing bracket, before a digit, is an operator, and the digits after it are a whole number. So
t.0.1(Rust, Swift) is a member by number. - A sign right before a digit is an operator in a language where no name starts with a digit.
- Three quotes, where no string opens with three, are the quote as a character (Julia:
'''). - A block comment opener made of one repeated character, followed by one more of that character, opens nothing:
###opens a CoffeeScript block comment, but####is a line comment. - Where case does not matter, a
delimited-stringopener that is a word matches in any case (Forth:S"ands"). - No text can stop the lexer or make it loop: every step moves forward, and embedding has a depth limit.
11. C and C++
Kami's built-in C and C++ languages (language_builtin()) are language files too, the same c.lang and cpp.lang that Unryu ships, with engine = c and engine = c++. lexer_run() lexes with them. A program may parse its own copy of such a file (a user's c.lang with more words) and lex with it through language_lex(), or give it to a brace session. What reads the names of C and C++ is not a grammar in the file but Kami's preprocessor and parser: semantic_build() (see The Parser and the Semantic Model), which lexes the headers it includes with the built-in languages.
Kami API
The whole library
Reading C and C++
Braces
Any language
