Cotton code
647 lines · 26.0 KB · RustRaw
//! Fountain (<https://fountain.io/syntax>) as Cotton Screenplays writes it://! the whole `.fountain` document in and out, what each line of a scene is,//! what Return and Tab do in the editor, a heading's parts, a character//! name's completion and the page each scene stands on.//!//! The scene's body is the source of truth and its heading lives in its own//! column (`cotton_core::screenplay`, whose parser reads a body's elements//! with the line tests here). Everything below is derived; the shell draws//! what it answers and decides nothing.//!//! Columns are UTF-16 code units, the unit a platform text view counts in.//! Cases are the shared vectors in `vectors/fountain.json`.use serde::{Deserialize, Serialize};use crate::js::{is_js_whitespace, js_trim};/// A formatted page holds about this many lines (one minute of screen time).pub const LINES_PER_PAGE: u64 = 55;/// The synthetic two-scene script every surface seeds and tests with:/// invented, from no real script (`vectors/fountain_sample.fountain`).pub const SAMPLE: &str = include_str!("../vectors/fountain_sample.fountain");/// What a scene heading costs on the page: the blank above it, the line, the blank below.pub const HEADING_LINES: u64 = 3;// ── the line tests ──────────────────────────────────────────────────────────/// A Fountain scene heading: INT / EXT / EST / INT./EXT / INT/EXT / I/E/// followed by a dot or whitespace, or a line forced with a leading `.` (but/// not `...`). ASCII-case-insensitive.pub fn is_scene_heading(line: &str) -> bool {    let trimmed = js_trim(line);    if let Some(rest) = trimmed.strip_prefix('.') {        if rest.chars().next().is_some_and(|char| char.is_ascii_alphanumeric()) {            return true;        }    }    setting_prefix(trimmed).is_some()}/// The setting a heading opens with and the byte length it takes, the/// longest spelling first.fn setting_prefix(trimmed: &str) -> Option<(&'static str, usize)> {    const PREFIXES: [(&str, &str); 6] =        [("INT./EXT", "INT/EXT"), ("INT/EXT", "INT/EXT"), ("I/E", "INT/EXT"), ("INT", "INT"), ("EXT", "EXT"), ("EST", "EST")];    PREFIXES.iter().find_map(|(prefix, setting)| {        let fits = trimmed.as_bytes().get(..prefix.len()).is_some_and(|head| head.eq_ignore_ascii_case(prefix.as_bytes()))            && trimmed[prefix.len()..].chars().next().is_some_and(|char| char == '.' || is_js_whitespace(char));        fits.then_some((*setting, prefix.len()))    })}/// All-caps with at least one letter, cue-legal punctuation, not a/// transition. `[A-Z]` is ASCII on purpose: an all-caps line in another/// script is not read as a character cue.pub fn is_cue_shaped(name: &str) -> bool {    if name.is_empty() || name.ends_with("TO:") || !name.bytes().any(|byte| byte.is_ascii_uppercase()) {        return false;    }    name.chars().all(|char| matches!(char, 'A'..='Z' | '0'..='9' | ' ' | '.' | '\'' | '-' | '#' | '&'))}/// An all-caps line ending `TO:` — `CUT TO:`, `SMASH CUT TO:`.pub fn is_transition(line: &str) -> bool {    line == line.to_uppercase() && line.bytes().any(|byte| byte.is_ascii_uppercase()) && line.ends_with("TO:")}/// A cue line's anatomy: name, optional (EXTENSION), optional dual `^`.#[derive(Debug, Clone, PartialEq, Eq)]pub struct CueLine {    pub name: String,    pub extension: Option<String>,    pub dual: bool,}const fn is_js_line_terminator(char: char) -> bool {    matches!(char, '\n' | '\r' | '\u{2028}' | '\u{2029}')}/// `\s*\^?$` — the tail of a cue line. `None` when the remainder is something else.fn cue_tail(rest: &str) -> Option<bool> {    if let Some(head) = rest.strip_suffix('^') {        return head.chars().all(is_js_whitespace).then_some(true);    }    rest.chars().all(is_js_whitespace).then_some(false)}/// Split a cue line into name, extension and dual marker: the regex/// `/^(.*?)(?:\s*\(([^()]*)\))?\s*(\^)?$/` over the trimmed line, written/// out in its preference order — the SHORTEST name that leaves a legal tail/// wins, and at each length the branch WITH the parenthetical is tried first/// (`"MEERA (V.O.) (CONT'D)"` names `"MEERA (V.O.)"`). When no split is legal/// the whole trimmed line is the name.pub fn split_cue_line(line: &str) -> CueLine {    let trimmed = js_trim(line);    let boundaries = trimmed.char_indices().map(|(index, _)| index).chain(std::iter::once(trimmed.len()));    for index in boundaries {        let head = &trimmed[..index];        if head.chars().any(is_js_line_terminator) {            break;        }        let rest = &trimmed[index..];        let after_space = rest.trim_start_matches(is_js_whitespace);        if let Some(inside) = after_space.strip_prefix('(') {            if let Some(close) = inside.find(['(', ')']) {                if inside.as_bytes()[close] == b')' {                    if let Some(dual) = cue_tail(&inside[close + 1..]) {                        let extension = js_trim(&inside[..close]);                        return CueLine {                            name: js_trim(head).to_string(),                            extension: (!extension.is_empty()).then(|| extension.to_string()),                            dual,                        };                    }                }            }        }        if let Some(dual) = cue_tail(rest) {            return CueLine { name: js_trim(head).to_string(), extension: None, dual };        }    }    CueLine { name: trimmed.to_string(), extension: None, dual: false }}// ── what each line is ───────────────────────────────────────────────────────/// What one line of a scene is, which is how the editor sets it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum LineKind {    SceneHeading,    Action,    Character,    Dialogue,    Parenthetical,    Transition,    Centered,    Lyric,    Section,    Synopsis,    Note,    PageBreak,    Blank,}impl LineKind {    /// Set in capitals as it is typed.    pub fn capitals(self) -> bool {        matches!(self, Self::SceneHeading | Self::Character | Self::Transition)    }    fn speech(self) -> bool {        matches!(self, Self::Character | Self::Dialogue | Self::Parenthetical)    }}/// The text's lines, `\r\n` and a lone `\r` read as `\n`.fn lines_of(text: &str) -> Vec<String> {    text.replace("\r\n", "\n").replace('\r', "\n").split('\n').map(str::to_string).collect()}fn is_blank(line: &str) -> bool {    js_trim(line).is_empty()}/// Each line of a scene's body, what it is. A cue stands after a blank line/// (or the start) with words under it — or with nothing under it yet but the/// line being typed, so a name just written sets as a name. Under a cue or a/// parenthetical, a line in brackets is a parenthetical and any other is/// dialogue, until a blank line.pub fn line_kinds(body: &str) -> Vec<LineKind> {    let lines = lines_of(body);    let mut kinds: Vec<LineKind> = Vec::with_capacity(lines.len());    for (at, line) in lines.iter().enumerate() {        let previous = at.checked_sub(1).map(|before| kinds[before]);        let after_blank = previous.is_none_or(|kind| kind == LineKind::Blank);        let trimmed = js_trim(line);        let next = lines.get(at + 1);        let words_follow = match next {            None => true,            Some(next) if !is_blank(next) => true,            // The line being typed: an empty last line.            Some(next) => at + 2 == lines.len() && next.is_empty(),        };        let kind = if trimmed.is_empty() {            LineKind::Blank        } else if previous.is_some_and(LineKind::speech) && !forced(trimmed) {            if trimmed.starts_with('(') && trimmed.ends_with(')') { LineKind::Parenthetical } else { LineKind::Dialogue }        } else if trimmed.len() >= 3 && trimmed.chars().all(|char| char == '=') {            LineKind::PageBreak        } else if trimmed.starts_with('#') {            LineKind::Section        } else if trimmed.starts_with('=') {            LineKind::Synopsis        } else if trimmed.starts_with("[[") && trimmed.ends_with("]]") {            LineKind::Note        } else if trimmed.starts_with('~') {            LineKind::Lyric        } else if trimmed.starts_with('>') && trimmed.ends_with('<') {            LineKind::Centered        } else if trimmed.starts_with('>') {            LineKind::Transition        } else if trimmed.starts_with('!') {            LineKind::Action        } else if after_blank && is_scene_heading(trimmed) {            LineKind::SceneHeading        } else if after_blank && is_transition(trimmed) {            LineKind::Transition        } else if after_blank && words_follow && (trimmed.starts_with('@') || is_cue_shaped(&split_cue_line(trimmed).name)) {            LineKind::Character        } else {            LineKind::Action        };        kinds.push(kind);    }    kinds}/// A line whose first mark forces its kind out of a speech.fn forced(trimmed: &str) -> bool {    trimmed.starts_with('!') || trimmed.starts_with("[[")}// ── Return and Tab ──────────────────────────────────────────────────────────#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Key {    Return,    Tab,}/// Where the caret stands: a line of the body and a UTF-16 column in it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct Caret {    pub line: usize,    pub column: usize,}/// The body after a key, where the caret goes, and what its line now is.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Pressed {    pub body: String,    pub caret: Caret,    pub kind: LineKind,    /// Set what is typed on the caret's line in capitals.    pub capitals: bool,}/// What Return makes the next element, from the element it leaves: a/// heading, a transition or dialogue leads to action, a transition to the/// next heading, a cue or parenthetical to dialogue; action stays action.pub fn after_return(kind: LineKind) -> LineKind {    match kind {        LineKind::Character | LineKind::Parenthetical => LineKind::Dialogue,        LineKind::Transition => LineKind::SceneHeading,        _ => LineKind::Action,    }}/// What Tab turns an empty line into: action → character → transition →/// action, dialogue ↔ parenthetical, a heading back to action.pub fn after_tab(kind: LineKind) -> LineKind {    match kind {        LineKind::Action | LineKind::Blank => LineKind::Character,        LineKind::Character => LineKind::Transition,        LineKind::Dialogue => LineKind::Parenthetical,        LineKind::Parenthetical => LineKind::Dialogue,        _ => LineKind::Action,    }}fn utf16_len(text: &str) -> usize {    text.encode_utf16().count()}/// The byte offset of a UTF-16 column, clamped to the line.fn byte_at(line: &str, column: usize) -> usize {    let mut units = 0;    for (index, char) in line.char_indices() {        if units >= column {            return index;        }        units += char.len_utf16();    }    line.len()}/// The kind the caret line is to be set as: what the text makes it, or, on/// a line still empty, the kind the key chose for it.fn answer(lines: Vec<String>, caret: Caret, chosen: LineKind) -> Pressed {    let body = lines.join("\n");    let read = line_kinds(&body)[caret.line];    let kind = if read == LineKind::Blank { chosen } else { read };    Pressed { body, caret, kind, capitals: kind.capitals() }}/// The editor's Return or Tab at `caret` in `body`.////// Return splits the line at the caret; the new line is the element/// [`after_return`] names, with the blank line Fountain wants between two/// elements that are not one speech. Return on an empty line in a speech/// leaves the speech for action.////// Tab on an empty line turns it into the next kind [`after_tab`] names,/// writing the marks that kind needs (`()` for a parenthetical, `> ` for a/// transition); on a line with words, Tab under dialogue opens a/// parenthetical line beneath it, and elsewhere does nothing.pub fn press(body: &str, caret: Caret, key: Key) -> Pressed {    let mut lines = lines_of(body);    let at = caret.line.min(lines.len() - 1);    let kinds = line_kinds(body);    let kind = kinds[at];    let line = lines[at].clone();    let split = byte_at(&line, caret.column);    match key {        Key::Return => {            if is_blank(&line) {                // An empty line: a new empty line under it, for action (an                // empty line under a speech ends the speech).                lines.insert(at + 1, String::new());                return answer(lines, Caret { line: at + 1, column: 0 }, LineKind::Action);            }            let next = after_return(kind);            let (head, tail) = line.split_at(split);            lines[at] = head.to_string();            let in_speech = next == LineKind::Dialogue && kind.speech();            let mut place = at + 1;            if !in_speech {                lines.insert(place, String::new());                place += 1;            }            lines.insert(place, tail.to_string());            answer(lines, Caret { line: place, column: 0 }, next)        }        Key::Tab => {            let trimmed = js_trim(&line);            if trimmed.is_empty() || trimmed == "()" || trimmed == ">" {                let current = if trimmed == "()" {                    LineKind::Parenthetical                } else if trimmed == ">" {                    LineKind::Transition                } else if kind == LineKind::Blank && at > 0 && kinds[at - 1].speech() {                    LineKind::Dialogue                } else if kind == LineKind::Blank {                    LineKind::Action                } else {                    kind                };                let to = after_tab(current);                let (text, column) = match to {                    LineKind::Parenthetical => ("()", 1),                    LineKind::Transition => ("> ", 2),                    _ => ("", 0),                };                lines[at] = text.to_string();                return answer(lines, Caret { line: at, column }, to);            }            if kind == LineKind::Dialogue || kind == LineKind::Character {                lines.insert(at + 1, "()".to_string());                return answer(lines, Caret { line: at + 1, column: 1 }, LineKind::Parenthetical);            }            let column = caret.column.min(utf16_len(&line));            answer(lines, Caret { line: at, column }, kind)        }    }}// ── a heading's parts ───────────────────────────────────────────────────────/// A scene heading read into its parts: `INT. KITCHEN - NIGHT` is setting/// INT, place KITCHEN, time NIGHT. A forced heading has no setting.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct HeadingParts {    /// `INT`, `EXT`, `INT/EXT` or `EST`.    pub setting: Option<String>,    pub place: String,    pub time: Option<String>,    /// A `#12#` scene number at its end.    pub number: Option<String>,}pub fn heading_parts(heading: &str) -> HeadingParts {    let mut rest = js_trim(heading);    let mut number = None;    if let Some(open) = rest.strip_suffix('#').and_then(|inner| inner.rfind('#')) {        number = Some(rest[open + 1..rest.len() - 1].to_string()).filter(|text| !text.is_empty());        rest = js_trim(&rest[..open]);    }    let setting = if let Some(forced) = rest.strip_prefix('.').filter(|after| !after.starts_with('.')) {        rest = js_trim(forced);        None    } else if let Some((setting, length)) = setting_prefix(rest) {        rest = js_trim(rest[length..].trim_start_matches('.'));        Some(setting.to_string())    } else {        None    };    let (place, time) = match rest.rfind(" - ") {        Some(dash) => (js_trim(&rest[..dash]), Some(js_trim(&rest[dash + 3..]).to_string()).filter(|time| !time.is_empty())),        None => (rest, None),    };    HeadingParts { setting, place: place.to_string(), time, number }}/// A heading written from its parts: `INT. KITCHEN - NIGHT`.pub fn heading_of(parts: &HeadingParts) -> String {    let mut out = String::new();    if let Some(setting) = &parts.setting {        out.push_str(setting);        out.push_str(". ");    }    out.push_str(js_trim(&parts.place));    if let Some(time) = parts.time.as_deref().map(js_trim).filter(|time| !time.is_empty()) {        out.push_str(" - ");        out.push_str(time);    }    if let Some(number) = &parts.number {        out.push_str(&format!(" #{number}#"));    }    out}// ── a character's name ──────────────────────────────────────────────────────/// The names that complete `typed` on a cue line, in the order `known`/// gives them (the caller orders by use): a name whose capitals start with/// the typed capitals and is longer than them, once each. Nothing typed/// completes nothing.pub fn complete_character(typed: &str, known: &[String]) -> Vec<String> {    let typed = js_trim(typed).trim_start_matches('@').to_uppercase();    if typed.is_empty() {        return Vec::new();    }    let mut out: Vec<String> = Vec::new();    for name in known {        let name = js_trim(name).to_uppercase();        if name.len() > typed.len() && name.starts_with(&typed) && !out.contains(&name) {            out.push(name);        }    }    out}// ── pages ───────────────────────────────────────────────────────────────────/// The pages one scene runs over, counted from 1.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct PageSpan {    pub start: u64,    pub end: u64,    /// Its length in eighths of a page, at least one for a scene with lines.    pub eighths: u64,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Paging {    /// The script's whole pages, the last one part-filled counting whole.    pub pages: u64,    pub scenes: Vec<PageSpan>,}/// Each scene's pages, from the lines each takes on the page, run end to/// end at [`LINES_PER_PAGE`] lines a page.pub fn page_spans(lines: &[u64]) -> Paging {    let mut before = 0u64;    let mut scenes = Vec::with_capacity(lines.len());    for &count in lines {        let start = before / LINES_PER_PAGE + 1;        let after = before + count;        let end = if count == 0 { start } else { (after - 1) / LINES_PER_PAGE + 1 };        let eighths = if count == 0 { 0 } else { ((count * 8 + LINES_PER_PAGE / 2) / LINES_PER_PAGE).max(1) };        scenes.push(PageSpan { start, end, eighths });        before = after;    }    Paging { pages: before.div_ceil(LINES_PER_PAGE), scenes }}// ── the whole document ──────────────────────────────────────────────────────/// One `Key: value` of a title page.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct TitleField {    pub key: String,    pub value: String,}/// One scene of a document: its heading (none for words before the first/// heading) and its body, without the blank lines around it.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct DocumentScene {    pub heading: Option<String>,    pub body: String,}#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct Document {    pub title_page: Vec<TitleField>,    pub scenes: Vec<DocumentScene>,}impl Document {    /// The title page's value for `key`, any case.    pub fn field(&self, key: &str) -> Option<&str> {        self.title_page.iter().find(|field| field.key.eq_ignore_ascii_case(key)).map(|field| field.value.as_str())    }}/// `Key:` at a line's start: a letter, then letters, digits, spaces or dashes.fn title_key(line: &str) -> Option<(&str, &str)> {    let (key, value) = line.split_once(':')?;    let mut chars = key.chars();    (chars.next()?.is_ascii_alphabetic() && chars.all(|char| char.is_ascii_alphanumeric() || char == ' ' || char == '-'))        .then_some((key, value))}/// The lines of a scene's body without the blank lines around them.fn body_of(lines: &[String]) -> String {    let first = lines.iter().position(|line| !is_blank(line));    let last = lines.iter().rposition(|line| !is_blank(line));    match (first, last) {        (Some(first), Some(last)) => lines[first..=last].join("\n"),        _ => String::new(),    }}/// A whole `.fountain` read: the title page when the text opens with one,/// then a scene at each heading that stands after a blank line. Words/// before the first heading are a scene with no heading. Boneyard and notes/// stay in the bodies as written.pub fn parse_document(text: &str) -> Document {    let text = text.strip_prefix('\u{feff}').unwrap_or(text);    let lines = lines_of(text);    let mut at = 0;    let mut title_page: Vec<TitleField> = Vec::new();    if lines.first().and_then(|line| title_key(line)).is_some() {        while at < lines.len() && !is_blank(&lines[at]) {            let line = &lines[at];            match title_key(line) {                Some((key, value)) if !line.starts_with(is_js_whitespace) => {                    title_page.push(TitleField { key: key.to_string(), value: js_trim(value).to_string() })                }                _ => {                    if let Some(field) = title_page.last_mut() {                        if !field.value.is_empty() {                            field.value.push('\n');                        }                        field.value.push_str(js_trim(line));                    }                }            }            at += 1;        }    }    let mut scenes: Vec<DocumentScene> = Vec::new();    let mut heading: Option<String> = None;    let mut body: Vec<String> = Vec::new();    let mut after_blank = true;    for line in &lines[at..] {        let trimmed = js_trim(line);        if after_blank && is_scene_heading(trimmed) {            let text = body_of(&body);            if heading.is_some() || !text.is_empty() {                scenes.push(DocumentScene { heading: heading.take(), body: text });            }            let written = trimmed.strip_prefix('.').filter(|_| setting_prefix(trimmed).is_none() && !trimmed.starts_with(".."));            heading = Some(written.unwrap_or(trimmed).to_string());            body.clear();        } else {            body.push(line.clone());        }        after_blank = trimmed.is_empty();    }    let text = body_of(&body);    if heading.is_some() || !text.is_empty() {        scenes.push(DocumentScene { heading, body: text });    }    Document { title_page, scenes }}/// A whole `.fountain` written: the title page (a value of several lines/// indented under its key), then each scene's heading and body as their own/// paragraphs, blank-line separated, with a trailing newline. A heading/// Fountain would not read as one is forced with `.`, a body line that would/// read as one is forced as action; an empty heading or body is left out.pub fn write_document(document: &Document) -> String {    let mut parts: Vec<String> = Vec::new();    if !document.title_page.is_empty() {        let page: Vec<String> = document            .title_page            .iter()            .map(|field| {                if field.value.contains('\n') {                    let indented: Vec<String> = field.value.split('\n').map(|line| format!("   {}", js_trim(line))).collect();                    format!("{}:\n{}", field.key, indented.join("\n"))                } else {                    format!("{}: {}", field.key, field.value)                }            })            .collect();        parts.push(page.join("\n"));    }    for scene in &document.scenes {        if let Some(heading) = scene.heading.as_deref().map(js_trim).filter(|heading| !heading.is_empty()) {            let forced = !is_scene_heading(heading) && heading.chars().next().is_some_and(|first| first.is_ascii_alphanumeric());            parts.push(if forced { format!(".{heading}") } else { heading.to_string() });        }        let body = js_trim(&scene.body);        if !body.is_empty() {            parts.push(guarded(body));        }    }    format!("{}\n", parts.join("\n\n"))}/// A body as the document carries it: a line that would read as a heading/// where it stands (the body's first, or after a blank line) is forced as/// action with `!`, so the scene comes back whole; a `.`-forced heading is/// the writer's own and stays.fn guarded(body: &str) -> String {    let mut after_blank = true;    let lines: Vec<String> = lines_of(body)        .into_iter()        .map(|line| {            let trimmed = js_trim(&line);            let force = after_blank && !trimmed.starts_with('.') && is_scene_heading(trimmed);            after_blank = trimmed.is_empty();            if force { format!("!{line}") } else { line }        })        .collect();    lines.join("\n")}/// The name a document is saved under: its title's words joined by spaces,/// the marks a file system refuses taken out, `.fountain` after; `None` for/// a title with no words, which the caller names from its lines.pub fn file_name(title: &str) -> Option<String> {    let clean: String = title        .chars()        .map(|char| if matches!(char, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || char.is_control() { ' ' } else { char })        .collect();    let words: Vec<&str> = clean.split_whitespace().collect();    (!words.is_empty()).then(|| format!("{}.fountain", words.join(" ")))}#[cfg(test)]#[path = "fountain_tests.rs"]mod tests;