Cosmetics.
[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 = 1024;
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 {
232
233     int new_line;
234     if(match(lines[*current_line], &matcher)) {
235       new_line = *current_line;
236     } else {
237       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
238       if(new_line < 0) {
239         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
240       }
241     }
242
243     // If we found a visible line and we should move, let's move
244
245     if(new_line >= 0 && motion != 0) {
246       int l = new_line;
247       if(motion > 0) {
248         // We want to go down, let's find the first visible line below
249         for(int m = 0; l >= 0 && m < motion; m++) {
250           l = next_visible(l, nb_lines, lines, &matcher);
251           if(l >= 0) {
252             new_line = l;
253           }
254         }
255       } else {
256         // We want to go up, let's find the first visible line above
257         for(int m = 0; l >= 0 && m < -motion; m++) {
258           l = previous_visible(l, nb_lines, lines, &matcher);
259           if(l >= 0) {
260             new_line = l;
261           }
262         }
263       }
264     }
265
266     // Here new_line is either a line number matching the patterns, or -1
267
268     if(new_line >= 0) {
269
270       int first_line = new_line, last_line = new_line, nb_match = 1;
271
272       // We find the first and last line to show, so that the total of
273       // visible lines between them (them include) is console_height - 1
274
275       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
276
277         if(first_line > 0) {
278           first_line--;
279           while(first_line > 0 && !match(lines[first_line], &matcher)) {
280             first_line--;
281           }
282           if(match(lines[first_line], &matcher)) {
283             nb_match++;
284           }
285         }
286
287         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
288           last_line++;
289           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
290             last_line++;
291           }
292
293           if(match(lines[last_line], &matcher)) {
294             nb_match++;
295           }
296         }
297       }
298
299       // Now we display them
300
301       for(int l = first_line; l <= last_line; l++) {
302         if(match(lines[l], &matcher)) {
303           int k = 0;
304
305           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
306             buffer[k] = lines[l][k];
307             k++;
308           }
309
310           // We fill the rest of the line with blanks if either we did
311           // not clear() or if this is the highlighted line
312
313           if(l == new_line) {
314             while(k < console_width) {
315               buffer[k++] = ' ';
316             }
317           }
318
319           buffer[k++] = '\n';
320           buffer[k++] = '\0';
321
322           // Highlight the highlighted line ...
323
324           if(l == new_line) {
325             if(with_colors) {
326               attron(COLOR_PAIR(2));
327               addnstr(buffer, console_width);
328               attroff(COLOR_PAIR(2));
329             } else {
330               attron(A_STANDOUT);
331               addnstr(buffer, console_width);
332               attroff(A_STANDOUT);
333             }
334           } else {
335             addnstr(buffer, console_width);
336           }
337
338           nb_printed_lines++;
339         }
340       }
341
342       if(motion != 0) {
343         *current_line = new_line;
344       }
345     }
346
347     *temporary_line = new_line;
348
349     if(nb_printed_lines == 0) {
350       addnstr("[no selection]\n", console_width);
351     }
352   }
353
354   // Draw the modeline
355
356   sprintf(buffer, "%d/%d pattern: %s%s",
357           nb_printed_lines,
358           nb_lines,
359           pattern,
360           use_regexp ? " [regexp]" : "");
361
362   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
363   buffer[console_width] = '\0';
364
365   move(0, 0);
366   if(with_colors) {
367     attron(COLOR_PAIR(1));
368     addnstr(buffer, console_width);
369     attroff(COLOR_PAIR(1));
370   } else {
371     attron(A_REVERSE);
372     addnstr(buffer, console_width);
373     attroff(A_REVERSE);
374   }
375
376   // We are done
377
378   refresh();
379   free_matcher(&matcher);
380 }
381
382 //////////////////////////////////////////////////////////////////////
383
384 int main(int argc, char **argv) {
385
386   if(!ttyname(STDIN_FILENO)) {
387     cerr << "The standard input is not a tty." << endl;
388     exit(1);
389   }
390
391   char buffer[buffer_size], raw_line[buffer_size];;
392   int color_fg_modeline, color_bg_modeline;
393   int color_fg_highlight, color_bg_highlight;
394
395   color_fg_modeline  = COLOR_WHITE;
396   color_bg_modeline  = COLOR_BLACK;
397   color_fg_highlight = COLOR_BLACK;
398   color_bg_highlight = COLOR_YELLOW;
399
400   setlocale(LC_ALL, "");
401
402   char input_filename[buffer_size], output_filename[buffer_size];
403
404   strcpy(input_filename, "");
405   strcpy(output_filename, "");
406
407   int i = 1;
408   int error = 0, show_help = 0;
409
410   while(!error && !show_help && i < argc) {
411
412     if(strcmp(argv[i], "-o") == 0) {
413       check_opt(argc, argv, i, 1, "<output filename>");
414       strncpy(output_filename, argv[i+1], buffer_size);
415       i += 2;
416     }
417
418     else if(strcmp(argv[i], "-s") == 0) {
419       check_opt(argc, argv, i, 1, "<pattern separator>");
420       pattern_separator = argv[i+1][0];
421       i += 2;
422     }
423
424     else if(strcmp(argv[i], "-v") == 0) {
425       output_to_vt_buffer = 1;
426       i++;
427     }
428
429     else if(strcmp(argv[i], "-m") == 0) {
430       with_colors = 0;
431       i++;
432     }
433
434     else if(strcmp(argv[i], "-f") == 0) {
435       check_opt(argc, argv, i, 1, "<input filename>");
436       strncpy(input_filename, argv[i+1], buffer_size);
437       i += 2;
438     }
439
440     else if(strcmp(argv[i], "-i") == 0) {
441       inverse_order = 1;
442       i++;
443     }
444
445     else if(strcmp(argv[i], "-b") == 0) {
446       bash_history = 1;
447       i++;
448     }
449
450     else if(strcmp(argv[i], "-z") == 0) {
451       zsh_history = 1;
452       i++;
453     }
454
455     else if(strcmp(argv[i], "-d") == 0) {
456       remove_duplicates = 1;
457       i++;
458     }
459
460     else if(strcmp(argv[i], "-e") == 0) {
461       use_regexp = 1;
462       i++;
463     }
464
465     else if(strcmp(argv[i], "-l") == 0) {
466       check_opt(argc, argv, i, 1, "<maximum number of lines>");
467       nb_lines_max = atoi(argv[i+1]);
468       i += 2;
469     }
470
471     else if(strcmp(argv[i], "-c") == 0) {
472       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
473       color_fg_modeline = atoi(argv[i+1]);
474       color_bg_modeline = atoi(argv[i+2]);
475       color_fg_highlight = atoi(argv[i+3]);
476       color_bg_highlight = atoi(argv[i+4]);
477       i += 5;
478     }
479
480     else if(strcmp(argv[i], "-h") == 0) {
481       show_help = 1;
482       i++;
483     }
484
485     else {
486       cerr << "Unknown argument " << argv[i] << "." << endl;
487       error = 1;
488     }
489   }
490
491   if(show_help || error) {
492     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
493          << endl
494          << "Written by Francois Fleuret <francois@fleuret.org>."
495          << endl
496          << endl
497          << "Usage: " << argv[0] << " [options] -f <file>" << endl
498          << endl
499          << " -h      show this help" << endl
500          << " -v      inject the selected line in the tty" << endl
501          << " -d      remove duplicated lines" << endl
502          << " -b      remove the bash history line prefix" << endl
503          << " -z      remove the zsh history line prefix" << endl
504          << " -i      invert the order of lines" << endl
505          << " -e      start in regexp mode" << endl
506          << " -m      monochrome mode" << endl
507          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
508          << "         set the display colors" << endl
509          << " -o <output filename>" << endl
510          << "         set a file to write the selected line to" << endl
511          << " -s <pattern separator>" << endl
512          << "         set the symbol to separate substrings in the pattern" << endl
513          << " -l <max number of lines>" << endl
514          << "         set the maximum number of lines to take into account" << endl
515          << endl;
516
517     exit(error);
518   }
519
520   char **lines = new char *[nb_lines_max];
521
522   if(!input_filename[0]) {
523     cerr << "You must specify a input file with -f." << endl;
524     exit(1);
525   }
526
527   int nb_lines = 0;
528
529   ifstream file(input_filename);
530
531   if(file.fail()) {
532     cerr << "Can not open " << input_filename << endl;
533     return 1;
534   }
535
536   int hash_table_size = nb_lines_max * 10;
537   int *hash_table = 0;
538
539   if(remove_duplicates) {
540     hash_table = new_hash_table(hash_table_size);
541   }
542
543   while(nb_lines < nb_lines_max && !file.eof()) {
544
545     file.getline(raw_line, buffer_size);
546
547     if(raw_line[0]) {
548
549       char *s, *t;
550       const char *u;
551
552       s = buffer;
553       t = raw_line;
554       while(*t) {
555         u = unctrl(*t++);
556         while(*u) { *s++ = *u++; }
557       }
558       *s = '\0';
559
560       s = buffer;
561
562       if(zsh_history && *s == ':') {
563         while(*s && *s != ';') s++;
564         if(*s == ';') s++;
565       }
566
567       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
568         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
569       }
570
571       int dup;
572
573       if(hash_table) {
574         dup = test_and_add(s, nb_lines, lines, hash_table, hash_table_size);
575       } else {
576         dup = -1;
577       }
578
579       if(dup < 0) {
580         lines[nb_lines] = new char[strlen(s) + 1];
581         strcpy(lines[nb_lines], s);
582       } else {
583         // We do not allocate a new string but use the pointer to the
584         // first occurence of it
585         lines[nb_lines] = lines[dup];
586         lines[dup] = 0;
587       }
588
589       nb_lines++;
590     }
591   }
592
593   delete[] hash_table;
594
595   // Now remove the null strings
596
597   int n = 0;
598   for(int k = 0; k < nb_lines; k++) {
599     if(lines[k]) {
600       lines[n++] = lines[k];
601     }
602   }
603   nb_lines = n;
604
605   if(inverse_order) {
606     for(int i = 0; i < nb_lines/2; i++) {
607       char *s = lines[nb_lines - 1 - i];
608       lines[nb_lines - 1 - i] = lines[i];
609       lines[i] = s;
610     }
611   }
612
613   char pattern[buffer_size];
614   pattern[0] = '\0';
615   int pattern_point;
616   pattern_point = 0;
617
618   //////////////////////////////////////////////////////////////////////
619   // Here we start to display with curse
620
621   initscr();
622
623   noecho();
624
625   // Hide the cursor
626   curs_set(0);
627
628   // So that the arrow keys work
629   keypad(stdscr, TRUE);
630
631   if(with_colors) {
632     if(has_colors()) {
633       start_color();
634       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
635          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
636          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
637          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
638         echo();
639         curs_set(1);
640         endwin();
641         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
642         exit(1);
643       }
644       init_pair(1, color_fg_modeline, color_bg_modeline);
645       init_pair(2, color_fg_highlight, color_bg_highlight);
646     } else {
647       with_colors = 0;
648     }
649   }
650
651   int key;
652   int current_line = 0, temporary_line = 0;
653
654   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, pattern);
655
656   do {
657
658     key = getch();
659
660     int motion = 0;
661
662     if(key >= ' ' && key <= '~') {
663       pattern[pattern_point++] = key;
664       pattern[pattern_point] = '\0';
665     }
666
667     else if(key == KEY_BACKSPACE || key == '\b' || key == '\7f' ||
668             key == KEY_DC || key == '\ 4') {
669       if(pattern_point > 0) {
670         pattern_point--;
671         pattern[pattern_point] = '\0';
672       }
673     }
674
675     else if(key == KEY_HOME) {
676       current_line = 0;
677     }
678
679     else if(key == KEY_END) {
680       current_line = nb_lines - 1;
681     }
682
683     else if(key == KEY_NPAGE) {
684       motion = 10;
685     }
686
687     else if(key == KEY_PPAGE) {
688       motion = -10;
689     }
690
691     else if(key == KEY_DOWN || key == '\ e') {
692       motion = 1;
693     }
694
695     else if(key == KEY_UP || key == '\10') {
696       motion = -1;
697     }
698
699     else if(key == '\12') {
700       use_regexp = !use_regexp;
701     }
702
703     else if(key == '\15') {
704       pattern_point = 0;
705       pattern[pattern_point] = '\0';
706     }
707
708     update_screen(&current_line, &temporary_line, motion,
709                   nb_lines, lines, pattern);
710
711   } while(key != '\n' && key != KEY_ENTER && key != '\a');
712
713   echo();
714   curs_set(1);
715   endwin();
716
717   //////////////////////////////////////////////////////////////////////
718   // Here we come back to standard display
719
720   if((key == KEY_ENTER || key == '\n')) {
721
722     if(output_to_vt_buffer) {
723       if(temporary_line >= 0 && temporary_line < nb_lines) {
724         inject_into_tty_buffer(lines[temporary_line]);
725       }
726     }
727
728     if(output_filename[0]) {
729       ofstream out(output_filename);
730       if(out.fail()) {
731         cerr << "Can not open " << output_filename << " for writing." << endl;
732         exit(1);
733       } else {
734         if(temporary_line >= 0 && temporary_line < nb_lines) {
735           out << lines[temporary_line] << endl;
736         } else {
737           out << endl;
738         }
739       }
740       out.flush();
741     }
742
743   }
744
745   for(int l = 0; l < nb_lines; l++) {
746     delete[] lines[l];
747   }
748
749   delete[] lines;
750
751   exit(0);
752 }