Skip to main content

rhwp/document_core/queries/
grep.rs

1//! 주소를 가진 문서 검색 — 매치마다 (구역·문단·**페이지**·문자 오프셋)을 돌려준다.
2//!
3//! 평문 추출 후 외부에서 검색하면 주소가 소멸해 근거 제시가 불가능하다. rhwp 는 조판
4//! 엔진을 갖고 있어 "몇 쪽"에 답할 수 있는데, 그 답을 낼 출구가 없었다.
5//!
6//! 페이지 매핑 비용은 0이다 — `DocumentCore::from_bytes` 가 로드 시 `paginate()` 를
7//! 끝내므로 순수 조회다. 다만 매치마다 조회하면 O(N × 페이지 아이템)이므로
8//! `(구역,문단) → 페이지` 인덱스를 **한 번만** 만들어 재사용한다.
9//!
10//! 파서/렌더 무변경의 읽기 전용 질의(추가 기능).
11
12use std::collections::HashMap;
13
14use serde::Serialize;
15
16use crate::document_core::DocumentCore;
17use crate::model::control::Control;
18use crate::model::paragraph::Paragraph;
19use crate::renderer::pagination::PageItem;
20
21/// 검색 매치 하나.
22#[derive(Debug, Clone, Serialize)]
23pub struct GrepMatch {
24    /// 구역 인덱스.
25    pub section: usize,
26    /// 본문 문단 인덱스 (표 셀·글상자 매치는 그 컨트롤을 담은 본문 문단).
27    pub paragraph: usize,
28    /// 0부터 시작하는 글로벌 페이지 번호. 조판에 배치되지 않은 문단이면 생략된다.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub page: Option<u32>,
31    /// 문단 텍스트 내 매치 시작 위치 (문자 단위).
32    #[serde(rename = "charOffset")]
33    pub char_offset: usize,
34    /// 매치 길이 (문자 단위).
35    pub length: usize,
36    /// 매치가 속한 문단의 전체 텍스트.
37    pub text: String,
38    /// 매치 주변 발췌 (앞뒤 문맥).
39    pub context: String,
40    /// 표 셀 안의 매치면 셀 좌표. 본문 매치면 생략된다.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub cell: Option<CellRef>,
43    /// 글상자 안의 매치면 글상자 좌표. 본문·표 셀 매치면 생략된다.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub textbox: Option<TextBoxRef>,
46    /// 수식 스크립트 안의 매치면 수식 좌표. 표 셀·글상자 안의 수식은 해당
47    /// `cell`/`textbox` 좌표와 함께 제공된다.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub equation: Option<EquationRef>,
50    /// `--context N` 을 준 경우 매치가 속한 문단 **앞** N개 문단의 텍스트
51    /// (문서/셀/글상자 경계 밖으로는 나가지 않는다 — 있는 만큼만 준다).
52    #[serde(rename = "contextBefore", skip_serializing_if = "Option::is_none")]
53    pub context_before: Option<Vec<String>>,
54    /// `--context N` 을 준 경우 매치가 속한 문단 **뒤** N개 문단의 텍스트.
55    #[serde(rename = "contextAfter", skip_serializing_if = "Option::is_none")]
56    pub context_after: Option<Vec<String>>,
57    /// [#2792] 표 안의 표에서 나온 매치면 그 중첩 깊이(바깥 표 = 0). 0 이면 생략되므로
58    /// 중첩이 없는 문서의 봉투는 종전과 바이트까지 같다.
59    ///
60    /// 0 이 아니면 **`cell` 은 매치의 정확한 위치가 아니라 그것을 담은 최외곽 칸 문단**을
61    /// 가리킨다 — 정확한 칸은 `cellPath` 의 마지막 단계다.
62    #[serde(rename = "nestedDepth", skip_serializing_if = "is_zero")]
63    pub nested_depth: usize,
64    /// [#8989] 표 안의 표·글상자 안의 표에서 나온 매치의 정확한 칸 경로(바깥 → 안쪽).
65    ///
66    /// `fields` 의 `location.nested` 와 같은 꼴이다. 마지막 단계가 매치가 든 칸과 그 칸
67    /// 문단이다. 본문 표 한 단계 매치는 `cell` 로 충분하므로 생략된다 — 중첩이 없는
68    /// 문서의 봉투는 종전과 같다.
69    #[serde(rename = "cellPath", skip_serializing_if = "Vec::is_empty")]
70    pub cell_path: Vec<CellPathStep>,
71}
72
73/// [#8989] 중첩 칸 경로 한 단계. `kind` 는 `tableCell` 또는 `textBox` 다.
74///
75/// `control` 은 앞 단계 문단(첫 단계는 본문 문단) 안의 컨트롤 인덱스, `cell` 은
76/// `tableCell` 단계의 칸 인덱스, `paragraph` 는 그 칸·글상자 안의 문단 인덱스다.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
78pub struct CellPathStep {
79    pub kind: &'static str,
80    pub control: usize,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub cell: Option<usize>,
83    pub paragraph: usize,
84}
85
86impl CellPathStep {
87    pub fn table_cell(control: usize, cell: usize, paragraph: usize) -> Self {
88        Self {
89            kind: "tableCell",
90            control,
91            cell: Some(cell),
92            paragraph,
93        }
94    }
95
96    pub fn text_box(control: usize, paragraph: usize) -> Self {
97        Self {
98            kind: "textBox",
99            control,
100            cell: None,
101            paragraph,
102        }
103    }
104}
105
106/// 중첩이 없는 흔한 경우에 필드를 아예 빼기 위한 serde 술어.
107fn is_zero(value: &usize) -> bool {
108    *value == 0
109}
110
111/// 병적으로 깊은 중첩(손상/악의적 문서)에서 순회가 스택을 태우지 않게 하는 상한.
112/// `table_extract::MAX_NEST_DEPTH` / `explain` / `hidden_text` / `chart_extract` /
113/// `clipboard` 와 같은 값 — 깊이 0..=7 만 방문한다.
114const MAX_NEST_DEPTH: usize = 8;
115
116/// 표 셀 매치의 좌표.
117#[derive(Debug, Clone, Serialize)]
118pub struct CellRef {
119    /// 표를 담은 본문 문단의 컨트롤 인덱스.
120    pub control: usize,
121    /// 셀 인덱스.
122    pub cell: usize,
123    /// 셀 안의 문단 인덱스.
124    pub paragraph: usize,
125}
126
127/// 글상자 매치의 좌표.
128#[derive(Debug, Clone, Serialize)]
129pub struct TextBoxRef {
130    /// 글상자를 담은 본문 문단의 컨트롤 인덱스.
131    pub control: usize,
132    /// 글상자 안의 문단 인덱스.
133    pub paragraph: usize,
134}
135
136/// 수식 매치의 좌표.
137#[derive(Debug, Clone, Serialize)]
138pub struct EquationRef {
139    /// 수식을 담은 문단(본문·셀·글상자)의 컨트롤 인덱스.
140    pub control: usize,
141}
142
143/// 매치 주변 발췌를 만든다 (앞뒤 `WINDOW` 문자).
144fn make_context(text: &str, offset: usize, length: usize) -> String {
145    const WINDOW: usize = 40;
146    let chars: Vec<char> = text.chars().collect();
147    let start = offset.saturating_sub(WINDOW);
148    let end = (offset + length + WINDOW).min(chars.len());
149    let mut out = String::new();
150    if start > 0 {
151        out.push('…');
152    }
153    out.extend(chars[start..end].iter());
154    if end < chars.len() {
155        out.push('…');
156    }
157    out
158}
159
160/// 매치가 속한 문단을 담은 `paragraphs` 슬라이스에서 `idx` 앞뒤 `n`개 문단의
161/// 텍스트를 뽑는다. 경계(첫/마지막 문단)에서는 있는 만큼만 준다 — 범위 밖으로
162/// 나가지 않는다.
163fn context_window(paragraphs: &[Paragraph], idx: usize, n: usize) -> (Vec<String>, Vec<String>) {
164    let start = idx.saturating_sub(n);
165    let before = paragraphs[start..idx]
166        .iter()
167        .map(|p| p.text.clone())
168        .collect();
169    let end = (idx + 1 + n).min(paragraphs.len());
170    let after = paragraphs[idx + 1..end]
171        .iter()
172        .map(|p| p.text.clone())
173        .collect();
174    (before, after)
175}
176
177impl DocumentCore {
178    /// `(구역, 문단) → 글로벌 페이지` 인덱스를 한 번에 만든다.
179    ///
180    /// 한 문단이 여러 쪽에 걸치면 **처음 등장한 쪽**을 쓴다 — 인용은 시작 위치가 기준이다.
181    ///
182    /// [#3719] `extract_data` 도 같은 인덱스를 쓴다 — 주소가 붙은 질의는 "몇 쪽"의 정의를
183    /// 하나만 가져야 한다. 복제하면 두 명령이 서로 다른 쪽을 답하게 된다.
184    pub(crate) fn build_paragraph_page_index(&self) -> HashMap<(usize, usize), u32> {
185        let mut index: HashMap<(usize, usize), u32> = HashMap::new();
186        let mut global_offset = 0u32;
187        for (sec_idx, pr) in self.pagination.iter().enumerate() {
188            for (local_i, page) in pr.pages.iter().enumerate() {
189                let global_page = global_offset + local_i as u32;
190                for col in &page.column_contents {
191                    for item in &col.items {
192                        let para_index = match item {
193                            PageItem::FullParagraph { para_index }
194                            | PageItem::PartialParagraph { para_index, .. }
195                            | PageItem::Table { para_index, .. }
196                            | PageItem::PartialTable { para_index, .. }
197                            | PageItem::Shape { para_index, .. } => Some(*para_index),
198                            _ => None,
199                        };
200                        if let Some(p) = para_index {
201                            index.entry((sec_idx, p)).or_insert(global_page);
202                        }
203                    }
204                }
205            }
206            global_offset += pr.pages.len() as u32;
207        }
208        index
209    }
210
211    /// `(구역, 문단, 컨트롤) → [(시작 행, 끝 행, 글로벌 페이지)]` 인덱스.
212    ///
213    /// [#3403] 표가 쪽을 넘겨 이어지면 뒤쪽 행의 셀은 다음 쪽에 렌더되는데, 문단 단위
214    /// 페이지 인덱스는 표 호스트 문단의 **첫 쪽**만 알고 있다. 그래서 분할 표 셀 매치가
215    /// 한 쪽 앞을 가리켰다(RAG 인용이 엉뚱한 쪽을 렌더). 행 범위를 함께 들고 있으면
216    /// 셀의 행 번호로 실제 렌더 쪽을 고를 수 있다.
217    ///
218    /// 분할되지 않은 표(`PageItem::Table`)도 전 행 범위로 함께 넣어, 셀 경로가 항상 같은
219    /// 조회를 쓰도록 한다.
220    pub(crate) fn build_table_row_page_index(
221        &self,
222    ) -> HashMap<(usize, usize, usize), Vec<(usize, usize, u32)>> {
223        let mut index: HashMap<(usize, usize, usize), Vec<(usize, usize, u32)>> = HashMap::new();
224        let mut global_offset = 0u32;
225        for (sec_idx, pr) in self.pagination.iter().enumerate() {
226            for (local_i, page) in pr.pages.iter().enumerate() {
227                let global_page = global_offset + local_i as u32;
228                for col in &page.column_contents {
229                    for item in &col.items {
230                        match item {
231                            PageItem::Table {
232                                para_index,
233                                control_index,
234                            } => {
235                                index
236                                    .entry((sec_idx, *para_index, *control_index))
237                                    .or_default()
238                                    .push((0, usize::MAX, global_page));
239                            }
240                            PageItem::PartialTable {
241                                para_index,
242                                control_index,
243                                start_row,
244                                end_row,
245                                ..
246                            } => {
247                                index
248                                    .entry((sec_idx, *para_index, *control_index))
249                                    .or_default()
250                                    .push((*start_row, *end_row, global_page));
251                            }
252                            _ => {}
253                        }
254                    }
255                }
256            }
257            global_offset += pr.pages.len() as u32;
258        }
259        index
260    }
261
262    /// 문서를 검색해 주소가 붙은 매치 목록을 돌려준다.
263    ///
264    /// 본문·표 셀·글상자·중첩 표를 순회한다. 치환 계열은 별도 검색 순회
265    /// (`search_all_text_native`/`replace_all_native`)와 범위·순서를 맞춘다.
266    /// `limit` 이 `Some` 이면 그 개수에서 멈춘다.
267    ///
268    /// 기존 계약과 완전히 동일한 얇은 래퍼다(`context: None`) — `grep_with_context` 로
269    /// 위임한다.
270    pub fn grep(&self, query: &str, case_sensitive: bool, limit: Option<usize>) -> Vec<GrepMatch> {
271        self.grep_with_context(query, case_sensitive, limit, None)
272    }
273
274    /// `grep` 과 같지만 `context` 가 `Some(n)` 이면 매치가 속한 문단의 앞뒤 `n`개
275    /// 문단 텍스트를 `contextBefore`/`contextAfter` 로 함께 돌려준다(표 셀·글상자
276    /// 매치는 그 컨테이너 안에서, 본문 매치는 구역 문단 목록 안에서 앞뒤를 센다).
277    pub fn grep_with_context(
278        &self,
279        query: &str,
280        case_sensitive: bool,
281        limit: Option<usize>,
282        context: Option<usize>,
283    ) -> Vec<GrepMatch> {
284        if query.is_empty() {
285            return Vec::new();
286        }
287        let page_index = self.build_paragraph_page_index();
288        let table_row_pages = self.build_table_row_page_index();
289        let mut out: Vec<GrepMatch> = Vec::new();
290
291        for (sec_idx, section) in self.document.sections.iter().enumerate() {
292            for (para_idx, para) in section.paragraphs.iter().enumerate() {
293                let page = page_index.get(&(sec_idx, para_idx)).copied();
294
295                let make_at =
296                    |page: Option<u32>,
297                     text: &str,
298                     offset: usize,
299                     length: usize,
300                     cell: Option<CellRef>,
301                     textbox: Option<TextBoxRef>,
302                     equation: Option<EquationRef>,
303                     context_before: Option<Vec<String>>,
304                     context_after: Option<Vec<String>>| GrepMatch {
305                        section: sec_idx,
306                        paragraph: para_idx,
307                        page,
308                        char_offset: offset,
309                        length,
310                        text: text.to_string(),
311                        context: make_context(text, offset, length),
312                        cell,
313                        textbox,
314                        equation,
315                        context_before,
316                        context_after,
317                        nested_depth: 0,
318                        cell_path: Vec::new(),
319                    };
320                // 본문 문단 기준 컨텍스트 — 구역 문단 목록 안에서 앞뒤를 센다.
321                let (body_ctx_before, body_ctx_after) = match context {
322                    Some(n) => {
323                        let (b, a) = context_window(&section.paragraphs, para_idx, n);
324                        (Some(b), Some(a))
325                    }
326                    None => (None, None),
327                };
328                let make = |text: &str,
329                            offset: usize,
330                            length: usize,
331                            cell: Option<CellRef>,
332                            textbox: Option<TextBoxRef>,
333                            equation: Option<EquationRef>| {
334                    make_at(
335                        page,
336                        text,
337                        offset,
338                        length,
339                        cell,
340                        textbox,
341                        equation,
342                        body_ctx_before.clone(),
343                        body_ctx_after.clone(),
344                    )
345                };
346                // [#3403] 분할 표 셀은 호스트 문단의 첫 쪽이 아니라 그 행이 실제로 렌더되는
347                // 쪽을 쓴다. 행 범위를 못 찾으면 종전 문단 쪽으로 물러선다.
348                let cell_page = |ctrl_idx: usize, row: usize| -> Option<u32> {
349                    table_row_pages
350                        .get(&(sec_idx, para_idx, ctrl_idx))
351                        .and_then(|ranges| {
352                            ranges
353                                .iter()
354                                .find(|(start, end, _)| row >= *start && row < *end)
355                                .map(|(_, _, page)| *page)
356                        })
357                        .or(page)
358                };
359
360                for (offset, length) in
361                    super::search_query::find_matches(&para.text, query, case_sensitive)
362                {
363                    out.push(make(&para.text, offset, length, None, None, None));
364                    if limit.is_some_and(|n| out.len() >= n) {
365                        return out;
366                    }
367                }
368
369                for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
370                    match ctrl {
371                        Control::Table(table) => {
372                            // [#2792] 셀 안의 표까지 내려간다. 종전에는 셀 문단 컨트롤
373                            // 순회가 Equation 만 봐서 중첩 표가 조용히 버려졌다.
374                            let mut queue = std::collections::VecDeque::new();
375                            queue.push_back((
376                                table,
377                                0usize,
378                                None::<CellRef>,
379                                Vec::<CellPathStep>::new(),
380                                ctrl_idx,
381                            ));
382                            while let Some((current, depth, host, prefix, table_ctrl)) =
383                                queue.pop_front()
384                            {
385                                if depth >= MAX_NEST_DEPTH {
386                                    continue;
387                                }
388                                for (cell_idx, cell) in current.cells.iter().enumerate() {
389                                    for (cp_idx, cp) in cell.paragraphs.iter().enumerate() {
390                                        let (cell_ctx_before, cell_ctx_after) = match context {
391                                            Some(n) => {
392                                                let (b, a) =
393                                                    context_window(&cell.paragraphs, cp_idx, n);
394                                                (Some(b), Some(a))
395                                            }
396                                            None => (None, None),
397                                        };
398                                        let addr = host.clone().unwrap_or(CellRef {
399                                            control: ctrl_idx,
400                                            cell: cell_idx,
401                                            paragraph: cp_idx,
402                                        });
403                                        let mut path = prefix.clone();
404                                        path.push(CellPathStep::table_cell(
405                                            table_ctrl, cell_idx, cp_idx,
406                                        ));
407                                        // 한 단계 표는 `cell` 이 곧 정확한 주소다.
408                                        let hit_path =
409                                            if depth > 0 { path.clone() } else { Vec::new() };
410                                        let match_page = if depth == 0 {
411                                            cell_page(ctrl_idx, cell.row as usize)
412                                        } else {
413                                            None
414                                        };
415                                        for (offset, length) in super::search_query::find_matches(
416                                            &cp.text,
417                                            query,
418                                            case_sensitive,
419                                        ) {
420                                            let mut hit = make_at(
421                                                match_page,
422                                                &cp.text,
423                                                offset,
424                                                length,
425                                                Some(addr.clone()),
426                                                None,
427                                                None,
428                                                cell_ctx_before.clone(),
429                                                cell_ctx_after.clone(),
430                                            );
431                                            hit.nested_depth = depth;
432                                            hit.cell_path = hit_path.clone();
433                                            out.push(hit);
434                                            if limit.is_some_and(|n| out.len() >= n) {
435                                                return out;
436                                            }
437                                        }
438                                        for (equation_idx, nested_control) in
439                                            cp.controls.iter().enumerate()
440                                        {
441                                            match nested_control {
442                                                Control::Equation(equation) => {
443                                                    for (offset, length) in
444                                                        super::search_query::find_matches(
445                                                            &equation.script,
446                                                            query,
447                                                            case_sensitive,
448                                                        )
449                                                    {
450                                                        let mut hit = make_at(
451                                                            match_page,
452                                                            &equation.script,
453                                                            offset,
454                                                            length,
455                                                            Some(addr.clone()),
456                                                            None,
457                                                            Some(EquationRef {
458                                                                control: equation_idx,
459                                                            }),
460                                                            cell_ctx_before.clone(),
461                                                            cell_ctx_after.clone(),
462                                                        );
463                                                        hit.nested_depth = depth;
464                                                        hit.cell_path = hit_path.clone();
465                                                        out.push(hit);
466                                                        if limit.is_some_and(|n| out.len() >= n) {
467                                                            return out;
468                                                        }
469                                                    }
470                                                }
471                                                Control::Table(inner) => {
472                                                    queue.push_back((
473                                                        inner,
474                                                        depth + 1,
475                                                        Some(addr.clone()),
476                                                        path.clone(),
477                                                        equation_idx,
478                                                    ));
479                                                }
480                                                _ => {}
481                                            }
482                                        }
483                                    }
484                                }
485                            }
486                        }
487                        Control::Shape(shape) => {
488                            if let Some(tb) =
489                                crate::document_core::helpers::get_textbox_from_shape(shape)
490                            {
491                                for (tp_idx, tp) in tb.paragraphs.iter().enumerate() {
492                                    // 글상자 안의 매치는 글상자 문단 목록 안에서 앞뒤를
493                                    // 센다(본문 문단 목록이 아니다).
494                                    let (tb_ctx_before, tb_ctx_after) = match context {
495                                        Some(n) => {
496                                            let (b, a) = context_window(&tb.paragraphs, tp_idx, n);
497                                            (Some(b), Some(a))
498                                        }
499                                        None => (None, None),
500                                    };
501                                    for (offset, length) in super::search_query::find_matches(
502                                        &tp.text,
503                                        query,
504                                        case_sensitive,
505                                    ) {
506                                        out.push(make_at(
507                                            page,
508                                            &tp.text,
509                                            offset,
510                                            length,
511                                            None,
512                                            Some(TextBoxRef {
513                                                control: ctrl_idx,
514                                                paragraph: tp_idx,
515                                            }),
516                                            None,
517                                            tb_ctx_before.clone(),
518                                            tb_ctx_after.clone(),
519                                        ));
520                                        if limit.is_some_and(|n| out.len() >= n) {
521                                            return out;
522                                        }
523                                    }
524                                    for (nested_control_idx, nested_control) in
525                                        tp.controls.iter().enumerate()
526                                    {
527                                        match nested_control {
528                                            Control::Equation(equation) => {
529                                                for (offset, length) in
530                                                    super::search_query::find_matches(
531                                                        &equation.script,
532                                                        query,
533                                                        case_sensitive,
534                                                    )
535                                                {
536                                                    out.push(make_at(
537                                                        page,
538                                                        &equation.script,
539                                                        offset,
540                                                        length,
541                                                        None,
542                                                        Some(TextBoxRef {
543                                                            control: ctrl_idx,
544                                                            paragraph: tp_idx,
545                                                        }),
546                                                        Some(EquationRef {
547                                                            control: nested_control_idx,
548                                                        }),
549                                                        tb_ctx_before.clone(),
550                                                        tb_ctx_after.clone(),
551                                                    ));
552                                                    if limit.is_some_and(|n| out.len() >= n) {
553                                                        return out;
554                                                    }
555                                                }
556                                            }
557                                            Control::Table(table) => {
558                                                // 글상자 안 표도 검색 범위에 포함한다. flat `cell`
559                                                // 주소로는 글상자 내부 표의 정확한 경로를 표현할 수
560                                                // 없으므로, match에는 글상자 호스트를 싣는다.
561                                                let mut queue = std::collections::VecDeque::new();
562                                                queue.push_back((
563                                                    table,
564                                                    0usize,
565                                                    vec![CellPathStep::text_box(ctrl_idx, tp_idx)],
566                                                    nested_control_idx,
567                                                ));
568                                                while let Some((
569                                                    current,
570                                                    depth,
571                                                    prefix,
572                                                    table_ctrl,
573                                                )) = queue.pop_front()
574                                                {
575                                                    if depth >= MAX_NEST_DEPTH {
576                                                        continue;
577                                                    }
578                                                    for (cell_idx, cell) in
579                                                        current.cells.iter().enumerate()
580                                                    {
581                                                        for (cp_idx, cp) in
582                                                            cell.paragraphs.iter().enumerate()
583                                                        {
584                                                            let mut path = prefix.clone();
585                                                            path.push(CellPathStep::table_cell(
586                                                                table_ctrl, cell_idx, cp_idx,
587                                                            ));
588                                                            let (cell_ctx_before, cell_ctx_after) =
589                                                                match context {
590                                                                    Some(n) => {
591                                                                        let (b, a) = context_window(
592                                                                            &cell.paragraphs,
593                                                                            cp_idx,
594                                                                            n,
595                                                                        );
596                                                                        (Some(b), Some(a))
597                                                                    }
598                                                                    None => (None, None),
599                                                                };
600                                                            let match_page = if depth == 0 {
601                                                                page
602                                                            } else {
603                                                                None
604                                                            };
605                                                            for (offset, length) in
606                                                                super::search_query::find_matches(
607                                                                    &cp.text,
608                                                                    query,
609                                                                    case_sensitive,
610                                                                )
611                                                            {
612                                                                let mut hit = make_at(
613                                                                    match_page,
614                                                                    &cp.text,
615                                                                    offset,
616                                                                    length,
617                                                                    None,
618                                                                    Some(TextBoxRef {
619                                                                        control: ctrl_idx,
620                                                                        paragraph: tp_idx,
621                                                                    }),
622                                                                    None,
623                                                                    cell_ctx_before.clone(),
624                                                                    cell_ctx_after.clone(),
625                                                                );
626                                                                hit.nested_depth = depth;
627                                                                hit.cell_path = path.clone();
628                                                                out.push(hit);
629                                                                if limit
630                                                                    .is_some_and(|n| out.len() >= n)
631                                                                {
632                                                                    return out;
633                                                                }
634                                                            }
635                                                            for (
636                                                                inner_control_idx,
637                                                                inner_control,
638                                                            ) in cp.controls.iter().enumerate()
639                                                            {
640                                                                match inner_control {
641                                                                    Control::Equation(equation) => {
642                                                                        for (offset, length) in super::search_query::find_matches(
643                                                                            &equation.script,
644                                                                            query,
645                                                                            case_sensitive,
646                                                                        ) {
647                                                                            let mut hit = make_at(
648                                                                                match_page,
649                                                                                &equation.script,
650                                                                                offset,
651                        length,
652                                                                                None,
653                                                                                Some(TextBoxRef {
654                                                                                    control: ctrl_idx,
655                                                                                    paragraph: tp_idx,
656                                                                                }),
657                                                                                Some(EquationRef {
658                                                                                    control: inner_control_idx,
659                                                                                }),
660                                                                                cell_ctx_before.clone(),
661                                                                                cell_ctx_after.clone(),
662                                                                            );
663                                                                            hit.nested_depth =
664                                                                                depth;
665                                                                            hit.cell_path =
666                                                                                path.clone();
667                                                                            out.push(hit);
668                                                                            if limit.is_some_and(
669                                                                                |n| out.len() >= n,
670                                                                            ) {
671                                                                                return out;
672                                                                            }
673                                                                        }
674                                                                    }
675                                                                    Control::Table(inner) => {
676                                                                        queue.push_back((
677                                                                            inner,
678                                                                            depth + 1,
679                                                                            path.clone(),
680                                                                            inner_control_idx,
681                                                                        ));
682                                                                    }
683                                                                    _ => {}
684                                                                }
685                                                            }
686                                                        }
687                                                    }
688                                                }
689                                            }
690                                            _ => {}
691                                        }
692                                    }
693                                }
694                            }
695                        }
696                        // 수식 스크립트 — 렌더 트리(EquationNode)가 아니라 IR을 직접 순회하므로
697                        // #3419(export-text/markdown 쪽 수식 텍스트화)와는 별개 경로였다.
698                        // 표 셀·글상자와 동일하게 본문 문단 순회 중 함께 검색한다.
699                        Control::Equation(eq) => {
700                            for (offset, length) in
701                                super::search_query::find_matches(&eq.script, query, case_sensitive)
702                            {
703                                out.push(make(
704                                    &eq.script,
705                                    offset,
706                                    length,
707                                    None,
708                                    None,
709                                    Some(EquationRef { control: ctrl_idx }),
710                                ));
711                                if limit.is_some_and(|n| out.len() >= n) {
712                                    return out;
713                                }
714                            }
715                        }
716                        _ => {}
717                    }
718                }
719            }
720        }
721        out
722    }
723}