Skip to main content

iced_code_editor/
lib.rs

1//! A high-performance code editor widget for Iced.
2//!
3//! This crate provides a canvas-based code editor with syntax highlighting,
4//! line numbers, and text selection capabilities for the Iced GUI framework.
5//!
6//! # Features
7//!
8//! - **Syntax highlighting** for multiple programming languages
9//! - **Line numbers** with styled gutter
10//! - **Text selection** via mouse drag and keyboard
11//! - **Clipboard operations** (copy, paste)
12//! - **Custom scrollbars** with themed styling
13//! - **Focus management** for multiple editors
14//! - **Dark & light themes** support with customizable colors
15//! - **Undo/Redo** with command history
16//! - **Command palette** (`Ctrl+Shift+P`), extensible with the host's own commands
17//! - **Optional Vim mode** with Normal, Insert, Visual, and Visual Line modes
18//!
19//! # Example
20//!
21//! ```no_run
22//! use iced::widget::container;
23//! use iced::{Element, Task};
24//! use iced_code_editor::{CodeEditor, Message as EditorMessage};
25//!
26//! struct MyApp {
27//!     editor: CodeEditor,
28//! }
29//!
30//! #[derive(Debug, Clone)]
31//! enum Message {
32//!     EditorEvent(EditorMessage),
33//! }
34//!
35//! impl Default for MyApp {
36//!     fn default() -> Self {
37//!         let code = r#"fn main() {
38//!     println!("Hello, world!");
39//! }
40//! "#;
41//!
42//!         Self { editor: CodeEditor::new(code, "rust") }
43//!     }
44//! }
45//!
46//! impl MyApp {
47//!     fn update(&mut self, message: Message) -> Task<Message> {
48//!         match message {
49//!             Message::EditorEvent(event) => {
50//!                 self.editor.update(&event).map(Message::EditorEvent)
51//!             }
52//!         }
53//!     }
54//!
55//!     fn view(&self) -> Element<'_, Message> {
56//!         container(self.editor.view().map(Message::EditorEvent))
57//!             .padding(20)
58//!             .into()
59//!     }
60//! }
61//!
62//! fn main() -> iced::Result {
63//!     iced::run(MyApp::update, MyApp::view)
64//! }
65//! ```
66//!
67//! # Themes
68//!
69//! The editor supports all native Iced themes with automatic color adaptation:
70//!
71//! ```no_run
72//! use iced_code_editor::{CodeEditor, theme};
73//!
74//! // Create an editor (defaults to Tokyo Night Storm theme)
75//! let mut editor = CodeEditor::new("fn main() {}", "rs");
76//!
77//! // Switch to any Iced theme
78//! editor.set_theme(theme::from_iced_theme(&iced::Theme::Dracula));
79//! editor.set_theme(theme::from_iced_theme(&iced::Theme::CatppuccinMocha));
80//! editor.set_theme(theme::from_iced_theme(&iced::Theme::Nord));
81//! ```
82//!
83//! # Vim Mode
84//!
85//! Vim behavior is disabled by default and configured per editor instance:
86//!
87//! ```
88//! use iced_code_editor::{CodeEditor, VimMode};
89//!
90//! let mut editor =
91//!     CodeEditor::new("fn main() {}", "rs").with_vim_enabled(true);
92//! assert!(editor.vim_enabled());
93//! assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
94//!
95//! editor.set_vim_enabled(false);
96//! assert_eq!(editor.vim_mode(), None);
97//! ```
98//!
99//! A focused editor can toggle Vim behavior with `Ctrl+Alt+V`, or
100//! `Command+Alt+V` on macOS. Regular `Ctrl`/`Command+V` system paste is
101//! unchanged. Counts support both target lines (`5G`/`5gg` jump to logical
102//! line 5) and line operators (`5yy`, `5dd`, and `5cc` affect five lines).
103//! A fixed bottom status line shows the current mode, pending keys, and active
104//! `/pattern` or `:N` input. Submit with Enter, edit with Backspace, or cancel
105//! with Escape. `n` and `N` repeat the last search forward or backward.
106//!
107//! The Vim MVP provides Normal, Insert, Visual, and Visual Line modes; counts;
108//! `h/j/k/l`, word and line motions; `d/c/y`, `x`, `p/P`, and `u`/`Ctrl+R`;
109//! `/` search with `n`/`N`, `:N` line jumps; and a per-editor unnamed register.
110//! It is single-cursor and does not include general Ex commands, regex/search
111//! history, text objects, macros, named registers, marks, `.` repeat, or
112//! configurable mappings. Platform clipboard shortcuts continue to use the
113//! system clipboard instead of the Vim register.
114//!
115//! # Keyboard Shortcuts
116//!
117//! The editor supports a comprehensive set of keyboard shortcuts:
118//!
119//! ## Navigation
120//!
121//! | Shortcut | Action |
122//! |----------|--------|
123//! | **Arrow Keys** (Up, Down, Left, Right) | Move cursor |
124//! | **Shift + Arrows** | Move cursor with selection |
125//! | **Ctrl + Left** / **Ctrl + Right** | Move one word left/right (**Alt** on macOS) |
126//! | **Shift + Ctrl + Left/Right** | Select one word left/right |
127//! | **Home** | Jump to the first non-blank character; press again for column 0 |
128//! | **End** | Jump to end of line |
129//! | **Shift + Home** / **Shift + End** | Select to start/end of line |
130//! | **Ctrl + Home** / **Ctrl + End** | Jump to start/end of document |
131//! | **Page Up** / **Page Down** | Scroll one page up/down |
132//!
133//! ## Editing
134//!
135//! | Shortcut | Action |
136//! |----------|--------|
137//! | **Backspace** | Delete character before cursor (or delete selection if text is selected) |
138//! | **Delete** | Delete character after cursor (or delete selection if text is selected) |
139//! | **Ctrl + Backspace** | Delete the word before the cursor (**Alt** on macOS) |
140//! | **Ctrl + Delete** | Delete the word after the cursor (**Alt** on macOS) |
141//! | **Shift + Delete** | Delete selected text (same as Delete when selection exists) |
142//! | **Enter** | Insert new line |
143//!
144//! ## Clipboard
145//!
146//! | Shortcut | Action |
147//! |----------|--------|
148//! | **Ctrl + C** or **Ctrl + Insert** | Copy selected text |
149//! | **Ctrl + V** or **Shift + Insert** | Paste from clipboard |
150//!
151//! # Supported Languages
152//!
153//! The editor supports syntax highlighting through the `syntect` crate:
154//! - Python (`"py"` or `"python"`)
155//! - Lua (`"lua"`)
156//! - Rust (`"rs"` or `"rust"`)
157//! - JavaScript (`"js"` or `"javascript"`)
158//! - And many more...
159//!
160//! For a complete list, refer to the `syntect` crate documentation.
161//!
162//! # Command History Management
163//!
164//! The [`CommandHistory`] type provides fine-grained control over undo/redo operations.
165//! While the editor handles history automatically, you can access it directly for
166//! advanced use cases:
167//!
168//! ## Monitoring History State
169//!
170//! ```no_run
171//! use iced_code_editor::CommandHistory;
172//!
173//! let history = CommandHistory::new(100);
174//!
175//! // Check how many operations are available
176//! println!("Undo operations: {}", history.undo_count());
177//! println!("Redo operations: {}", history.redo_count());
178//!
179//! // Check if operations are possible
180//! if history.can_undo() {
181//!     println!("Can undo!");
182//! }
183//! ```
184//!
185//! ## Adjusting History Size
186//!
187//! You can dynamically adjust the maximum number of operations kept in history:
188//!
189//! ```no_run
190//! use iced_code_editor::CommandHistory;
191//!
192//! let history = CommandHistory::new(100);
193//!
194//! // Get current maximum
195//! assert_eq!(history.max_size(), 100);
196//!
197//! // Increase limit for memory-rich environments
198//! history.set_max_size(500);
199//!
200//! // Or decrease for constrained environments
201//! history.set_max_size(50);
202//! ```
203//!
204//! ## Clearing History
205//!
206//! You can reset the entire history when needed:
207//!
208//! ```no_run
209//! use iced_code_editor::CommandHistory;
210//!
211//! let history = CommandHistory::new(100);
212//!
213//! // Clear all undo/redo operations
214//! history.clear();
215//!
216//! assert_eq!(history.undo_count(), 0);
217//! assert_eq!(history.redo_count(), 0);
218//! ```
219//!
220//! ## Save Point Tracking
221//!
222//! Track whether the document has been modified since the last save:
223//!
224//! ```no_run
225//! use iced_code_editor::CommandHistory;
226//!
227//! let history = CommandHistory::new(100);
228//!
229//! // After loading or saving a file
230//! history.mark_saved();
231//!
232//! // Check if there are unsaved changes
233//! if history.is_modified() {
234//!     println!("Document has unsaved changes!");
235//! }
236//! ```
237
238// Initialize rust-i18n for the entire crate
239rust_i18n::i18n!("locales", fallback = "en");
240
241mod buffer;
242mod canvas_editor;
243
244pub mod i18n;
245pub mod theme;
246
247/// Hidden re-exports for the `criterion` benchmark harness (`benches/`).
248///
249/// Compiled only with the `bench` feature; not part of the public API.
250#[doc(hidden)]
251#[cfg(feature = "bench")]
252pub use canvas_editor::bench_support;
253pub use canvas_editor::features::folding::FoldRegion;
254/// LSP integration types and traits for editor clients.
255pub use canvas_editor::lsp::{
256    LspClient, LspDocument, LspFormattingOptions, LspPosition, LspRange,
257    LspTextChange, compute_text_change,
258};
259pub use canvas_editor::{
260    ArrowDirection, CodeEditor, CommandHistory, ContextMenuEntry,
261    ContextMenuItem, IndentStyle, Message, VimMode,
262};
263pub use i18n::{Language, Translations};
264pub use theme::{Catalog, Style, StyleFn, from_iced_theme};
265
266#[cfg(all(feature = "lsp-process", not(target_arch = "wasm32")))]
267pub use canvas_editor::lsp::process::{
268    LSP_EVENT_QUEUE_CAPACITY, LspEvent, LspProcessClient,
269};
270
271#[cfg(all(feature = "lsp-process", not(target_arch = "wasm32")))]
272pub use canvas_editor::lsp::process::config::{
273    LspCommand, LspLanguage, LspServerConfig, ensure_rust_analyzer_config,
274    lsp_language_for_extension, lsp_language_for_path, lsp_server_config,
275    resolve_lsp_command,
276};
277
278#[cfg(all(feature = "lsp-process", not(target_arch = "wasm32")))]
279pub use canvas_editor::lsp::process::overlay::{
280    LspOverlayMessage, LspOverlayState, view_lsp_overlay,
281};