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