Java Code Examples for com.intellij.openapi.editor.Editor#getCaretModel()

The following examples show how to use com.intellij.openapi.editor.Editor#getCaretModel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SwapSelectionBoundariesAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Editor editor, DataContext dataContext) {
  if (!(editor instanceof EditorEx)) {
    return;
  }
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (!selectionModel.hasSelection()) {
    return;
  }

  EditorEx editorEx = (EditorEx)editor;
  final int start = selectionModel.getSelectionStart();
  final int end = selectionModel.getSelectionEnd();
  final CaretModel caretModel = editor.getCaretModel();
  boolean moveToEnd = caretModel.getOffset() == start;
  editorEx.setStickySelection(false);
  editorEx.setStickySelection(true);
  if (moveToEnd) {
    caretModel.moveToOffset(end);
  }
  else {
    caretModel.moveToOffset(start);
  }
}
 
Example 2
Source File: KillToWordStartAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  if (caretOffset <= 0) {
    return;
  }

  boolean camel = editor.getSettings().isCamelWords();
  for (int i = caretOffset - 1; i >= 0; i--) {
    if (EditorActionUtil.isWordOrLexemeStart(editor, i, camel)) {
      KillRingUtil.cut(editor, i, caretOffset);
      return;
    }
  }

  KillRingUtil.cut(editor, 0, caretOffset);
}
 
Example 3
Source File: EditorDocOps.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
public final void gotoLine(final int pLineNumber, final Document document) {
    int lineNumber = pLineNumber;
    Editor projectEditor =
            FileEditorManager.getInstance(windowObjects.getProject()).getSelectedTextEditor();

    if (projectEditor != null) {
        CaretModel caretModel = projectEditor.getCaretModel();

        //document is 0-indexed
        if (lineNumber > document.getLineCount()) {
            lineNumber = document.getLineCount() - 1;
        } else {
            lineNumber = lineNumber - 1;
        }

        caretModel.moveToLogicalPosition(new LogicalPosition(lineNumber, 0));

        ScrollingModel scrollingModel = projectEditor.getScrollingModel();
        scrollingModel.scrollToCaret(ScrollType.CENTER);
    }
}
 
Example 4
Source File: SearchAction.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    Optional<PsiFile> psiFile = Optional.ofNullable(e.getData(LangDataKeys.PSI_FILE));
    String languageTag = psiFile
            .map(PsiFile::getLanguage)
            .map(Language::getDisplayName)
            .map(String::toLowerCase)
            .map(lang -> "[" + lang + "]")
            .orElse("");

    Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
    CaretModel caretModel = editor.getCaretModel();
    String selectedText = caretModel.getCurrentCaret().getSelectedText();

    BrowserUtil.browse("https://stackoverflow.com/search?q=" + languageTag + selectedText);
}
 
Example 5
Source File: DustTypedHandler.java    From Intellij-Dust with MIT License 6 votes vote down vote up
/**
 * When appropriate, automatically reduce the indentation for else tags "{:else}"
 */
private void adjustFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
  PsiElement elementAtCaret = provider.findElementAt(offset - 1, DustLanguage.class);
  PsiElement elseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
    @Override
    public boolean value(PsiElement element) {
      return element != null
          && (element instanceof DustElseTag);
    }
  });

  // run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
  if (elseParent != null) {
    // grab the current caret position (AutoIndentLinesHandler is about to mess with it)
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    CaretModel caretModel = editor.getCaretModel();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
  }
}
 
Example 6
Source File: PhpClassInsertHandler.java    From intellij-latte with MIT License 6 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	// for removing first `\` (because class completion is triggered if prev element is `\` and PHP completion adding `\` before)
	super.handleInsert(context, lookupElement);

	PsiElement prev = context.getFile().findElementAt(context.getStartOffset() - 1);
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	String prevText = prev != null ? prev.getText() : null;
	String text = element != null ? element.getText() : null;
	if (prevText == null || text == null || (prevText.startsWith("\\") && !text.startsWith("\\"))) {
		return;
	}
	LattePhpClassUsage classUsage = element.getParent() instanceof LattePhpClassUsage ? (LattePhpClassUsage) element.getParent() : null;
	String[] className = (classUsage != null ? classUsage.getClassName() : "").split("\\\\");

	if ((prevText.length() > 0 || className.length > 1) && element.getNode().getElementType() == LatteTypes.T_PHP_NAMESPACE_RESOLUTION) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		caretModel.moveToOffset(element.getTextOffset());
		editor.getSelectionModel().setSelection(element.getTextOffset(), element.getTextOffset() + 1);
		EditorModificationUtil.deleteSelectedText(editor);
		caretModel.moveToOffset(offset - 1);
		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example 7
Source File: AttrMacroInsertHandler.java    From intellij-latte with MIT License 6 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE && element.getNode().getElementType() == LatteTypes.T_HTML_TAG_NATTR_NAME) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		if (LatteUtil.isStringAtCaret(editor, "=")) {
			caretModel.moveToOffset(offset + 2);
			return;
		}

		String attrName = LatteUtil.normalizeNAttrNameModifier(element.getText());
		LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(attrName);
		if (macro != null && !macro.hasParameters()) {
			return;
		}

		editor.getDocument().insertString(offset, "=\"\"");
		caretModel.moveToOffset(offset + 2);

		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example 8
Source File: PopupFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Point getVisibleBestPopupLocation(@Nonnull Editor editor) {
  VisualPosition visualPosition = editor.getUserData(ANCHOR_POPUP_POSITION);

  if (visualPosition == null) {
    CaretModel caretModel = editor.getCaretModel();
    if (caretModel.isUpToDate()) {
      visualPosition = caretModel.getVisualPosition();
    }
    else {
      visualPosition = editor.offsetToVisualPosition(caretModel.getOffset());
    }
  }

  final int lineHeight = editor.getLineHeight();
  Point p = editor.visualPositionToXY(visualPosition);
  p.y += lineHeight;

  final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
  return !visibleArea.contains(p) && !visibleArea.contains(p.x, p.y - lineHeight) ? null : p;
}
 
Example 9
Source File: LatteTypedHandler.java    From intellij-latte with MIT License 5 votes vote down vote up
@Override
public Result beforeCharTyped(char charTyped, Project project, Editor editor, PsiFile file, FileType fileType) {
	// ignores typing '}' before '}'
	if (chars.contains(charTyped) && project != null && file.getViewProvider().getLanguages().contains(LatteLanguage.INSTANCE)) {
		CaretModel caretModel = editor.getCaretModel();
		String text = editor.getDocument().getText();
		int offset = caretModel.getOffset();
		if (text.length() > offset && text.charAt(offset) == charTyped) {
			caretModel.moveToOffset(offset + 1);
			return Result.STOP;
		}
	}
	return super.beforeCharTyped(charTyped, project, editor, file, fileType);
}
 
Example 10
Source File: SearchAction.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Only make this action visible when text is selected.
 * @param e
 */
@Override
public void update(AnActionEvent e)
{
   final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
   CaretModel caretModel = editor.getCaretModel();
   e.getPresentation().setEnabledAndVisible(caretModel.getCurrentCaret().hasSelection());
}
 
Example 11
Source File: SearchAction.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Convert selected text to a URL friendly string.
 * @param e
 */
@Override
public void actionPerformed(AnActionEvent e)
{
   final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
   CaretModel caretModel = editor.getCaretModel();

   // For searches from the editor, we should also get file type information
   // to help add scope to the search using the Stack overflow search syntax.
   //
   // https://stackoverflow.com/help/searching

   String languageTag = "";
   PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
   if(file != null)
   {
      Language lang = e.getData(CommonDataKeys.PSI_FILE).getLanguage();
      languageTag = "+[" + lang.getDisplayName().toLowerCase() + "]";
   }

   // The update method below is only called periodically so need
   // to be careful to check for selected text
   if(caretModel.getCurrentCaret().hasSelection())
   {
      String query = caretModel.getCurrentCaret().getSelectedText().replace(' ', '+') + languageTag;
      BrowserUtil.browse("https://stackoverflow.com/search?q=" + query);
   }
}
 
