Java 类org.eclipse.jface.text.ITextSelection 实例源码

项目:lcdsl    文件:AbstractLaunchConfigGeneratorHandler.java   
protected LaunchConfig getLaunchConfigFromEditor(ExecutionEvent event) {
    XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
    if (activeXtextEditor == null) {
        return null;
    }
    final ITextSelection selection = (ITextSelection) activeXtextEditor.getSelectionProvider().getSelection();
    return activeXtextEditor.getDocument().priorityReadOnly(new IUnitOfWork<LaunchConfig, XtextResource>() {

        @Override
        public LaunchConfig exec(XtextResource xTextResource) throws Exception {
            EObject lc = eObjectAtOffsetHelper.resolveContainedElementAt(xTextResource, selection.getOffset());
            return findParentLaunchConfig(lc);
        }

    });
}
项目:vertigo-chroma-kspplugin    文件:UiUtils.java   
public static String getCurrentEditorCurrentWord(WordSelectionType wordSelectionType) {
    IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    /* Extrait l'éditeur courant. */
    ITextEditor editor = (ITextEditor) activePage.getActiveEditor();
    if (editor == null) {
        return null;
    }

    /* Extrait la sélection courante. */
    ITextSelection selection = (ITextSelection) activePage.getSelection();
    if (selection == null) {
        return null;
    }

    /* Extrait le document courant. */
    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());

    /* Extrait le mot sélectionné. */
    ITextSelection currentWordSelection = DocumentUtils.findCurrentWord(document, selection, wordSelectionType);
    if (currentWordSelection == null) {
        return null;
    }

    return currentWordSelection.getText();
}
项目:vertigo-chroma-kspplugin    文件:KspTextHover.java   
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {

    IDocument document = textViewer.getDocument();

    /* Vérifie qu'on est dans une String de KSP */
    boolean isSqlString = DocumentUtils.isContentType(document, offset, KspRegionType.STRING);
    if (!isSqlString) {
        return null;
    }

    /* Extrait le mot courant. */
    ITextSelection selection = new TextSelection(document, offset, 0);
    ITextSelection currentWordSelection = DocumentUtils.findCurrentWord(document, selection, WordSelectionType.SNAKE_CASE);
    if (currentWordSelection == null) {
        return null;
    }
    String currentWord = currentWordSelection.getText();
    if (currentWord == null) {
        return null;
    }

    /* Renvoie la région du mot. */
    return new Region(currentWordSelection.getOffset(), currentWordSelection.getLength());
}
项目:vertigo-chroma-kspplugin    文件:BaseContentAssistProcessor.java   
/**
 * Constuit les propositions d'aucomplétion.
 * 
 * @param suggestions Suggestionsà proposer.
 * @param currentWordSelection Mot courant à remplacer dans le document.
 * @return Propositions d'autocomplétion.
 */
