Cotton code
187 lines · 6.9 KB · RustRaw
//! A whole story as a Fountain file (<https://fountain.io/syntax>) and back://! the title page's keys, then each scene's heading, its one-line summary as//! a Fountain synopsis (`= …`) and its body. Reading what [`write`] wrote//! gives the same story, so writing it again gives the same bytes.use serde::{Deserialize, Serialize};use super::heading;#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct SceneDoc {    #[serde(default)]    pub heading: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub summary: Option<String>,    #[serde(default)]    pub body: String,}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Doc {    /// The title page, `(key, value)` in order; a value may hold lines.    #[serde(default)]    pub title: Vec<(String, String)>,    #[serde(default)]    pub scenes: Vec<SceneDoc>,}fn forced_heading(trimmed: &str) -> bool {    trimmed == "." || trimmed.strip_prefix('.').is_some_and(|rest| !rest.starts_with('.'))}fn heading_like(line: &str) -> bool {    let trimmed = line.trim();    forced_heading(trimmed) || heading::is_heading(trimmed)}/// A body line [`write`] escapes with `!` (Fountain's forced action) so it/// cannot be read as a heading or a synopsis: one that would, or one that/// already starts with a `!` such a line would get.fn escapable(line: &str) -> bool {    let trimmed = line.trim_start();    heading_like(trimmed) || trimmed.starts_with('=') || trimmed.strip_prefix('!').is_some_and(escapable)}/// `Key:` at a title page 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();    let first = chars.next()?;    (first.is_alphabetic() && chars.all(|c| c.is_alphanumeric() || c == ' ' || c == '-')).then_some((key.trim(), value.trim()))}/// The story written as Fountain, one trailing newline.pub fn write(doc: &Doc) -> String {    let mut out = String::new();    for (key, value) in &doc.title {        if value.contains('\n') {            out.push_str(key);            out.push_str(":\n");            for line in value.split('\n') {                out.push_str("   ");                out.push_str(line);                out.push('\n');            }        } else {            out.push_str(key);            out.push_str(": ");            out.push_str(value);            out.push('\n');        }    }    for scene in &doc.scenes {        if !out.is_empty() {            out.push('\n');        }        let head = scene.heading.trim();        if heading::is_heading(head) {            out.push_str(head);        } else {            out.push('.');            out.push_str(head);        }        out.push('\n');        if let Some(summary) = scene.summary.as_deref().map(str::trim).filter(|summary| !summary.is_empty()) {            out.push_str("\n= ");            out.push_str(summary);            out.push('\n');        }        let body = scene.body.trim_matches('\n');        if !body.trim().is_empty() {            out.push('\n');            for line in body.split('\n') {                if escapable(line) {                    out.push('!');                }                out.push_str(line);                out.push('\n');            }        }    }    out}/// A Fountain file read into a story: the title page when it 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.pub fn read(text: &str) -> Doc {    let text = text.replace("\r\n", "\n").replace('\r', "\n");    let text = text.strip_prefix('\u{feff}').unwrap_or(&text);    let lines: Vec<&str> = text.split('\n').collect();    let mut doc = Doc::default();    let mut at = 0;    // A title page opens with one of Fountain's own keys.    const KEYS: [&str; 11] = ["title", "credit", "author", "authors", "source", "draft date", "date", "contact", "copyright", "notes", "revision"];    let opens_title = lines.first().and_then(|line| title_key(line)).is_some_and(|(key, _)| KEYS.contains(&key.to_lowercase().as_str()));    if opens_title {        while at < lines.len() && !lines[at].trim().is_empty() {            let line = lines[at];            if let Some((key, value)) = title_key(line).filter(|_| !line.starts_with([' ', '\t'])) {                doc.title.push((key.to_string(), value.to_string()));            } else if let Some((_, value)) = doc.title.last_mut() {                let more = line.strip_prefix("   ").or_else(|| line.strip_prefix('\t')).unwrap_or(line.trim_start());                if value.is_empty() {                    value.push_str(more);                } else {                    value.push('\n');                    value.push_str(more);                }            }            at += 1;        }    }    let starts = |index: usize| -> bool {        heading_like(lines[index]) && (index == 0 || index == at || lines[index - 1].trim().is_empty())    };    let mut current: Option<(String, Vec<&str>)> = None;    let mut scenes: Vec<(String, Vec<&str>)> = Vec::new();    for index in at..lines.len() {        if starts(index) {            if let Some(scene) = current.take() {                scenes.push(scene);            }            let trimmed = lines[index].trim();            let head = if forced_heading(trimmed) { trimmed[1..].to_string() } else { trimmed.to_string() };            current = Some((head, Vec::new()));        } else {            match current.as_mut() {                Some((_, body)) => body.push(lines[index]),                None if lines[index].trim().is_empty() => {}                None => current = Some((String::new(), vec![lines[index]])),            }        }    }    if let Some(scene) = current.take() {        scenes.push(scene);    }    for (head, mut body) in scenes {        while body.first().is_some_and(|line| line.trim().is_empty()) {            body.remove(0);        }        let mut summary = None;        if let Some(first) = body.first() {            let trimmed = first.trim();            if trimmed.starts_with('=') && !trimmed.starts_with("===") && body.get(1).is_none_or(|next| next.trim().is_empty()) {                summary = Some(trimmed[1..].trim().to_string());                body.remove(0);            }        }        while body.first().is_some_and(|line| line.trim().is_empty()) {            body.remove(0);        }        while body.last().is_some_and(|line| line.trim().is_empty()) {            body.pop();        }        let body: Vec<String> = body            .iter()            .map(|line| match line.strip_prefix('!').filter(|rest| escapable(rest)) {                Some(rest) => rest.to_string(),                None => line.to_string(),            })            .collect();        doc.scenes.push(SceneDoc { heading: head, summary, body: body.join("\n") });    }    doc}