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();
  }
示例#2
0
    void execute(BrowseMode browseMode) {
      myBrowseMode = browseMode;

      Document document = myEditor.getDocument();
      final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
      if (file == null) return;
      PsiDocumentManager.getInstance(myProject).commitAllDocuments();

      if (EditorUtil.inVirtualSpace(myEditor, myPosition)) {
        return;
      }

      final int offset = myEditor.logicalPositionToOffset(myPosition);

      int selStart = myEditor.getSelectionModel().getSelectionStart();
      int selEnd = myEditor.getSelectionModel().getSelectionEnd();

      if (offset >= selStart && offset < selEnd) return;

      ProgressIndicatorUtils.scheduleWithWriteActionPriority(
          myProgress,
          new ReadTask() {
            @Override
            public void computeInReadAction(@NotNull ProgressIndicator indicator) {
              doExecute(file, offset);
            }

            @Override
            public void onCanceled(@NotNull ProgressIndicator indicator) {}
          });
    }
    public void execute(BrowseMode browseMode) {
      myBrowseMode = browseMode;

      Document document = myEditor.getDocument();
      final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
      if (file == null) return;
      PsiDocumentManager.getInstance(myProject).commitAllDocuments();

      if (TargetElementUtilBase.inVirtualSpace(myEditor, myPosition)) {
        return;
      }

      final int offset = myEditor.logicalPositionToOffset(myPosition);

      int selStart = myEditor.getSelectionModel().getSelectionStart();
      int selEnd = myEditor.getSelectionModel().getSelectionEnd();

      if (offset >= selStart && offset < selEnd) return;

      ApplicationManager.getApplication()
          .executeOnPooledThread(
              new Runnable() {
                public void run() {
                  final ProgressIndicator progressIndicator = new ProgressIndicatorBase();
                  final ApplicationAdapter listener =
                      new ApplicationAdapter() {
                        @Override
                        public void beforeWriteActionStart(Object action) {
                          progressIndicator.cancel();
                        }
                      };
                  final Application application = ApplicationManager.getApplication();
                  try {
                    application.addApplicationListener(listener);
                    ProgressManager.getInstance()
                        .runProcess(
                            new Runnable() {
                              @Override
                              public void run() {
                                // This read action can possibe last for a long time, we want it to
                                // stop immediately on the first write access.
                                // For this purpose we launch it under empty progress and invoke
                                // progressIndicator#cancel on write access to avoid possible write
                                // lock delays.
                                application.runReadAction(
                                    new Runnable() {
                                      public void run() {
                                        doExecute(file, offset);
                                      }
                                    });
                              }
                            },
                            progressIndicator);
                  } finally {
                    application.removeApplicationListener(listener);
                  }
                }
              });
    }
  public static boolean performExtractMethod(
      boolean doRefactor,
      boolean replaceAllDuplicates,
      Editor editor,
      PsiFile file,
      Project project,
      final boolean extractChainedConstructor,
      int... disabledParams)
      throws PrepareFailedException, IncorrectOperationException {
    int startOffset = editor.getSelectionModel().getSelectionStart();
    int endOffset = editor.getSelectionModel().getSelectionEnd();

    PsiElement[] elements;
    PsiExpression expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
    if (expr != null) {
      elements = new PsiElement[] {expr};
    } else {
      elements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
    }
    if (elements.length == 0) {
      final PsiExpression expression =
          IntroduceVariableBase.getSelectedExpression(project, file, startOffset, endOffset);
      if (expression != null) {
        elements = new PsiElement[] {expression};
      }
    }
    assertTrue(elements.length > 0);

    final ExtractMethodProcessor processor =
        new ExtractMethodProcessor(
            project, editor, elements, null, "Extract Method", "newMethod", null);
    processor.setShowErrorDialogs(false);
    processor.setChainedConstructor(extractChainedConstructor);

    if (!processor.prepare()) {
      return false;
    }

    if (doRefactor) {
      processor.testPrepare();
      if (disabledParams != null) {
        for (int param : disabledParams) {
          processor.doNotPassParameter(param);
        }
      }
      ExtractMethodHandler.run(project, editor, processor);
    }

    if (replaceAllDuplicates) {
      final List<Match> duplicates = processor.getDuplicates();
      for (final Match match : duplicates) {
        if (!match.getMatchStart().isValid() || !match.getMatchEnd().isValid()) continue;
        processor.processMatch(match);
      }
    }

    return true;
  }
 public static PsiFile insertDummyIdentifier(final Editor editor, PsiFile file) {
   boolean selection = editor.getSelectionModel().hasSelection();
   final int startOffset =
       selection
           ? editor.getSelectionModel().getSelectionStart()
           : editor.getCaretModel().getOffset();
   final int endOffset = selection ? editor.getSelectionModel().getSelectionEnd() : startOffset;
   return insertDummyIdentifierIfNeeded(
       file, startOffset, endOffset, CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
 }
示例#6
0
 private static FindModel createDefaultFindModel(Project project, Editor editor) {
   FindModel findModel = new FindModel();
   findModel.copyFrom(FindManager.getInstance(project).getFindInFileModel());
   if (editor.getSelectionModel().hasSelection()) {
     String selectedText = editor.getSelectionModel().getSelectedText();
     if (selectedText != null) {
       findModel.setStringToFind(selectedText);
     }
   }
   findModel.setPromptOnReplace(false);
   return findModel;
 }
 @Nullable
 public static TextRange getSelectedRange(Editor editor, final PsiFile psiFile) {
   if (editor == null) return null;
   String selectedText = editor.getSelectionModel().getSelectedText();
   if (selectedText != null) {
     return new TextRange(
         editor.getSelectionModel().getSelectionStart(),
         editor.getSelectionModel().getSelectionEnd());
   }
   PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
   if (psiElement == null || psiElement instanceof PsiWhiteSpace) return null;
   return psiElement.getTextRange();
 }
 @Override
 public void actionPerformed(AnActionEvent e) {
   final boolean hasSelection = _commitLog.getSelectionModel().hasSelection();
   if (!hasSelection) {
     _commitLog
         .getSelectionModel()
         .setSelection(0, _commitLog.getDocument().getCharsSequence().length() - 1);
   }
   _commitLog.getSelectionModel().copySelectionToClipboard();
   if (!hasSelection) {
     _commitLog.getSelectionModel().removeSelection();
   }
 }
  private static ElementToWorkOn getElementToWorkOn(
      final Editor editor,
      final PsiFile file,
      final String refactoringName,
      final String helpId,
      final Project project,
      PsiLocalVariable localVar,
      PsiExpression expr) {
    int startOffset = 0;
    int endOffset = 0;
    if (localVar == null && expr == null) {
      startOffset = editor.getSelectionModel().getSelectionStart();
      endOffset = editor.getSelectionModel().getSelectionEnd();
      expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
      if (expr == null) {
        PsiIdentifier ident =
            CodeInsightUtil.findElementInRange(file, startOffset, endOffset, PsiIdentifier.class);
        if (ident != null) {
          localVar = PsiTreeUtil.getParentOfType(ident, PsiLocalVariable.class);
        }
      }
    }

    if (expr == null && localVar == null) {
      PsiElement[] statements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
      if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
        expr = ((PsiExpressionStatement) statements[0]).getExpression();
      } else if (statements.length == 1 && statements[0] instanceof PsiDeclarationStatement) {
        PsiDeclarationStatement decl = (PsiDeclarationStatement) statements[0];
        PsiElement[] declaredElements = decl.getDeclaredElements();
        if (declaredElements.length == 1 && declaredElements[0] instanceof PsiLocalVariable) {
          localVar = (PsiLocalVariable) declaredElements[0];
        }
      }
    }
    if (localVar == null && expr == null) {
      expr = IntroduceVariableBase.getSelectedExpression(project, file, startOffset, endOffset);
    }

    if (localVar == null && expr == null) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("error.wrong.caret.position.local.or.expression.name"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId);
      return null;
    }
    return new ElementToWorkOn(localVar, expr);
  }
