Java Code Examples for com.intellij.openapi.editor.CaretModel#moveToOffset()

The following examples show how to use com.intellij.openapi.editor.CaretModel#moveToOffset() . 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: 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 2
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 3
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 4
Source File: DialogEditorAction.java    From idea-latex with MIT License 6 votes vote down vote up
@NotNull
protected Runnable getDialogAction(@NotNull final T dialog, @NotNull final TextEditor editor) {
    return new Runnable() {
        @Override
        public void run() {
            final Document document = editor.getEditor().getDocument();
            final CaretModel caretModel = editor.getEditor().getCaretModel();
            final String content = getContent(dialog);

            int offset = caretModel.getOffset();

            document.insertString(offset, content);
            caretModel.moveToOffset(offset + content.length());
        }
    };
}
 
Example 5
Source File: WrapEditorAction.java    From idea-latex with MIT License 6 votes vote down vote up
/**
 * Wraps selection.
 *
 * @param editor Current editor.
 */
private void wrap(@NotNull TextEditor editor) {
    final Document document = editor.getEditor().getDocument();
    final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
    final CaretModel caretModel = editor.getEditor().getCaretModel();

    final int start = selectionModel.getSelectionStart();
    final int end = selectionModel.getSelectionEnd();
    final String text = StringUtil.notNullize(selectionModel.getSelectedText());

    String newText = getLeftText() + text + getRightText();
    int newStart = start + getLeftText().length();
    int newEnd = StringUtil.isEmpty(text) ? newStart : end + getLeftText().length();

    document.replaceString(start, end, newText);
    selectionModel.setSelection(newStart, newEnd);
    caretModel.moveToOffset(newEnd);
}
 
Example 6
Source File: WrapEditorAction.java    From idea-latex with MIT License 6 votes vote down vote up
/**
 * Unwraps selection.
 *
 * @param editor  Current editor.
 * @param matched Matched PSI element.
 */
private void unwrap(@NotNull final TextEditor editor, @NotNull final PsiElement matched) {
    final Document document = editor.getEditor().getDocument();
    final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
    final CaretModel caretModel = editor.getEditor().getCaretModel();

    final int start = matched.getTextRange().getStartOffset();
    final int end = matched.getTextRange().getEndOffset();
    final String text = StringUtil.notNullize(matched.getText());

    String newText = StringUtil.trimEnd(StringUtil.trimStart(text, getLeftText()), getRightText());
    int newStart = selectionModel.getSelectionStart() - getLeftText().length();
    int newEnd = selectionModel.getSelectionEnd() - getLeftText().length();

    document.replaceString(start, end, newText);

    selectionModel.setSelection(newStart, newEnd);
    caretModel.moveToOffset(newEnd);
}
 
Example 7
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 8
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 9
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 10
Source File: SelectionQuotingTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Result beforeCharTyped(final char charTyped, final Project project, final Editor editor, final PsiFile file, final FileType fileType) {
  // TODO[oleg] remove this hack when API changes
  if (myReplacedTextRange != null) {
    if (myReplacedTextRange.getEndOffset() <= editor.getDocument().getTextLength()) {
      if (myRestoreStickySelection && editor instanceof EditorEx) {
        EditorEx editorEx = (EditorEx)editor;
        CaretModel caretModel = editorEx.getCaretModel();
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getStartOffset() : myReplacedTextRange.getEndOffset());
        editorEx.setStickySelection(true);
        caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
      }
      else {
        if (myLtrSelection || editor instanceof EditorWindow) {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getStartOffset(), myReplacedTextRange.getEndOffset());
        }
        else {
          editor.getSelectionModel().setSelection(myReplacedTextRange.getEndOffset(), myReplacedTextRange.getStartOffset());
        }
        if (Registry.is("editor.smarterSelectionQuoting")) {
          editor.getCaretModel().moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
        }
      }
    }
    myReplacedTextRange = null;
    return Result.STOP;
  }
  return Result.CONTINUE;
}
 
Example 11
Source File: TailType.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected static int moveCaret(final Editor editor, final int tailOffset, final int delta) {
  final CaretModel model = editor.getCaretModel();
  if (model.getOffset() == tailOffset) {
    model.moveToOffset(tailOffset + delta);
  }
  return tailOffset + delta;
}
 
Example 12
Source File: MyActionUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void moveCursor(Editor editor, int cursorOffset) {
	CaretModel caretModel = editor.getCaretModel();
	caretModel.moveToOffset(cursorOffset);
	ScrollingModel scrollingModel = editor.getScrollingModel();
	scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE);
	editor.getContentComponent().requestFocus();
}
 
