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