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 10000 <(history)
36 #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;
69 tcgetattr(STDIN_FILENO, &oldtio);
70 memset(&newtio, 0, sizeof(newtio));
71 // Set input mode (non-canonical, *no echo*,...)
72 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
73 const char control_q = '\021';
74 // Put the selected string in the tty input buffer
75 for(const char *k = string; *k; k++) {
76 if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
77 // Add ^Q to quote control characters
78 ioctl(STDIN_FILENO, TIOCSTI, &control_q);
80 ioctl(STDIN_FILENO, TIOCSTI, k);
82 // Restore the old settings
83 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
86 //////////////////////////////////////////////////////////////////////
88 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
89 if(n_opt + n >= argc) {
90 cerr << "Missing argument for " << argv[n_opt] << "."
92 << "Expecting " << help << "."
98 int string_to_positive_integer(char *string) {
103 for(char *s = string; *s; s++) {
104 if(*s >= '0' && *s <= '9') {
105 result = result * 10 + int(*s - '0');
111 cerr << "Value `" << string << "' is not a positive integer." << endl;
118 void error_feedback() {
126 //////////////////////////////////////////////////////////////////////
127 // A quick and dirty hash table
129 // The table itself stores index of the strings 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 = new int[hash_table_size];
136 for(int 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,
147 char **strings, int *hash_table, int hash_table_size) {
149 unsigned int code = 0;
151 // This is my recipe. I checked, it seems to work (as long as
152 // hash_table_size is not a multiple of 387433 that should be okay)
154 for(int k = 0; new_string[k]; k++) {
155 code = code * 387433 + (unsigned int) (new_string[k]);
158 code = code % hash_table_size;
160 while(hash_table[code] >= 0) {
161 // There is a string with that code
162 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
163 // It is the same string, we keep a copy of the stored index
164 int result = hash_table[code];
166 hash_table[code] = new_index;
167 // And return the previous one
170 // This collision was not the same string, let's move to the next
172 code = (code + 1) % hash_table_size;
175 // This string was not already in there, store the index in the
176 // table and return -1
177 hash_table[code] = new_index;
181 //////////////////////////////////////////////////////////////////////
182 // A matcher matches either with a collection of substrings, or with a
190 char *splitted_patterns, **patterns;
193 int match(char *string, matcher_t *matcher) {
194 if(matcher->nb_patterns >= 0) {
195 if(matcher->case_sensitive) {
196 for(int n = 0; n < matcher->nb_patterns; n++) {
197 if(strstr(string, matcher->patterns[n]) == 0) return 0;
200 for(int n = 0; n < matcher->nb_patterns; n++) {
201 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
206 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
210 void free_matcher(matcher_t *matcher) {
211 if(matcher->nb_patterns < 0) {
212 if(!matcher->regexp_error) regfree(&matcher->preg);
214 delete[] matcher->splitted_patterns;
215 delete[] matcher->patterns;
219 void initialize_matcher(int use_regexp, int case_sensitive,
220 matcher_t *matcher, const char *pattern) {
223 matcher->nb_patterns = -1;
224 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
226 matcher->regexp_error = 0;
227 matcher->nb_patterns = 1;
228 matcher->case_sensitive = case_sensitive;
230 for(const char *s = pattern; *s; s++) {
231 if(*s == pattern_separator) {
232 matcher->nb_patterns++;
236 matcher->splitted_patterns = new char[strlen(pattern) + 1];
237 matcher->patterns = new char*[matcher->nb_patterns];
239 strcpy(matcher->splitted_patterns, pattern);
242 char *last_pattern_start = matcher->splitted_patterns;
243 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
244 if(*s == pattern_separator || *s == '\0') {
246 matcher->patterns[n++] = last_pattern_start;
247 last_pattern_start = s + 1;
253 //////////////////////////////////////////////////////////////////////
256 void delete_char(char *buffer, int *position) {
257 if(buffer[*position]) {
259 while(c < buffer_size && buffer[c]) {
260 buffer[c] = buffer[c+1];
263 } else error_feedback();
266 void backspace_char(char *buffer, int *position) {
268 if(buffer[*position]) {
269 int c = *position - 1;
271 buffer[c] = buffer[c+1];
275 buffer[*position - 1] = '\0';
279 } else error_feedback();
282 void insert_char(char *buffer, int *position, char character) {
283 if(strlen(buffer) < buffer_size - 1) {
285 char t = buffer[c], u;
294 buffer[(*position)++] = character;
295 } else error_feedback();
298 void kill_before_cursor(char *buffer, int *position) {
300 while(buffer[*position + s]) {
301 buffer[s] = buffer[*position + s];
308 void kill_after_cursor(char *buffer, int *position) {
309 buffer[*position] = '\0';
312 //////////////////////////////////////////////////////////////////////
314 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
315 int line = current_line - 1;
316 while(line >= 0 && !match(lines[line], matcher)) line--;
320 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
321 int line = current_line + 1;
322 while(line < nb_lines && !match(lines[line], matcher)) line++;
330 //////////////////////////////////////////////////////////////////////
332 // The value passed to this routine in current_focus_line is the index
333 // of the line to highlighted if it matches the matcher. The line
334 // highlighted is the first the one matching the matcher in that
335 // order: The current_focus_line itself, the first with a greated
336 // index, the first with a lesser index.
338 // The index of the line actually shown highlighted is written in
339 // displayed_focus_line (it can be -1)
341 // If there is a motion and a line is actually shown highlighted, its
342 // value is written in current_focus_line
344 void update_screen(int *current_focus_line, int *displayed_focus_line,
346 int nb_lines, char **lines,
350 char buffer[buffer_size];
353 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
355 int console_width = getmaxx(stdscr);
356 int console_height = getmaxy(stdscr);
358 // First, we find a visible line. In priority: The current, or the
359 // first visible after it, or the first visible before it.
361 int nb_printed_lines = 0;
363 use_default_colors();
366 if(matcher.regexp_error) {
368 addnstr("Regexp syntax error", console_width);
370 } else if(nb_lines > 0) {
372 if(match(lines[*current_focus_line], &matcher)) {
373 new_focus_line = *current_focus_line;
375 new_focus_line = next_visible(*current_focus_line, nb_lines, lines, &matcher);
376 if(new_focus_line < 0) {
377 new_focus_line = previous_visible(*current_focus_line, nb_lines, lines, &matcher);
381 // If we found a visible line and we should move, let's move
383 if(new_focus_line >= 0 && motion != 0) {
384 int l = new_focus_line;
386 // We want to go down, let's find the first visible line below
387 for(int m = 0; l >= 0 && m < motion; m++) {
388 l = next_visible(l, nb_lines, lines, &matcher);
394 // We want to go up, let's find the first visible line above
395 for(int m = 0; l >= 0 && m < -motion; m++) {
396 l = previous_visible(l, nb_lines, lines, &matcher);
404 // Here new_focus_line is either a line number matching the pattern, or -1
406 if(new_focus_line >= 0) {
408 int first_line = new_focus_line, last_line = new_focus_line, nb_match = 1;
410 // We find the first and last line to show, so that the total of
411 // visible lines between them (them included) is console_height-1
413 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
417 while(first_line > 0 && !match(lines[first_line], &matcher)) {
420 if(match(lines[first_line], &matcher)) {
425 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
427 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
431 if(match(lines[last_line], &matcher)) {
437 // Now we display them
439 for(int l = first_line; l <= last_line; l++) {
440 if(match(lines[l], &matcher)) {
443 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
444 buffer[k] = lines[l][k];
448 // We fill the rest of the line with blanks if this is the
451 if(l == new_focus_line) {
452 while(k < console_width) {
462 // Highlight the highlighted line ...
464 if(l == new_focus_line) {
465 attron(attr_focus_line);
466 addnstr(buffer, console_width);
467 attroff(attr_focus_line);
469 addnstr(buffer, console_width);
476 // If we are on a focused line and we moved, this become the new
480 *current_focus_line = new_focus_line;
484 *displayed_focus_line = new_focus_line;
486 if(nb_printed_lines == 0) {
488 addnstr("No selection", console_width);
493 addnstr("Empty choice", console_width);
503 attron(attr_modeline);
505 for(int k = 0; k < console_width; k++) buffer[k] = ' ';
506 buffer[console_width] = '\0';
507 addnstr(buffer, console_width);
511 // There must be a more elegant way of moving the cursor at a
512 // location met during display
519 cursor_x += strlen(title) + 1;
522 sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
524 cursor_x += strlen(buffer);
526 addnstr(pattern, cursor_position);
527 cursor_x += cursor_position;
529 if(pattern[cursor_position]) {
530 addstr(pattern + cursor_position);
535 if(use_regexp || case_sensitive) {
552 attroff(attr_modeline);
557 free_matcher(&matcher);
560 //////////////////////////////////////////////////////////////////////
562 void read_file(const char *input_filename,
563 int nb_lines_max, int *nb_lines, char **lines,
564 int hash_table_size, int *hash_table) {
566 char raw_line[buffer_size];;
568 ifstream file(input_filename);
571 cerr << "Can not open " << input_filename << endl;
575 while(*nb_lines < nb_lines_max && !file.eof()) {
577 file.getline(raw_line, buffer_size);
582 cerr << "Line too long:" << endl;
583 cerr << raw_line << endl;
591 // Remove the zsh history prefix
593 if(zsh_history && *t == ':') {
594 while(*t && *t != ';') t++;
598 // Remove the bash history prefix
601 while(*t == ' ') t++;
602 while(*t >= '0' && *t <= '9') t++;
603 while(*t == ' ') t++;
606 // Check for duplicates with the hash table and insert the line
607 // in the list if necessary
612 dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
618 lines[*nb_lines] = new char[strlen(t) + 1];
619 strcpy(lines[*nb_lines], t);
621 // The string was already in there, so we do not allocate a
622 // new string but use the pointer to the first occurence of it
623 lines[*nb_lines] = lines[dup];
632 //////////////////////////////////////////////////////////////////////
634 int main(int argc, char **argv) {
636 if(!ttyname(STDIN_FILENO)) {
637 cerr << "The standard input is not a tty." << endl;
641 int color_fg_modeline, color_bg_modeline;
642 int color_fg_highlight, color_bg_highlight;
644 color_fg_modeline = COLOR_WHITE;
645 color_bg_modeline = COLOR_BLACK;
646 color_fg_highlight = COLOR_BLACK;
647 color_bg_highlight = COLOR_YELLOW;
649 setlocale(LC_ALL, "");
651 char input_filename[buffer_size], output_filename[buffer_size];
653 strcpy(input_filename, "");
654 strcpy(output_filename, "");
657 int error = 0, show_help = 0;
658 int rest_are_files = 0;
660 while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
662 if(strcmp(argv[i], "-o") == 0) {
663 check_opt(argc, argv, i, 1, "<output filename>");
664 strncpy(output_filename, argv[i+1], buffer_size);
668 else if(strcmp(argv[i], "-s") == 0) {
669 check_opt(argc, argv, i, 1, "<pattern separator>");
670 pattern_separator = argv[i+1][0];
674 else if(strcmp(argv[i], "-x") == 0) {
675 check_opt(argc, argv, i, 1, "<label separator>");
676 label_separator = argv[i+1][0];
680 else if(strcmp(argv[i], "-v") == 0) {
681 output_to_vt_buffer = 1;
685 else if(strcmp(argv[i], "-w") == 0) {
690 else if(strcmp(argv[i], "-m") == 0) {
695 else if(strcmp(argv[i], "-q") == 0) {
700 else if(strcmp(argv[i], "-f") == 0) {
701 check_opt(argc, argv, i, 1, "<input filename>");
702 strncpy(input_filename, argv[i+1], buffer_size);
706 else if(strcmp(argv[i], "-i") == 0) {
711 else if(strcmp(argv[i], "-b") == 0) {
716 else if(strcmp(argv[i], "-z") == 0) {
721 else if(strcmp(argv[i], "-d") == 0) {
722 remove_duplicates = 1;
726 else if(strcmp(argv[i], "-e") == 0) {
731 else if(strcmp(argv[i], "-a") == 0) {
736 else if(strcmp(argv[i], "-t") == 0) {
737 check_opt(argc, argv, i, 1, "<title>");
739 title = new char[strlen(argv[i+1]) + 1];
740 strcpy(title, argv[i+1]);
744 else if(strcmp(argv[i], "-l") == 0) {
745 check_opt(argc, argv, i, 1, "<maximum number of lines>");
746 nb_lines_max = string_to_positive_integer(argv[i+1]);
750 else if(strcmp(argv[i], "-c") == 0) {
751 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
752 color_fg_modeline = string_to_positive_integer(argv[i + 1]);
753 color_bg_modeline = string_to_positive_integer(argv[i + 2]);
754 color_fg_highlight = string_to_positive_integer(argv[i + 3]);
755 color_bg_highlight = string_to_positive_integer(argv[i + 4]);
759 else if(strcmp(argv[i], "--") == 0) {
764 else if(strcmp(argv[i], "-h") == 0) {
770 cerr << "Unknown option " << argv[i] << "." << endl;
775 if(show_help || error) {
776 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
778 << "Written by Francois Fleuret <francois@fleuret.org>."
781 << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
783 << " -h show this help" << endl
784 << " -v inject the selected line in the tty" << endl
785 << " -w quote control characters with ^Qs when using -v" << endl
786 << " -d remove duplicated lines" << endl
787 << " -b remove the bash history line prefix" << endl
788 << " -z remove the zsh history line prefix" << endl
789 << " -i invert the order of lines" << endl
790 << " -e start in regexp mode" << endl
791 << " -a case sensitive" << endl
792 << " -m monochrome mode" << endl
793 << " -q make a flash instead of a beep on an edition error" << endl
794 << " -- all following arguments are filenames" << endl
795 << " -t <title>" << endl
796 << " add a title in the modeline" << endl
797 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
798 << " set the display colors" << endl
799 << " -o <output filename>" << endl
800 << " set a file to write the selected line to" << endl
801 << " -s <pattern separator>" << endl
802 << " set the symbol to separate substrings in the pattern" << endl
803 << " -x <label separator>" << endl
804 << " set the symbol to terminate the label" << endl
805 << " -l <max number of lines>" << endl
806 << " set the maximum number of lines to take into account" << endl
812 char **lines = new char *[nb_lines_max];
815 int hash_table_size = nb_lines_max * 10;
818 if(remove_duplicates) {
819 hash_table = new_hash_table(hash_table_size);
822 if(input_filename[0]) {
823 read_file(input_filename,
824 nb_lines_max, &nb_lines, lines,
825 hash_table_size, hash_table);
830 nb_lines_max, &nb_lines, lines,
831 hash_table_size, hash_table);
837 // Now remove the null strings
840 for(int k = 0; k < nb_lines; k++) {
842 lines[n++] = lines[k];
849 for(int i = 0; i < nb_lines / 2; i++) {
850 char *s = lines[nb_lines - 1 - i];
851 lines[nb_lines - 1 - i] = lines[i];
856 // Build the labels from the strings, take only the part before the
857 // label_separator and transform control characters to printable
860 char **labels = new char *[nb_lines];
861 for(int l = 0; l < nb_lines; l++) {
866 while(*t && *t != label_separator) {
870 labels[l] = new char[e + 1];
873 while(*t && *t != label_separator) {
875 while(*u) { *s++ = *u++; }
880 char pattern[buffer_size];
886 //////////////////////////////////////////////////////////////////////
887 // Here we start to display with curse
893 // So that the arrow keys work
894 keypad(stdscr, TRUE);
896 attr_error = A_STANDOUT;
897 attr_modeline = A_REVERSE;
898 attr_focus_line = A_STANDOUT;
900 if(with_colors && has_colors()) {
904 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
905 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
906 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
907 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
910 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
914 init_pair(1, color_fg_modeline, color_bg_modeline);
915 attr_modeline = COLOR_PAIR(1);
917 init_pair(2, color_fg_highlight, color_bg_highlight);
918 attr_focus_line = COLOR_PAIR(2);
920 init_pair(3, COLOR_WHITE, COLOR_RED);
921 attr_error = COLOR_PAIR(3);
926 int current_focus_line = 0, displayed_focus_line = 0;
928 update_screen(¤t_focus_line, &displayed_focus_line,
930 nb_lines, labels, cursor_position, pattern);
938 if(key >= ' ' && key <= '~') { // Insert character
939 insert_char(pattern, &cursor_position, key);
942 else if(key == KEY_BACKSPACE ||
943 key == '\010' || // ^H
944 key == '\177') { // ^?
945 backspace_char(pattern, &cursor_position);
948 else if(key == KEY_DC ||
949 key == '\004') { // ^D
950 delete_char(pattern, &cursor_position);
953 else if(key == KEY_HOME) {
954 current_focus_line = 0;
957 else if(key == KEY_END) {
958 current_focus_line = nb_lines - 1;
961 else if(key == KEY_NPAGE) {
965 else if(key == KEY_PPAGE) {
969 else if(key == KEY_DOWN ||
970 key == '\016') { // ^N
974 else if(key == KEY_UP ||
975 key == '\020') { // ^P
979 else if(key == KEY_LEFT ||
980 key == '\002') { // ^B
981 if(cursor_position > 0) cursor_position--;
982 else error_feedback();
985 else if(key == KEY_RIGHT ||
986 key == '\006') { // ^F
987 if(pattern[cursor_position]) cursor_position++;
988 else error_feedback();
991 else if(key == '\001') { // ^A
995 else if(key == '\005') { // ^E
996 cursor_position = strlen(pattern);
999 else if(key == '\022') { // ^R
1000 use_regexp = !use_regexp;
1003 else if(key == '\011') { // ^I
1004 case_sensitive = !case_sensitive;
1007 else if(key == '\025') { // ^U
1008 kill_before_cursor(pattern, &cursor_position);
1011 else if(key == '\013') { // ^K
1012 kill_after_cursor(pattern, &cursor_position);
1015 else if(key == '\014') { // ^L
1016 // I suspect that we may sometime mess up the display
1020 update_screen(¤t_focus_line, &displayed_focus_line,
1022 nb_lines, labels, cursor_position, pattern);
1024 } while(key != '\007' && // ^G
1025 key != '\033' && // ^[ (escape)
1032 //////////////////////////////////////////////////////////////////////
1033 // Here we come back to standard display
1035 if((key == KEY_ENTER || key == '\n')) {
1037 if(output_to_vt_buffer) {
1038 if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1039 inject_into_tty_buffer(lines[displayed_focus_line]);
1043 if(output_filename[0]) {
1044 ofstream out(output_filename);
1046 cerr << "Can not open " << output_filename << " for writing." << endl;
1049 if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1050 out << lines[displayed_focus_line] << endl;
1058 cout << "Aborted." << endl;
1061 for(int l = 0; l < nb_lines; l++) {