下面列出了com.intellij.psi.search.EverythingGlobalScope#com.intellij.psi.codeStyle.CodeStyleManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void update(State state) {
this.lock.lock();
try {
CodeStyleManager manager = CodeStyleManager.getInstance(this.project);
if (manager == null) {
logger.warn("Unable to find exiting CodeStyleManager");
return;
}
if (state == State.ACTIVE && !(manager instanceof SpringCodeStyleManager)) {
logger.debug("Enabling SpringCodeStyleManager");
registerCodeStyleManager(new SpringCodeStyleManager(manager));
this.properties.setValue(ACTIVE_PROPERTY, true);
}
if (state == State.NOT_ACTIVE && (manager instanceof SpringCodeStyleManager)) {
logger.debug("Disabling SpringCodeStyleManager");
registerCodeStyleManager(((SpringCodeStyleManager) manager).getDelegate());
this.properties.setValue(ACTIVE_PROPERTY, false);
}
ApplicationManager.getApplication().invokeLater(() -> this.statusIndicator.update(state));
}
finally {
this.lock.unlock();
}
}
private void registerCodeStyleManager(CodeStyleManager manager) {
if (ApplicationInfo.getInstance().getBuild().getBaselineVersion() >= 193) {
IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(PluginId.getId("spring-javaformat"));
try {
((ComponentManagerImpl) this.project).registerServiceInstance(CodeStyleManager.class, manager, plugin);
}
catch (NoSuchMethodError ex) {
Method method = findRegisterServiceInstanceMethod(this.project.getClass());
invokeRegisterServiceInstanceMethod(manager, plugin, method);
}
}
else {
MutablePicoContainer container = (MutablePicoContainer) this.project.getPicoContainer();
container.unregisterComponent(CODE_STYLE_MANAGER_KEY);
container.registerComponentInstance(CODE_STYLE_MANAGER_KEY, manager);
}
}
private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
Runnable task = new Runnable() {
@Override
public void run() {
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
try {
CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
};
if (endOffset - startOffset > 1000) {
DocumentUtil.executeInBulk(editor.getDocument(), true, task);
}
else {
task.run();
}
}
/**
* @param templateFile Name of the generated file
* @param destinationPath Relative path to the target file system entry
* @param extensionDefinition Extension definition containing all relevant metadata
* @param context Template Context variables
* @param project Project in context
*/
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull TYPO3ExtensionDefinition extensionDefinition, @NotNull Map<String, String> context, Project project) {
String template = readTemplateToString(templateFile, context);
VirtualFile targetDirectory = getOrCreateDestinationPath(extensionDefinition.getRootDirectory(), destinationPath);
LanguageFileType fileType = FileTypes.PLAIN_TEXT;
if (templateFile.endsWith(".php")) {
fileType = PhpFileType.INSTANCE;
}
PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
CodeStyleManager.getInstance(project).reformat(fileFromText);
return PsiDirectoryFactory
.getInstance(project)
.createDirectory(targetDirectory)
.add(fileFromText);
}
/**
* @param templateFile Name of the generated file
* @param destinationPath Relative path to the target file system entry
* @param extensionRootDirectory Extension definition containing all relevant metadata
* @param context Template Context variables
* @param project Project in context
*/
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull PsiDirectory extensionRootDirectory, @NotNull Map<String, String> context, Project project) {
String template = readTemplateToString(templateFile, context);
VirtualFile targetDirectory = getOrCreateDestinationPath(extensionRootDirectory.getVirtualFile(), destinationPath);
LanguageFileType fileType = FileTypes.PLAIN_TEXT;
if (templateFile.endsWith(".php")) {
fileType = PhpFileType.INSTANCE;
}
PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
CodeStyleManager.getInstance(project).reformat(fileFromText);
return PsiDirectoryFactory
.getInstance(project)
.createDirectory(targetDirectory)
.add(fileFromText);
}
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
myOriginalHandler.execute(editor, charTyped, dataContext);
if (isMatchForClosingTag(editor, charTyped)) {
PsiFile file = dataContext.getData(LangDataKeys.PSI_FILE);
if (file == null) {
return;
}
int offset = editor.getCaretModel().getOffset();
TagBlockElement block = findEnclosingTagBlockElement(file, offset);
if (block == null) {
return;
}
insertClosingTag(editor, offset, block.getOpeningTag().generateClosingTag());
if (editor.getProject() != null) {
PsiDocumentManager.getInstance(editor.getProject()).commitDocument(editor.getDocument());
TagBlockElement completedBlock = findEnclosingTagBlockElement(file, editor.getCaretModel().getOffset());
if (completedBlock == null) {
return;
}
CodeStyleManager.getInstance(editor.getProject()).reformat(completedBlock);
}
}
}
@Nonnull
protected String doExtract(final PsiDirectory targetDirectory,
final String targetfileName,
final T first,
final T last,
final Language includingLanguage) throws IncorrectOperationException {
final PsiFile file = targetDirectory.createFile(targetfileName);
Project project = targetDirectory.getProject();
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
final Document document = documentManager.getDocument(file);
document.replaceString(0, document.getTextLength(), first.getText().trim());
documentManager.commitDocument(document);
CodeStyleManager.getInstance(PsiManager.getInstance(project).getProject()).reformat(file); //TODO: adjustLineIndent
final String relativePath = PsiFileSystemItemUtil.getRelativePath(first.getContainingFile(), file);
if (relativePath == null) throw new IncorrectOperationException("Cannot extract!");
return relativePath;
}
/**
* This function should be executed (remove the underscore) if the current results are correct (manual testing).
*
* @throws Exception
*/
public void _testResultGenerator() throws Exception {
for (int binarySettings = 0; binarySettings < 128; ++binarySettings) {
tearDown();
setUp();
myFixture.configureByFiles("/generated/TestData.csv");
initCsvCodeStyleSettings(binarySettings);
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
}
}.execute();
try (PrintWriter writer = new PrintWriter(getTestDataPath() + String.format("/generated/TestResult%08d.csv", binarySettings))
) {
writer.print(myFixture.getFile().getText());
}
}
}
public static PsiFile createFromTemplate(final PsiDirectory directory, final String name,
String fileName, String templateName,
@NonNls String... parameters) throws IncorrectOperationException {
final FileTemplate template = FileTemplateManager.getInstance(directory.getProject()).getInternalTemplate(templateName);
String text;
try {
text = template.getText();
} catch (Exception e) {
throw new RuntimeException("Unable to load template for " +
FileTemplateManager.getInstance().internalTemplateToSubject(templateName), e);
}
final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());
final PsiFile file = factory.createFileFromText(fileName, WeexFileType.INSTANCE, text);
CodeStyleManager.getInstance(directory.getProject()).reformat(file);
return (PsiFile) directory.add(file);
}
protected void checkFormatting(String expected) throws IOException {
CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
final PsiFile file = myFixture.getFile();
TextRange myTextRange = file.getTextRange();
CodeStyleManager.getInstance(file.getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
}
}, null, null);
myFixture.checkResult(expected);
}
/**
* When appropriate, automatically reduce the indentation for else tags "{:else}"
*/
private void adjustFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
PsiElement elementAtCaret = provider.findElementAt(offset - 1, DustLanguage.class);
PsiElement elseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement element) {
return element != null
&& (element instanceof DustElseTag);
}
});
// run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
if (elseParent != null) {
// grab the current caret position (AutoIndentLinesHandler is about to mess with it)
PsiDocumentManager.getInstance(project).commitAllDocuments();
CaretModel caretModel = editor.getCaretModel();
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
}
}
@Override
protected PsiFile doReformat(final Project project, final PsiFile psiFile) {
final String text = psiFile.getText();
final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
final Document doc = manager.getDocument(psiFile);
CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
if (doc != null) {
doc.replaceString(0, doc.getTextLength(), text);
manager.commitDocument(doc);
}
try {
CodeStyleManager.getInstance(project).reformat(psiFile);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}), "", "");
if (doc != null) {
manager.commitDocument(doc);
}
return psiFile;
}
/**
* Replace the text within the given range and reformat it according to the user's
* code style/formatting rules.
*
* NOTE: The PSI may be entirely invalidated and re-created by this call.
*
* @param range Range of text or PsiElements to replace.
* @param text Replacement text (may be null).
*/
public void replaceAndFormat(@NotNull final TextRange range, @Nullable String text) {
if (null == text) {
text = "";
}
// Mark the beginning and end so that we have the proper range after adding text.
// Greedy means that the text immediately added at the beginning/end of the marker are included.
RangeMarker marker = document.createRangeMarker(range);
marker.setGreedyToLeft(true);
marker.setGreedyToRight(true);
try {
document.replaceString(range.getStartOffset(), range.getEndOffset(), text);
//PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); // force update PSI.
if (marker.isValid()) { // If the range wasn't reduced to zero.
CodeStyleManager.getInstance(file.getProject()).reformatText(file, marker.getStartOffset(), marker.getEndOffset());
}
}
finally {
marker.dispose();
}
}
protected void doTest(final Surrounder surrounder) throws Exception {
myFixture.configureByFile(getTestName(false) + ".hx");
WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
@Override
public void run() {
SurroundWithHandler.invoke(getProject(), myFixture.getEditor(), myFixture.getFile(), surrounder);
PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(myFixture.getDocument(myFixture.getFile()));
CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
}
});
/*CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
SurroundWithHandler.invoke(getProject(), myFixture.getEditor(), myFixture.getFile(), surrounder);
PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(myFixture.getDocument(myFixture.getFile()));
CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
}
}, null, null);*/
myFixture.checkResultByFile(getTestName(false) + "_after.hx");
}
private void doTest(String... files) throws Exception {
myFixture.configureByFiles(files);
if (IdeaTarget.IS_VERSION_17_COMPATIBLE) {
// The implementation of finishLookup in IDEA 2017 requires that it run OUTSIDE of a write command,
// while previous versions require that is run inside of one.
expandTemplate(myFixture.getEditor());
}
WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
@Override
public void run() {
if (!IdeaTarget.IS_VERSION_17_COMPATIBLE) {
expandTemplate(myFixture.getEditor());
}
CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
}
});
myFixture.getEditor().getSelectionModel().removeSelection();
myFixture.checkResultByFile(getTestName(false) + "_after.hx");
}
private void reparseParallelTrees(PsiFile changedFile, PsiToDocumentSynchronizer synchronizer) {
List<PsiFile> allFiles = changedFile.getViewProvider().getAllFiles();
if (allFiles.size() <= 1) {
return;
}
CharSequence newText = changedFile.getNode().getChars();
for (final PsiFile file : allFiles) {
FileElement fileElement = file == changedFile ? null : ((PsiFileImpl)file).getTreeElement();
Runnable changeAction = fileElement == null ? null : reparseFile(file, fileElement, newText);
if (changeAction == null) continue;
synchronizer.setIgnorePsiEvents(true);
try {
CodeStyleManager.getInstance(file.getProject()).performActionWithFormatterDisabled(changeAction);
}
finally {
synchronizer.setIgnorePsiEvents(false);
}
}
}
public void write(Project project, PsiElement psiElement, PsiDocComment comment) {
try {
WriteCommandAction.writeCommandAction(project).run(
(ThrowableRunnable<Throwable>)() -> {
if (psiElement.getContainingFile() == null) {
return;
}
// 写入文档注释
if (psiElement instanceof PsiJavaDocumentedElement) {
PsiDocComment psiDocComment = ((PsiJavaDocumentedElement)psiElement).getDocComment();
if (psiDocComment == null) {
psiElement.getNode().addChild(comment.getNode(), psiElement.getFirstChild().getNode());
} else {
psiDocComment.replace(comment);
}
}
// 格式化文档注释
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(psiElement.getProject());
PsiElement javadocElement = psiElement.getFirstChild();
int startOffset = javadocElement.getTextOffset();
int endOffset = javadocElement.getTextOffset() + javadocElement.getText().length();
codeStyleManager.reformatText(psiElement.getContainingFile(), startOffset, endOffset + 1);
});
} catch (Throwable throwable) {
LOGGER.error("写入错误", throwable);
}
}
public GodClassPreviewResultDialog(@NotNull Project project, @NotNull MutableDiffRequestChain requestChain,
@NotNull DiffDialogHints hints, ExtractClassPreviewProcessor previewProcessor) {
super(project, requestChain, hints);
this.myChain = requestChain;
this.project = project;
this.diffContentFactory = DiffContentFactory.getInstance();
this.previewProcessor = previewProcessor;
this.javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
this.codeStyleManager = CodeStyleManager.getInstance(project);
}
public PolymorphismRefactoring(PsiFile sourceFile,
Project project,
PsiClass sourceTypeDeclaration,
TypeCheckElimination typeCheckElimination) {
this.sourceFile = sourceFile;
this.sourceTypeDeclaration = sourceTypeDeclaration;
this.typeCheckElimination = typeCheckElimination;
elementFactory = PsiElementFactory.getInstance(project);
codeStyleManager = CodeStyleManager.getInstance(project);
this.project = project;
semicolon = (PsiJavaToken) elementFactory.createStatementFromText(";", null).getFirstChild();
}
private void invokeRegisterServiceInstanceMethod(CodeStyleManager manager, IdeaPluginDescriptor plugin,
Method method) {
if (method == null) {
throw new IllegalStateException("Unsupported IntelliJ version");
}
method.setAccessible(true);
try {
method.invoke(this.project, manager, plugin);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void build(PsiFile psiFile, Project project1, Editor editor) {
if (psiFile == null) return;
WriteCommandAction.runWriteCommandAction(project1, () -> {
if (editor == null) return;
Project project = editor.getProject();
if (project == null) return;
PsiElement mouse = psiFile.findElementAt(editor.getCaretModel().getOffset());
if (mouse == null) return;
KtClass ktClass = Utils.getKtClassForElement(mouse);
if (ktClass == null) return;
if (ktClass.getNameIdentifier() == null) return;
String className = ktClass.getNameIdentifier().getText();
KtClassBody body = ktClass.getBody();
if (body == null) return;
KtPsiFactory elementFactory = KtPsiFactoryKt.KtPsiFactory(ktClass.getProject());
KtLightClass lightClass = LightClassUtilsKt.toLightClass(ktClass);
if (lightClass == null) return;
build(editor, mouse, elementFactory, project, ktClass, body, lightClass, psiFile, className);
String[] imports = getImports();
if (imports != null) {
for (String fqName : imports) {
final Collection<DeclarationDescriptor> descriptors = ResolutionUtils.resolveImportReference(ktClass.getContainingKtFile(), new FqName(fqName));
Iterator<DeclarationDescriptor> iterator = descriptors.iterator();
if (iterator.hasNext()) {
DeclarationDescriptor descriptor = iterator.next();
ImportInsertHelper.getInstance(project).importDescriptor(ktClass.getContainingKtFile(), descriptor, false);
}
}
}
CodeStyleManager styleManager = CodeStyleManager.getInstance(ktClass.getProject());
styleManager.reformatText(ktClass.getContainingFile(), ContainerUtil.newArrayList(ktClass.getTextRange()));
});
}
protected void doTest() {
myFixture.configureByFiles(getTestName(false) + ".soy");
WriteCommandAction.writeCommandAction(getProject()).compute(() -> {
CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
return null;
});
myFixture.checkResultByFile(getTestName(false) + "_after.soy");
}
@Nullable
@Override
public String getLineIndent(@Nonnull Project project, @Nonnull Editor editor, Language language, int offset) {
Document document = editor.getDocument();
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
documentManager.commitDocument(document);
PsiFile file = documentManager.getPsiFile(document);
if (file == null) return "";
return CodeStyleManager.getInstance(project).getLineIndent(file, offset, FormattingMode.ADJUST_INDENT_ON_ENTER);
}
public static void reformatJavaDoc(PsiElement theElement) {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(theElement.getProject());
try {
int javadocTextOffset = findJavaDocTextOffset(theElement);
int javaCodeTextOffset = findJavaCodeTextOffset(theElement);
codeStyleManager.reformatText(theElement.getContainingFile(), javadocTextOffset,
javaCodeTextOffset + 1);
} catch (Exception e) {
LOGGER.error("reformat code failed", e);
}
}
@Nullable
private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings) throws IncorrectOperationException {
myDocument.insertString(myOffset, buffer);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
CodeStyleManager.getInstance(getProject()).adjustLineIndent(myFile, myOffset + buffer.length() - 2);
PsiComment comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
comment = createJavaDocStub(settings, comment, getProject());
if (comment == null) {
return null;
}
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
final Ref<PsiComment> commentRef = Ref.create(comment);
codeStyleManager.runWithDocCommentFormattingDisabled(myFile, () -> formatComment(commentRef, codeStyleManager));
comment = commentRef.get();
PsiElement next = comment.getNextSibling();
if (next == null && comment.getParent().getClass() == comment.getClass()) {
next = comment.getParent().getNextSibling(); // expanding chameleon comment produces comment under comment
}
if (next != null) {
next = myFile.findElementAt(next.getTextRange().getStartOffset()); // maybe switch to another tree
}
if (next != null && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode()) || !next.getText().contains(LINE_SEPARATOR))) {
int lineBreakOffset = comment.getTextRange().getEndOffset();
myDocument.insertString(lineBreakOffset, LINE_SEPARATOR);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1);
comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
}
return comment;
}
private void run(String test, Consumer<CommonCodeStyleSettings> settings) {
myFixture.configureByFiles(test + "/Source.proto");
CodeStyleSettings codeStyleSettings = CodeStyle.getSettings(getProject());
CommonCodeStyleSettings protoSettings = codeStyleSettings.getCommonSettings(ProtoLanguage.INSTANCE);
settings.accept(protoSettings);
WriteCommandAction.writeCommandAction(getProject())
.run(() -> CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile()));
myFixture.checkResultByFile(test + "/Expected.proto");
}
private void formatComment(Ref<PsiComment> commentRef, CodeStyleManager codeStyleManager) {
PsiComment comment = commentRef.get();
RangeMarker commentMarker = myDocument.createRangeMarker(comment.getTextRange().getStartOffset(), comment.getTextRange().getEndOffset());
codeStyleManager.reformatNewlyAddedElement(comment.getNode().getTreeParent(), comment.getNode());
commentRef.set(PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(commentMarker.getStartOffset()), PsiComment.class));
commentMarker.dispose();
}
private static void reformatCommentKeepingEmptyTags(@Nonnull PsiFile file, @Nonnull Project project, int start, int end) {
CodeStyleSettings tempSettings = CodeStyle.getSettings(file).clone();
LanguageCodeStyleSettingsProvider langProvider = LanguageCodeStyleSettingsProvider.forLanguage(file.getLanguage());
if (langProvider != null) {
DocCommentSettings docCommentSettings = langProvider.getDocCommentSettings(tempSettings);
docCommentSettings.setRemoveEmptyTags(false);
}
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
CodeStyle.doWithTemporarySettings(project, tempSettings, () -> codeStyleManager.reformatText(file, start, end));
}
@Test
public void testFormatter() {
myFixture.configureByFiles("FormatterTestData.graphql");
CodeStyleSettingsManager.getSettings(getProject()).KEEP_BLANK_LINES_IN_CODE = 2;
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
}
}.execute();
myFixture.checkResultByFile("FormatterExpectedResult.graphql");
}
private String doTest(@Nullable Character c, String testName) {
if (c == null) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
}
});
}
else {
myFixture.type(c);
}
return String.format("%s-after.BUCK", testName);
}