馃獎 dd's hex editor
README
Hello! If you're here, you're interested in understanding how ddhx works
internally.

This document explains:
- How the codebase is organized
- The program's execution flow
- How the Piece Table backend works
- The command-based undo/redo system
- How documents are saved, in-place or not

For user-facing documentation, see the main README in the project root.

********************************************************************************
* SOURCE STRUCTURE
********************************************************************************

The folder structure is pretty straight-forward:
- ddhx/editor/*
  Contains editor backends. Each provide an implementation of a document
  editor.
- ddhx/document/*
  Source documents. Often representing a specific media, such as a file, a disk
  a process, and other physical representation of a source document.
  Currently, only saving to files are supported, it is planned that each
  document will have different strategies to save modifications.
- ddhx/*
  Other files that compliments the engine.
- os/*
  Operation system interfaces.
- *
  TUI front-end files.

********************************************************************************
* PROGRAM CONTROL FLOW
********************************************************************************

      START
    +--------+ - Command-line parsing, init logging
    | main.d | - Initialize default keys, commands
    +--------+ - Find and parse configuration
        |      - Initialize document editor, open document
        v
    +--------+ - Setup terminal and session
    | view.d | - Loop (read input, modify state, update)
    +--------+ - menu (prompt) system, command implementation
        |      - Renders text/data to buffer
        v
+---------------+ - Manage terminal features
| os/terminal.d | - readkey, readline implementation
+---------------+ - Translate key names to key values
        |
        v
    + ~ ~ ~ ~+
    | screen |
    +~ ~ ~ ~ +

********************************************************************************
* COMMAND LINE
********************************************************************************

This section is about typing commands at the ':' prompt and in .ddhxrc. The
HISTORY section further down is about undo, which is unrelated.

A typed line goes through two steps:

  utils.arguments()   Splits the line into arguments, applying quoting and C
                      escapes.
  patterns.pattern()  Turns one argument into a needle, applying prefixes and
                      wildcards.

A hex editor's job is precision, so each rule below trades a little
convenience for a needle whose bytes are never a surprise.

*
* QUOTING
*

The two quotes buy two independent things, and neither buys the other's:

                    protects whitespace    escape sequences
    text            no                     no
    'text'          yes                    no
    "text"          yes                    yes

So text is raw unless double quoted, which makes it a C string literal:

    find utf8:C:\Users              a path, typed as a path
    find utf8:'C:\Program Files'    a path with a space, quoted for the space
    find utf8:"\x1b[0m"             an escape sequence, opted into

Adjacent runs concatenate, each read its own way, and a prefix may sit inside
or outside the quotes ("utf8:abc" is utf8:"abc"):

    find utf8:'C:\Users'"\0"        a raw path with a NUL after it
    find utf8:'a'"\t"'b'            tab between two raw runs

Why is an argument bytes, not text?
- Once escapes resolve, "\0" and "\xff" are not valid UTF-8, and POSIX
  filenames are byte strings anyway. Commands wanting text validate it; the
  rest never care.

Why are escapes the same for every command?
- They resolve while the quotes are read, before a command is chosen. "\xff"
  is one byte for find and diff-file alike, and diff-file "C:\dir" is an error
  rather than a path.

Why is a backslash a byte outside double quotes, even before a quote?
- Interpreting escapes everywhere makes backslashes and quotes a chore to
  search for. A quote is written with the other kind instead: 'it'"'"'s', not
  POSIX's 'it'\''s'.

Why is an unknown escape an error?
- As in a compiler: with one policy for every command, the strict one is the
  safe one. "C:\dir" names \d and stops; write 'C:\dir' or "C:\\dir".

Why is an unterminated quote an error?
- Guessing where the line ended would silently run half a command.

Why do empty quotes produce no argument?
- No command distinguishes "" from absent, so find "" reports "Need search"
  instead of an obscure empty needle.

Why do wildcards ignore quoting?
- They match whole arguments before prefixes, so anything prefixed is already
  data; consulting quotes only made find '*' an error.

*
* BYTES AND SCALARS
*

Prefixes split into byte strings, taken as written, and scalars, which still
have to be encoded and so have a width and a byte order:

    x: 0x                 bytes, two hex digits each
    x8: x16: x32: x64:    scalar, unsigned, that many bits
    u8: u16: u32: u64:    likewise, decimal
    o8: o16: o32: o64:    likewise, octal
    i8: i16: i32: i64:    likewise, signed, two's complement

Scalars are ordered by the `endian` setting (the inspector's, flipped by
Alt+E). An argument without a prefix continues the previous one, width
included, so `find u16:1 2` is two 16-bit values.

Why must every scalar name its width?
- The prefix decides the length, never the value. The old d:, o:, and 0o
  sized themselves to the value (d:255 one byte, d:65536 three), so under
  replace or insert the number decided how much of the file got overwritten.

Why is hex on both sides?
- Two digits are exactly one byte. Decimal and octal do not tile bytes, so
  they are scalars only. 0x survives where 0o went because it is a byte
  string, like x:.

Why is an odd hex digit count an error?
- Padding means guessing which end gains the zero.

Why u32: and i32:, not db/dw/dd?
- They are the type names the program already shows, better known, and do
  not collide with endian suffixes.

Why is endianness a setting and not a prefix?
- It belongs to the file, applies to every scalar and the inspector alike,
  and in the prefix would double every type.

Why does only i* take a sign?
- A minus on an unsigned type is a mistake, not a wrap. There is no bare i:
  or u: either.

Why is a value too large for its width an error?
- Truncating it searches for bytes nobody asked for, and a needle that
  quietly matches the wrong thing is the worst outcome available.

*
* RANGES
*

An integer scalar may be an inclusive range, find u16:1..9, matching any
value from 1 to 9 as a 16-bit value in the endian setting's order. Both ends
take the prefix's rules (sign, width, min/max), and a range is fixed-width,
so it mixes with literals and wildcards. Only searches take one.

Why inclusive?
- It reads as "1 to 9", and address ranges (START:END) are inclusive too.

Why integers only?
- A byte string has no order to range over, and ordering floats means
  handling their bits (signs, NaNs) without a host float; not worth it yet.
  Text ranges can be spelled with scalars (u8:0x41..0x5a is x8:41..5a).

*
* TEXT
*

    utf8:                 bytes, text as typed
    utf16: utf32:         transcoded, one scalar per code unit
    utf8bom: utf16bom:    likewise, preceded by a byte order mark
    utf32bom:
    ascii: cp437:         transcoded, one byte per character, named by the
    ebcdic037: ...        charset setting's ids

utf8: is byte transparent: utf8:"\xff" is one byte, which is what makes
escapes worth having. utf16: and utf32: refuse anything that is not UTF-8,
lone surrogates included; x16: searches an unpaired D800. Code units are
scalars, ordered a half at a time: U+10000 is 00 D8 00 DC little endian.

A mark is U+FEFF in the encoding named, ordered with the text: utf8bom:hi is
EF BB BF 68 69 and utf16bom:hi is FF FE 68 00 69 00. A mark alone is still
x:efbbbf or x16:feff, since an empty prefix is a typo.

A character a single-byte set lacks is an error, never substituted. Raw bytes
go in their own x: argument. Escapes resolve before encoding, so
ebcdic037:"\x25" is '%' (6C), not byte 25.

Why does text name its encoding rather than use the charset setting?
- The encoding belongs to the needle: taking it from the text column makes a
  line mean something that is not in the line, and searching EBCDIC while
  reading ASCII would mean flipping it twice per search. utf8: is the base,
  being D's native format and what readline returns.

Why don't utf16: and utf32: widen bytes that are not UTF-8?
- That would be Latin-1 wearing a UTF-16 name.

Why no utf16le: and utf16be:?
- A code unit is a scalar, so the endian setting already answers it.

Why no mark unless asked for?
- A marked file has it at the front, not before every match.

Why *bom: prefixes, when x: can already spell a mark?
- x:fffe ignores the endian setting and x16:feff is one more thing to know. A
  prefix costs a table row; it saves remembering, under pressure, a mark's
  bytes and how the setting orders them.

Why only the single-byte sets in the charset list?
- Spelled by the charset setting's id, the two share one vocabulary. One id
  per encoding (ebcdic037, not ebcdic, of which there are dozens). Unbounded
  or user-loaded sets would get one parametric form (text(koi8r):, say)
  rather than more flat prefixes.

Why not utf8: for raw bytes next to set text?
- It would splice UTF-8 into EBCDIC.

*
* FLOATS
*

    f32: f64:             IEEE-754 binary32 and binary64, on every host
    f80:                  x87's 80-bit extended: ten bytes, a 64-bit
                          significand with the integer bit stored, then
                          sign and exponent

They encode the value's bit pattern, not its digits. The literal keeps its own
'-', there being no unsigned float, and one that rounds to infinity (f32:1e39)
is too large for its width. Literals are converted from their digits exactly,
never through a host float or a wider format, so the same literal is the same
bytes on every host and f80: gets its full precision and range (f80:1e400).

All three take named constants, since a float's bytes are not recognizable:

    inf                           one encoding, the format says so
    nan qnan snan snan_hi         the NaNs, below
    indefinite                    ...including Intel's
    pi e tau sqrt2 phi            maths, as compiled into binaries
    max min epsilon denorm_min    the format's edges, as used for sentinels

A name is the whole literal, sign aside, case insensitive: "1e5" has an
exponent, "e" is the constant, "f32:pi2" is an error. Each width gets its own
value: f32:max is the largest binary32, not binary64's narrowed to infinity,
and f80:pi is all 64 bits, what FLDPI loads.

Any nonzero mantissa is a NaN, so which one is a choice. They use IEEE's names:

    nan  qnan       7FC00000    quiet, the standard's recommended bit
    snan            7F800001    signaling, so the quiet bit clear, payload 1
    snan_hi         7FA00000    signaling, payload's high bit
    indefinite      FFC00000    Intel's name for the negative quiet NaN

    binary32   0 11111111 1 0000000000000000000000    nan
               0 11111111 0 1000000000000000000000    snan_hi
               0 11111111 0 0000000000000000000001    snan
                 exponent ^ quiet bit

Why f80:, when its width is not a power of two?
- It is what a file holds and what the x86 ABIs call long double.

Why the recommended quiet bit on every host?
- It is IEEE-754's recommendation, followed by x86, ARM, SPARC, POWER and
  RISC-V and inverted by pre-r6 MIPS and PA-RISC. ddhx follows the format,
  not the host.

Why snan_hi?
- It is the highest bit a signaling NaN may set without going quiet, and what
  GCC and glibc's SNANF emit, since it keeps its shape across widths:
  7FA00000 widens to 7FFC000000000000, where 7F800001 becomes
  7FF8000020000000. Any other payload is x32: territory.

Why indefinite, and why does a NaN keep its sign?
- x87 and SSE produce -qnan for invalid operations (ARM produces +qnan),
  making it the NaN most likely in a file. std.conv drops the sign; ddhx
  cannot, or the common case is unreachable.

*
* EXPECTATIONS
*

These are the cases the design is pinned to. The executable copies live in the
unittests of utils.d (splitting and escapes alone), patterns.d (prefixes alone),
and the unittest at the end of patterns.d (both, by typed command line).

  TYPED                             NEEDLE (or result)
  find utf8:a\tb                    'a' 5C 't' 'b'      raw
  find utf8:'a\tb'                  'a' 5C 't' 'b'      raw, quotes buy whitespace
  find utf8:"a\tb"                  'a' 09 'b'          C string
  find utf8:C:\Users                C:\Users            no doubling, no quoting
  find utf8:'C:\Example Space\2'    C:\Example Space\2  quoted only for the space
  find utf8:"C:\\Example Space\\2"  C:\Example Space\2  C string, so doubled
  find utf8:C:\                     C:\                 needle ending in backslash
  find utf8:'C:\'                   C:\                 ...in any of the three
  find utf8:"C:\\"                  C:\                    quoting forms
  find utf8:C:\\Users               C:\\Users           raw, so two is two
  find utf8:\x1b[0m                 5C 'x' '1' 'b' ...  raw, so not an escape
  find utf8:"\x1b[0m"               1B '[' '0' 'm'      C string, so it is
  find utf8:"C:\Users"              error, unknown escape \U
  find utf8:"abc\"                  error, unterminated quote
  find utf8:'C:\Users'"\0"          C:\Users 00         concatenated per run
  find utf8:C:\dir"a b"             C:\dira b           ...same, no rule broken
  find utf8:'it'"'"'s'              it's                a quote needs no escape
  find utf16:hi                     68 00 69 00         code units, per endian
  find utf32:hi                     68 00 00 00 69 00 00 00
  find utf16:<U+1F600>              3D D8 00 DE         a pair, ordered by half
  find utf8:"\xff"                  FF                  transparent, so a byte
  find utf16:"\xff"                 error, nothing to transcode
  find utf16le:hi                   error, byte order is the endian setting's
  find utf8bom:hi                   EF BB BF 68 69      the mark, then the text
  find utf16bom:hi                  FF FE 68 00 69 00   ...ordered like the text
  find utf16bom:a b                 FF FE 61 00 62 00   one needle, one mark
  find utf8bom:                     error, a mark alone is x:efbbbf
  find ebcdic037:Hi                 C8 89               a set, by its charset id
  find ebcdic037:"\x25"             6C                  '%', escapes come first
  find ebcdic037:Hi x:25            C8 89 25            ...raw bytes go in x:
  find ascii:'茅'                    error, not in the set
  find x:1122                       11 22               bytes, as written
  find x16:1122                     22 11               a value, so encoded
  find x:0001                       00 01               no leading zero eaten
  find x:fff                        error, half a byte on the end
  find u16:255                      ff 00               length is the prefix's
  find u16:256                      00 01                  ...not the value's
  find u8:256                       error, too large for its width
  find d:255                        error, unknown prefix; d: named no width
  find i16:-1                       ff ff               two's complement
  find u16:-1                       error, only i* takes a sign
  find u8:max                       ff                  the width's own edge
  find i8:max                       7f                  ...per signedness
  find i8:min                       80                     ...and it is signed
  find u8:min                       00                  unsigned starts at zero
  find i8:-max                      81                  a name takes a sign
  find i8:-min                      error, +128 is the value the width lacks
  find u64:max                      ff ff ff ff ff ff ff ff   beats retyping it
  find u8:maximum                   error, a name is the whole literal
  find f32:1.0                      00 00 80 3F         IEEE-754, not the digits
  find f64:1.0                      00 00 00 00 00 00 F0 3F
  find f32:nan                      00 00 C0 7F         the quiet one, always
  find f32:-nan                     00 00 C0 FF         a NaN keeps its sign
  find f32:indefinite               00 00 C0 FF         ...which x86 hands out
  find f32:snan                     01 00 80 7F         signaling, payload 1
  find f32:pi                       DB 0F 49 40         a name, not digits
  find f32:-pi                      DB 0F 49 C0         ...and it takes a sign
  find f32:max                      FF FF 7F 7F         the format's own edge
  find f32:pi2                      error, a name is the whole literal
  find f32:1e39                     error, rounds to infinity at that width
  find f80:1.0                      00 00 00 00 00 00 00 80 FF 3F    ten bytes
  find f80:pi                       35 C2 68 21 A2 DA 0F C9 00 40    ditto
  find f80:3.14159265358979323846   ...the same, all 64 bits of it.  bit and all
  find f80:1e400                    E6 F9 9F CB C8 3F 76 DA 2F 45    no double
  find f80:1e4933                   error, past the largest finite value
  find x:00 * x:FF                  00 <any> FF
  find u16:1 2                      01 00 02 00         prefix carries, width too
  find utf8:*                       '*'                 prefixed, so data
  find '*'                          <any run>           quoting does not matter
  find "quoted"                     error, unknown prefix; quotes are not a type
  find ''                           no argument at all, can't search nothing
  find utf8:'abc                    error, unterminated quote
  diff-file 'C:\dump.bin'           opens C:\dump.bin   raw, so no escaping
  diff-file "C:\\dump.bin"          opens C:\dump.bin   C string, so doubled
  diff-file "C:\dump.bin"           error, unknown escape \d
  save-as "dump\x2Etxt"             saves dump.txt      escapes are not pattern-only
  save-as "\xff"                    error, argument is not valid UTF-8 text

********************************************************************************
* DOCUMENT EDITOR
********************************************************************************

The default backend is piecev4 (ddhx/editor/piecev4.d), and it is the one
explained here. piecev3 (ddhx/editor/piecev3.d) is a red-black tree over the
same idea, still selectable with DDHX_BACKEND=piecev3; how the two differ is
under DESIGN RATIONALE.

All document editor backends implement IDocumentEditor (ddhx/editor/base.d),
and edit an IDocument (ddhx/document/base.d) instance given to its open()
function.

Conceptually, a piece is a run of bytes in some source: which source, where in
it, and how many bytes. The edited document is its pieces laid end to end, so
an edit only ever rearranges pieces, and the document itself is not touched
until saved.

(See "Piece types" in the VIEWING section for details on each type)

In the diagrams below, "source @N" is a piece reading the opened document from
offset N.

*
* PIECE TABLE
*

The table is two parallel arrays. `ends` holds where each piece stops in the
edited document (exclusive), and `pieces` holds what each piece is:

             0              100     120                 220
             +---------------+-------+-------------------+
  document   | source @0     | buffer| source @100       |
             +---------------+-------+-------------------+

  i   ends[i]   pieces[i]
  0   100       { source=source, position=0,   size=100 }
  1   120       { source=buffer, position=0,   size=20  }
  2   220       { source=source, position=100, size=100 }

Piece i covers [ends[i-1], ends[i]), and the document size is the last end.

A piece's position is relative to its own source and never a document offset,
so `ends` alone describes the layout. Locating an offset is a binary search
over `ends` only, eight to a cache line, without touching `pieces`.

*
* DESIGN RATIONALE
*

Why not using a memory-mapped file? (std.mmfile)
- Inefficient: Specifying size=0 loads the entire file in memory.
- Dangerous: If size is set, seeking past it truncates the file.
- Undeterministic: Depends on specific system functions. Often incompatible.

Why a Piece Table?
- Efficient: Original file data is never duplicated.
- Fast: No need to shift large amounts of data in fixed buffers.
- Natural: Changes are discrete pieces, easier to implement undo/redo.

Why flat arrays over piecev3's red-black tree?
- Cache: A search walks a packed array of offsets instead of chasing pointers
  across scattered nodes.
- Splicing: piecev3 kept cumulative sizes in its nodes, so an edit removed and
  re-inserted every node after it. Here it is one memmove of the tail and an
  addition over the following ends.
- Undo: With no document offsets stored in pieces, reversing an operation is
  splicing its old pieces back in. There is no cumulative bookkeeping to go
  stale.

The memmove is O(n) in pieces, and still beats the tree's constant factors at
any piece count an interactive session produces. Should that stop being true,
an offset scheme (Fenwick) over the same arrays is the next step, not a tree.

*
* OPENING
*

Opening a document clears the history and inserts a single source piece
covering it (none when the document is empty):

  0                                                size
  +------------------------------------------------+
  | source @0                                      |
  +------------------------------------------------+

No operation is recorded, so undoing never unloads the document by accident.

The document's capabilities (DocCaps) set the editing policy:
- Without `resize` (disks, devices), operations changing the size throw.
- Without `stable` (devices, pseudo files), the editor runs in direct mode:
  edits are applied to the table but not recorded, since the medium changes
  outside of our control and history would point at bytes that are gone.

Direct mode, by example:

  /dev/urandom, /dev/zero   character devices, not disks: readable at any
                            offset, with no extent, and not the same bytes
                            twice (urandom)
  /proc/self/maps, /sys/*   pseudo files: regular by their mode, but with no
                            end to seek to, and regenerated on every read
  a type the platform will  claims nothing beyond reading and writing, so
  not state                 it gets the cautious answer

Disks are not in direct mode: a block device (or a BSD character disk)
changes size never and content only through us, so it is stable, only fixed
in size. Process memory, when it gets a document, is the textbook case.

*
* MODIFYING
*

Every edit is an operation: at piece index `index`, the pieces `removed`
became the pieces `added`. Applying it is one splice of the table.

Insert "xyz" at 40, into a 100-byte document. The piece containing the
position is split in two around the new one:

  before  0                                          100
          +------------------------------------------+
          | source @0                                |
          +------------------------------------------+
  after   0             40  43                       103
          +--------------+---+-----------------------+
          | source @0    |xyz| source @40            |
          +--------------+---+-----------------------+

  Operation { index=0, removed=[ source @0 (100) ],
              added=[ source @0 (40), buffer "xyz", source @40 (60) ] }

Inserting at a piece boundary splits nothing, and removes nothing.

Replacing "xyz" at 40 instead, the overwritten range is cut out of the pieces
it spans. A replace running past the end grows the document:

          0             40  43                       100
          +--------------+---+-----------------------+
          | source @0    |xyz| source @43            |
          +--------------+---+-----------------------+

Removing 20 bytes at 40, pieces inside the range are dropped, and the ones
straddling its edges are trimmed:

          0             40                   80
          +--------------+--------------------+
          | source @0    | source @60         |
          +--------------+--------------------+

Inserted and replaced bytes are copied into the add buffer, a list of
append-only blocks (page-sized, or larger for a larger edit), and buffer
pieces point into it. Nothing is freed from it before closing, so pieces kept
in the history always point at valid data.

Pattern edits store the pattern once and repeat it when read, so filling a
gigabyte with zeros only holds one byte in memory.

In debug builds, a consistency check follows every operation, ensuring pieces
have a size and that `ends` follow each other without gaps.

*
* COALESCING
*

Sequential edits are coalesced as one operation, so typing a word is undone
as one word rather than one byte at a time.

An edit coalesces into the previous operation when it is of the same type and:
- insert, replace: it starts where the previous one ended, and its bytes
  follow the previous ones in the add buffer (a new block breaks this, which
  only costs an extra history entry);
- remove: it removes at the same position (forward delete), or ends where the
  previous one started (backward delete).

Undo, redo, opening, closing, and in-place saving reset the coalesce state. An
edit never coalesces into the operation at the save point, or edited() would
report a clean document after it.

*
* HISTORY
*

The history system uses a command-based approach.

No snapshots and no differences are recorded, due to memory concerns. Saving
thousants of snapshots of pieces blew memory usage past a gigabyte.

Only affected pieces are kept in memory as a command, which is all a splice
needs to run in either direction:

  apply    splice(index, index + removed.length, added)
  reverse  splice(index, index + added.length,   removed)

The history is a list with two cursors:

              history_saved     history_index
                    v                 v
  +-----+-----+-----+-----+-----+-----+
  | op0 | op1 | op2 | op3 | op4 | op5 |
  +-----+-----+-----+-----+-----+-----+
                                \_____/ redo

- undo: history_index--, reverse that operation.
- redo: apply the operation at history_index, history_index++.
- edit: drop the redo tail, append, history_index++.
- save: history_saved = history_index.

edited() is history_index != history_saved. When an edit drops a redo tail
holding the save point, the saved state is unreachable, so the document stays
edited until the next save.

In direct mode (see OPENING), there is no history, and a flag tracks edits
instead.

*
* VIEWING
*

Viewing binary searches `ends` for the first piece ending past the position,
then walks pieces forward, reading each one's part into the view buffer:

  view(110, 50 bytes)

             0              100     120                 220
             +---------------+-------+-------------------+
             | source @0     | buffer| source @100       |
             +---------------+-------+-------------------+
                                 |10 |   40   |
                                 +---+--------+
                                110 120      160

  find(110) = 1, ends[1]=120 being the first end past 110
  piece 1: 10 bytes, from 10 bytes into the buffer piece
  piece 2: 40 bytes, from document offset 100

The walk stops when the view buffer is full, at the end of the document, or
at a short read, returning only what was read (e.g., the file shrank under
us).

Piece types:
- source:   The opened document, unmodified (typically a file on disk).
            This is the "main" source that other pieces reference.
- document: Another IDocument instance. Used when inserting content from
            another file, and for the stash (see IN-PLACE SAVING).
- buffer:   Bytes in the add buffer, from inserts and replaces.
- pattern:  Repeated data (e.g., filling with zeros). Its position is the
            phase within the pattern, so a split piece stays in step.

*
* THREADING
*

threadSafe(true) guards the editor with a reader-writer lock (writers
preferred): views, sizes, and dirty region queries run concurrently, and every
mutation takes the write lock. It is off by default, so a single-threaded
client pays nothing for it, and must be set before other threads get the
editor. The measurements behind the lock choice are in a NOTE in threadSafe().

The editor does not lock around document reads: IDocument.readAt must be
reentrant, and documents serialize themselves when they must.

********************************************************************************
* SAVING
********************************************************************************

Saving (view.save) picks between two strategies:

  FULL      Writes the whole edited document to a temporary file next to the
            target, then renames it over the target. Atomic, but writes the
            entire document on disk.
  IN-PLACE  Writes only the modified ranges into the target itself. Costs
            only what changed, but a failure midway leaves a mix of both.

                           save
                             |
        DDHX_NO_INPLACE_SAVE=1? --------------------------- yes -+
                             | no                                |
    replaceable, and writing >= 75% of the document? ---- yes -+ |
                             | no                              | |
                        save_inplace --- throws ---+           | |
                             |                     |           | |
                             |               replaceable? - yes+ |
                             |                     | no        | |
                             v                     v           v v
                           done                  error      full save

"Replaceable" is DocCaps.replace, which regular files have. A disk or device
cannot be renamed over (that would replace the device node with a file), so it
is only ever saved in-place, and an in-place failure is reported as is. The
full save refuses it too, when DDHX_NO_INPLACE_SAVE=1 sends it there.

Past 75% of the document, the full save costs about the same I/O and brings
atomicity with it. In-place saving throws, before writing anything, when the
target does not exist, cannot be opened read-write (e.g., GVFS), or when the
edits cannot be written in-place safely (below).

*
* IN-PLACE SAVING
*

When able, instead of saving the entire documet to disk to save I/O, ddhx will
attempt to save to the target "in-place", only writing modified regions.

The difficulty is that the file being written is also the file being read.
Source pieces read the target's old bytes, and an insert or a remove shifts
them: a source piece whose position no longer matches its document offset is
displaced, and must be written to its new place.

Take a file of 8 bytes, and insert "xy" at 2:

  file       0 1 2 3 4 5 6 7
             A B C D E F G H

  document   0 1 2 3 4 5 6 7 8 9
             A B x y C D E F G H
             +---+---+-----------+
             |s@0|buf| source @2 |     source @2 is displaced
             +---+---+-----------+

  piece       reads file   writes file
  source @0   [0,2)        -             same place, not written
  buffer      -            [2,4)
  source @2   [2,8)        [4,10)
                   \______/
                    [4,8) is overwritten while still to be read

Writing source @2 front to back, in chunks, overwrites E F before they are
read, and the tail comes out repeated rather than shifted. Back to front works
here, but not in general: two pieces trading places each read what the other
writes, and no order is correct.

Current pieces are also not the only readers. The history keeps its own
source pieces (op0 removed source @0, all 8 bytes), and undoing after the save
would read the new bytes as if they were the old ones.

prepareInplaceSave() fixes both before anything is written. It copies aside,
in a stash, the old bytes of every range the save overwrites that any piece,
current or in history, still reads:

  1. Written ranges: every dirty or displaced piece's document range, and
     everything past the new end (truncated away), merged.
                     [2,4) + [4,10) + [10,max)  ->  [2,max)
  2. Read ranges: every source piece in the table and in the history,
     merged.
                     [0,2) + [2,8) + [0,8)      ->  [0,8)
  3. Capture their intersection into the stash.
                     [2,8) = C D E F G H
  4. Retarget every source piece reading a written range at the stash,
     keeping its position.

  stash      0 1 2 3 4 5 6 7
             . . C D E F G H          '.' reads through to the file

  document   +---+---+-----------+
             |s@0|buf| stash @2  |
             +---+---+-----------+
  history    op0 removed [ stash @0 (8) ]     was source @0 (8)

What still reads the file only reads ranges the save leaves alone, so pieces
can be written in any order (save_inplace):

  1. Extend the file, if the document grew.
                     A B C D E F G H . .
  2. Write every dirty or displaced piece.
                     A B x y C D E F G H
  3. Shrink the file, if the document shrank.
  4. Flush, and mark the history as saved.

Undo still works afterwards: op0 reverses into stash @0, which reads A B from
the file, where the save left them, and C D E F G H from the stash.

The stash is sparse because a history piece commonly spans the whole file
(or disk), and copying it whole would cost its full size rather than the
bytes that changed. It stays with the editor across saves: a later save only
captures what is not already held, since the bytes held are older and are the
ones pieces expect. Stash pieces count as readers in step 2, as they read
through to the file for whatever they do not hold.

The stash lives in memory, so preservation is skipped past a write volume of
CONFIG_INPLACE_STASH_BUDGET (64 MiB). Without it:
- With no displaced piece, only buffer, pattern, and document pieces are
  written, none of which read the file, so the save proceeds. The history
  still reads old bytes, so the document is reopened afterwards, losing it.
- With a displaced piece, no write order is safe, so it throws before writing
  and the full save takes over (if replaceable).

Write order used to be solved with a dependency graph (Kahn's algorithm). The
stash replaced it, since a graph cannot order a cycle, and ordering writes
does nothing for the history.

This works similarly to HexFiend (BSD-2-Clause), which also inspired this
feature to be implemented. More like, Hex Friends.