Moved the binary path for make install to /usr/bin/.
[selector.git] / selector.cc
1
2 /*
3  *  selector is a simple shell command for selection of strings with a
4  *  dynamic pattern-matching.
5  *
6  *  Copyright (c) 2009 Francois Fleuret
7  *  Written by Francois Fleuret <francois@fleuret.org>
8  *
9  *  This file is part of selector.
10  *
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.
14  *
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.
19  *
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/>.
22  *
23  */
24
25 // To use it as a super-history-search for bash:
26 // alias h='selector -d -i -b -v -f <(history)'
27
28 #include <fstream>
29 #include <iostream>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ncurses.h>
35 #include <fcntl.h>
36 #include <sys/ioctl.h>
37 #include <termios.h>
38 #include <regex.h>
39
40 using namespace std;
41
42 #define VERSION "1.0"
43
44 const int buffer_size = 4096;
45
46 // Yeah, global variables!
47
48 int nb_lines_max = 1000;
49 char pattern_separator = ';';
50 int output_to_vt_buffer = 0;
51 int with_colors = 1;
52 int zsh_history = 0, bash_history = 0;
53 int inverse_order = 0;
54 int remove_duplicates = 0;
55 int use_regexp = 0;
56 int case_sensitive = 0;
57 char *title = 0;
58
59 //////////////////////////////////////////////////////////////////////
60
61 void inject_into_tty_buffer(char *string) {
62   struct termios oldtio, newtio;
63   tcgetattr(STDIN_FILENO, &oldtio);
64   memset(&newtio, 0, sizeof(newtio));
65   // Set input mode (non-canonical, *no echo*,...)
66   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
67   // Put the selected string in the tty input buffer
68   for(char *k = string; *k; k++) {
69     ioctl(STDIN_FILENO, TIOCSTI, k);
70   }
71   // Restore the old settings
72   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
73 }
74
75 //////////////////////////////////////////////////////////////////////
76
77 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
78   if(n_opt + n >= argc) {
79     cerr << "Missing argument for " << argv[n_opt] << "."
80          << " "
81          << "Expecting " << help << "."
82          << endl;
83     exit(1);
84   }
85 }
86
87 //////////////////////////////////////////////////////////////////////
88 // A quick and dirty hash table
89
90 // The table itself stores index of the strings in a char
91 // **table. When a string is added, if it was already in the table,
92 // the new index replaces the previous one.
93
94 int *new_hash_table(int hash_table_size) {
95   int *result;
96   result = new int[hash_table_size];
97   for(int k = 0; k < hash_table_size; k++) {
98     result[k] = -1;
99   }
100   return result;
101 }
102
103 // Adds new_string in the table, associated to new_index. If this
104 // string was not already in the table, returns -1. Otherwise, returns
105 // the previous index it had.
106
107 int test_and_add(char *new_string, int new_index,
108                  char **strings, int *hash_table, int hash_table_size) {
109   unsigned int code = 0;
110
111   // This is my recipe. I checked, it seems to work (as long as
112   // hash_table_size is not a multiple of 387433 that should be okay)
113
114   for(int k = 0; new_string[k]; k++) {
115     code = code * 387433 + (unsigned int) (new_string[k]);
116   }
117
118   code = code % hash_table_size;
119
120   while(hash_table[code] >= 0) {
121     // There is a string with that code
122     if(strcmp(new_string, strings[hash_table[code]]) == 0) {
123       // It is the same string, we keep a copy of the stored index
124       int result = hash_table[code];
125       // Put the new one
126       hash_table[code] = new_index;
127       // And return the previous one
128       return result;
129     }
130     // This collision was not the same string, let's move to the next
131     // in the table
132     code = (code + 1) % hash_table_size;
133   }
134
135   // This string was not already in there, store the index in the
136   // table and return -1
137   hash_table[code] = new_index;
138   return -1;
139 }
140
141 //////////////////////////////////////////////////////////////////////
142 // A matcher matches either with a collection of substrings, or with a
143 // regexp
144
145 struct matcher_t {
146   regex_t preg;
147   int regexp_error;
148   int nb_patterns;
149   int case_sensitive;
150   char *splitted_patterns, **patterns;
151 };
152
153 int match(char *string, matcher_t *matcher) {
154   if(matcher->nb_patterns >= 0) {
155     if(matcher->case_sensitive) {
156       for(int n = 0; n < matcher->nb_patterns; n++) {
157         if(strstr(string, matcher->patterns[n]) == 0) return 0;
158       }
159     } else {
160       for(int n = 0; n < matcher->nb_patterns; n++) {
161         if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
162       }
163     }
164     return 1;
165   } else {
166     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
167   }
168 }
169
170 void free_matcher(matcher_t *matcher) {
171   if(matcher->nb_patterns >= 0) {
172     delete[] matcher->splitted_patterns;
173     delete[] matcher->patterns;
174   } else {
175     if(!matcher->regexp_error) regfree(&matcher->preg);
176   }
177 }
178
179 void initialize_matcher(int use_regexp, int case_sensitive, matcher_t *matcher, const char *pattern) {
180   if(use_regexp) {
181     matcher->nb_patterns = -1;
182     matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
183   } else {
184     matcher->regexp_error = 0;
185     matcher->nb_patterns = 1;
186     matcher->case_sensitive = case_sensitive;
187
188     for(const char *s = pattern; *s; s++) {
189       if(*s == pattern_separator) {
190         matcher->nb_patterns++;
191       }
192     }
193
194     matcher->splitted_patterns = new char[strlen(pattern) + 1];
195     matcher->patterns = new char*[matcher->nb_patterns];
196
197     strcpy(matcher->splitted_patterns, pattern);
198
199     int n = 0;
200     char *last_pattern_start = matcher->splitted_patterns;
201     for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
202       if(*s == pattern_separator || *s == '\0') {
203         *s = '\0';
204         matcher->patterns[n++] = last_pattern_start;
205         last_pattern_start = s + 1;
206       }
207     }
208   }
209 }
210
211 //////////////////////////////////////////////////////////////////////
212
213 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
214   int line = current_line - 1;
215   while(line >= 0 && !match(lines[line], matcher)) line--;
216   return line;
217 }
218
219 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
220   int line = current_line + 1;
221   while(line < nb_lines && !match(lines[line], matcher)) line++;
222
223   if(line < nb_lines)
224     return line;
225   else
226     return -1;
227 }
228
229 //////////////////////////////////////////////////////////////////////
230
231 void update_screen(int *current_line, int *temporary_line, int motion,
232                    int nb_lines, char **lines,
233                    char *pattern) {
234
235   char buffer[buffer_size];
236   matcher_t matcher;
237
238   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
239
240   // We now take care of printing the lines per se
241
242   int console_width = getmaxx(stdscr);
243   int console_height = getmaxy(stdscr);
244
245   // First, we find a visible line. In priority: The current, or the
246   // first visible after it, or the first visible before it.
247
248   int nb_printed_lines = 0;
249
250   clear();
251   use_default_colors();
252   addstr("\n");
253
254   if(matcher.regexp_error) {
255     addstr("[regexp error]");
256   } else if(nb_lines > 0) {
257     int new_line;
258     if(match(lines[*current_line], &matcher)) {
259       new_line = *current_line;
260     } else {
261       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
262       if(new_line < 0) {
263         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
264       }
265     }
266
267     // If we found a visible line and we should move, let's move
268
269     if(new_line >= 0 && motion != 0) {
270       int l = new_line;
271       if(motion > 0) {
272         // We want to go down, let's find the first visible line below
273         for(int m = 0; l >= 0 && m < motion; m++) {
274           l = next_visible(l, nb_lines, lines, &matcher);
275           if(l >= 0) {
276             new_line = l;
277           }
278         }
279       } else {
280         // We want to go up, let's find the first visible line above
281         for(int m = 0; l >= 0 && m < -motion; m++) {
282           l = previous_visible(l, nb_lines, lines, &matcher);
283           if(l >= 0) {
284             new_line = l;
285           }
286         }
287       }
288     }
289
290     // Here new_line is either a line number matching the patterns, or -1
291
292     if(new_line >= 0) {
293
294       int first_line = new_line, last_line = new_line, nb_match = 1;
295
296       // We find the first and last line to show, so that the total of
297       // visible lines between them (them include) is console_height - 1
298
299       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
300
301         if(first_line > 0) {
302           first_line--;
303           while(first_line > 0 && !match(lines[first_line], &matcher)) {
304             first_line--;
305           }
306           if(match(lines[first_line], &matcher)) {
307             nb_match++;
308           }
309         }
310
311         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
312           last_line++;
313           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
314             last_line++;
315           }
316
317           if(match(lines[last_line], &matcher)) {
318             nb_match++;
319           }
320         }
321       }
322
323       // Now we display them
324
325       for(int l = first_line; l <= last_line; l++) {
326         if(match(lines[l], &matcher)) {
327           int k = 0;
328
329           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
330             buffer[k] = lines[l][k];
331             k++;
332           }
333
334           // We fill the rest of the line with blanks if either we did
335           // not clear() or if this is the highlighted line
336
337           if(l == new_line) {
338             while(k < console_width) {
339               buffer[k++] = ' ';
340             }
341           }
342
343           buffer[k++] = '\n';
344           buffer[k++] = '\0';
345
346           // Highlight the highlighted line ...
347
348           if(l == new_line) {
349             if(with_colors) {
350               attron(COLOR_PAIR(2));
351               addnstr(buffer, console_width);
352               attroff(COLOR_PAIR(2));
353             } else {
354               attron(A_STANDOUT);
355               addnstr(buffer, console_width);
356               attroff(A_STANDOUT);
357             }
358           } else {
359             addnstr(buffer, console_width);
360           }
361
362           nb_printed_lines++;
363         }
364       }
365
366       if(motion != 0) {
367         *current_line = new_line;
368       }
369     }
370
371     *temporary_line = new_line;
372
373     if(nb_printed_lines == 0) {
374       addnstr("[no selection]\n", console_width);
375     }
376   } else {
377     addnstr("[empty choice]\n", console_width);
378   }
379
380   // Draw the modeline
381
382   if(title) {
383     sprintf(buffer, "%s %d/%d pattern: %s%s",
384             title,
385             nb_printed_lines,
386             nb_lines,
387             pattern,
388             use_regexp ? " [regexp]" : "");
389   } else {
390     sprintf(buffer, "%d/%d pattern: %s%s",
391             nb_printed_lines,
392             nb_lines,
393             pattern,
394             use_regexp ? " [regexp]" : "");
395   }
396
397   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
398   buffer[console_width] = '\0';
399
400   move(0, 0);
401   if(with_colors) {
402     attron(COLOR_PAIR(1));
403     addnstr(buffer, console_width);
404     attroff(COLOR_PAIR(1));
405   } else {
406     attron(A_REVERSE);
407     addnstr(buffer, console_width);
408     attroff(A_REVERSE);
409   }
410
411   // We are done
412
413   refresh();
414   free_matcher(&matcher);
415 }
416
417 //////////////////////////////////////////////////////////////////////
418
419 int main(int argc, char **argv) {
420
421   if(!ttyname(STDIN_FILENO)) {
422     cerr << "The standard input is not a tty." << endl;
423     exit(1);
424   }
425
426   char buffer[buffer_size], raw_line[buffer_size];;
427   int color_fg_modeline, color_bg_modeline;
428   int color_fg_highlight, color_bg_highlight;
429
430   color_fg_modeline  = COLOR_WHITE;
431   color_bg_modeline  = COLOR_BLACK;
432   color_fg_highlight = COLOR_BLACK;
433   color_bg_highlight = COLOR_YELLOW;
434
435   setlocale(LC_ALL, "");
436
437   char input_filename[buffer_size], output_filename[buffer_size];
438
439   strcpy(input_filename, "");
440   strcpy(output_filename, "");
441
442   int i = 1;
443   int error = 0, show_help = 0;
444
445   while(!error && !show_help && i < argc) {
446
447     if(strcmp(argv[i], "-o") == 0) {
448       check_opt(argc, argv, i, 1, "<output filename>");
449       strncpy(output_filename, argv[i+1], buffer_size);
450       i += 2;
451     }
452
453     else if(strcmp(argv[i], "-s") == 0) {
454       check_opt(argc, argv, i, 1, "<pattern separator>");
455       pattern_separator = argv[i+1][0];
456       i += 2;
457     }
458
459     else if(strcmp(argv[i], "-v") == 0) {
460       output_to_vt_buffer = 1;
461       i++;
462     }
463
464     else if(strcmp(argv[i], "-m") == 0) {
465       with_colors = 0;
466       i++;
467     }
468
469     else if(strcmp(argv[i], "-f") == 0) {
470       check_opt(argc, argv, i, 1, "<input filename>");
471       strncpy(input_filename, argv[i+1], buffer_size);
472       i += 2;
473     }
474
475     else if(strcmp(argv[i], "-i") == 0) {
476       inverse_order = 1;
477       i++;
478     }
479
480     else if(strcmp(argv[i], "-b") == 0) {
481       bash_history = 1;
482       i++;
483     }
484
485     else if(strcmp(argv[i], "-z") == 0) {
486       zsh_history = 1;
487       i++;
488     }
489
490     else if(strcmp(argv[i], "-d") == 0) {
491       remove_duplicates = 1;
492       i++;
493     }
494
495     else if(strcmp(argv[i], "-e") == 0) {
496       use_regexp = 1;
497       i++;
498     }
499
500     else if(strcmp(argv[i], "-a") == 0) {
501       case_sensitive = 1;
502       i++;
503     }
504
505     else if(strcmp(argv[i], "-t") == 0) {
506       check_opt(argc, argv, i, 1, "<title>");
507       delete[] title;
508       title = new char[strlen(argv[i+1]) + 1];
509       strcpy(title, argv[i+1]);
510       i += 2;
511     }
512
513     else if(strcmp(argv[i], "-l") == 0) {
514       check_opt(argc, argv, i, 1, "<maximum number of lines>");
515       nb_lines_max = atoi(argv[i+1]);
516       i += 2;
517     }
518
519     else if(strcmp(argv[i], "-c") == 0) {
520       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
521       color_fg_modeline = atoi(argv[i+1]);
522       color_bg_modeline = atoi(argv[i+2]);
523       color_fg_highlight = atoi(argv[i+3]);
524       color_bg_highlight = atoi(argv[i+4]);
525       i += 5;
526     }
527
528     else if(strcmp(argv[i], "-h") == 0) {
529       show_help = 1;
530       i++;
531     }
532
533     else {
534       cerr << "Unknown argument " << argv[i] << "." << endl;
535       error = 1;
536     }
537   }
538
539   if(show_help || error) {
540     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
541          << endl
542          << "Written by Francois Fleuret <francois@fleuret.org>."
543          << endl
544          << endl
545          << "Usage: " << argv[0] << " [options] -f <file>" << endl
546          << endl
547          << " -h      show this help" << endl
548          << " -v      inject the selected line in the tty" << endl
549          << " -d      remove duplicated lines" << endl
550          << " -b      remove the bash history line prefix" << endl
551          << " -z      remove the zsh history line prefix" << endl
552          << " -i      invert the order of lines" << endl
553          << " -e      start in regexp mode" << endl
554          << " -a      case sensitive" << endl
555          << " -m      monochrome mode" << endl
556          << " -t <title>" << endl
557          << "         add a title in the modeline" << endl
558          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
559          << "         set the display colors" << endl
560          << " -o <output filename>" << endl
561          << "         set a file to write the selected line to" << endl
562          << " -s <pattern separator>" << endl
563          << "         set the symbol to separate substrings in the pattern" << endl
564          << " -l <max number of lines>" << endl
565          << "         set the maximum number of lines to take into account" << endl
566          << endl;
567
568     exit(error);
569   }
570
571   char **lines = new char *[nb_lines_max];
572
573   if(!input_filename[0]) {
574     cerr << "You must specify a input file with -f." << endl;
575     exit(1);
576   }
577
578   int nb_lines = 0;
579
580   ifstream file(input_filename);
581
582   if(file.fail()) {
583     cerr << "Can not open " << input_filename << endl;
584     return 1;
585   }
586
587   int hash_table_size = nb_lines_max * 10;
588   int *hash_table = 0;
589
590   if(remove_duplicates) {
591     hash_table = new_hash_table(hash_table_size);
592   }
593
594   while(nb_lines < nb_lines_max && !file.eof()) {
595
596     file.getline(raw_line, buffer_size);
597
598     if(raw_line[0]) {
599
600       if(file.fail()) {
601         cerr << "Line too long:" << endl;
602         cerr << raw_line << endl;
603         exit(1);
604       }
605
606       char *s, *t;
607       const char *u;
608
609       s = buffer;
610       t = raw_line;
611       while(*t) {
612         u = unctrl(*t++);
613         while(*u) { *s++ = *u++; }
614       }
615       *s = '\0';
616
617       s = buffer;
618
619       if(zsh_history && *s == ':') {
620         while(*s && *s != ';') s++;
621         if(*s == ';') s++;
622       }
623
624       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
625         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
626       }
627
628       int dup;
629
630       if(hash_table) {
631         dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
632       } else {
633         dup = -1;
634       }
635
636       if(dup < 0) {
637         lines[nb_lines] = new char[strlen(s) + 1];
638         strcpy(lines[nb_lines], s);
639       } else {
640         // The string was already in there, so we do not allocate a
641         // new string but use the pointer to the first occurence of it
642         lines[nb_lines] = lines[dup];
643         lines[dup] = 0;
644       }
645
646       nb_lines++;
647     }
648   }
649
650   delete[] hash_table;
651
652   // Now remove the null strings
653
654   int n = 0;
655   for(int k = 0; k < nb_lines; k++) {
656     if(lines[k]) {
657       lines[n++] = lines[k];
658     }
659   }
660   nb_lines = n;
661
662   if(inverse_order) {
663     for(int i = 0; i < nb_lines/2; i++) {
664       char *s = lines[nb_lines - 1 - i];
665       lines[nb_lines - 1 - i] = lines[i];
666       lines[i] = s;
667     }
668   }
669
670   char pattern[buffer_size];
671   pattern[0] = '\0';
672   int pattern_point;
673   pattern_point = 0;
674
675   //////////////////////////////////////////////////////////////////////
676   // Here we start to display with curse
677
678   initscr();
679
680   noecho();
681
682   // Hide the cursor
683   curs_set(0);
684
685   // So that the arrow keys work
686   keypad(stdscr, TRUE);
687
688   if(with_colors) {
689     if(has_colors()) {
690       start_color();
691       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
692          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
693          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
694          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
695         echo();
696         curs_set(1);
697         endwin();
698         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
699         exit(1);
700       }
701       init_pair(1, color_fg_modeline, color_bg_modeline);
702       init_pair(2, color_fg_highlight, color_bg_highlight);
703     } else {
704       with_colors = 0;
705     }
706   }
707
708   int key;
709   int current_line = 0, temporary_line = 0;
710
711   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, pattern);
712
713   do {
714
715     key = getch();
716
717     int motion = 0;
718
719     if(key >= ' ' && key <= '~') {
720       pattern[pattern_point++] = key;
721       pattern[pattern_point] = '\0';
722     }
723
724     else if(key == KEY_BACKSPACE || key == '\b' || key == '\7f' ||
725             key == KEY_DC || key == '\ 4') {
726       if(pattern_point > 0) {
727         pattern_point--;
728         pattern[pattern_point] = '\0';
729       }
730     }
731
732     else if(key == KEY_HOME) {
733       current_line = 0;
734     }
735
736     else if(key == KEY_END) {
737       current_line = nb_lines - 1;
738     }
739
740     else if(key == KEY_NPAGE) {
741       motion = 10;
742     }
743
744     else if(key == KEY_PPAGE) {
745       motion = -10;
746     }
747
748     else if(key == KEY_DOWN || key == '\ e') {
749       motion = 1;
750     }
751
752     else if(key == KEY_UP || key == '\10') {
753       motion = -1;
754     }
755
756     else if(key == '\12') {
757       use_regexp = !use_regexp;
758     }
759
760     else if(key == '\15') {
761       pattern_point = 0;
762       pattern[pattern_point] = '\0';
763     }
764
765     update_screen(&current_line, &temporary_line, motion,
766                   nb_lines, lines, pattern);
767
768   } while(key != '\n' && key != KEY_ENTER && key != '\a');
769
770   echo();
771   curs_set(1);
772   endwin();
773
774   //////////////////////////////////////////////////////////////////////
775   // Here we come back to standard display
776
777   if((key == KEY_ENTER || key == '\n')) {
778
779     if(output_to_vt_buffer) {
780       if(temporary_line >= 0 && temporary_line < nb_lines) {
781         inject_into_tty_buffer(lines[temporary_line]);
782       }
783     }
784
785     if(output_filename[0]) {
786       ofstream out(output_filename);
787       if(out.fail()) {
788         cerr << "Can not open " << output_filename << " for writing." << endl;
789         exit(1);
790       } else {
791         if(temporary_line >= 0 && temporary_line < nb_lines) {
792           out << lines[temporary_line] << endl;
793         } else {
794           out << endl;
795         }
796       }
797       out.flush();
798     }
799
800   }
801
802   for(int l = 0; l < nb_lines; l++) {
803     delete[] lines[l];
804   }
805
806   delete[] lines;
807   delete[] title;
808
809   exit(0);
810 }