private ICompletionProposal[] buildProposals(List<CompletionCandidate> suggestions, ITextSelection currentWordSelection) {
    /* Calcul l'offset et la longueur du mot à remplacer dans le document. */
    int replacementLength = currentWordSelection.getLength();
    int replacementOffset = currentWordSelection.getOffset();

    /* Construit les propositions en parcourant les suggestions. */
    List<ICompletionProposal> proposals = new ArrayList<>();
    for (CompletionCandidate suggestion : suggestions) {
        /* String qui remplacera le mot courant. */
        String replacementString = suggestion.getDisplayString();

        /* String affiché comme libellé de la proposition. */
        String displayString = replacementString;

        /* String affiché comme description de la proposition (dans la boîte jaune). */
        String additionalProposalInfo = suggestion.getAdditionalProposalInfo();
        CompletionProposal proposal = new CompletionProposal(replacementString, replacementOffset, replacementLength, replacementString.length(), null,
                displayString, null, additionalProposalInfo);
        proposals.add(proposal);
    }
    return proposals.toArray(new ICompletionProposal[0]);
}
项目:vertigo-chroma-kspplugin    文件:KspStringContentAssistProcessor.java   
@Override
protected List<CompletionCandidate> getCandidates(ITextSelection currentWordSelection) {
    List<CompletionCandidate> list = new ArrayList<>();

    /* Trouve la déclaration contenant le nom de paramètre. */
    IFile file = UiUtils.getCurrentEditorFile();
    FileRegion fileRegion = new FileRegion(file, currentWordSelection.getOffset(), currentWordSelection.getLength());
    KspDeclaration declaration = KspManager.getInstance().findDeclarationAt(fileRegion);
    if (declaration == null) {
        return list;
    }

    /* Construit les candidats */
    for (KspAttribute attribute : declaration.getAttributes()) {
        handleAttribute(attribute, list);
    }

    /* Tri par libellé. */
    list.sort((o1, o2) -> o1.getDisplayString().compareTo(o2.getDisplayString()));

    return list;
}
项目:dsp4e    文件:DSPBreakpointAdapter.java   
@Override
public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
    ITextEditor textEditor = getEditor(part);
    if (textEditor != null) {
        IResource resource = textEditor.getEditorInput().getAdapter(IResource.class);
        ITextSelection textSelection = (ITextSelection) selection;
        int lineNumber = textSelection.getStartLine();
        IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager()
                .getBreakpoints(DSPPlugin.ID_DSP_DEBUG_MODEL);
        for (int i = 0; i < breakpoints.length; i++) {
            IBreakpoint breakpoint = breakpoints[i];
            if (breakpoint instanceof ILineBreakpoint && resource.equals(breakpoint.getMarker().getResource())) {
                if (((ILineBreakpoint) breakpoint).getLineNumber() == (lineNumber + 1)) {
                    // remove
                    breakpoint.delete();
                    return;
                }
            }
        }
        // create line breakpoint (doc line numbers start at 0)
        DSPLineBreakpoint lineBreakpoint = new DSPLineBreakpoint(resource, lineNumber + 1);
        DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(lineBreakpoint);
    }
}
项目:Tarski    文件:MarkerFactory.java   
/**
 * @param resource
 * @param selection
 * @returns list of markers which are found by selection
 */
public static ArrayList<IMarker> findMarkersInSelection(final IResource resource,
    final ITextSelection selection) {
  final ArrayList<IMarker> markerListInArea = new ArrayList<>();
  final ArrayList<IMarker> markerList = MarkerFactory.findMarkersAsArrayList(resource);

  if (markerList.isEmpty()) {
    return null;
  }
  final int textStart = selection.getOffset();
  final int textEnd = textStart + selection.getLength();

  for (final IMarker iMarker : markerList) {
    final int markerStart = MarkUtilities.getStart(iMarker);
    final int markerEnd = MarkUtilities.getEnd(iMarker);
    if (textStart >= markerStart && textStart <= markerEnd
        || textEnd >= markerStart && textEnd <= markerEnd
        || markerStart >= textStart && markerStart <= textEnd
        || markerEnd >= textStart && markerEnd <= textEnd) {

      markerListInArea.add(iMarker);
    }
  }
  return markerListInArea;
}
项目:subclipse    文件:TeamAction.java   
public void selectionChanged(IAction action, ISelection sel) {
    if (sel instanceof IStructuredSelection) {
        this.selection = (IStructuredSelection) sel;
        if (action != null) {
            setActionEnablement(action);
        }
    }
    if (sel instanceof ITextSelection){
            IEditorPart part = getTargetPage().getActiveEditor();
            if (part != null) {
                IEditorInput input = part.getEditorInput();
                IResource r = (IResource) input.getAdapter(IResource.class);
                if (r != null) {
                    switch(r.getType()){
                        case IResource.FILE:
                            this.selection = new StructuredSelection(r);
                            if (action != null) {
                                setActionEnablement(action);
                            }
                        break;
                    }
                }   //  set selection to current editor file;
            }
    }
}
项目:subclipse    文件:AnnotateView.java   
/**
 * A selection event in the Annotate Source Editor
 * @param event
 */
