







With the page space finished, the next character of the layout editor became clear. Placing shapes and images at exact positions is not enough to edit a book. A manuscript changes in length, and every time the font, leading or trim size changes, the boundaries of lines, paragraphs and pages move together. Typesetting was not a matter of computing coordinates once; it was the problem of continually re-solving for a layout that satisfies many constraints.
Browsers have flow-based layout engines too, but the objective function of publishing typesetting is a little different. A screen can extend downward without limit to fit the available width, while a book is divided into a finite sequence of page boxes. Depending on where to cut a paragraph, how far to avoid orphan and widow lines, and whether to keep a figure and its caption on the same page, several possible solutions arise. A simple overflow check alone could not define good typesetting.
I saw this problem as a composition system more than as a feature for moving text between boxes. Free coordinates and flow-based structure, paragraph meaning and physical pages all meet in one constraint system. Even with the same input string, the solution changes if the font metrics and widths change, and under the same conditions the result must be identical no matter when it is computed. At this stage I reorganized typesetting in the language of graphs, optimization and fixed-point computation.
A book's page is not made up of absolute coordinates alone. There are areas where an image and its description sit side by side, where several items follow one another at regular intervals, or where items must wrap to the next line when the width shrinks. Such arrangements are described more accurately by a formatting context than by a list of coordinates. The container sets the main axis and cross axis, and each child submits its minimum size, preferred size and capacity to grow as constraints.
Let the available length be A, a child's base length `b_i`, its grow factor `g_i` and its shrink factor `s_i`; layout is then the problem of distributing the difference between `Σb_i` and A among the children. With slack, you divide it by the grow ratios; with a shortage, you reduce considering the shrink factors and base sizes together. However, once an item appears that cannot go below its minimum content size, the remaining items must be recomputed, so it is closer to an active-set problem than to a single proportional formula.
When wrapping is allowed, the problem changes from 1D distribution to interval partitioning. Keeping the children's order, you decide at which point to start the next line, and recompute the leftover space and alignment for each line. The number of possible partitions grows quickly with the number of items, but in a real editor a local greedy solution with minimum-size constraints alone can produce predictable results. What mattered was distinguishing computed results from the constraints the user specified.
From this viewpoint, flow inside a fixed page was not a special exception either. Free coordinates are strong constraints that determine position directly, and flow containers are weak constraints that determine position through relationships. Both are ultimately expressed as transforms and size constraints in the scene graph. Even though the tools look different, the internal math settled into a combination of variables, constraints and computed solutions.
The difference between free placement and flow placement lies less in the kind of object than in who decides the coordinates. In free placement, `(x, y, w, h)` are close to independent variables, while in flow placement, once order, minimum sizes and alignment rules are given, the coordinates become computed results. Moving from one representation to the other is not changing the DOM but swapping the roles of independent and dependent variables.
Inferring structure from a free-placement result is essentially an inverse problem. The same screen can be explained by several structures. Two elements sitting side by side might be one row, or two independent objects that happen to share the same y coordinate. Since the original intent cannot be uniquely recovered from observed geometry alone, criteria like minimum description length and stability are needed. A structure that explains the current layout with few rules while preserving relationships even when the screen width changes makes the better candidate.
Conversely, fixing a flow structure into free coordinates is forward evaluation. You evaluate the constraint system once and convert the resulting box geometry into coordinates in document space. Here, screen zoom and viewport movement are merely observation transforms, so they must be removed by the inverse matrix. The resulting coordinates must belong to the reference space defined by the document, not to the screen the user was looking at.
This round trip is not a perfect inverse. The moment you fix things to free coordinates, information such as wrapping possibilities and relative alignment can vanish, and when you infer the structure again, the same solution is not guaranteed. So I looked at the conversion from the standpoint of information preservation, and clearly distinguished the degrees of freedom lost from the constraints newly created. The relationship between paper typesetting and responsive documents could also be understood as a combination of the same inverse problem and forward computation.
Body typesetting started from the relationship between the manuscript's logical order and the physical regions that hold it. A manuscript is one linear sequence, but a page is divided into several boxes. Viewed as a graph, text segments are ordered vertices, frames are compartments with capacity, and typesetting is a function that maps segments to compartments while preserving order. Even when the pages on screen are split, the topological order of the manuscript must not break.
The key invariants needed in the graph are connectedness and acyclicity. If a single story branches or has a cycle, the next sentence can split into two places or circle endlessly through the same frame. So a valid flow is closer to a path graph than a general graph, and strong restrictions apply to the in-degree and out-degree of each vertex. This condition is not about a particular storage method; it is a mathematical property of the typesetting model itself.
When frames are added or removed by editing, what must be preserved is the manuscript sequence rather than the objects on screen. Before and after a graph transformation, the relative order of all characters and paragraphs must be the same, and no segment may be duplicated or lost. This can be seen as multiset preservation and an order-preserving mapping. As structural changes grow larger, verifying this global invariant is stronger than checking individual pointers.
In a partially observed graph, global typesetting cannot be fixed. This is similar to how a distributed system cannot judge the whole state from an incomplete view. If the needed segments are not ready, it is safer to defer the computation and evaluate the same story once, when the complete boundary conditions are in place. Reducing computation in large documents was also, in the end, the problem of finding which part of the graph affects the current solution.
Line breaking was not a matter of filling characters to the width and cutting when they overflow. The real input is closer to a glyph sequence than to characters. After ligatures, kerning, Hangul composition and script shaping, the number of characters and the number of displayed glyphs differ, and a line's width is determined by the sum of each glyph's advance and the adjustable spaces. I first had to distinguish linguistic boundaries from the break opportunities available for typesetting.
The quality of one line can be evaluated by a single quantity, the leftover space. If the target width is W, the line's natural width N, the stretchable space S and the shrinkable amount R, the adjustment ratio is `(W-N)/S` or `(W-N)/R` depending on the sign of the leftover. If this ratio is too large the spaces open up, and if it is too small the letters feel cramped. If you set badness as something like the cube of the ratio, you can tell several slightly bad lines apart from one very bad line.
Line breaking for a whole paragraph turns into a shortest-path problem on a DAG whose vertices are the possible break points. If the stretch between two break points can be a line, you create an edge and set that line's badness and hyphen penalty as its cost. If you find the path with the smallest total cost by dynamic programming, the paragraph's overall gray value comes out more even than with a greedy method that only fits the last line. The reason Knuth-Plass style typesetting is strong is that it optimizes the whole paragraph, not a single line.
At page boundaries the cost function grows further. Separate penalties are needed when only the first or last line of a paragraph is left on another page, when a heading is split from its body, or when a footnote appears before its reference. Typesetting becomes an optimization with many semantic constraints, not string splitting. Results were reproducible only after even the tie-break rules were decided, so that the same input and metrics select the same minimum-cost solution.
Typesetting looks like a process of content being pushed out in one direction, but mathematically it is closer to an iterative computation that seeks a stable state. If the current layout is `x_n` and the typesetting operation is F, the next state is `x_(n+1) = F(x_n)`. The `x = F(x)` at which line and page boundaries no longer change is the fixed point. Even when text grows or shrinks, repeating the same operation must converge to a new stable point.
To guarantee convergence, state changes need monotonicity. If content sent backward to reduce overflow comes back forward by some arbitrary rule within the same pass, oscillation can occur. You can fix the direction and priority of computation and put in a potential function so that the amount of violation each step tries to resolve decreases. For example, you check whether a weighted sum of every frame's excess height and its empty space toward the front decreases at each iteration.
But if a font changes late, or an image size is settled asynchronously, the function F itself changes mid-computation. Convergence cannot be discussed for a moving objective, so you first have to fix a single layout epoch in which metrics and assets are ready. Within one epoch, inputs and constraints are held immutable, and when new information arrives, instead of modifying the earlier computation you re-evaluate in a new epoch.
For the termination condition as well, it is better to use a meaningful state difference rather than a simple iteration count. If the per-page break points and the overset set have become the same, the typesetting result can be considered stable even if small floating-point errors remain in the geometry. Conversely, if the break points swing back and forth between two states, you detect the cycle and fall back to safer constraints. A deterministic solution in finite time mattered more to an editor than a theoretically perfect one.
The latter part of a paragraph that crosses a frame is not a new paragraph. In the logical tree it is one block, but in physical typesetting it appears as several fragments. Here you have to distinguish properties that apply only to the start of the paragraph, such as margin, first-line indent and drop cap, from backgrounds and borders that must repeat on each fragment. A fragmentation context starts by abandoning the assumption that logical objects and physical pieces are one to one.
Seen as a function, a single box B is decomposed by the page constraint P into `F_P(B) = {b_1, b_2, ..., b_k}`. Joining the contents of the pieces in order must give back the original B, and the inner intervals of the pieces must not overlap. In other words, fragmentation is an order-preserving partition. When the page width changes, you must apply the new P to the original B rather than re-cutting the old pieces, so that idempotence is maintained.
Styles have different fragmentation laws per property as well. First-line style applies only to the first line box of the first piece, space before the paragraph belongs to the first piece, and space after belongs to the last piece. Line-height and font, on the other hand, are inherited by all pieces. Rather than scattering these rules as individual exceptions, it is more general to classify which repetition meaning a property has: `first`, `last`, `each` or `slice`.
Widows and orphans are global constraints on this partition. If you simply choose the maximum number of lines that fit on the current page, only one line may be left on the next. If you move the break point earlier to satisfy a minimum starting-line count and a minimum ending-line count, the current page gets some empty space but the paragraph's reading rhythm improves. The correctness of typesetting lay in correctly preserving the logical structure in the physical pieces, more than in filling space to the end.
Text being typeset does not exist only in a completed document state. Korean, Japanese and Chinese input methods in particular have an intermediate state that composes several keystrokes into one committed string. This state is not yet fully committed to the document but must be visible on screen. The editor had to treat committed text and composing text as states with different lifetimes.
Viewing the input process as a state machine gives the transitions `idle -> composing -> committed`. During composing, the browser and the input method jointly manage the temporary string and selection range, so if an external typesetter rebuilds the tree, ownership of the transition breaks. A safe principle regardless of language is to restrict structural changes in the intermediate state and reflect them in the logical document after the commit event arrives.
The caret, too, is more accurately seen as a position on the manuscript sequence than as the address of a DOM node. The on-screen tree can disappear and reappear with typesetting, but a logical position can be expressed as a boundary counted from the document start, or as a position between adjacent stable tokens. Even if the trees before and after re-typesetting differ, finding the same logical boundary again in the new fragment keeps the editing feel continuous. It is similar to how a syntax editor distinguishes source offsets from syntax nodes.
From a concurrency viewpoint, input and layout are different transactions. If layout reads an intermediate value as the authoritative manuscript while the input transaction is not yet committed, the same event can be applied twice or a composing string can be split. I defined the input's commit boundary first and made typesetting read only the last committed revision. Editing stability and the accuracy of the final typesetting were maintained together through this revision boundary.
Pagination was a partition problem at a larger unit than line breaking. You list paragraphs, figures and tables in order and divide them into intervals so that none exceeds each page's capacity. Unlike simple bin packing, the order of items cannot be changed, some items are splittable, and there are relationships like a heading that must stay with the next paragraph. It was an ordered capacitated partition with semantic penalties attached.
If you put the possible page breaks as vertices, it can again be seen as a DAG shortest path. If the interval `(i, j)` fits on one page, you create an edge, and assign costs to the square of the leftover margin, widows and orphans, keep-with-next violations and forced splits. Choosing the path with the smallest total cost lets you lay out even the later pages evenly, more than a greedy solution that fills the current page as full as possible.
Once floats and footnotes come in, the constraints become interdependent. Which page the body goes on determines the footnote height, and the footnote height in turn reduces the body's capacity. In this case you alternately compute the body layout and the height of the auxiliary regions to find a fixed point, or, if it does not converge within a set number of iterations, choose a more conservative break. A deterministic and explainable solution mattered more to an editor than an optimal solution for every case.
Adding and removing pages is a by-product of this optimization result. Even if a single user input changes several page breaks, it should be seen as one document transformation semantically. If the difference between the input revision and the new partition is handled as one command, rather than as individual DOM changes in the typesetting result, the manuscript and the structure can keep the same time axis in undo as well.
The history of a multi-page editor had to be the logical time of the whole document, not a per-screen stack. A single command can change several pages and assets at once, so if you revert only part of the state, nonexistent references or different revisions get mixed. Like a database transaction, all the writes of one action must be seen together or not at all.
There are two extremes for representing history: snapshots and operation logs. Snapshots make restoration simple but use a lot of space in large documents, and operations are small but an inverse operation does not always exist. Even a reversible command like rotation cannot guarantee the original bytes by simply applying the same operation in reverse once external asset replacement or automatic typesetting is involved. In a real system a hybrid that mixes semantic commands with snapshots of the needed scope is the natural choice.
Serializability is needed for multiple asynchronous tasks as well. If user input A, automatic typesetting B and saving C overlap and the final state is not equal to any sequential execution, the history and the persisted state diverge. Based on revisions, you check the state each task read and the state it wants to write, and a result that started from an old revision must not overwrite a newer state. This was the same problem as optimistic concurrency control.
The purpose of autosave is not to record every intermediate screen but to make the last committed revision durable. If a new revision appears during a save, it is easier to guarantee ordering by finalizing the latest revision again after the previous write finishes, rather than racing two saves. By making explicit how the history head relates to the saved revision, undo, redo and restore after restart all came into a single time model.
Once pages grow to hundreds, loading every scene, font and image into memory at the same time is no longer sustainable. The concept needed here was separating the whole document from the current working set. It is enough to keep in the fast tier only the pages the user is viewing or is likely to view soon, the pages that affect the story being edited, and the state referenced by recent history.
The working set is wider than a simple set of rectangles intersecting the screen. The neighbors of the current page are likely to be visited soon, and the segments before and after linked text are needed for re-typesetting. Conversely, even if they are visible, there is no need to keep the detailed DOM of dozens of pages shrunk very small. Using spatial distance, temporal locality and semantic dependency together makes the cache policy match the editing feel.
Eviction is not an act of freeing memory but one that is possible only after proof that the authoritative state safely exists in another tier. Dirty state, values being computed and values referenced by undo must be pinned, and items that are costly to reconstruct are worth keeping longer than plain LRU would. A cost-weighted cache takes into account item size, regeneration time and access probability together.
Full output and global re-typesetting are separate computations to which working-set optimization does not apply. All semantic state is needed then, but not all the UI for editing. If you separate reading the document model from building all the on-screen objects, even the full computation can stream within a memory ceiling. The performance of large documents depended less on one fast function than on which state gets materialized and when.
At this stage the layout editor went beyond a tool for placing text boxes on a page. I viewed free coordinates and formatting contexts as one constraint system, organized manuscript order as an acyclic story graph, and framed line breaking and pagination as shortest-path problems with penalties. I kept the invariant that a paragraph is logically one, even when it becomes several fragments on physical pages.
Typesetting converges to the fixed point of an iterative operation, and the input method's composition state and caret are tied to the logical document revision, not the physical DOM. I treated history and autosave as serializable transactions, and for large documents I materialized only the working set reflecting spatial, temporal and semantic locality. Features that had looked unrelated became one system within graph theory, optimization, transactions and cache theory.
I repeatedly checked it with combinations of short paragraphs and very long ones, multiple writing systems, extreme font metrics, orphan and widow lines, trim size changes and large documents. I confirmed that the same input and constraints produce the same break points, and that the manuscript's order and paragraph meaning hold through revision switches, saves and memory pressure. A typesetting engine that keeps its logical structure as the manuscript crosses pages was fully implemented and stabilized at this stage.
