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