Example 13
Source File: ReplaceAfterJumpCommand.java    From emacsIDEAs with Apache License 2.0 5 votes vote down vote up
@Override
public void afterJump() {
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {

            TextRange tr = EditorUtils.getRangeOf(_selectorClass, _te);
            if (tr != null)
            {
                _te.getSelectionModel().setSelection(tr.getStartOffset(), tr.getEndOffset());
                EditorUtils.deleteRange(tr, _te);
            }

            CaretModel targetCaret = _te.getCaretModel();

            if (_addNewLineBeforePaste) {
                _te.getDocument().insertString(targetCaret.getOffset(), "\n");
                targetCaret.moveToOffset(targetCaret.getOffset() + 1);
            }

            TextRange[] textRanges = EditorCopyPasteHelperImpl.getInstance().pasteFromClipboard(_te);

            if (_config._needSelectTextAfterJump) {
                int caret = textRanges[0].getStartOffset() + _caretOffsetFromSelectRangeStartBeforeJump;
                targetCaret.moveToOffset(caret);
                EditorUtils.selectRangeOf(_selectorClass, _te);
            }
        }
    };

    AppUtil.runWriteAction(runnable, _se);
}
 
Example 14
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 15
Source File: FilterInsertHandler.java    From intellij-latte with MIT License 5 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) {
		PsiElement parent = element.getParent();

		LatteFilterSettings filter = null;
		if (parent instanceof LatteMacroModifier) {
			String modifierName = ((LatteMacroModifier) parent).getModifierName();
			filter = LatteConfiguration.getInstance(element.getProject()).getFilter(modifierName);
		}

		Editor editor = context.getEditor();
		if (filter != null && filter.getModifierInsert() != null && filter.getModifierInsert().length() > 0) {
			CaretModel caretModel = editor.getCaretModel();
			String text = editor.getDocument().getText();

			int offset = caretModel.getOffset();

			int lastBraceOffset = text.indexOf(":", offset);
			int endOfLineOffset = text.indexOf("\n", offset);

			if (endOfLineOffset == -1) {
				endOfLineOffset = text.length();
			}
			if (lastBraceOffset == -1 || lastBraceOffset > endOfLineOffset) {
				EditorModificationUtil.insertStringAtCaret(editor, filter.getModifierInsert());
				caretModel.moveToOffset(offset + 1);
			}
		}
		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example 16
Source File: PhpVariableInsertHandler.java    From intellij-latte with MIT License 5 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) {
		PsiElement parent = element.getParent();
		if (!(parent instanceof Variable) && !element.getText().startsWith("$")) {
			Editor editor = context.getEditor();
			CaretModel caretModel = editor.getCaretModel();
			int offset = caretModel.getOffset();
			caretModel.moveToOffset(element.getTextOffset() + (PhpPsiUtil.isOfType(parent, PhpElementTypes.CAST_EXPRESSION) ? 1 : 0));
			EditorModificationUtil.insertStringAtCaret(editor, "$");
			caretModel.moveToOffset(offset + 1);
			PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
		}
	}
}
 
Example 17
Source File: CSharpTypeLikeLookupElement.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
@RequiredWriteAction
public void handleInsert(InsertionContext context)
{
	super.handleInsert(context);

	if(myAfterNew)
	{
		context.commitDocument();

		PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(context.getDocument());

		boolean hasParameters = false;
		if(myExtractor != DotNetGenericExtractor.EMPTY)
		{
			PsiElement psiElement = getPsiElement();
			if(psiElement instanceof CSharpTypeDeclaration)
			{
				DotNetNamedElement[] members = ((CSharpTypeDeclaration) psiElement).getMembers();
				for(DotNetNamedElement member : members)
				{
					if(member instanceof CSharpConstructorDeclaration)
					{
						int length = ((CSharpConstructorDeclaration) member).getParameters().length;
						if(length > 0)
						{
							hasParameters = true;
							break;
						}
					}
				}
			}
			else if(CSharpMethodUtil.isDelegate(psiElement))
			{
				hasParameters = true;
			}
		}

		CaretModel caretModel = context.getEditor().getCaretModel();
		int oldCaretOffset = caretModel.getOffset();

		ParenthesesInsertHandler.getInstance(true).handleInsert(context, this);

		if(!hasParameters)
		{
			caretModel.moveToOffset(oldCaretOffset + 2);
		}
	}
}
 
