Merge branch 'master' of ssh://fleuret@login.idiap.ch/homes/fleuret/public/git/selector
[selector.git] / selector.cc
1
2 /*
3  *  selector is a simple command line utility for selection of strings
4  *  with a 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 // selector -q -b -i -d -v -w -l ${HISTSIZE} <(history)
27
28 #include <fstream>
29 #include <iostream>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <ncurses.h>
36 #include <fcntl.h>
37 #include <sys/ioctl.h>
38 #include <termios.h>
39 #include <regex.h>
40
41 using namespace std;
42
43 #define VERSION "1.0"
44
45 const int buffer_size = 4096;
46
47 // Yeah, global variables!
48
49 int nb_lines_max = 1000;
50 char pattern_separator = ';';
51 char label_separator = '\0';
52 int output_to_vt_buffer = 0;
53 int add_control_qs = 0;
54 int with_colors = 1;
55 int zsh_history = 0;
56 int bash_history = 0;
57 int inverse_order = 0;
58 int remove_duplicates = 0;
59 int use_regexp = 0;
60 int case_sensitive = 0;
61 char *title = 0;
62 int error_flash = 0;
63
64 int attr_modeline, attr_focus_line, attr_error;
65
66 //////////////////////////////////////////////////////////////////////
67
68 void inject_into_tty_buffer(char *string) {
69   struct termios oldtio, newtio;
70   tcgetattr(STDIN_FILENO, &oldtio);
71   memset(&newtio, 0, sizeof(newtio));
72   // Set input mode (non-canonical, *no echo*,...)
73   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
74   const char control_q = '\021';
75   // Put the selected string in the tty input buffer
76   for(const char *k = string; *k; k++) {
77     if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
78       // Add ^Q to quote control characters
79       ioctl(STDIN_FILENO, TIOCSTI, &control_q);
80     }
81     ioctl(STDIN_FILENO, TIOCSTI, k);
82   }
83   // Restore the old settings
84   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
85 }
86
87 //////////////////////////////////////////////////////////////////////
88
89 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
90   if(n_opt + n >= argc) {
91     cerr << "Missing argument for " << argv[n_opt] << "."
92          << " "
93          << "Expecting " << help << "."
94          << endl;
95     exit(1);
96   }
97 }
98
99 int string_to_positive_integer(char *string) {
100   int error = 0;
101   int result = 0;
102
103   if(*string) {
104     for(char *s = string; *s; s++) {
105       if(*s >= '0' && *s <= '9') {
106         result = result * 10 + int(*s - '0');
107       } else error = 1;
108     }
109   } else error = 1;
110
111   if(error) {
112     cerr << "Value `" << string << "' is not a positive integer." << endl;
113     exit(1);
114   }
115
116   return result;
117 }
118
119 void error_feedback() {
120   if(error_flash) {
121     flash();
122   } else {
123     beep();
124   }
125 }
126
127 //////////////////////////////////////////////////////////////////////
128 // A quick and dirty hash table
129
130 // The table itself stores indexes of the strings taken in a char
131 // **table. When a string is added, if it was already in the table,
132 // the new index replaces the previous one.
133
134 int *new_hash_table(int hash_table_size) {
135   int *result;
136   result = new int[hash_table_size];
137   for(int k = 0; k < hash_table_size; k++) {
138     result[k] = -1;
139   }
140   return result;
141 }
142
143 // Adds new_string in the table, associated to new_index. If this
144 // string was not already in the table, returns -1. Otherwise, returns
145 // the previous index it had.
146
147 int test_and_add(char *new_string, int new_index,
148                  char **strings,
149                  int *hash_table, int hash_table_size) {
150
151   unsigned int code = 0;
152
153   // This is my recipe. I checked, it seems to work (as long as
154   // hash_table_size is not a multiple of 387433 that should be okay)
155
156   for(int k = 0; new_string[k]; k++) {
157     code = code * 387433 + (unsigned int) (new_string[k]);
158   }
159
160   code = code % hash_table_size;
161
162   while(hash_table[code] >= 0) {
163     // There is a string with that code
164     if(strcmp(new_string, strings[hash_table[code]]) == 0) {
165       // It is the same string, we keep a copy of the stored index
166       int result = hash_table[code];
167       // Put the new one
168       hash_table[code] = new_index;
169       // And return the previous one
170       return result;
171     }
172     // This collision was not the same string, let's move to the next
173     // in the table
174     code = (code + 1) % hash_table_size;
175   }
176
177   // This string was not already in there, store the index in the
178   // table and return -1
179   hash_table[code] = new_index;
180   return -1;
181 }
182
183 //////////////////////////////////////////////////////////////////////
184 // A matcher matches either with a collection of substrings, or with a
185 // regexp
186
187 struct matcher_t {
188   regex_t preg;
189   int regexp_error;
190   int nb_patterns;
191   int case_sensitive;
192   char *splitted_patterns, **patterns;
193 };
194
195 int match(char *string, matcher_t *matcher) {
196   if(matcher->nb_patterns >= 0) {
197     if(matcher->case_sensitive) {
198       for(int n = 0; n < matcher->nb_patterns; n++) {
199         if(strstr(string, matcher->patterns[n]) == 0) return 0;
200       }
201     } else {
202       for(int n = 0; n < matcher->nb_patterns; n++) {
203         if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
204       }
205     }
206     return 1;
207   } else {
208     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
209   }
210 }
211
212 void free_matcher(matcher_t *matcher) {
213   if(matcher->nb_patterns < 0) {
214     if(!matcher->regexp_error) regfree(&matcher->preg);
215   } else {
216     delete[] matcher->splitted_patterns;
217     delete[] matcher->patterns;
218   }
219 }
220
221 void initialize_matcher(int use_regexp, int case_sensitive,
222                         matcher_t *matcher, const char *pattern) {
223
224   if(use_regexp) {
225     matcher->nb_patterns = -1;
226     matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
227   } else {
228     matcher->regexp_error = 0;
229     matcher->nb_patterns = 1;
230     matcher->case_sensitive = case_sensitive;
231
232     for(const char *s = pattern; *s; s++) {
233       if(*s == pattern_separator) {
234         matcher->nb_patterns++;
235       }
236     }
237
238     matcher->splitted_patterns = new char[strlen(pattern) + 1];
239     matcher->patterns = new char*[matcher->nb_patterns];
240
241     strcpy(matcher->splitted_patterns, pattern);
242
243     int n = 0;
244     char *last_pattern_start = matcher->splitted_patterns;
245     for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
246       if(*s == pattern_separator || *s == '\0') {
247         *s = '\0';
248         matcher->patterns[n++] = last_pattern_start;
249         last_pattern_start = s + 1;
250       }
251     }
252   }
253 }
254
255 //////////////////////////////////////////////////////////////////////
256 // Buffer edition
257
258 void delete_char(char *buffer, int *position) {
259   if(buffer[*position]) {
260     int c = *position;
261     while(c < buffer_size && buffer[c]) {
262       buffer[c] = buffer[c+1];
263       c++;
264     }
265   } else error_feedback();
266 }
267
268 void backspace_char(char *buffer, int *position) {
269   if(*position > 0) {
270     if(buffer[*position]) {
271       int c = *position - 1;
272       while(buffer[c]) {
273         buffer[c] = buffer[c+1];
274         c++;
275       }
276     } else {
277       buffer[*position - 1] = '\0';
278     }
279
280     (*position)--;
281   } else error_feedback();
282 }
283
284 void insert_char(char *buffer, int *position, char character) {
285   if(strlen(buffer) < buffer_size - 1) {
286     int c = *position;
287     char t = buffer[c], u;
288     while(t) {
289       c++;
290       u = buffer[c];
291       buffer[c] = t;
292       t = u;
293     }
294     c++;
295     buffer[c] = '\0';
296     buffer[(*position)++] = character;
297   } else error_feedback();
298 }
299
300 void kill_before_cursor(char *buffer, int *position) {
301   int s = 0;
302   while(buffer[*position + s]) {
303     buffer[s] = buffer[*position + s];
304     s++;
305   }
306   buffer[s] = '\0';
307   *position = 0;
308 }
309
310 void kill_after_cursor(char *buffer, int *position) {
311   buffer[*position] = '\0';
312 }
313
314 //////////////////////////////////////////////////////////////////////
315
316 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
317   int line = current_line - 1;
318   while(line >= 0 && !match(lines[line], matcher)) line--;
319   return line;
320 }
321
322 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
323   int line = current_line + 1;
324   while(line < nb_lines && !match(lines[line], matcher)) line++;
325
326   if(line < nb_lines)
327     return line;
328   else
329     return -1;
330 }
331
332 //////////////////////////////////////////////////////////////////////
333
334 // The value passed to this routine in current_focus_line is the index
335 // of the line we should have highlited if there was no motion and if
336 // it matched the matcher. So, the line actually highlighted is the
337 // first one matching the matcher in that order: (1)
338 // current_focus_line after motion, (2) the first with a greater
339 // index, (3) the first with a lesser index.
340
341 // The index of the line actually shown highlighted is written in
342 // displayed_focus_line (it can be -1)
343
344 // If there is a motion and a line is actually shown highlighted, its
345 // value is written in current_focus_line.
346
347 void update_screen(int *current_focus_line, int *displayed_focus_line,
348                    int motion,
349                    int nb_lines, char **lines,
350                    int cursor_position,
351                    char *pattern) {
352
353   char buffer[buffer_size];
354   matcher_t matcher;
355
356   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
357
358   int console_width = getmaxx(stdscr);
359   int console_height = getmaxy(stdscr);
360
361   // First, we find a visible line.
362
363   int nb_printed_lines = 0;
364
365   use_default_colors();
366
367   addstr("\n");
368
369   if(matcher.regexp_error) {
370     attron(attr_error);
371     addnstr("Regexp syntax error", console_width);
372     attroff(attr_error);
373   } else if(nb_lines > 0) {
374     int new_focus_line;
375     if(match(lines[*current_focus_line], &matcher)) {
376       new_focus_line = *current_focus_line;
377     } else {
378       new_focus_line = next_visible(*current_focus_line, nb_lines, lines, &matcher);
379       if(new_focus_line < 0) {
380         new_focus_line = previous_visible(*current_focus_line, nb_lines, lines, &matcher);
381       }
382     }
383
384     // If we found a visible line and we should move, let's move
385
386     if(new_focus_line >= 0 && motion != 0) {
387       int l = new_focus_line;
388       if(motion > 0) {
389         // We want to go down, let's find the first visible line below
390         for(int m = 0; l >= 0 && m < motion; m++) {
391           l = next_visible(l, nb_lines, lines, &matcher);
392           if(l >= 0) {
393             new_focus_line = l;
394           }
395         }
396       } else {
397         // We want to go up, let's find the first visible line above
398         for(int m = 0; l >= 0 && m < -motion; m++) {
399           l = previous_visible(l, nb_lines, lines, &matcher);
400           if(l >= 0) {
401             new_focus_line = l;
402           }
403         }
404       }
405     }
406
407     // Here new_focus_line is either a line number matching the pattern, or -1
408
409     if(new_focus_line >= 0) {
410
411       int first_line = new_focus_line, last_line = new_focus_line, nb_match = 1;
412
413       // We find the first and last line to show, so that the total of
414       // visible lines between them (them included) is console_height-1
415
416       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
417
418         if(first_line > 0) {
419           first_line--;
420           while(first_line > 0 && !match(lines[first_line], &matcher)) {
421             first_line--;
422           }
423           if(match(lines[first_line], &matcher)) {
424             nb_match++;
425           }
426         }
427
428         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
429           last_line++;
430           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
431             last_line++;
432           }
433
434           if(match(lines[last_line], &matcher)) {
435             nb_match++;
436           }
437         }
438       }
439
440       // Now we display them
441
442       for(int l = first_line; l <= last_line; l++) {
443         if(match(lines[l], &matcher)) {
444           int k = 0;
445
446           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
447             buffer[k] = lines[l][k];
448             k++;
449           }
450
451           // We fill the rest of the line with blanks if this is the
452           // highlighted line
453
454           if(l == new_focus_line) {
455             while(k < console_width) {
456               buffer[k++] = ' ';
457             }
458           }
459
460           buffer[k++] = '\n';
461           buffer[k++] = '\0';
462
463           clrtoeol();
464
465           // Highlight the highlighted line ...
466
467           if(l == new_focus_line) {
468             attron(attr_focus_line);
469             addnstr(buffer, console_width);
470             attroff(attr_focus_line);
471           } else {
472             addnstr(buffer, console_width);
473           }
474
475           nb_printed_lines++;
476         }
477       }
478
479       // If we are on a focused line and we moved, this become the new
480       // focus line
481
482       if(motion != 0) {
483         *current_focus_line = new_focus_line;
484       }
485     }
486
487     *displayed_focus_line = new_focus_line;
488
489     if(nb_printed_lines == 0) {
490       attron(attr_error);
491       addnstr("No selection", console_width);
492       attroff(attr_error);
493     }
494   } else {
495     attron(attr_error);
496     addnstr("Empty choice", console_width);
497     attroff(attr_error);
498   }
499
500   clrtobot();
501
502   // Draw the modeline
503
504   move(0, 0);
505
506   attron(attr_modeline);
507
508   for(int k = 0; k < console_width; k++) buffer[k] = ' ';
509   buffer[console_width] = '\0';
510   addnstr(buffer, console_width);
511
512   move(0, 0);
513
514   // There must be a more elegant way of moving the cursor at a
515   // location met during display
516
517   int cursor_x = 0;
518
519   if(title) {
520     addstr(title);
521     addstr(" ");
522     cursor_x += strlen(title) + 1;
523   }
524
525   sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
526   addstr(buffer);
527   cursor_x += strlen(buffer);
528
529   addnstr(pattern, cursor_position);
530   cursor_x += cursor_position;
531
532   if(pattern[cursor_position]) {
533     addstr(pattern + cursor_position);
534   } else {
535     addstr(" ");
536   }
537
538   if(use_regexp || case_sensitive) {
539     addstr(" [");
540     if(use_regexp) {
541       addstr("regexp");
542     }
543
544     if(case_sensitive) {
545       if(use_regexp) {
546         addstr(",");
547       }
548       addstr("case");
549     }
550     addstr("]");
551   }
552
553   move(0, cursor_x);
554
555   attroff(attr_modeline);
556
557   // We are done
558
559   refresh();
560   free_matcher(&matcher);
561 }
562
563 //////////////////////////////////////////////////////////////////////
564
565 void read_file(const char *input_filename,
566                int nb_lines_max, int *nb_lines, char **lines,
567                int hash_table_size, int *hash_table) {
568
569   char raw_line[buffer_size];;
570
571   ifstream file(input_filename);
572
573   if(file.fail()) {
574     cerr << "Can not open " << input_filename << endl;
575     exit(1);
576   }
577
578   while(*nb_lines < nb_lines_max && !file.eof()) {
579
580     file.getline(raw_line, buffer_size);
581
582     if(raw_line[0]) {
583
584       if(file.fail()) {
585         cerr << "Line too long:" << endl;
586         cerr << raw_line << endl;
587         exit(1);
588       }
589
590       char *t;
591
592       t = raw_line;
593
594       // Remove the zsh history prefix
595
596       if(zsh_history && *t == ':') {
597         while(*t && *t != ';') t++;
598         if(*t == ';') t++;
599       }
600
601       // Remove the bash history prefix
602
603       if(bash_history) {
604         while(*t == ' ') t++;
605         while(*t >= '0' && *t <= '9') t++;
606         while(*t == ' ') t++;
607       }
608
609       // Check for duplicates with the hash table and insert the line
610       // in the list if necessary
611
612       int dup;
613
614       if(hash_table) {
615         dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
616       } else {
617         dup = -1;
618       }
619
620       if(dup < 0) {
621         lines[*nb_lines] = new char[strlen(t) + 1];
622         strcpy(lines[*nb_lines], t);
623       } else {
624         // The string was already in there, so we do not allocate a
625         // new string but use the pointer to the first occurence of it
626         lines[*nb_lines] = lines[dup];
627         lines[dup] = 0;
628       }
629
630       (*nb_lines)++;
631     }
632   }
633 }
634
635 //////////////////////////////////////////////////////////////////////
636
637 int main(int argc, char **argv) {
638
639   if(!ttyname(STDIN_FILENO)) {
640     cerr << "The standard input is not a tty." << endl;
641     exit(1);
642   }
643
644   int color_fg_modeline, color_bg_modeline;
645   int color_fg_highlight, color_bg_highlight;
646
647   color_fg_modeline  = COLOR_WHITE;
648   color_bg_modeline  = COLOR_BLACK;
649   color_fg_highlight = COLOR_BLACK;
650   color_bg_highlight = COLOR_YELLOW;
651
652   setlocale(LC_ALL, "");
653
654   char input_filename[buffer_size], output_filename[buffer_size];
655
656   strcpy(input_filename, "");
657   strcpy(output_filename, "");
658
659   int i = 1;
660   int error = 0, show_help = 0;
661   int rest_are_files = 0;
662
663   while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
664
665     if(strcmp(argv[i], "-o") == 0) {
666       check_opt(argc, argv, i, 1, "<output filename>");
667       strncpy(output_filename, argv[i+1], buffer_size);
668       i += 2;
669     }
670
671     else if(strcmp(argv[i], "-s") == 0) {
672       check_opt(argc, argv, i, 1, "<pattern separator>");
673       pattern_separator = argv[i+1][0];
674       i += 2;
675     }
676
677     else if(strcmp(argv[i], "-x") == 0) {
678       check_opt(argc, argv, i, 1, "<label separator>");
679       label_separator = argv[i+1][0];
680       i += 2;
681     }
682
683     else if(strcmp(argv[i], "-v") == 0) {
684       output_to_vt_buffer = 1;
685       i++;
686     }
687
688     else if(strcmp(argv[i], "-w") == 0) {
689       add_control_qs = 1;
690       i++;
691     }
692
693     else if(strcmp(argv[i], "-m") == 0) {
694       with_colors = 0;
695       i++;
696     }
697
698     else if(strcmp(argv[i], "-q") == 0) {
699       error_flash = 1;
700       i++;
701     }
702
703     else if(strcmp(argv[i], "-f") == 0) {
704       check_opt(argc, argv, i, 1, "<input filename>");
705       strncpy(input_filename, argv[i+1], buffer_size);
706       i += 2;
707     }
708
709     else if(strcmp(argv[i], "-i") == 0) {
710       inverse_order = 1;
711       i++;
712     }
713
714     else if(strcmp(argv[i], "-b") == 0) {
715       bash_history = 1;
716       i++;
717     }
718
719     else if(strcmp(argv[i], "-z") == 0) {
720       zsh_history = 1;
721       i++;
722     }
723
724     else if(strcmp(argv[i], "-d") == 0) {
725       remove_duplicates = 1;
726       i++;
727     }
728
729     else if(strcmp(argv[i], "-e") == 0) {
730       use_regexp = 1;
731       i++;
732     }
733
734     else if(strcmp(argv[i], "-a") == 0) {
735       case_sensitive = 1;
736       i++;
737     }
738
739     else if(strcmp(argv[i], "-t") == 0) {
740       check_opt(argc, argv, i, 1, "<title>");
741       delete[] title;
742       title = new char[strlen(argv[i+1]) + 1];
743       strcpy(title, argv[i+1]);
744       i += 2;
745     }
746
747     else if(strcmp(argv[i], "-l") == 0) {
748       check_opt(argc, argv, i, 1, "<maximum number of lines>");
749       nb_lines_max = string_to_positive_integer(argv[i+1]);
750       i += 2;
751     }
752
753     else if(strcmp(argv[i], "-c") == 0) {
754       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
755       color_fg_modeline = string_to_positive_integer(argv[i + 1]);
756       color_bg_modeline = string_to_positive_integer(argv[i + 2]);
757       color_fg_highlight = string_to_positive_integer(argv[i + 3]);
758       color_bg_highlight = string_to_positive_integer(argv[i + 4]);
759       i += 5;
760     }
761
762     else if(strcmp(argv[i], "--") == 0) {
763       rest_are_files = 1;
764       i++;
765     }
766
767     else if(strcmp(argv[i], "-h") == 0) {
768       show_help = 1;
769       i++;
770     }
771
772     else {
773       cerr << "Unknown option " << argv[i] << "." << endl;
774       error = 1;
775     }
776   }
777
778   if(show_help || error) {
779     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
780          << endl
781          << "Written by Francois Fleuret <francois@fleuret.org>."
782          << endl
783          << endl
784          << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
785          << endl
786          << " -h      show this help" << endl
787          << " -v      inject the selected line in the tty" << endl
788          << " -w      quote control characters with ^Qs when using -v" << endl
789          << " -d      remove duplicated lines" << endl
790          << " -b      remove the bash history line prefix" << endl
791          << " -z      remove the zsh history line prefix" << endl
792          << " -i      invert the order of lines" << endl
793          << " -e      start in regexp mode" << endl
794          << " -a      case sensitive" << endl
795          << " -m      monochrome mode" << endl
796          << " -q      make a flash instead of a beep on an edition error" << endl
797          << " --      all following arguments are filenames" << endl
798          << " -t <title>" << endl
799          << "         add a title in the modeline" << endl
800          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
801          << "         set the display colors" << endl
802          << " -o <output filename>" << endl
803          << "         set a file to write the selected line to" << endl
804          << " -s <pattern separator>" << endl
805          << "         set the symbol to separate substrings in the pattern" << endl
806          << " -x <label separator>" << endl
807          << "         set the symbol to terminate the label" << endl
808          << " -l <max number of lines>" << endl
809          << "         set the maximum number of lines to take into account" << endl
810          << endl;
811
812     exit(error);
813   }
814
815   char **lines = new char *[nb_lines_max];
816
817   int nb_lines = 0;
818   int hash_table_size = nb_lines_max * 10;
819   int *hash_table = 0;
820
821   if(remove_duplicates) {
822     hash_table = new_hash_table(hash_table_size);
823   }
824
825   if(input_filename[0]) {
826     read_file(input_filename,
827               nb_lines_max, &nb_lines, lines,
828               hash_table_size, hash_table);
829   }
830
831   while(i < argc) {
832     read_file(argv[i],
833               nb_lines_max, &nb_lines, lines,
834               hash_table_size, hash_table);
835     i++;
836   }
837
838   delete[] hash_table;
839
840   // Now remove the null strings
841
842   int n = 0;
843   for(int k = 0; k < nb_lines; k++) {
844     if(lines[k]) {
845       lines[n++] = lines[k];
846     }
847   }
848
849   nb_lines = n;
850
851   if(inverse_order) {
852     for(int i = 0; i < nb_lines / 2; i++) {
853       char *s = lines[nb_lines - 1 - i];
854       lines[nb_lines - 1 - i] = lines[i];
855       lines[i] = s;
856     }
857   }
858
859   // Build the labels from the strings, take only the part before the
860   // label_separator and transform control characters to printable
861   // ones
862
863   char **labels = new char *[nb_lines];
864   for(int l = 0; l < nb_lines; l++) {
865     char *s, *t;
866     const char *u;
867     t = lines[l];
868     int e = 0;
869     while(*t && *t != label_separator) {
870       u = unctrl(*t++);
871       e += strlen(u);
872     }
873     labels[l] = new char[e + 1];
874     t = lines[l];
875     s = labels[l];
876     while(*t && *t != label_separator) {
877       u = unctrl(*t++);
878       while(*u) { *s++ = *u++; }
879     }
880     *s = '\0';
881   }
882
883   char pattern[buffer_size];
884   pattern[0] = '\0';
885
886   int cursor_position;
887   cursor_position = 0;
888
889   //////////////////////////////////////////////////////////////////////
890   // Here we start to display with curse
891
892   initscr();
893
894   noecho();
895
896   // So that the arrow keys work
897   keypad(stdscr, TRUE);
898
899   attr_error = A_STANDOUT;
900   attr_modeline = A_REVERSE;
901   attr_focus_line = A_STANDOUT;
902
903   if(with_colors && has_colors()) {
904
905     start_color();
906
907     if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
908        color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
909        color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
910        color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
911       echo();
912       endwin();
913       cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
914       exit(1);
915     }
916
917     init_pair(1, color_fg_modeline, color_bg_modeline);
918     attr_modeline = COLOR_PAIR(1);
919
920     init_pair(2, color_fg_highlight, color_bg_highlight);
921     attr_focus_line = COLOR_PAIR(2);
922
923     init_pair(3, COLOR_WHITE, COLOR_RED);
924     attr_error = COLOR_PAIR(3);
925
926   }
927
928   int key;
929   int current_focus_line = 0, displayed_focus_line = 0;
930
931   update_screen(&current_focus_line, &displayed_focus_line,
932                 0,
933                 nb_lines, labels, cursor_position, pattern);
934
935   do {
936
937     key = getch();
938
939     int motion = 0;
940
941     if(key >= ' ' && key <= '~') { // Insert character
942       insert_char(pattern, &cursor_position, key);
943     }
944
945     else if(key == KEY_BACKSPACE ||
946             key == '\010' || // ^H
947             key == '\177') { // ^?
948       backspace_char(pattern, &cursor_position);
949     }
950
951     else if(key == KEY_DC ||
952             key == '\004') { // ^D
953       delete_char(pattern, &cursor_position);
954     }
955
956     else if(key == KEY_HOME) {
957       current_focus_line = 0;
958     }
959
960     else if(key == KEY_END) {
961       current_focus_line = nb_lines - 1;
962     }
963
964     else if(key == KEY_NPAGE) {
965       motion = 10;
966     }
967
968     else if(key == KEY_PPAGE) {
969       motion = -10;
970     }
971
972     else if(key == KEY_DOWN ||
973             key == '\016') { // ^N
974       motion = 1;
975     }
976
977     else if(key == KEY_UP ||
978             key == '\020') { // ^P
979       motion = -1;
980     }
981
982     else if(key == KEY_LEFT ||
983             key == '\002') { // ^B
984       if(cursor_position > 0) cursor_position--;
985       else error_feedback();
986     }
987
988     else if(key == KEY_RIGHT ||
989             key == '\006') { // ^F
990       if(pattern[cursor_position]) cursor_position++;
991       else error_feedback();
992     }
993
994     else if(key == '\001') { // ^A
995       cursor_position = 0;
996     }
997
998     else if(key == '\005') { // ^E
999       cursor_position = strlen(pattern);
1000     }
1001
1002     else if(key == '\022') { // ^R
1003       use_regexp = !use_regexp;
1004     }
1005
1006     else if(key == '\011') { // ^I
1007       case_sensitive = !case_sensitive;
1008     }
1009
1010     else if(key == '\025') { // ^U
1011       kill_before_cursor(pattern, &cursor_position);
1012     }
1013
1014     else if(key == '\013') { // ^K
1015       kill_after_cursor(pattern, &cursor_position);
1016     }
1017
1018     else if(key == '\014') { // ^L
1019       // I suspect that we may sometime mess up the display
1020       clear();
1021     }
1022
1023     update_screen(&current_focus_line, &displayed_focus_line,
1024                   motion,
1025                   nb_lines, labels, cursor_position, pattern);
1026
1027   } while(key != '\007' && // ^G
1028           key != '\033' && // ^[ (escape)
1029           key != '\n' &&
1030           key != KEY_ENTER);
1031
1032   echo();
1033   endwin();
1034
1035   //////////////////////////////////////////////////////////////////////
1036   // Here we come back to standard display
1037
1038   if((key == KEY_ENTER || key == '\n')) {
1039
1040     char *t;
1041
1042     if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1043       t = lines[displayed_focus_line];
1044       if(label_separator) {
1045         while(*t && *t != label_separator) t++;
1046         if(*t) t++;
1047       }
1048     } else {
1049       t = 0;
1050     }
1051
1052     if(output_to_vt_buffer && t) {
1053       inject_into_tty_buffer(t);
1054     }
1055
1056     if(output_filename[0]) {
1057       ofstream out(output_filename);
1058       if(out.fail()) {
1059         cerr << "Can not open " << output_filename << " for writing." << endl;
1060         exit(1);
1061       } else {
1062         if(t) {
1063           out << t << endl;
1064         } else {
1065           out << endl;
1066         }
1067       }
1068       out.flush();
1069     }
1070
1071   } else {
1072     cout << "Aborted." << endl;
1073   }
1074
1075   for(int l = 0; l < nb_lines; l++) {
1076     delete[] lines[l];
1077     delete[] labels[l];
1078   }
1079
1080   delete[] labels;
1081   delete[] lines;
1082   delete[] title;
1083
1084   exit(0);
1085 }