Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
848a06a
feat: add a syntax tokenizer with Kotlin support
MohamedRejeb Oct 8, 2026
5544b74
feat: tokenize sixteen languages and whole files line by line
MohamedRejeb Oct 8, 2026
1901d88
feat: turn code into a coloured AnnotatedString
MohamedRejeb Oct 8, 2026
41ad4ec
feat: add BasicCodeText for showing code alone
MohamedRejeb Oct 8, 2026
3c3335b
feat: add a code block paragraph type
MohamedRejeb Oct 8, 2026
abb70df
feat: import and export fenced code blocks in Markdown
MohamedRejeb Oct 8, 2026
aff3b29
fix: keep br blank lines next to a fenced code block
MohamedRejeb Oct 8, 2026
2c043f2
feat: import and export code blocks in HTML
MohamedRejeb Oct 8, 2026
4132a4b
feat: carry code blocks in the document model and JSON
MohamedRejeb Oct 8, 2026
73295b4
feat: draw code blocks with a background and token colours
MohamedRejeb Oct 8, 2026
e694ef1
docs: document code blocks and add a sample screen
MohamedRejeb Oct 8, 2026
afb0cea
fix: keep a pasted code block whole and paste into a block as plain code
MohamedRejeb Oct 8, 2026
36530df
fix: draw a cut off code block safely and leave typing shortcuts out …
MohamedRejeb Oct 8, 2026
3eeb1bf
feat: add a copy button and an action slot on code blocks in RichText
MohamedRejeb Oct 8, 2026
06a8e85
Merge branch 'main' into feat/code-block-syntax-highlighting
MohamedRejeb Oct 9, 2026
a563509
feat: customizable code block copy button, block spacing and editor b…
MohamedRejeb Oct 9, 2026
75992a3
fix: code blocks keep URLs as code, one pasted line joins the text it…
MohamedRejeb Nov 11, 2026
07ac2d6
Merge branch 'main' into feat/code-block-syntax-highlighting
MohamedRejeb Nov 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
257 changes: 251 additions & 6 deletions docs/code_blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,255 @@ Normal text with `inline code` within it.

## Code Blocks

Multiline code blocks are planned for a future release. They will support:
- Syntax highlighting
- Multiple lines of code
- Language specification
- Copy to clipboard functionality
A fenced Markdown code block or an HTML `<pre>` is imported as a code block: its lines are drawn
in a fixed-width font on a background, and coloured by the language the block names (keywords,
strings, numbers, comments, annotations). `RichText` and the editors both draw it. The colours
are presentation only, they are never written to HTML, Markdown or JSON.

Stay tuned for updates!
Code blocks are experimental API (`@ExperimentalRichTextApi`).

### Basic usage

```kotlin
val state = rememberRichTextState()

LaunchedEffect(Unit) {
state.setMarkdown(
"""
Here is a function:

```kotlin
fun greet() = println("Hi")
```
""".trimIndent()
)
}

RichText(state = state, modifier = Modifier.fillMaxWidth())
```

The background is as wide as the composable, so give it the width the block should have
(`fillMaxWidth()` in most layouts).

The same block in each format:

| Format | Form |
|---|---|
| Markdown | A fence of three or more backticks with the language after it. Export uses a fence longer than any backtick run in the code |
| HTML | `<pre><code class="language-kotlin">...</code></pre>`. A `<pre>` without `<code>` or without a class is a block with no language |
| JSON | One `"type": "code-block"` block per line, with `"language"` and `"start": true` on the first line of a block |

The text inside a block is kept exactly as written: indentation, tabs, blank lines, and Markdown
or HTML that would otherwise be formatting.

### Copy and paste

Copying or cutting a selection that covers code writes the code line by line, with its
indentation, as plain text and as a `<pre><code>` block in HTML.

A code block pasted into ordinary text stays whole: the text is split around it. A single line
of code pasted into a sentence joins the sentence as text. Whatever is pasted into a code block,
formatted or not, becomes plain lines of that block.

