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