<div align="center">

# Iced Code Editor
A high-performance, canvas-based code editor widget for [Iced](https://github.com/iced-rs/iced).
[](https://crates.io/crates/iced-code-editor)
[](https://docs.rs/iced-code-editor)
[](https://github.com/LuDog71FR/iced-code-editor/blob/main/LICENSE)
[](https://crates.io/crates/iced-code-editor)
[](https://github.com/LuDog71FR/iced-code-editor/actions)
</div>
## Overview
This crate provides a fully-featured code editor widget with syntax highlighting, line numbers, text selection, and comprehensive keyboard navigation for the Iced GUI framework.
Screenshot of the demo application:

## Features
- **Syntax highlighting** for multiple programming languages via [syntect](https://github.com/trishume/syntect), with a choice of bundled syntax themes and per-token-kind color overrides (keys, strings, numbers, literals, comments, punctuation)
- **Line numbers** with styled gutter
- **Text selection** via mouse drag, Shift+Click and keyboard shortcuts
- **Clipboard operations** (copy, paste)
- **Undo/Redo** with smart command grouping and configurable history
- **Custom scrollbars** — thin, themed pill scrollers that stay faint until the pointer comes near
- **Focus management** for multiple editors — a click outside an editor releases its keyboard focus
- **Native Iced theme support** - Automatically adapts to all 23+ built-in Iced themes
- **Line wrapping** to split long lines
- **Code folding** to collapse/expand indentation-based blocks, with fold markers shown always, on gutter hover, or never, on either side of the line numbers
- **High performance** canvas-based rendering — large pastes, select-all and syntax highlighting of big files stay responsive
- **Search and replace** text
- **Command palette** (`Ctrl+Shift+P`) listing every editor action, extensible with the host application's own commands
- **Language Server Protocol** (LSP) support
- **Diagnostic underlines** with severity colors, including wrapped lines, and their messages on hover
- **Virtual text** — text drawn inside a line without being in the buffer, such as LSP inlay hints, and hidden per editor on demand
- **Range styles** — host-defined colors over the syntax highlighting, such as LSP semantic tokens
- **Auto indentation** with custom indent style
- **Auto-closing brackets/quotes** with surround selection
- **Matching bracket/quote highlight** — highlights the paired bracket or quote next to the cursor
- **Bracket-pair colorization** — colors each bracket by nesting depth (rainbow brackets)
- **Multiple cursors** for simultaneous editing at multiple positions
- **Move and duplicate lines** with keyboard shortcuts
- **Toggle comment** on the current line or selection (`Ctrl+/`)
- **Visible whitespace rendering** — spaces shown as `·`, tabs as `→`
- **Indentation guides** — vertical lines marking each indentation level
- **Inline color previews** — a swatch next to every `#rrggbb`, `0xrrggbb` or `rgb(…)` literal
- **Sticky scroll** — the headers of the enclosing blocks stay pinned above the viewport, and clicking one scrolls back to it
- **Optional Vim mode** with Normal, Insert, Visual, and Visual Line modes
## Quick Start
Add this to your `Cargo.toml`:
```toml
[dependencies]
iced = "0.14"
iced-code-editor = "0.7"
```
### Basic Example
Here's a minimal example to integrate the code editor into your Iced application:
> **Note:** A press outside the editor releases its keyboard focus automatically.
> Call `editor.lose_focus()` when focus moves *without* a click, such as keyboard
> navigation or a programmatic focus change. The `mouse_area` pattern below still
> works, but is no longer required for clicks.
```rust
use iced::widget::{column, container, mouse_area, text_input};
use iced::{Element, Task};
use iced_code_editor::{CodeEditor, Message as EditorMessage};
struct MyApp {
editor: CodeEditor,
input_value: String,
}
#[derive(Debug, Clone)]
enum Message {
EditorEvent(EditorMessage),
InputChanged(String),
InputClicked,
}
impl Default for MyApp {
fn default() -> Self {
let code = r#"fn main() {
println!("Hello, world!");
}
"#;
Self {
editor: CodeEditor::new(code, "rust"),
input_value: String::new(),
}
}
}
impl MyApp {
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::EditorEvent(event) => {
self.editor.update(&event).map(Message::EditorEvent)
}
Message::InputChanged(value) => {
self.input_value = value;
self.editor.lose_focus(); // explicit transfer, e.g. for keyboard focus
Task::none()
}
Message::InputClicked => {
self.editor.lose_focus(); // explicit transfer, e.g. for keyboard focus
Task::none()
}
}
}
fn view(&self) -> Element<'_, Message> {
let input = mouse_area(
text_input("Type something...", &self.input_value)
.on_input(Message::InputChanged)
.padding(8),
)
.on_press(Message::InputClicked); // detect click to trigger lose_focus
container(
column![input, self.editor.view().map(Message::EditorEvent)]
.spacing(10)
.height(iced::Fill),
)
.padding(20)
.into()
}
}
fn main() -> iced::Result {
iced::run(MyApp::update, MyApp::view)
}
```
## Vim Mode
Vim behavior is disabled by default and configured independently for each
`CodeEditor` instance. Enabling it enters Normal mode and collapses any
multi-cursor state to the primary cursor:
```rust
use iced_code_editor::{CodeEditor, VimMode};
let mut editor =
CodeEditor::new("fn main() {}", "rs").with_vim_enabled(true);
assert!(editor.vim_enabled());
assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
editor.set_vim_enabled(false);
assert_eq!(editor.vim_mode(), None);
```
With the editor focused, press `Ctrl+Alt+V` (or `Command+Alt+V` on macOS)
to switch between Vim and standard editing. Enabling Vim always starts in
Normal mode. The regular `Ctrl`/`Command+V` system-paste shortcut is unchanged.
The MVP supports these keys:
| Context | Keys | Behavior |
| ------- | ---- | -------- |
| Normal/Visual motion | `h`, `j`, `k`, `l` | Move left, down, up, or right |
| Normal/Visual motion | `w`, `b`, `e` | Move to the next word, previous word, or word end |
| Normal/Visual motion | `0`, `^`, `$` | Move to line start, first non-blank, or line end |
| Normal/Visual motion | `gg`, `G` | Move to document start or end when no count is given |
| Normal/Visual motion | `[count]gg`, `[count]G` | Jump to the 1-based logical line, e.g. `5G` or `5gg` jumps to line 5 |
| Enter Insert | `i`, `a`, `I`, `A` | Insert before/after the cursor, at first non-blank, or at line end |
| Enter Insert | `o`, `O` | Open line(s) below or above |
| Select | `v`, `V` | Enter character-wise Visual or Visual Line mode |
| Operators | `d{motion}`, `c{motion}`, `y{motion}` | Delete, change, or yank through any supported motion |
| Line operators | `[count]dd`, `[count]cc`, `[count]yy` | Delete, change, or yank consecutive lines, e.g. `5yy` yanks five lines |
| Visual operators | `d`, `c`, `y` | Apply the operator to the Visual selection |
| Direct edits | `x`, `p`, `P` | Delete characters; paste after or before from the unnamed register |
| History | `u`, `Ctrl+R` | Undo or redo |
| Search | `/pattern`, then `Enter` | Search forward from the cursor and wrap at the end |
| Search repeat | `n`, `N` | Repeat the last search forward or backward |
| Go to line | `:N`, then `Enter` | Jump to 1-based logical line `N`, clamped to the document |
| Save | `:w`, then `Enter` | Request that the host save the current document |
| Exit Vim mode | `:q`, then `Enter` | Disable Vim behavior for the current editor |
| Save and exit Vim mode | `:wq`, then `Enter` | Request a save and disable Vim behavior |
| Command line | `Backspace`, `Escape` | Edit or cancel the active `/` or `:` input |
| Mode exit | `Escape` | Return to Normal mode and clear pending prefixes/selections |
| Count prefix | `1`–`9`, then `0` | Repeat motions, line operators, `x`, paste, undo, or opened lines; operator and motion counts multiply |
When Vim mode is enabled, a fixed status line below the editor shows the
current mode. While entering `/pattern` or `:N`, it shows the command and
current input; otherwise it shows pending Normal-mode keys such as `5d` or
`3g`. The status line remains visible while the document scrolls.
`j` and `k` move by visible display lines, so they follow wrapped lines and
skip folded content. Vim mode is intentionally single-cursor; attempts to add
extra cursors are ignored while it is enabled.
Vim `d`, `c`, `y`, `x`, `p`, and `P` use an unnamed register stored inside
that editor instance. It distinguishes character-wise and line-wise content
and does not access the system clipboard. Platform `Ctrl`/`Command` clipboard
shortcuts (`C`, `X`, and `V`) keep their existing system-clipboard behavior
and take priority over Vim parsing.
Because the editor does not own a file path or perform disk I/O, `:w`, `:wq`,
and `Ctrl`/`Command+S` emit `Message::WriteRequested`. Hosts should intercept
that message and save the corresponding document. The demo app binds all
three inputs to its existing Save/Save As flow.
This is a focused MVP, not full Vim compatibility. Apart from the supported
`:N` line jump and `:q`/`:w`/`:wq` commands, it does not implement Ex
commands. It also does not implement regex search, search history, text
objects, macros, named registers, marks, `.` repeat, or configurable key
mappings.
## Keyboard Shortcuts
The editor supports a comprehensive set of keyboard shortcuts:
### Navigation
| Shortcut | Action |
| -------------------------------------- | ----------------------------- |
| **Arrow Keys** (Up, Down, Left, Right) | Move cursor |
| **Shift + Arrows** | Move cursor with selection |
| **Ctrl + Left** / **Ctrl + Right** | Move one word left/right (**Alt** on macOS) |
| **Shift + Ctrl + Left/Right** | Select one word left/right (**Shift + Alt** on macOS) |
| **Home** | Jump to the first non-blank character of the line; press again for column 0 |
| **End** | Jump to end of line |
| **Shift + Home** / **Shift + End** | Select to start/end of line |
| **Ctrl + Home** / **Ctrl + End** | Jump to start/end of document |
| **Page Up** / **Page Down** | Move cursor one page up/down |
| **Shift + Page Up** / **Shift + Page Down** | Select one page up/down |
| **Shift + Click** | Extend the selection from its anchor (or the caret) to the clicked position |
| **Ctrl + Page Up** / **Ctrl + Page Down** | *Not handled* — left uncaptured for the host application to bind (the usual previous/next-tab combination). The same holds for **Alt + Page Up/Down**. |
### Editing
| Shortcut | Action |
| ------------------ | ------------------------------------------------------------------------ |
| **Backspace** | Delete character before cursor (or delete selection if text is selected) |
| **Delete** | Delete character after cursor (or delete selection if text is selected) |
| **Ctrl + Backspace** | Delete the word before the cursor (**Alt + Backspace** on macOS) |
| **Ctrl + Delete** | Delete the word after the cursor (**Alt + Delete** on macOS) |
| **Shift + Delete** | Delete selected text (same as Delete when selection exists) |
| **Enter** | Insert new line |
| **Tab** | Insert indent |
| **Shift + Tab** | Remove one indentation level before each cursor |
| **Alt + Up/Down** | Move current line (or selected lines) up/down |
| **Shift + Alt + Up/Down** | Duplicate current line (or selected lines) above/below |
| **Ctrl + /** | Toggle line comment on current line (or selected lines) |
| **Ctrl + S** | Request a save from the host application (emits `Message::WriteRequested`) |
### Clipboard
| Shortcut | Action |
| ---------------------------------- | -------------------- |
| **Ctrl + C** or **Ctrl + Insert** | Copy selected text |
| **Ctrl + X** | Cut selected text |
| **Ctrl + V** or **Shift + Insert** | Paste from clipboard |
| **Ctrl + A** | Select the whole document |
### Undo/Redo
| Shortcut | Action |
| ------------ | -------------------------- |
| **Ctrl + Z** | Undo last operation |
| **Ctrl + Y** or **Shift + Ctrl + Z** | Redo last undone operation |
The editor features smart command grouping - consecutive typing is grouped into single undo operations, while navigation or deletion actions create separate undo points.
### Multiple Cursors
| Shortcut | Action |
| --------------------- | ----------------------------------------------- |
| **Alt + Click** | Add a cursor at the clicked position |
| **Ctrl + Alt + Up** | Add a cursor on the line above |
| **Ctrl + Alt + Down** | Add a cursor on the line below |
| **Ctrl + D** | Select the next occurrence of the current word/selection |
| **Escape** | Collapse all cursors back to one (when search dialog is closed) |
All editing operations (typing, backspace, delete, enter, tab, paste) apply simultaneously to every cursor. Copy with multiple selections joins all selected texts with newlines. Paste with the same number of clipboard lines as cursors pastes one line per cursor.
### Search and Replace
| Action | macOS | Windows / Linux |
| --- | --- | --- |
| Open search | Cmd+F | Ctrl+F |
| Open search and replace | Cmd+H | Ctrl+H |
| Toggle replacement row (search open) | Cmd+Shift+H | Ctrl+H |
| Match case | Cmd+Option+C | Alt+C |
| Match whole words | Cmd+Option+W | Alt+W |
| Use regular expressions | Cmd+Option+R | Alt+R |
| Expand / collapse multiline input | Cmd+Option+M | Alt+M |
| Select all matches | Option+Enter | Alt+Enter |
| Next match | Cmd+G or F3 | F3 |
| Previous match | Cmd+Shift+G or Shift+F3 | Shift+F3 |
| Replace next match | Enter in replacement field | Enter in replacement field |
| Replace next match (also in multiline mode) | Cmd+Shift+Enter | Ctrl+Shift+Enter |
| Replace all matches | Cmd+Enter | Ctrl+Enter |
| Cycle dialog fields | Tab / Shift+Tab | Tab / Shift+Tab |
| Close search | Escape | Escape |
Toolbar shortcuts apply while search is open. Enter in the compact search field finds the next match; Enter in expanded inputs inserts a newline. Replacement shortcuts require the replacement row to be visible. Hover each toolbar button to see its platform-specific shortcut.
### Go to Line
| Shortcut | Action |
| ------------ | ----------------------------------- |
| **Ctrl + G** | Open the go-to-line dialog |
| **Enter** | Jump to the entered 1-based line |
| **Escape** | Close the dialog |
The target line is clamped to the document, so a number past the end jumps to
the last line.
### Command Palette
| Shortcut | Action |
| ------------------------ | ------------------------------------------ |
| **Ctrl + Shift + P** | Open the command palette |
| **Up / Down** | Move through the filtered commands |
| **Enter** | Run the highlighted command |
| **Escape** | Close the palette |
Typing filters the list by subsequence, so `tc` finds "Toggle Line Comment" and `fldall` finds "Fold All". Only commands that are usable right now are listed — undo does not appear with an empty history, and the folding commands stay out while folding is disabled. Each row shows the command's own keyboard shortcut, so the palette doubles as a way to learn them.
The three commands most recently run from the palette are listed first, above a separator line, and a toggle command shows its current state as an On/Off badge beside its label. The recent block is filtered like the rest of the list, and is kept per editor for the session.
See [Extend the command palette](#extend-the-command-palette) to register the host application's own commands, hide the built-in ones, or turn the palette off entirely.
### Code Folding
These shortcuts are active only when code folding is enabled:
| Shortcut | Action |
| ------------ | ----------------------------------------------- |
| **Ctrl + .** | Toggle fold of the block at the cursor |
| **Ctrl + K** | Fold all blocks |
| **Ctrl + J** | Unfold all blocks |
You can also click the fold chevrons (▼ / ▶) in the gutter to collapse or expand a block.
When they are configured to appear only on hover (see
[Fold markers](#fold-markers)), move the pointer over the gutter to reveal them.
### LSP Completion
These shortcuts are active only when the LSP completion menu is visible:
| Shortcut | Action |
| --------------------------------- | ----------------------------------- |
| **Arrow Up** | Navigate to previous completion item |
| **Arrow Down** | Navigate to next completion item |
| **Enter** | Confirm and apply selected completion |
| **Escape** | Close completion menu |
| **Arrow Left** / **Arrow Right** | Clear completion menu |
## Usage Examples
### Custom context menu
Custom context-menu actions are identified by stable strings chosen by your
application. Custom entries appear before the built-in editing actions:
```rust
use iced_code_editor::{CodeEditor, ContextMenuEntry};
let editor = CodeEditor::new("fn main() {}", "rust")
.with_custom_context_menu_entries(vec![
ContextMenuEntry::item(
"app.format_document",
"Format document",
)
.with_shortcut("Ctrl+Shift+F"),
ContextMenuEntry::separator(),
ContextMenuEntry::item("app.rename_symbol", "Rename symbol")
.with_enabled(false),
])
.with_default_context_menu_enabled(true);
```
The editor automatically adds a separator between the custom and built-in
groups. Pass `false` to `with_default_context_menu_enabled` to replace the
built-in menu completely. At runtime, use
`set_custom_context_menu_entries` and
`set_default_context_menu_enabled` to update the same configuration.
Handle custom actions in the outer application before forwarding other editor
messages to `CodeEditor::update`:
```rust
match event {
EditorMessage::CustomContextMenuAction(id) => {
match id.as_str() {
"app.format_document" => format_document(),
"app.rename_symbol" => rename_symbol(),
unknown => {
eprintln!(
"Ignoring unknown context-menu action: {unknown}"
);
}
}
Task::none()
}
other => editor.update(&other).map(Message::EditorEvent),
}
```
Unknown IDs should be ignored or logged explicitly. The editor emits custom
action IDs unchanged and does not interpret or execute them internally.
`EditorMessage` is `#[non_exhaustive]`: new editor features add variants, so a
`match` on it always needs a wildcard arm. Forwarding that arm to
`editor.update`, as above, is what keeps every built-in feature working.
The built-in labels follow the language configured with `set_language`.
Custom-entry labels are supplied by the host application, so localize those
strings before passing them to the editor.
Applications with a real filesystem path can opt into the built-in reveal
request:
```rust
editor.set_reveal_in_file_manager_enabled(file_path.is_some());
match event {
EditorMessage::RevealInFileManager => {
reveal_file(file_path.as_deref());
Task::none()
}
other => editor.update(&other).map(Message::EditorEvent),
}
```
The menu label is platform-specific: **Reveal in Finder** on macOS,
**Reveal in File Explorer** on Windows, and **Open Containing Folder** on
other desktop platforms. The editor only emits the request; the host is
responsible for invoking the operating system and reporting failures. The demo
enables this item for tabs backed by a desktop path and keeps it hidden for
untitled tabs and WebAssembly.
### Extend the command palette
The palette lists the built-in editor commands out of the box. Register your
application's own commands to have them listed first:
```rust
use iced_code_editor::{CodeEditor, ContextMenuItem};
let editor = CodeEditor::new("fn main() {}", "rust")
.with_custom_command_palette_entries(vec![
ContextMenuItem::new("app.open_file", "Open File")
.with_shortcut("Ctrl+O"),
ContextMenuItem::new("app.new_tab", "New Tab"),
]);
```
Entries reuse `ContextMenuItem`, so an action offered in both surfaces is
described once and keeps a single identifier. An entry built with
`with_enabled(false)` is left out of the palette entirely rather than dimmed:
the palette is a search result list, so every row it offers is runnable.
A command that switches a setting can report that setting's state with
`with_status`, which the palette shows as an On/Off badge beside the label:
```rust
use iced_code_editor::ContextMenuItem;
let item = ContextMenuItem::new("app.toggle_format_on_save", "Toggle Format On Save")
.with_status(format_on_save);
```
The badge is a snapshot taken when the entries are registered, so register them
again whenever the setting changes. The context menu ignores the field.
Running a custom entry emits `CommandPaletteAction` carrying its ID. Handle it
in the outer application, exactly like a custom context-menu action:
```rust
match event {
EditorMessage::CustomContextMenuAction(id)
| EditorMessage::CommandPaletteAction(id) => {
match id.as_str() {
"app.open_file" => open_file(),
"app.new_tab" => new_tab(),
unknown => eprintln!("Ignoring unknown action: {unknown}"),
}
Task::none()
}
other => editor.update(&other).map(Message::EditorEvent),
}
```
Built-in commands the editor cannot perform on its own — saving, revealing the
file in the file manager — are emitted the same way they would be if the user
had pressed the shortcut, so the host intercepts them where it already does.
Pass `false` to `with_default_command_palette_enabled` to list only your own
commands, and use `set_command_palette_enabled(false)` to disable the palette
altogether, freeing `Ctrl+Shift+P` for an application-provided one:
```rust
let editor = CodeEditor::new("fn main() {}", "rust")
.with_default_command_palette_enabled(false)
.with_command_palette_enabled(true);
// Or open it from your own menu item:
let task = editor.open_command_palette();
```
The built-in labels follow the language configured with `set_language`;
localize your own entry labels before passing them in.
### Changing Themes
The editor uses **TokyoNightStorm** as the default theme. It automatically adapts to any Iced theme. All 23+ built-in Iced themes are supported:
```rust
use iced_code_editor::theme;
// Apply any built-in Iced theme
editor.set_theme(theme::from_iced_theme(&iced::Theme::TokyoNightStorm));
editor.set_theme(theme::from_iced_theme(&iced::Theme::Dracula));
editor.set_theme(theme::from_iced_theme(&iced::Theme::Nord));
editor.set_theme(theme::from_iced_theme(&iced::Theme::CatppuccinMocha));
editor.set_theme(theme::from_iced_theme(&iced::Theme::GruvboxDark));
// Or use any theme from Theme::ALL
for theme in iced::Theme::ALL {
editor.set_theme(theme::from_iced_theme(theme));
}
```
#### Syntax theme and token colors
Code tokens are colored by a syntect theme. By default it is `base16-ocean`,
in its dark or light variant to match the editor background. Pick another
bundled theme with `Style::syntax_theme_name`, and override the color of
common token kinds with `Style::token_colors`:
```rust
use iced::Color;
use iced_code_editor::{TokenColors, theme};
let mut style = theme::from_iced_theme(&iced::Theme::Dark);
// Any syntect bundled theme: "base16-ocean.dark", "base16-eighties.dark",
// "base16-mocha.dark", "base16-ocean.light", "InspiredGitHub",
// "Solarized (dark)", "Solarized (light)". An unknown name falls back to
// the automatic choice.
style.syntax_theme_name = Some("base16-mocha.dark");
// Recolor token kinds by TextMate scope, across grammars (JSON, YAML,
// JavaScript, Rust, ...). `None` keeps the syntax theme's color.
style.token_colors = TokenColors {
key: Some(Color::from_rgb(0.55, 0.75, 1.0)),
string: Some(Color::from_rgb(0.65, 0.85, 0.5)),
number: Some(Color::from_rgb(0.95, 0.65, 0.4)),
..TokenColors::default()
};
editor.set_theme(style);
```
Object keys (JSON and YAML keys, object-literal keys) take the `key` color
even though they are quoted strings. Tokens that a theme draws as a
background highlight, such as invalid syntax in base16 themes, always fall
back to a legible color, so half-typed code never disappears.
### Adding syntaxes
Languages that syntect (or `two-face`) does not ship can be added at startup, in Sublime Text's
`.sublime-syntax` format. A registered syntax is picked by its `file_extensions`, like the bundled ones,
and is looked up first, so it can also replace a bundled one. Registered syntaxes form a small set of
their own (adding to the bundled set would re-link every bundled grammar, which takes hundreds of
milliseconds): they can include each other by scope (`include: scope:source.zig`), so register the
grammars a definition includes along with it.
```rust
// Before the first editor highlights text: the syntax set is built once per process.
let zig = std::fs::read_to_string("syntaxes/zig.sublime-syntax")?;
let zx = std::fs::read_to_string("syntaxes/zx.sublime-syntax")?; // includes scope:source.zig
iced_code_editor::register_syntaxes([zig.as_str(), zx.as_str()])?;
let editor = iced_code_editor::CodeEditor::new(source, "zx");
```
### Getting and Setting Content
```rust
// Get current content
let content = editor.content();
// Check if content has been modified
if editor.is_modified() {
println!("Editor has unsaved changes");
}
// Mark content as saved (e.g., after saving to file)
editor.mark_saved();
```
### Enable/disable search/replace
The search/replace functionality is **enabled by default**. It can be toggled on or off. When disabled, search shortcuts (Ctrl+F, Ctrl+H, F3) are ignored and the search dialog is hidden:
```rust
// Disable search/replace functionality
editor.set_search_replace_enabled(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("code", "rs")
.with_search_replace_enabled(false);
// Check current state
if editor.search_replace_enabled() {
println!("Search and replace is available");
}
```
This is useful for read-only editors or when you want to provide your own search interface.
### Open search/replace from your own buttons
Besides keyboard shortcuts, you can open or close the dialogs via API:
```rust
// Open search dialog (same as Ctrl+F)
let task = editor.open_search_dialog();
// Open search+replace dialog (same as Ctrl+H)
let task = editor.open_search_replace_dialog();
// Close dialog (same as Esc)
let task = editor.close_search_dialog();
```
Return these tasks from your app `update` function after mapping to your message type.
### Enable/disable line wrapping
Line wrapping is **enabled by default** at viewport width. Long lines can be wrapped automatically at the viewport width or at a fixed column:
```rust
// Enable line wrapping at viewport width
editor.set_wrap_enabled(true);
// Wrap at a fixed column (e.g., 80 characters)
let editor = CodeEditor::new("code", "rs")
.with_wrap_enabled(true)
.with_wrap_column(Some(80));
// Change the wrap column at runtime (`None` = viewport width)
editor.set_wrap_column(Some(100));
assert_eq!(editor.wrap_column(), Some(100));
// Disable wrapping
editor.set_wrap_enabled(false);
// Check current state
if editor.wrap_enabled() {
println!("Line wrapping is active");
}
```
When enabled, wrapped lines show a continuation indicator (↪) in the line number gutter.
The wrap column is measured in narrow-character columns and `Some(0)` is normalized to `Some(1)`. It is kept while wrapping is disabled, so re-enabling wrapping restores it. Changing it while wrapping is enabled resets the horizontal scroll.
### Enable/disable code folding
Code folding is **enabled by default**. Foldable regions are detected from indentation: a line is a fold header when the following non-blank line is more deeply indented (language-agnostic, works for Rust, Python, YAML, etc.). When enabled, a fold margin with clickable chevrons (▼ expanded, ▶ collapsed) is shown in the gutter, and a `⋯` marker appears after a collapsed block header.
```rust
// Disable code folding (chevrons hidden, all lines shown)
editor.set_folding_enabled(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("code", "rs")
.with_folding_enabled(false);
// Check current state
if editor.folding_enabled() {
println!("Code folding is active");
}
```
Folds can also be driven programmatically (useful for your own buttons or commands):
```rust
// Toggle the fold of the block whose header is a given logical line
editor.toggle_fold(0);
// Toggle / fold / unfold the innermost block containing a line
editor.toggle_fold_at(line);
editor.fold_at(line);
editor.unfold_at(line);
// Fold or unfold every block at once
editor.fold_all();
editor.unfold_all();
// Query whether a header line is collapsed
if editor.is_folded(0) {
println!("Block at line 0 is collapsed");
}
```
When folding is disabled, the collapsed state is preserved (so re-enabling restores the previously collapsed blocks) but no lines are hidden.
#### Fold markers
`FoldMarkers` chooses when the chevrons are drawn, and `FoldMarkerPosition`
which side of the line numbers their column sits on:
```rust
use iced_code_editor::{FoldMarkerPosition, FoldMarkers};
// Default: chevrons always visible, between the line numbers and the text.
editor.set_fold_markers(FoldMarkers::Always);
// Show them only while the pointer is over the gutter. Collapsed blocks keep
// their ▶ so hidden content stays discoverable.
editor.set_fold_markers(FoldMarkers::OnGutterHover);
// Never show them: their column is freed and the text moves closer to the
// line numbers. Folding still works with the shortcuts and the API above.
editor.set_fold_markers(FoldMarkers::Never);
// Put the chevron column at the outer edge of the gutter instead.
editor.set_fold_marker_position(FoldMarkerPosition::BeforeLineNumbers);
assert_eq!(editor.fold_marker_position(), FoldMarkerPosition::BeforeLineNumbers);
```
### Enable/disable line numbers
Line numbers are **displayed by default**. They can be hidden to maximize space for code:
```rust
// Hide line numbers
editor.set_line_numbers_enabled(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("code", "rs")
.with_line_numbers_enabled(false);
// Show line numbers (default behavior)
editor.set_line_numbers_enabled(true);
// Check current state
if editor.line_numbers_enabled() {
println!("Line numbers are visible");
}
```
When disabled, the gutter is completely removed (0px width), providing more horizontal space for code display.
### Visible whitespace rendering
Whitespace rendering is **enabled by default**. Spaces are displayed as `·` and tab characters as `→` (with `·` fill to preserve alignment), both drawn in a dimmed color that blends with the active theme.
```rust
// Disable whitespace rendering
editor.set_show_whitespace(false);
// Re-enable it
editor.set_show_whitespace(true);
// Check current state
if editor.show_whitespace() {
println!("Whitespace is visible");
}
```
The whitespace color is derived automatically from the active theme via `Style::whitespace_color` and can be overridden in a custom `Style`.
### Indentation guides
Indentation guides are **enabled by default**. A thin vertical line is drawn at every indentation level, making the nesting of a block visible without following its braces. Their spacing follows the configured `IndentStyle`, so switching from 4 spaces to 2 spaces (or to tabs) moves the guides accordingly.
```rust
// Disable indentation guides
editor.set_show_indent_guides(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("code", "rs")
.with_show_indent_guides(false);
// Check current state
if editor.show_indent_guides() {
println!("Indentation guides are visible");
}
```
Blank lines take the level of the surrounding block, so a blank line *inside* a block keeps its guides while a blank line *between* two blocks does not. Guides are not drawn on wrapped continuation segments, since those restart at the left edge of the code area. The guide color is derived automatically from the active theme via `Style::indent_guide_color` and can be overridden in a custom `Style`.
### Inline color previews
Inline color previews are **enabled by default**. Every color literal in the visible text gets a small square, filled with the color it denotes, drawn just after it — so a palette can be read at a glance instead of decoded by eye.
The recognized notations are:
| Notation | Examples |
| --- | --- |
| CSS hexadecimal | `#f0c`, `#f008`, `#1e1e2e`, `#ff000080` |
| Rust-style hexadecimal | `0x3A7BD5`, `0xFF6B6BCC` |
| Functional | `rgb(58, 123, 213)`, `rgba(255, 0, 0, 0.5)`, `rgb(100%, 0%, 50%)` |
```rust
// Disable inline color previews
editor.set_show_color_previews(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("body { color: #f0c; }", "css")
.with_show_color_previews(false);
// Check current state
if editor.show_color_previews() {
println!("Color previews are visible");
}
```
Detection is purely lexical, so a literal inside a comment or a string gets a swatch too — which is what a reader looking for colors expects. Runs of hexadecimal digits of any other length are rejected (`#12345` is not a color), and a literal that continues an identifier (`raw0xff0000`) is ignored. The swatch is drawn as geometry and Iced renders all text above all geometry, so the character following the literal stays readable even when the square extends under it. Its frame uses `Style::gutter_border`, and translucent colors are composited over `Style::background`.
### Sticky scroll
Sticky scroll is **enabled by default**. While scrolling deep inside a long block, the header lines of the blocks enclosing the topmost visible line stay pinned at the top of the viewport, outermost first — so the structural context (which `impl`, which function, which `match`) never leaves the screen. Clicking a pinned header scrolls back to that line; the cursor and the selection are left untouched.
```rust
// Disable sticky scroll
editor.set_sticky_scroll_enabled(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new(source, "rs")
.with_sticky_scroll_enabled(false);
// Check current state
if editor.sticky_scroll_enabled() {
println!("Enclosing block headers are pinned");
}
```
At most five headers are pinned at once, so a deeply nested block cannot bury the code being read. Enclosing blocks are detected from **indentation**, exactly like code folding: the feature needs no language grammar and works on any file, but it follows how the file is indented rather than how it parses. Only the detection is shared — the two features are independently toggled, so `set_folding_enabled(false)` removes the fold chevrons and leaves the pinned headers in place. Pinned headers keep the syntax colors, range styles and virtual text of the code they mirror, reusing the per-line highlight cache, and stay anchored to the gutter instead of following the horizontal scroll, so they remain readable when a long line is scrolled sideways.
### Indentation
Auto-indentation is **enabled by default**: pressing Enter copies the leading whitespace of the current line to the new line. The indentation style (spaces or tab) is **4 spaces by default** and controls what is inserted when pressing Tab.
```rust
// Disable auto-indentation on Enter
editor.set_auto_indent_enabled(false);
// Check current state
if editor.auto_indent_enabled() {
println!("Auto-indentation is active");
}
```
```rust
use iced_code_editor::IndentStyle;
// Use 2 spaces per indent level
editor.set_indent_style(IndentStyle::Spaces(2));
// Use tabs instead of spaces
editor.set_indent_style(IndentStyle::Tab);
// Restore the default (4 spaces)
editor.set_indent_style(IndentStyle::Spaces(4));
// Check current style
match editor.indent_style() {
IndentStyle::Spaces(n) => println!("Indenting with {n} spaces"),
IndentStyle::Tab => println!("Indenting with tabs"),
}
```
Available styles via `IndentStyle::ALL`: `Spaces(2)`, `Spaces(4)`, `Spaces(8)`, `Tab`.
### Auto-closing brackets/quotes
Auto-closing is **enabled by default**. Typing an opening bracket or quote (`(`, `[`, `{`, `"`, `'`) auto-inserts its matching closing character with the cursor placed between them; typing the closing character right after an already-inserted match moves the cursor past it instead of duplicating it; and typing an opening bracket/quote while text is selected wraps the selection in the pair instead of replacing it.
```rust
// Disable auto-closing of brackets/quotes
editor.set_auto_close_brackets(false);
// Check current state
if editor.auto_close_brackets() {
println!("Auto-closing is active");
}
```
### Matching bracket/quote highlight
Matching bracket/quote highlight is **enabled by default**. Placing the cursor next to a bracket (`(`, `)`, `[`, `]`, `{`, `}`) or a quote (`"`, `'`) highlights it and its matching pair.
```rust
// Disable the matching bracket/quote highlight
editor.set_bracket_match_highlight_enabled(false);
// Check current state
if editor.bracket_match_highlight_enabled() {
println!("Matching bracket/quote highlight is active");
}
```
### Bracket-pair colorization
Bracket-pair colorization is **enabled by default**. Each `(`, `)`, `[`, `]`, `{`, `}` is colored by its nesting depth, so a matching pair always shares the same color, cycling through a fixed palette (gold, orchid, light sky blue) as depth increases.
```rust
// Disable bracket-pair colorization
editor.set_bracket_pair_colorization_enabled(false);
// Check current state
if editor.bracket_pair_colorization_enabled() {
println!("Bracket-pair colorization is active");
}
```
### Virtual text
Virtual text is drawn inside a line without being part of the buffer, which suits LSP inlay hints or inline debug values. Each source owns a named layer, so it can replace its items without touching the others:
```rust
use iced::Color;
use iced_code_editor::{CodeEditor, VirtualText};
let mut editor = CodeEditor::new("let total = 1;", "rs");
// Draw `: u32` before the character at column 9
editor.set_virtual_text("inlay-hints", vec![VirtualText {
line: 0,
column: 9,
text: ": u32".to_string(),
color: Color::from_rgb(0.5, 0.5, 0.5),
}]);
assert_eq!(editor.virtual_text("inlay-hints").len(), 1);
// Remove this layer only
editor.clear_virtual_text("inlay-hints");
```
- The text pushes the rest of the line to the right. A column at or past the end of the line draws it after the last character.
- With line wrapping, a piece is never split: it moves to the next row with the character that follows it, or with the last character at the end of a line. A piece wider than a whole row extends past the wrap width.
- Sticky scroll headers show the virtual text of the line they pin.
- The cursor steps over it, and copy, `content()` and the LSP sync never see it.
- Lines and columns are 0-based and count characters. The text must fit on one line.
- Positions do not follow edits: replace the layer after a change. Until then, an item on a line past the end of the buffer is not drawn.
Virtual text is **displayed by default** and can be hidden per editor. While hidden it takes no space, but the layers are still stored: showing it again displays the current layers at once.
```rust
// Hide virtual text
editor.set_virtual_text_enabled(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("code", "rs")
.with_virtual_text_enabled(false);
// Check current state
if editor.virtual_text_enabled() {
println!("Virtual text is shown");
}
```
### Range styles
A range style recolors part of a line over the syntax highlighting, which suits LSP semantic tokens or highlighted references. Layers work as they do for virtual text. `scope_color` returns the color that the current theme gives a TextMate scope, so the ranges match the rest of the code:
```rust
use iced_code_editor::{CodeEditor, RangeStyle};
let mut editor = CodeEditor::new("fn main() {}", "rs");
if let Some(color) = editor.scope_color("entity.name.function") {
// Columns 3 to 7, end exclusive
editor.set_range_styles("semantic-tokens", vec![RangeStyle {
line: 0,
start: 3,
end: 7,
color,
}]);
}
// Remove this layer only
editor.clear_range_styles("semantic-tokens");
```
- A style changes colors only, so the cursor, selection and wrapping are not affected.
- Sticky scroll headers show the range styles of the line they pin.
- Where styles overlap, layers later in name order win, then later styles within a layer.
- `scope_color` returns `None` when the scope name is invalid, when the theme has no rule for the scope, or when the color would not stand out from the background.
- Positions do not follow edits: replace the layer after a change. Until then, a range past the end of its line is cut there.
### Language Server Protocol (LSP)
LSP support provides hover documentation, auto-completion, go-to-definition, document formatting, and diagnostics. It requires the `lsp-process` feature (not available on WASM):
```toml
[dependencies]
iced-code-editor = { version = "0.7", features = ["lsp-process"] }
```
#### Enable/disable LSP on an editor
```rust
// Enable LSP (attach a client and open the document)
editor.set_lsp_enabled(true);
// Disable LSP (detach the client)
editor.set_lsp_enabled(false);
```
#### Connecting an LSP server
```rust
use std::sync::mpsc;
use iced_code_editor::{
LspProcessClient, LspEvent, LspDocument, LSP_EVENT_QUEUE_CAPACITY,
};
// Create a channel to receive LSP events. It must be *bounded*: it is fed by
// a language server your application does not control, and an unbounded queue
// turns a chatty server into unbounded memory. When it fills, the client drops
// events rather than blocking the thread that drains the server's stdout —
// every event is a UI update superseded by the next one, so nothing is lost
// but a refresh.
let (tx, rx) = mpsc::sync_channel::<LspEvent>(LSP_EVENT_QUEUE_CAPACITY);
// Start the server (e.g., lua-language-server)
let client = LspProcessClient::new_with_server(
"file:///path/to/project",
tx,
"lua-language-server",
)?;
// Attach the client to an editor with a document URI
editor.attach_lsp(
Box::new(client),
LspDocument::new("file:///path/to/file.lua", "lua"),
);
```
#### Rendering the overlay (hover + completion)
Use `LspOverlayState` to hold display state and `view_lsp_overlay` to render it:
```rust
use iced_code_editor::{LspOverlayState, LspOverlayMessage, view_lsp_overlay};
struct App {
editor: CodeEditor,
overlay: LspOverlayState,
}
#[derive(Clone)]
enum Message {
LspOverlay(LspOverlayMessage),
// ...
}
fn view(app: &App) -> Element<'_, Message> {
// Stack the overlay on top of the editor
stack![
app.editor.view().map(Message::EditorEvent),
view_lsp_overlay(
&app.overlay,
&app.editor,
&app.theme,
14.0, // font size
20.0, // line height
Message::LspOverlay,
),
].into()
}
```
Poll `LspEvent`s from the channel on each tick and update the overlay state:
```rust
// On LspEvent::Hover
overlay.show_hover(text);
// On LspEvent::Completion
overlay.set_completions(items, cursor_position);
// On LspEvent::Diagnostics (see "Diagnostic underlines" below)
editor.set_diagnostics(diagnostics);
```
#### Formatting the document
Ask the server to reformat the whole buffer, then apply the edits it sends
back. The request is fire-and-forget like every other one: the reply arrives as
an `LspEvent::Formatting`, so the two halves live in different places.
```rust
// Trigger it from a menu entry, a shortcut, or just before saving.
// The formatting options follow the editor's own `IndentStyle`.
editor.lsp_request_formatting();
// On LspEvent::Formatting { uri, edits }
// Applies the whole batch as one undo step, keeping the cursor in place.
editor.apply_lsp_text_edits(&edits);
```
`apply_lsp_text_edits` returns `false` — leaving the buffer untouched — when
the reply changes nothing, or when its edits overlap (which LSP forbids).
For *format on save*, send the request first and write the file once the edits
have been applied. Give that wait a deadline: a server that never answers must
not be able to swallow the save. The demo app does this with a two-second
timeout, after which it writes the file unformatted.
#### Diagnostic underlines
The editor draws a wavy underline under each diagnostic range, colored by
severity. The types are always available: the `lsp-process` feature is not
required, so diagnostics can come from any source (a compiler, a linter, a
server of your own).
```rust
use iced_code_editor::{Diagnostic, DiagnosticSeverity, LspPosition, LspRange};
editor.set_diagnostics(vec![Diagnostic::new(
// Zero-based line, character columns; the end is exclusive.
LspRange {
start: LspPosition { line: 0, character: 4 },
end: LspPosition { line: 0, character: 8 },
},
DiagnosticSeverity::Error,
"cannot find value `name` in this scope",
)
// Optional: the tool that reported it
.with_source("rustc")]);
assert_eq!(editor.diagnostics().len(), 1);
// Clear them
editor.set_diagnostics(Vec::new());
```
Diagnostics are **enabled by default** and can be turned off per editor. While
disabled, nothing is underlined and `diagnostics_at` returns nothing, but the
list is still stored: enabling them again shows the current diagnostics at once,
without waiting for the server to publish again.
```rust
// Hide diagnostics (underlines and hover messages)
editor.set_diagnostics_enabled(false);
// Or use builder pattern during initialization
let editor = CodeEditor::new("code", "rs")
.with_diagnostics_enabled(false);
// Check current state
if editor.diagnostics_enabled() {
println!("Diagnostics are shown");
}
```
- Columns count characters, not UTF-16 code units.
- The list replaces the previous one, and the editor does not move the ranges
when the text is edited. Send a new list each time the source publishes one.
- Underlines follow wrapped lines. An empty range underlines one character.
- The colors come from `Style::diagnostic_error_color`,
`diagnostic_warning_color`, `diagnostic_information_color` and
`diagnostic_hint_color`. `theme::from_iced_theme` takes them from the danger,
warning, primary and secondary colors of the iced palette.
With `LspProcessClient`, the server's `textDocument/publishDiagnostics`
notifications arrive as `LspEvent::Diagnostics`, already converted to character
columns. Route each one to the editor that has the document open:
```rust
// On LspEvent::Diagnostics { uri, diagnostics }
for editor in &mut editors {
if editor.lsp_document_uri() == Some(uri.as_str()) {
editor.set_diagnostics(diagnostics.clone());
}
}
```
Only documents opened through the client are reported. An empty list means the
server cleared the document's diagnostics.
To show the messages on hover, look up the diagnostics under the pointer and
display them in your tooltip, for example above the server's hover text in the
LSP overlay:
```rust
// On EditorMessage::MouseHover(point)
if let Some(position) = editor.lsp_position_at_point(point) {
for diagnostic in editor.diagnostics_at(position) {
// `source` names the tool that reported it, e.g. "rustc" or "clippy"
let source = diagnostic.source.as_deref().unwrap_or("unknown");
println!("{:?} ({source}): {}", diagnostic.severity, diagnostic.message);
}
}
```
`diagnostics_at` returns every diagnostic whose range covers the position, in
the order they were set. `LspProcessClient` fills `message` and `source` from
the server's diagnostic. The demo app shows them in the hover tooltip, even
when no language server is attached, and adds the server's hover text below a
separator when it arrives.
#### Supported servers
Out of the box, the following servers are supported (the binary must be on `$PATH`):
| Server key | Language |
| ---------------------------- | -------- |
| `rust-analyzer` | Rust |
| `pyright` | Python |
| `typescript-language-server` | JS / TS |
| `lua-language-server` | Lua |
| `gopls` | Go |
### Changing font
The default font of the editor is `iced::Font::MONOSPACE`. It can be changed with one of the default `iced` font or by loading a specific font:
```rust
let font = iced::font::Family::SansSerif;
editor.set_font(font);
```
> The editor support CJK font.
The default font size is **14px**. It can be changed:
```rust
editor.set_font_size(12.0, true);
```
## Themes
The editor natively supports all built-in Iced themes with automatic color adaptation.
Each theme automatically provides:
- Optimized background and foreground colors
- Adaptive gutter (line numbers) styling
- Appropriate text selection colors
- Themed cursor appearance
- Custom scrollbar styling
- Diagnostic underline colors per severity
- Subtle current line highlighting
The editor intelligently adapts colors from the Iced theme palette for optimal code readability.


## Supported Languages
The editor supports syntax highlighting for numerous languages via the `syntect` crate:
- **Rust** (`"rs"` or `"rust"`)
- **Python** (`"py"` or `"python"`)
- **JavaScript/TypeScript** (`"js"`, `"javascript"`, `"ts"`, `"typescript"`)
- **Lua** (`"lua"`)
- **C/C++** (`"c"`, `"cpp"`, `"c++"`)
- **Java** (`"java"`)
- **Go** (`"go"`)
- **HTML/CSS** (`"html"`, `"css"`)
- **Markdown** (`"md"`, `"markdown"`)
- And many more...
For a complete list, refer to the [syntect documentation](https://docs.rs/syntect/).
## Demo Application
A full-featured demo application is included in the `demo-app` directory, showcasing:
- File operations (open, save, save as)
- Theme switching
- Fold markers shown on gutter hover (`FoldMarkers::OnGutterHover`)
- Modified state tracking
- Clipboard operations
- Full keyboard navigation
- LSP integration: hover, completion, go-to-definition, format on save, and
diagnostic underlines whose messages and sources appear in the hover tooltip
- Virtual text and range styles: pick the **Decorations** template to see inlay
hints and semantic colors that are replaced after each edit, and use the
**Show inlay hints** option to hide the hints
Run it with:
```bash
cargo run --package demo-app --release
```
## Simple Example
A minimal standalone example is available in the `simple-example` directory. It demonstrates the basic integration pattern with a `text_input` sibling widget and focus management:
```bash
cargo run --package simple-example
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Check [docs\DEV.md](https://github.com/LuDog71FR/iced-code-editor/blob/main/docs/DEV.md) for more details.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Acknowledgments
- Built with [Iced](https://github.com/iced-rs/iced) - A cross-platform GUI library for Rust
- Syntax highlighting powered by [syntect](https://github.com/trishume/syntect)