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;
 }
Esempio n. 2
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());
  }
 /** 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);
 }
  @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);
  }
 /**
  * Returns the variable and function names at the current line, or <code>null</code> if none.
  *
  * @param part text editor
  * @param selection text selection
  * @return the variable and function names at the current line, or <code>null</code> if none. The
  *     array has two elements, the first is the variable name, the second is the function name.
  */
 protected String[] getVariableAndFunctionName(IWorkbenchPart part, ISelection selection) {
   ITextEditor editor = getEditor(part);
   if (editor != null && selection instanceof ITextSelection) {
     ITextSelection textSelection = (ITextSelection) selection;
     IDocumentProvider documentProvider = editor.getDocumentProvider();
     try {
       documentProvider.connect(this);
       IDocument document = documentProvider.getDocument(editor.getEditorInput());
       IRegion region = document.getLineInformationOfOffset(textSelection.getOffset());
       String string = document.get(region.getOffset(), region.getLength()).trim();
       if (string.startsWith("var ")) { // $NON-NLS-1$
         String varName = string.substring(4).trim();
         String fcnName =
             getFunctionName(
                 document, varName, document.getLineOfOffset(textSelection.getOffset()));
         return new String[] {varName, fcnName};
       }
     } catch (CoreException e) {
     } catch (BadLocationException e) {
     } finally {
       documentProvider.disconnect(this);
     }
   }
   return null;
 }
 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);
 }
  /*
   * 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();
    }
  }
Esempio n. 8
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);
         }
       }
     }
   }
 }
 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;
 }
  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;
  }
  protected void setEditorTextPreservingCarret(String newContents) throws CommonException {
    if (areEqual(newContents, doc.get())) {
      return;
    }

    LangSourceViewer sourceViewer = getEditorSourceViewer();

    ISelection sel = sourceViewer.getSelectionProvider().getSelection();

    int line = -1;
    int col = -1;
    if (sel instanceof ITextSelection) {
      ITextSelection textSelection = (ITextSelection) sel;

      try {
        line = doc.getLineOfOffset(textSelection.getOffset());
        col = textSelection.getOffset() - doc.getLineOffset(line);
      } catch (BadLocationException e) {
        // Ignore
      }
    }

    IDocument document = sourceViewer.getDocument();

    if (document instanceof IDocumentExtension4) {
      IDocumentExtension4 doc_4 = (IDocumentExtension4) document;
      // We use the DocumentRewriteSession to prevent the caret from jumping around
      DocumentRewriteSession rewriteSession =
          doc_4.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
      document.set(newContents);
      doc_4.stopRewriteSession(rewriteSession);
    } else {
      int topIndex = sourceViewer.getTopIndex();
      document.set(newContents);
      sourceViewer.setTopIndex(topIndex);
    }

    int newOffset = -1;
    if (line != -1 && col != -1) {
      try {
        newOffset = getOffsetFor(line, col);
      } catch (BadLocationException e) {
        // ignore
      }
    }

    if (newOffset != -1) {
      sourceViewer.getSelectionProvider().setSelection(new TextSelection(newOffset, 0));
    } else {
      sourceViewer.getSelectionProvider().setSelection(sel);
    }
  }
 /**
  * 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;
 }
 static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection)
     throws JavaModelException {
   if (input instanceof ICompilationUnit) {
     ICompilationUnit cunit = (ICompilationUnit) input;
     reconcile(cunit);
     IJavaElement ref = cunit.getElementAt(selection.getOffset());
     if (ref == null) return input;
     else return ref;
   } else if (input instanceof IClassFile) {
     IJavaElement ref = ((IClassFile) input).getElementAt(selection.getOffset());
     if (ref == null) return input;
     else return ref;
   }
   return input;
 }
Esempio n. 15
0
  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;
  }
Esempio n. 16
0
 public SearchPatternData tryErlangTextSelection(
     final SearchPatternData initData0, final IEditorPart activePart) throws ErlModelException {
   final AbstractErlangEditor erlangEditor = (AbstractErlangEditor) activePart;
   final IErlModule module = erlangEditor.getModule();
   SearchPatternData initData = initData0;
   if (module != null) {
     final ISelection ssel = erlangEditor.getSite().getSelectionProvider().getSelection();
     final ITextSelection textSel = (ITextSelection) ssel;
     final int offset = textSel.getOffset();
     OpenResult res;
     try {
       res =
           ErlangEngine.getInstance()
               .getService(OpenService.class)
               .open(
                   module.getScannerName(),
                   offset,
                   ErlangEngine.getInstance().getModelUtilService().getImportsAsList(module),
                   "",
                   ErlangEngine.getInstance().getModel().getPathVars());
     } catch (final RpcException e) {
       res = null;
     }
     ErlLogger.debug("searchPage(open) " + res);
     initData = determineInitValuesFrom(module, offset, res);
   }
   return initData;
 }
 public static SurroundWithTryCatchRefactoring create(
     ICompilationUnit cu, ITextSelection selection, boolean isMultiCatch) {
   return new SurroundWithTryCatchRefactoring(
       cu,
       Selection.createFromStartLength(selection.getOffset(), selection.getLength()),
       isMultiCatch);
 }
Esempio n. 18
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();
      }
    }
  }
Esempio n. 19
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;
 }
Esempio n. 21
0
  /*
   * Method declared on SelectionChangedAction.
   */
  @Override
  public void run(final ITextSelection selection) {
    // if (!ActionUtil.isProcessable(fEditor)) {
    // return;
    // }
    IErlModule module = fEditor.getModule();
    if (module == null) {
      return;
    }
    final Backend b = ErlangCore.getBackendManager().getIdeBackend();
    final ISelection sel = getSelection();
    final ITextSelection textSel = (ITextSelection) sel;
    final int offset = textSel.getOffset();
    try {
      String scannerModuleName = ErlangToolkit.createScannerModuleName(module);
      final OpenResult res =
          ErlideOpen.open(b, scannerModuleName, offset, "", ErlangCore.getModel().getPathVars());
      ErlLogger.debug("open " + res);

      // final String title =
      // "SearchMessages.SearchElementSelectionDialog_title";
      // final String message =
      // "SearchMessages.SearchElementSelectionDialog_message";

      if (res.isExternalCall()) {
        performNewSearch(SearchUtil.getRefFromOpenRes(res));
      }
    } catch (final Exception e) {
      // final String title = "SearchMessages.Search_Error_search_title";
      // final String message = "SearchMessages.Search_Error_codeResolve";
      // ExceptionHandler.handle(e, getShell(), title, message);
      ErlLogger.debug(e);
    }
  }