private void textSelectionChanged(ITextSelection selection) {

    // Track where the last selection event came from to avoid
    // a selection event loop.
    lastSelectionWasText = true;

    // Locate the annotate block containing the selected line number.
    AnnotateBlock match = null;
    for (Iterator iterator = svnAnnotateBlocks.iterator(); iterator.hasNext();) {
        AnnotateBlock block = (AnnotateBlock) iterator.next();
        if (block.contains(selection.getStartLine())) {
            match = block;
            break;
        }
    }

    // Select the annotate block in the List View.
    if (match == null) {
        return;
    }

    StructuredSelection listSelection = new StructuredSelection(match); 
    viewer.setSelection(listSelection, true);
}
项目:ftc    文件:TweakedLinkedModeUI.java   
public void selectionChanged(SelectionChangedEvent event) {
    ISelection selection = event.getSelection();
    if (selection instanceof ITextSelection) {
        ITextSelection textsel = (ITextSelection) selection;
        if (event.getSelectionProvider() instanceof ITextViewer) {
            IDocument doc = ((ITextViewer) event.getSelectionProvider()).getDocument();
            if (doc != null) {
                int offset = textsel.getOffset();
                int length = textsel.getLength();
                if (offset >= 0 && length >= 0) {
                    LinkedPosition find = new LinkedPosition(doc, offset, length, LinkedPositionGroup.NO_STOP);
                    LinkedPosition pos = fModel.findPosition(find);
                    if (pos == null && fExitPosition != null && fExitPosition.includes(find))
                        pos = fExitPosition;

                    if (pos != null)
                        switchPosition(pos, false, false);
                }
            }
        }
    }
}
项目:texlipse    文件:TexSelections.java   
/**
 * Takes a text editor as a parameter and sets variables 
 * to correspond selection features.
 * 
 * @param textEditor The currenct text editor
 */
