Automatic commit
[selector.git] / selector.cc
index ab793b0..f15154f 100644 (file)
+/*
+ *  selector is a simple shell command for selection of strings with a
+ *  dynamic pattern-matching.
+ *
+ *  Copyright (c) 2008 Francois Fleuret
+ *  Written by Francois Fleuret <francois.fleuret@idiap.ch>
+ *
+ *  This file is part of selector.
+ *
+ *  selector is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License version 3 as
+ *  published by the Free Software Foundation.
+ *
+ *  selector is distributed in the hope that it will be useful, but
+ *  WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with selector.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
 
-///////////////////////////////////////////////////////////////////////////
-// START_IP_HEADER                                                       //
-//                                                                       //
-// This program is free software: you can redistribute it and/or modify  //
-// it under the terms of the version 3 of the GNU General Public License //
-// as published by the Free Software Foundation.                         //
-//                                                                       //
-// This program is distributed in the hope that it will be useful, but   //
-// WITHOUT ANY WARRANTY; without even the implied warranty of            //
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      //
-// General Public License for more details.                              //
-//                                                                       //
-// You should have received a copy of the GNU General Public License     //
-// along with this program. If not, see <http://www.gnu.org/licenses/>.  //
-//                                                                       //
-// Written by and Copyright (C) Francois Fleuret                         //
-// Contact <francois.fleuret@idiap.ch> for comments & bug reports        //
-//                                                                       //
-// END_IP_HEADER                                                         //
-///////////////////////////////////////////////////////////////////////////
+/*
+
+  Here is the magical shell script for a smart bash-history. Note that
+  the line remains in /tmp/selector.out, which may be a scurity concern.
+
+  ./selector -f ~/.bash_history
+  OLD_SETTINGS=`stty -g`
+  stty -echo raw
+  writevt `tty` "`cat /tmp/selector.out`"
+  stty ${OLD_SETTINGS}
+
+*/
 
 #include <stdio.h>
 #include <ncurses.h>
 #include <iostream>
 #include <fstream>
 #include <string.h>
+#include <stdlib.h>
 
 using namespace std;
 
