@Override
  public boolean doEnter(Editor editor, PsiElement psiElement, boolean isModified) {
    PsiCodeBlock block = getControlStatementBlock(editor.getCaretModel().getOffset(), psiElement);
    if (processExistingBlankLine(editor, block, psiElement)) {
      return true;
    }
    EditorActionHandler enterHandler = getEnterHandler(IdeActions.ACTION_EDITOR_START_NEW_LINE);
    if (block != null) {
      PsiElement firstElement = block.getFirstBodyElement();
      if (firstElement == null) {
        firstElement = block.getRBrace();
        // Plain enter processor inserts enter after the end of line, hence, we don't want to use it
        // here because the line ends with
        // the empty braces block. So, we get the following in case of default handler usage:
        //     Before:
        //         if (condition[caret]) {}
        //     After:
        //         if (condition) {}
        //             [caret]
        enterHandler = getEnterHandler(IdeActions.ACTION_EDITOR_ENTER);
      }
      editor
          .getCaretModel()
          .moveToOffset(
              firstElement != null
                  ? firstElement.getTextRange().getStartOffset()
                  : block.getTextRange().getEndOffset());
    }

    enterHandler.execute(editor, ((EditorEx) editor).getDataContext());
    return true;
  }
  protected void moveCaretInsideBracesIfAny(
      @NotNull final Editor editor, @NotNull final PsiFile file)
      throws IncorrectOperationException {
    int caretOffset = editor.getCaretModel().getOffset();
    final CharSequence chars = editor.getDocument().getCharsSequence();

    if (CharArrayUtil.regionMatches(chars, caretOffset, "{}")) {
      caretOffset += 2;
    } else if (CharArrayUtil.regionMatches(chars, caretOffset, "{\n}")) {
      caretOffset += 3;
    }

    caretOffset = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1;

    if (CharArrayUtil.regionMatches(chars, caretOffset - "{}".length(), "{}")
        || CharArrayUtil.regionMatches(chars, caretOffset - "{\n}".length(), "{\n}")) {
      commit(editor);
      final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject());
      final boolean old = settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE;
      settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false;
      PsiElement elt =
          PsiTreeUtil.getParentOfType(file.findElementAt(caretOffset - 1), PsiCodeBlock.class);
      reformat(elt);
      settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = old;
      editor.getCaretModel().moveToOffset(caretOffset - 1);
    }
  }
  protected void doEnter(@NotNull PsiElement atCaret, @NotNull PsiFile file, @NotNull Editor editor)
      throws IncorrectOperationException {
    if (myFirstErrorOffset != Integer.MAX_VALUE) {
      editor.getCaretModel().moveToOffset(myFirstErrorOffset);
      reformat(atCaret);
      return;
    }

    reformat(atCaret);
    commit(editor);

    for (FixEnterProcessor enterProcessor : ourEnterProcessors) {
      if (enterProcessor.doEnter(atCaret, file, editor, isModified(editor))) {
        return;
      }
    }

    if (!isModified(editor)) {
      plainEnter(editor);
    } else {
      if (myFirstErrorOffset == Integer.MAX_VALUE) {
        editor.getCaretModel().moveToOffset(atCaret.getTextRange().getEndOffset());
      } else {
        editor.getCaretModel().moveToOffset(myFirstErrorOffset);
      }
    }
  }
 public void startTemplateWithPrefix(
     final Editor editor,
     final TemplateImpl template,
     final int templateStart,
     @Nullable final PairProcessor<String, String> processor,
     @Nullable final String argument) {
   final int caretOffset = editor.getCaretModel().getOffset();
   final TemplateState templateState = initTemplateState(editor);
   CommandProcessor commandProcessor = CommandProcessor.getInstance();
   commandProcessor.executeCommand(
       myProject,
       () -> {
         editor.getDocument().deleteString(templateStart, caretOffset);
         editor.getCaretModel().moveToOffset(templateStart);
         editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
         editor.getSelectionModel().removeSelection();
         Map<String, String> predefinedVarValues = null;
         if (argument != null) {
           predefinedVarValues = new HashMap<String, String>();
           predefinedVarValues.put(TemplateImpl.ARG, argument);
         }
         templateState.start(template, processor, predefinedVarValues);
       },
       CodeInsightBundle.message("insert.code.template.command"),
       null);
 }
  protected void doOKAction() {
    final LogicalPosition currentPosition = myEditor.getCaretModel().getLogicalPosition();
    int lineNumber = getLineNumber(currentPosition.line + 1);
    if (isInternal() && myOffsetField.getText().length() > 0) {
      try {
        final int offset = Integer.parseInt(myOffsetField.getText());
        if (offset < myEditor.getDocument().getTextLength()) {
          myEditor.getCaretModel().removeSecondaryCarets();
          myEditor.getCaretModel().moveToOffset(offset);
          myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
          myEditor.getSelectionModel().removeSelection();
          IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true);
          super.doOKAction();
        }
        return;
      } catch (NumberFormatException e) {
        return;
      }
    }

    if (lineNumber < 0) return;

    int columnNumber = getColumnNumber(currentPosition.column);
    myEditor.getCaretModel().removeSecondaryCarets();
    myEditor
        .getCaretModel()
        .moveToLogicalPosition(
            new LogicalPosition(Math.max(0, lineNumber - 1), Math.max(0, columnNumber - 1)));
    myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
    myEditor.getSelectionModel().removeSelection();
    IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true);
    super.doOKAction();
  }
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
  @Override
  public void invoke(
      @NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    DumbService.getInstance(project).setAlternativeResolveEnabled(true);
    try {
      int offset = editor.getCaretModel().getOffset();
      PsiElement[] elements =
          underModalProgress(
              project,
              "Resolving Reference...",
              () -> findAllTargetElements(project, editor, offset));
      FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration");

      if (elements.length != 1) {
        if (elements.length == 0
            && suggestCandidates(TargetElementUtil.findReference(editor, offset)).isEmpty()) {
          PsiElement element =
              findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset());
          if (startFindUsages(editor, element)) {
            return;
          }

          // disable 'no declaration found' notification for keywords
          final PsiElement elementAtCaret = file.findElementAt(offset);
          if (elementAtCaret != null) {
            final NamesValidator namesValidator =
                LanguageNamesValidation.INSTANCE.forLanguage(elementAtCaret.getLanguage());
            if (namesValidator != null
                && namesValidator.isKeyword(elementAtCaret.getText(), project)) {
              return;
            }
          }
        }
        chooseAmbiguousTarget(editor, offset, elements, file);
        return;
      }

      PsiElement element = elements[0];
      if (element == findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset())
          && startFindUsages(editor, element)) {
        return;
      }

      PsiElement navElement = element.getNavigationElement();
      navElement = TargetElementUtil.getInstance().getGotoDeclarationTarget(element, navElement);
      if (navElement != null) {
        gotoTargetElement(navElement, editor, file);
      }
    } catch (IndexNotReadyException e) {
      DumbService.getInstance(project)
          .showDumbModeNotification("Navigation is not available here during index update");
    } finally {
      DumbService.getInstance(project).setAlternativeResolveEnabled(false);
    }
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    if (!(element instanceof GrConditionalExpression)) {
      throw new IncorrectOperationException("Not invoked on a conditional");
    }
    GroovyPsiElementFactory groovyPsiElementFactory = GroovyPsiElementFactory.getInstance(project);
    GrConditionalExpression condExp = (GrConditionalExpression) element;
    GrExpression thenBranch = condExp.getThenBranch();
    GrExpression elseBranch = condExp.getElseBranch();

    Object thenVal = GroovyConstantExpressionEvaluator.evaluate(thenBranch);
    if (Boolean.TRUE.equals(thenVal) && elseBranch != null) {
      // aaa ? true : bbb -> aaa || bbb
      GrExpression conditionExp = condExp.getCondition();

      String conditionExpText = getStringToPutIntoOrExpression(conditionExp);
      String elseExpText = getStringToPutIntoOrExpression(elseBranch);
      String newExp = conditionExpText + "||" + elseExpText;
      int caretOffset = conditionExpText.length() + 2; // after "||"

      GrExpression expressionFromText =
          groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext());

      expressionFromText = (GrExpression) condExp.replace(expressionFromText);

      editor
          .getCaretModel()
          .moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "||"
      return;
    }

    Object elseVal = GroovyConstantExpressionEvaluator.evaluate(elseBranch);
    if (Boolean.FALSE.equals(elseVal) && thenBranch != null) {
      // aaa ? bbb : false -> aaa && bbb
      GrExpression conditionExp = condExp.getCondition();

      String conditionExpText = getStringToPutIntoAndExpression(conditionExp);
      String thenExpText = getStringToPutIntoAndExpression(thenBranch);

      String newExp = conditionExpText + "&&" + thenExpText;
      int caretOffset = conditionExpText.length() + 2; // after "&&"
      GrExpression expressionFromText =
          groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext());

      expressionFromText = (GrExpression) condExp.replace(expressionFromText);

      editor
          .getCaretModel()
          .moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "&&"
    }
  }
  public static void run(
      @NotNull final Project project,
      @NotNull final Editor editor,
      @NotNull final ExtractMethodObjectProcessor processor,
      @NotNull final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor) {
    final int offset = editor.getCaretModel().getOffset();
    final RangeMarker marker =
        editor.getDocument().createRangeMarker(new TextRange(offset, offset));
    CommandProcessor.getInstance()
        .executeCommand(
            project,
            new Runnable() {
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            extractProcessor.doRefactoring();
                          }
                        });

                processor.run();
                processor.runChangeSignature();
                PsiDocumentManager.getInstance(project).commitAllDocuments();
                if (processor.isCreateInnerClass()) {
                  processor.moveUsedMethodsToInner();
                  PsiDocumentManager.getInstance(project).commitAllDocuments();
                  DuplicatesImpl.processDuplicates(extractProcessor, project, editor);
                }
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (processor.isCreateInnerClass()) {
                              processor.changeInstanceAccess(project);
                            }
                            final PsiElement method = processor.getMethod();
                            LOG.assertTrue(method != null);
                            method.delete();
                          }
                        });
              }
            },
            ExtractMethodObjectProcessor.REFACTORING_NAME,
            ExtractMethodObjectProcessor.REFACTORING_NAME);
    editor.getCaretModel().moveToOffset(marker.getStartOffset());
    marker.dispose();
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
  }
  protected void runOverEditor(
      @NotNull final Project project,
      @NotNull final Editor editor,
      @NotNull final PsiFile psiFile) {
    final Document document = editor.getDocument();
    if (!ReadonlyStatusHandler.ensureDocumentWritable(project, document)) return;

    final Runnable runnable =
        () -> {
          final int caretOffset = editor.getCaretModel().getOffset();
          final int lineLength = getRightMargin(project);

          DartAnalysisServerService.getInstance().updateFilesContent();
          DartAnalysisServerService.FormatResult formatResult =
              DartAnalysisServerService.getInstance()
                  .edit_format(psiFile.getVirtualFile(), caretOffset, 0, lineLength);

          if (formatResult == null) {
            showHintLater(editor, DartBundle.message("dart.style.hint.failed"), true);
            LOG.warn("Unexpected response from edit_format, formatResult is null");
            return;
          }

          final List<SourceEdit> edits = formatResult.getEdits();
          if (edits == null || edits.size() == 0) {
            showHintLater(editor, DartBundle.message("dart.style.hint.already.good"), false);
          } else if (edits.size() == 1) {
            final String replacement =
                StringUtil.convertLineSeparators(edits.get(0).getReplacement());
            document.replaceString(0, document.getTextLength(), replacement);
            final int offset =
                DartAnalysisServerService.getInstance()
                    .getConvertedOffset(psiFile.getVirtualFile(), formatResult.getOffset());
            editor.getCaretModel().moveToOffset(offset);
            showHintLater(editor, DartBundle.message("dart.style.hint.success"), false);
          } else {
            showHintLater(editor, DartBundle.message("dart.style.hint.failed"), true);
            LOG.warn(
                "Unexpected response from edit_format, formatResult.getEdits().size() = "
                    + edits.size());
          }
        };

    ApplicationManager.getApplication()
        .runWriteAction(
            () ->
                CommandProcessor.getInstance()
                    .executeCommand(
                        project, runnable, DartBundle.message("dart.style.action.name"), null));
  }
  protected JComponent createNorthPanel() {
    class MyTextField extends JTextField {
      public MyTextField() {
        super("");
      }

      public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();
        return new Dimension(200, d.height);
      }
    }

    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbConstraints = new GridBagConstraints();

    gbConstraints.insets = new Insets(4, 0, 8, 8);
    gbConstraints.fill = GridBagConstraints.VERTICAL;
    gbConstraints.weightx = 0;
    gbConstraints.weighty = 1;
    gbConstraints.anchor = GridBagConstraints.EAST;
    JLabel label = new JLabel(IdeBundle.message("editbox.line.number"));
    panel.add(label, gbConstraints);

    gbConstraints.fill = GridBagConstraints.BOTH;
    gbConstraints.weightx = 1;
    myField = new MyTextField();
    panel.add(myField, gbConstraints);
    myField.setToolTipText(IdeBundle.message("tooltip.syntax.linenumber.columnnumber"));
    LogicalPosition position = myEditor.getCaretModel().getLogicalPosition();
    myField.setText(String.format("%d:%d", position.line + 1, position.column + 1));

    if (isInternal()) {
      gbConstraints.gridy = 1;
      gbConstraints.weightx = 0;
      gbConstraints.weighty = 1;
      gbConstraints.anchor = GridBagConstraints.EAST;
      final JLabel offsetLabel = new JLabel("Offset:");
      panel.add(offsetLabel, gbConstraints);

      gbConstraints.fill = GridBagConstraints.BOTH;
      gbConstraints.weightx = 1;
      myOffsetField = new MyTextField();
      panel.add(myOffsetField, gbConstraints);
      myOffsetField.setToolTipText(String.valueOf(myEditor.getCaretModel().getOffset()));
    }

    return panel;
  }
 protected IdentifierHighlighterPass(
     @NotNull Project project, @NotNull PsiFile file, @NotNull Editor editor) {
   super(project, editor.getDocument(), false);
   myFile = file;
   myEditor = editor;
   myCaretOffset = myEditor.getCaretModel().getOffset();
 }
  public void doInvoke(@NotNull Project project, Editor editor, PsiFile file)
      throws IncorrectOperationException {
    final PsiElement element =
        PyUtil.findNonWhitespaceAtOffset(file, editor.getCaretModel().getOffset());
    PyFunction problemFunction = PsiTreeUtil.getParentOfType(element, PyFunction.class);
    if (problemFunction == null) return;
    final PyClass containingClass = problemFunction.getContainingClass();
    if (containingClass == null) return;
    final List<UsageInfo> usages = PyRefactoringUtil.findUsages(problemFunction, false);
    final PyDecoratorList decoratorList = problemFunction.getDecoratorList();
    if (decoratorList != null) {
      final PyDecorator decorator = decoratorList.findDecorator(PyNames.STATICMETHOD);
      if (decorator != null) decorator.delete();
    }

    final PsiElement copy = problemFunction.copy();
    problemFunction.delete();
    file.addAfter(copy, containingClass);

    for (UsageInfo usage : usages) {
      final PsiElement usageElement = usage.getElement();
      if (usageElement instanceof PyReferenceExpression) {
        PyUtil.removeQualifier((PyReferenceExpression) usageElement);
      }
    }
  }
