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 File Reference

Go to the source code of this file.

Data Structures

struct  grep_pattern_t
 grep pattern keeps the values that move through the subsystem: original, parsed_pattern, compiled, is_fixed_string. Some members are pointers into caller- or subsystem-owned memory, so lifetime follows the API that populated them rather than the struct copy itself. More...

Typedefs

typedef grep_parse_result_t parse_result_t

Functions

grep_parse_result_t grep_parse_pattern (const char *input)
 Parse pattern in /pattern/flags or pattern/flags format.
asciichat_error_t grep_init (const char *pattern)
 Initialize log filtering with PCRE2 regex pattern.
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).
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.
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.
const char * grep_highlight (const char *log_line, size_t match_start, size_t match_len)
 Highlight matched portion with background color.
void grep_destroy (void)
 Clean up filter resources.
asciichat_error_t grep_save_patterns (void)
 Save current filter patterns for later restoration.
asciichat_error_t grep_restore_patterns (void)
 Restore previously saved filter patterns.
void grep_clear_patterns (void)
 Clear all filter patterns.
int grep_get_pattern_count (void)
 Get number of active filter patterns.
const char * grep_get_last_pattern (void)
 Get the last (most recent) filter pattern string.

Typedef Documentation

◆ parse_result_t

Definition at line 222 of file grep.c.

Function Documentation

◆ grep_clear_patterns()

void grep_clear_patterns ( void )

Clear all filter patterns.

Temporarily disables filtering by setting pattern count to 0. Patterns remain allocated and can be restored later. Used by interactive grep when user types first character.

Definition at line 1113 of file grep.c.

1113 {
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}

◆ grep_destroy()

void grep_destroy ( void )

Clean up filter resources.

Frees compiled regex. Thread-local match_data is cleaned up via pthread_key destructor.

Definition at line 995 of file grep.c.

995 {
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);
1002 SAFE_FREE(pat->parsed_pattern);
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}
#define SAFE_FREE(ptr)
grep pattern keeps the values that move through the subsystem: original, parsed_pattern,...
Definition grep.c:43
const char * original
Original pattern string (for display).
Definition grep.c:44

References grep_pattern_t::compiled, grep_pattern_t::original, grep_pattern_t::parsed_pattern, and SAFE_FREE.

Referenced by log_destroy().

◆ grep_get_last_pattern()

const char * grep_get_last_pattern ( void )

Get the last (most recent) filter pattern string.

Returns the original pattern string (with /pattern/flags syntax if provided) of the last –grep argument. Used by interactive grep to populate its input buffer when starting with CLI –grep patterns.

Returns
Pattern string of last CLI –grep, or NULL if no patterns

Definition at line 1124 of file grep.c.

1124 {
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}

Referenced by log_search_enter_mode(), log_search_init(), ui_status_display(), and ui_status_display_interactive().

◆ grep_get_pattern_count()

int grep_get_pattern_count ( void )

Get number of active filter patterns.

Returns
Number of currently active patterns

Definition at line 1120 of file grep.c.

1120 {
1121 return g_filter_state.pattern_count;
1122}

◆ grep_highlight()

const char * grep_highlight ( const char * log_line,
size_t match_start,
size_t match_len )

Highlight matched portion with background color.

Inserts ANSI escape codes for yellow background (255, 200, 0) with black foreground (0, 0, 0) around the matched text.

Parameters
log_lineOriginal log line
match_startStart offset of match
match_lenLength of match
Returns
Highlighted string (pointer to static thread-local buffer)

Definition at line 989 of file grep.c.

989 {
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}
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

References grep_highlight_colored().

◆ grep_highlight_colored()

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.

Parameters
colored_textOriginal text with ANSI color codes
plain_textStripped plain text (for match positions)
match_startMatch start position in plain text
match_lenMatch length in plain text
Returns
Highlighted text with yellow background added to matches (pointer to static thread-local buffer)

Definition at line 665 of file grep.c.

665 {
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}
grep_parse_result_t grep_parse_pattern(const char *input)
Parse pattern in /pattern/flags or pattern/flags format.
Definition grep.c:265
#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_STRNCPY(dst, src, size)
unsigned char uint8_t
#define LOG_TERMINAL_BUFFER_SIZE
Definition log/log.h:103
const char * utf8_strcasestr(const char *haystack, const char *needle)
Case-insensitive substring search with full Unicode support.
Definition utf8.c:205
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
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
Parsed pattern result from /pattern/flags syntax.
Definition grep.h:26
char pattern[4096]
Parsed pattern string.
Definition grep.h:27
bool valid
True if parsing succeeded.
Definition grep.h:35
bool case_insensitive
Case-insensitive matching (i flag).
Definition grep.c:48
bool is_fixed_string
True for fixed string matching (no regex).
Definition grep.c:47
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

