Beispiel #1
0
  void processAction(ITextEditor textEditor, IDocument document, ITextSelection textSelection) {
    int openCommentOffset = textSelection.getOffset();
    int closeCommentOffset = openCommentOffset + textSelection.getLength();

    if (textSelection.getLength() == 0) {
      return;
    }

    IStructuredModel model =
        StructuredModelManager.getModelManager().getExistingModelForEdit(document);
    if (model != null) {
      try {
        model.beginRecording(this, PHPUIMessages.AddBlockComment_tooltip);
        model.aboutToChangeModel();

        try {
          document.replace(closeCommentOffset, 0, CLOSE_COMMENT);
          document.replace(openCommentOffset, 0, OPEN_COMMENT);
        } catch (BadLocationException e) {
          Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e);
        } finally {
          model.changedModel();
          model.endRecording(this);
        }
      } finally {
        model.releaseFromEdit();
      }
    }
  }
Beispiel #2
0
  @Override
  protected void runInternal(
      ITextSelection selection, IDocumentExtension3 docExtension, Edit.EditFactory factory)
      throws BadLocationException, BadPartitioningException {

    if (!(docExtension instanceof IDocument)) return;

    List<Edit> edits = new LinkedList<Edit>();

    ITypedRegion firstPartition =
        docExtension.getPartition(ICPartitions.C_PARTITIONING, selection.getOffset(), false);
    ITypedRegion lastPartition =
        docExtension.getPartition(
            ICPartitions.C_PARTITIONING, selection.getOffset() + selection.getLength() - 1, false);

    int commentAreaStart = selection.getOffset();
    int commentAreaEnd = selection.getOffset() + selection.getLength();
    // Include special partitions fully in the comment area
    if (isSpecialPartition(firstPartition.getType())) {
      commentAreaStart = firstPartition.getOffset();
    }
    if (isSpecialPartition(lastPartition.getType())) {
      commentAreaEnd = lastPartition.getOffset() + lastPartition.getLength();
    }
    Region estimatedCommentArea = new Region(commentAreaStart, commentAreaEnd - commentAreaStart);

    Region commentArea =
        handleEnclosingPartitions(
            estimatedCommentArea, lastPartition, (IDocument) docExtension, factory, edits);

    handleInteriorPartition(commentArea, firstPartition, docExtension, factory, edits);

    executeEdits(edits);
  }
 @Override
 public void run(ITextSelection currentSelection) {
   if (currentSelection != null && editor != null) {
     GroovyCompilationUnit unit = editor.getGroovyCompilationUnit();
     if (unit != null) {
       ModuleNode node = unit.getModuleNode();
       if (node != null) {
         FindSurroundingNode finder =
             new FindSurroundingNode(
                 new Region(currentSelection.getOffset(), currentSelection.getLength()));
         IASTFragment result = finder.doVisitSurroundingNode(node);
         if (result != null) {
           TextSelection newSelection = new TextSelection(result.getStart(), result.getLength());
           if (!newSelection.equals(currentSelection)) {
             history.remember(
                 new SourceRange(currentSelection.getOffset(), currentSelection.getLength()));
             try {
               history.ignoreSelectionChanges();
               editor.selectAndReveal(result.getStart(), result.getLength());
             } finally {
               history.listenToSelectionChanges();
             }
           }
           editor.getSelectionProvider().setSelection(newSelection);
         }
       }
     }
   }
 }
  /*
   * Method declared in IAction.
   */
  @Override
  public final void run() {
    DartElement inputElement = EditorUtility.getEditorInputJavaElement(fEditor, false);
    if (!(inputElement instanceof SourceReference && inputElement.exists())) {
      return;
    }

    SourceReference source = (SourceReference) inputElement;
    SourceRange sourceRange;
    try {
      sourceRange = source.getSourceRange();
      if (sourceRange == null || sourceRange.getLength() == 0) {
        MessageDialog.openInformation(
            fEditor.getEditorSite().getShell(),
            SelectionActionMessages.StructureSelect_error_title,
            SelectionActionMessages.StructureSelect_error_message);
        return;
      }
    } catch (DartModelException e) {
    }
    ITextSelection selection = getTextSelection();
    SourceRange newRange = getNewSelectionRange(createSourceRange(selection), source);
    // Check if new selection differs from current selection
    if (selection.getOffset() == newRange.getOffset()
        && selection.getLength() == newRange.getLength()) {
      return;
    }
    fSelectionHistory.remember(newSourceRange(selection.getOffset(), selection.getLength()));
    try {
      fSelectionHistory.ignoreSelectionChanges();
      fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
    } finally {
      fSelectionHistory.listenToSelectionChanges();
    }
  }
