演示Eclipse插件實現代碼提示和補全

續上文重拾《 兩週自制腳本語言 》- Eclipse插件實現語法高亮, 但僅達到了演示Eclipse自己功能的程度, 與石頭語言並沒有直接聯繫. 源碼庫相同, 仍在同一插件. 演示效果以下:
java

懸浮窗顯示的是當前所在行內容. 而鍵入"新"字會彈出自動補全, 選項僅有"新建"一項. 再進一步的話, 二者都應該須要準確獲取鼠標所在位置字段的語法信息, 即集成語法分析器的功能, 而那還只是第一步.git

因爲僅做演示功能, 相關代碼還較簡短. 內容輔助處理器, 提供自動補全功能.github

public static final String[] 全部建議 = new String[] {"新建"};

  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer 視圖, int 偏移) {

    IDocument 文件 = 視圖.getDocument();

    try {
      int 偏移所在行 = 文件.getLineOfOffset(偏移);
      int 行頭偏移 = 文件.getLineOffset(偏移所在行);

      int 當前行文本長度 = 偏移 - 行頭偏移;
      String 當前行文本 = 文件.get(行頭偏移, 當前行文本長度).toLowerCase();

      return Arrays.asList(全部建議).stream()
          .filter(建議 -> !視圖.getDocument().get().contains(建議) && 建議.toLowerCase().startsWith(當前行文本))
          .map(建議 -> new CompletionProposal(建議, 行頭偏移, 當前行文本長度, 建議.length()))
          .toArray(ICompletionProposal[]::new);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
    return new ICompletionProposal[0];
  }

  @Override
  public char[] getCompletionProposalAutoActivationCharacters() {
    String keys = "新";
    return keys.toCharArray();
}

懸浮提供器eclipse

@Override
  public String getHoverInfo(ITextViewer 文本視圖, IRegion 懸浮位置) {
    int 偏移 = 懸浮位置.getOffset();
    IDocument 文件 = 文本視圖.getDocument();
    try {
      // 僅提取當前所在行, 如要取得當前鼠標所在詞, 需進一步詞法分析?
      int 所在行 = 文件.getLineOfOffset(偏移);
      IRegion 行信息 = 文件.getLineInformation(所在行);
      int 行長 = 行信息.getLength();
      int 行偏移 = 行信息.getOffset();
      return 文件.get(行偏移, 行長);

    } catch (BadLocationException e) {
      e.printStackTrace();
    }
    return "";
}
相關文章
相關標籤/搜索