示例#10
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 testColumnModeBlockSelectionWithGaps() {
    String text =
        "public class TestClass {\n"
            + "\n"
            + "    int field;\n"
            + "\n"
            + "    int otherField;\n"
            + "}";
    init(text);

    int blockSelectionStartOffset = text.indexOf("int");
    Editor editor = myFixture.getEditor();
    ((EditorEx) editor).setColumnMode(true);
    LogicalPosition blockSelectionStartPosition =
        editor.offsetToLogicalPosition(blockSelectionStartOffset);
    LogicalPosition blockSelectionEndPosition =
        new LogicalPosition(
            blockSelectionStartPosition.line + 2, blockSelectionStartPosition.column + 16);
    editor
        .getSelectionModel()
        .setBlockSelection(blockSelectionStartPosition, blockSelectionEndPosition);

    verifySyntaxInfo(
        "foreground=java.awt.Color[r=0,g=0,b=128],fontStyle=1,text=int \n"
            + "foreground=java.awt.Color[r=102,g=14,b=122],text=field\n"
            + "foreground=java.awt.Color[r=0,g=0,b=0],fontStyle=0,text=;\n"
            + "text=\n"
            + "\n"
            + "text=\n"
            + "\n"
            + "foreground=java.awt.Color[r=0,g=0,b=128],fontStyle=1,text=int \n"
            + "foreground=java.awt.Color[r=102,g=14,b=122],text=otherField\n"
            + "foreground=java.awt.Color[r=0,g=0,b=0],fontStyle=0,text=;\n");
  }
  @Override
  public void actionPerformed(AnActionEvent e) {
    Project project = e.getData(PlatformDataKeys.PROJECT);
    Editor editor = e.getData(PlatformDataKeys.EDITOR);

    if (editor == null) {
      return;
    }

    if (!editor.getDocument().isWritable()) {
      return;
    }

    Document document = editor.getDocument();
    SelectionModel selection = editor.getSelectionModel();
    String selectedText = selection.getSelectedText();

    String autoAlignedText;
    int startOffset;
    int endOffset;

    if (selectedText != null) {
      // just align the selected text
      autoAlignedText = aligner.align(selectedText);
      startOffset = selection.getSelectionStart();
      endOffset = selection.getSelectionEnd();
    } else {
      // auto-align the whole document
      autoAlignedText = aligner.align(document.getText());
      startOffset = 0;
      endOffset = document.getTextLength();
    }

    replaceString(project, document, autoAlignedText, startOffset, endOffset);
  }
  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));
  }
 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);
 }
  @Override
  public void actionPerformed(AnActionEvent event) {
    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (project == null || editor == null) {
      presentation.setEnabled(false);
      return;
    }

    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null || file.getVirtualFile() == null) {
      presentation.setEnabled(false);
      return;
    }

    boolean hasSelection = editor.getSelectionModel().hasSelection();
    LayoutCodeDialog dialog = new LayoutCodeDialog(project, file, hasSelection, HELP_ID);
    dialog.show();

    if (dialog.isOK()) {
      new FileInEditorProcessor(file, editor, dialog.getRunOptions()).processCode();
    }
  }
  public void update(final AnActionEvent event) {
    super.update(event);

    final Presentation presentation = event.getPresentation();
    final DataContext context = event.getDataContext();
    Module module = (Module) context.getData(LangDataKeys.MODULE.getName());
    PsiFile currentFile = (PsiFile) context.getData(LangDataKeys.PSI_FILE.getName());
    Editor editor = (Editor) context.getData(PlatformDataKeys.EDITOR.getName());
    // VirtualFile currentFile = (VirtualFile)
    // context.getData(PlatformDataKeys.VIRTUAL_FILE.getName());
    if (currentFile != null && editor != null) {
      boolean isSSFile =
          currentFile
              .getFileType()
              .getDefaultExtension()
              .equals(SilverStripeFileType.DEFAULT_EXTENSION);
      SelectionModel selectionModel = editor.getSelectionModel();
      String selectedText = selectionModel.getSelectedText();
      this.selectedText = selectedText;
      this.selectonModel = selectionModel;
      this.editor = editor;
      this.currentFile = currentFile;
      if (selectedText == null) {
        presentation.setEnabled(false);
      }
      if (!isSSFile) {
        presentation.setEnabled(false);
        presentation.setVisible(false);
      }
    } else {
      presentation.setEnabled(false);
      presentation.setVisible(false);
    }
  }
    public boolean isEnabled(@NotNull final Project project, final AnActionEvent event) {
      if (!myHandler.isEnabled(project)) return false;

      Editor editor = event.getData(PlatformDataKeys.EDITOR);
      if (editor == null) return false;

      InputEvent inputEvent = event.getInputEvent();
      if (inputEvent instanceof MouseEvent && inputEvent.isAltDown()) {
        MouseEvent mouseEvent = (MouseEvent) inputEvent;
        Component component =
            SwingUtilities.getDeepestComponentAt(
                mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent.getY());
        if (SwingUtilities.isDescendingFrom(component, editor.getComponent())) {
          MouseEvent convertedEvent =
              SwingUtilities.convertMouseEvent(mouseEvent.getComponent(), mouseEvent, component);
          EditorMouseEventArea area = editor.getMouseEventArea(convertedEvent);
          if (area != EditorMouseEventArea.EDITING_AREA) {
            return false;
          }
        }
      } else {
        if (StringUtil.isEmptyOrSpaces(editor.getSelectionModel().getSelectedText())) {
          return false;
        }
      }

      return true;
    }
 @Override
 public void selectInEditor() {
   if (!isValid()) return;
   Editor editor = openTextEditor(true);
   Segment marker = getFirstSegment();
   editor.getSelectionModel().setSelection(marker.getStartOffset(), marker.getEndOffset());
 }
