使用Reformat and Compile插件(受Alexandre DuBreuil的Save Actions插件启发):
https://plugins.jetbrains.com/plugin/8231?pr=idea_ce
目前,我仅提供一个jar文件,但这是代码中最重要的部分:
private final static Set<Document> documentsToProcess = new HashSet<Document>();
private static VirtualFile[] fileToCompile = VirtualFile.EMPTY_ARRAY;
// The plugin extends FileDocumentManagerAdapter.
// beforeDocumentSaving calls reformatAndCompile
private static void reformatAndCompile(
@NotNull final Project project,
@NotNull final Document document,
@NotNull final PsiFile psiFile) {
documentsToProcess.add(document);
if (storage.isEnabled(Action.compileFile) && isDocumentActive(project, document)) {
fileToCompile = isFileCompilable(project, psiFile.getVirtualFile());
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
if (documentsToProcess.contains(document)) {
documentsToProcess.remove(document);
if (storage.isEnabled(Action.optimizeImports)
|| storage.isEnabled(Action.reformatCode)) {
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
if (storage.isEnabled(Action.optimizeImports)) {
new OptimizeImportsProcessor(project, psiFile)
.run();
}
if (storage.isEnabled(Action.reformatCode)) {
new ReformatCodeProcessor(
project,
psiFile,
null,
ChangeListManager
.getInstance(project)
.getChange(psiFile.getVirtualFile()) != null)
.run();
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(psiFile);
}
});
}
});
}
}
if (fileToCompile.length > 0) {
if (documentsToProcess.isEmpty()) {
compileFile(project, fileToCompile);
fileToCompile = VirtualFile.EMPTY_ARRAY;
}
} else if (storage.isEnabled(Action.makeProject)) {
if (documentsToProcess.isEmpty()) {
makeProject(project);
}
} else {
saveFile(project, document, psiFile.getVirtualFile());
}
}
}, project.getDisposed());
}
private static void makeProject(@NotNull final Project project) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
CompilerManager.getInstance(project).make(null);
}
}, project.getDisposed());
}
private static void compileFile(
@NotNull final Project project,
@NotNull final VirtualFile[] files) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
CompilerManager.getInstance(project).compile(files, null);
}
}, project.getDisposed());
}
private static void saveFile(
@NotNull final Project project,
@NotNull final Document document,
@NotNull final VirtualFile file) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
if (fileDocumentManager.isFileModified(file)) {
fileDocumentManager.saveDocument(document);
}
}
}, project.getDisposed());
}
Ctrl
+ 键F9
呢?这将构建整个项目,如果仅更改了两个文件,则将对其进行重建。