ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
grep.h File Reference

Go to the source code of this file.

Data Structures

struct  grep_parse_result_t
 Parsed pattern result from /pattern/flags syntax. More...

Macros

#define LOG_GREP_PATTERN_BUFFER_SIZE   4096

Functions

grep_parse_result_t grep_parse_pattern (const char *input)
 Parse pattern in /pattern/flags format or plain regex 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).
const char * grep_highlight (const char *log_line, size_t match_start, size_t match_len)
 Highlight matched portion with background color.
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.
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.
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.

Macro Definition Documentation

◆ LOG_GREP_PATTERN_BUFFER_SIZE

#define LOG_GREP_PATTERN_BUFFER_SIZE   4096

Pattern storage capacity in bytes, including NUL.

Definition at line 9 of file grep.h.

Referenced by grep_highlight_colored().

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 1189 of file grep.c.

1189 {
1190 for (int i = 0; i < g_filter_state.pattern_count; i++)
1191 grep_free_pattern(&g_filter_state.patterns[i]);
1192 g_filter_state.pattern_count = 0;
1193 g_filter_state.enabled = false;
1194}

◆ 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 1065 of file grep.c.

1065 {
1066 // Free all patterns
1067 for (int i = 0; i < g_filter_state.pattern_count; i++) {
1068 grep_pattern_t *pat = &g_filter_state.patterns[i];
1069 // Free the copied original string (need temp variable due to const
1070 // qualifier)
1071 char *original_to_free = (char *)pat->original;
1072 SAFE_FREE(original_to_free);
1073 SAFE_FREE(pat->parsed_pattern);
1074 if (pat->compiled)
1075 pcre2_code_free(pat->compiled);
1076 pat->compiled = NULL;
1077 }
1078 SAFE_FREE(g_filter_state.patterns);
1079 g_filter_state.patterns = NULL; // Make idempotent
1080 for (int i = 0; i < g_filter_state.saved_pattern_count; i++) {
1081 grep_pattern_t *saved = &g_filter_state.saved_patterns[i];
1082 char *original = (char *)saved->original;
1083 SAFE_FREE(original);
1084 SAFE_FREE(saved->parsed_pattern);
1085 if (saved->compiled)
1086 pcre2_code_free(saved->compiled);
1087 }
1088 SAFE_FREE(g_filter_state.saved_patterns);
1089 g_filter_state.saved_pattern_count = 0;
1090 g_filter_state.saved_pattern_capacity = 0;
1091
1092 // Free context buffer
1093 if (g_filter_state.line_buffer) {
1094 for (int i = 0; i < g_filter_state.buffer_size; i++) {
1095 SAFE_FREE(g_filter_state.line_buffer[i]);
1096 }
1097 SAFE_FREE(g_filter_state.line_buffer);
1098 g_filter_state.line_buffer = NULL; // Make idempotent
1099 }
1100
1101 g_filter_state.pattern_count = 0;
1102 g_filter_state.pattern_capacity = 0;
1103 g_filter_state.buffer_size = 0;
1104 g_filter_state.buffer_pos = 0;
1105 g_filter_state.lines_after_match = 0;
1106 g_filter_state.max_context_after = 0;
1107 g_filter_state.enabled = false;
1108
1109 // Note: Thread-local match_data is cleaned up via pthread_key destructor
1110}
#define SAFE_FREE(ptr)
grep pattern keeps the values that move through the subsystem: original, parsed_pattern,...
Definition grep.c:44
const char * original
Original pattern string (for display).
Definition grep.c:45

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 1198 of file grep.c.

1198 {
1199 if (g_filter_state.pattern_count == 0) {
1200 return NULL;
1201 }
1202
1203 // Return the original pattern string of the last pattern
1204 return g_filter_state.patterns[g_filter_state.pattern_count - 1].original;
1205}

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 1196 of file grep.c.

1196{ return g_filter_state.pattern_count; }

◆ 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 1057 of file grep.c.

1058 {
1059 if (!log_line || match_start > strlen(log_line) ||
1060 match_len > strlen(log_line) - match_start)
1061 return log_line;
1062 return grep_highlight_colored(log_line, log_line, match_start, match_len);
1063}
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:702

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 702 of file grep.c.

