예제 #1
0
  private void goToSelectedNode(int mode) {
    TreePath path = resultTree.getSelectionPath();
    if (path == null) return;

    DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
    Object value = node.getUserObject();

    // do nothing if clicked "foo (showing n occurrences in m files)"
    if (node.getParent() != resultTreeRoot && value instanceof HyperSearchNode) {
      HyperSearchNode n = (HyperSearchNode) value;
      Buffer buffer = n.getBuffer(view);
      if (buffer == null) return;

      EditPane pane;

      switch (mode) {
        case M_OPEN:
          pane = view.goToBuffer(buffer);
          break;
        case M_OPEN_NEW_VIEW:
          pane = jEdit.newView(view, buffer, false).getEditPane();
          break;
        case M_OPEN_NEW_PLAIN_VIEW:
          pane = jEdit.newView(view, buffer, true).getEditPane();
          break;
        case M_OPEN_NEW_SPLIT:
          pane = view.splitHorizontally();
          break;
        default:
          throw new IllegalArgumentException("Bad mode: " + mode);
      }

      n.goTo(pane);
    }
  } // }}}
  public CompleteWordList(
      View view,
      String word,
      Vector completions,
      Point location,
      String noWordSep,
      boolean isGlobalSearch) {
    super(view);
    this.isGlobalSearch = isGlobalSearch;
    this.noWordSep = noWordSep;

    setContentPane(
        new JPanel(new BorderLayout()) {
          /**
           * Returns if this component can be traversed by pressing the Tab key. This returns false.
           */
          public boolean isManagingFocus() {
            return false;
          }

          /** Makes the tab key work in Java 1.4. */
          public boolean getFocusTraversalKeysEnabled() {
            return false;
          }
        });

    this.view = view;
    this.textArea = view.getTextArea();
    this.buffer = view.getBuffer();
    this.word = word;

    words = new JList(completions);

    words.setVisibleRowCount(Math.min(completions.size(), 8));

    words.addMouseListener(new MouseHandler());
    words.setSelectedIndex(0);
    words.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    words.setCellRenderer(new Renderer());

    // stupid scrollbar policy is an attempt to work around
    // bugs people have been seeing with IBM's JDK -- 7 Sep 2000
    JScrollPane scroller =
        new JScrollPane(
            words, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    getContentPane().add(scroller, BorderLayout.CENTER);

    GUIUtilities.requestFocus(this, words);

    pack();
    setLocation(location);
    show();

    KeyHandler keyHandler = new KeyHandler();
    addKeyListener(keyHandler);
    words.addKeyListener(keyHandler);
    view.setKeyEventInterceptor(keyHandler);
  }
  /** Get local members and Haxe classes. */
  protected void getCtagsCompletions(View view, List<CompletionCandidate> candidates) {
    // Ctags cannot current complete dot completion, save that for the compiler.
    if (CompletionUtil.isDotCompletion(view)) {
      return;
    }

    List<CompletionCandidate> localCandidates = new ArrayList<CompletionCandidate>();
    String prefix = CompletionUtil.getCompletionPrefix(view);
    prefix = prefix == null ? "" : prefix;

    // If the prefix is all lower case, ignore case
    boolean islowercase = prefix.toLowerCase().equals(prefix);
    // Local members
    String q =
        (islowercase ? TagIndex._NAME_LOWERCASE_FLD : TagIndex._NAME_FLD)
            + ":"
            + prefix
            + "*"
            + " AND "
            + TagIndex._PATH_FLD
            + ":"
            + view.getBuffer().getPath()
            + " AND (kind:function OR kind:variable)";

    Vector<Tag> tags = CtagsInterfacePlugin.runScopedQuery(view, q);

    for (Tag t : tags) {
      if (t.getName().length() > 1) {
        localCandidates.add(new CtagsCompletionCandidate(t));
      }
    }

    TextArea ta = view.getTextArea();
    // If we're not dot-completing, look for classes
    if (prefix.length() > 0
        && !ta.getText(ta.getCaretPosition() - 1 - prefix.length(), 1).equals(".")) {
      q =
          (islowercase ? TagIndex._NAME_LOWERCASE_FLD : TagIndex._NAME_FLD)
              + ":"
              + prefix
              + "* AND (kind:class OR kind:enum)"
              + " AND "
              + TagIndex._PATH_FLD
              + ":*.hx";
      tags = CtagsInterfacePlugin.runScopedQuery(view, q);
      Set<String> classes = new HashSet<String>();
      for (Tag t : tags) {
        if (!classes.contains(t.getName()) && !prefix.equals(t.getName())) {
          localCandidates.add(new CtagsCompletionCandidate(t));
          classes.add(t.getName());
        }
      }
    }

    Collections.sort(localCandidates);
    candidates.addAll(localCandidates);
  }
예제 #4
0
  /** {@inheritDoc} */
  public ProjectFile getActiveFile() {
    View view = jEdit.getActiveView();

    if (view != null) {
      Buffer buffer = view.getBuffer();

      return new JEditProjectFile(this, buffer);
    }

    return null;
  }
예제 #5
0
 public void update() {
   Buffer buffer = view.getBuffer();
   String wrap = buffer.getStringProperty("wrap");
   if (wrap.equals("none")) this.wrap.setText("-");
   else if (wrap.equals("hard")) this.wrap.setText("H");
   else if (wrap.equals("soft")) this.wrap.setText("S");
 }
  // {{{ record() method
  private static void record(
      View view, String action, boolean replaceAction, boolean recordFileSet) {
    Macros.Recorder recorder = view.getMacroRecorder();

    if (recorder != null) {
      recorder.record(
          "SearchAndReplace.setSearchString(\""
              + StandardUtilities.charsToEscapes(search)
              + "\");");

      if (replaceAction) {
        recorder.record(
            "SearchAndReplace.setReplaceString(\""
                + StandardUtilities.charsToEscapes(replace)
                + "\");");
        recorder.record("SearchAndReplace.setBeanShellReplace(" + beanshell + ");");
      } else {
        // only record this if doing a find next
        recorder.record("SearchAndReplace.setAutoWrapAround(" + wrap + ");");
        recorder.record("SearchAndReplace.setReverseSearch(" + reverse + ");");
      }

      recorder.record("SearchAndReplace.setWholeWord(" + wholeWord + ");");
      recorder.record("SearchAndReplace.setIgnoreCase(" + ignoreCase + ");");
      recorder.record("SearchAndReplace.setRegexp(" + regexp + ");");

      if (recordFileSet) {
        recorder.record("SearchAndReplace.setSearchFileSet(" + fileset.getCode() + ");");
      }

      recorder.record("SearchAndReplace." + action + ';');
    }
  } // }}}
  /**
   * Finds the next instance of the search string in the specified buffer.
   *
   * @param view The view
   * @param buffer The buffer
   * @param start Location where to start the search
   * @param firstTime See {@link
   *     SearchMatcher#nextMatch(CharSequence,boolean,boolean,boolean,boolean)}.
   * @since jEdit 4.1pre7
   */
  public static boolean find(
      View view, Buffer buffer, int start, boolean firstTime, boolean reverse) throws Exception {

    EditBus.send(new PositionChanging(view.getEditPane()));

    SearchMatcher matcher = getSearchMatcher();
    if (matcher == null) {
      view.getToolkit().beep();
      return false;
    }

    CharSequence text;
    boolean startOfLine;
    boolean endOfLine;
    if (reverse) {
      text = new ReverseCharSequence(buffer.getSegment(0, start));
      startOfLine = true;
      endOfLine = (buffer.getLineEndOffset(buffer.getLineOfOffset(start)) - 1 == start);
    } else {
      text = buffer.getSegment(start, buffer.getLength() - start);
      startOfLine = (buffer.getLineStartOffset(buffer.getLineOfOffset(start)) == start);
      endOfLine = true;
    }

    String noWordSep = buffer.getStringProperty("noWordSep");
    matcher.setNoWordSep(noWordSep);
    SearchMatcher.Match match = matcher.nextMatch(text, startOfLine, endOfLine, firstTime, reverse);
    if (match != null) {
      jEdit.commitTemporary(buffer);
      view.setBuffer(buffer, true);
      JEditTextArea textArea = view.getTextArea();

      if (reverse) {
        textArea.setSelection(new Selection.Range(start - match.end, start - match.start));
        // make sure end of match is visible
        textArea.scrollTo(start - match.start, false);
        textArea.moveCaretPosition(start - match.end);
      } else {
        textArea.setSelection(new Selection.Range(start + match.start, start + match.end));
        textArea.moveCaretPosition(start + match.end);
        // make sure start of match is visible
        textArea.scrollTo(start + match.start, false);
      }

      return true;
    } else return false;
  } // }}}
예제 #8
0
 /**
  * insert text.
  *
  * <p>/** invokes an Action.
  *
  * @param view The view to run the script in.
  * @param node The node item
  * @param text The node content to be inserted.
  */
 public static void insertText(View view, String text, XTreeNode node) {
   CommandQueue queue = new CommandQueue();
   ScriptContext context = new ScriptContext(view, node, queue);
   Buffer buffer = view.getBuffer();
   buffer.beginCompoundEdit();
   InsertTextCommand.insertText(text, context);
   buffer.endCompoundEdit();
 }
예제 #9
0
  // {{{ userInput() method
  protected void userInput(char ch) {
    lastActionCount = 0;

    JEditTextArea textArea = view.getTextArea();

    /* Buffer buffer = view.getBuffer();
    if(!buffer.insideCompoundEdit())
    	buffer.beginCompoundEdit(); */

    if (repeatCount == 1) textArea.userInput(ch);
    else {
      // stop people doing dumb stuff like C+ENTER 100 C+n
      if (repeatCount > REPEAT_COUNT_THRESHOLD) {
        Object[] pp = {String.valueOf(ch), repeatCount};

        if (GUIUtilities.confirm(
                view,
                "large-repeat-count.user-input",
                pp,
                JOptionPane.WARNING_MESSAGE,
                JOptionPane.YES_NO_OPTION)
            != JOptionPane.YES_OPTION) {
          repeatCount = 1;
          view.getStatus().setMessage(null);
          return;
        }
      }

      JEditBuffer buffer = view.getBuffer();
      try {
        if (repeatCount != 1) buffer.beginCompoundEdit();
        for (int i = 0; i < repeatCount; i++) textArea.userInput(ch);
      } finally {
        if (repeatCount != 1) buffer.endCompoundEdit();
      }
    }

    Macros.Recorder recorder = view.getMacroRecorder();

    if (recorder != null) {
      recorder.recordInput(repeatCount, ch, textArea.isOverwriteEnabled());
    }

    repeatCount = 1;
  } // }}}
예제 #10
0
 public static Buffer createFeatureBuffer() {
   View view = jEdit.getActiveView();
   String parent = null;
   if (view != null) {
     Buffer buffer = view.getBuffer();
     parent = buffer.getDirectory();
   }
   if (parent == null) {
     parent = System.getProperty("user.home");
   }
   VFS vfs = VFSManager.getVFSForPath(parent);
   if ((vfs.getCapabilities() & VFS.WRITE_CAP) == 0) {
     // cannot write on that VFS, creating untitled buffer in home directory
     parent = System.getProperty("user.home");
   }
   Buffer buffer = jEdit.openTemporary(view, tempPath(), getNextFeatureTemp(), true, null);
   jEdit.commitTemporary(buffer);
   return buffer;
 }
예제 #11
0
 /**
  * runs an XInsertScript.
  *
  * @param view The view to run the script in.
  * @param script The node content to be run as a script.
  * @param node The node from where to start searching for variable substitutions
  */
 public static void runXInsertScript(View view, String script, XTreeNode node) {
   CommandQueue queue = new CommandQueue();
   Buffer buffer = view.getBuffer();
   buffer.beginCompoundEdit();
   try {
     char[] chars = script.toCharArray();
     int start = 0;
     for (int i = start; i < chars.length; i++) {
       switch (chars[i]) {
         case '{':
           if (chars[i + 1] == '$'
               || chars[i + 1] == '@'
               || chars[i + 1] == '!'
               || chars[i + 1] == '%'
               || chars[i + 1] == '#'
               || chars[i + 1] == '*'
               || chars[i + 1] == '&') {
             // Log.log(Log.DEBUG, XScripter.class, "Adding insert text (\"" + text + "\") command
             // to queue");
             // Insert the text between the last command and this one
             String text = script.substring(start, i);
             queue.add(new InsertTextCommand(text));
             int j;
             inner:
             for (j = i; j < chars.length; j++) {
               if (chars[j] == '}' && chars[j - 1] != '\\') { // If end of command
                 String cmd = script.substring(i + 1, j);
                 cmd = Utilities.replace(cmd, "\\}", "}");
                 queue.add(getCommand(view, node, cmd)); // Add this command to queue
                 break inner;
               }
             }
             i = j; // set parsing to continue at the end of the command
             start = j + 1; // set the start position for the next insert text command
           }
           break;
       }
     }
     String remainder = script.substring(start, script.length());
     queue.add(new InsertTextCommand(remainder)); // Insert the text left over
     // Run commands in queue
     ScriptContext context = new ScriptContext(view, node, queue);
     queue.executeAll(context);
   } catch (StringIndexOutOfBoundsException e) {
     doError("Unknown", "Missing \"}\"");
     return;
   } catch (Exception e) {
     doError("Unknown", "Syntax error in script - Execution Aborted", e);
     return;
   } finally {
     buffer.endCompoundEdit();
   }
 } // }}}
예제 #12
0
  // {{{ invokeReadNextChar() method
  protected void invokeReadNextChar(char ch) {
    JEditBuffer buffer = view.getBuffer();

    /* if(buffer.insideCompoundEdit())
    buffer.endCompoundEdit(); */

    String charStr = StandardUtilities.charsToEscapes(String.valueOf(ch));

    // this might be a bit slow if __char__ occurs a lot
    int index;
    while ((index = readNextChar.indexOf("__char__")) != -1) {
      readNextChar =
          readNextChar.substring(0, index)
              + '\''
              + charStr
              + '\''
              + readNextChar.substring(index + 8);
    }

    Macros.Recorder recorder = view.getMacroRecorder();
    if (recorder != null) recorder.record(getRepeatCount(), readNextChar);

    view.getStatus().setMessage(null);

    if (getRepeatCount() != 1) {
      try {
        buffer.beginCompoundEdit();

        BeanShell.eval(
            view,
            BeanShell.getNameSpace(),
            "for(int i = 1; i < " + getRepeatCount() + "; i++)\n{\n" + readNextChar + "\n}");
      } finally {
        buffer.endCompoundEdit();
      }
    } else BeanShell.eval(view, BeanShell.getNameSpace(), readNextChar);

    readNextChar = null;
  } // }}}
예제 #13
0
  private String getPrevOrNextFile(View view, String path, Direction direction) {
    if (files == null) files = _getFiles(view);

    if (files == null || files.length == 0) return null;

    if (path == null) {
      path = view.getBuffer().getSymlinkPath();
      VFS vfs = VFSManager.getVFSForPath(path);
      boolean ignoreCase = ((vfs.getCapabilities() & VFS.CASE_INSENSITIVE_CAP) != 0);

      for (int i = 0; i < files.length; i++) {
        if (StandardUtilities.compareStrings(files[i], path, ignoreCase) == 0) {
          return path;
        }
      }

      if (direction == Direction.NEXT) {
        return getFirstFile(view);
      } else {
        return getLastFile(view);
      }
    } else {
      // -1 so that the last isn't checked
      VFS vfs = VFSManager.getVFSForPath(path);
      boolean ignoreCase = ((vfs.getCapabilities() & VFS.CASE_INSENSITIVE_CAP) != 0);

      if (direction == Direction.NEXT
          && StandardUtilities.compareStrings(files[files.length - 1], path, ignoreCase) == 0) {
        // Going forward and already at the last file
        return null;
      } else if (direction == Direction.PREV
          && StandardUtilities.compareStrings(files[0], path, ignoreCase) == 0) {
        // Going backward and already at the first file
        return null;
      }

      for (int i = 0; i < files.length - 1; i++) {
        if (StandardUtilities.compareStrings(files[i], path, ignoreCase) == 0) {
          if (direction == Direction.NEXT) return files[i + 1];
          else {
            if (i == 0) return files[files.length - 1];
            return files[i - 1];
          }
        }
      }

      return null;
    }
  } // }}}
예제 #14
0
  /**
   * Performs a HyperSearch.
   *
   * @param view The view
   * @param selection If true, will only search in the current selection. Note that the file set
   *     must be the current buffer file set for this to work.
   * @since jEdit 4.0pre1
   */
  public static boolean hyperSearch(View view, boolean selection) {
    // component that will parent any dialog boxes
    Component comp = SearchDialog.getSearchDialog(view);
    if (comp == null) comp = view;

    record(view, "hyperSearch(view," + selection + ')', false, !selection);

    view.getDockableWindowManager().addDockableWindow(HyperSearchResults.NAME);
    HyperSearchResults results =
        (HyperSearchResults) view.getDockableWindowManager().getDockable(HyperSearchResults.NAME);
    results.searchStarted();

    try {
      SearchMatcher matcher = getSearchMatcher();
      if (matcher == null) {
        view.getToolkit().beep();
        results.searchFailed();
        return false;
      }

      Selection[] s;
      if (selection) {
        s = view.getTextArea().getSelection();
        if (s == null) {
          results.searchFailed();
          return false;
        }
      } else s = null;
      ThreadUtilities.runInBackground(new HyperSearchRequest(view, matcher, results, s));
      return true;
    } catch (Exception e) {
      results.searchFailed();
      handleError(comp, e);
      return false;
    }
  } // }}}
예제 #15
0
 /**
  * invokes an Action.
  *
  * @param view The view to run the script in.
  * @param name The name of the node item
  * @param content The node content to be invoked as an action.
  */
 public static void invokeAction(View view, String name, String content) {
   // borrowed from jedit/gui/ActionBar.java
   Log.log(Log.DEBUG, XScripter.class, "Invoking action for item named = " + name);
   final int repeatCount = 1; //  is it worthwhile to make this configurable?
   final View v = view;
   final EditAction action = (content == null ? null : jEdit.getAction(content));
   if (action == null) {
     if (content != null)
       view.getStatus().setMessageAndClear(jEdit.getProperty("view.action.no-completions"));
   }
   SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           v.getInputHandler().setRepeatCount(repeatCount);
           v.getInputHandler().invokeAction(action);
         }
       });
 } // }}}
