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