Esempio n. 22
0
  private IModelElement getEnclosingMethod(IModelElement input, ITextSelection selection) {
    IModelElement enclosingElement = null;
    try {
      switch (input.getElementType()) {
          //                case IModelElement.CLASS_FILE :
          //                    IClassFile classFile= (IClassFile)
          // input.getAncestor(IModelElement.CLASS_FILE);
          //                    if (classFile != null) {
          //                        enclosingElement= classFile.getElementAt(selection.getOffset());
          //                    }
          //                    break;
        case IModelElement.SOURCE_MODULE:
          ISourceModule cu = (ISourceModule) input.getAncestor(IModelElement.SOURCE_MODULE);
          if (cu != null) {
            enclosingElement = cu.getElementAt(selection.getOffset());
          }
          break;
      }
      if (enclosingElement != null && enclosingElement.getElementType() == IModelElement.METHOD) {
        return enclosingElement;
      }
    } catch (ModelException e) {
      DLTKUIPlugin.log(e);
    }

    return null;
  }
  @Override
  public void doRun(
      ITextSelection selection, Event event, UIInstrumentationBuilder instrumentation) {

    if (!ActionUtil.isEditable(fEditor)) {
      instrumentation.metric("Problem", "Editor not editable");
      return;
    }

    CompilationUnit cu = SelectionConverter.getInputAsCompilationUnit(fEditor);
    instrumentation.record(cu);
    try {
      DartFunction function = DartModelUtil.findFunction(cu, selection.getOffset());
      instrumentation.data("function", function.getSource());

      boolean success =
          RefactoringExecutionStarter_OLD.startConvertGetterToMethodRefactoring(
              function, getShell());

      if (success) {
        return;
      }
      instrumentation.metric(
          "Problem", "RefactoringExecutionStarter.startConvertGetterToMethodRefactoring False");

    } catch (Throwable e) {
      instrumentation.record(e);
    }

    instrumentation.metric("Problem", "No valid selection, showing dialog");
    MessageDialog.openInformation(
        getShell(),
        RefactoringMessages.ConvertGetterToMethodAction_dialog_title,
        RefactoringMessages.ConvertGetterToMethodAction_select);
  }
