com.intellij.openapi.editor.CaretModel Java Examples

The following examples show how to use com.intellij.openapi.editor.CaretModel. 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: 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 #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: 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 #4
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 #5
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 #6
Source File: OperatorCompletionAction.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    final Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    final int offset = caretModel.getOffset();
    new PopupChooserBuilder(QUERY_OPERATOR_LIST)
            .setMovable(false)
            .setCancelKeyEnabled(true)
            .setItemChoosenCallback(new Runnable() {
                public void run() {
                    final String selectedQueryOperator = (String) QUERY_OPERATOR_LIST.getSelectedValue();
                    if (selectedQueryOperator == null) return;

                    new WriteCommandAction(project, MONGO_OPERATOR_COMPLETION) {
                        @Override
                        protected void run(@NotNull Result result) throws Throwable {
                            document.insertString(offset, selectedQueryOperator);
                        }
                    }.execute();
                }
            })
            .createPopup()
            .showInBestPositionFor(editor);
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: CustomRenameHandlerTest.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldRenameWhenElementIsNotPresentInDataContext() throws Exception {
    CaretModel caretModel = mock(CaretModel.class);
    PsiFile file = mock(PsiFile.class);

    when(dataContext.getData(CommonDataKeys.PSI_ELEMENT.getName())).thenReturn(null);
    when(dataContext.getData(CommonDataKeys.EDITOR.getName())).thenReturn(editor);
    when(editor.getCaretModel()).thenReturn(caretModel);
    when(caretModel.getOffset()).thenReturn(0);
    when(dataContext.getData(CommonDataKeys.PSI_FILE.getName())).thenReturn(file);
    when(file.findElementAt(0)).thenReturn(mock(SpecStepImpl.class));

    boolean isAvailable = new CustomRenameHandler().isAvailableOnDataContext(dataContext);
    assertTrue("Should rename when element is not present in DataContext. Expected: true, Actual: false", isAvailable);

    when(file.findElementAt(0)).thenReturn(mock(ConceptStepImpl.class));
    isAvailable = new CustomRenameHandler().isAvailableOnDataContext(dataContext);
    assertTrue("Should rename when element is not present in DataContext. Expected: true, Actual: false", isAvailable);
}
 
Example #13
Source File: AddArgumentFixTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void createAddMethodCallFix() {
  testHelper.getPsiClass(
      classes -> {
        // Setup test environment
        PsiClass cls = classes.get(0);
        PsiMethodCallExpression call =
            PsiTreeUtil.findChildOfType(cls, PsiMethodCallExpression.class);
        Project project = testHelper.getFixture().getProject();
        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        Editor editor = mock(Editor.class);
        when(editor.getCaretModel()).thenReturn(mock(CaretModel.class));

        IntentionAction fix =
            AddArgumentFix.createAddMethodCallFix(call, "ClassName", "methodName", factory);

        assertThat(call.getArgumentList().getExpressions()[0].getText())
            .isNotEqualTo("ClassName.methodName()");
        fix.invoke(project, editor, testHelper.getFixture().getFile());
        assertThat(call.getArgumentList().getExpressions()[0].getText())
            .isEqualTo("ClassName.methodName()");
        return true;
      },
      "RequiredPropAnnotatorTest.java");
}
 
Example #14
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 #15
Source File: CustomRenameHandlerTest.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldRenameWhenPsiFileIsNotPresentInDataContext() throws Exception {
    CaretModel caretModel = mock(CaretModel.class);

    when(dataContext.getData(CommonDataKeys.PSI_ELEMENT.getName())).thenReturn(null);
    when(dataContext.getData(CommonDataKeys.EDITOR.getName())).thenReturn(editor);
    when(editor.getCaretModel()).thenReturn(caretModel);
    when(caretModel.getOffset()).thenReturn(0);
    when(dataContext.getData(CommonDataKeys.PSI_FILE.getName())).thenReturn(null);

    boolean isAvailable = new CustomRenameHandler().isAvailableOnDataContext(dataContext);
    assertFalse("Should rename when psi file is not present. Expected: false, Actual: true", isAvailable);
}
 
Example #16
Source File: CurrentLineMarker.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void attach(EditorSource editorSource) {
  if (myEditor != null) hide();
  myEditor = editorSource.getEditor();
  if (myEditor == null) return;
  final CaretModel caretModel = myEditor.getCaretModel();
  caretModel.addCaretListener(this);
  editorSource.addDisposable(new Disposable() {
    @Override
    public void dispose() {
      caretModel.removeCaretListener(CurrentLineMarker.this);
    }
  });
}
 
Example #17
Source File: BookmarkManagerTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void checkBookmarkNavigation(Bookmark bookmark) {
  int line = bookmark.getLine();
  int anotherLine = line;
  if (line > 0) {
    anotherLine--;
  }
  else {
    anotherLine++;
  }
  CaretModel caretModel = myEditor.getCaretModel();
  caretModel.moveToLogicalPosition(new LogicalPosition(anotherLine, 0));
  bookmark.navigate(true);
  assertEquals(line, caretModel.getLogicalPosition().line);
}
 
