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