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