ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
grep.c
Go to the documentation of this file.
1
15
16#include <ascii-chat/log/grep.h>
17#include <options/colorscheme.h>
18#include <ascii-chat/common.h>
19#include <ascii-chat/log/log.h>
20#include <libplatform/lifecycle.h>
24#include <libplatform/terminal.h>
25#include <libplatform/thread.h>
27
28#include <string.h>
29#include <stdint.h>
30
31#ifdef _WIN32
32#include <windows.h>
33#else
34#include <sched.h>
35#endif
36
54
58static struct {
62 bool enabled;
63 tls_key_t match_data_key;
65
66 // Context line buffering
67 char **line_buffer;
72
73 // Save/restore for interactive grep
78
79} g_filter_state = {
80 .patterns = NULL,
81 .pattern_count = 0,
82 .pattern_capacity = 0,
83 .enabled = false,
84 .match_data_lifecycle = LIFECYCLE_INIT,
85 .line_buffer = NULL,
86 .buffer_size = 0,
87 .buffer_pos = 0,
88 .lines_after_match = 0,
89 .max_context_after = 0,
90 .saved_patterns = NULL,
91 .saved_pattern_count = 0,
92 .saved_pattern_capacity = 0,
93 .saved_enabled = false,
94};
95
99static void destroy_match_data(void *data) {
100 if (data) {
101 pcre2_match_data_free((pcre2_match_data *)data);
102 }
103}
104
108static void create_match_data_key(void) {
109 platform_tls_key_create(&g_filter_state.match_data_key, destroy_match_data);
110}
111
113static void get_highlight_color(uint8_t *r, uint8_t *g, uint8_t *b) {
114 *r = *g = *b = colorscheme_highlight_background();
115}
116
124static size_t map_plain_to_colored_pos(const char *colored_text, size_t char_pos) {
125 size_t byte_pos = 0;
126 size_t chars_seen = 0;
127
128 while (colored_text[byte_pos] != '\0' && chars_seen < char_pos) {
129 // Check for ANSI escape sequence (handle all escape types, not just CSI)
130 if (colored_text[byte_pos] == '\x1b') {
131 byte_pos++;
132 // Check if there's a next byte before reading it
133 if (colored_text[byte_pos] == '\0') {
134 // Incomplete escape sequence at end of string, just break
135 break;
136 }
137 unsigned char next = (unsigned char)colored_text[byte_pos];
138 if (next == '[') {
139 // CSI sequence: \x1b[...final_byte (where final byte is 0x40-0x7E)
140 byte_pos++;
141 while (colored_text[byte_pos] != '\0') {
142 unsigned char c = (unsigned char)colored_text[byte_pos];
143 byte_pos++;
144 // Final byte ends the sequence (0x40-0x7E)
145 if (c >= 0x40 && c <= 0x7E) {
146 break;
147 }
148 }
149 } else if (next >= 0x40 && next <= 0x7E) {
150 // 2-byte Fe sequence: \x1b + final_byte (e.g., \x1b7, \x1b8)
151 byte_pos++;
152 } else if (next == '(' || next == ')' || next == '*' || next == '+') {
153 // Designate character set sequences: \x1b( + charset (3 bytes total)
154 byte_pos++; // skip designator
155 if (colored_text[byte_pos] != '\0') {
156 byte_pos++; // skip charset ID
157 }
158 } else {
159 // Unknown escape sequence type, try to skip conservatively
160 if (colored_text[byte_pos] != '\0') {
161 byte_pos++;
162 }
163 }
164 } else {
165 // Regular character - decode UTF-8 to get byte length
166 uint32_t codepoint;
167 int utf8_len = utf8_decode((const uint8_t *)(colored_text + byte_pos), &codepoint);
168 if (utf8_len < 0) {
169 utf8_len = 1; // Invalid UTF-8, treat as single byte
170 }
171
172 // Advance by all bytes of this UTF-8 character
173 byte_pos += utf8_len;
174
175 // Match offsets from PCRE2 and strstr are measured in bytes.
176 chars_seen += (size_t)utf8_len;
177 }
178 }
179
180 return byte_pos;
181}
182
186static void ensure_match_data_key_initialized(void) {
187 if (!lifecycle_init_once(&g_filter_state.match_data_lifecycle)) {
188 return; // Already initialized, spin-wait completed
189 }
190 // Winner of init_once - do the initialization work
191 create_match_data_key();
192 lifecycle_init_commit(&g_filter_state.match_data_lifecycle);
193}
194
198static pcre2_match_data *get_thread_match_data(void) {
199 ensure_match_data_key_initialized();
200
201 pcre2_match_data *data = platform_tls_get(g_filter_state.match_data_key);
202 if (!data) {
203 // Find any regex pattern to create match data from
204 for (int i = 0; i < g_filter_state.pattern_count; i++) {
205 if (g_filter_state.patterns[i].compiled) {
206 pcre2_code *code = g_filter_state.patterns[i].compiled;
207 if (code) {
208 data = pcre2_match_data_create_from_pattern(code, NULL);
209 if (data) {
210 platform_tls_set(g_filter_state.match_data_key, data);
211 break;
212 }
213 }
214 }
215 }
216 }
217
218 return data;
219}
220
221// Use the shared parse_result_t from filter.h
223
266 parse_result_t result = {0};
267 result.pcre2_options = PCRE2_UTF | PCRE2_UCP; // Default: UTF-8 mode
268
269 if (!input || strlen(input) == 0) {
270 return result; // Invalid: empty pattern
271 }
272
273 size_t len = strlen(input);
274 const char *closing_slash = NULL;
275 const char *pattern_start = input;
276
277 // Check if pattern uses /pattern/flags format (explicit)
278 if (input[0] == '/') {
279 // Format 1: /pattern/flags
280 if (len < 3) {
281 return result; // Invalid: too short for /pattern/ format
282 }
283
284 // Find closing slash - don't treat backslash as an escape character
285 // (backslashes are regex escapes, not delimiter escapes)
286 closing_slash = strchr(input + 1, '/');
287 if (!closing_slash) {
288 return result; // Invalid: missing closing /
289 }
290
291 pattern_start = input + 1;
292 } else {
293 // Check for pattern/flags format (implicit, no leading slash)
294 // Find the last forward slash to use as delimiter
295 closing_slash = strrchr(input, '/');
296
297 const char *implicit_flags = closing_slash ? closing_slash + 1 : NULL;
298 bool implicit_flags_valid = closing_slash && closing_slash > input && *implicit_flags != '\0';
299 if (implicit_flags_valid) {
300 for (const char *flag = implicit_flags; *flag; flag++) {
301 if (!strchr("imsxgIF", *flag) && *flag != 'A' && *flag != 'B' && *flag != 'C' && !(*flag >= '0' && *flag <= '9')) {
302 implicit_flags_valid = false;
303 break;
304 }
305 }
306 }
307
308 if (implicit_flags_valid) {
309 // There's at least one slash (not at the beginning)
310 // Try to parse as pattern/flags format
311 pattern_start = input;
312 } else {
313 // No slash or slash at beginning - treat as plain pattern
314 closing_slash = NULL;
315 }
316 }
317
318 if (closing_slash) {
319 // Extract pattern between start and closing slash
320 size_t pattern_len = (size_t)(closing_slash - pattern_start);
321 if (pattern_len == 0) {
322 return result; // Invalid: empty pattern
323 }
324 if (pattern_len >= sizeof(result.pattern)) {
325 pattern_len = sizeof(result.pattern) - 1;
326 }
327 memcpy(result.pattern, pattern_start, pattern_len);
328 result.pattern[pattern_len] = '\0';
329
330 // Parse flags after closing slash
331 // First pass: check for F flag
332 const char *flags = closing_slash + 1;
333 bool has_F_flag = (strchr(flags, 'F') != NULL);
334
335 // Parse all flags
336 for (const char *p = flags; *p; p++) {
337 char c = *p;
338
339 // Single-character flags
340 if (c == 'i') {
341 result.pcre2_options |= PCRE2_CASELESS;
342 result.case_insensitive = true;
343 } else if (c == 'm') {
344 result.pcre2_options |= PCRE2_MULTILINE;
345 } else if (c == 's') {
346 result.pcre2_options |= PCRE2_DOTALL;
347 } else if (c == 'x') {
348 result.pcre2_options |= PCRE2_EXTENDED;
349 } else if (c == 'g') {
350 result.global_flag = true;
351 } else if (c == 'I') {
352 result.invert = true;
353 } else if (c == 'F') {
354 result.is_fixed_string = true;
355 }
356 // Multi-character flags with integers
357 else if (c == 'A') {
358 p++; // Move to digits
359 int num = 0;
360 while (*p >= '0' && *p <= '9') {
361 num = num * 10 + (*p - '0');
362 p++;
363 }
364 p--; // Back up one (for loop will increment)
365 result.context_after = (num > 0) ? num : 1; // Default to 1 if no number
366 } else if (c == 'B') {
367 p++;
368 int num = 0;
369 while (*p >= '0' && *p <= '9') {
370 num = num * 10 + (*p - '0');
371 p++;
372 }
373 p--;
374 result.context_before = (num > 0) ? num : 1;
375 } else if (c == 'C') {
376 p++;
377 int num = 0;
378 while (*p >= '0' && *p <= '9') {
379 num = num * 10 + (*p - '0');
380 p++;
381 }
382 p--;
383 int ctx = (num > 0) ? num : 1;
384 result.context_before = ctx;
385 result.context_after = ctx;
386 } else {
387 // Invalid flag character - only error if not using F flag
388 if (!has_F_flag) {
389 return result; // Invalid
390 }
391 // Otherwise ignore invalid flags (they're part of the fixed string context)
392 }
393 }
394 } else {
395 // Format 3: Plain pattern without slashes (treat as regex, no flags)
396 size_t pattern_len = len;
397 if (pattern_len >= sizeof(result.pattern)) {
398 pattern_len = sizeof(result.pattern) - 1;
399 }
400 memcpy(result.pattern, input, pattern_len);
401 result.pattern[pattern_len] = '\0';
402
403 // No flags for plain format - just use default options
404 // (PCRE2_UTF | PCRE2_UCP already set at the top)
405 }
406
407 result.valid = true;
408 return result;
409}
410
411asciichat_error_t grep_init(const char *pattern) {
412 // Reject NULL or empty patterns
413 if (!pattern) {
414 return SET_ERRNO(ERROR_INVALID_PARAM, "Pattern cannot be NULL");
415 }
416 if (strlen(pattern) == 0) {
417 return SET_ERRNO(ERROR_INVALID_PARAM, "Pattern cannot be empty");
418 }
419
420 // Parse pattern
421 parse_result_t parsed = grep_parse_pattern(pattern);
422 if (!parsed.valid) {
423 log_error("Invalid --grep pattern format: \"%s\"", pattern);
424 log_error("Use /pattern/flags format (e.g., \"/query/ig\") or plain regex (e.g., \"query\")");
425 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid --grep pattern format");
426 }
427
428 // Allocate or expand pattern array
429 if (g_filter_state.pattern_count >= g_filter_state.pattern_capacity) {
430 int new_capacity = (g_filter_state.pattern_capacity == 0) ? 4 : g_filter_state.pattern_capacity * 2;
431 grep_pattern_t *new_patterns = SAFE_REALLOC(g_filter_state.patterns, new_capacity * sizeof(grep_pattern_t), grep_pattern_t *);
432 if (!new_patterns) {
433 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate pattern array");
434 }
435 g_filter_state.patterns = new_patterns;
436 g_filter_state.pattern_capacity = new_capacity;
437 }
438
439 // Add new pattern
440 grep_pattern_t *new_pat = &g_filter_state.patterns[g_filter_state.pattern_count];
441 memset(new_pat, 0, sizeof(*new_pat));
442
443 // Make a copy of the original pattern string (argv pointers may be deallocated)
444 char *original_copy = SAFE_MALLOC(strlen(pattern) + 1, char *);
445 if (!original_copy) {
446 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate original pattern string");
447 }
448 memcpy(original_copy, pattern, strlen(pattern) + 1);
449 new_pat->original = original_copy;
450
451 new_pat->parsed_pattern = SAFE_MALLOC(strlen(parsed.pattern) + 1, char *);
452 if (!new_pat->parsed_pattern) {
453 SAFE_FREE(original_copy);
454 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate pattern string");
455 }
456 memcpy(new_pat->parsed_pattern, parsed.pattern, strlen(parsed.pattern) + 1);
457
458 new_pat->is_fixed_string = parsed.is_fixed_string;
459 new_pat->case_insensitive = parsed.case_insensitive;
460 new_pat->invert = parsed.invert;
461 new_pat->global_flag = parsed.global_flag;
462 new_pat->context_before = parsed.context_before;
463 new_pat->context_after = parsed.context_after;
464
465 // Compile regex (skip for fixed strings)
466 if (!parsed.is_fixed_string) {
467 new_pat->compiled = asciichat_pcre2_compile(parsed.pattern, parsed.pcre2_options);
468 if (!new_pat->compiled) {
469 SAFE_FREE(original_copy);
470 SAFE_FREE(new_pat->parsed_pattern);
471 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to compile regex pattern");
472 }
473
474 // Validate compilation
475 pcre2_code *code = new_pat->compiled;
476 if (!code) {
477 SAFE_FREE(new_pat->parsed_pattern);
478 return SET_ERRNO(ERROR_INVALID_PARAM, "Regex compilation failed");
479 }
480 }
481
482 g_filter_state.pattern_count++;
483
484 // Update context buffer size if needed
485 if (parsed.context_before > g_filter_state.buffer_size) {
486 // Reallocate line buffer
487 char **new_buffer = SAFE_REALLOC(g_filter_state.line_buffer, parsed.context_before * sizeof(char *), char **);
488 if (!new_buffer) {
489 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate context line buffer");
490 }
491 // Initialize new slots
492 for (int i = g_filter_state.buffer_size; i < parsed.context_before; i++) {
493 new_buffer[i] = NULL;
494 }
495 g_filter_state.line_buffer = new_buffer;
496 g_filter_state.buffer_size = parsed.context_before;
497 }
498
499 // Update max context_after
500 if (parsed.context_after > g_filter_state.max_context_after) {
501 g_filter_state.max_context_after = parsed.context_after;
502 }
503
504 g_filter_state.enabled = true;
505 log_info("Added --grep pattern #%d: %s", g_filter_state.pattern_count, pattern);
506
507 return ASCIICHAT_OK;
508}
509
510bool grep_should_output(const char *log_line, size_t *match_start, size_t *match_len) {
511 // Reject NULL lines
512 if (!log_line) {
513 if (match_start)
514 *match_start = 0;
515 if (match_len)
516 *match_len = 0;
517 return false;
518 }
519
520 // If filtering disabled, output everything
521 if (!g_filter_state.enabled) {
522 return true;
523 }
524
525 // Check if we're in "context after" mode (outputting lines after a match)
526 if (g_filter_state.lines_after_match > 0) {
527 g_filter_state.lines_after_match--;
528 *match_start = 0;
529 *match_len = 0;
530
531 // Store in buffer even during context-after mode
532 if (g_filter_state.buffer_size > 0) {
533 SAFE_FREE(g_filter_state.line_buffer[g_filter_state.buffer_pos]);
534 size_t line_len = strlen(log_line) + 1;
535 g_filter_state.line_buffer[g_filter_state.buffer_pos] = SAFE_MALLOC(line_len, char *);
536 if (g_filter_state.line_buffer[g_filter_state.buffer_pos]) {
537 memcpy(g_filter_state.line_buffer[g_filter_state.buffer_pos], log_line, line_len);
538 }
539 g_filter_state.buffer_pos = (g_filter_state.buffer_pos + 1) % g_filter_state.buffer_size;
540 }
541
542 return true; // Output context line
543 }
544
545 pcre2_match_data *match_data = get_thread_match_data();
546 size_t line_len = strlen(log_line);
547
548 // Try each pattern (OR logic)
549 bool any_match = false;
550 grep_pattern_t *matched_pattern = NULL;
551
552 for (int i = 0; i < g_filter_state.pattern_count; i++) {
553 grep_pattern_t *pat = &g_filter_state.patterns[i];
554 bool this_match = false;
555
556 if (pat->is_fixed_string) {
557 // Fixed string matching (with optional case-insensitive support)
558 const char *found;
559 if (pat->case_insensitive) {
560 // Unicode-aware case-insensitive search
561 found = utf8_strcasestr(log_line, pat->parsed_pattern);
562 } else {
563 // Case-sensitive search
564 found = strstr(log_line, pat->parsed_pattern);
565 }
566
567 if (found) {
568 this_match = true;
569 if (!matched_pattern) {
570 *match_start = (size_t)(found - log_line);
571 *match_len = strlen(pat->parsed_pattern);
572 matched_pattern = pat;
573 }
574 }
575 } else {
576 // Regex matching
577 if (!match_data || !pat->compiled) {
578 continue;
579 }
580
581 pcre2_code *code = pat->compiled;
582 if (!code) {
583 continue;
584 }
585
586 int rc = asciichat_pcre2_match(code, (PCRE2_SPTR)log_line, line_len, 0, 0, match_data, NULL);
587 if (rc >= 0) {
588 this_match = true;
589 if (!matched_pattern) {
590 PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
591 *match_start = (size_t)ovector[0];
592 *match_len = (size_t)(ovector[1] - ovector[0]);
593 matched_pattern = pat;
594 }
595 }
596 }
597
598 // Apply invert flag
599 if (pat->invert) {
600 this_match = !this_match;
601 }
602
603 if (this_match) {
604 any_match = true;
605 // Update matched_pattern if this one has more context
606 if (!matched_pattern || (pat->context_before + pat->context_after) > (matched_pattern->context_before + matched_pattern->context_after)) {
607 matched_pattern = pat;
608 }
609 }
610 }
611
612 // If any pattern matched
613 if (any_match && matched_pattern) {
614 // Output context_before lines from circular buffer
615 if (matched_pattern->context_before > 0 && g_filter_state.buffer_size > 0) {
616 int num_lines = (matched_pattern->context_before < g_filter_state.buffer_size) ? matched_pattern->context_before : g_filter_state.buffer_size;
617
618 // Calculate starting position in circular buffer
619 int start_pos = (g_filter_state.buffer_pos - num_lines + g_filter_state.buffer_size) % g_filter_state.buffer_size;
620
621 // Output buffered lines
622 for (int i = 0; i < num_lines; i++) {
623 int pos = (start_pos + i) % g_filter_state.buffer_size;
624 if (g_filter_state.line_buffer[pos]) {
625 fprintf(stderr, "%s\n", g_filter_state.line_buffer[pos]);
626 }
627 }
628 }
629
630 // Set up context_after counter
631 if (matched_pattern->context_after > 0) {
632 g_filter_state.lines_after_match = matched_pattern->context_after;
633 }
634
635 return true; // Match found, output line
636 }
637
638 // No match - store in context buffer for potential future use
639 if (g_filter_state.buffer_size > 0) {
640 SAFE_FREE(g_filter_state.line_buffer[g_filter_state.buffer_pos]);
641 size_t line_len_copy = strlen(log_line) + 1;
642 g_filter_state.line_buffer[g_filter_state.buffer_pos] = SAFE_MALLOC(line_len_copy, char *);
643 if (g_filter_state.line_buffer[g_filter_state.buffer_pos]) {
644 memcpy(g_filter_state.line_buffer[g_filter_state.buffer_pos], log_line, line_len_copy);
645 }
646 g_filter_state.buffer_pos = (g_filter_state.buffer_pos + 1) % g_filter_state.buffer_size;
647 }
648
649 return false; // No match, suppress line
650}
651
652char *grep_highlight_colored_copy(const char *colored_text, const char *plain_text, size_t match_start, size_t match_len) {
653 const char *result = grep_highlight_colored(colored_text, plain_text, match_start, match_len);
654 if (result) {
655 size_t result_len = strlen(result) + 1;
656 char *copy = SAFE_MALLOC(result_len, char *);
657 if (copy) {
658 memcpy(copy, result, result_len);
659 return copy;
660 }
661 }
662 return NULL;
663}
664
665const char *grep_highlight_colored(const char *colored_text, const char *plain_text, size_t match_start, size_t match_len) {
666 static __thread char highlight_buffer[LOG_TERMINAL_BUFFER_SIZE];
667
668 if (!colored_text || !plain_text || match_len == 0) {
669 return colored_text;
670 }
671
672 // When interactive grep is active, check if it has global flag
673 bool is_log_search = log_search_is_active();
674 bool should_use_global_pattern = false;
675 grep_pattern_t *global_pat = NULL;
676
677 if (!is_log_search) {
678 // If any pattern has global flag, highlight ALL matches for that pattern
679 // Find first pattern with global flag
680 for (int i = 0; i < g_filter_state.pattern_count; i++) {
681 if (g_filter_state.patterns[i].global_flag) {
682 global_pat = &g_filter_state.patterns[i];
683 should_use_global_pattern = true;
684 break;
685 }
686 }
687 } else if (log_search_get_global_highlight()) {
688 // Interactive grep is active and has /g flag - do global matching on the provided pattern
689 // We'll do all-match highlighting using the match position to extract the pattern
690 // and re-match for all occurrences
691 should_use_global_pattern = true;
692 // global_pat stays NULL, but we set the flag to enable global matching below
693 }
694
695 if (should_use_global_pattern) {
696 pcre2_code *code = NULL;
697 pcre2_match_data *match_data = NULL;
698 char fixed_string_pattern[LOG_GREP_PATTERN_BUFFER_SIZE] = {0};
699 bool is_fixed_string_pattern = false;
700 bool case_insensitive_fixed = false;
701
702 // Get code from CLI pattern or interactive grep pattern
703 if (global_pat && global_pat->is_fixed_string) {
704 SAFE_STRNCPY(fixed_string_pattern, global_pat->parsed_pattern, sizeof(fixed_string_pattern));
705 is_fixed_string_pattern = true;
706 case_insensitive_fixed = global_pat->case_insensitive;
707 } else if (global_pat && global_pat->compiled) {
708 code = global_pat->compiled;
709 match_data = get_thread_match_data();
710 } else if (is_log_search) {
711 // Interactive grep global highlighting - get pattern from grep state
712 code = (pcre2_code *)log_search_copy_pattern();
713 if (code) {
714 match_data = pcre2_match_data_create_from_pattern(code, NULL);
715 } else {
716 // No regex pattern - check if it's a fixed string pattern in interactive grep
717 int pattern_len = log_search_get_input_len();
718 const char *pattern = log_search_get_input_buffer();
719 if (pattern_len > 0 && pattern && pattern_len < (int)sizeof(fixed_string_pattern)) {
720 grep_parse_result_t parsed = grep_parse_pattern(pattern);
721 const char *literal = parsed.valid ? parsed.pattern : pattern;
722 SAFE_STRNCPY(fixed_string_pattern, literal, sizeof(fixed_string_pattern) - 1);
723 is_fixed_string_pattern = true;
724 case_insensitive_fixed = log_search_get_case_insensitive();
725 }
726 }
727 }
728
729 if ((!code || !match_data) && !is_fixed_string_pattern) {
730 if (match_data && is_log_search) {
731 pcre2_match_data_free(match_data); // Free if we created it
732 }
733 if (is_log_search && !global_pat && code)
734 pcre2_code_free(code);
735 return colored_text; // Fall back to no highlighting
736 }
737
738 size_t plain_len = strlen(plain_text);
739 size_t colored_len = strlen(colored_text);
740 char *dst = highlight_buffer;
741 size_t plain_offset = 0;
742 size_t colored_pos = 0;
743
744 // Handle fixed string global matching
745 if (is_fixed_string_pattern) {
746 while (plain_offset < plain_len) {
747 // Find next occurrence of fixed string
748 const char *found = NULL;
749 if (case_insensitive_fixed) {
750 found = utf8_strcasestr(plain_text + plain_offset, fixed_string_pattern);
751 } else {
752 found = strstr(plain_text + plain_offset, fixed_string_pattern);
753 }
754
755 if (!found) {
756 break; // No more matches
757 }
758
759 size_t plain_match_start = (size_t)(found - plain_text);
760 size_t plain_match_end = plain_match_start + strlen(fixed_string_pattern);
761
762 // Map to colored text positions (same as single-match path)
763 size_t colored_match_start = map_plain_to_colored_pos(colored_text, plain_match_start);
764 size_t colored_match_end = map_plain_to_colored_pos(colored_text, plain_match_end);
765
766 // Reserve the untouched tail plus the next background/reset sequences.
767 if ((size_t)(dst - highlight_buffer) + colored_len - colored_pos + 37 >= sizeof(highlight_buffer)) {
768 return colored_text;
769 }
770
771 // Copy text before match
772 if (colored_match_start > colored_pos) {
773 memcpy(dst, colored_text + colored_pos, colored_match_start - colored_pos);
774 dst += (colored_match_start - colored_pos);
775 }
776
777 // Add highlight background
778 uint8_t r, g, b;
779 get_highlight_color(&r, &g, &b);
780 dst = append_truecolor_bg(dst, r, g, b);
781
782 // Copy matched text with background
783 size_t match_byte_len = colored_match_end - colored_match_start;
784 memcpy(dst, colored_text + colored_match_start, match_byte_len);
785 dst += match_byte_len;
786
787 // Reset background
788 memcpy(dst, "\x1b[49m", 5);
789 dst += 5;
790
791 colored_pos = colored_match_end;
792 plain_offset = plain_match_end;
793 }
794
795 // Copy remaining text
796 if (colored_pos < colored_len) {
797 memcpy(dst, colored_text + colored_pos, colored_len - colored_pos);
798 dst += (colored_len - colored_pos);
799 }
800
801 // Reset both background and foreground at end
802 *dst = '\0';
803 return highlight_buffer;
804 }
805
806 // Find all matches in plain text and highlight in colored text (regex matching)
807 while (plain_offset < plain_len) {
808 int rc = asciichat_pcre2_match(code, (PCRE2_SPTR)plain_text, plain_len, plain_offset, 0, match_data, NULL);
809 if (rc < 0) {
810 break; // No more matches
811 }
812
813 PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
814 size_t plain_match_start = (size_t)ovector[0];
815 size_t plain_match_end = (size_t)ovector[1];
816
817 // Map to colored text positions
818 size_t colored_match_start = map_plain_to_colored_pos(colored_text, plain_match_start);
819 size_t colored_match_end = map_plain_to_colored_pos(colored_text, plain_match_end);
820
821 // Copy text before match
822 if (colored_match_start > colored_pos) {
823 memcpy(dst, colored_text + colored_pos, colored_match_start - colored_pos);
824 dst += (colored_match_start - colored_pos);
825 }
826
827 // Add highlight background
828 uint8_t r, g, b;
829 get_highlight_color(&r, &g, &b);
830 dst = append_truecolor_bg(dst, r, g, b);
831
832 // Copy matched text, re-applying background after any [0m or [00m reset codes
833 size_t match_byte_len = colored_match_end - colored_match_start;
834 const char *match_src = colored_text + colored_match_start;
835 char *dst_end = highlight_buffer + sizeof(highlight_buffer) - 1; // Absolute buffer end
836 size_t i = 0;
837 while (i < match_byte_len) {
838 // Check for [0m or [00m reset codes
839 if (i + 4 <= match_byte_len && match_src[i] == '\x1b' && match_src[i + 1] == '[' && match_src[i + 2] == '0' && match_src[i + 3] == 'm') {
840 // Found [0m - copy it and re-apply background (if room)
841 if (dst + 4 >= dst_end)
842 break; // Not enough space for the reset code itself
843 *dst++ = match_src[i++]; // ESC
844 *dst++ = match_src[i++]; // '['
845 *dst++ = match_src[i++]; // '0'
846 *dst++ = match_src[i++]; // 'm'
847 // Re-apply highlight background after reset (only if room)
848 if (dst + 20 < dst_end) {
849 uint8_t r2, g2, b2;
850 get_highlight_color(&r2, &g2, &b2);
851 dst = append_truecolor_bg(dst, r2, g2, b2);
852 }
853 } else if (i + 5 <= match_byte_len && match_src[i] == '\x1b' && match_src[i + 1] == '[' && match_src[i + 2] == '0' && match_src[i + 3] == '0' && match_src[i + 4] == 'm') {
854 // Found [00m - copy it and re-apply background (if room)
855 if (dst + 5 >= dst_end)
856 break; // Not enough space for the reset code itself
857 *dst++ = match_src[i++]; // ESC
858 *dst++ = match_src[i++]; // '['
859 *dst++ = match_src[i++]; // '0'
860 *dst++ = match_src[i++]; // '0'
861 *dst++ = match_src[i++]; // 'm'
862 // Re-apply highlight background after reset (only if room)
863 if (dst + 20 < dst_end) {
864 uint8_t r2, g2, b2;
865 get_highlight_color(&r2, &g2, &b2);
866 dst = append_truecolor_bg(dst, r2, g2, b2);
867 }
868 } else {
869 // Regular character - just copy
870 if (dst + 1 >= dst_end)
871 break;
872 *dst++ = match_src[i++];
873 }
874 }
875
876 // Reset background only
877 memcpy(dst, "\x1b[49m", 5);
878 dst += 5;
879
880 colored_pos = colored_match_end;
881 plain_offset = plain_match_end;
882
883 // Prevent infinite loop on zero-length matches
884 if (plain_match_end == plain_match_start) {
885 plain_offset++;
886 }
887 }
888
889 // Copy remaining text
890 if (colored_pos < colored_len) {
891 memcpy(dst, colored_text + colored_pos, colored_len - colored_pos);
892 dst += (colored_len - colored_pos);
893 }
894
895 // Reset both background and foreground at end to prevent color bleeding
896 *dst = '\0';
897
898 // Clean up match data if we created it for interactive grep
899 if (is_log_search && match_data && !global_pat) {
900 pcre2_match_data_free(match_data);
901 }
902 if (is_log_search && !global_pat && code)
903 pcre2_code_free(code);
904
905 return highlight_buffer;
906 }
907
908 // Single match highlighting (same logic as global path)
909 // map_plain_to_colored_pos(N) returns byte position after counting N plain bytes
910 size_t colored_start = map_plain_to_colored_pos(colored_text, match_start);
911 size_t colored_end = map_plain_to_colored_pos(colored_text, match_start + match_len);
912
913 size_t colored_len = strlen(colored_text);
914 char *dst = highlight_buffer;
915
916 // Copy everything before the match
917 if (colored_start > 0) {
918 memcpy(dst, colored_text, colored_start);
919 dst += colored_start;
920 }
921
922 // Add highlight background
923 uint8_t r, g, b;
924 get_highlight_color(&r, &g, &b);
925 dst = append_truecolor_bg(dst, r, g, b);
926
927 // Copy matched text, re-applying background after any [0m or [00m reset codes
928 size_t match_byte_len = colored_end - colored_start;
929 const char *match_src = colored_text + colored_start;
930 char *dst_end = highlight_buffer + sizeof(highlight_buffer) - 1; // Absolute buffer end
931 size_t i = 0;
932
933 while (i < match_byte_len) {
934 // Check for [0m or [00m reset codes
935 if (i + 4 <= match_byte_len && match_src[i] == '\x1b' && match_src[i + 1] == '[' && match_src[i + 2] == '0' && match_src[i + 3] == 'm') {
936 // Found [0m - copy it and re-apply background (if room)
937 if (dst + 4 >= dst_end)
938 break; // Not enough space for even the reset code
939 *dst++ = match_src[i++]; // ESC
940 *dst++ = match_src[i++]; // '['
941 *dst++ = match_src[i++]; // '0'
942 *dst++ = match_src[i++]; // 'm'
943 // Re-apply highlight background after reset (only if room)
944 if (dst + 20 < dst_end) {
945 uint8_t r2, g2, b2;
946 get_highlight_color(&r2, &g2, &b2);
947 dst = append_truecolor_bg(dst, r2, g2, b2);
948 }
949 } else if (i + 5 <= match_byte_len && match_src[i] == '\x1b' && match_src[i + 1] == '[' && match_src[i + 2] == '0' && match_src[i + 3] == '0' && match_src[i + 4] == 'm') {
950 // Found [00m - copy it and re-apply background (if room)
951 if (dst + 5 >= dst_end)
952 break; // Not enough space for even the reset code
953 *dst++ = match_src[i++]; // ESC
954 *dst++ = match_src[i++]; // '['
955 *dst++ = match_src[i++]; // '0'
956 *dst++ = match_src[i++]; // '0'
957 *dst++ = match_src[i++]; // 'm'
958 // Re-apply highlight background after reset (only if room)
959 if (dst + 20 < dst_end) {
960 uint8_t r3, g3, b3;
961 get_highlight_color(&r3, &g3, &b3);
962 dst = append_truecolor_bg(dst, r3, g3, b3);
963 }
964 } else {
965 // Regular character - just copy
966 if (dst + 1 >= dst_end) {
967 break;
968 }
969 *dst++ = match_src[i++];
970 }
971 }
972
973 // Reset only the background color to preserve foreground colors from headers
974 // Using \x1b[49m (reset background only) instead of \x1b[0m (reset all)
975 memcpy(dst, "\x1b[49m", 5);
976 dst += 5;
977
978 // Copy remaining text
979 size_t remaining = colored_len - colored_end;
980 if (remaining > 0) {
981 memcpy(dst, colored_text + colored_end, remaining);
982 dst += remaining;
983 }
984
985 *dst = '\0';
986 return highlight_buffer;
987}
988
989const char *grep_highlight(const char *log_line, size_t match_start, size_t match_len) {
990 if (!log_line || match_start > strlen(log_line) || match_len > strlen(log_line) - match_start)
991 return log_line;
992 return grep_highlight_colored(log_line, log_line, match_start, match_len);
993}
994
995void grep_destroy(void) {
996 // Free all patterns
997 for (int i = 0; i < g_filter_state.pattern_count; i++) {
998 grep_pattern_t *pat = &g_filter_state.patterns[i];
999 // Free the copied original string (need temp variable due to const qualifier)
1000 char *original_to_free = (char *)pat->original;
1001 SAFE_FREE(original_to_free);
1003 if (pat->compiled)
1004 pcre2_code_free(pat->compiled);
1005 pat->compiled = NULL;
1006 }
1007 SAFE_FREE(g_filter_state.patterns);
1008 g_filter_state.patterns = NULL; // Make idempotent
1009 for (int i = 0; i < g_filter_state.saved_pattern_count; i++) {
1010 grep_pattern_t *saved = &g_filter_state.saved_patterns[i];
1011 char *original = (char *)saved->original;
1012 SAFE_FREE(original);
1013 SAFE_FREE(saved->parsed_pattern);
1014 if (saved->compiled)
1015 pcre2_code_free(saved->compiled);
1016 }
1017 SAFE_FREE(g_filter_state.saved_patterns);
1018 g_filter_state.saved_pattern_count = 0;
1019 g_filter_state.saved_pattern_capacity = 0;
1020
1021 // Free context buffer
1022 if (g_filter_state.line_buffer) {
1023 for (int i = 0; i < g_filter_state.buffer_size; i++) {
1024 SAFE_FREE(g_filter_state.line_buffer[i]);
1025 }
1026 SAFE_FREE(g_filter_state.line_buffer);
1027 g_filter_state.line_buffer = NULL; // Make idempotent
1028 }
1029
1030 g_filter_state.pattern_count = 0;
1031 g_filter_state.pattern_capacity = 0;
1032 g_filter_state.buffer_size = 0;
1033 g_filter_state.buffer_pos = 0;
1034 g_filter_state.lines_after_match = 0;
1035 g_filter_state.max_context_after = 0;
1036 g_filter_state.enabled = false;
1037
1038 // Note: Thread-local match_data is cleaned up via pthread_key destructor
1039}
1040
1041/* ============================================================================
1042 * Save/Restore Functions for Interactive Grep
1043 * ========================================================================== */
1044
1045static void grep_free_pattern(grep_pattern_t *pattern) {
1046 char *original = (char *)pattern->original;
1047 SAFE_FREE(original);
1048 SAFE_FREE(pattern->parsed_pattern);
1049 if (pattern->compiled)
1050 pcre2_code_free(pattern->compiled);
1051 memset(pattern, 0, sizeof(*pattern));
1052}
1053
1054static asciichat_error_t grep_copy_patterns(const grep_pattern_t *src, int count, grep_pattern_t **out) {
1055 *out = NULL;
1056 if (!count)
1057 return ASCIICHAT_OK;
1058 grep_pattern_t *copy = SAFE_CALLOC((size_t)count, sizeof(*copy), grep_pattern_t *);
1059 if (!copy)
1060 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate filter patterns");
1061 for (int i = 0; i < count; i++) {
1062 copy[i] = src[i];
1063 copy[i].original = NULL;
1064 copy[i].parsed_pattern = NULL;
1065 copy[i].compiled = NULL;
1066 char *original = NULL;
1067 SAFE_STRDUP(original, src[i].original);
1068 copy[i].original = original;
1069 SAFE_STRDUP(copy[i].parsed_pattern, src[i].parsed_pattern);
1070 if (src[i].compiled)
1071 copy[i].compiled = pcre2_code_copy(src[i].compiled);
1072 if (!copy[i].original || !copy[i].parsed_pattern || (src[i].compiled && !copy[i].compiled)) {
1073 for (int j = 0; j <= i; j++)
1074 grep_free_pattern(&copy[j]);
1075 SAFE_FREE(copy);
1076 return SET_ERRNO(ERROR_MEMORY, "Failed to copy filter pattern");
1077 }
1078 }
1079 *out = copy;
1080 return ASCIICHAT_OK;
1081}
1082
1084 grep_pattern_t *copy = NULL;
1085 asciichat_error_t result = grep_copy_patterns(g_filter_state.patterns, g_filter_state.pattern_count, &copy);
1086 if (result != ASCIICHAT_OK)
1087 return result;
1088 for (int i = 0; i < g_filter_state.saved_pattern_count; i++)
1089 grep_free_pattern(&g_filter_state.saved_patterns[i]);
1090 SAFE_FREE(g_filter_state.saved_patterns);
1091 g_filter_state.saved_patterns = copy;
1092 g_filter_state.saved_pattern_count = g_filter_state.pattern_count;
1093 g_filter_state.saved_pattern_capacity = g_filter_state.pattern_count;
1094 g_filter_state.saved_enabled = g_filter_state.enabled;
1095 return ASCIICHAT_OK;
1096}
1097
1099 grep_pattern_t *copy = NULL;
1100 asciichat_error_t result = grep_copy_patterns(g_filter_state.saved_patterns, g_filter_state.saved_pattern_count, &copy);
1101 if (result != ASCIICHAT_OK)
1102 return result;
1103 for (int i = 0; i < g_filter_state.pattern_count; i++)
1104 grep_free_pattern(&g_filter_state.patterns[i]);
1105 SAFE_FREE(g_filter_state.patterns);
1106 g_filter_state.patterns = copy;
1107 g_filter_state.pattern_count = g_filter_state.saved_pattern_count;
1108 g_filter_state.pattern_capacity = g_filter_state.saved_pattern_count;
1109 g_filter_state.enabled = g_filter_state.saved_enabled;
1110 return ASCIICHAT_OK;
1111}
1112
1114 for (int i = 0; i < g_filter_state.pattern_count; i++)
1115 grep_free_pattern(&g_filter_state.patterns[i]);
1116 g_filter_state.pattern_count = 0;
1117 g_filter_state.enabled = false;
1118}
1119
1121 return g_filter_state.pattern_count;
1122}
1123
1124const char *grep_get_last_pattern(void) {
1125 if (g_filter_state.pattern_count == 0) {
1126 return NULL;
1127 }
1128
1129 // Return the original pattern string of the last pattern
1130 return g_filter_state.patterns[g_filter_state.pattern_count - 1].original;
1131}
ANSI escape sequence utilities and fast color code generation.
#define SET_ERRNO(code,...)
uint8_t colorscheme_highlight_background(void)
lifecycle_t match_data_lifecycle
Lifecycle for TLS key initialization.
Definition grep.c:64
asciichat_error_t grep_restore_patterns(void)
Restore previously saved filter patterns.
Definition grep.c:1098
asciichat_error_t grep_save_patterns(void)
Save current filter patterns for later restoration.
Definition grep.c:1083
char * grep_highlight_colored_copy(const char *colored_text, const char *plain_text, size_t match_start, size_t match_len)
Highlight matches in colored text, returning a new allocated copy.
Definition grep.c:652
int pattern_count
Number of active patterns.
Definition grep.c:60
int saved_pattern_count
Number of saved patterns.
Definition grep.c:75
int lines_after_match
Counter for context_after lines.
Definition grep.c:70
const char * grep_get_last_pattern(void)
Get the last (most recent) filter pattern string.
Definition grep.c:1124
const char * grep_highlight(const char *log_line, size_t match_start, size_t match_len)
Highlight matched portion with background color.
Definition grep.c:989
void grep_clear_patterns(void)
Clear all filter patterns.
Definition grep.c:1113
bool saved_enabled
Saved enabled state.
Definition grep.c:77
int grep_get_pattern_count(void)
Get number of active filter patterns.
Definition grep.c:1120
asciichat_error_t grep_init(const char *pattern)
Initialize log filtering with PCRE2 regex pattern.
Definition grep.c:411
tls_key_t match_data_key
Thread-local match_data key.
Definition grep.c:63
void grep_destroy(void)
Clean up filter resources.
Definition grep.c:995
bool grep_should_output(const char *log_line, size_t *match_start, size_t *match_len)
Check if log line should be output (matches filter).
Definition grep.c:510
grep_parse_result_t grep_parse_pattern(const char *input)
Parse pattern in /pattern/flags or pattern/flags format.
Definition grep.c:265
bool enabled
Is filtering active?
Definition grep.c:62
int buffer_pos
Current position in buffer.
Definition grep.c:69
grep_parse_result_t parse_result_t
Definition grep.c:222
int pattern_capacity
Allocated capacity.
Definition grep.c:61
int saved_pattern_capacity
Allocated capacity for saved.
Definition grep.c:76
grep_pattern_t * saved_patterns
Backup of patterns for restore.
Definition grep.c:74
int buffer_size
Size of circular buffer.
Definition grep.c:68
grep_pattern_t * patterns
Array of patterns.
Definition grep.c:59
char ** line_buffer
Circular buffer for context_before.
Definition grep.c:67
const char * grep_highlight_colored(const char *colored_text, const char *plain_text, size_t match_start, size_t match_len)
Highlight matches in colored text while preserving original colors.
Definition grep.c:665
int max_context_after
Maximum context_after across all patterns.
Definition grep.c:71
#define LOG_GREP_PATTERN_BUFFER_SIZE
Definition grep.h:9
char * append_truecolor_bg(char *dst, uint8_t r, uint8_t g, uint8_t b)
Definition ansi.c:145
#define SAFE_REALLOC(ptr, size, cast)
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
#define SAFE_STRDUP(dst, src)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define LOG_TERMINAL_BUFFER_SIZE
Definition log/log.h:103
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
int utf8_decode(const uint8_t *s, uint32_t *codepoint)
Decode a UTF-8 sequence to a Unicode codepoint.
Definition utf8.c:27
const char * utf8_strcasestr(const char *haystack, const char *needle)
Case-insensitive substring search with full Unicode support.
Definition utf8.c:205
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
pcre2_code * asciichat_pcre2_compile(const char *pattern, uint32_t flags)
Definition pcre2.c:16
int asciichat_pcre2_match(const pcre2_code *code, PCRE2_SPTR subject, PCRE2_SIZE length, PCRE2_SIZE startoffset, uint32_t options, pcre2_match_data *match_data, pcre2_match_context *context)
Definition pcre2.c:161
PCRE2 compilation and match helpers.
static bool size_t gotel_query_t * out
Definition queries.h:8
bool log_search_get_global_highlight(void)
Check if global highlighting (/g flag) is enabled in current pattern.
Definition search.c:939
int log_search_get_input_len(void)
Get current input buffer length (must hold mutex).
Definition search.c:983
const char * log_search_get_input_buffer(void)
Get current input buffer content (must hold mutex).
Definition search.c:991
bool log_search_is_active(void)
Check if filtering is active.
Definition search.c:413
bool log_search_get_case_insensitive(void)
Check if case-insensitive flag is set (must hold mutex).
Definition search.c:995
void * log_search_copy_pattern(void)
Get the compiled regex pattern for interactive grep (internal use).
Definition search.c:954
Interactive search filtering for terminal screens.
🔤 String Manipulation and Shell Escaping Utilities
Parsed pattern result from /pattern/flags syntax.
Definition grep.h:26
int context_before
Lines before match (B<n> flag).
Definition grep.h:33
bool global_flag
Highlight all matches (g flag).
Definition grep.h:32
bool is_fixed_string
True if fixed string (not regex).
Definition grep.h:29
bool invert
Invert match (I flag).
Definition grep.h:31
char pattern[4096]
Parsed pattern string.
Definition grep.h:27
bool case_insensitive
Case-insensitive (i flag).
Definition grep.h:30
bool valid
True if parsing succeeded.
Definition grep.h:35
int context_after
Lines after match (A<n> flag).
Definition grep.h:34
uint32_t pcre2_options
PCRE2 compile options.
Definition grep.h:28
grep pattern keeps the values that move through the subsystem: original, parsed_pattern,...
Definition grep.c:43
int context_before
Lines before match (B flag).
Definition grep.c:51
int context_after
Lines after match (A flag).
Definition grep.c:52
bool case_insensitive
Case-insensitive matching (i flag).
Definition grep.c:48
bool global_flag
Highlight all matches (g flag).
Definition grep.c:50
bool is_fixed_string
True for fixed string matching (no regex).
Definition grep.c:47
const char * original
Original pattern string (for display).
Definition grep.c:44
bool invert
Invert match (I flag).
Definition grep.c:49
char * parsed_pattern
Parsed pattern (without delimiters/flags).
Definition grep.c:45
pcre2_code * compiled
Compiled pattern (NULL if fixed string).
Definition grep.c:46
🔤 UTF-8 Encoding and Decoding Utilities