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