Beispiel #5
0
  /**
   * Remembers and returns the current selection. The saved selection can be restored by calling
   * <code>restoreSelection()</code>.
   *
   * @return the current selection
   * @see org.eclipse.jface.text.ITextViewer#getSelectedRange()
   * @since 3.0
   */
  protected Point rememberSelection() {

    final ITextSelection selection = (ITextSelection) getSelection();
    final IDocument document = getDocument();

    if (fSelections.isEmpty()) {
      fSelectionCategory = _SELECTION_POSITION_CATEGORY + hashCode();
      fSelectionUpdater = new NonDeletingPositionUpdater(fSelectionCategory);
      document.addPositionCategory(fSelectionCategory);
      document.addPositionUpdater(fSelectionUpdater);
    }

    try {
      final Position position;
      if (selection instanceof IBlockTextSelection)
        position =
            new ColumnPosition(
                selection.getOffset(),
                selection.getLength(),
                ((IBlockTextSelection) selection).getStartColumn(),
                ((IBlockTextSelection) selection).getEndColumn());
      else position = new Position(selection.getOffset(), selection.getLength());
      document.addPosition(fSelectionCategory, position);
      fSelections.push(position);

    } catch (BadLocationException exception) {
      // Should not happen
    } catch (BadPositionCategoryException exception) {
      // Should not happen
    }

    return new Point(selection.getOffset(), selection.getLength());
  }
 private ICompletionProposal findCorrection(
     String id,
     boolean isAssist,
     ITextSelection selection,
     ICompilationUnit cu,
     IAnnotationModel model) {
   AssistContext context =
       new AssistContext(
           cu, fEditor.getViewer(), fEditor, selection.getOffset(), selection.getLength());
   Collection<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>(10);
   if (isAssist) {
     if (id.equals(LinkedNamesAssistProposal.ASSIST_ID)) {
       return getLocalRenameProposal(context); // shortcut for local rename
     }
     JavaCorrectionProcessor.collectAssists(context, new ProblemLocation[0], proposals);
   } else {
     try {
       boolean goToClosest = selection.getLength() == 0;
       Annotation[] annotations = getAnnotations(selection.getOffset(), goToClosest);
       JavaCorrectionProcessor.collectProposals(
           context, model, annotations, true, false, proposals);
     } catch (BadLocationException e) {
       return null;
     }
   }
   for (Iterator<IJavaCompletionProposal> iter = proposals.iterator(); iter.hasNext(); ) {
     Object curr = iter.next();
     if (curr instanceof ICommandAccess) {
       if (id.equals(((ICommandAccess) curr).getCommandId())) {
         return (ICompletionProposal) curr;
       }
     }
   }
   return null;
 }
  /**
   * {@inheritDoc}
   *
   * @see java.util.concurrent.Callable#call()
   */
  public CompilationResult call() throws Exception {
    checkCancelled();

    String fullExpression = acceleoSource.rebuildFullExpression(context);

    ResourceSet resourceSet = new ResourceSetImpl();
    Resource resource =
        ModelUtils.createResource(
            URI.createURI("http://acceleo.eclipse.org/default.emtl"), resourceSet); // $NON-NLS-1$

    AcceleoSourceBuffer source = new AcceleoSourceBuffer(new StringBuffer(fullExpression));

    List<URI> dependencies = new ArrayList<URI>();
    if (acceleoSource.getModuleImport() != null) {
      dependencies.addAll(computeImportList(acceleoSource.getModuleImport(), resourceSet));
    }

    AcceleoParser parser = new AcceleoParser();
    parser.parse(source, resource, dependencies);

    checkCancelled();

    ASTNode selectedNode = null;
    if (!resource.getContents().isEmpty()) {
      Module module = (Module) resource.getContents().get(0);

      ISelection selection = context.getSelection();
      if (selection instanceof ITextSelection && ((ITextSelection) selection).getLength() > 0) {
        ITextSelection textSelection = (ITextSelection) selection;
        int startOffset = textSelection.getOffset() + acceleoSource.getGap();
        int endOffset = startOffset + textSelection.getLength();

        if (textSelection.getText().startsWith("[")) { // $NON-NLS-1$
          startOffset++;
        }
        if (textSelection.getText().endsWith("/]")) { // $NON-NLS-1$
          endOffset -= 2;
        }

        selectedNode = getChildrenCandidate(module, startOffset, endOffset);

        if (textSelection.getLength() == 0) {
          while (selectedNode != null && !(selectedNode instanceof ModuleElement)) {
            selectedNode = (ASTNode) selectedNode.eContainer();
          }
        }
      }

      if (selectedNode == null && module != null && !module.getOwnedModuleElement().isEmpty()) {
        selectedNode = module.getOwnedModuleElement().get(0);
      }
    }

    checkCancelled();

    IStatus problems = parseProblems(source.getProblems(), source.getWarnings(), source.getInfos());
    return new CompilationResult(selectedNode, problems);
  }
 /**
  * Creates a region describing the text block (something that starts at the beginning of a line)
  * completely containing the current selection.
  *
  * @param selection The selection to use
  * @param document The document
  * @return the region describing the text block comprising the given selection
  */
 private IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) {
   try {
     IRegion line = document.getLineInformationOfOffset(selection.getOffset());
     int length =
         selection.getLength() == 0
             ? line.getLength()
             : selection.getLength() + (selection.getOffset() - line.getOffset());
     return new Region(line.getOffset(), length);
   } catch (BadLocationException x) {
     // should not happen
     // JavaPlugin.log(x);
   }
   return null;
 }
  private IASTFunctionDeclarator findDeclaratorInSelection(
      ITextSelection selection, IASTTranslationUnit unit) {
    IASTNode firstNodeInsideSelection =
        unit.getNodeSelector(null)
            .findFirstContainedNode(selection.getOffset(), selection.getLength());
    IASTFunctionDeclarator declarator = findDeclaratorInAncestors(firstNodeInsideSelection);

    if (declarator == null) {
      firstNodeInsideSelection =
          unit.getNodeSelector(null)
              .findEnclosingNode(selection.getOffset(), selection.getLength());
      declarator = findDeclaratorInAncestors(firstNodeInsideSelection);
    }
    return declarator;
  }
  @SuppressWarnings("unchecked")
  protected static StatementSequence findEnclosingStatementSequence(
      IFortranAST ast, ITextSelection selection) {
    Token firstToken = findFirstTokenAfter(ast, selection.getOffset());
    Token lastToken = findLastTokenBefore(ast, selection.getOffset() + selection.getLength());
    if (firstToken == null || lastToken == null) return null;

    IASTListNode<? extends IASTNode> listContainingFirstToken =
        firstToken.findNearestAncestor(IASTListNode.class);
    IASTListNode<? extends IASTNode> listContainingLastToken =
        lastToken.findNearestAncestor(IASTListNode.class);
    if (listContainingFirstToken == null
        || listContainingLastToken == null
        || listContainingFirstToken != listContainingLastToken) return null;

    IASTListNode<? extends IASTNode> listContainingStmts = listContainingFirstToken;
    int startIndex = -1;
    int endIndex = -1;
    for (int i = 0; i < listContainingStmts.size(); i++) {
      IASTNode node = listContainingStmts.get(i);
      if (contains(node, firstToken)) startIndex = i;
      if (contains(node, lastToken)) endIndex = i;
    }
    if (startIndex < 0 || endIndex < 0 || endIndex < startIndex)
      throw new Error(
          "INTERNAL ERROR: Unable to locate selected statements in IASTListNode"); //$NON-NLS-1$

    return new StatementSequence(
        listContainingStmts.findNearestAncestor(ScopingNode.class),
        listContainingStmts,
        startIndex,
        endIndex);
  }
 /** end test code */
 protected static <T extends IASTNode> T getNode(
     IFortranAST ast, ITextSelection selection, Class<T> node) {
   Token firstToken = findFirstTokenAfter(ast, selection.getOffset());
   Token lastToken = findLastTokenBefore(ast, selection.getOffset() + selection.getLength());
   if (firstToken == null || lastToken == null) return null;
   return getNode(firstToken, lastToken, node);
 }
 protected static ASTNode getNodeAtIndx(
     IFortranAST ast, ITextSelection selection, Class<? extends ASTNode> node, int off) {
   Token firstToken = findFirstTokenAfter(ast, selection.getOffset() + off);
   Token lastToken = findLastTokenBefore(ast, selection.getOffset() + selection.getLength());
   if (firstToken == null || lastToken == null) return null;
   return getNode(firstToken, lastToken, node);
 }
  /**
   * the command has been executed, so extract extract the needed information from the application
   * context.
   */
  public Object execute(ExecutionEvent event) throws ExecutionException {
    IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
    if (!ITextEditor.class.isAssignableFrom(activeEditor.getClass())) {
      return null;
    }
    ITextEditor iTextEditor = (ITextEditor) activeEditor;
    ISelection selection = iTextEditor.getSelectionProvider().getSelection();
    if (!ITextSelection.class.isAssignableFrom(selection.getClass())) {
      return null;
    }
    ITextSelection textSelection = (ITextSelection) selection;

    IHandlerService service =
        (IHandlerService) HandlerUtil.getActiveSite(event).getService(IHandlerService.class);
    try {
      if (textSelection.getLength() == 0) {
        service.executeCommand("org.eclipse.ui.edit.text.cut.line", null);
      } else {
        service.executeCommand("org.eclipse.ui.edit.cut", null);
      }
    } catch (NotDefinedException e) {
      throw new ExecutionException("Failed to cut line or selection", e);
    } catch (NotEnabledException e) {
      throw new ExecutionException("Failed to cut line or selection", e);
    } catch (NotHandledException e) {
      throw new ExecutionException("Failed to cut line or selection", e);
    }

    return null;
  }
 public static SurroundWithTryCatchRefactoring create(
     ICompilationUnit cu, ITextSelection selection, boolean isMultiCatch) {
   return new SurroundWithTryCatchRefactoring(
       cu,
       Selection.createFromStartLength(selection.getOffset(), selection.getLength()),
       isMultiCatch);
 }
