aafaf9d63369a8bc7d12f058ed0af3df620614f4
[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, 2010, 2011, 2012 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 /*
26
27   To use it as a super-history-search for bash:
28   selector --bash <(history)
29
30 */
31
32 #define _GNU_SOURCE
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <ncurses.h>
40 #include <fcntl.h>
41 #include <sys/ioctl.h>
42 #include <termios.h>
43 #include <regex.h>
44 #include <locale.h>
45 #include <getopt.h>
46 #include <limits.h>
47
48 #define VERSION "1.1.6"
49
50 #define BUFFER_SIZE 4096
51
52 /* Yeah, global variables! */
53
54 int nb_lines_max = 1000;
55 char pattern_separator = ';';
56 char label_separator = '\0';
57 int output_to_vt_buffer = 0;
58 int add_control_qs = 0;
59 int with_colors = 1;
60 int zsh_history = 0;
61 int bash_history = 0;
62 int inverse_order = 0;
63 int remove_duplicates = 0;
64 int use_regexp = 0;
65 int case_sensitive = 0;
66 char *title = 0;
67 int error_flash = 0;
68 int upper_caps_makes_case_sensitive = 0;
69 int show_long_lines = 0;
70 int show_hits = 0;
71
72 int attr_modeline, attr_focus_line, attr_error, attr_hits;
73
74 /********************************************************************/
75
76 /* malloc with error checking.  */
77
78 void *safe_malloc(size_t n) {
79   void *p = malloc(n);
80   if(!p && n != 0) {
81     fprintf(stderr,
82             "selector: can not allocate memory: %s\n", strerror(errno));
83     exit(EXIT_FAILURE);
84   }
85   return p;
86 }
87
88 /*********************************************************************/
89
90 void inject_into_tty_buffer(char *string, int add_control_qs) {
91   struct termios oldtio, newtio;
92   const char *k;
93   const char control_q = '\021';
94   tcgetattr(STDIN_FILENO, &oldtio);
95   memset(&newtio, 0, sizeof(newtio));
96   /* Set input mode (non-canonical, *no echo*,...) */
97   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
98   /* Put the selected string in the tty input buffer */
99   for(k = string; *k; k++) {
100     if(add_control_qs && !(*k >= ' ' && *k <= '~')) {
101       /* Add ^Q to quote control characters */
102       ioctl(STDIN_FILENO, TIOCSTI, &control_q);
103     }
104     ioctl(STDIN_FILENO, TIOCSTI, k);
105   }
106   /* Restore the old settings */
107   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
108 }
109
110 /*********************************************************************/
111
112 void str_to_positive_integers(char *string, int *values, int nb) {
113   int current_value, gotone;
114   char *s;
115   int n;
116
117   n = 0;
118   current_value = 0;
119   gotone = 0;
120   s = string;
121
122   while(1) {
123     if(*s >= '0' && *s <= '9') {
124       current_value = current_value * 10 + (int) (*s - '0');
125       gotone = 1;
126     } else if(*s == ',' || *s == '\0') {
127       if(gotone) {
128         if(n < nb) {
129           values[n++] = current_value;
130           if(*s == '\0') {
131             if(n == nb) {
132               return;
133             } else {
134               fprintf(stderr,
135                       "selector: Missing value in `%s'.\n", string);
136               exit(EXIT_FAILURE);
137             }
138           }
139           current_value = 0;
140           gotone = 0;
141         } else {
142           fprintf(stderr,
143                   "selector: Too many values in `%s'.\n", string);
144           exit(EXIT_FAILURE);
145         }
146       } else {
147         fprintf(stderr,
148                 "selector: Empty value in `%s'.\n", string);
149         exit(EXIT_FAILURE);
150       }
151     } else {
152       fprintf(stderr,
153               "selector: Syntax error in `%s'.\n", string);
154       exit(EXIT_FAILURE);
155     }
156     s++;
157   }
158 }
159
160 void error_feedback() {
161   if(error_flash) {
162     flash();
163   } else {
164     beep();
165   }
166 }
167
168 void usage(FILE *out) {
169
170   fprintf(out, "Selector version %s (%s)\n", VERSION, UNAME);
171   fprintf(out, "Written by Francois Fleuret <francois@fleuret.org>.\n");
172   fprintf(out, "\n");
173   fprintf(out, "Usage: selector [options] [<filename1> [<filename2> ...]]\n");
174   fprintf(out, "\n");
175   fprintf(out, " -h, --help\n");
176   fprintf(out, "         show this help\n");
177   fprintf(out, " -v, --inject-in-tty\n");
178   fprintf(out, "         inject the selected line in the tty\n");
179   fprintf(out, " -w, --add-control-qs\n");
180   fprintf(out, "         quote control characters with ^Qs when using -v\n");
181   fprintf(out, " -d, --remove-duplicates\n");
182   fprintf(out, "         remove duplicated lines\n");
183   fprintf(out, " -b, --remove-bash-prefix\n");
184   fprintf(out, "         remove the bash history line prefix\n");
185   fprintf(out, " -z, --remove-zsh-prefix\n");
186   fprintf(out, "         remove the zsh history line prefix\n");
187   fprintf(out, " -i, --revert-order\n");
188   fprintf(out, "         invert the order of lines\n");
189   fprintf(out, " -e, --regexp\n");
190   fprintf(out, "         start in regexp mode\n");
191   fprintf(out, " -a, --case-sensitive\n");
192   fprintf(out, "         start in case sensitive mode\n");
193   fprintf(out, " -j, --show-long-lines\n");
194   fprintf(out, "         print a long-line indicator at the end of truncated lines\n");
195   fprintf(out, " -y, --show-hits\n");
196   fprintf(out, "         highlight the matching substrings\n");
197   fprintf(out, " -u, --upper-case-makes-case-sensitive\n");
198   fprintf(out, "         using an upper case character in the matching string makes\n");
199   fprintf(out, "         the matching case-sensitive\n");
200   fprintf(out, " -m, --monochrome\n");
201   fprintf(out, "         monochrome mode\n");
202   fprintf(out, " -q, --no-beep\n");
203   fprintf(out, "         make a flash instead of a beep on an edition error\n");
204   fprintf(out, " --bash\n");
205   fprintf(out, "         setting for bash history search, same as -b -i -d -v -w -l ${HISTSIZE}\n");
206   fprintf(out, " --      all following arguments are filenames\n");
207   fprintf(out, " -t <title>, --title <title>\n");
208   fprintf(out, "         add a title in the modeline\n");
209   fprintf(out, " -r <pattern>, --pattern <pattern>\n");
210   fprintf(out, "         set an initial pattern\n");
211   fprintf(out, " -c <colors>, --colors <colors>\n");
212   fprintf(out, "         set the display colors with an argument of the form\n");
213   fprintf(out, "         <fg_modeline>,<bg_modeline>,<fg_highlight>,<bg_highlight>\n");
214   fprintf(out, " -o <output filename>, --output-file <output filename>\n");
215   fprintf(out, "         set a file to write the selected line to\n");
216   fprintf(out, " -s <pattern separator>, --pattern-separator <pattern separator>\n");
217   fprintf(out, "         set the symbol to separate substrings in the pattern\n");
218   fprintf(out, " -x <label separator>, --label-separator <label separator>\n");
219   fprintf(out, "         set the symbol to terminate the label\n");
220   fprintf(out, " -l <max number of lines>, --number-of-lines <max number of lines>\n");
221   fprintf(out, "         set the maximum number of lines to take into account\n");
222   fprintf(out, "\n");
223 }
224
225 /*********************************************************************/
226
227 /* A quick and dirty hash table */
228
229 #define MAGIC_HASH_MULTIPLIER 387433
230
231 /* The table itself stores indexes of the strings taken in a char**
232    table. When a string is added, if it was already in the table, the
233    new index replaces the previous one.  */
234
235 struct hash_table_t {
236   int size;
237   int *entries;
238 };
239
240 struct hash_table_t *new_hash_table(int size) {
241   int k;
242   struct hash_table_t *hash_table;
243
244   hash_table = safe_malloc(sizeof(struct hash_table_t));
245
246   hash_table->size = size;
247   hash_table->entries = safe_malloc(hash_table->size * sizeof(int));
248
249   for(k = 0; k < hash_table->size; k++) {
250     hash_table->entries[k] = -1;
251   }
252
253   return hash_table;
254 }
255
256 void free_hash_table(struct hash_table_t *hash_table) {
257   free(hash_table->entries);
258   free(hash_table);
259 }
260
261 /* Adds new_string in the table, associated to new_index. If this
262    string was not already in the table, returns -1. Otherwise, returns
263    the previous index it had. */
264
265 int add_and_get_previous_index(struct hash_table_t *hash_table,
266                                const char *new_string, int new_index,
267                                char **strings) {
268
269   unsigned int code = 0, start;
270   int k;
271
272   /* This is my recipe. I checked, it seems to work (as long as
273      hash_table->size is not a multiple of MAGIC_HASH_MULTIPLIER that
274      should be okay) */
275
276   for(k = 0; new_string[k]; k++) {
277     code = code * MAGIC_HASH_MULTIPLIER + (unsigned int) (new_string[k]);
278   }
279
280   code = code % hash_table->size;
281   start = code;
282
283   while(hash_table->entries[code] >= 0) {
284     /* There is a string with that code */
285     if(strcmp(new_string, strings[hash_table->entries[code]]) == 0) {
286       /* It is the same string, we keep a copy of the stored index */
287       int result = hash_table->entries[code];
288       /* Put the new one */
289       hash_table->entries[code] = new_index;
290       /* And return the previous one */
291       return result;
292     }
293     /* This collision was not the same string, let's move to the next
294        in the table */
295     code = (code + 1) % hash_table->size;
296     /* We came back to our original code, which means that the table
297        is full */
298     if(code == start) {
299       fprintf(stderr,
300               "Full hash table (that should not happen)\n");
301       exit(EXIT_FAILURE);
302    }
303   }
304
305   /* This string was not already in there, store the index in the
306      table and return -1 */
307
308   hash_table->entries[code] = new_index;
309   return -1;
310 }
311
312 /*********************************************************************
313  A matcher matches either with a collection of substrings, or with a
314  regexp */
315
316 struct matcher {
317   regex_t preg;
318   int regexp_error;
319   int nb_patterns;
320   int case_sensitive;
321   char *splitted_patterns, **patterns;
322 };
323
324 /* Routine to add an interval to a sorted list of intervals
325    extremities. Returns the resulting number of extremities.
326
327    This routine is an effing nightmare */
328
329 int add_interval(int n, int *switches, int start, int end) {
330   int f, g, k;
331
332   if(start == end) { return n; }
333
334   f = 0;
335   while(f < n && switches[f] <= start) { f++; }
336   g = f;
337   while(g < n && switches[g] <= end) { g++; }
338
339   if(f == n) {
340     /* switches[n-1]   start  end  */
341     /* XXXXXXXXXXXX|               */
342     switches[f] = start;
343     switches[f+1] = end;
344     return n + 2;
345   }
346
347   if(f % 2) {
348
349     if(g % 2) {
350       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
351       /* |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|   ...   |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| */
352       for(k = f; k < n; k++) { switches[k] = switches[k + (g - f)]; }
353       return n - (g - f);
354     } else {
355       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
356       /* |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|   ...   XXXXXXXXXXXX|          |XXXXXXXXXX */
357       switches[g - 1] = end;
358       for(k = f; k < n; k++) { switches[k] = switches[k + ((g - 1) - f)]; }
359       return n - ((g - 1) - f);
360     }
361
362   } else {
363
364     if(f == g) {
365       /* switches[f-1]   start  end   switches[f]  */
366       /* XXXXXXXXXXXX|                |XXXXXXXXXX  */
367       for(k = n - 1; k >= f; k--) {
368         switches[k + 2] = switches[k];
369       }
370       switches[f] = start;
371       switches[f + 1] = end;
372       return n + 2;
373     }
374
375     if(g % 2) {
376       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
377       /* XXXXXXXXXXXX|           |XXXXXXXXXX   ...   |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| */
378       switches[f] = start;
379       for(k = f + 1; k < n; k++) { switches[k] = switches[k + (g - (f + 1))]; }
380       return n - (g - (f + 1));
381     } else {
382       /* switches[f-1]   start   switches[f]         switches[g-1]   end    switches[g] */
383       /* XXXXXXXXXXXX|           |XXXXXXXXXX   ...   XXXXXXXXXXXX|          |XXXXXXXXXX */
384       switches[f] = start;
385       switches[g - 1] = end;
386       for(k = f + 1; k < n; k++) { switches[k] = switches[k + ((g - 1) - (f + 1))]; }
387       return n - ((g - 1) - (f + 1));
388     }
389   }
390 }
391
392 int match(struct matcher *matcher, char *string, int *nb_switches, int *switches) {
393   int n;
394   char *where;
395   regmatch_t matches;
396
397   if(nb_switches) { *nb_switches = 0; }
398
399   if(matcher->nb_patterns >= 0) {
400     if(matcher->case_sensitive) {
401       for(n = 0; n < matcher->nb_patterns; n++) {
402         if((where = strstr(string, matcher->patterns[n])) == 0) return 0;
403         if(switches) {
404           *nb_switches = add_interval(*nb_switches, switches,
405                                       (int) (where - string),
406                                       (int) (where - string) + strlen(matcher->patterns[n]));
407         }
408       }
409     } else {
410       for(n = 0; n < matcher->nb_patterns; n++) {
411         if((where = strcasestr(string, matcher->patterns[n])) == 0) return 0;
412         if(switches) {
413           *nb_switches = add_interval(*nb_switches, switches,
414                                       (int) (where - string),
415                                       (int) (where - string) + strlen(matcher->patterns[n]));
416         }
417       }
418     }
419     return 1;
420   } else {
421     if(switches) {
422       if(regexec(&matcher->preg, string, 1, &matches, 0) == 0) {
423         *nb_switches = 2;
424         switches[0] = matches.rm_so;
425         switches[1] = matches.rm_eo;
426         return 1;
427       } else {
428         return 0;
429       }
430     } else {
431       return regexec(&matcher->preg, string, 0, 0, 0) == 0;
432     }
433   }
434 }
435
436 void free_matcher(struct matcher *matcher) {
437   if(matcher->nb_patterns < 0) {
438     if(!matcher->regexp_error) regfree(&matcher->preg);
439   } else {
440     free(matcher->splitted_patterns);
441     free(matcher->patterns);
442   }
443 }
444
445 void initialize_matcher(struct matcher *matcher,
446                         int use_regexp, int case_sensitive,
447                         const char *pattern) {
448   const char *s;
449   char *t, *last_pattern_start;
450   int n;
451
452   if(use_regexp) {
453     matcher->case_sensitive = case_sensitive;
454     matcher->nb_patterns = -1;
455     matcher->regexp_error = regcomp(&matcher->preg, pattern,
456                                     case_sensitive ? 0 : REG_ICASE);
457   } else {
458     matcher->regexp_error = 0;
459     matcher->nb_patterns = 1;
460
461     if(upper_caps_makes_case_sensitive) {
462       for(s = pattern; *s && !case_sensitive; s++) {
463         case_sensitive = (*s >= 'A' && *s <= 'Z');
464       }
465     }
466
467     matcher->case_sensitive = case_sensitive;
468
469     for(s = pattern; *s; s++) {
470       if(*s == pattern_separator) {
471         matcher->nb_patterns++;
472       }
473     }
474
475     matcher->splitted_patterns =
476       safe_malloc((strlen(pattern) + 1) * sizeof(char));
477
478     matcher->patterns =
479       safe_malloc(matcher->nb_patterns * sizeof(char *));
480
481     strcpy(matcher->splitted_patterns, pattern);
482
483     n = 0;
484     last_pattern_start = matcher->splitted_patterns;
485     for(t = matcher->splitted_patterns; n < matcher->nb_patterns; t++) {
486       if(*t == pattern_separator || *t == '\0') {
487         *t = '\0';
488         matcher->patterns[n++] = last_pattern_start;
489         last_pattern_start = t + 1;
490       }
491     }
492   }
493 }
494
495 /*********************************************************************
496  Buffer edition */
497
498 void delete_char(char *buffer, int *position) {
499   if(buffer[*position]) {
500     int c = *position;
501     while(c < BUFFER_SIZE && buffer[c]) {
502       buffer[c] = buffer[c+1];
503       c++;
504     }
505   } else error_feedback();
506 }
507
508 void backspace_char(char *buffer, int *position) {
509   if(*position > 0) {
510     if(buffer[*position]) {
511       int c = *position - 1;
512       while(buffer[c]) {
513         buffer[c] = buffer[c+1];
514         c++;
515       }
516     } else {
517       buffer[*position - 1] = '\0';
518     }
519
520     (*position)--;
521   } else error_feedback();
522 }
523
524 void insert_char(char *buffer, int *position, char character) {
525   if(strlen(buffer) < BUFFER_SIZE - 1) {
526     int c = *position;
527     char t = buffer[c], u;
528     while(t) {
529       c++;
530       u = buffer[c];
531       buffer[c] = t;
532       t = u;
533     }
534     c++;
535     buffer[c] = '\0';
536     buffer[(*position)++] = character;
537   } else error_feedback();
538 }
539
540 void kill_before_cursor(char *buffer, int *position) {
541   int s = 0;
542   while(buffer[*position + s]) {
543     buffer[s] = buffer[*position + s];
544     s++;
545   }
546   buffer[s] = '\0';
547   *position = 0;
548 }
549
550 void kill_after_cursor(char *buffer, int *position) {
551   buffer[*position] = '\0';
552 }
553
554 /*********************************************************************/
555
556 int previous_visible(int current_line, char **lines, struct matcher *matcher) {
557   int line = current_line - 1;
558   while(line >= 0 && !match(matcher, lines[line], 0, 0)) line--;
559   return line;
560 }
561
562 int next_visible(int current_line, int nb_lines, char **lines,
563                  struct matcher *matcher) {
564   int line = current_line + 1;
565   while(line < nb_lines && !match(matcher, lines[line], 0, 0)) line++;
566
567   if(line < nb_lines)
568     return line;
569   else
570     return -1;
571 }
572
573 /*********************************************************************/
574
575 void print_string_with_switches(char *buffer, int line_width,
576                                 int nb_patterns, int *switches) {
577   int w, current = 0, next;
578   if(switches) {
579     for(w = 0; w < nb_patterns && switches[2 * w] < line_width; w++) {
580       if(switches[2 * w] < switches[2 * w + 1]) {
581         next = switches[2 * w];
582         if(next > line_width) { next = line_width; }
583         if(next > current) { addnstr(buffer + current,  next - current); }
584         attron(attr_hits);
585         current = next;
586         next = switches[2 * w + 1];
587         if(next > line_width) { next = line_width; }
588         if(next > current) { addnstr(buffer + current,  next - current); }
589         attroff(attr_hits);
590         current = next;
591       }
592     }
593     if(current < line_width) {
594       addnstr(buffer + current, line_width - current);
595     }
596   } else {
597     addnstr(buffer, line_width);
598   }
599 }
600
601 /* The line highlighted is the first one matching the matcher in that
602    order: (1) current_focus_line after motion, if it does not match,
603    then (2) the first with a greater index, if none matches, then (3)
604    the first with a lesser index.
605
606    The index of the line actually shown highlighted is written in
607    displayed_focus_line (it can be -1 if no line at all matches the
608    matcher)
609
610    If there is a motion and a line is actually shown highlighted, its
611    value is written in current_focus_line. */
612
613 void update_screen(int *current_focus_line, int *displayed_focus_line,
614                    int motion,
615                    int nb_lines, char **lines,
616                    int cursor_position,
617                    char *pattern) {
618   int *switches;
619   char buffer[BUFFER_SIZE];
620   struct matcher matcher;
621   int k, l, m;
622   int console_width, console_height;
623   int nb_printed_lines = 0;
624   int cursor_x;
625   int nb_switches;
626
627   initialize_matcher(&matcher, use_regexp, case_sensitive, pattern);
628
629   if(show_hits) {
630     if(matcher.nb_patterns >= 0) {
631       switches = safe_malloc(sizeof(int) * matcher.nb_patterns * 2);
632     } else {
633       switches = safe_malloc(sizeof(int) * 2);
634     }
635   } else {
636     switches = 0;
637   }
638
639   console_width = getmaxx(stdscr);
640   console_height = getmaxy(stdscr);
641
642   use_default_colors();
643
644   /* Add an empty line where we will print the modeline at the end */
645
646   addstr("\n");
647
648   /* If the regexp is erroneous, print a message saying so */
649
650   if(matcher.regexp_error) {
651     attron(attr_error);
652     addnstr("Regexp syntax error", console_width);
653     attroff(attr_error);
654   }
655
656   /* Else, and we do have lines to select from, find a visible line. */
657
658   else if(nb_lines > 0) {
659     int new_focus_line;
660     if(match(&matcher, lines[*current_focus_line], 0, 0)) {
661       new_focus_line = *current_focus_line;
662     } else {
663       new_focus_line = next_visible(*current_focus_line, nb_lines, lines,
664                                     &matcher);
665       if(new_focus_line < 0) {
666         new_focus_line = previous_visible(*current_focus_line, lines, &matcher);
667       }
668     }
669
670     /* If we found a visible line and we should move, let's move */
671
672     if(new_focus_line >= 0 && motion != 0) {
673       int l = new_focus_line;
674       if(motion > 0) {
675         /* We want to go down, let's find the first visible line below */
676         for(m = 0; l >= 0 && m < motion; m++) {
677           l = next_visible(l, nb_lines, lines, &matcher);
678           if(l >= 0) {
679             new_focus_line = l;
680           }
681         }
682       } else {
683         /* We want to go up, let's find the first visible line above */
684         for(m = 0; l >= 0 && m < -motion; m++) {
685           l = previous_visible(l, lines, &matcher);
686           if(l >= 0) {
687             new_focus_line = l;
688           }
689         }
690       }
691     }
692
693     /* Here new_focus_line is either a line number matching the
694        pattern, or -1 */
695
696     if(new_focus_line >= 0) {
697
698       int first_line = new_focus_line, last_line = new_focus_line;
699       int nb_match = 1;
700
701       /* We find the first and last lines to show, so that the total
702          of visible lines between them (them included) is
703          console_height-1 */
704
705       while(nb_match < console_height-1 &&
706             (first_line > 0 || last_line < nb_lines - 1)) {
707
708         if(first_line > 0) {
709           first_line--;
710           while(first_line > 0 && !match(&matcher, lines[first_line], 0, 0)) {
711             first_line--;
712           }
713           if(match(&matcher, lines[first_line], 0, 0)) {
714             nb_match++;
715           }
716         }
717
718         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
719           last_line++;
720           while(last_line < nb_lines - 1 && !match(&matcher, lines[last_line], 0, 0)) {
721             last_line++;
722           }
723
724           if(match(&matcher, lines[last_line], 0, 0)) {
725             nb_match++;
726           }
727         }
728       }
729
730       /* Now we display them */
731
732       for(l = first_line; l <= last_line; l++) {
733         if(match(&matcher, lines[l], &nb_switches, switches)) {
734           int k = 0;
735
736           while(lines[l][k] && k < BUFFER_SIZE - 2 && k < console_width) {
737             buffer[k] = lines[l][k];
738             k++;
739           }
740
741           /* Highlight the highlighted line ... */
742
743           if(l == new_focus_line) {
744             if(show_long_lines && k >= console_width) {
745               attron(attr_focus_line);
746               print_string_with_switches(buffer, console_width-1,
747                                          nb_switches / 2, switches);
748               /* attron(attr_error); */
749               addnstr("\\", 1);
750               /* attroff(attr_error); */
751               attroff(attr_focus_line);
752             } else {
753               while(k < console_width) {
754                 buffer[k++] = ' ';
755               }
756               attron(attr_focus_line);
757               print_string_with_switches(buffer, k,
758                                          nb_switches / 2, switches);
759               attroff(attr_focus_line);
760             }
761           } else {
762             if(show_long_lines && k >= console_width) {
763               print_string_with_switches(buffer, console_width-1,
764                                          nb_switches / 2, switches);
765               attron(attr_focus_line);
766               addnstr("\\", 1);
767               attroff(attr_focus_line);
768             } else {
769               if(k < console_width) {
770                 buffer[k++] = '\n';
771                 buffer[k++] = '\0';
772               }
773               print_string_with_switches(buffer, k,
774                                          nb_switches / 2, switches);
775             }
776           }
777
778           nb_printed_lines++;
779         }
780       }
781
782       /* If we are on a focused line and we moved, this become the new
783          focus line */
784
785       if(motion != 0) {
786         *current_focus_line = new_focus_line;
787       }
788     }
789
790     *displayed_focus_line = new_focus_line;
791
792     if(nb_printed_lines == 0) {
793       attron(attr_error);
794       addnstr("No selection", console_width);
795       attroff(attr_error);
796     }
797   }
798
799   /* Else, print a message saying that there are no lines to select from */
800
801   else {
802     attron(attr_error);
803     addnstr("Empty choice", console_width);
804     attroff(attr_error);
805   }
806
807   clrtobot();
808
809   /* Draw the modeline */
810
811   move(0, 0);
812
813   attron(attr_modeline);
814
815   for(k = 0; k < console_width; k++) buffer[k] = ' ';
816   buffer[console_width] = '\0';
817   addnstr(buffer, console_width);
818
819   move(0, 0);
820
821   /* There must be a more elegant way of moving the cursor at a
822      location met during display */
823
824   cursor_x = 0;
825
826   if(title) {
827     addstr(title);
828     addstr(" ");
829     cursor_x += strlen(title) + 1;
830   }
831
832   sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
833   addstr(buffer);
834   cursor_x += strlen(buffer);
835
836   addnstr(pattern, cursor_position);
837   cursor_x += cursor_position;
838
839   if(pattern[cursor_position]) {
840     addstr(pattern + cursor_position);
841   } else {
842     addstr(" ");
843   }
844
845   /* Add a few info about the mode we are in (regexp and/or case
846      sensitive) */
847
848   if(use_regexp || matcher.case_sensitive) {
849     addstr(" [");
850     if(use_regexp) {
851       addstr("regexp");
852     }
853
854     if(matcher.case_sensitive) {
855       if(use_regexp) {
856         addstr(",");
857       }
858       addstr("case");
859     }
860     addstr("]");
861   }
862
863   move(0, cursor_x);
864
865   attroff(attr_modeline);
866
867   /* We are done */
868
869   refresh();
870   if(switches) { free(switches); }
871   free_matcher(&matcher);
872 }
873
874 /*********************************************************************/
875
876 void store_line(struct hash_table_t *hash_table,
877                 const char *new_line,
878                 int *nb_lines, char **lines) {
879   int dup;
880
881   /* Remove the zsh history prefix */
882
883   if(zsh_history && *new_line == ':') {
884     while(*new_line && *new_line != ';') new_line++;
885     if(*new_line == ';') new_line++;
886   }
887
888   /* Remove the bash history prefix */
889
890   if(bash_history) {
891     while(*new_line == ' ') new_line++;
892     while(*new_line >= '0' && *new_line <= '9') new_line++;
893     while(*new_line == ' ') new_line++;
894   }
895
896   /* Check for duplicates with the hash table and insert the line in
897      the list if necessary */
898
899   if(hash_table) {
900     dup = add_and_get_previous_index(hash_table,
901                                      new_line, *nb_lines, lines);
902   } else {
903     dup = -1;
904   }
905
906   if(dup < 0) {
907     lines[*nb_lines] = safe_malloc((strlen(new_line) + 1) * sizeof(char));
908     strcpy(lines[*nb_lines], new_line);
909   } else {
910     /* The string was already in there, so we do not allocate a new
911        string but use the pointer to the first occurence of it */
912     lines[*nb_lines] = lines[dup];
913     lines[dup] = 0;
914   }
915
916   (*nb_lines)++;
917 }
918
919 void read_file(struct hash_table_t *hash_table,
920                const char *input_filename,
921                int nb_lines_max, int *nb_lines, char **lines) {
922
923   char raw_line[BUFFER_SIZE];
924   char *s;
925   FILE *file;
926
927   file = fopen(input_filename, "r");
928
929   if(!file) {
930     fprintf(stderr, "selector: Can not open `%s'.\n", input_filename);
931     exit(EXIT_FAILURE);
932   }
933
934   while(*nb_lines < nb_lines_max && fgets(raw_line, BUFFER_SIZE, file)) {
935     for(s = raw_line + strlen(raw_line) - 1; s > raw_line && *s == '\n'; s--) {
936       *s = '\0';
937     }
938     store_line(hash_table, raw_line, nb_lines, lines);
939   }
940
941   fclose(file);
942 }
943
944 /*********************************************************************/
945
946 /* For long options that have no equivalent short option, use a
947    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
948 enum
949 {
950   OPT_BASH_MODE = CHAR_MAX + 1
951 };
952
953 static struct option long_options[] = {
954   { "output-file", 1, 0, 'o' },
955   { "pattern-separator", 1, 0, 's' },
956   { "label-separator", 1, 0, 'x' },
957   { "inject-in-tty", no_argument, 0, 'v' },
958   { "add-control-qs", no_argument, 0, 'w' },
959   { "monochrome", no_argument, 0, 'm' },
960   { "no-beep", no_argument, 0, 'q' },
961   { "revert-order", no_argument, 0, 'i' },
962   { "remove-bash-prefix", no_argument, 0, 'b' },
963   { "remove-zsh-prefix", no_argument, 0, 'z' },
964   { "remove-duplicates", no_argument, 0, 'd' },
965   { "regexp", no_argument, 0, 'e' },
966   { "case-sensitive", no_argument, 0, 'a' },
967   { "show-long-lines", no_argument, 0, 'j'},
968   { "show-hits", no_argument, 0, 'j'},
969   { "upper-case-makes-case-sensitive", no_argument, 0, 'u' },
970   { "title", 1, 0, 't' },
971   { "pattern", 1, 0, 'r' },
972   { "number-of-lines", 1, 0, 'l' },
973   { "colors", 1, 0, 'c' },
974   { "bash", no_argument, 0, OPT_BASH_MODE },
975   { "help", no_argument, 0, 'h' },
976   { 0, 0, 0, 0 }
977 };
978
979 int main(int argc, char **argv) {
980
981   char output_filename[BUFFER_SIZE];
982   char pattern[BUFFER_SIZE];
983   int c, k, l, n;
984   int cursor_position;
985   int error = 0, show_help = 0, done = 0;
986   int key;
987   int current_focus_line, displayed_focus_line;
988
989   int colors[4];
990   int color_fg_modeline, color_bg_modeline;
991   int color_fg_highlight, color_bg_highlight;
992
993   char **lines, **labels;
994   int nb_lines;
995   struct hash_table_t *hash_table;
996   char *bash_histsize;
997
998   if(!isatty(STDIN_FILENO)) {
999     fprintf(stderr, "selector: The standard input is not a tty.\n");
1000     exit(EXIT_FAILURE);
1001   }
1002
1003   pattern[0] = '\0';
1004
1005   color_fg_modeline  = COLOR_WHITE;
1006   color_bg_modeline  = COLOR_BLACK;
1007   color_fg_highlight = COLOR_BLACK;
1008   color_bg_highlight = COLOR_YELLOW;
1009
1010   setlocale(LC_ALL, "");
1011
1012   strcpy(output_filename, "");
1013
1014   while ((c = getopt_long(argc, argv, "o:s:x:vwmqf:ibzdeajyunt:r:l:c:-h",
1015                           long_options, NULL)) != -1) {
1016
1017     switch(c) {
1018
1019     case 'o':
1020       strncpy(output_filename, optarg, BUFFER_SIZE);
1021       break;
1022
1023     case 's':
1024       pattern_separator = optarg[0];
1025       break;
1026
1027     case 'x':
1028       label_separator = optarg[0];
1029       break;
1030
1031     case 'v':
1032       output_to_vt_buffer = 1;
1033       break;
1034
1035     case 'w':
1036       add_control_qs = 1;
1037       break;
1038
1039     case 'm':
1040       with_colors = 0;
1041       break;
1042
1043     case 'q':
1044       error_flash = 1;
1045       break;
1046
1047     case 'i':
1048       inverse_order = 1;
1049       break;
1050
1051     case 'b':
1052       bash_history = 1;
1053       break;
1054
1055     case 'z':
1056       zsh_history = 1;
1057       break;
1058
1059     case 'd':
1060       remove_duplicates = 1;
1061       break;
1062
1063     case 'e':
1064       use_regexp = 1;
1065       break;
1066
1067     case 'a':
1068       case_sensitive = 1;
1069       break;
1070
1071     case 'j':
1072       show_long_lines = 1;
1073       break;
1074
1075     case 'y':
1076       show_hits = 1;
1077       break;
1078
1079     case 'u':
1080       upper_caps_makes_case_sensitive = 1;
1081       break;
1082
1083     case 't':
1084       free(title);
1085       title = safe_malloc((strlen(optarg) + 1) * sizeof(char));
1086       strcpy(title, optarg);
1087       break;
1088
1089     case 'r':
1090       strcpy(pattern, optarg);
1091       break;
1092
1093     case 'l':
1094       str_to_positive_integers(optarg, &nb_lines_max, 1);
1095       break;
1096
1097     case 'c':
1098       str_to_positive_integers(optarg, colors, 4);
1099       color_fg_modeline = colors[0];
1100       color_bg_modeline = colors[1];
1101       color_fg_highlight = colors[2];
1102       color_bg_highlight = colors[3];
1103       break;
1104
1105     case 'h':
1106       show_help = 1;
1107       break;
1108
1109     case OPT_BASH_MODE:
1110       /* Same as -c 7,4,0,3 -q */
1111       /* color_fg_modeline = 7; */
1112       /* color_bg_modeline = 4; */
1113       /* color_fg_highlight = 0; */
1114       /* color_bg_highlight = 3; */
1115       /* error_flash = 1; */
1116       /* Same as -b -i -d -v -w */
1117       bash_history = 1;
1118       inverse_order = 1;
1119       remove_duplicates = 1;
1120       output_to_vt_buffer = 1;
1121       add_control_qs = 1;
1122       bash_histsize = getenv("HISTSIZE");
1123       if(bash_histsize) {
1124         str_to_positive_integers(bash_histsize, &nb_lines_max, 1);
1125       }
1126       break;
1127
1128     default:
1129       error = 1;
1130       break;
1131     }
1132   }
1133
1134   if(error) {
1135     usage(stderr);
1136     exit(EXIT_FAILURE);
1137   }
1138
1139   if(show_help) {
1140     usage(stdout);
1141     exit(EXIT_SUCCESS);
1142   }
1143
1144   lines = safe_malloc(nb_lines_max * sizeof(char *));
1145
1146   nb_lines = 0;
1147
1148   if(remove_duplicates) {
1149     hash_table = new_hash_table(nb_lines_max * 10);
1150   } else {
1151     hash_table = 0;
1152   }
1153
1154   while(optind < argc) {
1155     read_file(hash_table,
1156               argv[optind],
1157               nb_lines_max, &nb_lines, lines);
1158     optind++;
1159   }
1160
1161   if(hash_table) {
1162     free_hash_table(hash_table);
1163   }
1164
1165   /* Now remove the null strings */
1166
1167   n = 0;
1168   for(k = 0; k < nb_lines; k++) {
1169     if(lines[k]) {
1170       lines[n++] = lines[k];
1171     }
1172   }
1173
1174   nb_lines = n;
1175
1176   if(inverse_order) {
1177     for(l = 0; l < nb_lines / 2; l++) {
1178       char *s = lines[nb_lines - 1 - l];
1179       lines[nb_lines - 1 - l] = lines[l];
1180       lines[l] = s;
1181     }
1182   }
1183
1184   /* Build the labels from the strings, take only the part before the
1185      label_separator and transform control characters to printable
1186      ones */
1187
1188   labels = safe_malloc(nb_lines * sizeof(char *));
1189
1190   for(l = 0; l < nb_lines; l++) {
1191     char *s, *t;
1192     int e = 0;
1193     const char *u;
1194     t = lines[l];
1195
1196     while(*t && *t != label_separator) {
1197       u = unctrl(*t++);
1198       e += strlen(u);
1199     }
1200
1201     labels[l] = safe_malloc((e + 1) * sizeof(char));
1202     t = lines[l];
1203     s = labels[l];
1204     while(*t && *t != label_separator) {
1205       u = unctrl(*t++);
1206       while(*u) { *s++ = *u++; }
1207     }
1208     *s = '\0';
1209   }
1210
1211   cursor_position = 0;
1212
1213   /* Here we start to display with curse */
1214
1215   initscr();
1216   cbreak();
1217   noecho();
1218   intrflush(stdscr, FALSE);
1219
1220   /* So that the arrow keys work */
1221   keypad(stdscr, TRUE);
1222
1223   attr_error = A_STANDOUT;
1224   attr_modeline = A_REVERSE;
1225   attr_focus_line = A_STANDOUT;
1226   attr_hits = A_BOLD;
1227
1228   if(with_colors && has_colors()) {
1229
1230     start_color();
1231
1232     if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
1233        color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
1234        color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
1235        color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
1236       echo();
1237       endwin();
1238       fprintf(stderr, "selector: Color numbers have to be between 0 and %d.\n",
1239               COLORS - 1);
1240       exit(EXIT_FAILURE);
1241     }
1242
1243     init_pair(1, color_fg_modeline, color_bg_modeline);
1244     attr_modeline = COLOR_PAIR(1);
1245
1246     init_pair(2, color_fg_highlight, color_bg_highlight);
1247     attr_focus_line = COLOR_PAIR(2);
1248
1249     init_pair(3, COLOR_WHITE, COLOR_RED);
1250     attr_error = COLOR_PAIR(3);
1251
1252   }
1253
1254   current_focus_line = 0;
1255   displayed_focus_line = 0;
1256   cursor_position = strlen(pattern);
1257
1258   update_screen(&current_focus_line, &displayed_focus_line,
1259                 0,
1260                 nb_lines, labels, cursor_position, pattern);
1261
1262   do {
1263     int motion = 0;
1264
1265     key = getch();
1266
1267     if(key >= ' ' && key <= '~') { /* Insert character */
1268       insert_char(pattern, &cursor_position, key);
1269     }
1270
1271     else if(key == KEY_BACKSPACE ||
1272             key == '\010' || /* ^H */
1273             key == '\177') { /* ^? */
1274       backspace_char(pattern, &cursor_position);
1275     }
1276
1277     else if(key == KEY_DC ||
1278             key == '\004') { /* ^D */
1279       delete_char(pattern, &cursor_position);
1280     }
1281
1282     else if(key == KEY_HOME) {
1283       current_focus_line = 0;
1284     }
1285
1286     else if(key == KEY_END) {
1287       current_focus_line = nb_lines - 1;
1288     }
1289
1290     else if(key == KEY_NPAGE) {
1291       motion = 10;
1292     }
1293
1294     else if(key == KEY_PPAGE) {
1295       motion = -10;
1296     }
1297
1298     else if(key == KEY_DOWN ||
1299             key == '\016') { /* ^N */
1300       motion = 1;
1301     }
1302
1303     else if(key == KEY_UP ||
1304             key == '\020') { /* ^P */
1305       motion = -1;
1306     }
1307
1308     else if(key == KEY_LEFT ||
1309             key == '\002') { /* ^B */
1310       if(cursor_position > 0) cursor_position--;
1311       else error_feedback();
1312     }
1313
1314     else if(key == KEY_RIGHT ||
1315             key == '\006') { /* ^F */
1316       if(pattern[cursor_position]) cursor_position++;
1317       else error_feedback();
1318     }
1319
1320     else if(key == '\001') { /* ^A */
1321       cursor_position = 0;
1322     }
1323
1324     else if(key == '\005') { /* ^E */
1325       cursor_position = strlen(pattern);
1326     }
1327
1328     else if(key == '\022') { /* ^R */
1329       use_regexp = !use_regexp;
1330     }
1331
1332     else if(key == '\011') { /* ^I */
1333       case_sensitive = !case_sensitive;
1334     }
1335
1336     else if(key == '\025') { /* ^U */
1337       kill_before_cursor(pattern, &cursor_position);
1338     }
1339
1340     else if(key == '\013') { /* ^K */
1341       kill_after_cursor(pattern, &cursor_position);
1342     }
1343
1344     else if(key == '\014') { /* ^L */
1345       /* I suspect that we may sometime mess up the display, so ^L is
1346          here to force a full refresh */
1347       clear();
1348     }
1349
1350     else if(key == '\007' || /* ^G */
1351             key == '\033' || /* ^[ (escape) */
1352             key == '\n' ||
1353             key == KEY_ENTER) {
1354       done = 1;
1355     }
1356
1357     else if(key == KEY_RESIZE || key == -1) {
1358       /* Do nothing when the tty is resized */
1359     }
1360
1361     else {
1362       /* Unknown key */
1363       error_feedback();
1364     }
1365
1366     update_screen(&current_focus_line, &displayed_focus_line,
1367                   motion,
1368                   nb_lines, labels, cursor_position, pattern);
1369
1370   } while(!done);
1371
1372   echo();
1373   endwin();
1374
1375   /* Here we come back to standard display */
1376
1377   if(key == KEY_ENTER || key == '\n') {
1378
1379     char *t;
1380
1381     if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1382       t = lines[displayed_focus_line];
1383       if(label_separator) {
1384         while(*t && *t != label_separator) t++;
1385         if(*t) t++;
1386       }
1387     } else {
1388       t = 0;
1389     }
1390
1391     if(output_to_vt_buffer && t) {
1392       inject_into_tty_buffer(t, add_control_qs);
1393     }
1394
1395     if(output_filename[0]) {
1396       FILE *out = fopen(output_filename, "w");
1397       if(out) {
1398         if(t) {
1399           fprintf(out, "%s", t);
1400         }
1401         fprintf(out, "\n");
1402       } else {
1403         fprintf(stderr,
1404                 "selector: Can not open %s for writing.\n",
1405                 output_filename);
1406         exit(EXIT_FAILURE);
1407       }
1408       fclose(out);
1409     }
1410
1411   } else {
1412     printf("Aborted.\n");
1413   }
1414
1415   for(l = 0; l < nb_lines; l++) {
1416     free(lines[l]);
1417     free(labels[l]);
1418   }
1419
1420   free(labels);
1421   free(lines);
1422   free(title);
1423
1424   exit(EXIT_SUCCESS);
1425 }