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