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