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