mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
Merge pull request #1287 from vangel76/feat/rtf-rtl-paragraphs
RTF keeps right-to-left paragraph direction
This commit is contained in:
8 files changed
+171
-3
No files matched your search
@@ -493,6 +493,8 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
|
||||
kind,
|
||||
list,
|
||||
align: p.props.align,
|
||||
// Direction can come from the paragraph's style (`w:bidi` in the style's pPr).
|
||||
rtl: doc.styles.resolve_para(&p.props).bidi,
|
||||
page_break: p.props.page_break_before.unwrap_or(false),
|
||||
keep_next: p.props.keep_next.unwrap_or(false),
|
||||
inlines: Vec::new(),
|
||||
@@ -536,6 +538,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
|
||||
kind,
|
||||
list: None,
|
||||
align: p.props.align,
|
||||
rtl: out.rtl,
|
||||
page_break: true,
|
||||
keep_next: p.props.keep_next.unwrap_or(false),
|
||||
inlines: Vec::new(),
|
||||
@@ -658,7 +661,10 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
|
||||
{
|
||||
(li.list, li.label) = (0, None);
|
||||
}
|
||||
let old = Para { kind, list, align: c.old.align, page_break: c.old.page_break_before.unwrap_or(false), ..Default::default() };
|
||||
// Direction resolved like the current paragraph's: the old properties' own `w:bidi`, else
|
||||
// the style's.
|
||||
let rtl = doc.styles.resolve_para(&c.old).bidi;
|
||||
let old = Para { kind, list, align: c.old.align, rtl, page_break: c.old.page_break_before.unwrap_or(false), ..Default::default() };
|
||||
Box::new(FmtChange { mark: rev_mark(doc, c.rev), old })
|
||||
});
|
||||
}
|
||||
|
||||
@@ -159,6 +159,9 @@ fn para_props(p: &Para, list_num: Option<u32>) -> ParaProps {
|
||||
out.numbering = Some(NumRef { num, level: li.level.min(8) });
|
||||
}
|
||||
out.align = p.align;
|
||||
if p.rtl {
|
||||
out.bidi = Some(true);
|
||||
}
|
||||
let sp = p.spacing;
|
||||
out.space_before = sp.before;
|
||||
out.space_after = sp.after;
|
||||
|
||||
@@ -676,6 +676,8 @@ pub struct Para {
|
||||
pub kind: Kind,
|
||||
pub list: Option<ListInfo>,
|
||||
pub align: Option<Align>,
|
||||
/// The paragraph reads right to left (OOXML `w:bidi`, RTF `\rtlpar`).
|
||||
pub rtl: bool,
|
||||
pub page_break: bool,
|
||||
/// Keep the paragraph on the same page as the next one (ODT `fo:keep-with-next`).
|
||||
pub keep_next: bool,
|
||||
|
||||
@@ -659,6 +659,10 @@ impl Writer {
|
||||
Some(Align::Distribute) => out.push_str("\\qd"),
|
||||
_ => out.push_str("\\ql"),
|
||||
}
|
||||
// The paragraph's text direction, as Word writes it (`\rtlpar`; `\ltrpar` is the default).
|
||||
if p.rtl {
|
||||
out.push_str("\\rtlpar");
|
||||
}
|
||||
if p.page_break {
|
||||
out.push_str("\\pagebb");
|
||||
}
|
||||
|
||||
@@ -148,6 +148,8 @@ pub(super) struct St {
|
||||
pub(super) hidden: bool,
|
||||
// Paragraph properties.
|
||||
pub(super) align: Option<Align>,
|
||||
/// `\rtlpar`: the paragraph reads right to left.
|
||||
pub(super) rtldir: Option<bool>,
|
||||
pub(super) style: i32,
|
||||
pub(super) intbl: bool,
|
||||
pub(super) ls: Option<i32>,
|
||||
@@ -185,6 +187,7 @@ impl Default for St {
|
||||
uc: 1,
|
||||
hidden: false,
|
||||
align: None,
|
||||
rtldir: None,
|
||||
style: 0,
|
||||
intbl: false,
|
||||
ls: None,
|
||||
|
||||
@@ -30,6 +30,7 @@ impl Reader {
|
||||
out.italic = out.italic.or(d.italic);
|
||||
out.size = out.size.or(d.size);
|
||||
out.font = out.font.or(d.font);
|
||||
out.rtl = out.rtl.or(d.rtl);
|
||||
cur = d.based_on;
|
||||
}
|
||||
out
|
||||
@@ -87,6 +88,8 @@ impl Reader {
|
||||
pub(super) fn para_props(&self, st: &St) -> Para {
|
||||
let mut p = Para::new(self.para_kind(st));
|
||||
p.align = st.align;
|
||||
// Direct `\rtlpar`/`\ltrpar` wins over the style's direction.
|
||||
p.rtl = st.rtldir.or_else(|| self.file_style(st.style).rtl).unwrap_or(false);
|
||||
p.page_break = st.pagebb;
|
||||
p.spacing = spacing(st);
|
||||
p.borders = st.borders.any_visible().then_some(st.borders);
|
||||
@@ -135,6 +138,8 @@ pub(super) struct StyleDef {
|
||||
pub(super) size: Option<f32>,
|
||||
/// A `\fonttbl` index, named when it's used (the table may follow).
|
||||
pub(super) font: Option<i32>,
|
||||
/// `\rtlpar` (`Some(true)`) or `\ltrpar`: the paragraph direction the style sets.
|
||||
pub(super) rtl: Option<bool>,
|
||||
}
|
||||
|
||||
/// Clear from `f` the formatting a paragraph of kind `kind` gets from its style, whose
|
||||
@@ -203,6 +208,10 @@ pub(super) fn is_format_word(w: &str) -> bool {
|
||||
| "s"
|
||||
| "outlinelevel"
|
||||
| "pagebb"
|
||||
| "rtlpar"
|
||||
| "ltrpar"
|
||||
| "rtldir"
|
||||
| "ltrdir"
|
||||
| "intbl"
|
||||
| "ls"
|
||||
| "ilvl"
|
||||
|
||||
@@ -38,6 +38,86 @@ fn basic_reader() {
|
||||
assert!(matches!(&l.inlines[0], Inline::Text(_, f) if f.link.as_deref() == Some("http://a.b")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_paragraphs_read_and_write_their_direction() {
|
||||
// Word writes an RTL paragraph as `\rtlpar` (`\ltrpar` for LTR); reading it keeps the
|
||||
// direction as w:bidi on the document paragraph, and export writes it back.
|
||||
let rtf = br#"{\rtf1\ansi\pard\rtlpar RTL\par\pard\ltrpar LTR\par\pard plain\par}"#;
|
||||
let flow = parse(rtf).unwrap();
|
||||
let paras: Vec<&Para> = flow.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p) } else { None }).collect();
|
||||
assert!(paras[0].rtl, "rtlpar sets the direction");
|
||||
assert!(!paras[1].rtl && !paras[2].rtl, "ltrpar and no word: not RTL");
|
||||
// \rtldir and \ltrdir, which some writers used for paragraphs, are read too.
|
||||
let old = parse(br#"{\rtf1\ansi\pard\rtldir RTL\par\pard\ltrdir LTR\par}"#).unwrap();
|
||||
let old: Vec<&Para> = old.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p) } else { None }).collect();
|
||||
assert!(old[0].rtl && !old[1].rtl, "rtldir and ltrdir are read");
|
||||
// \pard resets the direction.
|
||||
let reset = parse(br#"{\rtf1\ansi\pard\rtlpar A\par\pard B\par}"#).unwrap();
|
||||
let reset: Vec<&Para> = reset.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p) } else { None }).collect();
|
||||
assert!(reset[0].rtl && !reset[1].rtl, "pard resets the direction");
|
||||
// Import keeps it as bidi on the document paragraph.
|
||||
let bidi = |d: &Document| {
|
||||
d.body.iter().filter_map(|b| if let Block::Para(p) = &**b { Some(p.props.bidi.unwrap_or(false)) } else { None }).collect::<Vec<_>>()
|
||||
};
|
||||
let doc = import(rtf).unwrap();
|
||||
assert_eq!(bidi(&doc), [true, false, false]);
|
||||
// Export writes \rtlpar once, and not the \rtldir.
|
||||
let out = export(&doc);
|
||||
assert_eq!(out.matches("\\rtlpar").count(), 1, "{out}");
|
||||
assert!(!out.contains("rtldir"), "{out}");
|
||||
assert_eq!(bidi(&import(out.as_bytes()).unwrap()), [true, false, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtl_paragraph_styles_carry_their_direction() {
|
||||
// Word often writes the direction in the style: `{\s1\rtlpar RTL;}` then `\pard\s1`.
|
||||
let rtf = br#"{\rtf1\ansi{\stylesheet{\s0 Normal;}{\s1\rtlpar RTL;}{\s2\sbasedon1 Child;}{\s3\sbasedon1\ltrpar Back;}}
|
||||
\pard\s1 A\par\pard\s2 B\par\pard\s3 C\par\pard\s1\ltrpar D\par\pard\s0\rtlpar E\par\pard F\par}"#;
|
||||
let flow = parse(rtf).unwrap();
|
||||
let rtl: Vec<bool> = flow.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p.rtl) } else { None }).collect();
|
||||
// A: style. B: inherited from the base style. C: the style overrides its base. D: direct
|
||||
// \ltrpar beats the style. E: direct \rtlpar on Normal. F: \pard drops direct formatting.
|
||||
assert_eq!(rtl, [true, true, false, false, true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oldpprops_keep_the_old_paragraph_direction() {
|
||||
// A tracked change of direction: now LTR, before RTL (`\rtlpar` in the old properties).
|
||||
let rtf = br"{\rtf1\ansi{\*\revtbl {Unknown;}{Alice;}}
|
||||
\pard\ltrpar\prauth1\prdate-2014675576{\*\oldpprops \pard \rtlpar}A\par}";
|
||||
let flow = parse(rtf).unwrap();
|
||||
let Some(FBlock::Para(p)) = flow.blocks.first() else { panic!("no paragraph") };
|
||||
assert!(!p.rtl);
|
||||
assert!(p.fmt_change.as_deref().expect("paragraph change").old.rtl, "old direction is RTL");
|
||||
let doc = import(rtf).unwrap();
|
||||
let c = doc_paras(&doc)[0].props.fmt_change.as_deref().expect("change");
|
||||
assert_eq!(c.old.bidi, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_rtl_to_ltr_change_from_a_document_keeps_the_old_direction() {
|
||||
use craft_wordmodel::props::{CharProps, ParaProps, PropChange};
|
||||
use craft_wordmodel::{Revision, RevisionKind};
|
||||
// Document origin (not RTF): now LTR, before RTL.
|
||||
let mut p = craft_wordmodel::Paragraph::with_text("A", CharProps::default());
|
||||
p.props.bidi = Some(false);
|
||||
p.props.fmt_change = PropChange::boxed(0, ParaProps { bidi: Some(true), ..Default::default() });
|
||||
let doc = doc_with(vec![p], vec![Revision::new(RevisionKind::Format, "Bob", "2025-01-02T08:05:00Z")]);
|
||||
let flow = model::from_doc_tracked(&doc);
|
||||
let Some(FBlock::Para(fp)) = flow.blocks.first() else { panic!("no paragraph") };
|
||||
assert!(!fp.rtl);
|
||||
assert!(fp.fmt_change.as_deref().expect("change").old.rtl, "snapshot keeps RTL");
|
||||
let rtf = export(&doc);
|
||||
assert!(rtf.contains("{\\*\\oldpprops"), "{rtf}");
|
||||
let back = import(rtf.as_bytes()).unwrap();
|
||||
let p = doc_paras(&back)[0];
|
||||
assert_ne!(p.props.bidi, Some(true), "current direction is LTR");
|
||||
let change = p.props.fmt_change.as_deref().expect("change read back");
|
||||
assert_eq!(change.old.bidi, Some(true));
|
||||
// Reject restores RTL.
|
||||
assert_eq!(change.old.formatting().bidi, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stylesheet_names_take_unicode_escapes() {
|
||||
// \u116?=t \u105?=i \u116?=t \u108?=l \u101?=e — how Word writes a non-Latin style name.
|
||||
@@ -1863,3 +1943,46 @@ fn compound_borders_round_trip() {
|
||||
let back = import(export(&d).as_bytes()).unwrap();
|
||||
assert_eq!(tops(&back), want);
|
||||
}
|
||||
|
||||
fn para_aligns(flow: &Flow) -> Vec<(bool, Option<Align>)> {
|
||||
flow.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some((p.rtl, p.align)) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alignment_words_after_rtlpar_mean_start_and_end() {
|
||||
// Word reads `\ql`/`\qr` that follow `\rtlpar` as start/end (the model's alignment is
|
||||
// logical), so `\rtlpar\qr` sits at the right edge and `\rtlpar\ql` at the left edge.
|
||||
// Words written before `\rtlpar` keep their plain meaning (checked in Word by saving to DOCX:
|
||||
// `\qr\rtlpar` gives jc=right, i.e. end, in the bidi paragraph; `\ql\rtlpar` gives no jc).
|
||||
let rtf = br#"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}\pard LTR one.\par \pard\rtlpar\qr A.\par \pard\rtlpar B.\par \pard\ltrpar Back.\par \pard\rtlpar\ql C.\par \pard\rtlpar\qc D.\par \pard\ql\rtlpar E.\par \pard\qr\rtlpar F.\par \pard\rtlpar\ltrpar\qr G.\par}"#;
|
||||
let got = para_aligns(&parse(rtf).unwrap());
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(false, None),
|
||||
(true, Some(Align::Left)),
|
||||
(true, None),
|
||||
(false, None),
|
||||
(true, Some(Align::Right)),
|
||||
(true, Some(Align::Center)),
|
||||
(true, Some(Align::Left)),
|
||||
(true, Some(Align::Right)),
|
||||
(false, Some(Align::Right)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alignment_survives_an_export_import_round_trip() {
|
||||
let rtf = br#"{\rtf1\ansi\pard\ql L.\par \pard\qr R.\par \pard\qc C.\par \pard\rtlpar\qr start.\par \pard\rtlpar\ql end.\par \pard\rtlpar\qc mid.\par \pard\rtlpar plain.\par}"#;
|
||||
let first = para_aligns(&parse(rtf).unwrap());
|
||||
let doc = import(rtf).unwrap();
|
||||
let out = export(&doc);
|
||||
let second = para_aligns(&parse(out.as_bytes()).unwrap());
|
||||
let norm = |v: Vec<(bool, Option<Align>)>| v.into_iter().map(|(r, a)| (r, a.filter(|a| *a != Align::Left))).collect::<Vec<_>>();
|
||||
assert_eq!(norm(first), norm(second.clone()), "{out}");
|
||||
// `\rtlpar\qr` is start (no explicit alignment in the model) and `\rtlpar\ql` is end.
|
||||
assert_eq!(norm(second)[3..5], [(true, None), (true, Some(Align::Right))], "{out}");
|
||||
// The export writes the alignment before the direction, which Word reads as logical start/end.
|
||||
assert!(out.contains("\\qr\\rtlpar"), "{out}");
|
||||
}
|
||||
@@ -3,6 +3,18 @@ use super::styles::{StyleDef, is_char_format_word, is_format_word};
|
||||
use super::{Align, Fmt, Reader, VAlign, model};
|
||||
|
||||
impl Reader {
|
||||
/// The logical alignment for a side word (`Left` for `\ql`, `Right` for `\qr`). The model's
|
||||
/// alignment is logical (start/end), and Word reads a side word that comes after `\rtlpar` as
|
||||
/// start/end: the sides swap in a paragraph already marked right to left. Before `\rtlpar`
|
||||
/// the side keeps its plain meaning, which is why the writer puts the alignment first.
|
||||
fn side_align(&self, side: Align) -> Align {
|
||||
match (self.st.rtldir, side) {
|
||||
(Some(true), Align::Left) => Align::Right,
|
||||
(Some(true), Align::Right) => Align::Left,
|
||||
_ => side,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn word(&mut self, w: &str, p: Option<i32>, starred: bool, first_in_group: bool) {
|
||||
// Every control word ends a multibyte run: the code page it is read in may change here
|
||||
// (`\f`, `\fcharset`, `\cpg`, `\ansicpg`, `\pard`), and `\par` must see the text before it.
|
||||
@@ -166,11 +178,15 @@ impl Reader {
|
||||
"cf" => self.st.fmt.color = self.colors.get(pv.max(0) as usize).copied().flatten(),
|
||||
"highlight" | "chcbpat" | "cb" => self.st.fmt.background = self.colors.get(pv.max(0) as usize).copied().flatten(),
|
||||
"v" => self.st.hidden = on,
|
||||
"ql" => self.st.align = Some(Align::Left),
|
||||
"ql" => self.st.align = Some(self.side_align(Align::Left)),
|
||||
"qc" => self.st.align = Some(Align::Center),
|
||||
"qr" => self.st.align = Some(Align::Right),
|
||||
"qr" => self.st.align = Some(self.side_align(Align::Right)),
|
||||
"qj" => self.st.align = Some(Align::Justify),
|
||||
"qd" => self.st.align = Some(Align::Distribute),
|
||||
// `\rtldir`/`\ltrdir` are not paragraph words (they set a table's or section's
|
||||
// direction in RTF); some writers used them for paragraphs, so they are read too.
|
||||
"rtlpar" | "rtldir" => self.st.rtldir = Some(true),
|
||||
"ltrpar" | "ltrdir" => self.st.rtldir = Some(false),
|
||||
"s" => self.st.style = pv,
|
||||
"outlinelevel" => self.st.outline = Some(pv.clamp(0, 9) as u8),
|
||||
"pagebb" => self.st.pagebb = on,
|
||||
@@ -417,6 +433,8 @@ impl Reader {
|
||||
"i" => def.italic = Some(on),
|
||||
"fs" => def.size = (value > 0).then(|| (value as f32 / 2.0).clamp(1.0, 1638.0)),
|
||||
"f" => def.font = Some(value),
|
||||
"rtlpar" | "rtldir" => def.rtl = Some(true),
|
||||
"ltrpar" | "ltrdir" => def.rtl = Some(false),
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
|
||||
Reference in new issue
Block a user