//  "Find"
// This macro searches for text in files contained in a directory.
// It is built into ImageJ as the Plugins>Utilities>Search command.

  extensions = newArray(".java", ".txt", ".ijm", ".html");
  requires("1.35r");
  Dialog.create("Find");
  if (getVersion>"1.37a")
      Dialog.addString("Find:", "", 20);
  else
      Dialog.addString("Find:", "");
  Dialog.addCheckbox("Ignore Case", false);
  Dialog.addCheckbox("Search Contents", true);
  Dialog.addCheckbox("Search macros folder", false);
  Dialog.show();
  str = Dialog.getString();
  ignore = Dialog.getCheckbox();
  contents = Dialog.getCheckbox();
  macros = Dialog.getCheckbox();
  if (macros)
    dir = getDirectory("macros");
  else
      dir = getDirectory("Choose a Directory ");
  if (ignore)
      str = toLowerCase(str);
  find(dir); 

  function find(dir) {
      list = getFileList(dir);
      for (i=0; i<list.length; i++) {
          showProgress(i, list.length);
          if (endsWith(list[i], "/"))
              find(""+dir+list[i]);
          else if (contents && valid(list[i])) {
              s = File.openAsString(dir+list[i]);
              s2 = s;
              if (ignore)
                  s2 = toLowerCase(s);
              if (indexOf(s2,str)!=-1) {
                  print("");
                  print(dir+list[i]);
                  lines = split(s, "\n");
                  n = 0;
                  for (j=0; j<lines.length; j++) {
                      line = lines[j];
                      line2 = line;
                      if (ignore) line2 = toLowerCase(line);
                      if (indexOf(line2,str)!=-1 && n<8) {
                          print((j+1)+": "+line);
                          n++;
                      }
                 } // for
              } // if match
          } else {
              name = list[i];
              if (ignore)
                  name = toLowerCase(name);
              if (indexOf(name,str)!=-1) { // string in name?
                  print("");
                  print(dir+list[i]);
              }
          }
      }
  }

  function valid(name) {
      for (i=0; i<extensions.length; i++) {
         if (endsWith(name, extensions[i]))
             return true;
      }
      return false;
  }

