Syntax highlighting in the file viewer and in a reply's code blocks
CI / check (push) Canceled after 0s

A small scanner of the app's own (ui/Highlight.kt) rather than Prism4j (annotation processor,
unmaintained since 2019): comments, strings, numbers, keywords, types, markup tags/attributes,
YAML/TOML keys and shell/PHP variables for the server's `show` languages plus common fence
aliases. Colours are theme tokens only (accent, success, warning, leaf, ink-faint). The viewer
highlights off the main thread (plain until ready; at once in previews); over 400k chars stays
plain. HighlightTest; shots 33-viewer-{kotlin,python,yaml,typescript}, 34-code-block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-10 16:17:39 +00:00
1 parent 9976186599
commit 9592fbeeb4
7 files changed
+618 -14

No files matched your search

@@ -0,0 +1,85 @@
package eu.llembas.android
import eu.llembas.android.ui.TokenKind
import eu.llembas.android.ui.highlights
import eu.llembas.android.ui.tokenize
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class HighlightTest {
/** Each token as its text and kind, for reading a test at a glance. */
private fun read(text: String, language: String): List<Pair<String, TokenKind>> =
tokenize(text, language).map { text.substring(it.start, it.end) to it.kind }
@Test
fun kotlinKeywordsStringsCommentsNumbersAndTypes() {
val got = read("val x: Int = 42 // the answer\nfun f() = \"a \\\" b\"", "kotlin")
assertTrue("val" to TokenKind.Keyword in got)
assertTrue("Int" to TokenKind.Type in got)
assertTrue("42" to TokenKind.Number in got)
assertTrue("// the answer" to TokenKind.Comment in got)
assertTrue("fun" to TokenKind.Keyword in got)
// An escaped quote does not end the string.
assertTrue("\"a \\\" b\"" to TokenKind.Text in got)
}
@Test
fun aBlockCommentRunsAcrossLines() {
val text = "/* one\n two */ int x;"
val got = read(text, "c")
assertEquals("/* one\n two */" to TokenKind.Comment, got.first())
assertTrue("int" to TokenKind.Keyword in got)
}
@Test
fun pythonTripleQuotesAndHashComments() {
val got = read("def f():\n \"\"\"Doc\n string\"\"\"\n return None # nothing", "py")
assertTrue("def" to TokenKind.Keyword in got)
assertTrue("\"\"\"Doc\n string\"\"\"" to TokenKind.Text in got)
assertTrue("None" to TokenKind.Keyword in got)
assertTrue("# nothing" to TokenKind.Comment in got)
}
@Test
fun anUnclosedQuoteColoursOneLineNotTheFile() {
val got = read("echo don't\nls -la", "bash")
val string = got.first { it.second == TokenKind.Text }
assertFalse(string.first.contains('\n'))
}
@Test
fun sqlIgnoresCaseAndShellHasVariables() {
assertTrue("SELECT" to TokenKind.Keyword in read("SELECT * FROM t -- all", "sql"))
assertTrue("-- all" to TokenKind.Comment in read("SELECT * FROM t -- all", "sql"))
assertTrue("\$HOME" to TokenKind.Attribute in read("cd \$HOME", "sh"))
}
@Test
fun markupTagsAttributesAndValues() {
val got = read("<!-- note -->\n<a href=\"x\">don't</a>", "xml")
assertEquals("<!-- note -->" to TokenKind.Comment, got.first())
assertTrue("a" to TokenKind.Tag in got)
assertTrue("href" to TokenKind.Attribute in got)
assertTrue("\"x\"" to TokenKind.Text in got)
// Prose between tags is not a string.
assertFalse(got.any { it.first.startsWith("'") })
}
@Test
fun yamlKeys() {
val got = read("name: lembas\ncount: 3\n# end", "yaml")
assertTrue("name" to TokenKind.Type in got)
assertTrue("3" to TokenKind.Number in got)
assertTrue("# end" to TokenKind.Comment in got)
}
@Test
fun anUnknownLanguageIsPlain() {
assertFalse(highlights("brainfuck"))
assertTrue(tokenize("anything at all", "").isEmpty())
assertTrue(highlights("TypeScript"))
assertTrue(highlights("c++"))
}
}
@@ -423,6 +423,60 @@ object Fakes {
error = "Home cannot be reached.",
)
/** Source files for the viewer's highlighting: language and text. */
val codeFiles: Map<String, Pair<String, String>> = mapOf(
"kotlin" to (
"kotlin" to """
|package shire.kitchen
|
|/** Waybread keeps for days if it is wrapped in a leaf. */
|data class Lembas(val pieces: Int = 3, val wrapped: Boolean = true)
|
|fun share(bread: Lembas, walkers: List<String>): Map<String, Double> {
| if (!bread.wrapped) return emptyMap() // it has gone stale
| val each = bread.pieces.toDouble() / walkers.size
| return walkers.associateWith { each * 0.5 }
|}
""".trimMargin()
),
"python" to (
"python" to """
|import json
|
|
|class Pantry:
| ""${'"'}What is left for the road.""${'"'}
|
| def __init__(self, path: str) -> None:
| self.items = json.load(open(path)) # one file, read once
|
| def count(self, name="lembas"):
| return sum(1 for item in self.items if item == name) or None
""".trimMargin()
),
"yaml" to (
"yaml" to """
|# The road east
|name: Long Road
|stops: 7
|provisions:
| - lembas
| - "honey cakes"
|rest: true
""".trimMargin()
),
"typescript" to (
"typescript" to """
|interface Stop { name: string; miles: number }
|
|export async function next(stops: Stop[]): Promise<Stop | undefined> {
| // the nearest first
| return stops.sort((a, b) => a.miles - b.miles)[0];
|}
""".trimMargin()
),
)
// A share from another app.
val shareLink = ShareState(
text = "The Long Road: a walker's guide to waybread\nhttps://example.org/waybread",
@@ -39,6 +39,7 @@ import eu.llembas.android.ui.chat.ActivityContent
import eu.llembas.android.ui.chat.CardSheet
import eu.llembas.android.ui.chat.ChatActions
import eu.llembas.android.ui.chat.ChatContent
import eu.llembas.android.ui.chat.CodeBlock
import eu.llembas.android.ui.chat.ModelPickerContent
import eu.llembas.android.ui.chat.TuneContent
import eu.llembas.android.ui.chat.modelId
@@ -59,6 +60,7 @@ import eu.llembas.android.ui.settings.LanguageChoices
import eu.llembas.android.ui.settings.SettingsActions
import eu.llembas.android.ui.settings.SettingsContent
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.ui.viewer.FileBody
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -306,6 +308,18 @@ class ScreenShots {
shoot("28-memory-none") { MemoryContent(MemoryState(), NoMemoryActions) }
}
/** The file viewer's code in the theme's colours, a few languages, and a reply's code block. */
@Test
fun highlighting() {
for ((name, file) in Fakes.codeFiles) {
shoot("33-viewer-$name") { FileBody("code", file.first, line = 3, text = file.second) }
}
shoot("33-viewer-kotlin", Phone.Small, fontScale = 1.5f) { FileBody("code", "kotlin", line = 0, text = Fakes.codeFiles.getValue("kotlin").second) }
shoot("34-code-block") {
Column(Modifier.fillMaxSize().padding(16.dp)) { CodeBlock("ts", Fakes.codeFiles.getValue("typescript").second) }
}
}
/** "Ask LLeMbas" from another app's share menu: a link, and a picture with a file. */
@Test
fun share() {