·5 min read
TaskPad code highlighting: 30 languages from one table, generated XSHD, cached fences
I wanted fenced code blocks in TaskPad notes to be coloured like a real editor, and I did not want to hand-write thirty AvalonEdit .xshd files, one per language and one per theme. Thirty languages times eight themes is 240 XML files that would all need the same change the first time I decided strings should be italic. So the highlighting file has no .xshd files at all. It has a table of language specs and a function that prints XML.
- Project
- TaskPad
- Date
- Oct 2026
- Stack
- C#, WPF, AvalonEdit
- Commit
- 5b2216b
One spec, one generator
A language looks like this in src/CodeHighlight.cs:
new Lang { Name = "Go", Aliases = new[] { "go", "golang" }, Exts = new[] { ".go" },
Line = "//", BlockStart = "/*", BlockEnd = "*/", Backtick = true,
Keywords = "break case chan const continue default defer else ...",
Types = "bool byte ... string uint ... make new len cap append panic recover fmt",
Constants = "true false nil iota" },There are 30 of these. The boolean flags carry the quirks: Triple for Python/Kotlin/Swift triple-quoted strings, DollarVars for shell and PHP, HashPreproc for C and Rust attributes, Decorators for @name, KeysBeforeEquals for TOML and INI, and dedicated Json, Yaml, Css, Diff and Markup modes where the structure is too different from "keywords and strings" to share rules.
Xshd(Lang, CodeTheme) turns one of these into an XML string: a <Color> per token class, then rules in a deliberate order. Comments first, so # or // wins over everything after it; then strings; then decorators and variables; then keyword, type and constant word lists; then PascalCase identifiers, function calls (an identifier followed by () and numbers. The order is part of the semantics: the rules are tried together, and where two start at the same position the earlier one decides.
The generated string is fed to HighlightingLoader.Load and cached in a Definitions dictionary. Changing the theme calls Refresh(), which clears that dictionary and the block cache and asks every open view to re-apply. No file is touched. Eight themes are just eight calls to a helper T(...) that takes a background and twelve hex colours.
Word lists that are not words
One detail in the generator came from a real constraint. <Keywords> in XSHD builds a word-boundary match, so it works for def and while but not for $true, .PHONY, @media, !important or ~. These all appear in the specs (PowerShell constants, Makefile directives, CSS at-rules, YAML null). The Words helper splits each list with a regex:
var plain = list.Where(w => Regex.IsMatch(w, @"^[A-Za-z_][\w]*$")).ToList();
var odd = list.Except(plain).ToList();
...
foreach (var w in odd)
sb.Append($"<Rule color='{color}'>(?<![\\w$@-]){Rx(w)}(?![\\w-])</Rule>");Ordinary identifiers go into a <Keywords> block; everything else becomes an individual rule with lookarounds, so $true is matched whole and -important inside a longer word is not. Every string passes through SecurityElement.Escape or Regex.Escape on its way into the XML, because a marker like PowerShell's <# block-comment opener would otherwise produce an invalid XML document.
If a definition still fails to load, Get catches the exception, appends it to TaskPad-error.log in the temp folder, and stores null, so that block simply renders as plain text instead of taking the editor down.
Finding the fences
Fences live inside an ordinary text editor document, so there is no parse tree to ask. MapOf(doc) scans the lines once and builds an array from line number to fence index, plus a list of Fence objects with Open, Close, Lang and the resolved definition. It is cached in a ConditionalWeakTable<TextDocument, FenceMap>, so a closed document does not leak its map, and a Changed handler only sets Dirty = true. The scan runs again lazily, on the next question, not on every keystroke.
The scan handles both marker styles. A fence opened with three backticks closes only on a line made of those characters; a ~~~ fence is not closed by backticks:
if (open != null && t.StartsWith(marker) && t.TrimStart(marker[0]).Length == 0)An unclosed fence is a normal state while someone is typing, so Close is -1 and everything to the end of the document counts as inside. The background renderer treats that as doc.LineCount. The README also notes that Enter after an opening fence adds the closing one, which keeps that state short-lived.
The language tag is parsed leniently: ForFence takes the text up to the first space, { or comma, and strips a leading dot, so ``` `python {1,3} `` and `` `.py ``` still resolve through the alias table.
Highlighting a block without highlighting the note
The colourizer cannot just run a DocumentHighlighter over the main document, because the note around the fence is not code. Instead, Highlight copies the block's lines into a scratch TextDocument, runs DocumentHighlighter over that, and records each line's sections with offsets relative to the line. The result is cached under lang + "\u0001" + text, and the cache is cleared when it passes 300 entries. Typing in one block therefore re-highlights that block, not the others, and scrolling is a dictionary lookup.
The side effect is that multi-line constructs (a Python triple-quoted string, a /* */ comment) are carried correctly from line to line, because the scratch document is the whole block.
What had to learn about code
Highlighting was the easy half. Task markers, image references, comments and # headings all rewrite or recolour lines, and inside a fence they would corrupt code: a Python comment starting with # is not a heading. The fix was a single predicate, IsCodeLine(doc, line), true for any line of a code file (.py, Dockerfile, Makefile and so on, detected by extension) or inside a fence, and a one-line guard calling it in each of those features. The commit touches Comments.cs, Images.cs, MarkerGenerator.cs, SmartEditing.cs and TaskColorizer.cs for exactly that reason.
The lesson I took: a generated, table-driven design makes adding the thirty-first language a ten-line change, but the cost moves to the boundaries. The grammar was not the hard part; deciding which parts of the editor are allowed to have opinions about a line was.
#csharp#wpf#avalonedit#syntax-highlighting#editor
Keep reading
Have a project in mind?