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