code: add comment toggle, line ops, bracket/line highlight, session restore, auto-save
- Commit
79f6ead047f924355567b1d46deb62b2313ad216- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 22:19 UTC (4 months ago)
- Parents
186c410
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 547420a10c..42f7a930cf 100644--- a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt+++ b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt@@ -40,29 +40,29 @@ class LanguageSpec(private val parts: List<Pair<TokenKind, String>>) { } } -enum class Language(val label: String) {- KOTLIN("Kotlin"),- JAVA("Java"),- JAVASCRIPT("JavaScript"),- TYPESCRIPT("TypeScript"),- PYTHON("Python"),- C("C"),- CPP("C++"),- RUST("Rust"),- GO("Go"),- SWIFT("Swift"),- RUBY("Ruby"),- PHP("PHP"),+enum class Language(val label: String, val lineCommentPrefix: String? = null) {+ KOTLIN("Kotlin", "//"),+ JAVA("Java", "//"),+ JAVASCRIPT("JavaScript", "//"),+ TYPESCRIPT("TypeScript", "//"),+ PYTHON("Python", "#"),+ C("C", "//"),+ CPP("C++", "//"),+ RUST("Rust", "//"),+ GO("Go", "//"),+ SWIFT("Swift", "//"),+ RUBY("Ruby", "#"),+ PHP("PHP", "//"), JSON("JSON"), XML("XML"), MARKDOWN("Markdown"),- YAML("YAML"),- TOML("TOML"),- SHELL("Shell"),+ YAML("YAML", "#"),+ TOML("TOML", "#"),+ SHELL("Shell", "#"), CSS("CSS"),- SQL("SQL"),- DOCKERFILE("Dockerfile"),- GRADLE("Gradle"),+ SQL("SQL", "--"),+ DOCKERFILE("Dockerfile", "#"),+ GRADLE("Gradle", "//"), PLAINTEXT("Plain Text"); /** The tokenizer for this language, or null for languages we render without colors. */@@ -433,6 +433,8 @@ data class SyntaxColors( val annotation: Color, val match: Color, val activeMatch: Color,+ val currentLine: Color,+ val matchedBracket: Color, ) { fun colorFor(kind: TokenKind): Color = when (kind) { TokenKind.COMMENT -> comment@@ -454,25 +456,80 @@ fun rememberSyntaxColors(): SyntaxColors { annotation = scheme.error, match = scheme.primary.copy(alpha = 0.30f), activeMatch = scheme.tertiary.copy(alpha = 0.55f),+ currentLine = scheme.onSurface.copy(alpha = 0.06f),+ matchedBracket = scheme.primary.copy(alpha = 0.35f), ) } +/** Index of the bracket matching the one at [index], or -1 if [index] isn't a bracket / unmatched. */+private fun matchingBracketIndex(text: String, index: Int): Int {+ if (index < 0 || index >= text.length) return -1+ val c = text[index]+ val openers = "([{"+ val closers = ")]}"+ val openIdx = openers.indexOf(c)+ if (openIdx >= 0) {+ val close = closers[openIdx]+ var depth = 0+ var i = index+ while (i < text.length) {+ val ch = text[i]+ if (ch == c) depth++ else if (ch == close) {+ depth--+ if (depth == 0) return i+ }+ i+++ }+ return -1+ }+ val closeIdx = closers.indexOf(c)+ if (closeIdx >= 0) {+ val open = openers[closeIdx]+ var depth = 0+ var i = index+ while (i >= 0) {+ val ch = text[i]+ if (ch == c) depth++ else if (ch == open) {+ depth--+ if (depth == 0) return i+ }+ i--+ }+ return -1+ }+ return -1+}+ /** * A [VisualTransformation] that leaves the text unchanged (identity offset mapping) but * layers syntax spans and find-match backgrounds onto it. Highlighting is skipped for * very large documents to keep typing responsive.+ *+ * When [caret] is a valid collapsed offset, the caret's line gets a subtle background and, if+ * the caret sits next to a bracket, that bracket and its match are highlighted. */ class SyntaxTransformation( private val spec: LanguageSpec?, private val colors: SyntaxColors, private val matches: List<IntRange> = emptyList(), private val activeMatch: Int = -1,+ private val caret: Int = -1, ) : VisualTransformation { override fun filter(text: AnnotatedString): TransformedText { val raw = text.text val builder = AnnotatedString.Builder(text) + // Current-line background (drawn first so token colors sit on top).+ if (caret in 0..raw.length) {+ val lineStart = raw.lastIndexOf('\n', caret - 1) + 1+ var lineEnd = raw.indexOf('\n', caret)+ if (lineEnd < 0) lineEnd = raw.length+ if (lineEnd > lineStart) {+ builder.addStyle(SpanStyle(background = colors.currentLine), lineStart, lineEnd)+ }+ }+ if (spec != null && raw.length <= MAX_HIGHLIGHT_LENGTH) { for (match in spec.regex.findAll(raw)) { val kind = spec.kindFor(match) ?: continue@@ -484,6 +541,22 @@ class SyntaxTransformation( } } + // Bracket matching: check the char before and at the caret.+ if (caret in 0..raw.length) {+ val candidate = when {+ caret > 0 && raw[caret - 1] in "()[]{}" -> caret - 1+ caret < raw.length && raw[caret] in "()[]{}" -> caret+ else -> -1+ }+ if (candidate >= 0) {+ val other = matchingBracketIndex(raw, candidate)+ if (other >= 0) {+ builder.addStyle(SpanStyle(background = colors.matchedBracket), candidate, candidate + 1)+ builder.addStyle(SpanStyle(background = colors.matchedBracket), other, other + 1)+ }+ }+ }+ matches.forEachIndexed { index, range -> if (range.isEmpty()) return@forEachIndexed val background = if (index == activeMatch) colors.activeMatch else colors.match
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 7d633f1c59..e7d44f2fd6 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -155,8 +155,9 @@ fun CodeEditor( ) val syntaxColors = rememberSyntaxColors() val highlightMatches = if (showFind) matches else emptyList()- val transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch) {- SyntaxTransformation(tab.language.spec, syntaxColors, highlightMatches, activeMatch)+ val caret = if (tab.value.selection.collapsed) tab.value.selection.start else -1+ val transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch, caret) {+ SyntaxTransformation(tab.language.spec, syntaxColors, highlightMatches, activeMatch, caret) } val verticalScroll = rememberScrollState()
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 0032e42302..a3211dd595 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -284,6 +284,11 @@ private fun EditorToolbar( IconButton(onClick = { actions.insertText(" ".repeat(state.tabWidth)) }) { IconFormatIndentIncrease() } OverflowMenu(icon = { IconMoreVert() }) { Item(text = stringResource(R.string.go_to_line)) { showGoToLine = true }+ Item(text = stringResource(R.string.toggle_comment)) { actions.toggleComment() }+ Item(text = stringResource(R.string.duplicate_line)) { actions.duplicateLine() }+ Item(text = stringResource(R.string.move_line_up)) { actions.moveLineUp() }+ Item(text = stringResource(R.string.move_line_down)) { actions.moveLineDown() }+ Item(text = stringResource(R.string.delete_line)) { actions.deleteLine() } Item(text = stringResource(R.string.search_in_project)) { onOpenSearch() } } Spacer(Modifier.width(8.dp))
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 9ac36f00f1..dc14fbfd41 100644--- a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt@@ -103,6 +103,13 @@ fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) { checked = viewModel.softWrap, onCheckedChange = { viewModel.toggleSoftWrap() }, )+ SettingsDivider()+ SettingsSwitchRow(+ title = stringResource(R.string.auto_save),+ supportingText = stringResource(R.string.auto_save_desc),+ checked = viewModel.autoSave,+ onCheckedChange = viewModel::setAutoSave,+ ) } } }
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 56f9d06edc..69b9690ab8 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -83,6 +83,23 @@ interface CodeActions { fun insertText(insert: String) {} fun onEditorChange(new: TextFieldValue) {} + // ---- Line editing ----++ /** Toggle the line comment on the line(s) the selection touches (no-op if the language has none). */+ fun toggleComment() {}++ /** Duplicate the line(s) the selection touches. */+ fun duplicateLine() {}++ /** Move the line(s) the selection touches up one line. */+ fun moveLineUp() {}++ /** Move the line(s) the selection touches down one line. */+ fun moveLineDown() {}++ /** Delete the line(s) the selection touches. */+ fun deleteLine() {}+ /** Move the selection without recording an undo step (used by find navigation). */ fun setSelection(range: TextRange) {}
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 7abaad441d..d1ef79b845 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorInput.kt@@ -82,6 +82,110 @@ fun applyEditorInput( return new } +// ---- Line operations (pure; each is a single undo step at the call site) ----++/**+ * The `[start, end)` character range of the block of whole lines the selection touches: from+ * the start of the line containing the selection start to the end (before the newline) of the+ * line containing the selection end.+ */+private fun lineBlock(text: String, selMin: Int, selMax: Int): Pair<Int, Int> {+ val start = text.lastIndexOf('\n', selMin - 1) + 1+ var end = text.indexOf('\n', selMax)+ if (end < 0) end = text.length+ return start to end+}++/** Duplicates the line(s) the selection touches, placing the copy below and moving the caret to it. */+fun duplicateLine(value: TextFieldValue): TextFieldValue {+ val text = value.text+ val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+ val block = text.substring(start, end)+ val newText = text.substring(0, end) + "\n" + block + text.substring(end)+ val shift = block.length + 1+ val sel = value.selection+ return TextFieldValue(newText, TextRange(sel.start + shift, sel.end + shift))+}++/** Deletes the line(s) the selection touches, along with one adjacent newline. */+fun deleteLine(value: TextFieldValue): TextFieldValue {+ val text = value.text+ val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+ var removeStart = start+ val removeEnd: Int+ if (end < text.length) {+ removeEnd = end + 1 // drop the trailing newline+ } else {+ removeEnd = end+ if (start > 0) removeStart = start - 1 // last line: drop the preceding newline instead+ }+ val newText = text.substring(0, removeStart) + text.substring(removeEnd)+ val caret = removeStart.coerceAtMost(newText.length)+ return TextFieldValue(newText, TextRange(caret))+}++/** Swaps the line(s) the selection touches with the line above; a no-op on the first line. */+fun moveLineUp(value: TextFieldValue): TextFieldValue {+ val text = value.text+ val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+ if (start == 0) return value+ val prevStart = text.lastIndexOf('\n', start - 2) + 1+ val prevLine = text.substring(prevStart, start - 1)+ val block = text.substring(start, end)+ val newText = text.substring(0, prevStart) + block + "\n" + prevLine + text.substring(end)+ val shift = -(prevLine.length + 1)+ val sel = value.selection+ return TextFieldValue(newText, TextRange(sel.start + shift, sel.end + shift))+}++/** Swaps the line(s) the selection touches with the line below; a no-op on the last line. */+fun moveLineDown(value: TextFieldValue): TextFieldValue {+ val text = value.text+ val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+ if (end >= text.length) return value+ val nextStart = end + 1+ var nextEnd = text.indexOf('\n', nextStart)+ if (nextEnd < 0) nextEnd = text.length+ val nextLine = text.substring(nextStart, nextEnd)+ val block = text.substring(start, end)+ val newText = text.substring(0, start) + nextLine + "\n" + block + text.substring(nextEnd)+ val shift = nextLine.length + 1+ val sel = value.selection+ return TextFieldValue(newText, TextRange(sel.start + shift, sel.end + shift))+}++/**+ * Toggles a line comment [prefix] (e.g. `//`, `#`, `--`) on every line the selection touches.+ * If every non-blank line is already commented it uncomments; otherwise it comments, inserting+ * `"$prefix "` at each line's first non-whitespace column. Blank lines are left alone. The+ * returned selection spans the affected block.+ */+fun toggleLineComment(value: TextFieldValue, prefix: String): TextFieldValue {+ val text = value.text+ val (start, end) = lineBlock(text, value.selection.min, value.selection.max)+ val block = text.substring(start, end)+ val lines = block.split('\n')+ val nonBlank = lines.filter { it.isNotBlank() }+ val allCommented = nonBlank.isNotEmpty() && nonBlank.all { it.trimStart().startsWith(prefix) }++ val newLines = lines.map { line ->+ if (line.isBlank()) return@map line+ val indentLen = line.indexOfFirst { it != ' ' && it != '\t' }.let { if (it < 0) 0 else it }+ val indent = line.substring(0, indentLen)+ val rest = line.substring(indentLen)+ if (allCommented) {+ var r = rest.removePrefix(prefix)+ if (r.startsWith(" ")) r = r.substring(1)+ indent + r+ } else {+ "$indent$prefix $rest"+ }+ }+ val newBlock = newLines.joinToString("\n")+ 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 01ba4d3f70..3a89e9d615 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -30,6 +30,15 @@ class EditorPrefs(context: Context) { val autoIndent: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_INDENT_KEY] ?: true } val autoCloseBrackets: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_CLOSE_KEY] ?: true }+ val autoSave: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_SAVE_KEY] ?: false }++ /** Open tab file paths, in order, for session restore. */+ val sessionPaths: Flow<List<String>> = appContext.editorDataStore.data.map { prefs ->+ prefs[SESSION_PATHS_KEY]?.split("\n")?.filter { it.isNotEmpty() } ?: emptyList()+ }++ /** File path of the tab that was in the foreground, for session restore. */+ val sessionCurrent: Flow<String?> = appContext.editorDataStore.data.map { it[SESSION_CURRENT_KEY] } suspend fun setFolderPath(path: String) { appContext.editorDataStore.edit { it[FOLDER_PATH_KEY] = path }@@ -63,6 +72,19 @@ class EditorPrefs(context: Context) { appContext.editorDataStore.edit { it[AUTO_CLOSE_KEY] = enabled } } + suspend fun setAutoSave(enabled: Boolean) {+ appContext.editorDataStore.edit { it[AUTO_SAVE_KEY] = enabled }+ }++ /** Persists the open-tabs session; clears the keys when there is nothing open. */+ suspend fun setSession(paths: List<String>, current: String?) {+ appContext.editorDataStore.edit { prefs ->+ if (paths.isEmpty()) prefs.remove(SESSION_PATHS_KEY)+ else prefs[SESSION_PATHS_KEY] = paths.joinToString("\n")+ if (current == null) prefs.remove(SESSION_CURRENT_KEY) else prefs[SESSION_CURRENT_KEY] = current+ }+ }+ companion object { const val DEFAULT_FONT_SIZE = 14 const val DEFAULT_TAB_WIDTH = 4@@ -77,5 +99,8 @@ class EditorPrefs(context: Context) { private val THEME_MODE_KEY = stringPreferencesKey("theme_mode") private val AUTO_INDENT_KEY = booleanPreferencesKey("auto_indent") private val AUTO_CLOSE_KEY = booleanPreferencesKey("auto_close_brackets")+ private val AUTO_SAVE_KEY = booleanPreferencesKey("auto_save")+ 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 3f4e48d755..6f32b9d7b5 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -14,6 +14,7 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.code.syntax.Language import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch@@ -139,6 +140,9 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val autoIndent: Boolean get() = _autoIndent.value private val _autoCloseBrackets = mutableStateOf(true) val autoCloseBrackets: Boolean get() = _autoCloseBrackets.value+ private val _autoSave = mutableStateOf(false)+ val autoSave: Boolean get() = _autoSave.value+ private var autoSaveJob: Job? = null // ---- Project search ---- val searchResults = mutableStateListOf<SearchResult>()@@ -186,6 +190,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { _themeMode.value = prefs.themeMode.first() } viewModelScope.launch { _autoIndent.value = prefs.autoIndent.first() } viewModelScope.launch { _autoCloseBrackets.value = prefs.autoCloseBrackets.first() }+ viewModelScope.launch { _autoSave.value = prefs.autoSave.first() } viewModelScope.launch { val stored = prefs.folderPath.first() ?: return@launch val dir = File(stored)@@ -195,6 +200,32 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), prefs.clearFolderPath() } }+ viewModelScope.launch { restoreSession() }+ }++ /** Reopens the tabs from the previous session (files that still exist), off the main thread. */+ private suspend fun restoreSession() {+ val paths = prefs.sessionPaths.first()+ if (paths.isEmpty()) return+ val current = prefs.sessionCurrent.first()+ for (path in paths) {+ val file = File(path)+ if (!file.isFile) continue+ if (tabs.any { it.key == path }) continue+ val text = withContext(Dispatchers.IO) {+ runCatching { FileFiles.readText(file) }.getOrDefault("")+ }+ tabs.add(OpenTab(file = file, initialName = file.name, initialText = text, language = Language.fromFileName(file.name)))+ }+ currentIndex = tabs.indexOfFirst { it.file?.absolutePath == current }+ .takeIf { it >= 0 } ?: if (tabs.isEmpty()) -1 else 0+ }++ /** Persists the current set of file-backed tabs and the foreground tab for session restore. */+ private fun saveSession() {+ val paths = tabs.mapNotNull { it.file?.absolutePath }+ val current = currentTab?.file?.absolutePath+ viewModelScope.launch { prefs.setSession(paths, current) } } // ---- Folder handling ----@@ -357,6 +388,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tab.file = File(newPath + p.substring(oldPath.length)) } }+ saveSession() } } @@ -401,10 +433,9 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), } tabs.add(OpenTab(file = file, initialName = file.name, initialText = text, language = Language.fromFileName(file.name))) currentIndex = tabs.lastIndex+ saveSession() } }-- /** Handles a VIEW/EDIT intent that carries a single file URI. */ fun openExternal(uri: Uri) { if (uri.scheme == "file") { uri.path?.let { openFile(File(it)) }@@ -435,11 +466,15 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), ) ) currentIndex = tabs.lastIndex+ saveSession() } } override fun selectTab(index: Int) {- if (index in tabs.indices) currentIndex = index+ if (index in tabs.indices) {+ currentIndex = index+ saveSession()+ } } override fun closeTab(index: Int) {@@ -452,6 +487,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), removingCurrent -> index.coerceAtMost(tabs.lastIndex) else -> currentIndex }+ saveSession() } // ---- Editing ----@@ -462,8 +498,41 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val processed = applyEditorInput(tab.value, new, indentUnit, autoIndent, autoCloseBrackets) if (processed.text != tab.value.text) tab.pushUndo(tab.value) tab.value = processed+ if (autoSave) scheduleAutoSave()+ }++ /** Debounced auto-save: writes the current tab a short idle period after the last edit. */+ private fun scheduleAutoSave() {+ autoSaveJob?.cancel()+ autoSaveJob = viewModelScope.launch {+ delay(AUTO_SAVE_DELAY_MS)+ if (currentTab?.isDirty == true) save()+ } } + /** Applies a pure whole-line edit as a single undo step. */+ private fun applyLineEdit(transform: (TextFieldValue) -> TextFieldValue) {+ val tab = currentTab ?: return+ val next = transform(tab.value)+ if (next.text == tab.value.text && next.selection == tab.value.selection) return+ tab.pushUndo(tab.value)+ tab.value = next+ if (autoSave) scheduleAutoSave()+ }++ override fun toggleComment() {+ val prefix = currentTab?.language?.lineCommentPrefix ?: return+ applyLineEdit { toggleLineComment(it, prefix) }+ }++ override fun duplicateLine() = applyLineEdit(::duplicateLine)++ override fun moveLineUp() = applyLineEdit(::moveLineUp)++ override fun moveLineDown() = applyLineEdit(::moveLineDown)++ override fun deleteLine() = applyLineEdit(::deleteLine)+ /** Moves the caret to the start of [line] (1-based), without recording an undo step. */ override fun goToLine(line: Int) { val tab = currentTab ?: return@@ -537,6 +606,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { prefs.setAutoCloseBrackets(enabled) } } + fun setAutoSave(enabled: Boolean) {+ _autoSave.value = enabled+ viewModelScope.launch { prefs.setAutoSave(enabled) }+ if (enabled) scheduleAutoSave()+ }+ // ---- Find & replace ---- override fun replaceRange(range: IntRange, replacement: String) {@@ -645,10 +720,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), tabs.add(OpenTab(file = file, initialName = result.name, initialText = text, language = Language.fromFileName(result.name))) currentIndex = tabs.lastIndex goToLine(result.line)+ saveSession() } } private companion object {+ const val AUTO_SAVE_DELAY_MS = 1500L const val MAX_SEARCH_RESULTS = 500 const val MAX_MATCHES_PER_FILE = 50 const val MAX_SEARCH_FILE_SIZE = 500_000
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 402232848a..1f1b6fb0b4 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -52,4 +52,11 @@ <string name="storage_permission_rationale">Code needs all-files access to open your projects, run git and use the terminal on real file paths.</string> <string name="grant_access">Grant access</string> <string name="open_this_folder">Open this folder</string>+ <string name="toggle_comment">Toggle comment</string>+ <string name="duplicate_line">Duplicate line</string>+ <string name="move_line_up">Move line up</string>+ <string name="move_line_down">Move line down</string>+ <string name="delete_line">Delete line</string>+ <string name="auto_save">Auto-save</string>+ <string name="auto_save_desc">Save automatically a moment after you stop typing</string> </resources>
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 4ccbaa900e..6d4f8a7d39 100644--- a/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt+++ b/code/src/test/java/com/vayunmathur/code/util/EditorInputTest.kt@@ -160,4 +160,98 @@ class EditorInputTest { val matches = findLineMatches(text, "(", caseSensitive = false, useRegex = true) assertEquals(emptyList(), matches.map { it.line }) }++ // ---- Line operations ----++ @Test+ fun duplicateLineCopiesCurrentLineBelow() {+ val result = duplicateLine(TextFieldValue("foo\nbar", TextRange(1)))+ assertEquals("foo\nfoo\nbar", result.text)+ assertEquals(5, result.selection.start)+ }++ @Test+ fun deleteLineRemovesCurrentLineAndNewline() {+ val result = deleteLine(TextFieldValue("foo\nbar\nbaz", TextRange(5)))+ assertEquals("foo\nbaz", result.text)+ assertEquals(4, result.selection.start)+ }++ @Test+ fun deleteLineOnLastLineDropsPrecedingNewline() {+ val result = deleteLine(TextFieldValue("foo\nbar", TextRange(6)))+ assertEquals("foo", result.text)+ assertEquals(3, result.selection.start)+ }++ @Test+ fun moveLineUpSwapsWithLineAbove() {+ val result = moveLineUp(TextFieldValue("foo\nbar\nbaz", TextRange(5)))+ assertEquals("bar\nfoo\nbaz", result.text)+ assertEquals(1, result.selection.start)+ }++ @Test+ fun moveLineUpOnFirstLineIsNoOp() {+ val value = TextFieldValue("foo\nbar", TextRange(1))+ val result = moveLineUp(value)+ assertEquals("foo\nbar", result.text)+ assertEquals(1, result.selection.start)+ }++ @Test+ fun moveLineDownSwapsWithLineBelow() {+ val result = moveLineDown(TextFieldValue("foo\nbar\nbaz", TextRange(1)))+ assertEquals("bar\nfoo\nbaz", result.text)+ assertEquals(5, result.selection.start)+ }++ @Test+ fun moveLineDownOnLastLineIsNoOp() {+ val value = TextFieldValue("foo\nbar", TextRange(5))+ val result = moveLineDown(value)+ assertEquals("foo\nbar", result.text)+ assertEquals(5, result.selection.start)+ }++ // ---- Comment toggle ----++ @Test+ fun toggleCommentAddsPrefixWithSpace() {+ val result = toggleLineComment(TextFieldValue("foo", TextRange(0)), "//")+ assertEquals("// foo", result.text)+ }++ @Test+ fun toggleCommentRemovesPrefixAndSpace() {+ val result = toggleLineComment(TextFieldValue("// foo", TextRange(0)), "//")+ assertEquals("foo", result.text)+ }++ @Test+ fun toggleCommentPreservesIndent() {+ val result = toggleLineComment(TextFieldValue(" foo", TextRange(4)), "//")+ assertEquals(" // foo", result.text)+ }++ @Test+ fun toggleCommentAcrossMultipleLines() {+ val value = TextFieldValue("foo\nbar", TextRange(0, 7))+ val result = toggleLineComment(value, "#")+ assertEquals("# foo\n# bar", result.text)+ }++ @Test+ fun toggleCommentUncommentsWhenAllCommented() {+ val value = TextFieldValue("# foo\n# bar", TextRange(0, 11))+ val result = toggleLineComment(value, "#")+ assertEquals("foo\nbar", result.text)+ }++ @Test+ fun toggleCommentLeavesBlankLinesAlone() {+ val value = TextFieldValue("foo\n\nbar", TextRange(0, 8))+ val result = toggleLineComment(value, "//")+ assertEquals("// foo\n\n// bar", result.text)+ } }