Skip to content

Dynamic Configuration

Extensions are normally fixed when you create an EditorState. To change configuration at runtime — switch languages, toggle features, change themes — use Compartment.

Compartments

A Compartment wraps part of your extension configuration so it can be replaced later via an effect. Here is the demo's compartment setup:

    val langCompartment = remember { Compartment() }
    val themeCompartment = remember { Compartment() }

    val session = rememberEditorSession(
        doc = lang.doc,
        extensions = basicSetup +
            langCompartment.of(lang.ext) +
            themeCompartment.of(theme.ext)
    )

Switching configuration

To reconfigure at runtime, dispatch a transaction with the compartment's reconfigure effect:

                            session.dispatch(
                                TransactionSpec(
                                    effects = listOf(
                                        langCompartment.reconfigure(choice.ext)
                                    )
                                )
                            )

The editor re-parses the document with the new language and updates highlighting immediately.

Toggle example

A compartment can also wrap a feature you want to enable/disable:

val lineNumberCompartment = Compartment()

// Start with line numbers on
val session = rememberEditorSession(
    doc = "...",
    extensions = lineNumberCompartment.of(lineNumbers) + // ...
)

// Toggle off — replace with an empty extension list
fun toggleLineNumbers(session: EditorSession, enabled: Boolean) {
    session.dispatch(TransactionSpec(
        effects = listOf(
            lineNumberCompartment.reconfigure(
                if (enabled) lineNumbers
                else ExtensionList(emptyList())
            )
        )
    ))
}

Theme switching

Themes work the same way:

import com.monkopedia.kodemirror.view.*
import com.monkopedia.kodemirror.themonedark.oneDark

val themeCompartment = Compartment()

val session = rememberEditorSession(
    doc = "...",
    extensions = themeCompartment.of(oneDark) + // ...
)

// Switch to light theme
fun switchToLight(session: EditorSession) {
    session.dispatch(TransactionSpec(
        effects = listOf(
            themeCompartment.reconfigure(editorTheme.of(lightEditorTheme))
        )
    ))
}

Reading current configuration

You can query a compartment's current content:

val currentLanguage = languageCompartment.get(state)
  • Compartment — dynamic extension reconfiguration
  • Extension — base extension type
  • Facet — facet system for extension composition
  • StateEffect — state effect for reconfiguration

Based on the CodeMirror Configuration example.