. "$BST_LIB"
require ed ed/present

tmp=${TMPDIR:-/tmp}/bst-ed.$$
in="$tmp.in"; out="$tmp.out"; cmds="$tmp.cmds"

printf '%s\n' 'alpha' 'bravo' 'charlie' > "$in"

# ed is a batch line editor: it reads the file into a buffer and takes commands
# from stdin. -s = script mode (suppress byte counts / diagnostics). Q quits
# unconditionally (plain q warns on a modified buffer and would need a second q).

# 1) Edit -> print to stdout, no file write: substitute on line 2, print buffer.
printf '%s\n' '2s/bravo/BRAVO/' ',p' 'Q' > "$cmds"
edp=$(ed -s "$in" < "$cmds" 2>&1)
check_out ed/subst  "BRAVO"    printf '%s\n' "$edp"
check_out ed/keep   "charlie"  printf '%s\n' "$edp"

# 2) Append a line and write the buffer to a new file, then read it back.
printf '%s\n' '3a' 'delta' '.' "w $out" 'Q' > "$cmds"
check     ed/write   sh -c "ed -s '$in' < '$cmds'"
check_out ed/append  "delta"   sh -c "cat '$out'"
check_eq  ed/lines   4         "$(wc -l < "$out" 2>/dev/null | tr -d ' ')"

rm -f "$in" "$out" "$cmds"
