rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
//! HTML 붙여넣기 + HTML 파싱 관련 native 메서드

use super::super::helpers::*;
use super::clipboard::text_to_split_logical_offset;

mod cell_flow;
mod inline_content;
use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;
use crate::model::paragraph::Paragraph;

/// parse_inline_content 가 서식으로 읽는 span·b·strong·i·em·u 태그면
/// (태그 이름, 닫는 태그인지)를 돌려준다.
fn inline_format_tag(tag_lower: &str) -> Option<(&str, bool)> {
    let tag = tag_lower.strip_prefix('<')?;
    let (closing, tag) = match tag.strip_prefix('/') {
        Some(rest) => (true, rest),
        None => (false, tag),
    };
    let name = tag.split(|c: char| !c.is_ascii_alphanumeric()).next()?;
    matches!(name, "span" | "b" | "strong" | "i" | "em" | "u").then_some((name, closing))
}

/// 인라인 구간 끝까지 닫히지 않은 서식 여는 태그들을 순서대로 이어 돌려준다.
fn open_format_tags(run: &str) -> String {
    let mut open: Vec<(String, &str)> = Vec::new();
    for (start, _) in run.match_indices('<') {
        let Some(end) = run[start..].find('>') else {
            break;
        };
        let tag = &run[start..=start + end];
        match inline_format_tag(&tag.to_lowercase()) {
            Some((name, true)) => {
                if let Some(i) = open.iter().rposition(|(open, _)| open == name) {
                    open.truncate(i);
                }
            }
            Some((name, false)) => open.push((name.to_string(), tag)),
            None => {}
        }
    }
    open.into_iter().map(|(_, tag)| tag).collect()
}

fn html_fragment(html: &str) -> &str {
    if let Some(start) = html.find("<!--StartFragment-->") {
        let after = &html[start + 20..];
        return after.split("<!--EndFragment-->").next().unwrap_or(after);
    }
    if let Some(start) = html.find("<body") {
        if let Some(gt) = html[start..].find('>') {
            let inner = &html[start + gt + 1..];
            return inner.split("</body>").next().unwrap_or(inner);
        }
    }
    html
}

/// 글로 바꾸어 버리는 파서 폴백과 누락된 개체를 순수 글로 오인하지 않는다.
fn is_text_only_html(html: &str) -> bool {
    if html.len() > DocumentCore::HTML_PASTE_MAX_BYTES
        || html
            .split("<!--")
            .skip(1)
            .any(|comment| comment.trim_start().starts_with("[data-hwpjson]"))
        || (html.contains("<!--sudal-clipboard:") && !html.contains("<!--sudal-text-fragment-->"))
    {
        return false;
    }
    let mut rest = html_fragment(html);
    let mut open = Vec::<String>::new();
    while let Some(start) = rest.find('<') {
        rest = &rest[start..];
        if let Some(comment) = rest.strip_prefix("<!--") {
            let Some((_, after)) = comment.split_once("-->") else {
                return false;
            };
            rest = after;
            continue;
        }
        let Some(end) = rest.find('>') else {
            return false;
        };
        let raw = &rest[1..end];
        if raw.starts_with(char::is_whitespace) || raw.contains('<') {
            return false;
        }
        let (closing, tag) = match raw.strip_prefix('/') {
            Some(tag) => (true, tag),
            None => (false, raw),
        };
        let name_end = tag
            .find(|c: char| c.is_whitespace() || c == '/')
            .unwrap_or(tag.len());
        let name = tag[..name_end].to_ascii_lowercase();
        if !matches!(
            name.as_str(),
            "p" | "div" | "span" | "b" | "strong" | "i" | "em" | "u" | "br"
        ) {
            return false;
        }
        // 인라인 서식이나 p 안의 블록은 파서가 글로 합쳐 문단 경계를 잃는다.
        if !closing
            && matches!(name.as_str(), "p" | "div")
            && open.iter().any(|parent| parent != "div")
        {
            return false;
        }
        let attrs = &tag[name_end..];
        let mut quote = None;
        for character in attrs.chars() {
            match quote {
                Some(current) if character == current => quote = None,
                None if matches!(character, '\'' | '"') => quote = Some(character),
                _ => {}
            }
        }
        if quote.is_some() {
            return false;
        }
        if closing {
            if !attrs.trim().is_empty() || open.pop().as_deref() != Some(name.as_str()) {
                return false;
            }
        } else if name != "br" {
            if attrs.trim_end().ends_with('/')
                || open.len() + 1 >= DocumentCore::HTML_PASTE_MAX_RECURSION_DEPTH as usize
            {
                return false;
            }
            open.push(name);
        }
        rest = &rest[end + 1..];
    }
    open.is_empty()
}