예제 #16
0
  /**
   * Finds the next occurrence of the search string.
   *
   * @param view The view
   * @return True if the operation was successful, false otherwise
   */
  public static boolean find(View view) {
    // component that will parent any dialog boxes
    Component comp = SearchDialog.getSearchDialog(view);
    if (comp == null || !comp.isShowing()) comp = view;

    String path = fileset.getNextFile(view, null);
    if (path == null) {
      GUIUtilities.error(comp, "empty-fileset", null);
      return false;
    }

    try {
      view.showWaitCursor();

      SearchMatcher matcher = getSearchMatcher();
      if (matcher == null) {
        view.getToolkit().beep();
        return false;
      }

      record(view, "find(view)", false, true);

      boolean repeat = false;
      loop:
      for (; ; ) {
        while (path != null) {
          Buffer buffer = jEdit.openTemporary(view, null, path, false);

          /* this is stupid and misleading.
           * but 'path' is not used anywhere except
           * the above line, and if this is done
           * after the 'continue', then we will
           * either hang, or be forced to duplicate
           * it inside the buffer == null, or add
           * a 'finally' clause. you decide which one's
           * worse. */
          if (reverse) {
            path = fileset.getPrevFile(view, path);
          } else {
            path = fileset.getNextFile(view, path);
          }

          if (buffer == null) continue loop;

          // Wait for the buffer to load
          if (!buffer.isLoaded()) VFSManager.waitForRequests();

          int start;

          if (view.getBuffer() == buffer && !repeat) {
            JEditTextArea textArea = view.getTextArea();
            Selection s = textArea.getSelectionAtOffset(textArea.getCaretPosition());
            if (s == null) start = textArea.getCaretPosition();
            else if (reverse) start = s.getStart();
            else start = s.getEnd();
          } else if (reverse) start = buffer.getLength();
          else start = 0;

          if (find(view, buffer, start, repeat, reverse)) return true;
        }

        if (repeat) {
          if (!BeanShell.isScriptRunning()) {
            view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.search-not-found"));

            view.getToolkit().beep();
          }
          return false;
        }

        boolean restart;

        // if auto wrap is on, always restart search.
        // if auto wrap is off, and we're called from
        // a macro, stop search. If we're called
        // interactively, ask the user what to do.
        if (wrap) {
          if (!BeanShell.isScriptRunning()) {
            view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.auto-wrap"));
            // beep if beep property set
            if (jEdit.getBooleanProperty("search.beepOnSearchAutoWrap")) {
              view.getToolkit().beep();
            }
          }
          restart = true;
        } else if (BeanShell.isScriptRunning()) {
          restart = false;
        } else {
          Integer[] args = {Integer.valueOf(reverse ? 1 : 0)};
          int result =
              GUIUtilities.confirm(
                  comp,
                  "keepsearching",
                  args,
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
          restart = (result == JOptionPane.YES_OPTION);
        }

        if (restart) {
          // start search from beginning
          path = fileset.getFirstFile(view);
          repeat = true;
        } else break loop;
      }
    } catch (Exception e) {
      handleError(comp, e);
    } finally {
      view.hideWaitCursor();
    }

    return false;
  } // }}}
  protected void getHaxeCompilerCompletions(View view, List<CompletionCandidate> candidates) {
    TextArea ta = view.getTextArea();
    int dotPosition = ta.getCaretPosition();
    if (!ta.getText(dotPosition - 1, 1).equals(".")) {
      return;
    }

    // If the caret is at a ".", use the Haxe compiler to provide completion hints
    Buffer buffer = view.getBuffer();
    // Save the file if dirty
    if (buffer.isDirty()) {
      buffer.save(view, null, false, true);
      // Wait a bit to allow the save notifications to go through and not
      // bork the reload/popup
      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    HaxeCompilerOutput output =
        HaXeSideKickPlugin.getHaxeBuildOutput(view.getEditPane(), dotPosition, true);

    trace(output);

    if (output == null || output.output == null || output.output.errors == null) {
      trace("  haxe build error, no completion candidates");
      return;
    }

    String completionXMLString = output.output.errors.trim();

    if (completionXMLString == null
        || completionXMLString.equals("")
        || !completionXMLString.startsWith("<")) {
      return;
    }

    List<CompletionCandidate> localCandidates = new ArrayList<CompletionCandidate>();

    try {
      // Example see http://www.rgagnon.com/javadetails/java-0573.html
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(completionXMLString));

      Document doc = db.parse(is);
      NodeList insertions = doc.getElementsByTagName("i");

      // iterate the insertions
      for (int i = 0; i < insertions.getLength(); i++) {
        Element element = (Element) insertions.item(i);
        if (element.getNodeName().equals("i")) {
          // Insertion
          String codeName = element.getAttribute("n");
          String argString = ((Element) element.getElementsByTagName("t").item(0)).getTextContent();
          String[] methodTokens = argString.split("->");
          String returns = methodTokens[methodTokens.length - 1];
          String docs = ((Element) element.getElementsByTagName("d").item(0)).getTextContent();
          if (methodTokens.length == 1) {
            localCandidates.add(new CodeCompletionField(codeName, returns, docs));
          } else {
            CodeCompletionMethod cc = new CodeCompletionMethod(codeName, returns, docs);
            if (methodTokens.length > 1 && !methodTokens[0].trim().equals("Void")) {
              List<String> args = new ArrayList<String>(methodTokens.length - 1);
              List<String> argsTypes = new ArrayList<String>(methodTokens.length - 1);
              for (int jj = 0; jj < methodTokens.length - 1; ++jj) {
                String[] argTokens = methodTokens[jj].split(":");
                args.add(argTokens[0]);
                if (argTokens.length > 1) {
                  argsTypes.add(argTokens[1]);
                }
              }
              cc.arguments = args;
              cc.argumentTypes = argsTypes;
            }
            localCandidates.add(cc);
          }
        }
      }
      trace("Number of code completions=" + localCandidates.size());
    } catch (Exception e) {
      e.printStackTrace();
    }

    Collections.sort(localCandidates);
    candidates.addAll(localCandidates);
  }
예제 #18
0
  private void invoke() {
    String cmd;
    if (popup != null) cmd = popup.list.getSelectedValue().toString();
    else {
      cmd = action.getText().trim();
      int index = cmd.indexOf('=');
      if (index != -1) {
        action.addCurrentToHistory();
        String propName = cmd.substring(0, index).trim();
        String propValue = cmd.substring(index + 1).trim();
        String code;

        if (propName.startsWith("buffer.")) {
          if (propName.equals("buffer.mode")) {
            code = "buffer.setMode(\"" + MiscUtilities.charsToEscapes(propValue) + "\");";
          } else {
            code =
                "buffer.setStringProperty(\""
                    + MiscUtilities.charsToEscapes(propName.substring("buffer.".length()))
                    + "\",\""
                    + MiscUtilities.charsToEscapes(propValue)
                    + "\");";
          }

          code += "\nbuffer.propertiesChanged();";
        } else if (propName.startsWith("!buffer.")) {
          code =
              "jEdit.setProperty(\""
                  + MiscUtilities.charsToEscapes(propName.substring(1))
                  + "\",\""
                  + MiscUtilities.charsToEscapes(propValue)
                  + "\");\n"
                  + "jEdit.propertiesChanged();";
        } else {
          code =
              "jEdit.setProperty(\""
                  + MiscUtilities.charsToEscapes(propName)
                  + "\",\""
                  + MiscUtilities.charsToEscapes(propValue)
                  + "\");\n"
                  + "jEdit.propertiesChanged();";
        }

        Macros.Recorder recorder = view.getMacroRecorder();
        if (recorder != null) recorder.record(code);
        BeanShell.eval(view, namespace, code);
        cmd = null;
      } else if (cmd.length() != 0) {
        String[] completions = getCompletions(cmd);
        if (completions.length != 0) {
          cmd = completions[0];
        }
      } else cmd = null;
    }

    if (popup != null) {
      popup.dispose();
      popup = null;
    }

    final String finalCmd = cmd;
    final EditAction act = (finalCmd == null ? null : jEdit.getAction(finalCmd));
    if (temp) view.removeToolBar(this);

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            view.getTextArea().requestFocus();
            if (act == null) {
              if (finalCmd != null) {
                view.getStatus()
                    .setMessageAndClear(jEdit.getProperty("view.action.no-completions"));
              }
            } else {
              view.getInputHandler().setRepeatCount(repeatCount);
              view.getInputHandler().invokeAction(act);
            }
          }
        });
  }
