1use crate::{merge_text, CodeData, Inline, TagKind};
26use serde::{Deserialize, Serialize};
27use std::collections::BTreeMap;
28
29const OPEN: char = '\u{27E6}';
30const CLOSE: char = '\u{27E7}';
31
32pub const PAIR_LETTER: char = 'g';
34pub const POINT_LETTER: char = 'x';
36pub const FREE_LETTER: char = 'p';
38
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41pub struct LocosCode {
42 pub id: String,
44 pub letter: char,
46 #[serde(default)]
48 pub open: Option<String>,
49 #[serde(default)]
51 pub close: Option<String>,
52 #[serde(default)]
54 pub free: bool,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub unpaired: Option<TagKind>,
58}
59
60pub type LocosMap = BTreeMap<String, LocosCode>;
62
63pub fn to_locos_text(inl: &[Inline]) -> (String, LocosMap) {
65 to_locos_text_as(inl, PAIR_LETTER)
66}
67
68pub fn to_locos_text_as(inl: &[Inline], pair_letter: char) -> (String, LocosMap) {
71 convert(inl, pair_letter, pairs(inl), None, None)
72}
73
74pub fn locos_pair_letter(format: &str) -> char {
77 if matches!(format, "docx" | "pptx" | "xlsx") {
78 'r'
79 } else {
80 PAIR_LETTER
81 }
82}
83
84const LOCOS_PAIRS_BY_ID: &[&str] = &["html", "aspx", "erb", "shtml", "jsp", "phtml", "epub", "eml"];
93
94const LOCOS_NUMBERED_BY_ID: &[&str] = &["docx", "pptx", "xlsx"];
100
101pub fn to_locos_text_for(format: &str, inl: &[Inline]) -> (String, LocosMap) {
109 let letter = locos_pair_letter(format);
110 if LOCOS_PAIRS_BY_ID.contains(&format) {
111 convert(inl, letter, pairs_by_id(inl), None, None)
112 } else if LOCOS_NUMBERED_BY_ID.contains(&format) {
113 to_locos_text_numbered(inl, letter)
114 } else {
115 to_locos_text_as(inl, letter)
116 }
117}
118
119const LOCOS_RUN_PAIRS: &[&str] = &["idml", "icml"];
123
124pub fn to_locos_text_coded(format: &str, inl: &[Inline], codes: &BTreeMap<String, CodeData>) -> (String, LocosMap) {
129 if !LOCOS_RUN_PAIRS.contains(&format) {
130 return to_locos_text_for(format, inl);
131 }
132 let run = |id: &str| codes.get(id).filter(|c| c.label.as_deref() == Some("run")).map(|_| 'r');
133 convert(inl, PAIR_LETTER, pairs(inl), None, Some(&run))
134}
135
136pub fn to_locos_text_numbered(inl: &[Inline], pair_letter: char) -> (String, LocosMap) {
143 let partner = pairs(inl);
144 let mut nums = Vec::new();
145 let mut seen = std::collections::BTreeSet::new();
146 for (pos, i) in inl.iter().enumerate() {
147 let Inline::Tag { id, kind, .. } = i else { continue };
148 if *kind == TagKind::Close && partner[pos].is_some() {
150 continue;
151 }
152 let ok = !id.is_empty() && id.len() <= 18 && id.bytes().all(|b| b.is_ascii_digit()) && !id.starts_with('0');
153 match id.parse::<usize>() {
154 Ok(n) if ok && seen.insert(n) => nums.push(n),
155 _ => return to_locos_text_as(inl, pair_letter),
156 }
157 }
158 let reserved = reserved_numbers(inl);
160 if nums.iter().any(|n| reserved.contains(n)) {
161 return to_locos_text_as(inl, pair_letter);
162 }
163 convert(inl, pair_letter, partner, Some(&nums), None)
164}
165
166fn reserved_numbers(inl: &[Inline]) -> std::collections::BTreeSet<usize> {
171 let mut out = std::collections::BTreeSet::new();
172 let mut run = String::new();
173 let flush = |run: &mut String, out: &mut std::collections::BTreeSet<usize>| {
174 let mut rest = run.as_str();
175 while let Some(at) = rest.find(OPEN) {
176 rest = &rest[at..];
177 match scan_token(rest) {
178 Some((len, _, _, num)) => {
179 if let Ok(n) = num.parse() {
180 out.insert(n);
181 }
182 rest = &rest[len..];
183 }
184 None => rest = &rest[OPEN.len_utf8()..],
185 }
186 }
187 run.clear();
188 };
189 for i in inl {
190 match i {
191 Inline::Text(t) => run.push_str(t),
192 Inline::Tag { .. } => flush(&mut run, &mut out),
193 }
194 }
195 flush(&mut run, &mut out);
196 out
197}
198
199type PairLetterOf<'a> = &'a dyn Fn(&str) -> Option<char>;
202
203fn convert(inl: &[Inline], pair_letter: char, partner: Vec<Option<usize>>, nums: Option<&[usize]>, letter_of: Option<PairLetterOf>) -> (String, LocosMap) {
204 let pair = if pair_letter.is_ascii_lowercase() && pair_letter != POINT_LETTER && pair_letter != FREE_LETTER {
205 pair_letter
206 } else {
207 PAIR_LETTER
208 };
209 let reserved = if nums.is_some() { Default::default() } else { reserved_numbers(inl) };
211 let mut last = 0usize;
212 let mut number = |k: usize| match nums {
213 Some(v) => v.get(k - 1).copied().unwrap_or(k),
214 None => {
215 last += 1;
216 while reserved.contains(&last) {
217 last += 1;
218 }
219 last
220 }
221 };
222 let mut text = String::new();
223 let mut map = LocosMap::new();
224 let mut open_num: BTreeMap<usize, usize> = BTreeMap::new();
226 let mut k = 0usize;
227 for (pos, i) in inl.iter().enumerate() {
228 let (id, kind, display, free) = match i {
229 Inline::Text(t) => {
230 text.push_str(t);
231 continue;
232 }
233 Inline::Tag { id, kind, display, free } => (id, kind, display, free),
234 };
235 let code = |letter, open: Option<&String>, close: Option<&String>, free, unpaired| LocosCode {
236 id: id.clone(),
237 letter,
238 open: open.cloned(),
239 close: close.cloned(),
240 free,
241 unpaired,
242 };
243 match (kind, partner[pos]) {
244 (TagKind::Open, Some(_)) => {
245 k += 1;
246 let n = number(k);
247 open_num.insert(pos, n);
248 let pair = letter_of.and_then(|f| f(id)).unwrap_or(pair);
249 map.insert(n.to_string(), code(pair, Some(display), None, false, None));
250 text.push_str(&format!("{OPEN}{pair}{n}{CLOSE}"));
251 }
252 (TagKind::Close, Some(o)) => {
253 let num = open_num.get(&o).copied().unwrap_or_default();
254 let mut letter = pair;
256 if let Some(c) = map.get_mut(&num.to_string()) {
257 c.close = Some(display.clone());
258 letter = c.letter;
259 }
260 text.push_str(&format!("{OPEN}/{letter}{num}{CLOSE}"));
261 }
262 (TagKind::Open, None) => {
263 k += 1;
264 let n = number(k);
265 map.insert(n.to_string(), code(POINT_LETTER, Some(display), None, false, Some(TagKind::Open)));
266 text.push_str(&format!("{OPEN}{POINT_LETTER}{n}{CLOSE}"));
267 }
268 (TagKind::Close, None) => {
269 k += 1;
270 let n = number(k);
271 map.insert(n.to_string(), code(POINT_LETTER, None, Some(display), false, Some(TagKind::Close)));
272 text.push_str(&format!("{OPEN}{POINT_LETTER}{n}{CLOSE}"));
273 }
274 (TagKind::Standalone, _) => {
275 k += 1;
276 let n = number(k);
277 let letter = if *free { FREE_LETTER } else { POINT_LETTER };
278 map.insert(n.to_string(), code(letter, Some(display), None, *free, None));
279 text.push_str(&format!("{OPEN}{letter}{n}{CLOSE}"));
280 }
281 }
282 }
283 (text, map)
284}
285
286fn pairs(inl: &[Inline]) -> Vec<Option<usize>> {
290 let mut partner = vec![None; inl.len()];
291 let mut stack: Vec<(&str, usize)> = Vec::new();
292 for (pos, i) in inl.iter().enumerate() {
293 match i {
294 Inline::Tag { id, kind: TagKind::Open, .. } => stack.push((id.as_str(), pos)),
295 Inline::Tag { id, kind: TagKind::Close, .. } => {
296 if let Some(at) = stack.iter().rposition(|(oid, _)| oid == id) {
297 let (_, o) = stack[at];
298 stack.truncate(at);
299 partner[o] = Some(pos);
300 partner[pos] = Some(o);
301 }
302 }
303 _ => {}
304 }
305 }
306 partner
307}
308
309fn pairs_by_id(inl: &[Inline]) -> Vec<Option<usize>> {
313 let mut partner = vec![None; inl.len()];
314 let mut open: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
316 for (pos, i) in inl.iter().enumerate() {
317 match i {
318 Inline::Tag { id, kind: TagKind::Open, .. } => {
319 partner[pos] = Some(pos);
320 open.entry(id.as_str()).or_default().push(pos);
321 }
322 Inline::Tag { id, kind: TagKind::Close, .. } => {
323 if let Some(o) = open.get_mut(id.as_str()).and_then(Vec::pop) {
324 partner[o] = Some(pos);
325 partner[pos] = Some(o);
326 }
327 }
328 _ => {}
329 }
330 }
331 partner
332}
333
334#[derive(Debug, Clone, PartialEq, Eq)]
336pub enum TokenProblem {
337 Stray {
339 at: usize,
341 },
342 Unknown {
344 token: String,
346 },
347 KindMismatch {
350 token: String,
352 },
353}
354
355pub fn from_locos_text(text: &str, map: &LocosMap) -> Vec<Inline> {
358 parse_locos_text(text, map).0
359}
360
361pub fn parse_locos_text(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
363 parse_tokens(text, map, false, true)
364}
365
366const LOCOS_DROPS_MISMATCH: &[&str] = &["toml", "js", "rc"];
372
373const LOCOS_NO_FREE_LETTER: &[&str] = &["dxf"];
377
378pub fn parse_locos_text_for(format: &str, text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
382 let (inl, problems, _) = repair_locos_text_for(format, text, map);
383 (inl, problems)
384}
385
386const LOCOS_REPAIRS_TAGS: &[&str] =
394 &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "xml", "dita", "docbook", "android", "javaxml", "ttml", "xmb", "xtb", "mdx"];
395
396const LOCOS_TYPED_TAGS: &[&str] = &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "mdx"];
400
401pub fn locos_repairs_tags(format: &str) -> bool {
405 LOCOS_REPAIRS_TAGS.contains(&format)
406}
407
408pub(crate) fn locos_keeps_typed_tags(format: &str) -> bool {
411 LOCOS_TYPED_TAGS.contains(&format)
412}
413
414#[derive(Debug, Clone, PartialEq, Eq)]
417#[non_exhaustive]
418pub enum TagRepair {
419 Repeated {
421 token: String,
423 },
424 StrayClose {
426 token: String,
428 },
429 Unclosed {
431 token: String,
433 },
434 PairAsPoint {
437 token: String,
439 },
440}
441
442pub fn repair_locos_text_for(format: &str, text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>, Vec<TagRepair>) {
454 if locos_repairs_tags(format) {
455 return parse_tokens_repairing(text, map);
456 }
457 let (inl, problems) = parse_tokens(text, map, LOCOS_DROPS_MISMATCH.contains(&format), !LOCOS_NO_FREE_LETTER.contains(&format));
458 (inl, problems, Vec::new())
459}
460
461fn point_tag(code: &LocosCode) -> Inline {
463 match code.unpaired {
464 Some(TagKind::Close) => Inline::Tag { id: code.id.clone(), kind: TagKind::Close, display: code.close.clone().unwrap_or_default(), free: false },
465 Some(TagKind::Open) => Inline::Tag { id: code.id.clone(), kind: TagKind::Open, display: code.open.clone().unwrap_or_default(), free: false },
466 _ => Inline::Tag { id: code.id.clone(), kind: TagKind::Standalone, display: code.open.clone().unwrap_or_default(), free: code.free },
467 }
468}
469
470fn pair_tag(code: &LocosCode, kind: TagKind) -> Inline {
471 let display = if kind == TagKind::Close { code.close.clone() } else { code.open.clone() };
472 Inline::Tag { id: code.id.clone(), kind, display: display.unwrap_or_default(), free: false }
473}
474
475fn parse_tokens_repairing(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>, Vec<TagRepair>) {
478 let mut out: Vec<Inline> = Vec::new();
479 let mut problems = Vec::new();
480 let mut repairs = Vec::new();
481 let mut lit = String::new();
482 let mut used: std::collections::BTreeSet<String> = Default::default();
483 let mut stack: Vec<(String, String, bool)> = Vec::new();
485 let mut rest = text;
486 let mut pos = 0usize;
487 while let Some(ch) = rest.chars().next() {
488 let len = ch.len_utf8();
489 if ch == OPEN {
490 if let Some((tok_len, closing, letter, num)) = scan_token(rest) {
491 let token = rest[..tok_len].to_string();
492 rest = &rest[tok_len..];
493 pos += tok_len;
494 let Some(code) = map.get(&num) else {
495 problems.push(TokenProblem::Unknown { token: token.clone() });
496 lit.push_str(&token);
497 continue;
498 };
499 if !lit.is_empty() {
500 out.push(Inline::Text(std::mem::take(&mut lit)));
501 }
502 let code_point = code.letter == POINT_LETTER || code.letter == FREE_LETTER;
503 let typed_point = letter.is_some_and(|l| l == POINT_LETTER || l == FREE_LETTER);
504 if closing {
505 out.push(if code_point {
507 Inline::Tag { id: code.id.clone(), kind: TagKind::Close, display: code.close.clone().unwrap_or_default(), free: false }
508 } else {
509 pair_tag(code, TagKind::Close)
510 });
511 if !code_point && stack.last().is_some_and(|f| f.0 == num) {
512 stack.pop();
513 } else {
514 repairs.push(TagRepair::StrayClose { token });
515 }
516 } else if code_point {
517 out.push(point_tag(code));
518 if !used.insert(num) {
519 repairs.push(TagRepair::Repeated { token });
520 }
521 } else if typed_point {
522 out.push(pair_tag(code, TagKind::Open));
524 out.push(pair_tag(code, TagKind::Close));
525 repairs.push(if used.insert(num) { TagRepair::PairAsPoint { token } } else { TagRepair::Repeated { token } });
526 } else {
527 out.push(pair_tag(code, TagKind::Open));
528 let first = used.insert(num.clone());
529 if !first {
530 repairs.push(TagRepair::Repeated { token: token.clone() });
531 }
532 stack.push((num, token, first));
533 }
534 continue;
535 }
536 problems.push(TokenProblem::Stray { at: pos });
537 } else if ch == CLOSE {
538 problems.push(TokenProblem::Stray { at: pos });
539 }
540 lit.push(ch);
541 rest = &rest[len..];
542 pos += len;
543 }
544 if !lit.is_empty() {
545 out.push(Inline::Text(lit));
546 }
547 for (_, token, written) in stack.into_iter().rev() {
548 if written {
549 repairs.push(TagRepair::Unclosed { token });
550 }
551 }
552 (merge_text(out), problems, repairs)
553}
554
555pub(crate) fn repair_tags(source: &[Inline], target: Vec<Inline>, points: bool) -> Vec<Inline> {
561 use std::collections::HashMap;
562 let partner = pairs(source);
563 let mut pair_allowed: HashMap<&str, usize> = HashMap::new();
564 let mut point_allowed: HashMap<(&str, TagKind), usize> = HashMap::new();
565 let mut close_display: HashMap<&str, &str> = HashMap::new();
566 for (pos, i) in source.iter().enumerate() {
567 let Inline::Tag { id, kind, display, .. } = i else { continue };
568 match (kind, partner[pos]) {
569 (TagKind::Open, Some(_)) => *pair_allowed.entry(id.as_str()).or_default() += 1,
570 (TagKind::Close, Some(_)) => {
571 close_display.entry(id.as_str()).or_insert(display.as_str());
572 }
573 _ => *point_allowed.entry((id.as_str(), *kind)).or_default() += 1,
574 }
575 }
576 let known: std::collections::HashSet<&str> = source.iter().filter_map(|i| if let Inline::Tag { id, .. } = i { Some(id.as_str()) } else { None }).collect();
577 let mut pair_used: HashMap<String, usize> = HashMap::new();
578 let mut point_used: HashMap<(String, TagKind), usize> = HashMap::new();
579 let mut stack: Vec<(String, bool)> = Vec::new();
580 let mut out = Vec::with_capacity(target.len());
581 for i in target {
582 let Inline::Tag { id, kind, .. } = &i else {
583 out.push(i);
584 continue;
585 };
586 let paired = pair_allowed.get(id.as_str()).copied().unwrap_or(0);
587 match kind {
588 TagKind::Open if paired > 0 => {
589 let n = pair_used.entry(id.clone()).or_default();
590 let write = *n < paired;
591 if write {
592 *n += 1;
593 }
594 stack.push((id.clone(), write));
595 if write {
596 out.push(i);
597 }
598 }
599 TagKind::Close if paired > 0 && stack.last().is_some_and(|(top, _)| top == id) => {
600 if let Some((_, true)) = stack.pop() {
601 out.push(i);
602 }
603 }
604 TagKind::Close if paired > 0 && !point_allowed.contains_key(&(id.as_str(), TagKind::Close)) => {}
605 _ => match point_allowed.get(&(id.as_str(), *kind)) {
606 None if known.contains(id.as_str()) => {}
608 None => out.push(i),
610 Some(_) if !points => out.push(i),
611 Some(max) => {
612 let n = point_used.entry((id.clone(), *kind)).or_default();
613 if *n < *max {
614 *n += 1;
615 out.push(i);
616 }
617 }
618 },
619 }
620 }
621 for (id, written) in stack.into_iter().rev() {
622 if written {
623 let display = close_display.get(id.as_str()).map(|d| d.to_string()).unwrap_or_default();
624 out.push(Inline::Tag { id, kind: TagKind::Close, display, free: false });
625 }
626 }
627 merge_text(out)
628}
629
630fn parse_tokens(text: &str, map: &LocosMap, drop_mismatch: bool, free_letter: bool) -> (Vec<Inline>, Vec<TokenProblem>) {
631 let mut out: Vec<Inline> = Vec::new();
632 let mut problems = Vec::new();
633 let mut lit = String::new();
634 let mut rest = text;
635 let mut pos = 0usize;
636 while let Some(ch) = rest.chars().next() {
637 let len = ch.len_utf8();
638 if ch == OPEN {
639 if let Some((tok_len, closing, letter, num)) = scan_token(rest) {
640 let token = &rest[..tok_len];
641 let found = if free_letter || letter != Some(FREE_LETTER) {
642 resolve(map, closing, letter, &num)
643 } else if map.contains_key(num.as_str()) {
644 Resolved::Mismatch
645 } else {
646 Resolved::Unknown
647 };
648 match found {
649 Resolved::Tag(t) => {
650 if !lit.is_empty() {
651 out.push(Inline::Text(std::mem::take(&mut lit)));
652 }
653 out.push(t);
654 }
655 Resolved::Unknown => {
656 problems.push(TokenProblem::Unknown { token: token.to_string() });
657 lit.push_str(token);
658 }
659 Resolved::Mismatch => {
660 problems.push(TokenProblem::KindMismatch { token: token.to_string() });
661 if !drop_mismatch {
662 lit.push_str(token);
663 }
664 }
665 }
666 rest = &rest[tok_len..];
667 pos += tok_len;
668 continue;
669 }
670 problems.push(TokenProblem::Stray { at: pos });
671 } else if ch == CLOSE {
672 problems.push(TokenProblem::Stray { at: pos });
673 }
674 lit.push(ch);
675 rest = &rest[len..];
676 pos += len;
677 }
678 if !lit.is_empty() {
679 out.push(Inline::Text(lit));
680 }
681 (merge_text(out), problems)
682}
683
684fn scan_token(s: &str) -> Option<(usize, bool, Option<char>, String)> {
686 let mut it = s.char_indices();
687 let (_, c) = it.next()?;
688 if c != OPEN {
689 return None;
690 }
691 let mut closing = false;
692 let mut letter = None;
693 let mut num = String::new();
694 for (idx, c) in it {
695 match c {
696 '/' if !closing && letter.is_none() && num.is_empty() => closing = true,
697 c if c.is_ascii_lowercase() && letter.is_none() && num.is_empty() => letter = Some(c),
698 c if c.is_ascii_digit() => num.push(c),
699 CLOSE if !num.is_empty() => return Some((idx + CLOSE.len_utf8(), closing, letter, num)),
700 _ => return None,
701 }
702 }
703 None
704}
705
706enum Resolved {
707 Tag(Inline),
708 Unknown,
709 Mismatch,
710}
711
712fn resolve(map: &LocosMap, closing: bool, letter: Option<char>, num: &str) -> Resolved {
713 let Some(code) = map.get(num) else { return Resolved::Unknown };
714 let is_point = code.letter == POINT_LETTER || code.letter == FREE_LETTER;
715 if is_point {
718 if closing || letter.is_some_and(|l| l != POINT_LETTER && l != FREE_LETTER) {
719 return Resolved::Mismatch;
720 }
721 return Resolved::Tag(match code.unpaired {
722 Some(TagKind::Close) => Inline::Tag {
723 id: code.id.clone(),
724 kind: TagKind::Close,
725 display: code.close.clone().unwrap_or_default(),
726 free: false,
727 },
728 Some(TagKind::Open) => Inline::Tag {
729 id: code.id.clone(),
730 kind: TagKind::Open,
731 display: code.open.clone().unwrap_or_default(),
732 free: false,
733 },
734 _ => Inline::Tag {
735 id: code.id.clone(),
736 kind: TagKind::Standalone,
737 display: code.open.clone().unwrap_or_default(),
738 free: code.free,
739 },
740 });
741 }
742 if letter.is_some_and(|l| l == POINT_LETTER || l == FREE_LETTER) {
743 return Resolved::Mismatch;
744 }
745 if closing {
746 Resolved::Tag(Inline::Tag {
747 id: code.id.clone(),
748 kind: TagKind::Close,
749 display: code.close.clone().unwrap_or_default(),
750 free: false,
751 })
752 } else {
753 Resolved::Tag(Inline::Tag {
754 id: code.id.clone(),
755 kind: TagKind::Open,
756 display: code.open.clone().unwrap_or_default(),
757 free: false,
758 })
759 }
760}
761
762pub fn is_named_placeholder(s: &str) -> bool {
766 let b = s.as_bytes();
767 match b {
768 [b'{', b'{', ..] => s.ends_with("}}") && s.len() > 4,
769 [b'$', b'{', ..] => s.ends_with('}') && s.len() > 3,
770 [b'{', ..] => {
771 let inner = &s[1..s.len().saturating_sub(1)];
772 s.ends_with('}') && !inner.is_empty() && !inner.starts_with(' ')
773 }
774 [b'%', b'(', ..] => s[2..].contains(')'),
775 [b'%', d, ..] if d.is_ascii_digit() => {
776 let digits = s[1..].bytes().take_while(u8::is_ascii_digit).count();
777 s.as_bytes().get(1 + digits) == Some(&b'$')
778 }
779 _ => false,
780 }
781}
782
783#[doc(hidden)]
788pub fn escape_literal(s: &str) -> String {
789 if !s.contains([OPEN, LIT_MARK]) {
790 return s.to_string();
791 }
792 let mut out = String::with_capacity(s.len() + 8);
793 for c in s.chars() {
794 match c {
795 OPEN => out.push_str("\u{e000}\u{e001}"),
796 LIT_MARK => out.push_str("\u{e000}\u{e000}"),
797 c => out.push(c),
798 }
799 }
800 out
801}
802
803#[doc(hidden)]
806pub fn unescape_literal(s: &str) -> String {
807 if !s.contains(LIT_MARK) {
808 return s.to_string();
809 }
810 let mut out = String::with_capacity(s.len());
811 let mut it = s.chars().peekable();
812 while let Some(c) = it.next() {
813 if c == LIT_MARK {
814 match it.peek() {
815 Some('\u{e001}') => {
816 it.next();
817 out.push(OPEN);
818 continue;
819 }
820 Some(&LIT_MARK) => {
821 it.next();
822 }
823 _ => {}
824 }
825 }
826 out.push(c);
827 }
828 out
829}
830
831const LIT_MARK: char = '\u{e000}';
832
833#[cfg(test)]
834mod tests {
835 use super::*;
836
837 #[test]
838 fn literal_escape_round_trips_every_short_string() {
839 let alpha = ['\u{27e6}', '\u{27e7}', '\u{e000}', '\u{e001}', 'x', '1'];
842 let mut cur: Vec<String> = vec![String::new()];
843 for _ in 0..6 {
844 let mut next = Vec::new();
845 for s in &cur {
846 for c in alpha {
847 let mut t = s.clone();
848 t.push(c);
849 let e = escape_literal(&t);
850 assert!(!e.contains('\u{27e6}'), "{t:?}");
851 assert_eq!(unescape_literal(&e), t, "{t:?}");
852 next.push(t);
853 }
854 }
855 cur = next;
856 }
857 assert_eq!(escape_literal("a\u{e000}\u{27e6}x1\u{27e7}\u{e001}"), "a\u{e000}\u{e000}\u{e000}\u{e001}x1\u{27e7}\u{e001}");
860 assert_eq!(unescape_literal("lone \u{e000} mark"), "lone \u{e000} mark");
861 }
862
863 #[test]
864 fn docx_tokens_carry_locos_numbers() {
865 let inl = vec![
866 Inline::tag("1", TagKind::Open, "<w:r>"),
867 Inline::text("a"),
868 Inline::tag("1", TagKind::Close, "</w:r>"),
869 Inline::tag("3", TagKind::Standalone, "object"),
870 Inline::tag("2", TagKind::Open, "<w:r>"),
871 Inline::text("b"),
872 Inline::tag("2", TagKind::Close, "</w:r>"),
873 ];
874 let (t, map) = to_locos_text_for("docx", &inl);
875 assert_eq!(t, "\u{27e6}r1\u{27e7}a\u{27e6}/r1\u{27e7}\u{27e6}x3\u{27e7}\u{27e6}r2\u{27e7}b\u{27e6}/r2\u{27e7}");
876 assert_eq!(from_locos_text(&t, &map), inl);
877 for f in ["docx", "pptx", "xlsx"] {
879 assert_eq!(to_locos_text_for(f, &inl), to_locos_text_numbered(&inl, 'r'), "{f}");
880 }
881 for f in ["xliff", "html", "po", "markdown", "json", "odt", ""] {
882 assert_eq!(to_locos_text_for(f, &inl).0.matches("\u{27e6}x2\u{27e7}").count(), 1, "{f}");
883 }
884 assert_eq!(to_locos_text_for("xliff", &inl).0, "\u{27e6}g1\u{27e7}a\u{27e6}/g1\u{27e7}\u{27e6}x2\u{27e7}\u{27e6}g3\u{27e7}b\u{27e6}/g3\u{27e7}");
885 let cell = vec![Inline::text("Total")];
887 assert_eq!(to_locos_text_for("xlsx", &cell), to_locos_text_as(&cell, 'r'));
888 let dup = vec![Inline::tag("1", TagKind::Standalone, "o"), Inline::tag("1", TagKind::Standalone, "o")];
889 assert_eq!(to_locos_text_for("docx", &dup).0, "\u{27e6}x1\u{27e7}\u{27e6}x2\u{27e7}");
890 let odd = vec![Inline::tag("x", TagKind::Standalone, "o"), Inline::tag("07", TagKind::Standalone, "o")];
891 assert_eq!(to_locos_text_for("docx", &odd).0, "\u{27e6}x1\u{27e7}\u{27e6}x2\u{27e7}");
892 }
893
894 #[test]
896 fn idml_and_icml_runs_are_r_pairs() {
897 let inl = vec![
898 Inline::tag("1", TagKind::Open, "<CharacterStyleRange>"),
899 Inline::text("bold "),
900 Inline::tag("2", TagKind::Open, "<HyperlinkTextSource>"),
901 Inline::text("link"),
902 Inline::tag("2", TagKind::Close, "</HyperlinkTextSource>"),
903 Inline::tag("3", TagKind::Standalone, "<Br/>"),
904 Inline::tag("1", TagKind::Close, "</CharacterStyleRange>"),
905 ];
906 let mut codes = BTreeMap::new();
907 codes.insert("1".to_string(), CodeData::paired("<CharacterStyleRange>", "</CharacterStyleRange>").with_label("run"));
908 codes.insert("2".to_string(), CodeData::paired("<HyperlinkTextSource>", "</HyperlinkTextSource>").with_label("link"));
909 codes.insert("3".to_string(), CodeData::standalone("<Br/>").with_label("br"));
910 let want = "\u{27e6}r1\u{27e7}bold \u{27e6}g2\u{27e7}link\u{27e6}/g2\u{27e7}\u{27e6}x3\u{27e7}\u{27e6}/r1\u{27e7}";
911 for f in ["idml", "icml"] {
912 let (t, map) = to_locos_text_coded(f, &inl, &codes);
913 assert_eq!(t, want, "{f}");
914 assert_eq!(map["1"].letter, 'r');
915 assert_eq!(from_locos_text(&t, &map), inl, "{f}");
916 let (back, problems) = parse_locos_text(&t.replace("r1", "g1"), &map);
918 assert!(problems.is_empty() && back == inl);
919 }
920 assert_eq!(to_locos_text_coded("odt", &inl, &codes), to_locos_text_for("odt", &inl));
922 assert_eq!(to_locos_text_coded("idml", &inl, &BTreeMap::new()).0.matches("\u{27e6}g").count(), 2);
923 }
924
925 fn sample() -> Vec<Inline> {
926 vec![
927 Inline::text("Hola "),
928 Inline::tag("1", TagKind::Open, "<b>"),
929 Inline::text("mundo"),
930 Inline::tag("1", TagKind::Close, "</b>"),
931 Inline::text(", "),
932 Inline::free_tag("2", "{name}"),
933 Inline::text(" "),
934 Inline::tag("3", TagKind::Standalone, "%s"),
935 Inline::text("."),
936 ]
937 }
938
939 #[test]
940 fn tokens_follow_the_table() {
941 let (t, map) = to_locos_text(&sample());
942 assert_eq!(t, "Hola \u{27E6}g1\u{27E7}mundo\u{27E6}/g1\u{27E7}, \u{27E6}p2\u{27E7} \u{27E6}x3\u{27E7}.");
943 assert_eq!(map.len(), 3);
944 assert_eq!(map["1"].close.as_deref(), Some("</b>"));
945 assert!(map["2"].free && map["2"].letter == 'p');
946 assert!(!map["3"].free && map["3"].letter == 'x');
947 }
948
949 #[test]
950 fn round_trips() {
951 let s = sample();
952 let (t, map) = to_locos_text(&s);
953 assert_eq!(from_locos_text(&t, &map), s);
954 let (t, map) = to_locos_text_as(&s, 'r');
955 assert!(t.contains("\u{27E6}r1\u{27E7}") && t.contains("\u{27E6}/r1\u{27E7}"));
956 assert_eq!(from_locos_text(&t, &map), s);
957 }
958
959 #[test]
960 fn token_look_alikes_in_the_text_are_text() {
961 let inl = vec![
963 Inline::text("Use \u{27E6}x2\u{27E7} and \u{27E6}g1\u{27E7} "),
964 Inline::tag("a", TagKind::Open, "<b>"),
965 Inline::text("here"),
966 Inline::tag("a", TagKind::Close, "</b>"),
967 Inline::tag("b", TagKind::Standalone, "<br/>"),
968 ];
969 for f in ["xliff", "html", "docx"] {
970 let (t, map) = to_locos_text_for(f, &inl);
971 assert!(!map.contains_key("1") && !map.contains_key("2"), "{f}: {map:?}");
972 assert_eq!(from_locos_text(&t, &map), inl, "{f}: {t}");
973 let moved = t.replace("here", "HERE");
975 let back = from_locos_text(&moved, &map);
976 assert!(matches!(&back[0], Inline::Text(x) if x.starts_with("Use \u{27E6}x2\u{27E7} and \u{27E6}g1\u{27E7}")), "{f}");
977 }
978 let inl = vec![
980 Inline::text("\u{27E6}x2\u{27E7} "),
981 Inline::tag("1", TagKind::Open, "<b>"),
982 Inline::text("one"),
983 Inline::tag("1", TagKind::Close, "</b>"),
984 Inline::tag("3", TagKind::Standalone, "<br/>"),
985 Inline::text("two"),
986 ];
987 for f in ["html", "docx"] {
988 let (t, map) = to_locos_text_for(f, &inl);
989 let p = locos_pair_letter(f);
990 let (n_pair, n_point) = (map.iter().find(|(_, c)| c.id == "1").unwrap().0, map.iter().find(|(_, c)| c.id == "3").unwrap().0);
991 assert!(!map.contains_key("2"), "{f}: {map:?}");
992 let swapped = format!("\u{27E6}x2\u{27E7} two\u{27E6}x{n_point}\u{27E7}\u{27E6}{p}{n_pair}\u{27E7}one\u{27E6}/{p}{n_pair}\u{27E7}");
993 let (back, problems) = parse_locos_text(&swapped, &map);
994 assert_eq!(problems.len(), 1, "{f}: only the look-alike is unknown: {problems:?} ({t})");
995 assert_eq!(
996 back,
997 vec![
998 Inline::text("\u{27E6}x2\u{27E7} two"),
999 Inline::tag("3", TagKind::Standalone, "<br/>"),
1000 Inline::tag("1", TagKind::Open, "<b>"),
1001 Inline::text("one"),
1002 Inline::tag("1", TagKind::Close, "</b>"),
1003 ],
1004 "{f}"
1005 );
1006 }
1007 let inl = vec![Inline::text("\u{27E6}1\u{27E7} "), Inline::tag("a", TagKind::Standalone, "<br/>")];
1009 let (t, map) = to_locos_text(&inl);
1010 assert_eq!(t, "\u{27E6}1\u{27E7} \u{27E6}x2\u{27E7}");
1011 assert_eq!(from_locos_text(&t, &map), inl);
1012 }
1013
1014 #[test]
1015 fn bad_pair_letter_falls_back() {
1016 let (t, _) = to_locos_text_as(&sample(), 'x');
1017 assert!(t.contains("\u{27E6}g1\u{27E7}"));
1018 let (t, _) = to_locos_text_as(&sample(), 'G');
1019 assert!(t.contains("\u{27E6}g1\u{27E7}"));
1020 }
1021
1022 #[test]
1023 fn reordered_free_tokens_come_back_by_number() {
1024 let (_, map) = to_locos_text(&[Inline::free_tag("a", "%1$s"), Inline::text(" y "), Inline::free_tag("b", "%2$s")]);
1025 let back = from_locos_text("\u{27E6}p2\u{27E7} \u{27E6}p1\u{27E7}", &map);
1026 assert_eq!(back[0], Inline::free_tag("b", "%2$s"));
1027 assert_eq!(back[2], Inline::free_tag("a", "%1$s"));
1028 }
1029
1030 #[test]
1031 fn unmatched_close_and_open_survive() {
1032 let s = vec![
1033 Inline::tag("9", TagKind::Close, "</i>"),
1034 Inline::text("x"),
1035 Inline::tag("8", TagKind::Open, "<u>"),
1036 Inline::text("y"),
1037 ];
1038 let (t, map) = to_locos_text(&s);
1039 assert_eq!(t, "\u{27E6}x1\u{27E7}x\u{27E6}x2\u{27E7}y");
1040 assert!(well_formed(&t));
1041 assert_eq!(map["1"].unpaired, Some(TagKind::Close));
1042 assert_eq!(from_locos_text(&t, &map), s);
1043 let back: LocosMap = serde_json::from_str(&serde_json::to_string(&map).unwrap()).unwrap();
1045 assert_eq!(from_locos_text(&t, &back), s);
1046 }
1047
1048 fn well_formed(t: &str) -> bool {
1050 let mut stack = Vec::new();
1051 for tok in t.split('\u{27E6}').skip(1) {
1052 let tok = tok.split('\u{27E7}').next().unwrap_or_default();
1053 if let Some(rest) = tok.strip_prefix('/') {
1054 let key = rest.trim_start_matches(|c: char| c.is_ascii_lowercase());
1055 if stack.pop() != Some(key.to_string()) {
1056 return false;
1057 }
1058 } else if !tok.starts_with(['x', 'p']) {
1059 stack.push(tok.trim_start_matches(|c: char| c.is_ascii_lowercase()).to_string());
1060 }
1061 }
1062 stack.is_empty()
1063 }
1064
1065 #[test]
1066 fn crossed_pairs_become_well_formed() {
1067 let s = vec![
1068 Inline::tag("a", TagKind::Open, "<b>"),
1069 Inline::text("1"),
1070 Inline::tag("b", TagKind::Open, "<i>"),
1071 Inline::text("2"),
1072 Inline::tag("a", TagKind::Close, "</b>"),
1073 Inline::text("3"),
1074 Inline::tag("b", TagKind::Close, "</i>"),
1075 ];
1076 let (t, map) = to_locos_text(&s);
1077 assert_eq!(t, "\u{27E6}g1\u{27E7}1\u{27E6}x2\u{27E7}2\u{27E6}/g1\u{27E7}3\u{27E6}x3\u{27E7}");
1078 assert!(well_formed(&t));
1079 assert_eq!(from_locos_text(&t, &map), s);
1080 }
1081
1082 #[test]
1083 fn html_keeps_its_own_tokens() {
1084 let s = vec![
1086 Inline::tag("1", TagKind::Open, "<a>"),
1087 Inline::text("Hi "),
1088 Inline::tag("2", TagKind::Open, "<b>"),
1089 Inline::text("1"),
1090 Inline::tag("3", TagKind::Open, "<i>"),
1091 Inline::text("2"),
1092 Inline::tag("2", TagKind::Close, "</b>"),
1093 Inline::text("3"),
1094 Inline::tag("3", TagKind::Close, "</i>"),
1095 Inline::tag("4", TagKind::Standalone, "<br>"),
1096 Inline::tag("9", TagKind::Close, "</u>"),
1097 ];
1098 let (t, map) = to_locos_text_for("html", &s);
1099 assert_eq!(
1100 t,
1101 "\u{27E6}g1\u{27E7}Hi \u{27E6}g2\u{27E7}1\u{27E6}g3\u{27E7}2\u{27E6}/g2\u{27E7}3\u{27E6}/g3\u{27E7}\u{27E6}x4\u{27E7}\u{27E6}x5\u{27E7}"
1102 );
1103 assert_eq!(map["1"].letter, 'g');
1104 assert_eq!(map["1"].close, None);
1105 assert_eq!(from_locos_text(&t, &map), s);
1106 assert_eq!(to_locos_text_for("md", &s), to_locos_text_as(&s, 'g'));
1108 assert_eq!(to_locos_text_for("docx", &s), to_locos_text_as(&s, 'r'));
1109 }
1110
1111 #[test]
1112 fn html_family_formats_keep_an_open_with_no_close_a_pair_token() {
1113 let s = vec![
1115 Inline::tag("1", TagKind::Open, "<a>"),
1116 Inline::tag("2", TagKind::Open, "<span>"),
1117 Inline::text(" "),
1118 Inline::tag("2", TagKind::Close, "</span>"),
1119 ];
1120 for f in ["html", "aspx", "erb", "shtml", "jsp", "phtml", "epub", "eml"] {
1121 let (t, map) = to_locos_text_for(f, &s);
1122 assert_eq!(t, "\u{27E6}g1\u{27E7}\u{27E6}g2\u{27E7} \u{27E6}/g2\u{27E7}", "{f}");
1123 assert_eq!(from_locos_text(&t, &map), s, "{f}");
1124 }
1125 assert!(to_locos_text_for("md", &s).0.starts_with("\u{27E6}x1\u{27E7}"));
1127 }
1128
1129 #[test]
1130 fn nested_and_repeated_ids() {
1131 let s = vec![
1132 Inline::tag("a", TagKind::Open, "<b>"),
1133 Inline::tag("b", TagKind::Open, "<i>"),
1134 Inline::text("t"),
1135 Inline::tag("b", TagKind::Close, "</i>"),
1136 Inline::tag("a", TagKind::Close, "</b>"),
1137 Inline::tag("a", TagKind::Open, "<b>"),
1138 Inline::text("u"),
1139 Inline::tag("a", TagKind::Close, "</b>"),
1140 ];
1141 let (t, map) = to_locos_text(&s);
1142 assert_eq!(map.len(), 3);
1143 assert!(well_formed(&t));
1144 assert_eq!(from_locos_text(&t, &map), s);
1145 }
1146
1147 #[test]
1148 fn malformed_tokens_stay_as_text_and_are_reported() {
1149 let (_, map) = to_locos_text(&sample());
1150 for bad in [
1151 "a \u{27E6} b",
1152 "a \u{27E7} b",
1153 "\u{27E6}g\u{27E7}",
1154 "\u{27E6}g1",
1155 "\u{27E6}/\u{27E6}g1\u{27E7}",
1156 "\u{27E6}G1\u{27E7}",
1157 "\u{27E6}x1{limit}\u{27E7}",
1158 "\u{27E6}g99\u{27E7}",
1159 "\u{27E6}/x3\u{27E7}",
1160 "\u{27E6}x1\u{27E7}",
1161 ] {
1162 let (inl, problems) = parse_locos_text(bad, &map);
1163 let rebuilt: String = inl
1164 .iter()
1165 .map(|i| match i {
1166 Inline::Text(t) => t.clone(),
1167 Inline::Tag { .. } => String::from("#"),
1168 })
1169 .collect();
1170 if bad == "\u{27E6}x1\u{27E7}" {
1171 assert!(problems.iter().any(|p| matches!(p, TokenProblem::KindMismatch { .. })), "{bad}");
1173 } else {
1174 assert!(!problems.is_empty(), "{bad:?} gave no problem");
1175 }
1176 assert!(rebuilt.contains('\u{27E6}') || rebuilt.contains('\u{27E7}') || bad.contains("g1\u{27E7}"), "{bad:?} lost text");
1177 }
1178 }
1179
1180 #[test]
1181 fn text_in_every_language_survives() {
1182 for t in [
1183 "Hello", "Hola", "Bonjour", "Ciao", "Hallo", "Hallo", "Ola", "\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}",
1184 "\u{4f60}\u{597d}", "\u{c548}\u{b155}", "\u{645}\u{631}\u{62d}\u{628}\u{627}",
1185 ] {
1186 let s = vec![Inline::tag("1", TagKind::Open, "<b>"), Inline::text(t), Inline::tag("1", TagKind::Close, "</b>"), Inline::free_tag("2", "{0}")];
1187 let (x, map) = to_locos_text(&s);
1188 assert_eq!(from_locos_text(&x, &map), s);
1189 }
1190 }
1191
1192 #[test]
1193 fn numbered_by_id_like_locos_pptx() {
1194 let s = vec![
1196 Inline::tag("1", TagKind::Open, "<a:r>"),
1197 Inline::text("a"),
1198 Inline::tag("1", TagKind::Close, "</a:r>"),
1199 Inline::tag("3", TagKind::Standalone, "<a:br/>"),
1200 Inline::tag("2", TagKind::Open, "<a:r>"),
1201 Inline::text("b"),
1202 Inline::tag("2", TagKind::Close, "</a:r>"),
1203 Inline::tag("4", TagKind::Standalone, "<a:fld/>"),
1204 ];
1205 let (t, map) = to_locos_text_numbered(&s, 'r');
1206 assert_eq!(t, "\u{27E6}r1\u{27E7}a\u{27E6}/r1\u{27E7}\u{27E6}x3\u{27E7}\u{27E6}r2\u{27E7}b\u{27E6}/r2\u{27E7}\u{27E6}x4\u{27E7}");
1207 assert!(well_formed(&t));
1208 assert_eq!(from_locos_text(&t, &map), s);
1209 for bad in [
1211 vec![Inline::tag("a", TagKind::Standalone, "x")],
1212 vec![Inline::tag("0", TagKind::Standalone, "x")],
1213 vec![Inline::tag("01", TagKind::Standalone, "x")],
1214 vec![Inline::tag("+2", TagKind::Standalone, "x")],
1215 vec![Inline::tag("2", TagKind::Standalone, "x"), Inline::tag("2", TagKind::Standalone, "y")],
1216 vec![Inline::tag("9", TagKind::Open, "x"), Inline::tag("9", TagKind::Open, "y")],
1217 vec![Inline::tag("99999999999999999999999", TagKind::Standalone, "x")],
1218 ] {
1219 assert_eq!(to_locos_text_numbered(&bad, 'r'), to_locos_text_as(&bad, 'r'), "{bad:?}");
1220 }
1221 assert_eq!(to_locos_text_numbered(&sample(), 'g'), to_locos_text(&sample()));
1222 assert_eq!(to_locos_text_numbered(&[], 'r'), (String::new(), LocosMap::new()));
1223 assert_eq!(to_locos_text_for("pptx", &s), (t, map));
1225 }
1226
1227 #[test]
1228 fn empty_and_tagless() {
1229 let (t, m) = to_locos_text(&[]);
1230 assert!(t.is_empty() && m.is_empty());
1231 assert!(from_locos_text("", &m).is_empty());
1232 assert_eq!(from_locos_text("plain", &m), vec![Inline::text("plain")]);
1233 }
1234
1235 #[test]
1236 fn named_placeholders() {
1237 for yes in ["%1$s", "%12$d", "%(name)s", "{name}", "{0}", "{{count}}", "${user}"] {
1238 assert!(is_named_placeholder(yes), "{yes}");
1239 }
1240 for no in ["%s", "%d", "%.2f", "{}", "{ x }", "<b>", "%%", "%5d", "{{}}", "${}", "%(x"] {
1241 assert!(!is_named_placeholder(no), "{no}");
1242 }
1243 }
1244
1245 #[test]
1248 fn wrong_kind_tokens_are_dropped_for_toml_and_js() {
1249 let src = vec![Inline::text("Reading time "), Inline::tag("1", TagKind::Standalone, "{{ .Count }}"), Inline::text(" min")];
1250 let (_, map) = to_locos_text(&src);
1251 let t = "Lesezeit \u{27E6}x9\u{27E7} \u{27E6}g1\u{27E7}Min\u{27E6}/g1\u{27E7} \u{27E6}x1\u{27E7}";
1252 for f in ["toml", "js", "rc"] {
1254 let (inl, problems) = parse_locos_text_for(f, t, &map);
1255 assert_eq!(
1256 inl,
1257 vec![Inline::text("Lesezeit \u{27E6}x9\u{27E7} Min "), Inline::tag("1", TagKind::Standalone, "{{ .Count }}")],
1258 "{f}"
1259 );
1260 assert_eq!(problems.iter().filter(|p| matches!(p, TokenProblem::KindMismatch { .. })).count(), 2, "{f}");
1261 assert!(problems.contains(&TokenProblem::Unknown { token: "\u{27E6}x9\u{27E7}".into() }), "{f}");
1262 }
1263 let (kept, _) = parse_locos_text_for("json", t, &map);
1264 assert_eq!(kept, parse_locos_text(t, &map).0);
1265 assert!(matches!(&kept[0], Inline::Text(x) if x.contains("\u{27E6}g1\u{27E7}Min")));
1266 }
1267
1268 #[test]
1271 fn dxf_does_not_read_p_as_a_point() {
1272 let src = vec![Inline::text("a"), Inline::tag("1", TagKind::Standalone, "%%d")];
1273 let (_, map) = to_locos_text(&src);
1274 let t = "a%\u{27E6}p1\u{27E7}%b\u{27E6}x1\u{27E7}";
1275 let (inl, problems) = parse_locos_text_for("dxf", t, &map);
1276 assert_eq!(inl, vec![Inline::text("a%\u{27E6}p1\u{27E7}%b"), Inline::tag("1", TagKind::Standalone, "%%d")]);
1277 assert_eq!(problems, vec![TokenProblem::KindMismatch { token: "\u{27E6}p1\u{27E7}".into() }]);
1278 let (_, problems) = parse_locos_text_for("dxf", "\u{27E6}p7\u{27E7}", &map);
1280 assert_eq!(problems, vec![TokenProblem::Unknown { token: "\u{27E6}p7\u{27E7}".into() }]);
1281 let (inl, problems) = parse_locos_text_for("txt", t, &map);
1282 assert!(problems.is_empty() && inl.iter().filter(|i| matches!(i, Inline::Tag { .. })).count() == 2);
1283 }
1284
1285 #[test]
1289 fn cat_formats_repair_tags_like_locos() {
1290 let open = Inline::tag("1", TagKind::Open, "<g id=\"1\">");
1291 let close = Inline::tag("1", TagKind::Close, "</g>");
1292 let x = Inline::tag("2", TagKind::Standalone, "<x id=\"2\"/>");
1293 let src = vec![Inline::text("Click "), open.clone(), Inline::text("here"), close.clone(), x.clone()];
1294 let (text, map) = to_locos_text(&src);
1295 assert_eq!(text, "Click \u{27E6}g1\u{27E7}here\u{27E6}/g1\u{27E7}\u{27E6}x2\u{27E7}");
1296 let cases: Vec<(&str, Vec<Inline>, Vec<&str>)> = vec![
1297 (
1299 "bitte \u{27E6}g1\u{27E7}Klick\u{27E6}/g1\u{27E7} hier \u{27E6}g1\u{27E7}doppelt\u{27E6}/g1\u{27E7} jetzt",
1300 vec![Inline::text("bitte "), open.clone(), Inline::text("Klick"), close.clone(), Inline::text(" hier doppelt jetzt")],
1301 vec!["repeated"],
1302 ),
1303 (
1305 "\u{27E6}g1\u{27E7}A \u{27E6}x2\u{27E7}B \u{27E6}g1\u{27E7}C",
1306 vec![open.clone(), Inline::text("A "), x.clone(), Inline::text("B C"), close.clone()],
1307 vec!["repeated", "unclosed"],
1308 ),
1309 ("\u{27E6}/g1\u{27E7}Hi \u{27E6}/x2\u{27E7}", vec![Inline::text("Hi ")], vec!["stray_close", "stray_close"]),
1310 ("Hi \u{27E6}x1\u{27E7} you", vec![Inline::text("Hi "), open.clone(), close.clone(), Inline::text(" you")], vec!["pair_as_point"]),
1311 ("\u{27E6}x2\u{27E7}a\u{27E6}x2\u{27E7}b\u{27E6}g2\u{27E7}", vec![x.clone(), Inline::text("ab")], vec!["repeated", "repeated"]),
1312 ("\u{27E6}g1\u{27E7}a\u{27E6}/x1\u{27E7}", vec![open.clone(), Inline::text("a"), close.clone()], vec![]),
1314 ("a \u{27E6}g9\u{27E7}", vec![Inline::text("a \u{27E6}g9\u{27E7}")], vec![]),
1316 ];
1317 for (t, want, kinds) in cases {
1318 for f in ["sdlxliff", "xliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx"] {
1319 let (inl, _, repairs) = repair_locos_text_for(f, t, &map);
1320 assert_eq!(repair_tags(&src, inl.clone(), true), want, "{f}: {t}");
1322 let got: Vec<&str> = repairs
1323 .iter()
1324 .map(|r| match r {
1325 TagRepair::Repeated { .. } => "repeated",
1326 TagRepair::StrayClose { .. } => "stray_close",
1327 TagRepair::Unclosed { .. } => "unclosed",
1328 TagRepair::PairAsPoint { .. } => "pair_as_point",
1329 })
1330 .collect();
1331 assert_eq!(got, kinds, "{f}: {t}");
1332 assert_eq!(repair_tags(&src, want.clone(), true), want, "{f}: {t}");
1334 assert_eq!(parse_locos_text_for(f, t, &map).0, inl, "{f}: {t}");
1335 }
1336 let (plain, _, none) = repair_locos_text_for("json", t, &map);
1337 assert!(none.is_empty());
1338 assert_eq!(plain, parse_locos_text(t, &map).0);
1339 }
1340 }
1341
1342 #[test]
1345 fn inline_targets_are_repaired_by_id() {
1346 let open = Inline::tag("1", TagKind::Open, "<b>");
1347 let close = Inline::tag("1", TagKind::Close, "</b>");
1348 let src = vec![open.clone(), Inline::text("a"), close.clone()];
1349 let t = vec![open.clone(), Inline::text("x"), close.clone(), open.clone(), Inline::text("y"), close.clone(), close.clone(), open.clone()];
1350 assert_eq!(repair_tags(&src, t, true), vec![open.clone(), Inline::text("x"), close.clone(), Inline::text("y")]);
1351 assert_eq!(repair_tags(&src, vec![open.clone(), Inline::text("z")], true), vec![open.clone(), Inline::text("z"), close.clone()]);
1352 let twice = vec![open.clone(), Inline::text("a"), close.clone(), open.clone(), Inline::text("b"), close.clone()];
1353 assert_eq!(repair_tags(&twice, twice.clone(), true), twice);
1354 let invented = vec![Inline::tag("9", TagKind::Standalone, "<hr/>")];
1355 assert_eq!(repair_tags(&src, invented.clone(), true), invented);
1356 }
1357}