String lineSep = "\n";

public String formatRuby(String source){
  BufferedReader pbr = null;
  BufferedWriter pbw = null;
  StringBuffer result = new StringBuffer();
  try {
    Runtime runtime = Runtime.getRuntime();
    // System.out.println("sqlfmt -i" + buffer.getTabSize() + " -o ");
    // Process p = runtime.exec("ruby \"" + MiscUtilities.constructPath(jEdit.getSettingsDirectory() ,"../bin/ruby/beautify_funa.rb\"") + " " + buffer.getIndentSize());
    
    String[] command = new String[3];
    command[0] = "ruby";
    command[1] = MiscUtilities.constructPath(jEdit.getSettingsDirectory() ,"../bin/Ruby/beautify_funa.rb");
    command[2] = Integer.toString(buffer.getIndentSize());
    Process p = runtime.exec(command);
    
    pbr = new BufferedReader(new InputStreamReader(p.getInputStream()));
    pbw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    
    pbw.write(source);
    pbw.flush();
    pbw.close();
    
    String line = null;
    while ( (line = pbr.readLine()) != null){
      result.append(line);
      result.append(lineSep);
      // result.append(buffer.getProperty(Buffer.LINESEP));
    }
    pbr.close();
    
  } catch (Exception e){
    e.printStackTrace();
  } finally {
    try {
      if (pbr != null) pbr.close();
      if (pbw != null) pbw.close();
    } catch (Exception e){
      e.printStackTrace();
    }
  }
  return result.toString();
}

/*** メイン処理 ***/
void main() {
  
  sel = textArea.getSelection();
  int startIndex = 0;
  int endIndex = textArea.getText().length();
  if (sel.length > 0) {
    startIndex = sel[0].getStart();
    endIndex = sel[0].getEnd();
  }
  
  textArea.selectNone();
  try {
    String result = formatRuby(textArea.getText().substring(startIndex, endIndex));
    if (!result.equals("")){
      int caretPos = textArea.getCaretPosition();
      int caretLine = textArea.getCaretLine();
      int endPos = textArea.getLineEndOffset(caretLine);
      
      buffer.remove(startIndex, endIndex - startIndex);
      buffer.insert(startIndex, result);
      
      int newPos = textArea.getLineEndOffset(caretLine) - (endPos - caretPos);
      if (newPos > 0 && newPos < textArea.getText().length()){
        textArea.setCaretPosition(newPos);
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  
}

main();

