feat: write GREP and line styles, more nested style codes and composite fonts

- GREP styles (0x1BBA) and line styles (0x1BBB) are decoded and written
  as AllGREPStyles and AllLineStyles on styles, text defaults and
  paragraph ranges; empty lists are not written.
- Nested style delimiters (^c), ^t, ^L, ^p, ^9 and ^S in brackets map to
  Dropcap, Tabs, Repeat, EndNestedStyle, Digits and Sentence.
- An AppliedFont whose family name (with <hhhh> escapes decoded) is a
  composite font's name is written as CompositeFont/<name>, except in
  character styles, which keep the name.

compare.py --exclude own/, trustworthy pairs: ParagraphStyle
AllGREPStyles 152/152, TextDefault 48/48, text ranges 320/320,
AllLineStyles 6/6 and 9/9, ParagraphStyle AllNestedStyles 54 -> 124/124,
TextDefault 4 -> 10/10, ParagraphStyle AppliedFont 4,664 -> 4,803/4,804,
TextDefault 1,232 -> 1,250/1,251, text ranges 84,909 -> 85,587/85,587.
No new extra values; no pair loses values.
This commit is contained in:
aiongg committed 2026-10-10 12:51:16 +00:00
1 parent f1a9abeb42
commit bdf62e7646
8 files changed
+421 -52

No files matched your search

