承接上篇架構認知,本文進入實戰:在準備好開發環境後,基於 `StructuredTextEditor` 快速構建可運行的自定義 JSP 編輯器雛形,並深入剖析 JFace Text Framework 核心三大角色(`IEditorPart`、`IDocumentProvider`、`SourceViewerConfiguration`)的協作機制,為後續功能定制奠定堅實基礎。
編輯器構造時注入:`setSourceViewerConfiguration(new JSPConfiguration())`。所有編輯器行為通過此類配置:
| 配置方法 | 返回類型 | 功能 | 定制切入點 |
|---|---|---|---|
| getDocumentPartitioning() | String | 分區類型 ID (如 "JSP") | 自定義分區規則 |
| getPresentationReconciler() | IPresentationReconciler | 語法著色、增量掃描 | 自定義著色規則 |
| getContentAssistant() | IContentAssistant | 代碼完成、參數提示 | 核心:智能提示定制 |
| getAnnotationHover() | IAnnotationHover | 懸停顯示錯誤/文檔 | 自定義懸停內容 |
| getHyperlinkDetector() | IHyperlinkDetector | Ctrl+Click 跳轉 | 自定義跳轉目標 |
| getAutoEditStrategies() | Map<String, IAutoEditStrategy> | 智能編輯(括號、引號、縮進) | 自定義編輯行為 |
| getContentFormatter() | IContentFormatter | 代碼格式化 (Ctrl+Shift+F) | 自定義格式化規則 |
| getOverviewRulerAnnotationHover() | IAnnotationHover | 概覽標尺懸停 | 錯誤導航增強 |
<extension point="org.eclipse.ui.editors">
<editor
class="com.example.jsp.editor.CustomJSPEditor"
contributorClass="org.eclipse.ui.texteditor.BasicTextEditorActionContributor"
default="true"
extensions="jsp,jspf"
icon="icons/jsp.gif"
id="com.example.jsp.editor.CustomJSPEditor"
name="Custom JSP Editor">
</editor>
</extension>
<extension point="org.eclipse.core.contenttype.contentTypes">
<content-type
base-type="org.eclipse.core.runtime.xml"
file-extensions="jsp,jspf"
id="com.example.jsp.contenttype"
name="JSP File"
priority="normal">
</content-type>
</extension>
package com.example.jsp.editor;
import org.eclipse.jst.jsp.ui.editor.JSPEditor;
import org.eclipse.wst.sse.ui.StructuredTextEditor;
public class CustomJSPEditor extends JSPEditor { // 直接繼承 WTP 提供的 JSPEditor
public CustomJSPEditor() {
super();
// 可選:覆寫配置、文檔提供者
// setSourceViewerConfiguration(new CustomJSPConfiguration());
// setDocumentProvider(new CustomDocumentProvider());
}
}
💡 **技巧**:直接繼承 `org.eclipse.jst.jsp.ui.editor.JSPEditor` 即可獲得完整 JSP 編輯能力(語法著色、提示、驗證),僅需覆寫需定制的部分,避免從零構建。
| 現象 | 原因 | 解決 |
|---|---|---|
| ClassNotFoundException: JSPEditor | 依賴缺失 org.eclipse.jst.jsp.ui | MANIFEST.MF 添加 Require-Bundle |
| 編輯器打開報錯 "No editor descriptor" | plugin.xml editor 擴展點 id/class 錯誤 | 檢查 class 全限定名、id 唯一性 |
| 內容助手不工作 | SourceViewerConfiguration 未正確注入 | 確認 setSourceViewerConfiguration 調用 |
| 語法著色異常 | 分區器配置錯誤 | 覆寫 getDocumentPartitioning 返回 "JSP" |
擁有可運行編輯器後,下兩篇將深入 WTP 兩大核心數據模型:
掌握這兩個模型,才能真正理解「內容助手如何知道當前標籤屬性」、「驗證器如何檢測標籤嵌套錯誤」、「超鏈接如何跳轉到標籤定義」。