Example 12
Source File: ORTypedHandler.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Result beforeCharTyped(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file, @NotNull FileType fileType) {
    if (!(fileType instanceof OclFileType || fileType instanceof OclInterfaceFileType)) {
        return Result.CONTINUE;
    }

    // #62 - don't insert a ) when at the end of a comment
    if (c == ')') {
        Document doc = editor.getDocument();
        PsiDocumentManager.getInstance(project).commitDocument(doc);
        CaretModel caretModel = editor.getCaretModel();


        // * <caret> )
        int offsetBefore = caretModel.getOffset();
        if (offsetBefore < doc.getTextLength()) {
            CharSequence charsSequence = doc.getCharsSequence();
            char c1 = charsSequence.charAt(offsetBefore - 1);
            char c2 = charsSequence.charAt(offsetBefore);
            if (c1 == '*' && c2 == ')') {
                PsiElement leaf = file.findElementAt(offsetBefore);
                if (leaf instanceof PsiComment) {
                    caretModel.moveToOffset(offsetBefore + 1);
                    return Result.STOP;
                }
            }
        }
    }

    return super.beforeCharTyped(c, project, editor, file, fileType);
}
 
Example 13
Source File: SmartIndentingBackspaceHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doCharDeleted(char c, PsiFile file, Editor editor) {
  if (myReplacement == null) {
    return false;
  }

  Document document = editor.getDocument();
  CaretModel caretModel = editor.getCaretModel();
  int endOffset = CharArrayUtil.shiftForward(document.getImmutableCharSequence(), caretModel.getOffset(), " \t");

  document.replaceString(myStartOffset, endOffset, myReplacement);
  caretModel.moveToOffset(myStartOffset + myReplacement.length());

  return true;
}
 
Example 14
Source File: MatchBraceAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Editor editor, DataContext dataContext) {
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return;
  }

  CaretModel caretModel = editor.getCaretModel();
  int offset = caretModel.getOffset();
  CharSequence text = editor.getDocument().getCharsSequence();
  char c = text.charAt(offset);
  if (!OPEN_BRACES.contains(c) && !CLOSE_BRACES.contains(c)) {
    boolean canContinue = false;
    for (offset--; offset >= 0; offset--) {
      c = text.charAt(offset);
      if (OPEN_BRACES.contains(c) || CLOSE_BRACES.contains(c)) {
        canContinue = true;
        caretModel.moveToOffset(offset);
        break;
      }
    }
    if (!canContinue) {
      return;
    }
  }

  if (OPEN_BRACES.contains(c)) {
    CodeBlockUtil.moveCaretToCodeBlockEnd(project, editor, false);
  }
  else if (CLOSE_BRACES.contains(c)) {
    CodeBlockUtil.moveCaretToCodeBlockStart(project, editor, false);
  }
}
 
Example 15
Source File: AbstractIntention.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Nullable
private PsiElement findMatchingElement( @NotNull PsiFile file, @NotNull Editor editor )
{
    CaretModel caretModel = editor.getCaretModel();
    int position = caretModel.getOffset();
    PsiElement element = file.findElementAt( position );
    return findMatchingElement( element );
}
 
