3 * selector is a simple command line utility for selection of strings
4 * with a dynamic pattern-matching.
6 * Copyright (c) 2009 Francois Fleuret
7 * Written by Francois Fleuret <francois@fleuret.org>
9 * This file is part of selector.
11 * selector is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 3 as
13 * published by the Free Software Foundation.
15 * selector is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with selector. If not, see <http://www.gnu.org/licenses/>.
25 // To use it as a super-history-search for bash:
26 // selector -q -b -i -d -v -w -l ${HISTSIZE} <(history)
29 // #include <iostream>
37 #include <sys/ioctl.h>
44 const int buffer_size = 4096;
46 // Yeah, global variables!
48 int nb_lines_max = 1000;
49 char pattern_separator = ';';
50 char label_separator = '\0';
51 int output_to_vt_buffer = 0;
52 int add_control_qs = 0;
56 int inverse_order = 0;
57 int remove_duplicates = 0;
59 int case_sensitive = 0;
63 int attr_modeline, attr_focus_line, attr_error;
65 //////////////////////////////////////////////////////////////////////
67 void inject_into_tty_buffer(char *string) {
68 struct termios oldtio, newtio;
70 tcgetattr(STDIN_FILENO, &oldtio);
71 memset(&newtio, 0, sizeof(newtio));
72 // Set input mode (non-canonical, *no echo*,...)
73 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
74 const char control_q = '\021';
75 // Put the selected string in the tty input buffer
76 for(k = string; *k; k++) {
77 if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
78 // Add ^Q to quote control characters
79 ioctl(STDIN_FILENO, TIOCSTI, &control_q);
81 ioctl(STDIN_FILENO, TIOCSTI, k);
83 // Restore the old settings
84 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
87 //////////////////////////////////////////////////////////////////////
89 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
90 if(n_opt + n >= argc) {
91 fprintf(stderr, "Missing argument for %s, expecting %s.\n",
97 int string_to_positive_integer(char *string) {
103 for(s = string; *s; s++) {
104 if(*s >= '0' && *s <= '9') {
105 result = result * 10 + (int) (*s - '0');
111 fprintf(stderr, "Value `%s' is not a positive integer.\n", string);
118 void error_feedback() {
126 //////////////////////////////////////////////////////////////////////
127 // A quick and dirty hash table
129 // The table itself stores indexes of the strings taken in a char
130 // **table. When a string is added, if it was already in the table,
131 // the new index replaces the previous one.
133 int *new_hash_table(int hash_table_size) {
135 result = (int *) malloc(hash_table_size * sizeof(int));
136 for(k = 0; k < hash_table_size; k++) {
142 // Adds new_string in the table, associated to new_index. If this
143 // string was not already in the table, returns -1. Otherwise, returns
144 // the previous index it had.
146 int test_and_add(char *new_string, int new_index,
148 int *hash_table, int hash_table_size) {
150 unsigned int code = 0;
153 // This is my recipe. I checked, it seems to work (as long as
154 // hash_table_size is not a multiple of 387433 that should be okay)
156 for(k = 0; new_string[k]; k++) {
157 code = code * 387433 + (unsigned int) (new_string[k]);
160 code = code % hash_table_size;
162 while(hash_table[code] >= 0) {
163 // There is a string with that code
164 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
165 // It is the same string, we keep a copy of the stored index
166 int result = hash_table[code];
168 hash_table[code] = new_index;
169 // And return the previous one
172 // This collision was not the same string, let's move to the next
174 code = (code + 1) % hash_table_size;
177 // This string was not already in there, store the index in the
178 // table and return -1
179 hash_table[code] = new_index;
183 //////////////////////////////////////////////////////////////////////
184 // A matcher matches either with a collection of substrings, or with a
192 char *splitted_patterns, **patterns;
195 int match(char *string, matcher_t *matcher) {
197 if(matcher->nb_patterns >= 0) {
198 if(matcher->case_sensitive) {
199 for(n = 0; n < matcher->nb_patterns; n++) {
200 if(strstr(string, matcher->patterns[n]) == 0) return 0;
203 for(n = 0; n < matcher->nb_patterns; n++) {
204 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
209 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
213 void free_matcher(matcher_t *matcher) {
214 if(matcher->nb_patterns < 0) {
215 if(!matcher->regexp_error) regfree(&matcher->preg);
217 free(matcher->splitted_patterns);
218 free(matcher->patterns);
222 void initialize_matcher(int use_regexp, int case_sensitive,
223 matcher_t *matcher, const char *pattern) {
228 matcher->nb_patterns = -1;
229 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
231 matcher->regexp_error = 0;
232 matcher->nb_patterns = 1;
233 matcher->case_sensitive = case_sensitive;
235 for(s = pattern; *s; s++) {
236 if(*s == pattern_separator) {
237 matcher->nb_patterns++;
241 matcher->splitted_patterns = (char *) malloc((strlen(pattern) + 1) * sizeof(char));
242 matcher->patterns = (char **) malloc(matcher->nb_patterns * sizeof(char *));
244 strcpy(matcher->splitted_patterns, pattern);
247 char *last_pattern_start = matcher->splitted_patterns;
248 for(t = matcher->splitted_patterns; n < matcher->nb_patterns; t++) {
249 if(*t == pattern_separator || *t == '\0') {
251 matcher->patterns[n++] = last_pattern_start;
252 last_pattern_start = t + 1;
258 //////////////////////////////////////////////////////////////////////
261 void delete_char(char *buffer, int *position) {
262 if(buffer[*position]) {
264 while(c < buffer_size && buffer[c]) {
265 buffer[c] = buffer[c+1];
268 } else error_feedback();
271 void backspace_char(char *buffer, int *position) {
273 if(buffer[*position]) {
274 int c = *position - 1;
276 buffer[c] = buffer[c+1];
280 buffer[*position - 1] = '\0';
284 } else error_feedback();
287 void insert_char(char *buffer, int *position, char character) {
288 if(strlen(buffer) < buffer_size - 1) {
290 char t = buffer[c], u;
299 buffer[(*position)++] = character;
300 } else error_feedback();
303 void kill_before_cursor(char *buffer, int *position) {
305 while(buffer[*position + s]) {
306 buffer[s] = buffer[*position + s];
313 void kill_after_cursor(char *buffer, int *position) {
314 buffer[*position] = '\0';
317 //////////////////////////////////////////////////////////////////////
319 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
320 int line = current_line - 1;
321 while(line >= 0 && !match(lines[line], matcher)) line--;
325 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
326 int line = current_line + 1;
327 while(line < nb_lines && !match(lines[line], matcher)) line++;
335 //////////////////////////////////////////////////////////////////////
337 // The value passed to this routine in current_focus_line is the index
338 // of the line we should have highlited if there was no motion and if
339 // it matched the matcher. So, the line actually highlighted is the
340 // first one matching the matcher in that order: (1)
341 // current_focus_line after motion, (2) the first with a greater
342 // index, (3) the first with a lesser index.
344 // The index of the line actually shown highlighted is written in
345 // displayed_focus_line (it can be -1)
347 // If there is a motion and a line is actually shown highlighted, its
348 // value is written in current_focus_line.
350 void update_screen(int *current_focus_line, int *displayed_focus_line,
352 int nb_lines, char **lines,
356 char buffer[buffer_size];
360 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
362 int console_width = getmaxx(stdscr);
363 int console_height = getmaxy(stdscr);
365 // First, we find a visible line.
367 int nb_printed_lines = 0;
369 use_default_colors();
373 if(matcher.regexp_error) {
375 addnstr("Regexp syntax error", console_width);
377 } else if(nb_lines > 0) {
379 if(match(lines[*current_focus_line], &matcher)) {
380 new_focus_line = *current_focus_line;
382 new_focus_line = next_visible(*current_focus_line, nb_lines, lines, &matcher);
383 if(new_focus_line < 0) {
384 new_focus_line = previous_visible(*current_focus_line, nb_lines, lines, &matcher);
388 // If we found a visible line and we should move, let's move
390 if(new_focus_line >= 0 && motion != 0) {
391 int l = new_focus_line;
393 // We want to go down, let's find the first visible line below
394 for(m = 0; l >= 0 && m < motion; m++) {
395 l = next_visible(l, nb_lines, lines, &matcher);
401 // We want to go up, let's find the first visible line above
402 for(m = 0; l >= 0 && m < -motion; m++) {
403 l = previous_visible(l, nb_lines, lines, &matcher);
411 // Here new_focus_line is either a line number matching the pattern, or -1
413 if(new_focus_line >= 0) {
415 int first_line = new_focus_line, last_line = new_focus_line, nb_match = 1;
417 // We find the first and last line to show, so that the total of
418 // visible lines between them (them included) is console_height-1
420 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
424 while(first_line > 0 && !match(lines[first_line], &matcher)) {
427 if(match(lines[first_line], &matcher)) {
432 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
434 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
438 if(match(lines[last_line], &matcher)) {
444 // Now we display them
446 for(l = first_line; l <= last_line; l++) {
447 if(match(lines[l], &matcher)) {
450 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
451 buffer[k] = lines[l][k];
455 // We fill the rest of the line with blanks if this is the
458 if(l == new_focus_line) {
459 while(k < console_width) {
469 // Highlight the highlighted line ...
471 if(l == new_focus_line) {
472 attron(attr_focus_line);
473 addnstr(buffer, console_width);
474 attroff(attr_focus_line);
476 addnstr(buffer, console_width);
483 // If we are on a focused line and we moved, this become the new
487 *current_focus_line = new_focus_line;
491 *displayed_focus_line = new_focus_line;
493 if(nb_printed_lines == 0) {
495 addnstr("No selection", console_width);
500 addnstr("Empty choice", console_width);
510 attron(attr_modeline);
512 for(k = 0; k < console_width; k++) buffer[k] = ' ';
513 buffer[console_width] = '\0';
514 addnstr(buffer, console_width);
518 // There must be a more elegant way of moving the cursor at a
519 // location met during display
526 cursor_x += strlen(title) + 1;
529 sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
531 cursor_x += strlen(buffer);
533 addnstr(pattern, cursor_position);
534 cursor_x += cursor_position;
536 if(pattern[cursor_position]) {
537 addstr(pattern + cursor_position);
542 if(use_regexp || case_sensitive) {
559 attroff(attr_modeline);
564 free_matcher(&matcher);
567 //////////////////////////////////////////////////////////////////////
569 void read_file(const char *input_filename,
570 int nb_lines_max, int *nb_lines, char **lines,
571 int hash_table_size, int *hash_table) {
573 char raw_line[buffer_size];
575 FILE *file = fopen(input_filename, "r");
578 fprintf(stderr, "Can not open `%s'.\n", input_filename);
582 int start = 0, end = 0, k;
584 while(*nb_lines < nb_lines_max && (end > start || !feof(file))) {
586 while(eol < end && raw_line[eol] != '\n') eol++;
589 for(k = 0; k < end - start; k++) {
590 raw_line[k] = raw_line[k + start];
595 end += fread(raw_line + end, sizeof(char), buffer_size - end, file);
596 while(eol < end && raw_line[eol] != '\n') eol++;
599 if(eol == buffer_size) {
600 raw_line[buffer_size - 1] = '\0';
601 fprintf(stderr, "Line too long:\n");
602 fprintf(stderr, raw_line);
603 fprintf(stderr, "\n");
607 raw_line[eol] = '\0';
609 char *t = raw_line + start;
611 // Remove the zsh history prefix
613 if(zsh_history && *t == ':') {
614 while(*t && *t != ';') t++;
618 // Remove the bash history prefix
621 while(*t == ' ') t++;
622 while(*t >= '0' && *t <= '9') t++;
623 while(*t == ' ') t++;
626 // Check for duplicates with the hash table and insert the line
627 // in the list if necessary
632 dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
638 lines[*nb_lines] = (char *) malloc((strlen(t) + 1) * sizeof(char));
639 strcpy(lines[*nb_lines], t);
641 // The string was already in there, so we do not allocate a
642 // new string but use the pointer to the first occurence of it
643 lines[*nb_lines] = lines[dup];
653 //////////////////////////////////////////////////////////////////////
655 int main(int argc, char **argv) {
657 if(!ttyname(STDIN_FILENO)) {
658 fprintf(stderr, "The standard input is not a tty.\n");
662 char input_filename[buffer_size], output_filename[buffer_size];
664 int error = 0, show_help = 0;
665 int rest_are_files = 0;
667 int color_fg_modeline, color_bg_modeline;
668 int color_fg_highlight, color_bg_highlight;
670 color_fg_modeline = COLOR_WHITE;
671 color_bg_modeline = COLOR_BLACK;
672 color_fg_highlight = COLOR_BLACK;
673 color_bg_highlight = COLOR_YELLOW;
675 setlocale(LC_ALL, "");
677 strcpy(input_filename, "");
678 strcpy(output_filename, "");
681 while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
683 if(strcmp(argv[i], "-o") == 0) {
684 check_opt(argc, argv, i, 1, "<output filename>");
685 strncpy(output_filename, argv[i+1], buffer_size);
689 else if(strcmp(argv[i], "-s") == 0) {
690 check_opt(argc, argv, i, 1, "<pattern separator>");
691 pattern_separator = argv[i+1][0];
695 else if(strcmp(argv[i], "-x") == 0) {
696 check_opt(argc, argv, i, 1, "<label separator>");
697 label_separator = argv[i+1][0];
701 else if(strcmp(argv[i], "-v") == 0) {
702 output_to_vt_buffer = 1;
706 else if(strcmp(argv[i], "-w") == 0) {
711 else if(strcmp(argv[i], "-m") == 0) {
716 else if(strcmp(argv[i], "-q") == 0) {
721 else if(strcmp(argv[i], "-f") == 0) {
722 check_opt(argc, argv, i, 1, "<input filename>");
723 strncpy(input_filename, argv[i+1], buffer_size);
727 else if(strcmp(argv[i], "-i") == 0) {
732 else if(strcmp(argv[i], "-b") == 0) {
737 else if(strcmp(argv[i], "-z") == 0) {
742 else if(strcmp(argv[i], "-d") == 0) {
743 remove_duplicates = 1;
747 else if(strcmp(argv[i], "-e") == 0) {
752 else if(strcmp(argv[i], "-a") == 0) {
757 else if(strcmp(argv[i], "-t") == 0) {
758 check_opt(argc, argv, i, 1, "<title>");
760 title = (char *) malloc((strlen(argv[i+1]) + 1) * sizeof(char));
761 strcpy(title, argv[i+1]);
765 else if(strcmp(argv[i], "-l") == 0) {
766 check_opt(argc, argv, i, 1, "<maximum number of lines>");
767 nb_lines_max = string_to_positive_integer(argv[i+1]);
771 else if(strcmp(argv[i], "-c") == 0) {
772 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
773 color_fg_modeline = string_to_positive_integer(argv[i + 1]);
774 color_bg_modeline = string_to_positive_integer(argv[i + 2]);
775 color_fg_highlight = string_to_positive_integer(argv[i + 3]);
776 color_bg_highlight = string_to_positive_integer(argv[i + 4]);
780 else if(strcmp(argv[i], "--") == 0) {
785 else if(strcmp(argv[i], "-h") == 0) {
791 fprintf(stderr, "Unknown option %s.\n", argv[i]);
796 if(show_help || error) {
797 /* fprintf(stderr, "Selector version %s-R%s\n", VERSION, REVISION_NUMBER); */
798 fprintf(stderr, "Written by Francois Fleuret <francois@fleuret.org>.\n");
799 fprintf(stderr, "Usage: %s [options] [<filename1> [<filename2> ...]]\n", argv[0]);
800 fprintf(stderr, "\n");
801 fprintf(stderr, " -h show this help\n");
802 fprintf(stderr, " -v inject the selected line in the tty\n");
803 fprintf(stderr, " -w quote control characters with ^Qs when using -v\n");
804 fprintf(stderr, " -d remove duplicated lines\n");
805 fprintf(stderr, " -b remove the bash history line prefix\n");
806 fprintf(stderr, " -z remove the zsh history line prefix\n");
807 fprintf(stderr, " -i invert the order of lines\n");
808 fprintf(stderr, " -e start in regexp mode\n");
809 fprintf(stderr, " -a start in case sensitive mode\n");
810 fprintf(stderr, " -m monochrome mode\n");
811 fprintf(stderr, " -q make a flash instead of a beep on an edition error\n");
812 fprintf(stderr, " -- all following arguments are filenames\n");
813 fprintf(stderr, " -t <title>\n");
814 fprintf(stderr, " add a title in the modeline\n");
815 fprintf(stderr, " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>\n");
816 fprintf(stderr, " set the display colors\n");
817 fprintf(stderr, " -o <output filename>\n");
818 fprintf(stderr, " set a file to write the selected line to\n");
819 fprintf(stderr, " -s <pattern separator>\n");
820 fprintf(stderr, " set the symbol to separate substrings in the pattern\n");
821 fprintf(stderr, " -x <label separator>\n");
822 fprintf(stderr, " set the symbol to terminate the label\n");
823 fprintf(stderr, " -l <max number of lines>\n");
824 fprintf(stderr, " set the maximum number of lines to take into account\n");
825 fprintf(stderr, "\n");
829 char **lines = (char **) malloc(nb_lines_max * sizeof(char *));
832 int hash_table_size = nb_lines_max * 10;
835 if(remove_duplicates) {
836 hash_table = new_hash_table(hash_table_size);
839 if(input_filename[0]) {
840 read_file(input_filename,
841 nb_lines_max, &nb_lines, lines,
842 hash_table_size, hash_table);
847 nb_lines_max, &nb_lines, lines,
848 hash_table_size, hash_table);
854 // Now remove the null strings
857 for(k = 0; k < nb_lines; k++) {
859 lines[n++] = lines[k];
866 for(i = 0; i < nb_lines / 2; i++) {
867 char *s = lines[nb_lines - 1 - i];
868 lines[nb_lines - 1 - i] = lines[i];
873 // Build the labels from the strings, take only the part before the
874 // label_separator and transform control characters to printable
877 char **labels = (char **) malloc(nb_lines * sizeof(char *));
878 for(l = 0; l < nb_lines; l++) {
883 while(*t && *t != label_separator) {
887 labels[l] = (char *) malloc((e + 1) * sizeof(char));
890 while(*t && *t != label_separator) {
892 while(*u) { *s++ = *u++; }
897 char pattern[buffer_size];
903 //////////////////////////////////////////////////////////////////////
904 // Here we start to display with curse
910 intrflush(stdscr, FALSE);
912 // So that the arrow keys work
913 keypad(stdscr, TRUE);
915 attr_error = A_STANDOUT;
916 attr_modeline = A_REVERSE;
917 attr_focus_line = A_STANDOUT;
919 if(with_colors && has_colors()) {
923 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
924 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
925 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
926 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
929 fprintf(stderr, "Color numbers have to be between 0 and %d.\n", COLORS - 1);
933 init_pair(1, color_fg_modeline, color_bg_modeline);
934 attr_modeline = COLOR_PAIR(1);
936 init_pair(2, color_fg_highlight, color_bg_highlight);
937 attr_focus_line = COLOR_PAIR(2);
939 init_pair(3, COLOR_WHITE, COLOR_RED);
940 attr_error = COLOR_PAIR(3);
945 int current_focus_line = 0, displayed_focus_line = 0;
947 update_screen(¤t_focus_line, &displayed_focus_line,
949 nb_lines, labels, cursor_position, pattern);
957 if(key >= ' ' && key <= '~') { // Insert character
958 insert_char(pattern, &cursor_position, key);
961 else if(key == KEY_BACKSPACE ||
962 key == '\010' || // ^H
963 key == '\177') { // ^?
964 backspace_char(pattern, &cursor_position);
967 else if(key == KEY_DC ||
968 key == '\004') { // ^D
969 delete_char(pattern, &cursor_position);
972 else if(key == KEY_HOME) {
973 current_focus_line = 0;
976 else if(key == KEY_END) {
977 current_focus_line = nb_lines - 1;
980 else if(key == KEY_NPAGE) {
984 else if(key == KEY_PPAGE) {
988 else if(key == KEY_DOWN ||
989 key == '\016') { // ^N
993 else if(key == KEY_UP ||
994 key == '\020') { // ^P
998 else if(key == KEY_LEFT ||
999 key == '\002') { // ^B
1000 if(cursor_position > 0) cursor_position--;
1001 else error_feedback();
1004 else if(key == KEY_RIGHT ||
1005 key == '\006') { // ^F
1006 if(pattern[cursor_position]) cursor_position++;
1007 else error_feedback();
1010 else if(key == '\001') { // ^A
1011 cursor_position = 0;
1014 else if(key == '\005') { // ^E
1015 cursor_position = strlen(pattern);
1018 else if(key == '\022') { // ^R
1019 use_regexp = !use_regexp;
1022 else if(key == '\011') { // ^I
1023 case_sensitive = !case_sensitive;
1026 else if(key == '\025') { // ^U
1027 kill_before_cursor(pattern, &cursor_position);
1030 else if(key == '\013') { // ^K
1031 kill_after_cursor(pattern, &cursor_position);
1034 else if(key == '\014') { // ^L
1035 // I suspect that we may sometime mess up the display
1039 update_screen(¤t_focus_line, &displayed_focus_line,
1041 nb_lines, labels, cursor_position, pattern);
1043 } while(key != '\007' && // ^G
1044 key != '\033' && // ^[ (escape)
1051 //////////////////////////////////////////////////////////////////////
1052 // Here we come back to standard display
1054 if((key == KEY_ENTER || key == '\n')) {
1058 if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1059 t = lines[displayed_focus_line];
1060 if(label_separator) {
1061 while(*t && *t != label_separator) t++;
1068 if(output_to_vt_buffer && t) {
1069 inject_into_tty_buffer(t);
1072 if(output_filename[0]) {
1073 FILE *out = fopen(output_filename, "w");
1080 fprintf(stderr, "Can not open %s for writing.\n", output_filename);
1087 printf("Aborted.\n");
1090 for(l = 0; l < nb_lines; l++) {