Example #18
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 #19
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 #20
Source File: KillToWordEndAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  Document document = editor.getDocument();
  if (caretOffset >= document.getTextLength()) {
    return;
  }

  int caretLine = caretModel.getLogicalPosition().line;
  int lineEndOffset = document.getLineEndOffset(caretLine);
  CharSequence text = document.getCharsSequence();
  boolean camel = editor.getSettings().isCamelWords();
  for (int i = caretOffset + 1; i < lineEndOffset; i++) {
    if (EditorActionUtil.isWordEnd(text, i, camel)) {
      KillRingUtil.cut(editor, caretOffset, i);
      return;
    }
  }
  
  int end = lineEndOffset;
  if (caretLine < document.getLineCount() - 1) {
    // No word end found between the current position and line end, hence, remove line feed sign if possible.
    end++;
  }

  if (end > caretOffset) {
    KillRingUtil.cut(editor, caretOffset, end);
  }
}
 
Example #21
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 #22
Source File: EditorAPITextPositionTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private void setUpCaretMock() {
  caret = EasyMock.createNiceMock(Caret.class);

  CaretModel caretModel = EasyMock.createNiceMock(CaretModel.class);
  EasyMock.expect(caretModel.getPrimaryCaret()).andStubReturn(caret);
  EasyMock.replay(caretModel);

  EasyMock.expect(editor.getCaretModel()).andStubReturn(caretModel);
}
 
Example #23
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns whether the given selection range represent a backwards selection in the given editor.
 *
 * <p>A backwards selection is defined by the start of the selection being located before the end
 * of the selection. This is checked by using the caret position in the editor.
 *
 * <p>Returns <code>false</code> as the default value if the selection start matches the selection
 * end or the caret position in the editor matches neither the start nor the end of the selection
 * range.
 *
 * @param editor the editor for the selection
 * @param selectionStart the selection start
 * @param selectionEnd the selection end
 * @return whether the given selection range represent a backwards selection in the given editor
 *     or <code>false</code> if the selection start matches the selection end or the caret
 *     position in the editor matches neither the start nor the end of the selection range.
 */
private static boolean isBackwardsSelection(
    @NotNull Editor editor, int selectionStart, int selectionEnd) {
  if (selectionStart == selectionEnd) {
    return false;
  }

  CaretModel caretModel = editor.getCaretModel();

  Caret caret = caretModel.getPrimaryCaret();

  int caretOffset = caret.getOffset();

  if (caretOffset == selectionEnd) {
    return false;
  } else if (caretOffset == selectionStart) {
    return true;
  } else {
    VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument());

    log.warn(
        "Encountered caret for file "
            + file
            + " which is located neither at the start nor at the end of the selection."
            + " Returning 'isBackwardsSelection=false' by default - caret offset: "
            + caretOffset
            + ", selection start: "
            + selectionStart
            + ", selection end: "
            + selectionEnd);

    return false;
  }
}
 
Example #24
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 #25
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 #26
Source File: SettingsPanel.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
public void setPreviewText(@Nonnull String text) {
    final CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(null, () -> {
        final Application application = ApplicationManager.getApplication();
        application.runWriteAction(() -> {
            previewDocument.replaceString(INITIAL_OFFSET, previewDocument.getTextLength(), text);

            final int textLength = previewDocument.getTextLength();
            final CaretModel caret = previewEditor.getCaretModel();
            if (caret.getOffset() >= textLength) {
                caret.moveToOffset(textLength);
            }
        });
    }, null, null);
}
 
Example #27
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 #28
Source File: IncrementAction.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
public IncrementAction(boolean setupHandler) {
	super(null);
	if (setupHandler) {
		this.setupHandler(new EditorWriteActionHandler(true) {

			@Override
			public void executeWriteAction(Editor editor, DataContext dataContext) {
				MyApplicationService.setAction(getActionClass());

				// Column mode not supported
				if (editor.isColumnMode()) {
					return;
				}
				final CaretModel caretModel = editor.getCaretModel();

				final int line = caretModel.getLogicalPosition().line;
				final int column = caretModel.getLogicalPosition().column;
				int caretOffset = caretModel.getOffset();

				final SelectionModel selectionModel = editor.getSelectionModel();
				boolean hasSelection = selectionModel.hasSelection();
				if (hasSelection == false) {
					selectionModel.selectLineAtCaret();
				}
				final String selectedText = selectionModel.getSelectedText();

				if (selectedText != null) {
					final String newText = processSelection(selectedText);
					applyChanges(editor, caretModel, line, column, selectionModel, hasSelection, selectedText, newText,
						caretOffset);
				}
			}

		});

	}
}
 
Example #29
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 #30
Source File: DecrementAction.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
public DecrementAction() {
	super(null);
	this.setupHandler(new EditorWriteActionHandler(true) {
		@Override
		public void executeWriteAction(Editor editor, DataContext dataContext) {
			MyApplicationService.setAction(getActionClass());

			// Column mode not supported
			if (editor.isColumnMode()) {
				return;
			}
			final CaretModel caretModel = editor.getCaretModel();

			final int line = caretModel.getLogicalPosition().line;
			final int column = caretModel.getLogicalPosition().column;
			int caretOffset = caretModel.getOffset();

			final SelectionModel selectionModel = editor.getSelectionModel();
			boolean hasSelection = selectionModel.hasSelection();
			if (hasSelection == false) {
				selectionModel.selectLineAtCaret();
			}
			final String selectedText = selectionModel.getSelectedText();

			if (selectedText != null) {
				String[] textParts = StringUtil.splitPreserveAllTokens(selectedText,
					DuplicatUtils.SIMPLE_NUMBER_REGEX);
				for (int i = 0; i < textParts.length; i++) {
					textParts[i] = DuplicatUtils.simpleDec(textParts[i]);
				}

				final String newText = StringUtils.join(textParts);
				applyChanges(editor, caretModel, line, column, selectionModel, hasSelection, newText, caretOffset);
			}
		}
	});
}