1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! 1.2.19+ X.1 — standard manuscript-format export.
//!
//! Emits a submission-ready document in **Shunn standard
//! manuscript format** — the layout agents + editors
//! expect: a monospace, double-spaced typst document with
//! a title page (contact top-left, rounded word count
//! top-right, title a third of the way down), a running
//! `Surname / KEYWORD / page` header, each chapter
//! starting a fresh page, paragraph indents, and scene
//! breaks as a centred `#`.
//!
//! The reader-facing exports (ePub, audiobook) target
//! consumption; this targets submission. It compiles to
//! PDF through typst like every other inkhaven output.
//!
//! The pure pieces — word-count rounding, the header
//! keyword, scene-break detection, and the typst assembly
//! — are unit-tested; producing the PDF is a thin typst
//! call on the self-contained `.typ`.
/// Book-level metadata for the title page + header.
#[derive(Debug, Clone)]
pub struct ManuscriptMeta {
pub title: String,
/// Legal name + address block for the title-page
/// contact corner (newline-separated lines).
pub contact: String,
/// Byline / pen name shown under the title.
pub byline: String,
/// Surname for the running header.
pub surname: String,
/// Exact manuscript word count (rounded for display).
pub word_count: usize,
}
/// One chapter: title + its paragraphs (plain prose, in
/// order; a scene-break paragraph is its marker line).
#[derive(Debug, Clone)]
pub struct ManuscriptChapter {
pub title: String,
pub paragraphs: Vec<String>,
}
/// Round a word count the Shunn way: nearest 100 for
/// shorter work, nearest 1000 for novels (≥ 25 000).
pub fn round_word_count(n: usize) -> usize {
let step = if n >= 25_000 { 1000 } else { 100 };
((n + step / 2) / step) * step
}
/// Derive the running-header keyword from the title: drop
/// a leading article, take the first significant word,
/// uppercase, strip punctuation. "The Harbor Code" →
/// `HARBOR`; "An Inheritance of Salt" → `INHERITANCE`.
pub fn header_keyword(title: &str) -> String {
let mut words = title.split_whitespace().peekable();
if let Some(first) = words.peek() {
let lc = first.to_lowercase();
if matches!(lc.as_str(), "the" | "a" | "an") {
words.next();
}
}
words
.next()
.map(|w| {
w.chars()
.filter(|c| c.is_alphanumeric())
.collect::<String>()
.to_uppercase()
})
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "MANUSCRIPT".to_string())
}
/// True when a paragraph is *only* a scene-break marker:
/// 3+ copies of one of `*`, `-`, `_`, `~`, `#` (internal
/// single spaces allowed, so `* * *` and `***` both
/// match) or a lone `§`. Rejects typst headings
/// (`= Foo`) and mixed content (`***bold***`).
///
/// The single home for scene-break detection: the
/// manuscript exporter renders a match as a centred `#`,
/// and the editor (`crate::tui::app`) uses the same
/// function for scene-break navigation.
pub fn is_scene_break(text: &str) -> bool {
let trimmed = text.trim();
if trimmed == "§" {
return true;
}
let chars: Vec<char> =
trimmed.chars().filter(|c| !c.is_whitespace()).collect();
if chars.len() < 3 {
return false;
}
let first = chars[0];
if !"*-_~#".contains(first) {
return false;
}
chars.iter().all(|c| *c == first)
}
/// XP-2 — an inline emphasis span: a run of text that is plain, bold, or italic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Emphasis {
None,
Bold,
Italic,
}
pub(crate) struct Span {
pub text: String,
pub emphasis: Emphasis,
}
/// Split prose into emphasis spans on balanced `*bold*` / `_italic_` runs (flat,
/// non-nested — the common fiction case). An unbalanced or empty delimiter is
/// kept as literal text. Shared by the docx exporter (→ `<w:b>`/`<w:i>` runs) and
/// the Shunn-typst exporter (→ `*…*` / `_…_` markup), so authored emphasis stops
/// rendering as literal `\*bold\*`.
pub(crate) fn parse_emphasis(text: &str) -> Vec<Span> {
let mut spans = Vec::new();
let mut plain = String::new();
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
let em = match c {
'*' => Emphasis::Bold,
'_' => Emphasis::Italic,
_ => {
plain.push(c);
continue;
}
};
// Greedy: read until the next matching delimiter on this line.
let mut body = String::new();
let mut closed = false;
for d in chars.by_ref() {
if d == c {
closed = true;
break;
}
body.push(d);
}
if closed && !body.is_empty() {
if !plain.is_empty() {
spans.push(Span { text: std::mem::take(&mut plain), emphasis: Emphasis::None });
}
spans.push(Span { text: body, emphasis: em });
} else {
// Unbalanced / empty → literal delimiter + whatever we consumed.
plain.push(c);
plain.push_str(&body);
}
}
if !plain.is_empty() {
spans.push(Span { text: plain, emphasis: Emphasis::None });
}
spans
}
/// Escape a line of **prose** for typst while preserving authored emphasis:
/// balanced `*bold*` / `_italic_` become real typst markup (delimiters kept, the
/// content escaped), everything else is escaped literally. Used for chapter body
/// paragraphs; titles / contact blocks use the plain [`escape_typst`].
fn escape_typst_prose(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 8);
for span in parse_emphasis(s) {
let inner = escape_typst(&span.text);
match span.emphasis {
Emphasis::Bold => {
out.push('*');
out.push_str(&inner);
out.push('*');
}
Emphasis::Italic => {
out.push('_');
out.push_str(&inner);
out.push('_');
}
Emphasis::None => out.push_str(&inner),
}
}
out
}
/// Escape the characters typst treats as markup so prose
/// renders literally.
fn escape_typst(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' | '#' | '$' | '*' | '_' | '`' | '<' | '>' | '@'
| '=' | '-' | '+' | '/' | '"' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
out
}
/// Build the self-contained Shunn-format typst document.
/// Pure.
pub fn build_typst(meta: &ManuscriptMeta, chapters: &[ManuscriptChapter]) -> String {
let keyword = header_keyword(&meta.title);
let rounded = round_word_count(meta.word_count);
let mut s = String::new();
// ── global formatting: monospace, double-spaced ──
s.push_str("// Standard manuscript format (Shunn). Generated by inkhaven.\n");
s.push_str("#set text(font: (\"Courier New\", \"Courier\"), size: 12pt)\n");
s.push_str("#set par(leading: 1.5em, first-line-indent: 0.5in, justify: false, spacing: 1.5em)\n");
s.push_str("#set page(paper: \"us-letter\", margin: 1in)\n\n");
// ── title page (no header, flush-left contact) ───
s.push_str("#[\n");
s.push_str(" #set par(first-line-indent: 0pt, leading: 0.65em, spacing: 0.65em)\n");
// Contact block, top-left.
for line in meta.contact.lines() {
s.push_str(&format!(" {}\\\n", escape_typst(line.trim())));
}
// Word count, top-right.
s.push_str(&format!(
" #place(top + right)[about {} words]\n",
rounded,
));
// Title, ~1/3 down, centred.
s.push_str(" #v(3in)\n");
s.push_str(" #align(center)[\n");
s.push_str(&format!(" #upper[{}]\n\n", escape_typst(&meta.title)));
s.push_str(" by\n\n");
s.push_str(&format!(" {}\n", escape_typst(&meta.byline)));
s.push_str(" ]\n");
s.push_str("]\n");
s.push_str("#pagebreak()\n\n");
// ── running header from page 2 on ────────────────
s.push_str(&format!(
"#set page(header: context {{\n if counter(page).get().first() > 1 {{\n align(right)[{} / {} / #counter(page).display()]\n }}\n}})\n\n",
escape_typst(&meta.surname),
escape_typst(&keyword),
));
// ── chapters ─────────────────────────────────────
for (i, ch) in chapters.iter().enumerate() {
if i > 0 {
s.push_str("#pagebreak()\n");
}
// Chapter heading ~1/3 down the page, centred.
s.push_str("#v(12%)\n");
s.push_str(&format!(
"#align(center)[#upper[{}]]\n",
escape_typst(&ch.title),
));
s.push_str("#v(3em)\n\n");
for para in &ch.paragraphs {
if is_scene_break(para) {
s.push_str("#align(center)[\\#]\n\n");
} else {
s.push_str(&escape_typst_prose(para.trim()));
s.push_str("\n\n");
}
}
}
// ── end marker ───────────────────────────────────
s.push_str("#align(center)[\\# \\# \\#]\n");
s
}
#[cfg(test)]
mod tests {
use super::*;
// ── round_word_count ──────────────────────────────
#[test]
fn rounds_short_to_nearest_hundred() {
assert_eq!(round_word_count(3470), 3500);
assert_eq!(round_word_count(3449), 3400);
assert_eq!(round_word_count(50), 100);
assert_eq!(round_word_count(149), 100);
}
#[test]
fn rounds_novel_to_nearest_thousand() {
assert_eq!(round_word_count(82_400), 82_000);
assert_eq!(round_word_count(82_600), 83_000);
assert_eq!(round_word_count(25_000), 25_000);
}
// ── header_keyword ────────────────────────────────
#[test]
fn keyword_drops_leading_article() {
assert_eq!(header_keyword("The Harbor Code"), "HARBOR");
assert_eq!(header_keyword("An Inheritance of Salt"), "INHERITANCE");
assert_eq!(header_keyword("A Quiet Geometry"), "QUIET");
}
#[test]
fn keyword_handles_no_article() {
assert_eq!(header_keyword("Beneath the Slate Roofs"), "BENEATH");
}
#[test]
fn keyword_strips_punctuation() {
assert_eq!(header_keyword("\"Quoted\" Title"), "QUOTED");
}
#[test]
fn keyword_fallback_when_empty() {
assert_eq!(header_keyword(""), "MANUSCRIPT");
assert_eq!(header_keyword("The"), "MANUSCRIPT");
}
// ── is_scene_break ────────────────────────────────
#[test]
fn detects_scene_breaks() {
assert!(is_scene_break("* * *"));
assert!(is_scene_break("***"));
assert!(is_scene_break("---"));
assert!(is_scene_break("# # #"));
assert!(is_scene_break("§"));
assert!(is_scene_break("~~~"));
}
#[test]
fn rejects_non_scene_breaks() {
assert!(!is_scene_break("Helena paused."));
assert!(!is_scene_break("--")); // only 2
assert!(!is_scene_break(""));
assert!(!is_scene_break("a-b-c")); // mixed
}
// ── escape_typst ──────────────────────────────────
#[test]
fn escapes_typst_markup() {
let e = escape_typst("a #b *c* _d_ $e$");
assert!(e.contains("\\#"));
assert!(e.contains("\\*"));
assert!(e.contains("\\_"));
assert!(e.contains("\\$"));
}
#[test]
fn prose_escape_preserves_emphasis_but_escapes_content() {
// XP-2 — *bold* / _italic_ become real typst markup (not literal \*bold\*),
// while other specials inside them are still escaped.
let e = escape_typst_prose("say *bold #x* and _soft_ now");
assert!(e.contains("*bold \\#x*"), "bold markup kept, # escaped: {e}");
assert!(e.contains("_soft_"), "italic markup kept: {e}");
assert!(!e.contains("\\*"), "no escaped asterisk on balanced emphasis: {e}");
// An unbalanced delimiter stays literal (escaped).
let u = escape_typst_prose("2 * 3 = 6");
assert!(u.contains("\\*"), "stray asterisk stays literal: {u}");
}
#[test]
fn parse_emphasis_splits_flat_spans() {
let spans = parse_emphasis("a *b* c _d_");
let kinds: Vec<_> = spans.iter().map(|s| (s.text.as_str(), s.emphasis)).collect();
assert_eq!(
kinds,
vec![
("a ", Emphasis::None),
("b", Emphasis::Bold),
(" c ", Emphasis::None),
("d", Emphasis::Italic),
]
);
}
// ── build_typst structure ─────────────────────────
fn sample() -> (ManuscriptMeta, Vec<ManuscriptChapter>) {
let meta = ManuscriptMeta {
title: "The Harbor Code".into(),
contact: "Jane Author\n12 Wharf Lane\njane@example.com".into(),
byline: "Jane Author".into(),
surname: "Author".into(),
word_count: 82_417,
};
let chapters = vec![
ManuscriptChapter {
title: "Arrivals".into(),
paragraphs: vec![
"Helena paused at the threshold.".into(),
"* * *".into(),
"Marcus waited below.".into(),
],
},
ManuscriptChapter {
title: "The Wharf".into(),
paragraphs: vec!["The tide had turned.".into()],
},
];
(meta, chapters)
}
#[test]
fn typst_has_shunn_essentials() {
let (m, c) = sample();
let out = build_typst(&m, &c);
// Monospace + double-space + margins.
assert!(out.contains("Courier"));
assert!(out.contains("leading: 1.5em"));
assert!(out.contains("margin: 1in"));
// Title page: rounded word count + title + byline.
assert!(out.contains("about 82000 words"));
assert!(out.contains("#upper[The Harbor Code]"));
assert!(out.contains("by"));
// Running header keyword + surname.
assert!(out.contains("Author / HARBOR /"));
// Chapter headings + pagebreak between them.
assert!(out.contains("#upper[Arrivals]"));
assert!(out.contains("#upper[The Wharf]"));
assert!(out.contains("#pagebreak()"));
// Scene break rendered as centred #.
assert!(out.contains("#align(center)[\\#]"));
// End marker.
assert!(out.contains("\\# \\# \\#"));
}
#[test]
fn typst_escapes_prose_markup_but_keeps_emphasis() {
let meta = ManuscriptMeta {
title: "Test".into(),
contact: "X".into(),
byline: "X".into(),
surname: "X".into(),
word_count: 100,
};
let chapters = vec![ManuscriptChapter {
title: "One".into(),
paragraphs: vec!["A #hashtag and *stars* here.".into()],
}];
let out = build_typst(&meta, &chapters);
// A non-emphasis special is still escaped literally…
assert!(out.contains("\\#hashtag"));
// …but XP-2 keeps authored *bold* as real typst markup (renders bold),
// rather than the old over-escaped literal `\*stars\*`.
assert!(out.contains("*stars*"), "{out}");
assert!(!out.contains("\\*stars"), "emphasis no longer escaped: {out}");
}
}