Example 16
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
public void performAction(CSharpIntroduceOperation operation)
{
	final PsiFile file = operation.getFile();
	if(!CommonRefactoringUtil.checkReadOnlyStatus(file))
	{
		return;
	}
	final Editor editor = operation.getEditor();
	if(editor.getSettings().isVariableInplaceRenameEnabled())
	{
		final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
		if(templateState != null && !templateState.isFinished())
		{
			return;
		}
	}

	PsiElement element1 = null;
	PsiElement element2 = null;
	final SelectionModel selectionModel = editor.getSelectionModel();
	if(selectionModel.hasSelection())
	{
		element1 = file.findElementAt(selectionModel.getSelectionStart());
		element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
		if(element1 instanceof PsiWhiteSpace)
		{
			int startOffset = element1.getTextRange().getEndOffset();
			element1 = file.findElementAt(startOffset);
		}
		if(element2 instanceof PsiWhiteSpace)
		{
			int endOffset = element2.getTextRange().getStartOffset();
			element2 = file.findElementAt(endOffset - 1);
		}
	}
	else
	{
		if(smartIntroduce(operation))
		{
			return;
		}
		final CaretModel caretModel = editor.getCaretModel();
		final Document document = editor.getDocument();
		int lineNumber = document.getLineNumber(caretModel.getOffset());
		if((lineNumber >= 0) && (lineNumber < document.getLineCount()))
		{
			element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
			element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
		}
	}
	final Project project = operation.getProject();
	if(element1 == null || element2 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	element1 = CSharpRefactoringUtil.getSelectedExpression(project, file, element1, element2);
	if(element1 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	if(!checkIntroduceContext(file, editor, element1))
	{
		return;
	}
	operation.setElement(element1);
	performActionOnElement(operation);
}
 
Example 17
Source File: HaxeIntroduceHandler.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
protected void performAction(HaxeIntroduceOperation operation) {
  final PsiFile file = operation.getFile();
  if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
    return;
  }
  final Editor editor = operation.getEditor();
  if (editor.getSettings().isVariableInplaceRenameEnabled()) {
    final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
    if (templateState != null && !templateState.isFinished()) {
      return;
    }
  }

  PsiElement element1 = null;
  PsiElement element2 = null;
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection()) {
    element1 = file.findElementAt(selectionModel.getSelectionStart());
    element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
  }
  else {
    if (smartIntroduce(operation)) {
      return;
    }
    final CaretModel caretModel = editor.getCaretModel();
    final Document document = editor.getDocument();
    int lineNumber = document.getLineNumber(caretModel.getOffset());
    if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
      element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
      element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
    }
  }
  if (element1 instanceof PsiWhiteSpace) {
    int startOffset = element1.getTextRange().getEndOffset();
    element1 = file.findElementAt(startOffset);
  }
  if (element2 instanceof PsiWhiteSpace) {
    int endOffset = element2.getTextRange().getStartOffset();
    element2 = file.findElementAt(endOffset - 1);
  }


  final Project project = operation.getProject();
  if (element1 == null || element2 == null) {
    showCannotPerformError(project, editor);
    return;
  }

  element1 = HaxeRefactoringUtil.getSelectedExpression(project, file, element1, element2);
  if (!isValidForExtraction(element1)) {
    showCannotPerformError(project, editor);
    return;
  }

  if (!checkIntroduceContext(file, editor, element1)) {
    return;
  }
  operation.setElement(element1);
  performActionOnElement(operation);
}
 
Example 18
Source File: PsiElementBaseIntentionAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
private static PsiElement getElement(@Nonnull Editor editor, @Nonnull PsiFile file) {
  CaretModel caretModel = editor.getCaretModel();
  int position = caretModel.getOffset();
  return file.findElementAt(position);
}
 
Example 19
Source File: ActionPerformer.java    From dummytext-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * @param   event    ActionSystem event
 */
void write(final AnActionEvent event) {
    Editor editor = event.getData(PlatformDataKeys.EDITOR);

    if (editor != null) {
        final Document document = editor.getDocument();

        CaretModel caretModel = editor.getCaretModel();

        for (Caret caret : caretModel.getAllCarets()) {
            boolean hasSelection = caret.hasSelection();
            String selectedText  = caret.getSelectedText();

            String trailingCharacter    = TextualHelper.getTrailingPunctuationMark(selectedText);
            String leadingCharacters    = TextualHelper.getLeadingPreservation(selectedText);

            int amountLines     = 1;
            // applies only when replacing a single-lined selection, can be rounded up
            Integer amountWords = null;

            // Generated dummy text will replace the current selected text
            if (hasSelection && selectedText != null ) {
                int selectionLength = selectedText.length();
                if (selectionLength > 0) {
                    amountLines = TextualHelper.countLines(selectedText);
                    if (amountLines == 1) {
                        amountWords = TextualHelper.getWordCount(selectedText);
                    }
                }
            }

            // Generate and insert / replace selection with dummy text
            String dummyText  = generateText(amountLines, amountWords, leadingCharacters, trailingCharacter, selectedText).toString();

            Integer dummyTextLength = dummyText.length();
            Integer offsetStart;

            if (hasSelection) {
                // Move caret to end of selection
                offsetStart = caret.getSelectionStart();
                int offsetEnd = caret.getSelectionEnd();

                document.replaceString(offsetStart, offsetEnd, dummyText);
                caret.setSelection(offsetStart, offsetStart + dummyTextLength);
            } else {
                // Move caret to end of inserted text
                offsetStart  = caretModel.getOffset();
                dummyText   = dummyText.trim();
                document.insertString(offsetStart, dummyText);
            }
        }

    }
}
 
Example 20
Source File: SearchAction.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public void update(AnActionEvent e) {
    Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
    CaretModel caretModel = editor.getCaretModel();
    e.getPresentation().setEnabledAndVisible(caretModel.getCurrentCaret().hasSelection());
}