Text editing
tvision-rs ships a multi-line text editor and a scrolling terminal view, both
ported faithfully from Turbo Vision. They build on one engine,
Editor (TEditor): a gap-buffer
text editor with a cursor, a selection, single-level undo, word-by-word
navigation, and substring search. You rarely embed Editor directly; you
use one of the three faces it wears.
Three faces of the editor
| Type | Use it for |
|---|---|
Memo (TMemo) | a multi-line edit field inside a dialog |
FileEditor (TFileEditor) | an editor backed by a file on disk |
EditWindow (TEditWindow) | a ready-made window wrapping a FileEditor plus its scrollbars and indicator |
Memo is a thin wrapper over
Editor that does two extra things: it lets a plain Tab fall through
to the dialog's focus navigation (instead of inserting a tab), and it exposes
its text as a typed FieldValue so dialog gather/scatter works
as for any other control.
EditWindow is the one to
start from for an editor application. Its constructor inserts the (initially
hidden) horizontal and vertical scrollbars and the line/column indicator, wires
a FileEditor to them, and
titles the window after the file (or "Untitled"):
#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::widgets::EditWindow;
fn _demo(desktop: &mut tv::Group) {
let bounds = tv::Rect::new(0, 0, 80, 24);
let path = std::path::PathBuf::from("my_file.txt");
let window_number: i16 = 1;
let win = EditWindow::new(bounds, Some(path), window_number);
desktop.insert(Box::new(win));
}
}
Files: loading, saving, and the modified prompt
FileEditor loads its file in
the constructor when you pass a path; a None path is an untitled buffer. It
handles Command::SAVE itself, opens a Save-as file dialog for an untitled
buffer or Command::SAVE_AS, and, through its valid check, puts up the
classic "… has been modified. Save?" Yes/No/Cancel prompt before a dirty
buffer is closed. All of that runs through tvision-rs's deferred message-box and
file-dialog seams, so a single editor view can drive a modal dialog without
owning the event loop (see Deferred effects).
Backup files are off by default; when enabled, tvision-rs appends ~ to the
filename (foo.txt → foo.txt~), following Unix convention instead of the DOS
.bak rename.
Line endings and encoding
Two settings control how text is stored and stepped over:
LineEnding:Lf,CrLf, orCr, deciding the byte sequence written for each line break when text is inserted. tvision-rs defaults toLf(the modern-host default; DOS Turbo Vision defaulted toCrLf).Encoding:Defaultsteps over characters using width-aware (grapheme) logic, so multi-byte UTF-8 and wide glyphs advance the cursor correctly;SingleBytetreats every byte as one column.
The terminal view
Terminal (TTerminal)
is the other text view: a scrolling, ring-buffered output pane that you write into. It implements the
TextDevice trait, so
you append output by calling
write_bytes;
the most recent lines that fit are drawn, and the embedded scroller keeps its
scrollbars in sync. There is no stream wrapper, only the byte sink (the C++
streambuf/otstream layer is not ported).
Because its constructor cannot touch the screen, Terminal follows the
deferred-init pattern: build it, insert it into a group, then call
init once
to set up its limits and cursor.
Edit commands enable themselves
The editor tracks which editing commands make sense for the current state and
enables or disables them on every state change, including when the window gains
or loses focus. The update_commands method (src/widgets/editor.rs) runs after
every edit and on focus change:
| Command | Enabled when |
|---|---|
Command::UNDO | undo history is non-empty (`del_count > 0 |
Command::CUT | there is a selection |
Command::COPY | there is a selection |
Command::PASTE | no clipboard editor active, or clipboard has a selection |
Command::CLEAR | there is a selection |
Command::FIND | always (while the editor is focused) |
Command::REPLACE | always |
Command::SEARCH_AGAIN | always |
Command::SAVE / SAVE_AS | always, for a FileEditor |
The enable/disable changes go through the deferred channel
(ctx.enable_command / ctx.disable_command), so they apply after the current
dispatch. A menu that depends on these commands automatically grays or un-grays
its items at the next pump because the menu's draw reads the current command-set
snapshot.
The clipboard editor (is_clipboard: true) skips cut/copy/paste updates.
It is a special internal editor used for the clipboard window, which should not
compete with the main editor for those commands.
Source: src/widgets/editor.rs (Editor::update_commands, Editor::set_state).
Key bindings
tvision-rs extension: the configurable keymap is not in Turbo Vision. See Extensions beyond Turbo Vision.
The editor resolves keystrokes through the process-global
Keymap (src/keymap.rs). The
keymap maps one- or two-stroke chords to Command values. Three preset
keymaps ship with the crate:
| Preset | Default? | Style |
|---|---|---|
Keymap::word_star() | yes | WordStar / Ctrl-letter diamond + Ctrl-K/Ctrl-Q block prefixes |
Keymap::cua() | no | CUA / "Office" (Ctrl-C copy, Ctrl-V paste, Ctrl-Z undo) |
Keymap::emacs() | no | Emacs / readline (Ctrl-A line-start, Ctrl-E line-end, …) |
The WordStar preset mirrors the C++ editor's firstKeys / quickKeys /
blockKeys tables faithfully:
- Single-stroke
firstKeys: the Ctrl-letter diamond:Ctrl-Sleft,Ctrl-Dright,Ctrl-Eup,Ctrl-Xdown, etc., plus named keys (Left,Right,Home,End,PageUp,PageDown). Ctrl-Qprefix (quickKeys):Ctrl-Q Ffind,Ctrl-Q Areplace,Ctrl-Q Sline-start,Ctrl-Q Dline-end, …Ctrl-Kprefix (blockKeys):Ctrl-K Bstart-select,Ctrl-K Kcopy,Ctrl-K Cpaste,Ctrl-K Ycut,Ctrl-K Hhide-select.
Replace the keymap process-globally with keymap::set_global:
#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::keymap::{Keymap, set_global};
// Switch the whole application to CUA bindings.
set_global(Keymap::cua());
}
Or build a custom map from scratch:
#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::keymap::{Keymap, set_global};
use tv::Command;
let mut km = Keymap::word_star(); // start from the WordStar base
km.bind("ctrl+z", Command::UNDO); // add a CUA undo chord
set_global(km);
}
The two-stroke prefix (Ctrl-K, Ctrl-Q) works through the Keymap::resolve
API: when resolve(None, stroke) returns Resolve::Prefix, the editor holds the
first stroke as pending; the next keystroke is resolved as
resolve(Some(prefix), stroke).
Source: src/keymap.rs.
Turbo Vision heritage: the C++ editor maintained a
key_statemachine and three hard-coded tables (firstKeys,quickKeys,blockKeys). tvision-rs replaces them with a data-drivenKeymap; theword_star()preset is a direct transcription of those tables.
Search and replace
The editor handles Command::FIND, Command::REPLACE, and
Command::SEARCH_AGAIN:
FIND: requests a find dialog from the loop viaContext::open_find_dialog(editor_id). The loop builds the dialog (pre-filled with the editor's last search string), runs it, and on OK re-injects aSEARCH_AGAINcommand targeting the editor.REPLACE: same flow with a replace dialog that also has a replacement string field and option checkboxes.SEARCH_AGAIN: callsdo_search_replace, which runs the actual search using the storedfind_str,replace_str, andeditor_flags(EF_DO_REPLACE,EF_REPLACE_ALL,EF_PROMPT_ON_REPLACE).
The prompt-on-replace path is asynchronous: when the "prompt on replace"
option is checked, each found occurrence triggers a request_message_box (Yes /
No / Cancel). The editor caches the answer in pending_replace_answer via
set_modal_answer, then the loop re-injects SEARCH_AGAIN. On the next
dispatch the editor reads the cached answer before searching for the next
occurrence: "Yes" replaces and continues, "No" skips and continues, "Cancel"
aborts the whole loop.
The loop option EF_REPLACE_ALL skips the per-occurrence prompt and replaces
every match in a tight loop; EF_DO_REPLACE distinguishes replace from find-only.
Source: src/widgets/editor.rs (do_search_replace, Command::FIND /
REPLACE arms in handle_event, pending_replace_answer).
Turbo Vision heritage:
TEditorused a synchronous nested event loop for the search dialogs. tvision-rs routes both the dialog result and the prompt-on-replace answer through the deferred/async-modal seam, keeping the single event loop intact.
Editor as a dialog control (Memo)
Memo is a thin wrapper over
Editor that turns it into a dialog control:
- Tab pass-through: a plain (unmodified)
Tabkeystroke is not consumed by the editor; it falls through to the dialog's focus navigation.Shift-Tab,Ctrl-Tab, andAlt-Tabare forwarded to the editor as normal (those bindings have in-editor meaning or are editor-application-specific). FieldValuetransfer:Memo::value()returnsFieldValue::Text(contents)andMemo::set_value(FieldValue::Text(s))loads text into the buffer. This makesMemotransparent to the dialog's gather/scatter walk.
#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(dialog: &mut tv::Dialog) {
use tv::widgets::Memo;
let memo_id = dialog.insert_child(Box::new(
Memo::new(
tv::Rect::new(3, 3, 37, 10),
None, // h_scroll_bar
None, // v_scroll_bar
None, // indicator
4096, // buffer size in bytes
)
));
let _ = memo_id;
}
}
After exec_view returns Command::OK, gather the memo's text through the
dialog's child value (index in the gather Vec matches insertion order):
use tvision_rs::data::FieldValue;
let values = dialog.gather_data(); // Vec<Option<FieldValue>>
if let Some(Some(FieldValue::Text(text))) = values.first() {
// text is the memo's current content
println!("memo: {}", text);
}
Source: src/widgets/editor.rs (Memo::handle_event, Memo::value,
Memo::set_value), src/data.rs (FieldValue::Text).
Where to go next
- Dialogs & data: how a
Memo's text flows through gather/scatter. - Windows & the desktop: placing and tiling editor windows.
- Deferred effects: why a view can request a modal save prompt without owning the loop.