Skip to main content

music21/abc/
write.rs

1//! Writing ABC: a score as the text `from_abc` reads back.
2//!
3//! music21 has no ABC writer, so there is no text of its to match. What is
4//! matched is its *reader*: wherever ABC can be written two ways, the one
5//! written is the one music21's `abcFormat` reads back as the score it was
6//! written from, and the notes on what is where below are about that reader.
7
8use std::collections::BTreeMap;
9use std::fmt::Write as _;
10
11use super::translate::class_sort_order;
12use crate::articulations::{Articulation, ArticulationKind, Finger};
13use crate::bar::{Barline, BarlineType, Ending, RepeatDirection};
14use crate::chord::Chord;
15use crate::chordsymbol::ChordSymbol;
16use crate::clef::Clef;
17use crate::defaults::{FloatType, IntegerType, UnsignedIntegerType};
18use crate::duration::{Duration, TupletType, limited_fraction};
19use crate::error::{Error, Result};
20use crate::expressions::{ArpeggioType, Expression, FermataType, OrnamentKind};
21use crate::key::KeySignature;
22use crate::metadata::Metadata;
23use crate::meter::TimeSignature;
24use crate::notation::{BeamType, Beams, Lyric, Placement, TieType};
25use crate::note::Note;
26use crate::pitch::Pitch;
27use crate::repeat::RepeatExpressionKind;
28use crate::rest::Rest;
29use crate::spanner::SpannerKind;
30use crate::stream::{Stream, StreamElement, StreamKind};
31use crate::tempo::MetronomeMark;
32
33fn abc_error(message: impl Into<String>) -> Error {
34    Error::abc(message.into())
35}
36
37/// How [`to_abc`] writes a score.
38#[derive(Clone, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub struct ExportOptions {
41    /// The unit note length of the `L:` field as a fraction of a whole note,
42    /// `(1, 8)` for an eighth. `None` takes the one the tune's lengths are
43    /// shortest to write against.
44    pub unit_length: Option<(UnsignedIntegerType, UnsignedIntegerType)>,
45    /// How many measures go on a line of music.
46    pub measures_per_line: usize,
47}
48
49impl Default for ExportOptions {
50    fn default() -> Self {
51        Self {
52            unit_length: None,
53            measures_per_line: 4,
54        }
55    }
56}
57
58/// Writes a score as ABC.
59///
60/// A score is one tune and an opus one tune for each score it holds, under
61/// the `X:` number its metadata gives it. A part alone, or a stream of loose
62/// notes, is a tune of one voice. The header carries the title, composer and
63/// origin, the meter, the unit note length, the tempo and the key with its
64/// mode; a score of several parts has a `V:` voice for each, and a part
65/// whose measures hold voices of their own has one for each of those. A
66/// voice's clef is said on its `V:` line, unless it is a treble clef the
67/// notes fit, which is what a reader takes where none is said, and a part's
68/// name goes there too; a tune of one voice has a `V:` line only for those.
69/// A part opening with an instrument that has a General MIDI program says so
70/// with abc2midi's `%%MIDI program`, before its music.
71///
72/// What ABC has no way to say is refused with [`Error::Abc`] rather than
73/// left out: a microtone, a tuplet inside a tuplet, an unpitched stroke, a
74/// chord symbol or a dynamic standing where no note starts, a pedal with its
75/// bounces and gaps, an octave line, a glissando, a tremolo between notes, a
76/// rehearsal mark or a metric modulation. A barline inside a measure is
77/// drawn and not heard, and is written as nothing.
78///
79/// Three things are written as music21's reader takes them, since
80/// [`from_abc`](crate::abc::from_abc) is that reader. An accidental is
81/// written on every note that shows one and carries no further into the
82/// bar. A tuplet's count of notes takes in any grace notes written among
83/// them. And a field changing the meter, the key or the tempo at a barline
84/// stands on lines of its own after that barline, where two fields together
85/// are read as belonging to the measure that follows.
86///
87/// ```
88/// use music21::abc::{ExportOptions, from_abc, to_abc};
89///
90/// let tune = "X:1\nT:Scale\nM:4/4\nL:1/4\nK:G\nGABc|defg|a4|]\n";
91/// let score = from_abc(tune)?;
92/// let written = to_abc(&score, &ExportOptions::default())?;
93/// assert_eq!(
94///     written,
95///     "X:1\nT:Scale\nM:4/4\nL:1/4\nK:G\nG A B c | d e f g | a4 |]\n"
96/// );
97/// // What was written reads back as the score it was written from.
98/// assert_eq!(to_abc(&from_abc(&written)?, &ExportOptions::default())?, written);
99/// # Ok::<(), music21::Error>(())
100/// ```
101pub fn to_abc(stream: &Stream, options: &ExportOptions) -> Result<String> {
102    if stream.kind() == StreamKind::Opus {
103        let mut tunes = Vec::new();
104        for (index, event) in stream.events().iter().enumerate() {
105            let score = event
106                .element()
107                .as_stream()
108                .ok_or_else(|| abc_error("an opus holds something that is not a score"))?;
109            tunes.push(Tune::new(score, index as IntegerType + 1)?.write(options)?);
110        }
111        return Ok(tunes.join("\n"));
112    }
113    Tune::new(stream, 1)?.write(options)
114}
115
116const EPSILON: FloatType = 1e-6;
117
118/// A length as a fraction, where it is one a note could have.
119fn fraction(value: FloatType) -> Result<(i128, i128)> {
120    limited_fraction(value, 4096)
121        .filter(|(numerator, denominator)| {
122            (*numerator as FloatType / *denominator as FloatType - value).abs() < 1e-7
123        })
124        .ok_or_else(|| {
125            abc_error(format!(
126                "ABC cannot write a length of {value} quarter notes"
127            ))
128        })
129}
130
131/// A length against the unit note length, as it follows a note.
132fn length_text(written: FloatType, unit: FloatType) -> Result<String> {
133    let (numerator, denominator) = fraction(written / unit)?;
134    Ok(match (numerator, denominator) {
135        (1, 1) => String::new(),
136        (numerator, 1) => numerator.to_string(),
137        (1, 2) => "/".to_string(),
138        (1, denominator) => format!("/{denominator}"),
139        (numerator, denominator) => format!("{numerator}/{denominator}"),
140    })
141}
142
143/// Text that can stand in a field: on one line.
144fn plain(text: &str) -> String {
145    text.replace(['\n', '\r'], " ").trim().to_string()
146}
147
148/// Text that can stand between quotation marks.
149fn quoted(text: &str) -> String {
150    plain(text).replace('"', "'")
151}
152
153/// How far each of the seven letters, C to B, is moved by a signature.
154type Alters = [IntegerType; 7];
155
156fn letter_index(letter: char) -> usize {
157    match letter {
158        'C' => 0,
159        'D' => 1,
160        'E' => 2,
161        'F' => 3,
162        'G' => 4,
163        'A' => 5,
164        _ => 6,
165    }
166}
167
168fn alters_of(signature: &KeySignature) -> Alters {
169    let mut alters = [0; 7];
170    for pitch in signature.altered_pitches().unwrap_or_default() {
171        alters[letter_index(pitch.step().as_char())] = pitch.alter().round() as IntegerType;
172    }
173    alters
174}
175
176/// The signature a key or key signature element writes.
177fn signature_of(element: &StreamElement) -> Option<KeySignature> {
178    match element {
179        StreamElement::Key(key) => Some(key.key_signature()),
180        StreamElement::KeySignature(signature) => Some(signature.clone()),
181        _ => None,
182    }
183}
184
185/// The clef as ABC names one.
186fn clef_name(clef: &Clef) -> Result<String> {
187    let mut name = match (clef.sign(), clef.line()) {
188        (Some("G"), Some(2) | None) => "treble".to_string(),
189        (Some("G"), Some(line)) => format!("treble{line}"),
190        (Some("F"), Some(4) | None) => "bass".to_string(),
191        (Some("F"), Some(line)) => format!("bass{line}"),
192        (Some("C"), Some(3) | None) => "alto".to_string(),
193        (Some("C"), Some(4)) => "tenor".to_string(),
194        (Some("C"), Some(line)) => format!("alto{line}"),
195        (Some("percussion"), _) => "perc".to_string(),
196        (Some("none"), _) | (None, _) => "none".to_string(),
197        (Some(sign), _) => {
198            return Err(abc_error(format!("ABC has no {sign} clef")));
199        }
200    };
201    match clef.octave_change() {
202        0 => {}
203        1 => name.push_str("+8"),
204        -1 => name.push_str("-8"),
205        other => {
206            return Err(abc_error(format!(
207                "ABC has no clef moved by {other} octaves"
208            )));
209        }
210    }
211    Ok(name)
212}
213
214/// The data of a `K:` field for a key or a key signature, with a clef after
215/// it where one is to be named.
216fn key_field(element: &StreamElement, clef: Option<&Clef>) -> Result<String> {
217    let clef = clef.map(clef_name).transpose()?;
218    let mode = match element {
219        StreamElement::Key(key) => match key.mode() {
220            "major" => Some(""),
221            "minor" => Some("m"),
222            "dorian" => Some("dor"),
223            "phrygian" => Some("phr"),
224            "lydian" => Some("lyd"),
225            "mixolydian" => Some("mix"),
226            "aeolian" => Some("aeo"),
227            "ionian" => Some("ion"),
228            "locrian" => Some("loc"),
229            _ => None,
230        },
231        _ => None,
232    };
233    let mut text = match (element, mode) {
234        (StreamElement::Key(key), Some(mode)) => {
235            // A clef after a bare tonic would be read as the mode.
236            let mode = if mode.is_empty() && clef.is_some() {
237                " maj"
238            } else {
239                mode
240            };
241            format!("{}{mode}", key.tonic_pitch().name())
242        }
243        _ => {
244            // A signature with no mode: the major tonic it would have, and
245            // then every accidental said, which leaves no mode to read.
246            let signature = signature_of(element)
247                .ok_or_else(|| abc_error("a key field written for what is no key"))?;
248            // A non-traditional signature says every accidental itself.
249            let tonic = if signature.is_non_traditional() {
250                "C".to_string()
251            } else {
252                let key = KeySignature::new(signature.sharps()).as_key("major");
253                key.tonic_pitch().name()
254            };
255            let mut text = format!("{tonic} exp");
256            for pitch in signature.altered_pitches()? {
257                let _ = write!(
258                    text,
259                    " {}{}",
260                    accidental_marks(pitch.alter().round() as IntegerType)?,
261                    pitch.step().as_char().to_ascii_lowercase()
262                );
263            }
264            text
265        }
266    };
267    if let Some(clef) = clef {
268        let _ = write!(text, " clef={clef}");
269    }
270    Ok(text)
271}
272
273fn accidental_marks(alter: IntegerType) -> Result<&'static str> {
274    Ok(match alter {
275        -2 => "__",
276        -1 => "_",
277        0 => "=",
278        1 => "^",
279        2 => "^^",
280        other => {
281            return Err(abc_error(format!(
282                "ABC has no accidental moving a note by {other} semitones"
283            )));
284        }
285    })
286}
287
288fn meter_field(meter: &TimeSignature) -> String {
289    match meter.symbol() {
290        Some("common") => "C".to_string(),
291        Some("cut") => "C|".to_string(),
292        _ => meter.ratio_string(),
293    }
294}
295
296fn number_text(number: FloatType) -> String {
297    if number.fract() == 0.0 {
298        format!("{number:.0}")
299    } else {
300        number.to_string()
301    }
302}
303
304/// The data of a `Q:` field, or nothing for a mark that says nothing.
305fn tempo_field(mark: &MetronomeMark) -> Result<Option<String>> {
306    let mut parts = Vec::new();
307    if let Some(text) = mark.text().filter(|_| !mark.text_implicit()) {
308        parts.push(format!("\"{}\"", quoted(text)));
309    }
310    if let Some(number) = mark.number().filter(|_| !mark.number_implicit()) {
311        let (numerator, denominator) = fraction(mark.referent().quarter_length() / 4.0)?;
312        parts.push(format!("{numerator}/{denominator}={}", number_text(number)));
313    }
314    Ok((!parts.is_empty()).then(|| parts.join(" ")))
315}
316
317/// One element where a voice holds it: its offset in its measure and its
318/// place among the leaves of the score, which is how a spanner names it.
319#[derive(Clone, Copy, Debug)]
320struct Held<'a> {
321    offset: FloatType,
322    element: &'a StreamElement,
323    leaf: usize,
324}
325
326/// One measure of one voice, or the whole of a voice that has no measures.
327#[derive(Clone, Debug, Default)]
328struct Bar<'a> {
329    measure: Option<&'a Stream>,
330    held: Vec<Held<'a>>,
331    /// A voice its measure does not have is silent for this long.
332    filler: Option<FloatType>,
333}
334
335/// What ABC calls a voice: a part, or one voice of a part's measures.
336#[derive(Clone, Debug)]
337struct Voice<'a> {
338    part: &'a Stream,
339    bars: Vec<Bar<'a>>,
340    measured: bool,
341    /// Which voice of its part this is.
342    within: usize,
343}
344
345/// The General MIDI program of the instrument a part opens with: the first
346/// standing in it no later than its first note.
347fn program_of(part: &Stream) -> Option<u8> {
348    let leaves = part.leaves();
349    let first_note = leaves
350        .iter()
351        .filter(|(_, element)| is_sounding(element))
352        .map(|(offset, _)| *offset)
353        .fold(FloatType::INFINITY, FloatType::min);
354    leaves.iter().find_map(|(offset, element)| match element {
355        StreamElement::Instrument(instrument) if *offset <= first_note + EPSILON => {
356            instrument.midi_program()
357        }
358        _ => None,
359    })
360}
361
362fn is_sounding(element: &StreamElement) -> bool {
363    matches!(
364        element,
365        StreamElement::Note(_)
366            | StreamElement::Chord(_)
367            | StreamElement::Rest(_)
368            | StreamElement::Unpitched(_)
369            | StreamElement::PercussionChord(_)
370    )
371}
372
373fn is_grace(element: &StreamElement) -> bool {
374    is_sounding(element) && element.duration().is_some_and(Duration::is_grace)
375}
376
377/// The elements of a stream and of every stream inside it, in the order
378/// `Stream::leaves` counts them.
379fn gather<'a>(stream: &'a Stream, base: FloatType, leaf: &mut usize, out: &mut Vec<Held<'a>>) {
380    for event in stream.events() {
381        match event.element() {
382            StreamElement::Stream(inner) => gather(inner, base + event.offset(), leaf, out),
383            element => {
384                out.push(Held {
385                    offset: base + event.offset(),
386                    element,
387                    leaf: *leaf,
388                });
389                *leaf += 1;
390            }
391        }
392    }
393}
394
395fn sort_held(held: &mut [Held<'_>]) {
396    held.sort_by(|left, right| {
397        left.offset
398            .total_cmp(&right.offset)
399            .then(class_sort_order(left.element).cmp(&class_sort_order(right.element)))
400            .then(is_grace(right.element).cmp(&is_grace(left.element)))
401            .then(left.leaf.cmp(&right.leaf))
402    });
403}
404
405/// The voices a part is written as, counting its leaves on from `leaf`.
406fn voices_of<'a>(part: &'a Stream, leaf: &mut usize) -> Result<Vec<Voice<'a>>> {
407    let has_measures = part.events().iter().any(|event| {
408        event
409            .element()
410            .as_stream()
411            .is_some_and(|inner| inner.kind() == StreamKind::Measure)
412    });
413    if !has_measures {
414        let mut held = Vec::new();
415        gather(part, 0.0, leaf, &mut held);
416        return Ok(vec![Voice {
417            part,
418            bars: vec![Bar {
419                measure: None,
420                held,
421                filler: None,
422            }],
423            measured: false,
424            within: 0,
425        }]);
426    }
427
428    // Each measure as what stands in it outside any voice, and its voices.
429    type Split<'a> = (&'a Stream, Vec<Held<'a>>, Vec<Vec<Held<'a>>>);
430    let mut measures: Vec<Split<'a>> = Vec::new();
431    let mut loose: Vec<Held<'a>> = Vec::new();
432    for event in part.events() {
433        match event.element() {
434            StreamElement::Stream(measure) => {
435                let mut common = Vec::new();
436                let mut voices = Vec::new();
437                for inner in measure.events() {
438                    match inner.element() {
439                        StreamElement::Stream(voice) => {
440                            let mut held = Vec::new();
441                            gather(voice, inner.offset(), leaf, &mut held);
442                            voices.push(held);
443                        }
444                        element => {
445                            common.push(Held {
446                                offset: inner.offset(),
447                                element,
448                                leaf: *leaf,
449                            });
450                            *leaf += 1;
451                        }
452                    }
453                }
454                measures.push((measure, common, voices));
455            }
456            element => {
457                loose.push(Held {
458                    offset: event.offset(),
459                    element,
460                    leaf: *leaf,
461                });
462                *leaf += 1;
463            }
464        }
465    }
466    if loose.iter().any(|held| is_sounding(held.element)) {
467        return Err(abc_error(
468            "a part holds notes outside its measures as well as inside them",
469        ));
470    }
471
472    let count = measures
473        .iter()
474        .map(|(_, _, voices)| voices.len())
475        .max()
476        .unwrap_or(0)
477        .max(1);
478    let mut voices: Vec<Voice<'a>> = (0..count)
479        .map(|within| Voice {
480            part,
481            bars: Vec::new(),
482            measured: true,
483            within,
484        })
485        .collect();
486    for (index, (measure, common, inner)) in measures.into_iter().enumerate() {
487        let length = common
488            .iter()
489            .chain(inner.iter().flatten())
490            .map(|held| held.offset + held.element.quarter_length())
491            .fold(0.0, FloatType::max);
492        let plain_measure = inner.is_empty();
493        let mut inner = inner.into_iter();
494        for (within, voice) in voices.iter_mut().enumerate() {
495            let own = inner.next();
496            let mut held = Vec::new();
497            if within == 0 {
498                held.extend(common.iter().copied());
499                // What stands in the part before any measure is written at
500                // the head of the first.
501                if index == 0 {
502                    held.extend(loose.iter().filter(|held| held.offset < EPSILON).copied());
503                }
504            } else {
505                // The clef, key and meter standing outside the voices are
506                // every voice's: each voice of ABC states its own.
507                let shared = |held: &&Held<'a>| {
508                    matches!(
509                        held.element,
510                        StreamElement::Clef(_)
511                            | StreamElement::Key(_)
512                            | StreamElement::KeySignature(_)
513                            | StreamElement::TimeSignature(_)
514                    )
515                };
516                held.extend(common.iter().filter(shared).copied());
517                if index == 0 {
518                    held.extend(
519                        loose
520                            .iter()
521                            .filter(|held| held.offset < EPSILON)
522                            .filter(shared)
523                            .copied(),
524                    );
525                }
526            }
527            let filler = match own {
528                Some(own) => {
529                    held.extend(own);
530                    None
531                }
532                None if within == 0 && plain_measure => None,
533                None => Some(length),
534            };
535            if within > 0 || !plain_measure || index == 0 {
536                sort_held(&mut held);
537            }
538            voice.bars.push(Bar {
539                measure: Some(measure),
540                held,
541                filler,
542            });
543        }
544    }
545    Ok(voices)
546}
547
548/// The meter a measure states at its start.
549fn meter_of<'a>(bar: &Bar<'a>) -> Option<&'a TimeSignature> {
550    bar.held.iter().find_map(|held| match held.element {
551        StreamElement::TimeSignature(meter) if held.offset < EPSILON => Some(meter),
552        _ => None,
553    })
554}
555
556/// How long what a measure holds lasts.
557fn length_of(bar: &Bar<'_>) -> FloatType {
558    bar.held
559        .iter()
560        .map(|held| held.offset + held.element.quarter_length())
561        .fold(0.0, FloatType::max)
562}
563
564/// What the measure after gives the last note of a measure: the second half
565/// of a note music21 cut at the barline, written back onto the first.
566#[derive(Clone, Debug, Default)]
567struct Tail {
568    /// The length of the second half, in quarter notes.
569    extra: FloatType,
570    /// Whether the note is tied on past its second half.
571    tied: bool,
572    /// The slurs and hairpins closing on the second half.
573    closes: String,
574}
575
576/// How one measure is written where it is one of two music21 cut from one.
577#[derive(Clone, Debug, Default)]
578struct Plan {
579    /// The meter is the cut's to bring, not the text's.
580    drop_meter: bool,
581    /// The last note takes on the first of the next measure.
582    tail: Option<Tail>,
583    /// The first note is written on the measure before.
584    skip_head: bool,
585}
586
587fn first_sounding(bar: &Bar<'_>) -> Option<usize> {
588    bar.held.iter().position(|held| is_sounding(held.element))
589}
590
591fn last_sounding(bar: &Bar<'_>) -> Option<usize> {
592    bar.held
593        .iter()
594        .rposition(|held| is_sounding(held.element) && !is_grace(held.element))
595}
596
597/// The notes of a note or a chord.
598fn notes_of(element: &StreamElement) -> Option<&[Note]> {
599    match element {
600        StreamElement::Note(note) => Some(std::slice::from_ref(note)),
601        StreamElement::Chord(chord) => Some(chord.notes()),
602        _ => None,
603    }
604}
605
606/// Whether the note a measure ends with and the one the next begins with
607/// are the two halves of one, cut at the barline: the same pitches, tied
608/// from the one to the other. The answer inside is whether writing them
609/// apart would be read differently: a chord's ties are not read at all, and
610/// the second half does not show an accidental the first does.
611fn cut_note(first: &Bar<'_>, second: &Bar<'_>) -> Option<bool> {
612    let before = first.held[last_sounding(first)?];
613    let after = second.held[first_sounding(second)?];
614    if is_grace(after.element)
615        || after.offset > EPSILON
616        || (before.offset + before.element.quarter_length() - length_of(first)).abs() > EPSILON
617    {
618        return None;
619    }
620    let is_chord = matches!(before.element, StreamElement::Chord(_));
621    if is_chord != matches!(after.element, StreamElement::Chord(_)) {
622        return None;
623    }
624    let (ending, starting) = (notes_of(before.element)?, notes_of(after.element)?);
625    let said = |element: &StreamElement| {
626        element
627            .duration()
628            .and_then(Duration::said_tuplets)
629            .is_some_and(|tuplets| !tuplets.is_empty())
630    };
631    if ending.len() != starting.len() || said(before.element) || said(after.element) {
632        return None;
633    }
634    let tie = |note: &Note| note.tie().map(crate::notation::Tie::tie_type);
635    let halves = ending.iter().zip(starting).all(|(one, other)| {
636        one.pitch().name_with_octave() == other.pitch().name_with_octave()
637            && matches!(tie(one), Some(TieType::Start | TieType::Continue))
638            && matches!(tie(other), Some(TieType::Stop | TieType::Continue))
639            && other.lyrics().is_empty()
640    });
641    if !halves {
642        return None;
643    }
644    let hidden = ending.iter().zip(starting).any(|(one, other)| {
645        shows_accidental(one.pitch())
646            && other
647                .pitch()
648                .written_accidental()
649                .is_some_and(|accidental| accidental.display_status() == Some(false))
650    });
651    Some(is_chord || hidden)
652}
653
654/// What a note-like element is written from.
655struct Sounding<'a> {
656    duration: Duration,
657    /// The written length before any tuplet, in quarter notes.
658    written: FloatType,
659    /// A tuplet said on the note: so many notes in the time of so many.
660    tuplet: Option<(UnsignedIntegerType, UnsignedIntegerType)>,
661    bracket: Option<TupletType>,
662    grace: bool,
663    held: Held<'a>,
664}
665
666fn sounding_of<'a>(held: Held<'a>) -> Result<Option<Sounding<'a>>> {
667    let duration = match held.element {
668        StreamElement::Note(note) => note.duration().cloned().unwrap_or_else(Duration::quarter),
669        StreamElement::Chord(chord) => chord.duration().cloned().unwrap_or_else(Duration::quarter),
670        StreamElement::Rest(rest) => rest.duration().clone(),
671        StreamElement::Unpitched(_) | StreamElement::PercussionChord(_) => {
672            return Err(abc_error("ABC has no unpitched notes"));
673        }
674        _ => return Ok(None),
675    };
676    let grace = duration.is_grace();
677    let said = duration.said_tuplets().unwrap_or(&[]);
678    if said.len() > 1 {
679        return Err(abc_error("ABC cannot write a tuplet inside a tuplet"));
680    }
681    let (tuplet, bracket) = match said.first().filter(|_| !grace) {
682        Some(tuplet) => {
683            let multiplier = tuplet.multiplier();
684            let numerator = *multiplier.numer().unwrap_or(&0) as FloatType;
685            let denominator = *multiplier.denom().unwrap_or(&1) as FloatType;
686            let normal = FloatType::from(tuplet.actual()) * numerator / denominator;
687            if normal < 1.0 || (normal - normal.round()).abs() > EPSILON {
688                return Err(abc_error(format!(
689                    "ABC cannot write {} notes in the time of {normal}",
690                    tuplet.actual()
691                )));
692            }
693            (
694                Some((tuplet.actual(), normal.round() as UnsignedIntegerType)),
695                tuplet.tuplet_type(),
696            )
697        }
698        None => (None, None),
699    };
700    let written = if grace {
701        duration
702            .written_values()
703            .iter()
704            .filter_map(|value| {
705                Some(
706                    value
707                        .duration_type()?
708                        .quarter_length_with_dots(value.dots()),
709                )
710            })
711            .sum()
712    } else if tuplet.is_some() {
713        duration.quarter_length_no_tuplets()
714    } else {
715        duration.quarter_length()
716    };
717    Ok(Some(Sounding {
718        duration,
719        written,
720        tuplet,
721        bracket,
722        grace,
723        held,
724    }))
725}
726
727/// The marker opening a tuplet: `p` notes in the time of `q`, for the next
728/// `count` notes.
729fn tuplet_marker(actual: u32, normal: u32, count: usize) -> String {
730    let usual = match actual {
731        2 | 4 | 8 => Some(3),
732        3 | 6 => Some(2),
733        _ => None,
734    };
735    let mut marker = format!("({actual}");
736    let says_normal = usual != Some(normal);
737    if says_normal {
738        let _ = write!(marker, ":{normal}");
739    }
740    if count != actual as usize {
741        if !says_normal {
742            marker.push(':');
743        }
744        let _ = write!(marker, ":{count}");
745    }
746    marker
747}
748
749/// Where the tuplet markers of a voice go: before which note-like element,
750/// counted through the voice, and what each says.
751fn tuplet_markers(
752    tokens: &[Sounding<'_>],
753    opens_on: &dyn Fn(&Sounding<'_>) -> bool,
754) -> BTreeMap<usize, String> {
755    let mut markers = BTreeMap::new();
756    let mut index = 0;
757    while index < tokens.len() {
758        let Some((actual, normal)) = tokens[index].tuplet else {
759            index += 1;
760            continue;
761        };
762        // Grace notes before the first note are written before the marker
763        // and are none of its notes, unless a slur opens on one of them:
764        // music21 closes whichever of a slur and a tuplet it met last, so
765        // the marker then goes first, and counts them.
766        let mut start = index;
767        while start > 0 && tokens[start - 1].grace {
768            start -= 1;
769        }
770        if !tokens[start..index].iter().any(opens_on) {
771            start = index;
772        }
773        let mut last = index;
774        let mut filled = tokens[index].written;
775        loop {
776            // A marker with no count takes as many notes as it names, and
777            // fewer where they already fill the time: a quarter and an
778            // eighth are a whole triplet of eighths.
779            let whole = filled / FloatType::from(actual);
780            let filled_up = whole > 0.0 && (whole.log2() - whole.log2().round()).abs() < 1e-9;
781            let complete = last - start + 1 >= actual as usize || (filled_up && last > index);
782            if complete
783                || matches!(
784                    tokens[last].bracket,
785                    Some(TupletType::Stop | TupletType::StartStop)
786                )
787            {
788                break;
789            }
790            let mut next = last + 1;
791            while next < tokens.len() && tokens[next].grace {
792                next += 1;
793            }
794            // music21 reads one digit for the count.
795            if next >= tokens.len()
796                || tokens[next].tuplet != Some((actual, normal))
797                || matches!(
798                    tokens[next].bracket,
799                    Some(TupletType::Start | TupletType::StartStop)
800                )
801                || next - start + 1 > 9
802            {
803                break;
804            }
805            filled += tokens[next].written;
806            last = next;
807        }
808        markers.insert(start, tuplet_marker(actual, normal, last - start + 1));
809        index = last + 1;
810    }
811    markers
812}
813
814/// How a note, chord or rest is played.
815fn articulations_of(element: &StreamElement) -> &[Articulation] {
816    match element {
817        StreamElement::Note(note) => note.articulations(),
818        StreamElement::Chord(chord) => chord.articulations(),
819        StreamElement::Rest(rest) => rest.articulations(),
820        _ => &[],
821    }
822}
823
824/// Whether an articulation is written as one character, which music21
825/// reads as a token of its own.
826fn is_lettered(articulation: &Articulation) -> bool {
827    matches!(
828        articulation.kind(),
829        ArticulationKind::Staccato
830            | ArticulationKind::UpBow
831            | ArticulationKind::DownBow
832            | ArticulationKind::Accent
833            | ArticulationKind::StrongAccent
834            | ArticulationKind::Tenuto
835    )
836}
837
838/// The decoration an articulation is written as.
839fn articulation_text(articulation: &Articulation) -> Result<String> {
840    Ok(match articulation.kind() {
841        ArticulationKind::Staccato => ".".to_string(),
842        ArticulationKind::UpBow => "u".to_string(),
843        ArticulationKind::DownBow => "v".to_string(),
844        // The three letters the header gives these meanings to.
845        ArticulationKind::Accent => "K".to_string(),
846        ArticulationKind::StrongAccent => "k".to_string(),
847        ArticulationKind::Tenuto => "M".to_string(),
848        ArticulationKind::Staccatissimo => "!wedge!".to_string(),
849        ArticulationKind::BreathMark => "!breath!".to_string(),
850        ArticulationKind::OpenString => "!open!".to_string(),
851        ArticulationKind::Stopped => "!+!".to_string(),
852        ArticulationKind::SnapPizzicato => "!snap!".to_string(),
853        ArticulationKind::Fingering => match articulation.finger() {
854            Some(Finger::Number(number)) if (0..=5).contains(number) => format!("!{number}!"),
855            _ => return Err(abc_error("ABC writes fingers nought to five and no others")),
856        },
857        other => {
858            return Err(abc_error(format!(
859                "ABC has no decoration for {}",
860                other.class_name()
861            )));
862        }
863    })
864}
865
866fn expression_text(expression: &Expression) -> Result<&'static str> {
867    Ok(match expression {
868        Expression::Fermata(fermata) => match fermata.fermata_type() {
869            FermataType::Inverted => "!fermata!",
870            FermataType::Upright => "!invertedfermata!",
871            // ABC draws only these two; any other is written as the usual one.
872            _ => "!fermata!",
873        },
874        Expression::Arpeggio(ArpeggioType::Normal) => "!arpeggio!",
875        Expression::Arpeggio(_) => {
876            return Err(abc_error("ABC has one arpeggio sign, the plain one"));
877        }
878        Expression::Ornament(ornament) => match ornament.kind() {
879            OrnamentKind::Trill | OrnamentKind::HalfStepTrill | OrnamentKind::WholeStepTrill => {
880                "!trill!"
881            }
882            OrnamentKind::Mordent
883            | OrnamentKind::HalfStepMordent
884            | OrnamentKind::WholeStepMordent => "!lowermordent!",
885            OrnamentKind::InvertedMordent
886            | OrnamentKind::HalfStepInvertedMordent
887            | OrnamentKind::WholeStepInvertedMordent => "!uppermordent!",
888            OrnamentKind::Turn => "!turn!",
889            OrnamentKind::InvertedTurn => "!invertedturn!",
890            other => {
891                return Err(abc_error(format!(
892                    "ABC has no decoration for {}",
893                    other.class_name()
894                )));
895            }
896        },
897    })
898}
899
900fn decorations(articulations: &[Articulation], expressions: &[Expression]) -> Result<String> {
901    let mut text = String::new();
902    for expression in expressions {
903        text.push_str(expression_text(expression)?);
904    }
905    // The long ones first, so the single letters stand against the note.
906    let mut written = articulations
907        .iter()
908        .map(articulation_text)
909        .collect::<Result<Vec<_>>>()?;
910    written.sort_by_key(|text| std::cmp::Reverse(text.len()));
911    text.push_str(&written.concat());
912    Ok(text)
913}
914
915/// The start of a spanner as ABC opens one.
916fn spanner_open(kind: SpannerKind) -> Result<&'static str> {
917    Ok(match kind {
918        SpannerKind::Slur => "(",
919        SpannerKind::Crescendo => "!crescendo(!",
920        SpannerKind::Diminuendo => "!diminuendo(!",
921        other => {
922            return Err(abc_error(format!("ABC has no {}", other.class_name())));
923        }
924    })
925}
926
927fn spanner_close(kind: SpannerKind) -> &'static str {
928    match kind {
929        SpannerKind::Crescendo => "!crescendo)!",
930        SpannerKind::Diminuendo => "!diminuendo)!",
931        _ => ")",
932    }
933}
934
935/// What reading the tune keeps from one note to the next, across voices.
936struct Reading {
937    /// The signature music21 would read an unmarked note under here.
938    alters: Alters,
939}
940
941/// One measure as it is written: the lines of fields before and after its
942/// music, the music, and what its notes are sung to.
943#[derive(Default)]
944struct Written<'a> {
945    /// Fields standing after the barline that opens the measure.
946    opening: Vec<String>,
947    music: String,
948    /// Fields standing before the barline that closes it.
949    closing: Vec<String>,
950    /// The syllables of each note a `w:` line counts.
951    sung: Vec<&'a [Lyric]>,
952    /// Whether the music begins with a note, with nothing before it that
953    /// music21 counts as a token of its own.
954    starts_with_note: bool,
955}
956
957/// A tune: one score, its voices and what joins their notes.
958struct Tune<'a> {
959    metadata: Option<&'a Metadata>,
960    voices: Vec<Voice<'a>>,
961    /// The parts in order, each with how many voices it is written as.
962    parts: Vec<(&'a Stream, usize)>,
963    opens: BTreeMap<usize, Vec<SpannerKind>>,
964    closes: BTreeMap<usize, Vec<SpannerKind>>,
965    number: IntegerType,
966}
967
968impl<'a> Tune<'a> {
969    fn new(stream: &'a Stream, number: IntegerType) -> Result<Self> {
970        let mut leaf = 0;
971        let mut voices = Vec::new();
972        let mut parts = Vec::new();
973        let holds_parts = stream.events().iter().any(|event| {
974            event.element().as_stream().is_some_and(|inner| {
975                matches!(inner.kind(), StreamKind::Part | StreamKind::PartStaff)
976            })
977        });
978        if holds_parts {
979            for event in stream.events() {
980                match event.element() {
981                    StreamElement::Stream(part) => {
982                        let made = voices_of(part, &mut leaf)?;
983                        parts.push((part.as_ref(), made.len()));
984                        voices.extend(made);
985                    }
986                    element if is_sounding(element) => {
987                        return Err(abc_error(
988                            "a score holds notes outside its parts as well as inside them",
989                        ));
990                    }
991                    _ => leaf += 1,
992                }
993            }
994        } else if stream.kind() == StreamKind::Measure {
995            // A measure alone is a tune of that one measure.
996            let mut held = Vec::new();
997            gather(stream, 0.0, &mut leaf, &mut held);
998            parts.push((stream, 1));
999            voices.push(Voice {
1000                part: stream,
1001                bars: vec![Bar {
1002                    measure: None,
1003                    held,
1004                    filler: None,
1005                }],
1006                measured: false,
1007                within: 0,
1008            });
1009        } else {
1010            let made = voices_of(stream, &mut leaf)?;
1011            parts.push((stream, made.len()));
1012            voices.extend(made);
1013        }
1014
1015        // Where each slur and hairpin opens and closes, by leaf.
1016        let leaves = stream.leaves();
1017        let graced = |leaf: usize| {
1018            leaves
1019                .get(leaf)
1020                .is_some_and(|(_, element)| is_grace(element))
1021        };
1022        let mut opens: BTreeMap<usize, Vec<(usize, SpannerKind)>> = BTreeMap::new();
1023        let mut closes: BTreeMap<usize, Vec<(usize, SpannerKind)>> = BTreeMap::new();
1024        for spanner in stream.spanners() {
1025            spanner_open(spanner.kind())?;
1026            let spanned = spanner.spanned();
1027            let placed: Vec<usize> = spanned.iter().flatten().copied().collect();
1028            let (Some(first), Some(last)) = (placed.iter().min(), placed.iter().max()) else {
1029                continue;
1030            };
1031            // An element the score does not hold is the note a grace note
1032            // was copied from, which stood where the grace note stands.
1033            let mut start = *first;
1034            for _ in spanned.iter().take_while(|place| place.is_none()) {
1035                if start > 0 && graced(start - 1) {
1036                    start -= 1;
1037                }
1038            }
1039            let mut end = *last;
1040            for _ in spanned.iter().rev().take_while(|place| place.is_none()) {
1041                if graced(end + 1) {
1042                    end += 1;
1043                }
1044            }
1045            opens.entry(start).or_default().push((end, spanner.kind()));
1046            closes.entry(end).or_default().push((start, spanner.kind()));
1047        }
1048        // The spanner closing last opens first, and the one opened last
1049        // closes first.
1050        let ordered = |mut list: Vec<(usize, SpannerKind)>| {
1051            list.sort_by_key(|(other, _)| std::cmp::Reverse(*other));
1052            list.into_iter().map(|(_, kind)| kind).collect::<Vec<_>>()
1053        };
1054        Ok(Self {
1055            metadata: stream.metadata(),
1056            voices,
1057            parts,
1058            opens: opens
1059                .into_iter()
1060                .map(|(leaf, list)| (leaf, ordered(list)))
1061                .collect(),
1062            closes: closes
1063                .into_iter()
1064                .map(|(leaf, list)| (leaf, ordered(list)))
1065                .collect(),
1066            number,
1067        })
1068    }
1069
1070    /// The unit note length in quarter notes: the one asked for, or the
1071    /// one that leaves the least to write after the notes.
1072    fn unit(&self, options: &ExportOptions) -> Result<(FloatType, String)> {
1073        if let Some((numerator, denominator)) = options.unit_length {
1074            if numerator == 0 || denominator == 0 {
1075                return Err(abc_error("the unit note length cannot be nought"));
1076            }
1077            return Ok((
1078                4.0 * FloatType::from(numerator) / FloatType::from(denominator),
1079                format!("{numerator}/{denominator}"),
1080            ));
1081        }
1082        const UNITS: [(FloatType, &str); 6] = [
1083            (0.5, "1/8"),
1084            (1.0, "1/4"),
1085            (0.25, "1/16"),
1086            (2.0, "1/2"),
1087            (0.125, "1/32"),
1088            (4.0, "1/1"),
1089        ];
1090        // The unit that leaves the least to write after the notes.
1091        let mut written = Vec::new();
1092        for held in self
1093            .voices
1094            .iter()
1095            .flat_map(|voice| &voice.bars)
1096            .flat_map(|bar| &bar.held)
1097        {
1098            if let Some(sounding) = sounding_of(*held)? {
1099                written.push(sounding.written);
1100            }
1101        }
1102        let mut place = 0;
1103        let mut least = usize::MAX;
1104        for (index, (unit, _)) in UNITS.iter().enumerate() {
1105            let cost: usize = written
1106                .iter()
1107                .map(|length| length_text(*length, *unit).map_or(8, |text| text.len()))
1108                .sum();
1109            if cost < least {
1110                least = cost;
1111                place = index;
1112            }
1113        }
1114        Ok((UNITS[place].0, UNITS[place].1.to_string()))
1115    }
1116
1117    fn write(&self, options: &ExportOptions) -> Result<String> {
1118        let (unit, unit_text) = self.unit(options)?;
1119        let mut out = String::new();
1120        let number = self
1121            .metadata
1122            .and_then(|metadata| metadata.first_text("number"))
1123            .and_then(|text| text.trim().parse::<IntegerType>().ok())
1124            .unwrap_or(self.number);
1125        let _ = writeln!(out, "X:{number}");
1126        if let Some(metadata) = self.metadata {
1127            for (name, tag) in [
1128                ("title", 'T'),
1129                ("alternativeTitle", 'T'),
1130                ("composer", 'C'),
1131                ("localeOfComposition", 'O'),
1132            ] {
1133                for value in metadata.get(name) {
1134                    let _ = writeln!(out, "{tag}:{}", plain(value.text()));
1135                }
1136            }
1137        }
1138
1139        // The letters ABC leaves to be given a meaning, given the meanings
1140        // music21 reads them with.
1141        for (kind, field) in [
1142            (ArticulationKind::Accent, "U:K=!accent!"),
1143            (ArticulationKind::StrongAccent, "U:k=!marcato!"),
1144            (ArticulationKind::Tenuto, "U:M=!tenuto!"),
1145        ] {
1146            let used = self
1147                .voices
1148                .iter()
1149                .flat_map(|voice| &voice.bars)
1150                .flat_map(|bar| &bar.held)
1151                .flat_map(|held| articulations_of(held.element))
1152                .any(|articulation| articulation.kind() == kind);
1153            if used {
1154                let _ = writeln!(out, "{field}");
1155            }
1156        }
1157
1158        // What every voice opens with goes in the header, and what only
1159        // some do after their own `V:` line.
1160        let first = self.voices.first();
1161        let opening = |voice: &Voice<'a>| -> Opening<'a> {
1162            Opening::of(voice.bars.first().map_or(&[], |bar| bar.held.as_slice()))
1163        };
1164        let shared = first.map(opening).unwrap_or_default();
1165        let openings: Vec<Opening<'a>> = self.voices.iter().map(opening).collect();
1166        let all = |same: &dyn Fn(&Opening<'a>) -> bool| openings.iter().all(same);
1167        let shared_meter = all(&|other| other.meter == shared.meter);
1168        let shared_tempo = all(&|other| other.tempos == shared.tempos);
1169
1170        if shared_meter {
1171            let _ = writeln!(
1172                out,
1173                "M:{}",
1174                shared.meter.map_or("none".to_string(), meter_field)
1175            );
1176        }
1177        let _ = writeln!(out, "L:{unit_text}");
1178        if shared_tempo {
1179            for mark in &shared.tempos {
1180                if let Some(field) = tempo_field(mark)? {
1181                    let _ = writeln!(out, "Q:{field}");
1182                }
1183            }
1184        }
1185        let clef_of = |voice: &Voice<'a>, opening: &Opening<'a>| -> Option<&'a Clef> {
1186            let clef = opening.clef?;
1187            let pitches: Vec<Pitch> = voice
1188                .bars
1189                .iter()
1190                .flat_map(|bar| &bar.held)
1191                .flat_map(|held| match held.element {
1192                    StreamElement::ChordSymbol(symbol) => symbol.pitches().unwrap_or_default(),
1193                    element => element.pitches(),
1194                })
1195                .collect();
1196            // A clef is left unsaid only where it is treble, ABC's own
1197            // default, and fits the notes best, which is what music21's
1198            // reader takes where none is written.
1199            let unsaid = clef.kind() == crate::clef::ClefKind::TrebleClef
1200                && *clef == Clef::best_for(&pitches, false);
1201            (!unsaid).then_some(clef)
1202        };
1203        // A voice's opening clef is said on its `V:` line: music21's reader
1204        // takes a bass clef named in the header's `K:` as lowering every
1205        // note two octaves, and one on a `V:` line as the clef alone.
1206        let key_line = |opening: &Opening<'a>| -> Result<String> {
1207            match opening.key {
1208                Some(key) => key_field(key, None),
1209                None => Ok("none".to_string()),
1210            }
1211        };
1212        let voice_line =
1213            |index: usize, voice: &Voice<'a>, opening: &Opening<'a>| -> Result<String> {
1214                let mut line = format!("V:{}", index + 1);
1215                if let Some(clef) = clef_of(voice, opening) {
1216                    let _ = write!(line, " clef={}", clef_name(clef)?);
1217                }
1218                if let Some(name) = voice.part.name().filter(|_| voice.within == 0) {
1219                    let _ = write!(line, " name=\"{}\"", quoted(name));
1220                }
1221                Ok(line)
1222            };
1223        let mut reading = Reading { alters: [0; 7] };
1224        let several = self.voices.len() > 1;
1225        // A first voice stating no key leaves the key to the voices that
1226        // state one, each after its own `V:` line.
1227        let key_heads = !several || shared.key.is_some();
1228        if !key_heads {
1229        } else if first.is_some() {
1230            let _ = writeln!(out, "K:{}", key_line(&shared)?);
1231            reading.alters = shared
1232                .key
1233                .and_then(signature_of)
1234                .map_or([0; 7], |signature| alters_of(&signature));
1235        } else {
1236            let _ = writeln!(out, "K:none");
1237        }
1238
1239        if self.parts.iter().any(|(_, voices)| *voices > 1) {
1240            // Voices of one part share its staff.
1241            let mut next = 1;
1242            let groups: Vec<String> = self
1243                .parts
1244                .iter()
1245                .map(|(_, voices)| {
1246                    let ids: Vec<String> = (next..next + voices).map(|id| id.to_string()).collect();
1247                    next += voices;
1248                    if ids.len() > 1 {
1249                        format!("({})", ids.join(" "))
1250                    } else {
1251                        ids.concat()
1252                    }
1253                })
1254                .collect();
1255            let _ = writeln!(out, "%%score {}", groups.join(" "));
1256        }
1257        for (index, voice) in self.voices.iter().enumerate() {
1258            let opening = &openings[index];
1259            // A tune of one voice has a `V:` line only for a clef to say or
1260            // a part's name, which no reader takes for the part's but every
1261            // renderer draws.
1262            let line = voice_line(index, voice, opening)?;
1263            if several || line != "V:1" {
1264                let _ = writeln!(out, "{line}");
1265            }
1266            if several {
1267                if !shared_meter {
1268                    let _ = writeln!(
1269                        out,
1270                        "M:{}",
1271                        opening.meter.map_or("none".to_string(), meter_field)
1272                    );
1273                }
1274                if !shared_tempo {
1275                    for mark in &opening.tempos {
1276                        if let Some(field) = tempo_field(mark)? {
1277                            let _ = writeln!(out, "Q:{field}");
1278                        }
1279                    }
1280                }
1281                // The key is said again wherever the voice before left
1282                // another in force, or this voice opens in one of its own.
1283                let alters = opening
1284                    .key
1285                    .and_then(signature_of)
1286                    .map_or([0; 7], |signature| alters_of(&signature));
1287                let line = key_line(opening)?;
1288                let stated = opening.key.is_some();
1289                let differs = !key_heads || alters != reading.alters || line != key_line(&shared)?;
1290                if stated && differs && (index > 0 || !key_heads) {
1291                    let _ = writeln!(out, "K:{line}");
1292                }
1293                reading.alters = alters;
1294            }
1295            // The part's instrument, as abc2midi and abcjs take it: no
1296            // reader of ABC music21's or this crate's reads it back.
1297            if let Some(program) = program_of(voice.part) {
1298                let _ = writeln!(out, "%%MIDI program {program}");
1299            }
1300            self.write_voice(voice, unit, &unit_text, options, &mut reading, &mut out)?;
1301        }
1302        Ok(out)
1303    }
1304
1305    fn write_voice(
1306        &self,
1307        voice: &Voice<'a>,
1308        unit: FloatType,
1309        unit_text: &str,
1310        options: &ExportOptions,
1311        reading: &mut Reading,
1312        out: &mut String,
1313    ) -> Result<()> {
1314        // The tuplet markers, over the voice from end to end: a tuplet may
1315        // run across a barline.
1316        let mut tokens = Vec::new();
1317        let mut places = Vec::new();
1318        for (bar_index, bar) in voice.bars.iter().enumerate() {
1319            for (held_index, held) in bar.held.iter().enumerate() {
1320                if let Some(sounding) = sounding_of(*held)? {
1321                    places.push((bar_index, held_index));
1322                    tokens.push(sounding);
1323                }
1324            }
1325        }
1326        let opens_on = |sounding: &Sounding<'_>| self.opens.contains_key(&sounding.held.leaf);
1327        let markers: BTreeMap<(usize, usize), String> = tuplet_markers(&tokens, &opens_on)
1328            .into_iter()
1329            .map(|(token, marker)| (places[token], marker))
1330            .collect();
1331
1332        // Measures music21 cut in two are written as the one they were cut
1333        // from, so that it cuts them again: the barline that closed the long
1334        // measure is at the start of its second half, where no barline
1335        // written there would be read, and the meters the cut brought with
1336        // it are the cut's to bring again.
1337        let count = voice.bars.len();
1338        let mut joined = vec![false; count];
1339        let mut plans = vec![Plan::default(); count];
1340        if voice.measured {
1341            let mut meter: Option<&TimeSignature> = None;
1342            for index in 0..count {
1343                let before = meter;
1344                if let Some(own) = meter_of(&voice.bars[index]) {
1345                    meter = Some(own);
1346                }
1347                if index == 0 || joined[index - 1] {
1348                    continue;
1349                }
1350                let (first, second) = (&voice.bars[index - 1], &voice.bars[index]);
1351                let moved = second
1352                    .measure
1353                    .and_then(Stream::left_barline)
1354                    .is_some_and(|barline| {
1355                        barline.repeat_direction() != Some(RepeatDirection::Start)
1356                    });
1357                let closed = first.measure.and_then(Stream::right_barline).is_some()
1358                    || second.measure.and_then(Stream::right_barline).is_some();
1359                let bar_length = before.map(TimeSignature::bar_quarter_length);
1360                let full = bar_length.is_some_and(|bar| (length_of(first) - bar).abs() < EPSILON);
1361                // What is left of a cut measure is a whole bar or states the
1362                // meter that fits it.
1363                let remainder = meter_of(second).is_some()
1364                    || bar_length.is_some_and(|bar| (length_of(second) - bar).abs() < EPSILON);
1365                let cut = cut_note(first, second);
1366                if (moved || (cut == Some(true) && remainder))
1367                    && !closed
1368                    && full
1369                    && first.filler.is_none()
1370                    && second.filler.is_none()
1371                {
1372                    joined[index] = true;
1373                    plans[index].drop_meter = true;
1374                    if cut.is_some()
1375                        && let Some(head) = first_sounding(second)
1376                    {
1377                        let head = second.held[head];
1378                        plans[index].skip_head = true;
1379                        plans[index - 1].tail = Some(Tail {
1380                            extra: head.element.quarter_length(),
1381                            tied: notes_of(head.element).is_some_and(|notes| {
1382                                notes.iter().any(|note| {
1383                                    note.tie().map(crate::notation::Tie::tie_type)
1384                                        == Some(TieType::Continue)
1385                                })
1386                            }),
1387                            closes: self
1388                                .closes
1389                                .get(&head.leaf)
1390                                .map_or(&[][..], Vec::as_slice)
1391                                .iter()
1392                                .map(|kind| spanner_close(*kind))
1393                                .collect(),
1394                        });
1395                    }
1396                    // The measure after is given the old meter back.
1397                    if let (Some(next), Some(old)) = (voice.bars.get(index + 1), before)
1398                        && meter_of(next)
1399                            .is_some_and(|given| given.ratio_string() == old.ratio_string())
1400                    {
1401                        plans[index + 1].drop_meter = true;
1402                    }
1403                    meter = before;
1404                }
1405            }
1406        }
1407
1408        let mut written = Vec::new();
1409        for (index, bar) in voice.bars.iter().enumerate() {
1410            written.push(self.write_bar(
1411                voice,
1412                index,
1413                bar,
1414                unit,
1415                unit_text,
1416                &markers,
1417                reading,
1418                &plans[index],
1419            )?);
1420        }
1421        // The barline after each measure, with the ending the next opens.
1422        let barline_after = |index: usize| -> (String, bool) {
1423            if !voice.measured {
1424                return (String::new(), false);
1425            }
1426            let bar = &voice.bars[index];
1427            let right = if joined[index] {
1428                bar.measure.and_then(Stream::left_barline)
1429            } else {
1430                bar.measure.and_then(Stream::right_barline)
1431            };
1432            let next = voice.bars.get(index + 1).and_then(|bar| bar.measure);
1433            // After the last measure there is nothing to keep a barline off.
1434            let field_can_follow = written
1435                .get(index + 1)
1436                .is_none_or(|next| next.opening.is_empty() && next.starts_with_note);
1437            barline_text(
1438                right,
1439                next.and_then(Stream::left_barline),
1440                next.and_then(Stream::ending),
1441                false,
1442                field_can_follow,
1443            )
1444        };
1445
1446        let has_lyrics = written
1447            .iter()
1448            .any(|bar| bar.sung.iter().any(|lyrics| !lyrics.is_empty()));
1449        let per_line = options.measures_per_line.max(1);
1450        let last = written.len().saturating_sub(1);
1451        let mut line = String::new();
1452        let mut on_line = 0;
1453        let mut sung: Vec<&[Lyric]> = Vec::new();
1454        if voice.measured {
1455            let first = voice.bars.first().and_then(|bar| bar.measure);
1456            line.push_str(
1457                &barline_text(
1458                    None,
1459                    first.and_then(Stream::left_barline),
1460                    first.and_then(Stream::ending),
1461                    true,
1462                    false,
1463                )
1464                .0,
1465            );
1466        }
1467        for (index, bar) in written.iter().enumerate() {
1468            if !line.is_empty() && !line.ends_with(' ') && !bar.music.is_empty() {
1469                line.push(' ');
1470            }
1471            line.push_str(&bar.music);
1472            sung.extend(bar.sung.iter().copied());
1473            if joined.get(index + 1) == Some(&true) {
1474                continue;
1475            }
1476            on_line += 1;
1477            let next = written.get(index + 1);
1478            let (barline, keep_off) = barline_after(index);
1479            // The fields the next measure opens with. A barline that is not
1480            // the next measure's to take is kept off it by a field between
1481            // them, which music21 passes over: the unit note length again.
1482            let said_again = [format!("L:{unit_text}")];
1483            let opening: &[String] = match next {
1484                Some(next) if !next.opening.is_empty() => &next.opening,
1485                Some(_) if keep_off => &said_again,
1486                _ => &[],
1487            };
1488            let fields_follow = !opening.is_empty();
1489            // A word is not broken across lines of words.
1490            let mid_word = sung
1491                .iter()
1492                .rev()
1493                .find_map(|lyrics| lyrics.first())
1494                .is_some_and(|lyric| lyric.raw_text().ends_with('-'));
1495            let breaks = index == last
1496                || !bar.closing.is_empty()
1497                || fields_follow
1498                || (on_line >= per_line && !(has_lyrics && mid_word));
1499            if !breaks {
1500                if !barline.is_empty() {
1501                    let _ = write!(line, " {barline}");
1502                }
1503                continue;
1504            }
1505            let words = if has_lyrics {
1506                lyric_lines(&sung)
1507            } else {
1508                Vec::new()
1509            };
1510            sung.clear();
1511            on_line = 0;
1512            // Words and fields stand before the barline: after it and before
1513            // a note, music21 passes a field over.
1514            let before_bar = index != last && !words.is_empty() || !bar.closing.is_empty();
1515            if !before_bar && !barline.is_empty() {
1516                let _ = write!(line, " {barline}");
1517            }
1518            push_line(out, &line);
1519            line.clear();
1520            for words in words {
1521                let _ = writeln!(out, "w:{words}");
1522            }
1523            for field in &bar.closing {
1524                let _ = writeln!(out, "{field}");
1525            }
1526            if before_bar {
1527                line.push_str(&barline);
1528            }
1529            if !opening.is_empty() {
1530                push_line(out, &line);
1531                line.clear();
1532                for field in opening {
1533                    let _ = writeln!(out, "{field}");
1534                }
1535            }
1536        }
1537        push_line(out, &line);
1538        Ok(())
1539    }
1540
1541    #[allow(clippy::too_many_arguments)]
1542    fn write_bar(
1543        &self,
1544        voice: &Voice<'a>,
1545        index: usize,
1546        bar: &Bar<'a>,
1547        unit: FloatType,
1548        unit_text: &str,
1549        markers: &BTreeMap<(usize, usize), String>,
1550        reading: &mut Reading,
1551        plan: &Plan,
1552    ) -> Result<Written<'a>> {
1553        let mut written = Written::default();
1554        if let Some(length) = bar.filler {
1555            if length > EPSILON {
1556                written.music = format!("x{}", length_text(length, unit)?);
1557            }
1558            return Ok(written);
1559        }
1560        let end = bar
1561            .held
1562            .iter()
1563            .map(|held| held.offset + held.element.quarter_length())
1564            .fold(0.0, FloatType::max);
1565        let first = index == 0;
1566        let skipped = first_sounding(bar).filter(|_| plan.skip_head);
1567        let tailed = last_sounding(bar).filter(|_| plan.tail.is_some());
1568
1569        // How the key is said, where the measure states one: after the
1570        // barline, where the measure's own notes are read under it, or
1571        // before the barline closing it, where they are read under the old.
1572        let stated = bar
1573            .held
1574            .iter()
1575            .find(|held| held.offset < EPSILON && signature_of(held.element).is_some());
1576        let mut key_closes = false;
1577        let mut silent_key = None;
1578        if voice.measured && !first {
1579            let unmarked = unmarked_notes(bar, skipped);
1580            let fits = |alters: &Alters| {
1581                unmarked
1582                    .iter()
1583                    .all(|(letter, alter)| alters[*letter] == *alter)
1584            };
1585            match stated.and_then(|held| signature_of(held.element)) {
1586                Some(signature) => {
1587                    let alters = alters_of(&signature);
1588                    if !fits(&alters) && fits(&reading.alters) {
1589                        key_closes = true;
1590                    } else {
1591                        reading.alters = alters;
1592                    }
1593                }
1594                None if !fits(&reading.alters) => {
1595                    // The notes were read under a key the measure does not
1596                    // state: one said alone after a barline, which music21
1597                    // reads the notes under and then passes over.
1598                    let in_force = self.key_in_force(voice, index);
1599                    let candidates = in_force.into_iter().chain((-7..=7).map(KeySignature::new));
1600                    silent_key = candidates
1601                        .map(|signature| (alters_of(&signature), signature))
1602                        .find(|(alters, _)| fits(alters));
1603                }
1604                None => {}
1605            }
1606        }
1607
1608        // The fields the measure opens with. Those of the first measure are
1609        // in the header.
1610        let mut opening_clef = None;
1611        for held in &bar.held {
1612            if held.offset > EPSILON || first || !voice.measured {
1613                continue;
1614            }
1615            match held.element {
1616                StreamElement::TimeSignature(meter) if !plan.drop_meter => {
1617                    written.opening.push(format!("M:{}", meter_field(meter)));
1618                }
1619                StreamElement::MetronomeMark(mark) if end > EPSILON => {
1620                    if let Some(field) = tempo_field(mark)? {
1621                        written.opening.push(format!("Q:{field}"));
1622                    }
1623                }
1624                StreamElement::Clef(clef) => opening_clef = Some(clef),
1625                StreamElement::Key(_) | StreamElement::KeySignature(_) => {
1626                    let field = format!("K:{}", key_field(held.element, None)?);
1627                    if key_closes {
1628                        written.closing.push(field);
1629                    } else {
1630                        written.opening.push(field);
1631                    }
1632                }
1633                _ => {}
1634            }
1635        }
1636
1637        let mut music = Vec::new();
1638        let mut cursor = 0.0;
1639        // What waits for the next note: the chord symbol and the words and
1640        // signs written before it, and the grace notes leaning on it.
1641        let mut symbol: Option<String> = None;
1642        let mut before = String::new();
1643        let mut waiting_since: Option<FloatType> = None;
1644        let mut graces = String::new();
1645        let mut grace_slash = false;
1646        let mut grace_closes = String::new();
1647        let mut lead = String::new();
1648        let mut first_token = true;
1649        if let Some(clef) = opening_clef {
1650            lead.push_str(&format!("[K:clef={}]", clef_name(clef)?));
1651        }
1652
1653        for (held_index, held) in bar.held.iter().enumerate() {
1654            let at_start = held.offset < EPSILON;
1655            let header = at_start && (first || voice.measured);
1656            match held.element {
1657                StreamElement::Stream(_)
1658                | StreamElement::Instrument(_)
1659                | StreamElement::Variant(_)
1660                | StreamElement::GlobalComment(_)
1661                | StreamElement::MiscTandem(_)
1662                | StreamElement::SpineComment(_)
1663                | StreamElement::BrailleSegmentDivision(_) => {}
1664                StreamElement::Clef(clef) => {
1665                    if !header {
1666                        lead.push_str(&format!("[K:clef={}]", clef_name(clef)?));
1667                    }
1668                }
1669                StreamElement::TimeSignature(meter) => {
1670                    if !header {
1671                        self.field(
1672                            voice,
1673                            &mut music,
1674                            &mut lead,
1675                            format!("M:{}", meter_field(meter)),
1676                        );
1677                    }
1678                }
1679                StreamElement::Key(_) | StreamElement::KeySignature(_) => {
1680                    if !header {
1681                        let field = format!("K:{}", key_field(held.element, None)?);
1682                        self.field(voice, &mut music, &mut lead, field);
1683                        if !voice.measured
1684                            && let Some(signature) = signature_of(held.element)
1685                        {
1686                            reading.alters = alters_of(&signature);
1687                        }
1688                    }
1689                }
1690                StreamElement::MetronomeMark(mark) => {
1691                    let Some(field) = tempo_field(mark)? else {
1692                        continue;
1693                    };
1694                    if header && (first || end > EPSILON) {
1695                        // In the header, or among the measure's opening
1696                        // fields.
1697                    } else if voice.measured && (held.offset - end).abs() < EPSILON {
1698                        written.closing.push(format!("Q:{field}"));
1699                    } else {
1700                        self.field(voice, &mut music, &mut lead, format!("Q:{field}"));
1701                    }
1702                }
1703                StreamElement::TempoText(text) => {
1704                    let field = format!("Q:\"{}\"", quoted(text.text()));
1705                    self.field(voice, &mut music, &mut lead, field);
1706                }
1707                StreamElement::ChordSymbol(chord_symbol) => {
1708                    if symbol.is_some() {
1709                        return Err(abc_error("ABC writes one chord symbol on a note"));
1710                    }
1711                    symbol = Some(format!("\"{}\"", symbol_text(chord_symbol)));
1712                    waiting_since.get_or_insert(held.offset);
1713                }
1714                StreamElement::Dynamic(dynamic) => {
1715                    let value = dynamic.value();
1716                    if value.is_empty() || !value.chars().all(|c| c.is_ascii_alphabetic()) {
1717                        return Err(abc_error(format!("ABC has no dynamic {value:?}")));
1718                    }
1719                    let _ = write!(before, "!{value}!");
1720                    waiting_since.get_or_insert(held.offset);
1721                }
1722                StreamElement::TextExpression(expression) => {
1723                    let side = if expression.placement() == Some(Placement::Below) {
1724                        '_'
1725                    } else {
1726                        '^'
1727                    };
1728                    let _ = write!(before, "\"{side}{}\"", quoted(expression.content()));
1729                    waiting_since.get_or_insert(held.offset);
1730                }
1731                StreamElement::RepeatExpression(mark) => {
1732                    let sign = match mark.kind() {
1733                        RepeatExpressionKind::Coda => "!coda!".to_string(),
1734                        RepeatExpressionKind::Segno => "!segno!".to_string(),
1735                        RepeatExpressionKind::Fine => "!fine!".to_string(),
1736                        RepeatExpressionKind::DaCapo => "!D.C.!".to_string(),
1737                        RepeatExpressionKind::DalSegno => "!D.S.!".to_string(),
1738                        _ => format!("\"^{}\"", quoted(mark.text())),
1739                    };
1740                    before.push_str(&sign);
1741                    waiting_since.get_or_insert(held.offset);
1742                }
1743                // A barline inside a measure is drawn and not heard, and
1744                // music21's exporters write nothing for one either.
1745                // How the page is laid out is not the tune's to say.
1746                StreamElement::Barline(_)
1747                | StreamElement::Layout(_)
1748                | StreamElement::TextBox(_) => {}
1749                StreamElement::PedalObject(_) => {
1750                    return Err(abc_error("ABC has no pedal bounces or gaps"));
1751                }
1752                StreamElement::RehearsalMark(_) => {
1753                    return Err(abc_error("ABC has no rehearsal marks"));
1754                }
1755                StreamElement::Break(_) => {
1756                    return Err(abc_error(
1757                        "ABC writes no manuscript's line, page or column breaks",
1758                    ));
1759                }
1760                StreamElement::MetricModulation(_) => {
1761                    return Err(abc_error("ABC has no metric modulations"));
1762                }
1763                StreamElement::Unpitched(_) | StreamElement::PercussionChord(_) => {
1764                    return Err(abc_error("ABC has no unpitched notes"));
1765                }
1766                StreamElement::Note(_) | StreamElement::Chord(_) | StreamElement::Rest(_) => {
1767                    if skipped == Some(held_index) {
1768                        cursor = held.offset + held.element.quarter_length();
1769                        continue;
1770                    }
1771                    let tail = plan.tail.as_ref().filter(|_| tailed == Some(held_index));
1772                    let sounding = sounding_of(*held)?
1773                        .ok_or_else(|| abc_error("a note with nothing to write it from"))?;
1774                    let opens = self.opens.get(&held.leaf).map_or(&[][..], Vec::as_slice);
1775                    let closes: String = self
1776                        .closes
1777                        .get(&held.leaf)
1778                        .map_or(&[][..], Vec::as_slice)
1779                        .iter()
1780                        .map(|kind| spanner_close(*kind))
1781                        .collect();
1782                    let marker = markers.get(&(index, held_index));
1783                    if marker.is_some() || !opens.is_empty() {
1784                        first_token = false;
1785                    }
1786                    let mut opening = String::new();
1787                    for kind in opens {
1788                        opening.push_str(spanner_open(*kind)?);
1789                    }
1790                    if sounding.grace {
1791                        if graces.is_empty() {
1792                            lead.push_str(marker.map_or("", String::as_str));
1793                            lead.push_str(&opening);
1794                            grace_slash = sounding
1795                                .duration
1796                                .grace()
1797                                .is_some_and(crate::duration::Grace::slash);
1798                        } else if marker.is_some() || !opening.is_empty() {
1799                            // A slur opened on a later grace note is opened
1800                            // before the group.
1801                            lead.push_str(&opening);
1802                        }
1803                        graces.push_str(&self.note_text(&sounding, unit, &reading.alters, None)?);
1804                        grace_closes.push_str(&closes);
1805                        first_token = false;
1806                        continue;
1807                    }
1808
1809                    // A rest for time nothing fills.
1810                    if held.offset > cursor + EPSILON {
1811                        music.push(format!("x{}", length_text(held.offset - cursor, unit)?));
1812                        first_token = false;
1813                    } else if held.offset < cursor - EPSILON {
1814                        return Err(abc_error(
1815                            "notes sound together outside a chord; ABC writes one line to a voice",
1816                        ));
1817                    }
1818                    if waiting_since.is_some_and(|since| since < held.offset - EPSILON) {
1819                        return Err(abc_error(
1820                            "a chord symbol, dynamic or text stands where no note starts",
1821                        ));
1822                    }
1823                    waiting_since = None;
1824
1825                    let mut token = std::mem::take(&mut lead);
1826                    if !graces.is_empty() {
1827                        let _ = write!(
1828                            token,
1829                            "{{{}{}}}{}",
1830                            if grace_slash { "/" } else { "" },
1831                            std::mem::take(&mut graces),
1832                            std::mem::take(&mut grace_closes)
1833                        );
1834                        token.push_str(marker.map_or("", String::as_str));
1835                    } else if let Some(marker) = marker {
1836                        token.push_str(marker);
1837                    }
1838                    token.push_str(&opening);
1839                    if first_token
1840                        && token.is_empty()
1841                        && !articulations_of(held.element).iter().any(is_lettered)
1842                    {
1843                        written.starts_with_note = true;
1844                    }
1845                    first_token = false;
1846                    token.push_str(symbol.take().as_deref().unwrap_or(""));
1847                    token.push_str(&std::mem::take(&mut before));
1848                    token.push_str(&self.note_text(&sounding, unit, &reading.alters, tail)?);
1849                    token.push_str(&closes);
1850                    token.push_str(tail.map_or("", |tail| tail.closes.as_str()));
1851                    music.push(token);
1852                    cursor = held.offset + held.element.quarter_length();
1853
1854                    match held.element {
1855                        StreamElement::Note(note) => written.sung.push(note.lyrics()),
1856                        StreamElement::Chord(chord) => written.sung.push(chord.lyrics()),
1857                        _ => {}
1858                    }
1859                    // Notes under one beam are written without a space.
1860                    let beams = match held.element {
1861                        StreamElement::Note(note) => Some(note.beams()),
1862                        StreamElement::Chord(chord) => Some(chord.beams()),
1863                        _ => None,
1864                    };
1865                    if !beams.is_some_and(beamed_on) {
1866                        music.push(" ".to_string());
1867                    }
1868                }
1869            }
1870        }
1871        if symbol.is_some() || !before.is_empty() {
1872            return Err(abc_error(
1873                "a chord symbol, dynamic or text stands where no note starts",
1874            ));
1875        }
1876        // Grace notes with no note after them, and whatever else waited.
1877        if !graces.is_empty() {
1878            lead.push_str(&format!(
1879                "{{{}{graces}}}{grace_closes}",
1880                if grace_slash { "/" } else { "" }
1881            ));
1882        }
1883        if !lead.is_empty() {
1884            music.push(lead);
1885        }
1886        written.music = music.concat().trim().to_string();
1887        if written.music.is_empty() && voice.measured {
1888            // A measure of nothing is a space.
1889            written.music = "y".to_string();
1890        }
1891
1892        // One field alone after a barline and before a note is passed over
1893        // by music21; with the unit note length said again after it, it and
1894        // the measure are read together.
1895        if let Some((alters, signature)) =
1896            silent_key.filter(|_| written.opening.is_empty() && written.starts_with_note)
1897        {
1898            {
1899                written
1900                    .opening
1901                    .push(format!("K:{}", key_field(&signature.into(), None)?));
1902                reading.alters = alters;
1903                // The notes were written before the key was known to be
1904                // readable under; write them again.
1905                let again =
1906                    self.write_bar(voice, index, bar, unit, unit_text, markers, reading, plan)?;
1907                written.music = again.music;
1908            }
1909        } else if written.opening.len() == 1 {
1910            written.opening.push(format!("L:{unit_text}"));
1911        }
1912        if key_closes && let Some(signature) = stated.and_then(|held| signature_of(held.element)) {
1913            reading.alters = alters_of(&signature);
1914        }
1915        Ok(written)
1916    }
1917
1918    /// A field in the middle of the music: on a line of its own where the
1919    /// voice has no measures, in brackets where it has.
1920    fn field(&self, voice: &Voice<'a>, music: &mut Vec<String>, lead: &mut String, field: String) {
1921        if voice.measured {
1922            let _ = write!(lead, "[{field}]");
1923        } else {
1924            music.push(format!("\n{field}\n"));
1925        }
1926    }
1927
1928    /// The key signature in force at a measure of a voice.
1929    fn key_in_force(&self, voice: &Voice<'a>, index: usize) -> Option<KeySignature> {
1930        voice.bars[..=index]
1931            .iter()
1932            .rev()
1933            .flat_map(|bar| bar.held.iter().rev())
1934            .find_map(|held| signature_of(held.element))
1935    }
1936
1937    /// A note, chord or rest with its length, its decorations before it and
1938    /// its tie after it.
1939    fn note_text(
1940        &self,
1941        sounding: &Sounding<'a>,
1942        unit: FloatType,
1943        alters: &Alters,
1944        tail: Option<&Tail>,
1945    ) -> Result<String> {
1946        let length = length_text(sounding.written + tail.map_or(0.0, |tail| tail.extra), unit)?;
1947        let tied = |note: &Note| match tail {
1948            Some(tail) => tail.tied,
1949            None => matches!(
1950                note.tie().map(crate::notation::Tie::tie_type),
1951                Some(TieType::Start | TieType::Continue)
1952            ),
1953        };
1954        Ok(match sounding.held.element {
1955            StreamElement::Note(note) => {
1956                // A grace note carries its own decorations, inside the
1957                // braces: `{vfga}` bows the first grace note down.
1958                let marks = decorations(note.articulations(), note.expressions())?;
1959                format!(
1960                    "{marks}{}{length}{}",
1961                    pitch_text(note.pitch(), alters)?,
1962                    if tied(note) { "-" } else { "" }
1963                )
1964            }
1965            StreamElement::Chord(chord) => chord_text(chord, alters, &length, tied)?,
1966            StreamElement::Rest(rest) => rest_text(rest, &length)?,
1967            _ => String::new(),
1968        })
1969    }
1970}
1971
1972/// What a voice's first measure opens with.
1973#[derive(Clone, Default)]
1974struct Opening<'a> {
1975    meter: Option<&'a TimeSignature>,
1976    key: Option<&'a StreamElement>,
1977    clef: Option<&'a Clef>,
1978    tempos: Vec<&'a MetronomeMark>,
1979}
1980
1981impl<'a> Opening<'a> {
1982    fn of(held: &[Held<'a>]) -> Self {
1983        let mut opening = Self::default();
1984        for held in held.iter().filter(|held| held.offset < EPSILON) {
1985            match held.element {
1986                StreamElement::TimeSignature(meter) => opening.meter = Some(meter),
1987                StreamElement::Key(_) | StreamElement::KeySignature(_) => {
1988                    opening.key = Some(held.element);
1989                }
1990                StreamElement::Clef(clef) => opening.clef = Some(clef),
1991                StreamElement::MetronomeMark(mark) => opening.tempos.push(mark),
1992                _ => {}
1993            }
1994        }
1995        opening
1996    }
1997}
1998
1999/// Whether a note is beamed to the one after it.
2000fn beamed_on(beams: &Beams) -> bool {
2001    matches!(
2002        beams
2003            .beams()
2004            .first()
2005            .and_then(crate::notation::Beam::beam_type),
2006        Some(BeamType::Start | BeamType::Continue)
2007    )
2008}
2009
2010/// The notes of a measure music21 would read with no accidental written:
2011/// each letter and how far it is moved.
2012fn unmarked_notes(bar: &Bar<'_>, skipped: Option<usize>) -> Vec<(usize, IntegerType)> {
2013    let mut notes = Vec::new();
2014    let mut take = |pitch: &Pitch| {
2015        if !shows_accidental(pitch) {
2016            notes.push((
2017                letter_index(pitch.step().as_char()),
2018                pitch.alter().round() as IntegerType,
2019            ));
2020        }
2021    };
2022    for (index, held) in bar.held.iter().enumerate() {
2023        if skipped == Some(index) {
2024            continue;
2025        }
2026        match held.element {
2027            StreamElement::Note(note) => take(note.pitch()),
2028            StreamElement::Chord(chord) => {
2029                chord.notes().iter().map(Note::pitch).for_each(&mut take)
2030            }
2031            _ => {}
2032        }
2033    }
2034    notes
2035}
2036
2037/// Whether a pitch carries an accidental that is to be seen.
2038fn shows_accidental(pitch: &Pitch) -> bool {
2039    pitch
2040        .written_accidental()
2041        .is_some_and(|accidental| accidental.display_status() != Some(false))
2042}
2043
2044/// A pitch as ABC writes one: an accidental where it shows one or the key
2045/// in force would give it another, the letter, and the octave.
2046fn pitch_text(pitch: &Pitch, alters: &Alters) -> Result<String> {
2047    if pitch
2048        .microtone()
2049        .is_some_and(|microtone| microtone.alter() != 0.0)
2050    {
2051        return Err(abc_error("ABC has no microtones"));
2052    }
2053    let alter = pitch.alter();
2054    if alter.fract() != 0.0 {
2055        return Err(abc_error("ABC has no quarter-tone accidentals"));
2056    }
2057    let alter = alter as IntegerType;
2058    let letter = pitch.step().as_char();
2059    let marks = if shows_accidental(pitch) || alters[letter_index(letter)] != alter {
2060        accidental_marks(alter)?
2061    } else {
2062        ""
2063    };
2064    let octave = pitch.octave().unwrap_or(4);
2065    Ok(if octave >= 5 {
2066        format!(
2067            "{marks}{}{}",
2068            letter.to_ascii_lowercase(),
2069            "'".repeat((octave - 5) as usize)
2070        )
2071    } else {
2072        format!("{marks}{letter}{}", ",".repeat((4 - octave) as usize))
2073    })
2074}
2075
2076fn chord_text(
2077    chord: &Chord,
2078    alters: &Alters,
2079    length: &str,
2080    tied: impl Fn(&Note) -> bool,
2081) -> Result<String> {
2082    let mut text = decorations(chord.articulations(), chord.expressions())?;
2083    text.push('[');
2084    for note in chord.notes() {
2085        text.push_str(&pitch_text(note.pitch(), alters)?);
2086        // A tie written after the chord would be read onto the next note.
2087        if tied(note) {
2088            text.push('-');
2089        }
2090    }
2091    text.push(']');
2092    text.push_str(length);
2093    Ok(text)
2094}
2095
2096fn rest_text(rest: &Rest, length: &str) -> Result<String> {
2097    let marks = decorations(rest.articulations(), rest.expressions())?;
2098    let tied = matches!(
2099        rest.tie().map(crate::notation::Tie::tie_type),
2100        Some(TieType::Start | TieType::Continue)
2101    );
2102    Ok(format!(
2103        "{marks}{}{length}{}",
2104        if rest.hidden() { 'x' } else { 'z' },
2105        if tied { "-" } else { "" }
2106    ))
2107}
2108
2109/// A chord symbol as it is written between quotation marks: a flat as `b`.
2110fn symbol_text(symbol: &ChordSymbol) -> String {
2111    if symbol.is_no_chord() {
2112        return quoted(symbol.kind_text().unwrap_or("N.C."));
2113    }
2114    let figure: Vec<char> = symbol.figure().chars().collect();
2115    let mut text = String::new();
2116    for (index, character) in figure.iter().enumerate() {
2117        let after_letter = index > 0 && matches!(figure[index - 1], 'A'..='G');
2118        text.push(if *character == '-' && after_letter {
2119            'b'
2120        } else {
2121            *character
2122        });
2123    }
2124    quoted(&text)
2125}
2126
2127/// The barline between two measures, or before the first or after the last,
2128/// with the ending the second opens: from the barline closing the one and
2129/// the barline and ending opening the other. The second answer is whether
2130/// the measure after must be kept from taking the barline as its own.
2131///
2132/// One barline written is read as closing the measure before it and opening
2133/// the one after, unless it is a repeat, which is read on its own side only.
2134/// Two different ones are written one after the other.
2135fn barline_text(
2136    right: Option<&Barline>,
2137    left: Option<&Barline>,
2138    ending: Option<&Ending>,
2139    opens_tune: bool,
2140    field_can_follow: bool,
2141) -> (String, bool) {
2142    let token = |barline: Option<&Barline>| -> Option<&'static str> {
2143        let barline = barline?;
2144        match barline.repeat_direction() {
2145            Some(RepeatDirection::End) => Some(":|"),
2146            Some(RepeatDirection::Start) => Some("|:"),
2147            None => match barline.bar_type() {
2148                BarlineType::Double => Some("||"),
2149                BarlineType::Final => Some("|]"),
2150                BarlineType::HeavyLight => Some("[|"),
2151                BarlineType::Dotted | BarlineType::Dashed => Some(":"),
2152                _ => None,
2153            },
2154        }
2155    };
2156    let repeats = |barline: Option<&Barline>| {
2157        barline.is_some_and(|barline| barline.repeat_direction().is_some())
2158    };
2159    let ending = ending.filter(|ending| ending.starts() && !ending.numbers().is_empty());
2160    let mut keep_off = false;
2161    let mut text = match (token(right), token(left)) {
2162        (Some(":|"), Some("|:")) => "::".to_string(),
2163        (Some(closing), Some(opening)) if closing == opening => closing.to_string(),
2164        // A dotted barline before another would be read with it as a repeat.
2165        (Some(":"), Some(opening)) => format!(": {opening}"),
2166        (Some(closing), Some(opening)) => format!("{closing}{opening}"),
2167        (Some(closing), None) if repeats(right) || opens_tune => closing.to_string(),
2168        // A barline that is not a repeat is read as the next measure's too.
2169        // A field after it keeps it off, and so does a plain barline.
2170        (Some(closing), None) if field_can_follow && ending.is_none() => {
2171            keep_off = true;
2172            closing.to_string()
2173        }
2174        (Some(closing), None) => format!("{closing} |"),
2175        (None, Some(opening)) if opens_tune || repeats(left) => opening.to_string(),
2176        // The plain barline closes the measure before and the other opens
2177        // the one after.
2178        (None, Some(opening)) => format!("| {opening}"),
2179        // Nothing is written before the first measure but what it opens
2180        // with.
2181        (None, None) if opens_tune => String::new(),
2182        (None, None) => "|".to_string(),
2183    };
2184    if let Some(ending) = ending {
2185        let numbers = ending
2186            .numbers()
2187            .iter()
2188            .map(u32::to_string)
2189            .collect::<Vec<_>>()
2190            .join(",");
2191        if !numbers.is_empty() {
2192            // `|1` and `:|2` are the forms music21 reads; after any other
2193            // barline the ending is opened by its bracket.
2194            if matches!(text.as_str(), "|" | ":|") && matches!(numbers.as_str(), "1" | "2") {
2195                text.push_str(&numbers);
2196            } else if matches!(numbers.as_str(), "1" | "2") {
2197                let _ = write!(text, "[{numbers}");
2198            } else if text.is_empty() {
2199                let _ = write!(text, "|{numbers}");
2200            } else {
2201                text.push_str(&numbers);
2202            }
2203        }
2204    }
2205    (text, keep_off)
2206}
2207
2208/// The `w:` lines for the notes of one line of music, a line for each verse.
2209fn lyric_lines(sung: &[&[Lyric]]) -> Vec<String> {
2210    let mut numbers: Vec<IntegerType> = sung
2211        .iter()
2212        .flat_map(|lyrics| lyrics.iter().map(Lyric::number))
2213        .collect();
2214    numbers.sort_unstable();
2215    numbers.dedup();
2216    if numbers.is_empty() {
2217        // Notes with no words still take their place, so the next line of
2218        // words starts at its own notes.
2219        numbers.push(1);
2220    }
2221    numbers
2222        .into_iter()
2223        .map(|number| {
2224            let mut words: Vec<String> = Vec::new();
2225            // The syllables of the word being written, a skipped note an
2226            // empty one.
2227            let mut word: Option<Vec<String>> = None;
2228            for lyrics in sung {
2229                let lyric = lyrics.iter().find(|lyric| lyric.number() == number);
2230                match lyric {
2231                    None => match &mut word {
2232                        Some(syllables) => syllables.push(String::new()),
2233                        None => words.push("*".to_string()),
2234                    },
2235                    Some(lyric) => {
2236                        let raw = lyric.raw_text();
2237                        let continues = raw.len() > 1 && raw.ends_with('-');
2238                        let syllable = lyric.text().replace(' ', "~").replace('-', "\\-");
2239                        let syllable = if syllable.is_empty() {
2240                            "*".to_string()
2241                        } else {
2242                            syllable
2243                        };
2244                        let joins = raw.len() > 1 && raw.starts_with('-');
2245                        match &mut word {
2246                            Some(syllables) if joins => syllables.push(syllable),
2247                            _ => {
2248                                if let Some(syllables) = word.take() {
2249                                    words.push(syllables.join("-"));
2250                                }
2251                                word = Some(vec![syllable]);
2252                            }
2253                        }
2254                        if !continues && let Some(syllables) = word.take() {
2255                            words.push(syllables.join("-"));
2256                        }
2257                    }
2258                }
2259            }
2260            if let Some(mut syllables) = word.take() {
2261                // A word left open says so with the hyphen after it.
2262                syllables.push(String::new());
2263                while syllables.len() > 2 && syllables[syllables.len() - 2].is_empty() {
2264                    syllables.pop();
2265                }
2266                words.push(syllables.join("-"));
2267            }
2268            words.join(" ")
2269        })
2270        .collect()
2271}
2272
2273fn push_line(out: &mut String, line: &str) {
2274    // A field in the middle of a voice with no measures brings its own
2275    // line breaks.
2276    for piece in line.split('\n') {
2277        let piece = piece.trim();
2278        if !piece.is_empty() {
2279            out.push_str(piece);
2280            out.push('\n');
2281        }
2282    }
2283}
2284
2285#[cfg(test)]
2286mod tests {
2287    use super::*;
2288    use crate::abc::from_abc;
2289
2290    /// What a tune is written as, having checked that it reads back as the
2291    /// score it was written from.
2292    fn round_trip(tune: &str) -> String {
2293        let score = from_abc(tune).unwrap();
2294        let written = to_abc(&score, &ExportOptions::default()).unwrap();
2295        assert_eq!(
2296            format!("{:#?}", from_abc(&written).unwrap()),
2297            format!("{score:#?}"),
2298            "read back differently:\n{written}"
2299        );
2300        written
2301    }
2302
2303    #[test]
2304    fn a_tune_is_written_with_its_header() {
2305        let written = round_trip(
2306            "X:7\nT:Tune\nT:Other\nC:Anon\nO:Here\nM:6/8\nL:1/8\nQ:3/8=120\nK:Ador\nABc def|gfe dcB|A6|]\n",
2307        );
2308        assert_eq!(
2309            written,
2310            "X:7\nT:Tune\nT:Other\nC:Anon\nO:Here\nM:6/8\nL:1/8\nQ:3/8=120\nK:Ador\nABc def | gfe dcB | A6 |]\n"
2311        );
2312    }
2313
2314    #[test]
2315    fn accidentals_octaves_and_lengths_are_written() {
2316        let written = round_trip("X:1\nM:4/4\nL:1/4\nK:G\n^C,/ _e'3/2 =F f/4 z3/4|c4|C4|]\n");
2317        assert!(
2318            written.contains("L:1/8\nK:G\n^C, _e'3 =F2 f/ z3/2 | c8 | C8 |]"),
2319            "{written}"
2320        );
2321    }
2322
2323    /// A part of whole notes in measures, holding what `opening` gives its
2324    /// first measure.
2325    fn part_of(names: &[&str], opening: Vec<StreamElement>) -> Stream {
2326        let mut part = Stream::with_kind(StreamKind::Part);
2327        for (index, name) in names.iter().enumerate() {
2328            let mut measure = Stream::with_kind(StreamKind::Measure);
2329            if index == 0 {
2330                for element in &opening {
2331                    measure.insert(0.0, element.clone());
2332                }
2333            }
2334            measure.insert(
2335                0.0,
2336                Note::from_name(name)
2337                    .unwrap()
2338                    .with_duration(Duration::whole()),
2339            );
2340            part.insert(index as FloatType * 4.0, measure);
2341        }
2342        part
2343    }
2344
2345    #[test]
2346    fn a_part_says_its_name_and_its_instrument_s_program() {
2347        let mut part = part_of(
2348            &["C4", "D4"],
2349            vec![StreamElement::TimeSignature(
2350                TimeSignature::new(4, 4).unwrap(),
2351            )],
2352        );
2353        part.set_name(Some("Guitar".to_string()));
2354        let mut guitar = crate::instrument::Instrument::new();
2355        guitar.set_midi_program(Some(24));
2356        part.insert(0.0, StreamElement::Instrument(Box::new(guitar)));
2357        let written = to_abc(&part, &ExportOptions::default()).unwrap();
2358        assert!(
2359            written.contains(
2360                "V:1 name=\"Guitar\"
2361%%MIDI program 24
2362"
2363            ),
2364            "{written}"
2365        );
2366    }
2367
2368    #[test]
2369    fn a_clef_other_than_treble_is_said_even_where_the_notes_imply_it() {
2370        let low = part_of(
2371            &["C2", "G2"],
2372            vec![
2373                StreamElement::Clef(Clef::of_kind(crate::clef::ClefKind::BassClef)),
2374                StreamElement::TimeSignature(TimeSignature::new(4, 4).unwrap()),
2375            ],
2376        );
2377        let written = to_abc(&low, &ExportOptions::default()).unwrap();
2378        assert!(written.contains("clef=bass"), "{written}");
2379        let high = part_of(
2380            &["C5", "G5"],
2381            vec![
2382                StreamElement::Clef(Clef::of_kind(crate::clef::ClefKind::TrebleClef)),
2383                StreamElement::TimeSignature(TimeSignature::new(4, 4).unwrap()),
2384            ],
2385        );
2386        let written = to_abc(&high, &ExportOptions::default()).unwrap();
2387        assert!(!written.contains("clef="), "{written}");
2388    }
2389}