簡體   English   中英

Eclipse從光標/插入符號下選擇文本並返回

[英]Eclipse select text from under the cursor/caret and return it

使用eclipse插件並為我的編輯器做一些功能,我有以下方法可以從編輯器中選擇突出顯示的文本並將其作為字符串返回:

public String getCurrentSelection() {
    IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
            .getActivePage().getActiveEditor();
    if (part instanceof ITextEditor) {
        final ITextEditor editor = (ITextEditor) part;
        ISelection sel = editor.getSelectionProvider().getSelection();
        if (sel instanceof TextSelection) {
            ITextSelection textSel = (ITextSelection) sel;
            return textSel.getText();
        }
    }
    return null;
}

但是現在我想要,如果將光標放在一個單詞中,它將選擇整個單詞並將其作為字符串返回。

除了一個復雜的算法,我可以解析整個編輯器,獲取光標的位置,在左右空間中搜索空格,還有什么更簡單的方法來獲取文本(將光標放置在字符串中)?

我設法使工作正常。 對於遇到相同問題的任何人,以下代碼均有效(至少對我而言):

private String getTextFromCursor() {
    IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
            .getActivePage().getActiveEditor();
    TextEditor editor = null;

    if (part instanceof TextEditor) {
        editor = (TextEditor) part;
    }

    if (editor == null) {
        return "";
    }

    StyledText text = (StyledText) editor.getAdapter(Control.class);

    int caretOffset = text.getCaretOffset();

    IDocumentProvider dp = editor.getDocumentProvider();
    IDocument doc = dp.getDocument(editor.getEditorInput());

    IRegion findWord = CWordFinder.findWord(doc, caretOffset);
    String text2 = "";
    if (findWord.getLength() != 0)
        text2 = text.getText(findWord.getOffset(), findWord.getOffset()
                + findWord.getLength() - 1);
    return text2;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM