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 element = psiFile.findElementAt(editor.getCaretModel().getOffset()); PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (psiClass == null) return; if (psiClass.getNameIdentifier() == null) return; String className = psiClass.getNameIdentifier().getText(); PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); build(editor, elementFactory, project, psiClass, className); JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); styleManager.optimizeImports(psiFile); styleManager.shortenClassReferences(psiClass); }); }
private void addAnnotationToPackageInfo(Project project, PsiJavaFile packageInfoFile) { if (!FileModificationService.getInstance().preparePsiElementForWrite(packageInfoFile)) { return; } PsiPackageStatement packageStatement = packageInfoFile.getPackageStatement(); if (packageStatement == null) { return; } PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiAnnotation annotation = factory.createAnnotationFromText("@" + annotationForTypeQualifierFqn, packageInfoFile.getContext()); PsiElement addedAnnotation = packageInfoFile.addBefore(annotation, packageStatement); JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedAnnotation); removeRedundantAnnotationsInPackage(project, packageInfoFile.getContainingDirectory().getFiles(), annotation); }
@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); } }
private boolean addExtendInterfaces(ClassInfo info, JavaCodeStyleManager styleManager, PsiElementFactory elementFactory, PsiClass psic) { List<String> interfaces = info.getInterfaces(); if(interfaces != null){ PsiReferenceList list = psic.getExtendsList(); if(list == null){ Util.log(" psic.getExtendsList() == null"); return false; } for(String inter : interfaces){ PsiJavaCodeReferenceElement reference = elementFactory.createReferenceFromText(inter, psic); styleManager.shortenClassReferences(reference); list.add(reference); } } return true; }
@Override public void makeInterfaceExtend(PsiClass mClass, PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) { // get extend interfaces. final PsiClassType[] implementsListTypes = mClass.getExtendsListTypes(); final String implementsType = "com.heaven7.java.data.mediator.DataPools.Poolable"; for (PsiClassType implementsListType : implementsListTypes) { PsiClass resolved = implementsListType.resolve(); // Already implements Parcelable, no need to add it if (resolved != null && implementsType.equals(resolved.getQualifiedName())) { return; } } PsiJavaCodeReferenceElement implementsReference = elementFactory.createReferenceFromText(implementsType, mClass); PsiReferenceList implementsList = mClass.getExtendsList(); if (implementsList != null) { styleManager.shortenClassReferences(implementsReference); implementsList.add(implementsReference); } }
public static void addJavaImport(Project project, @NotNull PsiJavaFile psiJavaFile, GlobalSearchScope scope, String... classQNames) { if (project == null) { project = psiJavaFile.getProject(); } if (scope == null) { scope = GlobalSearchScope.allScope(project); } if (classQNames != null) { JavaCodeStyleManager factory = JavaCodeStyleManager.getInstance(project); for (String name : classQNames) { PsiClass clazz = JavaPsiFacade.getInstance(project).findClass(name, scope); if (clazz != null) { factory.addImport(psiJavaFile, clazz); } } } }
@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); }
protected static NameSuggestionsGenerator createNameSuggestionGenerator(final PsiExpression expr, final String propName, final Project project, final String enteredName) { return new NameSuggestionsGenerator() { public SuggestedNameInfo getSuggestedNameInfo(PsiType type) { final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); SuggestedNameInfo info = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, propName, expr != null && expr.isValid() ? expr : null, type); if (expr != null && expr.isValid()) { info = codeStyleManager.suggestUniqueVariableName(info, expr, true); } final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil .completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, info), expr); return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings): strings, info); } }; }
@NotNull @Override public PsiField createField(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(type)) { throw new IncorrectOperationException("Cannot create field with type \"null\"."); } @NonNls final String text = "class _Dummy_ { private " + type.getCanonicalText(true) + " " + name + "; }"; final PsiJavaFile aFile = createDummyJavaFile(text); final PsiClass[] classes = aFile.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException("Class was not created " + text); } final PsiClass psiClass = classes[0]; final PsiField[] fields = psiClass.getFields(); if (fields.length < 1) { throw new IncorrectOperationException("Field was not created " + text); } PsiField field = fields[0]; field = (PsiField)JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(field); return (PsiField)CodeStyleManager.getInstance(myManager.getProject()).reformat(field); }
@NotNull @Override public PsiParameter createParameter(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(type)) { throw new IncorrectOperationException("Cannot create parameter with type \"null\"."); } final String text = type.getCanonicalText(true) + " " + name; PsiParameter parameter = createParameterFromText(text, null); final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myManager.getProject()); PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, JavaCodeStyleSettingsFacade.getInstance(myManager.getProject()).isGenerateFinalParameters()); GeneratedMarkerVisitor.markGenerated(parameter); parameter = (PsiParameter)JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(parameter); return (PsiParameter)codeStyleManager.reformat(parameter); }
public JavaCoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) { super(parentDisposable, applicationEnvironment); myProject.registerService(PsiElementFactory.class, new PsiElementFactoryImpl(myPsiManager)); myProject.registerService(JavaPsiImplementationHelper.class, createJavaPsiImplementationHelper()); myProject.registerService(PsiResolveHelper.class, new PsiResolveHelperImpl(myPsiManager)); myProject.registerService(LanguageLevelProjectExtension.class, new CoreLanguageLevelProjectExtension()); myProject.registerService(JavaResolveCache.class, new JavaResolveCache(myMessageBus)); myProject.registerService(JavaCodeStyleSettingsFacade.class, new CoreJavaCodeStyleSettingsFacade()); myProject.registerService(JavaCodeStyleManager.class, new CoreJavaCodeStyleManager()); myPackageIndex = createCorePackageIndex(); myProject.registerService(PackageIndex.class, myPackageIndex); myFileManager = createCoreFileManager(); myProject.registerService(JavaFileManager.class, myFileManager); JavaPsiFacadeImpl javaPsiFacade = new JavaPsiFacadeImpl(myProject, myPsiManager, myFileManager, myMessageBus); myProject.registerService(JavaPsiFacade.class, javaPsiFacade); }
@Override protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { if (!(element instanceof GrSwitchStatement)) return; final List<PsiEnumConstant> constants = findUnusedConstants((GrSwitchStatement)element); if (constants.isEmpty()) return; final PsiEnumConstant first = constants.get(0); final PsiClass aClass = first.getContainingClass(); if (aClass == null) return; String qName = aClass.getQualifiedName(); final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); PsiElement anchor = findAnchor(element); for (PsiEnumConstant constant : constants) { final GrCaseSection section = factory.createSwitchSection("case " + qName + "." + constant.getName() + ":\n break"); final PsiElement added = element.addBefore(section, anchor); element.addBefore(factory.createLineTerminator(1), anchor); JavaCodeStyleManager.getInstance(project).shortenClassReferences(added); } }
@Override public void processText(final Project project, final Template template, final Document document, final RangeMarker templateRange, final Editor editor) { if (!template.isToShortenLongNames()) return; try { PsiDocumentManager.getInstance(project).commitDocument(document); final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project); if (file instanceof GroovyFile) { JavaCodeStyleManager.getInstance(project).shortenClassReferences(file, templateRange.getStartOffset(),templateRange.getEndOffset()); } PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document); } catch (IncorrectOperationException e) { LOG.error(e); } }
private static void addToArrayConversion(final PsiElement element, final String prefix, @NonNls final String expressionString, @NonNls String presentableString, final Consumer<LookupElement> result, PsiElement qualifier) { final boolean callSpace = CodeStyleSettingsManager.getSettings(element.getProject()).SPACE_WITHIN_METHOD_CALL_PARENTHESES; final PsiExpression conversion; try { conversion = createExpression( getQualifierText(qualifier) + prefix + ".toArray(" + getSpace(callSpace) + expressionString + getSpace(callSpace) + ")", element); } catch (IncorrectOperationException e) { return; } String[] lookupStrings = {prefix + ".toArray(" + getSpace(callSpace) + expressionString + getSpace(callSpace) + ")", presentableString}; result.consume(new ExpressionLookupItem(conversion, PlatformIcons.METHOD_ICON, prefix + ".toArray(" + presentableString + ")", lookupStrings) { @Override public void handleInsert(InsertionContext context) { FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.SECOND_SMART_COMPLETION_TOAR); context.commitDocument(); JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(context.getFile(), context.getStartOffset(), context.getTailOffset()); } }); }
@Override public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { final PsiElement element = PsiUtilBase.getElementAtCaret(editor); final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (psiClass == null) return; final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); String annotation = ""; if (PsiUtil.getLanguageLevel(file).isAtLeast(LanguageLevel.JDK_1_5)) { annotation = "@SuppressWarnings({\"MethodOverridesStaticMethodOfSuperclass\", \"UnusedDeclaration\"})"; } final PsiMethod createUI = factory.createMethodFromText(annotation + "\npublic static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent c) {" + "\n return new " + psiClass.getName() + "();\n}", psiClass); final PsiMethod newMethod = (PsiMethod)psiClass.add(CodeStyleManager.getInstance(project).reformat(createUI)); JavaCodeStyleManager.getInstance(project).shortenClassReferences(newMethod); final PsiReturnStatement returnStatement = PsiTreeUtil.findChildOfType(newMethod, PsiReturnStatement.class); if (returnStatement != null) { final int offset = returnStatement.getTextRange().getEndOffset(); editor.getCaretModel().moveToOffset(offset - 2); } }
private static void registerPriorityActions(@NotNull QuickFixActionRegistrar registrar, @NotNull TextRange fixRange, @NotNull PsiReferenceExpression refExpr) { final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject()); final Map<VariableKind, IntentionAction> map = new EnumMap<VariableKind, IntentionAction>(VariableKind.class); map.put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr)); map.put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr)); if (!refExpr.isQualified()) { map.put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr)); map.put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr)); } final VariableKind kind = getKind(styleManager, refExpr); if (map.containsKey(kind)) { map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind))); } for (IntentionAction action : map.values()) { registrar.register(fixRange, action, null); } }
private ParameterInfoImpl[] getNewParametersInfo(PsiMethod method) throws IncorrectOperationException { List<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>(); PsiParameter[] parameters = method.getParameterList().getParameters(); PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(method.getProject()); SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, myParameterType); PsiParameter newParameter = factory.createParameter(nameInfo.names[0], myParameterType); if (method.getContainingClass().isInterface()) { PsiUtil.setModifierProperty(newParameter, PsiModifier.FINAL, false); } for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; if (i == myIndex) { newParameter.setName(parameter.getName()); parameter = newParameter; } result.add(new ParameterInfoImpl(i, parameter.getName(), parameter.getType())); } if (parameters.length == myIndex) { result.add(new ParameterInfoImpl(-1, newParameter.getName(), newParameter.getType())); } return result.toArray(new ParameterInfoImpl[result.size()]); }
@Override public PsiMethod[] generateGetters(PsiField field) { final Project project = field.getProject(); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiMethod getter = GenerateMembersUtil.generateSimpleGetterPrototype(field); final PsiType wrappedType = JavaFxPsiUtil.getWrappedPropertyType(field, project, JavaFxCommonClassNames.ourReadOnlyMap); final PsiTypeElement returnTypeElement = getter.getReturnTypeElement(); LOG.assertTrue(returnTypeElement != null); returnTypeElement.replace(factory.createTypeElement(wrappedType)); final PsiCodeBlock getterBody = getter.getBody(); LOG.assertTrue(getterBody != null); getterBody.getStatements()[0].replace(factory.createStatementFromText("return " + field.getName() + ".get();", field)); final PsiMethod propertyGetter = PropertyUtil.generateGetterPrototype(field); propertyGetter.setName(JavaCodeStyleManager.getInstance(project).variableNameToPropertyName(field.getName(), VariableKind.FIELD) + "Property"); return new PsiMethod[] {getter, GenerateMembersUtil.annotateOnOverrideImplement(field.getContainingClass(), propertyGetter)}; }
@Override protected boolean checkOutputVariablesCount() { myMultipleExitPoints = super.checkOutputVariablesCount(); myOutputFields = new PsiField[myOutputVariables.length]; for (int i = 0; i < myOutputVariables.length; i++) { PsiVariable variable = myOutputVariables[i]; if (!myInputVariables.contains(variable)) { //one field creation final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(myProject); final String fieldName = styleManager.suggestVariableName(VariableKind.FIELD, getPureName(variable), null, variable.getType()).names[0]; try { myOutputFields[i] = myElementFactory.createField(fieldName, variable.getType()); } catch (IncorrectOperationException e) { LOG.error(e); } } } return !myCreateInnerClass && myMultipleExitPoints; }
private static String createNewVariableName(@NotNull PsiWhileStatement scope, PsiType type, String containerName) { final Project project = scope.getProject(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); @NonNls String baseName; if (containerName != null) { baseName = StringUtils.createSingularFromName(containerName); } else { final SuggestedNameInfo suggestions = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, type); final String[] names = suggestions.names; if (names != null && names.length > 0) { baseName = names[0]; } else { baseName = "value"; } } if (baseName == null || baseName.isEmpty()) { baseName = "value"; } return codeStyleManager.suggestUniqueVariableName(baseName, scope, true); }
private static void shortenReference(PsiElement element, PsiElement elementToInsert) throws IncorrectOperationException { while (element.getParent() instanceof PsiJavaCodeReferenceElement) { element = element.getParent(); if (element == null) return; } //if (element instanceof PsiJavaCodeReferenceElement && elementToInsert != null) { // try { // element = ((PsiJavaCodeReferenceElement)element).bindToElement(elementToInsert); // } // catch (IncorrectOperationException e) { // // failed to bind // } //} final JavaCodeStyleManager codeStyleManagerEx = JavaCodeStyleManager.getInstance(element.getProject()); codeStyleManagerEx.shortenClassReferences(element, JavaCodeStyleManager.INCOMPLETE_CODE); }
private void outputConstructor(StringBuilder out) { final String typeText = myValueType.getCanonicalText(true); final String name = "value"; final String parameterName = JavaCodeStyleManager.getInstance(myProject).propertyNameToVariableName(name, VariableKind.PARAMETER); final String fieldName = getFieldName(name); out.append("\tpublic ").append(myClassName).append('('); out.append(CodeStyleSettingsManager.getSettings(myProject).GENERATE_FINAL_PARAMETERS ? "final " : ""); out.append(typeText).append(' ').append(parameterName); out.append(") {\n"); if (fieldName.equals(parameterName)) { out.append("\t\tthis.").append(fieldName).append(" = ").append(parameterName).append(";\n"); } else { out.append("\t\t").append(fieldName).append(" = ").append(parameterName).append(";\n"); } out.append("\t}"); }
private static void addSetContentViewStatement(final PsiCodeBlock body, final String layoutFieldRef) { final Project project = body.getProject(); final PsiElement lastBodyElement = body.getLastBodyElement(); if (lastBodyElement != null) { new WriteCommandAction(project, body.getContainingFile()) { @Override protected void run(@NotNull Result result) throws Throwable { final PsiStatement newStatement = PsiElementFactory.SERVICE.getInstance(project).createStatementFromText( "setContentView(" + layoutFieldRef + ");", body); body.addAfter(newStatement, lastBodyElement); JavaCodeStyleManager.getInstance(project).shortenClassReferences(body); CodeStyleManager.getInstance(project).reformat(body); } }.execute(); } }
private static void convertOldAnnotationAttributeToAnnotation(PsiModifierList modifierList, PsiAnnotation annotation, @NonNls String attribute, @NonNls String newAnnotation) throws IncorrectOperationException { PsiAnnotationParameterList list = annotation.getParameterList(); for (PsiNameValuePair pair : list.getAttributes()) { if (attribute.equals(pair.getName())) { final StringBuffer newAnnotationBuffer = new StringBuffer(); newAnnotationBuffer.append(newAnnotation).append('(').append(')'); final PsiElementFactory factory = JavaPsiFacade.getInstance(annotation.getProject()).getElementFactory(); final PsiAnnotation newPsiAnnotation = factory.createAnnotationFromText(newAnnotationBuffer.toString(), modifierList); JavaCodeStyleManager.getInstance(annotation.getProject()).shortenClassReferences(modifierList.addAfter(newPsiAnnotation, null)); } } }
private void applyNewSetterPrefix() { final String setterPrefix = Messages.showInputDialog(myTable, "New setter prefix:", "Rename Setters Prefix", null, mySetterPrefix, new MySetterPrefixInputValidator()); if (setterPrefix != null) { mySetterPrefix = setterPrefix; PropertiesComponent.getInstance(myProject).setValue(SETTER_PREFIX_KEY, setterPrefix); final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(myProject); for (String paramName : myParametersMap.keySet()) { final ParameterData data = myParametersMap.get(paramName); paramName = data.getParamName(); final String propertyName = javaCodeStyleManager.variableNameToPropertyName(paramName, VariableKind.PARAMETER); data.setSetterName(PropertyUtil.suggestSetterName(propertyName, setterPrefix)); } myTable.revalidate(); myTable.repaint(); } }
/** * This method is executed just after the <code>toString</code> method is created or updated. * * @param method the newly created/updated <code>toString</code> method. * @param params additional parameters stored with key/value in the map. * @param template the template to use * @throws IncorrectOperationException is thrown by IDEA */ private void afterCreateToStringMethod(PsiMethod method, Map<String, String> params, TemplateResource template) { PsiFile containingFile = clazz.getContainingFile(); if (containingFile instanceof PsiJavaFile) { final PsiJavaFile javaFile = (PsiJavaFile)containingFile; if (params.get("autoImportPackages") != null) { // keep this for old user templates autoImportPackages(javaFile, params.get("autoImportPackages")); } } method = (PsiMethod)JavaCodeStyleManager.getInstance(clazz.getProject()).shortenClassReferences(method); // jump to method if (!config.isJumpToMethod() || editor == null) { return; } int offset = method.getTextOffset(); if (offset <= 2) { return; } VisualPosition vp = editor.offsetToVisualPosition(offset); if (logger.isDebugEnabled()) logger.debug("Moving/Scrolling caret to " + vp + " (offset=" + offset + ")"); editor.getCaretModel().moveToVisualPosition(vp); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER_DOWN); }
private static void addDelegateArguments(JavaChangeInfo changeInfo, PsiElementFactory factory, final PsiCallExpression callExpression) throws IncorrectOperationException { final JavaParameterInfo[] newParms = changeInfo.getNewParameters(); final String[] oldParameterNames = changeInfo.getOldParameterNames(); for (int i = 0; i < newParms.length; i++) { JavaParameterInfo newParm = newParms[i]; final PsiExpression actualArg; if (newParm.getOldIndex() >= 0) { actualArg = factory.createExpressionFromText(oldParameterNames[newParm.getOldIndex()], callExpression); } else { actualArg = changeInfo.getValue(i, callExpression); } final PsiExpressionList argumentList = callExpression.getArgumentList(); if (actualArg != null && argumentList != null) { JavaCodeStyleManager.getInstance(callExpression.getProject()).shortenClassReferences(argumentList.add(actualArg)); } } }
protected void formatJavCode(PsiClass cls) { if (cls == null) { return; } JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(cls.getProject()); styleManager.optimizeImports(cls.getContainingFile()); styleManager.shortenClassReferences(cls); }
@Before @Override public void setUp() throws Exception { super.setUp(); final Project project = getProject(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); underTest = new FieldNamePolicy(codeStyleManager); }
@Before @Override public void setUp() throws Exception { super.setUp(); final Project project = getProject(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); underTest = new ParameterNamePolicy(codeStyleManager); }
protected PsiFile createFile(Project project, @NotNull PsiDirectory psiDirectory, String fileName, String context, LanguageFileType fileType) { PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, context); // reformat class CodeStyleManager.getInstance(project).reformat(psiFile); if (psiFile instanceof PsiJavaFile) { JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); styleManager.optimizeImports(psiFile); styleManager.shortenClassReferences(psiFile); } psiDirectory.add(psiFile); return psiFile; }
@Override protected void run() throws Throwable { // 将弹出dialog的方法写在StringBuilder里 StringBuilder dialog = new StringBuilder(); dialog.append("public void showDialog(){"); dialog.append("android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);"); dialog.append("builder.setTitle(\"Title\")\n"); dialog.append(".setMessage(\"Dialog content\")\n"); dialog.append(".setPositiveButton(\"OK\", new android.content.DialogInterface.OnClickListener() {\n" + "@Override\n" + "public void onClick(DialogInterface dialog, int which) {\n" + "\t\n" + "}" + "})\n"); dialog.append(".setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n" + "@Override\n" + "public void onClick(DialogInterface dialog, int which) {\n" + "\t\n" + "}" + "})\n"); dialog.append(".show();"); dialog.append("}"); // 将代码添加到当前类里 targetClass.add(factory.createMethodFromText(dialog.toString(), targetClass)); // 导入需要的类 JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); styleManager.optimizeImports(file); styleManager.shortenClassReferences(targetClass); }
@Override protected void run() throws Throwable { if (!onlyBinder) { createTypeClass(); } createItemViewBinderClass(); // reformat class JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); styleManager.optimizeImports(psiFile); styleManager.shortenClassReferences(clazz); new ReformatCodeProcessor(project, clazz.getContainingFile(), null, false).runWithoutProgress(); }
public static void replaceExpression(@NotNull String newExpression, @NotNull PsiExpression exp) throws IncorrectOperationException { final Project project = exp.getProject(); final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiExpression newCall = factory.createExpressionFromText(newExpression, null); final PsiElement insertedElement = exp.replace(newCall); final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(insertedElement); CodeStyleManager.getInstance(project).reformat(shortenedElement); }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final String newJBColor = String.format("new %s(%s, new java.awt.Color())", JBColor.class.getName(), element.getText()); final PsiExpression expression = factory.createExpressionFromText(newJBColor, element.getContext()); final PsiElement newElement = element.replace(expression); final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); final int offset = el.getTextOffset() + el.getText().length() - 2; final Editor editor = PsiUtilBase.findEditor(el); if (editor != null) { editor.getCaretModel().moveToOffset(offset); } }
private PsiMethod delegateMethod(@NonNls String delegationTarget, PsiMethod method, PsiSubstitutor substitutor) throws IncorrectOperationException { substitutor = OverrideImplementUtil.correctSubstitutor(method, substitutor); PsiMethod methodToAdd = GenerateMembersUtil.substituteGenericMethod(method, substitutor); final PsiModifierList modifierList = methodToAdd.getModifierList(); final NullableNotNullManager manager = NullableNotNullManager.getInstance(myProject); modifierList.setModifierProperty(PsiModifier.ABSTRACT, false); final PsiAnnotation nullable = manager.copyNullableAnnotation(method); if (nullable != null) { modifierList.addAfter(nullable, null); } else { final PsiAnnotation notNull = manager.copyNotNullAnnotation(method); if (notNull != null) { modifierList.addAfter(notNull, null); } } final String delegationBody = getDelegationBody(methodToAdd, delegationTarget); PsiCodeBlock newBody = myFactory.createCodeBlockFromText(delegationBody, method); PsiCodeBlock oldBody = methodToAdd.getBody(); if (oldBody != null) { oldBody.replace(newBody); } else { methodToAdd.addBefore(newBody, null); } if (methodToAdd.getDocComment() != null) methodToAdd.getDocComment().delete(); methodToAdd = (PsiMethod)CodeStyleManager.getInstance(myProject).reformat(methodToAdd); methodToAdd = (PsiMethod)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(methodToAdd); return methodToAdd; }
@Override protected void typeCalculationFinished(@Nullable final PsiType type) { if (type == null) { return; } hold(); final Project project = myElement.getProject(); DebuggerInvocationUtil.invokeLater(project, new Runnable() { public void run() { new WriteCommandAction(project, CodeInsightBundle.message("command.name.surround.with.runtime.cast")) { protected void run(@NotNull Result result) throws Throwable { try { PsiElementFactory factory = JavaPsiFacade.getInstance(myElement.getProject()).getElementFactory(); PsiParenthesizedExpression parenth = (PsiParenthesizedExpression)factory.createExpressionFromText("((" + type.getCanonicalText() + ")expr)", null); //noinspection ConstantConditions ((PsiTypeCastExpression)parenth.getExpression()).getOperand().replace(myElement); parenth = (PsiParenthesizedExpression)JavaCodeStyleManager.getInstance(project).shortenClassReferences(parenth); PsiExpression expr = (PsiExpression)myElement.replace(parenth); TextRange range = expr.getTextRange(); myEditor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); myEditor.getCaretModel().moveToOffset(range.getEndOffset()); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } catch (IncorrectOperationException e) { // OK here. Can be caused by invalid type like one for proxy starts with . '.Proxy34' } finally { release(); } } }.execute(); } }, myProgressIndicator.getModalityState()); }
/** * Adds an import statement to the javafile and optimizes the imports afterwards. * * * @param javaFile javafile. * @param importStatementOnDemand name of import statement, must be with a wildcard (etc. java.util.*). * @throws com.intellij.util.IncorrectOperationException * is thrown if there is an error creating the import statement. */ public static void addImportStatement(PsiJavaFile javaFile, String importStatementOnDemand) { PsiElementFactory factory = JavaPsiFacade.getInstance(javaFile.getProject()).getElementFactory(); PsiImportStatement is = factory.createImportStatementOnDemand(fixImportStatement(importStatementOnDemand)); // add the import to the file, and optimize the imports PsiImportList importList = javaFile.getImportList(); if (importList != null) { importList.add(is); } JavaCodeStyleManager.getInstance(javaFile.getProject()).optimizeImports(javaFile); }
private static void bindRef(@NotNull final PsiClass targetClass, @NotNull final GrReferenceElement ref) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { final PsiElement newRef = ref.bindToElement(targetClass); JavaCodeStyleManager.getInstance(targetClass.getProject()).shortenClassReferences(newRef); } }); }