簡體   English   中英

Eclipse JDT:以編程方式調用'正確的縮進'?

[英]Eclipse JDT: Call 'correct indentation' programmatically?

我正在開發一個Eclipse插件,用於修改用戶項目中的Java代碼。

基本上這個插件的結果是Java注釋被添加到某些方法中,所以

void foo() { ... }

@MyAnnotation
void foo() { ... }

除了它看起來不那么像; 新插入的注釋的縮進是wack(具體來說,新注釋一直到行的左側)。 我想對文件進行所有更改,然后以編程方式調用“Correct Indentation”。

有誰知道如何做到這一點? 我在這里或在JDT論壇中找不到答案,所有看起來相關的類(IndentAction,JavaIndenter)都在內部包中,我不應該使用...

謝謝!

好吧,我想我可能已經找到了我想要的解決方案。 猜猜我應該花更多時間在搜索之前...但是為了將來的參考,這就是我的所作所為! 好東西在ToolFactory中......

import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jdt.core.ICompilationUnit;

...

ICompilationUnit cu = ...

...

CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
ISourceRange range = cu.getSourceRange();
TextEdit indent_edit =
  formatter.format(CodeFormatter.K_COMPILATION_UNIT, 
    cu.getSource(), range.getOffset(), range.getLength(), 0, null);
cu.applyTextEdit(indent_edit, null);

cu.reconcile();

這會重新格式化整個文件。 如果您需要重新格式化,還有其他選擇......

在處理Java代碼時添加縮進可能更容易。

你的Eclipse插件必須讀取void foo() { ... }行知道添加@MyAnnotation ,對嗎? 只需從Java行獲取縮進,然后將縮進附加到縮進。

暫無
暫無

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

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