impl DocumentCore {
    /// HTML 을 파싱해 본문 캐럿 자리에 붙인다.
    ///
    /// `char_offset` 과 돌려주는 `charOffset` 은 캐럿의 논리 위치다 — 글자와 각주·미주·글자처럼
    /// 취급한 개체를 한 칸씩 센다(`getLogicalLength`·`navigateNextEditable` 과 같은 축).
    pub fn paste_html_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        html: &str,
    ) -> Result<String, HwpError> {
        self.paste_html_at_caret_native(section_idx, para_idx, char_offset, html, false)
    }

    /// 순수 한 문단 HTML을 일반 입력과 같은 누름틀·논리 캐럿 경계로 붙인다.
    /// 반환 charOffset은 paste_internal_text_logical_native와 같은 글자 자리다.
    pub fn paste_html_text_logical_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        logical_offset: usize,
        html: &str,
    ) -> Result<String, HwpError> {
        let para = self
            .document
            .sections
            .get(section_idx)
            .and_then(|section| section.paragraphs.get(para_idx))
            .ok_or_else(|| HwpError::RenderError("붙일 본문 위치를 확인해 주세요".into()))?;
        if logical_offset > logical_paragraph_length(para) {
            return Err(HwpError::RenderError(
                "붙일 캐럿 위치를 확인해 주세요".into(),
            ));
        }
        if !is_text_only_html(html) {
            return Ok("{\"ok\":false,\"error\":\"not a text HTML fragment\"}".into());
        }
        self.paste_html_at_caret_native(section_idx, para_idx, logical_offset, html, true)
    }

    fn paste_html_at_caret_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        html: &str,
        text_only: bool,
    ) -> Result<String, HwpError> {
        if section_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!(
                "구역 {} 범위 초과",
                section_idx
            )));
        }
        if para_idx >= self.document.sections[section_idx].paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "문단 {} 범위 초과",
                para_idx
            )));
        }

        // HTML 파싱 → 문단 목록 생성. 폭을 적지 않은 표는 이 구역 본문 글이 접히는 폭에 맞춘다.
        let body_width =
            crate::renderer::px_to_hwpunit(self.body_wrap_width(section_idx), self.dpi).max(0);
        let before = text_only.then(|| {
            (
                self.document.doc_info.clone(),
                self.document.bin_data_content.len(),
            )
        });
        let parsed_paras = self.parse_html_to_paragraphs(html, body_width as u32);
        if let Some((doc_info, bin_count)) = before {
            if !super::clipboard::is_single_text_fragment(&parsed_paras) {
                self.document.doc_info = doc_info;
                self.document.bin_data_content.truncate(bin_count);
                self.rebuild_resolved_styles();
                return Ok("{\"ok\":false,\"error\":\"not a single text fragment\"}".into());
            }
        }
        if parsed_paras.is_empty() {
            return Ok("{\"ok\":false,\"error\":\"empty html\"}".to_string());
        }

        self.document.sections[section_idx].raw_stream = None;

        let clip_count = parsed_paras.len();

        if clip_count == 1 && parsed_paras[0].controls.is_empty() {
            // 단일 문단 텍스트 삽입 — 논리 위치를 글자 위치와 그 자리 개체의 앞뒤로 바꿔 넣는다.
            // 아래 다중 문단 경로의 split_at 도 논리 위치를 받는다.
            let clip_text = parsed_paras[0].text.clone();
            let clip_char_shapes = parsed_paras[0].char_shapes.clone();
            let clip_char_offsets = parsed_paras[0].char_offsets.clone();
            let new_chars = clip_text.chars().count();

            let para = &mut self.document.sections[section_idx].paragraphs[para_idx];
            let (text_offset, after_control) = logical_to_text_offset(para, char_offset);
            let text_offset = if text_only {
                super::text_editing::insert_body_text_with_field_affinity(
                    para,
                    self.active_field.as_ref(),
                    section_idx,
                    para_idx,
                    text_offset,
                    after_control,
                    &parsed_paras[0],
                );
                text_offset
            } else {
                para.insert_text_at_caret(text_offset, &clip_text, after_control)
            };

            self.apply_clipboard_char_shapes(
                section_idx,
                para_idx,
                text_offset,
                &clip_char_shapes,
                &clip_char_offsets,
                new_chars,
            );

            // [Task #2299] 리셋 판별용 — reflow 이전 저장 흐름 end 캡처.
            let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
                &self.document.sections[section_idx].paragraphs[para_idx],
            );
            self.reflow_paragraph(section_idx, para_idx);
            // [Task #2299] 삽입/변경 문단들의 vpos 를 흐름에 연결한다 — placeholder 를
            // 방치하면 이후 편집의 vpos 재계산이 저장 단/쪽 리셋으로 오인해 고착시킨다.
            let doc_hwp3_layout = self.document.layout_profile().hwp3_layout();
            crate::renderer::composer::recalculate_section_vpos(
                &mut self.document.sections[section_idx].paragraphs,
                para_idx,
                None,
                stored_end_for_reset,
                &self.styles,
                self.dpi,
                doc_hwp3_layout,
            );
            self.recompose_paragraph(section_idx, para_idx);
            self.paginate_if_needed();

            let new_offset = if text_only {
                text_offset + new_chars
            } else {
                text_to_logical_offset(
                    &self.document.sections[section_idx].paragraphs[para_idx],
                    text_offset + new_chars,
                )
            };
            self.event_log.push(DocumentEvent::HtmlImported {
                section: section_idx,
                para: para_idx,
            });
            return Ok(format!(
                "{{\"ok\":true,\"paraIdx\":{},\"charOffset\":{}}}",
                para_idx, new_offset
            ));
        }

        // 글 없이 개체만 든 문단(표·단독 그림)이 있는지 확인한다.
        // 글 사이에 든 그림은 아래 다중 문단 경로가 글과 함께 캐럿 문단에 병합한다.
        let has_controls = parsed_paras
            .iter()
            .any(|p| p.text.is_empty() && !p.controls.is_empty());

        if has_controls {
            // 컨트롤 포함 문단은 merge 불가 → 직접 삽입
            let right_half =
                self.document.sections[section_idx].paragraphs[para_idx].split_at(char_offset);

            // 현재 문단 (왼쪽 반)이 비어있으면 첫 번째 파싱 문단으로 대체
            let left_empty = self.document.sections[section_idx].paragraphs[para_idx]
                .text
                .is_empty();

            let insert_idx = if left_empty {
                let host = &mut self.document.sections[section_idx].paragraphs[para_idx];
                if host.controls.is_empty() {
                    // 빈 왼쪽 문단을 첫 번째 파싱 문단으로 대체
                    *host = parsed_paras[0].clone();
                } else {
                    // 구역 첫 문단처럼 구역·단 정의가 든 빈 문단을 갈아 끼우면 그 정의가 사라진다.
                    // 첫 파싱 문단을 병합하고 문단 모양만 그 문단을 따른다.
                    host.merge_from(&parsed_paras[0]);
                    host.para_shape_id = parsed_paras[0].para_shape_id;
                }
                let idx = para_idx + 1;
                for i in 1..clip_count {
                    self.document.sections[section_idx]
                        .paragraphs
                        .insert(idx + i - 1, parsed_paras[i].clone());
                }
                para_idx + clip_count
            } else {
                // 왼쪽 문단에 텍스트 → 파싱 문단들을 그 뒤에 삽입
                let idx = para_idx + 1;
                for i in 0..clip_count {
                    self.document.sections[section_idx]
                        .paragraphs
                        .insert(idx + i, parsed_paras[i].clone());
                }
                para_idx + 1 + clip_count
            };

            // 오른쪽 반에 글이나 개체가 있으면 새 문단으로 추가한다.
            // 글 없이 캐럿 뒤 그림·표만 든 오른쪽 반도 버리면 그 개체가 지워진다.
            let last_para_idx;
            let merge_point;
            if !right_half.text.is_empty() || !right_half.controls.is_empty() {
                self.document.sections[section_idx]
                    .paragraphs
                    .insert(insert_idx, right_half);
                last_para_idx = insert_idx;
                merge_point = 0;
            } else {
                last_para_idx = insert_idx - 1;
                // 마지막 문단이 컨트롤 문단이면 그 뒤 위치
                let last = &self.document.sections[section_idx].paragraphs[last_para_idx];
                merge_point = last.text.chars().count();
            }

            for i in para_idx..=last_para_idx {
                self.reflow_paragraph(section_idx, i);
            }
            // [Task #2299] 삽입 문단들의 vpos 를 흐름에 연결한다 — 클론/placeholder
            // 좌표를 방치하면 이후 편집의 vpos 재계산이 저장 단/쪽 리셋으로 오인해
            // 고착시킨다. left_empty 면 host 자체가 클론이라 신규 구간에 포함한다.
            let fresh_start = if left_empty { para_idx } else { para_idx + 1 };
            let doc_hwp3_layout = self.document.layout_profile().hwp3_layout();
            crate::renderer::composer::recalculate_section_vpos(
                &mut self.document.sections[section_idx].paragraphs,
                para_idx,
                Some(fresh_start..last_para_idx + 1),
                None,
                &self.styles,
                self.dpi,
                doc_hwp3_layout,
            );

            // 선택적 재구성: 원본 문단 재구성 + 삽입 문단 composed 추가
            self.recompose_paragraph(section_idx, para_idx);
            // 역순(.rev()) 삽입은 composed 길이가 paragraphs 보다 짧은 시점에
            // index > len 으로 panic(문단+표 혼합 붙여넣기) 하고, panic 이 안 나도 기존/신규 항목이
            // 교차돼 composed[i] != paragraphs[i] 가 된다. 텍스트 분기(아래)와 같이 정방향으로 append.
            for i in para_idx + 1..=last_para_idx {
                self.insert_composed_paragraph(section_idx, i);
            }
            self.paginate_if_needed();

            self.event_log.push(DocumentEvent::HtmlImported {
                section: section_idx,
                para: para_idx,
            });
            return Ok(format!(
                "{{\"ok\":true,\"paraIdx\":{},\"charOffset\":{}}}",
                last_para_idx, merge_point
            ));
        }

        // 다중 문단 삽입 (컨트롤 없는 텍스트만)
        let right_half =
            self.document.sections[section_idx].paragraphs[para_idx].split_at(char_offset);

        self.document.sections[section_idx].paragraphs[para_idx].merge_from(&parsed_paras[0]);

        let mut insert_idx = para_idx + 1;
        for i in 1..clip_count {
            self.document.sections[section_idx]
                .paragraphs
                .insert(insert_idx, parsed_paras[i].clone());
            insert_idx += 1;
        }

        let last_para_idx = insert_idx - 1;
        let merge_point =
            self.document.sections[section_idx].paragraphs[last_para_idx].merge_from(&right_half);

        for i in para_idx..=last_para_idx {
            self.reflow_paragraph(section_idx, i);
        }
        // [Task #2299] 삽입/변경 문단들의 vpos 를 흐름에 연결한다 — placeholder 를
        // 방치하면 이후 편집의 vpos 재계산이 저장 단/쪽 리셋으로 오인해 고착시킨다.
        let doc_hwp3_layout = self.document.layout_profile().hwp3_layout();
        crate::renderer::composer::recalculate_section_vpos(
            &mut self.document.sections[section_idx].paragraphs,
            para_idx,
            Some(para_idx + 1..last_para_idx + 1),
            None,
            &self.styles,
            self.dpi,
            doc_hwp3_layout,
        );

        // 선택적 재구성: 원본 문단 재구성 + 삽입 문단 composed 추가
        self.recompose_paragraph(section_idx, para_idx);
        for i in para_idx + 1..=last_para_idx {
            self.insert_composed_paragraph(section_idx, i);
        }
        self.paginate_if_needed();

        self.event_log.push(DocumentEvent::HtmlImported {
            section: section_idx,
            para: para_idx,
        });
        Ok(format!(
            "{{\"ok\":true,\"paraIdx\":{},\"charOffset\":{}}}",
            last_para_idx, merge_point
        ))
    }

    fn normalize_html_paragraphs_for_cell_paste(parsed_paras: Vec<Paragraph>) -> Vec<Paragraph> {
        // 셀 내부에는 Table Control 중첩 불가 → 컨트롤 포함 문단은 텍스트만 추출
        parsed_paras
            .into_iter()
            .map(|mut p| {
                if !p.controls.is_empty() {
                    let keep_text = !(p.text.is_empty() || p.text == "\u{0002}");
                    let text = if !keep_text {
                        match p.controls.first() {
                            Some(Control::Table(tbl)) => tbl
                                .cells
                                .iter()
                                .map(|c| {
                                    c.paragraphs
                                        .iter()
                                        .map(|cp| cp.text.clone())
                                        .collect::<Vec<_>>()
                                        .join(" ")
                                })
                                .collect::<Vec<_>>()
                                .join("\t"),
                            _ => String::new(),
                        }
                    } else {
                        p.text.clone()
                    };
                    p.controls.clear();
                    p.text = text;
                    // [#3494] char_count 는 문단 종결자를 포함한다 (model/paragraph.rs:1042).
                    p.char_count = p.text.encode_utf16().count() as u32 + 1;
                    let gapped_offsets = std::mem::replace(
                        &mut p.char_offsets,
                        p.text
                            .chars()
                            .scan(0u32, |acc, c| {
                                let off = *acc;
                                *acc += c.len_utf16() as u32;
                                Some(off)
                            })
                            .collect(),
                    );
                    if keep_text {
                        // 글 사이 그림을 빼면 그 자리(8칸 갭)도 사라진다.
                        // 글자 모양 시작을 같은 글자의 새 위치로 옮긴다.
                        for cs in &mut p.char_shapes {
                            let idx = gapped_offsets.partition_point(|&off| off < cs.start_pos);
                            cs.start_pos =
                                p.char_offsets.get(idx).copied().unwrap_or(p.char_count - 1);
                        }
                    }
                }
                p
            })
            .collect()
    }

    /// 셀에 붙일 문단. 셀에는 개체를 넣지 않으므로 파싱하며 등록한 그림 데이터도 되돌린다.
    fn parse_html_to_cell_paragraphs(&mut self, html: &str) -> Vec<Paragraph> {
        let bin_content_len = self.document.bin_data_content.len();
        let bin_list_len = self.document.doc_info.bin_data_list.len();
        // 셀에는 표를 글로 펼쳐 넣으므로 표 폭은 쓰이지 않는다.
        let parsed_paras = self.parse_html_to_paragraphs(html, 0);
        self.document.bin_data_content.truncate(bin_content_len);
        self.document.doc_info.bin_data_list.truncate(bin_list_len);
        Self::normalize_html_paragraphs_for_cell_paste(parsed_paras)
    }

    fn paste_html_paragraphs_into_cell_paragraphs(
        cell_paras: &mut Vec<Paragraph>,
        cell_para_idx: usize,
        char_offset: usize,
        parsed_paras: &[Paragraph],
    ) -> Result<(usize, usize), HwpError> {
        if cell_para_idx >= cell_paras.len() {
            return Err(HwpError::RenderError(format!(
                "셀 문단 {} 범위 초과",
                cell_para_idx
            )));
        }

        let clip_count = parsed_paras.len();
        if clip_count == 1 && parsed_paras[0].controls.is_empty() {
            let clip_text = parsed_paras[0].text.clone();
            let new_chars = clip_text.chars().count();

            cell_paras[cell_para_idx].insert_text_from_paragraph(char_offset, &parsed_paras[0]);

            let clip_char_shapes = parsed_paras[0].char_shapes.clone();
            let clip_char_offsets = parsed_paras[0].char_offsets.clone();
            Self::apply_clipboard_char_shapes_to_para(
                &mut cell_paras[cell_para_idx],
                char_offset,
                &clip_char_shapes,
                &clip_char_offsets,
                new_chars,
            );

            return Ok((cell_para_idx, char_offset + new_chars));
        }

        // 셀 캐럿은 글자 위치다. split_at 이 한 칸으로 세는 컨트롤과 같은 기준으로 바꿔 넘긴다.
        let split_offset =
            text_to_split_logical_offset(&cell_paras[cell_para_idx], char_offset, false);
        let right_half = cell_paras[cell_para_idx].split_at(split_offset);
        cell_paras[cell_para_idx].merge_from(&parsed_paras[0]);

        let mut insert_idx = cell_para_idx + 1;
        for parsed_para in parsed_paras.iter().skip(1) {
            cell_paras.insert(insert_idx, parsed_para.clone());
            insert_idx += 1;
        }

        let last_para_idx = insert_idx - 1;
        let merge_point = cell_paras[last_para_idx].merge_from(&right_half);
        Ok((last_para_idx, merge_point))
    }

    /// HTML 문자열을 파싱하여 셀 내부 캐럿 위치에 삽입한다. 셀 캐럿 `char_offset` 은 글자 위치다.
    pub fn paste_html_in_cell_native(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
        html: &str,
    ) -> Result<String, HwpError> {
        let parsed_paras = self.parse_html_to_cell_paragraphs(html);
        if parsed_paras.is_empty() {
            return Ok("{\"ok\":false,\"error\":\"empty html\"}".to_string());
        }

        let (last_para_idx, merge_point) = {
            let section =
                self.document.sections.get_mut(section_idx).ok_or_else(|| {
                    HwpError::RenderError(format!("구역 {} 범위 초과", section_idx))
                })?;
            section.raw_stream = None;
            let para = section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
                HwpError::RenderError(format!("문단 {} 범위 초과", parent_para_idx))
            })?;
            let control = para.controls.get_mut(control_idx).ok_or_else(|| {
                HwpError::RenderError(format!("컨트롤 {} 범위 초과", control_idx))
            })?;
            let table = match control {
                Control::Table(t) => t,
                _ => return Err(HwpError::RenderError("표가 아님".to_string())),
            };
            let cell_paras = &mut table
                .cells
                .get_mut(cell_idx)
                .ok_or_else(|| HwpError::RenderError(format!("셀 {} 범위 초과", cell_idx)))?
                .paragraphs;
            Self::paste_html_paragraphs_into_cell_paragraphs(
                cell_paras,
                cell_para_idx,
                char_offset,
                &parsed_paras,
            )?
        };

        for i in cell_para_idx..=last_para_idx {
            self.reflow_cell_paragraph(section_idx, parent_para_idx, control_idx, cell_idx, i);
        }
        self.recalculate_cell_paragraph_vpos_native(
            section_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            None,
        );
        self.reflow_html_cell_host(section_idx, parent_para_idx, control_idx);
        self.mark_cell_control_dirty(section_idx, parent_para_idx, control_idx);
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        self.event_log.push(DocumentEvent::HtmlImported {
            section: section_idx,
            para: parent_para_idx,
        });
        Ok(format!(
            "{{\"ok\":true,\"cellParaIdx\":{},\"charOffset\":{}}}",
            last_para_idx, merge_point
        ))
    }

    /// HTML 문자열을 파싱하여 cellPath가 가리키는 중첩 표 셀에 삽입한다.
    pub fn paste_html_in_cell_by_path_native(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        char_offset: usize,
        html: &str,
    ) -> Result<String, HwpError> {
        if path.is_empty() {
            return Err(HwpError::RenderError("경로가 비어있습니다".to_string()));
        }

        let parsed_paras = self.parse_html_to_cell_paragraphs(html);
        if parsed_paras.is_empty() {
            return Ok("{\"ok\":false,\"error\":\"empty html\"}".to_string());
        }

        let cell_para_idx = path[path.len() - 1].2;
        let (last_para_idx, merge_point) = {
            let cell_paras =
                self.get_cell_paragraphs_mut_by_path(section_idx, parent_para_idx, path)?;
            Self::paste_html_paragraphs_into_cell_paragraphs(
                cell_paras,
                cell_para_idx,
                char_offset,
                &parsed_paras,
            )?
        };

        let outer_ctrl = path[0].0;
        for i in cell_para_idx..=last_para_idx {
            self.reflow_cell_paragraph_by_path(section_idx, parent_para_idx, path, i);
        }
        self.recalculate_cell_paragraph_vpos_by_path(
            section_idx,
            parent_para_idx,
            path,
            cell_para_idx,
            None,
        );
        self.reflow_html_cell_host(section_idx, parent_para_idx, outer_ctrl);
        self.mark_cell_control_dirty(section_idx, parent_para_idx, outer_ctrl);
        self.document.sections[section_idx].raw_stream = None;
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();

        self.event_log.push(DocumentEvent::HtmlImported {
            section: section_idx,
            para: parent_para_idx,
        });
        Ok(format!(
            "{{\"ok\":true,\"cellParaIdx\":{},\"charOffset\":{}}}",
            last_para_idx, merge_point
        ))
    }

    // === HTML 파서 ===

    /// HTML 문자열을 파싱하여 Paragraph 목록을 생성한다.
    /// `<div>`/`<p><table>` 재귀 하강 깊이 상한. Gmail 등 웹메일 클립보드는 서명·본문을
    /// 감싸는 wrapper `<div>`가 수십 겹인 경우가 흔하다(예: 실사용 리포트 — 서명 블록 하나에
    /// `</div>` 8개 이상 연속). 이 깊이만큼 매번 `find_closing_tag_chars`로 전체 구간을
    /// 다시 훑고 재귀하므로, 깊이가 무제한이면 붙여넣기 한 번이 브라우저를 "응답 없음"으로
    /// 멈춰 세울 만큼 느려진다(실사용 확인). 이 상한을 넘으면 태그 트리 파싱을 포기하고
    /// 태그만 제거한 평문 문단으로 폴백한다 — 서식은 잃어도 붙여넣기 자체는 항상 끝난다.
    const HTML_PASTE_MAX_RECURSION_DEPTH: u32 = 16;

    /// 파싱을 시도할 최대 HTML 바이트 크기. 이보다 크면 태그 트리 파싱 없이 평문으로
    /// 폴백한다 — 크기 자체가 계산량의 또 다른 축이라 깊이 상한과 별개로 방어한다.
    /// 400,000 은 실사용 한글 문서에 너무 빡빡하다 — 실측한 6쪽짜리 문서 하나가
    /// 정리 후 399,057바이트로 상한 바로 아래였고, 그림을 넣거나 문단이 조금만 늘면 넘겨
    /// 표·문단·그림이 통째로 평문이 됐다(실사용 신고). 실측 파싱 시간은 이 크기에서 1초 남짓이라
    /// 2MB(= 한글 본문 약 70만 자)로 올린다. data: URI 페이로드는 아래에서 따로 제외한다.
    const HTML_PASTE_MAX_BYTES: usize = 2_000_000;

    /// `container_width` 는 글이 놓일 폭(HWPUNIT)이다 — 본문 글이 접히는 폭이나 바깥 셀 안쪽 폭.
    /// 폭을 적지 않은 표는 이 폭에 맞춘다.
    pub(crate) fn parse_html_to_paragraphs(
        &mut self,
        html: &str,
        container_width: u32,
    ) -> Vec<Paragraph> {
        self.parse_html_to_paragraphs_at_depth(html, 0, container_width)
    }

    /// 크기 상한은 **태그 트리 복잡도**를 막으려는 것이므로 `data:` URI 로 실린
    /// 그림 바이트는 빼고 잰다. 안 그러면 그림이 있는 문서는 상한을 넘겨 평문으로 폴백해
    /// 표·문단·그림이 통째로 사라진다(한글 붙여넣기 실사용 신고 2026-09-03, 602KB 중 242KB 가 그림).
    fn html_markup_len(html: &str) -> usize {
        let mut payload = 0usize;
        let mut rest = html;
        while let Some(idx) = rest.find("data:") {
            let after = &rest[idx..];
            let end = after.find(['"', '\'', ' ', '>']).unwrap_or(after.len());
            payload += end;
            rest = &after[end..];
            if rest.is_empty() {
                break;
            }
        }
        html.len().saturating_sub(payload)
    }

    pub(in crate::document_core) fn parse_html_to_paragraphs_at_depth(
        &mut self,
        html: &str,
        depth: u32,
        container_width: u32,
    ) -> Vec<Paragraph> {
        if depth >= Self::HTML_PASTE_MAX_RECURSION_DEPTH
            || Self::html_markup_len(html) > Self::HTML_PASTE_MAX_BYTES
        {
            let mut fallback_paragraphs = Vec::new();
            self.flush_text_to_paragraphs(&mut fallback_paragraphs, &html_strip_tags(html));
            return fallback_paragraphs;
        }

        let mut paragraphs: Vec<Paragraph> = Vec::new();

        // <!--StartFragment-->...<!--EndFragment--> 영역 추출 (없으면 전체 사용)
        let content = if let Some(start) = html.find("<!--StartFragment-->") {
            let after = &html[start + 20..];
            if let Some(end) = after.find("<!--EndFragment-->") {
                &after[..end]
            } else {
                after
            }
        } else {
            // <body>...</body> 영역 추출 시도
            if let Some(start) = html.find("<body") {
                let after_tag = &html[start..];
                if let Some(gt) = after_tag.find('>') {
                    let inner = &after_tag[gt + 1..];
                    if let Some(end) = inner.find("</body>") {
                        &inner[..end]
                    } else {
                        inner
                    }
                } else {
                    html
                }
            } else {
                html
            }
        };

        // 최상위 태그 파싱
        let mut pos = 0;
        let chars: Vec<char> = content.chars().collect();
        let len = chars.len();
        // 블록 밖 인라인 구간: 글과 <span>·<b> 등 서식 태그 원문
        let mut pending_text = String::new();

        while pos < len {
            if chars[pos] == '<' {
                // 태그 시작
                let tag_start = pos;
                let tag_end = find_char(&chars, pos, '>');
                if tag_end >= len {
                    break;
                }

                let tag_str: String = chars[tag_start..=tag_end].iter().collect();
                let tag_lower = tag_str.to_lowercase();

                if tag_lower.starts_with("<table") {
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);

                    // 표 전체 추출
                    let table_end = find_closing_tag_chars(&chars, pos, "table");
                    let table_html: String = chars[tag_start..table_end.min(len)].iter().collect();
                    self.parse_table_html(&mut paragraphs, &table_html, container_width, depth);
                    pos = table_end;
                    continue;
                } else if tag_lower.starts_with("<img") {
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);

                    self.parse_img_html(&mut paragraphs, &tag_str);
                    pos = tag_end + 1;
                    continue;
                } else if tag_lower.starts_with("<p") {
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);

                    // <p> 블록 추출
                    let p_content_start = tag_end + 1;
                    let p_end = find_closing_tag_chars(&chars, pos, "p");
                    let p_inner: String = chars[p_content_start..p_end.min(len)].iter().collect();
                    // </p> 태그 제거
                    let p_inner = if let Some(idx) = p_inner.rfind("</p>") {
                        &p_inner[..idx]
                    } else {
                        &p_inner
                    };

                    // <p> 내부에 <table>이 있으면 재귀적으로 처리
                    if p_inner.to_lowercase().contains("<table") {
                        let sub_paras = self.parse_html_to_paragraphs_at_depth(
                            p_inner,
                            depth + 1,
                            container_width,
                        );
                        paragraphs.extend(sub_paras);
                        pos = p_end;
                        continue;
                    }

                    let para_style = parse_inline_style(&tag_str);
                    let para_shape_id = self.css_to_para_shape_id(&para_style);

                    let mut para = Paragraph::default();
                    para.para_shape_id = para_shape_id;
                    self.parse_inline_content(&mut para, p_inner, &para_style);
                    paragraphs.push(para);

                    pos = p_end;
                    continue;
                } else if tag_lower.starts_with("<div") {
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);
                    // div 내부의 콘텐츠를 재귀적으로 처리
                    let div_content_start = tag_end + 1;
                    let div_end = find_closing_tag_chars(&chars, pos, "div");
                    let div_inner: String =
                        chars[div_content_start..div_end.min(len)].iter().collect();
                    let div_inner = if let Some(idx) = div_inner.rfind("</div>") {
                        &div_inner[..idx]
                    } else {
                        &div_inner
                    };

                    let sub_paras = self.parse_html_to_paragraphs_at_depth(
                        div_inner,
                        depth + 1,
                        container_width,
                    );
                    paragraphs.extend(sub_paras);
                    pos = div_end;
                    continue;
                } else if tag_lower.starts_with("<ul") || tag_lower.starts_with("<ol") {
                    // [Gmail 등 웹메일 서명 붙여넣기가 raw 태그로 나오던 결함] 목록 태그
                    // 자체는 컨테이너일 뿐이라 <div>처럼 내부를 재귀 처리한다 — <li> 각각이
                    // 실제 항목 문단이 된다.
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);
                    let list_tag_name = if tag_lower.starts_with("<ul") {
                        "ul"
                    } else {
                        "ol"
                    };
                    let list_content_start = tag_end + 1;
                    let list_end = find_closing_tag_chars(&chars, pos, list_tag_name);
                    let list_inner: String = chars[list_content_start..list_end.min(len)]
                        .iter()
                        .collect();
                    let close_marker = format!("</{list_tag_name}>");
                    let list_inner = if let Some(idx) = list_inner.rfind(&close_marker) {
                        &list_inner[..idx]
                    } else {
                        &list_inner
                    };
                    let sub_paras = self.parse_html_to_paragraphs(list_inner, container_width);
                    paragraphs.extend(sub_paras);
                    pos = list_end;
                    continue;
                } else if tag_lower.starts_with("<li") {
                    // <li> 내부 전체(중첩 span/strong 등 포함)를 한 문단으로 묶어
                    // parse_inline_content 로 서식까지 보존해 파싱하고, 글머리 기호를
                    // 앞에 붙인다. 표 없는 최상위 <p> 처리와 동일한 패턴.
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);
                    let li_content_start = tag_end + 1;
                    let li_end = find_closing_tag_chars(&chars, pos, "li");
                    let li_inner: String =
                        chars[li_content_start..li_end.min(len)].iter().collect();
                    let li_inner = if let Some(idx) = li_inner.rfind("</li>") {
                        &li_inner[..idx]
                    } else {
                        &li_inner
                    };
                    let mut para = Paragraph::default();
                    self.parse_inline_content(&mut para, li_inner, &parse_inline_style(&tag_str));
                    // 그림만 든 항목도 버리지 않는다 — 버리면 등록한 그림 데이터만 문서에 남는다.
                    if !para.text.trim().is_empty() || !para.controls.is_empty() {
                        para.text = format!("• {}", para.text);
                        // 글머리 기호("• ")만큼 글자 위치와 스타일 구간을 오른쪽으로 민다.
                        // 다시 세지 않고 밀어야 글 사이 그림의 자리(8칸 갭)가 남는다.
                        // start_pos 는 UTF-16 코드유닛 단위(char_offsets 와 동일 축).
                        let bullet_len = "• ".encode_utf16().count() as u32;
                        para.char_offsets = (0..bullet_len)
                            .chain(para.char_offsets.iter().map(|off| off + bullet_len))
                            .collect();
                        para.char_count += bullet_len;
                        for cs in &mut para.char_shapes {
                            cs.start_pos += bullet_len;
                        }
                        paragraphs.push(para);
                    }
                    pos = li_end;
                    continue;
                } else if tag_lower.starts_with("<br") {
                    // <br> → 문단 구분. 서식 태그만 든 구간(<b><br></b>)도 빈 줄이다.
                    let blank = pending_text.is_empty() || pending_text.contains('<');
                    let reopen = open_format_tags(&pending_text);
                    let before = paragraphs.len();
                    self.flush_inline_run(&mut paragraphs, &mut pending_text);
                    if blank && paragraphs.len() == before {
                        paragraphs.push(Paragraph::default());
                    }
                    // <b>가<br>나</b> 의 "나" 도 굵게 남도록 열린 서식을 다음 줄에 다시 연다.
                    pending_text = reopen;
                    pos = tag_end + 1;
                    continue;
                } else if tag_lower.starts_with("<span") {
                    // Chrome 은 문단 중간부터 고른 글을 <p> 없이 <span style>·<b style> 로 쓴다.
                    // 서식 태그를 앞뒤 글과 한 인라인 구간에 모아 한 문단으로 읽는다.
                    // span 은 안쪽 그림까지 통째로 넣는다.
                    let span_end = find_closing_tag_chars(&chars, pos, "span");
                    pending_text.extend(&chars[pos..span_end.min(len)]);
                    pos = span_end;
                    continue;
                } else if inline_format_tag(&tag_lower).is_some() {
                    pending_text.push_str(&tag_str);
                    pos = tag_end + 1;
                    continue;
                } else if tag_lower.starts_with("</") {
                    // 닫는 태그 무시
                    pos = tag_end + 1;
                    continue;
                } else {
                    // 기타 태그 무시
                    pos = tag_end + 1;
                    continue;
                }
            } else {
                // 일반 텍스트
                pending_text.push(chars[pos]);
                pos += 1;
            }
        }

        // 남은 텍스트 처리
        self.flush_inline_run(&mut paragraphs, &mut pending_text);

        // 빈 결과 시 최소 처리 — flush_text_to_paragraphs 재사용으로 줄바꿈 분리와
        // 긴 줄 강제 절단(FLUSH_LINE_CHAR_CAP)을 여기도 동일하게 적용한다.
        // flush_text_to_paragraphs 가 자체적으로 decode_html_entities 를 수행하므로,
        // 여기서는 태그만 벗긴 원문(html_strip_tags)을 넘겨 엔티티 이중 디코딩을 피한다.
        if paragraphs.is_empty() {
            let stripped = html_strip_tags(html);
            if !stripped.trim().is_empty() {
                self.flush_text_to_paragraphs(&mut paragraphs, &stripped);
            }
        }

        paragraphs
    }

    /// 개행이 전혀 없는 한 "줄"을 이 길이(문자 수) 단위로 강제 절단해 별도 문단으로 만든다.
    ///
    /// [붙여넣기 화면 겹침 방지] 웹페이지 렌더 결과가 아니라 원본 소스(view-source 등)를
    /// 통째로 복사하면, 내부 텍스트에 실제 개행 문자가 전혀 없는 경우(예: 한 줄짜리 최소화
    /// JS/JSON 블록)가 있다 — 실사용 확인: Daum 홈페이지 전체 소스(HTML 598KB) 붙여넣기가
    /// 개행 없는 50만자 이상 단일 문단을 만들어 화면이 겹쳐 보이는 결과로 이어졌다. 문단
    /// 하나가 이 정도로 크면 줄바꿈 계산 등 조판 경로가 원래 가정하지 않은 크기라 무너진다.
    const FLUSH_LINE_CHAR_CAP: usize = 4000;

    /// 블록 밖 인라인 구간을 문단으로 만들고 비운다.
    /// 서식 태그가 있으면 `<p>` 안처럼 한 문단으로 읽어 서식을 살린다.
    /// 글뿐이면 종전처럼 줄마다 문단을 나눈다.
    fn flush_inline_run(&mut self, paragraphs: &mut Vec<Paragraph>, run: &mut String) {
        let run = std::mem::take(run);
        // 글 속 '<' 는 엔티티로 남으므로 '<' 가 있으면 서식 태그가 든 구간이다.
        if !run.contains('<') {
            self.flush_text_to_paragraphs(paragraphs, &run);
            return;
        }
        let mut para = Paragraph::default();
        self.parse_inline_content(&mut para, run.trim(), "");
        if !para.text.trim().is_empty() || !para.controls.is_empty() {
            // HTML 태그 분기도 plain paste와 같은 문자 수 제한을 지킨다.
            // 모델 분할은 UTF-16 서식 원점과 그림 소유를 함께 옮긴다.
            while para.text.chars().count() > Self::FLUSH_LINE_CHAR_CAP {
                let positions = para.control_text_positions();
                let pictures_before_cut = positions
                    .iter()
                    .filter(|position| **position < Self::FLUSH_LINE_CHAR_CAP)
                    .count();
                let pictures_at_cut = positions
                    .iter()
                    .filter(|position| **position == Self::FLUSH_LINE_CHAR_CAP)
                    .count();
                let mut tail = para.split_at(Self::FLUSH_LINE_CHAR_CAP + pictures_before_cut);
                // split_at의 문자 원점 뒤로 이동한 경계 그림은 새 문단 선두의
                // 확장 제어문자 공간을 보유해야 한다. 그림 수는 이미 char_count에 있다.
                tail.reserve_leading_extended_control_slots(pictures_at_cut);
                paragraphs.push(para);
                para = tail;
            }
            paragraphs.push(para);
        }
    }

    /// 텍스트를 문단으로 변환하여 추가한다 (줄바꿈 기준 분리, 개행 없는 긴 줄은 추가 절단).
    pub(crate) fn flush_text_to_paragraphs(&self, paragraphs: &mut Vec<Paragraph>, text: &str) {
        let decoded = decode_html_entities(text);
        for line in decoded.split('\n') {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            let chars: Vec<char> = trimmed.chars().collect();
            for chunk in chars.chunks(Self::FLUSH_LINE_CHAR_CAP) {
                let mut para = Paragraph::default();
                para.text = chunk.iter().collect();
                // [#3494] char_count 는 문단 종결자를 포함한다 (model/paragraph.rs:1042).
                para.char_count = para.text.encode_utf16().count() as u32 + 1;
                para.char_offsets = para
                    .text
                    .chars()
                    .scan(0u32, |acc, c| {
                        let off = *acc;
                        *acc += c.len_utf16() as u32;
                        Some(off)
                    })
                    .collect();
                paragraphs.push(para);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::document::Document;
    use crate::model::style::{CharShape, ParaShape};

    /// 파싱을 거친 문서를 흉내낸다 — CharShape/ParaShape 가 원본 레코드 바이트를
    /// raw_data 로 들고 있는 상태(parser/doc_info.rs 가 하는 일).
    fn core_with_parsed_shapes() -> DocumentCore {
        let mut doc = Document::default();
        let mut cs = CharShape::default();
        cs.raw_data = Some(vec![0xAA; 72]);
        doc.doc_info.char_shapes.push(cs);
        let mut ps = ParaShape::default();
        ps.raw_data = Some(vec![0xBB; 54]);
        doc.doc_info.para_shapes.push(ps);
        let mut core = DocumentCore::new_empty();
        core.document = doc;
        core
    }

    // HTML 붙여넣기가 만드는 CharShape/ParaShape 는 char_shapes[0]/para_shapes[0] 의 clone
    // 이라 원본 raw_data 를 물고 온다. 직렬화기는 raw_data 가 있으면 필드 대신 그 바이트를
    // 그대로 쓰므로(serializer/doc_info.rs), 비우지 않으면 붙여넣은 서식이 저장 시 사라진다.
    // PartialEq 가 raw_data 를 제외하므로 중복 검색도 이를 걸러내지 못한다.

    #[test]
    fn html_paste_char_shape_drops_stale_raw_data() {
        let mut core = core_with_parsed_shapes();
        let id = core.css_to_char_shape_id("font-weight:bold;color:#ff0000");
        let cs = &core.document.doc_info.char_shapes[id as usize];
        assert!(cs.bold, "전제: CSS 가 반영돼야 함");
        assert!(
            cs.raw_data.is_none(),
            "raw_data 가 남으면 저장 시 원본 서식 바이트가 나가 붙여넣은 서식이 사라진다"
        );
    }

    #[test]
    fn html_paste_para_shape_drops_stale_raw_data() {
        let mut core = core_with_parsed_shapes();
        let id = core.css_to_para_shape_id("text-align:center");
        let ps = &core.document.doc_info.para_shapes[id as usize];
        assert!(
            ps.raw_data.is_none(),
            "raw_data 가 남으면 정렬·줄간격 변경이 저장 시 사라진다"
        );
    }
}

#[cfg(test)]
mod textdecoline_tests {
    use super::*;
    use crate::model::document::Document;
    use crate::model::style::{CharShape, UnderlineType};

    #[test]
    fn css_underline_recognizes_text_decoration_line_with_space() {
        let mut doc = Document::default();
        doc.doc_info.char_shapes.push(CharShape::default());
        let mut core = DocumentCore::new_empty();
        core.document = doc;

        let id = core.css_to_char_shape_id("text-decoration-line: underline");
        let cs = &core.document.doc_info.char_shapes[id as usize];
        assert_ne!(
            cs.underline_type,
            UnderlineType::None,
            "콜론 뒤 공백이 있는 text-decoration-line: underline 도 밑줄로 인식돼야 함"
        );
    }
}