예제 #19
0
  /**
   * Replaces all occurrences of the search string with the replacement string.
   *
   * @param view The view
   * @param dontOpenChangedFiles Whether to open changed files or to autosave them quietly
   * @return the number of modified files
   */
  public static boolean replaceAll(View view, boolean dontOpenChangedFiles) {
    // component that will parent any dialog boxes
    Component comp = SearchDialog.getSearchDialog(view);
    if (comp == null) comp = view;

    if (fileset.getFileCount(view) == 0) {
      GUIUtilities.error(comp, "empty-fileset", null);
      return false;
    }

    record(view, "replaceAll(view)", true, true);

    view.showWaitCursor();

    boolean smartCaseReplace = getSmartCaseReplace();

    int fileCount = 0;
    int occurCount = 0;
    try {
      SearchMatcher matcher = getSearchMatcher();
      if (matcher == null) return false;

      initReplace();

      String path = fileset.getFirstFile(view);
      loop:
      while (path != null) {
        Buffer buffer = jEdit.openTemporary(view, null, path, false);

        /* this is stupid and misleading.
         * but 'path' is not used anywhere except
         * the above line, and if this is done
         * after the 'continue', then we will
         * either hang, or be forced to duplicate
         * it inside the buffer == null, or add
         * a 'finally' clause. you decide which one's
         * worse. */
        path = fileset.getNextFile(view, path);

        if (buffer == null) continue loop;

        // Wait for buffer to finish loading
        if (buffer.isPerformingIO()) VFSManager.waitForRequests();

        if (!buffer.isEditable()) continue loop;

        // Leave buffer in a consistent state if
        // an error occurs
        int retVal = 0;

        try {
          buffer.beginCompoundEdit();
          retVal = _replace(view, buffer, matcher, 0, buffer.getLength(), smartCaseReplace);
        } finally {
          buffer.endCompoundEdit();
        }

        if (retVal != 0) {
          fileCount++;
          occurCount += retVal;
          if (dontOpenChangedFiles) {
            buffer.save(null, null);
          } else {
            jEdit.commitTemporary(buffer);
            jEdit.getBufferSetManager().addBuffer(view, buffer);
          }
        }
      }
    } catch (Exception e) {
      handleError(comp, e);
    } finally {
      view.hideWaitCursor();
    }

    /* Don't do this when playing a macro, cos it's annoying */
    if (!BeanShell.isScriptRunning()) {
      Object[] args = {Integer.valueOf(occurCount), Integer.valueOf(fileCount)};
      view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.replace-all", args));
      if (occurCount == 0) view.getToolkit().beep();
    }

    return (fileCount != 0);
  } // }}}
