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
//! 주소를 가진 문서 검색 — 매치마다 (구역·문단·**페이지**·문자 오프셋)을 돌려준다.
//!
//! 평문 추출 후 외부에서 검색하면 주소가 소멸해 근거 제시가 불가능하다. rhwp 는 조판
//! 엔진을 갖고 있어 "몇 쪽"에 답할 수 있는데, 그 답을 낼 출구가 없었다.
//!
//! 페이지 매핑 비용은 0이다 — `DocumentCore::from_bytes` 가 로드 시 `paginate()` 를
//! 끝내므로 순수 조회다. 다만 매치마다 조회하면 O(N × 페이지 아이템)이므로
//! `(구역,문단) → 페이지` 인덱스를 **한 번만** 만들어 재사용한다.
//!
//! 파서/렌더 무변경의 읽기 전용 질의(추가 기능).
use std::collections::HashMap;
use serde::Serialize;
use crate::document_core::DocumentCore;
use crate::model::control::Control;
use crate::model::paragraph::Paragraph;
use crate::renderer::pagination::PageItem;
/// 검색 매치 하나.
#[derive(Debug, Clone, Serialize)]
pub struct GrepMatch {
/// 구역 인덱스.
pub section: usize,
/// 본문 문단 인덱스 (표 셀·글상자 매치는 그 컨트롤을 담은 본문 문단).
pub paragraph: usize,
/// 0부터 시작하는 글로벌 페이지 번호. 조판에 배치되지 않은 문단이면 생략된다.
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
/// 문단 텍스트 내 매치 시작 위치 (문자 단위).
#[serde(rename = "charOffset")]
pub char_offset: usize,
/// 매치 길이 (문자 단위).
pub length: usize,
/// 매치가 속한 문단의 전체 텍스트.
pub text: String,
/// 매치 주변 발췌 (앞뒤 문맥).
pub context: String,
/// 표 셀 안의 매치면 셀 좌표. 본문 매치면 생략된다.
#[serde(skip_serializing_if = "Option::is_none")]
pub cell: Option<CellRef>,
/// 글상자 안의 매치면 글상자 좌표. 본문·표 셀 매치면 생략된다.
#[serde(skip_serializing_if = "Option::is_none")]
pub textbox: Option<TextBoxRef>,
/// 수식 스크립트 안의 매치면 수식 좌표. 표 셀·글상자 안의 수식은 해당
/// `cell`/`textbox` 좌표와 함께 제공된다.
#[serde(skip_serializing_if = "Option::is_none")]
pub equation: Option<EquationRef>,
/// `--context N` 을 준 경우 매치가 속한 문단 **앞** N개 문단의 텍스트
/// (문서/셀/글상자 경계 밖으로는 나가지 않는다 — 있는 만큼만 준다).
#[serde(rename = "contextBefore", skip_serializing_if = "Option::is_none")]
pub context_before: Option<Vec<String>>,
/// `--context N` 을 준 경우 매치가 속한 문단 **뒤** N개 문단의 텍스트.
#[serde(rename = "contextAfter", skip_serializing_if = "Option::is_none")]
pub context_after: Option<Vec<String>>,
/// [#2792] 표 안의 표에서 나온 매치면 그 중첩 깊이(바깥 표 = 0). 0 이면 생략되므로
/// 중첩이 없는 문서의 봉투는 종전과 바이트까지 같다.
///
/// 0 이 아니면 **`cell` 은 매치의 정확한 위치가 아니라 그것을 담은 바깥 셀 문단**을
/// 가리킨다 — 중첩 경로를 그대로 싣는 정밀 주소는 별도 축(#2792 §경로 기반 선택)이다.
#[serde(rename = "nestedDepth", skip_serializing_if = "is_zero")]
pub nested_depth: usize,
}
/// 중첩이 없는 흔한 경우에 필드를 아예 빼기 위한 serde 술어.
fn is_zero(value: &usize) -> bool {
*value == 0
}
/// 병적으로 깊은 중첩(손상/악의적 문서)에서 순회가 스택을 태우지 않게 하는 상한.
/// `table_extract::MAX_NEST_DEPTH` / `explain` / `hidden_text` / `chart_extract` /
/// `clipboard` 와 같은 값 — 깊이 0..=7 만 방문한다.
const MAX_NEST_DEPTH: usize = 8;
/// 표 셀 매치의 좌표.
#[derive(Debug, Clone, Serialize)]
pub struct CellRef {
/// 표를 담은 본문 문단의 컨트롤 인덱스.
pub control: usize,
/// 셀 인덱스.
pub cell: usize,
/// 셀 안의 문단 인덱스.
pub paragraph: usize,
}
/// 글상자 매치의 좌표.
#[derive(Debug, Clone, Serialize)]
pub struct TextBoxRef {
/// 글상자를 담은 본문 문단의 컨트롤 인덱스.
pub control: usize,
/// 글상자 안의 문단 인덱스.
pub paragraph: usize,
}
/// 수식 매치의 좌표.
#[derive(Debug, Clone, Serialize)]
pub struct EquationRef {
/// 수식을 담은 문단(본문·셀·글상자)의 컨트롤 인덱스.
pub control: usize,
}
/// 매치 주변 발췌를 만든다 (앞뒤 `WINDOW` 문자).
fn make_context(text: &str, offset: usize, length: usize) -> String {
const WINDOW: usize = 40;
let chars: Vec<char> = text.chars().collect();
let start = offset.saturating_sub(WINDOW);
let end = (offset + length + WINDOW).min(chars.len());
let mut out = String::new();
if start > 0 {
out.push('…');
}
out.extend(chars[start..end].iter());
if end < chars.len() {
out.push('…');
}
out
}
/// 매치가 속한 문단을 담은 `paragraphs` 슬라이스에서 `idx` 앞뒤 `n`개 문단의
/// 텍스트를 뽑는다. 경계(첫/마지막 문단)에서는 있는 만큼만 준다 — 범위 밖으로
/// 나가지 않는다.
fn context_window(paragraphs: &[Paragraph], idx: usize, n: usize) -> (Vec<String>, Vec<String>) {
let start = idx.saturating_sub(n);
let before = paragraphs[start..idx]
.iter()
.map(|p| p.text.clone())
.collect();
let end = (idx + 1 + n).min(paragraphs.len());
let after = paragraphs[idx + 1..end]
.iter()
.map(|p| p.text.clone())
.collect();
(before, after)
}
impl DocumentCore {
/// `(구역, 문단) → 글로벌 페이지` 인덱스를 한 번에 만든다.
///
/// 한 문단이 여러 쪽에 걸치면 **처음 등장한 쪽**을 쓴다 — 인용은 시작 위치가 기준이다.
///
/// [#3719] `extract_data` 도 같은 인덱스를 쓴다 — 주소가 붙은 질의는 "몇 쪽"의 정의를
/// 하나만 가져야 한다. 복제하면 두 명령이 서로 다른 쪽을 답하게 된다.
pub(crate) fn build_paragraph_page_index(&self) -> HashMap<(usize, usize), u32> {
let mut index: HashMap<(usize, usize), u32> = HashMap::new();
let mut global_offset = 0u32;
for (sec_idx, pr) in self.pagination.iter().enumerate() {
for (local_i, page) in pr.pages.iter().enumerate() {
let global_page = global_offset + local_i as u32;
for col in &page.column_contents {
for item in &col.items {
let para_index = match item {
PageItem::FullParagraph { para_index }
| PageItem::PartialParagraph { para_index, .. }
| PageItem::Table { para_index, .. }
| PageItem::PartialTable { para_index, .. }
| PageItem::Shape { para_index, .. } => Some(*para_index),
_ => None,
};
if let Some(p) = para_index {
index.entry((sec_idx, p)).or_insert(global_page);
}
}
}
}
global_offset += pr.pages.len() as u32;
}
index
}
/// `(구역, 문단, 컨트롤) → [(시작 행, 끝 행, 글로벌 페이지)]` 인덱스.
///
/// [#3403] 표가 쪽을 넘겨 이어지면 뒤쪽 행의 셀은 다음 쪽에 렌더되는데, 문단 단위
/// 페이지 인덱스는 표 호스트 문단의 **첫 쪽**만 알고 있다. 그래서 분할 표 셀 매치가
/// 한 쪽 앞을 가리켰다(RAG 인용이 엉뚱한 쪽을 렌더). 행 범위를 함께 들고 있으면
/// 셀의 행 번호로 실제 렌더 쪽을 고를 수 있다.
///
/// 분할되지 않은 표(`PageItem::Table`)도 전 행 범위로 함께 넣어, 셀 경로가 항상 같은
/// 조회를 쓰도록 한다.
pub(crate) fn build_table_row_page_index(
&self,
) -> HashMap<(usize, usize, usize), Vec<(usize, usize, u32)>> {
let mut index: HashMap<(usize, usize, usize), Vec<(usize, usize, u32)>> = HashMap::new();
let mut global_offset = 0u32;
for (sec_idx, pr) in self.pagination.iter().enumerate() {
for (local_i, page) in pr.pages.iter().enumerate() {
let global_page = global_offset + local_i as u32;
for col in &page.column_contents {
for item in &col.items {
match item {
PageItem::Table {
para_index,
control_index,
} => {
index
.entry((sec_idx, *para_index, *control_index))
.or_default()
.push((0, usize::MAX, global_page));
}
PageItem::PartialTable {
para_index,
control_index,
start_row,
end_row,
..
} => {
index
.entry((sec_idx, *para_index, *control_index))
.or_default()
.push((*start_row, *end_row, global_page));
}
_ => {}
}
}
}
}
global_offset += pr.pages.len() as u32;
}
index
}
/// 문서를 검색해 주소가 붙은 매치 목록을 돌려준다.
///
/// 본문·표 셀·글상자·중첩 표를 순회한다. 치환 계열은 별도 검색 순회
/// (`search_all_text_native`/`replace_all_native`)와 범위·순서를 맞춘다.
/// `limit` 이 `Some` 이면 그 개수에서 멈춘다.
///
/// 기존 계약과 완전히 동일한 얇은 래퍼다(`context: None`) — `grep_with_context` 로
/// 위임한다.
pub fn grep(&self, query: &str, case_sensitive: bool, limit: Option<usize>) -> Vec<GrepMatch> {
self.grep_with_context(query, case_sensitive, limit, None)
}
/// `grep` 과 같지만 `context` 가 `Some(n)` 이면 매치가 속한 문단의 앞뒤 `n`개
/// 문단 텍스트를 `contextBefore`/`contextAfter` 로 함께 돌려준다(표 셀·글상자
/// 매치는 그 컨테이너 안에서, 본문 매치는 구역 문단 목록 안에서 앞뒤를 센다).
pub fn grep_with_context(
&self,
query: &str,
case_sensitive: bool,
limit: Option<usize>,
context: Option<usize>,
) -> Vec<GrepMatch> {
if query.is_empty() {
return Vec::new();
}
let page_index = self.build_paragraph_page_index();
let table_row_pages = self.build_table_row_page_index();
let mut out: Vec<GrepMatch> = Vec::new();
for (sec_idx, section) in self.document.sections.iter().enumerate() {
for (para_idx, para) in section.paragraphs.iter().enumerate() {
let page = page_index.get(&(sec_idx, para_idx)).copied();
let make_at =
|page: Option<u32>,
text: &str,
offset: usize,
length: usize,
cell: Option<CellRef>,
textbox: Option<TextBoxRef>,
equation: Option<EquationRef>,
context_before: Option<Vec<String>>,
context_after: Option<Vec<String>>| GrepMatch {
section: sec_idx,
paragraph: para_idx,
page,
char_offset: offset,
length,
text: text.to_string(),
context: make_context(text, offset, length),
cell,
textbox,
equation,
context_before,
context_after,
nested_depth: 0,
};
// 본문 문단 기준 컨텍스트 — 구역 문단 목록 안에서 앞뒤를 센다.
let (body_ctx_before, body_ctx_after) = match context {
Some(n) => {
let (b, a) = context_window(§ion.paragraphs, para_idx, n);
(Some(b), Some(a))
}
None => (None, None),
};
let make = |text: &str,
offset: usize,
length: usize,
cell: Option<CellRef>,
textbox: Option<TextBoxRef>,
equation: Option<EquationRef>| {
make_at(
page,
text,
offset,
length,
cell,
textbox,
equation,
body_ctx_before.clone(),
body_ctx_after.clone(),
)
};
// [#3403] 분할 표 셀은 호스트 문단의 첫 쪽이 아니라 그 행이 실제로 렌더되는
// 쪽을 쓴다. 행 범위를 못 찾으면 종전 문단 쪽으로 물러선다.
let cell_page = |ctrl_idx: usize, row: usize| -> Option<u32> {
table_row_pages
.get(&(sec_idx, para_idx, ctrl_idx))
.and_then(|ranges| {
ranges
.iter()
.find(|(start, end, _)| row >= *start && row < *end)
.map(|(_, _, page)| *page)
})
.or(page)
};
for (offset, length) in
super::search_query::find_matches(¶.text, query, case_sensitive)
{
out.push(make(¶.text, offset, length, None, None, None));
if limit.is_some_and(|n| out.len() >= n) {
return out;
}
}
for (ctrl_idx, ctrl) in para.controls.iter().enumerate() {
match ctrl {
Control::Table(table) => {
// [#2792] 셀 안의 표까지 내려간다. 종전에는 셀 문단 컨트롤
// 순회가 Equation 만 봐서 중첩 표가 조용히 버려졌다.
let mut queue = std::collections::VecDeque::new();
queue.push_back((table, 0usize, None::<CellRef>));
while let Some((current, depth, host)) = queue.pop_front() {
if depth >= MAX_NEST_DEPTH {
continue;
}
for (cell_idx, cell) in current.cells.iter().enumerate() {
for (cp_idx, cp) in cell.paragraphs.iter().enumerate() {
let (cell_ctx_before, cell_ctx_after) = match context {
Some(n) => {
let (b, a) =
context_window(&cell.paragraphs, cp_idx, n);
(Some(b), Some(a))
}
None => (None, None),
};
let addr = host.clone().unwrap_or(CellRef {
control: ctrl_idx,
cell: cell_idx,
paragraph: cp_idx,
});
let match_page = if depth == 0 {
cell_page(ctrl_idx, cell.row as usize)
} else {
None
};
for (offset, length) in super::search_query::find_matches(
&cp.text,
query,
case_sensitive,
) {
let mut hit = make_at(
match_page,
&cp.text,
offset,
length,
Some(addr.clone()),
None,
None,
cell_ctx_before.clone(),
cell_ctx_after.clone(),
);
hit.nested_depth = depth;
out.push(hit);
if limit.is_some_and(|n| out.len() >= n) {
return out;
}
}
for (equation_idx, nested_control) in
cp.controls.iter().enumerate()
{
match nested_control {
Control::Equation(equation) => {
for (offset, length) in
super::search_query::find_matches(
&equation.script,
query,
case_sensitive,
)
{
let mut hit = make_at(
match_page,
&equation.script,
offset,
length,
Some(addr.clone()),
None,
Some(EquationRef {
control: equation_idx,
}),
cell_ctx_before.clone(),
cell_ctx_after.clone(),
);
hit.nested_depth = depth;
out.push(hit);
if limit.is_some_and(|n| out.len() >= n) {
return out;
}
}
}
Control::Table(inner) => {
queue.push_back((
inner,
depth + 1,
Some(addr.clone()),
));
}
_ => {}
}
}
}
}
}
}
Control::Shape(shape) => {
if let Some(tb) =
crate::document_core::helpers::get_textbox_from_shape(shape)
{
for (tp_idx, tp) in tb.paragraphs.iter().enumerate() {
// 글상자 안의 매치는 글상자 문단 목록 안에서 앞뒤를
// 센다(본문 문단 목록이 아니다).
let (tb_ctx_before, tb_ctx_after) = match context {
Some(n) => {
let (b, a) = context_window(&tb.paragraphs, tp_idx, n);
(Some(b), Some(a))
}
None => (None, None),
};
for (offset, length) in super::search_query::find_matches(
&tp.text,
query,
case_sensitive,
) {
out.push(make_at(
page,
&tp.text,
offset,
length,
None,
Some(TextBoxRef {
control: ctrl_idx,
paragraph: tp_idx,
}),
None,
tb_ctx_before.clone(),
tb_ctx_after.clone(),
));
if limit.is_some_and(|n| out.len() >= n) {
return out;
}
}
for (nested_control_idx, nested_control) in
tp.controls.iter().enumerate()
{
match nested_control {
Control::Equation(equation) => {
for (offset, length) in
super::search_query::find_matches(
&equation.script,
query,
case_sensitive,
)
{
out.push(make_at(
page,
&equation.script,
offset,
length,
None,
Some(TextBoxRef {
control: ctrl_idx,
paragraph: tp_idx,
}),
Some(EquationRef {
control: nested_control_idx,
}),
tb_ctx_before.clone(),
tb_ctx_after.clone(),
));
if limit.is_some_and(|n| out.len() >= n) {
return out;
}
}
}
Control::Table(table) => {
// 글상자 안 표도 검색 범위에 포함한다. flat `cell`
// 주소로는 글상자 내부 표의 정확한 경로를 표현할 수
// 없으므로, match에는 글상자 호스트를 싣는다.
let mut queue = std::collections::VecDeque::new();
queue.push_back((table, 0usize));
while let Some((current, depth)) = queue.pop_front()
{
if depth >= MAX_NEST_DEPTH {
continue;
}
for cell in current.cells.iter() {
for (cp_idx, cp) in
cell.paragraphs.iter().enumerate()
{
let (cell_ctx_before, cell_ctx_after) =
match context {
Some(n) => {
let (b, a) = context_window(
&cell.paragraphs,
cp_idx,
n,
);
(Some(b), Some(a))
}
None => (None, None),
};
let match_page = if depth == 0 {
page
} else {
None
};
for (offset, length) in
super::search_query::find_matches(
&cp.text,
query,
case_sensitive,
)
{
let mut hit = make_at(
match_page,
&cp.text,
offset,
length,
None,
Some(TextBoxRef {
control: ctrl_idx,
paragraph: tp_idx,
}),
None,
cell_ctx_before.clone(),
cell_ctx_after.clone(),
);
hit.nested_depth = depth;
out.push(hit);
if limit
.is_some_and(|n| out.len() >= n)
{
return out;
}
}
for (
inner_control_idx,
inner_control,
) in cp.controls.iter().enumerate()
{
match inner_control {
Control::Equation(equation) => {
for (offset, length) in super::search_query::find_matches(
&equation.script,
query,
case_sensitive,
) {
let mut hit = make_at(
match_page,
&equation.script,
offset,
length,
None,
Some(TextBoxRef {
control: ctrl_idx,
paragraph: tp_idx,
}),
Some(EquationRef {
control: inner_control_idx,
}),
cell_ctx_before.clone(),
cell_ctx_after.clone(),
);
hit.nested_depth =
depth;
out.push(hit);
if limit.is_some_and(
|n| out.len() >= n,
) {
return out;
}
}
}
Control::Table(inner) => {
queue.push_back((
inner,
depth + 1,
));
}
_ => {}
}
}
}
}
}
}
_ => {}
}
}
}
}
}
// 수식 스크립트 — 렌더 트리(EquationNode)가 아니라 IR을 직접 순회하므로
// #3419(export-text/markdown 쪽 수식 텍스트화)와는 별개 경로였다.
// 표 셀·글상자와 동일하게 본문 문단 순회 중 함께 검색한다.
Control::Equation(eq) => {
for (offset, length) in
super::search_query::find_matches(&eq.script, query, case_sensitive)
{
out.push(make(
&eq.script,
offset,
length,
None,
None,
Some(EquationRef { control: ctrl_idx }),
));
if limit.is_some_and(|n| out.len() >= n) {
return out;
}
}
}
_ => {}
}
}
}
}
out
}
}