oficina / mapa Public

Columns, phase 2 (WIP): the layout grammar in Go and its port, rendering, Join's seams, and the merge's layout rules

Go: fences are blocks (columns, column, column_end, columns_end) with
Column on every block inside a layout; the strict scan of spec 1.1;
renderLayout; Join's Quarto seams; ValidLayouts, the opaque-conflict
check, the whole-layout second pass, fence alignment by content, and a
column added beside an edit merging cleanly. editor/markup.mjs ports the
grammar. The editor's schema, serialiser and commands are next.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 184668f83c8c4709c649bb10c7da653ee9d27a77 parent 0eed5a4
9 files changed, +928 −30
  • editor/markup.mjs +147 −5
  • internal/mapa/markup/blocks.go +45 −9
  • internal/mapa/markup/columns.go +222 −0
  • internal/mapa/markup/columns_test.go +142 −0
  • internal/mapa/markup/merge.go +36 −11
  • internal/mapa/markup/merge_columns.go +206 −0
  • internal/mapa/markup/merge_columns_test.go +121 −0
  • internal/mapa/markup/render.go +4 −0
  • internal/mapa/markup/settle.go +5 −5

CI failed — run details

CI log
=== editor ===
cd editor && npm ci --no-audit --no-fund --loglevel=error

added 16 packages in 313ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.65227d861604d067.js (355907 bytes, 111.9KB gzipped; L12 budget 120KB)
D	internal/mapa/static/editor.115ddee5d3f54787.js
internal/mapa/static/editor.65227d861604d067.js
make editor: internal/mapa/static/editor.*.js does not match a fresh build; commit the rebuilt bundle
make: *** [Makefile:108: editor] Error 1

amadan: step editor failed: exit status 2

