applyLineFilters applies regex filter/exclude and line-range clipping. Returns the filtered text. An empty filter matches all lines; an empty exclude drops none.
(content, filter, exclude string, fromLine, toLine int)
| 464 | // Returns the filtered text. An empty filter matches all lines; an empty |
| 465 | // exclude drops none. |
| 466 | func applyLineFilters(content, filter, exclude string, fromLine, toLine int) (string, error) { |
| 467 | // Fast path: no line operations needed. |
| 468 | if filter == "" && exclude == "" && fromLine <= 0 && toLine <= 0 { |
| 469 | return content, nil |
| 470 | } |
| 471 | |
| 472 | var keepRE, dropRE *regexp.Regexp |
| 473 | var err error |
| 474 | if filter != "" { |
| 475 | keepRE, err = regexp.Compile(filter) |
| 476 | if err != nil { |
| 477 | return "", fmt.Errorf("invalid filter regex %q: %w", filter, err) |
| 478 | } |
| 479 | } |
| 480 | if exclude != "" { |
| 481 | dropRE, err = regexp.Compile(exclude) |
| 482 | if err != nil { |
| 483 | return "", fmt.Errorf("invalid exclude regex %q: %w", exclude, err) |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | lines := strings.Split(content, "\n") |
| 488 | kept := make([]string, 0, len(lines)) |
| 489 | for _, line := range lines { |
| 490 | if keepRE != nil && !keepRE.MatchString(line) { |
| 491 | continue |
| 492 | } |
| 493 | if dropRE != nil && dropRE.MatchString(line) { |
| 494 | continue |
| 495 | } |
| 496 | kept = append(kept, line) |
| 497 | } |
| 498 | |
| 499 | // Apply line range AFTER filters so the agent's from/to is relative to |
| 500 | // the filtered view (which is more useful for paging). |
| 501 | if fromLine > 0 || toLine > 0 { |
| 502 | start := 0 |
| 503 | if fromLine > 0 { |
| 504 | start = fromLine - 1 |
| 505 | } |
| 506 | if start > len(kept) { |
| 507 | start = len(kept) |
| 508 | } |
| 509 | end := len(kept) |
| 510 | if toLine > 0 && toLine < end { |
| 511 | end = toLine |
| 512 | } |
| 513 | if end < start { |
| 514 | end = start |
| 515 | } |
| 516 | kept = kept[start:end] |
| 517 | } |
| 518 | |
| 519 | return strings.Join(kept, "\n"), nil |
| 520 | } |
| 521 | |
| 522 | // extractText extracts readable text from HTML, removing scripts, styles, and tags. |
| 523 | func extractText(htmlContent string) string { |