code: add buffer/keyword/snippet autocomplete with caret-anchored popup
- Commit
7fd4ab87e7176187900e9c92392bc3c15eb51ec3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 22:24 UTC (4 months ago)
- Parents
79f6ead
Diff
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 e7d44f2fd6..73edabe9a9 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -2,14 +2,18 @@ package com.vayunmathur.code.ui import androidx.compose.ui.res.stringResource import com.vayunmathur.code.R+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width@@ -25,15 +29,21 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupProperties import com.vayunmathur.code.syntax.SyntaxTransformation import com.vayunmathur.code.syntax.rememberSyntaxColors import com.vayunmathur.code.util.CodeActions+import com.vayunmathur.code.util.Completion import com.vayunmathur.code.util.TabUiState import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton@@ -44,6 +54,7 @@ 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 kotlin.math.roundToInt /** * The editing surface: an optional find/replace bar above a scroll-synced line-number gutter@@ -61,6 +72,8 @@ fun CodeEditor( fontSize: Int = 14, /** Preview seam: the query the find bar starts on. The app always starts it empty. */ initialQuery: String = "",+ completions: List<Completion> = emptyList(),+ showCompletions: Boolean = false, ) { // Find/replace state is per-tab, so it resets when switching files. Keyed on the file // name rather than the tab value: the latter is rebuilt on every keystroke, which would@@ -163,22 +176,85 @@ fun CodeEditor( val verticalScroll = rememberScrollState() val horizontalScroll = rememberScrollState() val lineCount = remember(text) { text.count { it == '\n' } + 1 }+ var layoutResult by remember { mutableStateOf<TextLayoutResult?>(null) } Row(Modifier.fillMaxSize()) { LineGutter(lineCount, verticalScroll, editorStyle)- BasicTextField(- value = tab.value,- onValueChange = actions::onEditorChange,- modifier = Modifier- .weight(1f)- .fillMaxHeight()- .verticalScroll(verticalScroll)- .then(if (softWrap) Modifier else Modifier.horizontalScroll(horizontalScroll))- .padding(horizontal = 8.dp),- textStyle = editorStyle,- cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),- visualTransformation = transformation,- )+ Box(Modifier.weight(1f).fillMaxHeight()) {+ BasicTextField(+ value = tab.value,+ onValueChange = actions::onEditorChange,+ modifier = Modifier+ .fillMaxSize()+ .verticalScroll(verticalScroll)+ .then(if (softWrap) Modifier else Modifier.horizontalScroll(horizontalScroll))+ .padding(horizontal = 8.dp),+ textStyle = editorStyle,+ cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),+ visualTransformation = transformation,+ onTextLayout = { layoutResult = it },+ )+ val layout = layoutResult+ if (showCompletions && completions.isNotEmpty() && caret >= 0 && layout != null) {+ CompletionPopup(+ completions = completions,+ layout = layout,+ caret = caret,+ hScroll = horizontalScroll.value,+ vScroll = verticalScroll.value,+ onAccept = { actions.acceptCompletion(it) },+ onDismiss = { actions.dismissCompletions() },+ )+ }+ }+ }+ }+}++/**+ * The autocomplete list, anchored just below the caret. Positioned with [TextLayoutResult]'s+ * cursor rect (offset mapping is identity, so no mapping is needed) minus the editor's scroll.+ * The popup is non-focusable so typing keeps driving the text field and the list.+ */+@Composable+private fun CompletionPopup(+ completions: List<Completion>,+ layout: TextLayoutResult,+ caret: Int,+ hScroll: Int,+ vScroll: Int,+ onAccept: (Completion) -> Unit,+ onDismiss: () -> Unit,+) {+ val padPx = with(LocalDensity.current) { 8.dp.roundToPx() }+ val safeCaret = caret.coerceIn(0, layout.layoutInput.text.length)+ val cursorRect = layout.getCursorRect(safeCaret)+ val x = (cursorRect.left - hScroll + padPx).roundToInt()+ val y = (cursorRect.bottom - vScroll).roundToInt()+ Popup(+ alignment = Alignment.TopStart,+ offset = IntOffset(x, y),+ onDismissRequest = onDismiss,+ properties = PopupProperties(focusable = false),+ ) {+ Column(+ Modifier+ .width(240.dp)+ .heightIn(max = 200.dp)+ .background(MaterialTheme.colorScheme.surfaceVariant)+ .verticalScroll(rememberScrollState()),+ ) {+ completions.forEach { completion ->+ Text(+ text = completion.label,+ modifier = Modifier+ .fillMaxWidth()+ .clickable { onAccept(completion) }+ .padding(horizontal = 12.dp, vertical = 6.dp),+ style = TextStyle(fontFamily = FontFamily.Monospace),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } } } }
code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.ktindex a3211dd595..26b8a101a3 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -170,6 +170,8 @@ fun EditorScreen( onCloseFind = { showFind = false }, modifier = Modifier.weight(1f), initialQuery = initialFind.orEmpty(),+ completions = state.completions,+ showCompletions = state.showCompletions, ) } }
code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.ktindex 69b9690ab8..4b4922a84e 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -58,6 +58,8 @@ data class CodeUiState( val autoCloseBrackets: Boolean = true, val searchResults: List<SearchResult> = emptyList(), val isSearching: Boolean = false,+ val completions: List<Completion> = emptyList(),+ val showCompletions: Boolean = false, ) { val currentTab: TabUiState? get() = tabs.getOrNull(currentIndex) }@@ -100,6 +102,17 @@ interface CodeActions { /** Delete the line(s) the selection touches. */ fun deleteLine() {} + // ---- Autocomplete ----++ /** Recompute completions for the current caret position. */+ fun requestCompletions() {}++ /** Accept a completion, replacing the current word (or expanding a snippet). */+ fun acceptCompletion(item: Completion) {}++ /** Hide the completion popup. */+ fun dismissCompletions() {}+ /** Move the selection without recording an undo step (used by find navigation). */ fun setSelection(range: TextRange) {}
code/src/main/java/com/vayunmathur/code/util/Completion.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/Completion.kt b/code/src/main/java/com/vayunmathur/code/util/Completion.ktnew file mode 100644index 0000000000..6d173e9636--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/Completion.kt@@ -0,0 +1,171 @@+package com.vayunmathur.code.util++import com.vayunmathur.code.syntax.Language++/** What a completion candidate came from, used to pick an icon/label in the popup. */+enum class CompletionKind { WORD, KEYWORD, SNIPPET }++/**+ * One completion candidate.+ *+ * [insertText] replaces the current word prefix; [caretOffset] is where the caret lands within+ * [insertText] after accepting (so snippets can place it inside a bracket pair or body).+ */+data class Completion(+ val label: String,+ val insertText: String,+ val caretOffset: Int = insertText.length,+ val kind: CompletionKind = CompletionKind.WORD,+)++/** A snippet template. [CARET_MARKER] in [template] marks where the caret should land. */+private data class Snippet(val trigger: String, val template: String)++private const val CARET_MARKER = "\u0000"++private val IDENTIFIER = Regex("[A-Za-z_][A-Za-z0-9_]*")++/** The identifier characters immediately before [caret] (the word being typed). */+fun currentWordPrefix(text: String, caret: Int): String {+ if (caret <= 0 || caret > text.length) return ""+ var i = caret+ while (i > 0) {+ val c = text[i - 1]+ if (c.isLetterOrDigit() || c == '_') i-- else break+ }+ return text.substring(i, caret)+}++/**+ * Buffer + keyword + snippet completions for [prefix], most relevant first.+ *+ * Candidates: snippet triggers for [language], distinct identifiers pulled from every open+ * buffer ([bufferTexts], ranked by frequency then length), and the language's keywords. All+ * are case-sensitive prefix matches; the exact word already typed is excluded. Pure and+ * testable — the ViewModel supplies the buffers and the UI draws the returned list.+ */+fun computeCompletions(+ prefix: String,+ language: Language,+ bufferTexts: List<String>,+ limit: Int = 50,+): List<Completion> {+ if (prefix.isEmpty()) return emptyList()+ val results = ArrayList<Completion>()+ val used = HashSet<String>()++ // 1. Snippets whose trigger starts with the prefix.+ for (s in snippetsFor(language)) {+ if (s.trigger.startsWith(prefix) && used.add("s:${s.trigger}")) {+ val caret = s.template.indexOf(CARET_MARKER).let { if (it < 0) s.template.length else it }+ val body = s.template.replace(CARET_MARKER, "")+ results.add(Completion("${s.trigger}…", body, caret, CompletionKind.SNIPPET))+ }+ }++ // 2. Identifiers from the open buffers, ranked by frequency then length.+ val freq = HashMap<String, Int>()+ for (text in bufferTexts) {+ for (m in IDENTIFIER.findAll(text)) freq.merge(m.value, 1) { a, b -> a + b }+ }+ val words = freq.keys+ .filter { it.startsWith(prefix) && it != prefix }+ .sortedWith(compareByDescending<String> { freq[it] ?: 0 }.thenBy { it.length }.thenBy { it })+ for (w in words) if (used.add("w:$w")) results.add(Completion(w, w, w.length, CompletionKind.WORD))++ // 3. Language keywords.+ val keywords = keywordsFor(language).filter { it.startsWith(prefix) && it != prefix }.sorted()+ for (k in keywords) if (used.add("k:$k")) results.add(Completion(k, k, k.length, CompletionKind.KEYWORD))++ return results.take(limit)+}++// --- Per-language keyword and snippet tables (a focused subset; buffer words fill the rest) ---++private val C_LIKE_SNIPPETS = listOf(+ Snippet("if", "if ($CARET_MARKER) {\n}"),+ Snippet("for", "for ($CARET_MARKER) {\n}"),+ Snippet("while", "while ($CARET_MARKER) {\n}"),+)++private fun snippetsFor(language: Language): List<Snippet> = when (language) {+ Language.KOTLIN -> C_LIKE_SNIPPETS + listOf(+ Snippet("fun", "fun $CARET_MARKER() {\n}"),+ Snippet("val", "val $CARET_MARKER ="),+ Snippet("var", "var $CARET_MARKER ="),+ Snippet("when", "when ($CARET_MARKER) {\n}"),+ )++ Language.JAVA -> C_LIKE_SNIPPETS + listOf(+ Snippet("class", "class $CARET_MARKER {\n}"),+ )++ Language.JAVASCRIPT, Language.TYPESCRIPT -> C_LIKE_SNIPPETS + listOf(+ Snippet("function", "function $CARET_MARKER() {\n}"),+ Snippet("const", "const $CARET_MARKER ="),+ Snippet("let", "let $CARET_MARKER ="),+ )++ Language.PYTHON -> listOf(+ Snippet("def", "def $CARET_MARKER():\n pass"),+ Snippet("if", "if $CARET_MARKER:\n pass"),+ Snippet("for", "for $CARET_MARKER in :\n pass"),+ Snippet("while", "while $CARET_MARKER:\n pass"),+ Snippet("class", "class $CARET_MARKER:\n pass"),+ )++ Language.C, Language.CPP, Language.RUST, Language.GO, Language.SWIFT -> C_LIKE_SNIPPETS++ else -> emptyList()+}++private val KOTLIN_KEYWORDS = listOf(+ "abstract", "as", "break", "class", "companion", "const", "continue", "data", "do", "else",+ "enum", "false", "final", "for", "fun", "if", "import", "in", "infix", "init", "inline",+ "interface", "internal", "is", "lateinit", "null", "object", "open", "operator", "override",+ "package", "private", "protected", "public", "return", "sealed", "super", "suspend", "this",+ "throw", "true", "try", "typealias", "val", "var", "vararg", "when", "where", "while",+)++private val JS_KEYWORDS = listOf(+ "async", "await", "break", "case", "catch", "class", "const", "continue", "default", "delete",+ "do", "else", "export", "extends", "false", "finally", "for", "from", "function", "if",+ "import", "in", "instanceof", "interface", "let", "new", "null", "return", "super", "switch",+ "this", "throw", "true", "try", "type", "typeof", "undefined", "var", "void", "while", "yield",+)++private val PYTHON_KEYWORDS = listOf(+ "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",+ "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",+ "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",+ "with", "yield",+)++private val C_KEYWORDS = listOf(+ "auto", "bool", "break", "case", "char", "class", "const", "continue", "default", "do",+ "double", "else", "enum", "extern", "false", "float", "for", "if", "int", "long", "namespace",+ "new", "nullptr", "return", "short", "signed", "sizeof", "static", "struct", "switch",+ "template", "this", "true", "typedef", "unsigned", "using", "void", "volatile", "while",+)++private val RUST_KEYWORDS = listOf(+ "as", "async", "await", "break", "const", "continue", "crate", "else", "enum", "false", "fn",+ "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",+ "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while",+)++private val GO_KEYWORDS = listOf(+ "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough",+ "false", "for", "func", "go", "goto", "if", "import", "interface", "map", "nil", "package",+ "range", "return", "select", "struct", "switch", "true", "type", "var",+)++private fun keywordsFor(language: Language): List<String> = when (language) {+ Language.KOTLIN -> KOTLIN_KEYWORDS+ Language.JAVASCRIPT, Language.TYPESCRIPT -> JS_KEYWORDS+ Language.PYTHON -> PYTHON_KEYWORDS+ Language.JAVA, Language.C, Language.CPP -> C_KEYWORDS+ Language.RUST -> RUST_KEYWORDS+ Language.GO -> GO_KEYWORDS+ else -> emptyList()+}
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 6f32b9d7b5..67eb8f7587 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -150,6 +150,11 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), private set private var searchJob: Job? = null + // ---- Autocomplete ----+ val completions = mutableStateListOf<Completion>()+ var showCompletions by mutableStateOf(false)+ private set+ /** Snapshot of everything the screens draw; rebuilt on every read, as Compose expects. */ val uiState: CodeUiState get() = CodeUiState(@@ -181,6 +186,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), autoCloseBrackets = autoCloseBrackets, searchResults = searchResults.toList(), isSearching = isSearching,+ completions = completions.toList(),+ showCompletions = showCompletions, ) init {@@ -473,6 +480,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), override fun selectTab(index: Int) { if (index in tabs.indices) { currentIndex = index+ dismissCompletions() saveSession() } }@@ -499,6 +507,49 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), if (processed.text != tab.value.text) tab.pushUndo(tab.value) tab.value = processed if (autoSave) scheduleAutoSave()+ updateCompletions()+ }++ // ---- Autocomplete ----++ override fun requestCompletions() = updateCompletions()++ /** Recomputes the completion list from the caret's word prefix and the open buffers. */+ private fun updateCompletions() {+ val tab = currentTab+ if (tab == null || !tab.value.selection.collapsed) {+ dismissCompletions()+ return+ }+ val prefix = currentWordPrefix(tab.value.text, tab.value.selection.start)+ if (prefix.length < MIN_COMPLETION_PREFIX) {+ dismissCompletions()+ return+ }+ val buffers = tabs.map { it.value.text }+ val list = computeCompletions(prefix, tab.language, buffers, MAX_COMPLETIONS)+ completions.clear()+ completions.addAll(list)+ showCompletions = list.isNotEmpty()+ }++ override fun acceptCompletion(item: Completion) {+ val tab = currentTab ?: return+ val v = tab.value+ val caret = v.selection.start+ val prefix = currentWordPrefix(v.text, caret)+ val start = caret - prefix.length+ val newText = v.text.substring(0, start) + item.insertText + v.text.substring(caret)+ val newCaret = (start + item.caretOffset).coerceIn(0, newText.length)+ tab.pushUndo(v)+ tab.value = TextFieldValue(newText, TextRange(newCaret))+ dismissCompletions()+ if (autoSave) scheduleAutoSave()+ }++ override fun dismissCompletions() {+ if (completions.isNotEmpty()) completions.clear()+ showCompletions = false } /** Debounced auto-save: writes the current tab a short idle period after the last edit. */@@ -726,6 +777,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), private companion object { const val AUTO_SAVE_DELAY_MS = 1500L+ const val MIN_COMPLETION_PREFIX = 1+ const val MAX_COMPLETIONS = 50 const val MAX_SEARCH_RESULTS = 500 const val MAX_MATCHES_PER_FILE = 50 const val MAX_SEARCH_FILE_SIZE = 500_000
code/src/test/java/com/vayunmathur/code/util/CompletionTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/CompletionTest.kt b/code/src/test/java/com/vayunmathur/code/util/CompletionTest.ktnew file mode 100644index 0000000000..4f6bf114bd--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/CompletionTest.kt@@ -0,0 +1,65 @@+package com.vayunmathur.code.util++import com.vayunmathur.code.syntax.Language+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Unit tests for the pure completion core: prefix extraction, ranking and snippet expansion. */+class CompletionTest {++ @Test+ fun currentWordPrefixReadsIdentifierBeforeCaret() {+ assertEquals("foo", currentWordPrefix("val foo", 7))+ assertEquals("", currentWordPrefix("val foo ", 8))+ assertEquals("ba", currentWordPrefix("foo.ba", 6))+ }++ @Test+ fun currentWordPrefixHandlesBounds() {+ assertEquals("", currentWordPrefix("", 0))+ assertEquals("", currentWordPrefix("abc", 0))+ }++ @Test+ fun emptyPrefixYieldsNoCompletions() {+ assertEquals(emptyList(), computeCompletions("", Language.KOTLIN, listOf("value")))+ }++ @Test+ fun bufferWordsAreCompletedAndRankedByFrequency() {+ val buffers = listOf("counter counter total", "counter")+ val result = computeCompletions("co", Language.PLAINTEXT, buffers)+ val words = result.filter { it.kind == CompletionKind.WORD }.map { it.insertText }+ assertEquals("counter", words.first())+ }++ @Test+ fun exactPrefixWordIsExcluded() {+ val result = computeCompletions("counter", Language.PLAINTEXT, listOf("counter counters"))+ val words = result.filter { it.kind == CompletionKind.WORD }.map { it.insertText }+ assertEquals(listOf("counters"), words)+ }++ @Test+ fun keywordsAreOfferedForTheLanguage() {+ val result = computeCompletions("fu", Language.KOTLIN, emptyList())+ assertTrue(result.any { it.kind == CompletionKind.KEYWORD && it.insertText == "fun" })+ }++ @Test+ fun snippetExpandsWithCaretInside() {+ val result = computeCompletions("fun", Language.KOTLIN, emptyList())+ val snippet = result.first { it.kind == CompletionKind.SNIPPET }+ assertEquals("fun () {\n}", snippet.insertText)+ // Caret should land right after "fun " (inside the parentheses).+ assertEquals("fun ".length, snippet.caretOffset)+ }++ @Test+ fun resultsAreCapped() {+ val many = (1..100).joinToString(" ") { "var$it" }+ val result = computeCompletions("var", Language.PLAINTEXT, listOf(many), limit = 10)+ assertTrue(result.size <= 10)+ }+}