mod address;
mod bre;
mod buffer;
mod enc;
use address::Spec;
use buffer::Buffer;
use std::env;
use std::io::{self, BufRead, Write};
use std::process::ExitCode;
fn main() -> ExitCode {
let args: Vec<String> = env::args().skip(1).collect();
let (prompt, filename) = match parse_args(&args) {
Ok(r) => r,
Err(e) => {
eprintln!("ved: {e}");
eprintln!("try 'ved --help' for usage information");
return ExitCode::from(2);
}
};
run_repl(prompt.as_deref(), filename.as_deref())
}
fn parse_args(args: &[String]) -> Result<(Option<String>, Option<String>), String> {
let mut prompt: Option<String> = None;
let mut filename: Option<String> = None;
let mut i = 0;
while i < args.len() {
let arg = &args[i];
match arg.as_str() {
"-p" | "--prompt" => {
i += 1;
if i >= args.len() {
return Err(format!("{arg} requires a value"));
}
prompt = Some(args[i].clone());
}
s if s.starts_with("--prompt=") => {
prompt = Some(s["--prompt=".len()..].to_string());
}
"-h" | "--help" => {
print_usage();
std::process::exit(0);
}
"-V" | "--version" => {
println!("ved {}", env!("CARGO_PKG_VERSION"));
std::process::exit(0);
}
s if s.starts_with('-') => {
return Err(format!("unknown option: {s}"));
}
_ => {
filename = Some(arg.clone());
}
}
i += 1;
}
Ok((prompt, filename))
}
fn print_usage() {
println!("ved - the verbose ed");
println!();
println!("Usage: ved [OPTIONS] [FILE]");
println!();
println!("Options:");
println!(" -p, --prompt <STRING> Set the command prompt");
println!(" -h, --help Show this help message and exit");
println!(" -V, --version Show version information and exit");
}
fn run_repl(prompt: Option<&str>, filename: Option<&str>) -> ExitCode {
let stdin = io::stdin();
let stdout = io::stdout();
let mut out = stdout.lock();
let mut reader = stdin.lock();
let mut line = String::new();
let mut buffer = Buffer::new();
let mut input_mode = false;
let mut quit_warned = false;
if let Some(f) = filename {
match load_file(f, &mut buffer) {
Ok(LoadOutcome::Loaded(bytes)) => {
let _ = writeln!(out, "{bytes}");
}
Ok(LoadOutcome::NewFile) => {
let _ = writeln!(out, "{f}: new file");
}
Err(e) => {
let _ = writeln!(out, "? {e}");
}
}
}
loop {
if !input_mode
&& let Some(p) = prompt
&& (write!(out, "{p}").is_err() || out.flush().is_err())
{
return ExitCode::FAILURE;
}
line.clear();
match reader.read_line(&mut line) {
Ok(0) => return ExitCode::SUCCESS, Ok(_) => {}
Err(e) => {
eprintln!("ved: read error: {e}");
return ExitCode::FAILURE;
}
}
let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
if input_mode {
if trimmed == "." {
input_mode = false;
} else {
buffer.append_after(buffer.current(), trimmed.to_string());
}
continue;
}
match dispatch(trimmed, &mut buffer) {
Action::Quit => {
if buffer.is_modified() && !quit_warned {
let _ = writeln!(out, "? warning: buffer modified");
quit_warned = true;
} else {
return ExitCode::SUCCESS;
}
}
Action::ForceQuit => {
return ExitCode::SUCCESS;
}
Action::EnterInputMode => {
input_mode = true;
quit_warned = false;
}
Action::Done => {
quit_warned = false;
}
Action::Print(msg) => {
let _ = writeln!(out, "{msg}");
quit_warned = false;
}
Action::Error(msg) => {
let _ = writeln!(out, "? {msg}");
quit_warned = false;
}
}
}
}
enum Action {
Quit,
ForceQuit,
EnterInputMode,
Done,
Print(String),
Error(String),
}
fn dispatch(cmd: &str, buf: &mut Buffer) -> Action {
let cmd = cmd.trim_start();
if cmd.is_empty() {
if buf.is_empty() {
return Action::Error("invalid address".to_string());
}
let next = buf.current() + 1;
if next > buf.len() {
return Action::Error("invalid address".to_string());
}
buf.set_current(next);
return match buf.line(next) {
Some(s) => Action::Print(s.to_string()),
None => Action::Error("invalid address".to_string()),
};
}
let (spec, rest) = match Spec::parse(cmd) {
Ok(parsed) => parsed,
Err(e) => return Action::Error(e),
};
if rest.is_empty() {
return run_print(&spec, buf, PrintMode::Plain);
}
match rest {
"q" | "quit" => return Action::Quit,
"a" | "append" => {
if !buf.is_empty()
&& let Ok(r) = spec.resolve(buf)
{
buf.set_current(r.end);
}
return Action::EnterInputMode;
}
"i" | "insert" => {
if !buf.is_empty() {
let addr = match spec.resolve(buf) {
Ok(r) => r.end,
Err(e) => return Action::Error(e),
};
buf.set_current(addr.saturating_sub(1));
}
return Action::EnterInputMode;
}
"c" | "change" => {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let start = range.start;
buf.delete_range(range.start, range.end);
buf.set_current(start.saturating_sub(1));
return Action::EnterInputMode;
}
"d" | "delete" => return run_delete(&spec, buf),
"p" | "print" => return run_print(&spec, buf, PrintMode::Plain),
"n" | "number" => return run_print(&spec, buf, PrintMode::Numbered),
"l" | "list" => return run_print(&spec, buf, PrintMode::List),
"j" | "join" => return run_join(&spec, buf),
"H" | "help" => return run_help(),
"Q" => return Action::ForceQuit,
_ => {}
}
let mut chars = rest.chars();
let first = match chars.next() {
Some(c) => c,
None => return Action::Error(format!("unknown command: {rest}")),
};
let args = chars.as_str();
match first {
'e' => run_edit(buf, args),
'r' => run_read(&spec, buf, args),
'g' => run_global(&spec, buf, args, false),
'v' => run_global(&spec, buf, args, true),
's' => run_substitute(&spec, buf, args),
'w' => run_write(&spec, buf, args),
'm' => run_move(&spec, buf, args),
't' => run_transfer(&spec, buf, args),
_ => Action::Error(format!("unknown command: {rest}")),
}
}
fn run_global(spec: &Spec, buf: &mut Buffer, args: &str, invert: bool) -> Action {
let args_bytes = args.as_bytes();
if args_bytes.is_empty() {
return Action::Error("no delimiter".to_string());
}
let delim = args_bytes[0];
let after_delim = &args_bytes[1..];
let (pattern, rest) = match scan_delimited(after_delim, delim) {
Some(r) => r,
None => return Action::Error("unterminated pattern".to_string()),
};
let cmd = std::str::from_utf8(rest).unwrap_or("p");
let cmd = cmd.trim_start();
let cmd = if cmd.is_empty() { "p" } else { cmd };
let re = bre::Regex::compile(&pattern);
let range = match spec.resolve_or_whole(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let mut marked = Vec::new();
for n in range.start..=range.end {
if let Some(line) = buf.line(n) {
let matched = re.find(line.as_bytes()).is_some();
if matched != invert {
marked.push(n);
}
}
}
if marked.is_empty() {
return Action::Error("no match".to_string());
}
if cmd == "d" {
for &n in marked.iter().rev() {
buf.delete_range(n, n);
}
return Action::Done;
}
let mut output = String::new();
for &n in &marked {
buf.set_current(n);
match dispatch(cmd, buf) {
Action::Print(msg) => {
if !output.is_empty() {
output.push('\n');
}
output.push_str(&msg);
}
Action::Error(msg) => {
if !output.is_empty() {
output.push('\n');
}
output.push_str(&format!("? {msg}"));
}
Action::Done => {}
_ => {}
}
}
if output.is_empty() {
Action::Done
} else {
Action::Print(output)
}
}
fn run_help() -> Action {
Action::Print(
"\
ved commands (addresses shown in brackets are optional):
[.]a, append Append text after the addressed line. End with '.'
[.]i, insert Insert text before the addressed line. End with '.'
[.,.]c, change Replace the addressed lines with new text. End with '.'
[.,.]d, delete Delete the addressed lines
[.,.]p, print Print the addressed lines
[.,.]n, number Print with line numbers
[.,.]l, list Print with non-printing chars as \\NNN octal, ending $
[.,.+1]j, join Join the addressed lines into one (default: . and next)
[.,.]m DEST Move the addressed lines to after DEST (0 = top)
[.,.]t DEST Copy the addressed lines to after DEST (0 = top)
[.,.]s/re/new/[g] Substitute: replace regex match in addressed lines
[.,.]s Repeat the last substitute (pattern, replacement, flags)
[.,.]g/re/cmd Global: run cmd on lines matching regex
[.,.]v/re/cmd Inverse global: run cmd on lines NOT matching regex
[.,.]w [file] Write addressed lines (default: all) to file
q, quit Quit (warns if buffer modified, repeat to force)
H, help Show this help
Addresses: 1 (line 1), $ (last), . (current), +N/-N (relative), , (all), ; (current to end)
Regex: . (any char), * (zero or more), ^ $ (anchors), [abc] [^abc] [a-z] (classes)
\\(...\\) (capture group), \\1-\\9 (backreference)
Replacement: & (whole match), \\1-\\9 (group), \\& (literal &)"
.to_string(),
)
}
fn run_delete(spec: &Spec, buf: &mut Buffer) -> Action {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let count = range.end - range.start + 1;
buf.delete_range(range.start, range.end);
if count == 1 {
Action::Print(format!("deleted line {}", range.start))
} else {
Action::Print(format!(
"deleted {count} lines ({}-{})",
range.start, range.end
))
}
}
fn run_join(spec: &Spec, buf: &mut Buffer) -> Action {
let range = match spec.resolve_or_pair_with_next(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
if range.start == range.end {
buf.set_current(range.start);
return Action::Print(String::new());
}
let mut joined = String::new();
for n in range.start..=range.end {
if let Some(line) = buf.line(n) {
joined.push_str(line);
}
}
buf.replace_line(range.start, joined);
buf.delete_range(range.start + 1, range.end);
buf.set_current(range.start);
let count = range.end - range.start + 1;
Action::Print(format!(
"joined {count} lines ({}-{}) into line {}",
range.start, range.end, range.start
))
}
fn run_move(spec: &Spec, buf: &mut Buffer, dest_arg: &str) -> Action {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let dest = match address::parse_dest(dest_arg, buf) {
Ok((d, _)) => d,
Err(e) => return Action::Error(e),
};
if dest >= range.start && dest <= range.end {
return Action::Error("invalid destination".to_string());
}
let lines: Vec<String> = (range.start..=range.end)
.filter_map(|n| buf.line(n).map(str::to_string))
.collect();
let count = lines.len();
buf.delete_range(range.start, range.end);
let adjusted = if dest > range.end { dest - count } else { dest };
for (at, line) in (adjusted..).zip(lines) {
buf.append_after(at, line);
}
buf.set_current(adjusted + count);
Action::Print(format!(
"moved {count} lines ({}-{}) to after {dest}",
range.start, range.end
))
}
fn run_transfer(spec: &Spec, buf: &mut Buffer, dest_arg: &str) -> Action {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let dest = match address::parse_dest(dest_arg, buf) {
Ok((d, _)) => d,
Err(e) => return Action::Error(e),
};
let lines: Vec<String> = (range.start..=range.end)
.filter_map(|n| buf.line(n).map(str::to_string))
.collect();
let count = lines.len();
for (at, line) in (dest..).zip(lines) {
buf.append_after(at, line);
}
buf.set_current(dest + count);
Action::Print(format!(
"copied {count} lines ({}-{}) to after {dest}",
range.start, range.end
))
}
enum PrintMode {
Plain,
Numbered,
List,
}
fn run_print(spec: &Spec, buf: &mut Buffer, mode: PrintMode) -> Action {
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let mut output = String::new();
for n in range.start..=range.end {
if n > range.start {
output.push('\n');
}
if matches!(mode, PrintMode::Numbered) {
output.push_str(&format!("{n}\t"));
}
if let Some(line) = buf.line(n) {
if matches!(mode, PrintMode::List) {
output.push_str(&render_list_line(line));
} else {
output.push_str(line);
}
}
}
buf.set_current(range.end);
Action::Print(output)
}
fn render_list_line(line: &str) -> String {
let mut out = String::new();
for b in line.bytes() {
match b {
b'\\' => out.push_str("\\\\"),
0x20..=0x7E => out.push(b as char),
_ => out.push_str(&format!("\\{b:03o}")),
}
}
out.push('$');
out
}
enum LoadOutcome {
Loaded(usize),
NewFile,
}
fn load_file(filename: &str, buf: &mut Buffer) -> Result<LoadOutcome, String> {
let detected = enc::warn_if_non_utf8(filename);
let content = match std::fs::read_to_string(filename) {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
buf.set_filename(filename.to_string());
buf.mark_saved();
return Ok(LoadOutcome::NewFile);
}
Err(e) => return Err(format!("cannot open {filename}: {e}")),
};
let bytes = content.len();
for line in content.lines() {
buf.append_after(buf.len(), line.to_string());
}
buf.set_filename(filename.to_string());
buf.mark_saved();
if let Some(enc) = detected {
buf.mark_non_utf8_source(enc, filename.to_string());
}
Ok(LoadOutcome::Loaded(bytes))
}
fn run_edit(buf: &mut Buffer, args: &str) -> Action {
let filename_arg = args.trim_start();
let filename = if filename_arg.is_empty() {
match buf.filename() {
Some(f) => f.to_string(),
None => return Action::Error("no current filename".to_string()),
}
} else {
filename_arg.to_string()
};
*buf = Buffer::new();
match load_file(&filename, buf) {
Ok(LoadOutcome::Loaded(bytes)) => Action::Print(format!("{bytes}")),
Ok(LoadOutcome::NewFile) => Action::Print(format!("{filename}: new file")),
Err(e) => Action::Error(e),
}
}
fn run_read(spec: &Spec, buf: &mut Buffer, args: &str) -> Action {
let filename_arg = args.trim_start();
let filename = if filename_arg.is_empty() {
match buf.filename() {
Some(f) => f.to_string(),
None => return Action::Error("no current filename".to_string()),
}
} else {
filename_arg.to_string()
};
let after = if buf.is_empty() {
0
} else if spec.is_empty() {
buf.len()
} else {
match spec.resolve(buf) {
Ok(r) => r.end,
Err(e) => return Action::Error(e),
}
};
enc::warn_if_non_utf8(&filename);
let content = match std::fs::read_to_string(&filename) {
Ok(c) => c,
Err(e) => return Action::Error(format!("cannot open {filename}: {e}")),
};
let bytes = content.len();
for (insert_at, line) in (after..).zip(content.lines()) {
buf.append_after(insert_at, line.to_string());
}
if buf.filename().is_none() {
buf.set_filename(filename);
}
Action::Print(format!("{bytes}"))
}
fn run_substitute(spec: &Spec, buf: &mut Buffer, args: &str) -> Action {
let args = args.as_bytes();
let (pattern, replacement, global) = if args.is_empty() {
match buf.last_subst() {
Some((p, r, g)) => (p.clone(), r.clone(), *g),
None => return Action::Error("no previous substitute".to_string()),
}
} else {
let delim = args[0];
let rest = &args[1..];
let (pattern, rest) = match scan_delimited(rest, delim) {
Some(r) => r,
None => return Action::Error("unterminated pattern".to_string()),
};
let (replacement, rest) = match scan_delimited(rest, delim) {
Some(r) => r,
None => return Action::Error("unterminated replacement".to_string()),
};
let global = rest.contains(&b'g');
buf.set_last_subst(pattern.clone(), replacement.clone(), global);
(pattern, replacement, global)
};
let re = bre::Regex::compile(&pattern);
let range = match spec.resolve(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let mut last_modified_line = None;
for n in range.start..=range.end {
let line = match buf.line(n) {
Some(l) => l.to_string(),
None => continue,
};
let line_bytes = line.as_bytes();
let new_line = if global {
substitute_all(&re, line_bytes, &replacement)
} else {
substitute_first(&re, line_bytes, &replacement)
};
if let Some(new_bytes) = new_line {
let new_str = String::from_utf8(new_bytes).expect("substitution result is valid UTF-8");
buf.replace_line(n, new_str);
last_modified_line = Some(n);
}
}
match last_modified_line {
Some(n) => {
buf.set_current(n);
match buf.line(n) {
Some(s) => Action::Print(s.to_string()),
None => Action::Error("invalid address".to_string()),
}
}
None => Action::Error("no match".to_string()),
}
}
fn scan_delimited(input: &[u8], delim: u8) -> Option<(Vec<u8>, &[u8])> {
let mut result = Vec::new();
let mut i = 0;
while i < input.len() {
if input[i] == delim {
return Some((result, &input[i + 1..]));
}
if input[i] == b'\\' && i + 1 < input.len() {
if input[i + 1] == delim {
result.push(delim);
i += 2;
} else {
result.push(input[i]);
result.push(input[i + 1]);
i += 2;
}
} else {
result.push(input[i]);
i += 1;
}
}
None }
fn substitute_first(re: &bre::Regex, text: &[u8], replacement: &[u8]) -> Option<Vec<u8>> {
let m = re.find(text)?;
let mut result = Vec::new();
result.extend_from_slice(&text[..m.start]);
result.extend_from_slice(&bre::expand_replacement(replacement, &m, text));
result.extend_from_slice(&text[m.end..]);
Some(result)
}
fn substitute_all(re: &bre::Regex, text: &[u8], replacement: &[u8]) -> Option<Vec<u8>> {
let mut result = Vec::new();
let mut pos = 0;
let mut matched = false;
while pos <= text.len() {
match re.find(&text[pos..]) {
Some(m) => {
matched = true;
let abs_start = pos + m.start;
let abs_end = pos + m.end;
result.extend_from_slice(&text[pos..abs_start]);
result.extend_from_slice(&bre::expand_replacement(replacement, &m, &text[pos..]));
if abs_end == abs_start {
let w = bre::char_width(&text[abs_start..]);
result.extend_from_slice(&text[abs_start..abs_start + w]);
pos = abs_start + w.max(1);
} else {
pos = abs_end;
}
}
None => {
result.extend_from_slice(&text[pos..]);
break;
}
}
}
if matched { Some(result) } else { None }
}
fn run_write(spec: &Spec, buf: &mut Buffer, args: &str) -> Action {
let filename_arg = args.trim_start();
let filename: String = if filename_arg.is_empty() {
match buf.filename() {
Some(f) => f.to_string(),
None => return Action::Error("no current filename".to_string()),
}
} else {
filename_arg.to_string()
};
if let Some(enc) = buf.non_utf8_block(&filename) {
return Action::Error(format!(
"refusing to overwrite {filename} (loaded as {enc}); convert with iconv first, or use `w <newname>` to write elsewhere"
));
}
let (content, wrote_whole) = if buf.is_empty() && spec.is_empty() {
(String::new(), true)
} else {
let range = match spec.resolve_or_whole(buf) {
Ok(r) => r,
Err(e) => return Action::Error(e),
};
let mut s = String::new();
for n in range.start..=range.end {
if let Some(line) = buf.line(n) {
s.push_str(line);
s.push('\n');
}
}
let whole = range.start == 1 && range.end == buf.len();
(s, whole)
};
let bytes = content.len();
if let Err(e) = std::fs::write(&filename, &content) {
return Action::Error(format!("cannot write {}: {}", filename, e));
}
let msg = format!("wrote {bytes} bytes to {filename}");
buf.set_filename(filename);
if wrote_whole {
buf.mark_saved();
}
Action::Print(msg)
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_path(tag: &str) -> std::path::PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let mut p = std::env::temp_dir();
p.push(format!("ved_test_{tag}_{}_{nanos}", std::process::id()));
p
}
#[test]
fn parse_args_with_nothing_returns_no_prompt_or_filename() {
let (prompt, filename) = parse_args(&[]).unwrap();
assert_eq!(prompt, None);
assert_eq!(filename, None);
}
#[test]
fn parse_args_prompt_flag_takes_the_next_arg() {
let args = ["-p".to_string(), "custom> ".to_string()];
let (prompt, filename) = parse_args(&args).unwrap();
assert_eq!(prompt, Some("custom> ".to_string()));
assert_eq!(filename, None);
}
#[test]
fn parse_args_long_prompt_flag_is_the_same_as_short() {
let args = ["--prompt".to_string(), "custom> ".to_string()];
let (prompt, _) = parse_args(&args).unwrap();
assert_eq!(prompt, Some("custom> ".to_string()));
}
#[test]
fn parse_args_prompt_equals_form() {
let args = ["--prompt=custom> ".to_string()];
let (prompt, _) = parse_args(&args).unwrap();
assert_eq!(prompt, Some("custom> ".to_string()));
}
#[test]
fn parse_args_prompt_flag_with_no_value_errors() {
let args = ["-p".to_string()];
assert!(parse_args(&args).is_err());
}
#[test]
fn parse_args_unknown_flag_errors() {
let args = ["--nope".to_string()];
assert!(parse_args(&args).is_err());
}
#[test]
fn parse_args_bare_word_is_a_filename() {
let args = ["notes.txt".to_string()];
let (prompt, filename) = parse_args(&args).unwrap();
assert_eq!(prompt, None);
assert_eq!(filename, Some("notes.txt".to_string()));
}
#[test]
fn parse_args_prompt_and_filename_together() {
let args = ["-p".to_string(), "> ".to_string(), "notes.txt".to_string()];
let (prompt, filename) = parse_args(&args).unwrap();
assert_eq!(prompt, Some("> ".to_string()));
assert_eq!(filename, Some("notes.txt".to_string()));
}
#[test]
fn missing_file_loads_as_new_file() {
let path = temp_path("newfile");
assert!(!path.exists());
let mut buf = Buffer::new();
let outcome = load_file(path.to_str().unwrap(), &mut buf);
assert!(matches!(outcome, Ok(LoadOutcome::NewFile)));
assert_eq!(buf.filename(), path.to_str());
assert!(buf.is_empty());
assert!(!buf.is_modified());
assert!(!path.exists(), "opening a new file must not create it");
}
#[test]
fn directory_is_still_an_error() {
let path = temp_path("dir");
std::fs::create_dir(&path).unwrap();
let mut buf = Buffer::new();
let outcome = load_file(path.to_str().unwrap(), &mut buf);
std::fs::remove_dir(&path).unwrap();
assert!(outcome.is_err());
assert!(buf.filename().is_none());
}
#[test]
fn write_command_writes_buffer_and_remembers_filename() {
let path = temp_path("write_explicit");
let mut buf = buf_with(&["foo", "bar"]);
let act = dispatch(&format!("w {}", path.to_str().unwrap()), &mut buf);
assert!(matches!(act, Action::Print(ref s) if s.contains("wrote")));
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"foo\nbar\n",
"written content"
);
assert_eq!(buf.filename(), path.to_str());
std::fs::remove_file(&path).unwrap();
}
#[test]
fn bare_write_reuses_remembered_filename() {
let path = temp_path("write_bare");
let mut buf = buf_with(&["only"]);
let _ = dispatch(&format!("w {}", path.to_str().unwrap()), &mut buf);
buf.replace_line(1, "changed".to_string());
let act = dispatch("w", &mut buf);
assert!(matches!(act, Action::Print(_)));
assert_eq!(std::fs::read_to_string(&path).unwrap(), "changed\n");
std::fs::remove_file(&path).unwrap();
}
#[test]
fn write_with_no_filename_and_none_remembered_errors() {
let mut buf = buf_with(&["x"]);
let act = dispatch("w", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn write_refuses_to_overwrite_a_non_utf8_source() {
let path = temp_path("write_non_utf8");
let mut buf = buf_with(&["x"]);
buf.set_filename(path.to_str().unwrap().to_string());
buf.mark_non_utf8_source("UTF-16".to_string(), path.to_str().unwrap().to_string());
let act = dispatch("w", &mut buf);
assert!(matches!(act, Action::Error(ref e) if e.contains("UTF-16")));
assert!(!path.exists());
}
#[test]
fn write_of_a_partial_range_does_not_mark_the_buffer_saved() {
let path = temp_path("write_partial");
let mut buf = buf_with(&["a", "b", "c"]);
assert!(buf.is_modified());
let _ = dispatch(&format!("1w {}", path.to_str().unwrap()), &mut buf);
assert!(buf.is_modified());
std::fs::remove_file(&path).unwrap();
}
#[test]
fn write_of_the_whole_buffer_marks_it_saved() {
let path = temp_path("write_whole");
let mut buf = buf_with(&["a", "b", "c"]);
assert!(buf.is_modified());
let _ = dispatch(&format!("w {}", path.to_str().unwrap()), &mut buf);
assert!(!buf.is_modified());
std::fs::remove_file(&path).unwrap();
}
#[test]
fn read_command_inserts_file_contents_after_the_address() {
let path = temp_path("read_insert");
std::fs::write(&path, "x\ny\n").unwrap();
let mut buf = buf_with(&["foo", "bar"]);
let act = dispatch(&format!("1r {}", path.to_str().unwrap()), &mut buf);
assert!(matches!(act, Action::Print(_)));
assert_eq!(buf.line(1), Some("foo"));
assert_eq!(buf.line(2), Some("x"));
assert_eq!(buf.line(3), Some("y"));
assert_eq!(buf.line(4), Some("bar"));
std::fs::remove_file(&path).unwrap();
}
#[test]
fn read_with_no_filename_and_none_remembered_errors() {
let mut buf = buf_with(&["x"]);
let act = dispatch("r", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn read_of_a_missing_file_errors() {
let path = temp_path("read_missing");
let mut buf = buf_with(&["x"]);
let act = dispatch(&format!("r {}", path.to_str().unwrap()), &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn edit_command_replaces_the_buffer_with_file_contents() {
let path = temp_path("edit_replace");
std::fs::write(&path, "new1\nnew2\n").unwrap();
let mut buf = buf_with(&["old1", "old2", "old3"]);
let act = dispatch(&format!("e {}", path.to_str().unwrap()), &mut buf);
assert!(matches!(act, Action::Print(_)));
assert_eq!(buf.len(), 2);
assert_eq!(buf.line(1), Some("new1"));
assert_eq!(buf.line(2), Some("new2"));
std::fs::remove_file(&path).unwrap();
}
#[test]
fn edit_with_no_filename_and_none_remembered_errors() {
let mut buf = buf_with(&["x"]);
let act = dispatch("e", &mut buf);
assert!(matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("x"));
}
#[test]
fn edit_of_a_missing_file_wipes_the_buffer_as_a_new_file() {
let path = temp_path("edit_missing");
let mut buf = buf_with(&["old1"]);
let act = dispatch(&format!("e {}", path.to_str().unwrap()), &mut buf);
assert!(matches!(act, Action::Print(ref s) if s.contains("new file")));
assert!(buf.is_empty());
}
#[test]
fn list_printable_ascii_passes_through() {
assert_eq!(render_list_line("hello world"), "hello world$");
}
#[test]
fn list_empty_line_is_just_dollar() {
assert_eq!(render_list_line(""), "$");
}
#[test]
fn list_tab_becomes_octal() {
assert_eq!(render_list_line("a\tb"), "a\\011b$");
}
#[test]
fn list_ascii_separators_become_octal() {
let s = "A\u{1C}B\u{1D}C\u{1E}D\u{1F}E";
assert_eq!(render_list_line(s), "A\\034B\\035C\\036D\\037E$");
}
#[test]
fn list_backslash_escapes_to_double_backslash() {
assert_eq!(render_list_line("a\\b"), "a\\\\b$");
}
#[test]
fn list_utf8_multibyte_renders_byte_by_byte() {
assert_eq!(render_list_line("ü"), "\\303\\274$");
}
#[test]
fn list_high_bit_byte_pads_to_three_digits() {
let s = "\u{7F}";
assert_eq!(render_list_line(s), "\\177$");
}
fn buf_with(lines: &[&str]) -> Buffer {
let mut b = Buffer::new();
for (i, l) in lines.iter().enumerate() {
b.append_after(i, (*l).to_string());
}
b
}
#[test]
fn join_default_joins_current_and_next() {
let mut buf = buf_with(&["foo", "bar", "baz"]);
buf.set_current(1);
let act = dispatch("j", &mut buf);
assert!(matches!(act, Action::Print(_)));
assert_eq!(buf.len(), 2);
assert_eq!(buf.line(1), Some("foobar"));
assert_eq!(buf.line(2), Some("baz"));
assert_eq!(buf.current(), 1);
}
#[test]
fn join_range_concatenates_all_lines() {
let mut buf = buf_with(&["a", "b", "c", "d", "e"]);
let act = dispatch("2,4j", &mut buf);
assert!(matches!(act, Action::Print(_)));
assert_eq!(buf.len(), 3);
assert_eq!(buf.line(2), Some("bcd"));
assert_eq!(buf.line(3), Some("e"));
assert_eq!(buf.current(), 2);
}
#[test]
fn join_single_line_is_silent_noop() {
let mut buf = buf_with(&["one", "two", "three"]);
let act = dispatch("2j", &mut buf);
if let Action::Print(s) = act {
assert!(s.is_empty());
} else {
panic!("expected silent Print on single-line join");
}
assert_eq!(buf.len(), 3);
assert_eq!(buf.line(2), Some("two"));
assert_eq!(buf.current(), 2);
}
#[test]
fn join_does_not_insert_separators() {
let mut buf = buf_with(&["hello", "world"]);
let _ = dispatch("1,2j", &mut buf);
assert_eq!(buf.line(1), Some("helloworld"));
}
#[test]
fn join_at_last_line_errors() {
let mut buf = buf_with(&["only", "lines", "here"]);
buf.set_current(3);
let act = dispatch("j", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn join_long_form_alias_works() {
let mut buf = buf_with(&["a", "b", "c"]);
let _ = dispatch("1,3join", &mut buf);
assert_eq!(buf.len(), 1);
assert_eq!(buf.line(1), Some("abc"));
}
#[test]
fn join_marks_buffer_modified() {
let mut buf = buf_with(&["x", "y"]);
buf.mark_saved();
assert!(!buf.is_modified());
let _ = dispatch("1,2j", &mut buf);
assert!(buf.is_modified());
}
#[test]
fn delete_single_line_reports_singular_message() {
let mut buf = buf_with(&["a", "b", "c"]);
let act = dispatch("2d", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "deleted line 2"));
assert_eq!(buf.len(), 2);
assert_eq!(buf.line(1), Some("a"));
assert_eq!(buf.line(2), Some("c"));
}
#[test]
fn delete_range_reports_count_and_bounds() {
let mut buf = buf_with(&["a", "b", "c", "d"]);
let act = dispatch("2,3d", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "deleted 2 lines (2-3)"));
assert_eq!(buf.len(), 2);
}
#[test]
fn delete_long_form_alias_works() {
let mut buf = buf_with(&["a", "b"]);
let _ = dispatch("1delete", &mut buf);
assert_eq!(buf.len(), 1);
assert_eq!(buf.line(1), Some("b"));
}
#[test]
fn global_runs_print_on_every_matching_line() {
let mut buf = buf_with(&["foo", "bar", "foo2"]);
let act = dispatch("g/foo/p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "foo\nfoo2"));
}
#[test]
fn global_defaults_to_print_when_no_command_is_given() {
let mut buf = buf_with(&["foo", "bar"]);
let act = dispatch("g/foo/", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "foo"));
}
#[test]
fn inverse_global_v_runs_on_lines_that_do_not_match() {
let mut buf = buf_with(&["foo", "bar", "foo2"]);
let act = dispatch("v/foo/p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "bar"));
}
#[test]
fn global_delete_removes_matching_lines() {
let mut buf = buf_with(&["foo", "bar", "foo2", "baz"]);
let act = dispatch("g/foo/d", &mut buf);
assert!(matches!(act, Action::Done));
assert_eq!(buf.len(), 2);
assert_eq!(buf.line(1), Some("bar"));
assert_eq!(buf.line(2), Some("baz"));
}
#[test]
fn global_with_no_matches_errors() {
let mut buf = buf_with(&["x", "y"]);
let act = dispatch("g/zzz/p", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn global_with_no_delimiter_errors() {
let mut buf = buf_with(&["x"]);
let act = dispatch("g", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn global_unterminated_pattern_errors() {
let mut buf = buf_with(&["x"]);
let act = dispatch("g/unterminated", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn help_command_prints_command_summary() {
let mut buf = buf_with(&["a"]);
let act = dispatch("H", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s.contains("ved commands")));
}
#[test]
fn help_long_form_alias_works() {
let mut buf = buf_with(&["a"]);
let act = dispatch("help", &mut buf);
assert!(matches!(act, Action::Print(_)));
}
#[test]
fn append_positions_current_at_the_addressed_line() {
let mut buf = buf_with(&["x", "y"]);
let act = dispatch("1a", &mut buf);
assert!(matches!(act, Action::EnterInputMode));
assert_eq!(buf.current(), 1);
}
#[test]
fn insert_positions_current_before_the_addressed_line() {
let mut buf = buf_with(&["x", "y"]);
let act = dispatch("2i", &mut buf);
assert!(matches!(act, Action::EnterInputMode));
assert_eq!(buf.current(), 1);
}
#[test]
fn insert_at_line_one_positions_current_at_the_sentinel() {
let mut buf = buf_with(&["x", "y"]);
let _ = dispatch("1i", &mut buf);
assert_eq!(buf.current(), 0);
}
#[test]
fn change_deletes_the_range_and_positions_before_it() {
let mut buf = buf_with(&["a", "b", "c"]);
let act = dispatch("1,2c", &mut buf);
assert!(matches!(act, Action::EnterInputMode));
assert_eq!(buf.len(), 1);
assert_eq!(buf.line(1), Some("c"));
assert_eq!(buf.current(), 0);
}
#[test]
fn force_quit_returns_force_quit_regardless_of_modified_state() {
let mut buf = buf_with(&["x"]);
assert!(matches!(dispatch("Q", &mut buf), Action::ForceQuit));
}
#[test]
fn move_range_to_after_later_line() {
let mut buf = buf_with(&["a", "b", "c", "d", "e"]);
let _ = dispatch("2,3m5", &mut buf);
assert_eq!(buf.line(1), Some("a"));
assert_eq!(buf.line(2), Some("d"));
assert_eq!(buf.line(3), Some("e"));
assert_eq!(buf.line(4), Some("b"));
assert_eq!(buf.line(5), Some("c"));
assert_eq!(buf.current(), 5);
}
#[test]
fn move_range_to_after_earlier_line() {
let mut buf = buf_with(&["a", "b", "c", "d", "e"]);
let _ = dispatch("4,5m1", &mut buf);
assert_eq!(buf.line(1), Some("a"));
assert_eq!(buf.line(2), Some("d"));
assert_eq!(buf.line(3), Some("e"));
assert_eq!(buf.line(4), Some("b"));
assert_eq!(buf.line(5), Some("c"));
}
#[test]
fn move_to_top_with_dest_zero() {
let mut buf = buf_with(&["a", "b", "c"]);
let _ = dispatch("3m0", &mut buf);
assert_eq!(buf.line(1), Some("c"));
assert_eq!(buf.line(2), Some("a"));
assert_eq!(buf.line(3), Some("b"));
assert_eq!(buf.current(), 1);
}
#[test]
fn move_to_end_with_dollar() {
let mut buf = buf_with(&["a", "b", "c", "d"]);
let _ = dispatch("1m$", &mut buf);
assert_eq!(buf.line(1), Some("b"));
assert_eq!(buf.line(2), Some("c"));
assert_eq!(buf.line(3), Some("d"));
assert_eq!(buf.line(4), Some("a"));
}
#[test]
fn move_into_self_errors() {
let mut buf = buf_with(&["a", "b", "c", "d", "e"]);
let act = dispatch("2,4m3", &mut buf);
assert!(matches!(act, Action::Error(_)));
assert_eq!(buf.line(2), Some("b"));
assert_eq!(buf.line(3), Some("c"));
assert_eq!(buf.line(4), Some("d"));
}
#[test]
fn move_invalid_dest_errors() {
let mut buf = buf_with(&["a", "b"]);
let act = dispatch("1m99", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn transfer_copies_range_after_dest() {
let mut buf = buf_with(&["a", "b", "c"]);
let _ = dispatch("1,2t3", &mut buf);
assert_eq!(buf.len(), 5);
assert_eq!(buf.line(4), Some("a"));
assert_eq!(buf.line(5), Some("b"));
assert_eq!(buf.current(), 5);
}
#[test]
fn transfer_to_top_with_dest_zero() {
let mut buf = buf_with(&["x", "y"]);
let _ = dispatch("2t0", &mut buf);
assert_eq!(buf.line(1), Some("y"));
assert_eq!(buf.line(2), Some("x"));
assert_eq!(buf.line(3), Some("y"));
assert_eq!(buf.current(), 1);
}
#[test]
fn transfer_within_self_is_allowed() {
let mut buf = buf_with(&["a", "b", "c", "d"]);
let act = dispatch("1,3t2", &mut buf);
assert!(matches!(act, Action::Print(_)));
assert_eq!(buf.len(), 7);
}
#[test]
fn move_and_transfer_mark_buffer_modified() {
let mut buf = buf_with(&["a", "b", "c"]);
buf.mark_saved();
let _ = dispatch("1t3", &mut buf);
assert!(buf.is_modified());
let mut buf = buf_with(&["a", "b", "c"]);
buf.mark_saved();
let _ = dispatch("1m3", &mut buf);
assert!(buf.is_modified());
}
#[test]
fn bare_s_with_no_prior_substitute_errors() {
let mut buf = buf_with(&["hello world"]);
let act = dispatch("s", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn bare_s_repeats_last_substitute() {
let mut buf = buf_with(&["foo", "foo", "foo"]);
let _ = dispatch("1s/foo/bar/", &mut buf);
assert_eq!(buf.line(1), Some("bar"));
let _ = dispatch("2s", &mut buf);
assert_eq!(buf.line(2), Some("bar"));
let _ = dispatch("3s", &mut buf);
assert_eq!(buf.line(3), Some("bar"));
}
#[test]
fn bare_s_preserves_global_flag() {
let mut buf = buf_with(&["xxx xxx xxx"]);
let _ = dispatch("s/x/Y/g", &mut buf);
assert_eq!(buf.line(1), Some("YYY YYY YYY"));
buf.replace_line(1, "xxx xxx xxx".to_string());
let _ = dispatch("s", &mut buf);
assert_eq!(buf.line(1), Some("YYY YYY YYY"));
}
#[test]
fn substitute_dot_global_on_multibyte_line_matches_by_character() {
let mut buf = buf_with(&["café"]);
let act = dispatch("s/./Y/g", &mut buf);
assert!(!matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("YYYY"));
}
#[test]
fn substitute_does_not_panic_when_search_would_slide_into_a_character() {
let mut buf = buf_with(&["\u{20ac}yq"]); let act = dispatch("s/\\(..\\)y/[\\1]/", &mut buf);
assert!(matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("\u{20ac}yq"));
}
#[test]
fn global_substitute_with_star_that_can_match_empty_preserves_characters() {
let mut buf = buf_with(&["café"]);
let act = dispatch("s/[a-z]*/X/g", &mut buf);
assert!(!matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("XXéX"));
}
#[test]
fn forward_search_finds_next_matching_line() {
let mut buf = buf_with(&["alpha", "beta", "gamma"]);
buf.set_current(1);
let act = dispatch("/beta/p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "beta"));
assert_eq!(buf.current(), 2);
}
#[test]
fn backward_search_wraps_past_the_top() {
let mut buf = buf_with(&["alpha", "beta", "gamma"]);
buf.set_current(1);
let act = dispatch("?gamma?p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "gamma"));
assert_eq!(buf.current(), 3);
}
#[test]
fn forward_search_wraps_past_the_bottom() {
let mut buf = buf_with(&["alpha", "beta", "gamma"]);
buf.set_current(3);
let act = dispatch("/alpha/p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "alpha"));
assert_eq!(buf.current(), 1);
}
#[test]
fn search_can_match_current_line_on_full_wraparound() {
let mut buf = buf_with(&["alpha", "beta"]);
buf.set_current(1);
let act = dispatch("/alpha/p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "alpha"));
}
#[test]
fn search_with_no_match_errors() {
let mut buf = buf_with(&["alpha", "beta"]);
buf.set_current(1);
let act = dispatch("/nope/p", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn search_address_with_no_command_letter_prints() {
let mut buf = buf_with(&["alpha", "beta"]);
buf.set_current(1);
let act = dispatch("/beta", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "beta"));
}
#[test]
fn search_pattern_can_escape_its_own_delimiter() {
let mut buf = buf_with(&["foo/bar", "baz"]);
buf.set_current(1);
let act = dispatch("/foo\\/bar/p", &mut buf);
assert!(matches!(act, Action::Print(ref s) if s == "foo/bar"));
}
#[test]
fn search_address_works_as_a_range_endpoint() {
let mut buf = buf_with(&["one", "two", "three", "four"]);
buf.set_current(1);
let act = dispatch("/two/,/four/p", &mut buf);
assert!(matches!(act, Action::Print(_)));
}
#[test]
fn search_on_empty_buffer_errors_not_panics() {
let mut buf = Buffer::new();
let act = dispatch("/x/p", &mut buf);
assert!(matches!(act, Action::Error(_)));
}
#[test]
fn dot_after_literal_consumes_the_whole_next_character() {
let mut buf = buf_with(&["café"]);
let act = dispatch("s/f./Z/", &mut buf);
assert!(!matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("caZ"));
}
#[test]
fn substitute_whole_multibyte_character_still_works() {
let mut buf = buf_with(&["café"]);
let act = dispatch("s/é/e/", &mut buf);
assert!(!matches!(act, Action::Error(_)));
assert_eq!(buf.line(1), Some("cafe"));
}
#[test]
fn bare_s_without_global_flag_stays_non_global() {
let mut buf = buf_with(&["aaa aaa"]);
let _ = dispatch("s/a/Z/", &mut buf);
assert_eq!(buf.line(1), Some("Zaa aaa"));
let _ = dispatch("s", &mut buf);
assert_eq!(buf.line(1), Some("ZZa aaa"));
}
#[test]
fn explicit_s_updates_the_remembered_state() {
let mut buf = buf_with(&["one two three"]);
let _ = dispatch("s/one/ONE/", &mut buf);
assert_eq!(buf.line(1), Some("ONE two three"));
let _ = dispatch("s/two/TWO/", &mut buf);
assert_eq!(buf.line(1), Some("ONE TWO three"));
buf.replace_line(1, "one two three".to_string());
let _ = dispatch("s", &mut buf);
assert_eq!(buf.line(1), Some("one TWO three"));
}
#[test]
fn non_ascii_command_letter_is_an_error_not_a_panic() {
let mut buf = buf_with(&["a", "b"]);
assert!(matches!(dispatch("\u{e9}", &mut buf), Action::Error(_)));
assert!(matches!(
dispatch("\u{4e16}\u{754c}", &mut buf),
Action::Error(_)
));
assert!(matches!(dispatch("1\u{e9}", &mut buf), Action::Error(_)));
assert!(matches!(
dispatch("1,2\u{e9}foo", &mut buf),
Action::Error(_)
));
assert_eq!(buf.len(), 2);
assert_eq!(buf.line(1), Some("a"));
}
}