use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.
the class PyCommentBreakerEnterProcessor method doEnter.
public boolean doEnter(Editor editor, PsiElement psiElement, boolean isModified) {
if (isModified) {
return false;
}
final CaretModel caretModel = editor.getCaretModel();
PsiElement atCaret = psiElement.getContainingFile().findElementAt(caretModel.getOffset());
if (atCaret instanceof PsiWhiteSpace) {
atCaret = atCaret.getPrevSibling();
}
final PsiElement comment = PsiTreeUtil.getParentOfType(atCaret, PsiComment.class, false);
if (comment != null) {
SmartEnterUtil.plainEnter(editor);
editor.getDocument().insertString(caretModel.getOffset(), "# ");
caretModel.moveToOffset(caretModel.getOffset() + 2);
return true;
}
return false;
}
use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.
the class IntroduceHandler method performAction.
public void performAction(IntroduceOperation operation) {
final PsiFile file = operation.getFile();
if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
return;
}
final Editor editor = operation.getEditor();
if (editor.getSettings().isVariableInplaceRenameEnabled()) {
final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
if (templateState != null && !templateState.isFinished()) {
return;
}
}
PsiElement element1 = null;
PsiElement element2 = null;
final SelectionModel selectionModel = editor.getSelectionModel();
boolean singleElementSelection = false;
if (selectionModel.hasSelection()) {
element1 = file.findElementAt(selectionModel.getSelectionStart());
element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
if (element1 instanceof PsiWhiteSpace) {
int startOffset = element1.getTextRange().getEndOffset();
element1 = file.findElementAt(startOffset);
}
if (element2 instanceof PsiWhiteSpace) {
int endOffset = element2.getTextRange().getStartOffset();
element2 = file.findElementAt(endOffset - 1);
}
if (element1 == element2) {
singleElementSelection = true;
}
} else {
if (smartIntroduce(operation)) {
return;
}
final CaretModel caretModel = editor.getCaretModel();
final Document document = editor.getDocument();
int lineNumber = document.getLineNumber(caretModel.getOffset());
if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
}
}
final Project project = operation.getProject();
if (element1 == null || element2 == null) {
showCannotPerformError(project, editor);
return;
}
element1 = PyRefactoringUtil.getSelectedExpression(project, file, element1, element2);
final PyComprehensionElement comprehension = PsiTreeUtil.getParentOfType(element1, PyComprehensionElement.class, true);
if (element1 == null || comprehension != null) {
showCannotPerformError(project, editor);
return;
}
if (singleElementSelection && element1 instanceof PyStringLiteralExpression) {
final PyStringLiteralExpression literal = (PyStringLiteralExpression) element1;
// Currently introduce for substrings of a multi-part string literals is not supported
if (literal.getStringNodes().size() > 1) {
showCannotPerformError(project, editor);
return;
}
final int offset = element1.getTextOffset();
final TextRange selectionRange = TextRange.create(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
final TextRange elementRange = element1.getTextRange();
if (!elementRange.equals(selectionRange) && elementRange.contains(selectionRange)) {
final TextRange innerRange = literal.getStringValueTextRange();
final TextRange intersection = selectionRange.shiftRight(-offset).intersection(innerRange);
final TextRange finalRange = intersection != null ? intersection : selectionRange;
final String text = literal.getText();
if (getFormatValueExpression(literal) != null && breaksStringFormatting(text, finalRange) || getNewStyleFormatValueExpression(literal) != null && breaksNewStyleStringFormatting(text, finalRange) || breaksStringEscaping(text, finalRange)) {
showCannotPerformError(project, editor);
return;
}
element1.putUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE, Pair.create(element1, finalRange));
}
}
if (!checkIntroduceContext(file, editor, element1)) {
return;
}
operation.setElement(element1);
performActionOnElement(operation);
}
use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.
the class PyIntroduceFieldHandler method isTestClass.
private static boolean isTestClass(PsiFile file, Editor editor) {
PsiElement element1 = null;
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
element1 = file.findElementAt(selectionModel.getSelectionStart());
} else {
final CaretModel caretModel = editor.getCaretModel();
final Document document = editor.getDocument();
int lineNumber = document.getLineNumber(caretModel.getOffset());
if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
}
}
if (element1 != null) {
final PyClass clazz = PyUtil.getContainingClassOrSelf(element1);
if (clazz != null && PythonUnitTestUtil.isTestCaseClass(clazz, null))
return true;
}
return false;
}
use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.
the class GroovyInsertHandler method handleInsert.
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
@NonNls Object obj = item.getObject();
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (obj instanceof GroovyResolveResult) {
substitutor = ((GroovyResolveResult) obj).getSubstitutor();
obj = ((GroovyResolveResult) obj).getElement();
}
if (obj instanceof PsiMethod) {
final PsiMethod method = (PsiMethod) obj;
PsiParameter[] parameters = method.getParameterList().getParameters();
Editor editor = context.getEditor();
Document document = editor.getDocument();
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
handleOverwrite(editor.getCaretModel().getOffset(), document);
}
CaretModel caretModel = editor.getCaretModel();
int offset = context.getTailOffset();
PsiFile file = context.getFile();
PsiElement elementAt = file.findElementAt(context.getStartOffset());
assert elementAt != null;
PsiElement parent = elementAt.getParent();
if (parent instanceof GrReferenceExpression && ((GrReferenceExpression) parent).getDotTokenType() == GroovyTokenTypes.mMEMBER_POINTER) {
return;
}
CharSequence charsSequence = document.getCharsSequence();
if (isAnnotationNameValuePair(obj, parent)) {
int endOffset = offset;
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
endOffset = CharArrayUtil.shiftForward(charsSequence, offset, " \t");
if (charsSequence.length() > endOffset && charsSequence.charAt(endOffset) == '=') {
endOffset++;
endOffset = CharArrayUtil.shiftForward(charsSequence, endOffset, " \t");
}
}
document.replaceString(offset, endOffset, " = ");
caretModel.moveToOffset(offset + 3);
return;
}
if (PsiTreeUtil.getParentOfType(elementAt, GrImportStatement.class) != null)
return;
if (parameters.length == 1) {
if ((context.getCompletionChar() != '(' && context.getCompletionChar() != ' ') && TypesUtil.isClassType(parameters[0].getType(), GroovyCommonClassNames.GROOVY_LANG_CLOSURE)) {
int afterBrace;
final int nonWs = CharArrayUtil.shiftForward(charsSequence, offset, " \t");
if (nonWs < document.getTextLength() && charsSequence.charAt(nonWs) == '{') {
afterBrace = nonWs + 1;
} else {
if (isSpaceBeforeClosure(file)) {
document.insertString(offset, " ");
offset++;
}
if (ClosureCompleter.runClosureCompletion(context, method, substitutor, document, offset, parent))
return;
if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
//smart enter invoked
document.insertString(offset, "{\n}");
//position caret before '{' for smart enter
afterBrace = offset + 1;
context.setTailOffset(afterBrace);
} else {
document.insertString(offset, "{}");
afterBrace = offset + 1;
}
}
caretModel.moveToOffset(afterBrace);
return;
}
}
context.commitDocument();
if (context.getCompletionChar() == ' ' && MethodParenthesesHandler.hasParams(item, context.getElements(), true, method)) {
return;
}
CommonCodeStyleSettings settings = context.getCodeStyleSettings();
ParenthesesInsertHandler.getInstance(MethodParenthesesHandler.hasParams(item, context.getElements(), true, method), settings.SPACE_BEFORE_METHOD_CALL_PARENTHESES, settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES, true, true).handleInsert(context, item);
AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(editor, method);
return;
}
if (obj instanceof PsiClass) {
final PsiClass clazz = (PsiClass) obj;
Editor editor = context.getEditor();
Document document = editor.getDocument();
PsiFile file = PsiDocumentManager.getInstance(clazz.getProject()).getPsiFile(document);
assert file != null;
PsiElement elementAt = file.findElementAt(context.getStartOffset());
assert elementAt != null;
CaretModel caretModel = editor.getCaretModel();
int offset = context.getStartOffset() + elementAt.getTextLength();
final String text = document.getText();
final PsiElement parent = elementAt.getParent();
if (parent instanceof GrCodeReferenceElement && parent.getParent() instanceof GrNewExpression && (offset == text.length() || !text.substring(offset).trim().startsWith("("))) {
document.insertString(offset, "()");
if (GroovyCompletionUtil.hasConstructorParameters(clazz, parent)) {
caretModel.moveToOffset(offset + 1);
return;
}
caretModel.moveToOffset(offset + 2);
return;
}
}
if (context.getCompletionChar() == '=') {
context.setAddCompletionChar(false);
TailType.EQ.processTail(context.getEditor(), context.getTailOffset());
return;
}
if (obj instanceof PsiPackage) {
AutoPopupController.getInstance(context.getProject()).scheduleAutoPopup(context.getEditor());
}
}
use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.
the class ClosureCompleter method runTemplate.
public static void runTemplate(List<ClosureParameterInfo> parameters, GrClosableBlock block, PsiSubstitutor substitutor, PsiMethod method, final Project project, final Editor editor) {
if (method instanceof ClsMethodImpl)
method = ((ClsMethodImpl) method).getSourceMirrorMethod();
assert block.getArrow() == null;
if (parameters.isEmpty())
return;
StringBuilder buffer = new StringBuilder();
buffer.append("{");
List<PsiType> paramTypes = ContainerUtil.newArrayList();
for (ClosureParameterInfo parameter : parameters) {
final String type = parameter.getType();
final String name = parameter.getName();
if (type != null) {
final PsiType fromText = JavaPsiFacade.getElementFactory(project).createTypeFromText(type, method);
final PsiType substituted = substitutor.substitute(fromText);
paramTypes.add(substituted);
buffer.append(substituted.getCanonicalText()).append(" ");
} else {
buffer.append("def ");
}
buffer.append(name);
buffer.append(", ");
}
buffer.replace(buffer.length() - 2, buffer.length(), " ->}");
final Document document = editor.getDocument();
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
assert file != null;
final GrClosableBlock closure = GroovyPsiElementFactory.getInstance(project).createClosureFromText(buffer.toString());
final GrClosableBlock templateClosure = (GrClosableBlock) block.replaceWithExpression(closure, false);
final TemplateBuilderImpl builder = new TemplateBuilderImpl(templateClosure);
int i = 0;
for (GrParameter p : templateClosure.getParameters()) {
final GrTypeElement typeElement = p.getTypeElementGroovy();
final PsiElement nameIdentifier = p.getNameIdentifierGroovy();
if (typeElement != null) {
final TypeConstraint[] typeConstraints = { SupertypeConstraint.create(paramTypes.get(i++)) };
final ChooseTypeExpression expression = new ChooseTypeExpression(typeConstraints, PsiManager.getInstance(project), nameIdentifier.getResolveScope());
builder.replaceElement(typeElement, expression);
} else {
final ChooseTypeExpression expression = new ChooseTypeExpression(TypeConstraint.EMPTY_ARRAY, PsiManager.getInstance(project), nameIdentifier.getResolveScope());
builder.replaceElement(p.getModifierList(), expression);
}
builder.replaceElement(nameIdentifier, new ParameterNameExpression(nameIdentifier.getText()));
}
final GrClosableBlock afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(templateClosure);
final Template template = builder.buildTemplate();
TextRange range = afterPostprocess.getTextRange();
document.deleteString(range.getStartOffset(), range.getEndOffset());
TemplateEditingListener templateListener = new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
ApplicationManager.getApplication().runWriteAction(() -> {
PsiDocumentManager.getInstance(project).commitDocument(document);
final CaretModel caretModel = editor.getCaretModel();
final int offset = caretModel.getOffset();
GrClosableBlock block1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, GrClosableBlock.class, false);
if (block1 != null) {
final PsiElement arrow = block1.getArrow();
if (arrow != null) {
caretModel.moveToOffset(arrow.getTextRange().getEndOffset());
}
// fix space before closure lbrace
final TextRange range1 = block1.getTextRange();
CodeStyleManager.getInstance(project).reformatRange(block1.getParent(), range1.getStartOffset() - 1, range1.getEndOffset(), true);
}
});
}
};
TemplateManager manager = TemplateManager.getInstance(project);
manager.startTemplate(editor, template, templateListener);
}
Aggregations