Typing shortcuts (`**bold**`, `__bold__`, `` `code` `` and the others) do nothing inside a code
block, where those marks are code. A URL typed or pasted there is not turned into a link either.

### Copy button

A read-only `RichText` can draw an action at the top end corner of each code block. Pass
`CodeBlockCopyButton` to get a button that copies the block's code exactly, line ends and
indentation included:

```kotlin
RichText(
state = state,
modifier = Modifier.fillMaxWidth(),
codeBlockAction = { code, language -> CodeBlockCopyButton(code) },
)
```

`BasicRichText` and the Material and Material3 `RichText` all take `codeBlockAction`. It is given
the code and the language of the block, and nothing is drawn when it is null, which is the
default.

`CodeBlockCopyButton` can be adjusted:

| Parameter | Type | Default | Description |
|---|---|---|---|
| `code` | `String` | required | The code to copy |
| `modifier` | `Modifier` | `Modifier` | Applied to the button |
| `tint` | `Color` | mid-tone grey | The colour of the icon |
| `contentDescription` | `String` | `"Copy code"` | What accessibility services call the button. Pass a translated string for other languages |
| `onCopied` | `() -> Unit` | `{}` | Called after the copy, for example to show a "Copied" message |

```kotlin
codeBlockAction = { code, _ ->
CodeBlockCopyButton(
code = code,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
contentDescription = stringResource(Res.string.copy_code),
onCopied = { showCopiedMessage() },
)
}
```

The slot takes any composable, so the action can also be a button of your own, a language label,
or both in a `Row`.

The action is drawn over the corner of the block and takes no room of its own, so keep it about
one line tall: on a block with a long first line it covers the end of that line. The editors do
not draw it.

### Customizing

| Property on `RichTextState.config` | Type | Default | Description |
|---|---|---|---|
| `codeBlockBackgroundColor` | `Color` | translucent grey | The background drawn behind a block |
| `codeBlockFontFamily` | `FontFamily` | `FontFamily.Monospace` | The font of the code |
| `codeBlockColors` | `CodeBlockColors` | `CodeBlockColors.Default` | The style of each kind of token |

`CodeBlockColors` holds a `SpanStyle` per token kind, not just a colour, so a comment can be
italic:

```kotlin
val scheme = MaterialTheme.colorScheme

state.config.codeBlockBackgroundColor = scheme.surfaceVariant
state.config.codeBlockColors = CodeBlockColors(
keyword = SpanStyle(color = scheme.primary),
string = SpanStyle(color = scheme.tertiary),
number = SpanStyle(color = scheme.secondary),
comment = SpanStyle(color = scheme.outline, fontStyle = FontStyle.Italic),
annotation = SpanStyle(color = scheme.secondary),
)
```

`CodeBlockColors.Default` uses mid-tone colours that stay readable on light and dark backgrounds.

### Turning code blocks off

Code blocks are one of the [editor features](features.md). An editor whose feature set leaves out
`RichTextFeature.CodeBlock` loads and pastes a code block as plain paragraphs:

```kotlin
state.config.features = RichTextFeature.All - RichTextFeature.CodeBlock
```

## Showing Code Alone

To show code that is not part of a rich text, such as a snippet or a whole file, use
`BasicCodeText`. It needs no `RichTextState`:

```kotlin
BasicCodeText(
code = "fun greet() = println(\"Hi\")",
language = CodeLanguage.Kotlin,
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp))
.padding(12.dp),
)
```

| Parameter | Type | Default | Description |
|---|---|---|---|
| `code` | `String` | required | The code to show |
| `language` | `CodeLanguage?` | required | The language to colour by, or null to draw the code plain |
| `modifier` | `Modifier` | `Modifier` | Background, padding and shape come from here |
| `style` | `TextStyle` | monospace | The text style of the code |
| `colors` | `CodeBlockColors` | `CodeBlockColors.Default` | The style of each kind of token |
| `softWrap` | `Boolean` | `false` | When false, a long line scrolls sideways instead of wrapping |
| `onTextLayout` | `(TextLayoutResult) -> Unit` | `{}` | Called when the text is laid out |