References append_truecolor_bg(), asciichat_pcre2_match(), grep_pattern_t::case_insensitive, grep_pattern_t::compiled, grep_parse_pattern(), grep_pattern_t::is_fixed_string, LOG_GREP_PATTERN_BUFFER_SIZE, log_search_copy_pattern(), log_search_get_case_insensitive(), log_search_get_global_highlight(), log_search_get_input_buffer(), log_search_get_input_len(), log_search_is_active(), LOG_TERMINAL_BUFFER_SIZE, grep_pattern_t::parsed_pattern, grep_parse_result_t::pattern, SAFE_STRNCPY, utf8_strcasestr(), and grep_parse_result_t::valid.

Referenced by grep_highlight(), and grep_highlight_colored_copy().

◆ grep_highlight_colored_copy()

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.

Like grep_highlight_colored() but returns a newly allocated string instead of a static buffer. Caller must free the returned string with SAFE_FREE().

Parameters
colored_textOriginal text with ANSI color codes
plain_textStripped plain text (for match positions)
match_startMatch start position in plain text
match_lenMatch length in plain text
Returns
Newly allocated highlighted text (caller must free), or NULL on error

Definition at line 652 of file grep.c.

652 {
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}
#define SAFE_MALLOC(size, cast)

References grep_highlight_colored(), and SAFE_MALLOC.

◆ grep_init()

asciichat_error_t grep_init ( const char * pattern)

Initialize log filtering with PCRE2 regex pattern.

Compiles the pattern eagerly at startup. If compilation fails, logs a warning and disables filtering.

Parameters
patternPCRE2 regex pattern (NULL or empty = no filtering)
Returns
ASCIICHAT_OK on success, ERROR_INVALID_PARAM on bad regex

Definition at line 411 of file grep.c.

411 {
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}
#define SET_ERRNO(code,...)
grep_parse_result_t parse_result_t
Definition grep.c:222
int pattern_capacity
Allocated capacity.
Definition grep.c:61
#define SAFE_REALLOC(ptr, size, cast)
@ 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_info(...)
Log an INFO message.
Definition log/log.h:602
pcre2_code * asciichat_pcre2_compile(const char *pattern, uint32_t flags)
Definition pcre2.c:16
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
bool case_insensitive
Case-insensitive (i flag).
Definition grep.h:30
int context_after
Lines after match (A<n> flag).
Definition grep.h:34
uint32_t pcre2_options
PCRE2 compile options.
Definition grep.h:28
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 global_flag
Highlight all matches (g flag).
Definition grep.c:50
bool invert
Invert match (I flag).
Definition grep.c:49

References ASCIICHAT_OK, asciichat_pcre2_compile(), grep_parse_result_t::case_insensitive, grep_pattern_t::case_insensitive, grep_pattern_t::compiled, grep_parse_result_t::context_after, grep_pattern_t::context_after, grep_parse_result_t::context_before, grep_pattern_t::context_before, ERROR_INVALID_PARAM, ERROR_MEMORY, grep_parse_result_t::global_flag, grep_pattern_t::global_flag, grep_parse_pattern(), grep_parse_result_t::invert, grep_pattern_t::invert, grep_parse_result_t::is_fixed_string, grep_pattern_t::is_fixed_string, log_error, log_info, grep_pattern_t::original, grep_pattern_t::parsed_pattern, grep_parse_result_t::pattern, grep_parse_result_t::pcre2_options, SAFE_FREE, SAFE_MALLOC, SAFE_REALLOC, SET_ERRNO, and grep_parse_result_t::valid.

Referenced by main().

◆ grep_parse_pattern()

grep_parse_result_t grep_parse_pattern ( const char * input)

Parse pattern in /pattern/flags or pattern/flags format.

Parse pattern in /pattern/flags format or plain regex format.

Parameters
inputInput pattern string (either /pattern/flags, pattern/flags, or plain pattern)
Returns
Parse result with all extracted settings

Format 1 (with flags, explicit): /pattern/flags

  • Pattern enclosed in forward slashes with optional flags
  • Use F flag for fixed string (literal) matching

Format 2 (with flags, implicit): pattern/flags

  • Interactive grep format (no leading slash, since / starts the grep command)
  • Treats last slash as delimiter

Format 3 (plain regex): pattern

  • Plain regex pattern without slashes or flags
  • Treated as regex with default options (no flags)

Flags (formats 1 & 2):

  • i: case-insensitive
  • m: multiline mode (regex only)
  • s: dotall mode (regex only)
  • x: extended mode (regex only)
  • g: global (highlight all matches)
  • I: invert match (show non-matching lines)
  • F: fixed string (literal match, no regex)
  • A<n>: show n lines after match (e.g., A3)
  • B<n>: show n lines before match (e.g., B2)
  • C<n>: show n lines before and after match (e.g., C5)