示例#19
0
  @Override
  public void execute(
      final Editor editor,
      final DataContext dataContext,
      @Nullable final Producer<Transferable> producer) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;

    final Document document = editor.getDocument();
    if (!FileDocumentManager.getInstance()
        .requestWriting(document, CommonDataKeys.PROJECT.getData(dataContext))) {
      return;
    }

    DataContext context = dataContext;
    if (producer != null) {
      context =
          new DataContext() {
            @Override
            public Object getData(@NonNls String dataId) {
              return PasteAction.TRANSFERABLE_PROVIDER.is(dataId)
                  ? producer
                  : dataContext.getData(dataId);
            }
          };
    }

    final Project project = editor.getProject();
    if (project == null
        || editor.isColumnMode()
        || editor.getSelectionModel().hasBlockSelection()
        || editor.getCaretModel().getCaretCount() > 1) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    document.startGuardedBlockChecking();
    try {
      for (PasteProvider provider : Extensions.getExtensions(EP_NAME)) {
        if (provider.isPasteEnabled(context)) {
          provider.performPaste(context);
          return;
        }
      }
      doPaste(editor, project, file, document, producer);
    } catch (ReadOnlyFragmentModificationException e) {
      EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e);
    } finally {
      document.stopGuardedBlockChecking();
    }
  }