Esempio n. 24
0
 /**
  * @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;
 }
  protected IndexedRegion getCursorIndexedRegion(IDocument document, ITextSelection textSelection) {
    IndexedRegion indexedRegion = null;

    indexedRegion = getIndexedRegion(document, textSelection.getOffset());

    return indexedRegion;
  }
Esempio n. 26
0
 /*
  * (non-Javadoc) Method declared on SelectionDispatchAction.
  */
 @Override
 public void run(final ITextSelection selection) {
   final ErlangEditor editor = (ErlangEditor) getSite().getPage().getActiveEditor();
   editor.reconcileNow();
   final IErlModule module = editor.getModule();
   if (module == null) {
     return;
   }
   final Backend b = ErlangCore.getBackendManager().getIdeBackend();
   final int offset = selection.getOffset();
   try {
     final IErlProject erlProject = module.getErlProject();
     final IErlModel model = ErlangCore.getModel();
     final OpenResult res =
         ErlideOpen.open(
             b,
             ErlangToolkit.createScannerModuleName(module),
             offset,
             ErlModelUtils.getImportsAsList(module),
             model.getExternalModules(erlProject),
             model.getPathVars());
     ErlLogger.debug("open " + res);
     openOpenResult(editor, module, b, offset, erlProject, res);
   } catch (final Exception e) {
     ErlLogger.warn(e);
   }
 }
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    DMDLMultiPageEditor multiEditor = (DMDLMultiPageEditor) HandlerUtil.getActiveEditor(event);
    DMDLTextEditor editor = (DMDLTextEditor) multiEditor.getActiveEditor();
    DMDLDocument document = editor.getDocument();
    ModelList models = document.getModelList();

    ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
    int offset = selection.getOffset();
    DMDLToken token = models.getTokenByOffset(offset);
    if (token != null && token instanceof WordToken) {
      WordToken word = (WordToken) token;
      switch (word.getWordType()) {
        case REF_MODEL_NAME:
        case REF_PROPERTY_NAME:
          DMDLHyperlink link = new DMDLHyperlink(editor, token);
          link.open();
          break;
        default:
          break;
      }
    }

    return null;
  }
  protected static boolean nodeExactlyEnclosesRegion(
      IASTNode node, IFortranAST ast, ITextSelection selection) {
    Token firstInNode = node.findFirstToken();
    Token lastInNode = node.findLastToken();

    Token firstInSel = findFirstTokenAfter(ast, selection.getOffset());
    Token lastInSel =
        findLastTokenBefore(
            ast, OffsetLength.getPositionPastEnd(selection.getOffset(), selection.getLength()));

    return firstInNode != null
        && lastInNode != null
        && firstInSel != null
        && lastInSel != null
        && firstInNode == firstInSel
        && lastInNode == lastInSel;
  }
 /* (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());
 }
  /**
   * {@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);
  }