From b7b01494926a134f39daf8102281889702ddf62b Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 17:13:24 +0100 Subject: 0.5.3: session locking, UTF-8 and size guards for edit, correct character widths - exclusive flock on session files - edit refuses non-UTF-8 and >64 MiB files with actionable messages - editor uses unicode-width, expands tabs, handles resize --- src/line.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++- src/session.rs | 15 +++++++++++++++ src/tools/fs.rs | 17 ++++++++++++++++- 3 files changed, 75 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/line.rs b/src/line.rs index accf6cd..1ae210a 100644 --- a/src/line.rs +++ b/src/line.rs @@ -57,6 +57,14 @@ impl Editor { insert(&mut buffer, &mut cursor, &text); draw(prompt, &buffer, cursor, &mut rows)?; } + Event::Resize(_, _) => { + // The terminal reflowed the block we were tracking, so the + // old row count is meaningless. Start a fresh prompt line + // rather than risk erasing output above it. + println!(); + rows = 1; + draw(prompt, &buffer, cursor, &mut rows)?; + } Event::Key(key) if key.kind == KeyEventKind::Press => { match handle_key(key, &mut buffer, &mut cursor, self) { Action::Continue => {} @@ -266,7 +274,17 @@ fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, u col = 0; pending_wrap = false; } - col += 1; + + let cells = cells(ch, col); + if cells == 0 { + // Combining marks draw on top of the previous cell. + continue; + } + if col + cells > width { + row += 1; + col = 0; + } + col += cells; if col >= width { col = width - 1; pending_wrap = true; @@ -276,6 +294,15 @@ fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, u (row, col) } +/// Columns a character occupies at the given cursor position. Terminals expand +/// a tab to the next multiple of eight; wide characters occupy two cells. +fn cells(ch: char, col: usize) -> usize { + if ch == '\t' { + return 8 - (col % 8); + } + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1) +} + fn draw(prompt: &str, buffer: &[char], cursor: usize, rows: &mut usize) -> io::Result<()> { let width = terminal_width(); let mut out = io::stdout(); @@ -406,6 +433,22 @@ mod tests { assert!(terminal_width() >= 1); } + #[test] + fn layout_counts_wide_and_combining_characters() { + let wide: Vec = "日本語".chars().collect(); + assert_eq!(layout("> ", &wide, 3, 20), (0, 8)); + + let combining: Vec = "e\u{0301}".chars().collect(); + assert_eq!(layout("", &combining, 2, 20), (0, 1)); + } + + #[test] + fn layout_expands_tabs_to_the_next_stop() { + let tab: Vec = "\t".chars().collect(); + assert_eq!(layout("> ", &tab, 1, 80), (0, 8)); + assert_eq!(layout("", &tab, 1, 80), (0, 8)); + } + #[test] fn insert_normalises_line_endings() { let mut buffer = vec!['a']; diff --git a/src/session.rs b/src/session.rs index 6e3c1c1..6416b56 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2,6 +2,7 @@ use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::fs::PermissionsExt; +use std::os::unix::io::AsRawFd; use std::path::Path; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -48,6 +49,18 @@ fn restrict(path: &Path, mode: u32) { let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)); } +/// Two processes appending to one transcript interleave messages and corrupt it +/// permanently, because history is never rewritten. Refuse the second one. +fn lock_exclusive(file: &File, id: &str) -> Result<(), String> { + let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; + if locked != 0 { + return Err(format!( + "session {id} is already open in another process" + )); + } + Ok(()) +} + pub struct Session { pub id: String, pub model: String, @@ -84,6 +97,7 @@ impl Session { .open(&path) .map_err(|e| format!("{}: {e}", path.display()))?; restrict(&path, 0o600); + lock_exclusive(&file, &id)?; let cwd = std::env::current_dir() .map(|path| path.display().to_string()) @@ -164,6 +178,7 @@ impl Session { .map_err(|e| format!("{}: {e}", path.display()))?; // Older builds created these 0644. restrict(&path, 0o600); + lock_exclusive(&file, &session_id)?; Ok(( Session { diff --git a/src/tools/fs.rs b/src/tools/fs.rs index 947649f..ac0a475 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -10,6 +10,9 @@ const MAX_LINE_BYTES: usize = 4096; const MAX_READ_LINES: usize = 2000; const MAX_MATCHES: usize = 200; const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; +/// Edit rewrites the whole file, so it has to fit comfortably in the 32-bit +/// address space together with its own copy. +const MAX_EDIT_BYTES: u64 = 64 * 1024 * 1024; const PREVIEW_BUDGET: usize = 60; const SKIP_DIRS: &[&str] = &[ @@ -239,7 +242,19 @@ pub fn plan_edit(args: &Value) -> Result { if old.is_empty() { return Err("`old` must not be empty; use write to create a file".into()); } - let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; + let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; + if bytes.len() as u64 > MAX_EDIT_BYTES { + return Err(format!( + "{path} is {} MiB, too large to edit safely; use bash (sed) instead", + bytes.len() / (1024 * 1024) + )); + } + let text = String::from_utf8(bytes).map_err(|_| { + format!( + "{path} is not valid UTF-8, so edit cannot round-trip it without \ + corrupting the file; use bash (sed, perl) instead" + ) + })?; // Fail before the approval prompt if the match is unusable. locate(&text, &old)?; Ok(Change::Edit { path, old, new }) -- cgit v1.2.3