示例#20
0
  private void removeFromEditor() {
    Editor editor = mySearchResults.getEditor();
    if (myReplacementBalloon != null) {
      myReplacementBalloon.hide();
    }

    if (editor != null) {

      for (VisibleAreaListener visibleAreaListener : myVisibleAreaListenersToRemove) {
        editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
      }
      myVisibleAreaListenersToRemove.clear();
      Project project = mySearchResults.getProject();
      if (project != null && !project.isDisposed()) {
        for (RangeHighlighter h : myHighlighters) {
          HighlightManager.getInstance(project).removeSegmentHighlighter(editor, h);
        }
        if (myCursorHighlighter != null) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, myCursorHighlighter);
          myCursorHighlighter = null;
        }
      }
      myHighlighters.clear();
      if (myListeningSelection) {
        editor.getSelectionModel().removeSelectionListener(this);
        myListeningSelection = false;
      }
    }
  }
  public static List<TemplateImpl> listApplicableTemplateWithInsertingDummyIdentifier(
      Editor editor, PsiFile file, boolean selectionOnly) {
    int startOffset = editor.getSelectionModel().getSelectionStart();
    file = insertDummyIdentifier(editor, file);

    return listApplicableTemplates(file, startOffset, selectionOnly);
  }
示例#22
0
  private void updateCursorHighlighting(boolean scroll) {
    hideBalloon();

    if (myCursorHighlighter != null) {
      HighlightManager.getInstance(mySearchResults.getProject())
          .removeSegmentHighlighter(mySearchResults.getEditor(), myCursorHighlighter);
      myCursorHighlighter = null;
    }

    final FindResult cursor = mySearchResults.getCursor();
    Editor editor = mySearchResults.getEditor();
    SelectionModel selection = editor.getSelectionModel();
    if (cursor != null) {
      Set<RangeHighlighter> dummy = new HashSet<RangeHighlighter>();
      highlightRange(
          cursor, new TextAttributes(null, null, Color.BLACK, EffectType.ROUNDED_BOX, 0), dummy);
      if (!dummy.isEmpty()) {
        myCursorHighlighter = dummy.iterator().next();
      }

      if (scroll) {
        if (mySearchResults.getFindModel().isGlobal()) {
          FoldingModel foldingModel = editor.getFoldingModel();
          final FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();

          foldingModel.runBatchFoldingOperation(
              new Runnable() {
                @Override
                public void run() {
                  for (FoldRegion region : allRegions) {
                    if (!region.isValid()) continue;
                    if (cursor.intersects(TextRange.create(region))) {
                      region.setExpanded(true);
                    }
                  }
                }
              });
          selection.setSelection(cursor.getStartOffset(), cursor.getEndOffset());

          editor.getCaretModel().moveToOffset(cursor.getEndOffset());
          editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
        } else {
          if (!SearchResults.insideVisibleArea(editor, cursor)) {
            LogicalPosition pos = editor.offsetToLogicalPosition(cursor.getStartOffset());
            editor.getScrollingModel().scrollTo(pos, ScrollType.CENTER);
          }
        }
      }
      editor
          .getScrollingModel()
          .runActionOnScrollingFinished(
              new Runnable() {
                @Override
                public void run() {
                  showReplacementPreview();
                }
              });
    }
  }
