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 // alias h='selector -d -i -b -v -f <(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 int output_to_vt_buffer = 0;
52 int zsh_history = 0, bash_history = 0;
53 int inverse_order = 0;
54 int remove_duplicates = 0;
56 int case_sensitive = 0;
59 #define COLOR_MODELINE 1
60 #define COLOR_HIGHLIGHTED_LINE 2
62 //////////////////////////////////////////////////////////////////////
64 void inject_into_tty_buffer(char *string) {
65 struct termios oldtio, newtio;
66 tcgetattr(STDIN_FILENO, &oldtio);
67 memset(&newtio, 0, sizeof(newtio));
68 // Set input mode (non-canonical, *no echo*,...)
69 tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
70 // Put the selected string in the tty input buffer
71 for(char *k = string; *k; k++) {
72 ioctl(STDIN_FILENO, TIOCSTI, k);
74 // Restore the old settings
75 tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
78 //////////////////////////////////////////////////////////////////////
80 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
81 if(n_opt + n >= argc) {
82 cerr << "Missing argument for " << argv[n_opt] << "."
84 << "Expecting " << help << "."
90 int string_to_positive_integer(char *string) {
95 for(char *s = string; *s; s++) {
96 if(*s >= '0' && *s <= '9') {
97 result = result * 10 + int(*s - '0');
103 cerr << "Value `" << string << "' is not a positive integer." << endl;
110 void error_feedback() {
114 //////////////////////////////////////////////////////////////////////
115 // A quick and dirty hash table
117 // The table itself stores index of the strings in a char
118 // **table. When a string is added, if it was already in the table,
119 // the new index replaces the previous one.
121 int *new_hash_table(int hash_table_size) {
123 result = new int[hash_table_size];
124 for(int k = 0; k < hash_table_size; k++) {
130 // Adds new_string in the table, associated to new_index. If this
131 // string was not already in the table, returns -1. Otherwise, returns
132 // the previous index it had.
134 int test_and_add(char *new_string, int new_index,
135 char **strings, int *hash_table, int hash_table_size) {
136 unsigned int code = 0;
138 // This is my recipe. I checked, it seems to work (as long as
139 // hash_table_size is not a multiple of 387433 that should be okay)
141 for(int k = 0; new_string[k]; k++) {
142 code = code * 387433 + (unsigned int) (new_string[k]);
145 code = code % hash_table_size;
147 while(hash_table[code] >= 0) {
148 // There is a string with that code
149 if(strcmp(new_string, strings[hash_table[code]]) == 0) {
150 // It is the same string, we keep a copy of the stored index
151 int result = hash_table[code];
153 hash_table[code] = new_index;
154 // And return the previous one
157 // This collision was not the same string, let's move to the next
159 code = (code + 1) % hash_table_size;
162 // This string was not already in there, store the index in the
163 // table and return -1
164 hash_table[code] = new_index;
168 //////////////////////////////////////////////////////////////////////
169 // A matcher matches either with a collection of substrings, or with a
177 char *splitted_patterns, **patterns;
180 int match(char *string, matcher_t *matcher) {
181 if(matcher->nb_patterns >= 0) {
182 if(matcher->case_sensitive) {
183 for(int n = 0; n < matcher->nb_patterns; n++) {
184 if(strstr(string, matcher->patterns[n]) == 0) return 0;
187 for(int n = 0; n < matcher->nb_patterns; n++) {
188 if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
193 return regexec(&matcher->preg, string, 0, 0, 0) == 0;
197 void free_matcher(matcher_t *matcher) {
198 if(matcher->nb_patterns >= 0) {
199 delete[] matcher->splitted_patterns;
200 delete[] matcher->patterns;
202 if(!matcher->regexp_error) regfree(&matcher->preg);
206 void initialize_matcher(int use_regexp, int case_sensitive,
207 matcher_t *matcher, const char *pattern) {
210 matcher->nb_patterns = -1;
211 matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
213 matcher->regexp_error = 0;
214 matcher->nb_patterns = 1;
215 matcher->case_sensitive = case_sensitive;
217 for(const char *s = pattern; *s; s++) {
218 if(*s == pattern_separator) {
219 matcher->nb_patterns++;
223 matcher->splitted_patterns = new char[strlen(pattern) + 1];
224 matcher->patterns = new char*[matcher->nb_patterns];
226 strcpy(matcher->splitted_patterns, pattern);
229 char *last_pattern_start = matcher->splitted_patterns;
230 for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
231 if(*s == pattern_separator || *s == '\0') {
233 matcher->patterns[n++] = last_pattern_start;
234 last_pattern_start = s + 1;
240 //////////////////////////////////////////////////////////////////////
243 void delete_char(char *buffer, int *position) {
244 if(buffer[*position]) {
246 while(c < buffer_size && buffer[c]) {
247 buffer[c] = buffer[c+1];
250 } else error_feedback();
253 void backspace_char(char *buffer, int *position) {
255 if(buffer[*position]) {
256 int c = *position - 1;
258 buffer[c] = buffer[c+1];
262 buffer[*position - 1] = '\0';
266 } else error_feedback();
269 void insert_char(char *buffer, int *position, char character) {
270 if(strlen(buffer) < buffer_size - 1) {
272 char t = buffer[c], u;
281 buffer[(*position)++] = character;
282 } else error_feedback();
285 void kill_before_cursor(char *buffer, int *position) {
287 while(buffer[*position + s]) {
288 buffer[s] = buffer[*position + s];
295 void kill_after_cursor(char *buffer, int *position) {
296 buffer[*position] = '\0';
299 //////////////////////////////////////////////////////////////////////
301 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
302 int line = current_line - 1;
303 while(line >= 0 && !match(lines[line], matcher)) line--;
307 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
308 int line = current_line + 1;
309 while(line < nb_lines && !match(lines[line], matcher)) line++;
317 //////////////////////////////////////////////////////////////////////
319 void update_screen(int *current_line, int *temporary_line, int motion,
320 int nb_lines, char **lines,
324 char buffer[buffer_size];
327 initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
329 // We now take care of printing the lines per se
331 int console_width = getmaxx(stdscr);
332 int console_height = getmaxy(stdscr);
334 // First, we find a visible line. In priority: The current, or the
335 // first visible after it, or the first visible before it.
337 int nb_printed_lines = 0;
340 use_default_colors();
343 if(matcher.regexp_error) {
344 addstr("[regexp error]");
345 } else if(nb_lines > 0) {
347 if(match(lines[*current_line], &matcher)) {
348 new_line = *current_line;
350 new_line = next_visible(*current_line, nb_lines, lines, &matcher);
352 new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
356 // If we found a visible line and we should move, let's move
358 if(new_line >= 0 && motion != 0) {
361 // We want to go down, let's find the first visible line below
362 for(int m = 0; l >= 0 && m < motion; m++) {
363 l = next_visible(l, nb_lines, lines, &matcher);
369 // We want to go up, let's find the first visible line above
370 for(int m = 0; l >= 0 && m < -motion; m++) {
371 l = previous_visible(l, nb_lines, lines, &matcher);
379 // Here new_line is either a line number matching the patterns, or -1
383 int first_line = new_line, last_line = new_line, nb_match = 1;
385 // We find the first and last line to show, so that the total of
386 // visible lines between them (them include) is console_height - 1
388 while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
392 while(first_line > 0 && !match(lines[first_line], &matcher)) {
395 if(match(lines[first_line], &matcher)) {
400 if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
402 while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
406 if(match(lines[last_line], &matcher)) {
412 // Now we display them
414 for(int l = first_line; l <= last_line; l++) {
415 if(match(lines[l], &matcher)) {
418 while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
419 buffer[k] = lines[l][k];
423 // We fill the rest of the line with blanks if either we did
424 // not clear() or if this is the highlighted line
427 while(k < console_width) {
435 // Highlight the highlighted line ...
439 attron(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
440 addnstr(buffer, console_width);
441 attroff(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
444 addnstr(buffer, console_width);
448 addnstr(buffer, console_width);
456 *current_line = new_line;
460 *temporary_line = new_line;
462 if(nb_printed_lines == 0) {
463 addnstr("[no selection]\n", console_width);
466 addnstr("[empty choice]\n", console_width);
474 attron(COLOR_PAIR(COLOR_MODELINE));
479 for(int k = 0; k < console_width; k++) buffer[k] = ' ';
480 buffer[console_width] = '\0';
481 addnstr(buffer, console_width);
485 // There must be a more elegant way of moving the cursor at a
486 // location met during display
493 cursor_x += strlen(title) + 1;
496 sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
498 cursor_x += strlen(buffer);
500 addnstr(pattern, cursor_position);
501 cursor_x += cursor_position;
503 if(pattern[cursor_position]) {
504 addstr(pattern + cursor_position);
509 if(use_regexp || case_sensitive) {
527 attroff(COLOR_PAIR(COLOR_MODELINE));
535 free_matcher(&matcher);
538 //////////////////////////////////////////////////////////////////////
540 void read_file(const char *input_filename,
541 int nb_lines_max, int *nb_lines, char **lines,
542 int hash_table_size, int *hash_table) {
544 char buffer[buffer_size], raw_line[buffer_size];;
546 ifstream file(input_filename);
549 cerr << "Can not open " << input_filename << endl;
553 while(*nb_lines < nb_lines_max && !file.eof()) {
555 file.getline(raw_line, buffer_size);
560 cerr << "Line too long:" << endl;
561 cerr << raw_line << endl;
572 while(*u) { *s++ = *u++; }
578 if(zsh_history && *s == ':') {
579 while(*s && *s != ';') s++;
583 if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
584 while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
590 dup = test_and_add(s, *nb_lines, lines, hash_table, hash_table_size);
596 lines[*nb_lines] = new char[strlen(s) + 1];
597 strcpy(lines[*nb_lines], s);
599 // The string was already in there, so we do not allocate a
600 // new string but use the pointer to the first occurence of it
601 lines[*nb_lines] = lines[dup];
610 //////////////////////////////////////////////////////////////////////
612 int main(int argc, char **argv) {
614 if(!ttyname(STDIN_FILENO)) {
615 cerr << "The standard input is not a tty." << endl;
619 int color_fg_modeline, color_bg_modeline;
620 int color_fg_highlight, color_bg_highlight;
622 color_fg_modeline = COLOR_WHITE;
623 color_bg_modeline = COLOR_BLACK;
624 color_fg_highlight = COLOR_BLACK;
625 color_bg_highlight = COLOR_YELLOW;
627 setlocale(LC_ALL, "");
629 char input_filename[buffer_size], output_filename[buffer_size];
631 strcpy(input_filename, "");
632 strcpy(output_filename, "");
635 int error = 0, show_help = 0;
636 int rest_are_files = 0;
638 while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
640 if(strcmp(argv[i], "-o") == 0) {
641 check_opt(argc, argv, i, 1, "<output filename>");
642 strncpy(output_filename, argv[i+1], buffer_size);
646 else if(strcmp(argv[i], "-s") == 0) {
647 check_opt(argc, argv, i, 1, "<pattern separator>");
648 pattern_separator = argv[i+1][0];
652 else if(strcmp(argv[i], "-v") == 0) {
653 output_to_vt_buffer = 1;
657 else if(strcmp(argv[i], "-m") == 0) {
662 else if(strcmp(argv[i], "-f") == 0) {
663 check_opt(argc, argv, i, 1, "<input filename>");
664 strncpy(input_filename, argv[i+1], buffer_size);
668 else if(strcmp(argv[i], "-i") == 0) {
673 else if(strcmp(argv[i], "-b") == 0) {
678 else if(strcmp(argv[i], "-z") == 0) {
683 else if(strcmp(argv[i], "-d") == 0) {
684 remove_duplicates = 1;
688 else if(strcmp(argv[i], "-e") == 0) {
693 else if(strcmp(argv[i], "-a") == 0) {
698 else if(strcmp(argv[i], "-t") == 0) {
699 check_opt(argc, argv, i, 1, "<title>");
701 title = new char[strlen(argv[i+1]) + 1];
702 strcpy(title, argv[i+1]);
706 else if(strcmp(argv[i], "-l") == 0) {
707 check_opt(argc, argv, i, 1, "<maximum number of lines>");
708 nb_lines_max = string_to_positive_integer(argv[i+1]);
712 else if(strcmp(argv[i], "-c") == 0) {
713 check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
714 color_fg_modeline = string_to_positive_integer(argv[i + 1]);
715 color_bg_modeline = string_to_positive_integer(argv[i + 2]);
716 color_fg_highlight = string_to_positive_integer(argv[i + 3]);
717 color_bg_highlight = string_to_positive_integer(argv[i + 4]);
721 else if(strcmp(argv[i], "--") == 0) {
726 else if(strcmp(argv[i], "-h") == 0) {
732 cerr << "Unknown option " << argv[i] << "." << endl;
737 if(show_help || error) {
738 cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
740 << "Written by Francois Fleuret <francois@fleuret.org>."
743 << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
745 << " -h show this help" << endl
746 << " -v inject the selected line in the tty" << endl
747 << " -d remove duplicated lines" << endl
748 << " -b remove the bash history line prefix" << endl
749 << " -z remove the zsh history line prefix" << endl
750 << " -i invert the order of lines" << endl
751 << " -e start in regexp mode" << endl
752 << " -a case sensitive" << endl
753 << " -m monochrome mode" << endl
754 << " -- rest of the arguments are filenames" << endl
755 << " -t <title>" << endl
756 << " add a title in the modeline" << endl
757 << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
758 << " set the display colors" << endl
759 << " -o <output filename>" << endl
760 << " set a file to write the selected line to" << endl
761 << " -s <pattern separator>" << endl
762 << " set the symbol to separate substrings in the pattern" << endl
763 << " -l <max number of lines>" << endl
764 << " set the maximum number of lines to take into account" << endl
770 char **lines = new char *[nb_lines_max];
773 int hash_table_size = nb_lines_max * 10;
776 if(remove_duplicates) {
777 hash_table = new_hash_table(hash_table_size);
780 if(input_filename[0]) {
781 read_file(input_filename,
782 nb_lines_max, &nb_lines, lines,
783 hash_table_size, hash_table);
788 nb_lines_max, &nb_lines, lines,
789 hash_table_size, hash_table);
795 // Now remove the null strings
798 for(int k = 0; k < nb_lines; k++) {
800 lines[n++] = lines[k];
807 for(int i = 0; i < nb_lines / 2; i++) {
808 char *s = lines[nb_lines - 1 - i];
809 lines[nb_lines - 1 - i] = lines[i];
814 char pattern[buffer_size];
819 //////////////////////////////////////////////////////////////////////
820 // Here we start to display with curse
826 // So that the arrow keys work
827 keypad(stdscr, TRUE);
832 if(color_fg_modeline < 0 || color_fg_modeline >= COLORS ||
833 color_bg_modeline < 0 || color_bg_modeline >= COLORS ||
834 color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
835 color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
838 cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
841 init_pair(COLOR_MODELINE , color_fg_modeline, color_bg_modeline);
842 init_pair(COLOR_HIGHLIGHTED_LINE, color_fg_highlight, color_bg_highlight);
849 int current_line = 0, temporary_line = 0;
851 update_screen(¤t_line, &temporary_line, 0, nb_lines, lines, cursor_position, pattern);
859 if(key >= ' ' && key <= '~') { // Insert character
860 insert_char(pattern, &cursor_position, key);
863 else if(key == KEY_BACKSPACE ||
864 key == '\010' || // ^H
865 key == '\177') { // ^?
866 backspace_char(pattern, &cursor_position);
869 else if(key == KEY_DC ||
870 key == '\004') { // ^D
871 delete_char(pattern, &cursor_position);
874 else if(key == KEY_HOME) {
878 else if(key == KEY_END) {
879 current_line = nb_lines - 1;
882 else if(key == KEY_NPAGE) {
886 else if(key == KEY_PPAGE) {
890 else if(key == KEY_DOWN ||
891 key == '\016') { // ^N
895 else if(key == KEY_UP ||
896 key == '\020') { // ^P
900 else if(key == KEY_LEFT ||
901 key == '\002') { // ^B
902 if(cursor_position > 0) cursor_position--;
903 else error_feedback();
906 else if(key == KEY_RIGHT ||
907 key == '\006') { // ^F
908 if(pattern[cursor_position]) cursor_position++;
909 else error_feedback();
912 else if(key == '\001') { // ^A
916 else if(key == '\005') { // ^E
917 cursor_position = strlen(pattern);
920 else if(key == '\022') { // ^R
921 use_regexp = !use_regexp;
924 else if(key == '\011') { // ^I
925 case_sensitive = !case_sensitive;
928 else if(key == '\025') { // ^U
929 kill_before_cursor(pattern, &cursor_position);
932 else if(key == '\013') { // ^K
933 kill_after_cursor(pattern, &cursor_position);
936 update_screen(¤t_line, &temporary_line, motion,
937 nb_lines, lines, cursor_position, pattern);
939 } while(key != '\n' && key != KEY_ENTER && key != '\007'); // ^G
944 //////////////////////////////////////////////////////////////////////
945 // Here we come back to standard display
947 if((key == KEY_ENTER || key == '\n')) {
949 if(output_to_vt_buffer) {
950 if(temporary_line >= 0 && temporary_line < nb_lines) {
951 inject_into_tty_buffer(lines[temporary_line]);
955 if(output_filename[0]) {
956 ofstream out(output_filename);
958 cerr << "Can not open " << output_filename << " for writing." << endl;
961 if(temporary_line >= 0 && temporary_line < nb_lines) {
962 out << lines[temporary_line] << endl;
970 cout << "Aborted." << endl;
973 for(int l = 0; l < nb_lines; l++) {