use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class XsltExtractFunctionAction method extractImpl.
protected boolean extractImpl(XPathExpression expression, Set<XPathExpression> matchingExpressions, List<XmlTag> otherMatches, RefactoringOptions dlg) {
final XmlAttribute attribute = PsiTreeUtil.getContextOfType(expression, XmlAttribute.class, true);
assert attribute != null;
try {
final String name = dlg.getName();
final XmlTag rootTag = ((XmlFile) attribute.getParent().getContainingFile()).getRootTag();
final XmlTag[] templates = rootTag.findSubTags("template", XsltSupport.XSLT_NS);
final XmlTag insertionPoint = templates.length > 0 ? templates[0] : rootTag.getSubTags()[0];
final XmlTag parentTag = insertionPoint.getParentTag();
assert parentTag != null : "Could not locate position to create function at";
final XmlTag xmlTag = parentTag.createChildTag("function", XsltSupport.XSLT_NS, null, false);
xmlTag.setAttribute("name", name);
final XPathType type = ExpectedTypeUtil.mapType(expression, expression.getType());
xmlTag.setAttribute("as", prefixedName(type, insertionPoint));
final StringBuilder argList = new StringBuilder();
final List<XPathVariableReference> references = RefactoringUtil.collectVariableReferences(expression);
for (XPathVariableReference reference : references) {
final XPathVariable variable = reference.resolve();
if (variable instanceof XsltVariable) {
// don't pass through global parameters and variables
if (XsltCodeInsightUtil.getTemplateTag(variable, false) != null) {
final XmlTag param = parentTag.createChildTag("param", XsltSupport.XSLT_NS, null, false);
param.setAttribute("name", variable.getName());
if (!variable.getType().isAbstract()) {
param.setAttribute("as", prefixedName(ExpectedTypeUtil.mapType(expression, variable.getType()), parentTag));
}
RefactoringUtil.addParameter(xmlTag, param);
if (argList.length() > 0) {
argList.append(", ");
}
argList.append("$").append(variable.getName());
}
}
}
final XmlTag seqTag = parentTag.createChildTag("sequence", XsltSupport.XSLT_NS, null, false);
seqTag.setAttribute("select", expression.getText());
xmlTag.add(seqTag);
// TODO: revisit the formatting
final PsiElement element = parentTag.addBefore(xmlTag, insertionPoint);
final ASTNode node1 = parentTag.getNode();
assert node1 != null;
final ASTNode node2 = element.getNode();
assert node2 != null;
CodeStyleManager.getInstance(xmlTag.getManager().getProject()).reformatNewlyAddedElement(node1, node2);
final XPathExpression var = XPathChangeUtil.createExpression(expression, name + "(" + argList + ")");
expression.replace(var);
return true;
} catch (IncorrectOperationException e) {
Logger.getInstance(getClass().getName()).error(e);
return false;
}
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class PySmartEnterProcessor method process.
private void process(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile psiFile, final int attempt) throws TooManyAttemptsException {
if (attempt > MAX_ATTEMPTS) {
throw new TooManyAttemptsException();
}
try {
commit(editor);
if (myFirstErrorOffset != Integer.MAX_VALUE) {
editor.getCaretModel().moveToOffset(myFirstErrorOffset);
}
//myFirstErrorOffset = Integer.MAX_VALUE;
PsiElement statementAtCaret = getStatementAtCaret(editor, psiFile);
if (statementAtCaret == null) {
if (!new PyCommentBreakerEnterProcessor().doEnter(editor, psiFile, false)) {
SmartEnterUtil.plainEnter(editor);
}
return;
}
List<PsiElement> queue = new ArrayList<>();
collectAllElements(statementAtCaret, queue, true);
queue.add(statementAtCaret);
for (PsiElement element : queue) {
for (PyFixer fixer : ourFixers) {
fixer.apply(editor, this, element);
if (LookupManager.getInstance(project).getActiveLookup() != null) {
return;
}
PyPsiUtils.assertValid(element);
if (isUncommited(project) || !element.isValid()) {
process(project, editor, psiFile, attempt + 1);
return;
}
}
}
doEnter(statementAtCaret, editor);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class PyMoveModuleMembersProcessor method performRefactoring.
@Override
protected void performRefactoring(@NotNull final UsageInfo[] usages) {
final MultiMap<PsiElement, UsageInfo> usagesByElement = MultiMap.create();
for (UsageInfo usage : usages) {
usagesByElement.putValue(((MyUsageInfo) usage).myMovedElement, usage);
}
CommandProcessor.getInstance().executeCommand(myElements[0].getProject(), new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
final PyFile destination = PyUtil.getOrCreateFile(myDestination, myProject);
CommonRefactoringUtil.checkReadOnlyStatus(myProject, destination);
for (final PsiNamedElement e : myElements) {
// TODO: Check for resulting circular imports
CommonRefactoringUtil.checkReadOnlyStatus(myProject, e);
assert e instanceof PyClass || e instanceof PyFunction || e instanceof PyTargetExpression;
final String name = e.getName();
if (name == null) {
continue;
}
if (e instanceof PyClass && destination.findTopLevelClass(name) != null) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.error.destination.file.contains.class.$0", name));
}
if (e instanceof PyFunction && destination.findTopLevelFunction(name) != null) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.error.destination.file.contains.function.$0", name));
}
if (e instanceof PyTargetExpression && destination.findTopLevelAttribute(name) != null) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.error.destination.file.contains.global.variable.$0", name));
}
final Collection<UsageInfo> usageInfos = usagesByElement.get(e);
final boolean usedFromOutside = ContainerUtil.exists(usageInfos, new Condition<UsageInfo>() {
@Override
public boolean value(UsageInfo usageInfo) {
final PsiElement element = usageInfo.getElement();
return element != null && !PsiTreeUtil.isAncestor(e, element, false);
}
});
if (usedFromOutside) {
PyMoveRefactoringUtil.checkValidImportableFile(e, destination.getVirtualFile());
}
new PyMoveSymbolProcessor(e, destination, usageInfos, myElements).moveElement();
}
}
});
}
}, REFACTORING_NAME, null);
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class PyMoveSymbolDelegate method doMove.
public void doMove(@NotNull Project project, @NotNull List<PyElement> elements) {
final PsiElement firstElement = elements.get(0);
final String initialPath = StringUtil.notNullize(PyPsiUtils.getContainingFilePath(firstElement));
final BaseRefactoringProcessor processor;
if (isMovableLocalFunctionOrMethod(firstElement)) {
final PyFunction function = (PyFunction) firstElement;
final PyMakeFunctionTopLevelDialog dialog = new PyMakeFunctionTopLevelDialog(project, function, initialPath, initialPath);
if (!dialog.showAndGet()) {
return;
}
if (function.getContainingClass() != null) {
processor = new PyMakeMethodTopLevelProcessor(function, dialog.getTargetPath());
} else {
processor = new PyMakeLocalFunctionTopLevelProcessor(function, dialog.getTargetPath());
}
processor.setPreviewUsages(dialog.isPreviewUsages());
} else {
final List<PsiNamedElement> initialElements = Lists.newArrayList();
for (PsiElement element : elements) {
final PsiNamedElement e = PyMoveModuleMembersHelper.extractNamedElement(element);
if (e == null) {
return;
}
initialElements.add(e);
}
final PyMoveModuleMembersDialog dialog = new PyMoveModuleMembersDialog(project, initialElements, initialPath, initialPath);
if (!dialog.showAndGet()) {
return;
}
final PsiNamedElement[] selectedElements = ContainerUtil.findAllAsArray(dialog.getSelectedTopLevelSymbols(), PsiNamedElement.class);
processor = new PyMoveModuleMembersProcessor(selectedElements, dialog.getTargetPath());
processor.setPreviewUsages(dialog.isPreviewUsages());
}
try {
processor.run();
} catch (IncorrectOperationException e) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
throw e;
}
CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(), null, project);
}
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class XmlGtTypedHandler method beforeCharTyped.
@Override
public Result beforeCharTyped(final char c, final Project project, Editor editor, PsiFile editedFile, final FileType fileType) {
final WebEditorOptions webEditorOptions = WebEditorOptions.getInstance();
if (c == '>' && webEditorOptions != null && webEditorOptions.isAutomaticallyInsertClosingTag() && fileContainsXmlLanguage(editedFile)) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
FileViewProvider provider = editedFile.getViewProvider();
int offset = editor.getCaretModel().getOffset();
PsiElement element, elementAtCaret = null;
if (offset < editor.getDocument().getTextLength()) {
elementAtCaret = element = provider.findElementAt(offset, XMLLanguage.class);
if (element == null && offset > 0) {
// seems like a template language
// <xml_code><caret><outer_element>
elementAtCaret = element = provider.findElementAt(offset - 1, XMLLanguage.class);
}
if (!(element instanceof PsiWhiteSpace)) {
boolean nonAcceptableDelimiter = true;
if (element instanceof XmlToken) {
IElementType tokenType = ((XmlToken) element).getTokenType();
if (tokenType == XmlTokenType.XML_START_TAG_START || tokenType == XmlTokenType.XML_END_TAG_START) {
if (offset > 0) {
PsiElement previousElement = provider.findElementAt(offset - 1, XMLLanguage.class);
if (previousElement instanceof XmlToken) {
tokenType = ((XmlToken) previousElement).getTokenType();
element = previousElement;
nonAcceptableDelimiter = false;
}
}
} else if (tokenType == XmlTokenType.XML_NAME || tokenType == XmlTokenType.XML_TAG_NAME) {
if (element.getNextSibling() instanceof PsiErrorElement) {
nonAcceptableDelimiter = false;
}
}
if (tokenType == XmlTokenType.XML_TAG_END || tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END && element.getTextOffset() == offset - 1) {
EditorModificationUtil.moveCaretRelatively(editor, 1);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
return Result.STOP;
}
}
if (nonAcceptableDelimiter)
return Result.CONTINUE;
} else {
// check if right after empty end
PsiElement previousElement = provider.findElementAt(offset - 1, XMLLanguage.class);
if (previousElement instanceof XmlToken) {
final IElementType tokenType = ((XmlToken) previousElement).getTokenType();
if (tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END) {
return Result.STOP;
}
}
}
PsiElement parent = element.getParent();
if (parent instanceof XmlText) {
final String text = parent.getText();
// check /
final int index = offset - parent.getTextOffset() - 1;
if (index >= 0 && text.charAt(index) == '/') {
// already seen /
return Result.CONTINUE;
}
element = parent.getPrevSibling();
} else if (parent instanceof XmlTag && !(element.getPrevSibling() instanceof XmlTag) && !(element.getPrevSibling() instanceof OuterLanguageElement)) {
element = parent;
} else if (parent instanceof XmlAttributeValue) {
element = parent;
}
} else {
element = provider.findElementAt(editor.getDocument().getTextLength() - 1, XMLLanguage.class);
if (element == null)
return Result.CONTINUE;
element = element.getParent();
}
if (offset > 0 && offset <= editor.getDocument().getTextLength()) {
if (editor.getDocument().getCharsSequence().charAt(offset - 1) == '/') {
// Some languages (e.g. GSP) allow character '/' in tag name.
return Result.CONTINUE;
}
}
if (element instanceof XmlAttributeValue) {
element = element.getParent().getParent();
}
while (element instanceof PsiWhiteSpace || element instanceof OuterLanguageElement) element = element.getPrevSibling();
if (element instanceof XmlDocument) {
// hack for closing tags in RHTML
element = element.getLastChild();
}
if (element == null)
return Result.CONTINUE;
if (!(element instanceof XmlTag)) {
if (element instanceof XmlTokenImpl && element.getPrevSibling() != null && element.getPrevSibling().getText().equals("<")) {
// tag is started and there is another text in the end
EditorModificationUtil.insertStringAtCaret(editor, "</" + element.getText() + ">", false, 0);
}
return Result.CONTINUE;
}
XmlTag tag = (XmlTag) element;
if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_TAG_END) != null)
return Result.CONTINUE;
if (XmlUtil.getTokenOfType(tag, XmlTokenType.XML_EMPTY_ELEMENT_END) != null)
return Result.CONTINUE;
final XmlToken startToken = XmlUtil.getTokenOfType(tag, XmlTokenType.XML_START_TAG_START);
if (startToken == null || !startToken.getText().equals("<"))
return Result.CONTINUE;
String name = tag.getName();
if (elementAtCaret instanceof XmlToken && (((XmlToken) elementAtCaret).getTokenType() == XmlTokenType.XML_NAME || ((XmlToken) elementAtCaret).getTokenType() == XmlTokenType.XML_TAG_NAME)) {
name = name.substring(0, offset - elementAtCaret.getTextOffset());
}
if (tag instanceof HtmlTag && HtmlUtil.isSingleHtmlTag(name))
return Result.CONTINUE;
if (name.isEmpty())
return Result.CONTINUE;
int tagOffset = tag.getTextRange().getStartOffset();
final XmlToken nameToken = XmlUtil.getTokenOfType(tag, XmlTokenType.XML_NAME);
if (nameToken != null && nameToken.getTextRange().getStartOffset() > offset)
return Result.CONTINUE;
HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(tagOffset);
if (BraceMatchingUtil.matchBrace(editor.getDocument().getCharsSequence(), editedFile.getFileType(), iterator, true, true)) {
PsiElement parent = tag.getParent();
boolean hasBalance = true;
loop: while (parent instanceof XmlTag) {
if (name.equals(((XmlTag) parent).getName())) {
hasBalance = false;
ASTNode astNode = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(parent.getNode());
if (astNode == null) {
hasBalance = true;
break;
}
for (PsiElement el = parent.getNextSibling(); el != null; el = el.getNextSibling()) {
if (el instanceof PsiErrorElement && el.getText().startsWith("</" + name)) {
hasBalance = true;
break loop;
}
}
}
parent = parent.getParent();
}
if (hasBalance)
return Result.CONTINUE;
}
Collection<TextRange> cdataReformatRanges = null;
final XmlElementDescriptor descriptor = tag.getDescriptor();
EditorModificationUtil.insertStringAtCaret(editor, "</" + name + ">", false, 0);
if (descriptor instanceof XmlElementDescriptorWithCDataContent) {
final XmlElementDescriptorWithCDataContent cDataContainer = (XmlElementDescriptorWithCDataContent) descriptor;
cdataReformatRanges = ContainerUtil.newSmartList();
if (cDataContainer.requiresCdataBracesInContext(tag)) {
@NonNls final String cDataStart = "><![CDATA[";
final String inserted = cDataStart + "\n]]>";
EditorModificationUtil.insertStringAtCaret(editor, inserted, false, cDataStart.length());
int caretOffset = editor.getCaretModel().getOffset();
if (caretOffset >= cDataStart.length()) {
cdataReformatRanges.add(TextRange.from(caretOffset - cDataStart.length(), inserted.length() + 1));
}
}
}
if (cdataReformatRanges != null && !cdataReformatRanges.isEmpty()) {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
try {
CodeStyleManager.getInstance(project).reformatText(file, cdataReformatRanges);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
return cdataReformatRanges != null && !cdataReformatRanges.isEmpty() ? Result.STOP : Result.CONTINUE;
}
return Result.CONTINUE;
}
Aggregations