예제 #20
0
  /**
   * Replaces the current selection with the replacement string.
   *
   * @param view The view
   * @return True if the operation was successful, false otherwise
   */
  public static boolean replace(View view) {
    // component that will parent any dialog boxes
    Component comp = SearchDialog.getSearchDialog(view);
    if (comp == null) comp = view;

    JEditTextArea textArea = view.getTextArea();

    Buffer buffer = view.getBuffer();
    if (!buffer.isEditable()) return false;

    boolean smartCaseReplace = getSmartCaseReplace();

    Selection[] selection = textArea.getSelection();
    if (selection.length == 0) {
      view.getToolkit().beep();
      return false;
    }

    record(view, "replace(view)", true, false);

    // a little hack for reverse replace and find
    int caret = textArea.getCaretPosition();
    Selection s = textArea.getSelectionAtOffset(caret);
    if (s != null) caret = s.getStart();

    try {
      buffer.beginCompoundEdit();

      SearchMatcher matcher = getSearchMatcher();
      if (matcher == null) return false;

      initReplace();

      int retVal = 0;

      for (int i = 0; i < selection.length; i++) {
        s = selection[i];

        retVal += replaceInSelection(view, textArea, buffer, matcher, smartCaseReplace, s);
      }

      if (reverse) {
        // so that Replace and Find continues from
        // the right location
        textArea.moveCaretPosition(caret);
      } else {
        s = textArea.getSelectionAtOffset(textArea.getCaretPosition());
        if (s != null) textArea.moveCaretPosition(s.getEnd());
      }

      if (!BeanShell.isScriptRunning()) {
        Object[] args = {Integer.valueOf(retVal), Integer.valueOf(1)};
        view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.replace-all", args));
      }

      if (retVal == 0) {
        view.getToolkit().beep();
        return false;
      }

      return true;
    } catch (Exception e) {
      handleError(comp, e);
    } finally {
      buffer.endCompoundEdit();
    }

    return false;
  } // }}}