示例#23
0
        @Override
        public void mouseMoved(final EditorMouseEvent e) {
          if (e.isConsumed() || !myProject.isInitialized() || myProject.isDisposed()) {
            return;
          }
          MouseEvent mouseEvent = e.getMouseEvent();

          if (isMouseOverTooltip(mouseEvent.getLocationOnScreen())
              || ScreenUtil.isMovementTowards(
                  myPrevMouseLocation, mouseEvent.getLocationOnScreen(), getHintBounds())) {
            myPrevMouseLocation = mouseEvent.getLocationOnScreen();
            return;
          }
          myPrevMouseLocation = mouseEvent.getLocationOnScreen();

          Editor editor = e.getEditor();
          if (editor.getProject() != null && editor.getProject() != myProject) return;
          PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
          PsiFile psiFile = documentManager.getPsiFile(editor.getDocument());
          Point point = new Point(mouseEvent.getPoint());
          if (documentManager.isCommitted(editor.getDocument())) {
            // when document is committed, try to check injected stuff - it's fast
            int offset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(point));
            editor =
                InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, psiFile, offset);
          }

          LogicalPosition pos = editor.xyToLogicalPosition(point);
          int offset = editor.logicalPositionToOffset(pos);
          int selStart = editor.getSelectionModel().getSelectionStart();
          int selEnd = editor.getSelectionModel().getSelectionEnd();

          myStoredModifiers = mouseEvent.getModifiers();
          BrowseMode browseMode = getBrowseMode(myStoredModifiers);

          cancelPreviousTooltip();

          if (browseMode == BrowseMode.None || offset >= selStart && offset < selEnd) {
            disposeHighlighter();
            return;
          }

          myTooltipProvider = new TooltipProvider(editor, pos);
          myTooltipProvider.execute(browseMode);
        }
示例#24
0
  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());
  }
