Skip to content

Getting Started

1. Add the dependency

In your module's build.gradle.kts:

dependencies {
    implementation("dev.hossain:compose-highlight:<version>")
}

Check Maven Central or the releases page for the latest version.


2. Wrap your screen in HighlightThemeProvider

Place HighlightThemeProvider once near the root of your composition - inside setContent {} or at the top of your screen composable. It creates one shared WebView for the entire subtree and automatically selects the light or dark theme based on the system setting.

import dev.hossain.highlight.ui.HighlightThemeProvider
import dev.hossain.highlight.ui.rememberTomorrowTheme
import dev.hossain.highlight.ui.rememberTomorrowNightTheme

setContent {
    MyAppTheme {
        HighlightThemeProvider(
            lightHighlightTheme = rememberTomorrowTheme(),
            darkHighlightTheme  = rememberTomorrowNightTheme(),
        ) {
            MyAppContent()
        }
    }
}

3. Display a code block

import dev.hossain.highlight.ui.SyntaxHighlightedCode

SyntaxHighlightedCode(
    code     = """
        fun greet(name: String): String {
            return "Hello, ${'$'}name!"
        }
    """.trimIndent(),
    language = "kotlin",
)

The composable shows unstyled monospace text immediately and fades in highlighted colors once the WebView finishes processing - no visible flicker.


4. Common customizations

Show line numbers

import dev.hossain.highlight.ui.SyntaxHighlightedCode

SyntaxHighlightedCode(
    code            = snippet,
    language        = "kotlin",
    showLineNumbers = true,
)

Custom font size

import dev.hossain.highlight.ui.CodeBlockStyle
import dev.hossain.highlight.ui.SyntaxHighlightedCode
import dev.hossain.highlight.ui.SyntaxHighlightedCodeDefaults

SyntaxHighlightedCode(
    code     = snippet,
    language = "kotlin",
    style    = CodeBlockStyle(
        textStyle = SyntaxHighlightedCodeDefaults.codeTextStyle.copy(fontSize = 15.sp),
    ),
)

Hide header elements

import dev.hossain.highlight.ui.SyntaxHighlightedCode

SyntaxHighlightedCode(
    code                 = snippet,
    language             = "kotlin",
    languageLabel = null,  // hide language badge
    copyButton    = null,  // hide copy button
)

5. (Optional) Pre-warm the WebView

The hidden WebView initializes lazily on the first highlight call. To reduce first-call latency, pre-warm the WebView renderer process in Application.onCreate():

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        runCatching {
            WebViewCompat.startUpWebView(
                applicationContext,
                WebViewStartUpConfig.Builder(mainExecutor).build(),
                WebViewOutcomeReceiver { /* no-op */ },
            )
        }
    }
}

Requires androidx.webkit:webkit:1.16+ (already a transitive dependency of this library).


Next steps