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