code: add rainbow brackets, function/type colors, trailing-whitespace flag, theme presets
- Commit
d7b223a7a8531942c85ca15ec2e464750a22dbbd- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 23:02 UTC (4 months ago)
- Parents
10c0556
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 42f7a930cf..89889fa001 100644--- a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt+++ b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt@@ -424,17 +424,29 @@ private fun specFor(language: Language): LanguageSpec? = when (language) { Language.PLAINTEXT -> null } -/** Theme-derived colors for each token kind plus find-match highlights. */+/** Named color presets for the editor, theme-aware for [DEFAULT] and fixed for the others. */+object EditorThemes {+ const val DEFAULT = "default"+ const val MONOKAI = "monokai"+ const val SOLARIZED = "solarized"+ val ALL = listOf(DEFAULT to "Default", MONOKAI to "Monokai", SOLARIZED to "Solarized")+}++/** Theme-derived colors for each token kind plus find-match, bracket and whitespace highlights. */ data class SyntaxColors( val keyword: Color, val string: Color, val number: Color, val comment: Color, val annotation: Color,+ val function: Color,+ val type: Color, val match: Color, val activeMatch: Color, val currentLine: Color, val matchedBracket: Color,+ val trailingWhitespace: Color,+ val brackets: List<Color>, ) { fun colorFor(kind: TokenKind): Color = when (kind) { TokenKind.COMMENT -> comment@@ -446,21 +458,63 @@ data class SyntaxColors( } @Composable-fun rememberSyntaxColors(): SyntaxColors {+fun rememberSyntaxColors(theme: String = EditorThemes.DEFAULT): SyntaxColors { val scheme = MaterialTheme.colorScheme- return SyntaxColors(- keyword = scheme.primary,- string = scheme.tertiary,- number = scheme.secondary,- comment = scheme.onSurfaceVariant,- 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),- )+ return when (theme) {+ EditorThemes.MONOKAI -> monokaiColors(scheme)+ EditorThemes.SOLARIZED -> solarizedColors(scheme)+ else -> defaultColors(scheme)+ } } +private fun defaultColors(scheme: androidx.compose.material3.ColorScheme) = SyntaxColors(+ keyword = scheme.primary,+ string = scheme.tertiary,+ number = scheme.secondary,+ comment = scheme.onSurfaceVariant,+ annotation = scheme.error,+ function = scheme.primary,+ type = scheme.secondary,+ 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),+ trailingWhitespace = scheme.error.copy(alpha = 0.15f),+ brackets = listOf(scheme.primary, scheme.tertiary, scheme.secondary),+)++private fun monokaiColors(scheme: androidx.compose.material3.ColorScheme) = SyntaxColors(+ keyword = Color(0xFFF92672),+ string = Color(0xFFE6DB74),+ number = Color(0xFFAE81FF),+ comment = Color(0xFF75715E),+ annotation = Color(0xFFA6E22E),+ function = Color(0xFFA6E22E),+ type = Color(0xFF66D9EF),+ match = scheme.primary.copy(alpha = 0.30f),+ activeMatch = scheme.tertiary.copy(alpha = 0.55f),+ currentLine = Color(0xFFFFFFFF).copy(alpha = 0.06f),+ matchedBracket = Color(0xFFF92672).copy(alpha = 0.35f),+ trailingWhitespace = Color(0xFFF92672).copy(alpha = 0.15f),+ brackets = listOf(Color(0xFFF92672), Color(0xFFA6E22E), Color(0xFF66D9EF), Color(0xFFFD971F)),+)++private fun solarizedColors(scheme: androidx.compose.material3.ColorScheme) = SyntaxColors(+ keyword = Color(0xFF859900),+ string = Color(0xFF2AA198),+ number = Color(0xFFD33682),+ comment = Color(0xFF93A1A1),+ annotation = Color(0xFFB58900),+ function = Color(0xFF268BD2),+ type = Color(0xFFB58900),+ match = scheme.primary.copy(alpha = 0.30f),+ activeMatch = scheme.tertiary.copy(alpha = 0.55f),+ currentLine = Color(0xFF586E75).copy(alpha = 0.12f),+ matchedBracket = Color(0xFF268BD2).copy(alpha = 0.35f),+ trailingWhitespace = Color(0xFFDC322F).copy(alpha = 0.15f),+ brackets = listOf(Color(0xFF268BD2), Color(0xFF6C71C4), Color(0xFF2AA198), Color(0xFFB58900)),+)+ /** 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@@ -530,14 +584,51 @@ class SyntaxTransformation( } } - if (spec != null && raw.length <= MAX_HIGHLIGHT_LENGTH) {- for (match in spec.regex.findAll(raw)) {+ val highlight = spec != null && raw.length <= MAX_HIGHLIGHT_LENGTH+ if (highlight) {+ // Rainbow brackets first, so string/comment spec spans repaint any brackets inside them.+ if (colors.brackets.isNotEmpty()) {+ var depth = 0+ val n = colors.brackets.size+ for (i in raw.indices) {+ when (raw[i]) {+ '(', '[', '{' -> {+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ depth+++ }+ ')', ']', '}' -> {+ depth = (depth - 1).coerceAtLeast(0)+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ }+ }+ }+ }++ val covered = BooleanArray(raw.length)+ for (match in spec!!.regex.findAll(raw)) { val kind = spec.kindFor(match) ?: continue- builder.addStyle(- SpanStyle(color = colors.colorFor(kind)),- match.range.first,- match.range.last + 1,- )+ val first = match.range.first+ val lastExclusive = match.range.last + 1+ builder.addStyle(SpanStyle(color = colors.colorFor(kind)), first, lastExclusive)+ for (p in first until lastExclusive) covered[p] = true+ }++ // Function calls: an identifier immediately before "(", where not already a token.+ for (m in FUNCTION_REGEX.findAll(raw)) {+ if (!rangeCovered(covered, m.range)) {+ builder.addStyle(SpanStyle(color = colors.function), m.range.first, m.range.last + 1)+ for (p in m.range) covered[p] = true+ }+ }+ // Types: Capitalized identifiers not already covered.+ for (m in TYPE_REGEX.findAll(raw)) {+ if (!rangeCovered(covered, m.range)) {+ builder.addStyle(SpanStyle(color = colors.type), m.range.first, m.range.last + 1)+ }+ }+ // Trailing whitespace: a subtle background flag per line.+ for (m in TRAILING_WS_REGEX.findAll(raw)) {+ builder.addStyle(SpanStyle(background = colors.trailingWhitespace), m.range.first, m.range.last + 1) } } @@ -574,5 +665,14 @@ class SyntaxTransformation( // 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) } }++/** True if any index in [range] is already marked in [covered]. */+private fun rangeCovered(covered: BooleanArray, range: IntRange): Boolean {+ for (p in range) if (p in covered.indices && covered[p]) return true+ return false+}
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 73edabe9a9..cbb2988974 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -74,6 +74,7 @@ fun CodeEditor( initialQuery: String = "", completions: List<Completion> = emptyList(), showCompletions: Boolean = false,+ editorTheme: String = com.vayunmathur.code.syntax.EditorThemes.DEFAULT, ) { // 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@@ -166,7 +167,7 @@ fun CodeEditor( lineHeight = (fontSize * 1.4f).sp, color = MaterialTheme.colorScheme.onSurface, )- val syntaxColors = rememberSyntaxColors()+ 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 transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch, caret) {
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 d9113f37f3..79737b771b 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -184,6 +184,7 @@ fun EditorScreen( initialQuery = initialFind.orEmpty(), completions = state.completions, showCompletions = state.showCompletions,+ editorTheme = state.editorTheme, ) } }
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 dc14fbfd41..ec72e06c07 100644--- a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt@@ -22,6 +22,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.code.R import com.vayunmathur.code.Route+import com.vayunmathur.code.syntax.EditorThemes import com.vayunmathur.code.util.EditorPrefs import com.vayunmathur.code.util.EditorViewModel import com.vayunmathur.library.ui.AlertDialog@@ -47,6 +48,7 @@ import kotlin.math.roundToInt fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) { var showThemeDialog by remember { mutableStateOf(false) } var showTabWidthDialog by remember { mutableStateOf(false) }+ var showEditorThemeDialog by remember { mutableStateOf(false) } AppScaffold(title = stringResource(R.string.settings), backStack = backStack) { padding -> Column(@@ -61,6 +63,12 @@ fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) { supportingText = themeLabel(viewModel.themeMode), onClick = { showThemeDialog = true }, )+ SettingsDivider()+ SettingsRow(+ title = stringResource(R.string.editor_theme),+ supportingText = editorThemeLabel(viewModel.editorTheme),+ onClick = { showEditorThemeDialog = true },+ ) } SettingsSection(title = stringResource(R.string.editor)) {@@ -139,6 +147,16 @@ fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) { onDismiss = { showTabWidthDialog = false }, ) }++ if (showEditorThemeDialog) {+ ChoiceDialog(+ title = stringResource(R.string.editor_theme),+ options = EditorThemes.ALL,+ selected = viewModel.editorTheme,+ onSelect = { viewModel.setEditorTheme(it) },+ onDismiss = { showEditorThemeDialog = false },+ )+ } } @Composable@@ -148,6 +166,9 @@ private fun themeLabel(mode: String): String = when (mode) { else -> stringResource(R.string.theme_system) } +private fun editorThemeLabel(theme: String): String =+ EditorThemes.ALL.firstOrNull { it.first == theme }?.second ?: theme+ /** A single-choice list dialog of radio rows; selecting a value applies it and closes. */ @Composable private fun <T> ChoiceDialog(
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 0803258bf8..61de41ec3c 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -2,6 +2,7 @@ package com.vayunmathur.code.util import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue+import com.vayunmathur.code.syntax.EditorThemes import com.vayunmathur.code.syntax.Language /**@@ -60,6 +61,7 @@ data class CodeUiState( val isSearching: Boolean = false, val completions: List<Completion> = emptyList(), val showCompletions: Boolean = false,+ val editorTheme: String = EditorThemes.DEFAULT, ) { val currentTab: TabUiState? get() = tabs.getOrNull(currentIndex) }
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 4b933cfb4e..1cd6f7c0e0 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -8,6 +8,7 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore+import com.vayunmathur.code.syntax.EditorThemes import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map @@ -31,6 +32,8 @@ class EditorPrefs(context: Context) { 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 }+ val editorTheme: Flow<String> =+ appContext.editorDataStore.data.map { it[EDITOR_THEME_KEY] ?: EditorThemes.DEFAULT } /** Open tab file paths, in order, for session restore. */ val sessionPaths: Flow<List<String>> = appContext.editorDataStore.data.map { prefs ->@@ -82,6 +85,10 @@ class EditorPrefs(context: Context) { appContext.editorDataStore.edit { it[AUTO_SAVE_KEY] = enabled } } + suspend fun setEditorTheme(theme: String) {+ appContext.editorDataStore.edit { it[EDITOR_THEME_KEY] = theme }+ }+ /** 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 ->@@ -122,6 +129,7 @@ class EditorPrefs(context: Context) { 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 EDITOR_THEME_KEY = stringPreferencesKey("editor_theme") private val SESSION_PATHS_KEY = stringPreferencesKey("session_paths") private val SESSION_CURRENT_KEY = stringPreferencesKey("session_current") private val GIT_USERNAME_KEY = stringPreferencesKey("git_username")
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 7f59fad1c1..e635e256d2 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -11,6 +11,7 @@ import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.code.syntax.EditorThemes import com.vayunmathur.code.syntax.Language import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -142,6 +143,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val autoCloseBrackets: Boolean get() = _autoCloseBrackets.value private val _autoSave = mutableStateOf(false) val autoSave: Boolean get() = _autoSave.value+ private val _editorTheme = mutableStateOf(EditorThemes.DEFAULT)+ val editorTheme: String get() = _editorTheme.value private var autoSaveJob: Job? = null // ---- Project search ----@@ -217,6 +220,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), isSearching = isSearching, completions = completions.toList(), showCompletions = showCompletions,+ editorTheme = editorTheme, ) init {@@ -227,6 +231,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { _autoIndent.value = prefs.autoIndent.first() } viewModelScope.launch { _autoCloseBrackets.value = prefs.autoCloseBrackets.first() } viewModelScope.launch { _autoSave.value = prefs.autoSave.first() }+ viewModelScope.launch { _editorTheme.value = prefs.editorTheme.first() } viewModelScope.launch { _gitUsername.value = prefs.gitUsername.first() } viewModelScope.launch { _gitToken.value = prefs.gitToken.first() } viewModelScope.launch { _gitAuthorName.value = prefs.gitAuthorName.first() }@@ -870,6 +875,11 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), if (enabled) scheduleAutoSave() } + fun setEditorTheme(theme: String) {+ _editorTheme.value = theme+ viewModelScope.launch { prefs.setEditorTheme(theme) }+ }+ // ---- Find & replace ---- override fun replaceRange(range: IntRange, replacement: String) {
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 db9f6652fc..d39db534b0 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -25,6 +25,7 @@ <string name="font_size">Font size</string> <string name="tab_width">Tab width</string> <string name="theme">Theme</string>+ <string name="editor_theme">Editor color theme</string> <string name="theme_system">System</string> <string name="theme_light">Light</string> <string name="theme_dark">Dark</string>