jumpcut 1.0.0

JumpCut is a library and CLI for converting Fountain-formatted text files into FDX, HTML, JSON, text, and PDF formats.
Documentation
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use crate::ElementLayoutOverrides;
use crate::pagination::LayoutGeometry;
use crate::pagination::margin::calculate_element_width;
use crate::styled_text::{StyledRun, StyledText};

#[derive(Debug, Clone, Copy)]
pub enum ElementType {
    Action,
    ColdOpening,
    NewAct,
    EndOfAct,
    SceneHeading,
    Character,
    Dialogue,
    Parenthetical,
    Transition,
    Lyric,
    DualDialogueLeft,
    DualDialogueRight,
    DualDialogueCharacterLeft,
    DualDialogueCharacterRight,
    DualDialogueParentheticalLeft,
    DualDialogueParentheticalRight,
}

impl ElementType {
    pub fn from_item_kind(kind: &str, dual_dialogue_side: Option<u8>) -> Self {
        if let Some(side) = dual_dialogue_side {
            return match (kind, side) {
                ("Character", 1) => Self::DualDialogueCharacterLeft,
                ("Character", _) => Self::DualDialogueCharacterRight,
                ("Parenthetical", 1) => Self::DualDialogueParentheticalLeft,
                ("Parenthetical", _) => Self::DualDialogueParentheticalRight,
                (_, 1) => Self::DualDialogueLeft,
                _ => Self::DualDialogueRight,
            };
        }

        match kind {
            "Character" => Self::Character,
            "Dialogue" => Self::Dialogue,
            "Parenthetical" => Self::Parenthetical,
            "Lyric" => Self::Lyric,
            "Scene Heading" => Self::SceneHeading,
            "Transition" => Self::Transition,
            "Cold Opening" => Self::ColdOpening,
            "New Act" => Self::NewAct,
            "End of Act" => Self::EndOfAct,
            _ => Self::Action,
        }
    }

    pub fn from_flow_kind(kind: &crate::pagination::FlowKind) -> Self {
        match kind {
            crate::pagination::FlowKind::Action => Self::Action,
            crate::pagination::FlowKind::SceneHeading => Self::SceneHeading,
            crate::pagination::FlowKind::Transition => Self::Transition,
            crate::pagination::FlowKind::ColdOpening => Self::ColdOpening,
            crate::pagination::FlowKind::NewAct => Self::NewAct,
            crate::pagination::FlowKind::EndOfAct => Self::EndOfAct,
            _ => Self::Action,
        }
    }

    pub fn from_dialogue_part_kind(kind: &crate::pagination::DialoguePartKind) -> Self {
        match kind {
            crate::pagination::DialoguePartKind::Character => Self::Character,
            crate::pagination::DialoguePartKind::Dialogue => Self::Dialogue,
            crate::pagination::DialoguePartKind::Parenthetical => Self::Parenthetical,
            crate::pagination::DialoguePartKind::Lyric => Self::Lyric,
        }
    }

