//! What Return and Tab do in the writer, and the element bar's "make this//! line that kind". The person just types and presses Return; these decide//! what the next line is and write the marks a kind needs so that Fountain//! reads it that way on its own.use serde::{Deserialize, Serialize};usesuper::lines::{bare_name, caps_name, known, lines_chosen, raw_lines, transition_shaped, unmarked, Kind, Line};usesuper::{byte_at, heading, utf16_len};#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pubenumKey {Return,Tab,}/// The body after a key or an element, where the cursor stands, and the/// kind of the line the cursor stands on.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructPressed {pub body: String,pub cursor: usize,pub kind: Kind,/// The line the cursor stands on (0-based).pub line: usize,}structDoc { lines: Vec<String>,}implDoc {fn of(body: &str) -> Doc {Doc { lines: raw_lines(body).into_iter().map(|(_, text)| text.to_string()).collect() } }fn body(&self) -> String {self.lines.join("\n") }/// The UTF-16 offset of `column` (UTF-16) in line `line`.fn offset(&self, line: usize, column: usize) -> usize {self.lines[..line].iter().map(|text| utf16_len(text) + 1).sum::<usize>() + column }/// The line and UTF-16 column of an offset, clamped.fn caret(&self, offset: usize) -> (usize, usize) {letmut left = offset;for (index, text) inself.lines.iter().enumerate() {let len = utf16_len(text);if left <= len || index + 1 == self.lines.len() {return (index, left.min(len)); } left -= len + 1; } (0, 0) }}fn is_blank(text: &str) -> bool { text.trim().is_empty()}/// The kind the line stands as: the text's reading, or the person's chosen/// kind while the text alone reads it as action or blank.fn kind_at(body: &str, names: &[String], line: usize, chosen: Option<Kind>) -> Kind {let read = lines_chosen(body, names, chosen.map(|kind| (line, kind))); read.get(line).map(|line| line.kind).unwrap_or(Kind::Blank)}fn latin(text: &str) -> bool { text.chars().any(|c| c.is_ascii_alphabetic())}/// Rewrite `text` (its marks taken off) so that, standing where it stands,/// Fountain reads it as `kind`.fn marked(kind: Kind, bare: &str, names: &[String], in_speech_above: bool) -> String {match kind {Kind::Blank => String::new(),Kind::Action => {// Forced only where the words alone would read otherwise.let name = bare_name(bare);let reads_otherwise = in_speech_above || heading::is_heading(bare) || transition_shaped(bare) || caps_name(&name) || known(&name, names) || bare.starts_with(['!', '@', '>', '.', '=', '#', '(', '[']) || bare.is_empty();if reads_otherwise && !bare.is_empty() { format!("!{bare}") } else { bare.to_string() } }Kind::Character => {if bare.is_empty() {returnString::new(); }let upper = if latin(bare) { bare.to_uppercase() } else { bare.to_string() };let name = bare_name(&upper);if caps_name(&name) || known(&name, names) { upper } else { format!("@{upper}") } }Kind::Dialogue => bare.to_string(),Kind::Parenthetical => format!("({bare})"),Kind::Transition => {let upper = bare.to_uppercase();if transition_shaped(&upper) { upper } else { format!(">{upper}") } }Kind::Heading => {let upper = bare.to_uppercase();if heading::is_heading(&upper) { upper } else { format!(".{upper}") } }Kind::Centered => format!(">{bare}<"),Kind::Note => format!("[[{bare}]]"), }}/// Make line `line` of `body` the kind `kind` (the element bar). The line's/// marks are rewritten for the new kind, a blank line is put above a name,/// a transition or a heading that needs one, and a speech line under a blank/// joins the speech above it. The cursor goes to the end of that line; on an/// empty line the kind stands as chosen for the line being typed.pubfn kind(body: &str, line: usize, kind: Kind, names: &[String]) -> Pressed {letmut doc = Doc::of(body);if line >= doc.lines.len() {let end = doc.offset(doc.lines.len() - 1, utf16_len(doc.lines.last().unwrap()));let at = doc.lines.len() - 1;returnPressed { body: doc.body(), cursor: end, kind: kind_at(body, names, at, None), line: at }; }let read = lines_chosen(body, names, None);let current = read[line].kind;letmut bare = unmarked(current, &doc.lines[line]);if current == Kind::Note && (bare.starts_with('#') || bare.starts_with('=')) { bare = bare.trim_start_matches(['#', '=']).trim().to_string(); }letmut line = line;let above_blank = line == 0 || is_blank(&doc.lines[line - 1]);let in_speech_above = line > 0 && !above_blank && read[line - 1].kind.in_speech();match kind {Kind::Character | Kind::Transition | Kind::Headingif !above_blank => { doc.lines.insert(line, String::new()); line += 1; }Kind::Dialogue | Kind::Parentheticalif above_blank && line >= 2 && read[line - 2].kind.in_speech() => { doc.lines.remove(line - 1); line -= 1; } _ => {} }let speech_above = kind.in_speech() || in_speech_above; doc.lines[line] = marked(kind, &bare, names, speech_above && kind == Kind::Action);letmut cursor_column = utf16_len(&doc.lines[line]);if kind == Kind::Parenthetical && bare.is_empty() { cursor_column = 1; }let body = doc.body();let chosen = is_blank(&doc.lines[line]) || kind == Kind::Parenthetical && bare.is_empty();let answered = kind_at(&body, names, line, chosen.then_some(kind));Pressed { cursor: doc.offset(line, cursor_column), body, kind: answered, line }}/// The writer's Return or Tab at `cursor` (UTF-16) in `body`. `chosen` is/// the kind the bar shows for the cursor's line, when the person picked one.////// Return:/// - on a line with words, the line is first written as the kind it stands/// as (a chosen name in capitals, or forced with `@` in a script without/// them), then split at the cursor; at the line's end the new line is/// what follows its kind: speech after a name or an aside; after speech, a/// blank line and a line for the next name; after action, a heading or a/// transition, a blank line and action. Inside a line the split keeps the/// kind./// - on an empty line of speech or a name (the empty Return), the line is/// action, the body untouched./// - on an empty line otherwise, a new line of action.////// Tab on an empty line: action or blank becomes a name, a name action,/// speech an aside (its brackets written, the cursor inside), an empty/// aside speech. On a line with words it turns the line into the next kind:/// action ↔ name, speech ↔ aside, a transition or heading to action.pubfn press(body: &str, cursor: usize, key: Key, names: &[String], chosen: Option<Kind>) -> Pressed {let doc = Doc::of(body);let (line, column) = doc.caret(cursor);let stands = kind_at(body, names, line, chosen);let text = doc.lines[line].clone();match key {Key::Tab => tab(body, line, stands, &text, names),Key::Return => enter(doc, line, column, stands, names), }}fn tab(body: &str, line: usize, stands: Kind, text: &str, names: &[String]) -> Pressed {let empty_aside = stands == Kind::Parenthetical && unmarked(Kind::Parenthetical, text).is_empty();if is_blank(text) || empty_aside {let next = match stands {Kind::Character => Kind::Action,Kind::Dialogue => Kind::Parenthetical,Kind::Parenthetical => Kind::Dialogue, _ => Kind::Character, };return kind(body, line, next, names); }let next = match stands {Kind::Action => Kind::Character,Kind::Character => Kind::Action,Kind::Dialogue => Kind::Parenthetical,Kind::Parenthetical => Kind::Dialogue, _ => Kind::Action, }; kind(body, line, next, names)}fn enter(mut doc: Doc, line: usize, column: usize, stands: Kind, names: &[String]) -> Pressed {let text = doc.lines[line].clone();if is_blank(&text) {if stands.in_speech() {// The empty Return: the line leaves the speech for action.let body = doc.body();let cursor = doc.offset(line, utf16_len(&text));returnPressed { kind: kind_at(&body, names, line, Some(Kind::Action)), body, cursor, line }; } doc.lines.insert(line + 1, String::new());let body = doc.body();returnPressed { cursor: doc.offset(line + 1, 0), kind: kind_at(&body, names, line + 1, Some(Kind::Action)), body, line: line + 1 }; }// Write the line as the kind it stands as, so its text says so.let read_alone = kind_at(&doc.body(), names, line, None);letmut column = column;if read_alone != stands && matches!(stands, Kind::Character | Kind::Transition | Kind::Parenthetical | Kind::Heading) {let before = utf16_len(&doc.lines[line]);let body = doc.body();let rewritten = kind(&body, line, stands, names);let at_end = column >= before; doc = Doc::of(&rewritten.body);let line_now = rewritten.line;let len = utf16_len(&doc.lines[line_now]); column = if at_end { len } else { column.min(len) };return split(doc, line_now, column, stands, names); } split(doc, line, column, stands, names)}fn split(mut doc: Doc, line: usize, column: usize, stands: Kind, names: &[String]) -> Pressed {let text = doc.lines[line].clone();let at = byte_at(&text, column);let (head, tail) = (text[..at].to_string(), text[at..].to_string());let at_end = tail.trim().is_empty();let (next, gap) = if at_end {match stands {Kind::Character | Kind::Parenthetical => (Kind::Dialogue, false),Kind::Dialogue => (Kind::Character, true), _ => (Kind::Action, true), } } else { (stands, false) }; doc.lines[line] = head;letmut new_line = line + 1;if gap { doc.lines.insert(new_line, String::new()); new_line += 1; } doc.lines.insert(new_line, if at_end { String::new() } else { tail });let body = doc.body();let chosen = at_end.then_some(next);Pressed { cursor: doc.offset(new_line, 0), kind: kind_at(&body, names, new_line, chosen), body, line: new_line }}/// The lines of a body with the kind chosen for one line ([`lines_chosen`]),/// for the methods' answers.pubfn read(body: &str, names: &[String], chosen: Option<(usize, Kind)>) -> Vec<Line> { lines_chosen(body, names, chosen)}