`BasicCodeText` draws the text and nothing else, so it fits any design system.

For a `Text` of your own, `highlightCode` returns the coloured `AnnotatedString`:

```kotlin
Text(text = highlightCode(code, CodeLanguage.fromName("python")))
```

## Custom Layouts Such as a Diff View

A view that draws its own rows, for example a diff with a gutter and added or removed
backgrounds, needs the tokens of each line. `CodeHighlighter.tokenizeLines` returns them with
offsets relative to each line. The lines are read as one piece of code, so a comment or string
that opens on one line is still coloured on the next:

```kotlin
val language = CodeLanguage.fromFileName("src/main/kotlin/Greeter.kt") ?: return
val colors = CodeBlockColors.Default
val tokens = CodeHighlighter.tokenizeLines(lines, language)

lines.forEachIndexed { index, line ->
val text = buildAnnotatedString {
append(line)
tokens[index].forEach { token ->
addStyle(colors.styleOf(token.kind), token.start, token.end)
}
}
DiffRow(text)
}
```

Lines that do not follow each other in the file, such as two hunks of a diff, are two calls.
A hunk that starts in the middle of a comment or string is coloured as code until that comment
or string ends, because the lines above it are not known.

`CodeHighlighter.tokenize(code, language)` returns the tokens of a whole piece of code.
Tokenizing is linear in the length of the code and never throws, whatever the input.

## Supported Languages

| Language | `CodeLanguage` | Names it answers to | File endings |
|---|---|---|---|
| Kotlin | `Kotlin` | `kotlin`, `kt`, `kts` | `kt`, `kts` |
| Java | `Java` | `java` | `java` |
| JavaScript | `JavaScript` | `javascript`, `js`, `jsx`, `mjs`, `cjs`, `node` | `js`, `jsx`, `mjs`, `cjs` |
| TypeScript | `TypeScript` | `typescript`, `ts`, `tsx` | `ts`, `tsx` |
| Python | `Python` | `python`, `py`, `python3` | `py` |
| Swift | `Swift` | `swift` | `swift` |
| Go | `Go` | `go`, `golang` | `go` |
| Rust | `Rust` | `rust`, `rs` | `rs` |
| C | `C` | `c`, `h` | `c`, `h` |
| C++ | `Cpp` | `cpp`, `c++`, `cc`, `cxx`, `hpp` | `cpp`, `cc`, `cxx`, `hpp`, `hh` |
| C# | `CSharp` | `csharp`, `cs`, `c#` | `cs` |
| Dart | `Dart` | `dart` | `dart` |
| Shell | `Shell` | `shell`, `sh`, `bash`, `zsh`, `shellscript` | `sh`, `bash`, `zsh` |
| SQL | `Sql` | `sql` | `sql` |
| JSON | `Json` | `json` | `json` |
| YAML | `Yaml` | `yaml`, `yml` | `yaml`, `yml` |

`CodeLanguage.fromName` takes the name of a fence or of a `language-x` class, ignoring case, and
`CodeLanguage.fromFileName` takes a file name or path. Both return null for a language the
library does not know. A code block with an unknown language is drawn as plain code and keeps
its language tag on export.

## Limitations

- A long line in a code block inside `RichText` or an editor wraps. Use `BasicCodeText` when the
code should scroll sideways.
- There is no editor action yet to turn text into a code block or to leave one. A code block
that was loaded can be edited, and Enter adds a line to it.
- Only fenced Markdown code is a code block. Code indented by four spaces is not.
- HTML, XML, CSS and diffs are not coloured yet.
- Markup inside an HTML `<pre>` is read as plain code. Code copied from an IDE arrives as a
`<pre>` with coloured spans and no language, so it is pasted as a code block without colours.
- A code block inside a list item or a quote is moved to the top level.
- The room above and below a block comes from a taller first and last line, because a text
layout has no space between paragraphs. When the first or last line of a block is long enough
to wrap, its wrapped lines are spaced a little wider than the rest. A one-line block that wraps
shows this most.
- In Markdown, an empty paragraph directly after a block is not kept on a round trip.
- Text selected in a read-only `RichText` inside a `SelectionContainer` is copied with a space
between paragraphs, so code selected that way loses its line ends. Copy and cut in the editors
keep them.
- `ExpandableBasicRichText` colours the code but draws no background behind it.