public TexSelections(ITextEditor textEditor) {

    // Get the document
    this.document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    this.editor = textEditor;

    // Get the selection
    this.textSelection = (ITextSelection) this.editor.getSelectionProvider().getSelection();

    this.startLineIndex = this.textSelection.getStartLine();
    this.endLineIndex = this.textSelection.getEndLine();
    this.selLength = this.textSelection.getLength();

    // Store selection information
    select();
}
项目:texlipse    文件:TexInsertMathSymbolAction.java   
public void run() {
    if (editor == null)
        return;
    ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
    IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
    TexCompletionProposal prop = new TexCompletionProposal(entry, selection.getOffset() + 1, 0, 
            editor.getViewer());
    try {
        // insert a backslash first
        doc.replace(selection.getOffset(), 0, "\\");
        prop.apply(doc);
        int newOffset = selection.getOffset() + entry.key.length() + 1;
        if (entry.arguments > 0) {
            newOffset += 1;
        }
        editor.getSelectionProvider().setSelection(new TextSelection(newOffset, 0));
    } catch (BadLocationException e) {
        TexlipsePlugin.log("Error while trying to insert command", e);
    }
}
项目:texlipse    文件:TexQuoteListener.java   
public void documentChanged(DocumentEvent event) {
    // if this is enabled
    if ("\"".equals(event.getText())) {
        ITextSelection textSelection = (ITextSelection) this.editor.getSelectionProvider().getSelection();            
        try {
            char prev = document.getChar(textSelection.getOffset() - 1);
            String replacement = "\"";
            // TODO null checks?
            IProject project = ((FileEditorInput)editor.getEditorInput()).getFile().getProject();
            String lang = TexlipseProperties.getProjectProperty(project, TexlipseProperties.LANGUAGE_PROPERTY);
            if (Character.isWhitespace(prev)) {
                replacement = (String) quotes.get(lang + "o");
            } else if (Character.isLetterOrDigit(prev)) {
                replacement = (String) quotes.get(lang + "c");
            } else {
                return;
            }
            document.removeDocumentListener(this);
            document.replace(textSelection.getOffset(), 1, replacement);
            document.addDocumentListener(this);
            //editor.resetHighlightRange();
            //editor.setHighlightRange(textSelection.getOffset() + 1, 1, true);
            //editor.getSelectionProvider().setSelection(new TextSelection(textSelection.getOffset() + 3, 5));
        } catch (BadLocationException e) {}
    }
}
项目:mesfavoris    文件:TextEditorBookmarkPropertiesProvider.java   
private void addBookmarkProperties(Map<String, String> properties, ITextEditor textEditor,
        ITextSelection textSelection) {
    int lineNumber = textSelection.getStartLine();
    addLineNumber(properties, lineNumber);
    addLineContent(properties, textEditor, lineNumber);
    addWorkspacePath(properties, textEditor);
    putIfAbsent(properties, PROPERTY_NAME, () -> {
        String lineContent = properties.get(PROP_LINE_CONTENT);
        if (lineContent != null) {
            return textEditor.getEditorInput().getName() + " : " + lineContent;
        } else {
            return textEditor.getEditorInput().getName();
        }
    });
    IPath filePath = getFilePath(textEditor);
    if (filePath != null) {
        addFilePath(properties, filePath);
    }
}
项目:mesfavoris    文件:BookmarksViewTest.java   
@Test
public void testGotoBookmarkOnDoubleClick() throws Exception {
    // Given
    Bookmark bookmark = new Bookmark(new BookmarkId(), ImmutableMap.of(Bookmark.PROPERTY_NAME, "bookmark",
            PROP_WORKSPACE_PATH, "/BookmarksViewTest/src/main/java/org/apache/commons/cli/DefaultParser.java",
            PROP_LINE_CONTENT,
            "for (Enumeration<?> enumeration = properties.propertyNames(); enumeration.hasMoreElements();)"));
    addBookmark(getBookmarksRootFolderId(), bookmark);
    SWTBotTreeItem bookmarkTreeItem = waitUntil("Cannot find new bookmark",
            () -> bookmarksViewDriver.tree().getTreeItem("bookmark"));

    // When
    bookmarkTreeItem.doubleClick();

    // Then
    waitUntil("cannot go to bookmark", () -> "DefaultParser.java".equals(getActivePart().getTitle()));
    IWorkbenchPart workbenchPart = getActivePart();
    ITextSelection selection = (ITextSelection) getSelection(workbenchPart);
    assertEquals("DefaultParser.java", workbenchPart.getTitle());
    assertEquals(146, selection.getStartLine());
}
项目:mesfavoris    文件:GotoBookmarkOperationTest.java   
@Test
public void testGotoBookmark() throws Exception {
    // Given
    Bookmark bookmark = bookmark(new BookmarkId(), "LICENSE.txt")
            .withProperty(PROP_WORKSPACE_PATH, "/gotoBookmarkOperationTest/LICENSE.txt")
            .withProperty(PROP_LINE_NUMBER, "10").build();
    addBookmark(new BookmarkId("rootFolder"), bookmark);

    // When
    gotoBookmarkOperation.gotoBookmark(bookmark.getId(), new NullProgressMonitor());

    // Then
    IWorkbenchPart workbenchPart = getActivePart();
    ITextSelection selection = (ITextSelection) getSelection(workbenchPart);
    assertEquals("LICENSE.txt", workbenchPart.getTitle());
    assertEquals(10, selection.getStartLine());
    waitUntil("Cannot find marker", () -> bookmarksMarkers.findMarker(bookmark.getId(), null));
}
项目:code    文件:RelatedObjectsEdges.java   
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
    if (selection instanceof ITextSelection) {
        ASTNode node = ASTUtils.getASTNode((ITextSelection) selection);
        if (node != null) {
            String string = node.toString();
            CharSequence subSequence = string.subSequence(0,
                    string.length() > 100 ? 100 : string.length());
            RelatedObjectsEdges.this.setContentDescription(subSequence.toString()
                    .trim());
            RelatedObjectsEdges.this.fTreeViewer.setInput(node);
            RelatedObjectsEdges.this.fTreeViewer.expandAll();
            RelatedObjectsEdges.this.tableViewer.setInput(null);
        }
    }

}
项目:tlaplus    文件:ToggleCommentAction.java   
/**
 * 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
        // TODO
    }

    return null;
}
项目:fluentmark    文件:SmartAutoEditStrategy.java   
/**
 * Computes an insert position for an opening brace if <code>offset</code> maps to a position in
 * <code>doc</code> involving a keyword taking a block after it. These are: <code>try</code>,
 * <code>do</code>, <code>synchronized</code>, <code>static</code>, <code>finally</code>, or
 * <code>else</code>.
 *
 * @param doc the document being modified
 * @param line the current line under investigation
 * @param offset the offset of the caret position, relative to the line start.
 * @return an insert position relative to the line start if <code>line</code> contains one of
 *         the above keywords at or before <code>offset</code>, -1 otherwise
 */