Beispiel #15
0
  @Override
  public void run() {
    ISearchQuery searchJob = null;

    ISelection selection = getSelection();
    if (selection instanceof IStructuredSelection) {
      Object object = ((IStructuredSelection) selection).getFirstElement();
      if (object instanceof ISourceReference) searchJob = createQuery((ISourceReference) object);
    } else if (selection instanceof ITextSelection) {
      ITextSelection selNode = (ITextSelection) selection;
      ICElement element = fEditor.getInputCElement();
      while (element != null && !(element instanceof ITranslationUnit))
        element = element.getParent();
      if (element != null) {
        if (selNode.getLength() == 0) {
          IDocument document = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
          IRegion reg = CWordFinder.findWord(document, selNode.getOffset());
          selNode = new TextSelection(document, reg.getOffset(), reg.getLength());
        }
        searchJob = createQuery(element, selNode);
      }
    }

    if (searchJob == null) {
      showStatusLineMessage(CSearchMessages.CSearchOperation_operationUnavailable_message);
      return;
    }

    clearStatusLine();
    NewSearchUI.activateSearchResultView();
    NewSearchUI.runQueryInBackground(searchJob);
  }
 @Override
 public Object execute(final ExecutionEvent event) throws ExecutionException {
   final ISelection selection = WorkbenchUIUtil.getCurrentSelection(event.getApplicationContext());
   final IWorkbenchPart activePart = WorkbenchUIUtil.getActivePart(event.getApplicationContext());
   if (selection == null || activePart == null) {
     return null;
   }
   final ISourceUnit su = LTKSelectionUtil.getSingleSourceUnit(activePart);
   if (!(su instanceof IRSourceUnit)) {
     return null;
   }
   ExtractFunctionRefactoring refactoring = null;
   if (selection instanceof ITextSelection) {
     final ITextSelection textSelection = (ITextSelection) selection;
     refactoring =
         new ExtractFunctionRefactoring(
             (IRSourceUnit) su, new Region(textSelection.getOffset(), textSelection.getLength()));
   }
   if (refactoring != null) {
     final RefactoringWizardExecutionHelper executionHelper =
         new RefactoringWizardExecutionHelper(
             new ExtractFunctionWizard(refactoring), RefactoringSaveHelper.SAVE_NOTHING);
     executionHelper.perform(activePart.getSite().getShell());
   }
   //			}
   //			catch (final CoreException e) {
   //				StatusManager.getManager().handle(new Status(
   //						IStatus.ERROR, RUI.PLUGIN_ID, -1,
   //						Messages.InlineTemp_Wizard_title, e),
   //						StatusManager.LOG | StatusManager.SHOW);
   //			}
   return null;
 }
 /**
  * @see com.mulgasoft.emacsplus.commands.EmacsPlusCmdHandler#transform(ITextEditor, IDocument,
  *     ITextSelection, ExecutionEvent)
  */
 @Override
 protected int transform(
     ITextEditor editor, IDocument document, ITextSelection currentSelection, ExecutionEvent event)
     throws BadLocationException {
   int result = getCursorOffset(editor, currentSelection);
   // get the selection encompassing the appropriate set of lines
   ITextSelection selection = getLineSelection(editor, document, currentSelection);
   if (selection != null) {
     int offset = selection.getOffset();
     int endOffset = offset + selection.getLength();
     int begin = document.getLineOfOffset(offset);
     int end = document.getLineOfOffset(endOffset);
     if (begin != end && begin < end) {
       ArrayList<String> alst = new ArrayList<String>();
       IRegion region = document.getLineInformation(begin);
       // get text from point or mark
       alst.add(document.get(offset, region.getLength() - (offset - region.getOffset())));
       for (int i = begin + 1; i < end; i++) {
         region = document.getLineInformation(i);
         // get full line of text
         alst.add(document.get(region.getOffset(), region.getLength()));
       }
       region = document.getLineInformation(end);
       // get text to point or mark
       alst.add(document.get(region.getOffset(), endOffset - region.getOffset()));
       Collections.sort(alst, (getComparator(isUniversalPresent())));
       updateLines(document, selection, alst.toArray(new String[0]));
     } else {
       EmacsPlusUtils.showMessage(editor, NO_REGION, true);
     }
   } else {
     EmacsPlusUtils.showMessage(editor, NO_REGION, true);
   }
   return result;
 }
 /* (non-JavaDoc)
  * Method declared in IAction.
  */
 public final void run() {
   ITextSelection selection = getTextSelection();
   ISourceRange newRange = getNewSelectionRange(createSourceRange(selection), null);
   // Check if new selection differs from current selection
   if (selection.getOffset() == newRange.getOffset()
       && selection.getLength() == newRange.getLength()) return;
   fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
 }
 @Override
 public void run(ITextSelection selection) {
   if (!ActionUtil.isEditable(fEditor)) return;
   RefactoringExecutionStarter.startChangeTypeRefactoring(
       SelectionConverter.getInputAsCompilationUnit(fEditor),
       getShell(),
       selection.getOffset(),
       selection.getLength());
 }
 private List<Statement> getStatements(Tree.Body body, ITextSelection selection) {
   List<Statement> statements = new ArrayList<Statement>();
   for (Tree.Statement s : body.getStatements()) {
     if (s.getStartIndex() >= selection.getOffset()
         && s.getStopIndex() <= selection.getOffset() + selection.getLength()) {
       statements.add(s);
     }
   }
   return statements;
 }
 /** @return the Selected text */
 public String getSelectedText() {
   ITextSelection txtSel = getTextSelection();
   int start = txtSel.getOffset();
   int len = txtSel.getLength();
   try {
     return this.doc.get(start, len);
   } catch (BadLocationException e) {
     throw new RuntimeException(e);
   }
 }
  protected Region getNewSelectionRegion(
      IndexedRegion indexedRegion, ITextSelection textSelection) {
    Region newRegion = null;
    if (indexedRegion instanceof Node) {
      Node cursorNode = (Node) indexedRegion;

      // use parent node for empty text node
      if ((cursorNode.getNodeType() == Node.TEXT_NODE)
          && (cursorNode.getNodeValue().trim().length() == 0)) {
        cursorNode = cursorNode.getParentNode();

        if (cursorNode instanceof IndexedRegion) {
          indexedRegion = (IndexedRegion) cursorNode;
        }
      }

      Region cursorNodeRegion =
          new Region(
              indexedRegion.getStartOffset(),
              indexedRegion.getEndOffset() - indexedRegion.getStartOffset());

      if ((cursorNodeRegion.getOffset() >= textSelection.getOffset())
          && (cursorNodeRegion.getOffset() <= textSelection.getOffset() + textSelection.getLength())
          && (cursorNodeRegion.getOffset() + cursorNodeRegion.getLength()
              >= textSelection.getOffset())
          && (cursorNodeRegion.getOffset() + cursorNodeRegion.getLength()
              <= textSelection.getOffset() + textSelection.getLength())) {
        Node newNode = cursorNode.getParentNode();

        if (newNode instanceof IndexedRegion) {
          IndexedRegion newIndexedRegion = (IndexedRegion) newNode;
          newRegion =
              new Region(
                  newIndexedRegion.getStartOffset(),
                  newIndexedRegion.getEndOffset() - newIndexedRegion.getStartOffset());
        }
      } else {
        newRegion = cursorNodeRegion;
      }
    }
    return newRegion;
  }
  public void run(ITextSelection selection) {

    if (!checkEnabled(selection)) return;

    IRegion region = new Region(selection.getOffset(), selection.getLength());
    PropertyKeyHyperlinkDetector detector = new PropertyKeyHyperlinkDetector();
    detector.setContext(fEditor);
    IHyperlink[] hyperlinks =
        detector.detectHyperlinks(fEditor.internalGetSourceViewer(), region, false);

    if (hyperlinks != null && hyperlinks.length == 1) hyperlinks[0].open();
  }
 static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection)
     throws JavaModelException {
   if (input instanceof ICodeAssist) {
     if (input instanceof ICompilationUnit) {
       reconcile((ICompilationUnit) input);
     }
     IJavaElement[] elements =
         ((ICodeAssist) input).codeSelect(selection.getOffset(), selection.getLength());
     if (elements != null && elements.length > 0) return elements;
   }
   return new IJavaElement[0];
 }
  private void doCutCopyWithImportsOperation() {
    ITextEditor editor = getTextEditor();
    ITypeRoot inputElement = JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
    ISelection selection = editor.getSelectionProvider().getSelection();

    Object clipboardData = null;
    if (inputElement != null && selection instanceof ITextSelection && !selection.isEmpty()) {
      ITextSelection textSelection = (ITextSelection) selection;
      if (isNonTrivialSelection(textSelection)) {
        clipboardData =
            getClipboardData(inputElement, textSelection.getOffset(), textSelection.getLength());
      }
    }

    fOperationTarget.doOperation(fOperationCode);

    if (clipboardData != null) {
      /*
       * We currently make assumptions about what the styled text widget sets,
       * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=61876
       */
      Clipboard clipboard = new Clipboard(getDisplay());
      try {
        Object textData = clipboard.getContents(TextTransfer.getInstance());
        /*
         * Don't add if we didn't get any text data from the clipboard, see:
         * - https://bugs.eclipse.org/bugs/show_bug.cgi?id=70077
         * - https://bugs.eclipse.org/bugs/show_bug.cgi?id=200743
         */
        if (textData == null) return;

        ArrayList<Object> datas = new ArrayList<Object>(3);
        ArrayList<ByteArrayTransfer> transfers = new ArrayList<ByteArrayTransfer>(3);
        datas.add(textData);
        transfers.add(TextTransfer.getInstance());

        Object rtfData = clipboard.getContents(RTFTransfer.getInstance());
        if (rtfData != null) {
          datas.add(rtfData);
          transfers.add(RTFTransfer.getInstance());
        }

        datas.add(clipboardData);
        transfers.add(fgTransferInstance);

        Transfer[] dataTypes = transfers.toArray(new Transfer[transfers.size()]);
        Object[] data = datas.toArray();
        setClipboardContents(clipboard, data, dataTypes);
      } finally {
        clipboard.dispose();
      }
    }
  }
 /* (non-JavaDoc)
  * Method declared in SelectionDispatchAction.
  */
 public final void run(ITextSelection ts) {
   ITypeRoot input = getEditorInput(fEditor);
   if (!ActionUtil.isProcessable(getShell(), input)) return;
   OccurrencesFinder finder = new OccurrencesFinder();
   FindOccurrencesEngine engine = FindOccurrencesEngine.create(finder);
   try {
     String result = engine.run(input, ts.getOffset(), ts.getLength());
     if (result != null) showMessage(getShell(), fEditor, result);
   } catch (JavaModelException e) {
     JavaPlugin.log(e);
   }
 }
  protected static IASTNode findEnclosingNode(IFortranAST ast, ITextSelection selection) {
    Token firstToken = findFirstTokenAfter(ast, selection.getOffset());
    Token lastToken =
        findLastTokenBefore(
            ast, OffsetLength.getPositionPastEnd(selection.getOffset(), selection.getLength()));
    if (firstToken == null || lastToken == null) return null;

    for (IASTNode parent = lastToken.getParent(); parent != null; parent = parent.getParent())
      if (contains(parent, firstToken)) return parent;

    return null;
  }
  private static IAction[] getTemplateActions(JavaEditor editor) {
    ITextSelection textSelection = getTextSelection(editor);
    if (textSelection == null || textSelection.getLength() == 0) return null;

    ICompilationUnit cu = JavaUI.getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
    if (cu == null) return null;

    QuickTemplateProcessor quickTemplateProcessor = new QuickTemplateProcessor();
    IInvocationContext context =
        new AssistContext(cu, textSelection.getOffset(), textSelection.getLength());

    try {
      IJavaCompletionProposal[] proposals = quickTemplateProcessor.getAssists(context, null);
      if (proposals == null || proposals.length == 0) return null;

      return getActionsFromProposals(proposals, context.getSelectionOffset(), editor.getViewer());
    } catch (CoreException e) {
      JavaPlugin.log(e);
    }
    return null;
  }
 @Override
 public void run(ITextSelection selection) {
   if (!ActionUtil.isEditable(fEditor)) return;
   ConvertGroovyLocalToFieldRefactoring refactoring =
       new ConvertGroovyLocalToFieldRefactoring(
           fEditor.getGroovyCompilationUnit(), selection.getOffset(), selection.getLength());
   new RefactoringStarter()
       .activate(
           new PromoteTempWizard(refactoring),
           getShell(),
           RefactoringMessages.ConvertLocalToField_title,
           RefactoringSaveHelper.SAVE_NOTHING);
 }
 /**
  * Provide the text selection that is needed to execute the command. Default implementation,
  * extend to Erlang elements selected.
  *
  * @param document text {@link IDocument}
  * @param selection selection affected by command (extended by extendSelection)
  * @return new {@link ITextSelection} with all text up to selection
  */
 protected ITextSelection getTextSelection(
     final IDocument document, final ITextSelection selection) {
   if (getTextEditor() instanceof ErlangEditor) {
     final ErlangEditor erlangEditor = (ErlangEditor) getTextEditor();
     final IErlModule module = erlangEditor.getModule();
     if (module != null) {
       final int offset1 = selection.getOffset(), offset2 = offset1 + selection.getLength();
       try {
         final IErlElement e1 = module.getElementAt(offset1);
         final IErlElement e2 = module.getElementAt(offset2);
         if (e1 instanceof ISourceReference) {
           final ISourceReference ref1 = (ISourceReference) e1;
           final ISourceRange r1 = ref1.getSourceRange();
           if (e1 == e2) {
             return extendSelectionToWholeLines(
                 document, new TextSelection(document, r1.getOffset(), r1.getLength()));
           } else if (e2 == null) {
             return extendSelectionToWholeLines(
                 document,
                 new TextSelection(
                     document,
                     r1.getOffset(),
                     selection.getLength() + selection.getOffset() - r1.getOffset()));
           } else if (e2 instanceof ISourceReference) {
             final ISourceReference ref2 = (ISourceReference) e2;
             final ISourceRange r2 = ref2.getSourceRange();
             return extendSelectionToWholeLines(
                 document,
                 new TextSelection(
                     document, r1.getOffset(), r2.getOffset() - r1.getOffset() + r2.getLength()));
           }
         }
       } catch (final ErlModelException e) {
       }
     }
   }
   return extendSelectionToWholeLines(document, selection);
 }