Example 18
Source File: MacroInsertHandler.java    From intellij-latte with MIT License 4 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) {
		PsiElement parent = element.getParent();

		String spacesBefore = "";
		boolean resolvePairMacro = false;
		boolean lastError = parent.getLastChild().getNode().getElementType() == TokenType.ERROR_ELEMENT;
		String macroName = null;
		LatteTagSettings macro = null;
		if (lastError && element.getNode().getElementType() == LatteTypes.T_MACRO_NAME) {
			macroName = element.getText();
			macro = LatteConfiguration.getInstance(element.getProject()).getTag(macroName);

		} else if (parent instanceof LatteMacroTag) {
			macroName = ((LatteMacroTag) parent).getMacroName();
			macro = LatteConfiguration.getInstance(element.getProject()).getTag(macroName);
		}

		boolean isCloseTag = parent instanceof LatteMacroCloseTag;
		if (!isCloseTag && macro != null && macro.getType() == LatteTagSettings.Type.PAIR) {
			resolvePairMacro = true;
		}

		if (macroName != null) {
			if (resolvePairMacro && macro.isMultiLine()) {
				spacesBefore += LatteUtil.getSpacesBeforeCaret(context.getEditor());
			}

			Editor editor = context.getEditor();
			CaretModel caretModel = editor.getCaretModel();
			String text = editor.getDocument().getText();

			int spaceInserted = 0;
			int offset = caretModel.getOffset();

			if (macro != null && !isCloseTag && macro.hasParameters() && !LatteUtil.isStringAtCaret(editor, " ")) {
				EditorModificationUtil.insertStringAtCaret(editor, " ");
				spaceInserted = 1;
			}

			int lastBraceOffset = text.indexOf("}", offset);
			int endOfLineOffset = text.indexOf("\n", offset);

			if (endOfLineOffset == -1) {
				endOfLineOffset = text.length();
			}
			if (lastBraceOffset == -1 || lastBraceOffset > endOfLineOffset) {
				caretModel.moveToOffset(endOfLineOffset + spaceInserted);
				EditorModificationUtil.insertStringAtCaret(editor, "}");
				lastBraceOffset = endOfLineOffset;
				endOfLineOffset++;
			}

			if (resolvePairMacro) {
				String endTag = "";
				if (macro.isMultiLine()) {
					endTag += "\n\n" + spacesBefore;
				}
				endTag += "{/" + macroName + "}";

				int endTagOffset = text.indexOf(endTag, offset);
				if (endTagOffset == -1 || endTagOffset > endOfLineOffset) {
					caretModel.moveToOffset(lastBraceOffset + spaceInserted + 1);
					EditorModificationUtil.insertStringAtCaret(editor, endTag);
				}
			}

			caretModel.moveToOffset(offset + 1);
			PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
		}
	}
}
 
Example 19
Source File: RunTest.java    From phpstorm-plugin with MIT License 4 votes vote down vote up
public void testGetCurrentTestMethod() {
    Run action = new Run();
    TestActionEvent e = new TestActionEvent(action);
    CaretModel cursor = CommonDataKeys.EDITOR.getData(e.getDataContext()).getCaretModel();

    // Ensure cursor is at position 0
    cursor.moveToOffset(0);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run test : TestWithMethods", e.getPresentation().getText());

    // Move cursor on the class declaration
    cursor.moveToOffset(190);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run test : TestWithMethods", e.getPresentation().getText());

    // Move cursor on method declaration: beforeTestMethod
    cursor.moveToOffset(230);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run test : TestWithMethods", e.getPresentation().getText());

    // Move cursor in method body: beforeTestMethod
    cursor.moveToOffset(345);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run test : TestWithMethods", e.getPresentation().getText());

    // Move cursor on method declaration: test__construct_bad
    cursor.moveToOffset(420);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run TestWithMethods::test__construct_bad", e.getPresentation().getText());

    // Move cursor in method body: test__construct_bad
    cursor.moveToOffset(580);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run TestWithMethods::test__construct_bad", e.getPresentation().getText());

    // Move cursor on method declaration: test__construct_ok
    cursor.moveToOffset(740);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run TestWithMethods::test__construct_ok", e.getPresentation().getText());

    // Move cursor in method body: test__construct_ok
    cursor.moveToOffset(815);
    action.update(e);
    assertTrue(e.getPresentation().isEnabledAndVisible());
    assertEquals("atoum - run TestWithMethods::test__construct_ok", e.getPresentation().getText());
}