use of com.intellij.psi.codeStyle.CodeStyleManager in project idea-handlebars by dmarcotte.
the class HbTypedHandler method adjustMustacheFormatting.
/**
* When appropriate, adjusts the formatting for some 'staches, particularily close 'staches
* and simple inverses ("{{^}}" and "{{else}}")
*/
private static void adjustMustacheFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
if (!HbConfig.isFormattingEnabled()) {
// formatting disabled; nothing to do
return;
}
PsiElement elementAtCaret = provider.findElementAt(offset - 1, HbLanguage.class);
PsiElement closeOrSimpleInverseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement element) {
return element != null && (element instanceof HbSimpleInverse || element instanceof HbCloseBlockMustache);
}
});
// run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
if (closeOrSimpleInverseParent != null) {
// grab the current caret position (AutoIndentLinesHandler is about to mess with it)
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
CaretModel caretModel = editor.getCaretModel();
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
}
}
use of com.intellij.psi.codeStyle.CodeStyleManager in project android by JetBrains.
the class AndroidExtractAsIncludeAction method doRefactor.
private static void doRefactor(AndroidFacet facet, PsiFile file, XmlFile newFile, PsiElement from, PsiElement to, XmlTag parentTag, boolean wrapWithMerge) {
final Project project = facet.getModule().getProject();
final String textToExtract = file.getText().substring(from.getTextRange().getStartOffset(), to.getTextRange().getEndOffset());
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
final Document document = documentManager.getDocument(newFile);
assert document != null;
document.setText("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + (wrapWithMerge ? "<merge>\n" + textToExtract + "\n</merge>" : textToExtract));
documentManager.commitDocument(document);
final Set<String> unknownPrefixes = new HashSet<String>();
newFile.accept(new XmlRecursiveElementVisitor() {
@Override
public void visitXmlTag(XmlTag tag) {
super.visitXmlTag(tag);
final String prefix = tag.getNamespacePrefix();
if (!unknownPrefixes.contains(prefix) && tag.getNamespace().length() == 0) {
unknownPrefixes.add(prefix);
}
}
@Override
public void visitXmlAttribute(XmlAttribute attribute) {
final String prefix = attribute.getNamespacePrefix();
if (!unknownPrefixes.contains(prefix) && attribute.getNamespace().length() == 0) {
unknownPrefixes.add(prefix);
}
}
});
final XmlTag rootTag = newFile.getRootTag();
assert rootTag != null;
final XmlElementFactory elementFactory = XmlElementFactory.getInstance(project);
final XmlAttribute[] attributes = rootTag.getAttributes();
final XmlAttribute firstAttribute = attributes.length > 0 ? attributes[0] : null;
for (String prefix : unknownPrefixes) {
final String namespace = parentTag.getNamespaceByPrefix(prefix);
final String xmlNsAttrName = "xmlns:" + prefix;
if (namespace.length() > 0 && rootTag.getAttribute(xmlNsAttrName) == null) {
final XmlAttribute xmlnsAttr = elementFactory.createXmlAttribute(xmlNsAttrName, namespace);
if (firstAttribute != null) {
rootTag.addBefore(xmlnsAttr, firstAttribute);
} else {
rootTag.add(xmlnsAttr);
}
}
}
String includingLayout = SdkConstants.LAYOUT_RESOURCE_PREFIX + ResourceHelper.getResourceName(file);
IncludeReference.setIncludingLayout(project, newFile, includingLayout);
final String resourceName = AndroidCommonUtils.getResourceName(ResourceType.LAYOUT.getName(), newFile.getName());
final XmlTag includeTag = elementFactory.createTagFromText("<include layout=\"@layout/" + resourceName + "\"/>");
parentTag.addAfter(includeTag, to);
parentTag.deleteChildRange(from, to);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.reformat(newFile);
}
use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.
the class ExtractParameterAsLocalVariableFix method doFix.
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement element = descriptor.getPsiElement();
if (!(element instanceof PsiExpression)) {
return;
}
final PsiExpression expression = ParenthesesUtils.stripParentheses((PsiExpression) element);
if (!(expression instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression parameterReference = (PsiReferenceExpression) expression;
final PsiElement target = parameterReference.resolve();
if (!(target instanceof PsiParameter)) {
return;
}
final PsiParameter parameter = (PsiParameter) target;
final PsiElement declarationScope = parameter.getDeclarationScope();
final PsiElement body;
if (declarationScope instanceof PsiMethod) {
final PsiMethod method = (PsiMethod) declarationScope;
body = method.getBody();
} else if (declarationScope instanceof PsiCatchSection) {
final PsiCatchSection catchSection = (PsiCatchSection) declarationScope;
body = catchSection.getCatchBlock();
} else if (declarationScope instanceof PsiLoopStatement) {
final PsiLoopStatement forStatement = (PsiLoopStatement) declarationScope;
final PsiStatement forBody = forStatement.getBody();
if (forBody instanceof PsiBlockStatement) {
final PsiBlockStatement blockStatement = (PsiBlockStatement) forBody;
body = blockStatement.getCodeBlock();
} else {
body = forBody;
}
} else if (declarationScope instanceof PsiLambdaExpression) {
final PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) declarationScope;
body = lambdaExpression.getBody();
} else {
return;
}
if (body == null) {
return;
}
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
final String parameterName = parameterReference.getText();
final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
final String variableName = javaCodeStyleManager.suggestUniqueVariableName(parameterName, parameterReference, true);
final SearchScope scope = parameter.getUseScope();
final Query<PsiReference> search = ReferencesSearch.search(parameter, scope);
final PsiReference reference = search.findFirst();
if (reference == null) {
return;
}
final PsiElement referenceElement = reference.getElement();
if (!(referenceElement instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression firstReference = (PsiReferenceExpression) referenceElement;
final PsiElement[] children = body.getChildren();
final int startIndex;
final int endIndex;
if (body instanceof PsiCodeBlock) {
startIndex = 1;
endIndex = children.length - 1;
} else {
startIndex = 0;
endIndex = children.length;
}
boolean newDeclarationCreated = false;
final StringBuilder buffer = new StringBuilder();
for (int i = startIndex; i < endIndex; i++) {
final PsiElement child = children[i];
newDeclarationCreated |= replaceVariableName(child, firstReference, variableName, parameterName, buffer);
}
if (body instanceof PsiExpression) {
// expression lambda
buffer.insert(0, "return ");
buffer.append(';');
}
final String replacementText;
if (newDeclarationCreated) {
replacementText = "{" + buffer + '}';
} else {
final PsiType type = parameter.getType();
final String className = type.getCanonicalText();
replacementText = '{' + className + ' ' + variableName + " = " + parameterName + ';' + buffer + '}';
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiCodeBlock block = elementFactory.createCodeBlockFromText(replacementText, declarationScope);
body.replace(block);
codeStyleManager.reformat(declarationScope);
}
use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.
the class GenerateComponentExternalizationAction method actionPerformed.
public void actionPerformed(AnActionEvent e) {
final PsiClass target = getComponentInContext(e.getDataContext());
assert target != null;
final PsiElementFactory factory = JavaPsiFacade.getInstance(target.getProject()).getElementFactory();
final CodeStyleManager formatter = CodeStyleManager.getInstance(target.getManager().getProject());
final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(target.getProject());
final String qualifiedName = target.getQualifiedName();
Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> {
try {
final PsiReferenceList implList = target.getImplementsList();
assert implList != null;
final PsiJavaCodeReferenceElement referenceElement = factory.createReferenceFromText(PERSISTENCE_STATE_COMPONENT + "<" + qualifiedName + ">", target);
implList.add(styler.shortenClassReferences(referenceElement.copy()));
PsiMethod read = factory.createMethodFromText("public void loadState(" + qualifiedName + " state) {\n" + " com.intellij.util.xmlb.XmlSerializerUtil.copyBean(state, this);\n" + "}", target);
read = (PsiMethod) formatter.reformat(target.add(read));
styler.shortenClassReferences(read);
PsiMethod write = factory.createMethodFromText("public " + qualifiedName + " getState() {\n" + " return this;\n" + "}\n", target);
write = (PsiMethod) formatter.reformat(target.add(write));
styler.shortenClassReferences(write);
PsiAnnotation annotation = target.getModifierList().addAnnotation(STATE);
annotation = (PsiAnnotation) formatter.reformat(annotation.replace(factory.createAnnotationFromText("@" + STATE + "(name = \"" + qualifiedName + "\", " + "storages = {@" + STORAGE + "(file = \"" + StoragePathMacros.WORKSPACE_FILE + "\"\n )})", target)));
styler.shortenClassReferences(annotation);
} catch (IncorrectOperationException e1) {
LOG.error(e1);
}
});
CommandProcessor.getInstance().executeCommand(target.getProject(), runnable, DevKitBundle.message("command.implement.externalizable"), null);
}
use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.
the class InlineIncrementIntention method processIntention.
@Override
protected void processIntention(@NotNull PsiElement element) {
final PsiReferenceExpression operandExpression = IncrementUtil.getIncrementOrDecrementOperand(element);
final PsiExpressionStatement expressionStatement = ObjectUtils.tryCast(element.getParent(), PsiExpressionStatement.class);
final String operatorText = IncrementUtil.getOperatorText(element);
if (operandExpression != null && expressionStatement != null && operatorText != null) {
final PsiVariable variable = resolveSimpleVariableReference(operandExpression);
if (variable != null) {
final Occurrence occurrence = findSingleReadOccurrence(expressionStatement, variable);
if (occurrence != null) {
final Project project = expressionStatement.getProject();
final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
final String text = occurrence.isPrevious ? occurrence.referenceExpression.getText() + operatorText : operatorText + occurrence.referenceExpression.getText();
PsiExpression incrementOrDecrement = factory.createExpressionFromText(text, expressionStatement);
incrementOrDecrement = (PsiExpression) occurrence.referenceExpression.replace(incrementOrDecrement);
final CodeStyleManager codeStyle = CodeStyleManager.getInstance(project);
codeStyle.reformat(incrementOrDecrement, true);
final CommentTracker ct = new CommentTracker();
ct.deleteAndRestoreComments(expressionStatement);
}
}
}
}
Aggregations