/** * @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)) { int offset = editor.getCaretModel().getOffset(); PsiFile file = dataContext.getData(LangDataKeys.PSI_FILE); if (file == null) { return; } PsiElement el = file.findElementAt(offset - 1); TagBlockElement block = (TagBlockElement) PsiTreeUtil .findFirstParent(el, parent -> parent instanceof TagBlockElement && !(parent instanceof SoyChoiceClause)); if (block == null) { return; } String closingTag = block.getOpeningTag().generateClosingTag(); insertClosingTag(editor, offset, closingTag); if (editor.getProject() != null) { PsiDocumentManager.getInstance(editor.getProject()).commitDocument(editor.getDocument()); CodeStyleManager.getInstance(editor.getProject()).reformat(block); } } }
@Override protected void run(@NotNull Result<PsiFile> result) throws Throwable { final PsiPackage packageElement = directoryService.getPackage(directory); if (packageElement == null) { throw new InvalidDirectoryException("Target directory does not provide a package"); } final String fileName = Extensions.append(name, StdFileTypes.JAVA); final PsiFile found = directory.findFile(fileName); if (found != null) { throw new ClassAlreadyExistsException("Class '" + name + "'already exists in " + packageElement.getName()); } final String packageName = packageElement.getQualifiedName(); final String className = Extensions.remove(this.name, StdFileTypes.JAVA); try { final String java = converter.convert(packageName, className, json); final PsiFile classFile = fileFactory.createFileFromText(fileName, JavaFileType.INSTANCE, java); CodeStyleManager.getInstance(classFile.getProject()).reformat(classFile); JavaCodeStyleManager.getInstance(classFile.getProject()).optimizeImports(classFile); final PsiFile created = (PsiFile) directory.add(classFile); result.setResult(created); } catch (IOException e) { throw new ClassCreationException("Failed to create new class from JSON", e); } }
public void addAnnotation(Project project) { for (FieldEntity entity : getFieldList()) { entity.addAnnotation(project); } editTableAnnotation(project, tablePsiAnnotation, getSelectedEntities().size() == 0); PsiJavaFile javaFile = (PsiJavaFile) psiClass.getContainingFile(); Utils.saveDocument(javaFile); Utils.addImport(project, javaFile, null, AormConstants.tableQName, AormConstants.columnQName); Utils.optimizeImport(project, psiClass); CodeStyleManager.getInstance(project).reformat(psiClass); Utils.saveDocument(psiClass.getContainingFile()); }
@Override public void run() { // deleting old fields Stream.of(sourceJavaPsiClass.getAllFields()) .peek(psiField -> System.out.println("going to delete field: " + psiField.getText())) .forEach(psiField -> psiField.delete()); // deleting orphanage COMMAs Stream.of(sourceJavaPsiClass.getChildren()) .filter(psiElement -> psiElement instanceof PsiJavaToken) .map(psiElement -> (PsiJavaToken) psiElement) .filter(psiJavaToken -> "COMMA".equals(psiJavaToken.getTokenType().toString())) .peek(psiJavaToken -> System.out.println("going to delete token:" + psiJavaToken)) .forEach(psiElement -> psiElement.delete()); // start of additions new ValueClass(extractedVariables, sourceClass).getGeneratedPsiElements(project).forEach( psiElement -> sourceJavaPsiClass.add(psiElement) ); CodeStyleManager.getInstance(project).reformat(rootPsiFile); JavaCodeStyleManager.getInstance(project).shortenClassReferences(rootPsiFile); }
private void executeTestConfiguration(int binarySettings, String relativeTargetPath, boolean checkResults) { if (relativeTargetPath == null || relativeTargetPath.isEmpty()) { relativeTargetPath = "."; } myFixture.configureByFiles(relativeTargetPath + "/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(); if (checkResults) { myFixture.checkResultByFile(relativeTargetPath + String.format("/TestResult%08d.csv", binarySettings)); } }
/** * 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()); } } }
@Override public void processIntention(@NotNull PsiElement element) { final PsiReturnStatement returnStatement = (PsiReturnStatement)element; final PsiExpression returnValue = returnStatement.getReturnValue(); if (returnValue == null || ErrorUtil.containsDeepError(returnValue)) { return; } final String newStatementText = buildIf(returnValue, true, new StringBuilder()).toString(); final Project project = returnStatement.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiBlockStatement blockStatement = (PsiBlockStatement)elementFactory.createStatementFromText("{" + newStatementText + "}", returnStatement); final PsiElement parent = returnStatement.getParent(); for (PsiStatement st : blockStatement.getCodeBlock().getStatements()) { CodeStyleManager.getInstance(project).reformat(parent.addBefore(st, returnStatement)); } PsiReplacementUtil.replaceStatement(returnStatement, "return false;"); }
@Override public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { List<LuaExpression> exprs = getLuaExpressions(); if (exprs.size() == 0) { add(element); } else { element = super.addAfter(element, anchor); final ASTNode astNode = getNode(); if (anchor != null) { astNode.addLeaf(COMMA, ",", element.getNode()); } else { astNode.addLeaf(COMMA, ",", element.getNextSibling().getNode()); } CodeStyleManager.getInstance(getManager().getProject()).reformat(this); } return element; }
@Override public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { List<LuaExpression> exprs = getLuaExpressions(); if (exprs.size() == 0) { add(element); } else { element = super.addBefore(element, anchor); final ASTNode astNode = getNode(); if (anchor != null) { astNode.addLeaf(COMMA, ",", anchor.getNode()); } else { astNode.addLeaf(COMMA, ",", element.getNode()); } CodeStyleManager.getInstance(getManager().getProject()).reformat(this); } return element; }
public static GrReferenceExpression qualifyReference(GrReferenceExpression referenceExpression, final PsiMember member, @Nullable final PsiClass qualifyingClass) throws IncorrectOperationException { PsiManager manager = referenceExpression.getManager(); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(manager.getProject()); GrReferenceExpression expressionFromText; if (qualifyingClass == null) { final PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class); final PsiClass containingClass = member.getContainingClass(); if (parentClass != null && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) { expressionFromText = (GrReferenceExpression)factory.createExpressionFromText(containingClass.getQualifiedName()+ ".this." + member.getName()); } else { expressionFromText = (GrReferenceExpression)factory.createExpressionFromText("this." + member.getName()); } } else { expressionFromText = (GrReferenceExpression)factory.createExpressionFromText(qualifyingClass.getQualifiedName()+ '.' + member.getName()); } CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject()); expressionFromText = (GrReferenceExpression)codeStyleManager.reformat(expressionFromText); return (GrReferenceExpression)referenceExpression.replace(expressionFromText); }
@Override public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr) throws IncorrectOperationException { PsiManager manager = expr.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); @NonNls String text = "if(a){\nst;\n}elseif(){else{\n}"; PsiIfStatement ifStatement = (PsiIfStatement)factory.createStatementFromText(text, null); ifStatement = (PsiIfStatement)codeStyleManager.reformat(ifStatement); ifStatement.getCondition().replace(expr); PsiExpressionStatement statement = (PsiExpressionStatement)expr.getParent(); ifStatement = (PsiIfStatement)statement.replace(ifStatement); PsiCodeBlock block = ((PsiBlockStatement)ifStatement.getThenBranch()).getCodeBlock(); PsiStatement afterStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(block.getStatements()[0]); TextRange range = afterStatement.getTextRange(); editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()); return new TextRange(range.getStartOffset(), range.getStartOffset()); }
public void testFormatterTurnedOff() { myFixture.configureByFiles("FormatterTestData.dot"); // everything is turned off test CodeStyleSettingsManager.getSettings(getProject()).SPACE_AROUND_ASSIGNMENT_OPERATORS = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_AFTER_SEMICOLON = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_AROUND_EQUALITY_OPERATORS = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_CLASS_LBRACE = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_METHOD_LBRACE = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_WITHIN_BRACKETS= false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_CLASS_LBRACE = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_METHOD_LBRACE = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_WITHIN_BRACKETS= false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_AFTER_SEMICOLON = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_SEMICOLON = false; CodeStyleSettingsManager.getSettings(getProject()).SPACE_AFTER_COLON = false; new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(), ContainerUtil.newArrayList(myFixture.getFile().getTextRange())); } }.execute(); myFixture.checkResultByFile("FormatterTestDataTurnedOff.dot"); }
private void onProcessItemViewBinder(final PsiDirectory dir, final String typeName, final PsiClass itemClass) { PsiFile file = itemClass.getContainingFile(); final PsiDocumentManager manager = PsiDocumentManager.getInstance(itemClass.getProject()); final Document document = manager.getDocument(file); if (document == null) { return; } new WriteCommandAction.Simple(itemClass.getProject()) { @Override protected void run() throws Throwable { manager.doPostponedOperationsAndUnblockDocument(document); document.setText(document.getText() .replace("MTI_CLASS", typeName) .replace("MTI_LOWER_NAME", CaseFormat.UPPER_CAMEL.to(LOWER_UNDERSCORE, typeName)) .replace("MTI_NAME", CaseFormat.UPPER_CAMEL.to(LOWER_CAMEL, typeName))); CodeStyleManager.getInstance(itemClass.getProject()).reformat(itemClass); } }.execute(); }
@Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement methodName = descriptor.getPsiElement(); final PsiMethod method = (PsiMethod)methodName.getParent(); if (method == null) { return; } final PsiCodeBlock body = method.getBody(); if (body == null) { return; } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiStatement newStatement = factory.createStatementFromText("super.tearDown();", null); final CodeStyleManager styleManager = CodeStyleManager.getInstance(project); final PsiJavaToken brace = body.getRBrace(); body.addBefore(newStatement, brace); styleManager.reformat(body); }
@NotNull @Override public PsiMethod createMethod(@NotNull final String name, final PsiType returnType) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(returnType)) { throw new IncorrectOperationException("Cannot create method with type \"null\"."); } final String canonicalText = returnType.getCanonicalText(true); final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { public " + canonicalText + " " + name + "() {} }"); final PsiClass[] classes = aFile.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException("Class was not created. Method name: " + name + "; return type: " + canonicalText); } final PsiMethod[] methods = classes[0].getMethods(); if (methods.length < 1) { throw new IncorrectOperationException("Method was not created. Method name: " + name + "; return type: " + canonicalText); } PsiMethod method = methods[0]; method = (PsiMethod)JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(method); return (PsiMethod)CodeStyleManager.getInstance(myManager.getProject()).reformat(method); }
public static Indent getMinLineIndent(Project project, Document document, int line1, int line2, FileType fileType) { CharSequence chars = document.getCharsSequence(); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); Indent minIndent = null; for (int line = line1; line <= line2; line++) { int lineStart = document.getLineStartOffset(line); int textStart = CharArrayUtil.shiftForward(chars, lineStart, " \t"); if (textStart >= document.getTextLength()) { textStart = document.getTextLength(); } else { char c = chars.charAt(textStart); if (c == '\n' || c == '\r') continue; // empty line } String space = chars.subSequence(lineStart, textStart).toString(); Indent indent = codeStyleManager.getIndent(space, fileType); minIndent = minIndent != null ? indent.min(minIndent) : indent; } if (minIndent == null && line1 == line2 && line1 < document.getLineCount() - 1) { return getMinLineIndent(project, document, line1 + 1, line1 + 1, fileType); } //if (minIndent == Integer.MAX_VALUE){ // minIndent = 0; //} return minIndent; }
private static PsiExpressionStatement createAssignment(PsiLocalVariable local, String fieldname, PsiElementFactory factory) { try { String pattern = fieldname + "=0;"; PsiExpressionStatement statement = (PsiExpressionStatement)factory.createStatementFromText(pattern, null); statement = (PsiExpressionStatement)CodeStyleManager.getInstance(local.getProject()).reformat(statement); PsiAssignmentExpression expr = (PsiAssignmentExpression)statement.getExpression(); final PsiExpression initializer = RefactoringUtil.convertInitializerToNormalExpression(local.getInitializer(), local.getType()); expr.getRExpression().replace(initializer); return statement; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
public static PsiExpression createNewExpressionFromArrayInitializer(PsiArrayInitializerExpression initializer, PsiType forcedType) throws IncorrectOperationException { PsiType initializerType = null; if (initializer != null) { if (forcedType != null) { initializerType = forcedType; } else { initializerType = getTypeByExpression(initializer); } } if (initializerType == null) { return initializer; } LOG.assertTrue(initializerType instanceof PsiArrayType); PsiElementFactory factory = JavaPsiFacade.getInstance(initializer.getProject()).getElementFactory(); PsiNewExpression result = (PsiNewExpression)factory.createExpressionFromText("new " + initializerType.getPresentableText() + "{}", null); result = (PsiNewExpression)CodeStyleManager.getInstance(initializer.getProject()).reformat(result); PsiArrayInitializerExpression arrayInitializer = result.getArrayInitializer(); LOG.assertTrue(arrayInitializer != null); arrayInitializer.replace(initializer); return result; }
@NotNull @Override public PsiCatchSection createCatchSection(@NotNull final PsiType exceptionType, @NotNull final String exceptionName, @Nullable final PsiElement context) throws IncorrectOperationException { if (!(exceptionType instanceof PsiClassType || exceptionType instanceof PsiDisjunctionType)) { throw new IncorrectOperationException("Unexpected type:" + exceptionType); } @NonNls final String text = "catch (" + exceptionType.getCanonicalText(true) + " " + exceptionName + ") {}"; final DummyHolder holder = DummyHolderFactory.createHolder(myManager, new JavaDummyElement(text, CATCH_SECTION, level(context)), context); final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode()); if (!(element instanceof PsiCatchSection)) { throw new IncorrectOperationException("Incorrect catch section '" + text + "'. Parsed element: " + element); } final Project project = myManager.getProject(); final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(project); helper.setupCatchBlock(exceptionName, exceptionType, context, (PsiCatchSection)element); final CodeStyleManager styleManager = CodeStyleManager.getInstance(project); final PsiCatchSection catchSection = (PsiCatchSection)styleManager.reformat(element); GeneratedMarkerVisitor.markGenerated(catchSection); return catchSection; }
public static PsiElement replaceDiamondWithExplicitTypes(PsiElement element) { final PsiElement parent = element.getParent(); if (!(parent instanceof PsiJavaCodeReferenceElement)) { return parent; } final PsiJavaCodeReferenceElement javaCodeReferenceElement = (PsiJavaCodeReferenceElement) parent; final StringBuilder text = new StringBuilder(); text.append(javaCodeReferenceElement.getQualifiedName()); text.append('<'); final PsiNewExpression newExpression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class); final PsiDiamondType.DiamondInferenceResult result = PsiDiamondTypeImpl.resolveInferredTypesNoCheck(newExpression, newExpression); text.append(StringUtil.join(result.getInferredTypes(), new Function<PsiType, String>() { @Override public String fun(PsiType psiType) { return psiType.getCanonicalText(); } }, ",")); text.append('>'); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(element.getProject()); final PsiJavaCodeReferenceElement newReference = elementFactory.createReferenceFromText(text.toString(), element); return CodeStyleManager.getInstance(javaCodeReferenceElement.getProject()).reformat(javaCodeReferenceElement.replace(newReference)); }
static <T extends PsiQualifiedExpression> T createQualifiedExpression(@NotNull PsiManager manager, PsiClass qualifierClass, @NotNull String qName) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); if (qualifierClass != null) { T qualifiedThis = (T)factory.createExpressionFromText("q." + qName, null); qualifiedThis = (T)CodeStyleManager.getInstance(manager.getProject()).reformat(qualifiedThis); PsiJavaCodeReferenceElement thisQualifier = qualifiedThis.getQualifier(); LOG.assertTrue(thisQualifier != null); thisQualifier.bindToElement(qualifierClass); return qualifiedThis; } else { return (T)factory.createExpressionFromText(qName, null); } }
private static boolean isCastRedundantInRefExpression (final PsiReferenceExpression refExpression, final PsiExpression castOperand) { final PsiElement resolved = refExpression.resolve(); final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE); CodeStyleManager.getInstance(refExpression.getProject()).performActionWithFormatterDisabled(new Runnable() { @Override public void run() { try { final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(refExpression.getProject()).getElementFactory(); final PsiExpression copyExpression = elementFactory.createExpressionFromText(refExpression.getText(), refExpression); if (copyExpression instanceof PsiReferenceExpression) { final PsiReferenceExpression copy = (PsiReferenceExpression)copyExpression; final PsiExpression qualifier = copy.getQualifierExpression(); if (qualifier != null) { qualifier.replace(castOperand); result.set(Boolean.valueOf(copy.resolve() == resolved)); } } } catch (IncorrectOperationException ignore) { } } }); return result.get().booleanValue(); }
private void addAssignmentToField(final String parameterName, final PsiMethod constructor) { @NonNls String fieldName = convertToFieldName(parameterName); final PsiManager manager = PsiManager.getInstance(myProject); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final PsiCodeBlock body = constructor.getBody(); if (body != null) { try { final PsiReferenceExpression refExpr = (PsiReferenceExpression)factory.createExpressionFromText(fieldName, body); if (refExpr.resolve() != null) fieldName = "this." + fieldName; PsiStatement statement = factory.createStatementFromText(fieldName + "=" + parameterName + ";", null); statement = (PsiStatement)CodeStyleManager.getInstance(manager.getProject()).reformat(statement); body.add(statement); } catch (IncorrectOperationException e) { LOG.error(e); } } }
public PsiElement replaceByStatement(final PsiMethod extractedMethod, final PsiMethodCallExpression methodCallExpression, final PsiVariable outputVariable) throws IncorrectOperationException { PsiStatement statement = null; if (outputVariable != null) { ReturnValue returnValue = getOutputVariableValue(outputVariable); if (returnValue == null && outputVariable instanceof PsiField) { returnValue = new FieldReturnValue((PsiField)outputVariable); } if (returnValue == null) return null; statement = returnValue.createReplacement(extractedMethod, methodCallExpression); } else if (getReturnValue() != null) { statement = getReturnValue().createReplacement(extractedMethod, methodCallExpression); } if (statement == null) { final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(methodCallExpression.getProject()).getElementFactory(); PsiExpressionStatement expressionStatement = (PsiExpressionStatement) elementFactory.createStatementFromText("x();", null); final CodeStyleManager styleManager = CodeStyleManager.getInstance(methodCallExpression.getManager()); expressionStatement = (PsiExpressionStatement)styleManager.reformat(expressionStatement); expressionStatement.getExpression().replace(methodCallExpression); statement = expressionStatement; } return replaceWith(statement); }
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent, final Editor editor, final PsiFile file, final Project project) { try { CodeStyleManager.getInstance(project).reformat(parent); } catch (IncorrectOperationException e) { LOG.error(e); } int offset = parent.getTextRange().getEndOffset() - 1; editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); final PsiReferenceParameterList parameterList = parent.getBaseClassReference().getParameterList(); final PsiTypeElement[] parameters = parameterList != null ? parameterList.getTypeParameterElements() : null; if (shouldStartTypeTemplate(parameters)) { startTemplate(parent, editor, createOverrideRunnable(editor, file, project), parameters); return null; } return createOverrideRunnable(editor, file, project); }
public void testFormatCodeFragment() throws Exception { final JavaCodeFragmentFactory factory = JavaCodeFragmentFactory.getInstance(getProject()); final PsiCodeFragment fragment = factory.createCodeBlockCodeFragment("a=1;int b=2;", null, true); final PsiElement[] result = new PsiElement[1]; CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { @Override public void run() { WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { try { result[0] = CodeStyleManager.getInstance(getProject()).reformat(fragment); } catch (IncorrectOperationException e) { fail(e.getLocalizedMessage()); } } }); } }, null, null); assertEquals("a = 1;\n" + "int b = 2;", result[0].getText()); }
public void testFormatter() { myFixture.configureByFile("FormatterTest.epigraph"); // String psiDump = DebugUtil.psiToString(myFixture.getFile(), true, false).trim(); // System.out.println(psiDump); new WriteCommandAction.Simple<Void>(getProject()) { @Override protected void run() throws com.intellij.util.IncorrectOperationException { CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile()); } }.execute(); try { myFixture.checkResultByFile("FormatterTest-out.epigraph"); } catch (FileComparisonFailure fce) { fail(fce.getMessage()); } }
@Override public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr) throws IncorrectOperationException { PsiManager manager = expr.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); @NonNls String text = "if(a){\nst;\n}else{\n}"; PsiIfStatement ifStatement = (PsiIfStatement)factory.createStatementFromText(text, null); ifStatement = (PsiIfStatement)codeStyleManager.reformat(ifStatement); ifStatement.getCondition().replace(expr); PsiExpressionStatement statement = (PsiExpressionStatement)expr.getParent(); ifStatement = (PsiIfStatement)statement.replace(ifStatement); PsiCodeBlock block = ((PsiBlockStatement)ifStatement.getThenBranch()).getCodeBlock(); PsiStatement afterStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(block.getStatements()[0]); TextRange range = afterStatement.getTextRange(); editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()); return new TextRange(range.getStartOffset(), range.getStartOffset()); }
@Override public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr) throws IncorrectOperationException { PsiManager manager = expr.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); PsiPrefixExpression prefixExpr = (PsiPrefixExpression)factory.createExpressionFromText("!(a instanceof Type)", null); prefixExpr = (PsiPrefixExpression)codeStyleManager.reformat(prefixExpr); PsiParenthesizedExpression parenthExpr = (PsiParenthesizedExpression)prefixExpr.getOperand(); PsiInstanceOfExpression instanceofExpr = (PsiInstanceOfExpression)parenthExpr.getExpression(); instanceofExpr.getOperand().replace(expr); prefixExpr = (PsiPrefixExpression)expr.replace(prefixExpr); parenthExpr = (PsiParenthesizedExpression)prefixExpr.getOperand(); instanceofExpr = (PsiInstanceOfExpression)parenthExpr.getExpression(); instanceofExpr = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(instanceofExpr); TextRange range = instanceofExpr.getCheckType().getTextRange(); editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()); return new TextRange(range.getStartOffset(), range.getStartOffset()); }
private void doTest(final boolean reformatText) { myFixture.configureByFile("formatter/" + getTestName(true) + ".py"); WriteCommandAction.runWriteCommandAction(null, new Runnable() { @Override public void run() { CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject()); PsiFile file = myFixture.getFile(); if (reformatText) { codeStyleManager.reformatText(file, 0, file.getTextLength()); } else { codeStyleManager.reformat(file); } } }); myFixture.checkResultByFile("formatter/" + getTestName(true) + "_after.py"); }
public boolean processAddDefaultConstructor(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) { if (!(usage.getElement() instanceof PsiClass) || !isJavaUsage(usage)) return true; PsiClass aClass = (PsiClass)usage.getElement(); if (!(aClass instanceof PsiAnonymousClass)) { final PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiMethod constructor = factory.createMethodFromText(aClass.getName() + "(){}", aClass); constructor = (PsiMethod)CodeStyleManager.getInstance(data.getProject()).reformat(constructor); constructor = (PsiMethod)aClass.add(constructor); PsiUtil.setModifierProperty(constructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true); processAddSuperCall(data, new UsageInfo(constructor), usages); } else { return true; } return false; }
private static PsiClass createClassInQualifier(PsiClass psiClass, CreateClassKind classKind, String name, PsiJavaCodeReferenceElement referenceElement) { try { if (!FileModificationService.getInstance().preparePsiElementForWrite(psiClass)) return null; PsiManager manager = psiClass.getManager(); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); PsiClass result = classKind == CreateClassKind.INTERFACE ? elementFactory.createInterface(name) : classKind == CreateClassKind.CLASS ? elementFactory.createClass(name) : classKind == CreateClassKind.ANNOTATION ? elementFactory.createAnnotationType(name) : elementFactory.createEnum(name); CreateFromUsageBaseFix.setupGenericParameters(result, referenceElement); result = (PsiClass)CodeStyleManager.getInstance(manager.getProject()).reformat(result); return (PsiClass) psiClass.add(result); } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
@Override protected void reformat(PsiElement atCaret) throws IncorrectOperationException { if (atCaret == null) { return; } PsiElement parent = atCaret.getParent(); if (parent instanceof PsiForStatement) { atCaret = parent; } if (parent instanceof PsiIfStatement && atCaret == ((PsiIfStatement)parent).getElseBranch()) { PsiFile file = atCaret.getContainingFile(); Document document = file.getViewProvider().getDocument(); if (document != null) { TextRange elseIfRange = atCaret.getTextRange(); int lineStart = document.getLineStartOffset(document.getLineNumber(elseIfRange.getStartOffset())); CodeStyleManager.getInstance(atCaret.getProject()).reformatText(file, lineStart, elseIfRange.getEndOffset()); return; } } super.reformat(atCaret); }
@Override protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { if (PsiImplUtil.isWhiteSpaceOrNls(element)) { element = PsiTreeUtil.prevLeaf(element); } LOG.assertTrue(GeeseUtil.isClosureRBrace(element) && GeeseUtil.isClosureContainLF(element)); PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiFile file = element.getContainingFile(); Document document = PsiDocumentManager.getInstance(project).getDocument(file); TextRange textRange = findRange(element); int startOffset = textRange.getStartOffset(); int endOffset = textRange.getEndOffset(); RangeMarker rangeMarker = document.createRangeMarker(textRange); String text = document.getText(); for (int i = endOffset - 1; i >= startOffset; i--) { if (text.charAt(i) == '\n') document.deleteString(i, i + 1); } CodeStyleManager.getInstance(project).reformatText(file, rangeMarker.getStartOffset(), rangeMarker.getEndOffset()); }
@Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return; final PsiConditionalExpression conditionalExpression = PsiTreeUtil.getParentOfType(element, PsiConditionalExpression.class); final PsiExpression thenExpression = (PsiExpression)conditionalExpression.getThenExpression().copy(); final PsiExpressionList thenArgsList = ((PsiCallExpression)thenExpression).getArgumentList(); final PsiExpression[] thenExpressions = thenArgsList.getExpressions(); final PsiExpression elseExpression = conditionalExpression.getElseExpression(); final PsiExpressionList elseArgsList = ((PsiCallExpression)elseExpression).getArgumentList(); final PsiExpression[] elseExpressions = elseArgsList.getExpressions(); for (int i = 0; i < thenExpressions.length; i++) { PsiExpression lExpr = thenExpressions[i]; PsiExpression rExpr = elseExpressions[i]; if (!PsiEquivalenceUtil.areElementsEquivalent(lExpr, rExpr)) { lExpr.replace(JavaPsiFacade.getElementFactory(project).createExpressionFromText( conditionalExpression.getCondition().getText() + "?" + lExpr.getText() + ":" + rExpr.getText(), lExpr)); break; } } CodeStyleManager.getInstance(project).reformat(conditionalExpression.replace(thenExpression)); }
/** * This test merely checks that call to {@link com.intellij.psi.codeStyle.CodeStyleManager#reformat(com.intellij.psi.PsiElement)} * is possible for Python sources. */ public void testReformatOfSingleElementPossible() { myFixture.configureByFile("formatter/" + getTestName(true) + ".py"); WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new Runnable() { @Override public void run() { final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); assertNotNull(elementAtCaret); final PyStatement statement = PsiTreeUtil.getParentOfType(elementAtCaret, PyStatement.class, false); assertNotNull(statement); final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myFixture.getProject()); codeStyleManager.reformat(statement); } }); myFixture.checkResultByFile("formatter/" + getTestName(true) + "_after.py"); }
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(); } }
private void doPostProcessing(PsiElement newFile) { if (ApplicationManager.getApplication().isUnitTestMode()) return; // don't move classes to new files with corresponding class names and reformat if (!(newFile instanceof PsiJavaFile)) { LOG.info(".java is not assigned to java file type"); return; } newFile = JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newFile); newFile = CodeStyleManager.getInstance(myProject).reformat(newFile); PsiClass[] inner = ((PsiJavaFile)newFile).getClasses(); for (PsiClass psiClass : inner) { MoveClassToSeparateFileFix fix = new MoveClassToSeparateFileFix(psiClass); if (fix.isAvailable(myProject, null, (PsiFile)newFile)) { fix.invoke(myProject, null, (PsiFile)newFile); } } }