mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
Merge remote-tracking branch 'upstream/main' into fw365-followup
This commit is contained in:
commit
dc02ffd6e2
36 files changed
+1836
-176
No files matched your search
@@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) ->
|
||||
let mut doc = Document::new();
|
||||
// Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default
|
||||
// 15 would apply Word 2013+ justification and line-breaking rules to them.
|
||||
doc.settings.compat_mode = 11;
|
||||
doc.settings.compat_mode = Some(11);
|
||||
if let Some(core) = metadata::read(&comp) {
|
||||
doc.core = core;
|
||||
}
|
||||
@@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u
|
||||
let content = word6::content(word, &fib)?;
|
||||
let mut doc = Document::new();
|
||||
// Word opens these files in compatibility mode 11 too.
|
||||
doc.settings.compat_mode = 11;
|
||||
doc.settings.compat_mode = Some(11);
|
||||
if let Some(core) = metadata::read(comp) {
|
||||
doc.core = core;
|
||||
}
|
||||
|
||||
@@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() {
|
||||
let doc = read(&f).expect("opens");
|
||||
// Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and
|
||||
// line breaking.
|
||||
assert_eq!(doc.settings.compat_mode, 11);
|
||||
assert_eq!(doc.settings.compat_mode, Some(11));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -254,7 +254,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize,
|
||||
lenient("numbering", r.read_numbering(&p));
|
||||
}
|
||||
// Without a stated mode (or settings at all) Word lays a document out as Word 2007 did.
|
||||
r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE;
|
||||
// Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308).
|
||||
r.doc.settings.compat_mode = None;
|
||||
if let Some(p) = part(rt::SETTINGS) {
|
||||
lenient("settings", r.read_settings(&p));
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ impl Reader<'_> {
|
||||
})
|
||||
.and_then(|c| c.attr("w:val"));
|
||||
if let Some(m) = mode.and_then(u32_of) {
|
||||
s.compat_mode = m.clamp(11, 99);
|
||||
s.compat_mode = Some(m.clamp(11, 99));
|
||||
}
|
||||
s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off);
|
||||
s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off);
|
||||
|
||||
@@ -49,6 +49,7 @@ const MAX_FORM: usize = 64 * 1024;
|
||||
pub struct RunCtx {
|
||||
link: Option<String>,
|
||||
link_tooltip: Option<std::sync::Arc<str>>,
|
||||
link_history: Option<craft_wordmodel::props::LinkHistory>,
|
||||
ins: Option<u32>,
|
||||
del: Option<u32>,
|
||||
}
|
||||
@@ -212,5 +213,5 @@ fn placeholder_of(s: &str) -> String {
|
||||
}
|
||||
|
||||
fn on_off_attr(e: &El, name: &str) -> bool {
|
||||
e.attr(name).is_some_and(|v| !matches!(v, "0" | "false" | "off"))
|
||||
e.attr(name).is_some_and(|v| !crate::units::is_off_val(v))
|
||||
}
|
||||
@@ -32,6 +32,12 @@ impl Reader<'_> {
|
||||
if let Some(link) = link {
|
||||
c.link = Some(link);
|
||||
c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from);
|
||||
// History on stays `None`: it is what the writer writes for a link with none.
|
||||
c.link_history = match k.attr("w:history") {
|
||||
Some(v) if crate::units::is_off_val(v) => Some(craft_wordmodel::props::LinkHistory::Off),
|
||||
Some(_) => None,
|
||||
None => Some(craft_wordmodel::props::LinkHistory::Omitted),
|
||||
};
|
||||
}
|
||||
self.read_inline_children(sc, pb, k, rels, &c, depth + 1);
|
||||
}
|
||||
@@ -138,6 +144,7 @@ impl Reader<'_> {
|
||||
let mut p = self.pc.rpr(rpr);
|
||||
p.link = ctx.link.clone();
|
||||
p.link_tooltip = ctx.link_tooltip.clone();
|
||||
p.link_history = ctx.link_history;
|
||||
p.ins = ctx.ins;
|
||||
p.del = ctx.del;
|
||||
p.fmt_change = self.rpr_change(rpr);
|
||||
@@ -145,7 +152,14 @@ impl Reader<'_> {
|
||||
}
|
||||
|
||||
fn run_props_none(&self, ctx: &RunCtx) -> CharProps {
|
||||
CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() }
|
||||
CharProps {
|
||||
link: ctx.link.clone(),
|
||||
link_tooltip: ctx.link_tooltip.clone(),
|
||||
link_history: ctx.link_history,
|
||||
ins: ctx.ins,
|
||||
del: ctx.del,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) {
|
||||
@@ -354,7 +368,7 @@ impl Reader<'_> {
|
||||
let (base, base_props) = part("w:rubyBase");
|
||||
let (ruby, ruby_props) = part("w:rt");
|
||||
let mut bp = base_props.unwrap_or_default();
|
||||
(bp.link, bp.ins, bp.del) = (props.link.clone(), props.ins, props.del);
|
||||
(bp.link, bp.link_history, bp.ins, bp.del) = (props.link.clone(), props.link_history, props.ins, props.del);
|
||||
if base.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -141,11 +141,16 @@ pub fn tw_u16(e: &El, attr: &str) -> Option<f32> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return whether an XML attribute value for an `ST_OnOff` represents "off" / false.
|
||||
pub fn is_off_val(v: &str) -> bool {
|
||||
matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE")
|
||||
}
|
||||
|
||||
/// ST_OnOff: absent `w:val` = on; `0`, `false`, `off` = off.
|
||||
pub fn on_off(e: &El) -> bool {
|
||||
match e.attr("w:val") {
|
||||
None => true,
|
||||
Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"),
|
||||
Some(v) => !is_off_val(v),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,13 @@ fn write_note_settings(
|
||||
}
|
||||
|
||||
fn write_compatibility_settings(w: &mut W, doc: &Document) {
|
||||
let has_compat = doc.settings.do_not_expand_shift_return
|
||||
|| doc.settings.sum_paragraph_spacing
|
||||
|| doc.settings.allow_space_of_same_style_in_table
|
||||
|| doc.settings.compat_mode.is_some();
|
||||
if !has_compat {
|
||||
return;
|
||||
}
|
||||
w.open("w:compat", &[]);
|
||||
// CT_Compat: the older switches come before the `w:compatSetting`s.
|
||||
if doc.settings.do_not_expand_shift_return {
|
||||
@@ -162,8 +169,10 @@ fn write_compatibility_settings(w: &mut W, doc: &Document) {
|
||||
if doc.settings.allow_space_of_same_style_in_table {
|
||||
w.empty("w:allowSpaceOfSameStyleInTable", &[]);
|
||||
}
|
||||
let mode = doc.settings.compat_mode.clamp(11, 15).to_string();
|
||||
w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]);
|
||||
if let Some(mode) = doc.settings.compat_mode {
|
||||
let mode = mode.clamp(11, 15).to_string();
|
||||
w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]);
|
||||
}
|
||||
w.close("w:compat");
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! tag (namespace declarations, `mc:Ignorable`) and every child the model doesn't own are kept
|
||||
//! byte for byte; owned children come from the generated part (or go, when the model turned
|
||||
//! them off); owned children the original lacks are inserted at their CT_Settings position; in
|
||||
//! `w:compat` only the `compatibilityMode` setting is replaced. Kept children that refer to a
|
||||
//! `w:compat` only the switches the model writes and the `compatibilityMode` setting come from the
|
||||
//! generated part, and a block left empty goes. Kept children that refer to a
|
||||
//! relationship are dropped unless owned: mail merge is regenerated with remapped external
|
||||
//! sources by `mail_merge`. Anything unexpected returns `None`, and the generated part is written as before.
|
||||
|
||||
@@ -232,29 +233,125 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec<Child>)> {
|
||||
Some((open_end, close, out))
|
||||
}
|
||||
|
||||
/// The original `w:compat` with its `compatibilityMode` taken from the generated one.
|
||||
/// The `w:compat` switches the model writes (`super::settings`).
|
||||
const OWNED_COMPAT_SWITCHES: &[&str] = &["w:doNotExpandShiftReturn", "w:doNotUseHTMLParagraphAutoSpacing", "w:allowSpaceOfSameStyleInTable"];
|
||||
|
||||
/// CT_Compat's sequence (ECMA-376 §17.15.3.9), for placing inserted switches.
|
||||
const CT_COMPAT_ORDER: &[&str] = &[
|
||||
"useSingleBorderforContiguousCells",
|
||||
"wpJustification",
|
||||
"noTabHangInd",
|
||||
"noLeading",
|
||||
"spaceForUL",
|
||||
"noColumnBalance",
|
||||
"balanceSingleByteDoubleByteWidth",
|
||||
"noExtraLineSpacing",
|
||||
"doNotLeaveBackslashAlone",
|
||||
"ulTrailSpace",
|
||||
"doNotExpandShiftReturn",
|
||||
"spacingInWholePoints",
|
||||
"lineWrapLikeWord6",
|
||||
"printBodyTextBeforeHeader",
|
||||
"printColBlack",
|
||||
"wpSpaceWidth",
|
||||
"showBreaksInFrames",
|
||||
"subFontBySize",
|
||||
"suppressBottomSpacing",
|
||||
"suppressTopSpacing",
|
||||
"suppressSpacingAtTopOfPage",
|
||||
"suppressTopSpacingWP",
|
||||
"suppressSpBfAfterPgBrk",
|
||||
"swapBordersFacingPages",
|
||||
"convMailMergeEsc",
|
||||
"truncateFontHeightsLikeWP6",
|
||||
"mwSmallCaps",
|
||||
"usePrinterMetrics",
|
||||
"doNotSuppressParagraphBorders",
|
||||
"wrapTrailSpaces",
|
||||
"footnoteLayoutLikeWW8",
|
||||
"shapeLayoutLikeWW8",
|
||||
"alignTablesRowByRow",
|
||||
"forgetLastTabAlignment",
|
||||
"adjustLineHeightInTable",
|
||||
"autoSpaceLikeWord95",
|
||||
"noSpaceRaiseLower",
|
||||
"doNotUseHTMLParagraphAutoSpacing",
|
||||
"layoutRawTableWidth",
|
||||
"layoutTableRowsApart",
|
||||
"useWord97LineBreakRules",
|
||||
"doNotBreakWrappedTables",
|
||||
"doNotSnapToGridInCell",
|
||||
"selectFldWithFirstOrLastChar",
|
||||
"applyBreakingRules",
|
||||
"doNotWrapTextWithPunct",
|
||||
"doNotUseEastAsianBreakRules",
|
||||
"useWord2002TableStyleRules",
|
||||
"growAutofit",
|
||||
"useFELayout",
|
||||
"useNormalStyleForList",
|
||||
"doNotUseIndentAsNumberingTabStop",
|
||||
"useAltKinsokuLineBreakRules",
|
||||
"allowSpaceOfSameStyleInTable",
|
||||
"doNotSuppressIndentation",
|
||||
"doNotAutofitConstrainedTables",
|
||||
"autofitToFirstFixedWidthCell",
|
||||
"underlineTabInNumList",
|
||||
"displayHangulFixedWidth",
|
||||
"splitPgBreakAndParaMark",
|
||||
"doNotVertAlignCellWithSp",
|
||||
"doNotBreakConstrainedForcedTable",
|
||||
"doNotVertAlignInTxbx",
|
||||
"useAnsiKerningPairs",
|
||||
"cachedColBalance",
|
||||
"compatSetting",
|
||||
];
|
||||
|
||||
/// Position of a `w:`-prefixed `w:compat` child in [`CT_COMPAT_ORDER`]; `None` for anything else.
|
||||
fn compat_rank(name: &str) -> Option<usize> {
|
||||
let local = name.strip_prefix("w:")?;
|
||||
CT_COMPAT_ORDER.iter().position(|n| *n == local)
|
||||
}
|
||||
|
||||
/// Is this `w:compat` child Word's `compatibilityMode` setting?
|
||||
fn is_compat_mode(child: &str) -> bool {
|
||||
let mut reader = quick_xml::Reader::from_str(child);
|
||||
let Ok(quick_xml::events::Event::Start(e) | quick_xml::events::Event::Empty(e)) = reader.read_event() else { return false };
|
||||
e.name().as_ref() == b"w:compatSetting"
|
||||
&& e.attributes().with_checks(false).flatten().any(|a| a.key.as_ref() == b"w:name" && a.value.as_ref() == b"compatibilityMode")
|
||||
}
|
||||
|
||||
/// The original `w:compat` with what the model owns in it taken from the generated one (`""`
|
||||
/// when the model writes none): its switches, and the `compatibilityMode` setting. A block left
|
||||
/// without children goes (`""`).
|
||||
fn merge_compat(orig: &str, generated: &str) -> Option<String> {
|
||||
let mode = |s: &str| -> Option<(usize, usize)> {
|
||||
let at = s.find("w:name=\"compatibilityMode\"")?;
|
||||
let tag_start = s.get(..at)?.rfind('<')?;
|
||||
let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1;
|
||||
Some((tag_start, tag_end))
|
||||
let g_kids = children(generated, "w:compat").map(|(_, _, kids)| kids).unwrap_or_default();
|
||||
let g_child = |pred: &dyn Fn(&Child, &str) -> bool| g_kids.iter().find_map(|k| generated.get(k.start..k.end).filter(|text| pred(k, text)));
|
||||
let mut out = match orig.strip_suffix("/>") {
|
||||
Some(open) => format!("{}></w:compat>", open.trim_end()),
|
||||
None => orig.to_string(),
|
||||
};
|
||||
match (mode(orig), mode(generated)) {
|
||||
(Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)),
|
||||
(None, Some((c, d))) => {
|
||||
// No mode in the original: add the generated one before `</w:compat>`, or expand a self-closing `<w:compat/>`.
|
||||
if let Some(close) = orig.rfind("</w:compat>") {
|
||||
Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?))
|
||||
} else if let Some(slash) = orig.rfind("/>") {
|
||||
let open = orig.get(..slash)?.trim_end();
|
||||
Some(format!("{open}>{}</w:compat>", generated.get(c..d)?))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
for sw in OWNED_COMPAT_SWITCHES {
|
||||
let (_, _, kids) = children(&out, "w:compat")?;
|
||||
for k in kids.iter().rev().filter(|k| k.name == *sw) {
|
||||
out.replace_range(k.start..k.end, "");
|
||||
}
|
||||
if let Some(g) = g_child(&|k, _| k.name == *sw) {
|
||||
let (_, close, kids) = children(&out, "w:compat")?;
|
||||
let rank = compat_rank(sw);
|
||||
let at = kids.iter().find(|k| compat_rank(&k.name) > rank).map_or(close, |k| k.start);
|
||||
out.insert_str(at, g);
|
||||
}
|
||||
_ => Some(orig.to_string()),
|
||||
}
|
||||
let (_, close, kids) = children(&out, "w:compat")?;
|
||||
let o_mode = kids.iter().find(|k| out.get(k.start..k.end).is_some_and(is_compat_mode)).map(|k| k.start..k.end);
|
||||
match (o_mode, g_child(&|_, text| is_compat_mode(text))) {
|
||||
(Some(span), Some(g)) => out.replace_range(span, g),
|
||||
(Some(span), None) => out.replace_range(span, ""),
|
||||
(None, Some(g)) => out.insert_str(close, g),
|
||||
(None, None) => {}
|
||||
}
|
||||
let (_, _, kids) = children(&out, "w:compat")?;
|
||||
Some(if kids.is_empty() { String::new() } else { out })
|
||||
}
|
||||
|
||||
/// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps
|
||||
@@ -358,11 +455,11 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option<Vec<u8>> {
|
||||
out.push((k.name.clone(), g_text(g_kids.get(gi)?)?));
|
||||
}
|
||||
} else if k.name == "w:compat" {
|
||||
let merged = match mark("w:compat", &mut used) {
|
||||
Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?,
|
||||
None => text.to_string(),
|
||||
};
|
||||
out.push((k.name.clone(), merged));
|
||||
let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?));
|
||||
let merged = merge_compat(text, g_compat.as_deref().unwrap_or(""))?;
|
||||
if !merged.is_empty() {
|
||||
out.push((k.name.clone(), merged));
|
||||
}
|
||||
} else if !text.contains("r:id=") {
|
||||
out.push((k.name.clone(), text.to_string()));
|
||||
}
|
||||
@@ -475,4 +572,95 @@ mod tests {
|
||||
// A file whose only extra setting is this one has nothing foreign to keep.
|
||||
assert!(!has_unowned(br#"<w:settings xmlns:w="w"><w:zoom w:percent="100"/><w:gutterAtTop/></w:settings>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compatibility_mode_removal_handles_paired_tags_quotes_and_whitespace() {
|
||||
let gen_no_mode = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:zoom w:percent="100"/></w:settings>"#;
|
||||
|
||||
// Paired tag with closing </w:compatSetting>
|
||||
let orig_paired = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"></w:compatSetting><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat></w:settings>"#;
|
||||
assert!(has_unowned(orig_paired.as_bytes()));
|
||||
let out_paired = String::from_utf8(merge(orig_paired.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap();
|
||||
assert!(!out_paired.contains("compatibilityMode"), "{out_paired}");
|
||||
assert!(!out_paired.contains("</w:compatSetting>"), "{out_paired}");
|
||||
assert!(out_paired.contains("overrideTableStyleFontSizeAndJustification"), "{out_paired}");
|
||||
|
||||
// Single quotes
|
||||
let orig_single_quotes = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:compatSetting w:name='compatibilityMode' w:uri='http://schemas.microsoft.com/office/word' w:val='15'/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:val="1"/></w:compat></w:settings>"#;
|
||||
let out_sq = String::from_utf8(merge(orig_single_quotes.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap();
|
||||
assert!(!out_sq.contains("compatibilityMode"), "{out_sq}");
|
||||
assert!(out_sq.contains("overrideTableStyleFontSizeAndJustification"), "{out_sq}");
|
||||
|
||||
// Whitespace around equals
|
||||
let orig_spaces = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:compatSetting w:name = "compatibilityMode" w:uri = "http://schemas.microsoft.com/office/word" w:val = "15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:val="1"/></w:compat></w:settings>"#;
|
||||
let out_sp = String::from_utf8(merge(orig_spaces.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap();
|
||||
assert!(!out_sp.contains("compatibilityMode"), "{out_sp}");
|
||||
assert!(out_sp.contains("overrideTableStyleFontSizeAndJustification"), "{out_sp}");
|
||||
|
||||
// Foreign vendor compatSetting element is preserved
|
||||
let orig_foreign = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="m" xmlns:r="r" xmlns:x="urn:vendor"><w:compat><x:compatSetting x:name="compatibilityMode" x:uri="urn:vendor" x:val="1"/><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat></w:settings>"#;
|
||||
let gen_foreign =
|
||||
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:zoom w:percent="100"/></w:settings>"#;
|
||||
let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap();
|
||||
assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}");
|
||||
assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_compat_switches_are_all_removed_when_disabled_and_deduplicated_when_enabled() {
|
||||
let orig_two = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/><w:useFELayout/><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
|
||||
// Disabled in generated: both must be removed
|
||||
let gen_disabled =
|
||||
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:zoom w:percent="100"/></w:settings>"#;
|
||||
let out_disabled = String::from_utf8(merge(orig_two.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap();
|
||||
assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}");
|
||||
assert!(out_disabled.contains("<w:useFELayout/>"), "{out_disabled}");
|
||||
|
||||
// Enabled in generated: exactly one occurrence emitted
|
||||
let gen_enabled = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
|
||||
let out_enabled = String::from_utf8(merge(orig_two.as_bytes(), gen_enabled.as_bytes()).unwrap()).unwrap();
|
||||
assert_eq!(out_enabled.matches("doNotExpandShiftReturn").count(), 1, "{out_enabled}");
|
||||
assert!(out_enabled.contains("<w:useFELayout/>"), "{out_enabled}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_compat_switches_are_inserted_in_schema_order() {
|
||||
// spacingInWholePoints is ranked after doNotExpandShiftReturn in CT_Compat
|
||||
let orig = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:spacingInWholePoints/></w:compat></w:settings>"#;
|
||||
let gen_xml = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
|
||||
let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap();
|
||||
let idx_shift = merged.find("<w:doNotExpandShiftReturn/>").unwrap();
|
||||
let idx_spacing = merged.find("<w:spacingInWholePoints/>").unwrap();
|
||||
assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_child_is_ignored_when_finding_switch_insertion_point() {
|
||||
// x:spacingInWholePoints precedes w:ulTrailSpace
|
||||
let orig = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:x="urn:vendor"><w:compat><x:spacingInWholePoints/><w:ulTrailSpace/><w:spacingInWholePoints/></w:compat></w:settings>"#;
|
||||
let gen_xml = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
|
||||
let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap();
|
||||
let idx_custom = merged.find("<x:spacingInWholePoints/>").unwrap();
|
||||
let idx_trail = merged.find("<w:ulTrailSpace/>").unwrap();
|
||||
let idx_shift = merged.find("<w:doNotExpandShiftReturn/>").unwrap();
|
||||
let idx_spacing = merged.find("<w:spacingInWholePoints/>").unwrap();
|
||||
assert!(idx_custom < idx_trail, "custom before trail: {merged}");
|
||||
assert!(idx_trail < idx_shift, "trail before shift: {merged}");
|
||||
assert!(idx_shift < idx_spacing, "shift before spacing: {merged}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() {
|
||||
let gen_xml = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:zoom w:percent="100"/></w:settings>"#;
|
||||
let merged_with = |compat: &str| {
|
||||
let orig = format!(
|
||||
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{compat}<w:rsids><w:rsidRoot w:val="00112233"/></w:rsids></w:settings>"#
|
||||
);
|
||||
String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap()
|
||||
};
|
||||
let self_closing = merged_with("<w:compat/>");
|
||||
assert!(!self_closing.contains("compat"), "{self_closing}");
|
||||
assert!(self_closing.contains(r#"<w:rsidRoot w:val="00112233"/>"#), "{self_closing}");
|
||||
assert_eq!(self_closing, merged_with("<w:compat></w:compat>"));
|
||||
}
|
||||
}
|
||||
@@ -210,17 +210,24 @@ impl Writer<'_> {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// Hyperlinks with different ScreenTips stay separate even if their target is shared.
|
||||
let link = props
|
||||
.link
|
||||
.as_deref()
|
||||
.filter(|target| !target.is_empty())
|
||||
.map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip)));
|
||||
// Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared.
|
||||
let base = link_target_and_tip;
|
||||
// Text with no history of its own (typed into a link) takes the history of the link it
|
||||
// is in: the open one, or else the first of the following text in the same link that has one.
|
||||
let link = base(props).map(|(target, tip)| {
|
||||
let history = match open_link {
|
||||
Some((open_target, open_tip, open_history)) if (open_target, open_tip) == (target, tip) => props.link_history.or(open_history),
|
||||
_ => props.link_history.or_else(|| {
|
||||
pieces.iter().skip(i + 1).map(|(_, p)| *p).take_while(|p| base(p) == Some((target, tip))).find_map(|p| p.link_history)
|
||||
}),
|
||||
};
|
||||
(target, tip, history)
|
||||
});
|
||||
if link != open_link {
|
||||
if open_link.is_some() {
|
||||
w.close("w:hyperlink");
|
||||
}
|
||||
if let Some((link, tip)) = link {
|
||||
if let Some((link, tip, hist)) = link {
|
||||
let id;
|
||||
let target = if let Some(anchor) = link.strip_prefix('#') {
|
||||
("w:anchor", anchor)
|
||||
@@ -228,11 +235,19 @@ impl Writer<'_> {
|
||||
id = rels.add(rt::HYPERLINK, link, true);
|
||||
("r:id", id.as_str())
|
||||
};
|
||||
if let Some(tip) = tip {
|
||||
w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]);
|
||||
} else {
|
||||
w.open("w:hyperlink", &[target, ("w:history", "1")]);
|
||||
let mut attrs = [("", ""); 3];
|
||||
let mut n = 0;
|
||||
attrs[n] = target;
|
||||
n += 1;
|
||||
if let Some(h) = link_history_val(hist) {
|
||||
attrs[n] = ("w:history", h);
|
||||
n += 1;
|
||||
}
|
||||
if let Some(tip) = tip {
|
||||
attrs[n] = ("w:tooltip", tip);
|
||||
n += 1;
|
||||
}
|
||||
w.open("w:hyperlink", &attrs[..n]);
|
||||
}
|
||||
open_link = link;
|
||||
}
|
||||
@@ -355,3 +370,19 @@ impl Writer<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run's hyperlink target and the ScreenTip it is written with, or `None` outside a link.
|
||||
fn link_target_and_tip(p: &CharProps) -> Option<(&str, Option<&str>)> {
|
||||
p.link.as_deref().filter(|target| !target.is_empty()).map(|target| (target, p.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip)))
|
||||
}
|
||||
|
||||
/// The `w:history` value a hyperlink is written with: off or none when a .docx file gave that,
|
||||
/// otherwise on, as Word writes it for a new link.
|
||||
fn link_history_val(history: Option<craft_wordmodel::props::LinkHistory>) -> Option<&'static str> {
|
||||
use craft_wordmodel::props::LinkHistory;
|
||||
match history {
|
||||
None => Some("1"),
|
||||
Some(LinkHistory::Off) => Some("0"),
|
||||
Some(LinkHistory::Omitted) => None,
|
||||
}
|
||||
}
|
||||
@@ -1280,17 +1280,17 @@ fn compatibility_mode_is_read_and_defaults_to_word_2007() {
|
||||
let compat = |v: &str| {
|
||||
format!(r#"<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="{v}"/></w:compat>"#)
|
||||
};
|
||||
assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, 15);
|
||||
assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, 14);
|
||||
assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, Some(15));
|
||||
assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, Some(14));
|
||||
// Unnamed, out of range or junk values.
|
||||
assert_eq!(with_settings(Some("<w:compat/>")).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
assert_eq!(with_settings(None).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, 11);
|
||||
assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, 99);
|
||||
assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
assert_eq!(with_settings(Some("<w:compat/>")).settings.compat_mode, None);
|
||||
assert_eq!(with_settings(None).settings.compat_mode, None);
|
||||
assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, Some(11));
|
||||
assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, Some(99));
|
||||
assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, None);
|
||||
// Another vendor's setting of the same name is ignored.
|
||||
let other = r#"<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="urn:example" w:val="15"/></w:compat>"#;
|
||||
assert_eq!(with_settings(Some(other)).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
assert_eq!(with_settings(Some(other)).settings.compat_mode, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1458,7 +1458,9 @@ fn anchor_stacking_order_is_read_and_kept() {
|
||||
|
||||
#[test]
|
||||
fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() {
|
||||
assert_eq!(read_body("<w:p/>").settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
let d = read_body("<w:p/>");
|
||||
assert_eq!(d.settings.compat_mode, None);
|
||||
assert_eq!(d.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -143,6 +143,7 @@ fn every_char_prop_round_trips() {
|
||||
}),
|
||||
link: None,
|
||||
link_tooltip: None,
|
||||
link_history: None,
|
||||
ins: None,
|
||||
del: None,
|
||||
fmt_change: None,
|
||||
@@ -1564,11 +1565,11 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
|
||||
for mode in [11, 12, 14, 15] {
|
||||
for allow in [false, true] {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = mode;
|
||||
d.settings.compat_mode = Some(mode);
|
||||
d.settings.allow_space_of_same_style_in_table = allow;
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.settings.allow_space_of_same_style_in_table, allow);
|
||||
assert_eq!(r.settings.compat_mode, mode);
|
||||
assert_eq!(r.settings.compat_mode, Some(mode));
|
||||
if allow {
|
||||
let bytes = craft_docx::write(&d).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
@@ -1585,14 +1586,165 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
|
||||
fn compatibility_mode_round_trips() {
|
||||
// New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't
|
||||
// change how Word lays it out.
|
||||
assert_eq!(rt(&Document::new()).settings.compat_mode, craft_wordmodel::COMPAT_MODE_CURRENT);
|
||||
assert_eq!(rt(&Document::new()).settings.compat_mode, Some(craft_wordmodel::COMPAT_MODE_CURRENT));
|
||||
for mode in [11, 12, 14, 15] {
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = mode;
|
||||
assert_eq!(rt(&d).settings.compat_mode, mode);
|
||||
d.settings.compat_mode = Some(mode);
|
||||
assert_eq!(rt(&d).settings.compat_mode, Some(mode));
|
||||
}
|
||||
}
|
||||
|
||||
/// #3308: A document without `<w:compat>` or without `<w:compatSetting w:name="compatibilityMode">`
|
||||
/// round-trips without synthesizing the tag on save.
|
||||
#[test]
|
||||
fn compatibility_mode_omitted_round_trips_without_synthesizing() {
|
||||
let settings_xml_of = |bytes: &[u8]| {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
match zip.by_name("word/settings.xml") {
|
||||
Ok(mut file) => {
|
||||
std::io::Read::read_to_string(&mut file, &mut xml).unwrap();
|
||||
Some(xml)
|
||||
}
|
||||
Err(zip::result::ZipError::FileNotFound) => None,
|
||||
Err(e) => panic!("zip error: {e:?}"),
|
||||
}
|
||||
};
|
||||
|
||||
// Case 1: settings.xml without `<w:compat>` at all.
|
||||
let base_docx = craft_docx::write(&Document::new()).unwrap();
|
||||
let original_settings = settings_xml_of(&base_docx).unwrap();
|
||||
let without_compat = original_settings.replace(
|
||||
"<w:compat><w:compatSetting w:name=\"compatibilityMode\" w:uri=\"http://schemas.microsoft.com/office/word\" w:val=\"15\"/></w:compat>",
|
||||
"",
|
||||
);
|
||||
assert_ne!(original_settings, without_compat);
|
||||
let docx_without_compat = replace_part(&base_docx, "word/settings.xml", without_compat.as_bytes());
|
||||
|
||||
let doc = craft_docx::read(&docx_without_compat).unwrap();
|
||||
assert_eq!(doc.settings.compat_mode, None);
|
||||
assert_eq!(doc.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE);
|
||||
|
||||
let saved_bytes = craft_docx::write(&doc).unwrap();
|
||||
let saved_settings = settings_xml_of(&saved_bytes).unwrap();
|
||||
assert!(!saved_settings.contains("<w:compat"), "expected no <w:compat>, got: {saved_settings}");
|
||||
assert!(!saved_settings.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings}");
|
||||
|
||||
let read_back = craft_docx::read(&saved_bytes).unwrap();
|
||||
assert_eq!(read_back.settings.compat_mode, None);
|
||||
|
||||
// Case 2: settings.xml with `<w:compat>` but without `<w:compatSetting w:name="compatibilityMode">`
|
||||
// (e.g. only legacy compatibility flags like `<w:doNotExpandShiftReturn/>`).
|
||||
let with_other_compat = original_settings.replace(
|
||||
"<w:compatSetting w:name=\"compatibilityMode\" w:uri=\"http://schemas.microsoft.com/office/word\" w:val=\"15\"/>",
|
||||
"<w:doNotExpandShiftReturn/>",
|
||||
);
|
||||
assert_ne!(original_settings, with_other_compat);
|
||||
let docx_with_other = replace_part(&base_docx, "word/settings.xml", with_other_compat.as_bytes());
|
||||
|
||||
let doc2 = craft_docx::read(&docx_with_other).unwrap();
|
||||
assert_eq!(doc2.settings.compat_mode, None);
|
||||
assert!(doc2.settings.do_not_expand_shift_return);
|
||||
|
||||
let saved_bytes2 = craft_docx::write(&doc2).unwrap();
|
||||
let saved_settings2 = settings_xml_of(&saved_bytes2).unwrap();
|
||||
assert!(saved_settings2.contains("<w:compat>"), "expected <w:compat>, got: {saved_settings2}");
|
||||
assert!(saved_settings2.contains("<w:doNotExpandShiftReturn/>"), "expected doNotExpandShiftReturn, got: {saved_settings2}");
|
||||
assert!(!saved_settings2.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings2}");
|
||||
|
||||
let read_back2 = craft_docx::read(&saved_bytes2).unwrap();
|
||||
assert_eq!(read_back2.settings.compat_mode, None);
|
||||
assert!(read_back2.settings.do_not_expand_shift_return);
|
||||
}
|
||||
|
||||
/// #3305: a hyperlink keeps the `w:history` a .docx file gave it (on, off or none), and a link
|
||||
/// with no value, as one made in the app has, is written with history on and reads back the same.
|
||||
#[test]
|
||||
fn hyperlink_history_attribute_preservation_round_trips() {
|
||||
use craft_wordmodel::props::LinkHistory;
|
||||
let doc_xml_of = |bytes: &[u8]| {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
xml
|
||||
};
|
||||
|
||||
// 1. Each model value is written as the matching attribute and read back as it.
|
||||
for (history, written) in [(None, Some("1")), (Some(LinkHistory::Off), Some("0")), (Some(LinkHistory::Omitted), None)] {
|
||||
let mut p = Paragraph::new();
|
||||
p.insert_text(0, "link", &CharProps { link: Some("https://example.com/".into()), link_history: history, ..Default::default() }).unwrap();
|
||||
let bytes = craft_docx::write(&doc_with(vec![p])).unwrap();
|
||||
let xml = doc_xml_of(&bytes);
|
||||
assert!(xml.contains("<w:hyperlink "), "{xml}");
|
||||
match written {
|
||||
Some(v) => assert!(xml.contains(&format!(r#"w:history="{v}""#)), "{history:?}: {xml}"),
|
||||
None => assert!(!xml.contains("w:history"), "{history:?}: {xml}"),
|
||||
}
|
||||
let read = craft_docx::read(&bytes).unwrap();
|
||||
assert_eq!(paras(&read)[0].props_of_char(0).link_history, history);
|
||||
}
|
||||
let mut p_one = Paragraph::new();
|
||||
p_one
|
||||
.insert_text(
|
||||
0,
|
||||
"link with history 1",
|
||||
&CharProps { link: Some("https://example.com/hist-one".into()), link_history: None, ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
let d_one = doc_with(vec![p_one]);
|
||||
|
||||
// 2. Original XML fixture round-trip:
|
||||
// Verify that reading raw XML with omitted w:history and w:history="0" saves back identically.
|
||||
let base = craft_docx::write(&d_one).unwrap();
|
||||
// Replace the hyperlink in document.xml to have NO w:history attribute
|
||||
let orig_doc_xml = doc_xml_of(&base);
|
||||
let xml_omitted_hist = orig_doc_xml.replace(r#" w:history="1""#, "");
|
||||
assert_ne!(orig_doc_xml, xml_omitted_hist);
|
||||
let file_omitted = replace_part(&base, "word/document.xml", xml_omitted_hist.as_bytes());
|
||||
|
||||
let read_omitted = craft_docx::read(&file_omitted).unwrap();
|
||||
assert_eq!(paras(&read_omitted)[0].props_of_char(0).link_history, Some(LinkHistory::Omitted));
|
||||
let saved_omitted = craft_docx::write(&read_omitted).unwrap();
|
||||
let resaved_xml = doc_xml_of(&saved_omitted);
|
||||
assert!(!resaved_xml.contains("w:history"), "expected no w:history on save, got: {resaved_xml}");
|
||||
|
||||
// Replace the hyperlink in document.xml to have w:history="0"
|
||||
let xml_zero_hist = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history="0""#);
|
||||
assert_ne!(orig_doc_xml, xml_zero_hist);
|
||||
let file_zero = replace_part(&base, "word/document.xml", xml_zero_hist.as_bytes());
|
||||
|
||||
let read_zero = craft_docx::read(&file_zero).unwrap();
|
||||
assert_eq!(paras(&read_zero)[0].props_of_char(0).link_history, Some(LinkHistory::Off));
|
||||
let saved_zero = craft_docx::write(&read_zero).unwrap();
|
||||
let resaved_zero_xml = doc_xml_of(&saved_zero);
|
||||
assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}");
|
||||
|
||||
// Replace the hyperlink in document.xml to have w:history=" 0 " (whitespace-padded false)
|
||||
let xml_padded_zero = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history=" 0 ""#);
|
||||
assert_ne!(orig_doc_xml, xml_padded_zero);
|
||||
let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes());
|
||||
|
||||
let read_padded = craft_docx::read(&file_padded).unwrap();
|
||||
assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(LinkHistory::Off));
|
||||
let saved_padded = craft_docx::write(&read_padded).unwrap();
|
||||
let resaved_padded_xml = doc_xml_of(&saved_padded);
|
||||
assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}");
|
||||
}
|
||||
|
||||
/// #3305: a link the app makes, by laying a `CharProps` patch with a target over text, saves with
|
||||
/// history on, as it did before `w:history` was kept from .docx files.
|
||||
#[test]
|
||||
fn a_link_made_with_a_char_props_patch_saves_with_history_on() {
|
||||
let mut p = Paragraph::with_text("see the site", CharProps::default());
|
||||
let patch = CharProps { link: Some("https://example.com/".into()), ..Default::default() };
|
||||
p.format(4, 12, &|c| c.overlay(&patch)).unwrap();
|
||||
let bytes = craft_docx::write(&doc_with(vec![p])).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
assert!(xml.contains("<w:hyperlink ") && xml.contains(r#"w:history="1""#), "{xml}");
|
||||
}
|
||||
|
||||
/// Tools › Templates and Add-ins: the attached template (an external relationship of the settings
|
||||
/// part) and "Automatically update document styles" (`w:linkStyles`) round-trip, written in the
|
||||
/// schema's order (after `w:mirrorMargins`, before `w:trackRevisions`).
|
||||
|
||||
@@ -205,6 +205,39 @@ fn do_not_track_moves_round_trips() {
|
||||
assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleared_compatibility_mode_removes_it_from_merged_settings() {
|
||||
let mut doc = craft_docx::read(&with_settings(SETTINGS)).unwrap();
|
||||
assert_eq!(doc.settings.compat_mode, Some(15));
|
||||
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
|
||||
|
||||
// Case 1: compat_mode is set to None, and no other compat switch is enabled.
|
||||
doc.settings.compat_mode = None;
|
||||
let files = save(&doc);
|
||||
let s = text(&files, "word/settings.xml");
|
||||
assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}");
|
||||
assert!(s.contains("<w:compat>"), "expected w:compat preserved for unowned settings: {s}");
|
||||
assert!(s.contains("overrideTableStyleFontSizeAndJustification"), "{s}");
|
||||
assert!(s.contains("enableOpenTypeFeatures"), "{s}");
|
||||
|
||||
let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(reopened.settings.compat_mode, None);
|
||||
|
||||
// Case 2: compat_mode is set to None, but another switch is enabled.
|
||||
doc.settings.do_not_expand_shift_return = true;
|
||||
let files2 = save(&doc);
|
||||
let s2 = text(&files2, "word/settings.xml");
|
||||
assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}");
|
||||
assert!(s2.contains("<w:compat>"), "{s2}");
|
||||
assert!(s2.contains("<w:doNotExpandShiftReturn/>"), "expected switch preserved: {s2}");
|
||||
assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}");
|
||||
assert!(s2.contains("enableOpenTypeFeatures"), "{s2}");
|
||||
|
||||
let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert_eq!(reopened2.settings.compat_mode, None);
|
||||
assert!(reopened2.settings.do_not_expand_shift_return);
|
||||
}
|
||||
|
||||
/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`,
|
||||
/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged
|
||||
/// part), written in a generated part, and left out when they are turned off.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! [`GlyphsPanel`]: Photoshop's Glyphs panel. A family and style picker, a category list (Entire Font, Punctuation,
|
||||
//! Currency, ...), a grid of glyph cells drawn by the app's text engine, a zoom slider, and the recently used
|
||||
//! glyphs in a row at the top. Double-click or Enter inserts the glyph where the app can insert.
|
||||
//! A secondary click on a grid cell reports that cell ([`GlyphsPanelOutput::menu`]); the app opens
|
||||
//! the menu from the grid response.
|
||||
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) mod stories;
|
||||
@@ -209,6 +211,19 @@ pub struct GlyphsPanelOutput {
|
||||
pub alternate: Option<AlternatePick>,
|
||||
/// The family or style changed in the panel's own pickers.
|
||||
pub font_changed: bool,
|
||||
/// The grid cell a context menu was asked for, with the grid response the menu hangs from.
|
||||
/// Reported on the secondary click and on every later pass while that menu stays open.
|
||||
pub menu: Option<GlyphCellMenu>,
|
||||
}
|
||||
|
||||
/// A grid cell's context menu: the cell, and the grid response the app hangs the menu from.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct GlyphCellMenu {
|
||||
/// The cell.
|
||||
pub cell: GlyphCell,
|
||||
/// The grid the menu hangs from.
|
||||
pub opener: Response,
|
||||
}
|
||||
|
||||
/// The cell whose popup was used and the picked glyph.
|
||||
@@ -313,6 +328,30 @@ struct Marked {
|
||||
host: Option<(GlyphCell, usize)>,
|
||||
}
|
||||
|
||||
/// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid
|
||||
/// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph
|
||||
/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and
|
||||
/// for a glyph id the same source revision, since the source can replace a face under the same names.
|
||||
#[derive(Clone, Default)]
|
||||
struct HeldMenu(Option<MenuCell>);
|
||||
|
||||
/// A held menu's cell, the family and style it was clicked in, and the source revision then.
|
||||
#[derive(Clone)]
|
||||
struct MenuCell {
|
||||
cell: GlyphCell,
|
||||
family: String,
|
||||
style: String,
|
||||
revision: u64,
|
||||
}
|
||||
|
||||
impl MenuCell {
|
||||
/// Whether the cell still names the glyph it was clicked on in `face` at `revision`. A character names the same
|
||||
/// glyph after the source reads its faces again; a glyph id may not.
|
||||
fn holds_in(&self, face: (&str, &str), revision: u64) -> bool {
|
||||
(self.family.as_str(), self.style.as_str()) == face && (matches!(self.cell, GlyphCell::Char(_)) || self.revision == revision)
|
||||
}
|
||||
}
|
||||
|
||||
/// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when
|
||||
/// it opened.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -337,10 +376,12 @@ fn recent_cells(recent: &[String]) -> Vec<GlyphCell> {
|
||||
seen.into_iter().map(GlyphCell::Char).collect()
|
||||
}
|
||||
|
||||
/// The cells of the shown set: the recents, or the source's cells of the category.
|
||||
/// The cells of the shown set: the recents, or the source's cells of the category, read again when the source's
|
||||
/// `revision` (read once for the pass) is not the one they were read at.
|
||||
fn category_cells(
|
||||
cache: &mut CellsCache,
|
||||
source: &dyn GlyphSource,
|
||||
revision: u64,
|
||||
family: &str,
|
||||
style: &str,
|
||||
category: &str,
|
||||
@@ -350,7 +391,6 @@ fn category_cells(
|
||||
return Arc::new(recent_cells(recent));
|
||||
}
|
||||
let key = (family.to_owned(), style.to_owned(), category.to_owned());
|
||||
let revision = source.revision();
|
||||
if cache.key != key || cache.revision != revision {
|
||||
*cache = CellsCache { key, revision, cells: Arc::new(source.cells(family, style, category)) };
|
||||
}
|
||||
@@ -486,12 +526,13 @@ impl<'a> GlyphsPanel<'a> {
|
||||
});
|
||||
});
|
||||
craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS);
|
||||
return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false };
|
||||
return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false, menu: None };
|
||||
}
|
||||
let ctx = ui.ctx().clone();
|
||||
let mut activated_out: Option<GlyphCell> = None;
|
||||
let mut picked: Option<AlternatePick> = None;
|
||||
let mut font_changed = false;
|
||||
let mut menu: Option<GlyphCellMenu> = None;
|
||||
let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| {
|
||||
cx.publish(GlyphsCommand::Alternates, CommandState::new());
|
||||
let mut state = read_bind(&mut settings, cx).unwrap_or_default();
|
||||
@@ -592,8 +633,10 @@ impl<'a> GlyphsPanel<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// The grid.
|
||||
let cells = category_cells(cx.memory::<CellsCache>(), source, face.0, face.1, &state.category, &state.recent);
|
||||
// The grid. One revision read serves the pass: a menu cell is stamped with the revision its list was read
|
||||
// at, so a source that moves on mid-pass cannot give an old glyph id the new revision.
|
||||
let revision = source.revision();
|
||||
let cells = category_cells(cx.memory::<CellsCache>(), source, revision, face.0, face.1, &state.category, &state.recent);
|
||||
let index_of = |cell: GlyphCell| cells.iter().position(|c| *c == cell);
|
||||
let mut marked = cx.memory::<Marked>().clone();
|
||||
let host = marked_cell.and_then(|cell| index_of(cell).map(|at| (cell, at)));
|
||||
@@ -633,6 +676,25 @@ impl<'a> GlyphsPanel<'a> {
|
||||
None => tile,
|
||||
}
|
||||
});
|
||||
// The click names the glyph. Later passes keep that glyph: the grid remembers the row, so a
|
||||
// same-length list must not move the open menu onto whatever glyph is there now.
|
||||
let clicked = shown_grid.response.events.iter().find_map(|event| match event {
|
||||
CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(),
|
||||
_ => None,
|
||||
});
|
||||
let mut held = std::mem::take(cx.memory::<HeldMenu>());
|
||||
if let Some(cell) = clicked {
|
||||
held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision }));
|
||||
}
|
||||
// A closed menu lets go of its cell, and so does another face, or a glyph id after the source
|
||||
// replaced its faces: the same id there is another glyph.
|
||||
let other_face = held.0.as_ref().is_some_and(|held| !held.holds_in(face, revision));
|
||||
if shown_grid.response.menu.is_none() || other_face {
|
||||
held = HeldMenu(None);
|
||||
}
|
||||
let opener = shown_grid.response.response.clone();
|
||||
menu = held.0.as_ref().map(|held| GlyphCellMenu { cell: held.cell, opener });
|
||||
*cx.memory::<HeldMenu>() = held;
|
||||
for event in shown_grid.response.events {
|
||||
match event {
|
||||
CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated),
|
||||
@@ -718,6 +780,6 @@ impl<'a> GlyphsPanel<'a> {
|
||||
write_bind(&mut settings, cx, state, "Glyphs panel");
|
||||
}
|
||||
});
|
||||
GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed }
|
||||
GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu }
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,13 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::testing::pointer;
|
||||
use craft_ui::testing::{Fixture, Room, trial};
|
||||
use egui::{ColorImage, Event};
|
||||
|
||||
@@ -43,6 +47,8 @@ struct Seen {
|
||||
marked: Option<GlyphCell>,
|
||||
reveal: Option<GlyphCell>,
|
||||
picks: Vec<(GlyphCell, GlyphCell)>,
|
||||
/// Cells a secondary click asked for a menu on, in order.
|
||||
menu: Vec<GlyphCell>,
|
||||
}
|
||||
|
||||
fn rig() -> (Fixture, Rc<RefCell<Seen>>) {
|
||||
@@ -62,9 +68,13 @@ fn rig() -> (Fixture, Rc<RefCell<Seen>>) {
|
||||
if let Some(cell) = reveal {
|
||||
panel = panel.reveal(cell);
|
||||
}
|
||||
if let Some(pick) = panel.show(ui).alternate {
|
||||
let out = panel.show(ui);
|
||||
if let Some(pick) = out.alternate {
|
||||
shown.borrow_mut().picks.push((pick.cell, pick.glyph));
|
||||
}
|
||||
if let Some(menu) = out.menu {
|
||||
shown.borrow_mut().menu.push(menu.cell);
|
||||
}
|
||||
});
|
||||
fx.in_room(Room::Window);
|
||||
fx.settle();
|
||||
@@ -158,6 +168,159 @@ fn a_corner_pick_reports_the_cell_and_the_glyph() {
|
||||
assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_secondary_click_reports_the_cell_the_menu_is_for() {
|
||||
let (mut fx, seen) = rig();
|
||||
let cell = fx.by_label(&name(FIRST)).expect("the first cell");
|
||||
let at = cell.center();
|
||||
fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]);
|
||||
fx.frame(vec![pointer::secondary(at, false)]);
|
||||
fx.settle();
|
||||
let menu = seen.borrow().menu.clone();
|
||||
assert!(!menu.is_empty(), "the secondary click names the cell");
|
||||
assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}");
|
||||
}
|
||||
|
||||
/// A list whose first cell changes, at the same length, when `swapped` is set. The revision changes with it, so the
|
||||
/// panel reads the list again.
|
||||
struct Swap(Arc<AtomicBool>);
|
||||
|
||||
impl GlyphSource for Swap {
|
||||
fn cells(&self, _: &str, _: &str, _: &str) -> Vec<GlyphCell> {
|
||||
let first = if self.0.load(Ordering::Relaxed) { '\u{0102}' } else { FIRST };
|
||||
std::iter::once(GlyphCell::Char(first)).chain((1..300).filter_map(|i| char::from_u32(0x100 + i).map(GlyphCell::Char))).collect()
|
||||
}
|
||||
|
||||
fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option<egui::ColorImage> {
|
||||
None
|
||||
}
|
||||
|
||||
fn revision(&self) -> u64 {
|
||||
u64::from(self.0.load(Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() {
|
||||
let swapped = Arc::new(AtomicBool::new(false));
|
||||
let source = Swap(Arc::clone(&swapped));
|
||||
let seen = Rc::new(RefCell::new(Vec::<GlyphCell>::new()));
|
||||
let shown = Rc::clone(&seen);
|
||||
let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default());
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
let out = GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings))
|
||||
.can_insert(true)
|
||||
.show(ui);
|
||||
if let Some(menu) = out.menu {
|
||||
shown.borrow_mut().push(menu.cell);
|
||||
Menu::context("Glyph", &menu.opener).show(ui, |ui, _| {
|
||||
MenuItem::new("Insert Glyph").show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
fx.in_room(Room::Window);
|
||||
fx.settle();
|
||||
let cell = fx.by_label(&name(FIRST)).expect("the first cell");
|
||||
let at = cell.center();
|
||||
fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]);
|
||||
fx.frame(vec![pointer::secondary(at, false)]);
|
||||
fx.settle();
|
||||
assert!(seen.borrow().contains(&GlyphCell::Char(FIRST)), "the click names the cell");
|
||||
|
||||
seen.borrow_mut().clear();
|
||||
swapped.store(true, Ordering::Relaxed);
|
||||
fx.frame(Vec::new());
|
||||
fx.settle();
|
||||
let menu = seen.borrow().clone();
|
||||
assert!(!menu.is_empty(), "the menu stays open");
|
||||
assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}");
|
||||
}
|
||||
|
||||
/// Unencoded glyphs 1 to 300 in every face and at every revision: the same id names another glyph in another face,
|
||||
/// or in a face the source replaced under the same names.
|
||||
struct Unencoded(Arc<AtomicU64>);
|
||||
|
||||
impl GlyphSource for Unencoded {
|
||||
fn cells(&self, _: &str, _: &str, _: &str) -> Vec<GlyphCell> {
|
||||
(1..=300).map(GlyphCell::Glyph).collect()
|
||||
}
|
||||
|
||||
fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option<ColorImage> {
|
||||
None
|
||||
}
|
||||
|
||||
fn revision(&self) -> u64 {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// A host menu open on glyph 1 of an [`Unencoded`] source, with the family and the revision the test can change.
|
||||
struct GlyphMenu {
|
||||
fx: Fixture,
|
||||
family: Rc<RefCell<String>>,
|
||||
revision: Arc<AtomicU64>,
|
||||
seen: Rc<RefCell<Vec<GlyphCell>>>,
|
||||
}
|
||||
|
||||
impl GlyphMenu {
|
||||
fn open() -> Self {
|
||||
let revision = Arc::new(AtomicU64::new(0));
|
||||
let source = Unencoded(Arc::clone(&revision));
|
||||
let family = Rc::new(RefCell::new("Plain".to_owned()));
|
||||
let host_family = Rc::clone(&family);
|
||||
let seen = Rc::new(RefCell::new(Vec::<GlyphCell>::new()));
|
||||
let shown = Rc::clone(&seen);
|
||||
let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default());
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
let out = {
|
||||
let mut family = host_family.borrow_mut();
|
||||
GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings))
|
||||
.can_insert(true)
|
||||
.show(ui)
|
||||
};
|
||||
if let Some(menu) = out.menu {
|
||||
shown.borrow_mut().push(menu.cell);
|
||||
Menu::context("Glyph", &menu.opener).show(ui, |ui, _| {
|
||||
MenuItem::new("Insert Glyph").show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
fx.in_room(Room::Window);
|
||||
fx.settle();
|
||||
let cell = fx.by_label("1, glyph 1").expect("the first glyph");
|
||||
let at = cell.center();
|
||||
fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]);
|
||||
fx.frame(vec![pointer::secondary(at, false)]);
|
||||
fx.settle();
|
||||
assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph");
|
||||
seen.borrow_mut().clear();
|
||||
GlyphMenu { fx, family, revision, seen }
|
||||
}
|
||||
|
||||
/// The cells the menu reported over the next passes.
|
||||
fn reported(&mut self) -> Vec<GlyphCell> {
|
||||
self.fx.frame(Vec::new());
|
||||
self.fx.settle();
|
||||
self.seen.borrow().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_open_menu_does_not_report_a_glyph_id_from_another_face() {
|
||||
let mut open = GlyphMenu::open();
|
||||
*open.family.borrow_mut() = "Other".to_owned();
|
||||
let menu = open.reported();
|
||||
assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_open_menu_does_not_report_a_glyph_id_after_the_source_replaces_the_face() {
|
||||
let mut open = GlyphMenu::open();
|
||||
open.revision.store(1, Ordering::Relaxed);
|
||||
let menu = open.reported();
|
||||
assert!(menu.is_empty(), "the face behind the same names changed, so the clicked id names another glyph: {menu:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn glyphs_panel_alternates() {
|
||||
let (mut fx, _seen) = rig();
|
||||
|
||||
@@ -19,6 +19,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "<commit>
|
||||
| French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) |
|
||||
| German | — | — | TeX patterns (embedded, or a Language pack) |
|
||||
| Bulgarian | — | — | syllable rules |
|
||||
| Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) |
|
||||
|
||||
Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every
|
||||
build.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! What the proofing of a language written in Devanagari (Hindi now) needs to know about the
|
||||
//! script, for the shared checks ([`crate::script_checks`]): its letters (as the akshara rules
|
||||
//! classify them, [`crate::indic::Script::Devanagari`]), its digits and the two spellings of its
|
||||
//! nukta letters.
|
||||
|
||||
use crate::indic;
|
||||
use crate::script_checks::Script;
|
||||
|
||||
/// Devanagari for the shared checks.
|
||||
pub(crate) const SCRIPT: Script =
|
||||
Script { in_words: is_letter, is_letter, is_digit: is_devanagari_digit, variant: Some(nukta_variant as fn(&str) -> Option<String>) };
|
||||
|
||||
fn is_letter(c: char) -> bool {
|
||||
indic::Script::Devanagari.is_letter(c)
|
||||
}
|
||||
|
||||
/// Is `c` a Devanagari digit (`०`..=`९`, U+0966..=U+096F)?
|
||||
fn is_devanagari_digit(c: char) -> bool {
|
||||
('\u{0966}'..='\u{096F}').contains(&c)
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
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)
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -1,77 +1,30 @@
|
||||
//! Generic repeated-word and spacing checks with Gujarati messages.
|
||||
//! No Gujarati-specific grammar or case rules are inferred.
|
||||
//! Generic repeated-word and spacing checks, shared with the other languages proofed by their
|
||||
//! script, with Gujarati messages. No Gujarati-specific grammar or case rules are inferred.
|
||||
|
||||
use crate::{Issue, IssueKind, ProofLang, words};
|
||||
|
||||
fn issue(start: usize, end: usize, message: String, suggestions: Vec<String>) -> Issue {
|
||||
Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: ProofLang::Gu }
|
||||
}
|
||||
use crate::script_checks::Rules;
|
||||
use crate::{Issue, ProofLang};
|
||||
|
||||
/// Checks `text` for repeated words and spacing problems, with Gujarati messages.
|
||||
pub fn check(text: &str) -> Vec<Issue> {
|
||||
let mut issues = Vec::new();
|
||||
repeated_words(text, &words(text), &mut issues);
|
||||
spaces(text, &mut issues);
|
||||
issues.sort_by_key(|i| (i.start, i.end));
|
||||
issues
|
||||
crate::script_checks::check(text, &RULES)
|
||||
}
|
||||
|
||||
const RULES: Rules = Rules {
|
||||
lang: ProofLang::Gu,
|
||||
script: &super::SCRIPT,
|
||||
repeated_word: "પુનરાવર્તિત શબ્દ",
|
||||
space_before_punctuation: "વિરામચિહ્ન પહેલાં જગ્યા",
|
||||
double_space: "બેવડી જગ્યા",
|
||||
flag_repeat: |w| !ALLOWED_REPEATS.contains(&w),
|
||||
};
|
||||
|
||||
/// Words Gujarati repeats on purpose (`હા હા`, `ના ના`, `ધીમે ધીમે`, `સાચે સાચે`).
|
||||
const ALLOWED_REPEATS: &[&str] = &["હા", "ના", "ધીમે", "જલ્દી", "વારંવાર", "સાચે", "રોજે", "ખરેખર", "જરા", "થોડું", "સાથે", "પાસે"];
|
||||
|
||||
fn is_digit(c: char) -> bool {
|
||||
c.is_ascii_digit() || ('\u{0AE6}'..='\u{0AEF}').contains(&c)
|
||||
}
|
||||
|
||||
fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec<Issue>) {
|
||||
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() || (super::is_gujarati_char(c) && !c.is_numeric()))
|
||||
&& w0 == w1
|
||||
&& !ALLOWED_REPEATS.contains(&w0)
|
||||
{
|
||||
v.push(issue(*a0, *b1, format!("પુનરાવર્તિત શબ્દ: “{w1}”"), vec![w0.to_string()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spaces(text: &str, v: &mut Vec<Issue>) {
|
||||
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 Gujarati 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(|a| a.is_ascii_digit()),
|
||||
':' | '!' | '?' => after.is_none_or(|a| a.is_whitespace() || matches!(a, '"' | '”' | '’' | '!' | '?')),
|
||||
_ => false,
|
||||
};
|
||||
if flag {
|
||||
v.push(issue(i, i + 1 + p.len_utf8(), "વિરામચિહ્ન પહેલાં જગ્યા".into(), vec![p.to_string()]));
|
||||
}
|
||||
}
|
||||
for run in crate::space_runs(text) {
|
||||
v.push(issue(run.start, run.end, "બેવડી જગ્યા".into(), vec![" ".into()]));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::IssueKind;
|
||||
|
||||
#[test]
|
||||
fn intentional_repeats_are_fine() {
|
||||
|
||||
+14
-22
@@ -1,6 +1,6 @@
|
||||
//! Gujarati proofing using the installed Hunspell `gu_IN` dictionary (never bundled).
|
||||
//! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic grammar checks have Gujarati
|
||||
//! messages; hyphenation keeps the existing fallback.
|
||||
//! messages. Hyphenation is by akshara ([`crate::indic`]).
|
||||
|
||||
pub mod grammar;
|
||||
pub(crate) mod suggest;
|
||||
@@ -10,6 +10,7 @@ pub(crate) mod test_dict;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::affix::AffixDict;
|
||||
use crate::script_checks::Script;
|
||||
use crate::slot::DictSlot;
|
||||
|
||||
pub use suggest::suggest;
|
||||
@@ -61,29 +62,20 @@ pub fn is_correct_with(d: &AffixDict, word: &str) -> bool {
|
||||
|
||||
/// [`is_correct_with_options`] against a given dictionary.
|
||||
fn check(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_gujarati_char(c) && !matches!(c, '\'' | '’' | '-'));
|
||||
let w = w.trim_matches(['\'', '’', '-']);
|
||||
let letter_count = w.chars().filter(|&c| (is_gujarati_char(c) && !c.is_numeric()) || 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 Gujarati characters) is not marked by this dictionary.
|
||||
if !w.chars().any(is_gujarati_char) {
|
||||
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_gujarati_char) || known(d, p));
|
||||
}
|
||||
known(d, w)
|
||||
crate::script_checks::is_correct(&SCRIPT, d, word, opts)
|
||||
}
|
||||
|
||||
/// Is one word (no hyphens) in the dictionary or the user dictionary?
|
||||
fn known(d: &AffixDict, w: &str) -> bool {
|
||||
d.check(w) || crate::in_user_dictionary(&w.to_lowercase())
|
||||
/// Gujarati for the shared checks: the whole block is kept in words, its letters are everything
|
||||
/// in it but the digits.
|
||||
pub(crate) const SCRIPT: Script = Script { in_words: is_gujarati_char, is_letter, is_digit: is_gujarati_digit, variant: None };
|
||||
|
||||
fn is_letter(c: char) -> bool {
|
||||
is_gujarati_char(c) && !c.is_numeric()
|
||||
}
|
||||
|
||||
/// Is `c` a Gujarati digit (U+0AE6..=U+0AEF)?
|
||||
fn is_gujarati_digit(c: char) -> bool {
|
||||
('\u{0AE6}'..='\u{0AEF}').contains(&c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Generic repeated-word and spacing checks, shared with the other languages proofed by their
|
||||
//! script, with Hindi messages. No Hindi-specific grammar or agreement rules are inferred.
|
||||
|
||||
use crate::script_checks::Rules;
|
||||
use crate::{Issue, ProofLang};
|
||||
|
||||
/// Checks `text` for repeated words and spacing problems, with Hindi messages.
|
||||
pub fn check(text: &str) -> Vec<Issue> {
|
||||
crate::script_checks::check(text, &RULES)
|
||||
}
|
||||
|
||||
const RULES: Rules = Rules {
|
||||
lang: ProofLang::Hi,
|
||||
script: &crate::devanagari::SCRIPT,
|
||||
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(|c| ('\u{0900}'..='\u{097F}').contains(&c)) || 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Hindi proofing using the installed Hunspell `hi_IN` dictionary (never bundled).
|
||||
//! Suggestions use its runtime MAP/REP/TRY/KEY tables. Spelling and the generic checks are the
|
||||
//! ones Gujarati shares, with Devanagari's letters and digits and Hindi messages. Hyphenation is
|
||||
//! by akshara ([`crate::indic`]).
|
||||
|
||||
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<AffixDict> = 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<AffixDict> {
|
||||
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 {
|
||||
check(&dictionary(), word, opts)
|
||||
}
|
||||
|
||||
/// [`is_correct`] against a given dictionary (an empty one accepts everything).
|
||||
pub fn is_correct_with(d: &AffixDict, word: &str) -> bool {
|
||||
check(d, word, &crate::Options::default())
|
||||
}
|
||||
|
||||
/// [`is_correct_with_options`] against a given dictionary.
|
||||
fn check(d: &AffixDict, word: &str, opts: &crate::Options) -> bool {
|
||||
crate::script_checks::is_correct(&crate::devanagari::SCRIPT, d, word, opts)
|
||||
}
|
||||
|
||||
#[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!(check(&d, "१२", &no_ignore));
|
||||
assert!(check(&d, "2026", &no_ignore));
|
||||
assert!(!check(&d, "घरर१२", &no_ignore));
|
||||
assert!(check(&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")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! 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<String> {
|
||||
suggest_in(&super::dictionary(), word, max)
|
||||
}
|
||||
|
||||
/// [`suggest`] against a given dictionary.
|
||||
pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec<String> {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -15,6 +15,10 @@
|
||||
//!
|
||||
//! **Bulgarian**: the Bulgarian syllable rules ([`crate::bg`]); no pattern file or word list.
|
||||
//!
|
||||
//! **Gujarati and Hindi**: breaks between aksharas, never inside a conjunct or between a
|
||||
//! consonant and its vowel sign ([`crate::indic`], rules from the script's Unicode encoding); no
|
||||
//! pattern file.
|
||||
//!
|
||||
//! **German**: the TeX German patterns for the reformed spelling ([`Patterns::de`]), also for
|
||||
//! Swiss text, whose `ss` the patterns split like any double consonant (`Stras-se`).
|
||||
//!
|
||||
@@ -116,7 +120,7 @@ pub enum Source {
|
||||
Patterns,
|
||||
/// A heuristic for a language without a dictionary or patterns.
|
||||
Heuristic,
|
||||
/// A language's syllable rules (Bulgarian, [`crate::bg`]).
|
||||
/// A language's syllable rules (Bulgarian [`crate::bg`], Turkish, Gujarati and Hindi [`crate::indic`]).
|
||||
Rules,
|
||||
/// No break points: the word is too short or no source applies.
|
||||
None,
|
||||
@@ -131,6 +135,13 @@ fn is_word_char(c: char) -> bool {
|
||||
c.is_alphabetic() || is_apostrophe(c) || unicode_normalization::char::is_combining_mark(c)
|
||||
}
|
||||
|
||||
/// [`is_word_char`] in `lang`. In a language with Indic rules a zero-width joiner or non-joiner
|
||||
/// is part of the word too: it shapes a conjunct inside an akshara ([`crate::indic`]). In any
|
||||
/// other language it still ends a letter run (Persian's ZWNJ between a word's parts).
|
||||
fn is_word_char_in(c: char, lang: ProofLang) -> bool {
|
||||
is_word_char(c) || (crate::indic::is_joiner(c) && crate::indic::Script::of(lang.built_in()).is_some())
|
||||
}
|
||||
|
||||
/// Unrestricted break points of one lowercase core (letters and `'` only, no leading/trailing `'`).
|
||||
fn core_breaks(core: &[char], lang: ProofLang) -> (Vec<usize>, Source) {
|
||||
let n = core.len();
|
||||
@@ -156,6 +167,13 @@ fn core_breaks(core: &[char], lang: ProofLang) -> (Vec<usize>, Source) {
|
||||
if lang == ProofLang::Bg && core.iter().all(|&c| crate::bg::is_letter(c)) {
|
||||
return (crate::bg::points(core), Source::Rules);
|
||||
}
|
||||
// Gujarati and Hindi words break between aksharas ([`crate::indic`]); other words in their runs
|
||||
// (`WordCraft`) are hyphenated as English.
|
||||
if let Some(script) = crate::indic::Script::of(lang)
|
||||
&& core.iter().all(|&c| script.is_letter(c))
|
||||
{
|
||||
return (crate::indic::points(script, core), Source::Rules);
|
||||
}
|
||||
// A suffix written after an apostrophe (`Ankara'dan`, `Türkiye'nin`) is hyphenated part by
|
||||
// part; no break goes next to the apostrophe ([`word_breaks_in`] drops those).
|
||||
if lang == ProofLang::Tr && core.iter().all(|&c| c == '\'' || crate::tr::hyphen::is_letter(c)) {
|
||||
@@ -224,9 +242,10 @@ fn composed_chars(core: &[char]) -> (Vec<char>, Vec<Option<usize>>) {
|
||||
(nfc, starts)
|
||||
}
|
||||
|
||||
/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish and Gujarati: a
|
||||
/// word in their script (the guard their rules use) whose letters the patterns know, so a word with a
|
||||
/// letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian
|
||||
/// Does a pack's `pats` hyphenate `core` in `lang`? Russian, Bulgarian, Turkish, Gujarati and
|
||||
/// Hindi: a word in their script (the guard their rules use; for Gujarati and Hindi, the script's
|
||||
/// letters and marks and the joiners inside a conjunct, [`crate::indic`]) whose letters the
|
||||
/// patterns know, so a word with a letter the pack never mentions goes on to the fallback rules. Polish, Portuguese, Italian
|
||||
/// and German: every word, as their embedded patterns do. Any other language: a word whose letters
|
||||
/// the patterns know.
|
||||
fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool {
|
||||
@@ -235,7 +254,9 @@ fn pack_patterns_fit(lang: ProofLang, pats: &Patterns, core: &[char]) -> bool {
|
||||
ProofLang::Bg => core.iter().all(|&c| crate::bg::is_letter(c)) && pack_knows(pats, core),
|
||||
ProofLang::Tr => core.iter().all(|&c| crate::tr::hyphen::is_letter(c)) && pack_knows(pats, core),
|
||||
ProofLang::Pl | ProofLang::Pt | ProofLang::It | ProofLang::De => true,
|
||||
ProofLang::Gu => core.iter().all(|&c| crate::gu::is_gujarati_char(c)) && pack_knows(pats, core),
|
||||
ProofLang::Gu | ProofLang::Hi => {
|
||||
crate::indic::Script::of(lang).is_some_and(|s| core.iter().all(|&c| s.is_letter(c))) && pack_knows(pats, core)
|
||||
}
|
||||
_ => pats.values(core).is_some(),
|
||||
}
|
||||
}
|
||||
@@ -311,12 +332,12 @@ pub fn word_breaks_in(word: &str, lang: ProofLang) -> (Vec<usize>, Source) {
|
||||
let mut src = Source::None;
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if !is_word_char(chars[i]) {
|
||||
if !is_word_char_in(chars[i], lang) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i;
|
||||
while j < chars.len() && is_word_char(chars[j]) {
|
||||
while j < chars.len() && is_word_char_in(chars[j], lang) {
|
||||
j += 1;
|
||||
}
|
||||
let (mut a, mut b) = (i, j);
|
||||
@@ -370,7 +391,7 @@ pub fn hyphen_points_in(word: &str, lim: &Limits, lang: ProofLang) -> Vec<usize>
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
let mut j = i;
|
||||
while chars.get(j).is_some_and(|c| is_word_char(*c)) {
|
||||
while chars.get(j).is_some_and(|c| is_word_char_in(*c, lang)) {
|
||||
j += 1;
|
||||
}
|
||||
let (mut a, mut b) = (i, j);
|
||||
|
||||
@@ -194,3 +194,44 @@ fn gujarati_pack_patterns_fit_checks_script_and_exceptions() {
|
||||
let en_word: Vec<char> = "hyphenation".chars().collect();
|
||||
assert!(!pack_patterns_fit(ProofLang::Gu, &pats, &en_word));
|
||||
}
|
||||
|
||||
/// CodeRabbit on craft-libs#3905: a word with a joiner in a conjunct still reaches its pack's
|
||||
/// exception word (here: no break at all), in Gujarati and Hindi.
|
||||
#[test]
|
||||
fn indic_pack_exceptions_reach_words_with_joiners() {
|
||||
for (lang, word) in [(ProofLang::Gu, "પુસ્\u{200D}તક"), (ProofLang::Hi, "पुस्\u{200D}तक")] {
|
||||
let pats = Patterns::parse(&format!("1ક 1क \\hyphenation{{{word}}}"));
|
||||
let core: Vec<char> = word.chars().collect();
|
||||
assert!(pack_patterns_fit(lang, &pats, &core), "{lang:?}");
|
||||
assert_eq!(core_breaks_patterns(&pats, &core), (vec![], Source::Dictionary), "{lang:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// storytold/vectorcraft#4947: Gujarati text breaks between aksharas, within the paragraph's
|
||||
/// limits, where it used to fall to the English rules and get no break at all; a Latin word in
|
||||
/// a Gujarati run is still hyphenated as English.
|
||||
#[test]
|
||||
fn gujarati_breaks_between_aksharas_within_the_limits() {
|
||||
let lim = Limits::default();
|
||||
let gu = |w: &str| hyphenate_word_in(w, &lim, ProofLang::Gu);
|
||||
assert_eq!(gu("વિદ્યાર્થી"), "વિ-દ્યા-ર્થી", "a conjunct is never split");
|
||||
assert_eq!(word_breaks_in("વિદ્યાર્થી", ProofLang::Gu).1, Source::Rules);
|
||||
// A lone consonant at either end is fewer letters than `after_first`/`before_last` allow.
|
||||
assert_eq!(gu("અમદાવાદ"), "અમ-દા-વાદ");
|
||||
assert_eq!(gu("«ગુજરાતી»"), "«ગુ-જ-રા-તી»", "punctuation around the word");
|
||||
assert_eq!(gu("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En));
|
||||
// A joiner in a conjunct doesn't cut the word in two (each part then too short to break).
|
||||
assert_eq!(gu("પુસ્\u{200D}તક"), "પુ-સ્\u{200D}તક");
|
||||
}
|
||||
|
||||
/// Hindi text breaks between Devanagari aksharas by the same rules, where it used to get no
|
||||
/// break; a Latin word in a Hindi run is still hyphenated as English.
|
||||
#[test]
|
||||
fn hindi_breaks_between_aksharas_within_the_limits() {
|
||||
let lim = Limits::default();
|
||||
let hi = |w: &str| hyphenate_word_in(w, &lim, ProofLang::Hi);
|
||||
assert_eq!(hi("विद्यार्थी"), "वि-द्या-र्थी", "a conjunct is never split");
|
||||
assert_eq!(word_breaks_in("विद्यार्थी", ProofLang::Hi).1, Source::Rules);
|
||||
assert_eq!(hi("«विद्यार्थी»"), "«वि-द्या-र्थी»", "punctuation around the word");
|
||||
assert_eq!(hi("Typography"), hyphenate_word_in("Typography", &lim, ProofLang::En));
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! Hyphenation of Indic scripts by rule: a word breaks only between its orthographic syllables
|
||||
//! (aksharas), never inside one.
|
||||
//!
|
||||
//! An akshara is a consonant with what is written on it — its vowel sign, nukta, anusvara,
|
||||
//! candrabindu or visarga — and the consonants joined to it by a virama (a conjunct: `દ્ય`, `ર્થ`,
|
||||
//! `न्द`), or an independent vowel with its marks. So a break goes only before a consonant or an
|
||||
//! independent vowel that does not follow a virama: `ગુ-જ-રા-તી`, `વિ-દ્યા-ર્થી`, `સં-સ્કૃત`,
|
||||
//! `हि-न्दी`. A vowel sign, a mark or the second consonant of a conjunct never starts a line.
|
||||
//! Nor does a dead consonant — one ending in a virama with no consonant after it (`વાક્`) — since
|
||||
//! it has no vowel of its own and is the end of the syllable before. A zero-width joiner or
|
||||
//! non-joiner after a virama (`સ્` U+200D `ત`) only chooses how the conjunct is drawn: it stays
|
||||
//! inside the akshara, and no break goes next to a joiner.
|
||||
//!
|
||||
//! The rules come from the scripts' Unicode encoding alone; no pattern file or word list is
|
||||
//! read (and none is borrowed). The Brahmic blocks share one layout (the ISCII order), so a
|
||||
//! script is its block's start and a few script-specific code points (`Script::kind`).
|
||||
//! Gujarati ([`ProofLang::Gu`]) and Hindi ([`ProofLang::Hi`], [`Script::Devanagari`]) use them;
|
||||
//! another language written in one of these scripts is one more line in [`Script::of`].
|
||||
//!
|
||||
//! A single akshara left at the end or start of a line is ruled out by the paragraph's
|
||||
//! [`Limits`](crate::hyphen::Limits), which count letters (vowel signs and anusvara count,
|
||||
//! viramas and nuktas don't), so a bare consonant (`…-ત`) is not carried over with the default
|
||||
//! limits but a consonant with its vowel sign (`…-તી`) is.
|
||||
|
||||
use crate::ProofLang;
|
||||
|
||||
/// An Indic script hyphenated by [`points`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Script {
|
||||
/// Devanagari (U+0900..=U+097F): Hindi, Marathi, Nepali…
|
||||
Devanagari,
|
||||
/// Gujarati (U+0A80..=U+0AFF).
|
||||
Gujarati,
|
||||
}
|
||||
|
||||
/// What a code point is in an akshara.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
/// An independent vowel: starts an akshara.
|
||||
Vowel,
|
||||
/// A consonant: starts an akshara, unless a virama joins it to the consonant before.
|
||||
Consonant,
|
||||
/// The virama: joins the consonant before it to the next one, or kills its vowel.
|
||||
Virama,
|
||||
/// A vowel sign, nukta, anusvara, candrabindu, visarga or other mark (and the avagraha):
|
||||
/// belongs to the akshara before it.
|
||||
Mark,
|
||||
/// A zero-width joiner or non-joiner: shapes the conjunct around it, in the same akshara.
|
||||
Joiner,
|
||||
}
|
||||
|
||||
/// Is `c` a zero-width joiner or non-joiner (U+200D, U+200C)? Inside an Indic word it shapes a
|
||||
/// conjunct, so it is part of the word (as in Unicode's word boundaries, UAX #29).
|
||||
pub fn is_joiner(c: char) -> bool {
|
||||
matches!(c, '\u{200C}' | '\u{200D}')
|
||||
}
|
||||
|
||||
impl Script {
|
||||
/// The script whose rules hyphenate `lang`'s words, if any.
|
||||
pub fn of(lang: ProofLang) -> Option<Script> {
|
||||
match lang {
|
||||
ProofLang::Gu => Some(Script::Gujarati),
|
||||
ProofLang::Hi => Some(Script::Devanagari),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// First code point of the script's block.
|
||||
fn base(self) -> u32 {
|
||||
match self {
|
||||
Script::Devanagari => 0x0900,
|
||||
Script::Gujarati => 0x0A80,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `c` is in this script, or `None` for a character outside the script's letters and
|
||||
/// marks (another script, a digit, a danda, `ॐ`, the abbreviation sign…).
|
||||
fn kind(self, c: char) -> Option<Kind> {
|
||||
if is_joiner(c) {
|
||||
return Some(Kind::Joiner);
|
||||
}
|
||||
let o = u32::from(c).checked_sub(self.base()).filter(|&o| o < 0x80)?;
|
||||
let dev = self == Script::Devanagari;
|
||||
Some(match o {
|
||||
// Candrabindu, anusvara, visarga (and Devanagari's inverted candrabindu).
|
||||
0x00..=0x03 => Kind::Mark,
|
||||
0x04..=0x14 => Kind::Vowel,
|
||||
0x15..=0x39 => Kind::Consonant,
|
||||
// Devanagari's vowel signs OE and OOE, the nukta, the avagraha, the vowel signs.
|
||||
0x3A..=0x4C => Kind::Mark,
|
||||
0x4D => Kind::Virama,
|
||||
// Devanagari's vowel signs PRISHTHAMATRA E and AW, stress signs and vowel signs.
|
||||
0x4E..=0x4F | 0x51..=0x57 if dev => Kind::Mark,
|
||||
// Devanagari's consonants with nukta (`क़`, `ज़`, `फ़`…).
|
||||
0x58..=0x5F if dev => Kind::Consonant,
|
||||
// Vocalic RR and LL.
|
||||
0x60..=0x61 => Kind::Vowel,
|
||||
0x62..=0x63 => Kind::Mark,
|
||||
// Devanagari's vowels for Marathi, Kashmiri and Bihari languages, and consonants for
|
||||
// Sindhi, Marwari and others.
|
||||
0x72..=0x77 if dev => Kind::Vowel,
|
||||
0x78..=0x7F if dev => Kind::Consonant,
|
||||
// Gujarati ZHA, and the nuktas and signs for transliterating Arabic.
|
||||
0x79 => Kind::Consonant,
|
||||
0x7A..=0x7F => Kind::Mark,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `c` one of this script's letters or marks, or a joiner (the characters [`points`]
|
||||
/// splits)?
|
||||
pub fn is_letter(self, c: char) -> bool {
|
||||
self.kind(c).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Break points of one `word` in `script` (char indices; a hyphen goes before that char): before
|
||||
/// each akshara but the first, except a dead consonant. Empty for anything that is not entirely
|
||||
/// the script's letters and marks.
|
||||
pub fn points(script: Script, word: &[char]) -> Vec<usize> {
|
||||
let Some(kinds) = word.iter().map(|&c| script.kind(c)).collect::<Option<Vec<Kind>>>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let at = |i: usize| kinds.get(i).copied();
|
||||
// Has the akshara starting at `i` a vowel (independent, a sign, or the inherent one)? Only a
|
||||
// consonant cluster ending in a virama (`ક્`, `ન્ત્`, with or without a joiner) has none.
|
||||
let live = |i: usize| {
|
||||
let mut j = i;
|
||||
loop {
|
||||
if at(j) != Some(Kind::Consonant) {
|
||||
return true;
|
||||
}
|
||||
j += 1;
|
||||
while matches!(at(j), Some(Kind::Mark | Kind::Joiner)) {
|
||||
j += 1;
|
||||
}
|
||||
if at(j) != Some(Kind::Virama) {
|
||||
return true;
|
||||
}
|
||||
j += 1;
|
||||
while at(j) == Some(Kind::Joiner) {
|
||||
j += 1;
|
||||
}
|
||||
if at(j) != Some(Kind::Consonant) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
(1..word.len())
|
||||
.filter(|&i| matches!(at(i), Some(Kind::Vowel | Kind::Consonant)) && !matches!(at(i - 1), Some(Kind::Virama | Kind::Joiner)) && live(i))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn split(script: Script, w: &str) -> String {
|
||||
let c: Vec<char> = w.chars().collect();
|
||||
let pts = points(script, &c);
|
||||
let mut s = String::new();
|
||||
for (i, ch) in c.iter().enumerate() {
|
||||
if pts.contains(&i) {
|
||||
s.push('-');
|
||||
}
|
||||
s.push(*ch);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn gu(w: &str) -> String {
|
||||
split(Script::Gujarati, w)
|
||||
}
|
||||
|
||||
fn hi(w: &str) -> String {
|
||||
split(Script::Devanagari, w)
|
||||
}
|
||||
|
||||
/// Every akshara boundary is a break, and a vowel sign stays on its consonant.
|
||||
#[test]
|
||||
fn gujarati_breaks_between_aksharas() {
|
||||
assert_eq!(gu("ગુજરાતી"), "ગુ-જ-રા-તી");
|
||||
assert_eq!(gu("અમદાવાદ"), "અ-મ-દા-વા-દ");
|
||||
assert_eq!(gu("આવક"), "આ-વ-ક", "independent vowels start aksharas");
|
||||
assert_eq!(gu("કઈ"), "ક-ઈ", "an independent vowel after a consonant");
|
||||
}
|
||||
|
||||
/// A conjunct is never split, and the virama never ends a line.
|
||||
#[test]
|
||||
fn gujarati_conjuncts_stay_whole() {
|
||||
assert_eq!(gu("વિદ્યાર્થી"), "વિ-દ્યા-ર્થી");
|
||||
assert_eq!(gu("પુસ્તક"), "પુ-સ્ત-ક");
|
||||
assert_eq!(gu("સ્ત્રી"), "સ્ત્રી", "one akshara of three consonants");
|
||||
assert_eq!(gu("ક્ષત્રિય"), "ક્ષ-ત્રિ-ય");
|
||||
}
|
||||
|
||||
/// Anusvara, candrabindu and visarga stay with the akshara before them.
|
||||
#[test]
|
||||
fn gujarati_marks_stay_with_their_akshara() {
|
||||
assert_eq!(gu("સંસ્કૃત"), "સં-સ્કૃ-ત");
|
||||
assert_eq!(gu("હાઁસલ"), "હાઁ-સ-લ");
|
||||
assert_eq!(gu("દુઃખી"), "દુઃ-ખી");
|
||||
}
|
||||
|
||||
/// A consonant killed by a final virama has no vowel: it ends the syllable before.
|
||||
#[test]
|
||||
fn a_dead_final_consonant_is_not_carried_over() {
|
||||
assert_eq!(gu("વાક્"), "વાક્");
|
||||
assert_eq!(gu("સમ્યક્"), "સ-મ્યક્");
|
||||
assert_eq!(hi("जगत्"), "ज-गत्");
|
||||
}
|
||||
|
||||
/// Anything but the script's letters and marks: no breaks.
|
||||
#[test]
|
||||
fn other_characters_get_no_breaks() {
|
||||
assert_eq!(gu("ૐકાર"), "ૐકાર", "OM is not a letter here");
|
||||
assert_eq!(gu("ગુજ૧૨"), "ગુજ૧૨", "digits");
|
||||
assert_eq!(gu("hyphen"), "hyphen");
|
||||
assert_eq!(gu("हिन्दी"), "हिन्दी", "Devanagari is not Gujarati");
|
||||
assert!(points(Script::Gujarati, &[]).is_empty());
|
||||
}
|
||||
|
||||
/// The same rules on Devanagari, ready for Hindi: conjuncts, nukta (combining and in a
|
||||
/// precomposed consonant) and the anusvara.
|
||||
#[test]
|
||||
fn devanagari_uses_the_same_rules() {
|
||||
assert_eq!(hi("हिन्दी"), "हि-न्दी");
|
||||
assert_eq!(hi("विद्यार्थी"), "वि-द्या-र्थी");
|
||||
assert_eq!(hi("संस्कृत"), "सं-स्कृ-त");
|
||||
assert_eq!(hi("ज\u{093C}रूरी"), "ज\u{093C}-रू-री");
|
||||
assert_eq!(hi("\u{095B}रूरी"), "\u{095B}-रू-री");
|
||||
assert_eq!(hi("ગુજરાતી"), "ગુજરાતી", "Gujarati is not Devanagari");
|
||||
}
|
||||
|
||||
/// CodeRabbit on craft-libs#3901: a joiner after a virama stays inside its conjunct, the break
|
||||
/// before the conjunct remains, and no break goes next to a joiner.
|
||||
#[test]
|
||||
fn joiners_stay_inside_the_akshara() {
|
||||
assert_eq!(gu("પુસ્\u{200D}તક"), "પુ-સ્\u{200D}ત-ક");
|
||||
assert_eq!(gu("પુસ્\u{200C}તક"), "પુ-સ્\u{200C}ત-ક");
|
||||
assert_eq!(gu("વાક્\u{200D}"), "વાક્\u{200D}", "still a dead consonant");
|
||||
assert_eq!(gu("ક\u{200D}ખ"), "ક\u{200D}ખ", "a joiner outside a conjunct");
|
||||
assert_eq!(hi("क्\u{200D}षमा"), "क्\u{200D}ष-मा");
|
||||
}
|
||||
|
||||
/// Gujarati and Hindi are mapped to their scripts, other languages to none.
|
||||
#[test]
|
||||
fn languages_map_to_their_script() {
|
||||
assert_eq!(Script::of(ProofLang::Gu), Some(Script::Gujarati));
|
||||
assert_eq!(Script::of(ProofLang::Hi), Some(Script::Devanagari));
|
||||
assert_eq!(Script::of(ProofLang::En), None);
|
||||
assert_eq!(Script::of(ProofLang::Bg), None);
|
||||
}
|
||||
}
|
||||
@@ -71,9 +71,14 @@ pub enum ProofLang {
|
||||
/// and the `vos` forms of verbs (`tenés`, `vení`, `decime`) accepted ([`crate::es::voseo`]).
|
||||
EsUy,
|
||||
/// Gujarati (`gu`, `gu-IN`, `guj`): the installed Hunspell dictionary (`gu_IN`, when there is
|
||||
/// one), dictionary-driven suggestions and generic checks with Gujarati messages. Hyphenation
|
||||
/// keeps the fallback patterns.
|
||||
/// one), dictionary-driven suggestions and generic checks with Gujarati messages.
|
||||
/// Hyphenation breaks between aksharas ([`crate::indic`]), or follows a `gu` pack's 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 breaks between aksharas ([`crate::indic`]), or follows a `hi`
|
||||
/// pack's patterns.
|
||||
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 +99,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 +117,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 +155,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 +241,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 => "",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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, matching nukta letters however either side spells them), dictionary-driven
|
||||
//! suggestions and the generic checks Gujarati shares, with Hindi messages. Hyphenation breaks
|
||||
//! between aksharas ([`indic`]).
|
||||
//! - **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;
|
||||
mod devanagari;
|
||||
pub mod dict;
|
||||
pub mod en_variants;
|
||||
mod english;
|
||||
@@ -83,10 +88,12 @@ pub mod es;
|
||||
pub mod fr;
|
||||
mod grammar_en;
|
||||
pub mod gu;
|
||||
pub mod hi;
|
||||
pub mod hr;
|
||||
pub mod hunspell;
|
||||
pub mod hyphen;
|
||||
pub mod id;
|
||||
pub mod indic;
|
||||
pub mod it;
|
||||
pub mod lang;
|
||||
mod languages;
|
||||
@@ -97,6 +104,7 @@ pub mod pl;
|
||||
pub mod pt;
|
||||
pub mod ru;
|
||||
pub mod scowl;
|
||||
mod script_checks;
|
||||
mod slot;
|
||||
mod spelling;
|
||||
pub mod tr;
|
||||
|
||||
@@ -540,6 +540,7 @@ fn hyphenation_locales(lang: ProofLang) -> Vec<String> {
|
||||
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"],
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Spelling against a Hunspell dictionary and the generic checks (repeated words, spacing) for a
|
||||
//! language written in one script, with that language's messages. A language gives its
|
||||
//! [`Script`] (which characters are its letters and digits) and its [`Rules`]; Gujarati and Hindi
|
||||
//! share this one copy.
|
||||
|
||||
use crate::affix::AffixDict;
|
||||
use crate::{Issue, IssueKind, ProofLang, words};
|
||||
|
||||
/// What the checks need to know about a script.
|
||||
pub(crate) struct Script {
|
||||
/// Is `c` of the script, as far as a word goes: kept when a word is trimmed, and a word with
|
||||
/// none is in another script (and never marked).
|
||||
pub(crate) in_words: fn(char) -> bool,
|
||||
/// Is `c` one of the script's letters or marks (its digits and punctuation are not)? Words
|
||||
/// of one letter are accepted, and only words of letters are repeated words.
|
||||
pub(crate) is_letter: fn(char) -> bool,
|
||||
/// Is `c` one of the script's digits? (ASCII digits always are digits.)
|
||||
pub(crate) is_digit: fn(char) -> bool,
|
||||
/// Another spelling of a word the dictionary may list instead (Devanagari's nukta letters,
|
||||
/// [`crate::devanagari::nukta_variant`]).
|
||||
pub(crate) variant: Option<fn(&str) -> Option<String>>,
|
||||
}
|
||||
|
||||
/// Is `word` spelled correctly against `d`, the dictionary of a language written in `script`?
|
||||
/// Numbers, 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(script: &Script, d: &AffixDict, word: &str, opts: &crate::Options) -> bool {
|
||||
if d.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let w = word.trim_matches(|c: char| !c.is_alphanumeric() && !(script.in_words)(c) && !matches!(c, '\'' | '’' | '-'));
|
||||
let w = w.trim_matches(['\'', '’', '-']);
|
||||
let letter_count = w.chars().filter(|&c| (script.is_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 character of this one) is not marked by this dictionary.
|
||||
if !w.chars().any(script.in_words) {
|
||||
return true;
|
||||
}
|
||||
if w.contains('-') {
|
||||
// The whole word first, as Hunspell does: a hyphenated entry or user word.
|
||||
return known(script, d, w) || w.split('-').all(|p| p.chars().count() <= 1 || !p.chars().any(script.in_words) || known(script, d, p));
|
||||
}
|
||||
known(script, d, w)
|
||||
}
|
||||
|
||||
/// Is one word (no hyphens) in the dictionary or the user dictionary, spelled as it is or as the
|
||||
/// script's [`Script::variant`]?
|
||||
fn known(script: &Script, d: &AffixDict, w: &str) -> bool {
|
||||
let listed = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase());
|
||||
listed(w) || script.variant.and_then(|v| v(w)).is_some_and(|v| listed(&v))
|
||||
}
|
||||
|
||||
/// A language's script, messages and choices for [`check`].
|
||||
pub(crate) struct Rules {
|
||||
/// The language the issues are in.
|
||||
pub(crate) lang: ProofLang,
|
||||
/// Its script.
|
||||
pub(crate) script: &'static Script,
|
||||
/// 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? A language that doubles words on
|
||||
/// purpose answers no for those words.
|
||||
pub(crate) flag_repeat: fn(&str) -> bool,
|
||||
}
|
||||
|
||||
/// Repeated words and spacing problems in `text`, with `rules`' messages. A space before `,`,
|
||||
/// `;`, `:`, `!`, `?` or `.` is flagged, except in a ratio or score (`3 : 1`, in ASCII or the
|
||||
/// script's digits) and before a decimal point; a space before any other mark (the danda `।`
|
||||
/// among them) is not.
|
||||
pub(crate) fn check(text: &str, rules: &Rules) -> Vec<Issue> {
|
||||
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<String>) -> Issue {
|
||||
Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: rules.lang }
|
||||
}
|
||||
|
||||
fn repeated_words(text: &str, ws: &[(usize, usize)], rules: &Rules, v: &mut Vec<Issue>) {
|
||||
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() || (rules.script.is_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<Issue>) {
|
||||
let is_digit = |c: char| c.is_ascii_digit() || (rules.script.is_digit)(c);
|
||||
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 the script's 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(|a| a.is_ascii_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()]));
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
@@ -626,11 +627,47 @@ fn mixed_language_paragraphs_check_each_run_in_its_language() {
|
||||
assert!(v.iter().all(|i| i.lang == ProofLang::It && i.message == "Possibile errore di ortografia"), "{v:?}");
|
||||
}
|
||||
|
||||
/// Every [`ProofLang`], for `mixed_spans_never_panic` to draw from. `fr` stands for the
|
||||
/// [`ProofLang::Pack`] languages (and runs the French grammar rules, which need no dictionary).
|
||||
fn every_lang() -> Vec<ProofLang> {
|
||||
use ProofLang as L;
|
||||
// Stops compiling when a language is added: add it to the list below too.
|
||||
let _ = |l: L| match l {
|
||||
L::En | L::EnGb | L::EnAu | L::EnCa | L::Pl | L::Bg | L::Pt | L::It | L::Hr | L::Tr | L::Ru | L::Cs | L::Id => (),
|
||||
L::Es | L::EsMx | L::Es419 | L::EsUy | L::Gu | L::Hi | L::De | L::Pack(_) | L::Other => (),
|
||||
};
|
||||
let fr = ProofLang::from_tag(Some("fr"));
|
||||
assert!(matches!(fr, L::Pack(_)), "{fr:?}");
|
||||
vec![
|
||||
L::En,
|
||||
L::EnGb,
|
||||
L::EnAu,
|
||||
L::EnCa,
|
||||
L::Pl,
|
||||
L::Bg,
|
||||
L::Pt,
|
||||
L::It,
|
||||
L::Hr,
|
||||
L::Tr,
|
||||
L::Ru,
|
||||
L::Cs,
|
||||
L::Id,
|
||||
L::Es,
|
||||
L::EsMx,
|
||||
L::Es419,
|
||||
L::EsUy,
|
||||
L::Gu,
|
||||
L::Hi,
|
||||
L::De,
|
||||
fr,
|
||||
L::Other,
|
||||
]
|
||||
}
|
||||
|
||||
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 spans: Vec<(Range<usize>, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), langs[l as usize % langs.len()])).collect();
|
||||
fn mixed_spans_never_panic(s in "\\PC{0,60}", cuts in proptest::collection::vec((0usize..80, 0usize..80, proptest::sample::select(every_lang())), 0..6)) {
|
||||
let spans: Vec<(Range<usize>, ProofLang)> = cuts.iter().map(|&(a, b, l)| (a.min(b)..a.max(b), l)).collect();
|
||||
for i in check_text(&s, &spans) {
|
||||
proptest::prop_assert!(i.start <= i.end && i.end <= s.len());
|
||||
}
|
||||
|
||||
@@ -23,8 +23,8 @@ mod para_props;
|
||||
mod table_props;
|
||||
|
||||
pub use char_props::{
|
||||
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
|
||||
VertAlign,
|
||||
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, LinkHistory, NumChange, PropChange,
|
||||
ThemeFont, Underline, VertAlign,
|
||||
};
|
||||
pub use color::{Rgb, TextColor};
|
||||
pub use para_props::{
|
||||
|
||||
@@ -165,6 +165,18 @@ impl ThemeFont {
|
||||
}
|
||||
}
|
||||
|
||||
/// A hyperlink's `w:history` when a .docx file didn't have it on. Only the .docx reader sets one.
|
||||
/// A link with none, whether made in the app, read from another format or read with history on,
|
||||
/// is written with history on, so it reads back the same.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LinkHistory {
|
||||
/// `w:history` was off.
|
||||
Off,
|
||||
/// The hyperlink had no `w:history`, so none is written back.
|
||||
Omitted,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VertAlign {
|
||||
@@ -435,6 +447,10 @@ pub struct CharProps {
|
||||
/// Optional ScreenTip for the hyperlink. Runs from one link can share its text.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub link_tooltip: Option<Arc<str>>,
|
||||
/// The hyperlink's `w:history` when a .docx file had it off or left it out. `None` writes it
|
||||
/// on, as Word does for a new link.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub link_history: Option<LinkHistory>,
|
||||
/// Tracked insertion: index into `Document::revisions`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ins: Option<u32>,
|
||||
@@ -572,6 +588,7 @@ impl CharProps {
|
||||
c.style = None;
|
||||
}
|
||||
c.link_tooltip = None;
|
||||
c.link_history = None;
|
||||
c
|
||||
}
|
||||
|
||||
@@ -632,9 +649,10 @@ impl CharProps {
|
||||
}
|
||||
|
||||
fn minus_document_marks(&mut self, base: &CharProps) {
|
||||
if self.link == base.link && self.link_tooltip == base.link_tooltip {
|
||||
if self.link == base.link && self.link_tooltip == base.link_tooltip && self.link_history == base.link_history {
|
||||
self.link = None;
|
||||
self.link_tooltip = None;
|
||||
self.link_history = None;
|
||||
}
|
||||
drop_same_fields!(self, base; ins, del, ligatures);
|
||||
}
|
||||
@@ -689,6 +707,7 @@ impl CharProps {
|
||||
if let Some(link) = &patch.link {
|
||||
self.link = Some(link.clone());
|
||||
self.link_tooltip = patch.link_tooltip.clone();
|
||||
self.link_history = patch.link_history;
|
||||
}
|
||||
overlay_fields!(self, patch; ins, del, fmt_change, ligatures);
|
||||
}
|
||||
@@ -716,6 +735,7 @@ impl CharProps {
|
||||
CharProps {
|
||||
link: self.link.clone(),
|
||||
link_tooltip: self.link_tooltip.clone(),
|
||||
link_history: self.link_history,
|
||||
ins: self.ins,
|
||||
del: self.del,
|
||||
fmt_change: self.fmt_change.clone(),
|
||||
@@ -726,6 +746,6 @@ impl CharProps {
|
||||
}
|
||||
/// Just the formatting: without the link, revision marks and tracked formatting change.
|
||||
pub fn formatting(&self) -> CharProps {
|
||||
CharProps { link: None, link_tooltip: None, ins: None, del: None, fmt_change: None, ..self.clone() }
|
||||
CharProps { link: None, link_tooltip: None, link_history: None, ins: None, del: None, fmt_change: None, ..self.clone() }
|
||||
}
|
||||
}
|
||||
@@ -124,8 +124,9 @@ pub struct Settings {
|
||||
pub protect_hash: Vec<(String, String)>,
|
||||
/// Word compatibility mode the document is laid out in (`compatibilityMode`): 15 for Word
|
||||
/// 2013 and later, which places a table's border at the margin rather than its text and lets
|
||||
/// justified lines shrink their spaces to fit more text.
|
||||
pub compat_mode: u32,
|
||||
/// justified lines shrink their spaces to fit more text. `None` when omitted from the file.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub compat_mode: Option<u32>,
|
||||
/// Fonts the document's font table classes as roman (serif, `w:family w:val="roman"`): Word
|
||||
/// draws one that isn't installed in a serif face.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
@@ -326,7 +327,7 @@ impl Default for Settings {
|
||||
protection: None,
|
||||
protect_formatting: false,
|
||||
protect_hash: Vec::new(),
|
||||
compat_mode: COMPAT_MODE_CURRENT,
|
||||
compat_mode: Some(COMPAT_MODE_CURRENT),
|
||||
roman_fonts: Vec::new(),
|
||||
sum_paragraph_spacing: false,
|
||||
do_not_expand_shift_return: false,
|
||||
@@ -346,3 +347,11 @@ impl Default for Settings {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// The effective compatibility mode: the authored mode, or Word 2007 (`LEGACY_COMPAT_MODE` = 12)
|
||||
/// when omitted from the file.
|
||||
pub fn effective_compat_mode(&self) -> u32 {
|
||||
self.compat_mode.unwrap_or(LEGACY_COMPAT_MODE)
|
||||
}
|
||||
}
|
||||
@@ -309,6 +309,27 @@ fn json_round_trip() {
|
||||
assert_eq!(back.para(StoryRef::Body, &Path::top(0)).unwrap().runs[0].props.bold, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_compat_mode_serde_round_trip() {
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(s.compat_mode, Some(COMPAT_MODE_CURRENT));
|
||||
s.compat_mode = None;
|
||||
let json = serde_json::to_string(&s).unwrap();
|
||||
assert!(!json.contains("compatMode"), "expected compatMode omitted: {json}");
|
||||
let back: Settings = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back.compat_mode, None);
|
||||
assert_eq!(back.effective_compat_mode(), LEGACY_COMPAT_MODE);
|
||||
|
||||
let from_empty: Settings = serde_json::from_str("{}").unwrap();
|
||||
assert_eq!(from_empty.compat_mode, None);
|
||||
|
||||
s.compat_mode = Some(14);
|
||||
let json14 = serde_json::to_string(&s).unwrap();
|
||||
assert!(json14.contains(r#""compatMode":14"#), "{json14}");
|
||||
let back14: Settings = serde_json::from_str(&json14).unwrap();
|
||||
assert_eq!(back14.compat_mode, Some(14));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_nonempty_repairs() {
|
||||
let mut d = Document::new();
|
||||
|
||||
Reference in new issue
Block a user