private static int computeAfterTryDoElse(IDocument doc, ITextSelection line, int offset) {
    // search backward while WS, find 'try', 'do', 'else' in default partition
    int p = offset + line.getOffset();
    p = firstWhitespaceToRight(doc, p);
    if (p == -1) return -1;
    p--;

    if (looksLike(doc, p, "try") //$NON-NLS-1$
            || looksLike(doc, p, "do")  //$NON-NLS-1$
            || looksLike(doc, p, "synchronized")  //$NON-NLS-1$
            || looksLike(doc, p, "static")  //$NON-NLS-1$
            || looksLike(doc, p, "finally")  //$NON-NLS-1$
            || looksLike(doc, p, "else"))  //$NON-NLS-1$
        return p + 1 - line.getOffset();

    return -1;
}
项目:fluentmark    文件:FluentMkEditor.java   
/**
 * Reveals the specified ranges in this text editor.
 *
 * @param offset the offset of the revealed range
 * @param len the length of the revealed range
 */
protected void reveal(int offset, int len) {
    if (viewer == null) return;

    ISelection sel = getSelectionProvider().getSelection();
    if (sel instanceof ITextSelection) {
        ITextSelection tsel = (ITextSelection) sel;
        if (tsel.getOffset() != 0 || tsel.getLength() != 0) markInNavigationHistory();
    }

    StyledText widget = viewer.getTextWidget();
    widget.setRedraw(false);
    setHighlightRange(offset, len, false);
    viewer.revealRange(offset, len);
    markInNavigationHistory();
    widget.setRedraw(true);
}
项目:fluentmark    文件:FluentMkEditor.java   
@Override
public boolean show(ShowInContext context) {
    ISelection selection = context.getSelection();
    if (selection instanceof IStructuredSelection) {
        for (Object element : ((IStructuredSelection) selection).toArray()) {
            if (element instanceof PagePart) {
                PagePart item = (PagePart) element;
                revealPart(item);
                if (isOutlinePageValid()) {
                    outlinePage.setSelection(selection);
                }
                return true;
            }
        }
    } else if (selection instanceof ITextSelection) {
        ITextSelection textSel = (ITextSelection) selection;
        selectAndReveal(textSel.getOffset(), textSel.getLength());
        return true;
    }
    return false;
}
项目:typescript.java    文件:OpenSymbolSelectionDialog.java   
@Override
public int open() {
    if (getInitialPattern() == null) {
        IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (window != null) {
            ISelection selection = window.getSelectionService().getSelection();
            if (selection instanceof ITextSelection) {
                String text = ((ITextSelection) selection).getText();
                if (text != null) {
                    text = text.trim();
                    if (text.length() > 0) {
                        setInitialPattern(text);
                    }
                }
            }
        }
    }
    return super.open();
}
项目:APICloud-Studio    文件:TeamAction.java   
public void selectionChanged(IAction action, ISelection sel) {
    if (sel instanceof IStructuredSelection) {
        this.selection = (IStructuredSelection) sel;
        if (action != null) {
            setActionEnablement(action);
        }
    }
    if (sel instanceof ITextSelection){
            IEditorPart part = getTargetPage().getActiveEditor();
            if (part != null) {
                IEditorInput input = part.getEditorInput();
                IResource r = (IResource) input.getAdapter(IResource.class);
                if (r != null) {
                    switch(r.getType()){
                        case IResource.FILE:
                            this.selection = new StructuredSelection(r);
                            if (action != null) {
                                setActionEnablement(action);
                            }
                        break;
                    }
                }   //  set selection to current editor file;
            }
    }
}
项目:typescript.java    文件:NpmModuleVersionsSelectionDialog.java   
@Override
public int open() {
    if (getInitialPattern() == null) {
        IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (window != null) {
            ISelection selection = window.getSelectionService().getSelection();
            if (selection instanceof ITextSelection) {
                String text = ((ITextSelection) selection).getText();
                if (text != null) {
                    text = text.trim();
                    if (text.length() > 0) {
                        setInitialPattern(text);
                    }
                }
            }
        }
    }
    return super.open();
}
项目:typescript.java    文件:ImplementationsCodeLens.java   
@Override
public void open() {
    // Open Implementation dialog
    Display.getDefault().asyncExec(() -> {
        try {
            Shell parent = Display.getDefault().getActiveShell();
            TypeScriptImplementationDialog dialog = new TypeScriptImplementationDialog(parent, SWT.RESIZE, tsFile);
            int offset = tsFile.getPosition(getRange().startLineNumber, getRange().startColumn);
            ITextSelection selection = new TextSelection(offset, 1);
            dialog.setSize(450, 500);
            dialog.setInput(selection);
            dialog.open();
        } catch (TypeScriptException e) {
            e.printStackTrace();
        }
    });
}
项目:typescript.java    文件:RefactorActionGroup.java   
private void refactorMenuShown(IMenuManager refactorSubmenu) {
    // we know that we have an MenuManager since we created it in
    // addRefactorSubmenu.
    Menu menu = ((MenuManager) refactorSubmenu).getMenu();
    menu.addMenuListener(new MenuAdapter() {
        @Override
        public void menuHidden(MenuEvent e) {
            refactorMenuHidden();
        }
    });
    ITextSelection textSelection = (ITextSelection) fEditor.getSelectionProvider().getSelection();
    // JavaTextSelection javaSelection= new
    // JavaTextSelection(getEditorInput(), getDocument(),
    // textSelection.getOffset(), textSelection.getLength());

    for (Iterator<SelectionDispatchAction> iter = fActions.iterator(); iter.hasNext();) {
        SelectionDispatchAction action = iter.next();
        action.update(textSelection);
    }
    refactorSubmenu.removeAll();
    if (fillRefactorMenu(refactorSubmenu) == 0)
        refactorSubmenu.add(fNoActionAvailable);
}
项目:typescript.java    文件:TypeScriptEditor.java   
public void selectionChanged(SelectionChangedEvent event) {
    // TypeScriptEditor.this.selectionChanged();

    ISelection selection = event.getSelection();
    if (selection instanceof ITextSelection) {
        // Update occurrences
        ITextSelection textSelection = (ITextSelection) selection;
        updateOccurrenceAnnotations(textSelection);

        TypeScriptContentOutlinePage outlinePage = getOutlinePage();
        if (outlinePage != null && outlinePage.isLinkingEnabled()) {
            fOutlineSelectionChangedListener.uninstall(outlinePage);
            outlinePage.setSelection(selection);
            fOutlineSelectionChangedListener.install(outlinePage);
        }
    }
}
项目:typescript.java    文件:TypeScriptEditor.java   
protected void installOccurrencesFinder(boolean forceUpdate) {
    fMarkOccurrenceAnnotations = true;

    // fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
    // public void selectionChanged(IEditorPart part, ITextSelection
    // selection, JavaScriptUnit astRoot) {
    // updateOccurrenceAnnotations(selection, astRoot);
    // }
    // };
    // SelectionListenerWithASTManager.getDefault().addListener(this,
    // fPostSelectionListenerWithAST);
    if (forceUpdate && getSelectionProvider() != null) {
        fForcedMarkOccurrencesSelection = getSelectionProvider().getSelection();
        updateOccurrenceAnnotations((ITextSelection) fForcedMarkOccurrencesSelection);
    }

    if (fOccurrencesFinderJobCanceler == null) {
        fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler();
        fOccurrencesFinderJobCanceler.install();
    }
}
项目:typescript.java    文件:TypeScriptEditor.java   
protected void doSelectionChanged(SelectionChangedEvent event) {
    ISelection selection = event.getSelection();
    NavigationBarItem item = null;
    Iterator iter = ((IStructuredSelection) selection).iterator();
    while (iter.hasNext()) {
        Object o = iter.next();
        if (o instanceof NavigationBarItem) {
            item = (NavigationBarItem) o;
            break;
        }
    }

    setSelection(item, !isActivePart());

    ISelectionProvider selectionProvider = getSelectionProvider();
    if (selectionProvider == null)
        return;

    ISelection textSelection = selectionProvider.getSelection();
    if (!(textSelection instanceof ITextSelection))
        return;

    fForcedMarkOccurrencesSelection = textSelection;
    updateOccurrenceAnnotations((ITextSelection) textSelection);

}
项目:APICloud-Studio    文件:OpenDeclarationAction.java   
/**
 * Open the declaration if possible.
 */
