需求:在編輯器中選中代碼片段,點擊菜單/工具欄/快捷鍵,自動轉換(如大小寫、格式化、加密)並替換原文本,保持選中狀態。
// 1. 獲取當前活動編輯器
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IEditorPart editor = window.getActivePage().getActiveEditor();
if (!(editor instanceof ITextEditor)) return;
// 2. 獲取選中文本區域
ITextSelection selection = (ITextSelection) editor.getEditorSite()
.getSelectionProvider().getSelection();
int offset = selection.getOffset();
int length = selection.getLength();
String selectedText = selection.getText();
// 3. 業務轉換邏輯
String converted = transform(selectedText); // 你的轉換算法
// 4. 替換文檔內容
IDocumentProvider provider = ((ITextEditor) editor).getDocumentProvider();
IDocument document = provider.getDocument(editor.getEditorInput());
document.replace(offset, length, converted);
// 5. 重新選中轉換後文本(可選)
ITextSelection newSelection = new TextSelection(document, offset, converted.length());
editor.getEditorSite().getSelectionProvider().setSelection(newSelection);
<extension point="org.eclipse.ui.menus">
<menuContribution locationURI="menu:org.eclipse.ui.main.menu">
<menu id="com.example.tools.menu" label="MyTools (&T)">
<separator name="group.text" visible="true"/>
<separator name="group.sql" visible="true"/>
<separator name="group.code" visible="true"/>
<separator name="group.refactor" visible="true"/>
</menu>
</menuContribution>
</extension>
<extension point="org.eclipse.ui.commands">
<command id="com.example.tools.toLowerCase" name="To Lower Case" />
</extension>
<extension point="org.eclipse.ui.handlers">
<handler commandId="com.example.tools.toLowerCase"
class="com.example.tools.actions.ToLowerCaseHandler" />
</extension>
<extension point="org.eclipse.ui.menus">
<menuContribution locationURI="menu:com.example.tools.menu/group.text">
<command commandId="com.example.tools.toLowerCase"
label="To Lower Case (&L)"
icon="icons/lower.gif"
style="push" />
</menuContribution>
<!-- 工具欄 -->
<menuContribution locationURI="toolbar:com.example.tools.toolbar">
<command commandId="com.example.tools.toLowerCase"
icon="icons/lower.gif"
tooltip="To Lower Case" />
</menuContribution>
</extension>
<!-- 快捷鍵綁定 -->
<extension point="org.eclipse.ui.bindings">
<key commandId="com.example.tools.toLowerCase"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
sequence="M1+M2+L"
contextId="org.eclipse.ui.textEditorScope" />
</extension>
| 角色 | 接口/基類 | 職責 |
|---|---|---|
| Handler | AbstractHandler / IHandler | 命令執行入口,調用文本轉換邏輯 |
| Action (舊 API) | IEditorActionDelegate | 兼容 3.x 視圖貢獻,新專案建議用 Command/Handler |
| 文檔模型 | IDocument, ITextSelection | 無關 UI 的文本操作核心 |
<visibleWhen> / <enabledWhen> 限定僅在文本編輯器、有選中文本時顯示/啟用。document.replace 自動納入編輯器撤銷棧,無需額外代碼。Job 或 WorkspaceModifyOperation 避免凍結 UI。icons/ 目錄,plugin.xml 相對路徑引用。contextId="org.eclipse.ui.textEditorScope" 確保快捷鍵僅在編輯器生效。Eclipse 3.5+ 推薦Commands + Handlers + Menus 三位一體模型,優勢:
IEvaluationService 靈活控制。BindingService 統一管理。IEditorActionDelegate,減少樣板代碼。掌握 IDocument 文本替換核心流程、plugin.xml 菜單/工具欄/快捷鍵聲明式配置、Command/Handler 架構,即可高效開發高質量 Eclipse 文本處理插件。