amadan: job failed at step editor — its output is above, not at the tail of this log
diff --git a/editor/markup.mjs b/editor/markup.mjs
index d0435f2..89d5e72 100644
--- a/editor/markup.mjs
+++ b/editor/markup.mjs
@@ -26,6 +26,14 @@ export const Code = 'code'
export const Quote = 'quote'
export const Rule = 'rule'
+// The column layout's fence kinds (columns and icons spec §1.4), and
+// the block grammar's version (D17), markup.Grammar.
+export const Columns = 'columns'
+export const Column = 'column'
+export const ColumnEnd = 'column_end'
+export const ColumnsEnd = 'columns_end'
+export const Grammar = 2
+
export const Text = 'text'
export const InCode = 'code'
export const WikiLink = 'wiki'
@@ -106,13 +114,26 @@ export function parse (body) {
offsets.push(offsets[offsets.length - 1] + utf8Length(line) + 1)
indexes.push(indexes[indexes.length - 1] + line.length + 1)
}
+ return parseLines(lines, offsets, indexes, 0, lines.length, layouts(lines))
+}
+
+// parseLines is markup.parseLines: lines[from:to], every offset the
+// body's own; found is the whole column layouts by their opener's line.
+function parseLines (lines, offsets, indexes, from, to, found) {
+ const view = lines.slice(0, to)
const blocks = []
- for (let index = 0; index < lines.length;) {
- if (goTrimSpace(lines[index]) === '') {
+ for (let index = from; index < to;) {
+ if (goTrimSpace(view[index]) === '') {
index++
continue
}
- const [block, next] = parseBlock(lines, index)
+ const whole = found?.get(index)
+ if (whole) {
+ blocks.push(...parseLayout(lines, offsets, indexes, whole))
+ index = whole.close + 1
+ continue
+ }
+ const [block, next] = parseBlock(view, index)
block.marker = marker(block)
block.start = offsets[index]
block.end = block.start + utf8Length(block.source)
@@ -120,14 +141,134 @@ export function parse (body) {
// the normalised body, for the editor's own slicing (fidelity.mjs).
block.from = indexes[index]
block.to = block.from + block.source.length
+ block.column = 0
blocks.push(block)
index = next
}
return blocks
}
+const layoutOpener = /^(:{4,})[ \t]+columns[ \t]*$/u
+const columnOpener = /^(:{3,})[ \t]+column[ \t]*$/u
+const fenceLike = /^[ \t]*:::/u
+
+// fenceLike is markup.FenceLike: a line whose text, after any spaces and
+// tabs, starts with ":::".
+export function isFenceLike (line) { return fenceLike.test(line) }
+
+// isFence is markup.IsFence.
+export function isFence (kind) {
+ return kind === Columns || kind === Column || kind === ColumnEnd ||
+ kind === ColumnsEnd
+}
+
+function closesWith (line, colons) {
+ const trimmed = line.replace(/[ \t]+$/u, '')
+ return trimmed.length === colons && /^:+$/u.test(trimmed)
+}
+
+const blank = line => goTrimSpace(line) === ''
+
+// layouts is markup.layouts: the scan, exactly (spec §1.1).
+function layouts (lines) {
+ const found = new Map()
+ let fence = ''
+ for (let index = 0; index < lines.length; index++) {
+ const line = lines[index]
+ if (fence !== '') {
+ if (closesFence(line, fence)) fence = ''
+ continue
+ }
+ const opened = fenceLine.exec(line)
+ if (opened) {
+ fence = opened[1]
+ continue
+ }
+ if (index > 0 && !blank(lines[index - 1])) continue
+ const whole = readLayout(lines, index)
+ if (whole) {
+ found.set(index, whole)
+ index = whole.close
+ }
+ }
+ return found
+}
+
+function readLayout (lines, start) {
+ const match = layoutOpener.exec(lines[start])
+ if (!match) return null
+ const outer = match[1].length
+ const whole = { open: start, close: 0, columns: [] }
+ for (let at = skipBlank(lines, start + 1); at < lines.length;) {
+ const line = lines[at]
+ if (closesWith(line, outer)) {
+ const ends = at + 1 === lines.length || blank(lines[at + 1])
+ const count = whole.columns.length
+ whole.close = at
+ return ends && count >= 2 && count <= 4 ? whole : null
+ }
+ const inner = columnOpener.exec(line)
+ if (!inner || inner[1].length >= outer || whole.columns.length === 4) {
+ return null
+ }
+ const end = columnEnd(lines, at + 1, inner[1].length)
+ if (end < 0) return null
+ whole.columns.push([at, end])
+ at = skipBlank(lines, end + 1)
+ }
+ return null
+}
+
+function columnEnd (lines, start, colons) {
+ let fence = ''
+ for (let at = start; at < lines.length; at++) {
+ const line = lines[at]
+ if (fence !== '') {
+ if (closesFence(line, fence)) fence = ''
+ } else if (fenceLine.test(line)) {
+ fence = fenceLine.exec(line)[1]
+ } else if (closesWith(line, colons)) {
+ return at
+ } else if (fenceLike.test(line)) {
+ return -1
+ }
+ }
+ return -1
+}
+
+function skipBlank (lines, at) {
+ while (at < lines.length && blank(lines[at])) at++
+ return at
+}
+
+function fenceBlock (kind, lines, offsets, indexes, line, column) {
+ const made = block(kind, lines[line], { column })
+ made.start = offsets[line]
+ made.end = made.start + utf8Length(made.source)
+ made.from = indexes[line]
+ made.to = made.from + made.source.length
+ return made
+}
+
+function parseLayout (lines, offsets, indexes, whole) {
+ const opener = fenceBlock(Columns, lines, offsets, indexes, whole.open, 0)
+ opener.level = whole.columns.length
+ const blocks = [opener]
+ whole.columns.forEach(([open, close], number) => {
+ const column = number + 1
+ blocks.push(fenceBlock(Column, lines, offsets, indexes, open, column))
+ for (const inside of parseLines(lines, offsets, indexes, open + 1, close, null)) {
+ inside.column = column
+ blocks.push(inside)
+ }
+ blocks.push(fenceBlock(ColumnEnd, lines, offsets, indexes, close, column))
+ })
+ blocks.push(fenceBlock(ColumnsEnd, lines, offsets, indexes, whole.close, 0))
+ return blocks
+}
+
function block (kind, source, extra = {}) {
- return { kind, source, level: 0, ordered: false, marker: '', ...extra }
+ return { kind, source, level: 0, ordered: false, marker: '', column: 0, ...extra }
}
function parseBlock (lines, start) {
@@ -184,7 +325,7 @@ function startsBlock (line) {
}
function marker (block) {
- if (block.kind === Code || block.kind === Rule) return ''
+ if (block.kind === Code || block.kind === Rule || isFence(block.kind)) return ''
const last = block.source.slice(block.source.lastIndexOf('\n') + 1)
const match = markerTail.exec(last)
return match ? match[1] : ''
@@ -193,6 +334,7 @@ function marker (block) {
// plain is markup.Plain (and Strip): a block's words without its syntax.
export function plain (block) {
let text = block.source
+ if (isFence(block.kind)) return ''
switch (block.kind) {
case Code: return codeText(text)
case Heading: text = trimLeft(text, '# \t'); break
diff --git a/internal/mapa/markup/blocks.go b/internal/mapa/markup/blocks.go
index 96242f8..8cbee41 100644
--- a/internal/mapa/markup/blocks.go
+++ b/internal/mapa/markup/blocks.go
@@ -41,6 +41,11 @@ type Block struct {
// Start and End are the block's byte offsets in the normalised body:
// body[Start:End] == Source.
Start, End int
+ // Column is, for a block inside a column layout and for that
+ // column's own fences, the column it belongs to, 1 to 4; 0 anywhere
+ // else (columns and icons spec §1.4). It is a position, derived:
+ // the merge never compares it.
+ Column int
}
var (
@@ -60,13 +65,27 @@ func Parse(body string) []Block {
for index, line := range lines {
offsets[index+1] = offsets[index] + len(line) + 1
}
+ return parseLines(lines, offsets, 0, len(lines), layouts(lines))
+}
+
+// parseLines parses lines[from:to], every offset the body's own. found
+// is the whole column layouts, by their opener's line; a column's own
+// lines are parsed with none (no nesting).
+func parseLines(lines []string, offsets []int, from, to int,
+ found map[int]layout) []Block {
+ view := lines[:to]
var blocks []Block
- for index := 0; index < len(lines); {
- if strings.TrimSpace(lines[index]) == "" {
+ for index := from; index < to; {
+ if strings.TrimSpace(view[index]) == "" {
index++
continue
}
- block, next := parseBlock(lines, index)
+ if whole, ok := found[index]; ok {
+ blocks = append(blocks, parseLayout(lines, offsets, whole)...)
+ index = whole.close + 1
+ continue
+ }
+ block, next := parseBlock(view, index)
block.Marker = marker(block)
block.Start = offsets[index]
block.End = block.Start + len(block.Source)
@@ -160,7 +179,7 @@ func startsBlock(line string) bool {
// marker is a block's ^id: the last thing on its last line. A code block
// never has one; its text is code.
func marker(block Block) string {
- if block.Kind == Code || block.Kind == Rule {
+ if block.Kind == Code || block.Kind == Rule || IsFence(block.Kind) {
return ""
}
last := block.Source[strings.LastIndex(block.Source, "\n")+1:]
@@ -171,25 +190,42 @@ func marker(block Block) string {
}
// Join puts blocks back together: a blank line between blocks, except
-// between two list items, which stay a tight list.
+// between two list items, which stay a tight list, and inside a column
+// layout's fences (seam).
func Join(blocks []Block) string {
var out strings.Builder
for index, block := range blocks {
if index > 0 {
- out.WriteString("\n")
- if block.Kind != Item || blocks[index-1].Kind != Item {
- out.WriteString("\n")
- }
+ out.WriteString(seam(blocks[index-1], block))
}
out.WriteString(block.Source)
}
return out.String()
}
+// seam is Join's bytes between two neighbours. Fences are written as
+// columns and icons spec §1.4 says: one newline after a column's opener
+// (and between an empty column's two fences), a blank line everywhere
+// else, before a column's closer included, so no reader's lazy
+// continuation can carry a line into it.
+func seam(before, after Block) string {
+ switch {
+ case before.Kind == Column:
+ return "\n"
+ case before.Kind == Item && after.Kind == Item:
+ return "\n"
+ }
+ return "\n\n"
+}
+
// Plain is a block's words without its syntax: the list marker, heading
// hashes, quote marks and ^id. Backlink context and search read it.
func Plain(block Block) string {
text := block.Source
+ if IsFence(block.Kind) {
+ // A fence holds no words (columns and icons spec §1.4).
+ return ""
+ }
switch block.Kind {
case Code:
return codeText(text)
diff --git a/internal/mapa/markup/columns.go b/internal/mapa/markup/columns.go
new file mode 100644
index 0000000..5f1f156
--- /dev/null
+++ b/internal/mapa/markup/columns.go
@@ -0,0 +1,222 @@
+package markup
+
+import (
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// Column layouts (columns and icons spec §1): Pandoc's fenced divs, in
+// the strict form Mapa reads and writes.
+//
+// :::: columns
+//
+// ::: column
+// The left column's blocks.
+//
+// :::
+//
+// ::: column
+// The right column's blocks.
+//
+// :::
+//
+// ::::
+//
+// A layout is recognised only when it is whole (§1.1's six rules).
+// Anything less is today's text, byte for byte and meaning for meaning.
+// Its four kinds of fence line are blocks of their own (§1.4), so the
+// merge, Replace, Settle and block indices keep working on one flat
+// list; the blocks between them know their column.
+
+// The fence kinds.
+const (
+ Columns = "columns"
+ Column = "column"
+ ColumnEnd = "column_end"
+ ColumnsEnd = "columns_end"
+)
+
+// Grammar is the block grammar's version (D17): 2 from the column
+// layout. Every route that posts a block index sends it back.
+const Grammar = 2
+
+var (
+ layoutOpener = regexp.MustCompile(`^(:{4,})[ \t]+columns[ \t]*$`)
+ columnOpener = regexp.MustCompile(`^(:{3,})[ \t]+column[ \t]*$`)
+ fenceLike = regexp.MustCompile(`^[ \t]*:::`)
+)
+
+// FenceLike is the one predicate for a line that looks like a fence:
+// its text, after any spaces and tabs, starts with ":::". The grammar's
+// rule 5, the editor's neutraliser and the importer's all use it.
+func FenceLike(line string) bool { return fenceLike.MatchString(line) }
+
+// IsFence reports whether kind is one of the layout's fence kinds.
+func IsFence(kind string) bool {
+ return kind == Columns || kind == Column || kind == ColumnEnd ||
+ kind == ColumnsEnd
+}
+
+// closes reports whether line is exactly colons colons and blanks.
+func closes(line string, colons int) bool {
+ trimmed := strings.TrimRight(line, " \t")
+ return len(trimmed) == colons && strings.Count(trimmed, ":") == colons
+}
+
+// layout is one recognised layout: its opener and closer lines, and each
+// column's opener and closer lines.
+type layout struct {
+ open, close int
+ columns [][2]int
+}
+
+// layouts finds every whole layout, scanning top to bottom (§1.1, "The
+// scan, exactly"): outside a code fence, at an opener that starts a
+// block, it tries a whole layout; on success the scan resumes after its
+// closer, on failure at the very next line.
+func layouts(lines []string) map[int]layout {
+ found := map[int]layout{}
+ fence := ""
+ for index := 0; index < len(lines); index++ {
+ line := lines[index]
+ if fence != "" {
+ if ClosesFence(line, fence) {
+ fence = ""
+ }
+ continue
+ }
+ if match := fenceLine.FindStringSubmatch(line); match != nil {
+ fence = match[1]
+ continue
+ }
+ if index > 0 && strings.TrimSpace(lines[index-1]) != "" {
+ continue
+ }
+ if whole, ok := readLayout(lines, index); ok {
+ found[index] = whole
+ index = whole.close
+ }
+ }
+ return found
+}
+
+// readLayout reads a whole layout opening at start, by rules 2 to 6.
+func readLayout(lines []string, start int) (layout, bool) {
+ match := layoutOpener.FindStringSubmatch(lines[start])
+ if match == nil {
+ return layout{}, false
+ }
+ outer := len(match[1])
+ whole := layout{open: start}
+ for at := skipBlank(lines, start+1); at < len(lines); {
+ line := lines[at]
+ if closes(line, outer) {
+ ends := at+1 == len(lines) ||
+ strings.TrimSpace(lines[at+1]) == ""
+ count := len(whole.columns)
+ whole.close = at
+ return whole, ends && count >= 2 && count <= 4
+ }
+ inner := columnOpener.FindStringSubmatch(line)
+ if inner == nil || len(inner[1]) >= outer ||
+ len(whole.columns) == 4 {
+ return layout{}, false
+ }
+ end, ok := columnEnd(lines, at+1, len(inner[1]))
+ if !ok {
+ return layout{}, false
+ }
+ whole.columns = append(whole.columns, [2]int{at, end})
+ at = skipBlank(lines, end+1)
+ }
+ return layout{}, false
+}
+
+// columnEnd is the line that closes a column whose fence is colons long,
+// reading from start. Code fences are tracked as Parse tracks them; any
+// other fence-like line, or no closer, is no column (rules 4 and 5).
+func columnEnd(lines []string, start, colons int) (int, bool) {
+ fence := ""
+ for at := start; at < len(lines); at++ {
+ line := lines[at]
+ switch {
+ case fence != "":
+ if ClosesFence(line, fence) {
+ fence = ""
+ }
+ case fenceLine.MatchString(line):
+ fence = fenceLine.FindStringSubmatch(line)[1]
+ case closes(line, colons):
+ return at, true
+ case FenceLike(line):
+ return 0, false
+ }
+ }
+ return 0, false
+}
+
+func skipBlank(lines []string, at int) int {
+ for at < len(lines) && strings.TrimSpace(lines[at]) == "" {
+ at++
+ }
+ return at
+}
+
+// fenceBlock is one fence line as a block.
+func fenceBlock(kind, line string, column, start int) Block {
+ return Block{Kind: kind, Source: line, Column: column, Start: start,
+ End: start + len(line)}
+}
+
+// parseLayout gives a whole layout's blocks: its fences, and each
+// column's lines parsed as a body of their own.
+func parseLayout(lines []string, offsets []int, whole layout) []Block {
+ opener := fenceBlock(Columns, lines[whole.open], 0, offsets[whole.open])
+ opener.Level = len(whole.columns)
+ blocks := []Block{opener}
+ for number, span := range whole.columns {
+ column := number + 1
+ blocks = append(blocks, fenceBlock(Column, lines[span[0]], column,
+ offsets[span[0]]))
+ inside := parseLines(lines, offsets, span[0]+1, span[1], nil)
+ for at := range inside {
+ inside[at].Column = column
+ }
+ blocks = append(blocks, inside...)
+ blocks = append(blocks, fenceBlock(ColumnEnd, lines[span[1]],
+ column, offsets[span[1]]))
+ }
+ return append(blocks, fenceBlock(ColumnsEnd, lines[whole.close], 0,
+ offsets[whole.close]))
+}
+
+// renderLayout draws the layout opening at start (§1.5):
+//
+// <div mapa-columns="2"><div mapa-column>…</div>…</div>
+//
+// each column's blocks drawn as anywhere, and an empty column holding
+// the editor's own empty paragraph. It returns the index after the
+// layout's closer. editor/schema.mjs draws the same; L4 holds them.
+func renderLayout(out *strings.Builder, blocks []Block, start int,
+ resolver Resolver) int {
+ out.WriteString(`<div mapa-columns="` + strconv.Itoa(blocks[start].Level) +
+ `">`)
+ index := start + 1
+ for index < len(blocks) && blocks[index].Kind == Column {
+ end := index + 1
+ for end < len(blocks) && blocks[end].Kind != ColumnEnd {
+ end++
+ }
+ out.WriteString("<div mapa-column>")
+ if end == index+1 {
+ out.WriteString(EmptyParagraph)
+ } else {
+ out.WriteString(string(Render(blocks[index+1:end], resolver)))
+ }
+ out.WriteString("</div>")
+ index = end + 1
+ }
+ out.WriteString("</div>")
+ return index + 1
+}
diff --git a/internal/mapa/markup/columns_test.go b/internal/mapa/markup/columns_test.go
new file mode 100644
index 0000000..239e2f4
--- /dev/null
+++ b/internal/mapa/markup/columns_test.go
@@ -0,0 +1,142 @@
+package markup
+
+import (
+ "strings"
+ "testing"
+)
+
+// COL2, the grammar (columns and icons spec §1.1, §9): the layouts Mapa
+// recognises, and the shapes it does not, which parse exactly as they
+// did before layouts existed.
+
+// columnKinds is each block's kind and column, as "kind/column".
+func columnKinds(blocks []Block) string {
+ var out []string
+ for _, block := range blocks {
+ out = append(out, block.Kind+"/"+string(rune('0'+block.Column)))
+ }
+ return strings.Join(out, " ")
+}
+
+// withoutLayouts parses body as Parse did before layouts: no layout is
+// ever recognised.
+func withoutLayouts(body string) []Block {
+ lines := strings.Split(normalise(body), "\n")
+ offsets := make([]int, len(lines)+1)
+ for index, line := range lines {
+ offsets[index+1] = offsets[index] + len(line) + 1
+ }
+ return parseLines(lines, offsets, 0, len(lines), nil)
+}
+
+const twoColumns = ":::: columns\n\n::: column\nLeft.\n\n- one\n- two\n\n" +
+ ":::\n\n::: column\nRight.\n\n:::\n\n::::"
+
+func TestALayoutIsRecognisedWhole(t *testing.T) {
+ cases := map[string]string{
+ twoColumns: "columns/0 column/1 paragraph/1 item/1 item/1 " +
+ "column_end/1 column/2 paragraph/2 column_end/2 columns_end/0",
+ "Before.\n\n" + twoColumns + "\n\nAfter.": "paragraph/0 columns/0 " +
+ "column/1 paragraph/1 item/1 item/1 column_end/1 column/2 " +
+ "paragraph/2 column_end/2 columns_end/0 paragraph/0",
+ // Tight, empty, three columns, longer fences, CRLF.
+ "::::: columns\n:::: column\nA\n::::\n:::: column\n::::\n" +
+ ":::: column\n```\n:::\n```\n::::\n:::::": "columns/0 column/1 " +
+ "paragraph/1 column_end/1 column/2 column_end/2 column/3 code/3 " +
+ "column_end/3 columns_end/0",
+ strings.ReplaceAll(twoColumns, "\n", "\r\n"): "columns/0 column/1 " +
+ "paragraph/1 item/1 item/1 column_end/1 column/2 paragraph/2 " +
+ "column_end/2 columns_end/0",
+ // Text straight before a closer is ended by it.
+ ":::: columns\n::: column\nA\n> quoted\n:::\n::: column\nB\n:::\n" +
+ "::::": "columns/0 column/1 paragraph/1 quote/1 column_end/1 " +
+ "column/2 paragraph/2 column_end/2 columns_end/0",
+ }
+ for body, want := range cases {
+ if got := columnKinds(Parse(body)); got != want {
+ t.Errorf("%q:\n got %s\nwant %s", body, got, want)
+ }
+ }
+ blocks := Parse(twoColumns)
+ if blocks[0].Level != 2 || Plain(blocks[0]) != "" ||
+ Words(blocks[1]) != "" {
+ t.Error("a layout's opener counts no columns, or a fence has words")
+ }
+ for _, block := range blocks {
+ if twoColumns[block.Start:block.End] != block.Source {
+ t.Errorf("%s at %d:%d is not its source", block.Kind,
+ block.Start, block.End)
+ }
+ }
+}
+
+func TestShapesThatAreNotLayoutsParseAsBefore(t *testing.T) {
+ col := func(text string) string { return "::: column\n" + text + "\n:::\n" }
+ open, shut := ":::: columns\n", "::::"
+ bodies := []string{
+ open + col("A") + shut, // one column
+ open + strings.Repeat(col("A"), 5) + shut, // five
+ open + "Before.\n" + col("A") + col("B") + shut, // text first
+ open + col("A") + "Between.\n" + col("B") + shut, // between
+ open + "::: column\nA\n" + col("B") + shut, // unclosed
+ open + "::: column\nA\n::::\n" + col("B") + shut, // wrong closer
+ " " + open + col("A") + col("B") + shut, // indented
+ open + "::: column width=\"40%\"\nA\n:::\n" + col("B") + shut,
+ open + "::: {.column}\nA\n:::\n" + col("B") + shut,
+ // No blank line before, then none after.
+ "Text.\n" + open + col("A") + col("B") + shut,
+ open + col("A") + col("B") + shut + "\nText.",
+ "> " + open + col("A") + col("B") + shut, // in a quote
+ "- item\n " + open + col("A") + col("B") + shut, // in an item
+ open + "::: column\n```\nA\n:::\n" + col("B") + shut, // open code
+ open + col("A\n ::: stray") + col("B") + shut, // fence-like
+ "```\n" + open + col("A") + col("B") + shut + "\n```", // in code
+ }
+ for _, body := range bodies {
+ got := columnKinds(Parse(body))
+ if want := columnKinds(withoutLayouts(body)); got != want {
+ t.Errorf("%q:\n got %s\nwant %s", body, got, want)
+ }
+ }
+}
+
+func TestANestedLayoutGivesTheInnerOne(t *testing.T) {
+ body := "::::: columns\n\n:::: column\n\n:::: columns\n\n::: column\n" +
+ "A\n:::\n\n::: column\nB\n:::\n\n::::\n\n::::\n\n" +
+ ":::: column\nC\n::::\n\n:::::"
+ got := columnKinds(Parse(body))
+ if !strings.Contains(got, "columns/0 column/1 paragraph/1") ||
+ strings.Count(got, "columns/0") != 1 {
+ t.Fatalf("a nested layout: %s", got)
+ }
+}
+
+func TestJoinWritesTheQuartoForm(t *testing.T) {
+ if got := Join(Parse(twoColumns)); got != twoColumns {
+ t.Fatalf("Join:\n%q\nwant\n%q", got, twoColumns)
+ }
+ tight := ":::: columns\n::: column\nA\n:::\n::: column\n:::\n::::"
+ want := ":::: columns\n\n::: column\nA\n\n:::\n\n::: column\n:::\n\n::::"
+ if got := Join(Parse(tight)); got != want {
+ t.Fatalf("Join of a tight layout:\n%q\nwant\n%q", got, want)
+ }
+}
+
+func TestALayoutRendersAsColumns(t *testing.T) {
+ got := string(Render(Parse(":::: columns\n::: column\nA\n:::\n"+
+ "::: column\n:::\n::::"), nil))
+ want := `<div mapa-columns="2"><div mapa-column><p>A</p></div>` +
+ `<div mapa-column>` + EmptyParagraph + `</div></div>`
+ if got != want {
+ t.Fatalf("Render:\n%s\nwant\n%s", got, want)
+ }
+}
+
+func TestFenceLike(t *testing.T) {
+ for line, want := range map[string]bool{":::": true, " ::: x": true,
+ "\t::::": true, "::": false, "a :::": false, "\u200b:::": false} {
+ if FenceLike(line) != want {
+ t.Errorf("FenceLike(%q) is not %v", line, want)
+ }
+ }
+}
diff --git a/internal/mapa/markup/merge.go b/internal/mapa/markup/merge.go
index b3f4d4a..35b9810 100644
--- a/internal/mapa/markup/merge.go
+++ b/internal/mapa/markup/merge.go
@@ -49,18 +49,31 @@ func Merge3(base, mine, theirs string) (hunks []Hunk, clean bool) {
theirs: normalise(theirs)}
texts.baseBlocks, texts.mineBlocks, texts.theirsBlocks =
Parse(texts.base), Parse(texts.mine), Parse(texts.theirs)
+ hunks, clean = texts.merge(false)
+ if texts.anyFence() && !texts.layoutsHold(hunks) {
+ // A column layout would break: merge again with every layout a
+ // unit (columns and icons spec §1.8, rules 1 and 2).
+ hunks, clean = texts.merge(true)
+ }
+ return hunks, clean
+}
+
+// merge is one pass of Merge3. With whole, a stretch that touches a
+// column layout on any side is widened to whole layouts on every side,
+// and resolved as one.
+func (texts *sides) merge(whole bool) (hunks []Hunk, clean bool) {
toMine := align(texts.baseBlocks, texts.mineBlocks)
toTheirs := align(texts.baseBlocks, texts.theirsBlocks)
clean = true
at := cursor{}
for {
- stable := nextStable(at.base, toMine, toTheirs)
+ stable := texts.nextStable(at.base, toMine, toTheirs, whole)
end := cursor{len(texts.baseBlocks), len(texts.mineBlocks),
len(texts.theirsBlocks)}
if stable >= 0 {
end = cursor{stable, toMine[stable], toTheirs[stable]}
}
- for _, hunk := range texts.resolveStretch(at, end) {
+ for _, hunk := range texts.resolveStretch(at, end, whole) {
if hunk.Conflict || len(hunk.Blocks) > 0 {
hunks = append(hunks, hunk)
clean = clean && !hunk.Conflict
@@ -75,12 +88,20 @@ func Merge3(base, mine, theirs string) (hunks []Hunk, clean bool) {
}
// nextStable is the first base block at or after from that both sides
-// kept, or -1.
-func nextStable(from int, toMine, toTheirs []int) int {
+// kept, or -1. With whole, a block in a column layout on any side is
+// never an anchor, so a stretch reaches out to whole layouts.
+func (texts *sides) nextStable(from int, toMine, toTheirs []int,
+ whole bool) int {
for at := from; at < len(toMine); at++ {
- if toMine[at] >= 0 && toTheirs[at] >= 0 {
- return at
+ if toMine[at] < 0 || toTheirs[at] < 0 {
+ continue
}
+ if whole && (inLayout(texts.baseBlocks[at]) ||
+ inLayout(texts.mineBlocks[toMine[at]]) ||
+ inLayout(texts.theirsBlocks[toTheirs[at]])) {
+ continue
+ }
+ return at
}
return -1
}
@@ -89,10 +110,13 @@ func nextStable(from int, toMine, toTheirs []int) int {
// hold the same number of blocks, each was edited in place, so each
// position is resolved on its own: Ana's edit to one block and Bo's to
// the next do not conflict just because they are neighbours.
-func (texts *sides) resolveStretch(at, end cursor) []Hunk {
+func (texts *sides) resolveStretch(at, end cursor, whole bool) []Hunk {
+ if hunks, ok := texts.addedColumns(at, end); ok {
+ return hunks
+ }
count := end.base - at.base
if count < 2 || end.mine-at.mine != count ||
- end.theirs-at.theirs != count {
+ end.theirs-at.theirs != count || whole && texts.fenced(at, end) {
return []Hunk{texts.resolve(at, end)}
}
hunks := make([]Hunk, count)
@@ -145,7 +169,8 @@ func sameBlocks(one, other []Block) bool {
// align maps each block of from to its match in to, by a longest common
// subsequence of block sources, or -1 where it has none.
-func align(from, to []Block) []int {
+func align(fromBlocks, toBlocks []Block) []int {
+ from, to := alignKeys(fromBlocks), alignKeys(toBlocks)
rows, columns := len(from), len(to)
lengths := make([][]int32, rows+1)
for row := range lengths {
@@ -153,7 +178,7 @@ func align(from, to []Block) []int {
}
for row := rows - 1; row >= 0; row-- {
for column := columns - 1; column >= 0; column-- {
- if from[row].Source == to[column].Source {
+ if from[row] == to[column] {
lengths[row][column] = lengths[row+1][column+1] + 1
} else {
lengths[row][column] = max(lengths[row+1][column],
@@ -165,7 +190,7 @@ func align(from, to []Block) []int {
row, column := 0, 0
for row < rows {
switch {
- case column < columns && from[row].Source == to[column].Source:
+ case column < columns && from[row] == to[column]:
matched[row] = column
row, column = row+1, column+1
case column < columns &&
diff --git a/internal/mapa/markup/merge_columns.go b/internal/mapa/markup/merge_columns.go
new file mode 100644
index 0000000..e1ac130
--- /dev/null
+++ b/internal/mapa/markup/merge_columns.go
@@ -0,0 +1,206 @@
+package markup
+
+// The merge and column layouts (columns and icons spec §1.8). Inside a
+// column, blocks merge as they always have. Two rules keep every result
+// a valid body: a conflict never cuts a layout, and every result holds
+// valid layouts, conflicts or not. Merge3 checks the first pass; when
+// it would break a layout, it merges again with layouts as units.
+
+// inLayout is a fence, or a block inside a column.
+func inLayout(block Block) bool {
+ return block.Column > 0 || IsFence(block.Kind)
+}
+
+// anyFence reports whether any side holds a layout.
+func (texts *sides) anyFence() bool {
+ for _, blocks := range [][]Block{texts.baseBlocks, texts.mineBlocks,
+ texts.theirsBlocks} {
+ for _, block := range blocks {
+ if IsFence(block.Kind) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// fenced reports whether the stretch from at to end holds a fence on
+// any side.
+func (texts *sides) fenced(at, end cursor) bool {
+ return holdsFence(texts.baseBlocks[at.base:end.base]) ||
+ holdsFence(texts.mineBlocks[at.mine:end.mine]) ||
+ holdsFence(texts.theirsBlocks[at.theirs:end.theirs])
+}
+
+func holdsFence(blocks []Block) bool {
+ for _, block := range blocks {
+ if IsFence(block.Kind) {
+ return true
+ }
+ }
+ return false
+}
+
+// layoutsHold reports whether the first pass's hunks keep every layout
+// valid whatever is chosen: no conflict holds a fence on any side (rule
+// 1); the kinds in order are valid with each fence-free conflict there
+// and gone; and the result, each conflict taken as mine and as theirs,
+// parses back to those kinds (rule 2).
+func (texts *sides) layoutsHold(hunks []Hunk) bool {
+ var present, absent []Block
+ for _, hunk := range hunks {
+ if !hunk.Conflict {
+ present = append(present, hunk.Blocks...)
+ absent = append(absent, hunk.Blocks...)
+ continue
+ }
+ if holdsFence(hunk.Base) || holdsFence(hunk.Mine) ||
+ holdsFence(hunk.Theirs) {
+ return false
+ }
+ present = append(present, Block{Kind: Paragraph})
+ }
+ if !ValidLayouts(present) || !ValidLayouts(absent) {
+ return false
+ }
+ return parsesBack(hunks, KeepMine) && parsesBack(hunks, KeepTheirs)
+}
+
+// parsesBack reports whether settling every conflict as choice gives a
+// body whose blocks are, kind for kind, the ones settled.
+func parsesBack(hunks []Hunk, choice Choice) bool {
+ var want []Block
+ var choices []Choice
+ for _, hunk := range hunks {
+ switch {
+ case !hunk.Conflict:
+ want = append(want, hunk.Blocks...)
+ case choice == KeepMine:
+ want, choices = append(want, hunk.Mine...), append(choices, choice)
+ default:
+ want = append(want, hunk.Theirs...)
+ choices = append(choices, choice)
+ }
+ }
+ body, ok := Settle(hunks, choices)
+ if !ok {
+ return false
+ }
+ got := Parse(body)
+ if len(got) != len(want) {
+ return false
+ }
+ for at := range got {
+ if got[at].Kind != want[at].Kind || got[at].Source != want[at].Source {
+ return false
+ }
+ }
+ return true
+}
+
+// ValidLayouts reports whether blocks, in order, hold only whole column
+// layouts: an opener, two to four columns each opened and closed, no
+// block between columns, and no fence anywhere else. Column numbers and
+// the opener's count are positions; this is the check, not them.
+func ValidLayouts(blocks []Block) bool {
+ state, count := "top", 0
+ for _, block := range blocks {
+ switch {
+ case state == "top" && block.Kind == Columns:
+ state, count = "between", 0
+ case state == "top" && !IsFence(block.Kind):
+ case state == "between" && block.Kind == Column:
+ state, count = "in", count+1
+ case state == "between" && block.Kind == ColumnsEnd:
+ if count < 2 || count > 4 {
+ return false
+ }
+ state = "top"
+ case state == "in" && block.Kind == ColumnEnd:
+ state = "between"
+ case state == "in" && !IsFence(block.Kind):
+ default:
+ return false
+ }
+ }
+ return state == "top"
+}
+
+// alignKeys is what align matches blocks by: their source, and for a
+// column's fences, the source of the block inside them beside it too.
+// Every column's fences read alike, so by source alone a column added
+// before another would take the other's fences, and its edit would
+// meet the addition (§1.8: edits inside columns merge as anywhere).
+func alignKeys(blocks []Block) []string {
+ keys := make([]string, len(blocks))
+ for at, block := range blocks {
+ keys[at] = block.Source
+ switch {
+ case block.Kind == Column && at+1 < len(blocks) &&
+ !IsFence(blocks[at+1].Kind):
+ keys[at] += "\n" + blocks[at+1].Source
+ case block.Kind == ColumnEnd && at > 0 && !IsFence(blocks[at-1].Kind):
+ keys[at] += "\n" + blocks[at-1].Source
+ }
+ }
+ return keys
+}
+
+// addedColumns splits a stretch in which one side only added whole
+// columns at its start or its end and the other changed what follows or
+// precedes them: Ana adds a column before Bo's, while Bo edits his. Every
+// column's fences read alike, so without this the addition and the edit
+// meet in one stretch and conflict (§1.8: they merge).
+func (texts *sides) addedColumns(at, end cursor) ([]Hunk, bool) {
+ base := texts.baseBlocks[at.base:end.base]
+ for _, side := range []Side{FromMine, FromTheirs} {
+ start, stop := at.theirs, end.theirs
+ if side == FromMine {
+ start, stop = at.mine, end.mine
+ }
+ region := texts.blocks(side)[start:stop]
+ extra := len(region) - len(base)
+ if extra <= 0 {
+ continue
+ }
+ if sameBlocks(region[extra:], base) && wholeColumns(region[:extra]) {
+ return []Hunk{texts.settled(side, start, extra),
+ texts.resolve(moved(at, side, extra), end)}, true
+ }
+ if sameBlocks(region[:len(base)], base) &&
+ wholeColumns(region[len(base):]) {
+ return []Hunk{texts.resolve(at, moved(end, side, -extra)),
+ texts.settled(side, stop-extra, extra)}, true
+ }
+ }
+ return nil, false
+}
+
+// moved is a cursor with one side's position moved by count.
+func moved(at cursor, side Side, count int) cursor {
+ if side == FromMine {
+ at.mine += count
+ } else {
+ at.theirs += count
+ }
+ return at
+}
+
+// wholeColumns reports whether blocks are one or more whole columns.
+func wholeColumns(blocks []Block) bool {
+ if len(blocks) < 2 || blocks[0].Kind != Column {
+ return false
+ }
+ inside := false
+ for _, block := range blocks {
+ switch {
+ case block.Kind == Column && !inside:
+ inside = true
+ case block.Kind == ColumnEnd && inside:
+ inside = false
+ case IsFence(block.Kind) || !inside:
+ return false
+ }
+ }
+ return !inside
+}
diff --git a/internal/mapa/markup/merge_columns_test.go b/internal/mapa/markup/merge_columns_test.go
new file mode 100644
index 0000000..7a03d97
--- /dev/null
+++ b/internal/mapa/markup/merge_columns_test.go
@@ -0,0 +1,121 @@
+package markup
+
+import (
+ "strings"
+ "testing"
+)
+
+// COL4, the merge over column layouts (columns and icons spec §1.8).
+
+func layoutOf(columns ...string) string {
+ var out strings.Builder
+ out.WriteString(":::: columns\n\n")
+ for _, column := range columns {
+ out.WriteString("::: column\n" + column + "\n\n:::\n\n")
+ }
+ return out.String() + "::::"
+}
+
+func merged(t *testing.T, base, mine, theirs string) ([]Hunk, bool,
+ string) {
+ t.Helper()
+ hunks, clean := Merge3(base, mine, theirs)
+ if !clean {
+ return hunks, false, ""
+ }
+ body, ok := Settle(hunks, nil)
+ if !ok {
+ t.Fatal("a clean merge did not settle")
+ }
+ if !ValidLayouts(Parse(body)) {
+ t.Fatalf("an invalid layout was settled:\n%s", body)
+ }
+ return hunks, true, body
+}
+
+func TestEditsToDifferentColumnsMerge(t *testing.T) {
+ base := "Top.\n\n" + layoutOf("Left.", "Right.")
+ mine := "Top.\n\n" + layoutOf("Left, Ana.", "Right.")
+ theirs := "Top.\n\n" + layoutOf("Left.", "Right, Bo.")
+ _, clean, body := merged(t, base, mine, theirs)
+ if !clean || body != "Top.\n\n"+layoutOf("Left, Ana.", "Right, Bo.") {
+ t.Fatalf("clean %v:\n%s", clean, body)
+ }
+}
+
+func TestTheSameBlockConflictsInsideItsColumn(t *testing.T) {
+ base := layoutOf("Left.", "Right.")
+ mine := layoutOf("Left, Ana.", "Right.")
+ theirs := layoutOf("Left, Bo.", "Right.")
+ hunks, clean := Merge3(base, mine, theirs)
+ if clean {
+ t.Fatal("two edits to one block merged")
+ }
+ for _, choice := range []Choice{KeepMine, KeepTheirs, KeepBoth} {
+ body, ok := Settle(hunks, []Choice{choice})
+ if !ok || !ValidLayouts(Parse(body)) ||
+ strings.Count(body, ":::: columns") != 1 {
+ t.Fatalf("choice %d:\n%s", choice, body)
+ }
+ }
+}
+
+func TestAddingAColumnBesideAnEditMergesWithBothBytes(t *testing.T) {
+ base := layoutOf("Left.", "Right.")
+ mine := layoutOf("Left.", "Middle.", "Right.")
+ theirs := layoutOf("Left.", "Right, Bo.")
+ _, clean, body := merged(t, base, mine, theirs)
+ if !clean || body != layoutOf("Left.", "Middle.", "Right, Bo.") {
+ t.Fatalf("clean %v:\n%s", clean, body)
+ }
+}
+
+func TestUndoingALayoutAgainstAddingAColumnIsOneConflict(t *testing.T) {
+ base := layoutOf("Left.", "Right.")
+ mine := "Left.\n\nRight."
+ theirs := layoutOf("Left.", "Middle.", "Right.")
+ hunks, clean := Merge3(base, mine, theirs)
+ if clean {
+ t.Fatal("a broken layout merged cleanly")
+ }
+ for _, choice := range []Choice{KeepMine, KeepTheirs, KeepBoth} {
+ body, ok := Settle(hunks, []Choice{choice})
+ if !ok || !ValidLayouts(Parse(body)) {
+ t.Fatalf("choice %d gave an invalid body:\n%s", choice, body)
+ }
+ }
+}
+
+func TestABrokenCleanHunkBesideAConflictIsCaught(t *testing.T) {
+ base := "Top.\n\n" + layoutOf("A1.\n\nA2.", "B.")
+ mine := "Top, Ana.\n\nA1.\n\nA2.\n\nB."
+ theirs := "Top, Bo.\n\n" + layoutOf("A1.", "A2.", "B.")
+ hunks, clean := Merge3(base, mine, theirs)
+ if clean {
+ t.Fatal("merged cleanly")
+ }
+ choices := make([]Choice, 0)
+ for _, hunk := range hunks {
+ if hunk.Conflict {
+ choices = append(choices, KeepMine)
+ }
+ }
+ for _, choice := range []Choice{KeepMine, KeepTheirs, KeepBoth} {
+ for at := range choices {
+ choices[at] = choice
+ }
+ body, ok := Settle(hunks, choices)
+ if !ok || !ValidLayouts(Parse(body)) {
+ t.Fatalf("choice %d gave an invalid body:\n%s", choice, body)
+ }
+ }
+}
+
+func TestTwoRemovedColumnsLeavingOneAreAConflict(t *testing.T) {
+ base := layoutOf("A.", "B.", "C.")
+ mine := layoutOf("B.", "C.")
+ theirs := layoutOf("A.", "C.")
+ if _, clean := Merge3(base, mine, theirs); clean {
+ t.Fatal("a one-column layout merged cleanly")
+ }
+}
diff --git a/internal/mapa/markup/render.go b/internal/mapa/markup/render.go
index 7b82e91..aab4424 100644
--- a/internal/mapa/markup/render.go
+++ b/internal/mapa/markup/render.go
@@ -50,6 +50,10 @@ func Render(blocks []Block, resolver Resolver) template.HTML {
index = renderList(&out, blocks, index, resolver)
continue
}
+ if blocks[index].Kind == Columns {
+ index = renderLayout(&out, blocks, index, resolver)
+ continue
+ }
renderBlock(&out, blocks[index], resolver)
index++
}
diff --git a/internal/mapa/markup/settle.go b/internal/mapa/markup/settle.go
index 4311267..6001bf8 100644
--- a/internal/mapa/markup/settle.go
+++ b/internal/mapa/markup/settle.go
@@ -115,10 +115,7 @@ func (texts *sides) seam(before, after placed) string {
start, end := blocks[before.at].End, blocks[after.at].Start
return texts.text(before.from)[start:end]
}
- if before.block.Kind == Item && after.block.Kind == Item {
- return "\n"
- }
- return "\n\n"
+ return seam(before.block, after.block)
}
func (texts *sides) text(from Side) string {
@@ -143,7 +140,10 @@ func sameStructure(parsed, blocks []Block) bool {
}
for at := range parsed {
one, other := parsed[at], blocks[at]
- if one.Kind != other.Kind || one.Level != other.Level ||
+ // A layout opener's Level is its column count, a position, as
+ // Column is: neither is compared (columns and icons spec §1.4).
+ level := one.Kind == Columns || one.Level == other.Level
+ if one.Kind != other.Kind || !level ||
one.Ordered != other.Ordered || one.Source != other.Source {
return false
}