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