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