@Override
public void run()
{
    ITextEditor textEditor = getTextEditor();

    if (textEditor instanceof JSSourceEditor)
    {
        ITextSelection selection = (ITextSelection) textEditor.getSelectionProvider().getSelection();
        IRegion region = new Region(selection.getOffset(), 1);
        JSHyperlinkDetector detector = new JSHyperlinkDetector();
        IHyperlink[] hyperlinks = detector.detectHyperlinks((AbstractThemeableEditor) textEditor, region, true);

        if (!ArrayUtil.isEmpty(hyperlinks))
        {
            // give first link highest precedence
            hyperlinks[0].open();
        }
    }
}
项目:Source    文件:ObjectToLocationAdapterFactory.java   
/**
 * {@inheritDoc}
 *
 * @see org.eclipse.core.runtime.IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class)
 */
public Object getAdapter(Object adaptableObject, @SuppressWarnings("rawtypes") Class adapterType) {
    final Object res;

    final Object superRes = super.getAdapter(adaptableObject, adapterType);
    if (superRes != null) {
        res = superRes;
    } else {
        if (adaptableObject instanceof IStructuredSelection) {
            final Object firstElement = ((IStructuredSelection)adaptableObject).getFirstElement();
            if (firstElement instanceof ILocation) {
                res = (ILocation)firstElement;
            } else {
                res = selectionToLocationDescriptor((IStructuredSelection)adaptableObject);
            }
        } else if (adaptableObject instanceof ITextSelection) {
            res = textSelectionToLocationDescriptor((ITextSelection)adaptableObject);
        } else {
            res = objectToLocationDescriptor(adaptableObject);
        }
    }

    return adapt(res, adapterType);
}
项目:bts    文件:XtextEObjectSearchDialog.java   
@Override
public int open() {
    if (getInitialPattern() == null) {
        IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (window != null) {
            ISelection selection = window.getSelectionService().getSelection();
            if (selection instanceof ITextSelection) {
                String text = ((ITextSelection) selection).getText();
                if (text != null) {
                    text = text.trim();
                    if (text.length() > 0) {
                        setInitialPattern(text);
                    }
                }
            }
        }
    }
    return super.open();
}
项目:bts    文件:TextViewerMoveLinesAction.java   
/**
 * Given a selection on a document, computes the lines fully or partially covered by
 * <code>selection</code>. A line in the document is considered covered if
 * <code>selection</code> comprises any characters on it, including the terminating delimiter.
 * <p>Note that the last line in a selection is not considered covered if the selection only
 * comprises the line delimiter at its beginning (that is considered part of the second last
 * line).
 * As a special case, if the selection is empty, a line is considered covered if the caret is
 * at any position in the line, including between the delimiter and the start of the line. The
 * line containing the delimiter is not considered covered in that case.
 * </p>
 *
 * @param document the document <code>selection</code> refers to
 * @param selection a selection on <code>document</code>
 * @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
 * @return a selection describing the range of lines (partially) covered by
 * <code>selection</code>, without any terminating line delimiters
 * @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
 */
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ITextViewer viewer) throws BadLocationException {
    int low= document.getLineOffset(selection.getStartLine());
    int endLine= selection.getEndLine();
    int high= document.getLineOffset(endLine) + document.getLineLength(endLine);

    // get everything up to last line without its delimiter
    String delim= document.getLineDelimiter(endLine);
    if (delim != null)
        high -= delim.length();

    // the new selection will cover the entire lines being moved, except for the last line's
    // delimiter. The exception to this rule is an empty last line, which will stay covered
    // including its delimiter
    if (delim != null && document.getLineLength(endLine) == delim.length())
        fAddDelimiter= true;
    else
        fAddDelimiter= false;

    return new TextSelection(document, low, high - low);
}
项目:APICloud-Studio    文件:AnnotateView.java   
/**
 * A selection event in the Annotate Source Editor
 * @param event
 */
