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 static List<PsiGenerationInfo<PsiMethod>> overrideOrImplement(PsiClass psiClass, @NotNull PsiMethod baseMethod) throws IncorrectOperationException { FileEditorManager fileEditorManager = FileEditorManager.getInstance(baseMethod.getProject()); List<PsiGenerationInfo<PsiMethod>> results = new ArrayList<PsiGenerationInfo<PsiMethod>>(); try { List<PsiGenerationInfo<PsiMethod>> prototypes = convert2GenerationInfos(overrideOrImplementMethod(psiClass, baseMethod, false)); if (prototypes.isEmpty()) return null; PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseMethod.getContainingClass(), psiClass, PsiSubstitutor.EMPTY); PsiElement anchor = getDefaultAnchorToOverrideOrImplement(psiClass, baseMethod, substitutor); results = GenerateMembersUtil.insertMembersBeforeAnchor(psiClass, anchor, prototypes); return results; } finally { PsiFile psiFile = psiClass.getContainingFile(); Editor editor = fileEditorManager.openTextEditor(new OpenFileDescriptor(psiFile.getProject(), psiFile.getVirtualFile()), true); if (editor != null && !results.isEmpty()) { results.get(0).positionCaret(editor, true); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } } }
@Override public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return; PsiMethod method = canInsertSuper(project, editor, file); try { PsiMethod template = (PsiMethod)method.copy(); OverrideImplementUtil.setupMethodBody(template, method, method.getContainingClass()); PsiStatement superCall = template.getBody().getStatements()[0]; PsiCodeBlock body = method.getBody(); PsiElement toGo; if (body.getLBrace() == null) { toGo = body.addBefore(superCall, null); } else { toGo = body.addAfter(superCall, body.getLBrace()); } toGo = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(toGo); editor.getCaretModel().moveToOffset(toGo.getTextOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } catch (IncorrectOperationException e) { LOG.error(e); } }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (!FileModificationService.getInstance().prepareFileForWrite(myVariable.getContainingFile())) return; String initializerText = suggestInitializer(); PsiElementFactory factory = JavaPsiFacade.getInstance(myVariable.getProject()).getElementFactory(); PsiExpression initializer = factory.createExpressionFromText(initializerText, myVariable); if (myVariable instanceof PsiLocalVariable) { ((PsiLocalVariable)myVariable).setInitializer(initializer); } else if (myVariable instanceof PsiField) { ((PsiField)myVariable).setInitializer(initializer); } else { LOG.error("Unknown variable type: "+myVariable); } PsiVariable var = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(myVariable); TextRange range = var.getInitializer().getTextRange(); int offset = range.getStartOffset(); editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); }
private static void doOrSplit(PsiIfStatement ifStatement, PsiPolyadicExpression expression, PsiJavaToken token, Editor editor) throws IncorrectOperationException { PsiExpression lOperand = getLOperands(expression, token); PsiExpression rOperand = getROperands(expression, token); PsiIfStatement secondIf = (PsiIfStatement)ifStatement.copy(); PsiStatement elseBranch = ifStatement.getElseBranch(); if (elseBranch != null) { elseBranch = (PsiStatement)elseBranch.copy(); } ifStatement.getCondition().replace(RefactoringUtil.unparenthesizeExpression(lOperand)); secondIf.getCondition().replace(RefactoringUtil.unparenthesizeExpression(rOperand)); ifStatement.setElseBranch(secondIf); if (elseBranch != null) { secondIf.setElseBranch(elseBranch); } int offset1 = ifStatement.getCondition().getTextOffset(); editor.getCaretModel().moveToOffset(offset1); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); int offset = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.class")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_SUPERCLASS); return; } if (element instanceof PsiClass) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.push.members.from")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN); return; } if (element instanceof PsiClass || element instanceof PsiField || element instanceof PsiMethod) { if (element instanceof JspClass) { RefactoringMessageUtil.showNotSupportedForJspClassesError(project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN); return; } invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (element == null) { element = file.findElementAt(editor.getCaretModel().getOffset()); } if (element == null) return; if (element instanceof PsiIdentifier) element = element.getParent(); if(!(element instanceof PsiMethod)) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.method")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.CONVERT_TO_INSTANCE_METHOD); return; } if(LOG.isDebugEnabled()) { LOG.debug("MakeMethodStaticHandler invoked"); } invoke(project, new PsiElement[]{element}, dataContext); }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.class")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.TURN_REFS_TO_SUPER); return; } if (element instanceof PsiClass && !(element instanceof PsiAnonymousClass)) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.class")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_INTERFACE); return; } if (element instanceof PsiClass && !(element instanceof PsiAnonymousClass)) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (element == null) { element = file.findElementAt(editor.getCaretModel().getOffset()); } if (element == null) return; if (element instanceof PsiIdentifier) element = element.getParent(); if (!(element instanceof PsiMethod)) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.method")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MOVE_INSTANCE_METHOD); return; } if (LOG.isDebugEnabled()) { LOG.debug("Move Instance Method invoked"); } invoke(project, new PsiElement[]{element}, dataContext); }
public void invoke(@NotNull final Project project, Editor editor, final PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return; final int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final PsiAnonymousClass anonymousClass = findAnonymousClass(file, offset); if (anonymousClass == null) { showErrorMessage(editor, RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.anonymous"))); return; } final PsiElement parent = anonymousClass.getParent(); if (parent instanceof PsiEnumConstant) { showErrorMessage(editor, RefactoringBundle.getCannotRefactorMessage("Enum constant can't be converted to inner class")); return; } invoke(project, editor, anonymousClass); }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (element == null) { element = file.findElementAt(editor.getCaretModel().getOffset()); } if (element == null) return; if (element instanceof PsiIdentifier) element = element.getParent(); if(!(element instanceof PsiTypeParameterListOwner)) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.method.or.class.name")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MAKE_METHOD_STATIC); return; } if(LOG.isDebugEnabled()) { LOG.debug("MakeStaticHandler invoked"); } invoke(project, new PsiElement[]{element}, dataContext); }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final int offset = TargetElementUtil.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset()); final PsiElement element = file.findElementAt(offset); PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class); while (typeElement != null) { final PsiElement parent = typeElement.getParent(); if (parent instanceof PsiVariable || (parent instanceof PsiMember && !(parent instanceof PsiClass)) || isClassArgument(parent)) { invoke(project, parent, null, editor); return; } typeElement = PsiTreeUtil.getParentOfType(parent, PsiTypeElement.class, false); } CommonRefactoringUtil.showErrorHint(project, editor, "The caret should be positioned on type of field, variable, method or method parameter to be refactored", REFACTORING_NAME, "refactoring.migrateType"); }
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); int offset = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.class")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INHERITANCE_TO_DELEGATION); return; } if (element instanceof PsiClass && !(element instanceof PsiAnonymousClass)) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle .getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.pull.members.from")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PULL_UP); return; } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return; if (element instanceof PsiClass || element instanceof PsiField || element instanceof PsiMethod) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
@Override public void actionPerformed(@NotNull AnActionEvent e) { Side currentSide = getCurrentSide(); Side targetSide = currentSide.other(); EditorEx currentEditor = getEditor(currentSide); EditorEx targetEditor = getEditor(targetSide); if (myScrollToPosition) { LogicalPosition position = transferPosition(currentSide, currentEditor.getCaretModel().getLogicalPosition()); targetEditor.getCaretModel().moveToLogicalPosition(position); } setCurrentSide(targetSide); myContext.requestFocus(); currentEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); }
@Override public void execute(Editor editor, DataContext dataContext) { editor.getCaretModel().removeSecondaryCarets(); editor.getCaretModel().moveToOffset(0); editor.getSelectionModel().removeSelection(); ScrollingModel scrollingModel = editor.getScrollingModel(); scrollingModel.disableAnimation(); scrollingModel.scrollToCaret(ScrollType.RELATIVE); scrollingModel.enableAnimation(); Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { IdeDocumentHistory instance = IdeDocumentHistory.getInstance(project); if (instance != null) { instance.includeCurrentCommandAsNavigation(); } } }
@Override public void execute(Editor editor, DataContext dataContext) { editor.getCaretModel().removeSecondaryCarets(); int offset = editor.getDocument().getTextLength(); if (editor instanceof EditorImpl && ((EditorImpl)editor).myUseNewRendering) { editor.getCaretModel().moveToLogicalPosition(editor.offsetToLogicalPosition(offset).leanForward(true)); } else { editor.getCaretModel().moveToOffset(offset); } editor.getSelectionModel().removeSelection(); ScrollingModel scrollingModel = editor.getScrollingModel(); scrollingModel.disableAnimation(); scrollingModel.scrollToCaret(ScrollType.CENTER); scrollingModel.enableAnimation(); Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { IdeDocumentHistory instance = IdeDocumentHistory.getInstance(project); if (instance != null) { instance.includeCurrentCommandAsNavigation(); } } }
public void show(final @NotNull XSourcePosition position, final boolean notTopFrame, @Nullable final GutterIconRenderer gutterIconRenderer) { updateRequested.set(false); AppUIUtil.invokeLaterIfProjectAlive(myProject, new Runnable() { @Override public void run() { updateRequested.set(false); mySourcePosition = position; clearDescriptor(); myOpenFileDescriptor = XSourcePositionImpl.createOpenFileDescriptor(myProject, position); if (!XDebuggerSettingsManager.getInstanceImpl().getGeneralSettings().isScrollToCenter()) { myOpenFileDescriptor.setScrollType(notTopFrame ? ScrollType.CENTER : ScrollType.MAKE_VISIBLE); } //see IDEA-125645 and IDEA-63459 //myOpenFileDescriptor.setUseCurrentWindow(true); myGutterIconRenderer = gutterIconRenderer; myNotTopFrame = notTopFrame; doShow(true); } }); }
public void actionPerformedImpl(final Project project, final Editor hostEditor) { CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { MultiCaretCodeInsightActionHandler handler = getHandler(); try { iterateOverCarets(project, hostEditor, handler); } finally { handler.postInvoke(); } } }); } }, getCommandName(), DocCommandGroupId.noneGroupId(hostEditor.getDocument())); hostEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final PsiElement position = file.findElementAt(offset); PsiElement element = position; while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle .getCannotRefactorMessage(getInvalidPositionMessage()); CommonRefactoringUtil.showErrorHint(project, editor, message, getTitle(), getHelpId()); return; } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return; if (acceptsElement(element)) { invoke(project, new PsiElement[]{position}, dataContext); return; } element = element.getParent(); } }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { PsiElement element = getElement(dataContext); if (element == null) { element = BaseRefactoringAction.getElementAtCaret(editor, file); } if (ApplicationManager.getApplication().isUnitTestMode()) { final String newName = DEFAULT_NAME.getData(dataContext); if (newName != null) { rename(element, project, element, editor, newName); return; } } editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final PsiElement nameSuggestionContext = InjectedLanguageUtil.findElementAtNoCommit(file, editor.getCaretModel().getOffset()); invoke(element, project, nameSuggestionContext, editor); }
@Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, final DataContext dataContext) { PsiElement element = PsiElementRenameHandler.getElement(dataContext); if (element == null) { if (LookupManager.getActiveLookup(editor) != null) { final PsiElement elementUnderCaret = file.findElementAt(editor.getCaretModel().getOffset()); if (elementUnderCaret != null) { final PsiElement parent = elementUnderCaret.getParent(); if (parent instanceof PsiReference) { element = ((PsiReference)parent).resolve(); } else { element = PsiTreeUtil.getParentOfType(elementUnderCaret, PsiNamedElement.class); } } if (element == null) return; } else { return; } } editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); if (checkAvailable(element, editor, dataContext)) { doRename(element, editor, dataContext); } }
/** * 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); }
@Override public void invoke(@NotNull final Project project, Editor editor, PsiFile file, DataContext dataContext) { editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); if (element == null) { element = BaseRefactoringAction.getElementAtCaret(editor, file); } if (element != null) { for(InlineActionHandler handler: Extensions.getExtensions(InlineActionHandler.EP_NAME)) { if (handler.canInlineElementInEditor(element, editor)) { handler.inlineElement(project, editor, element); return; } } if (invokeInliner(editor, element)) return; String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.method.or.local.name")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, null); } }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.class")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_INTERFACE); return; } if (element instanceof GrTypeDefinition && !(element instanceof GrAnonymousClassDefinition)) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
@Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, @Nullable DataContext dataContext) { editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); final SelectionModel model = editor.getSelectionModel(); if (model.hasSelection()) { invokeImpl(project, editor, file, model.getSelectionStart(), model.getSelectionEnd()); } else { final List<GrExpression> expressions = GrIntroduceHandlerBase.collectExpressions(file, editor, editor.getCaretModel().getOffset(), true); final Pass<GrExpression> callback = new Callback(project, editor, file); if (expressions.size() == 1) { callback.pass(expressions.get(0)); } else if (expressions.isEmpty()) { model.selectLineAtCaret(); invokeImpl(project, editor, file, model.getSelectionStart(), model.getSelectionEnd()); } else { IntroduceTargetChooser.showChooser(editor, expressions, callback, GrIntroduceHandlerBase.GR_EXPRESSION_RENDERER); } } }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { int offset = editor.getCaretModel().getOffset(); editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); PsiElement element = file.findElementAt(offset); while (true) { if (element == null || element instanceof PsiFile) { String message = RefactoringBundle .getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.pull.members.from")); CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PULL_UP); return; } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return; if (element instanceof GrTypeDefinition || element instanceof GrField || element instanceof GrMethod) { invoke(project, new PsiElement[]{element}, dataContext); return; } element = element.getParent(); } }
public static void setLine(Editor editor, int line, int column) { if (editor != null) { try { int startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, column)); editor.getCaretModel().moveToOffset(startOffset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); editor.getSelectionModel().setSelection(startOffset, startOffset); } catch (Exception e) { // do nothing } } }
public static void selectFirstAnswerPlaceholder(@Nullable final StudyEditor studyEditor, @NotNull final Project project) { if (studyEditor == null) return; final Editor editor = studyEditor.getEditor(); IdeFocusManager.getInstance(project).requestFocus(editor.getContentComponent(), true); final List<AnswerPlaceholder> placeholders = studyEditor.getTaskFile().getActivePlaceholders(); if (placeholders.isEmpty()) return; final AnswerPlaceholder placeholder = placeholders.get(0); Pair<Integer, Integer> offsets = getPlaceholderOffsets(placeholder, editor.getDocument()); editor.getSelectionModel().setSelection(offsets.first, offsets.second); editor.getCaretModel().moveToOffset(offsets.first); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); }
@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()); }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); PsiStatement anchorStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); LOG.assertTrue(anchorStatement != null); Editor editor = PsiUtilBase.findEditor(element); if (editor == null) return; PsiFile file = element.getContainingFile(); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); Document document = documentManager.getDocument(file); if (document == null || !FileModificationService.getInstance().prepareFileForWrite(file)) return; PsiElement[] elements = {anchorStatement}; PsiElement prev = PsiTreeUtil.skipSiblingsBackward(anchorStatement, PsiWhiteSpace.class); if (prev instanceof PsiComment && JavaSuppressionUtil.getSuppressedInspectionIdsIn(prev) != null) { elements = new PsiElement[]{prev, anchorStatement}; } try { TextRange textRange = new JavaWithIfSurrounder().surroundElements(project, editor, elements); if (textRange == null) return; @NonNls String newText = myText + " != null"; document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(),newText); editor.getCaretModel().moveToOffset(textRange.getEndOffset() + newText.length()); PsiDocumentManager.getInstance(project).commitAllDocuments(); new MergeIfAndIntention().invoke(project, editor, file); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } catch (IncorrectOperationException e) { LOG.error(e); } }
protected static void positionCaretToDeclaration(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement declaration) { final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null && (IJSwingUtilities.hasFocus(editor.getComponent()) || ApplicationManager.getApplication().isUnitTestMode())) { final PsiFile openedFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (openedFile == psiFile) { editor.getCaretModel().moveToOffset(declaration.getTextOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } }
private static LookupElement createSmartCastElement(final CompletionParameters parameters, final boolean overwrite, final PsiType type) { return AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE.applyPolicy(new LookupElementDecorator<PsiTypeLookupItem>( PsiTypeLookupItem.createLookupItem(type, parameters.getPosition())) { @Override public void handleInsert(InsertionContext context) { FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.smarttype.casting"); final Editor editor = context.getEditor(); final Document document = editor.getDocument(); if (overwrite) { document.deleteString(context.getSelectionEndOffset(), context.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET)); } final CommonCodeStyleSettings csSettings = context.getCodeStyleSettings(); final int oldTail = context.getTailOffset(); context.setTailOffset(RParenthTailType.addRParenth(editor, oldTail, csSettings.SPACE_WITHIN_CAST_PARENTHESES)); getDelegate().handleInsert(CompletionUtil.newContext(context, getDelegate(), context.getStartOffset(), oldTail)); PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(); if (csSettings.SPACE_AFTER_TYPE_CAST) { context.setTailOffset(TailType.insertChar(editor, context.getTailOffset(), ' ')); } if (parameters.getCompletionType() == CompletionType.SMART) { editor.getCaretModel().moveToOffset(context.getTailOffset()); } editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } }); }
@Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; final PsiClass myClass = myField.getContainingClass(); if (myClass == null) { return; } if (myClass.getConstructors().length == 0) { createDefaultConstructor(myClass, project, editor, file); } final List<PsiMethod> constructors = choose(filterIfFieldAlreadyAssigned(myField, myClass.getConstructors()), project); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { final List<PsiExpressionStatement> statements = addFieldInitialization(constructors, myField, project); final PsiExpressionStatement highestStatement = getHighestElement(statements); if (highestStatement == null) return; final PsiAssignmentExpression expression = (PsiAssignmentExpression)highestStatement.getExpression(); final PsiElement rightExpression = expression.getRExpression(); final TextRange expressionRange = rightExpression.getTextRange(); editor.getCaretModel().moveToOffset(expressionRange.getStartOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().setSelection(expressionRange.getStartOffset(), expressionRange.getEndOffset()); } }); }
static void selectReturnValueInEditor(final PsiReturnStatement returnStatement, final Editor editor) { TextRange range = returnStatement.getReturnValue().getTextRange(); int offset = range.getStartOffset(); editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().setSelection(range.getEndOffset(), range.getStartOffset()); }
public static void setupEditor(PsiMethod method, final Editor newEditor) { PsiCodeBlock body = method.getBody(); if (body != null) { PsiElement l = PsiTreeUtil.skipSiblingsForward(body.getLBrace(), PsiWhiteSpace.class); PsiElement r = PsiTreeUtil.skipSiblingsBackward(body.getRBrace(), PsiWhiteSpace.class); if (l != null && r != null) { int start = l.getTextRange().getStartOffset(); int end = r.getTextRange().getEndOffset(); newEditor.getCaretModel().moveToOffset(Math.max(start, end)); if (end < start) { newEditor.getCaretModel().moveToOffset(end + 1); CodeStyleManager styleManager = CodeStyleManager.getInstance(method.getProject()); PsiFile containingFile = method.getContainingFile(); final String lineIndent = styleManager.getLineIndent(containingFile, Math.min(start, end)); PsiDocumentManager manager = PsiDocumentManager.getInstance(method.getProject()); manager.doPostponedOperationsAndUnblockDocument(manager.getDocument(containingFile)); EditorModificationUtil.insertStringAtCaret(newEditor, lineIndent); EditorModificationUtil.insertStringAtCaret(newEditor, "\n", false, false); } else { //correct position caret for groovy and java methods final PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(method); info.positionCaret(newEditor, true); } newEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } }
@Override public void handleInsert(InsertionContext context) { myImportFixer.handleInsert(context, this); PsiElement position = context.getFile().findElementAt(context.getStartOffset()); if (position != null) { int genericsStart = context.getTailOffset(); context.getDocument().insertString(genericsStart, JavaCompletionUtil.escapeXmlIfNeeded(context, calcGenerics(position, context))); JavaCompletionUtil.shortenReference(context.getFile(), genericsStart - 1); } int tail = context.getTailOffset(); String braces = StringUtil.repeat("[]", getBracketsCount()); Editor editor = context.getEditor(); if (!braces.isEmpty()) { if (myAddArrayInitializer) { context.getDocument().insertString(tail, braces + "{}"); editor.getCaretModel().moveToOffset(tail + braces.length() + 1); } else { context.getDocument().insertString(tail, braces); editor.getCaretModel().moveToOffset(tail + 1); if (context.getCompletionChar() == '[') { context.setAddCompletionChar(false); } } } else { editor.getCaretModel().moveToOffset(tail); } editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); InsertHandler handler = getInsertHandler(); if (handler != null) { //noinspection unchecked handler.handleInsert(context, this); } }
private static void doAndSplit(PsiIfStatement ifStatement, PsiPolyadicExpression expression, PsiJavaToken token, Editor editor) throws IncorrectOperationException { PsiExpression lOperand = getLOperands(expression, token); PsiExpression rOperand = getROperands(expression, token); PsiManager psiManager = ifStatement.getManager(); PsiIfStatement subIf = (PsiIfStatement)ifStatement.copy(); subIf.getCondition().replace(RefactoringUtil.unparenthesizeExpression(rOperand)); ifStatement.getCondition().replace(RefactoringUtil.unparenthesizeExpression(lOperand)); if (ifStatement.getThenBranch() instanceof PsiBlockStatement) { PsiBlockStatement blockStmt = (PsiBlockStatement)JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createStatementFromText("{}", null); blockStmt = (PsiBlockStatement)CodeStyleManager.getInstance(psiManager.getProject()).reformat(blockStmt); blockStmt = (PsiBlockStatement)ifStatement.getThenBranch().replace(blockStmt); blockStmt.getCodeBlock().add(subIf); } else { ifStatement.getThenBranch().replace(subIf); } int offset1 = ifStatement.getCondition().getTextOffset(); editor.getCaretModel().moveToOffset(offset1); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); }