    pub fn from_dual_dialogue_part_kind(
        kind: &crate::pagination::DialoguePartKind,
        side: u8,
    ) -> Self {
        match (kind, side) {
            (crate::pagination::DialoguePartKind::Character, 1) => Self::DualDialogueCharacterLeft,
            (crate::pagination::DialoguePartKind::Character, _) => Self::DualDialogueCharacterRight,
            (crate::pagination::DialoguePartKind::Parenthetical, 1) => {
                Self::DualDialogueParentheticalLeft
            }
            (crate::pagination::DialoguePartKind::Parenthetical, _) => {
                Self::DualDialogueParentheticalRight
            }
            (_, 1) => Self::DualDialogueLeft,
            (_, _) => Self::DualDialogueRight,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterruptionDashWrap {
    FinalDraft,
    KeepTogether,
}

pub struct WrapConfig {
    pub exact_width_chars: usize,
    pub interruption_dash_wrap: InterruptionDashWrap,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WrappedLine {
    pub text: String,
    pub start_offset: usize,
    pub end_offset: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WrappedStyledFragment {
    pub text: String,
    pub styles: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WrappedStyledLine {
    pub text: String,
    pub start_offset: usize,
    pub end_offset: usize,
    pub fragments: Vec<WrappedStyledFragment>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct WrapChunk {
    text: String,
    end_offset: usize,
}

impl WrapConfig {
    pub fn new(element_type: ElementType) -> Self {
        let geometry = LayoutGeometry::default();
        Self::from_geometry_final_draft(&geometry, element_type)
    }

    pub fn from_geometry_final_draft(geometry: &LayoutGeometry, element_type: ElementType) -> Self {
        Self::from_geometry_with_mode(geometry, element_type, InterruptionDashWrap::FinalDraft)
    }

    pub fn from_geometry_with_mode(
        geometry: &LayoutGeometry,
        element_type: ElementType,
        interruption_dash_wrap: InterruptionDashWrap,
    ) -> Self {
        Self {
            exact_width_chars: calculate_element_width(geometry, element_type),
            interruption_dash_wrap,
        }
    }

    pub fn with_exact_width_chars(width: usize) -> Self {
        Self {
            exact_width_chars: width,
            interruption_dash_wrap: InterruptionDashWrap::FinalDraft,
        }
    }
}

pub fn wrap_config_with_overrides(
    geometry: &LayoutGeometry,
    element_type: ElementType,
    overrides: &ElementLayoutOverrides,
    interruption_dash_wrap: InterruptionDashWrap,
) -> WrapConfig {
    if let Some(right_indent_delta) = overrides.right_indent_delta {
        let mut effective_geometry = geometry.clone();
        apply_right_indent_delta(&mut effective_geometry, element_type, right_indent_delta);
        return WrapConfig::from_geometry_with_mode(
            &effective_geometry,
            element_type,
            interruption_dash_wrap,
        );
    }

    WrapConfig::from_geometry_with_mode(geometry, element_type, interruption_dash_wrap)
}

fn apply_right_indent_delta(
    geometry: &mut LayoutGeometry,
    element_type: ElementType,
    right_indent_delta: f32,
) {
    match element_type {
        ElementType::Action => geometry.action_right += right_indent_delta,
        ElementType::ColdOpening => geometry.cold_opening_right += right_indent_delta,
        ElementType::NewAct => geometry.new_act_right += right_indent_delta,
        ElementType::EndOfAct => geometry.end_of_act_right += right_indent_delta,
        ElementType::SceneHeading => geometry.action_right += right_indent_delta,
        ElementType::Character => geometry.character_right += right_indent_delta,
        ElementType::Dialogue => geometry.dialogue_right += right_indent_delta,
        ElementType::Parenthetical => geometry.parenthetical_right += right_indent_delta,
        ElementType::Transition => geometry.transition_right += right_indent_delta,
        ElementType::Lyric => geometry.lyric_right += right_indent_delta,
        ElementType::DualDialogueLeft => geometry.dual_dialogue_left_right += right_indent_delta,
        ElementType::DualDialogueRight => geometry.dual_dialogue_right_right += right_indent_delta,
        ElementType::DualDialogueCharacterLeft => {
            geometry.dual_dialogue_left_character_right += right_indent_delta
        }
        ElementType::DualDialogueCharacterRight => {
            geometry.dual_dialogue_right_character_right += right_indent_delta
        }
        ElementType::DualDialogueParentheticalLeft => {
            geometry.dual_dialogue_left_parenthetical_right += right_indent_delta
        }
        ElementType::DualDialogueParentheticalRight => {
            geometry.dual_dialogue_right_parenthetical_right += right_indent_delta
        }
    }
}

pub fn wrap_text_for_element(text: &str, config: &WrapConfig) -> Vec<String> {
    wrap_text_for_element_with_offsets(text, config)
        .into_iter()
        .map(|line| line.text)
        .collect()
}

pub fn wrap_text_for_element_with_offsets(text: &str, config: &WrapConfig) -> Vec<WrappedLine> {
    let mut lines = Vec::new();
    let max_width = config.exact_width_chars;

    if text.is_empty() {
        return lines;
    }

    let paragraphs: Vec<&str> = text.split('\n').collect();
    let mut paragraph_offset = 0;

    for paragraph in paragraphs {
        let mut current_line = String::new();
        let mut current_line_start_offset = paragraph_offset;
        let mut current_line_end_offset = paragraph_offset;
        let words = tokenize_wrap_chunks(paragraph, paragraph_offset);

        let mut word_index = 0;
        while word_index < words.len() {
            let word = &words[word_index];
            let word_start_offset = line_start_offset_for_chunk(word);
            let combined = format!("{}{}", current_line, word.text);

            // Final Draft explicitly discounts trailing whitespace and exactly
            // ONE single trailing hyphen from column width limits.
            let trimmed = combined.trim_end_matches(' ');
            let mut effective_combined_len = trimmed.chars().count();

            if trimmed.ends_with('-') {
                effective_combined_len = effective_combined_len.saturating_sub(1);
            }

            let fits = effective_combined_len <= max_width;

            if current_line.is_empty() {
                // Always push the first word of a line, even if it's too long
                current_line.push_str(&word.text);
                current_line_start_offset = word_start_offset;
                current_line_end_offset = word.end_offset;
            } else if fits {
                current_line.push_str(&word.text);
                current_line_end_offset = word.end_offset;
            } else if should_split_interruption_dash(
                &current_line,
                &word.text,
                &words[word_index + 1..],
                max_width,
                config.interruption_dash_wrap,
            ) {
                let split_offset = word_start_offset + 1;
                current_line.push('-');
                current_line_end_offset = split_offset;
                lines.push(WrappedLine {
                    text: current_line.trim_end().to_string(),
                    start_offset: current_line_start_offset,
                    end_offset: current_line_end_offset,
                });
                current_line = split_interruption_dash_chunk(&word.text);
                current_line_start_offset = split_offset;
                current_line_end_offset = word.end_offset;
            } else if should_allow_hanging_trailing_double_hyphen_word(
                &current_line,
                &word.text,
                max_width,
                config.interruption_dash_wrap,
            ) {
                current_line.push_str(&word.text);
                current_line_end_offset = word.end_offset;
            } else if should_split_trailing_double_hyphen_word(
                &current_line,
                &word.text,
                max_width,
                config.interruption_dash_wrap,
            ) {
                let top_fragment = top_fragment_for_trailing_double_hyphen(&word.text);
                let split_offset = word_start_offset + top_fragment.len();
                current_line.push_str(&top_fragment);
                current_line_end_offset = split_offset;
                lines.push(WrappedLine {
                    text: current_line.trim_end().to_string(),
                    start_offset: current_line_start_offset,
                    end_offset: current_line_end_offset,
                });
                current_line = bottom_fragment_for_trailing_double_hyphen(&word.text);
                current_line_start_offset = split_offset;
                current_line_end_offset = word.end_offset;
            } else {
                // Line is full. Trim trailing spaces on the rendered visual line
                lines.push(WrappedLine {
                    text: current_line.trim_end().to_string(),
                    start_offset: current_line_start_offset,
                    end_offset: current_line_end_offset,
                });
                current_line = word.text.clone();
                current_line_start_offset = word_start_offset;
                current_line_end_offset = word.end_offset;
            }
            word_index += 1;
        }

        if !current_line.is_empty() {
            lines.push(WrappedLine {
                text: current_line.trim_end().to_string(),
                start_offset: current_line_start_offset,
                end_offset: current_line_end_offset,
            });
        }

        paragraph_offset += paragraph.len() + 1;
    }

    lines
}

fn should_split_interruption_dash(
    current_line: &str,
    next_chunk: &str,
    remaining_chunks: &[WrapChunk],
    max_width: usize,
    mode: InterruptionDashWrap,
) -> bool {
    if mode != InterruptionDashWrap::FinalDraft {
        return false;
    }

    if current_line.trim_end().is_empty() {
        return false;
    }

    if next_chunk.trim() != "--" {
        return false;
    }

    let keep_together_next_line =
        wrap_single_line_from_chunks(next_chunk.to_string(), remaining_chunks, max_width);
    let split_next_line = wrap_single_line_from_chunks(
        split_interruption_dash_chunk(next_chunk),
        remaining_chunks,
        max_width,
    );

    visible_alnum_count(&split_next_line) > visible_alnum_count(&keep_together_next_line)
}

fn split_interruption_dash_chunk(chunk: &str) -> String {
    let trailing_whitespace: String = chunk
        .chars()
        .rev()
        .take_while(|ch| ch.is_whitespace())
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    format!("-{trailing_whitespace}")
}

fn should_split_trailing_double_hyphen_word(
    current_line: &str,
    next_chunk: &str,
    max_width: usize,
    mode: InterruptionDashWrap,
) -> bool {
    if mode != InterruptionDashWrap::FinalDraft {
        return false;
    }

    let trimmed = next_chunk.trim_end();
    if !trimmed.ends_with("--") || trimmed.len() <= 2 {
        return false;
    }

    let stem = &trimmed[..trimmed.len() - 2];
    if !stem.chars().any(|ch| ch.is_alphanumeric()) {
        return false;
    }

    let combined = format!(
        "{current_line}{}",
        top_fragment_for_trailing_double_hyphen(next_chunk)
    );
    effective_line_len(&combined) <= max_width
}

fn should_allow_hanging_trailing_double_hyphen_word(
    current_line: &str,
    next_chunk: &str,
    max_width: usize,
    mode: InterruptionDashWrap,
) -> bool {
    if mode != InterruptionDashWrap::KeepTogether {
        return false;
    }

    if current_line.trim_end().is_empty() {
        return false;
    }

    let trimmed = next_chunk.trim_end();
    if !trimmed.ends_with("--") || trimmed.len() <= 2 {
        return false;
    }

    let stem = &trimmed[..trimmed.len() - 2];
    if !stem.chars().any(|ch| ch.is_alphanumeric()) {
        return false;
    }

    let combined = format!("{current_line}{next_chunk}");
    effective_line_len(&combined) == max_width + 1
}

fn top_fragment_for_trailing_double_hyphen(chunk: &str) -> String {
    let trimmed = chunk.trim_end();
    let trailing_whitespace: String = chunk[trimmed.len()..].to_string();
    let stem = &trimmed[..trimmed.len() - 2];
    format!("{stem}-{trailing_whitespace}")
}

fn bottom_fragment_for_trailing_double_hyphen(_chunk: &str) -> String {
    "-".to_string()
}

fn wrap_single_line_from_chunks(
    mut current_line: String,
    chunks: &[WrapChunk],
    max_width: usize,
) -> String {
    for chunk in chunks {
        let combined = format!("{current_line}{}", chunk.text);
        if current_line.is_empty() || effective_line_len(&combined) <= max_width {
            current_line.push_str(&chunk.text);
        } else {
            break;
        }
    }

    current_line.trim_end().to_string()
}

fn effective_line_len(text: &str) -> usize {
    let trimmed = text.trim_end_matches(' ');
    let mut effective_len = trimmed.chars().count();
    if trimmed.ends_with('-') {
        effective_len = effective_len.saturating_sub(1);
    }
    effective_len
}

fn visible_alnum_count(text: &str) -> usize {
    text.chars().filter(|ch| ch.is_alphanumeric()).count()
}

pub fn wrap_styled_text_for_element(
    text: &StyledText,
    config: &WrapConfig,
) -> Vec<WrappedStyledLine> {
    let wrapped_lines = wrap_text_for_element_with_offsets(&text.plain_text, config);
    let run_ranges = styled_run_ranges(text);

    wrapped_lines
        .into_iter()
        .map(|line| WrappedStyledLine {
            text: line.text,
            start_offset: line.start_offset,
            end_offset: line.end_offset,
            fragments: styled_fragments_for_range(&run_ranges, line.start_offset, line.end_offset),
        })
        .collect()
}

fn line_start_offset_for_chunk(chunk: &WrapChunk) -> usize {
    chunk.end_offset.saturating_sub(chunk.text.len())
}

fn styled_run_ranges(text: &StyledText) -> Vec<(usize, usize, &StyledRun)> {
    let mut ranges = Vec::with_capacity(text.runs.len());
    let mut start = 0usize;

    for run in &text.runs {
        let end = start + run.text.len();
        ranges.push((start, end, run));
        start = end;
    }

    ranges
}

fn styled_fragments_for_range(
    run_ranges: &[(usize, usize, &StyledRun)],
    start_offset: usize,
    end_offset: usize,
) -> Vec<WrappedStyledFragment> {
    run_ranges
        .iter()
        .filter_map(|(run_start, run_end, run)| {
            let slice_start = (*run_start).max(start_offset);
            let slice_end = (*run_end).min(end_offset);

            if slice_start >= slice_end {
                return None;
            }

            Some(WrappedStyledFragment {
                text: run.text[(slice_start - run_start)..(slice_end - run_start)].to_string(),
                styles: run.styles.clone(),
            })
        })
        .collect()
}

fn tokenize_wrap_chunks(paragraph: &str, paragraph_offset: usize) -> Vec<WrapChunk> {
    let chars: Vec<char> = paragraph.chars().collect();
    let mut chunks = Vec::new();
    let mut index = 0;
    let mut byte_index = paragraph_offset;

    while index < chars.len() {
        if chars[index].is_whitespace() {
            let start = index;
            while index < chars.len() && chars[index].is_whitespace() {
                byte_index += chars[index].len_utf8();
                index += 1;
            }
            chunks.push(WrapChunk {
                text: chars[start..index].iter().collect(),
                end_offset: byte_index,
            });
            continue;
        }

        let start = index;
        let word_start_offset = byte_index;
        while index < chars.len() && !chars[index].is_whitespace() {
            byte_index += chars[index].len_utf8();
            index += 1;
        }

        let word: String = chars[start..index].iter().collect();
        let mut word_chunks = split_breakable_hyphen_chunks(&word, word_start_offset);

        let ws_start = index;
        while index < chars.len() && chars[index].is_whitespace() {
            byte_index += chars[index].len_utf8();
            index += 1;
        }
        if ws_start < index {
            let whitespace: String = chars[ws_start..index].iter().collect();
            if let Some(last) = word_chunks.last_mut() {
                last.text.push_str(&whitespace);
                last.end_offset = byte_index;
            }
        }

        chunks.extend(word_chunks);
    }

    chunks
}

fn split_breakable_hyphen_chunks(word: &str, start_offset: usize) -> Vec<WrapChunk> {
    let chars: Vec<char> = word.chars().collect();
    let mut chunks = Vec::new();
    let mut current = String::new();
    let mut consumed_bytes = 0;
    let mut index = 0;

    while index < chars.len() {
        let ch = chars[index];
        current.push(ch);
        consumed_bytes += ch.len_utf8();

        if ch == '-' {
            let run_start = index;
            while index + 1 < chars.len() && chars[index + 1] == '-' {
                index += 1;
                current.push(chars[index]);
                consumed_bytes += chars[index].len_utf8();
            }

            let run_end = index;
            let has_alnum_neighbors = run_start > 0
                && run_end + 1 < chars.len()
                && chars[run_start - 1].is_alphanumeric()
                && chars[run_end + 1].is_alphanumeric();

            if has_alnum_neighbors {
                chunks.push(WrapChunk {
                    text: std::mem::take(&mut current),
                    end_offset: start_offset + consumed_bytes,
                });
            }
        }

        index += 1;
    }

    if !current.is_empty() {
        chunks.push(WrapChunk {
            text: current,
            end_offset: start_offset + consumed_bytes,
        });
    }

    chunks
}