20 KiB
Buffer Types Architecture
Problem
The current design uses a magic constant COMMAND_BUFFER_ID = BufferId(999) to identify the command buffer. The core checks == COMMAND_BUFFER_ID in ~6 places to decide special behavior (clear on focus/unfocus, keep main view stable, special rendering). This is brittle and doesn't generalize -- if we want other special-purpose buffers (finder, prompt, help), each would need its own magic constant and special-case checks.
Goal: Make "command buffer" a property that any buffer could have, so the editor reasons about buffer capabilities and roles rather than buffer identity.
Prior Art
Neovim: Explicit buftype
Neovim has an explicit, enumerated buftype option on each buffer:
| Value | Description |
|---|---|
"" (empty) |
Normal file-visiting buffer. Standard read/write/save. |
"nofile" |
Not associated with a file. :w doesn't work. Never considered "modified". Used for scratch buffers, plugin UI panels. |
"nowrite" |
Like nofile but buffer name is treated as a file path (changes with :cd). |
"acwrite" |
Custom write semantics via autocommands. :w triggers BufWriteCmd instead of file I/O. Used by netrw, database editors, REST clients. |
"quickfix" |
Quickfix/location list. Managed by Neovim's quickfix system. Read-only. |
"help" |
Help documentation. Read-only, special tag navigation. |
"terminal" |
Terminal emulator. Hosts a PTY subprocess. Special input handling. |
"prompt" |
Only the last line is editable. Enter invokes a callback. Used for REPL-style interfaces. |
buftype works in concert with other buffer-local options:
bufhidden-- what happens when buffer leaves all windows (hide,unload,delete,wipe)buflisted-- whether buffer appears in:lsand:bnextswapfile-- whether a swap file is createdmodifiable-- whether text can be changed
A typical special buffer combines these: buftype=nofile, bufhidden=wipe, nobuflisted, noswapfile, nomodifiable.
Key property of Neovim's approach: The set of buftypes is finite and known to the editor core. Each type changes how the core handles the buffer (whether :w works, whether the buffer is considered modified, how the name is interpreted). New buffer "kinds" are composed from these primitives rather than adding new enum variants.
Emacs: Emergent Type from Major Modes + Buffer-Local Variables
Emacs has no explicit buffer type enum. A buffer's "type" is emergent from:
- Its major mode (defines behavior, keybindings, syntax)
- Buffer-local variables (configure that behavior per-buffer)
- Whether it visits a file (
buffer-file-name) - Whether it is read-only (
buffer-read-only) - Whether it has an associated process
Major Modes
Every buffer has exactly one major mode. Modes form an inheritance hierarchy rooted in three base modes:
text-mode-- human-language editing (org-mode, markdown-mode, etc.)prog-mode-- programming languages (rust-mode, python-mode, etc.)special-mode-- Emacs-generated content, not files. Automatically read-only. Definesqto quit,gto revert. Parent of help-mode, compilation-mode, dired-mode, etc.
Plus fundamental-mode as the zero state.
define-derived-mode creates a child mode that inherits its parent's keymap, syntax table, and hooks. When activated, modes run parent body first, then child, and hooks fire from ancestors down. This is how you get modes like compilation-mode that inherit special-mode's read-only behavior and q-to-quit binding while adding their own error-navigation commands.
Buffer-Local Variables
Any Emacs variable can have a per-buffer binding. Built-in permanently buffer-local variables include major-mode, buffer-file-name, buffer-read-only, tab-width, indent-tabs-mode, mode-line-format, and many others. When a major mode activates, it calls kill-all-local-variables (reset), then sets up its own buffer-local bindings for things like comment-start, indent-line-function, font-lock-defaults, etc.
This means two buffers in the same major mode can still behave differently based on their other variable values. Buffer "type" is a continuous, multi-dimensional property space rather than a discrete enum.
The Minibuffer
The minibuffer is the closest analog to our command buffer. It is implemented as a real buffer (*Minibuf-N*) but with unique constraints:
- Displayed only in a dedicated minibuffer window (always at the bottom of the frame)
- When not active, uses
minibuffer-inactive-mode; when active, installs context-dependent keymaps (minibuffer-local-map,minibuffer-local-completion-map, etc.) - Recursive minibuffers: when a command invokes the minibuffer while one is already active, a new minibuffer buffer is created (
*Minibuf-2*, etc.). The innermost is active; exiting it restores the previous. Controlled byenable-recursive-minibuffers. - The minibuffer window doubles as the echo area when not in use for input (displaying messages, which are also logged to
*Messages*)
The minibuffer is "just a buffer" in that it supports editing commands and has text content, but it has special protections (can't be killed/renamed, dedicated window, special activation semantics).
Special Buffers
Special buffers in Emacs are distinguished by convention and properties, not by a type field:
| Buffer | Mode | Key Properties |
|---|---|---|
*scratch* |
lisp-interaction-mode |
No file, writable, evaluates Lisp |
*Messages* |
messages-buffer-mode |
Read-only, auto-maintained log |
*Help* |
help-mode |
Read-only, hyperlinks, back/forward navigation |
*Completions* |
completion-list-mode |
Read-only, navigable candidate list |
*compilation* |
compilation-mode |
Read-only, clickable source locations |
| Shell buffers | shell-mode (via comint-mode) |
Associated subprocess, input ring |
| Terminal buffers | term-mode |
Full VT100 emulation, char/line sub-modes |
| Dired buffers | dired-mode |
Directory listing, file operations |
Key property of Emacs's approach: Completely open-ended. New buffer "types" are invented by writing a new major mode -- the editor core doesn't need to know about them in advance. But this means the core can't reason abstractly about buffer categories without checking specific mode identities.
Kakoune
The prompt line is a regular buffer that supports normal editing commands. You can use movement, selection, and editing primitives to compose your command — the same muscle memory works everywhere. This is a notable improvement over Vim, where the command line is a separate input context with its own limited editing model. (Vim's q: cmdwin partially addresses this but is clunky.)
Xi Editor
Every view is just a buffer with metadata attached. No special-cased IDs.
Command Palettes (VS Code, Sublime, etc.)
The command palette pattern treats command input as a prominent UI element — typically a floating centered or top-anchored panel with:
- Real-time filtering/fuzzy matching
- Hints and documentation alongside candidates
- Categorized results (commands, files, symbols, etc.)
The key insight is that this is a presentation concern. The underlying buffer holding the user's input text is the same regardless of whether it renders as a vim-style bottom line or a centered floating palette. The pane layout / rendering layer decides how and where to display it.
Decomposing the Command Buffer
Before choosing an approach, it's worth asking: what actually makes the command buffer special? Here's every special behavior in the current code, and what property would express it:
| Current behavior | Where | Property |
|---|---|---|
| Always in Insert mode | core.rs:69 — set_mode(Mode::Insert) at creation |
Remove this. Command buffer should support Normal mode like any other buffer (Kakoune-style). You should be able to hjkl around and edit your command. |
Enter submits instead of inserting \n |
configuration.rs:49 — (Mode::Insert, true) => Command(Execute) |
Submit behavior lives in the input mapping layer (Configuration / future DSL), keyed off buffer properties. Not inherently tied to single-line — a multi-line command buffer could submit on e.g. Ctrl+Enter or a keybinding. |
| Escape returns to previous buffer | configuration.rs:58 — (_, true) => FocusPreviousBuffer |
ephemeral: true (Escape on ephemeral buffer = defocus) |
| Tab triggers completion | configuration.rs:62 — (Mode::Insert, true) => Command(Tab) |
Tab behavior is context-dependent, lives in input mapping |
| Cleared on focus | core.rs:254 — clears when target == COMMAND_BUFFER_ID |
ephemeral: true |
| Cleared on defocus | core.rs:265 — clears when leaving command buffer |
ephemeral: true |
| Doesn't replace main display | core.rs:115 — main_display_buffer() skips it |
listed: false (unlisted buffers don't claim the main editing area) |
| Not in tab bar | implicit | listed: false |
Almost every behavior decomposes into generic properties (ephemeral, listed). But there is one irreducible property: this buffer's contents are commands to be interpreted by the editor's command system. That's not the same as "ephemeral" — a finder buffer is ephemeral too, but submitting it opens a file rather than executing a command. The core needs to know which buffer to read command text from when CommandAction::Execute fires, and that's a property of the buffer itself: command: bool.
What Vim Gets Wrong Here
In Vim, the command line (: prompt) is a separate input context with its own limited editing model. You can't use Normal mode motions to edit your command — only basic readline-style bindings. Vim's q: cmdwin partially addresses this by opening an actual buffer, but it's a separate workflow. This is an unnecessary inconsistency.
In pane-editor, the command buffer is just a buffer. It starts in Insert mode (because you're typing a command), but you can Escape to Normal mode and use the full editing vocabulary — hjkl, word motions, etc. — then i back to Insert to keep typing. The same keybindings, the same muscle memory, everywhere.
Design: Properties-Only (Emacs-like)
Drop BufferKind entirely. Buffer behavior is determined by composable properties on TextBuffer. The properties are minimal — they capture what the core needs to know to handle buffer lifecycle. Everything else (keybindings, submit behavior, rendering position) lives in other layers.
Three Layers of "Buffer Behavior"
It's important to separate what lives where:
-
Buffer properties (on
TextBuffer) — intrinsic buffer state that the core needs for lifecycle management: Is it listed? Is it ephemeral? Is it read-only? Does it have a backing file? -
Input mapping (in
Configuration/ future DSL) — what keystrokes do in a given buffer context. Enter submits vs inserts newline. Tab completes vs inserts tab. Escape defocuses vs transitions to Normal mode. This is user-configurable and can vary per buffer properties, per mode, per anything. -
Presentation (in pane layout / rendering) — where and how a buffer is displayed. Bottom command line vs centered floating palette vs side panel. This is orthogonal to both buffer properties and input mapping.
This separation is what makes it possible to have the same command buffer render as a vim-style bottom line OR a VS Code-style command palette — the buffer doesn't change, only the pane layout does.
Buffer Properties
struct BufferProperties {
/// Buffer appears in tab bar / buffer list and claims the main editing area.
listed: bool,
/// Buffer is cleared on focus and defocus. No unsaved-changes warning.
ephemeral: bool,
/// Buffer contents cannot be modified. Mode::Insert doesn't apply —
/// `TransitionToMode(Mode::Insert)` is a no-op on a read-only buffer.
read_only: bool,
/// Buffer contents are interpreted as editor commands on submit.
/// The core reads this buffer's text when CommandAction::Execute fires.
command: bool,
}
Four properties. Note what's not here:
- No
single_line. Whether a buffer is constrained to one line is a rendering/UI concern, not an intrinsic buffer property. A command buffer could be single-line in a vim-style bottom bar and multi-line in a command palette. The buffer itself doesn't care. - No
on_submitcallback. Thecommandflag tells the core where submission goes (the command system). The input mapping layer decides when submission happens (Enter, Ctrl+Enter, whatever). Other buffer types (finder, prompt) would have their own semantic flags and their own submit routing. - No mode override. The command buffer supports Normal mode just like any other buffer. It starts in Insert mode because that's natural, but you can Escape to Normal, edit with motions, and
iback.
Constructing Buffers by Role
Convenience constructors express common configurations:
impl BufferProperties {
/// A normal file-editing buffer.
fn document() -> Self {
BufferProperties { listed: true, ephemeral: false, read_only: false, command: false }
}
/// A command-line input buffer (the `:` prompt).
fn command() -> Self {
BufferProperties { listed: false, ephemeral: true, read_only: false, command: true }
}
/// A read-only informational buffer (help text, about, etc.)
fn info() -> Self {
BufferProperties { listed: false, ephemeral: false, read_only: true, command: false }
}
}
A "finder" buffer is { listed: false, ephemeral: true, read_only: false, command: false } — ephemeral like a command buffer, but its submit action is "open the selected file" (handled by finder-specific logic, not the command system). A "scratch" buffer is document() with no backing file.
How the Core Uses Properties
The core never asks "is this the command buffer?" — it asks about capabilities:
// Instead of: if target == COMMAND_BUFFER_ID { self.clear_command_buffer(); }
if buffer.properties.ephemeral {
buffer.clear();
}
// Instead of: if self.active_buffer == COMMAND_BUFFER_ID { return previous }
if !active_buffer.properties.listed {
// unlisted buffer doesn't claim the main display area
return self.previous_buffer();
}
// Instead of: force Insert mode on command buffer
// Nothing. The buffer starts in whatever mode it starts in. Mode transitions
// are handled normally. read_only buffers reject TransitionToMode(Insert).
How Configuration Uses Properties
Configuration::get_editor_action receives &BufferProperties instead of a BufferId:
fn get_editor_action(&self, input: Input, props: &BufferProperties, mode: Mode, ...) {
match input {
// Escape in an ephemeral buffer defocuses. In a non-ephemeral buffer,
// transitions to Normal (from Insert) or is a no-op (already Normal).
Input::Escape if props.ephemeral => FocusPreviousBuffer,
Input::Escape => match mode {
Mode::Insert => TransitionToMode(Mode::Normal),
Mode::Normal => None,
},
// Enter in Insert mode in a command buffer submits to the command system.
// In a non-command buffer, inserts a newline. The future DSL will allow
// full customization of this per buffer property.
Input::Newline => match (mode, props.command) {
(Mode::Insert, true) => Command(CommandAction::Execute),
(Mode::Insert, false) => InsertCharacter('\n'),
_ => None,
},
// Normal mode works everywhere — hjkl, i, etc.
// The same bindings apply in a command buffer as in a document buffer.
Input::Character(ch) => match mode {
Mode::Insert if !props.read_only => InsertCharacter(ch),
Mode::Normal if ch == 'i' && !props.read_only => TransitionToMode(Mode::Insert),
Mode::Normal if ch == ':' => FocusCommandBuffer,
// hjkl etc. — same in all buffers
// ...
},
// ...
}
}
Notice: is_command (the identity check) disappears. The configuration checks props.command, props.ephemeral, and props.read_only — meaningful properties, not magic IDs. The same Normal mode keybindings work in every buffer.
Mode and read_only Interaction
Mode::Insert simply doesn't apply to a read-only buffer:
TransitionToMode(Mode::Insert)is a no-op (or never generated — Configuration checksread_onlybefore emitting it)- The buffer is always effectively in Normal mode
- This covers help buffers, about screens, etc. naturally
What About the Future DSL?
All of the hardcoded match arms in Configuration are temporary. The future scripting/DSL layer will allow users to define arbitrary input mappings per buffer property, per mode, per any predicate. The point of BufferProperties is that it provides stable, meaningful predicates for those mappings to key off of — not to encode behavior directly.
What Changes
-
Add
BufferPropertiestoTextBuffer. Four fields:listed,ephemeral,read_only,command. Plus convenience constructorsdocument(),command(),info(). -
Remove
COMMAND_BUFFER_IDconstant. Buffer identity no longer implies role. -
Remove forced
set_mode(Mode::Insert)on command buffer. The command buffer starts in Insert mode naturally (theFocusBufferaction could transition to Insert, or it just stays in whatever mode — the user can switch freely). -
Replace identity checks with property checks in
EditorCore:main_display_buffer()checks!listedinstead of== COMMAND_BUFFER_IDFocusBufferclears buffer ifephemeralinstead of== COMMAND_BUFFER_IDFocusPreviousBufferclears buffer ifephemeralcommand_buffer()/command_buffer_is_active()become property-based queries or go away entirely
-
Update
Configuration:- Receives
&BufferPropertiesinstead ofBufferId - Checks
props.command,props.ephemeral,props.read_onlyinstead ofis_command - No longer imports
COMMAND_BUFFER_ID - Normal mode keybindings work uniformly across all buffers
- Receives
-
Core tracks command buffer by
Option<BufferId>rather than a constant. Set when a command buffer is created/focused, cleared when it's destroyed.
Open Questions
- Lazy vs eager creation. Should the command buffer be created lazily (only when
:is pressed) or eagerly at startup? Currently eager. Lazy creation means the command buffer is truly "just another buffer" that gets created and destroyed on demand, but adds complexity to the:keybinding path. - Presentation layer. Rendering is currently driven by pane layout position (the command pane is always at the bottom).
BufferPropertiesshould not dictate rendering — the sameephemeralbuffer could render as a bottom bar or a floating palette depending on pane layout configuration. Is the current pane layout system flexible enough for this, or does it need extension? - Label / prompt prefix. The
:prefix in the command line is a rendering concern. Should there be alabel: Option<String>on the buffer or on the pane layout entry? Probably the latter (presentation, not buffer state). - Submit semantics.
command: truetells the core where submission goes (the command system). But what about non-command buffers that also have submit behavior (finder, prompt)? Each would need its own flag, or there could be a more generalsubmit_target: Option<SubmitTarget>enum. For nowcommand: boolis sufficient — generalize when a second submit target actually appears. - History. Vim's command line has history (up/down to cycle previous commands). If the command buffer is ephemeral (cleared on focus), history would need to live outside the buffer — in the command system. This is probably the right place for it anyway.