# Text input and output (M37, extended in M38 and M39)

RustLisp can read and write UTF-8 text files and standard input and output
from Lisp, with a recognisable subset of the Common Lisp stream interface. The
design is [ADR 0025](decisions/0025-text-streams.md) (streams, M37) and
[ADR 0026](decisions/0026-character-io-read-and-script-arguments.md) (characters,
`READ`, script arguments, M38). This page is the reference for the stream objects, `OPEN`,
line input and output, cleanup, the standard streams and batch execution;
characters, `READ`, `PRINT`, `PARSE-INTEGER` and the program arguments are in
[text and data processing](text-data.md); string streams and `FORMAT` (M39, [ADR 0027](decisions/0027-string-streams-format-and-sequence-utilities.md))
are in [text composition](text-composition.md). Only text is supported:
no binary or bidirectional streams, no pathname objects.

## Quick start

```lisp
(with-open-file (out "results.txt" :direction :output :if-exists :supersede)
  (write-line "Hello" out))

(with-open-file (in "results.txt")
  (read-line in))                       ; => "Hello", NIL
```

`WITH-OPEN-FILE` is the recommended form: it closes the file however the body is
left. Worked programs are in `examples/io/` (see [Examples](#examples)).

## Interfaces

| Operator | Where | Notes |
|---|---|---|
| `(open filename &key direction element-type if-exists if-does-not-exist external-format)` | Rust builtin | returns a stream, or `NIL` where a `NIL` policy says so |
| `(close stream &key abort)` | Rust builtin | returns `T`; repeatable |
| `(read-line &optional stream eof-error-p eof-value recursive-p)` | Rust builtin | two values: line, missing-newline-p |
| `(write-line string &optional stream &key start end)` | Rust builtin | returns `string` |
| `(princ object &optional stream)`, `(fresh-line &optional stream)` | Rust builtin (M18) | now accept file streams |
| `(with-open-file (var filename option*) form*)` | Layer 0 Lisp | |
| `streamp`, `open-stream-p`, `input-stream-p`, `output-stream-p` | Rust builtins | answer `NIL` for non-streams |
| `read-char`, `peek-char`, `unread-char`, `read`, `read-preserving-whitespace` | Rust builtins (M38) | [text and data processing](text-data.md) |
| `write-char`, `write-string`, `terpri`, `finish-output`, `force-output`, `prin1`, `print` | Rust builtins (M38) | [text and data processing](text-data.md) |
| `*standard-input*`, `*standard-output*` | special variables | host-stream objects |

A stream prints as `#<FILE-STREAM :INPUT "path">` (with ` closed` after close) or
`#<HOST-STREAM :OUTPUT>`. No operating-system handle is ever printed.

### Stream designators

For every operation that takes a stream (`READ-LINE`, `WRITE-LINE`, `PRINC`, `FRESH-LINE` and, since
M38, `READ-CHAR`, `PEEK-CHAR`, `UNREAD-CHAR`, `READ`, `WRITE-CHAR`, `WRITE-STRING`, `TERPRI`,
`FINISH-OUTPUT`, `PRIN1`, `PRINT`) the stream argument is:

- omitted or `NIL`: the current value of `*STANDARD-INPUT*` / `*STANDARD-OUTPUT*`,
  so `(let ((*standard-output* out)) (write-line "x"))` writes to `out`;
- `T`: the host stream itself, whatever the variable holds;
- a stream of the right direction that is open.

Anything else is a type error (`stream`, `input stream` or `output stream`); an
open-but-closed stream is a stream error ("the stream ... is closed"). `LOAD :print`
and the REPL write to the host directly and do not follow `*STANDARD-OUTPUT*`.

## OPEN

Filenames are strings. A relative name is relative to the **process's current
working directory** (not the file being loaded). Names are passed to the operating
system unchanged: spaces and Unicode are fine; there is no `~` expansion, no wildcard
or logical-pathname syntax and no `*default-pathname-defaults*`. On Windows `/` and
`\` both separate directories.

| Keyword | Accepted values | Default |
|---|---|---|
| `:direction` | `:input`, `:output` | `:input` |
| `:if-exists` (output) | `:error`, `:supersede`, `:append`, `:overwrite`, `NIL` | `:error` |
| `:if-does-not-exist` | `:error`, `NIL`; `:create` for output only | `:error` for input and for `:append`/`:overwrite`; otherwise `:create` |
| `:element-type` | `CHARACTER`, `:default` | character |
| `:external-format` | `:utf-8`, `:default` | UTF-8 |

Everything else (`:io`, `:probe`, `:rename`, `:rename-and-delete`, `:new-version`,
binary element types, other encodings, `:create` for input) is refused with
`not implemented: OPEN does not support ...` **before the file system is touched**.
The leftmost occurrence of a repeated keyword wins; an unknown keyword or an odd
list is `invalid syntax`; a non-string filename is a type error.

The default policy never overwrites: opening an existing file for output without
`:if-exists` is an error, and the file is untouched. (Common Lisp's default depends on
version semantics; `:error` is its choice for files without versions and is the only
conservative one.)

- `:supersede` truncates the file **at open time**; it is not atomic and is not
  undone by `:abort`.
- `:append` writes at the end. `:overwrite` writes from the start without truncating.
  Both require the file to exist unless `:if-does-not-exist :create`.
- `:if-exists NIL` / `:if-does-not-exist NIL` return `NIL` instead of signalling.
- A file that must be new is created atomically (`create_new`).
- A directory cannot be opened. Permission and other operating-system failures are
  stream errors that quote the system's reason.

A failed `OPEN` has no effect: nothing is created, truncated or left open.

## READ-LINE

- The line has its terminator removed: `LF` or `CR LF`. A lone `CR` is ordinary text.
  A final line without a newline is returned normally.
- Second value: `T` if end of file (not a newline) ended the line, else `NIL`.
- At end of file with nothing read: if `eof-error-p` is true (the default) it is an
  error; otherwise the values are `eof-value` (default `NIL`) and `T`.
  For a **file** stream the error is a stream error that `HANDLER-CASE ... (error ...)`
  catches. For the **host** input it is the M18 `end of file` error, which is *not*
  an `ERROR` condition (the Wizard driver relies on it); pass `eof-error-p` `NIL` when
  reading standard input in a program that must continue.
- Invalid UTF-8 is a stream error naming the file and the offset; that line is
  consumed, so the next `READ-LINE` continues with the following line. A UTF-8 byte
  order mark at the start of a file is ordinary data (unlike `LOAD`, which drops it).
- A line longer than 16 MiB (`MAX_LINE_BYTES`) is a stream error rather than an
  unbounded allocation. The rest of that line is left unread.
- `recursive-p` is accepted and ignored (there is no reader recursion).
- A read error (the file was removed or the medium failed) is a stream error.

## WRITE-LINE, PRINC, FRESH-LINE

`WRITE-LINE` writes `string[start, end)` and a newline, and returns the **whole**
original string. `:start` defaults to 0 and `:end` to the length (`NIL` means the
default); out-of-range or reversed bounds are type errors, and nothing is written.
The newline is `LF` on every platform. Output is buffered; `CLOSE` writes it out and
reports a failure. `PRINC` prints aesthetically (as before); `FRESH-LINE` tracks the
column per stream.

## CLOSE and cleanup

`(close stream)` flushes buffered output, releases the file and marks the stream
closed. It returns `T`, and closing a closed stream does nothing (also `T`). Later
`READ-LINE`/`WRITE-LINE`/`PRINC`/`FRESH-LINE` (and the M38 operations) on it are stream errors; the predicates
still work (`open-stream-p` is `NIL`, the direction predicates keep answering). If the
flush fails the error is reported **and the stream is closed regardless**.
`(close stream :abort t)` releases the file and ignores a flush failure; it does **not**
delete a file `OPEN` created or restore one it superseded (a deviation from ANSI).

Closing `*standard-input*` or `*standard-output*` (or `T`'s host stream) closes
nothing: output is flushed, `T` is returned, and the stream remains usable. A program
cannot close the process's standard handles.

### WITH-OPEN-FILE

`(with-open-file (var filename option*) form*)` opens the file once (arguments are
evaluated once, in the caller's scope), binds `var` for the body, returns the body's
values, and closes the stream:

- on normal exit, with `(close var)`: a flush failure is **reported**;
- on any other exit (an error, `THROW`, `RETURN-FROM`, `RETURN`, `QUIT`/`RUSTLISP-EXIT`),
  with `(close var :abort t)` from an `UNWIND-PROTECT` cleanup: a flush failure is
  **not** allowed to replace the error or transfer already unwinding.

If `OPEN` fails, the body does not run and there is nothing to close. If `OPEN` returns
`NIL`, `var` is `NIL` and nothing is closed. The expansion names only special operators
and protected builtins and binds only parameters of its own function, so user variables
(even ones called `stream`, `function` or `abort`) cannot clash with it. It costs about
two evaluator levels (the limit is 80; see `docs/deep-recursion.md`).

### Not closing

A stream that becomes unreachable without being closed is released when the garbage
collector reclaims it, and all streams are released when the interpreter is dropped.
Buffered output is then written on a best-effort basis with failures unreported. This
is a safety net, not a contract: the timing is up to the collector, and a loop that
opens many files without closing them can run out of descriptors first. Use
`WITH-OPEN-FILE` or `CLOSE`.

## Standard input and output

`*STANDARD-INPUT*` and `*STANDARD-OUTPUT*` are special variables whose values are
host-stream objects: input is the process's standard input (or the buffer an embedder
installed with `set_input_text`), output is standard output (or a capture buffer).
Both can be rebound with `LET` or assigned. Output goes through the same writer as
`PRINC`/`FRESH-LINE`/`WRITE-STRING`/`PRINT`, one flush per write, so interleaving with REPL output is ordered.

Standard input is **shared**: the REPL, `READ-LINE` on `*STANDARD-INPUT*`, and
`(read-line)` all read the same process stdin through the same buffer. In the REPL a
program that reads stdin therefore competes with the REPL for it. In `--script` mode
the program owns it.

## Batch execution and pipelines

Frontend output in `-e` and the REPL also uses fallible writes. A closed stdout
pipe ends quietly with status 141 on Unix (1 elsewhere), including prompts,
returned values and Lisp output; it does not produce a Rust panic. Lisp
unwinding and cleanup finish before a failed Lisp write reaches the frontend.

```
rustlisp [--quiet] --script FILE [ARGUMENT...]
```

`--script` loads `FILE` (as `LOAD` does, so errors are located) and ends:

- no banner, no `> ` prompt, no printed results (only what the program writes);
- the REPL never starts and never reads standard input: unread input is ignored, not
  evaluated;
- exit status 0 on success, the `RUSTLISP-EXIT :code` value (or 0 for `QUIT`), or 1
  when an error nothing handled escapes (the located message goes to standard error;
  stdout keeps whatever was already written);
- the arguments after `FILE` are the program's, verbatim, in `*COMMAND-LINE-ARGUMENTS*`
  (M38; [details](text-data.md#the-command-line)); an executable file may start with a
  `#!/usr/bin/env rustlisp --script` line, which is ignored;
- a closed output pipe (`... | head`) ends the program quietly with status 141 on Unix
  (1 elsewhere) after the usual unwinding;
- it cannot be combined with `-e` or `--load` **before** it, or with `--help`/`--version`
  (status 2, usage); `--quiet` is accepted and changes nothing.

The existing options are unchanged. `--load FILE` followed by the REPL is for
interactive work; `rustlisp --load f.lisp < input.txt` would hand the rest of the input
to the REPL as Lisp, which is why batch programs use `--script`.

```
$ printf '12\n18\n\n-6\n' | rustlisp --quiet --script examples/io/sum-stdin.lisp
count: 3
sum: 24
gcd: 6
$ rustlisp --quiet --script process-lines.lisp < input.txt > output.txt
$ rustlisp --script examples/text/csv-stats.lisp scores.csv report.txt
```

Run the examples from the repository root: their `LOAD` path is relative to the working
directory.

## Cross-platform notes

- Linux, macOS and Windows use the same code. Text is UTF-8 on every platform; there is
  no code-page translation. Standard input and output are treated as UTF-8 byte streams
  (an interactive Windows console that is not UTF-8 may show other characters wrongly).
- Reading accepts `LF` and `CRLF`; writing always emits `LF`.
- File names containing Unicode are accepted wherever the operating system accepts them
  (the tests cover spaces, accents, CJK and symbols). A name containing a NUL character
  is a stream error.
- Windows keeps files open exclusively against deletion in some configurations, so
  close files you intend to delete or rename.
- File locking, atomic replace, permissions and symbolic links are those of the
  operating system.

## Errors

| Situation | Error |
|---|---|
| missing file, permission, directory, other OS failure; closed stream; flush failure; file-stream end of file; invalid UTF-8; over-long line | `stream error: ...` (adapted: `HANDLER-CASE`/`HANDLER-BIND` for `ERROR` see it) |
| argument not a stream / wrong direction | type error |
| non-string filename, bad `:start`/`:end` | type error |
| unsupported `OPEN` option | `not implemented` |
| unknown or malformed keyword arguments | `invalid syntax` (not catchable by `HANDLER-CASE`, as for every keyword-argument error) |
| host input end of file | `end of file` (not an `ERROR` condition) |
| host input/output failure | `I/O error: ...` (not an `ERROR` condition) |
| `UNREAD-CHAR` of the wrong character or twice | stream error |
| `PARSE-INTEGER` of text that is not an integer | `parse error: ...` (adapted, like a stream error) |
| reader error in `READ` | `read error` (an `ERROR` condition since M39); `not implemented` for unsupported syntax (not a condition) |

## Unsupported

Binary and bidirectional streams; `:io`/`:probe`; `WRITE` on streams; `LISTEN`, `READ-CHAR-NO-HANG`, `CLEAR-INPUT`;
`FILE-POSITION`, `FILE-LENGTH`; `WITH-OPEN-STREAM`; `PROBE-FILE`, `DELETE-FILE`,
`DIRECTORY`, pathname objects and functions; `*ERROR-OUTPUT*`, `*TERMINAL-IO*`;
`END-OF-FILE`/`FILE-ERROR`/`STREAM-ERROR` condition types (every stream failure is an
`ERROR`); environment access. (M38 added `READ-CHAR`, `PEEK-CHAR`, `UNREAD-CHAR`,
`WRITE-CHAR`, `WRITE-STRING`, `TERPRI`, `FINISH-OUTPUT`, `FORCE-OUTPUT`, `READ`, `PRIN1`,
`PRINT` and script arguments; M39 added string streams and `FORMAT`.)

## Examples

All are original and in `examples/io/`:

- `integers.lisp`: `parse-int`, `read-integers`, `totals` and `summarize-file`, which
  reads one integer per line, validates every line (nothing is evaluated), and writes
  the count, sum and GCD (M36 `GCD`, M35 checked arithmetic) to another file, closing
  both. Bad input leaves the output file alone.
  `rustlisp --load examples/io/integers.lisp -e '(summarize-file "numbers.txt" "result.txt")'`
- `sum-stdin.lisp`: the same totals for standard input, for a pipeline.
- `number-lines.lisp`: numbers the non-blank lines of standard input.

Their contracts are in `examples/io/integer-cases.tsv` and `examples/paip/m37-cases.tsv`,
compared with SBCL by `scripts/paip-baseline.py` and run by `tests/m37.rs`. The M38 programs
(word frequencies, CSV statistics, symbolic records, a `READ`/`PRIN1` filter) are in
`examples/text/` and described in [text and data processing](text-data.md#examples).
