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