code: keep large-file parsing off the main thread (#665)
- Commit
3c38e28350af18045409222a9d0f3e2e241402c6- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-11 17:11 UTC (2 months ago)
- Parents
e229803
Diff
code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt
diff --git a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.ktindex 486c8d48fb..29bd16c887 100644--- a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt+++ b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt@@ -23,6 +23,17 @@ import com.vayunmathur.library.ui.MaterialTheme */ enum class TokenKind { COMMENT, STRING, NUMBER, ANNOTATION, KEYWORD } +/**+ * Above this many characters no whole-document highlighting is attempted at all.+ *+ * Every whole-document pass — the regex tokenizer, the native tree-sitter parse, and the+ * per-character rainbow-bracket scan — is O(document) and produces one span per token, and the+ * resulting spans are re-applied by Compose on every text layout. 150k characters is roughly a+ * 4000-line source file: larger than anything hand-written, and small enough that a single pass+ * stays in the low tens of milliseconds. Past it the file still opens and edits fine, uncolored.+ */+const val MAX_HIGHLIGHT_CHARS = 150_000+ /** Precompiled tokenizer for one language: the alternation regex + per-group kinds. */ class LanguageSpec(private val parts: List<Pair<TokenKind, String>>) { private val kinds: List<TokenKind> = parts.map { it.first }@@ -589,8 +600,9 @@ class SyntaxTransformation( } } - val highlight = spec != null && raw.length <= MAX_HIGHLIGHT_LENGTH- if (tsSpans != null) {+ val withinBudget = raw.length <= MAX_HIGHLIGHT_CHARS+ val highlight = spec != null && withinBudget+ if (tsSpans != null && withinBudget) { // Rainbow brackets first; tree-sitter colours paint on top. if (colors.brackets.isNotEmpty()) { var depth = 0@@ -663,8 +675,9 @@ class SyntaxTransformation( } } - // Bracket matching: check the char before and at the caret.- if (caret in 0..raw.length) {+ // Bracket matching: check the char before and at the caret. Finding the partner is a scan+ // that can run to the end of the document, so it shares the highlighting budget.+ if (withinBudget && caret in 0..raw.length) { val candidate = when { caret > 0 && raw[caret - 1] in "()[]{}" -> caret - 1 caret < raw.length && raw[caret] in "()[]{}" -> caret@@ -693,9 +706,6 @@ class SyntaxTransformation( } private companion object {- // Above this size, skip tokenization: a single regex pass over hundreds of KB per- // keystroke would jank. The file still opens and edits fine, just uncolored.- const val MAX_HIGHLIGHT_LENGTH = 150_000 val FUNCTION_REGEX = Regex("\\b[A-Za-z_]\\w*(?=\\s*\\()") val TYPE_REGEX = Regex("\\b[A-Z]\\w*\\b") val TRAILING_WS_REGEX = Regex("[ \\t]+$", RegexOption.MULTILINE)
code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.ktindex a511ab5eff..4d6533f4c3 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -144,9 +144,7 @@ fun CodeEditor( val syntaxColors = rememberSyntaxColors(editorTheme) val highlightMatches = if (showFind) matches else emptyList() val caret = if (tab.value.selection.collapsed) tab.value.selection.start else -1- val tsSpans = remember(text, tab.language, syntaxColors) {- treeSitterColorSpans(text, tab.language, syntaxColors)- }+ val tsSpans = rememberTreeSitterSpans(text, tab.language, syntaxColors) val transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch, caret, tsSpans) { SyntaxTransformation(tab.language.spec, syntaxColors, highlightMatches, activeMatch, caret, tsSpans) }
code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.ktindex 503f4f20a3..95b5370a74 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt@@ -119,8 +119,9 @@ fun CodeEditorView( } val diagnosticsByLine = remember(diagnostics) { diagnostics.groupBy { it.line } } val spec = tab.language.spec- // Native tree-sitter spans (cached); null → the regex tokenizer in [annotatedLine] is used.- val tsSpans = remember(text, tab.language, colors) { treeSitterColorSpans(text, tab.language, colors) }+ // Native tree-sitter spans (parsed off the main thread); null → the regex tokenizer in+ // [annotatedLine] is used, both while the parse is in flight and when it is unavailable.+ val tsSpans = rememberTreeSitterSpans(text, tab.language, colors) val measurer = rememberTextMeasurer() val density = LocalDensity.current@@ -438,9 +439,20 @@ fun CodeEditorView( drawText(arrowLayout, color = gutterColor, topLeft = Offset(2f, y)) } - val annotated = annotatedLine(lineText, spec, colors, tsSpans, lineStart)- val layout = measurer.measure(annotated, style)- drawText(layout, topLeft = Offset(gutterWidth - scrollX, y))+ // Lines past MAX_LINE_HIGHLIGHT render unstyled, so only the columns inside the+ // viewport need measuring — a one-line multi-megabyte document (a minified JSON+ // blob, say) would otherwise lay its whole line out on every frame.+ if (lineLen > MAX_LINE_HIGHLIGHT) {+ val firstCol = (scrollX / charWidth).toInt().coerceIn(0, lineLen)+ val lastCol = (firstCol + (size.width / charWidth).toInt() + 2).coerceAtMost(lineLen)+ if (lastCol > firstCol) {+ val slice = measurer.measure(AnnotatedString(lineText.substring(firstCol, lastCol)), style)+ drawText(slice, topLeft = Offset(gutterWidth + firstCol * charWidth - scrollX, y))+ }+ } else {+ val annotated = annotatedLine(lineText, spec, colors, tsSpans, lineStart)+ drawText(measurer.measure(annotated, style), topLeft = Offset(gutterWidth - scrollX, y))+ } if (caret in lineStart..(lineStart + lineLen)) { val cx = gutterWidth + (caret - lineStart) * charWidth - scrollX
code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.ktindex 00af09b35f..2a6fa64979 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorChrome.kt@@ -14,6 +14,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.produceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource@@ -25,6 +26,7 @@ import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupProperties import com.vayunmathur.code.R import com.vayunmathur.code.syntax.Language+import com.vayunmathur.code.syntax.MAX_HIGHLIGHT_CHARS import com.vayunmathur.code.syntax.SyntaxColors import com.vayunmathur.code.syntax.TsColorSpan import com.vayunmathur.code.util.Completion@@ -39,6 +41,8 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext /** * Shared editor chrome used by both the classic [CodeEditor] and the experimental@@ -208,7 +212,29 @@ fun SyntaxColors.tsColor(kind: TsKind): Color = when (kind) { /** * Native tree-sitter colour spans for [text] in [language] resolved against [colors], or null when * tree-sitter is unavailable / the language is unsupported — signalling the regex fallback. Blocking- * (parses the whole file), so callers must cache it via `remember(text, language)`.+ * (parses the whole file), so composables must go through [rememberTreeSitterSpans] rather than+ * calling this directly. */ fun treeSitterColorSpans(text: String, language: Language, colors: SyntaxColors): List<TsColorSpan>? = TreeSitterNative.spans(text, language)?.map { TsColorSpan(it.start, it.end, colors.tsColor(it.kind)) }++/**+ * [treeSitterColorSpans] parsed off the main thread.+ *+ * `remember` caches the result but still runs the parse during composition, so opening a large+ * file blocked the main thread for the whole parse — and did it again on every keystroke, since+ * the buffer text is a key. This starts at null (the per-line regex tokenizer takes over) and+ * swaps the spans in when the parse finishes. Documents past [MAX_HIGHLIGHT_CHARS] are never+ * parsed: applying that many spans on every text layout costs more than the colours are worth.+ */+@Composable+internal fun rememberTreeSitterSpans(+ text: String,+ language: Language,+ colors: SyntaxColors,+): List<TsColorSpan>? = produceState<List<TsColorSpan>?>(null, text, language, colors) {+ value = null+ if (text.length <= MAX_HIGHLIGHT_CHARS) {+ value = withContext(Dispatchers.Default) { treeSitterColorSpans(text, language, colors) }+ }+}.value
code/src/main/java/com/vayunmathur/code/util/EditorInput.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt b/code/src/main/java/com/vayunmathur/code/util/EditorInput.ktindex 14df9f3a50..6148be507e 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt@@ -24,6 +24,18 @@ private fun matchingCloser(opener: Char): Char = when (opener) { else -> opener } +/**+ * True when [new] is [old] with exactly [length] characters inserted so that the insertion ends at+ * [caret]. Compared in place: the equivalent `substring + concat + equals` allocated three copies+ * of the whole buffer on every keystroke, which is what made typing in a multi-megabyte file stall.+ */+private fun isPlainInsertion(old: String, new: String, caret: Int, length: Int): Boolean {+ val prefixLength = caret - length+ if (prefixLength < 0 || new.length != old.length + length) return false+ return new.regionMatches(0, old, 0, prefixLength) &&+ new.regionMatches(caret, old, prefixLength, old.length - prefixLength)+}+ fun applyEditorInput( old: TextFieldValue, new: TextFieldValue,@@ -38,9 +50,7 @@ fun applyEditorInput( // Paste: a multi-character insertion containing a newline. Re-base its indentation onto the // caret line so pasted blocks line up with their new surroundings. if (diff > 1 && caret >= diff) {- val cleanInsertion =- old.text == new.text.substring(0, caret - diff) + new.text.substring(caret)- if (cleanInsertion) {+ if (isPlainInsertion(old.text, new.text, caret, diff)) { val pasted = new.text.substring(caret - diff, caret) if (autoIndent && pasted.contains('\n')) { return reindentPaste(old.text, caret - diff, pasted, indentUnit)@@ -51,7 +61,7 @@ fun applyEditorInput( // Must be exactly one character longer, inserted so that removing it reproduces the old text. if (diff != 1 || caret < 1) return new- if (old.text != new.text.substring(0, caret - 1) + new.text.substring(caret)) return new+ if (!isPlainInsertion(old.text, new.text, caret, 1)) return new val c = new.text[caret - 1] val pos = caret - 1 // index in old.text where the character was inserted
code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.ktindex 4388d3e200..4948e4daa5 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -197,6 +197,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val completions = mutableStateListOf<Completion>() var showCompletions by mutableStateOf(false) private set+ private var completionsJob: Job? = null // ---- Diagnostics ---- val diagnostics = mutableStateListOf<Diagnostic>()@@ -704,8 +705,14 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), override fun requestCompletions() = updateCompletions() - /** Recomputes the completion list from the caret's word prefix and the open buffers. */+ /**+ * Recomputes the completion list from the caret's word prefix and the open buffers.+ *+ * Debounced and computed off the main thread: scanning every open buffer for identifiers is+ * O(all open documents), so doing it inline on each keystroke stalled typing in a large file.+ */ private fun updateCompletions() {+ completionsJob?.cancel() val tab = currentTab if (tab == null || !tab.value.selection.collapsed) { dismissCompletions()@@ -716,11 +723,18 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), dismissCompletions() return }- val buffers = tabs.map { it.value.text }- val list = computeCompletions(prefix, tab.language, buffers, MAX_COMPLETIONS, userSnippets.toList())- completions.clear()- completions.addAll(list)- showCompletions = list.isNotEmpty()+ val buffers = tabs.map { it.value.text }.filter { it.length <= MAX_COMPLETION_BUFFER_CHARS }+ val language = tab.language+ val snippets = userSnippets.toList()+ completionsJob = viewModelScope.launch {+ delay(COMPLETIONS_DELAY_MS)+ val list = withContext(Dispatchers.Default) {+ computeCompletions(prefix, language, buffers, MAX_COMPLETIONS, snippets)+ }+ completions.clear()+ completions.addAll(list)+ showCompletions = list.isNotEmpty()+ } } override fun acceptCompletion(item: Completion) {@@ -739,6 +753,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), } override fun dismissCompletions() {+ completionsJob?.cancel() if (completions.isNotEmpty()) completions.clear() showCompletions = false }@@ -1432,8 +1447,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), private companion object { const val AUTO_SAVE_DELAY_MS = 1500L const val DIAGNOSTICS_DELAY_MS = 400L+ const val COMPLETIONS_DELAY_MS = 150L const val MIN_COMPLETION_PREFIX = 1 const val MAX_COMPLETIONS = 50+ // Buffers larger than this are left out of the identifier scan. A multi-megabyte file has+ // no useful completions in it anyway, and scanning it on every keystroke burns a core.+ const val MAX_COMPLETION_BUFFER_CHARS = 1_000_000 const val GIT_LOG_LIMIT = 30 const val TERMINAL_SCROLLBACK = 2000 const val MAX_SEARCH_RESULTS = 500
code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt b/code/src/main/java/com/vayunmathur/code/util/TextEncoding.ktindex 8c3e9c7c6b..e099b5e193 100644--- a/code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt+++ b/code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt@@ -75,8 +75,13 @@ object TextEncoding { return if (crlf > 0 && crlf >= lf) LineEnding.CRLF else LineEnding.LF } - /** Collapses CRLF and lone CR to LF so the editor buffer is always `\n`-terminated. */- fun normalizeToLf(text: String): String = text.replace("\r\n", "\n").replace('\r', '\n')+ /**+ * Collapses CRLF and lone CR to LF so the editor buffer is always `\n`-terminated. Returns the+ * input untouched when there is no CR at all, which is the common case: the two `replace` calls+ * each copy the whole document, so on a large file they were the bulk of the open cost.+ */+ fun normalizeToLf(text: String): String =+ if (text.indexOf('\r') < 0) text else text.replace("\r\n", "\n").replace('\r', '\n') private fun bomFor(charset: Charset): ByteArray = when (charset) { Charsets.UTF_8 -> UTF8_BOM
code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt b/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.ktindex c3628511bd..f33556bcc7 100644--- a/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt+++ b/code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt@@ -14,8 +14,8 @@ data class TsSpan(val start: Int, val end: Int, val kind: TsKind) * missing for the current ABI (e.g. the reproducible `.so` was not built), so callers fall back to * the regex tokenizer instead of crashing. This mirrors the `PdfNative` graceful-degradation pattern. *- * [highlight] is blocking (it parses the whole file), so callers must cache its result off the hot- * path — see `remember(text, language)` in the editors.+ * [highlight] is blocking (it parses the whole file), so callers must run it off the main thread and+ * cache the result — see `rememberTreeSitterSpans` in the editors. */ object TreeSitterNative {
code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt b/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.ktindex 98356187c1..50a06330a0 100644--- a/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt+++ b/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt@@ -109,6 +109,16 @@ class EditorInputTest { assertEquals(2, result.selection.start) } + @Test+ fun editThatIsNotAPlainInsertionAtTheCaretIsReturnedUnchanged() {+ // Same length delta as typing one character, but the surrounding text also changed, so+ // smart input must not treat it as an insertion of "(" and auto-close it.+ val old = TextFieldValue("foo", TextRange(3))+ val new = TextFieldValue("f(oo", TextRange(4))+ val result = apply(old, new)+ assertEquals("f(oo", result.text)+ }+ @Test fun lineStartOffsetFindsLineStarts() { val text = "a\nbb\nccc"
code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt b/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.ktindex 134f50970b..25f47949d7 100644--- a/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt+++ b/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt@@ -4,6 +4,7 @@ import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFalse+import kotlin.test.assertSame import kotlin.test.assertTrue /** Unit tests for the pure encoding / line-ending detection and round-tripping. */@@ -32,6 +33,12 @@ class TextEncodingTest { assertEquals("a\nb\nc", TextEncoding.normalizeToLf("a\r\nb\rc")) } + @Test+ fun normalizeReturnsTheSameStringWhenThereIsNothingToDo() {+ val text = "a\nb\nc"+ assertSame(text, TextEncoding.normalizeToLf(text))+ }+ @Test fun decodesPlainUtf8() { val decoded = TextEncoding.decode("hello".toByteArray(Charsets.UTF_8))