Modern Apps git

← Modern-Apps.git

code: add folding, multi-cursor, minimap, indent guides and editor shortcuts

Commit
283e72bf8470c9bd6155e846dbf349ac55b349ac
Author
vayun-mathur <[email protected]>
When
2026-08-07 00:15 UTC (4 months ago)
Parents
06b798e

Diff

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 87e7263783..b55c3a522f 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt@@ -1,12 +1,17 @@ package com.vayunmathur.code.ui  import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.gestures.rememberScrollableState import androidx.compose.foundation.gestures.scrollable-import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -19,8 +24,10 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.isCtrlPressed+import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type@@ -42,18 +49,23 @@ import com.vayunmathur.code.syntax.LanguageSpec import com.vayunmathur.code.syntax.SyntaxColors import com.vayunmathur.code.syntax.rememberSyntaxColors import com.vayunmathur.code.util.CodeActions+import com.vayunmathur.code.util.Edit+import com.vayunmathur.code.util.EditorDocument import com.vayunmathur.code.util.TabUiState+import com.vayunmathur.code.util.computeFoldRegions+import com.vayunmathur.code.util.dedentSelection+import com.vayunmathur.code.util.indentSelection import com.vayunmathur.library.ui.MaterialTheme  /**- * The experimental virtualized editor engine (Phase 7). A [Canvas] draws only the lines inside the- * viewport, so syntax highlighting is computed per-visible-line instead of over the whole document.- * It reuses the existing edit pipeline: input is routed through [CodeActions.onEditorChange] /- * [CodeActions.setSelection], so undo/redo, auto-save and smart input all keep working.+ * The experimental virtualized editor engine (Phases 7–8). A [Canvas] draws only the lines inside+ * the viewport (with folded ranges skipped entirely), so syntax highlighting is per-visible-line.+ * It reuses the existing edit pipeline — input routes through [CodeActions.onEditorChange] /+ * [CodeActions.setSelection] — so undo/redo, auto-save and smart input keep working.  *- * v1 scope (documented follow-ups): hardware-keyboard input and tap-to-place-caret are supported;- * soft-keyboard IME and soft-wrap are not yet wired. Gated behind the `experimentalEditor` pref, so- * the stable [CodeEditor] stays the default until this reaches parity.+ * Phase-8 additions: real line-hiding folds with gutter arrows, multi-cursor (Ctrl-D / Alt-tap),+ * indent guides, whitespace rendering, a minimap, and editor keyboard shortcuts. v1 limitations+ * (documented follow-ups): soft-keyboard IME and soft-wrap are not yet wired.  */ @Composable fun CodeEditorView(@@ -62,6 +74,10 @@ fun CodeEditorView(     fontSize: Int,     editorTheme: String,     modifier: Modifier = Modifier,+    tabWidth: Int = 4,+    showWhitespace: Boolean = false,+    showIndentGuides: Boolean = false,+    showMinimap: Boolean = false,     onValueChangeOverride: ((TextFieldValue) -> Unit)? = null, ) {     val value = tab.value@@ -70,6 +86,8 @@ fun CodeEditorView(     val onSurface = MaterialTheme.colorScheme.onSurface     val gutterColor = MaterialTheme.colorScheme.onSurfaceVariant     val caretColor = MaterialTheme.colorScheme.primary+    val guideColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f)+    val extraCaretColor = MaterialTheme.colorScheme.tertiary     val spec = tab.language.spec      val measurer = rememberTextMeasurer()@@ -92,14 +110,29 @@ fun CodeEditorView(         }     }     val longestLine = remember(text) { lines.maxOfOrNull { it.length } ?: 0 }-    val gutterWidth = with(density) { ((lines.size.toString().length * 10) + 16).dp.toPx() }+    val gutterWidth = with(density) { ((lines.size.toString().length * 10) + 28).dp.toPx() }++    // Folding state, reset per file.+    var foldedHeaders by remember(tab.name) { mutableStateOf(setOf<Int>()) }+    var extraCarets by remember(tab.name) { mutableStateOf(listOf<Int>()) }++    val foldByHeader = remember(text) { computeFoldRegions(text).associateBy { it.startLine } }+    val hiddenLines = remember(text, foldedHeaders) {+        val hidden = HashSet<Int>()+        for (header in foldedHeaders) {+            val region = foldByHeader[header] ?: continue+            for (l in (region.startLine + 1)..region.endLine) hidden.add(l)+        }+        hidden+    }+    val visibleLines = remember(text, hiddenLines) { lines.indices.filter { it !in hiddenLines } }      var scrollY by remember { mutableStateOf(0f) }     var scrollX by remember { mutableStateOf(0f) }     var viewport by remember { mutableStateOf(IntSize.Zero) }     val focusRequester = remember { FocusRequester() } -    val totalHeight = lineHeight * lines.size+    val totalHeight = lineHeight * visibleLines.size     val totalWidth = gutterWidth + longestLine * charWidth + charWidth     val maxScrollY = (totalHeight - viewport.height).coerceAtLeast(0f)     val maxScrollX = (totalWidth - viewport.width).coerceAtLeast(0f)@@ -119,80 +152,210 @@ fun CodeEditorView(         consumed     } +    val emit: (TextFieldValue) -> Unit = onValueChangeOverride ?: actions::onEditorChange++    fun displayRowToSource(row: Int): Int? = visibleLines.getOrNull(row)+     fun offsetAt(x: Float, y: Float): Int {-        val line = ((y + scrollY) / lineHeight).toInt().coerceIn(0, lines.size - 1)-        val col = (((x + scrollX) - gutterWidth) / charWidth).toInt().coerceIn(0, lines[line].length)-        return (lineStarts[line] + col).coerceIn(0, text.length)+        val row = ((y + scrollY) / lineHeight).toInt()+        val source = displayRowToSource(row.coerceIn(0, (visibleLines.size - 1).coerceAtLeast(0))) ?: 0+        val col = (((x + scrollX) - gutterWidth) / charWidth).toInt().coerceIn(0, lines[source].length)+        return (lineStarts[source] + col).coerceIn(0, text.length)     } -    val emit: (TextFieldValue) -> Unit = onValueChangeOverride ?: actions::onEditorChange+    fun toggleFoldAt(source: Int) {+        if (!foldByHeader.containsKey(source)) return+        foldedHeaders = if (source in foldedHeaders) foldedHeaders - source else foldedHeaders + source+    } -    Canvas(-        modifier-            .fillMaxSize()-            .onSizeChanged { viewport = it }-            .scrollable(vScroll, Orientation.Vertical)-            .scrollable(hScroll, Orientation.Horizontal)-            .pointerInput(text) {-                detectTapGestures { pos ->-                    val offset = offsetAt(pos.x, pos.y)-                    actions.setSelection(TextRange(offset))-                    focusRequester.requestFocus()+    val editorCanvas: @Composable (Modifier) -> Unit = { canvasModifier ->+        Canvas(+            canvasModifier+                .onSizeChanged { viewport = it }+                .scrollable(vScroll, Orientation.Vertical)+                .scrollable(hScroll, Orientation.Horizontal)+                .pointerInput(text, visibleLines) {+                    detectTapGestures { pos ->+                        val row = ((pos.y + scrollY) / lineHeight).toInt()+                        val source = displayRowToSource(row)+                        if (pos.x < gutterWidth && source != null && foldByHeader.containsKey(source)) {+                            toggleFoldAt(source)+                        } else {+                            actions.setSelection(TextRange(offsetAt(pos.x, pos.y)))+                            extraCarets = emptyList()+                            focusRequester.requestFocus()+                        }+                    }                 }-            }-            .focusRequester(focusRequester)-            .focusable()-            .onPreviewKeyEvent { event ->-                if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false-                handleKey(event, value, emit) { range -> actions.setSelection(range) }-            },-    ) {-        viewport = IntSize(size.width.toInt(), size.height.toInt())-        val caret = if (value.selection.collapsed) value.selection.start else -1-        val selMin = value.selection.min-        val selMax = value.selection.max--        val first = (scrollY / lineHeight).toInt().coerceIn(0, (lines.size - 1).coerceAtLeast(0))-        val visible = (size.height / lineHeight).toInt() + 2-        val last = (first + visible).coerceAtMost(lines.size - 1)--        for (i in first..last) {-            val y = i * lineHeight - scrollY-            val lineStart = lineStarts[i]-            val lineLen = lines[i].length--            // Current-line background.-            if (caret in lineStart..(lineStart + lineLen)) {-                drawRect(colors.currentLine, topLeft = Offset(0f, y), size = Size(size.width, lineHeight))-            }+                .focusRequester(focusRequester)+                .focusable()+                .onPreviewKeyEvent { event ->+                    handleEditorKey(+                        event = event,+                        value = value,+                        tabWidth = tabWidth,+                        extraCarets = extraCarets,+                        setExtraCarets = { extraCarets = it },+                        emit = emit,+                        move = { actions.setSelection(it) },+                        onSave = { actions.save() },+                        onComment = { actions.toggleComment() },+                        foldAll = { foldedHeaders = foldByHeader.keys.toSet() },+                        unfoldAll = { foldedHeaders = emptySet() },+                        toggleFoldAtCaret = { caret ->+                            val line = lineOfOffset(lineStarts, caret)+                            val header = foldByHeader.keys.filter { h ->+                                val r = foldByHeader[h]!!+                                line in r.startLine..r.endLine+                            }.maxOrNull()+                            if (header != null) toggleFoldAt(header)+                        },+                    )+                },+        ) {+            val caret = if (value.selection.collapsed) value.selection.start else -1+            val selMin = value.selection.min+            val selMax = value.selection.max++            val firstRow = (scrollY / lineHeight).toInt().coerceAtLeast(0)+            val rowsInView = (size.height / lineHeight).toInt() + 2+            val lastRow = (firstRow + rowsInView).coerceAtMost(visibleLines.size - 1)++            for (row in firstRow..lastRow) {+                val source = visibleLines[row]+                val y = row * lineHeight - scrollY+                val lineStart = lineStarts[source]+                val lineText = lines[source]+                val lineLen = lineText.length -            // Selection background on this line.-            if (selMax > selMin) {-                val a = (selMin - lineStart).coerceIn(0, lineLen)-                val b = (selMax - lineStart).coerceIn(0, lineLen)-                if (b > a || (selMin <= lineStart + lineLen && selMax > lineStart + lineLen)) {-                    val endCol = if (selMax > lineStart + lineLen) lineLen else b-                    val startX = gutterWidth + a * charWidth - scrollX-                    val width = ((endCol - a).coerceAtLeast(0)) * charWidth + if (selMax > lineStart + lineLen) charWidth else 0f-                    if (width > 0f) drawRect(colors.match, topLeft = Offset(startX, y), size = Size(width, lineHeight))+                if (caret in lineStart..(lineStart + lineLen)) {+                    drawRect(colors.currentLine, topLeft = Offset(0f, y), size = Size(size.width, lineHeight))+                }++                if (selMax > selMin) {+                    val a = (selMin - lineStart).coerceIn(0, lineLen)+                    val spansEol = selMax > lineStart + lineLen+                    val b = if (spansEol) lineLen else (selMax - lineStart).coerceIn(0, lineLen)+                    if (b > a || (selMin <= lineStart + lineLen && spansEol)) {+                        val startX = gutterWidth + a * charWidth - scrollX+                        val w = (b - a).coerceAtLeast(0) * charWidth + if (spansEol) charWidth else 0f+                        if (w > 0f) drawRect(colors.match, topLeft = Offset(startX, y), size = Size(w, lineHeight))+                    }+                }++                if (showIndentGuides) {+                    val columns = leadingColumns(lineText, tabWidth)+                    var level = tabWidth+                    while (level < columns) {+                        val gx = gutterWidth + level * charWidth - scrollX+                        drawRect(guideColor, topLeft = Offset(gx, y), size = Size(1f, lineHeight))+                        level += tabWidth+                    }                 }-            } -            // Gutter line number.-            val number = measurer.measure(AnnotatedString((i + 1).toString()), style)-            drawText(number, color = gutterColor, topLeft = Offset(gutterWidth - number.size.width - 6f, y))+                if (showWhitespace) {+                    var i = 0+                    var col = 0+                    while (i < lineText.length && (lineText[i] == ' ' || lineText[i] == '\t')) {+                        val cx = gutterWidth + col * charWidth - scrollX+                        if (lineText[i] == ' ') {+                            drawCircle(guideColor, radius = 1.5f, center = Offset(cx + charWidth / 2f, y + lineHeight / 2f))+                            col+++                        } else {+                            col += tabWidth+                        }+                        i+++                    }+                }++                // Gutter: line number and fold arrow.+                val number = measurer.measure(AnnotatedString((source + 1).toString()), style)+                drawText(number, color = gutterColor, topLeft = Offset(gutterWidth - number.size.width - 6f, y))+                if (foldByHeader.containsKey(source)) {+                    val arrow = if (source in foldedHeaders) "\u25B8" else "\u25BE"+                    val arrowLayout = measurer.measure(AnnotatedString(arrow), style)+                    drawText(arrowLayout, color = gutterColor, topLeft = Offset(2f, y))+                } -            // Line text with per-line syntax colors.-            val annotated = annotatedLine(lines[i], spec, colors)-            val layout = measurer.measure(annotated, style)-            drawText(layout, topLeft = Offset(gutterWidth - scrollX, y))+                val annotated = annotatedLine(lineText, spec, colors)+                val layout = measurer.measure(annotated, style)+                drawText(layout, topLeft = Offset(gutterWidth - scrollX, y)) -            // Caret.-            if (caret in lineStart..(lineStart + lineLen)) {-                val col = caret - lineStart-                val caretX = gutterWidth + col * charWidth - scrollX-                drawRect(caretColor, topLeft = Offset(caretX, y), size = Size(2f, lineHeight))+                if (caret in lineStart..(lineStart + lineLen)) {+                    val cx = gutterWidth + (caret - lineStart) * charWidth - scrollX+                    drawRect(caretColor, topLeft = Offset(cx, y), size = Size(2f, lineHeight))+                }+                for (extra in extraCarets) {+                    if (extra in lineStart..(lineStart + lineLen)) {+                        val cx = gutterWidth + (extra - lineStart) * charWidth - scrollX+                        drawRect(extraCaretColor, topLeft = Offset(cx, y), size = Size(2f, lineHeight))+                    }+                }+            }+        }+    }++    if (showMinimap) {+        Row(modifier.fillMaxSize()) {+            editorCanvas(Modifier.weight(1f).fillMaxHeight())+            Minimap(+                lines = lines,+                lineHeight = lineHeight,+                scrollY = scrollY,+                maxScrollY = maxScrollY,+                viewportHeight = viewport.height.toFloat(),+                totalHeight = totalHeight,+                color = gutterColor.copy(alpha = 0.5f),+                viewportColor = caretColor.copy(alpha = 0.2f),+                onScrollTo = { fraction -> scrollY = (fraction * maxScrollY).coerceIn(0f, maxScrollY) },+                modifier = Modifier.width(56.dp).fillMaxHeight(),+            )+        }+    } else {+        editorCanvas(modifier.fillMaxSize())+    }+}++/** A narrow overview: one dim bar per source line (width ∝ length) plus a draggable viewport rect. */+@Composable+private fun Minimap(+    lines: List<String>,+    lineHeight: Float,+    scrollY: Float,+    maxScrollY: Float,+    viewportHeight: Float,+    totalHeight: Float,+    color: Color,+    viewportColor: Color,+    onScrollTo: (Float) -> Unit,+    modifier: Modifier = Modifier,+) {+    Canvas(+        modifier+            .background(color.copy(alpha = 0.05f))+            .pointerInput(Unit) {+                detectVerticalDragGestures { change, _ ->+                    onScrollTo((change.position.y / size.height).coerceIn(0f, 1f))+                }             }+            .pointerInput(Unit) {+                detectTapGestures { pos -> onScrollTo((pos.y / size.height).coerceIn(0f, 1f)) }+            },+    ) {+        if (lines.isEmpty()) return@Canvas+        val rowH = (size.height / lines.size).coerceAtMost(3f)+        val maxLen = (lines.maxOfOrNull { it.length } ?: 1).coerceAtLeast(1)+        for (i in lines.indices) {+            val len = lines[i].length+            if (len == 0) continue+            val w = (len.toFloat() / maxLen) * (size.width - 4f)+            drawRect(color, topLeft = Offset(2f, i * rowH), size = Size(w, (rowH - 0.5f).coerceAtLeast(0.5f)))+        }+        // Viewport rectangle.+        if (totalHeight > 0f && viewportHeight > 0f) {+            val top = (scrollY / totalHeight) * size.height+            val h = (viewportHeight / totalHeight) * size.height+            drawRect(viewportColor, topLeft = Offset(0f, top), size = Size(size.width, h))         }     } }@@ -224,56 +387,165 @@ private fun annotatedLine(line: String, spec: LanguageSpec?, colors: SyntaxColor     return builder.toAnnotatedString() } +/** Leading indentation width in columns, expanding each tab to [tabWidth]. */+private fun leadingColumns(line: String, tabWidth: Int): Int {+    var col = 0+    for (c in line) {+        when (c) {+            ' ' -> col+++            '\t' -> col += tabWidth+            else -> return col+        }+    }+    return col+}++/** The 0-based line containing [offset], by binary search over [lineStarts]. */+private fun lineOfOffset(lineStarts: IntArray, offset: Int): Int {+    var lo = 0+    var hi = lineStarts.size - 1+    while (lo < hi) {+        val mid = (lo + hi + 1) ushr 1+        if (lineStarts[mid] <= offset) lo = mid else hi = mid - 1+    }+    return lo+}+ /**- * Handles a hardware key press, producing the resulting [TextFieldValue] (via [emit]) or a caret- * move (via [move]). Text inserts/deletes go through [emit] so the ViewModel's smart input,- * undo/redo and auto-save all apply. Returns true when the event was consumed.+ * Handles an editor key press. Text edits go through [emit] (so smart input, undo/redo and+ * auto-save apply); multi-caret inserts/deletes are computed with an [EditorDocument]. Returns true+ * when the event was consumed.  */-private fun handleKey(-    event: androidx.compose.ui.input.key.KeyEvent,+private fun handleEditorKey(+    event: KeyEvent,     value: TextFieldValue,+    tabWidth: Int,+    extraCarets: List<Int>,+    setExtraCarets: (List<Int>) -> Unit,     emit: (TextFieldValue) -> Unit,     move: (TextRange) -> Unit,+    onSave: () -> Unit,+    onComment: () -> Unit,+    foldAll: () -> Unit,+    unfoldAll: () -> Unit,+    toggleFoldAtCaret: (Int) -> Unit, ): Boolean {+    if (event.type != KeyEventType.KeyDown) return false     val text = value.text     val start = value.selection.min     val end = value.selection.max++    if (event.isCtrlPressed) {+        when (event.key) {+            Key.S -> { onSave(); return true }+            Key.Slash -> { onComment(); return true }+            Key.D -> {+                val range = selectionOrWord(text, value.selection)+                if (range != null) {+                    val word = text.substring(range.first, range.second)+                    val from = (extraCarets + end).max()+                    val idx = text.indexOf(word, from)+                    if (idx >= 0) setExtraCarets(extraCarets + (idx + word.length))+                }+                return true+            }+            Key.LeftBracket -> {+                if (event.isShiftPressed) foldAll() else toggleFoldAtCaret(start)+                return true+            }+            Key.RightBracket -> {+                if (event.isShiftPressed) unfoldAll() else toggleFoldAtCaret(start)+                return true+            }+        }+        return false+    }+     when (event.key) {-        Key.Backspace -> {-            if (start != end) {-                emit(TextFieldValue(text.substring(0, start) + text.substring(end), TextRange(start)))-            } else if (start > 0) {-                emit(TextFieldValue(text.substring(0, start - 1) + text.substring(start), TextRange(start - 1)))+        Key.Escape -> {+            if (extraCarets.isNotEmpty()) {+                setExtraCarets(emptyList())+                return true             }+            return false+        }+        Key.Tab -> {+            emit(if (event.isShiftPressed) dedentSelection(value, tabWidth) else indentSelection(value, " ".repeat(tabWidth)))             return true         }-        Key.Delete -> {-            if (start != end) {+        Key.DirectionLeft -> { move(TextRange((start - 1).coerceAtLeast(0))); return true }+        Key.DirectionRight -> { move(TextRange((end + 1).coerceAtMost(text.length))); return true }+        Key.Backspace -> {+            if (extraCarets.isNotEmpty()) {+                applyMultiCaret(text, start, extraCarets, insert = null, emit, setExtraCarets)+            } else if (start != end) {                 emit(TextFieldValue(text.substring(0, start) + text.substring(end), TextRange(start)))-            } else if (start < text.length) {-                emit(TextFieldValue(text.substring(0, start) + text.substring(start + 1), TextRange(start)))+            } else if (start > 0) {+                emit(TextFieldValue(text.substring(0, start - 1) + text.substring(start), TextRange(start - 1)))             }             return true         }-        Key.DirectionLeft -> {-            move(TextRange((start - 1).coerceAtLeast(0))); return true-        }-        Key.DirectionRight -> {-            move(TextRange((end + 1).coerceAtMost(text.length))); return true-        }         Key.Enter, Key.NumPadEnter -> {             emit(TextFieldValue(text.substring(0, start) + "\n" + text.substring(end), TextRange(start + 1)))             return true         }     }-    if (event.isCtrlPressed) return false+     val codePoint = event.nativeKeyEvent.unicodeChar     if (codePoint != 0) {-        val ch = codePoint.toChar()-        emit(TextFieldValue(text.substring(0, start) + ch + text.substring(end), TextRange(start + 1)))+        val ch = codePoint.toChar().toString()+        if (extraCarets.isNotEmpty()) {+            applyMultiCaret(text, start, extraCarets, insert = ch, emit, setExtraCarets)+        } else {+            emit(TextFieldValue(text.substring(0, start) + ch + text.substring(end), TextRange(start + 1)))+        }         return true     }     return false } +/**+ * Applies a single-character [insert] (or a backspace when null) at the primary caret plus every+ * extra caret, using an [EditorDocument] for the edit, then re-emits the primary value and the+ * shifted extra carets.+ */+private fun applyMultiCaret(+    text: String,+    primary: Int,+    extras: List<Int>,+    insert: String?,+    emit: (TextFieldValue) -> Unit,+    setExtraCarets: (List<Int>) -> Unit,+) {+    val carets = (extras + primary).distinct().sorted()+    val doc = EditorDocument(text)+    val edits = if (insert != null) {+        carets.map { Edit(it, it, insert) }+    } else {+        carets.filter { it > 0 }.map { Edit(it - 1, it, "") }+    }+    if (edits.isEmpty()) return+    doc.applyEdits(edits)+    val delta = if (insert != null) insert.length else -1+    val newCarets = carets.mapIndexed { index, c ->+        if (insert != null) c + delta * (index + 1) else (c + delta * (index + 1)).coerceAtLeast(0)+    }+    val primaryIndex = carets.indexOf(primary)+    val newPrimary = newCarets.getOrElse(primaryIndex) { newCarets.lastOrNull() ?: 0 }+    emit(TextFieldValue(doc.text, TextRange(newPrimary.coerceIn(0, doc.length))))+    setExtraCarets(newCarets.filterIndexed { i, _ -> i != primaryIndex }.map { it.coerceIn(0, doc.length) })+}++/** The selection range (end-exclusive) if non-empty, else the identifier word around the caret. */+private fun selectionOrWord(text: String, selection: TextRange): Pair<Int, Int>? {+    if (!selection.collapsed) return selection.min to selection.max+    var start = selection.start+    var end = selection.start+    while (start > 0 && text[start - 1].isJavaIdentifierChar()) start--+    while (end < text.length && text[end].isJavaIdentifierChar()) end+++    return if (end > start) start to end else null+}++private fun Char.isJavaIdentifierChar(): Boolean = isLetterOrDigit() || this == '_'+ private const val MAX_LINE_HIGHLIGHT = 2000
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 12ce03e196..a1fc35eecb 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -269,6 +269,10 @@ fun EditorScreen(                                 fontSize = state.fontSize,                                 editorTheme = state.editorTheme,                                 modifier = Modifier.weight(1f),+                                tabWidth = state.tabWidth,+                                showWhitespace = state.showWhitespace,+                                showIndentGuides = state.showIndentGuides,+                                showMinimap = state.showMinimap,                             )                         } else {                             CodeEditor(
code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.ktindex 2ad7040d20..4162a3912d 100644--- a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt@@ -125,6 +125,27 @@ fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) {                     checked = viewModel.experimentalEditor,                     onCheckedChange = viewModel::setExperimentalEditor,                 )+                SettingsDivider()+                SettingsSwitchRow(+                    title = stringResource(R.string.show_whitespace),+                    supportingText = stringResource(R.string.show_whitespace_desc),+                    checked = viewModel.showWhitespace,+                    onCheckedChange = viewModel::setShowWhitespace,+                )+                SettingsDivider()+                SettingsSwitchRow(+                    title = stringResource(R.string.show_indent_guides),+                    supportingText = stringResource(R.string.show_indent_guides_desc),+                    checked = viewModel.showIndentGuides,+                    onCheckedChange = viewModel::setShowIndentGuides,+                )+                SettingsDivider()+                SettingsSwitchRow(+                    title = stringResource(R.string.show_minimap),+                    supportingText = stringResource(R.string.show_minimap_desc),+                    checked = viewModel.showMinimap,+                    onCheckedChange = viewModel::setShowMinimap,+                )             }              SettingsSection(title = stringResource(R.string.user_snippets)) {
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 98db17c99f..92ed4e76e2 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -80,6 +80,10 @@ data class CodeUiState(     val editorTheme: String = EditorThemes.DEFAULT,     /** When true, the editing surface uses the experimental virtualized [CodeEditorView]. */     val experimentalEditor: Boolean = false,+    /** Renderer toggles for the experimental editor. */+    val showWhitespace: Boolean = false,+    val showIndentGuides: Boolean = false,+    val showMinimap: Boolean = false,     /** All files under the open project, for quick-open (built lazily, cached in the ViewModel). */     val projectFiles: List<ProjectFileEntry> = emptyList(),     /** Most-recently-opened files, newest first, shown in quick-open when the query is empty. */
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 d1ef79b845..58008861f6 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt@@ -186,6 +186,46 @@ fun toggleLineComment(value: TextFieldValue, prefix: String): TextFieldValue {     return TextFieldValue(newText, TextRange(start, start + newBlock.length)) } +/**+ * Indents every line the selection touches by [indentUnit]; the returned selection spans the block.+ */+fun indentSelection(value: TextFieldValue, indentUnit: String): TextFieldValue {+    val text = value.text+    val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+    val newBlock = text.substring(start, end).split('\n').joinToString("\n") { indentUnit + it }+    val newText = text.substring(0, start) + newBlock + text.substring(end)+    return TextFieldValue(newText, TextRange(start, start + newBlock.length))+}++/**+ * Removes up to [tabWidth] leading spaces (or one leading tab) from every line the selection+ * touches; the returned selection spans the block.+ */+fun dedentSelection(value: TextFieldValue, tabWidth: Int): TextFieldValue {+    val text = value.text+    val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+    val newBlock = text.substring(start, end).split('\n').joinToString("\n") { line ->+        var removed = 0+        var i = 0+        while (i < line.length && removed < tabWidth) {+            when (line[i]) {+                ' ' -> {+                    removed+++                    i+++                }+                '\t' -> {+                    removed = tabWidth+                    i+++                }+                else -> break+            }+        }+        line.substring(i)+    }+    val newText = text.substring(0, start) + newBlock + text.substring(end)+    return TextFieldValue(newText, TextRange(start, start + newBlock.length))+}+ /** Char offset of the start of a 1-based [line] in [text], clamped to `0..text.length`. */ fun lineStartOffset(text: String, line: Int): Int {     val target = line.coerceAtLeast(1)
code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.ktindex a101216803..2a4e2cbf22 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -36,6 +36,12 @@ class EditorPrefs(context: Context) {     val autoSave: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_SAVE_KEY] ?: false }     val experimentalEditor: Flow<Boolean> =         appContext.editorDataStore.data.map { it[EXPERIMENTAL_EDITOR_KEY] ?: false }+    val showWhitespace: Flow<Boolean> =+        appContext.editorDataStore.data.map { it[SHOW_WHITESPACE_KEY] ?: false }+    val showIndentGuides: Flow<Boolean> =+        appContext.editorDataStore.data.map { it[SHOW_INDENT_GUIDES_KEY] ?: false }+    val showMinimap: Flow<Boolean> =+        appContext.editorDataStore.data.map { it[SHOW_MINIMAP_KEY] ?: false }     val editorTheme: Flow<String> =         appContext.editorDataStore.data.map { it[EDITOR_THEME_KEY] ?: EditorThemes.DEFAULT } @@ -102,6 +108,18 @@ class EditorPrefs(context: Context) {         appContext.editorDataStore.edit { it[EXPERIMENTAL_EDITOR_KEY] = enabled }     } +    suspend fun setShowWhitespace(enabled: Boolean) {+        appContext.editorDataStore.edit { it[SHOW_WHITESPACE_KEY] = enabled }+    }++    suspend fun setShowIndentGuides(enabled: Boolean) {+        appContext.editorDataStore.edit { it[SHOW_INDENT_GUIDES_KEY] = enabled }+    }++    suspend fun setShowMinimap(enabled: Boolean) {+        appContext.editorDataStore.edit { it[SHOW_MINIMAP_KEY] = enabled }+    }+     suspend fun setEditorTheme(theme: String) {         appContext.editorDataStore.edit { it[EDITOR_THEME_KEY] = theme }     }@@ -190,6 +208,9 @@ class EditorPrefs(context: Context) {         private val AUTO_CLOSE_KEY = booleanPreferencesKey("auto_close_brackets")         private val AUTO_SAVE_KEY = booleanPreferencesKey("auto_save")         private val EXPERIMENTAL_EDITOR_KEY = booleanPreferencesKey("experimental_editor")+        private val SHOW_WHITESPACE_KEY = booleanPreferencesKey("show_whitespace")+        private val SHOW_INDENT_GUIDES_KEY = booleanPreferencesKey("show_indent_guides")+        private val SHOW_MINIMAP_KEY = booleanPreferencesKey("show_minimap")         private val EDITOR_THEME_KEY = stringPreferencesKey("editor_theme")         private val SESSION_PATHS_KEY = stringPreferencesKey("session_paths")         private val SESSION_CURRENT_KEY = stringPreferencesKey("session_current")
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 1325aea7aa..5b8115f751 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -164,6 +164,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     val editorTheme: String get() = _editorTheme.value     private val _experimentalEditor = mutableStateOf(false)     val experimentalEditor: Boolean get() = _experimentalEditor.value+    private val _showWhitespace = mutableStateOf(false)+    val showWhitespace: Boolean get() = _showWhitespace.value+    private val _showIndentGuides = mutableStateOf(false)+    val showIndentGuides: Boolean get() = _showIndentGuides.value+    private val _showMinimap = mutableStateOf(false)+    val showMinimap: Boolean get() = _showMinimap.value     private var autoSaveJob: Job? = null      // ---- Project search ----@@ -255,6 +261,9 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             showCompletions = showCompletions,             editorTheme = editorTheme,             experimentalEditor = experimentalEditor,+            showWhitespace = showWhitespace,+            showIndentGuides = showIndentGuides,+            showMinimap = showMinimap,             projectFiles = projectFiles.toList(),             recentFiles = recentPaths.map { toProjectEntry(File(it)) },         )@@ -269,6 +278,9 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         viewModelScope.launch { _autoSave.value = prefs.autoSave.first() }         viewModelScope.launch { _editorTheme.value = prefs.editorTheme.first() }         viewModelScope.launch { _experimentalEditor.value = prefs.experimentalEditor.first() }+        viewModelScope.launch { _showWhitespace.value = prefs.showWhitespace.first() }+        viewModelScope.launch { _showIndentGuides.value = prefs.showIndentGuides.first() }+        viewModelScope.launch { _showMinimap.value = prefs.showMinimap.first() }         viewModelScope.launch { _gitUsername.value = prefs.gitUsername.first() }         viewModelScope.launch { _gitToken.value = prefs.gitToken.first() }         viewModelScope.launch { _gitAuthorName.value = prefs.gitAuthorName.first() }@@ -1088,6 +1100,21 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         viewModelScope.launch { prefs.setExperimentalEditor(enabled) }     } +    fun setShowWhitespace(enabled: Boolean) {+        _showWhitespace.value = enabled+        viewModelScope.launch { prefs.setShowWhitespace(enabled) }+    }++    fun setShowIndentGuides(enabled: Boolean) {+        _showIndentGuides.value = enabled+        viewModelScope.launch { prefs.setShowIndentGuides(enabled) }+    }++    fun setShowMinimap(enabled: Boolean) {+        _showMinimap.value = enabled+        viewModelScope.launch { prefs.setShowMinimap(enabled) }+    }+     // ---- Find & replace ----      override fun replaceRange(range: IntRange, replacement: String) {
code/src/main/java/com/vayunmathur/code/util/FoldRegions.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/FoldRegions.kt b/code/src/main/java/com/vayunmathur/code/util/FoldRegions.ktnew file mode 100644index 0000000000..9abea7aa1d--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/FoldRegions.kt@@ -0,0 +1,43 @@+package com.vayunmathur.code.util++/** A foldable region: the header is [startLine]; folding hides `startLine+1..endLine` (0-based). */+data class FoldRegion(val startLine: Int, val endLine: Int)++/**+ * Pure, indentation-based fold computation for the editor's code folding. A line is a fold header+ * when the following non-blank lines are more deeply indented; the region runs to the last such+ * line. Nested blocks produce nested regions. Blank lines never start or end a region. No Android+ * dependencies, so it is unit-tested directly.+ */+fun computeFoldRegions(text: String): List<FoldRegion> {+    val lines = text.split("\n")+    val regions = ArrayList<FoldRegion>()+    val stack = ArrayDeque<IntArray>() // each entry: [headerLine, indent]+    var lastNonBlank = -1++    for (i in lines.indices) {+        val line = lines[i]+        if (line.isBlank()) continue+        val indent = indentOf(line)+        while (stack.isNotEmpty() && indent <= stack.last()[1]) {+            val header = stack.removeLast()+            if (lastNonBlank > header[0]) regions.add(FoldRegion(header[0], lastNonBlank))+        }+        stack.addLast(intArrayOf(i, indent))+        lastNonBlank = i+    }+    while (stack.isNotEmpty()) {+        val header = stack.removeLast()+        if (lastNonBlank > header[0]) regions.add(FoldRegion(header[0], lastNonBlank))+    }+    return regions.sortedBy { it.startLine }+}++/** Leading-whitespace width, counting each space or tab as one unit (enough to compare depth). */+private fun indentOf(line: String): Int {+    var n = 0+    for (c in line) {+        if (c == ' ' || c == '\t') n++ else break+    }+    return n+}
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlindex cc907b259c..ae9b02d3eb 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -125,4 +125,12 @@     <string name="split_view">Split view</string>     <string name="experimental_editor">Experimental editor</string>     <string name="experimental_editor_desc">Use the new virtualized editor engine (hardware keyboard; work in progress)</string>+    <string name="show_whitespace">Show whitespace</string>+    <string name="show_whitespace_desc">Mark leading spaces and tabs in the experimental editor</string>+    <string name="show_indent_guides">Indent guides</string>+    <string name="show_indent_guides_desc">Draw vertical guides at each indent level</string>+    <string name="show_minimap">Minimap</string>+    <string name="show_minimap_desc">Show a code overview beside the experimental editor</string>+    <string name="fold_all">Fold all</string>+    <string name="unfold_all">Unfold all</string> </resources>
code/src/test/java/com/vayunmathur/code/util/FoldRegionsTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/FoldRegionsTest.kt b/code/src/test/java/com/vayunmathur/code/util/FoldRegionsTest.ktnew file mode 100644index 0000000000..b0ca8763f3--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/FoldRegionsTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.code.util++import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Unit tests for the pure fold-region computation and indent/dedent helpers. */+class FoldRegionsTest {++    @Test+    fun nestedIndentationProducesNestedRegions() {+        val src = "class A {\n    fun b() {\n        x()\n    }\n}"+        val regions = computeFoldRegions(src)+        assertTrue(FoldRegion(0, 3) in regions) // class body: lines 1..3+        assertTrue(FoldRegion(1, 2) in regions) // function body: line 2+    }++    @Test+    fun flatTextHasNoRegions() {+        assertTrue(computeFoldRegions("a\nb\nc").isEmpty())+    }++    @Test+    fun blankLinesDoNotBreakRegions() {+        val src = "def f():\n    a\n\n    b"+        val regions = computeFoldRegions(src)+        assertTrue(FoldRegion(0, 3) in regions)+    }++    @Test+    fun indentSelectionAddsIndentToEachLine() {+        val value = TextFieldValue("a\nb", TextRange(0, 3))+        val result = indentSelection(value, "  ")+        assertEquals("  a\n  b", result.text)+    }++    @Test+    fun dedentSelectionRemovesUpToTabWidthSpaces() {+        val value = TextFieldValue("    a\n  b", TextRange(0, 8))+        val result = dedentSelection(value, 4)+        assertEquals("a\nb", result.text)+    }++    @Test+    fun dedentSelectionRemovesOneLeadingTab() {+        val value = TextFieldValue("\tabc", TextRange(0, 4))+        val result = dedentSelection(value, 4)+        assertEquals("abc", result.text)+    }+}