+55 -6
View File
@@ -301,9 +301,9 @@ references, 0x1B28 for point size), so the converter decodes a text value
by the layout of its attribute. The attributes whose value is not a
single number have their layout listed in `text_layout`
(`src/model/attrs.rs`): string values (`FontStyle`) are a flag byte
followed by an in-object string; tab lists, nested styles, bullet
characters, points, ruby text and cell edge stroke types are described
below. Other values are numbers, decoded by length: 8 bytes f64, 4 bytes
followed by an in-object string; tab lists, nested, GREP and line
styles, bullet characters, points, ruby text and cell edge stroke types
are described below. Other values are numbers, decoded by length: 8 bytes f64, 4 bytes
u32, 2 bytes u16. A value that does not fit its attribute's layout is
kept undecoded and not written.
@@ -346,7 +346,7 @@ styles with INDD styles of the same name (486 styles), then checked with
| 0x1B27 | `SpaceAfter` | f64 | 42/42 ranges |
| 0x1B29 | `TabList` (Properties) | list; see below | 110/110 styles |
| 0x1B2A | `Underline` | 1 = true | 81/81 ranges |
| 0x1B2B | `AppliedFont` (Properties) | font family UID | 1,071/1,071 ranges, 236/247 styles |
| 0x1B2B | `AppliedFont` (Properties) | font family UID; a composite font as an object (below) | 1,071/1,071 ranges, 236/247 styles |
| 0x1B2C | `OTFFigureStyle` | 0 TabularLining (23 runs, 5 styles), 1 ProportionalOldstyle, 2 ProportionalLining, 4 Default | 4/4 ranges, 138/138 styles |
| 0x1B2E | `MaximumWordSpacing` | fraction ×100 | 77/77 styles |
| 0x1B2F | `MinimumWordSpacing` | fraction ×100 | 77/77 styles |
@@ -371,7 +371,7 @@ styles with INDD styles of the same name (486 styles), then checked with
| 0x1B5D | `RuleBelow` | 1 = true | 83/83 styles |
| 0x1B6A | `ParagraphBreakType` | 0 Anywhere, 1 NextColumn, 2 NextPage, 3 NextFrame, 4 NextOddPage (below) | 11/11 ranges, 78/78 styles |
| 0x1B6B | `SingleWordJustification` | 0 LeftAlign, 3 FullyJustified | 80/80 styles |
| 0x1B75 | `AllNestedStyles` (Properties) | list; see below | 14/14 styles |
| 0x1B75 | `AllNestedStyles` (Properties) | list; see below | 124/124 paragraph styles, 10/10 text defaults (1,251 trustworthy pairs) |
| 0x1B7E | `Justification` | 0 LeftAlign, 1 CenterAlign, 2 RightAlign, 3 FullyJustified, 4 LeftJustified, 5 CenterJustified, 6 RightJustified, 8 ToBindingSide, 9 AwayFromBindingSide (runs/styles for 3, 6, 8, 9: 34/1, 3/0, 2/1, 7/14) | 70/70 ranges |
| 0x1B80 | `DropcapDetail` | u32 | 5/5 ranges, 103/103 styles |
| 0x1B8C | `OTFContextualAlternate` | 1 = true | 220/220 ranges |
@@ -380,6 +380,8 @@ styles with INDD styles of the same name (486 styles), then checked with
| 0x1B94 | `UnderlineWeight` | f64 | 81/81 ranges |
| 0x1BB7 | `MiterLimit` | f64 | 161/161 ranges |
| 0x1BB9 | `EndJoin` | 0 MiterEndJoin, 1 RoundEndJoin | 86/86 styles |
| 0x1BBA | `AllGREPStyles` (Properties) | list; see below | 152/152 paragraph styles, 48/48 text defaults, 320/320 text ranges (1,251 trustworthy pairs) |
| 0x1BBB | `AllLineStyles` (Properties) | list; see below | 6/6 paragraph styles, 9/9 text ranges (1,251 trustworthy pairs) |
| 0x1BBD | `SpanColumnType` | 0 SingleColumn, 1 SpanColumns, 2 SplitColumns (69 runs, 10 styles) | 41/41 ranges, 94/94 styles |
| 0x1BBE | `SpanSplitColumnCount` (Properties) | u16; 1 = All | 12/12 ranges, 78/78 styles |
| 0x1BBF | `SplitColumnInsideGutter` | f64 | 155/155 ranges |
@@ -514,6 +516,12 @@ stored as text segments (see `objects.md`). The code gives `Delimiter`,
| digits after `)` or `]` | `Repetition`; no digits = 1 | a sample and its print PDF |
| `(^w)` | `AnyWord` | a sample and its print PDF |
| `(^?)` | `AnyCharacter` | a sample and its print PDF |
| `(^c)` | `Dropcap` | 54 `Dropcap` records in 18 pairs (with `^c`) |
| `^t` in brackets | `Tabs` | 9 records in 5 pairs (`[^t]`, `(^t)`, `(^t)2` seen) |
| `^L` in brackets | `Repeat`; the digits are `Repetition` | 41 records in 33 pairs (`(^L)2`, `(^L)4` seen) |
| `^p` in brackets | `EndNestedStyle` | 2 records in 1 pair |
| `^9` in brackets | `Digits` | 2 records in 1 pair (`[^9]`, `(^9)`) |
| `^S` in brackets | `Sentence` | 1 record in 1 pair |
The public pair has only single-character literals and repetition 1. The
last three rows rest on a sample and its print PDF:
@@ -535,8 +543,44 @@ last three rows rest on a sample and its print PDF:
words would keep full capitals, and that capital lies within them. So
`^?` counts characters: `AnyCharacter`.
The last six rows come from the 1,251 trustworthy pairs of the corpus
after 2026-10. Their reference IDMLs have 265 nested style records in
72 documents (styles, text defaults and text ranges; the record counts
above are these). The stored items map one to one onto the IDML
records, with the bracket giving `Inclusive` and the digits
`Repetition` as above: the converter reproduces `AllNestedStyles` of
124 of 124 paragraph styles, 10 of 10 text defaults, 274 of 274 text
ranges and 7 of 7 `Story/ParagraphStyleRange` elements. Without these
codes it reproduced 54 paragraph styles and 4 text defaults.
The converter leaves out a list that has any other code.
**GREP styles (0x1BBA).** The layout of nested styles, with a GREP
expression in place of the delimiter code: u32 count, then for each item
u32 character style UID (0 for none), u32 length *n* and the expression
as *n* UTF-16 code units in text segments. IDML writes
`AllGREPStyles` (`type="list"`), one `ListItem type="record"` per item in
stored order, with `AppliedCharacterStyle` (object) and `GrepExpression`
(string). Evidence over the 1,251 trustworthy pairs: every 0x1BBA value
of the paragraph styles parses and ends exactly after its last item; the
reference IDMLs have 494 such lists with 1,064 items, all of these two
fields. The converter reproduces 152 of 152 paragraph styles, 48 of 48
text defaults, 320 of 320 text ranges (`Story/ParagraphStyleRange` 110,
`Cell/ParagraphStyleRange` 94), with no extra value. A style's list is
its own value; IDML does not write an inherited one.
**Line styles (0x1BBB).** u32 count, then 8 bytes per item: u32
character style UID and u32 line count. IDML writes `AllLineStyles`,
one record per item: `AppliedCharacterStyle` (object), `LineCount`
(long) and `RepeatLast` (long). `RepeatLast` is −1 in all 9 list items of
the trustworthy reference IDMLs (3 documents) and no stored field holds
it, so the converter writes −1. Reproduced: 6 of 6 paragraph styles and
9 of 9 text ranges.
**Empty lists.** None of the 1,251 trustworthy reference IDMLs has an
`AllGREPStyles`, `AllLineStyles` or `AllNestedStyles` element without
items. The converter writes no GREP or line style list without items.
**Bullet character (0x1A406).** Two u32: the character type (0
`UnicodeOnly`, 1 `UnicodeWithFont`, 2 `GlyphWithFont`) and the character
value. IDML writes an empty `BulletChar` element with
@@ -995,6 +1039,8 @@ them out. Over the 489 trustworthy pairs (`measurement.md`):
| `NextStyle` of the root paragraph style | never (0 of 489) |
| `AllNestedStyles` of the root paragraph style | never (0 of 489) |
| `AllNestedStyles` of `TextDefault` | only when the list has items: absent in 485, written in the 4 with items |
| `AllGREPStyles` and `AllLineStyles` of the root paragraph style | never (0 of 1,251 trustworthy pairs after 2026-10); the root style stores a count of 0 in all 1,251 |
| `AllGREPStyles` of `TextDefault` | only when the list has items (48 of 48 such lists written, 1,251 trustworthy pairs) |
| Empty `TabList` of the root paragraph style | DOM 8 on: 482 of 482; DOM 7: 0 of 7 |
| `TabList` of `TextDefault` | DOM 8 on: in 482 of 482 (459 empty); DOM 7: 0 of 7 |
@@ -1072,4 +1118,7 @@ of these pairs aligns:
converter leaves other codes out.
**Font family names.** `AppliedFont` and `BulletsFont` name a font family
(class 0x3E03), and IDML writes the family's name. See `fonts.md`.
(class 0x3E03), and IDML writes the family's name. An `AppliedFont`
whose family stands for a composite font is written as a reference to
the composite font, except in character styles. See `fonts.md`,
composite fonts as applied fonts.
+36
View File
@@ -266,3 +266,39 @@ native name (family names, above).
`PlatformName` is `$ID/` in all 4,464 IDML fonts; the converter writes
that value (`idml-values.md`).
### Composite fonts as applied fonts
A text attribute `AppliedFont` (0x1B2B, `attributes.md`) that names a
composite font holds the UID of a font family (class 0x3E03) whose name
is the composite font's name; no `AppliedFont` value is the UID of the
0xCB02 object. The family name can contain escapes `<hhhh>`, four
hexadecimal digits of a UTF-16 code unit, for characters outside ASCII
(such as `<5927><6A19>`). Decoded, the name equals the composite font
name: in the conversions of the 1,251 trustworthy pairs, families with
escapes are used in 27 documents, and in 24 their decoded name is one of
the document's composite fonts. The other escaped names (in 3
documents) match no composite font and are written as family names, as
before.
IDML then writes `AppliedFont` as a reference to the composite font,
`<AppliedFont type="object">CompositeFont/<name></AppliedFont>`, in
every element but two. Over the trustworthy reference IDMLs, counting
every `AppliedFont` whose value is a composite font of the document:
| Element | Written as | Values (documents) |
|---|---|---:|
| `CharacterStyleRange` | object | 742 (30) |
| `ParagraphStyle` | object | 139 (27) |
| `TextDefault` | object | 18 (18) |
| `CharacterStyle` | string: the name | 48 (11) |
| `GridDataInformation` | string: the name | 12 (6) |
The converter writes the reference in paragraph styles, text defaults
and text ranges, and the name in character styles (grid settings do
not use these attribute lists). Reproduced over the trustworthy pairs:
`ParagraphStyle` `AppliedFont` 4,803 of 4,804 (4,664 by family name
alone), `TextDefault` 1,250 of 1,251 (1,232), text ranges 85,587 of
85,587 (84,909), `CharacterStyle` 1,102 of 1,102 (unchanged). The value
left in each of the first two is a family name that IDML writes in
English and the converter in the native script (family names, above).
+120 -6
View File
@@ -9,7 +9,7 @@
use super::*;
use crate::model::AnchorSettings;
use crate::model::attrs::{Delimiter, NestedStyle, TabStop};
use crate::model::attrs::{Delimiter, GrepStyle, LineStyle, NestedStyle, TabStop};
/// Frame fitting attributes of page items and object styles, in the
/// order IDML writes them (`docs/format/objects.md`).
@@ -350,6 +350,8 @@ pub(super) const TEXT_ATTRS: &[(u32, &str, Kind, bool)] = &[
false,
),
(0x1B75, "AllNestedStyles", Kind::NestedStyles, true),
(0x1BBA, "AllGREPStyles", Kind::GrepStyles, true),
(0x1BBB, "AllLineStyles", Kind::LineStyles, true),
(
0x42C0,
"TreatIdeographicSpaceAsSpace",
@@ -1430,6 +1432,11 @@ pub(super) fn delimiter_field(d: &Delimiter) -> Field {
Delimiter::Dropcap => enumeration("Dropcap"),
Delimiter::AnyWord => enumeration("AnyWord"),
Delimiter::AnyCharacter => enumeration("AnyCharacter"),
Delimiter::Tabs => enumeration("Tabs"),
Delimiter::EndNestedStyle => enumeration("EndNestedStyle"),
Delimiter::Digits => enumeration("Digits"),
Delimiter::Sentence => enumeration("Sentence"),
Delimiter::Repeat => enumeration("Repeat"),
Delimiter::Character(c) => ("Delimiter", "string", c.clone()),
}
}
@@ -1437,9 +1444,24 @@ pub(super) fn delimiter_field(d: &Delimiter) -> Field {
impl Writer<'_> {
/// IDML attributes and properties for a text attribute list.
pub(super) fn text_attrs(&self, attrs: &Attrs) -> (Vec<(&'static str, String)>, Vec<Property>) {
self.text_attrs_of(attrs, false)
}
/// Like [`Writer::text_attrs`]; a character style (`character_style`)
/// names a composite font by its family name (`docs/format/fonts.md`,
/// composite fonts as applied fonts).
pub(super) fn text_attrs_of(
&self,
attrs: &Attrs,
character_style: bool,
) -> (Vec<(&'static str, String)>, Vec<Property>) {
let mut plain = Vec::new();
let mut props = Vec::new();
for &(id, name, kind, in_props) in TEXT_ATTRS {
let kind = match kind {
Kind::Font if character_style => Kind::FamilyName,
k => k,
};
// IDML has `MergeConsecutiveParaBorders` from version 13.1
// (attributes.md).
if id == 0x1DF1F && !self.saved_by((13, 1)) {
@@ -1497,11 +1519,7 @@ impl Writer<'_> {
.iter()
.map(|n| {
vec![
(
"AppliedCharacterStyle",
"object",
self.style_ref(Some(n.style).filter(|&u| u != 0), false),
),
self.applied_character_style(n.style),
delimiter_field(&n.delimiter),
("Repetition", "long", n.repetition.to_string()),
("Inclusive", "boolean", n.inclusive.to_string()),
@@ -1510,6 +1528,42 @@ impl Writer<'_> {
.collect()
}
/// Records of an `AllGREPStyles` list. See `docs/format/attributes.md`.
pub(super) fn grep_styles(&self, styles: &[GrepStyle]) -> Vec<Vec<Field>> {
styles
.iter()
.map(|g| {
vec![
self.applied_character_style(g.style),
("GrepExpression", "string", g.expression.clone()),
]
})
.collect()
}
/// Records of an `AllLineStyles` list. `RepeatLast` is −1 in every
/// sample and has no stored field (`docs/format/attributes.md`).
pub(super) fn line_styles(&self, styles: &[LineStyle]) -> Vec<Vec<Field>> {
styles
.iter()
.map(|l| {
vec![
self.applied_character_style(l.style),
("LineCount", "long", l.lines.to_string()),
("RepeatLast", "long", "-1".into()),
]
})
.collect()
}
fn applied_character_style(&self, uid: u32) -> Field {
(
"AppliedCharacterStyle",
"object",
self.style_ref(Some(uid).filter(|&u| u != 0), false),
)
}
/// Page item attributes from an attribute list, as IDML values.
pub(super) fn item_attr_values(&self, attrs: &Attrs) -> Vec<(&'static str, String)> {
self.attr_values(attrs, ITEM_ATTRS)
@@ -1814,6 +1868,66 @@ mod tests {
assert!(plain.is_empty());
}
#[test]
fn writes_composite_fonts_and_grep_styles() {
let mut doc = Document::default();
doc.fonts.insert(
5,
crate::model::FontFamily {
uid: 5,
name: "<5927><6A19>".into(),
builtin: false,
native_name: String::new(),
fonts: Vec::new(),
writing_script: 0,
},
);
doc.composite_fonts.push(crate::model::CompositeFont {
uid: 9,
name: crate::model::Name {
builtin: false,
name: "\u{5927}\u{6A19}".into(),
},
entries: Vec::new(),
});
let w = Writer::for_test(&doc);
let grep = |items| Value::StyleList {
count: 1,
items: Some(crate::model::attrs::StyleItems::Grep(items)),
};
let mut a = Attrs::default();
a.values = vec![
(0x1B2B, Value::Ref(5)),
(
0x1BBA,
grep(vec![GrepStyle {
style: 0,
expression: "@|#".into(),
}]),
),
(
0x1BBB,
Value::StyleList {
count: 0,
items: Some(crate::model::attrs::StyleItems::Line(Vec::new())),
},
),
];
let (_, props) = w.text_attrs(&a);
let names: Vec<&str> = props.iter().map(|p| p.0).collect();
// An empty line style list is left out.
assert_eq!(names, ["AppliedFont", "AllGREPStyles"]);
assert_eq!(props[0].1, "object");
assert!(matches!(&props[0].2, PropValue::Text(t) if t == "CompositeFont/\u{5927}\u{6A19}"));
let PropValue::List(items) = &props[1].2 else {
panic!("not a list");
};
assert_eq!(items[0][1], ("GrepExpression", "string", "@|#".into()));
// A character style names the composite font by its family name.
let (_, props) = w.text_attrs_of(&a, true);
assert_eq!(props[0].1, "string");
}
#[test]
fn writes_ruby_and_warichu_attributes() {
let doc = Document::default();
+35 -3
View File
@@ -8,6 +8,7 @@
use super::*;
use crate::model::Value;
use crate::model::attrs::StyleItems;
/// How an attribute value is written in IDML.
#[derive(Clone, Copy)]
@@ -58,8 +59,11 @@ pub(super) enum Kind {
SwatchOrText,
/// A swatch, or 0 for the swatch `None`.
SwatchOrNone,
/// A font family.
/// A font family, or the composite font of that name as an object
/// (`docs/format/fonts.md`, composite fonts as applied fonts).
Font,
/// A font family, written as its name also for a composite font.
FamilyName,
/// A font family, or 0 for none (`$ID/`).
FontOrNone,
/// A numbering list UID.
@@ -87,6 +91,10 @@ pub(super) enum Kind {
TabList,
/// A list of nested styles (`AllNestedStyles`).
NestedStyles,
/// A list of GREP styles (`AllGREPStyles`); left out when empty.
GrepStyles,
/// A list of line styles (`AllLineStyles`); left out when empty.
LineStyles,
/// A bullet character (`BulletChar`).
BulletChar,
}
@@ -212,7 +220,16 @@ impl Writer<'_> {
.as_u32()
.and_then(|u| self.doc.numbering_lists.iter().find(|l| l.uid == u))
.map(|l| text("object", format!("NumberingList/{}", self_name(&l.name)))),
Kind::Font => v
Kind::Font => v.as_u32().and_then(|u| self.doc.fonts.get(&u)).map(|f| {
match self.composite_font_of(f) {
Some(c) => text(
"object",
format!("CompositeFont/{}", self_name(&c.name.idml())),
),
None => text("string", self.family_names(f).0),
}
}),
Kind::FamilyName => v
.as_u32()
.and_then(|u| self.doc.fonts.get(&u))
.map(|f| text("string", self.family_names(f).0)),
@@ -278,10 +295,25 @@ impl Writer<'_> {
},
Kind::NestedStyles => match v {
Value::StyleList {
nested: Some(n), ..
items: Some(StyleItems::Nested(n)),
..
} => Some(("list", PropValue::List(self.nested_styles(n)))),
_ => None,
},
Kind::GrepStyles => match v {
Value::StyleList {
items: Some(StyleItems::Grep(g)),
..
} if !g.is_empty() => Some(("list", PropValue::List(self.grep_styles(g)))),
_ => None,
},
Kind::LineStyles => match v {
Value::StyleList {
items: Some(StyleItems::Line(l)),
..
} if !l.is_empty() => Some(("list", PropValue::List(self.line_styles(l)))),
_ => None,
},
Kind::BulletChar => match *v {
Value::BulletChar { kind, value } => bullet_char(kind, value).map(|a| ("", a)),
_ => None,
+17
View File
@@ -170,6 +170,23 @@ impl Writer<'_> {
(idml, base.clone())
}
/// The composite font a font family stands for: the one whose name is
/// the family's name, with `<hhhh>` escapes decoded
/// (`docs/format/fonts.md`, composite fonts as applied fonts).
fn composite_font_of(
&self,
f: &crate::model::font::FontFamily,
) -> Option<&crate::model::CompositeFont> {
if self.doc.composite_fonts.is_empty() {
return None;
}
let name = f.unescaped_name();
self.doc
.composite_fonts
.iter()
.find(|c| c.name.name == name)
}
fn style_ref(&self, uid: Option<u32>, paragraph: bool) -> String {
let prefix = if paragraph {
"ParagraphStyle"
+1 -1
View File
@@ -856,7 +856,7 @@ impl Writer<'_> {
let doc = self.doc;
let paragraph = s.paragraph;
let name = self.grouped_name(s.uid, &s.name, s.builtin);
let (mut plain, mut props) = self.text_attrs(&s.attrs);
let (mut plain, mut props) = self.text_attrs_of(&s.attrs, !paragraph);
if paragraph {
// The schema allows KerningValue on character styles only.
plain.retain(|(k, _)| *k != "KerningValue");
+128 -36
View File
@@ -41,11 +41,10 @@ pub enum Value {
/// A tab list.
TabList(Vec<TabStop>),
/// A list of nested, line or GREP styles: u32 count, then records.
/// The records are decoded for nested styles only; `nested` is `None`
/// if they cannot be.
/// `items` is `None` if the records cannot be decoded.
StyleList {
count: u32,
nested: Option<Vec<NestedStyle>>,
items: Option<StyleItems>,
},
/// u32 bullet character type and u32 character value.
BulletChar {
@@ -70,6 +69,31 @@ pub struct TabStop {
pub leader: String,
}
/// The decoded records of a style list.
#[derive(Debug, Clone, PartialEq)]
pub enum StyleItems {
Nested(Vec<NestedStyle>),
Grep(Vec<GrepStyle>),
Line(Vec<LineStyle>),
}
/// A GREP style: the character style it applies (0 for none) to the text
/// that the expression matches. See `docs/format/attributes.md`, GREP
/// styles.
#[derive(Debug, Clone, PartialEq)]
pub struct GrepStyle {
pub style: u32,
pub expression: String,
}
/// A line style: the character style it applies (0 for none) to a number
/// of lines. See `docs/format/attributes.md`, line styles.
#[derive(Debug, Clone, PartialEq)]
pub struct LineStyle {
pub style: u32,
pub lines: u32,
}
/// A nested style: the character style it applies (0 for none) and up to
/// where. See `docs/format/attributes.md`, nested styles.
#[derive(Debug, Clone, PartialEq)]
@@ -89,13 +113,23 @@ pub enum Delimiter {
AnyWord,
/// `^?`
AnyCharacter,
/// `^t`
Tabs,
/// `^p`
EndNestedStyle,
/// `^9`
Digits,
/// `^S`
Sentence,
/// `^L`: repeat the previous styles.
Repeat,
/// A single character.
Character(String),
}
/// Delimiter, repetition and inclusiveness of a nested style's delimiter
/// code: `^c`, or `(d)` / `[d]` followed by an optional count. `None` for
/// codes without evidence. See `docs/format/attributes.md`.
/// codes without evidence. See `docs/format/attributes.md`, nested styles.
pub fn nested_delimiter(code: &str) -> Option<(Delimiter, u32, bool)> {
if code == "^c" {
return Some((Delimiter::Dropcap, 1, true));
@@ -114,8 +148,14 @@ pub fn nested_delimiter(code: &str) -> Option<(Delimiter, u32, bool)> {
count.parse().ok()?
};
let delimiter = match inner {
"^c" => Delimiter::Dropcap,
"^w" => Delimiter::AnyWord,
"^?" => Delimiter::AnyCharacter,
"^t" => Delimiter::Tabs,
"^p" => Delimiter::EndNestedStyle,
"^9" => Delimiter::Digits,
"^S" => Delimiter::Sentence,
"^L" => Delimiter::Repeat,
_ if inner.chars().count() == 1 && inner != "^" => Delimiter::Character(inner.to_string()),
_ => return None,
};
@@ -310,8 +350,8 @@ enum Layout {
Text,
TabList,
NestedStyles,
/// Line or GREP styles: u32 count, then records not decoded.
StyleList,
GrepStyles,
LineStyles,
BulletChar,
/// Two u32.
Words,
@@ -331,7 +371,8 @@ fn text_layout(id: u32) -> Option<Layout> {
0x422E => Layout::Text,
0x1B29 => Layout::TabList,
0x1B75 => Layout::NestedStyles,
0x1BBA | 0x1BBB => Layout::StyleList,
0x1BBA => Layout::GrepStyles,
0x1BBB => Layout::LineStyles,
0x1A406 => Layout::BulletChar,
// Stroke types of cell edges, table borders, rows and columns
// (tables.md).
@@ -373,13 +414,12 @@ fn decode_text(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value {
.ok()
.map(Value::Text),
Layout::TabList => tab_list(&mut c).map(Value::TabList),
Layout::NestedStyles | Layout::StyleList => c.u32().ok().map(|count| Value::StyleList {
count,
nested: match layout {
Layout::NestedStyles => nested_styles(&mut enc.cursor(data)),
_ => None,
},
}),
Layout::NestedStyles | Layout::GrepStyles | Layout::LineStyles => {
c.u32().ok().map(|count| Value::StyleList {
count,
items: style_items(layout, &mut enc.cursor(data)),
})
}
Layout::BulletChar if data.len() == 8 => (|| {
Ok::<_, Error>(Value::BulletChar {
kind: c.u32()?,
@@ -426,29 +466,55 @@ fn tab_list(c: &mut Cursor) -> Option<Vec<TabStop>> {
(c.remaining() == 0).then_some(out)
}
/// Nested styles: u32 count, then per style u32 character style, u32
/// length and the delimiter code as text segments. `None` unless every
/// delimiter is known and the styles fill the value exactly.
fn nested_styles(c: &mut Cursor) -> Option<Vec<NestedStyle>> {
/// The records of a style list: u32 count, then per record a u32
/// character style and
/// - nested styles: u32 length and the delimiter code as text segments;
/// - GREP styles: u32 length and the expression as text segments;
/// - line styles: u32 line count.
///
/// `None` unless every record can be read (every nested delimiter is
/// known) and the records fill the value exactly.
fn style_items(layout: Layout, c: &mut Cursor) -> Option<StyleItems> {
fn text(c: &mut Cursor) -> Option<String> {
match c.u32().ok()? as usize {
0 => Some(String::new()),
len => c.segments(len).ok(),
}
}
let n = c.u32().ok()?;
let mut out = Vec::new();
let mut nested = Vec::new();
let mut grep = Vec::new();
let mut line = Vec::new();
for _ in 0..n {
let style = c.u32().ok()?;
let len = c.u32().ok()? as usize;
let code = if len == 0 {
String::new()
} else {
c.segments(len).ok()?
};
let (delimiter, repetition, inclusive) = nested_delimiter(&code)?;
out.push(NestedStyle {
style,
delimiter,
repetition,
inclusive,
});
match layout {
Layout::NestedStyles => {
let (delimiter, repetition, inclusive) = nested_delimiter(&text(c)?)?;
nested.push(NestedStyle {
style,
delimiter,
repetition,
inclusive,
});
}
Layout::GrepStyles => grep.push(GrepStyle {
style,
expression: text(c)?,
}),
_ => line.push(LineStyle {
style,
lines: c.u32().ok()?,
}),
}
}
(c.remaining() == 0).then_some(out)
if c.remaining() != 0 {
return None;
}
Some(match layout {
Layout::NestedStyles => StyleItems::Nested(nested),
Layout::GrepStyles => StyleItems::Grep(grep),
_ => StyleItems::Line(line),
})
}
/// Page item attributes whose value is a list of opacity gradient stops:
@@ -593,6 +659,9 @@ mod tests {
assert_eq!(d("(:)"), Some((Delimiter::Character(":".into()), 1, true)));
assert_eq!(d("(^w)5"), Some((Delimiter::AnyWord, 5, true)));
assert_eq!(d("(^?)"), Some((Delimiter::AnyCharacter, 1, true)));
assert_eq!(d("(^c)"), Some((Delimiter::Dropcap, 1, true)));
assert_eq!(d("[^t]"), Some((Delimiter::Tabs, 1, false)));
assert_eq!(d("(^L)2"), Some((Delimiter::Repeat, 2, true)));
assert_eq!(d("(^x)"), None);
assert_eq!(d("^t"), None);
}
@@ -614,15 +683,38 @@ mod tests {
text_value(0x1B75, &b),
Value::StyleList {
count: 1,
nested: Some(nested)
items: Some(StyleItems::Nested(nested))
}
);
// GREP styles: only the count is read.
// The same record as a GREP style: the code is the expression.
assert_eq!(
text_value(0x1BBA, &b),
Value::StyleList {
count: 1,
nested: None
items: Some(StyleItems::Grep(vec![GrepStyle {
style: 7,
expression: "(^w)2".into()
}]))
}
);
// A line style: character style 7 for 3 lines; a byte too many
// leaves the records undecoded.
let mut l = 1u32.to_le_bytes().to_vec();
l.extend(7u32.to_le_bytes());
l.extend(3u32.to_le_bytes());
assert_eq!(
text_value(0x1BBB, &l),
Value::StyleList {
count: 1,
items: Some(StyleItems::Line(vec![LineStyle { style: 7, lines: 3 }]))
}
);
l.push(0);
assert_eq!(
text_value(0x1BBB, &l),
Value::StyleList {
count: 1,
items: None
}
);
}
+29
View File
@@ -24,6 +24,35 @@ pub struct FontFamily {
pub writing_script: u32,
}
impl FontFamily {
/// The family name with each `<hhhh>` escape (four hexadecimal digits
/// of a UTF-16 code unit) replaced by its character
/// (`docs/format/fonts.md`, composite fonts as applied fonts).
pub fn unescaped_name(&self) -> String {
let mut units = Vec::new();
let mut rest = self.name.as_str();
while let Some(i) = rest.find('<') {
units.extend(rest[..i].encode_utf16());
let unit = rest
.get(i + 1..i + 6)
.filter(|t| t.ends_with('>') && t[..4].bytes().all(|b| b.is_ascii_hexdigit()))
.and_then(|t| u16::from_str_radix(&t[..4], 16).ok());
match unit {
Some(u) => {
units.push(u);
rest = &rest[i + 6..];
}
None => {
units.push(u16::from(b'<'));
rest = &rest[i + 1..];
}
}
}
units.extend(rest.encode_utf16());
String::from_utf16_lossy(&units)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Font {
pub style: String,