1//! Clips as HTML, both ways. Copy writes what OneNote 2010 puts on the clipboard (lab,
2//! 2026-10-02): every run's formatting inline on a `span`, lists as `ul` and `ol` nested by
3//! level, tables bordered, pictures and note tags left out. Paste reads that and what other
4//! applications write into paragraphs, lists, tables and pictures.
5
6use super::Piece;
7use super::clip::Clip;
8use super::format::{AUTOMATIC, ListStyle, NUMBER_LIBRARY, list_definition};
9use super::link::{field_code, links};
10use super::table::COLUMN_WIDTH;
11use crate::document::node;
12use crate::layout::{DEFAULT_FONT, DEFAULT_FONT_SIZE};
13use onestore::ExGuid;
14use onestore::document::{Format, Kind};
15use onestore::page::text::{EditError, Paragraph, new_id};
16use onestore::page::{
17 Definition, PageParagraph, ParagraphContent, Table, TableCell, TableColumn, TableRow,
18};
19use std::collections::BTreeMap;
20use std::fmt::Write;
21
22impl Clip {
23 /// The clip as a web page whose fragment the comments OneNote's mark out hold.
24 pub fn html(&self) -> String {
25 let mut body = String::new();
26 blocks(&self.paragraphs, &self.definitions, &mut (), &mut body);
27 format!(
28 "<html>\n<head>\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\n\
29 <meta name=Generator content=\"Snowbound\">\n</head>\n<body>\n\
30 <!--StartFragment-->\n{body}<!--EndFragment-->\n</body>\n</html>\n"
31 )
32 }
33}
34
35/// What a writer of whole pages adds to the blocks the clipboard writes.
36pub(crate) trait Extras {
37 /// CSS added to text paragraph `node`'s own, each declaration led by `;`.
38 fn style(&mut self, _node: &PageParagraph) -> String {
39 String::new()
40 }
41
42 /// Attributes added to text paragraph `node`'s element, each led by a space.
43 fn attributes(&mut self, _node: &PageParagraph) -> String {
44 String::new()
45 }
46
47 /// What starts text paragraph `node`, inside its element, or stands for a picture, file or
48 /// drawing, which the clipboard leaves out.
49 fn content(&mut self, _node: &PageParagraph, _out: &mut String) {}
50
51 /// Where a link to stored `target` leads; none for one that stays text.
52 fn link(&mut self, target: &str) -> Option<String> {
53 linkable(target)
54 }
55}
56
57impl Extras for () {}
58
59/// `nodes` as blocks: a list opens at a paragraph whose list differs from the one open at
60/// its level, and a block's left margin steps it in from the list it sits in, which OneNote
61/// and Word take its level from.
62pub(crate) fn blocks(
63 nodes: &[PageParagraph],
64 definitions: &BTreeMap<ExGuid, Definition>,
65 extras: &mut dyn Extras,
66 out: &mut String,
67) {
68 let mut open: Vec<(u32, &str)> = Vec::new();
69 for node in nodes {
70 let list = node
71 .lists
72 .last()
73 .and_then(|id| definitions.get(id))
74 .filter(|definition| matches!(definition.kind, Kind::List { .. }))
75 .map(|definition| list_tag(&definition.kind));
76 while let Some(&(level, tag)) = open.last()
77 && (level > node.level || level == node.level && list.map(|(tag, _)| tag) != Some(tag))
78 {
79 let _ = writeln!(out, "</{tag}>");
80 open.pop();
81 }
82 // A level's step in, past the list it sits in, as OneNote indents its nested lists.
83 let indent = (node.level - open.last().map_or(1, |(level, _)| *level)) as f32 * 0.375;
84 match (list, &node.content) {
85 (Some((tag, kind)), ParagraphContent::Text(text)) => {
86 if open.last().map(|(level, _)| *level) != Some(node.level) {
87 let _ = writeln!(
88 out,
89 "<{tag} type={kind} style='margin-left:{indent}in;margin-top:0in;margin-bottom:0in'>"
90 );
91 open.push((node.level, tag));
92 }
93 let _ = write!(
94 out,
95 "<li style='margin-top:0;margin-bottom:0{}'{}>",
96 extras.style(node),
97 extras.attributes(node)
98 );
99 extras.content(node, out);
100 runs(&text.text, extras, out);
101 out.push_str("</li>\n");
102 }
103 (_, ParagraphContent::Text(text)) => {
104 let _ = write!(
105 out,
106 "<p style='margin:0in;margin-left:{indent}in{}'{}>",
107 extras.style(node),
108 extras.attributes(node)
109 );
110 extras.content(node, out);
111 runs(&text.text, extras, out);
112 out.push_str("</p>\n");
113 }
114 (_, ParagraphContent::Table(table)) => {
115 out.push_str(
116 "<table border=1 cellpadding=0 cellspacing=0 style='border-collapse:collapse;\
117 border-style:solid;border-color:#A3A3A3;border-width:1pt'>\n",
118 );
119 for row in &table.rows {
120 out.push_str("<tr>\n");
121 for (cell, column) in row.cells.iter().zip(&table.columns) {
122 let _ = writeln!(
123 out,
124 "<td style='border-style:solid;border-color:#A3A3A3;border-width:1pt;\
125 vertical-align:top;width:{}pt;padding:4pt 4pt 4pt 4pt'>",
126 column.width
127 );
128 blocks(&cell.paragraphs, definitions, extras, out);
129 out.push_str("</td>\n");
130 }
131 out.push_str("</tr>\n");
132 }
133 out.push_str("</table>\n");
134 }
135 _ => extras.content(node, out),
136 }
137 }
138 for (_, tag) in open.into_iter().rev() {
139 let _ = writeln!(out, "</{tag}>");
140 }
141}
142
143/// The element and `type` a stored list writes as.
144pub(super) fn list_tag(kind: &Kind) -> (&'static str, &'static str) {
145 let Kind::List { bullet, format, .. } = kind else {
146 return ("ul", "disc");
147 };
148 let sequence = format
149 .as_deref()
150 .and_then(|format| format.split('\u{fffd}').nth(1)?.chars().next());
151 if bullet.is_some() || sequence.is_none() {
152 let kind = match ListStyle::of(kind) {
153 Some(ListStyle::Bullet(3)) => "circle",
154 Some(ListStyle::Bullet(11 | 14)) => "square",
155 _ => "disc",
156 };
157 return ("ul", kind);
158 }
159 let kind = match sequence.map(u32::from) {
160 Some(1) => "I",
161 Some(2) => "i",
162 Some(3) => "A",
163 Some(4) => "a",
164 _ => "1",
165 };
166 ("ol", kind)
167}
168
169/// A paragraph's shown runs as spans, its links' around theirs.
170fn runs(text: &Paragraph, extras: &mut dyn Extras, out: &mut String) {
171 let links = links(text, 0);
172 let (mut byte, mut unit) = (0, 0);
173 let mut shown = false;
174 let mut space = true;
175 for span in text.spans() {
176 let fragment = &text.text()[byte..span.end];
177 let start = unit;
178 (byte, unit) = (span.end, unit + fragment.encode_utf16().count() as u32);
179 if span.format.hidden == Some(true) || fragment.is_empty() {
180 continue;
181 }
182 shown = true;
183 let link = (links.iter())
184 .find(|link| link.label.contains(&start))
185 .and_then(|link| extras.link(&link.target));
186 if let Some(target) = &link {
187 let _ = write!(out, "<a href=\"{}\">", escape(target, &mut false));
188 }
189 let _ = write!(
190 out,
191 "<span style='{}'>{}</span>",
192 css(&span.format),
193 escape(fragment, &mut space)
194 );
195 if link.is_some() {
196 out.push_str("</a>");
197 }
198 }
199 if !shown {
200 out.push_str("&nbsp;");
201 }
202}
203
204/// A stored link target as HTML may link it: a web or mail address, a link within the
205/// notebook, or a relative path, without the white space and controls browsers ignore in one.
206/// None for anything else, such as a script, which stays text.
207pub(crate) fn linkable(target: &str) -> Option<String> {
208 let target: String = (target.trim_matches(|c: char| c <= ' ').chars())
209 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
210 .collect();
211 let scheme = (target.split_once(':'))
212 .map(|(scheme, _)| scheme)
213 .filter(|scheme| !scheme.contains(['/', '?', '#']));
214 let allowed = match scheme {
215 Some(scheme) => matches!(
216 scheme.to_ascii_lowercase().as_str(),
217 "http" | "https" | "mailto" | "onenote"
218 ),
219 // A Windows path to a share or a drive names the writer's own files.
220 None => !target.is_empty() && !target.starts_with('\\'),
221 };
222 allowed.then_some(target)
223}
224
225/// A font name CSS can hold as it is: letters, digits, spaces and `-`, `_` and `.`; none for
226/// another, which might break out of the style it is put in.
227pub(crate) fn font_name(font: &str) -> Option<&str> {
228 (!font.is_empty()
229 && font
230 .chars()
231 .all(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.')))
232 .then_some(font)
233}
234
235fn css(format: &Format) -> String {
236 let mut css = String::new();
237 match font_name(format.font.as_deref().unwrap_or(DEFAULT_FONT)) {
238 Some(font) if font.contains(' ') => {
239 let _ = write!(css, "font-family:\"{font}\";");
240 }
241 Some(font) => {
242 let _ = write!(css, "font-family:{font};");
243 }
244 None => {}
245 }
246 let _ = write!(
247 css,
248 "font-size:{}pt",
249 format.font_size.unwrap_or(DEFAULT_FONT_SIZE)
250 );
251 let set = |value: Option<bool>| value == Some(true);
252 match format.bold {
253 Some(true) => css.push_str(";font-weight:bold"),
254 Some(false) => css.push_str(";font-weight:normal"),
255 None => {}
256 }
257 match format.italic {
258 Some(true) => css.push_str(";font-style:italic"),
259 Some(false) => css.push_str(";font-style:normal"),
260 None => {}
261 }
262 match (set(format.underline), set(format.strike)) {
263 (true, true) => css.push_str(";text-decoration:underline line-through"),
264 (true, false) => css.push_str(";text-decoration:underline"),
265 (false, true) => css.push_str(";text-decoration:line-through"),
266 (false, false) if format.underline.is_some() || format.strike.is_some() => {
267 css.push_str(";text-decoration:none")
268 }
269 (false, false) => {}
270 }
271 if set(format.superscript) {
272 css.push_str(";vertical-align:super");
273 } else if set(format.subscript) {
274 css.push_str(";vertical-align:sub");
275 }
276 let hex = |color: u32| {
277 let [red, green, blue, _] = color.to_le_bytes();
278 format!("#{red:02X}{green:02X}{blue:02X}")
279 };
280 if let Some(color) = format.color.filter(|color| *color != AUTOMATIC) {
281 let _ = write!(css, ";color:{}", hex(color));
282 }
283 if let Some(color) = format.highlight.filter(|color| *color != AUTOMATIC) {
284 let _ = write!(css, ";background:{}", hex(color));
285 }
286 css
287}
288
289/// Text as HTML keeps it, in an element or a quoted attribute: markup characters and quotes
290/// escaped, line breaks as `br`, and a space after `space`, whether the text follows a space
291/// or starts its paragraph, unbreakable so it doesn't collapse.
292pub(crate) fn escape(text: &str, space: &mut bool) -> String {
293 let mut escaped = String::with_capacity(text.len());
294 for c in text.chars() {
295 match c {
296 '&' => escaped.push_str("&amp;"),
297 '<' => escaped.push_str("&lt;"),
298 '>' => escaped.push_str("&gt;"),
299 '"' => escaped.push_str("&quot;"),
300 '\'' => escaped.push_str("&#39;"),
301 '\u{b}' | '\n' => escaped.push_str("<br>"),
302 '\t' => escaped.push_str("&nbsp;&nbsp;&nbsp; "),
303 ' ' if *space => escaped.push_str("&nbsp;"),
304 c => escaped.push(c),
305 }
306 *space = c == ' ';
307 }
308 escaped
309}
310
311/// A web page fragment's paragraphs, lists and tables as clips, split around its pictures
312/// in order, as OneNote 2010 pastes them (lab, 2026-09-30). Text without a font or size of
313/// its own is Calibri 11 in `language`, an LCID, as pasted text is. `load` makes a picture's
314/// piece from its source and its `width` and `height` in CSS pixels; one it can't, or one
315/// in a table, is left out.
316pub fn html_pieces(
317 html: &str,
318 language: u32,
319 load: impl FnMut(&str, [Option<f32>; 2]) -> Option<Piece>,
320) -> Vec<Piece> {
321 let html = html
322 .split_once("<!--StartFragment-->")
323 .map_or(html, |(_, fragment)| fragment);
324 let html = html
325 .split_once("<!--EndFragment-->")
326 .map_or(html, |(fragment, _)| fragment);
327 let mut reader = Reader {
328 base: Format {
329 font: Some("Calibri".into()),
330 font_size: Some(11.0),
331 language: Some(language),
332 ..Format::default()
333 },
334 load,
335 pieces: Vec::new(),
336 blocks: Vec::new(),
337 tables: Vec::new(),
338 lists: Vec::new(),
339 item: None,
340 word: None,
341 sequences: BTreeMap::new(),
342 open: Vec::new(),
343 runs: Vec::new(),
344 shown: false,
345 space: None,
346 };
347 reader.read(html);
348 reader.end_clip();
349 reader.pieces
350}
351
352/// A paragraph Word marks as a list item, its `mso-list` list and level, and the marker Word
353/// wrote before its text, in the marker's font.
354struct WordItem {
355 list: String,
356 level: usize,
357 marker: String,
358 font: Option<String>,
359}
360
361/// A paragraph or table read, before it becomes a clip's.
362enum Block {
363 Text {
364 runs: Vec<(String, Format)>,
365 /// How many lists it sits in, its own not counted.
366 depth: usize,
367 list: Option<Box<Definition>>,
368 },
369 Table {
370 rows: Vec<Vec<Vec<Block>>>,
371 widths: Vec<Option<f32>>,
372 depth: usize,
373 },
374}
375
376#[derive(Default)]
377struct TableRead {
378 rows: Vec<Vec<Vec<Block>>>,
379 widths: Vec<Option<f32>>,
380 /// The open cell's blocks.
381 cell: Option<Vec<Block>>,
382}
383
384/// An open element: its name, the formatting it gives what it holds, and where a link's
385/// field code went in the runs, if it is one.
386struct Open {
387 name: String,
388 format: Format,
389 link: Option<usize>,
390 /// Whether it holds a Word list item's marker (`mso-list:Ignore`).
391 marker: bool,
392}
393
394struct Reader<F> {
395 base: Format,
396 load: F,
397 pieces: Vec<Piece>,
398 blocks: Vec<Block>,
399 tables: Vec<TableRead>,
400 lists: Vec<ListStyle>,
401 /// The list of the item whose text has yet to come.
402 item: Option<ListStyle>,
403 /// The Word list item being read, as `mso-list` names it.
404 word: Option<WordItem>,
405 /// The number sequence each Word list level (`mso-list` list and level) began with.
406 sequences: BTreeMap<(String, usize), char>,
407 open: Vec<Open>,
408 runs: Vec<(String, Format)>,
409 /// Whether the paragraph read so far shows anything.
410 shown: bool,
411 /// The formatting of white space after what it shows, which shows as one space if
412 /// more follows.
413 space: Option<Format>,
414}
415
416/// Elements that hold no text and have no closing tag.
417const VOID: [&str; 9] = [
418 "br", "img", "meta", "link", "input", "hr", "col", "wbr", "area",
419];
420
421/// Elements that begin and end a paragraph.
422const BLOCKS: [&str; 20] = [
423 "p",
424 "div",
425 "li",
426 "h1",
427 "h2",
428 "h3",
429 "h4",
430 "h5",
431 "h6",
432 "blockquote",
433 "pre",
434 "dt",
435 "dd",
436 "section",
437 "article",
438 "header",
439 "footer",
440 "figure",
441 "figcaption",
442 "address",
443];
444
445impl<F: FnMut(&str, [Option<f32>; 2]) -> Option<Piece>> Reader<F> {
446 fn read(&mut self, html: &str) {
447 // Elements whose content is not text: script, style, head and title.
448 let mut hidden: Option<String> = None;
449 let mut rest = html;
450 while !rest.is_empty() {
451 if let Some(after) = rest.strip_prefix("<!--") {
452 rest = after.split_once("-->").map_or("", |(_, after)| after);
453 continue;
454 }
455 let Some(after) = rest.strip_prefix('<') else {
456 let end = rest.find('<').unwrap_or(rest.len());
457 if hidden.is_none() {
458 self.text(&decode_entities(&rest[..end]));
459 }
460 rest = &rest[end..];
461 continue;
462 };
463 let end = tag_end(after);
464 let tag = &after[..end];
465 rest = after.get(end + 1..).unwrap_or("");
466 // Declarations and Word's `<![if ...]>` conditions.
467 if tag.starts_with('!') {
468 continue;
469 }
470 let (closing, tag) = match tag.strip_prefix('/') {
471 Some(tag) => (true, tag),
472 None => (false, tag),
473 };
474 let name = tag
475 .split(|c: char| c.is_whitespace() || c == '/')
476 .next()
477 .unwrap_or_default()
478 .to_ascii_lowercase();
479 if let Some(until) = &hidden {
480 if closing && name == *until {
481 hidden = None;
482 }
483 continue;
484 }
485 match (name.as_str(), closing) {
486 ("script" | "style" | "head" | "title", false) => hidden = Some(name),
487 (_, false) => self.start(&name, tag),
488 (_, true) => self.end(&name),
489 }
490 }
491 }
492
493 fn start(&mut self, name: &str, tag: &str) {
494 let block = BLOCKS.contains(&name);
495 if block || matches!(name, "br" | "table" | "tr" | "td" | "th" | "ul" | "ol") {
496 self.paragraph();
497 }
498 let list = style(tag, "mso-list");
499 if block && let Some(list) = &list {
500 let mut words = list.split_whitespace();
501 if let (Some(id), Some(Ok(level))) = (
502 words.next(),
503 words
504 .next()
505 .and_then(|level| level.strip_prefix("level"))
506 .map(str::parse::<usize>),
507 ) && level > 0
508 {
509 self.word = Some(WordItem {
510 list: id.to_owned(),
511 level,
512 marker: String::new(),
513 font: None,
514 });
515 }
516 }
517 match name {
518 "br" => return,
519 "img" => {
520 let css = |name| {
521 attribute(tag, name)
522 .and_then(|value| value.trim_end_matches("px").parse::<f32>().ok())
523 .filter(|pixels| *pixels > 0.0)
524 };
525 if self.tables.is_empty()
526 && let Some(picture) = attribute(tag, "src").and_then(|source| {
527 (self.load)(&decode_entities(source), [css("width"), css("height")])
528 })
529 {
530 self.end_clip();
531 self.pieces.push(picture);
532 }
533 return;
534 }
535 "ul" | "ol" => {
536 let kind = attribute(tag, "type")
537 .map(str::to_owned)
538 .or_else(|| style(tag, "list-style-type"));
539 self.lists.push(list_style(name, kind.as_deref()));
540 }
541 "li" => {
542 self.implicit_end("li");
543 self.item = Some(self.lists.last().copied().unwrap_or(ListStyle::BULLET));
544 }
545 "p" => self.implicit_end("p"),
546 "table" => self.tables.push(TableRead::default()),
547 "tr" => {
548 if let Some(table) = self.tables.last_mut() {
549 table.end_cell();
550 table.rows.push(Vec::new());
551 }
552 }
553 "td" | "th" => {
554 if let Some(table) = self.tables.last_mut() {
555 table.end_cell();
556 if table.rows.is_empty() {
557 table.rows.push(Vec::new());
558 }
559 let column = table.rows.last().unwrap().len();
560 if table.widths.len() <= column {
561 table.widths.resize(column + 1, None);
562 }
563 let width = style(tag, "width")
564 .and_then(|width| length(&width, 12.0))
565 .or_else(|| {
566 attribute(tag, "width")?
567 .parse::<f32>()
568 .ok()
569 .map(|px| px * 0.75)
570 });
571 table.widths[column] = table.widths[column].or(width);
572 table.cell = Some(Vec::new());
573 }
574 }
575 _ => {}
576 }
577 if VOID.contains(&name) {
578 return;
579 }
580 let current = self.format();
581 let mut format = element_format(name, tag, &current);
582 let link = (name == "a")
583 .then(|| attribute(tag, "href"))
584 .flatten()
585 .map(|href| {
586 if let Some(space) = self.space.take() {
587 self.push(' ', space);
588 }
589 let mut code = format.inherit(&current);
590 code.hidden = Some(true);
591 code.hyperlink = Some(true);
592 code.hyperlink_label = Some(true);
593 self.runs.push((field_code(&decode_entities(href)), code));
594 format.hyperlink = Some(true);
595 format.hyperlink_label = Some(true);
596 self.runs.len() - 1
597 });
598 self.open.push(Open {
599 name: name.to_owned(),
600 format,
601 link,
602 marker: list.is_some_and(|list| list.eq_ignore_ascii_case("ignore")),
603 });
604 }
605
606 fn end(&mut self, name: &str) {
607 if BLOCKS.contains(&name) || matches!(name, "table" | "tr" | "td" | "th" | "ul" | "ol") {
608 self.paragraph();
609 }
610 if let Some(at) = self.open.iter().rposition(|open| open.name == name) {
611 for open in self.open.drain(at..) {
612 // A link that showed nothing keeps no field code.
613 if let Some(code) = open.link
614 && code + 1 == self.runs.len()
615 {
616 self.runs.pop();
617 }
618 }
619 }
620 match name {
621 "ul" | "ol" => {
622 self.lists.pop();
623 }
624 "li" => self.item = None,
625 "td" | "th" => {
626 if let Some(table) = self.tables.last_mut() {
627 table.end_cell();
628 }
629 }
630 "table" => {
631 if let Some(mut table) = self.tables.pop() {
632 table.end_cell();
633 table.rows.retain(|row| !row.is_empty());
634 if !table.rows.is_empty() {
635 let block = Block::Table {
636 rows: table.rows,
637 widths: table.widths,
638 depth: self.lists.len(),
639 };
640 self.sink().push(block);
641 }
642 }
643 }
644 _ => {}
645 }
646 }
647
648 /// Ends an unclosed `name`, as a `p` or `li` is by the next, within the innermost list
649 /// or table.
650 fn implicit_end(&mut self, name: &str) {
651 let boundary =
652 |open: &Open| matches!(open.name.as_str(), "ul" | "ol" | "table" | "td" | "th");
653 if let Some(at) = self
654 .open
655 .iter()
656 .rposition(|open| open.name == name || boundary(open))
657 && self.open[at].name == name
658 {
659 self.open.truncate(at);
660 }
661 }
662
663 fn format(&self) -> Format {
664 self.open.iter().fold(self.base.clone(), |format, open| {
665 open.format.inherit(&format)
666 })
667 }
668
669 fn text(&mut self, text: &str) {
670 let format = self.format();
671 if self.open.iter().any(|open| open.marker) {
672 if let Some(item) = &mut self.word {
673 let shown = text.trim_matches(|c: char| c.is_whitespace() || c == '\u{a0}');
674 if !shown.is_empty() && item.marker.is_empty() {
675 item.font = format.font.clone();
676 }
677 item.marker.push_str(shown);
678 }
679 return;
680 }
681 for c in text.chars() {
682 if c.is_whitespace() && c != '\u{a0}' {
683 if self.shown && self.space.is_none() {
684 self.space = Some(format.clone());
685 }
686 continue;
687 }
688 if let Some(space) = self.space.take() {
689 self.push(' ', space);
690 }
691 self.shown = true;
692 self.push(if c == '\u{a0}' { ' ' } else { c }, format.clone());
693 }
694 }
695
696 fn push(&mut self, c: char, format: Format) {
697 match self.runs.last_mut() {
698 Some((text, last)) if *last == format => text.push(c),
699 _ => self.runs.push((c.to_string(), format)),
700 }
701 }
702
703 /// Ends the paragraph being read, which goes in if it showed anything; a link's field
704 /// code begun in one that didn't carries on into the next.
705 fn paragraph(&mut self) {
706 self.space = None;
707 if !std::mem::take(&mut self.shown) {
708 return;
709 }
710 let mut runs = std::mem::take(&mut self.runs);
711 for open in &mut self.open {
712 open.link = None;
713 }
714 runs.retain(|(text, _)| !text.is_empty());
715 if runs.is_empty() {
716 runs.push((String::new(), self.format()));
717 }
718 let (list, depth) = match self.word.take() {
719 Some(item) => {
720 let depth = self.lists.len() + item.level - 1;
721 (Some(Box::new(self.word_list(item, &runs[0].1))), depth)
722 }
723 None => {
724 let list = self.item.take();
725 let depth =
726 self.lists.len() - usize::from(list.is_some() && !self.lists.is_empty());
727 (
728 list.map(|style| Box::new(list_definition(style, &runs[0].1))),
729 depth,
730 )
731 }
732 };
733 self.sink().push(Block::Text { runs, depth, list });
734 }
735
736 /// The list OneNote 2010 made of a Word list item whose text begins in `format` (lab,
737 /// 2026-10-02): a marker without a number is a bullet in Word's glyph and font; a number
738 /// keeps Word's punctuation, in the sequence its list level began with.
739 fn word_list(&mut self, item: WordItem, format: &Format) -> Definition {
740 let mut definition = list_definition(ListStyle::NUMBER, format);
741 let Kind::List {
742 font, format: list, ..
743 } = &mut definition.kind
744 else {
745 unreachable!("a number is a list")
746 };
747 let marker = item.marker;
748 let alphanumeric = |c: char| c.is_ascii_alphanumeric();
749 let token = marker
750 .find(alphanumeric)
751 .zip(marker.rfind(alphanumeric))
752 .map(|(start, end)| start..end + 1);
753 let digits = token
754 .as_ref()
755 .is_some_and(|token| marker[token.clone()].bytes().any(|b| b.is_ascii_digit()));
756 let Some(number) = token.filter(|token| digits || token.len() < marker.len()) else {
757 *font = item.font;
758 *list = Some(marker);
759 return definition;
760 };
761 let token = &marker[number.clone()];
762 let sequence = *self
763 .sequences
764 .entry((item.list, item.level))
765 .or_insert_with(|| {
766 let roman = token == "i"
767 || token == "I"
768 || token.len() > 1 && token.chars().all(|c| "ivxlcdmIVXLCDM".contains(c));
769 let upper = token.starts_with(|c: char| c.is_ascii_uppercase());
770 match (digits, roman, upper) {
771 (true, ..) => '\u{0}',
772 (_, true, true) => '\u{1}',
773 (_, true, false) => '\u{2}',
774 (_, false, true) => '\u{3}',
775 (_, false, false) => '\u{4}',
776 }
777 });
778 *list = Some(format!(
779 "{}\u{fffd}{sequence}{}",
780 &marker[..number.start],
781 &marker[number.end..]
782 ));
783 definition
784 }
785
786 /// Where a block read goes: the open cell, else the clip.
787 fn sink(&mut self) -> &mut Vec<Block> {
788 match self.tables.last_mut() {
789 Some(table) => table.cell.get_or_insert_with(Vec::new),
790 None => &mut self.blocks,
791 }
792 }
793
794 /// Makes what was read since the last picture a clip.
795 fn end_clip(&mut self) {
796 self.paragraph();
797 let blocks = std::mem::take(&mut self.blocks);
798 if blocks.is_empty() {
799 return;
800 }
801 let mut definitions = BTreeMap::new();
802 if let Ok(paragraphs) = nodes(blocks, &mut definitions)
803 && !paragraphs.is_empty()
804 {
805 self.pieces.push(Piece::Clip(Clip {
806 paragraphs,
807 definitions,
808 }));
809 }
810 }
811}
812
813impl TableRead {
814 fn end_cell(&mut self) {
815 if let Some(cell) = self.cell.take() {
816 match self.rows.last_mut() {
817 Some(row) => row.push(cell),
818 None => self.rows.push(vec![cell]),
819 }
820 }
821 }
822}
823
824/// `blocks` as paragraphs, each the child of the one before it at a lower level, with the
825/// list definitions they name added to `definitions`.
826fn nodes(
827 blocks: Vec<Block>,
828 definitions: &mut BTreeMap<ExGuid, Definition>,
829) -> Result<Vec<PageParagraph>, EditError> {
830 let depth = |block: &Block| match block {
831 Block::Text { depth, .. } | Block::Table { depth, .. } => *depth,
832 };
833 let least = blocks.iter().map(depth).min().unwrap_or(0);
834 let mut nodes = Vec::new();
835 let mut ancestors: Vec<(u32, ExGuid)> = Vec::new();
836 for block in blocks {
837 let level = (depth(&block) - least + 1) as u32;
838 let mut paragraph = match block {
839 Block::Text { runs, list, .. } => {
840 let mut paragraph = node(Paragraph::from_runs(runs), Format::default())?;
841 if let Some(list) = list {
842 let id = new_id()?;
843 definitions.insert(id, *list);
844 paragraph.lists = vec![id];
845 }
846 paragraph
847 }
848 Block::Table { rows, widths, .. } => table(rows, widths, definitions)?,
849 };
850 while ancestors.last().is_some_and(|(above, _)| *above >= level) {
851 ancestors.pop();
852 }
853 paragraph.parent = ancestors.last().map(|(_, id)| *id);
854 paragraph.level = level;
855 ancestors.push((level, paragraph.id));
856 nodes.push(paragraph);
857 }
858 Ok(nodes)
859}
860
861fn table(
862 rows: Vec<Vec<Vec<Block>>>,
863 widths: Vec<Option<f32>>,
864 definitions: &mut BTreeMap<ExGuid, Definition>,
865) -> Result<PageParagraph, EditError> {
866 let columns = rows.iter().map(Vec::len).max().unwrap_or(1).max(1);
867 let rows = rows
868 .into_iter()
869 .map(|mut cells| {
870 cells.resize_with(columns, Vec::new);
871 Ok(TableRow {
872 id: new_id()?,
873 cells: cells
874 .into_iter()
875 .map(|blocks| {
876 let mut paragraphs = nodes(blocks, definitions)?;
877 if paragraphs.is_empty() {
878 let empty = Paragraph::new(String::new(), Format::default());
879 paragraphs.push(node(empty, Format::default())?);
880 }
881 Ok(TableCell {
882 id: new_id()?,
883 layout: Default::default(),
884 indents: Vec::new(),
885 shading: None,
886 paragraphs,
887 unsupported: Vec::new(),
888 })
889 })
890 .collect::<Result<_, EditError>>()?,
891 })
892 })
893 .collect::<Result<_, EditError>>()?;
894 let mut paragraph = node(
895 Paragraph::new(String::new(), Format::default()),
896 Format::default(),
897 )?;
898 paragraph.content = ParagraphContent::Table(Table {
899 id: new_id()?,
900 columns: (0..columns)
901 .map(|column| TableColumn {
902 width: widths
903 .get(column)
904 .copied()
905 .flatten()
906 .unwrap_or(COLUMN_WIDTH)
907 .max(COLUMN_WIDTH),
908 locked: false,
909 })
910 .collect(),
911 rows,
912 borders: Some(true),
913 layout: Default::default(),
914 tags: Vec::new(),
915 });
916 Ok(paragraph)
917}
918
919/// The list style an `ul` or `ol` of `kind`, its `type` or `list-style-type`, gives.
920fn list_style(name: &str, kind: Option<&str>) -> ListStyle {
921 let number = |format: &str| {
922 let index = NUMBER_LIBRARY.iter().position(|known| *known == format);
923 ListStyle::Number(index.unwrap_or(0))
924 };
925 match (name, kind.map(str::trim)) {
926 ("ul", Some("circle")) => ListStyle::Bullet(3),
927 ("ul", Some("square")) => ListStyle::Bullet(11),
928 ("ul", _) => ListStyle::BULLET,
929 (_, Some("a" | "lower-alpha" | "lower-latin")) => number("\u{fffd}\u{4}."),
930 (_, Some("A" | "upper-alpha" | "upper-latin")) => number("\u{fffd}\u{3}."),
931 (_, Some("i" | "lower-roman")) => number("\u{fffd}\u{2}."),
932 (_, Some("I" | "upper-roman")) => number("\u{fffd}\u{1}."),
933 _ => ListStyle::NUMBER,
934 }
935}
936
937/// The formatting an element gives its text: its own, as `b` and `font` give, then its
938/// `style`'s. `current` is the formatting around it.
939fn element_format(name: &str, tag: &str, current: &Format) -> Format {
940 let mut format = Format::default();
941 match name {
942 "b" | "strong" => format.bold = Some(true),
943 "i" | "em" | "cite" | "dfn" | "var" => format.italic = Some(true),
944 "u" | "ins" => format.underline = Some(true),
945 "s" | "strike" | "del" => format.strike = Some(true),
946 "sup" => format.superscript = Some(true),
947 "sub" => format.subscript = Some(true),
948 "code" | "tt" | "pre" | "kbd" | "samp" => format.font = Some("Courier New".into()),
949 "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
950 const SIZES: [f32; 6] = [24.0, 18.0, 14.0, 12.0, 10.0, 8.0];
951 format.bold = Some(true);
952 format.font_size = Some(SIZES[usize::from(name.as_bytes()[1] - b'1')]);
953 }
954 "font" => {
955 format.font = attribute(tag, "face").and_then(family);
956 format.color = attribute(tag, "color").and_then(color).flatten();
957 format.font_size = attribute(tag, "size")
958 .and_then(|size| size.trim().parse::<usize>().ok())
959 .map(|size| [8.0, 10.0, 12.0, 14.0, 18.0, 24.0, 36.0][size.clamp(1, 7) - 1]);
960 }
961 _ => {}
962 }
963 let Some(css) = attribute(tag, "style") else {
964 return format;
965 };
966 let size = format
967 .font_size
968 .or(current.font_size)
969 .unwrap_or(DEFAULT_FONT_SIZE);
970 for declaration in decode_entities(css).split(';') {
971 let Some((property, value)) = declaration.split_once(':') else {
972 continue;
973 };
974 let value = value.trim().trim_end_matches("!important").trim();
975 match property.trim().to_ascii_lowercase().as_str() {
976 "font-weight" => {
977 format.bold = match value {
978 "bold" | "bolder" => Some(true),
979 "normal" | "lighter" => Some(false),
980 weight => weight.parse::<u32>().ok().map(|weight| weight >= 600),
981 }
982 }
983 "font-style" => format.italic = Some(matches!(value, "italic" | "oblique")),
984 "text-decoration" | "text-decoration-line" => {
985 format.underline = Some(value.contains("underline"));
986 format.strike = Some(value.contains("line-through"));
987 }
988 "font-family" => format.font = family(value).or(format.font),
989 "font-size" => format.font_size = length(value, size).or(format.font_size),
990 "color" => {
991 if let Some(color) = color(value) {
992 format.color = color;
993 }
994 }
995 "background" | "background-color" | "mso-highlight" => {
996 if let Some(color) = value.split_whitespace().find_map(color) {
997 format.highlight = color;
998 }
999 }
1000 "vertical-align" => match value {
1001 "super" => format.superscript = Some(true),
1002 "sub" => format.subscript = Some(true),
1003 _ => {}
1004 },
1005 _ => {}
1006 }
1007 }
1008 format
1009}
1010
1011/// The first family a `font-family` names, unless it is a generic one or a browser's name
1012/// for the system's.
1013fn family(value: &str) -> Option<String> {
1014 let first = value
1015 .split(',')
1016 .next()?
1017 .trim()
1018 .trim_matches(['"', '\''])
1019 .trim();
1020 let generic = [
1021 "serif",
1022 "sans-serif",
1023 "monospace",
1024 "cursive",
1025 "fantasy",
1026 "system-ui",
1027 "inherit",
1028 "blinkmacsystemfont",
1029 ];
1030 let lower = first.to_ascii_lowercase();
1031 (!first.is_empty() && !first.starts_with('-') && !generic.contains(&lower.as_str()))
1032 .then(|| first.to_owned())
1033}
1034
1035/// A CSS length in points, `em` and `%` of `size`.
1036fn length(value: &str, size: f32) -> Option<f32> {
1037 let value = value.trim();
1038 let keyword = match value {
1039 "xx-small" => Some(7.0),
1040 "x-small" => Some(7.5),
1041 "small" => Some(10.0),
1042 "medium" => Some(12.0),
1043 "large" => Some(13.5),
1044 "x-large" => Some(18.0),
1045 "xx-large" => Some(24.0),
1046 _ => None,
1047 };
1048 if keyword.is_some() {
1049 return keyword;
1050 }
1051 let split = value
1052 .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-'))
1053 .unwrap_or(value.len());
1054 let (number, unit) = value.split_at(split);
1055 let number: f32 = number.parse().ok()?;
1056 let points = match unit.trim().to_ascii_lowercase().as_str() {
1057 "pt" => number,
1058 "px" | "" => number * 0.75,
1059 "in" => number * 72.0,
1060 "cm" => number * 72.0 / 2.54,
1061 "mm" => number * 72.0 / 25.4,
1062 "pc" => number * 12.0,
1063 "em" | "rem" => number * size,
1064 "%" => number * size / 100.0,
1065 _ => return None,
1066 };
1067 (points.is_finite() && points > 0.0).then_some(points)
1068}
1069
1070/// A CSS colour as a COLORREF: `Some(None)` for black and the defaults, which pasted text
1071/// takes as automatic so it follows the page; none where it isn't one.
1072fn color(value: &str) -> Option<Option<u32>> {
1073 let value = value.trim().to_ascii_lowercase();
1074 let rgb = |red: u32, green: u32, blue: u32| Some(red | green << 8 | blue << 16);
1075 let parsed = if let Some(hex) = value.strip_prefix('#') {
1076 let digits: Vec<u32> = hex.chars().map(|c| c.to_digit(16)).collect::<Option<_>>()?;
1077 match digits[..] {
1078 [r, g, b] => rgb(r * 17, g * 17, b * 17),
1079 [r1, r0, g1, g0, b1, b0] => rgb(r1 * 16 + r0, g1 * 16 + g0, b1 * 16 + b0),
1080 _ => return None,
1081 }
1082 } else if let Some(arguments) = value
1083 .strip_prefix("rgb(")
1084 .or_else(|| value.strip_prefix("rgba("))
1085 {
1086 let channels: Vec<u32> = arguments
1087 .trim_end_matches(')')
1088 .split(',')
1089 .take(3)
1090 .map(|channel| {
1091 channel
1092 .trim()
1093 .parse::<f32>()
1094 .ok()
1095 .map(|c| c.clamp(0.0, 255.0) as u32)
1096 })
1097 .collect::<Option<_>>()?;
1098 match channels[..] {
1099 [r, g, b] => rgb(r, g, b),
1100 _ => return None,
1101 }
1102 } else {
1103 match value.as_str() {
1104 "black" | "windowtext" | "auto" | "inherit" | "initial" | "currentcolor" | "none"
1105 | "transparent" => None,
1106 "white" => rgb(255, 255, 255),
1107 "red" => rgb(255, 0, 0),
1108 "green" => rgb(0, 128, 0),
1109 "lime" => rgb(0, 255, 0),
1110 "blue" => rgb(0, 0, 255),
1111 "yellow" => rgb(255, 255, 0),
1112 "orange" => rgb(255, 165, 0),
1113 "purple" => rgb(128, 0, 128),
1114 "gray" | "grey" => rgb(128, 128, 128),
1115 "silver" => rgb(192, 192, 192),
1116 "maroon" => rgb(128, 0, 0),
1117 "navy" => rgb(0, 0, 128),
1118 "teal" => rgb(0, 128, 128),
1119 "olive" => rgb(128, 128, 0),
1120 "aqua" | "cyan" => rgb(0, 255, 255),
1121 "fuchsia" | "magenta" => rgb(255, 0, 255),
1122 "darkred" => rgb(139, 0, 0),
1123 "darkblue" => rgb(0, 0, 139),
1124 "darkgreen" => rgb(0, 100, 0),
1125 _ => return None,
1126 }
1127 };
1128 Some(parsed.filter(|color| *color != 0))
1129}
1130
1131/// The value `name` takes in a tag's `style`.
1132fn style(tag: &str, name: &str) -> Option<String> {
1133 decode_entities(attribute(tag, "style")?)
1134 .split(';')
1135 .filter_map(|declaration| declaration.split_once(':'))
1136 .find(|(property, _)| property.trim().eq_ignore_ascii_case(name))
1137 .map(|(_, value)| value.trim().to_owned())
1138}
1139
1140/// Where a tag's text ends, before its `>`, outside quoted attribute values.
1141fn tag_end(tag: &str) -> usize {
1142 let mut quote = None;
1143 for (at, c) in tag.char_indices() {
1144 match (quote, c) {
1145 (None, '"' | '\'') => quote = Some(c),
1146 (Some(open), _) if c == open => quote = None,
1147 (None, '>') => return at,
1148 _ => {}
1149 }
1150 }
1151 tag.len()
1152}
1153
1154/// The value of attribute `name` in `tag`, entities still encoded.
1155fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
1156 let mut rest = tag;
1157 while let Some(at) = rest.find('=') {
1158 let key = rest[..at].trim_end().rsplit(char::is_whitespace).next()?;
1159 let value = rest[at + 1..].trim_start();
1160 let (value, after) = match value.chars().next()? {
1161 quote @ ('"' | '\'') => value[1..].split_once(quote)?,
1162 _ => value.split_at(value.find(char::is_whitespace).unwrap_or(value.len())),
1163 };
1164 if key.eq_ignore_ascii_case(name) {
1165 return Some(value);
1166 }
1167 rest = after;
1168 }
1169 None
1170}
1171
1172fn decode_entities(text: &str) -> String {
1173 let mut decoded = String::with_capacity(text.len());
1174 let mut rest = text;
1175 while let Some(at) = rest.find('&') {
1176 decoded.push_str(&rest[..at]);
1177 rest = &rest[at..];
1178 let entity = rest[1..]
1179 .find(';')
1180 .filter(|end| *end <= 10)
1181 .map(|end| &rest[1..end + 1]);
1182 let c = entity.and_then(|entity| match entity {
1183 "amp" => Some('&'),
1184 "lt" => Some('<'),
1185 "gt" => Some('>'),
1186 "quot" => Some('"'),
1187 "apos" => Some('\''),
1188 "nbsp" => Some('\u{a0}'),
1189 _ => {
1190 let number = entity.strip_prefix('#')?;
1191 let code = match number.strip_prefix(['x', 'X']) {
1192 Some(hex) => u32::from_str_radix(hex, 16).ok()?,
1193 None => number.parse().ok()?,
1194 };
1195 char::from_u32(code)
1196 }
1197 });
1198 match (c, entity) {
1199 (Some(c), Some(entity)) => {
1200 decoded.push(c);
1201 rest = &rest[entity.len() + 2..];
1202 }
1203 _ => {
1204 decoded.push('&');
1205 rest = &rest[1..];
1206 }
1207 }
1208 }
1209 decoded.push_str(rest);
1210 decoded
1211}
1212
1213#[cfg(test)]
1214mod tests {
1215 use super::*;
1216
1217 fn clips(html: &str) -> Vec<Clip> {
1218 html_pieces(html, 0x409, |_, _| None)
1219 .into_iter()
1220 .map(|piece| match piece {
1221 Piece::Clip(clip) => clip,
1222 _ => panic!("a picture where none was loaded"),
1223 })
1224 .collect()
1225 }
1226
1227 const ONENOTE: &str = include_str!("../../../../corpus/clipboard/onenote-2010.html");
1228
1229 /// What OneNote 2010 copied (`corpus/clipboard`) pastes with its formatting, links,
1230 /// lists and table; its tag is not in its HTML.
1231 #[test]
1232 fn onenotes_html_pastes_with_its_formatting() {
1233 let [clip] = &clips(ONENOTE)[..] else {
1234 panic!("one clip")
1235 };
1236 assert_eq!(
1237 clip.outline(),
1238 [
1239 "<b>Bold line</>",
1240 "plain <i>italic</> <color=0000c0>red</> <size=16>big</> \
1241 <font=Times New Roman>times</> <u>under</> <highlight=00ffff>hi</> \
1242 <link>link</> -> https://example.com/",
1243 "• bullet one",
1244 " • nested bullet",
1245 "• bullet two",
1246 "1. number one",
1247 "1. number two",
1248 "tagged todo",
1249 "after",
1250 "table 2x2",
1251 " | 0,0: a1",
1252 " | 0,1: <b>b1</>",
1253 " | 1,0: a2",
1254 " | 1,1: b2",
1255 "last line",
1256 ]
1257 );
1258 }
1259
1260 /// Word 2010's list paragraphs (`corpus/clipboard/word-2010.html`) paste as the lists
1261 /// OneNote 2010 made of them (lab, 2026-10-02): each level nested under the item above,
1262 /// a bullet in Word's own glyph and font, a number in Word's sequence and punctuation.
1263 #[test]
1264 fn words_lists_paste_as_lists() {
1265 let html = include_str!("../../../../corpus/clipboard/word-2010.html");
1266 let [clip] = &clips(html)[..] else {
1267 panic!("one clip")
1268 };
1269 assert_eq!(
1270 clip.outline(),
1271 [
1272 "• Bullet one",
1273 " • Bullet nested",
1274 " • Bullet deeper",
1275 "• Bullet two",
1276 "Plain paragraph",
1277 "1. Number one",
1278 " a. Number nested",
1279 " i. Number deeper",
1280 "1. Number two",
1281 "Last plain",
1282 ]
1283 );
1284 let lists = crate::document::leaves(&clip.paragraphs, None)
1285 .filter_map(
1286 |(.., node)| match &clip.definitions[node.lists.first()?].kind {
1287 Kind::List {
1288 font,
1289 format,
1290 bullet,
1291 ..
1292 } => Some((font.clone(), format.clone().unwrap(), *bullet)),
1293 _ => None,
1294 },
1295 )
1296 .collect::<Vec<_>>();
1297 let bullet = |font: &str, glyph: &str| (Some(font.to_owned()), glyph.to_owned(), None);
1298 let number = |format: &str| (None, format.to_owned(), None);
1299 assert_eq!(
1300 lists,
1301 [
1302 bullet("Symbol", "\u{b7}"),
1303 bullet("Courier New", "o"),
1304 bullet("Wingdings", "\u{a7}"),
1305 bullet("Symbol", "\u{b7}"),
1306 number("\u{fffd}\u{0}."),
1307 number("\u{fffd}\u{4}."),
1308 number("\u{fffd}\u{2}."),
1309 number("\u{fffd}\u{0}."),
1310 ]
1311 );
1312 }
1313
1314 /// LibreOffice writes lists as nested `ul` and `ol` around paragraphs, leaving items
1315 /// unclosed.
1316 #[test]
1317 fn libreoffices_lists_paste_as_lists() {
1318 let clip = &clips(
1319 "<ul>\n\t<li><p style=\"margin-bottom: 0in\">Bullet one</p>\n\t<ul>\n\t\t\
1320 <li><p>Bullet nested</p>\n\t</ul>\n\t<li><p>Bullet two</p>\n</ul>\n<ol>\n\t\
1321 <li><p>Number one</p>\n\t<ol type=\"a\">\n\t\t<li><p>Number nested</p>\n\t\
1322 </ol>\n\t<li><p>Number two</p>\n</ol>",
1323 )[0];
1324 assert_eq!(
1325 clip.outline(),
1326 [
1327 "• Bullet one",
1328 " • Bullet nested",
1329 "• Bullet two",
1330 "1. Number one",
1331 " a. Number nested",
1332 "1. Number two",
1333 ]
1334 );
1335 }
1336
1337 /// Snowbound's HTML reads back as the clip it was written from.
1338 #[test]
1339 fn snowbound_html_reads_back_as_written() {
1340 let [clip] = &clips(ONENOTE)[..] else {
1341 panic!("one clip")
1342 };
1343 let written = clip.html();
1344 let [read] = &clips(&written)[..] else {
1345 panic!("one clip")
1346 };
1347 assert_eq!(read.outline(), clip.outline());
1348 let runs = |clip: &Clip| {
1349 crate::document::leaves(&clip.paragraphs, None)
1350 .map(|(.., node)| node.text().unwrap().text.clone())
1351 .collect::<Vec<_>>()
1352 };
1353 assert_eq!(runs(read), runs(clip));
1354 }
1355
1356 /// Markup in text is escaped, spaces kept, and a paragraph that shows nothing still
1357 /// takes a line.
1358 #[test]
1359 fn text_survives_html() {
1360 let clip = &clips("<p>a &lt;b&gt; &amp;&nbsp;&nbsp;c</p><p>&nbsp;</p><p>d</p>")[0];
1361 assert_eq!(clip.text(), "a <b> & c\n \nd");
1362 let read = &clips(&clip.html())[0];
1363 assert_eq!(read.text(), clip.text());
1364 }
1365
1366 /// Other applications' markup: tags and inline styles, unclosed items, sizes in pixels
1367 /// and colours by name.
1368 #[test]
1369 fn web_markup_gives_formatting() {
1370 let clip = &clips(
1371 "<div style=\"font-family: Arial, sans-serif; font-size: 16px\">\
1372 <strong>Bold</strong> <em>it</em> <font color=red size=5>big</font> \
1373 <span style=\"font-weight:700; text-decoration:line-through\">gone</span>\
1374 x<sup>2</sup></div><ol type=a><li>first<li>second</ol>",
1375 )[0];
1376 assert_eq!(
1377 clip.outline(),
1378 [
1379 "<b font=Arial size=12>Bold</><font=Arial size=12> </>\
1380 <i font=Arial size=12>it</><font=Arial size=12> </>\
1381 <color=0000ff font=Arial size=18>big</><font=Arial size=12> </>\
1382 <b s font=Arial size=12>gone</><font=Arial size=12>x</>\
1383 <sup font=Arial size=12>2</>",
1384 "a. first",
1385 "a. second",
1386 ]
1387 );
1388 }
1389
1390 /// Stored text, fonts and link targets can't break out of the HTML Copy writes: quotes are
1391 /// escaped, a font name that isn't plainly one is left out, and a link to anything but a
1392 /// web or mail address, the notebook or a relative path stays text.
1393 #[test]
1394 fn hostile_fonts_links_and_quotes_stay_inert() {
1395 let run = |text: &str, format: Format| (text.to_owned(), format);
1396 let link = |target: &str| {
1397 let code = Format {
1398 hyperlink: Some(true),
1399 hidden: Some(true),
1400 ..Format::default()
1401 };
1402 let label = Format {
1403 hyperlink: Some(true),
1404 hyperlink_label: Some(true),
1405 ..Format::default()
1406 };
1407 [run(&field_code(target), code), run("label", label)]
1408 };
1409 let fonts = [
1410 "Evil' tabindex=1 autofocus onfocus='alert(1)//",
1411 "A B\";background-image:url(https://evil.example/px.png);x:\"",
1412 ];
1413 let mut runs: Vec<(String, Format)> = fonts
1414 .iter()
1415 .map(|font| {
1416 let format = Format {
1417 font: Some((*font).to_owned()),
1418 ..Format::default()
1419 };
1420 run("it's <b>", format)
1421 })
1422 .collect();
1423 for target in [
1424 "javascript:alert(document.domain)",
1425 " JaVa\tScRiPt:alert(1)",
1426 "data:text/html,<script>alert(1)</script>",
1427 "vbscript:msgbox",
1428 "\\\\server\\share\\notes.one",
1429 "https://example.invalid/a?b='c'",
1430 "mailto:a@example.invalid",
1431 "onenote:#Page&section-id={00000000-0000-0000-0000-000000000000}&end",
1432 "notes/page.html",
1433 ] {
1434 runs.extend(link(target));
1435 runs.push(run(" ", Format::default()));
1436 }
1437 let paragraph = node(Paragraph::from_runs(runs), Format::default()).unwrap();
1438 let html = Clip::new(vec![paragraph], &BTreeMap::new()).html();
1439 for hostile in [
1440 "onfocus=",
1441 "autofocus",
1442 "url(",
1443 "javascript",
1444 "JaVa",
1445 "data:",
1446 "vbscript",
1447 "server",
1448 "<b>",
1449 "'c'",
1450 ] {
1451 assert!(!html.contains(hostile), "{hostile} in {html}");
1452 }
1453 assert!(html.contains("it&#39;s &lt;b&gt;"), "{html}");
1454 for kept in [
1455 "href=\"https://example.invalid/a?b=&#39;c&#39;\"",
1456 "href=\"mailto:a@example.invalid\"",
1457 "href=\"onenote:#Page",
1458 "href=\"notes/page.html\"",
1459 ] {
1460 assert!(html.contains(kept), "{kept} missing from {html}");
1461 }
1462 assert_eq!(html.matches("<a href").count(), 4, "{html}");
1463 }
1464
1465 /// As OneNote 2010 pasted `<p>before <img> after</p>` (lab, 2026-09-30): the text on
1466 /// either side of the picture, the picture at the size its attributes give; one in a
1467 /// table is left out.
1468 #[test]
1469 fn a_pasted_page_gives_its_text_and_pictures_in_order() {
1470 let html = "Version:0.9\r\n<html><head><style>p{}</style><title>T</title></head>\
1471 <body><!--StartFragment--><p>before <img alt=\"a > b\" \
1472 src=\"file:///C:/work/pic.png\" width=\"200\" height=\"100px\"> after</p>\
1473 <p>Fish &amp; chips&nbsp;&#x2014;&#8212;</p><ul><li>one<li>two<br>three</ul>\
1474 <table><tr><td><img src=\"cell.png\">cell</td></tr></table>\
1475 <img src=\"missing.png\"><IMG SRC='https://example.invalid/a.png' width=40>\
1476 <!--EndFragment--></body></html>";
1477 let mut asked = Vec::new();
1478 let pieces = html_pieces(html, 0x409, |source, css| {
1479 asked.push((source.to_owned(), css));
1480 match source {
1481 "missing.png" => None,
1482 "https://example.invalid/a.png" => Some(Piece::Awaited),
1483 _ => Some(Piece::Picture(vec![0; 3], [150.0, 75.0])),
1484 }
1485 });
1486 assert_eq!(
1487 asked,
1488 [
1489 (
1490 "file:///C:/work/pic.png".to_owned(),
1491 [Some(200.0), Some(100.0)]
1492 ),
1493 ("missing.png".to_owned(), [None, None]),
1494 (
1495 "https://example.invalid/a.png".to_owned(),
1496 [Some(40.0), None]
1497 ),
1498 ]
1499 );
1500 let shown: Vec<Vec<String>> = pieces
1501 .iter()
1502 .map(|piece| match piece {
1503 Piece::Clip(clip) => clip.outline(),
1504 Piece::Picture(bytes, size) => vec![format!("[{} {size:?}]", bytes.len())],
1505 Piece::Awaited => vec!["[awaited]".to_owned()],
1506 })
1507 .collect();
1508 assert_eq!(
1509 shown,
1510 [
1511 vec!["before"],
1512 vec!["[3 [150.0, 75.0]]"],
1513 vec![
1514 "after",
1515 "Fish & chips \u{2014}\u{2014}",
1516 "• one",
1517 "• two",
1518 " three",
1519 "table 1x1",
1520 " | 0,0: cell",
1521 ],
1522 vec!["[awaited]"],
1523 ]
1524 );
1525 }
1526}