# Text composition (M39)

M39 adds what a program needs to *build* text and to look inside it: string streams, `FORMAT`,
`SUBSEQ`, ordered string comparison, `POSITION`, `SEARCH` and `SORT`, and it makes reader errors
catchable. The design is
[ADR 0027](decisions/0027-string-streams-format-and-sequence-utilities.md); the stream basics are
in [text I/O](text-io.md) and the character, `READ` and `PRINT` operators in
[text and data processing](text-data.md). Everything works with the same streams: files, string
streams, `*STANDARD-INPUT*` and `*STANDARD-OUTPUT*`.

## Quick start

```lisp
(format nil "~A has ~D file~:P (~:D bytes)" "report" 2 1234567)
                                   ; => "report has 2 files (1,234,567 bytes)"

(with-output-to-string (out)       ; capture what output routines print
  (prin1 '(a "b") out)
  (format out " ~(~A~)" 'SHOUT))   ; => "(A \"b\") shout"

(with-input-from-string (in "10 (a b) \"c\"")
  (list (read in) (read in) (read in)))    ; => (10 (A B) "c")

(sort (list "pear" "fig" "apple") #'string<)   ; => ("apple" "fig" "pear")
(search "lo" "hello")                          ; => 3
(subseq "hello world" 6)                       ; => "world"
```

## Which operators, and where they live

| Operator | Where | Section |
|---|---|---|
| `MAKE-STRING-INPUT-STREAM` `MAKE-STRING-OUTPUT-STREAM` `GET-OUTPUT-STREAM-STRING` | Rust builtins | [String streams](#string-streams) |
| `WITH-OUTPUT-TO-STRING` `WITH-INPUT-FROM-STRING` | Layer 0 Lisp macros | [String streams](#string-streams) |
| `FORMAT` | Rust builtin (`src/format.rs`) | [FORMAT](#format) |
| `SUBSEQ` `STRING=` `STRING<` `STRING>` `STRING<=` `STRING>=` `STRING/=` `STRING-EQUAL` `STRING-LESSP` `STRING-GREATERP` `STRING-NOT-GREATERP` `STRING-NOT-LESSP` `STRING-NOT-EQUAL` | Rust builtins | [Sequences and strings](#sequences-and-strings) |
| `POSITION` `SEARCH` | Rust builtins since M40 (Layer 0 Lisp in M39) | [Sequences and strings](#sequences-and-strings) |
| `SORT` `STABLE-SORT` | Layer 0 Lisp functions | [Sequences and strings](#sequences-and-strings) |

The builtins are in the bare kernel (`Interp::new()`) and protected from `DEFUN`; the Lisp
definitions need the prelude (`Interp::standard()`, the executable) and, like the rest of Layer 0,
can be redefined by a program without breaking each other.

## String streams

`(make-string-input-stream string &optional start end)` reads the characters of `string` in
`[start, end)`. `(make-string-output-stream)` collects everything written to it;
`(get-output-stream-string stream)` returns the text so far as a fresh string and empties the
stream (and `FRESH-LINE` starts again at the beginning of a line). Every stream operation accepts
them where it accepts a file stream: `READ-CHAR`, `PEEK-CHAR`, `UNREAD-CHAR`, `READ-LINE`, `READ`,
`READ-PRESERVING-WHITESPACE`, `WRITE-CHAR`, `WRITE-STRING`, `WRITE-LINE`, `TERPRI`, `FRESH-LINE`,
`PRINC`, `PRIN1`, `PRINT`, `FORMAT`, `FINISH-OUTPUT`, `CLOSE` and the predicates. They print as
`#<STRING-STREAM :INPUT>` / `:OUTPUT`, and ` closed` after `CLOSE`.

```lisp
(with-output-to-string (s)                       ; => "x=1"
  (write-string "x=" s) (princ 1 s))
(with-output-to-string (*standard-output*)       ; rebinding captures ordinary output
  (princ "inner") (format t "~D" 2))             ; => "inner2"
(with-input-from-string (s "abcdef" :start 2 :end 5)
  (list (read-char s) (read-line s)))            ; => (#\c "de")
```

`WITH-OUTPUT-TO-STRING` takes `(variable)` and returns the collected string (the body's own values
are discarded). `WITH-INPUT-FROM-STRING` takes `(variable string [:start n] [:end n])` and returns the
body's values. Other options (`:index`, the string argument of the output macro) are errors when the
form is expanded. The variable is an ordinary lexical binding; the expansions bind nothing else, so
a body may freely use names such as `stream`.

* Errors are stream errors that `ERROR` handlers see: reading past the end
  (`READ-CHAR: end of file on the string stream`), using a closed stream, `UNREAD-CHAR` misuse. A
  non-stream or a stream of the wrong direction is a type error.
* `CLOSE` only marks the stream closed (there is no resource to release); text already written
  is kept until `GET-OUTPUT-STREAM-STRING`, which however needs an *open* stream.
* A string output stream holds at most 256 MiB; the write that would pass it is a stream error.
* String streams hold no heap references and are reclaimed like any object.

## FORMAT

`(format destination control-string &rest arguments)`. `NIL` returns a fresh string; `T` writes to
the current `*STANDARD-OUTPUT*`; an output stream (file, string, standard) receives the text.
Streams and `T` return `NIL`. The control string must be a string (not a function). Extra
arguments are ignored; too few are an error.

| Directive | Meaning |
|---|---|
| `~A` `~S` | `PRINC` / `PRIN1` form. `~mincol,colinc,minpad,padchar` pad on the right; `@` pads on the left; `:` prints `NIL` as `()`. |
| `~D` `~B` `~O` `~X` | integer in base 10 / 2 / 8 / 16 (upper-case digits). `~mincol,padchar,commachar,interval`; `:` groups digits (`~:D`); `@` always shows the sign. A non-integer argument is printed as by `~A`. |
| `~nR` | integer in radix *n* (2-36). Without *n*: English words (`~R` four, `~:R` fourth) or Roman numerals (`~@R` XIV, `~:@R` old style IIII, 1-3999). |
| `~C` | a character; `~@C` its `#\` syntax |
| `~%` `~&` `~~` | newline(s); a newline unless at the start of a line (the destination's state is known); tilde(s). Repeat counts are prefix parameters. |
| `~P` | plural: `s` unless the argument is 1; `~:P` reuses the previous argument; `~@P` gives `y` / `ies` |
| `~*` | skip an argument; `~:*` back up; `~n@*` go to argument *n* |
| newline | `~` followed by a newline ignores the newline and the white space after it (`~:` keeps the white space, `~@` keeps the newline) |
| `~{ ~}` | iterate over a list argument; `~@{` over the remaining arguments; `~:{` over a list of lists; `~n{` at most *n* times; `~:}` runs at least once |
| `~[ ~; ~]` | choose a clause by an integer argument (or prefix parameter); `~:;` makes the last clause the default; `~:[ ~; ~]` chooses by true/false (false first); `~@[ ~]` runs its clause, without consuming the argument, only when it is true |
| `~( ~)` | case conversion of the enclosed output: lower case; `~:(` capitalise every word; `~@(` capitalise the first word; `~:@(` upper case |
| `~^` | leave the enclosing `~{` (or the whole string) when no argument remains; with parameters `~n^` / `~n,m^` / `~n,m,k^` the usual tests; `~:^` leaves a `~:{` loop |
| prefix parameters | decimal numbers, `'c` characters, `V` (take the value from the next argument; `NIL` means absent) and `#` (the number of arguments left) |

```lisp
(format nil "~{~A~^, ~}" '(1 2 3))                    ; => "1, 2, 3"
(format nil "~:{(~A ~A)~}" '((1 2) (3 4)))            ; => "(1 2)(3 4)"
(format nil "~[none~;one~:;many~]" 7)                 ; => "many"
(format nil "~V,'0D|~10A|~10@A|" 5 42 "left" "right") ; => "00042|left      |     right|"
(format nil "~R, ~:R, ~@R" 1999 3 1999)               ; => "one thousand nine hundred ninety-nine, third, MCMXCIX"
```

Not supported, and reported as `NOT IMPLEMENTED` naming the directive: `~F ~E ~G ~$` (there are no
floating-point numbers), `~T`, `~< ~>` (justification), `~?`, `~/`, `~W`, `~I`, `~_`, `~|`, `~:C`, and
`~{~}` with an empty body (the control string as an argument). A malformed control string or an
argument that does not fit (`~D` is fine with any object, but `~C` needs a character, `~[` an integer,
`~{` a proper list, ...) is a `format error` that `HANDLER-CASE` takes. Limits, all errors:
prefix parameters that ask for output at most 1,000,000; nesting depth 32; result 64 MiB; a loop
whose body uses no argument (it could never end).
The remaining byte budget is enforced while printing `~A`, `~S` and the
non-integer fallback of numeric directives, before an oversized intermediate
can be allocated. UTF-8 encoding, readable escapes and field padding count
toward the budget.

## Sequences and strings

* `(subseq sequence start &optional end)` returns a fresh string or list of the elements in
  `[start, end)`. A list must be proper (dotted and circular lists are type errors). Out-of-range
  bounds are type errors. There is no `(setf subseq)`.
* `STRING<` `STRING>` `STRING<=` `STRING>=` `STRING/=` and the case-folding `STRING-LESSP`
  `STRING-GREATERP` `STRING-NOT-GREATERP` `STRING-NOT-LESSP` `STRING-NOT-EQUAL` take two string
  designators (strings, symbols, characters) and `:START1 :END1 :START2 :END2`. A false answer is
  `NIL`; a true one is the index in the first string where the compared ranges first differ (the
  end of the range when one is a prefix of the other). `STRING=` and `STRING-EQUAL` return `T` or
  `NIL` and accept the same keywords (`STRING=` used to be the two-argument subset). Comparison is
  by Unicode scalar value; the case-folding functions fold to lower case as `CHAR-LESSP` does.
* `(position item sequence &key key test test-not start end from-end)` and
  `(search sequence1 sequence2 &key key test test-not start1 end1 start2 end2 from-end)` work on
  lists, strings and (since M40) vectors (mixed for `SEARCH`); the default test is `EQL`; `:TEST` is called as
  `(funcall test item (funcall key element))`, for `SEARCH` as `(funcall test (key a) (key b))`.
  Bounds are checked eagerly (`:end` beyond the length is an error even if a match comes first). `SEARCH`
  costs the product of the lengths. Since M40 both are Rust builtins of the sequence library, together
  with `FIND`, `REMOVE` and `REVERSE`, which also accept strings and vectors now
  ([vectors, hash tables and the sequence library](data-structures.md)).
* `(sort sequence predicate &key key)` and `STABLE-SORT` are the same stable merge sort of a list, a
  string or (since M40) a vector, iterative, with O(n log n) calls of the predicate. **A list or string
  comes back as a new sequence and the argument is not modified; a vector is sorted in place and
  returned.** Common Lisp lets an implementation destroy the argument, so portable
  programs use the result and are fine. Equal elements keep their order (`SORT` is stable here, which
  Common Lisp does not promise). Strings sort by character: `(sort "banana" #'char<)`. The predicate
  and key may do anything, including non-local exits and errors, and are called with the evaluator
  depth they would have anywhere.

## Reader errors are conditions now

A malformed or truncated object read by `READ` (any stream) or `READ-FROM-STRING` -- an unmatched
`)`, an unterminated list or string, `#\` at the end of input, end of file inside an object, or end
of file with `eof-error-p` true on `READ-FROM-STRING` -- is an `ERROR` condition, so
`(handler-case (read-from-string text) (error () nil))` works. Still **not** conditions: a clean end
of file on the *host* input (`READ`, `READ-LINE`, `READ-CHAR` on standard input end the session;
the Wizard REPL depends on that), unsupported syntax (`#2(1 2)`, `|x|`),
and reading program text (`LOAD`, the REPL). Since M40 keyword-list mistakes such
as `:bogus` are also catchable argument errors. Without a handler
the error is exactly the one the host sees.

`READ-FROM-STRING` now ends its position the way stream `READ` does: it drops one white-space
character after the object (`CR LF` as one) unless `:PRESERVE-WHITESPACE` is true.
`(read-from-string "(a) b")` gives `(A)` and 4 (it was 3).

## Differences from Common Lisp

* `SORT` and `STABLE-SORT` do not destroy a list or string argument (they return a new one); a vector is sorted in place.
* `FORMAT`: the subset above; `~D` and friends take 64-bit integers; `~R` covers the 64-bit range.
  The control string must be a string; `NIL` and `T` and streams are the destinations (no string with a
  fill pointer).
* `WITH-OUTPUT-TO-STRING` has no string argument and no `:element-type`; `WITH-INPUT-FROM-STRING` has
  no `:index`; `MAKE-STRING-OUTPUT-STREAM` takes no options.
* `SUBSEQ` on a list needs a proper list; there is no `(setf subseq)`.
* `POSITION` and `SEARCH` check `:start`/`:end` eagerly and have no `-IF` variants.
* The `-EQUAL` / `-LESSP` string functions compare with the one-scalar case folding of the
  character functions (some Unicode characters fold differently from SBCL).

## Examples

Both examples are portable Common Lisp: their output is byte-for-byte what SBCL prints.

* `examples/text/report.lisp`: reads `name,department,salary` lines from standard input and prints a
  grouped, sorted salary report with `FORMAT` (`~22A`, `~9:D`, `~[~;person~:;people~]`), `SORT`,
  `POSITION`, `SUBSEQ`, `WITH-OUTPUT-TO-STRING` and a list of rejected lines.
  `rustlisp --script examples/text/report.lisp < examples/text/staff.csv`
* `examples/text/template.lisp`: fills `{{key}}` fields of a template (`card.txt`) from a file of
  property lists (`people.sexp`) with `SEARCH`, `SUBSEQ`, `WRITE-STRING :START :END`, `STRING-EQUAL` and
  a string stream.
  `rustlisp --script examples/text/template.lisp examples/text/card.txt examples/text/people.sexp`

227 Common Lisp contracts are compared with SBCL (`examples/paip/m39-cases.tsv`, run by
`scripts/paip-baseline.py` and `tests/m39.rs`).