示例#25
0
  public static TextRange findBlockRange(Editor editor, char type, int count, boolean isOuter) {
    CharSequence chars = EditorHelper.getDocumentChars(editor);
    int pos = editor.getCaretModel().getOffset();
    int start = editor.getSelectionModel().getSelectionStart();
    int end = editor.getSelectionModel().getSelectionEnd();
    if (start != end) {
      pos = Math.min(start, end);
    }

    int loc = blockChars.indexOf(type);
    char close = blockChars.charAt(loc + 1);

    int bstart = findBlockLocation(chars, close, type, -1, pos, count);
    if (bstart == -1) {
      return null;
    }

    int bend = findBlockLocation(chars, type, close, 1, bstart + 1, 1);

    if (!isOuter) {
      bstart++;
      if (chars.charAt(bstart) == '\n') {
        bstart++;
      }

      int o = EditorHelper.getLineStartForOffset(editor, bend);
      boolean allWhite = true;
      for (int i = o; i < bend; i++) {
        if (!Character.isWhitespace(chars.charAt(i))) {
          allWhite = false;
          break;
        }
      }

      if (allWhite) {
        bend = o - 2;
      } else {
        bend--;
      }
    }

    return new TextRange(bstart, bend);
  }
  private void moveToParameterAtOffset(int offset) {
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    PsiElement argsList = findArgumentList(file, offset, -1);
    if (argsList == null) return;

    myEditor.getCaretModel().moveToOffset(offset);
    myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    myEditor.getSelectionModel().removeSelection();
    myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file));
  }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final Editor editor =
          PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext());
      assert editor != null;
      final TextRange textRange = ((ProblemDescriptorImpl) descriptor).getTextRange();
      editor.getSelectionModel().setSelection(textRange.getStartOffset(), textRange.getEndOffset());

      final String word = editor.getSelectionModel().getSelectedText();

      if (word == null || StringUtil.isEmptyOrSpaces(word)) {
        return;
      }
      final List<LookupElement> items = new ArrayList<LookupElement>();
      for (String variant : myUnboundParams) {
        items.add(LookupElementBuilder.create(variant));
      }
      LookupManager.getInstance(project)
          .showLookup(editor, items.toArray(new LookupElement[items.size()]));
    }
  public void executeWriteAction(Editor editor, DataContext dataContext) {
    if (editor == null) {
      return;
    }

    SelectionModel selectionModel = editor.getSelectionModel();
    if ((selectionModel != null) && (selectionModel.hasSelection()))
      handleSelection(editor, selectionModel);
    else handleNoSelection(editor);
  }
示例#29
0
  private void paintSelection(Graphics2D g) {
    int selectionStartOffset = editor.getSelectionModel().getSelectionStart();
    int selectionEndOffset = editor.getSelectionModel().getSelectionEnd();
    int firstSelectedLine = coords.offsetToScreenSpace(selectionStartOffset);
    int firstSelectedCharacter = coords.offsetToCharacterInLine(selectionStartOffset);
    int lastSelectedLine = coords.offsetToScreenSpace(selectionEndOffset);
    int lastSelectedCharacter = coords.offsetToCharacterInLine(selectionEndOffset);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.90f));
    g.setColor(
        editor
            .getColorsScheme()
            .getColor(ColorKey.createColorKey("SELECTION_BACKGROUND", JBColor.BLUE)));

    if (firstSelectedLine == lastSelectedLine) {
      // Single line is easy
      g.fillRect(
          firstSelectedCharacter,
          firstSelectedLine,
          lastSelectedCharacter - firstSelectedCharacter,
          config.pixelsPerLine);
    } else {
      // Draw the line leading in
      g.fillRect(
          firstSelectedCharacter,
          firstSelectedLine,
          getWidth() - firstSelectedCharacter,
          config.pixelsPerLine);

      // Then the line at the end
      g.fillRect(0, lastSelectedLine, lastSelectedCharacter, config.pixelsPerLine);

      if (firstSelectedLine + 1 != lastSelectedLine) {
        // And if there is anything in between, fill it in
        g.fillRect(
            0,
            firstSelectedLine + config.pixelsPerLine,
            getWidth(),
            lastSelectedLine - firstSelectedLine - config.pixelsPerLine);
      }
    }
  }
示例#30
0
 private void selectAll(Component focusOwner) {
   if (focusOwner instanceof TextComponent) {
     ((TextComponent) focusOwner).selectAll();
   } else {
     Editor editor =
         PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext(focusOwner));
     if (editor != null) {
       editor.getSelectionModel().setSelection(0, editor.getDocument().getTextLength());
     }
   }
 }