private void textSelectionChanged(ITextSelection selection) {

    // Track where the last selection event came from to avoid
    // a selection event loop.
    lastSelectionWasText = true;

    // Locate the annotate block containing the selected line number.
    AnnotateBlock match = null;
    for (Iterator iterator = svnAnnotateBlocks.iterator(); iterator.hasNext();) {
        AnnotateBlock block = (AnnotateBlock) iterator.next();
        if (block.contains(selection.getStartLine())) {
            match = block;
            break;
        }
    }

    // Select the annotate block in the List View.
    if (match == null) {
        return;
    }

    StructuredSelection listSelection = new StructuredSelection(match); 
    viewer.setSelection(listSelection, true);
}
项目:bts    文件:FindReferencesHandler.java   
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
        if (editor != null) {
            final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
            editor.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>() {
                @Override
                public void process(XtextResource state) throws Exception {
                    EObject target = eObjectAtOffsetHelper.resolveElementAt(state, selection.getOffset());
                    findReferences(target);
                }
            });
        }
    } catch (Exception e) {
        LOG.error(Messages.FindReferencesHandler_3, e);
    }
    return null;
}
项目:bts    文件:OpenDeclarationHandler.java   
public Object execute(ExecutionEvent event) throws ExecutionException {
    XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
    if (xtextEditor != null) {
        ITextSelection selection = (ITextSelection) xtextEditor.getSelectionProvider().getSelection();

        IRegion region = new Region(selection.getOffset(), selection.getLength());

        ISourceViewer internalSourceViewer = xtextEditor.getInternalSourceViewer();

        IHyperlink[] hyperlinks = getDetector().detectHyperlinks(internalSourceViewer, region, false);
        if (hyperlinks != null && hyperlinks.length > 0) {
            IHyperlink hyperlink = hyperlinks[0];
            hyperlink.open();
        }
    }       
    return null;
}
项目:bts    文件:EditorCopyQualifiedNameHandler.java   
@Override
protected String getQualifiedName(ExecutionEvent event) {
    XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
    if (activeXtextEditor == null) {
        return null;
    }
    final ITextSelection selection = getTextSelection(activeXtextEditor);
    return activeXtextEditor.getDocument().readOnly(new IUnitOfWork<String, XtextResource>() {

        public String exec(XtextResource xTextResource) throws Exception {
            EObject context = getContext(selection, xTextResource);
            EObject selectedElement = getSelectedName(selection, xTextResource);
            return getQualifiedName(selectedElement, context);
        }

    });
}
项目:Permo    文件:SelectedMethods.java   
/**
 * Determines the Java element the given {@link ITextSelection} points to (i.e. the Java element the cursor is
 * positioned to).
 * 
 * @param textSelection
 *          the {@link ITextSelection} to be checked
 * @return the {@link IJavaElement} the cursor is positioned to or {@link Optional#empty()}, if there is no active
 *         editor, or the active editor is not a Java editor.
 */