## Related

- For the feature set that switches code blocks on and off, see [Editor features](features.md).
- For format details, see [HTML Import and Export](html_import_export.md),
[Markdown Import and Export](markdown_import_export.md) and
[JSON Import and Export](json_import_export.md).
- For the block model behind the JSON format, see [Rich Text Document](rich_text_document.md).
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ if (RichTextFeature.Link in state.config.features) {
| `OrderedList` | Ordered list items |
| `UnorderedList` | Unordered list items |
| `Heading` | Heading levels 1 to 6 |
| `CodeBlock` | Multi-line code blocks |
| `ParagraphStyle` | Paragraph alignment, direction, first-line indent and line height |

Each feature corresponds to one `RichTextSpanMark` or one block attribute of the [document model](rich_text_document.md). `RichTextFeature.All` is computed from the enum, so a library version that adds a feature keeps it allowed for editors on the default and excluded for editors with an explicit set.
Expand Down
1 change: 1 addition & 0 deletions docs/html_import_export.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ The following HTML tags are supported:
- `<p>` - Paragraphs
- `<div>` - Divisions
- `<br>` - Line breaks
- `<pre>` - Code blocks, with the language from `<code class="language-x">` (see [Code Blocks](code_blocks.md))
- `<h1>`..`<h6>` - Headings (see [Headings](headings.md))
- `<ul>` - Unordered lists. `style="list-style-type: ..."` sets the bullet (`disc`, `circle`, `square`)
- `<ol>` - Ordered lists. `start="N"` sets the first item's number; `style="list-style-type: ..."` sets the numbering (`decimal`, `lower-alpha`, `upper-alpha`, `lower-roman`, `upper-roman`, `arabic-indic`, `arabic-abjad`)
Expand Down
3 changes: 2 additions & 1 deletion docs/json_import_export.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@ Block fields:
| Field | When present | Meaning |
|---|---|---|
| `id` | always | `"b" + index`; accepted and ignored on import |
| `type` | always | `paragraph`, `heading`, or `list-item` |
| `type` | always | `paragraph`, `heading`, `list-item`, or `code-block` |
| `level` | headings | Heading level 1 to 6 |
| `ordered`, `indent`, `start` | list items | Ordered flag, 0-based nesting, numbering restart |
| `listStyle` | list items with a style of their own | CSS `list-style-type` keyword of the item's list (`lower-alpha`, `square`, ...) |
| `language`, `start` | code blocks | One block per line of code: the language tag as written, and `true` on the first line of a block (see [Code Blocks](code_blocks.md)). A library version from before code blocks rejects a document that contains one |
| `align`, `dir`, `lineHeight`, `textIndent` | when set | Paragraph style |
| `br` | line-break paragraphs | Paragraph created by `<br>` |
| `text`, `spans` | always | Content and styling marks |
Expand Down
1 change: 1 addition & 0 deletions docs/markdown_import_export.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ The following Markdown syntax elements are supported:
- `*text*` or `_text_` - Italic text
- `~~text~~` - Strikethrough text
- `` `code` `` - Code spans
- Fenced code with a language after the opening fence - Code blocks (see [Code Blocks](code_blocks.md))

### Headings
- `# Title` through `###### Title` - ATX headings H1..H6 (see [Headings](headings.md))
Expand Down
2 changes: 1 addition & 1 deletion docs/rich_text_document.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ A document is a list of blocks, one per paragraph:
| `RichTextBlock` field | Type | Meaning |
|---|---|---|
| `text` | `String` | Flattened paragraph text. List prefixes are excluded. Each inline image occupies one U+FFFC placeholder character. |
| `type` | `RichTextBlockType` | `Paragraph` or `ListItem(ordered, indent, startNumber, listStyleType)` |
| `type` | `RichTextBlockType` | `Paragraph`, `ListItem(ordered, indent, startNumber, listStyleType)` or `CodeBlock(language, isBlockStart)`, one per line of code |
| `spans` | `List<RichTextSpanMark>` | Styling marks over inclusive character ranges of `text` |
| `headingLevel` | `Int` | 0 for normal text, 1 to 6 for headings |
| `textAlign` | `TextAlign` | Paragraph alignment, `Unspecified` when not set |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ internal fun decodeBlock(json: JsonObject, registry: RichSpanStyleRegistry): Ric
},
) to ((json["heading"] as? JsonPrimitive)?.content?.toIntOrNull() ?: 0)
}
"code-block" -> RichTextBlockType.CodeBlock(
language = json["language"]?.takeIf { it !is JsonNull }?.let { element ->
(element as? JsonPrimitive)?.takeIf { it.isString }?.content
?: throw MalformedRichTextJsonException("code-block \"language\" must be a string")
},
isBlockStart = (json["start"] as? JsonPrimitive)?.booleanOrNull == true,
) to 0
else -> throw MalformedRichTextJsonException("Unknown block type: $typeName")
}

