diff --git a/crates/proof/src/devanagari.rs b/crates/proof/src/devanagari.rs new file mode 100644 index 0000000000..2b7772864d --- /dev/null +++ b/crates/proof/src/devanagari.rs @@ -0,0 +1,203 @@ +//! The Devanagari pieces of proofing, apart from any one language so that every language written +//! in Devanagari (Hindi now) can share them: the script's letters and digits, the two spellings of +//! its nukta letters, the spelling check against a Hunspell dictionary and the generic checks +//! (repeated words, spacing) with each language's messages. + +use crate::affix::AffixDict; +use crate::{Issue, IssueKind, ProofLang, words}; + +/// Is `c` in the Devanagari block (U+0900..=U+097F)? +pub fn is_devanagari_char(c: char) -> bool { + ('\u{0900}'..='\u{097F}').contains(&c) +} + +/// Is `c` a Devanagari digit (`०`..=`९`, U+0966..=U+096F)? +pub fn is_devanagari_digit(c: char) -> bool { + ('\u{0966}'..='\u{096F}').contains(&c) +} + +/// Is `c` part of a Devanagari word: a letter, vowel sign, virama, nukta or other mark of the +/// block? Digits, the danda (`।`, `॥`) and the abbreviation sign (`॰`) are not. +pub fn is_devanagari_letter(c: char) -> bool { + is_devanagari_char(c) && !is_devanagari_digit(c) && !matches!(c, '\u{0964}' | '\u{0965}' | '\u{0970}') +} + +/// The consonants with a precomposed nukta letter (U+0958..=U+095F): the base consonant, then +/// the precomposed letter. +const NUKTA_LETTERS: [(char, char); 8] = [ + ('\u{0915}', '\u{0958}'), + ('\u{0916}', '\u{0959}'), + ('\u{0917}', '\u{095A}'), + ('\u{091C}', '\u{095B}'), + ('\u{0921}', '\u{095C}'), + ('\u{0922}', '\u{095D}'), + ('\u{092B}', '\u{095E}'), + ('\u{092F}', '\u{095F}'), +]; + +/// The nukta sign (U+093C). +const NUKTA: char = '\u{093C}'; + +/// `w` with its nukta letters spelled the other way, if it has any: precomposed ones (`क़`, +/// U+0958) as consonant and nukta (`क` + `़`), else consonant-and-nukta pairs precomposed. +/// Composition (NFC) always gives the pair, since the precomposed letters are excluded from it, +/// but a dictionary may list either spelling. +pub(crate) fn nukta_variant(w: &str) -> Option { + let precomposed = |c: char| NUKTA_LETTERS.iter().find(|&&(_, p)| p == c).map(|&(base, _)| base); + if w.chars().any(|c| precomposed(c).is_some()) { + let mut out = String::with_capacity(w.len() + 4); + for c in w.chars() { + match precomposed(c) { + Some(base) => { + out.push(base); + out.push(NUKTA); + } + None => out.push(c), + } + } + return Some(out); + } + let mut out = String::with_capacity(w.len()); + let mut changed = false; + let mut chars = w.chars().peekable(); + while let Some(c) = chars.next() { + if let Some(&(_, p)) = NUKTA_LETTERS.iter().find(|&&(base, _)| base == c) + && chars.peek() == Some(&NUKTA) + { + chars.next(); + out.push(p); + changed = true; + } else { + out.push(c); + } + } + changed.then_some(out) +} + +/// Is `word` spelled correctly against `d`, the dictionary of a language written in Devanagari? +/// Numbers (ASCII or Devanagari digits), single letters, words with digits (when `opts` ignores +/// them) and words in other scripts are accepted, and so is every word when `d` is empty. +pub(crate) fn is_correct(d: &AffixDict, word: &str, opts: &crate::Options) -> bool { + if d.is_empty() { + return true; + } + let w = word.trim_matches(|c: char| !c.is_alphanumeric() && !is_devanagari_letter(c) && !matches!(c, '\'' | '’' | '-')); + let w = w.trim_matches(['\'', '’', '-']); + let letter_count = w.chars().filter(|&c| is_devanagari_letter(c) || c.is_alphabetic()).count(); + if letter_count <= 1 || (opts.ignore_numbers && w.chars().any(char::is_numeric)) { + return true; + } + // A word in another script (or with no Devanagari letters) is not marked by this dictionary. + if !w.chars().any(is_devanagari_letter) { + return true; + } + if w.contains('-') { + // The whole word first, as Hunspell does: a hyphenated entry or user word. + return known(d, w) || w.split('-').all(|p| p.chars().count() <= 1 || !p.chars().any(is_devanagari_letter) || known(d, p)); + } + known(d, w) +} + +/// Is one word (no hyphens) in the dictionary or the user dictionary, with its nukta letters +/// spelled either way ([`nukta_variant`])? +fn known(d: &AffixDict, w: &str) -> bool { + let listed = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase()); + listed(w) || nukta_variant(w).is_some_and(|v| listed(&v)) +} + +/// A language's messages and choices for [`check`]. +pub(crate) struct Rules { + /// The language the issues are in. + pub(crate) lang: ProofLang, + /// A repeated word's message, before `: “word”`. + pub(crate) repeated_word: &'static str, + /// A space before punctuation. + pub(crate) space_before_punctuation: &'static str, + /// Two or more spaces. + pub(crate) double_space: &'static str, + /// Is a word written twice in a row (`के के`) a likely mistake? Languages that double words + /// on purpose (`धीरे धीरे`, `घर घर`) flag only the words that never are. + pub(crate) flag_repeat: fn(&str) -> bool, +} + +/// Repeated words and spacing problems in `text`, with `rules`' messages. A space before `,`, +/// `;`, `:`, `!`, `?` or `.` is flagged; one before the danda (`।`, `॥`) is not, since text +/// sets it both ways. +pub(crate) fn check(text: &str, rules: &Rules) -> Vec { + let mut issues = Vec::new(); + repeated_words(text, &words(text), rules, &mut issues); + spaces(text, rules, &mut issues); + issues.sort_by_key(|i| (i.start, i.end)); + issues +} + +fn issue(rules: &Rules, start: usize, end: usize, message: String, suggestions: Vec) -> Issue { + Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: rules.lang } +} + +/// An ASCII or Devanagari digit. +fn is_digit(c: char) -> bool { + c.is_ascii_digit() || is_devanagari_digit(c) +} + +fn repeated_words(text: &str, ws: &[(usize, usize)], rules: &Rules, v: &mut Vec) { + for pair in ws.windows(2) { + let [(a0, b0), (a1, b1)] = pair else { continue }; + let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; + if !gap.is_empty() + && gap.chars().all(char::is_whitespace) + && w0.chars().all(|c| c.is_alphabetic() || is_devanagari_letter(c)) + && w0 == w1 + && (rules.flag_repeat)(w0) + { + v.push(issue(rules, *a0, *b1, format!("{}: “{w1}”", rules.repeated_word), vec![w0.to_string()])); + } + } +} + +fn spaces(text: &str, rules: &Rules, v: &mut Vec) { + for (i, c) in text.char_indices() { + if c != ' ' { + continue; + } + let rest = text.get(i + 1..).unwrap_or(""); + let mut it = rest.chars(); + let Some(p) = it.next() else { continue }; + let after = it.next(); + // A ratio/score keeps the spaces in digit-space-colon-space-digit (ASCII or Devanagari digits). + let ratio = p == ':' + && text.get(..i).and_then(|before| before.chars().next_back()).is_some_and(is_digit) + && after == Some(' ') + && it.next().is_some_and(is_digit); + let flag = !ratio + && match p { + ',' => true, + ';' => !matches!(after, Some(')' | '(' | '-' | 'P' | 'D')), + '.' => !matches!(after, Some('.')) && !after.is_some_and(is_digit), + ':' | '!' | '?' => after.is_none_or(|a| a.is_whitespace() || matches!(a, '"' | '”' | '’' | '!' | '?')), + _ => false, + }; + if flag { + v.push(issue(rules, i, i + 1 + p.len_utf8(), rules.space_before_punctuation.into(), vec![p.to_string()])); + } + } + for run in crate::space_runs(text) { + v.push(issue(rules, run.start, run.end, rules.double_space.into(), vec![" ".into()])); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nukta_letters_have_two_spellings() { + // ज़मीन precomposed and as ज + nukta; सड़क the same. + assert_eq!(nukta_variant("\u{095B}मीन").as_deref(), Some("ज\u{093C}मीन")); + assert_eq!(nukta_variant("ज\u{093C}मीन").as_deref(), Some("\u{095B}मीन")); + assert_eq!(nukta_variant("सड\u{093C}क").as_deref(), Some("स\u{095C}क")); + // A nukta on a consonant with no precomposed letter, and no nukta at all: one spelling. + assert_eq!(nukta_variant("स\u{093C}"), None); + assert_eq!(nukta_variant("किताब"), None); + } +} diff --git a/crates/proof/src/hi/grammar.rs b/crates/proof/src/hi/grammar.rs new file mode 100644 index 0000000000..b3e7aef47d --- /dev/null +++ b/crates/proof/src/hi/grammar.rs @@ -0,0 +1,90 @@ +//! Generic repeated-word and spacing checks ([`crate::devanagari::check`]) with Hindi messages. +//! No Hindi-specific grammar or agreement rules are inferred. + +use crate::devanagari::{Rules, is_devanagari_char}; +use crate::{Issue, ProofLang}; + +/// Checks `text` for repeated words and spacing problems, with Hindi messages. +pub fn check(text: &str) -> Vec { + crate::devanagari::check(text, &RULES) +} + +const RULES: Rules = Rules { + lang: ProofLang::Hi, + repeated_word: "दोहराया गया शब्द", + space_before_punctuation: "विराम चिह्न से पहले रिक्त स्थान", + double_space: "दोहरा रिक्त स्थान", + flag_repeat, +}; + +/// Hindi doubles words on purpose all the time (`धीरे धीरे`, `बार बार`, `घर घर`, `छोटे छोटे`), +/// so a doubled Hindi word is flagged only when it is one of these postpositions, auxiliaries +/// and conjunctions, which are never doubled on purpose (`के के`, `है है`). A doubled word in +/// another script is flagged as in the other languages. +const NEVER_DOUBLED: &[&str] = &[ + "का", "की", "के", "को", "में", "से", "ने", "पर", "तक", "है", "हैं", "था", "थी", "थे", "हूँ", "हूं", "और", "या", "कि", "एवं", "तथा", "लेकिन", + "परंतु", "किंतु", "क्योंकि", "भी", +]; + +fn flag_repeat(w: &str) -> bool { + !w.chars().any(is_devanagari_char) || NEVER_DOUBLED.contains(&w) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::IssueKind; + + #[test] + fn intentional_repeats_are_fine() { + for text in ["धीरे धीरे चलो।", "बार बार कहा।", "घर घर में दीये जले।", "कभी कभी", "अपने अपने घर जाओ।", "छोटे छोटे बच्चे"] { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + assert_eq!(check("मैं घर के के पास हूँ।").len(), 1); + assert_eq!(check("यह सच है है।").len(), 1); + assert!(check("1 1").is_empty()); + assert!(check("१ १").is_empty()); + } + + #[test] + fn repeated_words_and_spaces_have_hindi_messages() { + let text = "राम ने ने कहा , ठीक है।"; + let issues = check(text); + assert_eq!(issues.len(), 3, "{issues:?}"); + assert_eq!(issues[0].message, "दोहराया गया शब्द: “ने”"); + assert_eq!(issues[0].suggestions, ["ने"]); + assert_eq!(&text[issues[0].start..issues[0].end], "ने ने"); + assert!(issues.iter().any(|i| i.message == "विराम चिह्न से पहले रिक्त स्थान" && &text[i.start..i.end] == " ,")); + assert!(issues.iter().any(|i| i.message == "दोहरा रिक्त स्थान")); + assert!(issues.iter().all(|i| i.lang == ProofLang::Hi && i.kind == IssueKind::Grammar)); + // Latin words doubled inside Hindi text are still flagged. + assert_eq!(check("यह the the है").len(), 1); + } + + #[test] + fn a_space_before_the_danda_is_left_alone() { + for text in ["वह घर गया।", "वह घर गया ।", "श्लोक ॥"] { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + } + + #[test] + fn ratios_and_scores_keep_their_spaces() { + for text in ["3 : 1", "स्कोर 12 : 10।", "३ : १", "१ : २", "स्कोर १२ : १०।", "मूल्य .५ है"] { + assert!(check(text).is_empty(), "{text}: {:?}", check(text)); + } + for text in ["शब्द : दूसरा", "3 : शब्द", "3 :", "३ : शब्द", "३ :"] { + assert!(check(text).iter().any(|i| i.message == "विराम चिह्न से पहले रिक्त स्थान"), "{text}"); + } + } + + proptest::proptest! { + #[test] + fn never_panics_and_ranges_are_valid(s in "\\PC{0,80}") { + for issue in check(&s) { + proptest::prop_assert!(issue.start <= issue.end && issue.end <= s.len()); + proptest::prop_assert!(s.is_char_boundary(issue.start) && s.is_char_boundary(issue.end)); + } + } + } +} diff --git a/crates/proof/src/hi/mod.rs b/crates/proof/src/hi/mod.rs new file mode 100644 index 0000000000..58a1b7f60d --- /dev/null +++ b/crates/proof/src/hi/mod.rs @@ -0,0 +1,165 @@ +//! Hindi proofing using the installed Hunspell `hi_IN` dictionary (never bundled). +//! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic checks have Hindi messages; the +//! Devanagari pieces live in [`crate::devanagari`]. Hyphenation keeps the existing fallback. + +pub mod grammar; +pub(crate) mod suggest; +#[cfg(test)] +pub(crate) mod test_dict; + +use std::sync::Arc; + +use crate::affix::AffixDict; +use crate::slot::DictSlot; + +pub use suggest::suggest; + +/// File names of a Hindi Hunspell dictionary. +const NAMES: &[&str] = &["hi_IN", "hi-IN", "hi"]; + +/// The Hindi dictionary, found on first use (see [`DictSlot`]). +pub(crate) static DICT: DictSlot = DictSlot::new(NAMES, "Hindi"); + +/// The Hindi dictionary: the installed Hunspell `hi_IN` (read on first use), one given with +/// [`install_dictionary`], or an empty one when none is available (Hindi spelling is off then; +/// see [`has_dictionary`]). +pub fn dictionary() -> Arc { + DICT.get() +} + +/// Use this Hindi dictionary from now on (Hunspell `.aff` and `.dic` text, decoded to UTF-8), +/// for example one the user picked. On error the current dictionary stays. +pub fn install_dictionary(aff: &str, dic: &str) -> Result<(), String> { + DICT.install(aff, dic) +} + +/// Is a Hindi dictionary available (spelling is checked)? +pub fn has_dictionary() -> bool { + DICT.has_dictionary() +} + +/// Is `word` spelled correctly in Hindi? Numbers (ASCII or Devanagari digits), single letters, +/// short words with digits and words in other scripts are accepted, and so is every word when no +/// Hindi dictionary is installed. A nukta letter matches the dictionary however either spells it +/// (`ज़`, U+095B, or `ज` and the nukta). +pub fn is_correct(word: &str) -> bool { + is_correct_with(&dictionary(), word) +} + +/// [`is_correct`] with the File › Options › Proofing choices: with Ignore words that contain +/// numbers off, words with digits are checked. +pub fn is_correct_with_options(word: &str, opts: &crate::Options) -> bool { + crate::devanagari::is_correct(&dictionary(), word, opts) +} + +/// [`is_correct`] against a given dictionary (an empty one accepts everything). +pub fn is_correct_with(d: &AffixDict, word: &str) -> bool { + crate::devanagari::is_correct(d, word, &crate::Options::default()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dictionary_lookup_accepts_hindi_file_names() { + let dir = std::env::temp_dir().join(format!("wordcraft-hi-aliases-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for name in ["hi_IN", "hi-IN", "hi"] { + std::fs::write(dir.join(format!("{name}.aff")), test_dict::AFF).unwrap(); + std::fs::write(dir.join(format!("{name}.dic")), test_dict::DIC).unwrap(); + let (aff, dic) = crate::hunspell::find_in(&dir, NAMES).unwrap(); + let d = crate::hunspell::load(&aff, &dic).unwrap(); + assert!(is_correct_with(&d, "किताबें")); + std::fs::remove_file(aff).unwrap(); + std::fs::remove_file(dic).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } + + #[test] + fn hindi_words_affixes_and_misspellings() { + test_dict::install(); + assert!(has_dictionary()); + for w in [ + "घर", + "घरों", + "किताब", + "किताबें", + "किताबों", + "कमरा", + "कमरे", + "कमरों", + "बच्चे", + "बच्चों", + "गाँव", + "गाँवों", + "सफल", + "असफल", + "परीक्षण", + "घर-शहर", + "“किताब”", + ] { + assert!(is_correct(w), "{w}"); + } + for w in ["घरर", "किताबब", "पानीई", "कमरो", "zqप्रतिबंधित"] { + assert!(!is_correct(w), "{w}"); + } + } + + #[test] + fn missing_dictionary_and_ignored_inputs_are_quiet() { + let empty = AffixDict::default(); + assert!(is_correct_with(&empty, "किताबब")); + assert!(install_dictionary("FLAG bogus\n", "1\nघर\n").is_err()); + let d = AffixDict::from_hunspell(test_dict::AFF, test_dict::DIC, &[]).unwrap(); + for w in ["", "2026", "१२", "२०२६", "क", "।", "English", "日本語", "ગુજરાતી"] { + assert!(is_correct_with(&d, w), "{w}"); + } + let no_ignore = crate::Options { ignore_numbers: false, ..Default::default() }; + assert!(crate::devanagari::is_correct(&d, "१२", &no_ignore)); + assert!(crate::devanagari::is_correct(&d, "2026", &no_ignore)); + assert!(!crate::devanagari::is_correct(&d, "घरर१२", &no_ignore)); + assert!(crate::devanagari::is_correct(&d, "घरर१२", &crate::Options::default())); + } + + /// Composing a word (as every check does) splits a precomposed nukta letter into consonant + /// and nukta, so a dictionary that lists either spelling still knows the word. + #[test] + fn nukta_letters_match_either_spelling() { + crate::hold_dictionary_tests(); + // ज़मीन listed precomposed (U+095B), सड़क as ड and the nukta. + install_dictionary("SET UTF-8\n", "2\n\u{095B}मीन\nसड\u{093C}क\n").unwrap(); + for w in ["\u{095B}मीन", "ज\u{093C}मीन", "स\u{095C}क", "सड\u{093C}क"] { + assert!(crate::is_correct_in(w, crate::ProofLang::Hi), "{w:?}"); + } + assert!(!crate::is_correct_in("ज\u{093C}मीनन", crate::ProofLang::Hi)); + test_dict::install(); + } + + #[test] + fn user_dictionary_applies() { + test_dict::install(); + assert!(!is_correct("नयाशब्दहिंदी")); + crate::add_word("नयाशब्दहिंदी"); + assert!(is_correct("नयाशब्दहिंदी")); + } + + #[test] + fn hindi_dispatch_messages_options_and_mixed_spans() { + crate::hold_dictionary_tests(); + test_dict::install(); + assert!(crate::has_dictionary(Some("hi-IN"))); + assert!(crate::is_correct_for("किताबें", Some("hin"))); + // The danda ends the sentence and is no part of the word before it. + let text = "बच्चे किताबब घर।"; + let issues = crate::check_text(text, &[(0..text.len(), crate::ProofLang::Hi)]); + assert_eq!(issues.len(), 1, "{issues:?}"); + assert_eq!(&text[issues[0].start..issues[0].end], "किताबब"); + assert_eq!(issues[0].message, "संभावित वर्तनी त्रुटि"); + assert_eq!(issues[0].lang, crate::ProofLang::Hi); + let text = "घर this is is wrong"; + let issues = crate::check_text(text, &[(0..6, crate::ProofLang::Hi), (7..text.len(), crate::ProofLang::En)]); + assert!(issues.iter().any(|i| i.lang == crate::ProofLang::En && i.message.starts_with("Repeated word"))); + } +} diff --git a/crates/proof/src/hi/suggest.rs b/crates/proof/src/hi/suggest.rs new file mode 100644 index 0000000000..edadfb2d54 --- /dev/null +++ b/crates/proof/src/hi/suggest.rs @@ -0,0 +1,67 @@ +//! Hindi suggestions: the shared ranking ([`crate::affix_suggest`]) with the installed +//! dictionary's own MAP/REP/TRY/KEY tables and nothing Hindi hard-coded. + +use crate::affix::AffixDict; +use crate::affix_suggest::Tuning; + +/// Spelling suggestions for a Hindi word, best first, at most `max`. +pub fn suggest(word: &str, max: usize) -> Vec { + suggest_in(&super::dictionary(), word, max) +} + +/// [`suggest`] against a given dictionary. +pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec { + crate::affix_suggest::suggest_in(d, word, max, &Tuning::DEFAULT) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hindi_suggestions_use_runtime_tables() { + crate::hi::test_dict::install(); + // MAP (ि/ी, ं/ँ), REP (कश → क्ष) and a doubled letter. + for (word, want) in [("पानि", "पानी"), ("गांव", "गाँव"), ("परीकशण", "परीक्षण"), ("प्रेमम", "प्रेम"), ("किताबो", "किताबों")] { + let s = suggest(word, 8); + assert!(s.contains(&want.into()), "{word}: {s:?}"); + } + } + + #[test] + fn suggestions_stay_bounded_and_skip_forbidden_words() { + crate::hi::test_dict::install(); + for w in ["", "दो शब्द", &"क".repeat(41)] { + assert!(suggest(w, 4).is_empty()); + } + assert!(suggest("घर", 0).is_empty()); + assert!(suggest_in(&AffixDict::default(), "घर", 4).is_empty()); + for word in ["zqबहुतलंबाहिंदीशब्द", "किताबब", "परीक्षणण"] { + let res = suggest(word, 6); + assert!(res.len() <= 6, "{word}: got {} suggestions", res.len()); + assert!(!res.contains(&"zqप्रतिबंधित".to_string()), "{word}: {res:?}"); + assert!(res.iter().all(|s| !s.is_empty() && crate::hi::is_correct(s)), "{word}: {res:?}"); + } + } + + /// A NOSUGGEST stem stays correct spelling, but the Hindi collector never offers it or any + /// prefixed, suffixed or REP-reached form of it; ordinary stems are still offered. + #[test] + fn nosuggest_stems_and_forms_are_never_offered() { + let aff = "SET UTF-8\nNOSUGGEST N\nTRY गुप्तसामान्यअताएँ\nREP 2\nREP गुपत गुप्त\nREP सामानय सामान्य\nPFX X Y 1\nPFX X 0 अ .\nSFX A Y 1\nSFX A 0 ता/B .\nSFX B Y 1\nSFX B 0 एँ .\n"; + let d = AffixDict::from_hunspell(aff, "2\nगुप्त/NXA\nसामान्य/XA\n", &[]).unwrap(); + let hidden = d.forms("गुप्त"); + assert!(hidden.contains(&"अगुप्त".into()) && hidden.contains(&"गुप्तताएँ".into()), "{hidden:?}"); + for word in hidden.iter().chain(&["अगुप्तताएँ".to_string()]) { + assert!(d.check(word), "NOSUGGEST is still correct: {word}"); + assert!(!d.can_suggest(word), "NOSUGGEST form: {word}"); + } + for input in ["गुपत", "अगुपत", "गुपतता", "अगुपतताएँ", "गुप्तत", "अगुप्तताए"] { + let got = suggest_in(&d, input, 32); + assert!(got.iter().all(|w| w.split(' ').all(|part| d.can_suggest(part))), "{input}: {got:?}"); + assert!(got.iter().all(|w| !w.contains("गुप्त")), "{input}: {got:?}"); + } + assert!(suggest_in(&d, "सामानय", 8).contains(&"सामान्य".into())); + assert!(suggest_in(&d, "असामानयता", 8).contains(&"असामान्यता".into())); + } +} diff --git a/crates/proof/src/hi/test_dict.rs b/crates/proof/src/hi/test_dict.rs new file mode 100644 index 0000000000..bf0b128ea1 --- /dev/null +++ b/crates/proof/src/hi/test_dict.rs @@ -0,0 +1,47 @@ +//! Hand-written synthetic Hindi test data. No words, rules or suggestion tables were copied +//! from a system dictionary. This is a small fixture, not a redistributable Hindi dictionary. + +pub const AFF: &str = "SET UTF-8 +FLAG UTF-8 +FORBIDDENWORD F +TRY अआइईउऊऋएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलवशषसहािीुूृेैोौ्ंःँ +KEY सश|तद +MAP 4 +MAP इईिी +MAP उऊुू +MAP सशष +MAP ंँ +REP 1 +REP कश क्ष +SFX P Y 2 +SFX P ा े ा +SFX P ा ों ा +SFX O Y 1 +SFX O 0 ों . +SFX E Y 1 +SFX E 0 ें . +PFX X Y 1 +PFX X 0 अ . +"; + +pub const DIC: &str = "14 +घर/O +शहर/O +गाँव/O +मित्र/O +किताब/OE +कमरा/P +बच्चा/P +भाषा +पानी +परीक्षण +प्रेम +सूर्य +सफल/X +zqप्रतिबंधित/F +"; + +pub fn install() { + crate::hold_dictionary_tests(); + super::install_dictionary(AFF, DIC).unwrap(); +} diff --git a/crates/proof/src/lang.rs b/crates/proof/src/lang.rs index cb314c3a9f..193fc06073 100644 --- a/crates/proof/src/lang.rs +++ b/crates/proof/src/lang.rs @@ -74,6 +74,10 @@ pub enum ProofLang { /// one), dictionary-driven suggestions and generic checks with Gujarati messages. Hyphenation /// keeps the fallback patterns. Gu, + /// Hindi (`hi`, `hi-IN`, `hin`): the installed Hunspell dictionary (`hi_IN`, when there is + /// one), dictionary-driven suggestions and generic checks with Hindi messages + /// ([`crate::hi`]). Hyphenation keeps an installed pack's patterns, else the fallback. + Hi, /// German (`de`, `de-DE`, `de-AT`…; `de-CH` and `de-LI` are [`ProofLang::Pack`] `de-ch`, with /// their own dictionary and these patterns): hyphenation by the German patterns (reformed /// spelling), and spelling when a German Hunspell dictionary or `de` pack is found. No grammar @@ -94,7 +98,7 @@ pub enum ProofLang { impl ProofLang { /// Every language with a spelling dictionary, in display order. - pub const PROOFED: [ProofLang; 17] = [ + pub const PROOFED: [ProofLang; 18] = [ ProofLang::En, ProofLang::EnGb, ProofLang::EnAu, @@ -112,6 +116,7 @@ impl ProofLang { ProofLang::Es419, ProofLang::EsUy, ProofLang::Gu, + ProofLang::Hi, ]; /// The proofing language of a BCP 47 tag (`pl-PL`, `en_GB`, `PL`…). The primary subtag @@ -149,6 +154,8 @@ impl ProofLang { ProofLang::Id } else if primary.eq_ignore_ascii_case("gu") || primary.eq_ignore_ascii_case("guj") { ProofLang::Gu + } else if primary.eq_ignore_ascii_case("hi") || primary.eq_ignore_ascii_case("hin") { + ProofLang::Hi } else if primary.eq_ignore_ascii_case("es") || primary.eq_ignore_ascii_case("spa") { ProofLang::spanish(tag) } else if ["de", "deu", "ger"].iter().any(|c| primary.eq_ignore_ascii_case(c)) { @@ -233,6 +240,7 @@ impl ProofLang { ProofLang::Cs => "cs", ProofLang::Id => "id", ProofLang::Gu => "gu", + ProofLang::Hi => "hi", ProofLang::Es | ProofLang::EsMx | ProofLang::Es419 | ProofLang::EsUy => "es", ProofLang::De => "de", ProofLang::Other => "", diff --git a/crates/proof/src/languages.rs b/crates/proof/src/languages.rs index 12cf048489..e64e2cd77c 100644 --- a/crates/proof/src/languages.rs +++ b/crates/proof/src/languages.rs @@ -1,7 +1,7 @@ //! The table of languages proofed against Hunspell dictionaries, and the dictionary-folder and load-error API. use super::{ - DICTIONARY_GENERATION, EnglishSource, Issue, Options, Ordering, ProofLang, cs, english, es, gu, hr, hunspell, id, it, pack_lang, pl, pt, ru, + DICTIONARY_GENERATION, EnglishSource, Issue, Options, Ordering, ProofLang, cs, english, es, gu, hi, hr, hunspell, id, it, pack_lang, pl, pt, ru, slot, tr, }; @@ -21,7 +21,7 @@ pub(super) struct Language { /// Every language proofed against a Hunspell dictionary, in the order File › Options › Proofing /// lists them. English has a built-in word list and is handled apart. -pub(super) static LANGUAGES: [Language; 13] = [ +pub(super) static LANGUAGES: [Language; 14] = [ Language { lang: ProofLang::Pl, slot: &pl::DICT, @@ -96,6 +96,14 @@ pub(super) static LANGUAGES: [Language; 13] = [ suggest: |w, n, _| gu::suggest(w, n), grammar: |t, _, _| gu::grammar::check(t), }, + Language { + lang: ProofLang::Hi, + slot: &hi::DICT, + message: "संभावित वर्तनी त्रुटि", + is_correct: |w, _, o| hi::is_correct_with_options(w, o), + suggest: |w, n, _| hi::suggest(w, n), + grammar: |t, _, _| hi::grammar::check(t), + }, Language { lang: ProofLang::Es, slot: &es::SPAIN_DICT, diff --git a/crates/proof/src/lib.rs b/crates/proof/src/lib.rs index 07f01e32c1..6baae1809e 100644 --- a/crates/proof/src/lib.rs +++ b/crates/proof/src/lib.rs @@ -38,6 +38,10 @@ //! - **Gujarati** ([`ProofLang::Gu`], module [`gu`]): the installed Hunspell `gu_IN` //! dictionary (not bundled), dictionary-driven suggestions and generic checks with Gujarati //! messages. Hyphenation uses the existing English fallback. +//! - **Hindi** ([`ProofLang::Hi`], module [`hi`]): the installed Hunspell `hi_IN` dictionary +//! (not bundled), dictionary-driven suggestions and generic checks with Hindi messages, on the +//! Devanagari pieces of [`devanagari`] (letters, digits, both spellings of nukta letters). +//! Hyphenation uses an installed pack's patterns, else the existing English fallback. //! - **Spanish** ([`ProofLang::Es`], [`ProofLang::EsMx`], [`ProofLang::Es419`], [`ProofLang::EsUy`], //! module [`es`]): each variety's installed Hunspell dictionary (`es_ES`, `es_MX`, `es_419`, //! `es_UY`, with fallbacks; not bundled), dictionary-driven suggestions, Uruguayan `vos` forms, @@ -76,6 +80,7 @@ mod data { } pub mod bg; pub mod cs; +pub mod devanagari; pub mod dict; pub mod en_variants; mod english; @@ -83,6 +88,7 @@ pub mod es; pub mod fr; mod grammar_en; pub mod gu; +pub mod hi; pub mod hr; pub mod hunspell; pub mod hyphen; diff --git a/crates/proof/src/packs.rs b/crates/proof/src/packs.rs index a6bd525780..955982dcdf 100644 --- a/crates/proof/src/packs.rs +++ b/crates/proof/src/packs.rs @@ -540,6 +540,7 @@ fn hyphenation_locales(lang: ProofLang) -> Vec { ProofLang::Cs => &["cs"], ProofLang::Id => &["id"], ProofLang::Gu => &["gu-in", "gu"], + ProofLang::Hi => &["hi-in", "hi"], ProofLang::Es => &["es-es", "es"], ProofLang::EsMx => &["es-mx", "es-419", "es"], ProofLang::Es419 => &["es-419", "es"], diff --git a/crates/proof/src/tests.rs b/crates/proof/src/tests.rs index 76797d8c17..15f3c3c75f 100644 --- a/crates/proof/src/tests.rs +++ b/crates/proof/src/tests.rs @@ -14,6 +14,7 @@ fn write_test_dictionaries(dir: &std::path::Path) { ("cs_CZ", cs::test_dict::AFF, cs::test_dict::DIC), ("id_ID", id::test_dict::AFF, id::test_dict::DIC), ("gu_IN", gu::test_dict::AFF, gu::test_dict::DIC), + ("hi_IN", hi::test_dict::AFF, hi::test_dict::DIC), ("es_ES", es::test_dict::AFF, es::test_dict::DIC), ("es_MX", es::test_dict::AFF, es::test_dict::DIC_AMERICAS), ("es_419", es::test_dict::AFF, es::test_dict::DIC_AMERICAS), @@ -629,7 +630,7 @@ fn mixed_language_paragraphs_check_each_run_in_its_language() { proptest::proptest! { #[test] fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, 0u8..16), 0..6)) { - let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; + let langs = [ProofLang::En, ProofLang::EnGb, ProofLang::EnCa, ProofLang::Pl, ProofLang::Pt, ProofLang::It, ProofLang::Tr, ProofLang::Ru, ProofLang::Cs, ProofLang::Id, ProofLang::Gu, ProofLang::Hi, ProofLang::Es, ProofLang::EsMx, ProofLang::Es419, ProofLang::EsUy, ProofLang::Other]; let spans: Vec<(Range, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), langs[l as usize % langs.len()])).collect(); for i in check_text(&s, &spans) { proptest::prop_assert!(i.start <= i.end && i.end <= s.len());