bec4ed3841ccb2dc726348e9397c1525e74fea2d
[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 = 1;
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 color_theme = 0;
308
309   setlocale(LC_ALL, "");
310
311   char input_filename[buffer_size], output_filename[buffer_size];
312   strcpy(input_filename, "");
313   strcpy(output_filename, "/tmp/selector.out");
314
315   int i = 1;
316   while(i < argc) {
317     if(strcmp(argv[i], "-o") == 0) {
318       check_opt(argc, argv, i, 1, "<output filename>");
319       strncpy(output_filename, argv[i+1], buffer_size);
320       i += 2;
321     }
322
323     else if(strcmp(argv[i], "-s") == 0) {
324       check_opt(argc, argv, i, 1, "<pattern separator>");
325       pattern_separator = argv[i+1][0];
326       i += 2;
327     }
328
329     else if(strcmp(argv[i], "-v") == 0) {
330       output_to_vt_buffer = 1;
331       i++;
332     }
333
334     else if(strcmp(argv[i], "-m") == 0) {
335       with_colors = 0;
336       i++;
337     }
338
339     else if(strcmp(argv[i], "-f") == 0) {
340       check_opt(argc, argv, i, 1, "<input filename>");
341       strncpy(input_filename, argv[i+1], buffer_size);
342       i += 2;
343     }
344
345     else if(strcmp(argv[i], "-b") == 0) {
346       no_blink = 1;
347       i++;
348     }
349
350     else if(strcmp(argv[i], "-l") == 0) {
351       check_opt(argc, argv, i, 1, "<maximum number of lines>");
352       nb_lines_max = atoi(argv[i+1]);
353       i += 2;
354     }
355
356     else if(strcmp(argv[i], "-t") == 0) {
357       check_opt(argc, argv, i, 1, "<color theme number>");
358       color_theme = atoi(argv[i+1]);
359       i += 2;
360     }
361
362     else {
363       cerr << "Selector version " << VERSION
364            << endl
365            << "Written by Francois Fleuret <francois@fleuret.org>"
366            << endl
367            << argv[0]
368            << " [-h]"
369            << " [-b]"
370            << " [-v]"
371            << " [-m]"
372            << " [-t <color theme number>]"
373            << " [-o <output filename>]"
374            << " [-s <pattern separator>]"
375            << " [-l <max number of lines>]"
376            << " -f <input filename>"
377            << endl;
378       if(strcmp(argv[i], "-h") == 0) {
379         exit(0);
380       } else {
381         exit(1);
382       }
383     }
384   }
385
386   if(!input_filename[0]) {
387     cerr << "You must specify a input file with -f." << endl;
388     exit(1);
389   }
390
391   ifstream file(input_filename);
392
393   if(file.fail()) {
394     cerr << "Can not open " << input_filename << endl;
395     return 1;
396   }
397
398   int nb_lines = 0;
399   while(nb_lines < nb_lines_max && !file.eof()) {
400     file.getline(buffer, buffer_size);
401     lines[nb_lines] = new char[strlen(buffer) + 1];
402     strcpy(lines[nb_lines], buffer);
403     nb_lines++;
404   }
405
406   char patterns[buffer_size];
407   patterns[0] = '\0';
408   int patterns_point;
409   patterns_point = 0;
410
411   initscr();
412
413   if(with_colors) {
414     if(has_colors()) {
415       start_color();
416       switch(color_theme) {
417       default:
418       case 0:
419         init_pair(1, COLOR_WHITE, COLOR_GREEN);
420         init_pair(2, COLOR_BLACK, COLOR_YELLOW);
421         break;
422       case 1:
423         init_pair(1, COLOR_WHITE, COLOR_BLACK);
424         init_pair(2, COLOR_BLACK, COLOR_YELLOW);
425         break;
426       case 2:
427         init_pair(1, COLOR_BLACK, COLOR_GREEN);
428         init_pair(2, COLOR_BLACK, COLOR_YELLOW);
429         break;
430       case 3:
431         init_pair(1, COLOR_BLACK, COLOR_RED);
432         init_pair(2, COLOR_BLACK, COLOR_YELLOW);
433         break;
434       case 4:
435         init_pair(1, COLOR_WHITE, COLOR_BLACK);
436         init_pair(2, COLOR_BLACK, COLOR_BLUE);
437         break;
438       case 5:
439         init_pair(1, COLOR_BLACK, COLOR_MAGENTA);
440         init_pair(2, COLOR_BLACK, COLOR_CYAN);
441         break;
442       }
443     } else {
444       with_colors = 0;
445     }
446   }
447
448   noecho();
449   curs_set(0); // Hide the cursor
450   keypad(stdscr, TRUE); // So that the arrow keys work
451
452   int key;
453   int current_line = 0, temporary_line = 0;
454
455   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns, no_blink);
456
457   do {
458
459     key = getch();
460
461     int motion = 0;
462
463     if(key >= ' ' && key <= '~') {
464       patterns[patterns_point++] = key;
465       patterns[patterns_point] = '\0';
466     }
467
468     else if(key == KEY_BACKSPACE || key == KEY_DC || key == '\b') {
469       if(patterns_point > 0) {
470         patterns_point--;
471         patterns[patterns_point] = '\0';
472       }
473     }
474
475     else if(key == KEY_HOME) {
476       current_line = 0;
477     }
478
479     else if(key == KEY_END) {
480       current_line = nb_lines - 1;
481     }
482
483     else if(key == KEY_NPAGE) {
484       motion = 10;
485     }
486
487     else if(key == KEY_PPAGE) {
488       motion = -10;
489     }
490
491     else if(key == KEY_UP || key == '\10') {
492       motion = -1;
493     }
494
495     else if(key == KEY_DOWN || key == '\ e') {
496       motion = 1;
497     }
498
499     update_screen(&current_line, &temporary_line, motion,
500                   nb_lines, lines, patterns, no_blink);
501
502   } while(key != '\n' && key != KEY_ENTER && key != '\a');
503
504   echo();
505   curs_set(1);
506   endwin();
507
508   if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
509     if(output_to_vt_buffer) {
510       char *tty = ttyname(STDIN_FILENO);
511       int fd = open(tty, O_WRONLY);
512
513       struct termios oldtio, newtio;
514
515       if (fd >= 0) {
516         // Save current port settings
517         tcgetattr(fd,&oldtio);
518         memset(&newtio, 0, sizeof(newtio));
519         // Set input mode (non-canonical, *no echo*,...)
520         tcflush(fd, TCIFLUSH);
521         tcsetattr(fd,TCSANOW, &newtio);
522         // Put the selected line in the tty input buffer
523         for(char *k = lines[temporary_line]; *k; k++) {
524           ioctl(fd, TIOCSTI, k);
525         }
526         // Restore the old settings
527         tcsetattr(fd,TCSANOW, &oldtio);
528         close(fd);
529       } else {
530         cerr << "Can not open " << tty << "." << endl;
531         exit(1);
532       }
533     } else {
534       ofstream out(output_filename);
535       if(out.fail()) {
536         cerr << "Can not open " << output_filename << " for writing." << endl;
537         exit(1);
538       } else {
539         out << lines[temporary_line] << endl;
540       }
541       out.flush();
542     }
543   }
544
545   for(int l = 0; l < nb_lines; l++) {
546     delete[] lines[l];
547   }
548
549   exit(0);
550 }