Cosmetics.
[selector.git] / selector.cc
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 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 // To use it as a super-history-search for bash:
26 // alias h='selector -d -i -b -v -f <(history)'
27
28 #include <fstream>
29 #include <iostream>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ncurses.h>
35 #include <fcntl.h>
36 #include <sys/ioctl.h>
37 #include <termios.h>
38 #include <regex.h>
39
40 using namespace std;
41
42 #define VERSION "1.0"
43
44 const int buffer_size = 4096;
45
46 // Yeah, global variables!
47
48 int nb_lines_max = 1000;
49 char pattern_separator = ';';
50 char label_separator = '\0';
51 int output_to_vt_buffer = 0;
52 int add_control_qs = 0;
53 int with_colors = 1;
54 int zsh_history = 0, bash_history = 0;
55 int inverse_order = 0;
56 int remove_duplicates = 0;
57 int use_regexp = 0;
58 int case_sensitive = 0;
59 char *title = 0;
60 int error_flash = 0;
61
62 #define COLOR_MODELINE 1
63 #define COLOR_HIGHLIGHTED_LINE 2
64
65 //////////////////////////////////////////////////////////////////////
66
67 void inject_into_tty_buffer(char *string) {
68   struct termios oldtio, newtio;
69   tcgetattr(STDIN_FILENO, &oldtio);
70   memset(&newtio, 0, sizeof(newtio));
71   // Set input mode (non-canonical, *no echo*,...)
72   tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
73   char control_q = '\021';
74   // Put the selected string in the tty input buffer
75   for(char *k = string; *k; k++) {
76     if(add_control_qs) {
77       // Add ^Q to quote control characters
78       ioctl(STDIN_FILENO, TIOCSTI, &control_q);
79     }
80     ioctl(STDIN_FILENO, TIOCSTI, k);
81   }
82   // Restore the old settings
83   tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
84 }
85
86 //////////////////////////////////////////////////////////////////////
87
88 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
89   if(n_opt + n >= argc) {
90     cerr << "Missing argument for " << argv[n_opt] << "."
91          << " "
92          << "Expecting " << help << "."
93          << endl;
94     exit(1);
95   }
96 }
97
98 int string_to_positive_integer(char *string) {
99   int error = 0;
100   int result = 0;
101
102   if(*string) {
103     for(char *s = string; *s; s++) {
104       if(*s >= '0' && *s <= '9') {
105         result = result * 10 + int(*s - '0');
106       } else error = 1;
107     }
108   } else error = 1;
109
110   if(error) {
111     cerr << "Value `" << string << "' is not a positive integer." << endl;
112     exit(1);
113   }
114
115   return result;
116 }
117
118 void error_feedback() {
119   if(error_flash) {
120     flash();
121   } else {
122     beep();
123   }
124 }
125
126 //////////////////////////////////////////////////////////////////////
127 // A quick and dirty hash table
128
129 // The table itself stores index of the strings in a char
130 // **table. When a string is added, if it was already in the table,
131 // the new index replaces the previous one.
132
133 int *new_hash_table(int hash_table_size) {
134   int *result;
135   result = new int[hash_table_size];
136   for(int k = 0; k < hash_table_size; k++) {
137     result[k] = -1;
138   }
139   return result;
140 }
141
142 // Adds new_string in the table, associated to new_index. If this
143 // string was not already in the table, returns -1. Otherwise, returns
144 // the previous index it had.
145
146 int test_and_add(char *new_string, int new_index,
147                  char **strings, int *hash_table, int hash_table_size) {
148
149   unsigned int code = 0;
150
151   // This is my recipe. I checked, it seems to work (as long as
152   // hash_table_size is not a multiple of 387433 that should be okay)
153
154   for(int k = 0; new_string[k]; k++) {
155     code = code * 387433 + (unsigned int) (new_string[k]);
156   }
157
158   code = code % hash_table_size;
159
160   while(hash_table[code] >= 0) {
161     // There is a string with that code
162     if(strcmp(new_string, strings[hash_table[code]]) == 0) {
163       // It is the same string, we keep a copy of the stored index
164       int result = hash_table[code];
165       // Put the new one
166       hash_table[code] = new_index;
167       // And return the previous one
168       return result;
169     }
170     // This collision was not the same string, let's move to the next
171     // in the table
172     code = (code + 1) % hash_table_size;
173   }
174
175   // This string was not already in there, store the index in the
176   // table and return -1
177   hash_table[code] = new_index;
178   return -1;
179 }
180
181 //////////////////////////////////////////////////////////////////////
182 // A matcher matches either with a collection of substrings, or with a
183 // regexp
184
185 struct matcher_t {
186   regex_t preg;
187   int regexp_error;
188   int nb_patterns;
189   int case_sensitive;
190   char *splitted_patterns, **patterns;
191 };
192
193 int match(char *string, matcher_t *matcher) {
194   if(matcher->nb_patterns >= 0) {
195     if(matcher->case_sensitive) {
196       for(int n = 0; n < matcher->nb_patterns; n++) {
197         if(strstr(string, matcher->patterns[n]) == 0) return 0;
198       }
199     } else {
200       for(int n = 0; n < matcher->nb_patterns; n++) {
201         if(strcasestr(string, matcher->patterns[n]) == 0) return 0;
202       }
203     }
204     return 1;
205   } else {
206     return regexec(&matcher->preg, string, 0, 0, 0) == 0;
207   }
208 }
209
210 void free_matcher(matcher_t *matcher) {
211   if(matcher->nb_patterns < 0) {
212     if(!matcher->regexp_error) regfree(&matcher->preg);
213   } else {
214     delete[] matcher->splitted_patterns;
215     delete[] matcher->patterns;
216   }
217 }
218
219 void initialize_matcher(int use_regexp, int case_sensitive,
220                         matcher_t *matcher, const char *pattern) {
221
222   if(use_regexp) {
223     matcher->nb_patterns = -1;
224     matcher->regexp_error = regcomp(&matcher->preg, pattern, case_sensitive ? 0 : REG_ICASE);
225   } else {
226     matcher->regexp_error = 0;
227     matcher->nb_patterns = 1;
228     matcher->case_sensitive = case_sensitive;
229
230     for(const char *s = pattern; *s; s++) {
231       if(*s == pattern_separator) {
232         matcher->nb_patterns++;
233       }
234     }
235
236     matcher->splitted_patterns = new char[strlen(pattern) + 1];
237     matcher->patterns = new char*[matcher->nb_patterns];
238
239     strcpy(matcher->splitted_patterns, pattern);
240
241     int n = 0;
242     char *last_pattern_start = matcher->splitted_patterns;
243     for(char *s = matcher->splitted_patterns; n < matcher->nb_patterns; s++) {
244       if(*s == pattern_separator || *s == '\0') {
245         *s = '\0';
246         matcher->patterns[n++] = last_pattern_start;
247         last_pattern_start = s + 1;
248       }
249     }
250   }
251 }
252
253 //////////////////////////////////////////////////////////////////////
254 // Buffer edition
255
256 void delete_char(char *buffer, int *position) {
257   if(buffer[*position]) {
258     int c = *position;
259     while(c < buffer_size && buffer[c]) {
260       buffer[c] = buffer[c+1];
261       c++;
262     }
263   } else error_feedback();
264 }
265
266 void backspace_char(char *buffer, int *position) {
267   if(*position > 0) {
268     if(buffer[*position]) {
269       int c = *position - 1;
270       while(buffer[c]) {
271         buffer[c] = buffer[c+1];
272         c++;
273       }
274     } else {
275       buffer[*position - 1] = '\0';
276     }
277
278     (*position)--;
279   } else error_feedback();
280 }
281
282 void insert_char(char *buffer, int *position, char character) {
283   if(strlen(buffer) < buffer_size - 1) {
284     int c = *position;
285     char t = buffer[c], u;
286     while(t) {
287       c++;
288       u = buffer[c];
289       buffer[c] = t;
290       t = u;
291     }
292     c++;
293     buffer[c] = '\0';
294     buffer[(*position)++] = character;
295   } else error_feedback();
296 }
297
298 void kill_before_cursor(char *buffer, int *position) {
299   int s = 0;
300   while(buffer[*position + s]) {
301     buffer[s] = buffer[*position + s];
302     s++;
303   }
304   buffer[s] = '\0';
305   *position = 0;
306 }
307
308 void kill_after_cursor(char *buffer, int *position) {
309   buffer[*position] = '\0';
310 }
311
312 //////////////////////////////////////////////////////////////////////
313
314 int previous_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
315   int line = current_line - 1;
316   while(line >= 0 && !match(lines[line], matcher)) line--;
317   return line;
318 }
319
320 int next_visible(int current_line, int nb_lines, char **lines, matcher_t *matcher) {
321   int line = current_line + 1;
322   while(line < nb_lines && !match(lines[line], matcher)) line++;
323
324   if(line < nb_lines)
325     return line;
326   else
327     return -1;
328 }
329
330 //////////////////////////////////////////////////////////////////////
331
332 void update_screen(int *current_line, int *temporary_line, int motion,
333                    int nb_lines, char **lines,
334                    int cursor_position,
335                    char *pattern) {
336
337   char buffer[buffer_size];
338   matcher_t matcher;
339
340   initialize_matcher(use_regexp, case_sensitive, &matcher, pattern);
341
342   // We now take care of printing the lines per se
343
344   int console_width = getmaxx(stdscr);
345   int console_height = getmaxy(stdscr);
346
347   // First, we find a visible line. In priority: The current, or the
348   // first visible after it, or the first visible before it.
349
350   int nb_printed_lines = 0;
351
352   clear();
353   use_default_colors();
354   addstr("\n");
355
356   if(matcher.regexp_error) {
357     addstr("[regexp error]");
358   } else if(nb_lines > 0) {
359     int new_line;
360     if(match(lines[*current_line], &matcher)) {
361       new_line = *current_line;
362     } else {
363       new_line = next_visible(*current_line, nb_lines, lines, &matcher);
364       if(new_line < 0) {
365         new_line = previous_visible(*current_line, nb_lines, lines, &matcher);
366       }
367     }
368
369     // If we found a visible line and we should move, let's move
370
371     if(new_line >= 0 && motion != 0) {
372       int l = new_line;
373       if(motion > 0) {
374         // We want to go down, let's find the first visible line below
375         for(int m = 0; l >= 0 && m < motion; m++) {
376           l = next_visible(l, nb_lines, lines, &matcher);
377           if(l >= 0) {
378             new_line = l;
379           }
380         }
381       } else {
382         // We want to go up, let's find the first visible line above
383         for(int m = 0; l >= 0 && m < -motion; m++) {
384           l = previous_visible(l, nb_lines, lines, &matcher);
385           if(l >= 0) {
386             new_line = l;
387           }
388         }
389       }
390     }
391
392     // Here new_line is either a line number matching the patterns, or -1
393
394     if(new_line >= 0) {
395
396       int first_line = new_line, last_line = new_line, nb_match = 1;
397
398       // We find the first and last line to show, so that the total of
399       // visible lines between them (them included) is console_height-1
400
401       while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
402
403         if(first_line > 0) {
404           first_line--;
405           while(first_line > 0 && !match(lines[first_line], &matcher)) {
406             first_line--;
407           }
408           if(match(lines[first_line], &matcher)) {
409             nb_match++;
410           }
411         }
412
413         if(nb_match < console_height - 1 && last_line < nb_lines - 1) {
414           last_line++;
415           while(last_line < nb_lines - 1 && !match(lines[last_line], &matcher)) {
416             last_line++;
417           }
418
419           if(match(lines[last_line], &matcher)) {
420             nb_match++;
421           }
422         }
423       }
424
425       // Now we display them
426
427       for(int l = first_line; l <= last_line; l++) {
428         if(match(lines[l], &matcher)) {
429           int k = 0;
430
431           while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
432             buffer[k] = lines[l][k];
433             k++;
434           }
435
436           // We fill the rest of the line with blanks if this is the
437           // highlighted line
438
439           if(l == new_line) {
440             while(k < console_width) {
441               buffer[k++] = ' ';
442             }
443           }
444
445           buffer[k++] = '\n';
446           buffer[k++] = '\0';
447
448           // Highlight the highlighted line ...
449
450           if(l == new_line) {
451             if(with_colors) {
452               attron(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
453               addnstr(buffer, console_width);
454               attroff(COLOR_PAIR(COLOR_HIGHLIGHTED_LINE));
455             } else {
456               attron(A_STANDOUT);
457               addnstr(buffer, console_width);
458               attroff(A_STANDOUT);
459             }
460           } else {
461             addnstr(buffer, console_width);
462           }
463
464           nb_printed_lines++;
465         }
466       }
467
468       if(motion != 0) {
469         *current_line = new_line;
470       }
471     }
472
473     *temporary_line = new_line;
474
475     if(nb_printed_lines == 0) {
476       addnstr("[no selection]\n", console_width);
477     }
478   } else {
479     addnstr("[empty choice]\n", console_width);
480   }
481
482   // Draw the modeline
483
484   move(0, 0);
485
486   if(with_colors) {
487     attron(COLOR_PAIR(COLOR_MODELINE));
488   } else {
489     attron(A_REVERSE);
490   }
491
492   for(int k = 0; k < console_width; k++) buffer[k] = ' ';
493   buffer[console_width] = '\0';
494   addnstr(buffer, console_width);
495
496   move(0, 0);
497
498   // There must be a more elegant way of moving the cursor at a
499   // location met during display
500
501   int cursor_x = 0;
502
503   if(title) {
504     addstr(title);
505     addstr(" ");
506     cursor_x += strlen(title) + 1;
507   }
508
509   sprintf(buffer, "%d/%d ", nb_printed_lines, nb_lines);
510   addstr(buffer);
511   cursor_x += strlen(buffer);
512
513   addnstr(pattern, cursor_position);
514   cursor_x += cursor_position;
515
516   if(pattern[cursor_position]) {
517     addstr(pattern + cursor_position);
518   } else {
519     addstr(" ");
520   }
521
522   if(use_regexp || case_sensitive) {
523     addstr(" [");
524     if(use_regexp) {
525       addstr("regexp");
526     }
527
528     if(case_sensitive) {
529       if(use_regexp) {
530         addstr(",");
531       }
532       addstr("case");
533     }
534     addstr("]");
535   }
536
537   move(0, cursor_x);
538
539   if(with_colors) {
540     attroff(COLOR_PAIR(COLOR_MODELINE));
541   } else {
542     attroff(A_REVERSE);
543   }
544
545   // We are done
546
547   refresh();
548   free_matcher(&matcher);
549 }
550
551 //////////////////////////////////////////////////////////////////////
552
553 void read_file(const char *input_filename,
554                int nb_lines_max, int *nb_lines, char **lines,
555                int hash_table_size, int *hash_table) {
556
557   char raw_line[buffer_size];;
558
559   ifstream file(input_filename);
560
561   if(file.fail()) {
562     cerr << "Can not open " << input_filename << endl;
563     exit(1);
564   }
565
566   while(*nb_lines < nb_lines_max && !file.eof()) {
567
568     file.getline(raw_line, buffer_size);
569
570     if(raw_line[0]) {
571
572       if(file.fail()) {
573         cerr << "Line too long:" << endl;
574         cerr << raw_line << endl;
575         exit(1);
576       }
577
578       char *t;
579
580       t = raw_line;
581
582       // Remove the zsh history prefix
583
584       if(zsh_history && *t == ':') {
585         while(*t && *t != ';') t++;
586         if(*t == ';') t++;
587       }
588
589       // Remove the bash history prefix
590
591       if(bash_history) {
592         while(*t == ' ') t++;
593         while(*t >= '0' && *t <= '9') t++;
594         while(*t == ' ') t++;
595       }
596
597       // Check for duplicates with the hash table and insert the line
598       // in the list if necessary
599
600       int dup;
601
602       if(hash_table) {
603         dup = test_and_add(t, *nb_lines, lines, hash_table, hash_table_size);
604       } else {
605         dup = -1;
606       }
607
608       if(dup < 0) {
609         lines[*nb_lines] = new char[strlen(t) + 1];
610         strcpy(lines[*nb_lines], t);
611       } else {
612         // The string was already in there, so we do not allocate a
613         // new string but use the pointer to the first occurence of it
614         lines[*nb_lines] = lines[dup];
615         lines[dup] = 0;
616       }
617
618       (*nb_lines)++;
619     }
620   }
621 }
622
623 //////////////////////////////////////////////////////////////////////
624
625 int main(int argc, char **argv) {
626
627   if(!ttyname(STDIN_FILENO)) {
628     cerr << "The standard input is not a tty." << endl;
629     exit(1);
630   }
631
632   int color_fg_modeline, color_bg_modeline;
633   int color_fg_highlight, color_bg_highlight;
634
635   color_fg_modeline  = COLOR_WHITE;
636   color_bg_modeline  = COLOR_BLACK;
637   color_fg_highlight = COLOR_BLACK;
638   color_bg_highlight = COLOR_YELLOW;
639
640   setlocale(LC_ALL, "");
641
642   char input_filename[buffer_size], output_filename[buffer_size];
643
644   strcpy(input_filename, "");
645   strcpy(output_filename, "");
646
647   int i = 1;
648   int error = 0, show_help = 0;
649   int rest_are_files = 0;
650
651   while(!error && !show_help && i < argc && argv[i][0] == '-' && !rest_are_files) {
652
653     if(strcmp(argv[i], "-o") == 0) {
654       check_opt(argc, argv, i, 1, "<output filename>");
655       strncpy(output_filename, argv[i+1], buffer_size);
656       i += 2;
657     }
658
659     else if(strcmp(argv[i], "-s") == 0) {
660       check_opt(argc, argv, i, 1, "<pattern separator>");
661       pattern_separator = argv[i+1][0];
662       i += 2;
663     }
664
665     else if(strcmp(argv[i], "-x") == 0) {
666       check_opt(argc, argv, i, 1, "<label separator>");
667       label_separator = argv[i+1][0];
668       i += 2;
669     }
670
671     else if(strcmp(argv[i], "-v") == 0) {
672       output_to_vt_buffer = 1;
673       i++;
674     }
675
676     else if(strcmp(argv[i], "-w") == 0) {
677       add_control_qs = 1;
678       i++;
679     }
680
681     else if(strcmp(argv[i], "-m") == 0) {
682       with_colors = 0;
683       i++;
684     }
685
686     else if(strcmp(argv[i], "-q") == 0) {
687       error_flash = 1;
688       i++;
689     }
690
691     else if(strcmp(argv[i], "-f") == 0) {
692       check_opt(argc, argv, i, 1, "<input filename>");
693       strncpy(input_filename, argv[i+1], buffer_size);
694       i += 2;
695     }
696
697     else if(strcmp(argv[i], "-i") == 0) {
698       inverse_order = 1;
699       i++;
700     }
701
702     else if(strcmp(argv[i], "-b") == 0) {
703       bash_history = 1;
704       i++;
705     }
706
707     else if(strcmp(argv[i], "-z") == 0) {
708       zsh_history = 1;
709       i++;
710     }
711
712     else if(strcmp(argv[i], "-d") == 0) {
713       remove_duplicates = 1;
714       i++;
715     }
716
717     else if(strcmp(argv[i], "-e") == 0) {
718       use_regexp = 1;
719       i++;
720     }
721
722     else if(strcmp(argv[i], "-a") == 0) {
723       case_sensitive = 1;
724       i++;
725     }
726
727     else if(strcmp(argv[i], "-t") == 0) {
728       check_opt(argc, argv, i, 1, "<title>");
729       delete[] title;
730       title = new char[strlen(argv[i+1]) + 1];
731       strcpy(title, argv[i+1]);
732       i += 2;
733     }
734
735     else if(strcmp(argv[i], "-l") == 0) {
736       check_opt(argc, argv, i, 1, "<maximum number of lines>");
737       nb_lines_max = string_to_positive_integer(argv[i+1]);
738       i += 2;
739     }
740
741     else if(strcmp(argv[i], "-c") == 0) {
742       check_opt(argc, argv, i, 4, "<fg modeline> <bg modeline> <fg highlight> <bg highlight>");
743       color_fg_modeline = string_to_positive_integer(argv[i + 1]);
744       color_bg_modeline = string_to_positive_integer(argv[i + 2]);
745       color_fg_highlight = string_to_positive_integer(argv[i + 3]);
746       color_bg_highlight = string_to_positive_integer(argv[i + 4]);
747       i += 5;
748     }
749
750     else if(strcmp(argv[i], "--") == 0) {
751       rest_are_files = 1;
752       i++;
753     }
754
755     else if(strcmp(argv[i], "-h") == 0) {
756       show_help = 1;
757       i++;
758     }
759
760     else {
761       cerr << "Unknown option " << argv[i] << "." << endl;
762       error = 1;
763     }
764   }
765
766   if(show_help || error) {
767     cerr << "Selector version " << VERSION << "-R" << REVISION_NUMBER
768          << endl
769          << "Written by Francois Fleuret <francois@fleuret.org>."
770          << endl
771          << endl
772          << "Usage: " << argv[0] << " [options] [<filename1> [<filename2> ...]]" << endl
773          << endl
774          << " -h      show this help" << endl
775          << " -v      inject the selected line in the tty" << endl
776          << " -d      remove duplicated lines" << endl
777          << " -b      remove the bash history line prefix" << endl
778          << " -z      remove the zsh history line prefix" << endl
779          << " -i      invert the order of lines" << endl
780          << " -e      start in regexp mode" << endl
781          << " -a      case sensitive" << endl
782          << " -m      monochrome mode" << endl
783          << " -q      make a flash instead of a beep on an edition error" << endl
784          << " --      rest of the arguments are filenames" << endl
785          << " -t <title>" << endl
786          << "         add a title in the modeline" << endl
787          << " -c <fg modeline> <bg modeline> <fg highlight> <bg highlight>" << endl
788          << "         set the display colors" << endl
789          << " -o <output filename>" << endl
790          << "         set a file to write the selected line to" << endl
791          << " -s <pattern separator>" << endl
792          << "         set the symbol to separate substrings in the pattern" << endl
793          << " -x <label separator>" << endl
794          << "         set the symbol to terminate the label" << endl
795          << " -l <max number of lines>" << endl
796          << "         set the maximum number of lines to take into account" << endl
797          << endl;
798
799     exit(error);
800   }
801
802   char **lines = new char *[nb_lines_max];
803
804   int nb_lines = 0;
805   int hash_table_size = nb_lines_max * 10;
806   int *hash_table = 0;
807
808   if(remove_duplicates) {
809     hash_table = new_hash_table(hash_table_size);
810   }
811
812   if(input_filename[0]) {
813     read_file(input_filename,
814               nb_lines_max, &nb_lines, lines,
815               hash_table_size, hash_table);
816   }
817
818   while(i < argc) {
819     read_file(argv[i],
820               nb_lines_max, &nb_lines, lines,
821               hash_table_size, hash_table);
822     i++;
823   }
824
825   delete[] hash_table;
826
827   // Now remove the null strings
828
829   int n = 0;
830   for(int k = 0; k < nb_lines; k++) {
831     if(lines[k]) {
832       lines[n++] = lines[k];
833     }
834   }
835
836   nb_lines = n;
837
838   if(inverse_order) {
839     for(int i = 0; i < nb_lines / 2; i++) {
840       char *s = lines[nb_lines - 1 - i];
841       lines[nb_lines - 1 - i] = lines[i];
842       lines[i] = s;
843     }
844   }
845
846   // Build the labels from the strings, take only the part before the
847   // label_separator and transform control characters to printable
848   // ones
849
850   char **labels = new char *[nb_lines];
851   for(int l = 0; l < nb_lines; l++) {
852     char *s, *t;
853     const char *u;
854     t = lines[l];
855     int e = 0;
856     while(*t && *t != label_separator) {
857       u = unctrl(*t++);
858       e += strlen(u);
859     }
860     labels[l] = new char[e + 1];
861     t = lines[l];
862     s = labels[l];
863     while(*t && *t != label_separator) {
864       u = unctrl(*t++);
865       while(*u) { *s++ = *u++; }
866     }
867     *s = '\0';
868   }
869
870   char pattern[buffer_size];
871   pattern[0] = '\0';
872   int cursor_position;
873   cursor_position = 0;
874
875   //////////////////////////////////////////////////////////////////////
876   // Here we start to display with curse
877
878   initscr();
879
880   noecho();
881
882   // So that the arrow keys work
883   keypad(stdscr, TRUE);
884
885   if(with_colors) {
886
887     if(has_colors()) {
888
889       start_color();
890
891       if(color_fg_modeline < 0  || color_fg_modeline >= COLORS ||
892          color_bg_modeline < 0  || color_bg_modeline >= COLORS ||
893          color_fg_highlight < 0 || color_bg_highlight >= COLORS ||
894          color_bg_highlight < 0 || color_bg_highlight >= COLORS) {
895         echo();
896         endwin();
897         cerr << "Color numbers have to be between 0 and " << COLORS - 1 << "." << endl;
898         exit(1);
899       }
900
901       init_pair(COLOR_MODELINE, color_fg_modeline, color_bg_modeline);
902       init_pair(COLOR_HIGHLIGHTED_LINE, color_fg_highlight, color_bg_highlight);
903
904     } else {
905       with_colors = 0;
906     }
907   }
908
909   int key;
910   int current_line = 0, temporary_line = 0;
911
912   update_screen(&current_line, &temporary_line, 0, nb_lines, labels, cursor_position, pattern);
913
914   do {
915
916     key = getch();
917
918     int motion = 0;
919
920     if(key >= ' ' && key <= '~') { // Insert character
921       insert_char(pattern, &cursor_position, key);
922     }
923
924     else if(key == KEY_BACKSPACE ||
925             key == '\010' || // ^H
926             key == '\177') { // ^?
927       backspace_char(pattern, &cursor_position);
928     }
929
930     else if(key == KEY_DC ||
931             key == '\004') { // ^D
932       delete_char(pattern, &cursor_position);
933     }
934
935     else if(key == KEY_HOME) {
936       current_line = 0;
937     }
938
939     else if(key == KEY_END) {
940       current_line = nb_lines - 1;
941     }
942
943     else if(key == KEY_NPAGE) {
944       motion = 10;
945     }
946
947     else if(key == KEY_PPAGE) {
948       motion = -10;
949     }
950
951     else if(key == KEY_DOWN ||
952             key == '\016') { // ^N
953       motion = 1;
954     }
955
956     else if(key == KEY_UP ||
957             key == '\020') { // ^P
958       motion = -1;
959     }
960
961     else if(key == KEY_LEFT ||
962             key == '\002') { // ^B
963       if(cursor_position > 0) cursor_position--;
964       else error_feedback();
965     }
966
967     else if(key == KEY_RIGHT ||
968             key == '\006') { // ^F
969       if(pattern[cursor_position]) cursor_position++;
970       else error_feedback();
971     }
972
973     else if(key == '\001') { // ^A
974       cursor_position = 0;
975     }
976
977     else if(key == '\005') { // ^E
978       cursor_position = strlen(pattern);
979     }
980
981     else if(key == '\022') { // ^R
982       use_regexp = !use_regexp;
983     }
984
985     else if(key == '\011') { // ^I
986       case_sensitive = !case_sensitive;
987     }
988
989     else if(key == '\025') { // ^U
990       kill_before_cursor(pattern, &cursor_position);
991     }
992
993     else if(key == '\013') { // ^K
994       kill_after_cursor(pattern, &cursor_position);
995     }
996
997     update_screen(&current_line, &temporary_line, motion,
998                   nb_lines, labels, cursor_position, pattern);
999
1000   } while(key != '\007' && // ^G
1001           key != '\033' && // ^[ (escape)
1002           key != '\n' &&
1003           key != KEY_ENTER);
1004
1005   echo();
1006   endwin();
1007
1008   //////////////////////////////////////////////////////////////////////
1009   // Here we come back to standard display
1010
1011   if((key == KEY_ENTER || key == '\n')) {
1012
1013     if(output_to_vt_buffer) {
1014       if(temporary_line >= 0 && temporary_line < nb_lines) {
1015         inject_into_tty_buffer(lines[temporary_line]);
1016       }
1017     }
1018
1019     if(output_filename[0]) {
1020       ofstream out(output_filename);
1021       if(out.fail()) {
1022         cerr << "Can not open " << output_filename << " for writing." << endl;
1023         exit(1);
1024       } else {
1025         if(temporary_line >= 0 && temporary_line < nb_lines) {
1026           out << lines[temporary_line] << endl;
1027         } else {
1028           out << endl;
1029         }
1030       }
1031       out.flush();
1032     }
1033   } else {
1034     cout << "Aborted." << endl;
1035   }
1036
1037   for(int l = 0; l < nb_lines; l++) {
1038     delete[] lines[l];
1039     delete[] labels[l];
1040   }
1041
1042   delete[] labels;
1043   delete[] lines;
1044   delete[] title;
1045
1046   exit(0);
1047 }