Unryu: Languages in Files
Every language that Unryu understands is described in a plain text file, a .lang file. This page explains which languages ship with Unryu, how Unryu picks the language of a file, where the language files are kept, and how to change a language or add a new one, key by key.
What a language file does
Unryu does not have a list of languages built into it. Kami, the library that reads code for Unryu, learns each language from its language file. The file tells Kami:
- which files are in the language (by their file name ending, their whole name, or the program named on their
#!line); - how to cut the text into tokens: what a comment, a string, a number, a name and an operator look like;
- which words are keywords, types, constants and built-in names, so that each one gets its color;
- how the language makes blocks, for folding and for showing which definition holds which;
- how to find the definitions in a file, either with simple patterns or with a full grammar;
- what Toggle Line Commentation puts at the start of a line, and which characters make the next line indent.
Kami gives each token a style (for example keyword or comment). Kami has no idea of colors. Unryu looks up each style in the editor theme and draws the token with that color, so the same language file works with every theme. See Themes for the colors and How Unryu Uses the Analysis for what Unryu does with the definitions and braces that Kami finds.
The languages that ship with Unryu
Unryu ships with the languages below. The "Id" is the name of the file without .lang; other language files use the id to refer to a language (for example, HTML embeds javascript). "Blocks" is how the language makes blocks (see Blocks and folding). "What Kami understands" uses these levels:
| Level | What you get |
|---|---|
| C reader, C++ reader | Kami's own C or C++ reader with a real preprocessor: colors, a syntax check, every definition with its scope, every use linked to its definition, members found by type, folding by braces. Arduino and CUDA use the C++ reader. |
| Grammar | The language file has a full grammar: colors, a check of whether the file is valid (and the line where it stops being valid), every definition with its scope, every use linked to the right definition, members found through the type of what they are taken from, and folding by the grammar's blocks. |
| Headings | A document language: colors, and the headings in the Outline, nested by level. All text is valid, so there is no syntax check. |
| Colors only | Colors, and no definitions. |
| Language | Id | Files | Blocks | What Kami understands |
|---|---|---|---|---|
| Abaqus | abaqus | .inp | none | Grammar |
| ABC | abc | .abc .abp | none | Colors only |
| ActionScript | actionscript | .as | braces | Grammar. E4X XML elements. |
| Ada | ada | .adb .ads .ada | keywords | Grammar |
| Arduino | arduino | .ino .pde | braces | C++ reader |
| AsciiDoc | asciidoc | .asciidoc .adoc .asc | none | Headings. Listing blocks marked [source,python] are colored in that language. |
| Assembly | asm | .asm .s .S .sx .a51 .asm51 .nasm .inc | none | Grammar |
| AutoIt | autoit | .au3 | keywords | Grammar |
| Awk | awk | .awk .gawk .mawk .nawk; #! awk, gawk, mawk, nawk | braces | Colors only; functions are named in the Outline. Also the code of awk '...' in a shell script. |
| Batch | batch | .bat .cmd .nt | none | Grammar |
| BibTeX | bibtex | .bib | braces | Grammar |
| C | c | .c .h .xpm; #! tcc | braces | C reader. Your copy of c.lang sets the words and lexical rules; the C reader is built in. |
| C# | cs | .cs .csx | braces | Grammar |
| C++ | cpp | .cpp .cxx .c++ .cc .cp .hpp .hxx .h++ .hh .hp .C .H .ipp .tpp .tcc .txx .inl .ixx .cppm .mpp .ccm .cxxm .c++m | braces | C++ reader. Your copy of cpp.lang sets the words and lexical rules; the C++ reader is built in. |
| Clojure | clojure | .clj .cljs .cljc .cljr .edn; #! clojure, clj, bb | none | Grammar |
| CMake | cmake | .cmake .ctest; named CMakeLists.txt | none | Grammar |
| COBOL | cobol | .cob .cbl .cpy .cobol | none | Grammar |
| CoffeeScript | coffeescript | .coffee .iced; named Cakefile, *.Cakefile, *.coffee.erb, *.iced.erb | indentation | Grammar. JSX elements. |
| Config | conf | .conf .lang .ini .cfg .desktop .properties .service .socket .timer .mount .target .path .slice .cnf .prefs .reg .inf; named config, control, .gitconfig, .editorconfig, .npmrc, *rc | none | Grammar. Also colors the language files themselves (.lang). |
| CSS | css | .css .sass .styl .pcss | braces | Grammar |
| CUDA | cuda | .cu .cuh | braces | C++ reader |
| Cython | cython | .pyx .pxd .pxi | indentation | Grammar |
| D | d | .d .di | braces | Grammar |
| Diff | diff | .diff .patch .rej .debdiff .dpatch | none | Grammar. Each line colored by its first characters. |
| DocBook | docbook | .docbook .dbk | none | Grammar |
| Erlang | erlang | .erl .hrl .escript; named rebar.config; #! escript | none | Grammar |
| Forth | forth | .fs .fth .4th .forth .fb; #! gforth | none | Grammar |
| Fortran | fortran | .f90 .f95 .f03 .f08 .f18 .F90 .F95 .F03 .F08 | keywords | Grammar |
| Fortran 77 | f77 | .f .for .ftn .f77 .F .FOR .FTN .F77 .fpp .FPP | keywords | Grammar |
| FreeBasic | freebasic | .bas .bi .vbs .bb | keywords | Grammar |
| GDScript | gdscript | .gd | indentation | Grammar |
| Genie | genie | .gs | indentation | Grammar |
| GLSL | glsl | .glsl .frag .vert .geom .tesc .tese .comp | braces | Grammar |
| Go | go | .go | braces | Grammar |
| Graphviz | graphviz | .gv .dot | braces | Grammar |
| Groovy | groovy | .groovy .gradle .gvy .gy .gsh; #! groovy | braces | Grammar |
| Haskell | haskell | .hs .lhs .hs-boot .lhs-boot .hsc; #! runhaskell, runghc, stack | indentation | Grammar |
| Haxe | haxe | .hx | braces | Grammar |
| HTML | html | .html .htm .shtml .xhtml .hta .htd .htt .cfm .tpl | none | Grammar. JavaScript inside <script> and CSS inside <style> are colored as those languages. |
| Java | java | .java .jav | braces | Grammar |
| JavaScript | javascript | .js .mjs .cjs .jsx .es6; #! node, nodejs, deno, bun | braces | Grammar. JSX elements. |
| jq | jq | .jq; #! jq, gojq | braces | Colors only; def functions are named in the Outline. Also the filter of jq '...' in a shell script. |
| JSON | json | .json .jsonc .json5 .geojson .webmanifest .har; named .babelrc, .eslintrc, .prettierrc, .jshintrc, composer.lock | braces | Grammar |
| Julia | julia | .jl; #! julia | keywords | Grammar |
| Kotlin | kotlin | .kt .kts | braces | Grammar |
| LaTeX | latex | .tex .sty .cls .dtx .ins .idx .ltx .latex .aux .bbl | braces | Grammar |
| Lisp | lisp | .lisp .lsp .l .cl .el .scm .ss .rkt .asd; named .emacs, .sbclrc; #! sbcl, clisp, ecl, racket, guile | none | Grammar |
| Literate CoffeeScript | litcoffee | .litcoffee | indentation | Grammar. Prose with indented CoffeeScript; JSX elements. |
| Lua | lua | .lua .wlua .rockspec .luacheckrc; #! lua, luajit | keywords | Grammar |
| Makefile | makefile | .mak .mk .make; named Makefile, makefile, GNUmakefile, Makefile.*, makefile.*, *.mk; #! make | none | Grammar |
| Markdown | markdown | .md .markdown .mdml .mkd .mkdn .mdwn .mdown .mdtxt .mdtext .mdx .rmd; named README, CHANGELOG | none | Headings. Fenced code blocks in any installed language; YAML front matter. |
| Matlab/Octave | matlab | .m; #! octave, octave-cli | keywords | Grammar. Shares .m with Objective-C; detect words decide. |
| Meson | meson | named meson.build, meson.options, meson_options.txt | none | Grammar |
| Nim | nim | .nim .nims .nimble; #! nim | indentation | Grammar |
| NSIS | nsis | .nsi .nsh | none | Grammar |
| Objective-C | objectivec | .m .mm | braces | Grammar. Shares .m with Matlab; detect words decide. |
| OCaml | caml | .ml .mli; #! ocaml | none | Grammar |
| OCamllex | ocamllex | .mll | none | Grammar. The OCaml code in actions is read with the OCaml grammar. |
| OCamlyacc | ocamlyacc | .mly | none | Grammar. The OCaml code in actions is read with the OCaml grammar. |
| Pascal | pascal | .pas .pp .inc .dpr .dpk .lpr .lfm | keywords | Grammar |
| Perl | perl | .pl .perl .pm .agi .pod .t .psgi; #! perl, perl5 | braces | Grammar |
| PHP | php | .php .php3 .php4 .php5 .php7 .php8 .phtml .phps .inc; #! php | braces | Grammar. The PHP code between <?php ?>, <?= ?> and <? ?>; the HTML around it, with its JavaScript and CSS. |
| Po | po | .po .pot | none | Grammar |
| PowerShell | powershell | .ps1 .psm1 .psd1; #! pwsh, powershell | braces | Grammar |
| Python | python | .py .pyw .pyi; named SConstruct, SConscript, wscript, *.pyx.in; #! python, python3, python2, pypy, pypy3 | indentation | Grammar |
| R | r | .R .r .Rprofile .Rhistory; #! Rscript | braces | Grammar |
| reStructuredText | restructuredtext | .rst .rest .reST | none | Headings. .. code-block:: python blocks are colored in that language. |
| Ruby | ruby | .rb .rbw .rake .gemspec .rhtml .ruby .ru; named Gemfile, Rakefile, rakefile, Guardfile, Capfile, Vagrantfile, Podfile; #! ruby | keywords | Grammar |
| Rust | rust | .rs | braces | Grammar |
| Scala | scala | .scala .sc .scl | braces | Grammar. XML literals. |
| SCSS | scss | .scss .less | braces | Grammar |
| Sed | sed | .sed; #! sed, gsed | braces | Colors only; labels are named in the Outline. Also the script of sed '...' in a shell script. |
| Shell | sh | .sh .bash .ksh .mksh .zsh .ash .dash .m4 .bats .command; named configure, configure.ac, configure.in, configure.in.in, .bashrc, bash.bashrc, .profile, .bash_profile, .bash_login, .bash_logout, .bash_aliases, .bash_*, bash_*, .zshrc, .zprofile, .zshenv, .kshrc, PKGBUILD, APKBUILD, *profile; #! sh, bash, dash, ksh, mksh, zsh, ash, busybox | braces | Grammar. The single-quoted code of awk, sed, perl, python, ruby, node and jq is colored in its own language. |
| Smalltalk | smalltalk | .st | none | Grammar |
| SQL | sql | .sql .ddl .dml .pgsql .mysql | keywords | Grammar |
| Swift | swift | .swift | braces | Grammar |
| Tcl | tcl | .tcl .tk .wish .exp .itcl .itk; #! tclsh, wish, expect | braces | Grammar |
| TSX | tsx | .tsx; #! ts-node, deno, bun | braces | Grammar. JSX elements with type arguments. |
| Txt2tags | txt2tags | .t2t | none | Headings |
| TypeScript | typescript | .ts .mts .cts; #! ts-node, deno, bun | braces | Grammar |
| Vala | vala | .vala .vapi | braces | Grammar |
| Verilog | verilog | .v .vh .sv .svh | keywords | Grammar |
| VHDL | vhdl | .vhd .vhdl .vho .vht | keywords | Grammar |
| XML | xml | .xml .sgml .xsl .xslt .xsd .xul .dtd .xtpl .mml .mathml .svg .rss .atom .plist .csproj .vcxproj .xaml .glade .ui .wsdl .kml .gpx | none | Grammar |
| YAML | yaml | .yaml .yml; named .clang-format, .clang-tidy, .gitlab-ci.yml | indentation | Grammar |
| Zephir | zephir | .zep | braces | Grammar |
A file that no language claims is Plain Text: no colors and no rules. When it opens, the status bar says "Plain Text".
How Unryu chooses the language of a file
When you open a file, or save it under a new name, Unryu compares the file with every language file and takes the best match:
- The whole file name. A language whose
filenameslist holds the exact name (for exampleMakefileorCMakeLists.txt) wins over everything else. The comparison is case-sensitive. - The ending, or a file name pattern. The text after the last dot is looked up in each language's
extensions, case-sensitively (.Cis C++,.cis C). Only the text after the last dot of a file name is compared with the extensions, so an ending with a dot in it (pyx.in) never matches; use afilenamespattern such as*.pyx.ininstead. A pattern infilenameswith*or?(for examplemakefile.*or.bash_*) counts the same as an ending. - The
#!line. If the first line starts with#!, the program it names is looked up in each language'sshebangs. Only the program's own name counts, so#!/usr/bin/python3and#!/usr/bin/env python3both namepython3;env -Sis understood too.
When two languages match equally well (both Matlab and Objective-C claim .m), Unryu counts how many of each language's detect words appear in the first 4 KB of the file, and the language with more wins. So a .m file with @interface or #import is Objective-C, and one with function and endfunction is Matlab. If neither has more, the language whose name sorts first wins: a .inc file, claimed by Assembly, Pascal and PHP, opens as Assembly.
If nothing matches, the file is Plain Text. A new, untitled document is Plain Text until it gets a name, unless it was made from a template (see below).
Document > Set Filetype... lets you choose the language of the open document by hand. The dialog lists Plain Text first ("No rules: the text as it is"), then every language by name, with its file name endings and file names under it. The choice applies to that document only, and the status bar confirms it ("Filetype: Python"). Unryu does not remember the choice: the next time the file is opened, its language is chosen again by the rules above. Unryu does not read editor modelines (such as vim: ft= or -*- mode: -*-); to make Unryu recognise a file, add its name or ending to a language file.
File > New (with Template) sorts the templates by language. A template's language is the one that knows its whole name (a template named Makefile gives a new tab named Makefile); otherwise it is the language of its ending, as for a file untitled.ext, with the template's text deciding a tie and its #! line used when it has no ending.
Where the language files are
Unryu reads language files from these folders, in this order. A file in a later folder replaces a file with the same name from an earlier one:
- The shipped folders, all read in this order:
share/unryu/languages/of an installed Unryu,languages/one folder up from the program (a build folder), andlanguages/beside the program. - Your own folder:
~/.config/unryu/languages/(or$XDG_CONFIG_HOME/unryu/languages/whenXDG_CONFIG_HOMEis set).
The first time Unryu starts, it makes your folder and puts a copy of every shipped language file in it, for you to change. Once the folder exists Unryu never fills it again, so a file you delete stays deleted, and the shipped file of that name is then used. Because your copies win, a new version of Unryu does not change a language whose copy is in your folder: to get the shipped version of a language after an upgrade, delete (or rename) your copy. A language file that is new in the upgrade, and that you have no copy of, is used at once.
Only files that end in .lang are read. Older versions of Unryu named language files NAME.conf. When Unryu reads your folder, it renames each NAME.conf to NAME.lang if there is no NAME.lang yet, so a language you changed is still used. When it renames your conf.conf (the Config language), it also adds lang to that file's extensions, so that language files keep their colors. Unryu reads at most 256 languages.
Editing a language file in Unryu
Tools > Configuration Files > Language Files lists every language by name, in groups by first letter ("A - B", "C", "D - G" and so on). Choosing a language opens your copy of its file, ~/.config/unryu/languages/ID.lang. If you have no copy yet (you deleted it, or the language is shipped only), Unryu first writes one with the text of the file it is using now, so you always edit your own copy and never the shipped one.
You do not need to restart Unryu after changing a language file. Each time you open a menu of the menu bar, Unryu checks the names, sizes and times of the .lang files in both folders. If a file was added, deleted or saved since it last read them, Unryu reads all language files again, and every open document is read again with the new rules (each document keeps its language, found again by its id). A new language then appears at once in Tools > Configuration Files > Language Files, in Document > Set Filetype, and in File > New (with Template) when a template in it exists. Tools > Reload Configuration also reads the language files again, together with the other configuration files.
A language file with a mistake does not stop Unryu. A key or section that Kami does not know is ignored, and a value that is not valid leaves Kami's default. A grammar that cannot be compiled is dropped, and the file's [symbols] patterns are used instead (see Grammars).
The analysis runs in a separate, jailed process (see The Jail). Unryu sends that process the text of the document's language file, and the text of each language it embeds, together with the document. For C and C++ the process also reads the headers the file includes, inside the folders the jail allows. A language file cannot make it read or write anything on your disk.
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 section names[markup]and[markdown]are also accepted and mean the same as[lexical]. - 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=if there is none, so a key in[lines]may itself contain=. Spaces around the key and the value are ignored. - A line that starts with
;is a comment, and so is a line that starts with#, except in the[lines]section, where#can be a line prefix. Blank lines are ignored. - A key with an empty value is the same as a key that is not there: it keeps Kami's default. The shipped files list every key, mostly empty, each with a comment line above it saying what it does, so any shipped file shows everything that can be set.
- 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
true,yesor1, and off with anything else. - A key that takes one character takes the first and only character of its value;
noneor an empty value means no character. - Some keys "may come again": each line adds one more entry (for example one
block-commentline per kind of block comment). For every other key a second line replaces the first, except for these, whose lines add up: the marker lists of[lexical](line-comment,string,operators...), the block-word lists of[language](block-start,block-end...) and[words].extensions,filenames,shebangs,detect, thelayout-keys,operator-characters,soft-keywords,conditional-wordsand the keys that list single characters (such asvariable-prefixesorregex-flags) are replaced by a second line. - Key and section names are written in lower case, as shown on this page. The markers, words and patterns in the values are compared with the text exactly, unless the language sets
case-sensitive = false(see that key for which ones then match in any case).
Some limits apply: a list holds at most 24 markers (operators: 320), and each marker is at most 15 bytes long; a file has at most 32 [symbols] patterns of up to 6 words each, 24 [lines] rules, 24 embedded languages and 32 block-rule lines of up to 10 words each.
A small complete example
This is a whole language file for a made-up language, Tiny. Saved as ~/.config/unryu/languages/tiny.lang, it makes Unryu color .tiny files, list their functions and variables in the Outline, fold their blocks, check their syntax and link each name to its definition. Every key it leaves out keeps Kami's default.
; Tiny: a small example language for Unryu
[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 Outline shows countdown, and each later i and n leads to its definition (names inside a function's body are not listed in the Outline):
# 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)
The sections below explain every key, section by section.
[language]: the name, the files and the blocks
| Key | What it does |
|---|---|
name | The name people see, in menus, the Set Filetype dialog and the status bar. Without it, the id is used. A Markdown fence may also name a language by this name. |
extensions | File name endings, without the dot, separated by spaces. Case matters: C and c are different endings. |
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. Each word counts once, wherever it appears, even inside another word. |
engine | What finds the names after the lexer. generic (the default): the file's [grammar], or its [symbols] patterns. c: Kami's C preprocessor, C grammar and semantics. c++: the same with the C++ reader. 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). |
block-open | Words that open a block wherever they are (do, function). |
block-end | Words that close a block (end, until). |
block-endless | Openers that have no closer when their name is followed by =, like Ruby's one-line def area = width * height. |
block-join | Words that continue the block above instead of opening a new one: Ada's begin after procedure P is. |
block-join-to | The openers that a block-join word continues, once each (Ada: procedure function package task protected entry declare). |
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 for the tests. |
statements | lines: a statement ends at the end of its line, unless the line ends with the line-continuation character (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). Used by the grammar. |
pairs | Which pairs, besides ( ) [ ] { }, Unryu matches and draws as braces (Code analysis): quotes (a string's quotes), comments (a block comment's opener and closer), interpolation (${ } in a string), tags (start and end tags), angles (the < > of generics), keywords (block words: those of blocks = keywords, keyword-pair and named-pair), conditionals (#if ... #endif, by conditional-words, or C's words for a C engine) and text (text-pairs in prose). |
keyword-pair | An opening word and its closing word, for a language whose blocks is not keywords: the shell's if fi, case esac, do done. Several openers may share a closer (ifeq endif, ifdef endif). A word counts only where a statement starts. May come again. |
named-pair | An opening command and its closing one, whose { } names must be the same: LaTeX's \begin \end. May come again. |
text-pairs | Opening and closing characters in turn, matched in prose outside code: « » “ ” 「 」. |
void-tags | With tags: elements that have no end tag (HTML's br img input ...). |
optional-end-tags | With tags: elements whose end tag may be left out (HTML's li p td ...): they end when their parent ends, and no end tag is shown missing. |
The other [language] keys are explained under 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 only matter for a language with a grammar. operator-characters, dotted-operators, continuation-in-strings, digit-names and underscore-operators change how the lexer cuts tokens, in any language.
[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, 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.
Names
| Key | What it does |
|---|---|
identifier-start | The characters a name can start with: ranges such as A-Z, single characters such as _ $, and unicode for every non-ASCII character. Default: A-Z a-z _ unicode. |
identifier-part | The characters a name can continue with. Default: A-Z a-z 0-9 _ unicode. |
identifier-escapes | Escapes a name may contain, such as C's \u and \U. |
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, as the shipped files do, because the words are stored as they are read. |
unicode-spaces | true: Unicode space characters (no-break space, em space and so on) are white space, not part of a name. |
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 not one of the language's words and starts with the prefix gets the style (CSS: name-prefix = -- variable colors --accent as 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. The first one is also what Toggle Line Commentation uses when comment-toggle is empty. |
block-comment | An opener and its closer: /* */. May come again. |
nested-comments | true: a block comment may contain another one (Rust, Haskell). |
doc-comment | A comment that starts with one of these is documentation (/** /*! /// //!) and gets the comment-doc or comment-line-doc style. |
directive-comment | A comment that starts with one of these is a directive and gets the preprocessor style: Pascal's {$, Haskell's {-#. |
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. |
line-block-open-end | true: such a comment may run to the end of the file without its closer (Perl's POD). |
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 inside a block comment is read as a string, so a comment closer inside it ends nothing (OCaml: (* "*)" *) and (* {|*)|} *)). |
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 |. Forth: BL WORD|PARSE-NAME|PARSE-WORD. |
name-words | Words after which the next word, up to a blank, is a name whatever it contains. Forth: ' ['] POSTPONE [CHAR], so POSTPONE ." starts no string. |
Strings
| Key | What it does |
|---|---|
string | Delimiters of strings on one line: " '. The same delimiter opens and closes, and escapes apply. |
raw-string | Delimiters of one-line strings with no escapes (a backslash is just a backslash). |
multiline-string | Delimiters of strings that may span lines: """ '''. |
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|...|id}, also with an extension name first, {%sql|...|}) and comments (a # after a blank, and not the start of #{, runs to the end of the line: CoffeeScript's /// ... ///). May come again. |
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. |
raw-prefixes | Those prefixes that make the string raw: r R. |
any-string-prefix | true: any name right before a " is the string's prefix (Julia: doc"x", L"x"). A prefix that is not in string-prefixes makes the string raw, with no interpolation, because the language hands such text to a macro as it is (Julia's S"... $(x) ..."). |
cpp-raw-prefixes | Prefixes of C++ raw strings, R"tag( ... )tag": R u8R LR uR UR. |
hash-raw-prefixes | Prefixes of Rust raw strings, r#" ... "# with any number of #: r br. |
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 " string can end with “ ” „, and a ' string with ‘ ’ ‚ ‛). 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. |
heredoc-joined | true: the heredoc word must follow the opener with no space (Ruby, so that class << self is no heredoc). |
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 colored as 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. |
interpolation-variable | A string delimiter and a sigil: $name inside such strings is a variable (" $). |
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 \. |
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: '. |
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, Clojure's \newline). A character given by its number after the escape is one character too: $\101, $\x41, $\x{263A}. The character can be any UTF-8 character ($э). |
numbered-character | A character that, with digits after it, is a character constant: Pascal's #13. |
tick-style | A style for a ' followed by a name that is not a character constant: Rust's lifetimes 'a, Ada's attributes 'First. A ' before a space, a tab or a bracket that starts no character constant is an operator (OCaml's ' a, Scala 3's '{ code } and '[T], Haskell's '[A, B]). |
number-separator | A separator between digits: _, or C++'s '. |
number-characters | More characters a number may contain: 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 may follow the prefix (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, an opening bracket or a regex-after word), 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 (Scala: case <tag>). |
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. |
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. |
substitution-operators | Words that start two parts with any delimiter: Perl's s tr y. |
percent-literals | % and a letter that start a string with any delimiter, where a value may stand: Ruby's %w %q %Q %i. |
percent-regexes | The same for a regex: Ruby's %r. |
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. A special digit takes all the digits after it ($10), and a dash at the end of a variable is an operator ($end-$start). |
variable-braces | An opener and a closer: ${name} is one variable. |
variable-delimiters | An opener and a closer around a name: Batch's %name%. |
command-substitution | An opener and a closer around code: the shell's $( ). The code inside is colored as code. |
quote-transpose | true: a ' right after a value is an operator (Matlab's transpose). |
Directives, attributes and special tokens
| Key | What it does |
|---|---|
directive | A character that, at the start of a line, makes the line a directive (C's #). |
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, ### further in is an operator). |
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). |
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 |. Haxe: if elseif else end; FreeBASIC: if|ifdef|ifndef elseif else endif; C# and Vala: if elif else endif. The grammar reads only the first branch, so an #if that chooses between two headers gives the grammar one header; colors and brace pairing still see all the text. The condition can be an expression, so a mark at the start of a directive line hides its whole line from the grammar. |
conditional-in-line | true: a conditional mark ends after its condition (a name, ! and a name, or a group in brackets), 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. |
digraph | An alternative spelling and the standard token: <% {. 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 #[ ]. |
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 f(r):n and a[1]:b stay ranges. |
symbol-operators | Operators that are symbols after the symbol-prefix, and :name=: Ruby's [] []= <=> == + -@. |
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 always tokens of their own. At most 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 in ActionScript, XML literals in Scala). <{expression}> is a tag too, and type arguments can follow a tag's name (TSX: <Select<Option> ...>). |
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 the fence's language word apart from its ``` and the rest of its line, 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 (colored as HTML), $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. Without any inline line, Markdown's own rules apply. |
setext-headings | The characters of a line that underlines the heading above it (Markdown: = -), or none. Default: = -. |
indented-code | true: a line indented by four spaces after a blank line is code (Markdown). Default: true. |
literal-after | A marker (reStructuredText's ::). Any line that ends with it (a paragraph line such as For example::, or a line taken by a [lines] rule) 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 colored in that language; a word that names no language (.. image:: picture.png) opens no block. |
[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; AsciiDoc uses // = comment-line and "== " = heading. The longest matching prefix wins. Spaces around a key are dropped, so a prefix that ends with a space (a heading's == , which a ==== block line must not match) has to be in double quotes. Write a prefix in double quotes to keep spaces in it, or when it starts with ; or " (which would otherwise start a comment): ";" = comment-line. A value that is not a style name is ignored.
[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, attribute = override. Any style name from the style list can be a key, so a language can also have, for example, preprocessor or operator words. A word with a sigil ($display) or with operator characters (Fortran's .true.) keeps its class. A key that is not a style name is ignored.
The classes also matter beyond colors: a keyword can never be a name in the grammar (see soft-keywords for exceptions), 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: Kami uses them when the grammar cannot be compiled or gives up on a very large or unusual file. Each key is a kind, and each value a pattern of words around the word NAME:
[symbols]
function = def NAME
function = async def NAME
class = class NAME
variable = ^ NAME =
not-after = end
| Part | Meaning |
|---|---|
| the key | The kind of definition: variable, function, method, type, class, struct, namespace, module, constant, label, macro, member or field. method counts as a function; class, struct, namespace and module count as types that hold members; member and field are the same. The kind decides the definition's color and its group in the Outline. |
NAME | The name being defined. A pattern must have exactly one NAME and at least one other word. |
| a word | That exact token: def, =, :. |
* | Any name that is not a keyword or constant, 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 have a meaning in patterns (Nim's export mark '*'). |
^ | What follows starts its line (Batch's :label). |
$ | What comes before ends its line (Matlab's function with no arguments). |
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 pattern that starts with NAME only matches 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 function = function NAME pattern does not define TSquare, and only a pattern with * . NAME defines Area. Each definition sits inside the block that holds it (a method inside its class), according to the language's blocks. The comment lines right above a definition are its documentation, shown in its tooltip and in Details. Every other name spelled like a defined name counts as a use of its first definition.
[editing]
| Key | What it does |
|---|---|
comment-toggle | What Edit > Format > Comment Line(s), Uncomment Line(s) and Toggle Line Commentation (Ctrl+E) put before the first non-blank character of each line (blank lines are left as they are). Use quotes to keep a trailing space: comment-toggle = "# ". When it is empty, the first line-comment marker is used; a language with neither cannot comment lines. Toggle Line Commentation also adds a marker after the opener (by default ~ , giving #~ ), so it can tell its own comments apart; the marker is set in Preferences. |
indent-after | Characters that, at the end of a line, make the next line one level deeper when you press Enter (Python's :). An open { always does. This applies when auto-indentation is set to "Current chars" or "Match braces". |
import-words | Words that bring in another file: Python's import from, Rust's mod use, the shell's source .. Go to Definition on what follows one on its line (a module's name, or a file's name in quotes) opens that file; on a name after from x import, it opens x at that name (Code analysis). |
import-separator | The character between a module's parts (Python's and Java's ., Rust's : of ::): each, or each run of them, becomes a / of the module's path. Leading dots (from ..x import) go up from the file's folder. |
import-files | The files a module can be, {} standing for its path: Python has {}.py {}/__init__.py {}.pyi. Each is looked for beside the file, then from the project's folder, its src and its lib. |
spelling | What Tools > Check Spelling reads in the language: code (comments, and strings with a space in them), prose (all of the text but code, links, tags, commands and the like: Markdown, LaTeX, reStructuredText), markup (comments, strings with a space, and the text between the tags: HTML, XML) or none (a diff, JSON). See Editing. |
unicode-escape | How Edit > Format > Escape Unicode writes a character in a string: a form for the characters up to U+FFFF and, after a space, one for those past it. In a form, %4 and %8 are the code point in that many hexadecimal digits (at least), and % in as few as it takes: C has \u%4 \U%8, Rust \u{%} \u{%}, HTML &#x%; &#x%;. Instead of the second form, utf16 writes a surrogate pair with the first (Java, C#). Empty: the language has no such escapes. |
semicolon-after | Words, separated by spaces, whose { } block ends with a ;: C has struct union enum, and C++ adds class. When auto-close closes a { after one of them, it types }; (Auto-close). |
Blocks and folding
The blocks key says how the language makes blocks. Blocks decide what can be folded, which definition holds which (a method inside its class), and, for [symbols] languages, how far a definition reaches.
| Value | A block is | Languages |
|---|---|---|
braces | From a definition to the { } after it. 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 | A line and the deeper lines under it (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, GDScript ... |
keywords | From an opening word to the closing word that matches it. | Ruby, Lua, Julia, Matlab, Pascal, Verilog, AutoIt, Ada, Fortran, VHDL, FreeBASIC, SQL |
none | There are no blocks; definitions are listed flat. | COBOL, Assembly, configuration files, documents ... |
How Unryu folds (when Code folding is on in Preferences): a language with a grammar folds the blocks and scopes the grammar finds. Otherwise, an indent or keywords language folds its blocks from the first line to the last, and any other language folds between { and } pairs that Kami is certain of. Document languages do not fold by headings.
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 (#if, #endif) 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, End Sub). 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. 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.
| Test | The word counts | Example |
|---|---|---|
alone | Only when it is alone on its line. | SQL: declare alone (Oracle's DECLARE block, not T-SQL's DECLARE @x INT) |
not-alone | Only when more follows on its line. | FreeBASIC: end not-alone (End alone stops the program) |
next-not | Not when the next token is one of the words. | Fortran: do next-not 0 (do 10 i = 1, n ends at a label) |
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 (if (x) y opens no block) |
has | Only when its statement contains one of the words, outside brackets. | Ada: procedure has is (a declaration with no body opens no block) |
has-not | Not when its statement contains one of the words. | VHDL: component has-not map (an instance) |
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 (where (m) a = b opens no block) |
Brace pairing
For every language other than C and C++, Kami pairs { }, ( ) and [ ] after the lexer has taken out strings and comments, so a bracket inside a string never counts. When every bracket in the file pairs by nesting, every pair is certain. When some do not (usually while you are typing), Kami falls back on the layout of the code for braces and on statements for parentheses and square brackets, marks the doubtful pairs, and shows where a missing partner probably belongs. Keyword blocks (begin ... end) are used for folding and for nesting definitions, not for brace pairing. C and C++ have their own, more detailed pairing. What Unryu shows (the colors of certain, likely and doubtful braces, Go to Partner, Flash Missing Braces) is described in How Unryu Uses the Analysis. There are no brace settings in a language file.
Grammars
A [grammar] section gives Kami the full syntax of the language. With it, Kami reads the file the way a compiler would and gives the same kind of answers that its C reader gives: whether the file is valid and, if not, the line where it stops being valid; every definition with its scope and body; each use linked to the definition it refers to through the scopes around it; members found by the type of the value they are taken from; and the blocks that fold. Almost every shipped language has one.
A grammar is a parsing expression grammar over Kami's tokens (not over characters: the lexer has already found the strings, comments and names). It is a list of rules, one per line:
name = expression
A rule name may contain letters, digits, _ and -, and starts at the very beginning of its line. A line that starts with a space or tab continues the rule above it, so a long rule can span lines. Lines that start with ; are comments. The rule named file is where reading starts, and every grammar must have one. A rule may refer to rules written below it. The section ends at the next line that starts with [.
Terms
| Term | Matches |
|---|---|
"if" or 'if' | A token with exactly this text (in any case when the language is not case-sensitive). A literal never matches part of a string. A literal may take part of a longer token only when that token is in split-operators (the > of >>), or when it is the prefix of an attribute ("@" NAME reads @name). |
NAME | A name that is not a keyword (a word in soft-keywords is allowed). |
WORD | Any name, keywords included. |
LOWER | A NAME that starts with a small letter or _ (Rust's bindings, as opposed to None). |
NUMBER, STRING, CHAR | A number, a string (not a regex), a character constant. |
REGEX, VARIABLE | A regex literal; a variable written with its sigil ($x). |
OP | Any operator, but not a bracket, ; or , (write those as literals). |
ANY | Any one token. |
END | The end of the file. |
NEWLINE, INDENT, DEDENT | The end of a line, a deeper line, and the end of a deeper part. These exist only with a layout (see below). |
SAMELINE | Takes nothing: succeeds when the next token is on the line where the last one ended. |
JOINED | Takes nothing: succeeds when the next token touches the last one, with no space between (one shell word). |
NOTHING | Takes nothing and always succeeds. With :close-tag, it stands for an end tag that may be left out (HTML's <p>). |
<style> | A token of that style: <tag>, <heading>, <attribute>. |
rule | Another rule, by its name. |
Combining terms
| Written | Means |
|---|---|
a b | a then b. |
a / b | a, or if that fails, b. The first alternative that matches without skipping a broken statement is taken; if each one needs to skip something, the first that matches at all. A choice can have up to 64 alternatives. |
( ... ) | A group. |
a?, a*, a+ | a at most once, any number of times, at least once. A repetition stops when a no longer moves forward. |
&a, !a | Look ahead without taking anything: succeeds if a would match, or would not. |
Annotations: what a name means
A term that matches one token can carry an annotation after a colon, such as NAME:function. An annotation on a longer term is not allowed, and an unknown annotation is a fault.
| Annotation | The token is |
|---|---|
:function, :method | The name of a function being defined. |
:class, :struct, :namespace, :module | The name of a type that holds members. |
:type | The name of a type (an alias, a typedef). |
:variable | A variable defined in the scope it is in. |
:var | A variable of the nearest function body (or the file), not of the block it is in: JavaScript's var. |
:constant, :enumerator | A constant, an enumerator. |
:field | A member defined in a type. |
:parameter | A parameter, defined in the scope it is in: write the parameter list inside the function's @body(...), as the Tiny example does. A parameter written before @body would itself be the last definition and take the body; for a parameter written before the body, use :receiver. |
:label, :macro | A label, a macro. |
:import | A name brought in by an import; it counts as a variable. |
:assign | An assignment: defines a variable, unless a variable of that name is already visible (then it is a use). With assign-scope = local, it defines in its own scope unless :global said otherwise. |
:assign-file | A variable of the file, unless a visible one has the name (the shell's x=1). |
:global | A name that later assignments in this scope send to the outer name (Python's global and nonlocal). |
:use | A use of a name, linked to its definition through the scopes around it. |
:member | A name after ., found by the type of what stands before it. |
:member-assign | self.x = ...: defines a member of the class around it. |
:property | A member of the class around it, written elsewhere: TypeScript's constructor(private x). |
:typeref | The type of the last definition (so that its members can be found later). |
:returns | The return type of the function whose body this is. |
:receiver | A parameter of the next body: Go's s in func (s T) M(). |
:method-of | The type that the next function belongs to: Go's T in func (s T) M(). |
:owner | The type that the next body belongs to: Rust's impl T. |
:open-tag, :close-tag | An element's name, and a closing name that must be the name of the nearest open element (markup). |
:ignore | Not a name of the code: a keyword argument's name. |
Scopes, bodies, blocks and recovery
| Construct | Means |
|---|---|
@scope(e) | What e matches is a scope of its own: names defined inside are not visible outside (a lambda, a comprehension). |
@body(e) | A scope that is the body of the last definition before it: a function's parameters and statements, a class's members. It folds. |
@block(e) | A block that folds but defines nothing of its own (Python's if). |
@many(e) | e repeated until the end of the enclosing group (the end of the file, a DEDENT or a closing bracket). A statement that does not parse is noted as a fault and skipped (to after its ; or line end, or to the closer it is inside), so the rest of the file is still read and its definitions still found. |
@many(e, stop) | The same, stopping where stop would match (it is not taken) or at the end of the file: @many(statement, "end"). Closing brackets do not stop it, so ) and ] may be text (LaTeX). |
When a file is not valid, Kami reports the first fault as a line and a reason: "line 12: 'else' was not expected here", "line 3: what starts here is never closed", "line 5: the statement ends too soon", "line 9: the file ends too soon", or "line 4: a string with no end" (a comment too). Unryu shows it in the Details panel, after the number of symbols ("not all of it parses: ..."). The definitions are still found in the parts that parse.
Kami remembers where rules failed and most of where they matched, so it seldom reads a rule twice at one place in the file. Even so, it has a budget of steps per file: a grammar that would take too long on some file gives up on it, and Kami uses the [symbols] patterns for that file instead. A grammar with a fault (a literal with no end, an unknown rule, class, style or annotation, a missing file rule, text after a rule's end, a ( or @...( with no ), an @ word other than scope, body, block or many, more than 64 alternatives, a term out of place such as an annotation on a group, a <style> with no >, or a line that starts at the left edge without being a rule, such as a # line: in [grammar] only ; starts a comment) is not used at all, and the patterns take over for every file. Unryu does not show a grammar fault: when a grammar seems to have no effect, look for one of these faults in it.
Layout: lines and indentation
Many languages end statements at the end of a line, or make blocks by indentation. The layout key, in [language], gives the grammar NEWLINE, INDENT and DEDENT tokens for that:
| Value | The grammar gets |
|---|---|
| (none) | Only the tokens. Line ends do not count. |
lines | A NEWLINE at the end of each line that has tokens, and one at the end of the file. |
indent | NEWLINEs, plus an INDENT when a line is deeper than the line before and a DEDENT for each level a line goes back (Python). |
offside | Haskell's offside rule: after a word in layout-open, a block opens at the column of the next token. |
These [language] keys adjust the layout and the grammar's view of the tokens:
| Key | What it does |
|---|---|
layout-ignore-in | Brackets inside which a line end is not a NEWLINE: ( [ {. The innermost bracket decides, so a block in braces inside a call's parentheses (R's function(x) { ... }) still has its NEWLINEs. The #{ ... } and ${ ... } of a string also hide line ends, so interpolated code can take several lines. |
layout-continue-after | A line that ends with one of these continues on the next line (Go's +, Ruby's ,). The marker <operator> stands for every operator except : = ; :: * (Nim: a !& at the end of a line goes on). Such a word does not join a line that dedents (the last value of an enum, with its comma). |
layout-continue-before | A line that starts with one of these continues the line above (a leading .). The marker <attribute> stands for a line that starts with an attribute and is deeper than its block, after a token that is not : or = (Nim: a {.pragma.} under its proc's header). A pragma at the block's own indentation is a statement. |
layout-block-after | Only with layout = indent. A line that ends with one of these, followed by a deeper line, opens a block. Inside brackets that hide line ends, this lets Nim pass a proc ... = or a do: as an argument; the block closes when a line dedents under it or at the closing bracket, and when its last line ends with a comma the DEDENTs come before the comma, so the next argument follows. Outside brackets it applies to a word that also continues a line (Scala 3: def f =, then the lines of the body), so a one-line body and a many-line body both give NEWLINE, INDENT and DEDENT. |
layout-open | For the offside layout: the words after which a block opens at the next token's column (Haskell: where let do of). |
layout-restart | Words that no expression continues with: a line inside brackets that starts with one, no deeper than the brackets' line, closes them (Python's def, class, return ...). This keeps one unclosed bracket from swallowing the rest of the file. |
operator-characters | Any run of these characters is one operator, listed or not (Haskell: <$ >=> .:). |
underscore-operators | true: a name that ends in _ continues with a run of the operator characters (Scala: unary_!, tpe_*), but not after a lone _ (case _: T). |
dotted-operators | true: a dot, letters and a dot are one operator (Fortran: .det., .myop.). |
digit-names | true: digits followed by letters that make no number (no hex digits, exponent or suffix) are a name, as Vala reads 3DES_CBC. |
continuation-in-strings | true: the line-continuation character at the end of a line inside a string continues the string, and the same character at the start of the next line is skipped (Fortran). |
soft-keywords | Keywords that count as a NAME where the grammar wants a name (Python's match, case, type, _). They are still colored as keywords. |
split-operators | Tokens that a literal may take apart: >>, so Vec<Vec<T>> closes two type argument lists. |
self-words | Words for the object itself: self this. self.x is then a member of the class around it. |
class-scope | hidden: a method sees its class's names only through self (Python). Otherwise they are visible directly. |
assign-scope | local: an assignment defines a variable in its own scope (Python, unless global or nonlocal says otherwise). Otherwise an assignment reaches a visible name outside. |
sigil-free-names | true: $x and ${x} refer to the variable that x=1 defines (shell). |
loose-strings | true: a string with no end is not a fault, so the file can still be valid (INI values). The string is still colored as a string. |
More rules of the indent layout:
- A lone
line-continuationcharacter at the end of a line (in thelinesandindentlayouts) joins the lines and is not a token. - A line that dedents to a column between two levels opens a level of its own. Nim puts a routine's return type on the next line, deeper than the body under it.
- A bracket that keeps its line ends closes the blocks that opened in it. So
{for x in y, a deeper line, then}on that line is a complete block (CoffeeScript JSX).
The offside layout follows GHC's rules:
incloses the block of itslet(the lastletthat has noinyet) and the blocks that opened in it:let a = case x of _ -> 1 in a. When the layout already closed that block (aninat the start of a line, left of the block),incloses nothing more.- A bracket of
layout-ignore-in(Haskell:{) has no layout inside it, except for the blocks that open in it. So the}of a record can stand at the start of a line. - A line that starts with
|at the column of a block closes the block: a guard after the last statement of adoblock is not one of its statements. - A
,inside the brackets around a block closes the blocks that opened in those brackets ([ do ..., x ]). Outside brackets, a,closes only aletblock (f x | let y = 1, y > 0 = ...). A,between a|and its->or=is part of the guard and closes nothing. - Inside brackets, a
|after the->of an alternative closes its block ([case x of A -> 1 | c]). recopens a block only at the start of a statement; elsewhere it is a name.- A file that does not begin with
moduleis one block. - After a
layout-openword, a{opens an explicit block with no layout. - A line that starts with
whereat a block's column closes that block, as|does, and awherecloses an opendoblock. \caseopens a block of alternatives.
Code the grammar does not read
The grammar sees only the code that counts. The lines from #if 0 to its #endif (or to an #else or #elif at the same level), the later branches of conditional code (see conditional-words), and the body of a FreeBASIC #macro ... #endmacro (with its ## and #x) are hidden from it. The lexer still colors them, and brace pairing still sees them.
Embedded languages
Some files hold code in other languages. Kami colors that code with the other language's own file, so changing javascript.lang also changes the JavaScript inside HTML. For a document, Unryu sends the analysis the document's language file, each language it names with embed or command-embed (and the languages those embed), and, for a language with fence-languages = true, every installed language.
| Where | How the other language is found |
|---|---|
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 matched against each language's id, then its name, then its extensions, in any case (```python, ```py, ```Python). The rest of the fence line ({.numbered}) is kept apart. A fence in no known language gets the code style. |
| Markdown front matter | YAML between --- lines at the very start, colored with the yaml language; +++ lines give TOML, colored with a toml language when one is installed, otherwise as front matter. |
| HTML in Markdown | HTML blocks and tags in a Markdown file are colored as HTML. |
| 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. |
| Code given to a command in a shell script | command-embed = awk awk first ...: the single-quoted code of awk, sed, perl -e, python3 -c, ruby -e, node -e and jq is colored in that language, and its braces pair. Code in double quotes stays a shell string, as the shell expands it first. |
| String interpolation | interpolation = " ${ }: the code between the markers, in the same language. |
| Shell command substitution | command-substitution = $( ): the code inside, in the same language. |
To see it at work, open markdown-example.md from Unryu's doc folder, which has fenced blocks in several languages, in Unryu.
Styles and theme colors
Every token gets one style. A style name can be used as a key in [words], as a value in [lines], uppercase-style, tick-style, name-prefix, block-fence and inline, and as <style> in a grammar. Unryu colors each style with an item of the editor theme (see Themes):
| Style | Given to | Theme item |
|---|---|---|
default | Text with no other style. | [syntax] identifier |
comment | A block comment. | [syntax] comment |
comment-line | A line comment. | [syntax] comment-line |
comment-doc | A block comment that starts with a doc-comment opener. | [syntax] comment-doc |
comment-line-doc | A line comment that starts with a doc-comment opener. | [syntax] comment-line-doc |
number | A number. | [syntax] number |
string | A string, a heredoc, a header name; in Markdown, a link's address. | [syntax] string |
character | A character constant; in Markdown, an escape. | [syntax] character |
keyword | A [words] keyword; in Markdown, a task box and a quote kind. | [syntax] keyword |
type | A [words] type. | [syntax] type |
constant | A [words] constant, a symbol (:name); in Markdown, a done task, ^sup^ and ~sub~. | [syntax] constant |
builtin | A [words] builtin. | [syntax] builtin |
attribute | @name, #[...], a markup attribute's name, a [words] attribute; in Markdown, a fence's language and a link's title. | [syntax] attribute |
preprocessor | A directive; in Markdown, front matter. | [syntax] preprocessor |
operator | An operator or punctuation. | [syntax] operator |
brace | { } ( ) [ ]. | [syntax] brace |
identifier | Any other name. | [syntax] identifier, or the color of its kind (below) |
regex | A regex literal; in Markdown, math. | [syntax] regex |
variable | A name with its sigil: $x, @x, %x%. | [syntax] variable |
label | A tick name when tick-style = label (Rust's 'a), a label line; in Markdown, a link label and a footnote. | [names] label |
macro | A macro call: name!. | [names] macro |
tag | A markup tag with its < > </ />. | [syntax] tag |
entity | &, . | [syntax] entity |
heading | A document heading. | [syntax] heading |
emphasis | *emphasis*. | [syntax] emphasis |
strong | **strong**. | [syntax] strong |
link | A link's text, <url>. | [syntax] link |
code | `code`, a fenced block in no known language, CDATA. | [syntax] code |
inserted | A diff's added line. | [syntax] inserted |
deleted | A diff's removed line, ~~struck~~ text. | [syntax] deleted |
changed | A diff's @@ and file lines; in Markdown, ==marked== text. | [syntax] changed |
A name that Kami has linked to a definition does not use its style's color: it takes the color of its kind from the theme's [names] section (local, global, parameter, function, type-name, tag, member, enumerator, label, macro), and the place where it is defined can get a background from [declared]. A string or character with no end uses [syntax] string-eol when the theme sets it. View > Syntax Highlighting turns all these colors off and on; Plain Text never has them.
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 no-break space and the other Unicode spaces end a name.
- 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) and$keys.1.2(PowerShell) are members by number. - A sign right before a digit is an operator in a language where no name starts with a digit (PowerShell:
-1beside-Name). - 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.
C and C++
C, C++, Arduino and CUDA use engine = c or engine = c++. Their language files (c.lang and cpp.lang; Arduino and CUDA have their own) set the words and the lexical rules, as for any language, and your copy of them is used. What reads the names is Kami's own C machinery, with a real preprocessor for macros and conditional code, not a grammar in the file.
The C reader checks the C grammar. The C++ reader does not check the full grammar, because C++ cannot be parsed without knowing every type, and an editor needs the names of code that does not compile yet. It pairs the brackets first, then reads each statement by its form, so a statement it cannot read costs only that statement. A C++ file is "valid" when its brackets pair. It understands:
| Code | Is read as |
|---|---|
namespace A { }, namespace A::B { }, a namespace opened again | A type with its members. A namespace opened again is the same namespace for lookups. |
class, struct, union with bases, final and attributes | A type, owning its members, methods, nested types, constructor and destructor. |
template <typename T, int N> | The parameters are names of the class or function the template makes. |
void A::B::f() { }, int A::count = 0; | A member of its class, not of the file. |
enum, enum class | A type with its enumerators. A plain enum's enumerators are names of the scope around it. |
typedef, using T = ..., namespace X = Y;, concept | A type. |
Parameters, a constructor's initializer list, locals, for (auto &x : xs), auto [a, b], catch (E &e), lambdas | Names of their function or block. |
| Any other name | A use, found through the scopes around it, the class of a method and its bases, using namespace, and qualifiers (A::b). A member after . or -> is found by the type of what stands before it. auto x = ... takes the type of its value: Foo{}, Foo(1), new Foo, make_unique<Foo>(), static_cast<Foo *>(p), another variable, or a function's return type. |
Adding a new language
- Start from a similar language. Open Tools > Configuration Files > Language Files and pick a language that looks like yours (braces like Java, indentation like Python,
endwords like Ruby). Save it under a new name in~/.config/unryu/languages/, for exampletiny.lang. The file name without.langis the new language's id; use lower case letters, digits and_. Every key is already in the file with a comment saying what it does. Or start from the Tiny example above. - Name it and claim its files. Set
name, andextensions,filenamesandshebangsfor your files. Remove those of the language you copied, or both languages will claim the same files. If you must share an ending with another language, give one of themdetectwords. - Describe the tokens. Fill in the
[lexical]keys: comments, strings, the escape, numbers and the operators (list the long ones; Kami tries them longest first). Empty every key that does not apply. - List the words. Put the keywords, types, constants and built-in names in
[words]. - Look at it. Open a file in the language. Unryu reads the new file the next time you open a menu, and uses it for files opened after that; for a file that is already open, choose the language with Document > Set Filetype. Check the colors, and fix keys until they are right.
- Find the definitions. Set
blocks(and the block words forkeywords), then add[symbols]patterns. The Outline should now list the functions and types. - Set the editing keys. Set
comment-toggle,indent-afterand, for a language with C'sstruct S { };,semicolon-afterin[editing], and check Toggle Line Commentation (Ctrl+E). - Optionally, write a grammar. A
[grammar]gives a syntax check, scopes and exact links from each use to its definition. Start withfile = @many(statement) ENDand a few statements, and grow it rule by rule. Choose alayoutif line ends or indentation matter. Use the language's reference grammar as a guide, and annotate the names that define things. Keep your[symbols]patterns: they are the fallback. - Check the result. The Details panel shows how many symbols Kami found and, when the file does not parse, the first fault with its line. A valid file that Kami calls invalid points to a missing rule.
If something does not work, look for these common causes: a key in the wrong section; a marker longer than 15 bytes, or a list longer than 24 items (the rest is dropped); a [lines] prefix that starts with ; or ends with a space and is not in quotes; case-sensitive = false written after [words]; and another language that claims the same ending.
Using Kami in another program
Kami has no display and no toolkit, and a language is parsed from text (only the C preprocessor opens files: the headers a C file includes), so any program can ship its own language files. The functions are declared in language.h:
Language language;
language_parse(&language, file_text, "python");
if (language_match(&language, path, first_line)) {
Lexer lexer;
language_lex(&language, &lexer, text, length);
for (size_t index = 0; index < lexer.token_count; index++) {
LanguageStyle style = language_token_style(&language, &lexer, index);
// color lexer.tokens[index] as language_style_name(style) says
}
SemanticModel model;
if (!language_symbols_build(&language, &lexer, &model)) semantic_free(&model);
lexer_free(&lexer);
}
language_free(&language);
language_match() returns 3 for a whole file name, 2 for an ending or a file name pattern, 1 for a #! program and 0 for no match; language_detect_score() breaks ties. language_symbols_build() uses the grammar when there is one and the patterns otherwise (and the patterns when the grammar gives up). For engine = c or c++, Kami's C reader is semantic_build(), declared in semantic.h. For a language that embeds others, put several files in one text, each after a line %%language ID (the first file needs no such line), read them with language_set_parse() and lex with language_lex_set(). language_builtin("c") and language_builtin("cpp") give Kami's built-in C and C++ languages.