public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    Position[] positions = null;
    FormatterPrefs formatterPrefs = getFormatterPrefs();
    StringBuffer buffer = new StringBuffer();

    buffer.append(fProposal.getName());

    if (formatterPrefs.beforeOpeningParen) buffer.append(SPACE);

    buffer.append(LPAREN);

    if (formatterPrefs.afterOpeningParen) buffer.append(SPACE);

    if (Signature.getParameterCount(fProposal.getSignature()) > 0) {
      char[][] parameters = fProposal.findParameterNames(null);
      if (parameters != null) {
        positions = new Position[parameters.length];

        int base = getReplacementOffset();
        for (int i = 0; i < parameters.length; i++) {
          if (i != 0) {
            if (formatterPrefs.beforeComma) buffer.append(SPACE);

            buffer.append(COMMA);

            if (formatterPrefs.afterComma) buffer.append(SPACE);
          }
          Position position = new Position(0, 0);
          position.setOffset(base + buffer.length());
          position.setLength(parameters[i].length);
          positions[i] = position;
          buffer.append(parameters[i]);
        }
      }
    }

    if (formatterPrefs.beforeClosingParen) buffer.append(SPACE);

    buffer.append(RPAREN);
    setReplacementString(buffer.toString());

    super.apply(viewer, trigger, stateMask, offset);

    try {
      if (positions != null) {
        LinkedModeModel model = new LinkedModeModel();

        for (int i = 0; i < positions.length; i++) {
          LinkedPositionGroup group = new LinkedPositionGroup();
          Position position = positions[i];
          group.addPosition(
              new LinkedPosition(
                  viewer.getDocument(), position.getOffset(), position.getLength(), i));
          model.addGroup(group);
        }
        model.forceInstall();

        LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
        ui.setExitPosition(
            viewer, getReplacementOffset() + getReplacementString().length(), 0, Integer.MAX_VALUE);
        ui.setExitPolicy(new ExitPolicy(')', viewer.getDocument()));
        ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT);
        ui.setDoContextInfo(true);
        ui.enter();
        fSelectedRegion = ui.getSelectedRegion();
      }
    } catch (BadLocationException e) {

    }
  }