Examples:

  • "/test/" - Simple regex with slashes
  • "test" - Plain regex without slashes
  • "/query/i" - Case-insensitive regex
  • "/test/F" - Fixed string match for "test"
  • "/api/v1/users/F" - Fixed string match for "api/v1/users"
  • "/ERROR/IA3" - Invert match + 3 lines after
  • "/FATAL/B2A5F" - Fixed string, 2 before, 5 after
  • "error|warn" - Plain regex with alternation
  • "search/i" - Interactive grep: case-insensitive "search"
  • "api/v1/users/F" - Interactive grep: fixed string match

Definition at line 265 of file grep.c.

265 {
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}

References grep_parse_result_t::case_insensitive, grep_parse_result_t::context_after, grep_parse_result_t::context_before, grep_parse_result_t::global_flag, grep_parse_result_t::invert, grep_parse_result_t::is_fixed_string, grep_parse_result_t::pattern, grep_parse_result_t::pcre2_options, and grep_parse_result_t::valid.

Referenced by grep_highlight_colored(), grep_init(), log_search_enter_mode(), log_search_exit_mode(), log_search_filter_buffer(), log_search_get_match_info(), and log_search_init().

◆ grep_restore_patterns()

asciichat_error_t grep_restore_patterns ( void )

Restore previously saved filter patterns.

Restores filter patterns saved by grep_save_patterns(). Used by interactive grep when user cancels (Escape) to restore CLI –grep patterns.

Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 1098 of file grep.c.

1098 {
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}
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48

References ASCIICHAT_OK, and SAFE_FREE.

Referenced by log_search_exit_mode().

◆ grep_save_patterns()

asciichat_error_t grep_save_patterns ( void )

Save current filter patterns for later restoration.

Saves the current state of CLI –grep patterns so they can be restored later. Used by interactive grep to preserve initial filters when entering interactive mode.

Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 1083 of file grep.c.

1083 {
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}

References ASCIICHAT_OK, and SAFE_FREE.

Referenced by log_search_enter_mode().

◆ grep_should_output()

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).

Thread-safe: Uses thread-local match_data storage. Non-allocating: Reuses pre-allocated match_data.

Parameters
log_lineFormatted log line to check
match_startOutput: start offset of match
match_lenOutput: length of match
Returns
true if line should be output, false to suppress

Definition at line 510 of file grep.c.

510 {
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}
int buffer_size
Size of circular buffer.
Definition grep.c:68

References asciichat_pcre2_match(), grep_pattern_t::case_insensitive, grep_pattern_t::compiled, grep_pattern_t::context_after, grep_pattern_t::context_before, grep_pattern_t::invert, grep_pattern_t::is_fixed_string, grep_pattern_t::parsed_pattern, SAFE_FREE, SAFE_MALLOC, and utf8_strcasestr().

Variable Documentation

◆ buffer_pos

int buffer_pos

Current position in buffer.

Definition at line 69 of file grep.c.

◆ buffer_size

◆ enabled

◆ line_buffer

char** line_buffer

Circular buffer for context_before.

Definition at line 67 of file grep.c.

Referenced by sdp_parse().

◆ lines_after_match

int lines_after_match

Counter for context_after lines.

Definition at line 70 of file grep.c.

◆ match_data_key

tls_key_t match_data_key

Thread-local match_data key.

Definition at line 63 of file grep.c.

◆ match_data_lifecycle

lifecycle_t match_data_lifecycle

Lifecycle for TLS key initialization.

Definition at line 64 of file grep.c.

◆ max_context_after

int max_context_after

Maximum context_after across all patterns.

Definition at line 71 of file grep.c.

◆ pattern_capacity

int pattern_capacity

Allocated capacity.

Definition at line 61 of file grep.c.

◆ pattern_count

int pattern_count

Number of active patterns.

Definition at line 60 of file grep.c.

Referenced by log_search_get_match_info().

◆ patterns

grep_pattern_t* patterns

Array of patterns.

Definition at line 59 of file grep.c.

◆ saved_enabled

bool saved_enabled

Saved enabled state.

Definition at line 77 of file grep.c.

◆ saved_pattern_capacity

int saved_pattern_capacity

Allocated capacity for saved.

Definition at line 76 of file grep.c.

◆ saved_pattern_count

int saved_pattern_count

Number of saved patterns.

Definition at line 75 of file grep.c.

◆ saved_patterns

grep_pattern_t* saved_patterns

Backup of patterns for restore.

Definition at line 74 of file grep.c.