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