704 {
705 static _Thread_local char highlight_buffer[LOG_TERMINAL_BUFFER_SIZE];
706
707 if (!colored_text || !plain_text || match_len == 0) {
708 return colored_text;
709 }
710
711 // When interactive grep is active, check if it has global flag
712 bool is_log_search = log_search_is_active();
713 bool should_use_global_pattern = false;
714 grep_pattern_t *global_pat = NULL;
715
716 if (!is_log_search) {
717 // If any pattern has global flag, highlight ALL matches for that pattern
718 // Find first pattern with global flag
719 for (int i = 0; i < g_filter_state.pattern_count; i++) {
720 if (g_filter_state.patterns[i].global_flag) {
721 global_pat = &g_filter_state.patterns[i];
722 should_use_global_pattern = true;
723 break;
724 }
725 }
726 } else if (log_search_get_global_highlight()) {
727 // Interactive grep is active and has /g flag - do global matching on the
728 // provided pattern We'll do all-match highlighting using the match position
729 // to extract the pattern and re-match for all occurrences
730 should_use_global_pattern = true;
731 // global_pat stays NULL, but we set the flag to enable global matching
732 // below
733 }
734
735 if (should_use_global_pattern) {
736 pcre2_code *code = NULL;
737 pcre2_match_data *match_data = NULL;
738 char fixed_string_pattern[LOG_GREP_PATTERN_BUFFER_SIZE] = {0};
739 bool is_fixed_string_pattern = false;
740 bool case_insensitive_fixed = false;
741
742 // Get code from CLI pattern or interactive grep pattern
743 if (global_pat && global_pat->is_fixed_string) {
744 SAFE_STRNCPY(fixed_string_pattern, global_pat->parsed_pattern,
745 sizeof(fixed_string_pattern));
746 is_fixed_string_pattern = true;
747 case_insensitive_fixed = global_pat->case_insensitive;
748 } else if (global_pat && global_pat->compiled) {
749 code = global_pat->compiled;
750 match_data = get_thread_match_data();
751 } else if (is_log_search) {
752 // Interactive grep global highlighting - get pattern from grep state
753 code = (pcre2_code *)log_search_copy_pattern();
754 if (code) {
755 match_data = pcre2_match_data_create_from_pattern(code, NULL);
756 } else {
757 // No regex pattern - check if it's a fixed string pattern in
758 // interactive grep
759 int pattern_len = log_search_get_input_len();
760 const char *pattern = log_search_get_input_buffer();
761 if (pattern_len > 0 && pattern &&
762 pattern_len < (int)sizeof(fixed_string_pattern)) {
763 grep_parse_result_t parsed = grep_parse_pattern(pattern);
764 const char *literal = parsed.valid ? parsed.pattern : pattern;
765 SAFE_STRNCPY(fixed_string_pattern, literal,
766 sizeof(fixed_string_pattern) - 1);
767 is_fixed_string_pattern = true;
768 case_insensitive_fixed = log_search_get_case_insensitive();
769 }
770 }
771 }
772
773 if ((!code || !match_data) && !is_fixed_string_pattern) {
774 if (match_data && is_log_search) {
775 pcre2_match_data_free(match_data); // Free if we created it
776 }
777 if (is_log_search && !global_pat && code)
778 pcre2_code_free(code);
779 return colored_text; // Fall back to no highlighting
780 }
781
782 size_t plain_len = strlen(plain_text);
783 size_t colored_len = strlen(colored_text);
784 char *dst = highlight_buffer;
785 size_t plain_offset = 0;
786 size_t colored_pos = 0;
787
788 // Handle fixed string global matching
789 if (is_fixed_string_pattern) {
790 while (plain_offset < plain_len) {
791 // Find next occurrence of fixed string
792 const char *found = NULL;
793 if (case_insensitive_fixed) {
794 found =
795 utf8_strcasestr(plain_text + plain_offset, fixed_string_pattern);
796 } else {
797 found = strstr(plain_text + plain_offset, fixed_string_pattern);
798 }
799
800 if (!found) {
801 break; // No more matches
802 }
803
804 size_t plain_match_start = (size_t)(found - plain_text);
805 size_t plain_match_end =
806 plain_match_start + strlen(fixed_string_pattern);
807
808 // Map to colored text positions (same as single-match path)
809 size_t colored_match_start =
810 map_plain_to_colored_pos(colored_text, plain_match_start);
811 size_t colored_match_end =
812 map_plain_to_colored_pos(colored_text, plain_match_end);
813
814 // Reserve the untouched tail plus the next background/reset sequences.
815 if ((size_t)(dst - highlight_buffer) + colored_len - colored_pos + 37 >=
816 sizeof(highlight_buffer)) {
817 return colored_text;
818 }
819
820 // Copy text before match
821 if (colored_match_start > colored_pos) {
822 memcpy(dst, colored_text + colored_pos,
823 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 with background
833 size_t match_byte_len = colored_match_end - colored_match_start;
834 memcpy(dst, colored_text + colored_match_start, match_byte_len);
835 dst += match_byte_len;
836
837 // Reset background
838 memcpy(dst, "\x1b[49m", 5);
839 dst += 5;
840
841 colored_pos = colored_match_end;
842 plain_offset = plain_match_end;
843 }
844
845 // Copy remaining text
846 if (colored_pos < colored_len) {
847 memcpy(dst, colored_text + colored_pos, colored_len - colored_pos);
848 dst += (colored_len - colored_pos);
849 }
850
851 // Reset both background and foreground at end
852 *dst = '\0';
853 return highlight_buffer;
854 }
855
856 // Find all matches in plain text and highlight in colored text (regex
857 // matching)
858 while (plain_offset < plain_len) {
859 int rc = asciichat_pcre2_match(code, (PCRE2_SPTR)plain_text, plain_len,
860 plain_offset, 0, match_data, NULL);
861 if (rc < 0) {
862 break; // No more matches
863 }
864
865 PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
866 size_t plain_match_start = (size_t)ovector[0];
867 size_t plain_match_end = (size_t)ovector[1];
868
869 // Map to colored text positions
870 size_t colored_match_start =
871 map_plain_to_colored_pos(colored_text, plain_match_start);
872 size_t colored_match_end =
873 map_plain_to_colored_pos(colored_text, plain_match_end);
874
875 // Copy text before match
876 if (colored_match_start > colored_pos) {
877 memcpy(dst, colored_text + colored_pos,
878 colored_match_start - colored_pos);
879 dst += (colored_match_start - colored_pos);
880 }
881
882 // Add highlight background
883 uint8_t r, g, b;
884 get_highlight_color(&r, &g, &b);
885 dst = append_truecolor_bg(dst, r, g, b);
886
887 // Copy matched text, re-applying background after any [0m or [00m reset
888 // codes
889 size_t match_byte_len = colored_match_end - colored_match_start;
890 const char *match_src = colored_text + colored_match_start;
891 char *dst_end = highlight_buffer + sizeof(highlight_buffer) -
892 1; // Absolute buffer end
893 size_t i = 0;
894 while (i < match_byte_len) {
895 // Check for [0m or [00m reset codes
896 if (i + 4 <= match_byte_len && match_src[i] == '\x1b' &&
897 match_src[i + 1] == '[' && match_src[i + 2] == '0' &&
898 match_src[i + 3] == 'm') {
899 // Found [0m - copy it and re-apply background (if room)
900 if (dst + 4 >= dst_end)
901 break; // Not enough space for the reset code itself
902 *dst++ = match_src[i++]; // ESC
903 *dst++ = match_src[i++]; // '['
904 *dst++ = match_src[i++]; // '0'
905 *dst++ = match_src[i++]; // 'm'
906 // Re-apply highlight background after reset (only if room)
907 if (dst + 20 < dst_end) {
908 uint8_t r2, g2, b2;
909 get_highlight_color(&r2, &g2, &b2);
910 dst = append_truecolor_bg(dst, r2, g2, b2);
911 }
912 } else if (i + 5 <= match_byte_len && match_src[i] == '\x1b' &&
913 match_src[i + 1] == '[' && match_src[i + 2] == '0' &&
914 match_src[i + 3] == '0' && match_src[i + 4] == 'm') {
915 // Found [00m - copy it and re-apply background (if room)
916 if (dst + 5 >= dst_end)
917 break; // Not enough space for the reset code itself
918 *dst++ = match_src[i++]; // ESC
919 *dst++ = match_src[i++]; // '['
920 *dst++ = match_src[i++]; // '0'
921 *dst++ = match_src[i++]; // '0'
922 *dst++ = match_src[i++]; // 'm'
923 // Re-apply highlight background after reset (only if room)
924 if (dst + 20 < dst_end) {
925 uint8_t r2, g2, b2;
926 get_highlight_color(&r2, &g2, &b2);
927 dst = append_truecolor_bg(dst, r2, g2, b2);
928 }
929 } else {
930 // Regular character - just copy
931 if (dst + 1 >= dst_end)
932 break;
933 *dst++ = match_src[i++];
934 }
935 }
936
937 // Reset background only
938 memcpy(dst, "\x1b[49m", 5);
939 dst += 5;
940
941 colored_pos = colored_match_end;
942 plain_offset = plain_match_end;
943
944 // Prevent infinite loop on zero-length matches
945 if (plain_match_end == plain_match_start) {
946 plain_offset++;
947 }
948 }
949
950 // Copy remaining text
951 if (colored_pos < colored_len) {
952 memcpy(dst, colored_text + colored_pos, colored_len - colored_pos);
953 dst += (colored_len - colored_pos);
954 }
955
956 // Reset both background and foreground at end to prevent color bleeding
957 *dst = '\0';
958
959 // Clean up match data if we created it for interactive grep
960 if (is_log_search && match_data && !global_pat) {
961 pcre2_match_data_free(match_data);
962 }
963 if (is_log_search && !global_pat && code)
964 pcre2_code_free(code);
965
966 return highlight_buffer;
967 }
968
969 // Single match highlighting (same logic as global path)
970 // map_plain_to_colored_pos(N) returns byte position after counting N plain
971 // bytes
972 size_t colored_start = map_plain_to_colored_pos(colored_text, match_start);
973 size_t colored_end =
974 map_plain_to_colored_pos(colored_text, match_start + match_len);
975
976 size_t colored_len = strlen(colored_text);
977 char *dst = highlight_buffer;
978
979 // Copy everything before the match
980 if (colored_start > 0) {
981 memcpy(dst, colored_text, colored_start);
982 dst += colored_start;
983 }
984
985 // Add highlight background
986 uint8_t r, g, b;
987 get_highlight_color(&r, &g, &b);
988 dst = append_truecolor_bg(dst, r, g, b);
989
990 // Copy matched text, re-applying background after any [0m or [00m reset codes
991 size_t match_byte_len = colored_end - colored_start;
992 const char *match_src = colored_text + colored_start;
993 char *dst_end =
994 highlight_buffer + sizeof(highlight_buffer) - 1; // Absolute buffer end
995 size_t i = 0;
996
997 while (i < match_byte_len) {
998 // Check for [0m or [00m reset codes
999 if (i + 4 <= match_byte_len && match_src[i] == '\x1b' &&
1000 match_src[i + 1] == '[' && match_src[i + 2] == '0' &&
1001 match_src[i + 3] == 'm') {
1002 // Found [0m - copy it and re-apply background (if room)
1003 if (dst + 4 >= dst_end)
1004 break; // Not enough space for even the reset code
1005 *dst++ = match_src[i++]; // ESC
1006 *dst++ = match_src[i++]; // '['
1007 *dst++ = match_src[i++]; // '0'
1008 *dst++ = match_src[i++]; // 'm'
1009 // Re-apply highlight background after reset (only if room)
1010 if (dst + 20 < dst_end) {
1011 uint8_t r2, g2, b2;
1012 get_highlight_color(&r2, &g2, &b2);
1013 dst = append_truecolor_bg(dst, r2, g2, b2);
1014 }
1015 } else if (i + 5 <= match_byte_len && match_src[i] == '\x1b' &&
1016 match_src[i + 1] == '[' && match_src[i + 2] == '0' &&
1017 match_src[i + 3] == '0' && match_src[i + 4] == 'm') {
1018 // Found [00m - copy it and re-apply background (if room)
1019 if (dst + 5 >= dst_end)
1020 break; // Not enough space for even the reset code
1021 *dst++ = match_src[i++]; // ESC
1022 *dst++ = match_src[i++]; // '['
1023 *dst++ = match_src[i++]; // '0'
1024 *dst++ = match_src[i++]; // '0'
1025 *dst++ = match_src[i++]; // 'm'
1026 // Re-apply highlight background after reset (only if room)
1027 if (dst + 20 < dst_end) {
1028 uint8_t r3, g3, b3;
1029 get_highlight_color(&r3, &g3, &b3);
1030 dst = append_truecolor_bg(dst, r3, g3, b3);
1031 }
1032 } else {
1033 // Regular character - just copy
1034 if (dst + 1 >= dst_end) {
1035 break;
1036 }
1037 *dst++ = match_src[i++];
1038 }
1039 }
1040
1041 // Reset only the background color to preserve foreground colors from headers
1042 // Using \x1b[49m (reset background only) instead of \x1b[0m (reset all)
1043 memcpy(dst, "\x1b[49m", 5);
1044 dst += 5;
1045
1046 // Copy remaining text
1047 size_t remaining = colored_len - colored_end;
1048 if (remaining > 0) {
1049 memcpy(dst, colored_text + colored_end, remaining);
1050 dst += remaining;
1051 }
1052
1053 *dst = '\0';
1054 return highlight_buffer;
1055}
grep_parse_result_t grep_parse_pattern(const char *input)
Parse pattern in /pattern/flags or pattern/flags format.
Definition grep.c:269
#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:98
const char * utf8_strcasestr(const char *haystack, const char *needle)
Case-insensitive substring search with full Unicode support.
Definition utf8.c:212
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:175
bool log_search_get_global_highlight(void)
Check if global highlighting (/g flag) is enabled in current pattern.
Definition search.c:991
int log_search_get_input_len(void)
Get current input buffer length (must hold mutex).
Definition search.c:1033
const char * log_search_get_input_buffer(void)
Get current input buffer content (must hold mutex).
Definition search.c:1037
bool log_search_is_active(void)
Check if filtering is active.
Definition search.c:430
bool log_search_get_case_insensitive(void)
Check if case-insensitive flag is set (must hold mutex).
Definition search.c:1041
void * log_search_copy_pattern(void)
Get the compiled regex pattern for interactive grep (internal use).
Definition search.c:1006
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:49
bool is_fixed_string
True for fixed string matching (no regex).
Definition grep.c:48
char * parsed_pattern
Parsed pattern (without delimiters/flags).
Definition grep.c:46
pcre2_code * compiled
Compiled pattern (NULL if fixed string).
Definition grep.c:47

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 686 of file grep.c.

688 {
689 const char *result =
690 grep_highlight_colored(colored_text, plain_text, match_start, match_len);
691 if (result) {
692 size_t result_len = strlen(result) + 1;
693 char *copy = SAFE_MALLOC(result_len, char *);
694 if (copy) {
695 memcpy(copy, result, result_len);
696 return copy;
697 }
698 }
699 return NULL;
700}
#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 418 of file grep.c.

418 {
419 // Reject NULL or empty patterns
420 if (!pattern) {
421 return SET_ERRNO(ERROR_INVALID_PARAM, "Pattern cannot be NULL");
422 }
423 if (strlen(pattern) == 0) {
424 return SET_ERRNO(ERROR_INVALID_PARAM, "Pattern cannot be empty");
425 }
426
427 // Parse pattern
428 parse_result_t parsed = grep_parse_pattern(pattern);
429 if (!parsed.valid) {
430 log_error("Invalid --grep pattern format: \"%s\"", pattern);
431 log_error("Use /pattern/flags format (e.g., \"/query/ig\") or plain regex "
432 "(e.g., \"query\")");
433 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid --grep pattern format");
434 }
435
436 // Allocate or expand pattern array
437 if (g_filter_state.pattern_count >= g_filter_state.pattern_capacity) {
438 int new_capacity = (g_filter_state.pattern_capacity == 0)
439 ? 4
440 : g_filter_state.pattern_capacity * 2;
441 grep_pattern_t *new_patterns =
442 SAFE_REALLOC(g_filter_state.patterns,
443 new_capacity * sizeof(grep_pattern_t), grep_pattern_t *);
444 if (!new_patterns) {
445 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate pattern array");
446 }
447 g_filter_state.patterns = new_patterns;
448 g_filter_state.pattern_capacity = new_capacity;
449 }
450
451 // Add new pattern
452 grep_pattern_t *new_pat =
453 &g_filter_state.patterns[g_filter_state.pattern_count];
454 memset(new_pat, 0, sizeof(*new_pat));
455
456 // Make a copy of the original pattern string (argv pointers may be
457 // deallocated)
458 char *original_copy = SAFE_MALLOC(strlen(pattern) + 1, char *);
459 if (!original_copy) {
460 return SET_ERRNO(ERROR_MEMORY,
461 "Failed to allocate original pattern string");
462 }
463 memcpy(original_copy, pattern, strlen(pattern) + 1);
464 new_pat->original = original_copy;
465
466 new_pat->parsed_pattern = SAFE_MALLOC(strlen(parsed.pattern) + 1, char *);
467 if (!new_pat->parsed_pattern) {
468 SAFE_FREE(original_copy);
469 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate pattern string");
470 }
471 memcpy(new_pat->parsed_pattern, parsed.pattern, strlen(parsed.pattern) + 1);
472
473 new_pat->is_fixed_string = parsed.is_fixed_string;
474 new_pat->case_insensitive = parsed.case_insensitive;
475 new_pat->invert = parsed.invert;
476 new_pat->global_flag = parsed.global_flag;
477 new_pat->context_before = parsed.context_before;
478 new_pat->context_after = parsed.context_after;
479
480 // Compile regex (skip for fixed strings)
481 if (!parsed.is_fixed_string) {
482 new_pat->compiled =
484 if (!new_pat->compiled) {
485 SAFE_FREE(original_copy);
486 SAFE_FREE(new_pat->parsed_pattern);
487 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to compile regex pattern");
488 }
489
490 // Validate compilation
491 pcre2_code *code = new_pat->compiled;
492 if (!code) {
493 SAFE_FREE(new_pat->parsed_pattern);
494 return SET_ERRNO(ERROR_INVALID_PARAM, "Regex compilation failed");
495 }
496 }
497
498 g_filter_state.pattern_count++;
499
500 // Update context buffer size if needed
501 if (parsed.context_before > g_filter_state.buffer_size) {
502 // Reallocate line buffer
503 char **new_buffer =
504 SAFE_REALLOC(g_filter_state.line_buffer,
505 parsed.context_before * sizeof(char *), char **);
506 if (!new_buffer) {
507 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate context line buffer");
508 }
509 // Initialize new slots
510 for (int i = g_filter_state.buffer_size; i < parsed.context_before; i++) {
511 new_buffer[i] = NULL;
512 }
513 g_filter_state.line_buffer = new_buffer;
514 g_filter_state.buffer_size = parsed.context_before;
515 }
516
517 // Update max context_after
518 if (parsed.context_after > g_filter_state.max_context_after) {
519 g_filter_state.max_context_after = parsed.context_after;
520 }
521
522 g_filter_state.enabled = true;
523 log_info("Added --grep pattern #%d: %s", g_filter_state.pattern_count,
524 pattern);
525
526 return ASCIICHAT_OK;
527}
#define SET_ERRNO(code,...)
grep_parse_result_t parse_result_t
Definition grep.c:225
int pattern_capacity
Allocated capacity.
Definition grep.c:62
#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:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
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:52
int context_after
Lines after match (A flag).
Definition grep.c:53
bool global_flag
Highlight all matches (g flag).
Definition grep.c:51
bool invert
Invert match (I flag).
Definition grep.c:50

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.

◆ grep_parse_pattern()

grep_parse_result_t grep_parse_pattern ( const char * input)

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

Supports two formats:

  • Format 1: /pattern/flags (e.g., "/error/igC2")
  • Format 2: plain pattern (e.g., "error")

Flags: i(case-insensitive), m(multiline), s(dotall), x(extended), g(global highlight), I(invert), F(fixed string), A<n>(after context), B<n>(before context), C<n>(both context)

Parameters
inputInput pattern string
Returns
Parsed result with pattern, flags, and validity

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 269 of file grep.c.

269 {
270 parse_result_t result = {0};
271 result.pcre2_options = PCRE2_UTF | PCRE2_UCP; // Default: UTF-8 mode
272
273 if (!input || strlen(input) == 0) {
274 return result; // Invalid: empty pattern
275 }
276
277 size_t len = strlen(input);
278 const char *closing_slash = NULL;
279 const char *pattern_start = input;
280
281 // Check if pattern uses /pattern/flags format (explicit)
282 if (input[0] == '/') {
283 // Format 1: /pattern/flags
284 if (len < 3) {
285 return result; // Invalid: too short for /pattern/ format
286 }
287
288 // Find closing slash - don't treat backslash as an escape character
289 // (backslashes are regex escapes, not delimiter escapes)
290 closing_slash = strchr(input + 1, '/');
291 if (!closing_slash) {
292 return result; // Invalid: missing closing /
293 }
294
295 pattern_start = input + 1;
296 } else {
297 // Check for pattern/flags format (implicit, no leading slash)
298 // Find the last forward slash to use as delimiter
299 closing_slash = strrchr(input, '/');
300
301 const char *implicit_flags = closing_slash ? closing_slash + 1 : NULL;
302 bool implicit_flags_valid =
303 closing_slash && closing_slash > input && *implicit_flags != '\0';
304 if (implicit_flags_valid) {
305 for (const char *flag = implicit_flags; *flag; flag++) {
306 if (!strchr("imsxgIF", *flag) && *flag != 'A' && *flag != 'B' &&
307 *flag != 'C' && !(*flag >= '0' && *flag <= '9')) {
308 implicit_flags_valid = false;
309 break;
310 }
311 }
312 }
313
314 if (implicit_flags_valid) {
315 // There's at least one slash (not at the beginning)
316 // Try to parse as pattern/flags format
317 pattern_start = input;
318 } else {
319 // No slash or slash at beginning - treat as plain pattern
320 closing_slash = NULL;
321 }
322 }
323
324 if (closing_slash) {
325 // Extract pattern between start and closing slash
326 size_t pattern_len = (size_t)(closing_slash - pattern_start);
327 if (pattern_len == 0) {
328 return result; // Invalid: empty pattern
329 }
330 if (pattern_len >= sizeof(result.pattern)) {
331 pattern_len = sizeof(result.pattern) - 1;
332 }
333 memcpy(result.pattern, pattern_start, pattern_len);
334 result.pattern[pattern_len] = '\0';
335
336 // Parse flags after closing slash
337 // First pass: check for F flag
338 const char *flags = closing_slash + 1;
339 bool has_F_flag = (strchr(flags, 'F') != NULL);
340
341 // Parse all flags
342 for (const char *p = flags; *p; p++) {
343 char c = *p;
344
345 // Single-character flags
346 if (c == 'i') {
347 result.pcre2_options |= PCRE2_CASELESS;
348 result.case_insensitive = true;
349 } else if (c == 'm') {
350 result.pcre2_options |= PCRE2_MULTILINE;
351 } else if (c == 's') {
352 result.pcre2_options |= PCRE2_DOTALL;
353 } else if (c == 'x') {
354 result.pcre2_options |= PCRE2_EXTENDED;
355 } else if (c == 'g') {
356 result.global_flag = true;
357 } else if (c == 'I') {
358 result.invert = true;
359 } else if (c == 'F') {
360 result.is_fixed_string = true;
361 }
362 // Multi-character flags with integers
363 else if (c == 'A') {
364 p++; // Move to digits
365 int num = 0;
366 while (*p >= '0' && *p <= '9') {
367 num = num * 10 + (*p - '0');
368 p++;
369 }
370 p--; // Back up one (for loop will increment)
371 result.context_after = (num > 0) ? num : 1; // Default to 1 if no number
372 } else if (c == 'B') {
373 p++;
374 int num = 0;
375 while (*p >= '0' && *p <= '9') {
376 num = num * 10 + (*p - '0');
377 p++;
378 }
379 p--;
380 result.context_before = (num > 0) ? num : 1;
381 } else if (c == 'C') {
382 p++;
383 int num = 0;
384 while (*p >= '0' && *p <= '9') {
385 num = num * 10 + (*p - '0');
386 p++;
387 }
388 p--;
389 int ctx = (num > 0) ? num : 1;
390 result.context_before = ctx;
391 result.context_after = ctx;
392 } else {
393 // Invalid flag character - only error if not using F flag
394 if (!has_F_flag) {
395 return result; // Invalid
396 }
397 // Otherwise ignore invalid flags (they're part of the fixed string
398 // context)
399 }
400 }
401 } else {
402 // Format 3: Plain pattern without slashes (treat as regex, no flags)
403 size_t pattern_len = len;
404 if (pattern_len >= sizeof(result.pattern)) {
405 pattern_len = sizeof(result.pattern) - 1;
406 }
407 memcpy(result.pattern, input, pattern_len);
408 result.pattern[pattern_len] = '\0';
409
410 // No flags for plain format - just use default options
411 // (PCRE2_UTF | PCRE2_UCP already set at the top)
412 }
413
414 result.valid = true;
415 return result;
416}

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 1173 of file grep.c.

1173 {
1174 grep_pattern_t *copy = NULL;
1175 asciichat_error_t result = grep_copy_patterns(
1176 g_filter_state.saved_patterns, g_filter_state.saved_pattern_count, &copy);
1177 if (result != ASCIICHAT_OK)
1178 return result;
1179 for (int i = 0; i < g_filter_state.pattern_count; i++)
1180 grep_free_pattern(&g_filter_state.patterns[i]);
1181 SAFE_FREE(g_filter_state.patterns);
1182 g_filter_state.patterns = copy;
1183 g_filter_state.pattern_count = g_filter_state.saved_pattern_count;
1184 g_filter_state.pattern_capacity = g_filter_state.saved_pattern_count;
1185 g_filter_state.enabled = g_filter_state.saved_enabled;
1186 return ASCIICHAT_OK;
1187}
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 1157 of file grep.c.

1157 {
1158 grep_pattern_t *copy = NULL;
1159 asciichat_error_t result = grep_copy_patterns(
1160 g_filter_state.patterns, g_filter_state.pattern_count, &copy);
1161 if (result != ASCIICHAT_OK)
1162 return result;
1163 for (int i = 0; i < g_filter_state.saved_pattern_count; i++)
1164 grep_free_pattern(&g_filter_state.saved_patterns[i]);
1165 SAFE_FREE(g_filter_state.saved_patterns);
1166 g_filter_state.saved_patterns = copy;
1167 g_filter_state.saved_pattern_count = g_filter_state.pattern_count;
1168 g_filter_state.saved_pattern_capacity = g_filter_state.pattern_count;
1169 g_filter_state.saved_enabled = g_filter_state.enabled;
1170 return ASCIICHAT_OK;
1171}

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 529 of file grep.c.

530 {
531 // Reject NULL lines
532 if (!log_line) {
533 if (match_start)
534 *match_start = 0;
535 if (match_len)
536 *match_len = 0;
537 return false;
538 }
539
540 // If filtering disabled, output everything
541 if (!g_filter_state.enabled) {
542 return true;
543 }
544
545 // Check if we're in "context after" mode (outputting lines after a match)
546 if (g_filter_state.lines_after_match > 0) {
547 g_filter_state.lines_after_match--;
548 *match_start = 0;
549 *match_len = 0;
550
551 // Store in buffer even during context-after mode
552 if (g_filter_state.buffer_size > 0) {
553 SAFE_FREE(g_filter_state.line_buffer[g_filter_state.buffer_pos]);
554 size_t line_len = strlen(log_line) + 1;
555 g_filter_state.line_buffer[g_filter_state.buffer_pos] =
556 SAFE_MALLOC(line_len, char *);
557 if (g_filter_state.line_buffer[g_filter_state.buffer_pos]) {
558 memcpy(g_filter_state.line_buffer[g_filter_state.buffer_pos], log_line,
559 line_len);
560 }
561 g_filter_state.buffer_pos =
562 (g_filter_state.buffer_pos + 1) % g_filter_state.buffer_size;
563 }
564
565 return true; // Output context line
566 }
567
568 pcre2_match_data *match_data = get_thread_match_data();
569 size_t line_len = strlen(log_line);
570
571 // Try each pattern (OR logic)
572 bool any_match = false;
573 grep_pattern_t *matched_pattern = NULL;
574
575 for (int i = 0; i < g_filter_state.pattern_count; i++) {
576 grep_pattern_t *pat = &g_filter_state.patterns[i];
577 bool this_match = false;
578
579 if (pat->is_fixed_string) {
580 // Fixed string matching (with optional case-insensitive support)
581 const char *found;
582 if (pat->case_insensitive) {
583 // Unicode-aware case-insensitive search
584 found = utf8_strcasestr(log_line, pat->parsed_pattern);
585 } else {
586 // Case-sensitive search
587 found = strstr(log_line, pat->parsed_pattern);
588 }
589
590 if (found) {
591 this_match = true;
592 if (!matched_pattern) {
593 *match_start = (size_t)(found - log_line);
594 *match_len = strlen(pat->parsed_pattern);
595 matched_pattern = pat;
596 }
597 }
598 } else {
599 // Regex matching
600 if (!match_data || !pat->compiled) {
601 continue;
602 }
603
604 pcre2_code *code = pat->compiled;
605 if (!code) {
606 continue;
607 }
608
609 int rc = asciichat_pcre2_match(code, (PCRE2_SPTR)log_line, line_len, 0, 0,
610 match_data, NULL);
611 if (rc >= 0) {
612 this_match = true;
613 if (!matched_pattern) {
614 PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
615 *match_start = (size_t)ovector[0];
616 *match_len = (size_t)(ovector[1] - ovector[0]);
617 matched_pattern = pat;
618 }
619 }
620 }
621
622 // Apply invert flag
623 if (pat->invert) {
624 this_match = !this_match;
625 }
626
627 if (this_match) {
628 any_match = true;
629 // Update matched_pattern if this one has more context
630 if (!matched_pattern || (pat->context_before + pat->context_after) >
631 (matched_pattern->context_before +
632 matched_pattern->context_after)) {
633 matched_pattern = pat;
634 }
635 }
636 }
637
638 // If any pattern matched
639 if (any_match && matched_pattern) {
640 // Output context_before lines from circular buffer
641 if (matched_pattern->context_before > 0 && g_filter_state.buffer_size > 0) {
642 int num_lines =
643 (matched_pattern->context_before < g_filter_state.buffer_size)
644 ? matched_pattern->context_before
645 : g_filter_state.buffer_size;
646
647 // Calculate starting position in circular buffer
648 int start_pos =
649 (g_filter_state.buffer_pos - num_lines + g_filter_state.buffer_size) %
650 g_filter_state.buffer_size;
651
652 // Output buffered lines
653 for (int i = 0; i < num_lines; i++) {
654 int pos = (start_pos + i) % g_filter_state.buffer_size;
655 if (g_filter_state.line_buffer[pos]) {
656 fprintf(stderr, "%s\n", g_filter_state.line_buffer[pos]);
657 }
658 }
659 }
660
661 // Set up context_after counter
662 if (matched_pattern->context_after > 0) {
663 g_filter_state.lines_after_match = matched_pattern->context_after;
664 }
665
666 return true; // Match found, output line
667 }
668
669 // No match - store in context buffer for potential future use
670 if (g_filter_state.buffer_size > 0) {
671 SAFE_FREE(g_filter_state.line_buffer[g_filter_state.buffer_pos]);
672 size_t line_len_copy = strlen(log_line) + 1;
673 g_filter_state.line_buffer[g_filter_state.buffer_pos] =
674 SAFE_MALLOC(line_len_copy, char *);
675 if (g_filter_state.line_buffer[g_filter_state.buffer_pos]) {
676 memcpy(g_filter_state.line_buffer[g_filter_state.buffer_pos], log_line,
677 line_len_copy);
678 }
679 g_filter_state.buffer_pos =
680 (g_filter_state.buffer_pos + 1) % g_filter_state.buffer_size;
681 }
682
683 return false; // No match, suppress line
684}
int buffer_size
Size of circular buffer.
Definition grep.c:69

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