-void build_display(char **choices, char *regexp) {
-  clear();         // Cleaning the window
-  refresh();       // After doing something on the display, we refresh it
-  for(int y = 0; y < 10; y++) {
-    printw("y = %d\n", y);
+int buffer_size = 1024;
+int nb_lines_max = 100000;
+char pattern_separator = ';';
+
+int match(char *string, int nb_patterns, char **patterns) {
+  for(int n = 0; n < nb_patterns; n++) {
+    if(strstr(string, patterns[n]) == 0) return 0;
   }
-  printw("regexp = \"%s\"", regexp);
+  return 1;
 }
 
-int main(int argc, char **argv) {
-  int dummy, xpos, ypos;
-  const int buffer_size = 1024;
-  const int nb_lines_max = 1000;
+void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
+  if(n_opt + n >= argc) {
+    cerr << "Missing argument for " << argv[n_opt] << ". Expecting " << help << "." << endl;
+    exit(1);
+  }
+}
+
+int previous_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
+  int line = current_line - 1;
+  while(line >= 0 && !match(lines[line], nb_patterns, patterns)) line--;
+  return line;
+}
+
+int next_visible(int current_line, int nb_lines, char **lines, int nb_patterns, char **patterns) {
+  int line = current_line + 1;
+  while(line < nb_lines && !match(lines[line], nb_patterns, patterns)) line++;
+
+  if(line < nb_lines)
+    return line;
+  else
+    return -1;
+}
+
+void update_screen(int *current_line, int *temporary_line, int motion,
+                   int nb_lines, char **lines,
+                   char *pattern_list,
+                   int noblink) {
+
+  char buffer[buffer_size];
+
+  // We split the pattern list into individual patterns
+
+  int nb_patterns = 1;
+
+  for(char *s = pattern_list; *s; s++) {
+    if(*s == pattern_separator) {
+      nb_patterns++;
+    }
+  }
+
+  char splitted_patterns[strlen(pattern_list) + 1];
+  char *patterns[nb_patterns];
+
+  strcpy(splitted_patterns, pattern_list);
+
+  int n = 0;
+  char *last_pattern_start = splitted_patterns;
+  for(char *s = splitted_patterns; n < nb_patterns; s++) {
+    if(*s == pattern_separator || *s == '\0') {
+      *s = '\0';
+      patterns[n++] = last_pattern_start;
+      last_pattern_start = s + 1;
+    }
+  }
+
+  // We now take care of printing the lines per se
+
+  int console_width = getmaxx(stdscr);
+  int console_height = getmaxy(stdscr);
+
+  int nb_printed_lines = 1;
+
+  // First, we find a visible line. In priority: The current, or the
+  // first visible after it, or the first visible before it.
+
+  int new_line;
+  if(match(lines[*current_line], nb_patterns, patterns)) {
+    new_line = *current_line;
+  } else {
+    new_line = next_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
+    if(new_line < 0) {
+      new_line = previous_visible(*current_line, nb_lines, lines, nb_patterns, patterns);
+    }
+  }
+
+  // If we found a visible line and we should move, let's move
+
+  if(new_line >= 0 && motion != 0) {
+    int l = new_line;
+    l += motion;
+
+    if(motion > 0) {
+      // We want to go down, let's find the first visible line below
+      l = next_visible(new_line, nb_lines, lines, nb_patterns, patterns);
+      if(l >= 0) {
+        new_line = l;
+      }
+    } else {
+      // We want to go up, let's find the first visible line above
+      l = previous_visible(new_line, nb_lines, lines, nb_patterns, patterns);
+      if(l >= 0) {
+        new_line = l;
+      }
+    }
+  }
+
+  if(!noblink) {
+    clear();
+  }
+
+  use_default_colors();
+
+  addstr("\n");
+
+  // Here new_line is either a line number matching the patterns, or -1
+
+  if(new_line >= 0) {
+
+    int first_line = new_line, last_line = new_line, nb_match = 1;
+
+    // We find the first and last line to show, so that the total of
+    // visible lines between them (them include) is console_height - 1
+
+    while(nb_match < console_height-1 && (first_line > 0 || last_line < nb_lines - 1)) {
 
+      if(first_line > 0) {
+        first_line--;
+        while(first_line > 0 && !match(lines[first_line], nb_patterns, patterns)) {
+          first_line--;
+        }
+        if(match(lines[first_line], nb_patterns, patterns)) {
+          nb_match++;
+        }
+      }
+
+      if(last_line < nb_lines - 1) {
+        last_line++;
+        while(last_line < nb_lines - 1 && !match(lines[last_line], nb_patterns, patterns)) {
+          last_line++;
+        }
+
+        if(match(lines[last_line], nb_patterns, patterns)) {
+          nb_match++;
+        }
+      }
+    }
+
+    // Now we display them
+
+    for(int l = first_line; l <= last_line; l++) {
+      if(match(lines[l], nb_patterns, patterns)) {
+        int k = 0;
+
+        while(lines[l][k] && k < buffer_size - 2 && k < console_width - 2) {
+          buffer[k] = lines[l][k];
+          k++;
+        }
+
+        if(noblink || l == new_line) {
+          while(k < console_width) {
+            buffer[k++] = ' ';
+          }
+        }
+
+        buffer[k++] = '\n';
+        buffer[k++] = '\0';
+
+        if(l == new_line) {
+          attron(COLOR_PAIR(2));
+          addnstr(buffer, console_width);
+          attroff(COLOR_PAIR(2));
+        } else {
+          addnstr(buffer, console_width);
+        }
+
+        nb_printed_lines++;
+      }
+    }
+
+    *temporary_line = new_line;
+    if(motion != 0) {
+      *current_line = new_line;
+    }
+  }
+
+  if(noblink) { // Erase the rest of the window. That's slightly ugly.
+    int k = 0;
+    while(k < console_width) {
+      buffer[k++] = ' ';
+    }
+    buffer[k++] = '\n';
+    buffer[k++] = '\0';
+    for(int l = nb_printed_lines; l < console_height; l++) {
+      addnstr(buffer, console_width);
+    }
+  }
+
+  // Draw the modeline
+
+  sprintf(buffer, "%d/%d pattern: %s",
+          nb_printed_lines - 1,
+          nb_lines,
+          pattern_list);
+
+  for(int k = strlen(buffer); k < console_width; k++) buffer[k] = ' ';
+  buffer[console_width] = '\0';
+
+  move(0, 0);
+  attron(COLOR_PAIR(1));
+  addnstr(buffer, console_width);
+  attroff(COLOR_PAIR(1));
+
+  refresh();       // After doing something on the display, we refresh it
+}
+
+//////////////////////////////////////////////////////////////////////
+
+int main(int argc, char **argv) {
   char buffer[buffer_size];
   char *lines[nb_lines_max];
+  int noblink = 0;
 
-  ifstream file(argv[1]);
+  char input_filename[buffer_size], output_filename[buffer_size];
+  strcpy(input_filename, "/dev/stdin");
+  strcpy(output_filename, "/tmp/selector.out");
 
-  if(argc != 2) {
-    cerr << argv[0] << " <file>" << endl;
-    return 1;
+  int i = 1;
+  while(i < argc) {
+    if(strcmp(argv[i], "-o") == 0) {
+      check_opt(argc, argv, i, 1, "<output filename>");
+      strncpy(output_filename, argv[i+1], buffer_size);
+      i += 2;
+    }
+
+    else if(strcmp(argv[i], "-s") == 0) {
+      check_opt(argc, argv, i, 1, "<pattern separator>");
+      pattern_separator = argv[i+1][0];
+      i += 2;
+    }
+
+    else if(strcmp(argv[i], "-f") == 0) {
+      check_opt(argc, argv, i, 1, "<input filename>");
+      strncpy(input_filename, argv[i+1], buffer_size);
+      i += 2;
+    }
+
+    else if(strcmp(argv[i], "-b") == 0) {
+      noblink = 1;
+      i++;
+    }
+
+    else if(strcmp(argv[i], "-l") == 0) {
+      check_opt(argc, argv, i, 1, "<maximum number of lines>");
+      nb_lines_max = atoi(argv[i+1]);
+      i += 2;
+    }
+
+    else {
+      cerr << argv[0] << " [-h] [-o <output filename>] [-b] [-l <max number of lines>] [-s <pattern separator>]" << endl;
+      if(strcmp(argv[i], "-h") == 0) {
+        exit(0);
+      } else {
+        exit(1);
+      }
+    }
   }
 
+  ifstream file(input_filename);
+
   if(file.fail()) {
-    cerr << "Can not open \""
-         << argv[1]
-         << "\""
-         << endl;
+    cerr << "Can not open \"" << input_filename << "\"" << endl;
     return 1;
   }
 
@@ -65,48 +323,86 @@ int main(int argc, char **argv) {
     file.getline(buffer, buffer_size);
     lines[nb_lines] = new char[strlen(buffer) + 1];
     strcpy(lines[nb_lines], buffer);
+    nb_lines++;
   }
 
-  char regexp[buffer_size]="";
-  int regexp_point;
-  regexp_point = 0;
+  char patterns[buffer_size];
+  patterns[0] = '\0';
+  int patterns_point;
+  patterns_point = 0;
 
-  initscr();        // Necessary to start a curses session
+  initscr();
 
-  if (has_colors()) {
-    cout << "You can use color on this terminal" << endl;
-  } else {
-    cout << "No colors." << endl;
+  if(!has_colors()) {
+    cerr << "No colors." << endl;
     return 1;
   }
 
-  noecho();        // I don't want echo when I press a key
-  curs_set(0);     // I don't want to see the cursor
+  noecho();
+  curs_set(0);
+  keypad(stdscr, TRUE);
 
-  start_color();   // We will use colors
-  init_pair(1, COLOR_RED, COLOR_BLACK); // red on black for error messages
+  start_color();
+  // init_pair(1, COLOR_WHITE, COLOR_BLACK);
+  init_pair(1, COLOR_WHITE, COLOR_GREEN);
+  init_pair(2, COLOR_BLACK, COLOR_YELLOW);
 
-  // attron(COLOR_PAIR(1));        // Let's print something in red on black
-  // printw("Hello world\n");      // That's how we print something!
-  // attroff(COLOR_PAIR(1));       // Let's get back to default colors!
-
-  printw("Press a key to contine\n");
   int key;
 
+  int current_line = 0, temporary_line = 0;
+
+  update_screen(&current_line, &temporary_line, 0, nb_lines, lines, patterns, noblink);
+
   do {
-    build_display(0, regexp);
+
     key = getch();
-    regexp[regexp_point++] = key;
-    regexp[regexp_point] = '\0';
-  } while(key != 'q');
 
-  echo();         // We want to have echo
-  curs_set(1);    // We want to see the cursor again
-  endwin();       // Back to normal
+    int motion = 0;
+
+    if(key >= ' ' && key <= 'z') {
+      patterns[patterns_point++] = key;
+      patterns[patterns_point] = '\0';
+    }
+
+    else if(key == KEY_BACKSPACE || key == KEY_DC || key == '\b') {
+      if(patterns_point > 0) {
+        patterns_point--;
+        patterns[patterns_point] = '\0';
+      }
+    }
+
+    else if(key == KEY_UP || key == '\10') {
+      motion = -1;
+    }
+
+    else if(key == KEY_DOWN || key == '\ e') {
+      motion = 1;
+    }
+
+    update_screen(&current_line, &temporary_line, motion,
+                  nb_lines, lines, patterns, noblink);
+  } while(key != '\n' && key != KEY_ENTER && key != '\a');
+
+  echo();
+  curs_set(1);
+  endwin();
+
+  ofstream out(output_filename);
+  if(out.fail()) {
+    cerr << "Can not open " << output_filename << " for writing." << endl;
+    exit(1);
+  } else {
+    if((key == KEY_ENTER || key == '\n') && temporary_line >= 0 && temporary_line < nb_lines) {
+      out << lines[temporary_line] << endl;
+    } else {
+      out << endl;
+    }
+    out.flush();
+  }
 
   for(int l = 0; l < nb_lines; l++) {
     delete[] lines[l];
   }
 
-  return 0;
+  exit(0);
 }