rhwp 0.9.1

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
//! 각주/미주(+미주 수식) native 명령 (object_ops 분할, #1904).

use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::event::DocumentEvent;

impl DocumentCore {
    fn find_note_equation_ref(
        &self,
        kind: &str,
        section_idx: usize,
        parent_para_idx: usize,
        note_control_idx: usize,
        note_para_idx: usize,
        inner_control_idx: usize,
    ) -> Result<&crate::model::control::Equation, HwpError> {
        let section = self.document.sections.get(section_idx).ok_or_else(|| {
            HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
        })?;
        let para = section.paragraphs.get(parent_para_idx).ok_or_else(|| {
            HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
        })?;
        let note_para = match para.controls.get(note_control_idx) {
            Some(Control::Footnote(note)) if kind == "footnote" => {
                note.paragraphs.get(note_para_idx)
            }
            Some(Control::Endnote(note)) if kind == "endnote" => note.paragraphs.get(note_para_idx),
            _ => None,
        }
        .ok_or_else(|| {
            HwpError::RenderError(format!(
                "각주/미주 문단을 찾을 수 없습니다: kind={} sec={} para={} ctrl={} note_para={}",
                kind, section_idx, parent_para_idx, note_control_idx, note_para_idx
            ))
        })?;
        match note_para.controls.get(inner_control_idx) {
            Some(Control::Equation(eq)) => Ok(eq),
            _ => Err(HwpError::RenderError(format!(
                "각주/미주 내부 컨트롤 {}은 수식이 아닙니다",
                inner_control_idx
            ))),
        }
    }
    fn find_note_equation_mut(
        &mut self,
        kind: &str,
        section_idx: usize,
        parent_para_idx: usize,
        note_control_idx: usize,
        note_para_idx: usize,
        inner_control_idx: usize,
    ) -> Result<&mut crate::model::control::Equation, HwpError> {
        let section = self.document.sections.get_mut(section_idx).ok_or_else(|| {
            HwpError::RenderError(format!("구역 인덱스 {} 범위 초과", section_idx))
        })?;
        let para = section.paragraphs.get_mut(parent_para_idx).ok_or_else(|| {
            HwpError::RenderError(format!("문단 인덱스 {} 범위 초과", parent_para_idx))
        })?;
        let note_para = match para.controls.get_mut(note_control_idx) {
            Some(Control::Footnote(note)) if kind == "footnote" => {
                note.paragraphs.get_mut(note_para_idx)
            }
            Some(Control::Endnote(note)) if kind == "endnote" => {
                note.paragraphs.get_mut(note_para_idx)
            }
            _ => None,
        }
        .ok_or_else(|| {
            HwpError::RenderError(format!(
                "각주/미주 문단을 찾을 수 없습니다: kind={} sec={} para={} ctrl={} note_para={}",
                kind, section_idx, parent_para_idx, note_control_idx, note_para_idx
            ))
        })?;
        match note_para.controls.get_mut(inner_control_idx) {
            Some(Control::Equation(eq)) => Ok(eq),
            _ => Err(HwpError::RenderError(format!(
                "각주/미주 내부 컨트롤 {}은 수식이 아닙니다",
                inner_control_idx
            ))),
        }
    }
    pub fn get_note_equation_properties_native(
        &self,
        kind: &str,
        section_idx: usize,
        parent_para_idx: usize,
        note_control_idx: usize,
        note_para_idx: usize,
        inner_control_idx: usize,
    ) -> Result<String, HwpError> {
        let eq = self.find_note_equation_ref(
            kind,
            section_idx,
            parent_para_idx,
            note_control_idx,
            note_para_idx,
            inner_control_idx,
        )?;
        Ok(Self::equation_properties_json(eq))
    }
    pub fn set_note_equation_properties_native(
        &mut self,
        kind: &str,
        section_idx: usize,
        parent_para_idx: usize,
        note_control_idx: usize,
        note_para_idx: usize,
        inner_control_idx: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        let dpi = self.dpi;
        let eq = self.find_note_equation_mut(
            kind,
            section_idx,
            parent_para_idx,
            note_control_idx,
            note_para_idx,
            inner_control_idx,
        )?;
        Self::apply_equation_properties(eq, dpi, props_json);

        let section = &mut self.document.sections[section_idx];
        section.raw_stream = None;
        self.recompose_section(section_idx);
        self.paginate_if_needed();

        Ok(crate::document_core::helpers::json_ok())
    }
    pub(crate) fn footnote_numbering_name(
        numbering: crate::model::footnote::FootnoteNumbering,
    ) -> &'static str {
        use crate::model::footnote::FootnoteNumbering;
        match numbering {
            FootnoteNumbering::Continue => "continue",
            FootnoteNumbering::RestartSection => "restartSection",
            FootnoteNumbering::RestartPage => "restartPage",
        }
    }
    pub(crate) fn footnote_numbering_from_str(
        value: &str,
        fallback: crate::model::footnote::FootnoteNumbering,
    ) -> crate::model::footnote::FootnoteNumbering {
        use crate::model::footnote::FootnoteNumbering;
        match value {
            "continue" | "CONTINUOUS" | "continuous" => FootnoteNumbering::Continue,
            "restartSection" | "ON_SECTION" | "RESTART_SECTION" | "onSection" => {
                FootnoteNumbering::RestartSection
            }
            "restartPage" | "ON_PAGE" | "RESTART_PAGE" | "onPage" => FootnoteNumbering::RestartPage,
            _ => fallback,
        }
    }
    pub(crate) fn footnote_placement_name(
        placement: crate::model::footnote::FootnotePlacement,
    ) -> &'static str {
        use crate::model::footnote::FootnotePlacement;
        match placement {
            FootnotePlacement::EachColumn => "documentEnd",
            FootnotePlacement::BelowText => "sectionEnd",
            FootnotePlacement::RightColumn => "rightColumn",
        }
    }
    pub(crate) fn footnote_placement_from_str(
        value: &str,
        fallback: crate::model::footnote::FootnotePlacement,
    ) -> crate::model::footnote::FootnotePlacement {
        use crate::model::footnote::FootnotePlacement;
        match value {
            "documentEnd" | "eachColumn" => FootnotePlacement::EachColumn,
            "sectionEnd" | "belowText" => FootnotePlacement::BelowText,
            "rightColumn" => FootnotePlacement::RightColumn,
            _ => fallback,
        }
    }
    pub(crate) fn json_escape_note_char(ch: char) -> String {
        if ch == '\0' {
            String::new()
        } else {
            crate::document_core::helpers::json_escape(&ch.to_string())
        }
    }
    fn make_note_inner_paragraph(
        number_type: crate::model::control::AutoNumberType,
        number: u16,
        format: u8,
        prefix_char: char,
        suffix_char: char,
        default_char_shape_id: u32,
        para_shape_id: u16,
        style_id: u8,
    ) -> crate::model::paragraph::Paragraph {
        use crate::model::paragraph::{CharShapeRef, LineSeg, Paragraph};

        let auto_num = crate::model::control::AutoNumber {
            number_type,
            format,
            superscript: false,
            number,
            assigned_number: number,
            user_symbol: '\0',
            prefix_char,
            suffix_char,
        };

        Paragraph {
            text: "  ".to_string(),
            char_count: 10,
            char_count_msb: true,
            control_mask: 1u32 << 0x12,
            char_offsets: vec![0, 8],
            para_shape_id,
            style_id,
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: default_char_shape_id,
            }],
            controls: vec![crate::model::control::Control::AutoNumber(auto_num)],
            line_segs: vec![LineSeg {
                text_start: 0,
                line_height: 1000,
                text_height: 1000,
                baseline_distance: 850,
                line_spacing: 600,
                segment_width: 0,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..Default::default()
            }],
            has_para_text: true,
            ..Default::default()
        }
    }
    /// 이름이 `local_name`(영문 `english_name`)인 스타일과 그 번호. 각주·미주 스타일
    /// 번호는 서식마다 다르다(옛 서식 '각주' 11번, 빈 문서 서식 14번).
    fn note_style(
        &self,
        local_name: &str,
        english_name: &str,
    ) -> Option<(u8, &crate::model::style::Style)> {
        let styles = &self.document.doc_info.styles;
        let idx = styles.iter().position(|style| {
            style.local_name == local_name || style.english_name.eq_ignore_ascii_case(english_name)
        })?;
        Some((u8::try_from(idx).ok()?, &styles[idx]))
    }
    fn endnote_style_defaults(
        &self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> (u32, u16, u8) {
        let section = &self.document.sections[section_idx];

        for para in &section.paragraphs {
            for ctrl in &para.controls {
                if let Control::Endnote(en) = ctrl {
                    if let Some(ep) = en.paragraphs.first() {
                        let char_shape_id = ep
                            .char_shapes
                            .first()
                            .map(|cs| cs.char_shape_id)
                            .unwrap_or(0);
                        return (char_shape_id, ep.para_shape_id, ep.style_id);
                    }
                }
            }
        }

        if let Some((idx, style)) = self.note_style("미주", "Endnote") {
            return (style.char_shape_id as u32, style.para_shape_id, idx);
        }

        // 폴백 — 커서 offset 의 글자모양 기준 (첫 엔트리 아님).
        let current_para = &section.paragraphs[para_idx];
        (
            current_para.char_shape_id_at(char_offset).unwrap_or(0),
            current_para.para_shape_id,
            current_para.style_id,
        )
    }
    /// 각주를 삽입한다.
    /// 커서 위치에 각주 컨트롤을 추가하고 빈 문단 1개를 생성한다.
    /// 반환: JSON `{"ok":true, "paraIdx":N, "controlIdx":N, "footnoteNumber":N}`
    pub fn insert_footnote_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> Result<String, HwpError> {
        use crate::model::footnote::Footnote;
        use crate::model::paragraph::{CharShapeRef, LineSeg, Paragraph};

        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
            )));
        }

        // 각주 번호: 삽입 위치 이전의 모든 각주 수 + 1
        // 본문 문단 + 표 셀 + 글상자 내부의 각주를 모두 포함
        let footnote_number = {
            let mut count = 0u16;
            let section = &self.document.sections[section_idx];
            for (pi, para) in section.paragraphs.iter().enumerate() {
                let is_before = pi < para_idx;
                let is_same = pi == para_idx;
                // 본문 문단의 각주
                for (ci, ctrl) in para.controls.iter().enumerate() {
                    match ctrl {
                        Control::Footnote(_) => {
                            if is_before {
                                count += 1;
                            } else if is_same {
                                let positions =
                                    crate::document_core::helpers::find_control_text_positions(
                                        para,
                                    );
                                let pos = positions.get(ci).copied().unwrap_or(usize::MAX);
                                if pos <= char_offset {
                                    count += 1;
                                }
                            }
                        }
                        // 표 셀 내 각주
                        // [Task #825 후속] is_same(커서와 같은 문단)일 때, 이 Table
                        // 컨트롤 자체가 커서보다 뒤(char_offset 이후)에 있으면 그
                        // 안의 각주는 아직 삽입 시점 기준으로 "이전" 각주가 아니다.
                        // 기존 코드는 위치를 확인하지 않고 무조건 카운트해
                        // 본문에 텍스트 - 표(각주 포함) - 커서 순서가 아니라
                        // 커서 - 텍스트 - 표(각주 포함) 순서일 때도 표 각주를
                        // 선행으로 오산해 신규 각주 번호가 부풀려졌다.
                        Control::Table(table)
                            if is_before
                                || (is_same && {
                                    let positions =
                                        crate::document_core::helpers::find_control_text_positions(
                                            para,
                                        );
                                    positions.get(ci).copied().unwrap_or(usize::MAX) <= char_offset
                                }) =>
                        {
                            for cell in &table.cells {
                                for cp in &cell.paragraphs {
                                    count +=
                                        cp.controls
                                            .iter()
                                            .filter(|c| matches!(c, Control::Footnote(_)))
                                            .count() as u16;
                                }
                            }
                        }
                        // 글상자 내 각주 (표와 동일한 위치 검사)
                        Control::Shape(shape)
                            if is_before
                                || (is_same && {
                                    let positions =
                                        crate::document_core::helpers::find_control_text_positions(
                                            para,
                                        );
                                    positions.get(ci).copied().unwrap_or(usize::MAX) <= char_offset
                                }) =>
                        {
                            if let Some(text_box) =
                                shape.drawing().and_then(|d| d.text_box.as_ref())
                            {
                                for tp in &text_box.paragraphs {
                                    count +=
                                        tp.controls
                                            .iter()
                                            .filter(|c| matches!(c, Control::Footnote(_)))
                                            .count() as u16;
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
            count + 1
        };

        // 각주 내부 문단 생성: 기존 각주의 스타일을 참조하여 동일한 스타일 적용
        // 기존 각주가 없으면 본문 문단 스타일 사용
        let (default_char_shape_id, default_para_shape_id, default_style_id) = {
            let section = &self.document.sections[section_idx];
            let mut found = None;
            // 본문 문단의 각주에서 스타일 참조
            'outer: for para in &section.paragraphs {
                for ctrl in &para.controls {
                    if let Control::Footnote(fn_) = ctrl {
                        if let Some(fp) = fn_.paragraphs.first() {
                            found = Some((
                                fp.char_shapes
                                    .first()
                                    .map(|cs| cs.char_shape_id)
                                    .unwrap_or(0),
                                fp.para_shape_id,
                                fp.style_id,
                            ));
                            break 'outer;
                        }
                    }
                    // 표 셀 내 각주에서도 참조
                    if let Control::Table(table) = ctrl {
                        for cell in &table.cells {
                            for cp in &cell.paragraphs {
                                for cc in &cp.controls {
                                    if let Control::Footnote(fn_) = cc {
                                        if let Some(fp) = fn_.paragraphs.first() {
                                            found = Some((
                                                fp.char_shapes
                                                    .first()
                                                    .map(|cs| cs.char_shape_id)
                                                    .unwrap_or(0),
                                                fp.para_shape_id,
                                                fp.style_id,
                                            ));
                                            break 'outer;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            found.unwrap_or_else(|| {
                // 폴백 — 커서 offset 의 글자모양 기준 (첫 엔트리 아님).
                let current_para = &section.paragraphs[para_idx];
                (
                    current_para.char_shape_id_at(char_offset).unwrap_or(0),
                    current_para.para_shape_id,
                    current_para.style_id,
                )
            })
        };
        // 문단 모양과 스타일은 이름이 '각주'인 스타일을 따른다. 번호를 고정하면 빈 문서에서는
        // 11번 '개요 10'이 붙는다. '각주' 스타일이 없는 문서만 위의 기존 각주·커서 문단 값을 쓴다.
        let (para_shape_id, style_id) = self
            .note_style("각주", "Footnote")
            .map(|(idx, style)| (style.para_shape_id, idx))
            .unwrap_or((default_para_shape_id, default_style_id));

        // [Task #1058 reopen Round 5] 신규 각주 inner paragraph 한컴 contract 정합:
        //   - style_id / para_shape_id = '각주' 스타일과 그 문단 모양 (정답지는 11번·0번)
        //   - controls = [AutoNumber] (각주 번호 inline 컨트롤, char index 0 위치)
        //   - text = "  " (placeholder space ×2, AutoNumber 가 두 space 사이 8 cu 차지)
        //   - char_offsets = [0, 8] (첫 space pos 0, AutoNumber anchor 점유 pos 0~7, 두 번째 space pos 8)
        //   - char_count = 10 (2 placeholder + 8 AutoNumber inline ctrl)
        //   - has_para_text = true
        // 한컴 정답지 samples/footnote-01.hwp 의 각주 inner_para 와 동일한 contract.
        // 사용자 입력은 두 placeholder 뒤 (char_offset=2) 부터 시작 — insert_text_at 의
        // 일반 분기가 char_offsets[i] = base + sum(widths) 시프트 (jump 8 보존).
        let auto_num = crate::model::control::AutoNumber {
            number_type: crate::model::control::AutoNumberType::Footnote,
            format: 0, // Digit
            superscript: false,
            number: footnote_number,
            assigned_number: footnote_number,
            user_symbol: '\0',
            prefix_char: '\0',
            suffix_char: ')',
        };
        let inner_para = Paragraph {
            text: "  ".to_string(), // placeholder space ×2 (정답지 정합)
            char_count: 10,         // 2 placeholder + 8 (AutoNumber inline ctrl)
            char_count_msb: true,
            control_mask: 1u32 << 0x12, // bit 18 (AutoNumber)
            char_offsets: vec![0, 8],   // AutoNumber 가 두 space 사이 8 cu 차지
            para_shape_id,
            style_id,
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: default_char_shape_id,
            }],
            controls: vec![crate::model::control::Control::AutoNumber(auto_num)],
            line_segs: vec![LineSeg {
                text_start: 0,
                line_height: 1000,
                text_height: 1000,
                baseline_distance: 850,
                line_spacing: 600,
                segment_width: 0,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..Default::default()
            }],
            has_para_text: true,
            ..Default::default()
        };

        let footnote = Footnote {
            number: footnote_number,
            paragraphs: vec![inner_para],
            // [Task #1050] HWP5 CTRL_FOOTNOTE 한컴 default
            after_decoration_letter: 0x0029, // ')'
            ..Default::default()
        };

        // 문단에 각주 컨트롤 삽입
        self.document.sections[section_idx].raw_stream = None;
        let paragraph = &mut self.document.sections[section_idx].paragraphs[para_idx];

        // 삽입 위치 결정 (char_offset 기준)
        let insert_idx = {
            let positions = crate::document_core::helpers::find_control_text_positions(paragraph);
            let mut idx = paragraph.controls.len();
            for (i, &pos) in positions.iter().enumerate() {
                if pos > char_offset {
                    idx = i;
                    break;
                }
            }
            idx
        };

        // [#3214] insert_idx 는 controls 기준이다. HWPX 문서는 ctrl_data_records 가 controls
        // 보다 짧은 상태가 정상이므로(파서가 채우지 않음), 정렬 없이 같은 인덱스로 insert 하면
        // 범위 초과로 패닉한다.
        paragraph.align_ctrl_data_records();
        paragraph
            .controls
            .insert(insert_idx, Control::Footnote(Box::new(footnote)));
        paragraph.ctrl_data_records.insert(insert_idx, None);

        // char_offsets 조정: char_offset 위치에 8바이트 갭 생성
        // char_offsets[i]는 텍스트 i번째 문자의 UTF-16 오프셋 (컨트롤은 갭으로 표현)
        // 주의: char_offset은 텍스트 기준 인덱스이지만, char_offsets 배열 길이는 text.chars().count()
        // text에 포함되지 않는 제어 문자(cc - text_len 차이)가 있을 수 있으므로 범위 확인
        paragraph.shift_for_inline_control_insert(insert_idx, char_offset);
        paragraph.char_count += 8;
        paragraph.control_mask |= 1u32 << 0x0011; // 각주/미주 비트
        paragraph.has_para_text = true;
        self.shift_active_field_for_control_insert(section_idx, para_idx, insert_idx);

        // 전체 각주 순서 번호 재계산 (1부터 순차)
        // 본문 문단 + 표 셀 + 글상자 내부의 각주를 모두 포함
        {
            let mut num = 1u16;
            for pi in 0..self.document.sections[section_idx].paragraphs.len() {
                for ci in 0..self.document.sections[section_idx].paragraphs[pi]
                    .controls
                    .len()
                {
                    match &mut self.document.sections[section_idx].paragraphs[pi].controls[ci] {
                        Control::Footnote(ref mut fn_) => {
                            fn_.number = num;
                            num += 1;
                        }
                        Control::Table(ref mut table) => {
                            for cell in &mut table.cells {
                                for cp in &mut cell.paragraphs {
                                    for cc in &mut cp.controls {
                                        if let Control::Footnote(ref mut fn_) = cc {
                                            fn_.number = num;
                                            num += 1;
                                        }
                                    }
                                }
                            }
                        }
                        Control::Shape(ref mut shape) => {
                            if let Some(text_box) =
                                shape.drawing_mut().and_then(|d| d.text_box.as_mut())
                            {
                                for tp in &mut text_box.paragraphs {
                                    for tc in &mut tp.controls {
                                        if let Control::Footnote(ref mut fn_) = tc {
                                            fn_.number = num;
                                            num += 1;
                                        }
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
        }

        // 각주 내부 문단 리플로우
        self.reflow_footnote_paragraph(section_idx, para_idx, insert_idx, 0);

        // 본문 문단 리플로우 (각주 마커 폭으로 인한 줄넘김 변경 반영)
        // 본문 문단의 상자는 쪽 폭이 아니라 **열** 폭에서 나온다. 직접 계산하면
        // ColumnDef(다단)·margin_gutter·가로 용지·양면 짝수쪽 여백 교환·손상
        // PageDef 의 A4 폴백을 모두 놓친다 — 그리고 그 결과가 디스크로 나간다.
        // 대화형 편집의 관문과 같은 한 곳을 쓴다.
        self.reflow_paragraph(section_idx, para_idx);

        // 뒤 문단의 저장 줄 구성·단 소속은 보존한다. 각주 예약으로 바뀐
        // 프레임 수용은 같은 저장 줄의 점유를 소비하는 pagination이 계산한다.

        // 리플로우 + 페이지네이션
        self.recompose_section(section_idx);
        self.paginate_if_needed();
        // 새 각주와 뒤 각주의 번호·모양을 구역의 각주 모양대로 맞춘다(한/글처럼 모양을 따른다).
        self.refresh_footnote_numbers(section_idx);
        self.invalidate_page_tree_cache();
        let footnote_number = match self.document.sections[section_idx].paragraphs[para_idx]
            .controls
            .get(insert_idx)
        {
            Some(Control::Footnote(note)) => note.number,
            _ => footnote_number,
        };

        self.event_log.push(DocumentEvent::PictureInserted {
            section: section_idx,
            para: para_idx,
        });
        Ok(format!(
            "{{\"ok\":true,\"paraIdx\":{},\"controlIdx\":{},\"footnoteNumber\":{}}}",
            para_idx, insert_idx, footnote_number
        ))
    }
    /// 미주를 삽입한다.
    /// 커서 위치에 미주 컨트롤을 추가하고 빈 미주 문단 1개를 생성한다.
    /// 반환: JSON `{"ok":true, "paraIdx":N, "controlIdx":N, "endnoteNumber":N}`
    pub fn insert_endnote_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> Result<String, HwpError> {
        use crate::model::footnote::Endnote;

        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
            )));
        }

        let shape = self.document.sections[section_idx]
            .section_def
            .endnote_shape
            .clone();
        let number_format_code = Self::footnote_shape_number_format_code(shape.number_format);

        let (default_char_shape_id, para_shape_id, style_id) =
            self.endnote_style_defaults(section_idx, para_idx, char_offset);
        let prefix_char = if shape.prefix_char == '\0' {
            '\0'
        } else {
            shape.prefix_char
        };
        let suffix_char = if shape.suffix_char == '\0' {
            ')'
        } else {
            shape.suffix_char
        };

        // 번호는 넣은 뒤 `refresh_endnote_numbers`가 구역의 번호 매기기대로 매긴다.
        let inner_para = Self::make_note_inner_paragraph(
            crate::model::control::AutoNumberType::Endnote,
            0,
            number_format_code,
            prefix_char,
            suffix_char,
            default_char_shape_id,
            para_shape_id,
            style_id,
        );

        let endnote = Endnote {
            paragraphs: vec![inner_para],
            before_decoration_letter: prefix_char as u16,
            after_decoration_letter: suffix_char as u16,
            number_shape: number_format_code as u32,
            ..Default::default()
        };

        self.document.sections[section_idx].raw_stream = None;
        let paragraph = &mut self.document.sections[section_idx].paragraphs[para_idx];

        let insert_idx = {
            let positions = crate::document_core::helpers::find_control_text_positions(paragraph);
            let mut idx = paragraph.controls.len();
            for (i, &pos) in positions.iter().enumerate() {
                if pos > char_offset {
                    idx = i;
                    break;
                }
            }
            idx
        };

        // [#3214] 각주 경로와 동일 — controls 기준 인덱스를 쓰기 전에 정렬한다.
        paragraph.align_ctrl_data_records();
        paragraph
            .controls
            .insert(insert_idx, Control::Endnote(Box::new(endnote)));
        paragraph.ctrl_data_records.insert(insert_idx, None);

        paragraph.shift_for_inline_control_insert(insert_idx, char_offset);
        paragraph.char_count += 8;
        paragraph.control_mask |= 1u32 << 0x0011;
        paragraph.has_para_text = true;
        self.shift_active_field_for_control_insert(section_idx, para_idx, insert_idx);

        Self::sync_paragraph_endnotes_with_shape(
            &mut self.document.sections[section_idx].paragraphs,
            number_format_code,
            prefix_char,
            suffix_char,
        );
        self.refresh_endnote_numbers(section_idx);
        let endnote_number = match self.document.sections[section_idx].paragraphs[para_idx]
            .controls
            .get(insert_idx)
        {
            Some(Control::Endnote(note)) => note.number,
            _ => 0,
        };

        self.reflow_footnote_paragraph(section_idx, para_idx, insert_idx, 0);

        // 본문 문단의 상자는 쪽 폭이 아니라 **열** 폭에서 나온다. 직접 계산하면
        // ColumnDef(다단)·margin_gutter·가로 용지·양면 짝수쪽 여백 교환·손상
        // PageDef 의 A4 폴백을 모두 놓친다 — 그리고 그 결과가 디스크로 나간다.
        // 대화형 편집의 관문과 같은 한 곳을 쓴다.
        self.reflow_paragraph(section_idx, para_idx);

        self.recompose_section(section_idx);
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();

        self.event_log.push(DocumentEvent::PictureInserted {
            section: section_idx,
            para: para_idx,
        });
        Ok(format!(
            "{{\"ok\":true,\"paraIdx\":{},\"controlIdx\":{},\"endnoteNumber\":{}}}",
            para_idx, insert_idx, endnote_number
        ))
    }
}

#[cfg(test)]
mod char_shape_inherit_tests {
    use crate::document_core::DocumentCore;
    use crate::model::control::Control;
    use crate::model::paragraph::{CharShapeRef, Paragraph};

    /// 혼합 글자모양 문단: 텍스트 20자, 글자 인덱스 0~9 는 34, 10~ 는 37.
    fn core_with_mixed_shape_paragraph() -> DocumentCore {
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        core.insert_text_native(0, 0, 0, "0123456789abcdefghij")
            .unwrap();
        let para = &mut core.document.sections[0].paragraphs[0];
        // 컨트롤(SectionDef 등)이 UTF-16 앞자리를 차지하므로 경계는 char_offsets 로 계산.
        let boundary = para.char_offsets[10];
        para.char_shapes = vec![
            CharShapeRef {
                start_pos: 0,
                char_shape_id: 34,
            },
            CharShapeRef {
                start_pos: boundary,
                char_shape_id: 37,
            },
        ];
        core
    }

    /// 각주를 넣은 본문 문단의 상자는 **열** 폭이지 쪽 폭이 아니다.
    ///
    /// 종전 세 자리(`equation.rs`, `note.rs` ×2)는
    /// `page_def.width - margin_left - margin_right` 를 직접 계산했다. 2단 구역에서
    /// 그 값은 열 폭의 약 두 배이고, `segment_width` 는 저장된다 — 화면만의 문제가
    /// 아니라 파일이 틀린다. `ColumnDef` 말고도 `margin_gutter`, 가로 용지
    /// (`PageAreas::from_page_def_for_page` 가 width/height 를 먼저 바꾼다),
    /// 양면 짝수쪽 여백 교환, 손상 `PageDef` 의 A4 폴백을 모두 놓쳤다.
    fn a_footnote_host_paragraph_is_reflowed_on_its_column_not_the_page() {
        use crate::model::page::ColumnDef;

        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        core.insert_text_native(0, 0, 0, "0123456789abcdefghij")
            .unwrap();

        // 2단으로 바꾼다. 열 폭 ≈ (본문 폭 - 단 간격) / 2.
        let column_def = ColumnDef {
            column_count: 2,
            same_width: true,
            spacing: 0,
            ..Default::default()
        };
        core.document.sections[0]
            .paragraphs
            .first_mut()
            .expect("본문 문단")
            .controls
            .push(Control::ColumnDef(column_def));
        core.recompose_section(0);
        core.paginate();

        let page_text_width_hwp = {
            let page_def = &core.document.sections[0].section_def.page_def;
            page_def.width as i32 - page_def.margin_left as i32 - page_def.margin_right as i32
        };

        core.insert_footnote_native(0, 0, 10).unwrap();

        let published = core.document.sections[0].paragraphs[0]
            .line_segs
            .first()
            .map(|seg| seg.segment_width)
            .expect("본문 첫 줄");

        // 쪽 폭을 그대로 쓰면 열 폭의 두 배 가까이 나온다. 절반 근처여야 한다.
        assert!(
            published < page_text_width_hwp * 3 / 4,
            "2단 본문이 쪽 폭으로 발행되었다: segment_width={published}, \
             쪽 본문 폭={page_text_width_hwp}"
        );
        assert!(
            published > 0,
            "열 상자는 양수여야 한다: segment_width={published}"
        );
    }

    /// 기존 각주가 없는 문서의 폴백 — 커서 offset 글자모양(37) 상속.
    #[test]
    fn insert_footnote_fallback_inherits_char_shape_at_cursor_offset() {
        a_footnote_host_paragraph_is_reflowed_on_its_column_not_the_page();
        let mut core = core_with_mixed_shape_paragraph();
        core.insert_footnote_native(0, 0, 10).unwrap();

        let inner = core.document.sections[0]
            .paragraphs
            .iter()
            .find_map(|p| {
                p.controls.iter().find_map(|c| match c {
                    Control::Footnote(f) => f.paragraphs.first(),
                    _ => None,
                })
            })
            .expect("각주 내부 문단");
        assert_eq!(
            inner.char_shapes.first().map(|cs| cs.char_shape_id),
            Some(37),
            "각주 내부 문단이 커서 offset 글자모양(37)이 아닌 값을 상속"
        );
    }

    /// [Task #825 후속] 같은 문단 안, 커서보다 "뒤"(char_offset 이후)에 있는 표
    /// 안 각주는 신규 각주 번호 계산에서 선행 각주로 세면 안 된다.
    ///
    /// 문단 구성: 텍스트 "AB"(char_offset 0~2) 뒤에 표(각주 1개 포함)를 삽입한다.
    /// 그 상태에서 문단 맨 앞(char_offset=0), 즉 표보다 앞에 신규 각주를 삽입하면
    /// 표 각주는 아직 "이전" 각주가 아니므로 신규 각주 번호는 1이어야 한다.
    /// 버그가 있으면 같은 문단(is_same)이라는 이유만으로 표 각주를 무조건 세어
    /// 번호가 2로 부풀려진다.
    #[test]
    fn insert_footnote_ignores_table_footnote_positioned_after_cursor_in_same_paragraph() {
        use crate::model::footnote::Footnote;
        use crate::model::table::{Cell, Table};

        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        core.insert_text_native(0, 0, 0, "AB").unwrap();

        // 표(각주 1개 포함 셀)를 "AB" 텍스트 뒤 sibling control 로 직접 배치한다
        // (create_table_native 는 문단 끝 삽입 시 별도 문단으로 분리하므로, 같은
        // 문단 안 텍스트-뒤 컨트롤 배치를 재현하려면 IR 을 직접 구성해야 한다).
        let mut cell = Cell::default();
        cell.paragraphs.push(Paragraph::default());
        cell.paragraphs[0]
            .controls
            .push(Control::Footnote(Box::<Footnote>::default()));
        let mut table = Table::default();
        table.cells.push(cell);

        let para = &mut core.document.sections[0].paragraphs[0];
        para.controls.push(Control::Table(Box::new(table)));
        para.ctrl_data_records.push(None);
        // "AB"(2) 뒤에 표(8 코드유닛) 갭을 표현하는 char_offsets 항목 추가.
        para.char_offsets.push(2);
        para.char_count += 8;

        // 문단 맨 앞(표보다 앞)에 신규 각주 삽입.
        let result = core
            .insert_footnote_native(0, 0, 0)
            .expect("insert footnote before table");
        let footnote_number: u16 = result
            .split("\"footnoteNumber\":")
            .nth(1)
            .and_then(|s| s.split(|c: char| !c.is_ascii_digit()).next())
            .and_then(|s| s.parse().ok())
            .unwrap_or_else(|| panic!("missing footnoteNumber in {result}"));

        assert_eq!(
            footnote_number, 1,
            "표 안 각주가 커서보다 뒤에 있으므로 신규 각주는 1번이어야 한다: {result}"
        );
    }

    /// 기존 미주도 미주 스타일도 없는 문서의 폴백 — 커서 offset 글자모양(37) 상속.
    #[test]
    fn insert_endnote_fallback_inherits_char_shape_at_cursor_offset() {
        let mut core = core_with_mixed_shape_paragraph();
        core.document.doc_info.styles.clear();
        core.insert_endnote_native(0, 0, 10).unwrap();

        let inner = core.document.sections[0]
            .paragraphs
            .iter()
            .find_map(|p| {
                p.controls.iter().find_map(|c| match c {
                    Control::Endnote(e) => e.paragraphs.first(),
                    _ => None,
                })
            })
            .expect("미주 내부 문단");
        assert_eq!(
            inner.char_shapes.first().map(|cs| cs.char_shape_id),
            Some(37),
            "미주 내부 문단이 커서 offset 글자모양(37)이 아닌 값을 상속"
        );
    }

    /// [index-axis 회귀] 인라인 각주 삽입이 char_offsets 는 +8 시프트하면서
    /// char_shapes.start_pos 는 시프트하지 않아 글자모양 run 경계가 텍스트와 어긋나던 결함.
    /// text="abcd", char_offsets=[0,1,2,3], run [{0→id5},{2→id6}]. offset 1 에 각주 삽입 후
    /// 원래 'b'(char idx 1)는 여전히 id 5 여야 한다(결함 시 run1(id6)이 덮어 6 반환).
    #[test]
    fn insert_footnote_shifts_char_shapes_with_char_offsets() {
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        core.insert_text_native(0, 0, 0, "abcd").unwrap();
        {
            let para = &mut core.document.sections[0].paragraphs[0];
            para.text = "abcd".to_string();
            para.char_offsets = vec![0, 1, 2, 3];
            para.char_shapes = vec![
                CharShapeRef {
                    start_pos: 0,
                    char_shape_id: 5,
                },
                CharShapeRef {
                    start_pos: 2,
                    char_shape_id: 6,
                },
            ];
        }
        core.insert_footnote_native(0, 0, 1).unwrap();
        let para = &core.document.sections[0].paragraphs[0];
        assert_eq!(
            para.char_shape_id_at(1),
            Some(5),
            "각주 삽입 후 원래 'b'(char idx 1) 글자모양이 오염됨 — char_shapes.start_pos 미시프트"
        );
    }
}