public static Optional<IJavaElement> getSelectedJavaElement(final ITextSelection textSelection) {
  final Optional<ITypeRoot> javaRootElement = getJavaRootElementOfActiveEditor();
  if (javaRootElement.isPresent()) {
    try {
      final IJavaElement selectedJavaElement = ((ICompilationUnit) javaRootElement.get()).getElementAt(textSelection.getOffset());
      if (selectedJavaElement != null) {
        return Optional.of(selectedJavaElement);
      }
    }
    catch (final JavaModelException e) {
      e.printStackTrace();
    }
  }
  return Optional.empty();
}
项目:junit-tools    文件:JDTUtils.java   
public static IMethod getSelectedMethod() throws JavaModelException {
    IWorkbenchPage page = PlatformUI.getWorkbench()
            .getActiveWorkbenchWindow().getActivePage();
    ITextEditor editor = (ITextEditor) page.getActiveEditor();
    IJavaElement elem = JavaUI.getEditorInputJavaElement(editor
            .getEditorInput());
    if (elem instanceof ICompilationUnit) {
        ITextSelection sel = (ITextSelection) editor.getSelectionProvider()
                .getSelection();
        IJavaElement selected = ((ICompilationUnit) elem).getElementAt(sel
                .getOffset());
        if (selected != null
                && selected.getElementType() == IJavaElement.METHOD) {
            return (IMethod) selected;
        }
    }

    return null;
}
项目:gwt-eclipse-plugin    文件:JsniParser.java   
public static ITypedRegion getEnclosingJsniRegion(ITextSelection selection,
    IDocument document) {
  try {
    ITypedRegion region = TextUtilities.getPartition(document,
        GWTPartitions.GWT_PARTITIONING, selection.getOffset(), false);

    if (region.getType().equals(GWTPartitions.JSNI_METHOD)) {
      int regionEnd = region.getOffset() + region.getLength();
      int selectionEnd = selection.getOffset() + selection.getLength();

      // JSNI region should entirely contain the selection
      if (region.getOffset() <= selection.getOffset()
          && regionEnd >= selectionEnd) {
        return region;
      }
    }
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
  }

  return null;
}