Fixed the odd number of lines bug.
[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 -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
43 using namespace std;
44
45 #define VERSION "1.0"
46
47 const int buffer_size = 1024;
48
49 // Yeah, global variables!
50
51 int nb_lines_max = 1000;
52 char pattern_separator = ';';
53 int output_to_vt_buffer = 0;
54 int with_colors = 1;
55 int zsh_history = 0, bash_history = 0;
56 int inverse_order = 0;
57 int remove_duplicates = 0;
58
59 //////////////////////////////////////////////////////////////////////
60
61 // This looks severely Linux-only ...
62
63 void inject_into_tty_buffer(char *line) {
64   struct termios oldtio, newtio;
65   tcgetattr(STDIN_FILENO,&oldtio);
66   memset(&newtio, 0, sizeof(newtio));
67   // Set input mode (non-canonical, *no echo*,...)
68   tcsetattr(STDIN_FILENO,TCSANOW, &newtio);
69   // Put the selected line in the tty input buffer
70   for(char *k = line; *k; k++) {
71     ioctl(STDIN_FILENO, TIOCSTI, k);
72   }
73   // Restore the old settings
74   tcsetattr(STDIN_FILENO,TCSANOW, &oldtio);
75 }
76
77 //////////////////////////////////////////////////////////////////////
78
79 int match(char *string, int nb_patterns, char **patterns) {
80   for(int n = 0; n < nb_patterns; n++) {
81     if(strstr(string, patterns[n]) == 0) return 0;
82   }
83   return 1;
84 }
85
86 //////////////////////////////////////////////////////////////////////
87
88 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
89   if(n_opt + n >= argc) {
90     cerr << "Missing argument for " << argv[n_opt] << "."
91          << " "
92          << "Expecting " << help << "."
93          << endl;
94     exit(1);
95   }
96 }
97
98 //////////////////////////////////////////////////////////////////////
99
100 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
101   int line = current_line - 1;
102   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
103   return line;
104 }
105
106 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
107   int line = current_line + 1;
108   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
109
110   if(line < nb_lines)
111     return line;
112   else
113     return -1;
114 }
115
116 void update_screen(int *current_line, int *temporary_line, int motion,
117                    int nb_lines, char **lines,
118                    char *pattern_list) {
119
120   char buffer[buffer_size];
121
122   // We split the pattern list into individual patterns
123
124   int nb_patterns = 1;
125
126   for(char *s = pattern_list; *s; s++) {
127     if(*s == pattern_separator) {
128       nb_patterns++;
129     }
130   }
131
132   char splitted_patterns[strlen(pattern_list) + 1];
133   char *patterns[nb_patterns];
134
135   strcpy(splitted_patterns, pattern_list);
136
137   int n = 0;
138   char *last_pattern_start = splitted_patterns;
139   for(char *s = splitted_patterns; n < nb_patterns; s++) {
140     if(*s == pattern_separator || *s == '\0') {
141       *s = '\0';
142       patterns[n++] = last_pattern_start;
143       last_pattern_start = s + 1;
144     }
145   }
146
147   // We now take care of printing the lines per se
148
149   int console_width = getmaxx(stdscr);
150   int console_height = getmaxy(stdscr);
151
152   // First, we find a visible line. In priority: The current, or the
153   // first visible after it, or the first visible before it.
154
155   int new_line;
156   if(match(lines[*current_line], nb_patterns, patterns)) {
157     new_line = *current_line;
158   } else {
159     new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
160     if(new_line < 0) {
161       new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
162     }
163   }
164
165   // If we found a visible line and we should move, let's move
166
167   if(new_line >= 0 && motion != 0) {
168     int l = new_line;
169     if(motion > 0) {
170       // We want to go down, let's find the first visible line below
171       for(int m = 0; l >= 0 && m < motion; m++) {
172         l = next_visible(l, nb_lines, lines, nb_patterns, patterns);
173         if(l >= 0) {
174           new_line = l;
175         }
176       }
177     } else {
178       // We want to go up, let's find the first visible line above
179       for(int m = 0; l >= 0 && m < -motion; m++) {
180         l = previous_visible(l, nb_lines, lines, nb_patterns, patterns);
181         if(l >= 0) {
182           new_line = l;
183         }
184       }
185     }
186   }
187
188   clear();
189
190   use_default_colors();
191
192   addstr("\n");
193
194   int nb_printed_lines = 0;
195
196   // Here new_line is either a line number matching the patterns, or -1
197
198   if(new_line >= 0) {
199
200     int first_line = new_line, last_line = new_line, nb_match = 1;
201
202     // We find the first and last line to show, so that the total of
203     // visible lines between them (them include) is console_height - 1
204
205     while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
206
207       if(first_line > 0) {
208         first_line--;
209         while(first_line > 0 && !match(lines[first_line], nb_patterns, patterns)) {
210           first_line--;
211         }
212         if(match(lines[first_line], nb_patterns, patterns)) {
213           nb_match++;
214         }
215       }
216
217       if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
218         last_line++;
219         while(last_line < nb_lines - 1 && !match(lines[last_line], nb_patterns, patterns)) {
220           last_line++;
221         }
222
223         if(match(lines[last_line], nb_patterns, patterns)) {
224           nb_match++;
225         }
226       }
227     }
228
229     // Now we display them
230
231     for(int l = first_line; l <= last_line; l++) {
232       if(match(lines[l], nb_patterns, patterns)) {
233         int k = 0;
234
235         while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
236           buffer[k] = lines[l][k];
237           k++;
238         }
239
240         // We fill the rest of the line with blanks if either we did
241         // not clear() or if this is the highlighted line
242
243         if(l == new_line) {
244           while(k < console_width) {
245             buffer[k++] = ' ';
246           }
247         }
248
249         buffer[k++] = '\n';
250         buffer[k++] = '\0';
251
252         // Highlight the highlighted line ...
253
254         if(l == new_line) {
255           if(with_colors) {
256             attron(COLOR_PAIR(2));
257             addnstr(buffer, console_width);
258             attroff(COLOR_PAIR(2));
259           } else {
260             attron(A_STANDOUT);
261             addnstr(buffer, console_width);
262             attroff(A_STANDOUT);
263           }
264         } else {
265           addnstr(buffer, console_width);
266         }
267
268         nb_printed_lines++;
269       }
270     }
271
272     if(motion != 0) {
273       *current_line = new_line;
274     }
275   }
276
277   *temporary_line = new_line;
278
279   if(nb_printed_lines == 0) {
280     addnstr("[no selection]\n", console_width);
281   }
282
283   // Draw the modeline
284
285   sprintf(buffer, "%d/%d pattern: %s",
286           nb_printed_lines,
287           nb_lines,
288           pattern_list);
289
290   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
291   buffer[console_width] = '\0';
292
293   move(0, 0);
294   if(with_colors) {
295     attron(COLOR_PAIR(1));
296     addnstr(buffer, console_width);
297     attroff(COLOR_PAIR(1));
298   } else {
299     attron(A_REVERSE);
300     addnstr(buffer, console_width);
301     attroff(A_REVERSE);
302   }
303
304   // We are done
305
306   refresh();
307 }
308
309 //////////////////////////////////////////////////////////////////////
310
311 int main(int argc, char **argv) {
312   char buffer[buffer_size];
313   int color_fg_modeline, color_bg_modeline;
314   int color_fg_highlight, color_bg_highlight;
315
316   color_fg_modeline  = COLOR_WHITE;
317   color_bg_modeline  = COLOR_BLACK;
318   color_fg_highlight = COLOR_BLACK;
319   color_bg_highlight = COLOR_YELLOW;
320
321   setlocale(LC_ALL, "");
322
323   char input_filename[buffer_size], output_filename[buffer_size];
324
325   strcpy(input_filename, "");
326   strcpy(output_filename, "");
327
328   int i = 1;
329   while(i < argc) {
330
331     if(strcmp(argv[i], "-o") == 0) {
332       check_opt(argc, argv, i, 1, "<output filename>");
333       strncpy(output_filename, argv[i+1], buffer_size);
334       i += 2;
335     }
336
337     else if(strcmp(argv[i], "-s") == 0) {
338       check_opt(argc, argv, i, 1, "<pattern separator>");
339       pattern_separator = argv[i+1][0];
340       i += 2;
341     }
342
343     else if(strcmp(argv[i], "-v") == 0) {
344       output_to_vt_buffer = 1;
345       i++;
346     }
347
348     else if(strcmp(argv[i], "-m") == 0) {
349       with_colors = 0;
350       i++;
351     }
352
353     else if(strcmp(argv[i], "-f") == 0) {
354       check_opt(argc, argv, i, 1, "<input filename>");
355       strncpy(input_filename, argv[i+1], buffer_size);
356       i += 2;
357     }
358
359     else if(strcmp(argv[i], "-i") == 0) {
360       inverse_order = 1;
361       i++;
362     }
363
364     else if(strcmp(argv[i], "-z") == 0) {
365       zsh_history = 1;
366       i++;
367     }
368
369     else if(strcmp(argv[i], "-b") == 0) {
370       bash_history = 1;
371       i++;
372     }
373
374     else if(strcmp(argv[i], "-r") == 0) {
375       remove_duplicates = 1;
376       i++;
377     }
378
379     else if(strcmp(argv[i], "-l") == 0) {
380       check_opt(argc, argv, i, 1, "<maximum number of lines>");
381       nb_lines_max = atoi(argv[i+1]);
382       i += 2;
383     }
384
385     else if(strcmp(argv[i], "-c") == 0) {
386       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
387       color_fg_modeline = atoi(argv[i+1]);
388       color_bg_modeline = atoi(argv[i+2]);
389       color_fg_highlight = atoi(argv[i+3]);
390       color_bg_highlight = atoi(argv[i+4]);
391       i += 5;
392     }
393
394     else {
395       cerr << "Selector version " << VERSION
396            << endl
397            << "Written by Francois Fleuret <francois@fleuret.org>"
398            << endl
399            << argv[0]
400            << " [-h]"
401            << " [-v]"
402            << " [-m]"
403            << " [-r]"
404            << " [-z]"
405            << " [-i]"
406            << " [-c <fg modeline> <bg modeline> <fg highlight> <bg highlight>]"
407            << " [-o <output filename>]"
408            << " [-s <pattern separator>]"
409            << " [-l <max number of lines>]"
410            << " -f <input filename>"
411            << endl;
412       if(strcmp(argv[i], "-h") == 0) {
413         exit(0);
414       } else {
415         exit(1);
416       }
417     }
418   }
419
420   char **lines = new char *[nb_lines_max];
421
422   if(!input_filename[0]) {
423     cerr << "You must specify a input file with -f." << endl;
424     exit(1);
425   }
426
427   int nb_lines = 0;
428
429   ifstream file(input_filename);
430
431   if(file.fail()) {
432     cerr << "Can not open " << input_filename << endl;
433     return 1;
434   }
435
436   while(nb_lines < nb_lines_max && !file.eof()) {
437     file.getline(buffer, buffer_size);
438     if(strcmp(buffer, "") != 0) {
439       char *s = buffer;
440       if(zsh_history && *s == ':') {
441         while(*s && *s != ';') s++;
442         if(*s == ';') s++;
443       }
444
445       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
446         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
447       }
448
449       if(!remove_duplicates || nb_lines == 0 || strcmp(lines[nb_lines - 1], s)) {
450         lines[nb_lines] = new char[strlen(s) + 1];
451         strcpy(lines[nb_lines], s);
452         nb_lines++;
453       }
454     }
455   }
456
457   if(inverse_order) {
458     for(int i = 0; i < nb_lines/2; i++) {
459       char *s = lines[nb_lines - 1 - i];
460       lines[nb_lines - 1 - i] = lines[i];
461       lines[i] = s;
462     }
463   }
464
465   char patterns[buffer_size];
466   patterns[0] = '\0';
467   int patterns_point;
468   patterns_point = 0;
469
470   initscr();
471
472   if(with_colors) {
473     if(has_colors()) {
474       start_color();
475       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
476          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
477          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
478          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
479         echo();
480         curs_set(1);
481         endwin();
482         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
483         exit(1);
484       }
485       init_pair(1, color_fg_modeline, color_bg_modeline);
486       init_pair(2, color_fg_highlight, color_bg_highlight);
487     } else {
488       with_colors = 0;
489     }
490   }
491
492   noecho();
493   curs_set(0); // Hide the cursor
494   keypad(stdscr, TRUE); // So that the arrow keys work
495
496   int key;
497   int current_line = 0, temporary_line = 0;
498
499   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns);
500
501   do {
502
503     key = getch();
504
505     int motion = 0;
506
507     if(key >= ' ' && key <= '~') {
508       patterns[patterns_point++] = key;
509       patterns[patterns_point] = '\0';
510     }
511
512     else if(key == KEY_BACKSPACE || key == '\b' || key == '\7f' ||
513             key == KEY_DC || key == '\ 4') {
514       if(patterns_point > 0) {
515         patterns_point--;
516         patterns[patterns_point] = '\0';
517       }
518     }
519
520     else if(key == KEY_HOME) {
521       current_line = 0;
522     }
523
524     else if(key == KEY_END) {
525       current_line = nb_lines - 1;
526     }
527
528     else if(key == KEY_NPAGE) {
529       motion = 10;
530     }
531
532     else if(key == KEY_PPAGE) {
533       motion = -10;
534     }
535
536     else if(key == KEY_UP || key == '\10') {
537       motion = -1;
538     }
539
540     else if(key == KEY_DOWN || key == '\ e') {
541       motion = 1;
542     }
543
544     update_screen(&current_line, &temporary_line, motion,
545                   nb_lines, lines, patterns);
546
547   } while(key != '\n' && key != KEY_ENTER && key != '\a');
548
549   echo();
550   curs_set(1);
551   endwin();
552
553   if((key == KEY_ENTER || key == '\n')) {
554
555     if(output_to_vt_buffer) {
556       if(temporary_line >= 0 && temporary_line < nb_lines) {
557         inject_into_tty_buffer(lines[temporary_line]);
558       }
559     }
560
561     if(output_filename[0]) {
562       ofstream out(output_filename);
563       if(out.fail()) {
564         cerr << "Can not open " << output_filename << " for writing." << endl;
565         exit(1);
566       } else {
567         if(temporary_line >= 0 && temporary_line < nb_lines) {
568           out << lines[temporary_line] << endl;
569         } else {
570           out << endl;
571         }
572       }
573       out.flush();
574     }
575
576   }
577
578   for(int l = 0; l < nb_lines; l++) {
579     delete[] lines[l];
580   }
581   delete[] lines;
582
583   exit(0);
584 }