Beispiel #14
0
  public static int findNextSentenceStart(
      Editor editor, int count, boolean countCurrent, boolean requireAll) {
    int dir = count > 0 ? 1 : -1;
    count = Math.abs(count);
    int total = count;
    CharSequence chars = EditorHelper.getDocumentChars(editor);
    int start = editor.getCaretModel().getOffset();
    int max = EditorHelper.getFileSize(editor);

    int res = start;
    for (; count > 0 && res >= 0 && res <= max - 1; count--) {
      res = findSentenceStart(editor, chars, res, max, dir, countCurrent, count > 1);
      if (res == 0 || res == max - 1) {
        count--;
        break;
      }
    }

    if (res < 0 && (!requireAll || total == 1)) {
      res = dir > 0 ? max - 1 : 0;
    } else if (count > 0 && total > 1 && !requireAll) {
      res = dir > 0 ? max - 1 : 0;
    } else if (count > 0 && total > 1 && requireAll) {
      res = -count;
    }

    return res;
  }
 static void chooseAmbiguousTargetAndPerform(
     @NotNull final Project project,
     final Editor editor,
     @NotNull PsiElementProcessor<PsiElement> processor) {
   if (editor == null) {
     Messages.showMessageDialog(
         project,
         FindBundle.message("find.no.usages.at.cursor.error"),
         CommonBundle.getErrorTitle(),
         Messages.getErrorIcon());
   } else {
     int offset = editor.getCaretModel().getOffset();
     boolean chosen =
         GotoDeclarationAction.chooseAmbiguousTarget(
             editor,
             offset,
             processor,
             FindBundle.message("find.usages.ambiguous.title", "crap"),
             null);
     if (!chosen) {
       ApplicationManager.getApplication()
           .invokeLater(
               new Runnable() {
                 @Override
                 public void run() {
                   if (editor.isDisposed() || !editor.getComponent().isShowing()) return;
                   HintManager.getInstance()
                       .showErrorHint(
                           editor, FindBundle.message("find.no.usages.at.cursor.error"));
                 }
               },
               project.getDisposed());
     }
   }
 }
