Added a routine, now commented out, to remove all duplicates (not only
[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 int remove_duplicates = 0;
58
59 //////////////////////////////////////////////////////////////////////
60
61 // This looks severely Linux-only ...
62
63 void inject_into_tty_buffer(char *line) {
64   char *tty = ttyname(STDIN_FILENO);
65   int fd = open(tty, O_RDWR);
66
67   struct termios oldtio, newtio;
68
69   if (fd >= 0) {
70     // Save current port settings
71     tcgetattr(fd,&oldtio);
72     memset(&newtio, 0, sizeof(newtio));
73     // Set input mode (non-canonical, *no echo*,...)
74     tcflush(fd, TCIFLUSH);
75     tcsetattr(fd,TCSANOW, &newtio);
76     // Put the selected line in the tty input buffer
77     for(char *k = line; *k; k++) {
78       ioctl(fd, TIOCSTI, k);
79     }
80     // Restore the old settings
81     tcsetattr(fd,TCSANOW, &oldtio);
82     close(fd);
83   } else {
84     cerr << "Can not open " << tty << "." << endl;
85     exit(1);
86   }
87 }
88
89 //////////////////////////////////////////////////////////////////////
90
91 int match(char *string, int nb_patterns, char **patterns) {
92   for(int n = 0; n < nb_patterns; n++) {
93     if(strstr(string, patterns[n]) == 0) return 0;
94   }
95   return 1;
96 }
97
98 //////////////////////////////////////////////////////////////////////
99
100 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
101   if(n_opt + n >= argc) {
102     cerr << "Missing argument for " << argv[n_opt] << "."
103          << " "
104          << "Expecting " << help << "."
105          << endl;
106     exit(1);
107   }
108 }
109
110 //////////////////////////////////////////////////////////////////////
111
112 int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
113   int line = current_line - 1;
114   while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
115   return line;
116 }
117
118 int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
119   int line = current_line + 1;
120   while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
121
122   if(line < nb_lines)
123     return line;
124   else
125     return -1;
126 }
127
128 void update_screen(int *current_line, int *temporary_line, int motion,
129                    int nb_lines, char **lines,
130                    char *pattern_list) {
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   clear();
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(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   // Draw the modeline
297
298   sprintf(buffer, "%d/%d pattern: %s",
299           nb_printed_lines - 1,
300           nb_lines,
301           pattern_list);
302
303   for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
304   buffer[console_width] = '\0';
305
306   move(0, 0);
307   if(with_colors) {
308     attron(COLOR_PAIR(1));
309     addnstr(buffer, console_width);
310     attroff(COLOR_PAIR(1));
311   } else {
312     attron(A_REVERSE);
313     addnstr(buffer, console_width);
314     attroff(A_REVERSE);
315   }
316
317   // We are done
318
319   refresh();
320 }
321
322 //////////////////////////////////////////////////////////////////////
323
324 int main(int argc, char **argv) {
325   char buffer[buffer_size];
326   int color_fg_modeline, color_bg_modeline;
327   int color_fg_highlight, color_bg_highlight;
328
329   color_fg_modeline  = COLOR_WHITE;
330   color_bg_modeline  = COLOR_BLACK;
331   color_fg_highlight = COLOR_BLACK;
332   color_bg_highlight = COLOR_YELLOW;
333
334   setlocale(LC_ALL, "");
335
336   char input_filename[buffer_size], output_filename[buffer_size];
337
338   strcpy(input_filename, "");
339   strcpy(output_filename, "");
340
341   int i = 1;
342   while(i < argc) {
343
344     if(strcmp(argv[i], "-o") == 0) {
345       check_opt(argc, argv, i, 1, "<output filename>");
346       strncpy(output_filename, argv[i+1], buffer_size);
347       i += 2;
348     }
349
350     else if(strcmp(argv[i], "-s") == 0) {
351       check_opt(argc, argv, i, 1, "<pattern separator>");
352       pattern_separator = argv[i+1][0];
353       i += 2;
354     }
355
356     else if(strcmp(argv[i], "-v") == 0) {
357       output_to_vt_buffer = 1;
358       i++;
359     }
360
361     else if(strcmp(argv[i], "-m") == 0) {
362       with_colors = 0;
363       i++;
364     }
365
366     else if(strcmp(argv[i], "-f") == 0) {
367       check_opt(argc, argv, i, 1, "<input filename>");
368       strncpy(input_filename, argv[i+1], buffer_size);
369       i += 2;
370     }
371
372     else if(strcmp(argv[i], "-i") == 0) {
373       inverse_order = 1;
374       i++;
375     }
376
377     else if(strcmp(argv[i], "-z") == 0) {
378       zsh_history = 1;
379       i++;
380     }
381
382     else if(strcmp(argv[i], "-b") == 0) {
383       bash_history = 1;
384       i++;
385     }
386
387     else if(strcmp(argv[i], "-r") == 0) {
388       remove_duplicates = 1;
389       i++;
390     }
391
392     else if(strcmp(argv[i], "-l") == 0) {
393       check_opt(argc, argv, i, 1, "<maximum number of lines>");
394       nb_lines_max = atoi(argv[i+1]);
395       i += 2;
396     }
397
398     else if(strcmp(argv[i], "-c") == 0) {
399       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
400       color_fg_modeline = atoi(argv[i+1]);
401       color_bg_modeline = atoi(argv[i+2]);
402       color_fg_highlight = atoi(argv[i+3]);
403       color_bg_highlight = atoi(argv[i+4]);
404       i += 5;
405     }
406
407     else {
408       cerr << "Selector version " << VERSION
409            << endl
410            << "Written by Francois Fleuret <francois@fleuret.org>"
411            << endl
412            << argv[0]
413            << " [-h]"
414            << " [-v]"
415            << " [-m]"
416            << " [-r]"
417            << " [-z]"
418            << " [-i]"
419            << " [-c <fg modeline> <bg modeline> <fg highlight> <bg highlight>]"
420            << " [-o <output filename>]"
421            << " [-s <pattern separator>]"
422            << " [-l <max number of lines>]"
423            << " -f <input filename>"
424            << endl;
425       if(strcmp(argv[i], "-h") == 0) {
426         exit(0);
427       } else {
428         exit(1);
429       }
430     }
431   }
432
433   char **lines = new char *[nb_lines_max];
434
435   if(!input_filename[0]) {
436     cerr << "You must specify a input file with -f." << endl;
437     exit(1);
438   }
439
440   int nb_lines = 0;
441
442   ifstream file(input_filename);
443
444   if(file.fail()) {
445     cerr << "Can not open " << input_filename << endl;
446     return 1;
447   }
448
449   while(nb_lines < nb_lines_max && !file.eof()) {
450     file.getline(buffer, buffer_size);
451     if(strcmp(buffer, "") != 0) {
452       char *s = buffer;
453       if(zsh_history && *s == ':') {
454         while(*s && *s != ';') s++;
455         if(*s == ';') s++;
456       }
457
458       if(bash_history && (*s == ' ' || (*s >= '0' && *s <= '9'))) {
459         while(*s == ' ' || (*s >= '0' && *s <= '9')) s++;
460       }
461
462       /*
463
464       // This is supposed to remove any duplicates, not only
465       // successive ones. However, it is O(N^2), we should use
466       // hash-codes
467
468       int keep = 1;
469
470       if(remove_duplicates) {
471         for(int k = 0; keep && k < nb_lines; k++) {
472           keep &= strcmp(lines[k], s);
473         }
474       }
475
476       if(keep) {
477         lines[nb_lines] = new char[strlen(s) + 1];
478         strcpy(lines[nb_lines], s);
479         nb_lines++;
480       }
481
482       */
483
484       if(!remove_duplicates || nb_lines == 0 || strcmp(lines[nb_lines - 1], s)) {
485         lines[nb_lines] = new char[strlen(s) + 1];
486         strcpy(lines[nb_lines], s);
487         nb_lines++;
488       }
489     }
490   }
491
492   if(inverse_order) {
493     for(int i = 0; i < nb_lines/2; i++) {
494       char *s = lines[nb_lines - 1 - i];
495       lines[nb_lines - 1 - i] = lines[i];
496       lines[i] = s;
497     }
498   }
499
500   char patterns[buffer_size];
501   patterns[0] = '\0';
502   int patterns_point;
503   patterns_point = 0;
504
505   initscr();
506
507   if(with_colors) {
508     if(has_colors()) {
509       start_color();
510       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
511          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
512          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
513          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
514         echo();
515         curs_set(1);
516         endwin();
517         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
518         exit(1);
519       }
520       init_pair(1, color_fg_modeline, color_bg_modeline);
521       init_pair(2, color_fg_highlight, color_bg_highlight);
522     } else {
523       with_colors = 0;
524     }
525   }
526
527   noecho();
528   curs_set(0); // Hide the cursor
529   keypad(stdscr, TRUE); // So that the arrow keys work
530
531   int key;
532   int current_line = 0, temporary_line = 0;
533
534   update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns);
535
536   do {
537
538     key = getch();
539
540     int motion = 0;
541
542     if(key >= ' ' && key <= '~') {
543       patterns[patterns_point++] = key;
544       patterns[patterns_point] = '\0';
545     }
546
547     else if(key == KEY_BACKSPACE || key == '\b' ||
548             key == KEY_DC || key == '\ 4') {
549       if(patterns_point > 0) {
550         patterns_point--;
551         patterns[patterns_point] = '\0';
552       }
553     }
554
555     else if(key == KEY_HOME) {
556       current_line = 0;
557     }
558
559     else if(key == KEY_END) {
560       current_line = nb_lines - 1;
561     }
562
563     else if(key == KEY_NPAGE) {
564       motion = 10;
565     }
566
567     else if(key == KEY_PPAGE) {
568       motion = -10;
569     }
570
571     else if(key == KEY_UP || key == '\10') {
572       motion = -1;
573     }
574
575     else if(key == KEY_DOWN || key == '\ e') {
576       motion = 1;
577     }
578
579     update_screen(&current_line, &temporary_line, motion,
580                   nb_lines, lines, patterns);
581
582   } while(key != '\n' && key != KEY_ENTER && key != '\a');
583
584   echo();
585   curs_set(1);
586   endwin();
587
588   if((key == KEY_ENTER || key == '\n')) {
589
590     if(output_to_vt_buffer) {
591       if(temporary_line >= 0 && temporary_line < nb_lines) {
592         inject_into_tty_buffer(lines[temporary_line]);
593       }
594     }
595
596     if(output_filename[0]) {
597       ofstream out(output_filename);
598       if(out.fail()) {
599         cerr << "Can not open " << output_filename << " for writing." << endl;
600         exit(1);
601       } else {
602         if(temporary_line >= 0 && temporary_line < nb_lines) {
603           out << lines[temporary_line] << endl;
604         } else {
605           out << endl;
606         }
607       }
608       out.flush();
609     }
610
611   }
612
613   for(int l = 0; l < nb_lines; l++) {
614     delete[] lines[l];
615   }
616   delete[] lines;
617
618   exit(0);
619 }