예제 #2
0
  @Override
  public void apply(final ITextViewer viewer, char trigger, int stateMask, final int offset) {
    try {
      fLocations = null;
      Point selection = viewer.getSelectedRange();
      final int secectionOffset = selection.x;
      final int selectionLength = selection.y;

      ASTProvider.getASTProvider()
          .runOnAST(
              fTranslationUnit,
              ASTProvider.WAIT_ACTIVE_ONLY,
              new NullProgressMonitor(),
              new ASTRunnable() {
                @Override
                public IStatus runOnAST(ILanguage lang, IASTTranslationUnit astRoot)
                    throws CoreException {
                  if (astRoot == null) return Status.CANCEL_STATUS;

                  IASTNodeSelector selector = astRoot.getNodeSelector(null);
                  IASTName name = selector.findEnclosingName(secectionOffset, selectionLength);
                  if (name != null) {
                    fLocations = LinkedNamesFinder.findByName(astRoot, name);
                  }
                  return Status.OK_STATUS;
                }
              });

      if (fLocations == null || fLocations.length == 0) {
        return;
      }

      // Sort the locations starting with the one @ offset.
      Arrays.sort(
          fLocations,
          new Comparator<IRegion>() {
            @Override
            public int compare(IRegion n1, IRegion n2) {
              return rank(n1) - rank(n2);
            }

            /**
             * Returns the absolute rank of a location. Location preceding {@code offset} are ranked
             * last.
             *
             * @param location the location to compute the rank for
             * @return the rank of the location with respect to the invocation offset
             */
            private int rank(IRegion location) {
              int relativeRank = location.getOffset() + location.getLength() - offset;
              if (relativeRank < 0) {
                return Integer.MAX_VALUE + relativeRank;
              } else {
                return relativeRank;
              }
            }
          });

      IDocument document = viewer.getDocument();
      LinkedPositionGroup group = new LinkedPositionGroup();
      for (int i = 0; i < fLocations.length; i++) {
        IRegion item = fLocations[i];
        group.addPosition(new LinkedPosition(document, item.getOffset(), item.getLength(), i));
      }

      LinkedModeModel model = new LinkedModeModel();
      model.addGroup(group);
      model.forceInstall();
      CEditor editor = getCEditor();
      if (editor != null) {
        model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
      }

      LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
      ui.setExitPolicy(new DeleteBlockingExitPolicy(document));
      ui.setExitPosition(viewer, offset, 0, LinkedPositionGroup.NO_STOP);
      ui.enter();

      if (fValueSuggestion != null) {
        document.replace(fLocations[0].getOffset(), fLocations[0].getLength(), fValueSuggestion);
        IRegion selectedRegion = ui.getSelectedRegion();
        selection = new Point(selectedRegion.getOffset(), fValueSuggestion.length());
      }

      viewer.setSelectedRange(
          selection.x, selection.y); // By default full word is selected, restore original selection
    } catch (BadLocationException e) {
      CUIPlugin.log(e);
    }
  }
  /*
   * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
   */
  @Override
  public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {

    IDocument document = viewer.getDocument();
    try {
      fContext.setReadOnly(false);
      int start;
      TemplateBuffer templateBuffer;
      try {
        beginCompoundChange(viewer);

        int oldReplaceOffset = getReplaceOffset();
        try {
          // this may already modify the document (e.g. add imports)
          templateBuffer = fContext.evaluate(fTemplate);
        } catch (TemplateException e1) {
          fSelectedRegion = fRegion;
          return;
        }

        start = getReplaceOffset();
        int shift = start - oldReplaceOffset;
        int end = Math.max(getReplaceEndOffset(), offset + shift);

        // insert template string
        if (end > document.getLength()) end = offset;
        String templateString = templateBuffer.getString();
        document.replace(start, end - start, templateString);
      } finally {
        endCompoundChange(viewer);
      }

      // translate positions
      LinkedModeModel model = new LinkedModeModel();
      TemplateVariable[] variables = templateBuffer.getVariables();

      MultiVariableGuess guess =
          fContext instanceof CompilationUnitContext
              ? ((CompilationUnitContext) fContext).getMultiVariableGuess()
              : null;

      boolean hasPositions = false;
      for (int i = 0; i != variables.length; i++) {
        TemplateVariable variable = variables[i];

        if (variable.isUnambiguous()) continue;

        LinkedPositionGroup group = new LinkedPositionGroup();

        int[] offsets = variable.getOffsets();
        int length = variable.getLength();

        LinkedPosition first;
        if (guess != null && variable instanceof MultiVariable) {
          first =
              new VariablePosition(
                  document, offsets[0] + start, length, guess, (MultiVariable) variable);
          guess.addSlave((VariablePosition) first);
        } else {
          String[] values = variable.getValues();
          ICompletionProposal[] proposals = new ICompletionProposal[values.length];
          for (int j = 0; j < values.length; j++) {
            ensurePositionCategoryInstalled(document, model);
            Position pos = new Position(offsets[0] + start, length);
            document.addPosition(getCategory(), pos);
            proposals[j] = new PositionBasedCompletionProposal(values[j], pos, length);
          }

          if (proposals.length > 1)
            first = new ProposalPosition(document, offsets[0] + start, length, proposals);
          else first = new LinkedPosition(document, offsets[0] + start, length);
        }

        for (int j = 0; j != offsets.length; j++)
          if (j == 0) group.addPosition(first);
          else group.addPosition(new LinkedPosition(document, offsets[j] + start, length));

        model.addGroup(group);
        hasPositions = true;
      }

      if (hasPositions) {
        model.forceInstall();
        JavaEditor editor = getJavaEditor();
        if (editor != null) {
          model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
        }

        LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
        ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + start, 0, Integer.MAX_VALUE);
        ui.enter();

        fSelectedRegion = ui.getSelectedRegion();
      } else {
        fSelectedRegion = new Region(getCaretOffset(templateBuffer) + start, 0);
      }

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
      openErrorDialog(viewer.getTextWidget().getShell(), e);
      fSelectedRegion = fRegion;
    } catch (BadPositionCategoryException e) {
      JavaPlugin.log(e);
      openErrorDialog(viewer.getTextWidget().getShell(), e);
      fSelectedRegion = fRegion;
    }
  }