예제 #21
0
 // {{{ hideDockable() method
 private void hideDockable() {
   view.getDockableWindowManager().hideDockableWindow(NAME);
 } // }}}
  /** Constructor. Sets up and shows the GUI */
  public TextToolsSortDialog(View view, JEditTextArea textArea) {
    super(view, jEdit.getProperty("text-tools.sortadvanced.label"), false);

    this.view = view;
    this.textArea = textArea;
    //		this.data = data;
    //		this.selection = selection;

    view.showWaitCursor();

    sortTableModel = new SortTableModel();

    // preset sortTable if there is a rect selection
    boolean rectSel = false;
    int[] selRows = TextToolsSorting.getRectSelectionRows(textArea);
    if (selRows != null) {
      // we have rectangular selection: assign values to 1st row of table
      sortTableModel.setValueAt(new Integer(selRows[0] + 1), 0, 0);
      sortTableModel.setValueAt(new Integer(selRows[1] + 1), 0, 1);
      rectSel = true;
    }

    sortTable = new JTable(sortTableModel);
    TableColumnModel cMod = sortTable.getColumnModel();
    sortTable.setTableHeader((new SortTableHeader(cMod)));
    sortTable.setRowHeight(25);

    sortTable.setPreferredScrollableViewportSize(new Dimension(430, 200));

    JScrollPane scroll = new JScrollPane(sortTable);

    JPanel content = new JPanel(new BorderLayout());
    content.setBorder(new EmptyBorder(5, 8, 8, 8));
    content.setLayout(new BorderLayout());
    setContentPane(content);
    content.add(scroll, BorderLayout.CENTER);

    JPanel buttons = new JPanel();
    buttons.setBorder(new EmptyBorder(12, 0, 0, 0));
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
    buttons.add(Box.createGlue());

    ok = new JButton(jEdit.getProperty("common.ok"));
    ok.addActionListener(this);
    buttons.add(ok);
    buttons.add(Box.createHorizontalStrut(6));
    getRootPane().setDefaultButton(ok);

    cancel = new JButton(jEdit.getProperty("common.cancel"));
    cancel.addActionListener(this);
    buttons.add(cancel);
    buttons.add(Box.createHorizontalStrut(6));

    clear = new JButton("Clear");
    clear.addActionListener(this);
    buttons.add(clear);
    buttons.add(Box.createHorizontalStrut(6));

    help = new JButton("Help");
    help.addActionListener(this);
    buttons.add(help);
    buttons.add(Box.createHorizontalStrut(6));

    buttons.add(Box.createGlue());

    content.add(buttons, BorderLayout.SOUTH);

    delDupsCheckBox =
        new JCheckBox(jEdit.getProperty("text-tools.sortadvanced.delete-identic-lines"));
    onlySelectionCheckBox =
        new JCheckBox(jEdit.getProperty("text-tools.sortadvanced.sort-only-selection"));

    /*
    dontSortCheckBox = new JCheckBox(
    	jEdit.getProperty("text-tools.sortadvanced.dont-sort"));
    delDupsCheckBox.addActionListener(new java.awt.event.ActionListener() {
    	public void actionPerformed(ActionEvent e) {
    		dontSortCheckBox.setEnabled(delDupsCheckBox.isSelected());
    		dontSortCheckBox.setSelected(false);
    	}
    });
    dontSortCheckBox.setEnabled(false);
    */
    JPanel checkBoxes = new JPanel();
    if (rectSel) checkBoxes.add(onlySelectionCheckBox);
    checkBoxes.add(delDupsCheckBox);
    // checkBoxes.add(dontSortCheckBox);  not used, this is an extra action
    content.add(checkBoxes, BorderLayout.NORTH);
    view.hideWaitCursor();
    pack();
    GUIUtilities.loadGeometry(this, "texttools-sort-control");
    setLocationRelativeTo(view);
    setVisible(true);
  } // }}}
예제 #23
0
  // {{{ update() method
  public void update(JMenu menu) {
    final View view = GUIUtilities.getView(menu);

    String path;
    if (dir == null) {
      path = view.getBuffer().getDirectory();
    } else path = dir;

    JMenuItem mi = new JMenuItem(path + ':');
    mi.setActionCommand(path);
    mi.setIcon(FileCellRenderer.openDirIcon);

    // {{{ ActionListeners
    ActionListener fileListener =
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            jEdit.openFile(view, evt.getActionCommand());
          }
        };

    ActionListener dirListener =
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            VFSBrowser.browseDirectory(view, evt.getActionCommand());
          }
        }; // }}}

    mi.addActionListener(dirListener);

    menu.add(mi);
    menu.addSeparator();

    if (dir == null && !(view.getBuffer().getVFS() instanceof FileVFS)) {
      mi = new JMenuItem(jEdit.getProperty("directory.not-local"));
      mi.setEnabled(false);
      menu.add(mi);
      return;
    }

    File directory = new File(path);

    JMenu current = menu;

    // for filtering out backups
    String backupPrefix = jEdit.getProperty("backup.prefix");
    String backupSuffix = jEdit.getProperty("backup.suffix");

    File[] list = directory.listFiles();
    if (list == null || list.length == 0) {
      mi = new JMenuItem(jEdit.getProperty("directory.no-files"));
      mi.setEnabled(false);
      menu.add(mi);
    } else {
      int maxItems = jEdit.getIntegerProperty("menu.spillover", 20);

      Arrays.sort(list, new StandardUtilities.StringCompare<File>(true));
      for (int i = 0; i < list.length; i++) {
        File file = list[i];

        String name = file.getName();

        // skip marker files
        if (name.endsWith(".marks")) continue;

        // skip autosave files
        if (name.startsWith("#") && name.endsWith("#")) continue;

        // skip backup files
        if ((backupPrefix.length() != 0 && name.startsWith(backupPrefix))
            || (backupSuffix.length() != 0 && name.endsWith(backupSuffix))) continue;

        // skip directories
        // if(file.isDirectory())
        //	continue;

        mi = new JMenuItem(name);
        mi.setActionCommand(file.getPath());
        mi.addActionListener(file.isDirectory() ? dirListener : fileListener);
        mi.setIcon(file.isDirectory() ? FileCellRenderer.dirIcon : FileCellRenderer.fileIcon);

        if (current.getItemCount() >= maxItems && i != list.length - 1) {
          // current.addSeparator();
          JMenu newCurrent = new JMenu(jEdit.getProperty("common.more"));
          current.add(newCurrent);
          current = newCurrent;
        }
        current.add(mi);
      }
    }
  } // }}}
예제 #24
0
 public static void setStatusMessage(String msg) {
   View view = jEdit.getActiveView();
   if (view != null) view.getStatus().setMessageAndClear(msg);
   else longToast(msg);
 }