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