Skip to main content

f_office_docx/body/
links.rs

1//! The hyperlinks of the text: where a `w:hyperlink` or a field that links goes, and the marks
2//! on the runs where a link's text starts and ends, which the text map reads. Layout does not
3//! read them.
4
5use f_office_opc::Relationship;
6use f_office_xml::{Document, NodeId};
7
8use super::drawings::{DrawingMut, visit_drawings};
9use super::{Block, field_code, paragraphs_mut};
10use crate::ns::{R, W};
11
12/// Where a hyperlink goes (**Link target**).
13#[derive(Clone, Debug, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum LinkTarget {
16    /// An address outside the document, such as a web page, a mail address or a file, with
17    /// the location in it after a `#` when the link names one.
18    External(String),
19    /// A bookmark of the document, by its name.
20    Bookmark(String),
21}
22
23/// A hyperlink of the text, as the reader reads it (**Hyperlink**): a `w:hyperlink`, or a field
24/// that links (`HYPERLINK`, and `REF` or `PAGEREF` with `\h`).
25#[derive(Clone, Debug, Default, PartialEq, Eq)]
26pub(crate) struct Hyperlink {
27    /// The relationship of the part that names its external address (`r:id`), which
28    /// [`give_addresses`] turns into `address`.
29    pub(crate) relationship: Option<String>,
30    /// Its external address: the target of its relationship, or the address of a `HYPERLINK`
31    /// field.
32    pub(crate) address: Option<String>,
33    /// The bookmark that it goes to (`w:anchor`, the `\l` switch of a `HYPERLINK` field, or the
34    /// bookmark of a `REF` or `PAGEREF` field), or with an address the location there.
35    pub(crate) anchor: Option<String>,
36    /// Its tooltip (`w:tooltip`, or the `\o` switch of a `HYPERLINK` field).
37    pub(crate) tooltip: Option<String>,
38}
39
40impl Hyperlink {
41    /// The hyperlink of the `w:hyperlink` element `node`.
42    pub(crate) fn of_element(doc: &Document, node: NodeId) -> Self {
43        let value = |namespace, name: &str| {
44            doc.attribute(node, Some(namespace), name)
45                .filter(|value| !value.is_empty())
46                .map(str::to_owned)
47        };
48        Self {
49            relationship: value(R, "id"),
50            address: None,
51            anchor: value(W, "anchor"),
52            tooltip: value(W, "tooltip"),
53        }
54    }
55
56    /// The hyperlink of a field of the code `code`, when the field links: a `HYPERLINK` field
57    /// with its address, its `\l` location and its `\o` tooltip, or a `REF` or `PAGEREF` field
58    /// with `\h`, which goes to its bookmark.
59    pub(crate) fn of_code(code: &str) -> Option<Self> {
60        if !field_code::links(code) {
61            return None;
62        }
63        let kind = field_code::kind(code)?;
64        if !kind.eq_ignore_ascii_case("HYPERLINK") {
65            let bookmark = field_code::words_after_kind(code).next()?;
66            let bookmark = field_code::word_argument(bookmark);
67            return (!bookmark.is_empty() && !bookmark.starts_with('\\')).then(|| Self {
68                anchor: Some(bookmark.to_owned()),
69                ..Self::default()
70            });
71        }
72        let mut link = Self::default();
73        let mut rest = field_code::after_kind(code);
74        loop {
75            let word = field_code::quoted_argument(rest);
76            if word.text.is_empty() && word.rest.trim().is_empty() {
77                break;
78            }
79            rest = word.rest;
80            let switch = word.text.strip_prefix('\\').map(str::to_ascii_lowercase);
81            let Some(switch) = switch else {
82                if link.address.is_none() && !word.text.is_empty() {
83                    link.address = Some(word.text.to_owned());
84                }
85                continue;
86            };
87            // The switches with an argument: the location, the tooltip and the target frame.
88            if matches!(switch.as_str(), "l" | "o" | "t") {
89                let argument = field_code::quoted_argument(rest);
90                rest = argument.rest;
91                let text = Some(argument.text.to_owned()).filter(|text| !text.is_empty());
92                match switch.as_str() {
93                    "l" => link.anchor = text,
94                    "o" => link.tooltip = text,
95                    _ => {}
96                }
97            }
98        }
99        Some(link)
100    }
101
102    /// Where it goes: its external address, with its location after a `#`, or else its
103    /// bookmark; none when it names neither.
104    pub(crate) fn target(&self) -> Option<LinkTarget> {
105        match (&self.address, &self.anchor) {
106            (Some(address), Some(anchor)) => {
107                Some(LinkTarget::External(format!("{address}#{anchor}")))
108            }
109            (Some(address), None) => Some(LinkTarget::External(address.clone())),
110            (None, Some(anchor)) => Some(LinkTarget::Bookmark(anchor.clone())),
111            (None, None) => None,
112        }
113    }
114}
115
116/// A mark on a run where a hyperlink's text starts or ends (**Link mark**).
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub(crate) enum LinkMark {
119    /// The text of the hyperlink starts at the run: the run after a `w:hyperlink`'s start, or
120    /// the run of a linking field's separator, and the runs after it are the link's text.
121    Start(Box<Hyperlink>),
122    /// The text of the innermost open hyperlink ends at the run.
123    End,
124}
125
126/// Gives the hyperlinks of `blocks`, a story of one part, with those of its text boxes, the
127/// external addresses that the part's `relationships` name.
128pub(crate) fn give_addresses(blocks: &mut [Block], relationships: &[Relationship]) {
129    give_own_addresses(blocks, relationships);
130    visit_drawings(blocks, &mut |drawing| {
131        if let DrawingMut::Floating(floating) = drawing {
132            give_own_addresses(&mut floating.blocks, relationships);
133        }
134    });
135}
136
137/// Gives the hyperlinks of the paragraphs of `blocks` and of their table cells, but not of
138/// their text boxes, the external addresses that `relationships` name.
139fn give_own_addresses(blocks: &mut [Block], relationships: &[Relationship]) {
140    for paragraph in paragraphs_mut(blocks) {
141        for run in &mut paragraph.runs {
142            for mark in &mut run.links {
143                if let LinkMark::Start(link) = mark
144                    && let Some(id) = link.relationship.take()
145                {
146                    // A hyperlink's relationship names an external target, which
147                    // `Relationship::by_id` leaves out.
148                    link.address = relationships
149                        .iter()
150                        .find(|relationship| relationship.id == id)
151                        .map(|relationship| relationship.target.clone());
152                }
153            }
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests;