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