From 0c90568d97e9e347706153b8fd9391a47ac3a14c Mon Sep 17 00:00:00 2001 From: Hamza Naveed <45464935+Hamza0101@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:35:21 +0500 Subject: [PATCH] Hyphenation: a Korean word or an address is not broken by English rules (#1754) A whitespace-delimited token that carries Hangul, kana or Han, or that reads as an address, is not hyphenated by English rules. Breaking at a hyphen the author typed is still allowed. The ligature / visible-source follow-up is in #2196 and #2197. Fixes #1688. --- crates/compose/src/hyphen.rs | 260 +++++++++++++++++++++++++++++++++++ crates/compose/src/lib.rs | 42 +++++- crates/compose/src/tests.rs | 131 ++++++++++++++++++ docs/cjk.md | 2 +- 4 files changed, 432 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/hyphen.rs b/crates/compose/src/hyphen.rs index 3d2be41f9..a709995f4 100644 --- a/crates/compose/src/hyphen.rs +++ b/crates/compose/src/hyphen.rs @@ -224,6 +224,135 @@ pub fn word_breaks_in(word: &str, lang: Lang) -> (Vec, Source) { (out, src) } +/// Whether a whitespace-delimited token is one no language's hyphenation should break. +/// +/// Korean attaches particles straight onto Latin words ("News와", "PDF로"), and notices are full +/// of addresses. With the paragraph language left at the default English -- which is what an +/// ordinary Korean document has -- a word run inside such a token was hyphenated as English, +/// giving `New-` / `s와` and `library.exam-` / `ple.kr` (#1688). +/// +/// A token is kept whole when it carries Hangul, kana or Han, or when it reads as an address: a +/// URL with a scheme, an e-mail address, a dotted domain, a `/`-rooted path or a Windows drive +/// path. Breaking at a hyphen the author typed is still allowed; this only stops hyphens being +/// invented inside the token. +pub fn keep_whole(token: &str) -> bool { + let cjk = |c: char| { + matches!(c as u32, + 0xAC00..=0xD7A3 // Hangul syllables + | 0x1100..=0x11FF // Hangul Jamo + | 0x3130..=0x318F // Hangul compatibility Jamo + | 0xA960..=0xA97F // Hangul Jamo Extended-A + | 0xD7B0..=0xD7FF // Hangul Jamo Extended-B + | 0x3040..=0x30FF // kana + | 0xFF66..=0xFF9F // halfwidth katakana + | 0x4E00..=0x9FFF // CJK unified ideographs + | 0x3400..=0x4DBF + | 0xF900..=0xFAFF + | 0x20000..=0x3FFFF) // supplementary ideographs + }; + if token.chars().any(cjk) { + return true; + } + // Prose punctuation around a token is not part of the address inside it: `(https://...)` was + // not recognised because the bracket came first, and `library.example.kr,` because the comma + // ended the last label. Only this classification ignores it; the text keeps + // every character it had. + let wrapper = |c: char| { + matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '"' | '\'' | ',' | ';' | ':' | '!' | '?' | '\u{201C}' | '\u{201D}' | '\u{2018}' | '\u{2019}') + }; + // Full stops count with the wrapper characters at the end, so `(library.example.kr).` loses + // both its closing bracket and the sentence's full stop. + let token = token.trim_start_matches(wrapper).trim_end_matches(|c: char| wrapper(c) || c == '.'); + let lower = token.to_ascii_lowercase(); + if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("ftp://") || lower.starts_with("www.") { + return true; + } + // An e-mail address: one `@` with something either side, no space (tokens have none). + if let Some((user, host)) = token.split_once('@') { + return !user.is_empty() && host.contains('.'); + } + // A path, rooted or with a drive letter. + if token.starts_with('/') || token.starts_with('\\') { + return true; + } + let mut cs = token.chars(); + if let (Some(a), Some(b), Some(c)) = (cs.next(), cs.next(), cs.next()) + && a.is_ascii_alphabetic() + && b == ':' + && (c == '/' || c == '\\') + { + return true; + } + // A domain: dot-separated labels up to the first `/`, whose last label is a short run of + // letters -- "example.kr", "library.example.kr". Ordinary prose ("end. Next") never reaches + // here, because a token holds no space. + // Judged as written, not lower-cased: a domain's last label is lower-case letters, so `Mr.Smith` + // is not one and stays a word to hyphenate. + let host = token.split('/').next().unwrap_or(""); + let labels: Vec<&str> = host.trim_end_matches('.').split('.').collect(); + labels.len() >= 2 + && labels.iter().all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')) + && labels.last().is_some_and(|tld| tld.len() <= 6 && tld.chars().all(|c| c.is_ascii_lowercase())) +} + +/// Whether a paragraph is set in Korean, so automatic hyphenation does not apply to it. +/// +/// Korean is set word by word and is not hyphenated (KLREQ). A paragraph with at least as many +/// Hangul syllables as Latin letters is treated as Korean however its language is set, since an +/// ordinary Korean document leaves the paragraph language at the default English (#1688). +pub fn mostly_hangul(text: &str) -> bool { + mostly_hangul_chars(text.chars()) +} + +/// [`mostly_hangul`] over characters, for judging the text that is actually set: hidden text has +/// no glyphs, and counting it let hidden Korean turn hyphenation off for the visible English +/// around it, and hidden Latin keep it on for visible Korean. +pub fn mostly_hangul_chars(chars: impl Iterator) -> bool { + let (mut hangul, mut latin) = (0usize, 0usize); + for c in chars { + match c as u32 { + _ if crate::breaker::is_hangul(c) => hangul += 1, + _ if c.is_ascii_alphabetic() => latin += 1, + _ => {} + } + } + hangul > 0 && hangul >= latin +} + +/// [`mostly_hangul`] over a paragraph's set glyphs, given as `(source byte, character, +/// generated)` so it can be tested without a font. +/// +/// One vote per set character, not per glyph. Shaping makes a cluster several glyphs over one +/// character and each repeats that character, so a syllable shaped into three glyphs voted three +/// times -- and since the test is `hangul >= latin`, that can turn hyphenation off for a +/// paragraph that is mostly Latin. Consecutive glyphs on one source byte are one character. +/// +/// Generated glyphs do not vote: a list bullet or number, or a footnote label, is not the +/// paragraph's own text, and `prepend_label` gives it the paragraph's *first* byte -- so counting +/// it would also swallow the real first character in the deduplication. +/// +/// **Approximation.** A ligature is one glyph over several characters, so those characters vote +/// once between them and Latin is under-counted. That can change the answer: 16 Hangul with +/// `office hyphenation` is 17 Latin letters, and a font that shapes `fi` counts at most 16, so +/// the paragraph classifies as Korean and loses its hyphens. Fixing it needs +/// the visible source characters each cluster stands for; `byte..byte + len` is not that, because +/// the glyph after a hidden run spans it -- measured, every byte of the paragraph came out +/// covered -- which would revive the hidden-text bug this function was changed to avoid. +pub fn korean_paragraph(glyphs: impl Iterator) -> bool { + let mut chars: Vec = Vec::new(); + let mut last: Option = None; + for (byte, ch, generated) in glyphs { + if generated { + continue; + } + if last != Some(byte) { + chars.push(ch); + } + last = Some(byte); + } + mostly_hangul_chars(chars.into_iter()) +} + /// Allowed hyphenation points in `word` as char indices (a hyphen goes before that char), with /// the paragraph limits applied to each letter run. pub fn hyphen_points(word: &str, lim: &Limits) -> Vec { @@ -359,6 +488,65 @@ fn heuristic_points(c: &[char]) -> Vec { #[cfg(test)] mod tests { + /// A token no language's hyphenation should break: Korean particles on Latin words, and the + /// addresses a notice is full of (#1688). + #[test] + fn a_token_with_hangul_or_an_address_is_kept_whole() { + for t in [ + "News\u{C640}", // News와 + "PDF\u{B85C}", // PDF로 + "\u{C77C}\u{BCF8}\u{C5B4}", // 일본어 + "https://example.kr/page", + "www.example.kr", + "library.example.kr", + "mail@example.kr", + "/usr/share/fonts", + "C:\\Users\\Hong", + "example.kr", + ] { + assert!(keep_whole(t), "{t} should be kept whole"); + } + // Ordinary words, including ones with a hyphen or a full stop, are still hyphenated. + for t in ["hyphenation", "well-known", "sentence.", "Mr.", "re-examine", "3.5"] { + assert!(!keep_whole(t), "{t} should not be protected"); + } + + // An address wrapped in prose punctuation is the same address. + for t in [ + "library.example.kr,", + "(https://example.kr/page)", + "\u{201C}www.example.kr\u{201D}", + "mail@example.kr;", + "example.kr.", + // A bracket and then the sentence's full stop. + "(library.example.kr).", + "[https://example.kr]", + ] { + assert!(keep_whole(t), "{t} should be kept whole"); + } + + // Halfwidth katakana and a supplementary ideograph are CJK too. + for t in ["News\u{FF76}", "\u{20B9F}\u{C640}", "x\u{FF9F}"] { + assert!(keep_whole(t), "{t:?} should be kept whole"); + } + + // A domain's last label is lower-case letters as written: a name run into the next word + // after a full stop is not one, and its words still hyphenate. + for t in ["Mr.Smith", "Section.Introduction", "End.Next"] { + assert!(!keep_whole(t), "{t} is not an address"); + } + } + + /// A Korean paragraph gets no automatic hyphens whatever its language is set to (#1688). + #[test] + fn a_paragraph_that_is_mostly_hangul_is_not_hyphenated() { + assert!(mostly_hangul("\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} News\u{C640} \u{AD00}\u{B828}")); + assert!(!mostly_hangul("An English paragraph about hyphenation and composition")); + // A Latin paragraph with a Korean word in it is still hyphenated as Latin. + assert!(!mostly_hangul("The Korean word \u{D55C}\u{AD6D} appears once in this English sentence")); + assert!(!mostly_hangul("")); + } + use super::*; fn h(w: &str) -> String { @@ -720,3 +908,75 @@ mod tests { assert!(t.elapsed().as_secs() < 5, "{:?}", t.elapsed()); } } + +#[cfg(test)] +mod korean_paragraph_tests { + use super::korean_paragraph; + + /// `(byte, ch, generated)` per glyph, which is all the classification reads -- so these cases + /// need no font and state the counting rules directly. + fn k(glyphs: &[(usize, char, bool)]) -> bool { + korean_paragraph(glyphs.iter().copied()) + } + + /// One character per source byte, however many glyphs shaping made of it. A syllable shaped + /// into three glyphs voted three times, which could classify a mostly-Latin paragraph as + /// Korean. + #[test] + fn glyphs_of_one_cluster_vote_once() { + // Two Hangul characters, the first shaped into three glyphs, against three Latin letters. + let clustered = [ + (0, '\u{AC00}', false), + (0, '\u{AC00}', false), + (0, '\u{AC00}', false), + (3, '\u{B098}', false), + (6, 'a', false), + (7, 'b', false), + (8, 'c', false), + ]; + assert!(!k(&clustered), "two Hangul against three Latin is not Korean"); + // Counting each glyph instead gives four Hangul against three, which flips it -- so the + // deduplication is what decides this case. + let per_glyph: Vec = clustered.iter().map(|(_, c, _)| *c).collect(); + assert!(super::mostly_hangul_chars(per_glyph.into_iter()), "per-glyph counting would call it Korean"); + } + + /// A generated label is not the paragraph's own text, and `prepend_label` gives it the + /// paragraph's *first* byte -- so counting it also swallowed the real first character in the + /// deduplication. + #[test] + fn a_generated_label_neither_votes_nor_hides_the_first_character() { + // A footnote label at byte 0, then two Hangul characters (the first also at byte 0) and + // two Latin letters. Two against two is Korean, since the test is `hangul >= latin` -- + // and losing one Hangul character to the label makes it one against two, which is not. + let labelled = [(0, '1', true), (0, '\u{AC00}', false), (3, '\u{B098}', false), (6, 'a', false), (7, 'b', false)]; + assert!(k(&labelled), "two Hangul against two Latin is Korean"); + // Without the exclusion the label takes byte 0, the Hangul character there is deduplicated + // away, and one Hangul against two Latin is no longer Korean. + let counted: Vec = { + let mut out = Vec::new(); + let mut last = None; + for (b, c, _) in labelled { + if last != Some(b) { + out.push(c); + } + last = Some(b); + } + out + }; + assert!(!super::mostly_hangul_chars(counted.into_iter()), "counting the label loses the first character"); + } + + /// The remaining approximation, pinned so it is visible rather than surprising: a ligature is + /// one glyph over several characters, so Latin is under-counted and this paragraph classifies + /// as Korean although it has more Latin letters. + #[test] + fn a_ligature_under_counts_latin_which_is_a_known_approximation() { + // Two Hangul characters against three Latin letters shaped as one `ffi` glyph. + let ligated = [(0, '\u{AC00}', false), (3, '\u{B098}', false), (6, '\u{FB03}', false)]; + assert!(k(&ligated), "the ligature counts as one character, so this reads as Korean"); + // Spelled out, the same text is not Korean -- which is the error the approximation makes. + let spelled = [(0, '\u{AC00}', false), (3, '\u{B098}', false), (6, 'f', false), (7, 'f', false), (8, 'i', false)]; + assert!(!k(&spelled), "the same characters unligated are not Korean"); + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index c0ac12a90..17ad2f76b 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1699,6 +1699,9 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) { for _ in 0..3 { // The same drop cap, spacing, hyphenation and breaker as the layout below. let mut gl = sp.glyphs.clone(); + // Classified before the drop cap is split off: `split_drop_cap` takes those glyphs out + // of the vector, and the drop cap's character still votes (#1688). + let korean = hyphen::korean_paragraph(gl.iter().map(|g| (g.byte, g.ch, g.list_label || g.generated_text.is_some()))); let dc = split_drop_cap(db, &mut gl, drop_end, pp.drop_cap_lines, base_leading, base_cap, drop_grid, drop_align, drop_tabs); let width = |j: usize| { let ind = match &dc { @@ -1710,7 +1713,7 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) { }; apply_desired_spacing(&mut gl, pp); mojikumi::apply(&mut gl, &doc.styles, &pp.mojikumi); - let mut hy = hyphenation_points(&story.text, &gl, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars)); + let mut hy = hyphenation_points(&story.text, &gl, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars), korean); suppress_hyphens(&mut hy, &gl, suppressed_hyphens); let breaks = if pp.composer.single_line() || gl.iter().any(|g| g.ch == '\t') || gl.len() > 4000 { let tab = |j: usize, x: f64, i: usize| { @@ -2861,6 +2864,8 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { g.and_then(|g| table.styles.get(g.style as usize)).map_or((base_chars.fill.clone(), base_chars.fill_tint), |s| (s.fill.clone(), s.fill_tint)) }; let (above, below) = (text_color(sp.glyphs.iter().find(|g| g.len > 0)), text_color(sp.glyphs.iter().rev().find(|g| g.len > 0))); + // Classified before the drop cap is split off (see the same call in the measuring loop above). + let korean = hyphen::korean_paragraph(sp.glyphs.iter().map(|g| (g.byte, g.ch, g.list_label || g.generated_text.is_some()))); let drop_cap = split_drop_cap( db, &mut sp.glyphs, @@ -2950,7 +2955,8 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { ); apply_desired_spacing(&mut glyphs, pp); mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi); - let mut hyph_after = hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars)); + let mut hyph_after = + hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars), korean); suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens); let base_size = base_chars.size; let spacing = spacing_for(pp, base_size, story, cjk); @@ -5976,17 +5982,31 @@ fn hyphenation_points( pp: &ParaProps, exceptions: &HashMap>, foreign: &[(Range, Option)], + korean: bool, ) -> Vec { let mut out = vec![false; glyphs.len()]; if !pp.hyphenate { return out; } + // Korean is set word by word and is not hyphenated (KLREQ). An ordinary Korean document + // leaves the paragraph language at the default English, so the paragraph's own text decides + // rather than its language setting (#1688). + // + // Decided by the caller, from the paragraph's glyphs *before* its drop cap is split off: + // `split_drop_cap` takes those glyphs out of the vector, so classifying here lost the drop + // cap's character -- 15 Hangul against 15 Latin became 14 against 15, and the paragraph + // hyphenated its English. See `hyphen::korean_paragraph`. + if korean { + return out; + } let lim = hyphen::Limits { min_word: pp.hyph_min_word as usize, after_first: pp.hyph_after_first as usize, before_last: pp.hyph_before_last as usize, capitalized: pp.hyph_capitalized, }; + // The token the last word run sat in, and whether it is kept whole (see below). + let mut token: Option<(usize, usize, bool)> = None; let mut i = 0; while i < glyphs.len() { if !glyphs[i].is_letter() || glyphs[i].len == 0 { @@ -6007,6 +6027,24 @@ fn hyphenation_points( let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len); if !discretionary && b > a && b <= text.len() && text.is_char_boundary(a) && text.is_char_boundary(b) { let word = &text[a..b]; + // The whitespace-delimited token the word sits in: a Latin run with a Korean particle + // on it ("News와") or inside an address is not a word to hyphenate (#1688). Found once + // per token and reused for the word runs inside it: unspaced CJK text is one token + // however many Latin words it holds, and scanning it again for each was quadratic. + let keep = match token { + Some((start, end, keep)) if start <= a && b <= end => keep, + _ => { + let start = text[..a].rfind(char::is_whitespace).map_or(0, |i| i + text[i..].chars().next().map_or(1, char::len_utf8)); + let end = text[b..].find(char::is_whitespace).map_or(text.len(), |i| b + i); + let keep = hyphen::keep_whole(&text[start..end]); + token = Some((start, end, keep)); + keep + } + }; + if keep { + i = j.max(i + 1); + continue; + } // Do not hyphenate the paragraph's last word unless allowed. let is_last_word = !pp.hyph_last_word && glyphs[j..].iter().all(|g| !g.is_letter()); let lang = foreign.iter().find(|(r, _)| r.contains(&a)).map_or(Some(hyphen::Lang::English), |(_, l)| *l); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 8e03b35d0..f8cb4f3ce 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1499,6 +1499,137 @@ fn hyphen_limit_is_a_hard_constraint() { } } +/// Each paragraph's own text decides, not the story's: a Korean document's English paragraphs +/// still hyphenate, and a mostly-English story's Korean paragraphs still do not (noted in review +/// of #1688). +#[test] +fn hyphenation_follows_each_paragraph_not_the_story() { + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + // 이번 통지문은 아래와 같습니다 / an English paragraph that wants hyphenation + let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} \u{C544}\u{B798}\u{C640} \u{AC19}\u{C2B5}\u{B2C8}\u{B2E4}"; + let english = "This notice about hyphenation and composition continues for a while in English"; + let hyphens = |text: &str| { + let (d, sid, _) = doc_with(text, rect, para.clone()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + // Which paragraph each hyphenated line belongs to: the Korean one is first. + lines.iter().filter(|l| l.hyphenated).count() + }; + // The English paragraph in a Korean document still hyphenates: the story is mostly Hangul, + // but that paragraph is not. + let mixed = format!("{korean}\n{english}"); + assert!(hyphens(&mixed) > 0, "the English paragraph of a Korean document still hyphenates"); + // And the Korean paragraph alone invents none. + assert_eq!(hyphens(korean), 0, "a Korean paragraph invents no hyphens"); +} + +/// The paragraph's *glyphs* decide, not its source text: hidden conditional text is not set, so +/// it does not get a vote. Reading the source let hidden Korean turn hyphenation off for the +/// visible English around it (noted in review of #1688). +#[test] +fn hidden_text_does_not_decide_whether_a_paragraph_hyphenates() { + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + // 이번 통지문은 아래와 같습니다 — repeated, so the Hangul outweighs the English after it + // (`mostly_hangul` wants at least as many Hangul characters as ASCII letters). + let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} \u{C544}\u{B798}\u{C640} \u{AC19}\u{C2B5}\u{B2C8}\u{B2E4} ".repeat(6); + let english = "This notice about hyphenation and composition continues for a while in English"; + let text = format!("{korean}{english}"); + + let hyphens = |hide: bool| { + let (mut d, sid, _) = doc_with(&text, rect, para.clone()); + d.conditions.push(designcraft_doc::Condition { name: "Draft".into(), color: [255, 0, 0], visible: !hide }); + let story = d.story_mut(sid).expect("the story is there"); + let chars = designcraft_doc::CharAttrs { conditions: Some(vec!["Draft".into()]), ..Default::default() }; + story.chars = vec![ + designcraft_doc::CharRun { len: korean.len(), format: designcraft_doc::CharFormat { over: chars, ..Default::default() } }, + designcraft_doc::CharRun { len: english.len(), format: designcraft_doc::CharFormat::default() }, + ]; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().filter(|l| l.hyphenated).count() + }; + + // Shown, the Hangul outweighs the English and the paragraph is not hyphenated. + assert_eq!(hyphens(false), 0, "a visibly Korean paragraph invents no hyphens"); + // Hidden, the only text set is English, and it hyphenates like any English paragraph. + assert!(hyphens(true) > 0, "hidden Korean does not turn hyphenation off for the visible English"); +} + +/// `split_drop_cap` takes the drop cap's glyphs out of the vector, so classifying the paragraph +/// after it ran lost that character's vote: with the Hangul and Latin counts level, dropping one +/// Hangul character made the paragraph read as Latin and its English words took automatic hyphens +/// (noted in review). The classification is made before the split. +#[test] +fn a_drop_cap_still_counts_when_a_paragraph_is_judged_korean() { + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + // English long enough that it really does hyphenate in a 90 pt column -- the run + // `hidden_text_does_not_decide_whether_a_paragraph_hyphenates` uses for the same reason. A + // short run leaves no hyphens whichever way the paragraph is classified, so the test would + // pass without testing anything (measured: it did). + let english = "This notice about hyphenation and composition continues for a while in English"; + let letters = english.chars().filter(char::is_ascii_alphabetic).count(); + // One Hangul syllable per Latin letter, so the counts are level -- which `hangul >= latin` + // calls Korean, and one character either way decides it. + let korean: String = "\u{AC00}\u{B098}\u{B2E4}\u{B77C}\u{B9C8}".chars().cycle().take(letters).collect(); + assert_eq!(korean.chars().count(), letters, "the two counts are level at {letters}"); + let text = format!("{korean} {english}"); + + let hyphens = |para: ParaAttrs| { + let (d, sid, _) = doc_with(&text, rect, para); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().filter(|l| l.hyphenated).count() + }; + let base = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + + // Level counts read as Korean, so nothing hyphenates. + assert_eq!(hyphens(base.clone()), 0, "level counts read as Korean"); + // The paragraph opens on a Hangul character, so that character is the drop cap. It is still + // set, just larger, so the answer must not change. + let with_cap = ParaAttrs { drop_cap_lines: Some(2), drop_cap_chars: Some(1), ..base.clone() }; + assert_eq!(hyphens(with_cap), 0, "a drop cap does not turn the paragraph Latin"); + + // And the fixture really is poised on the boundary: one Latin letter more and the English + // hyphenates, so the assertions above are not passing for want of any hyphen at all. + let tipped = format!("{korean} {english}x"); + let (d, sid, _) = doc_with(&tipped, rect, base); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(all_lines(&cs).iter().any(|l| l.hyphenated), "one more Latin letter tips it and hyphens appear"); +} + +/// A Korean notice leaves its paragraphs at the default English language, so English +/// hyphenation broke the Latin words Korean particles attach to and the addresses such a document +/// is full of: `New-` / `s와`, `library.exam-` / `ple.kr` (#1688). The lines may now be looser -- +/// that is the cost of not hyphenating, and what #1691 is about -- but no hyphen is invented +/// inside those tokens. +#[test] +fn korean_text_and_addresses_are_not_hyphenated() { + // Narrow enough that every line has to break somewhere. + let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0); + let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() }; + let hyphens_in = |text: &str| { + let (d, sid, _) = doc_with(text, rect, para.clone()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().filter(|l| l.hyphenated).count() + }; + + // 이번 통지문은 News와 관련된 library.example.kr 주소를 포함합니다 + let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} News\u{C640} \u{AD00}\u{B828}\u{B41C} library.example.kr \u{C8FC}\u{C18C}\u{B97C} \u{D3EC}\u{D568}\u{D569}\u{B2C8}\u{B2E4}"; + assert_eq!(hyphens_in(korean), 0, "a Korean paragraph invents no hyphens"); + + // An English paragraph holding the same address: the prose still hyphenates, the address does + // not, so the protection is about the token and not about turning hyphenation off. + let english = "This notice about hyphenation and composition mentions library.example.kr somewhere inside a long sentence"; + assert!(hyphens_in(english) > 0, "English prose is still hyphenated"); + let (d, sid, _) = doc_with(english, rect, para.clone()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + for l in all_lines(&cs).iter().filter(|l| l.hyphenated) { + let upto = &english[..l.range.end.min(english.len())]; + let token = upto.rsplit(char::is_whitespace).next().unwrap_or(""); + assert!(!"library.example.kr".starts_with(token) || token.is_empty(), "a hyphen was invented inside the address: {token:?}"); + } +} + #[test] fn hyphenation_zone_limits_ragged_hyphens() { let text = CORPUS.join(" "); diff --git a/docs/cjk.md b/docs/cjk.md index e5782d8ae..5383c0594 100644 --- a/docs/cjk.md +++ b/docs/cjk.md @@ -36,7 +36,7 @@ presets or tables are copied. Our default mojikumi and kinsoku tables are built | Vertical text, upright CJK, rotated Latin | done: story direction per story (frames of a thread agree; IDML `StoryOrientation`); glyphs turned by transforms; arrow keys follow the vertical lines | | Vertical metrics and shaping | done: upright runs shaped top to bottom (`vert`; `vkrn`/`vpal` when asked) with `vmtx`/`VORG` advances and origins, centred on the ideographic em box (`BASE`, else OS/2); turned runs shaped horizontally, without `vrt2`; Horizontal Kana (`hkna`) takes the vertical kana (`vkna`) in upright runs. Default location of variable fonts only (no `VVAR`) | | Kinsoku | named (hard, soft, Chinese, Korean) and custom kinsoku sets, bunri-kinshi, rensuuji, hanging punctuation (regular, force); without a set, fixed no-start / no-end lists and a break anywhere between CJK characters; kinsoku type (push in / push out priorities) kept but not applied | -| Korean line breaking | at spaces (Hangul everywhere, hanja in Korean text); per-paragraph character-based breaking (`koreanCharBreaks`); DesignCraft-only, not in IDML | +| Korean line breaking | at spaces (Hangul everywhere, hanja in Korean text); per-paragraph character-based breaking (`koreanCharBreaks`); DesignCraft-only, not in IDML; no automatic hyphens in a paragraph with at least as many Hangul letters as ASCII Latin ones, whatever its language setting, and none invented inside a space-delimited token holding Hangul, kana or Han or reading as an address (URL, e-mail, domain, rooted or drive path) (#1688) | | Mojikumi | applied in composition: the built-in base sets (line end half-width, line end one em, Simplified and Traditional Chinese) and the document's tables with their override rows, kept through IDML; Preflight notes tables it can't apply. In the Japanese sets consecutive punctuation closes up (JLREQ 3.1.4: 」。, 「『 touch; 」・ a quarter em, 」「 half an em apart). Still open: 、・ and ・・ take the sum of both blanks in JLREQ (Table 1 notes) | | Aki, tsume, jidori | done ([cjk-typography.md](cjk-typography.md)) | | Character alignment, leading model | em box top / centre / bottom, ICF top / bottom (`BASE` `icft`/`icfb`, else the em box inset by 5%), roman baseline; aki above / below, centre (centre down as centre); under aki below a line's leading is the space to the line below it; with the Japanese composers (`Composer::Japanese`, `JapaneseSingleLine`, IDML `HL Composer J` / `HL Single J`), the others set lines baseline to baseline on the Roman baseline |