Beispiel #16
0
  public static TextWithImports getEditorText(final Editor editor) {
    if (editor == null) {
      return null;
    }
    final Project project = editor.getProject();
    if (project == null) return null;

    String defaultExpression = editor.getSelectionModel().getSelectedText();
    if (defaultExpression == null) {
      int offset = editor.getCaretModel().getOffset();
      PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (psiFile != null) {
        PsiElement elementAtCursor = psiFile.findElementAt(offset);
        if (elementAtCursor != null) {
          final EditorTextProvider textProvider =
              EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage());
          if (textProvider != null) {
            final TextWithImports editorText = textProvider.getEditorText(elementAtCursor);
            if (editorText != null) return editorText;
          }
        }
      }
    } else {
      return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression);
    }
    return null;
  }
  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();
    }
  }
Beispiel #18
0
  /**
   * This finds the offset to the end of the next/previous word/WORD.
   *
   * @param editor The editor to search in
   * @param count The number of words to skip. Negative for backward searches
   * @param skipPunc If true then find WORD, if false then find word
   * @return The offset of match
   */
  public static int findNextWordEnd(Editor editor, int count, boolean skipPunc, boolean stayEnd) {
    CharSequence chars = EditorHelper.getDocumentChars(editor);
    int pos = editor.getCaretModel().getOffset();
    int size = EditorHelper.getFileSize(editor);

    return findNextWordEnd(chars, pos, size, count, skipPunc, stayEnd, false);
  }
  protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myConstructorCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    try {
      PsiMethod constructor = (PsiMethod) targetClass.add(elementFactory.createConstructor());

      final PsiFile file = targetClass.getContainingFile();
      TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
      CreateFromUsageUtils.setupMethodParameters(
          constructor,
          templateBuilder,
          myConstructorCall.getArgumentList(),
          getTargetSubstitutor(myConstructorCall));
      final PsiMethod superConstructor =
          CreateClassFromNewFix.setupSuperCall(targetClass, constructor, templateBuilder);

      constructor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(constructor);
      Template template = templateBuilder.buildTemplate();
      if (targetClass == null) return;
      final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
      final TextRange textRange = constructor.getTextRange();
      editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
      editor.getCaretModel().moveToOffset(textRange.getStartOffset());

      startTemplate(
          editor,
          template,
          project,
          new TemplateEditingAdapter() {
            public void templateFinished(Template template, boolean brokenOff) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        public void run() {
                          try {
                            PsiDocumentManager.getInstance(project)
                                .commitDocument(editor.getDocument());
                            final int offset = editor.getCaretModel().getOffset();
                            PsiMethod constructor =
                                PsiTreeUtil.findElementOfClassAtOffset(
                                    file, offset, PsiMethod.class, false);
                            if (superConstructor == null) {
                              CreateFromUsageUtils.setupMethodBody(constructor);
                            } else {
                              OverrideImplementUtil.setupMethodBody(
                                  constructor, superConstructor, targetClass);
                            }
                            CreateFromUsageUtils.setupEditor(constructor, editor);
                          } catch (IncorrectOperationException e) {
                            LOG.error(e);
                          }
                        }
                      });
            }
          });
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 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();
     PsiElement[] toMigrate = null;
     if (parent instanceof PsiVariable) {
       toMigrate = extractReferencedVariables(typeElement);
     } else if ((parent instanceof PsiMember && !(parent instanceof PsiClass))
         || isClassArgument(parent)) {
       toMigrate = new PsiElement[] {parent};
     }
     if (toMigrate != null && toMigrate.length > 0) {
       invoke(project, toMigrate, null, 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");
 }
  /**
   * Scroll to the error specified by the given tree path, or do nothing if no error is specified.
   *
   * @param treePath the tree path to scroll to.
   */
  private void scrollToError(final TreePath treePath) {
    final DefaultMutableTreeNode treeNode =
        (DefaultMutableTreeNode) treePath.getLastPathComponent();
    if (treeNode == null || !(treeNode.getUserObject() instanceof ResultTreeNode)) {
      return;
    }

    final ResultTreeNode nodeInfo = (ResultTreeNode) treeNode.getUserObject();
    if (nodeInfo.getFile() == null || nodeInfo.getProblem() == null) {
      return; // no problem here :-)
    }

    final VirtualFile virtualFile = nodeInfo.getFile().getVirtualFile();
    if (virtualFile == null || !virtualFile.exists()) {
      return;
    }

    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    final FileEditor[] editor = fileEditorManager.openFile(virtualFile, true);

    if (editor.length > 0 && editor[0] instanceof TextEditor) {
      final LogicalPosition problemPos =
          new LogicalPosition(Math.max(lineFor(nodeInfo) - 1, 0), Math.max(columnFor(nodeInfo), 0));

      final Editor textEditor = ((TextEditor) editor[0]).getEditor();
      textEditor.getCaretModel().moveToLogicalPosition(problemPos);
      textEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
    }
  }
Beispiel #22
0
  public int searchWord(@NotNull Editor editor, int count, boolean whole, int dir) {
    TextRange range = SearchHelper.findWordUnderCursor(editor);
    if (range == null) {
      return -1;
    }

    StringBuilder pattern = new StringBuilder();
    if (whole) {
      pattern.append("\\<");
    }
    pattern.append(EditorHelper.getText(editor, range.getStartOffset(), range.getEndOffset()));
    if (whole) {
      pattern.append("\\>");
    }

    MotionGroup.moveCaret(editor, range.getStartOffset());

    lastSearch = pattern.toString();
    setLastPattern(editor, lastSearch);
    lastOffset = "";
    lastDir = dir;

    searchHighlight(true);

    return findItOffset(editor, editor.getCaretModel().getOffset(), count, lastDir, true);
  }
  public static Editor getEditorForInjectedLanguageNoCommit(
      @Nullable Editor editor, @Nullable PsiFile file) {
    if (editor == null || file == null || editor instanceof EditorWindow) return editor;

    int offset = editor.getCaretModel().getOffset();
    return getEditorForInjectedLanguageNoCommit(editor, file, offset);
  }
Beispiel #24
0
 @Nullable
 @Override
 public String computeTemplateKeyWithoutContextChecking(@NotNull CustomTemplateCallback callback) {
   Editor editor = callback.getEditor();
   return computeTemplateKeyWithoutContextChecking(
       editor.getDocument().getCharsSequence(), editor.getCaretModel().getOffset());
 }
  private void handleNoSelection(Editor editor) {
    CaretModel caretModel = editor.getCaretModel();
    Document doc = editor.getDocument();
    if ((caretModel == null) || (doc == null) || (doc.getTextLength() == 0)) {
      return;
    }

    char[] allChars = doc.getChars();
    int maxOffset = allChars.length;

    int startOffset = caretModel.getOffset();

    while ((startOffset < maxOffset) && (!Character.isLetterOrDigit(allChars[startOffset]))) {
      startOffset++;
    }

    StringBuffer word = new StringBuffer();
    int i = startOffset;
    while ((i < maxOffset) && (Character.isLetterOrDigit(allChars[i]))) {
      word.append(allChars[i]);

      i++;
    }

    if (word.length() > 0) {
      this.m_transformer.transform(word);
      int newOffset = startOffset + word.length();
      doc.replaceString(startOffset, newOffset, word.toString());

      caretModel.moveToOffset(newOffset);
    }
  }
  private static void restoreBlockSelection(
      Editor editor, List<RangeMarker> caretsAfter, int caretLine) {
    int column = -1;
    int minLine = Integer.MAX_VALUE;
    int maxLine = -1;
    for (RangeMarker marker : caretsAfter) {
      if (marker.isValid()) {
        LogicalPosition lp = editor.offsetToLogicalPosition(marker.getStartOffset());
        if (column == -1) {
          column = lp.column;
        } else if (column != lp.column) {
          return;
        }
        minLine = Math.min(minLine, lp.line);
        maxLine = Math.max(maxLine, lp.line);

        if (lp.line == caretLine) {
          editor.getCaretModel().moveToLogicalPosition(lp);
        }
      }
    }
    editor
        .getSelectionModel()
        .setBlockSelection(
            new LogicalPosition(minLine, column), new LogicalPosition(maxLine, column));
  }
 @Nullable
 private static PsiElement getSelectedPsiElement(
     final DataContext dataContext, final Project project) {
   PsiElement element = null;
   final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
   if (editor != null) {
     final PsiFile psiFile =
         PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
     if (psiFile != null) {
       final int offset = editor.getCaretModel().getOffset();
       element = psiFile.findElementAt(offset);
       if (element == null && offset > 0 && offset == psiFile.getTextLength()) {
         element = psiFile.findElementAt(offset - 1);
       }
     }
   }
   if (element == null) {
     final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
     element = elements != null && elements.length > 0 ? elements[0] : null;
   }
   if (element == null) {
     final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
     if (files != null && files.length > 0) {
       element = PsiManager.getInstance(project).findFile(files[0]);
     }
   }
   return element;
 }
Beispiel #28
0
  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 = getEditor(project, element);
    if (editor == null) return;
    PsiFile file = element.getContainingFile();
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    Document document = documentManager.getDocument(file);
    if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
    PsiElement[] elements = {anchorStatement};
    PsiElement prev = PsiTreeUtil.skipSiblingsBackward(anchorStatement, PsiWhiteSpace.class);
    if (prev instanceof PsiComment
        && SuppressManager.getInstance().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());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);

    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
    public BookmarkInContextInfo invoke() {
      myBookmarkAtPlace = null;
      myFile = null;
      myLine = -1;

      BookmarkManager bookmarkManager = BookmarkManager.getInstance(myProject);
      if (ToolWindowManager.getInstance(myProject).isEditorComponentActive()) {
        Editor editor = CommonDataKeys.EDITOR.getData(myDataContext);
        if (editor != null) {
          Document document = editor.getDocument();
          myLine = editor.getCaretModel().getLogicalPosition().line;
          myFile = FileDocumentManager.getInstance().getFile(document);
          myBookmarkAtPlace = bookmarkManager.findEditorBookmark(document, myLine);
        }
      }

      if (myFile == null) {
        myFile = CommonDataKeys.VIRTUAL_FILE.getData(myDataContext);
        myLine = -1;

        if (myBookmarkAtPlace == null && myFile != null) {
          myBookmarkAtPlace = bookmarkManager.findFileBookmark(myFile);
        }
      }
      return this;
    }
  /**
   * @param editor
   * @param idDialog
   * @param dialog
   * @param title
   */
  public static void setDialogVisible(
      @Nullable Editor editor, String idDialog, JDialog dialog, String title) {
    Point location = null;

    if (editor != null) {
      Point caretLocation = editor.visualPositionToXY(editor.getCaretModel().getVisualPosition());
      SwingUtilities.convertPointToScreen(caretLocation, editor.getComponent());

      String[] position = UtilsPreferences.getDialogPosition(idDialog).split("x");
      if (!(position[0].equals("0") && position[1].equals("0"))) {
        location = new Point(Integer.parseInt(position[0]), Integer.parseInt(position[1]));
      }
    }

    if (location == null) {
      // Center to screen
      dialog.setLocationRelativeTo(null);
    } else {
      dialog.setLocation(location.x, location.y);
    }

    dialog.setTitle(title);
    dialog.pack();
    dialog.setVisible(true);
  }