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