OCD 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-2015 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 global_nb_lines_max = 1000;
56 char global_pattern_separator = ';';
57 char global_label_separator = '\0';
58 int global_output_to_vt_buffer = 0;
59 int global_add_control_qs = 0;
60 int global_with_colors = 1;
61 int global_zsh_history = 0;
62 int global_bash_history = 0;
63 int global_inverse_order = 0;
64 int global_remove_duplicates = 0;
65 int global_use_regexp = 0;
66 int global_case_sensitive = 0;
67 char *global_title = 0;
68 int global_error_flash = 0;
69 int global_upper_caps_makes_case_sensitive = 0;
70 int global_show_long_lines = 0;
71 int global_show_hits = 0;
72
73 int global_attr_modeline, global_attr_focus_line, global_attr_error, global_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, got_one;
115   char *s;
116   int n;
117
118   n = 0;
119   current_value = 0;
120   got_one = 0;
121   s = string;
122
123   while(1) {
124     if(*s >= '0' && *s <= '9') {
125       current_value = current_value * 10 + (int) (*s - '0');
126       got_one = 1;
127     } else if(*s == ',' || *s == '\0') {
128       if(got_one) {
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           got_one = 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(global_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(global_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 == global_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 == global_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(global_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(global_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, global_use_regexp, global_case_sensitive, pattern);
631
632   if(global_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(global_attr_error);
655     addnstr("Regexp syntax error", console_width);
656     attroff(global_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(global_show_long_lines && k >= console_width) {
748               attron(global_attr_focus_line);
749               print_string_with_switches(buffer, console_width-1,
750                                          nb_switches / 2, switches);
751               /* attron(global_attr_error); */
752               addnstr("\\", 1);
753               /* attroff(global_attr_error); */
754               attroff(global_attr_focus_line);
755             } else {
756               while(k < console_width) {
757                 buffer[k++] = ' ';
758               }
759               attron(global_attr_focus_line);
760               print_string_with_switches(buffer, k,
761                                          nb_switches / 2, switches);
762               attroff(global_attr_focus_line);
763             }
764           } else {
765             if(global_show_long_lines && k >= console_width) {
766               print_string_with_switches(buffer, console_width-1,
767                                          nb_switches / 2, switches);
768               attron(global_attr_focus_line);
769               addnstr("\\", 1);
770               attroff(global_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(global_attr_error);
797       addnstr("No selection", console_width);
798       attroff(global_attr_error);
799     }
800   }
801
802   /* Else, print a message saying that there are no lines to select from */
803
804   else {
805     attron(global_attr_error);
806     addnstr("Empty choice", console_width);
807     attroff(global_attr_error);
808   }
809
810   clrtobot();
811
812   /* Draw the modeline */
813
814   move(0, 0);
815
816   attron(global_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(global_title) {
830     addstr(global_title);
831     addstr(" ");
832     cursor_x += strlen(global_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(global_use_regexp || matcher.case_sensitive) {
852     addstr(" [");
853     if(global_use_regexp) {
854       addstr("regexp");
855     }
856
857     if(matcher.case_sensitive) {
858       if(global_use_regexp) {
859         addstr(",");
860       }
861       addstr("case");
862     }
863     addstr("]");
864   }
865
866   move(0, cursor_x);
867
868   attroff(global_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(global_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(global_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(global_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   OPT_BASH_MODE = CHAR_MAX + 1
965 };
966
967 static struct option long_options[] = {
968   { "output-file", 1, 0, 'o' },
969   { "pattern-separator", 1, 0, 's' },
970   { "label-separator", 1, 0, 'x' },
971   { "inject-in-tty", no_argument, 0, 'v' },
972   { "add-control-qs", no_argument, 0, 'w' },
973   { "monochrome", no_argument, 0, 'm' },
974   { "no-beep", no_argument, 0, 'q' },
975   { "revert-order", no_argument, 0, 'i' },
976   { "remove-bash-prefix", no_argument, 0, 'b' },
977   { "remove-zsh-prefix", no_argument, 0, 'z' },
978   { "remove-duplicates", no_argument, 0, 'd' },
979   { "regexp", no_argument, 0, 'e' },
980   { "case-sensitive", no_argument, 0, 'a' },
981   { "show-long-lines", no_argument, 0, 'j'},
982   { "show-hits", no_argument, 0, 'j'},
983   { "upper-case-makes-case-sensitive", no_argument, 0, 'u' },
984   { "title", 1, 0, 't' },
985   { "pattern", 1, 0, 'r' },
986   { "number-of-lines", 1, 0, 'l' },
987   { "colors", 1, 0, 'c' },
988   { "bash", no_argument, 0, OPT_BASH_MODE },
989   { "help", no_argument, 0, 'h' },
990   { 0, 0, 0, 0 }
991 };
992
993 int main(int argc, char **argv) {
994
995   char output_filename[BUFFER_SIZE];
996   char pattern[BUFFER_SIZE];
997   int c, k, l, n;
998   int cursor_position;
999   int error = 0, show_help = 0, done = 0;
1000   int key;
1001   int current_focus_line, displayed_focus_line;
1002
1003   int colors[4];
1004   int color_fg_modeline, color_bg_modeline;
1005   int color_fg_highlight, color_bg_highlight;
1006
1007   char **lines, **labels;
1008   int nb_lines;
1009   struct hash_table_t *hash_table;
1010   char *bash_histsize;
1011
1012   if(!isatty(STDIN_FILENO)) {
1013     fprintf(stderr, "selector: The standard input is not a tty.\n");
1014     exit(EXIT_FAILURE);
1015   }
1016
1017   /* Group and others have no access to created files */
1018   umask(S_IRWXG | S_IRWXO);
1019
1020   pattern[0] = '\0';
1021
1022   color_fg_modeline  = COLOR_WHITE;
1023   color_bg_modeline  = COLOR_BLACK;
1024   color_fg_highlight = COLOR_BLACK;
1025   color_bg_highlight = COLOR_YELLOW;
1026
1027   setlocale(LC_ALL, "");
1028
1029   strcpy(output_filename, "");
1030
1031   while ((c = getopt_long(argc, argv, "o:s:x:vwmqf:ibzdeajyunt:r:l:c:-h",
1032                           long_options, NULL)) != -1) {
1033
1034     switch(c) {
1035
1036     case 'o':
1037       strncpy(output_filename, optarg, BUFFER_SIZE);
1038       break;
1039
1040     case 's':
1041       global_pattern_separator = optarg[0];
1042       break;
1043
1044     case 'x':
1045       if(strcmp(optarg, "\\n") == 0) {
1046         global_label_separator = '\n';
1047       } else {
1048         global_label_separator = optarg[0];
1049       }
1050       break;
1051
1052     case 'v':
1053       global_output_to_vt_buffer = 1;
1054       break;
1055
1056     case 'w':
1057       global_add_control_qs = 1;
1058       break;
1059
1060     case 'm':
1061       global_with_colors = 0;
1062       break;
1063
1064     case 'q':
1065       global_error_flash = 1;
1066       break;
1067
1068     case 'i':
1069       global_inverse_order = 1;
1070       break;
1071
1072     case 'b':
1073       global_bash_history = 1;
1074       break;
1075
1076     case 'z':
1077       global_zsh_history = 1;
1078       break;
1079
1080     case 'd':
1081       global_remove_duplicates = 1;
1082       break;
1083
1084     case 'e':
1085       global_use_regexp = 1;
1086       break;
1087
1088     case 'a':
1089       global_case_sensitive = 1;
1090       break;
1091
1092     case 'j':
1093       global_show_long_lines = 1;
1094       break;
1095
1096     case 'y':
1097       global_show_hits = 1;
1098       break;
1099
1100     case 'u':
1101       global_upper_caps_makes_case_sensitive = 1;
1102       break;
1103
1104     case 't':
1105       free(global_title);
1106       global_title = safe_malloc((strlen(optarg) + 1) * sizeof(char));
1107       strcpy(global_title, optarg);
1108       break;
1109
1110     case 'r':
1111       strcpy(pattern, optarg);
1112       break;
1113
1114     case 'l':
1115       str_to_positive_integers(optarg, &global_nb_lines_max, 1);
1116       break;
1117
1118     case 'c':
1119       str_to_positive_integers(optarg, colors, 4);
1120       color_fg_modeline = colors[0];
1121       color_bg_modeline = colors[1];
1122       color_fg_highlight = colors[2];
1123       color_bg_highlight = colors[3];
1124       break;
1125
1126     case 'h':
1127       show_help = 1;
1128       break;
1129
1130     case OPT_BASH_MODE:
1131       /* Same as -c 7,4,0,3 -q */
1132       /* color_fg_modeline = 7; */
1133       /* color_bg_modeline = 4; */
1134       /* color_fg_highlight = 0; */
1135       /* color_bg_highlight = 3; */
1136       /* error_flash = 1; */
1137       /* Same as -b -i -d -v -w */
1138       global_bash_history = 1;
1139       global_inverse_order = 1;
1140       global_remove_duplicates = 1;
1141       global_output_to_vt_buffer = 1;
1142       global_add_control_qs = 1;
1143       bash_histsize = getenv("HISTSIZE");
1144       if(bash_histsize) {
1145         str_to_positive_integers(bash_histsize, &global_nb_lines_max, 1);
1146       }
1147       break;
1148
1149     default:
1150       error = 1;
1151       break;
1152     }
1153   }
1154
1155   if(error) {
1156     usage(stderr);
1157     exit(EXIT_FAILURE);
1158   }
1159
1160   if(show_help) {
1161     usage(stdout);
1162     exit(EXIT_SUCCESS);
1163   }
1164
1165   lines = safe_malloc(global_nb_lines_max * sizeof(char *));
1166
1167   nb_lines = 0;
1168
1169   if(global_remove_duplicates) {
1170     hash_table = new_hash_table(global_nb_lines_max * 10);
1171   } else {
1172     hash_table = 0;
1173   }
1174
1175   while(optind < argc) {
1176     read_file(hash_table,
1177               argv[optind],
1178               global_nb_lines_max, &nb_lines, lines);
1179     optind++;
1180   }
1181
1182   if(hash_table) {
1183     free_hash_table(hash_table);
1184   }
1185
1186   /* Now remove the null strings */
1187
1188   n = 0;
1189   for(k = 0; k < nb_lines; k++) {
1190     if(lines[k]) {
1191       lines[n++] = lines[k];
1192     }
1193   }
1194
1195   nb_lines = n;
1196
1197   if(global_inverse_order) {
1198     for(l = 0; l < nb_lines / 2; l++) {
1199       char *s = lines[nb_lines - 1 - l];
1200       lines[nb_lines - 1 - l] = lines[l];
1201       lines[l] = s;
1202     }
1203   }
1204
1205   /* Build the labels from the strings, take only the part before the
1206      label_separator and transform control characters to printable
1207      ones */
1208
1209   labels = safe_malloc(nb_lines * sizeof(char *));
1210
1211   for(l = 0; l < nb_lines; l++) {
1212     char *s, *t;
1213     int e = 0;
1214     const char *u;
1215     t = lines[l];
1216
1217     while(*t && *t != global_label_separator) {
1218       u = unctrl(*t++);
1219       e += strlen(u);
1220     }
1221
1222     labels[l] = safe_malloc((e + 1) * sizeof(char));
1223     t = lines[l];
1224     s = labels[l];
1225     while(*t && *t != global_label_separator) {
1226       u = unctrl(*t++);
1227       while(*u) { *s++ = *u++; }
1228     }
1229     *s = '\0';
1230   }
1231
1232   cursor_position = 0;
1233
1234   /* Here we start to display with curse */
1235
1236   initscr();
1237   cbreak();
1238   noecho();
1239   intrflush(stdscr, FALSE);
1240
1241   /* So that the arrow keys work */
1242   keypad(stdscr, TRUE);
1243
1244   global_attr_error = A_STANDOUT;
1245   global_attr_modeline = A_REVERSE;
1246   global_attr_focus_line = A_STANDOUT;
1247   global_attr_hits = A_BOLD;
1248
1249   if(global_with_colors && has_colors()) {
1250
1251     start_color();
1252
1253     if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
1254        color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
1255        color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
1256        color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
1257       echo();
1258       endwin();
1259       fprintf(stderr, "selector: Color numbers have to be between 0 and %d.\n",
1260               COLORS - 1);
1261       exit(EXIT_FAILURE);
1262     }
1263
1264     init_pair(1, color_fg_modeline, color_bg_modeline);
1265     global_attr_modeline = COLOR_PAIR(1);
1266
1267     init_pair(2, color_fg_highlight, color_bg_highlight);
1268     global_attr_focus_line = COLOR_PAIR(2);
1269
1270     init_pair(3, COLOR_WHITE, COLOR_RED);
1271     global_attr_error = COLOR_PAIR(3);
1272
1273   }
1274
1275   current_focus_line = 0;
1276   displayed_focus_line = 0;
1277   cursor_position = strlen(pattern);
1278
1279   update_screen(&current_focus_line, &displayed_focus_line,
1280                 0,
1281                 nb_lines, labels, cursor_position, pattern);
1282
1283   do {
1284     int motion = 0;
1285
1286     key = getch();
1287
1288     if(key >= ' ' && key <= '~') { /* Insert character */
1289       insert_char(pattern, &cursor_position, key);
1290     }
1291
1292     else if(key == KEY_BACKSPACE ||
1293             key == '\010' || /* ^H */
1294             key == '\177') { /* ^? */
1295       backspace_char(pattern, &cursor_position);
1296     }
1297
1298     else if(key == KEY_DC ||
1299             key == '\004') { /* ^D */
1300       delete_char(pattern, &cursor_position);
1301     }
1302
1303     else if(key == KEY_HOME) {
1304       current_focus_line = 0;
1305     }
1306
1307     else if(key == KEY_END) {
1308       current_focus_line = nb_lines - 1;
1309     }
1310
1311     else if(key == KEY_NPAGE) {
1312       motion = 10;
1313     }
1314
1315     else if(key == KEY_PPAGE) {
1316       motion = -10;
1317     }
1318
1319     else if(key == KEY_DOWN ||
1320             key == '\016') { /* ^N */
1321       motion = 1;
1322     }
1323
1324     else if(key == KEY_UP ||
1325             key == '\020') { /* ^P */
1326       motion = -1;
1327     }
1328
1329     else if(key == KEY_LEFT ||
1330             key == '\002') { /* ^B */
1331       if(cursor_position > 0) cursor_position--;
1332       else error_feedback();
1333     }
1334
1335     else if(key == KEY_RIGHT ||
1336             key == '\006') { /* ^F */
1337       if(pattern[cursor_position]) cursor_position++;
1338       else error_feedback();
1339     }
1340
1341     else if(key == '\001') { /* ^A */
1342       cursor_position = 0;
1343     }
1344
1345     else if(key == '\005') { /* ^E */
1346       cursor_position = strlen(pattern);
1347     }
1348
1349     else if(key == '\022') { /* ^R */
1350       global_use_regexp = !global_use_regexp;
1351     }
1352
1353     else if(key == '\011') { /* ^I */
1354       global_case_sensitive = !global_case_sensitive;
1355     }
1356
1357     else if(key == '\025') { /* ^U */
1358       kill_before_cursor(pattern, &cursor_position);
1359     }
1360
1361     else if(key == '\013') { /* ^K */
1362       kill_after_cursor(pattern, &cursor_position);
1363     }
1364
1365     else if(key == '\014') { /* ^L */
1366       /* I suspect that we may sometime mess up the display, so ^L is
1367          here to force a full refresh */
1368       clear();
1369     }
1370
1371     else if(key == '\007' || /* ^G */
1372             key == '\033' || /* ^[ (escape) */
1373             key == '\n' ||
1374             key == KEY_ENTER) {
1375       done = 1;
1376     }
1377
1378     else if(key == KEY_RESIZE || key == -1) {
1379       /* Do nothing when the tty is resized */
1380     }
1381
1382     else {
1383       /* Unknown key */
1384       error_feedback();
1385     }
1386
1387     update_screen(&current_focus_line, &displayed_focus_line,
1388                   motion,
1389                   nb_lines, labels, cursor_position, pattern);
1390
1391   } while(!done);
1392
1393   echo();
1394   endwin();
1395
1396   /* Here we come back to standard display */
1397
1398   if(key == KEY_ENTER || key == '\n') {
1399
1400     char *t;
1401
1402     if(displayed_focus_line >= 0 && displayed_focus_line < nb_lines) {
1403       t = lines[displayed_focus_line];
1404       if(global_label_separator) {
1405         while(*t && *t != global_label_separator) t++;
1406         if(*t) t++;
1407       }
1408     } else {
1409       t = 0;
1410     }
1411
1412     if(global_output_to_vt_buffer && t) {
1413       inject_into_tty_buffer(t, global_add_control_qs);
1414     }
1415
1416     if(output_filename[0]) {
1417       FILE *out = fopen(output_filename, "w");
1418       if(out) {
1419         if(t) {
1420           fprintf(out, "%s", t);
1421         }
1422         fprintf(out, "\n");
1423       } else {
1424         fprintf(stderr,
1425                 "selector: Cannot open %s for writing.\n",
1426                 output_filename);
1427         exit(EXIT_FAILURE);
1428       }
1429       fclose(out);
1430     }
1431
1432   } else {
1433     printf("Aborted.\n");
1434   }
1435
1436   for(l = 0; l < nb_lines; l++) {
1437     free(lines[l]);
1438     free(labels[l]);
1439   }
1440
1441   free(labels);
1442   free(lines);
1443   free(global_title);
1444
1445   exit(EXIT_SUCCESS);
1446 }