Expand Down Expand Up @@ -100,6 +107,11 @@ internal fun encodeBlock(
type.listStyleType?.let { put("listStyle", it) }
if (block.headingLevel > 0) put("heading", block.headingLevel)
}
type is RichTextBlockType.CodeBlock -> {
put("type", "code-block")
type.language?.let { put("language", it) }
if (type.isBlockStart) put("start", true)
}
block.headingLevel > 0 -> {
put("type", "heading")
put("level", block.headingLevel)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.mohamedrejeb.richeditor.json

import com.mohamedrejeb.richeditor.annotation.ExperimentalRichTextApi
import com.mohamedrejeb.richeditor.document.RichTextBlock
import com.mohamedrejeb.richeditor.document.RichTextBlockType
import com.mohamedrejeb.richeditor.document.RichTextDocument
import com.mohamedrejeb.richeditor.model.RichTextState
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

@OptIn(ExperimentalRichTextApi::class)
class CodeBlockJsonTest {

private val document = RichTextDocument(
blocks = listOf(
RichTextBlock(text = "val a", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = true)),
RichTextBlock(text = "", type = RichTextBlockType.CodeBlock("kotlin", isBlockStart = false)),
RichTextBlock(text = "c", type = RichTextBlockType.CodeBlock(null, isBlockStart = true)),
RichTextBlock(text = "d", type = RichTextBlockType.CodeBlock(null, isBlockStart = false)),
),
)

@Test
fun `language and start are written and left out when unset`() {
assertEquals(
"""{"v":1,"blocks":[""" +
"""{"id":"b0","type":"code-block","language":"kotlin","start":true,"text":"val a","spans":[]},""" +
"""{"id":"b1","type":"code-block","language":"kotlin","text":"","spans":[]},""" +
"""{"id":"b2","type":"code-block","start":true,"text":"c","spans":[]},""" +
"""{"id":"b3","type":"code-block","text":"d","spans":[]}]}""",
codecEncode(document),
)
}

@Test
fun `code blocks survive a json round trip`() {
assertEquals(document.blocks, codecDecode(codecEncode(document)).blocks)
}

@Test
fun `a language that is not a string is malformed`() {
assertFailsWith<MalformedRichTextJsonException> {
codecDecode("""{"v":1,"blocks":[{"id":"b0","type":"code-block","language":5,"text":"a","spans":[]}]}""")
}
}

@Test
fun `a code block survives a state json round trip`() {
val html = "<p>Before</p><pre><code class=\"language-kotlin\">val a\n\n val b</code></pre>" +
"<pre><code>c</code></pre><p>After</p>"
val state = RichTextState().apply { setHtml(html) }

val json = state.toJson()
val reloaded = RichTextState().setJson(json)

assertEquals(html, reloaded.toHtml())
assertEquals(json, reloaded.toJson())
}
}
Loading
Loading