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