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