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

The following examples show how to use com.intellij.openapi.editor.CaretModel#getOffset() . 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: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
Source File: ReciteWords.java    From ReciteWords with MIT License 5 votes vote down vote up
public String getCurrentWords(Editor editor) {
    Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int lineNum = document.getLineNumber(caretOffset);
    int lineStartOffset = document.getLineStartOffset(lineNum);
    int lineEndOffset = document.getLineEndOffset(lineNum);
    String lineContent = document.getText(new TextRange(lineStartOffset, lineEndOffset));
    char[] chars = lineContent.toCharArray();
    int start = 0, end = 0, cursor = caretOffset - lineStartOffset;

    if (!Character.isLetter(chars[cursor])) {
        Logger.warn("Caret not in a word");
        return null;
    }

    for (int ptr = cursor; ptr >= 0; ptr--) {
        if (!Character.isLetter(chars[ptr])) {
            start = ptr + 1;
            break;
        }
    }

    int lastLetter = 0;
    for (int ptr = cursor; ptr < lineEndOffset - lineStartOffset; ptr++) {
        lastLetter = ptr;
        if (!Character.isLetter(chars[ptr])) {
            end = ptr;
            break;
        }
    }
    if (end == 0) {
        end = lastLetter + 1;
    }

    String ret = new String(chars, start, end-start);
    Logger.info("Selected words: " + ret);
    return ret;
}
 
Example 15
Source File: GoogleTranslation.java    From GoogleTranslation with Apache License 2.0 5 votes vote down vote up
private String getCurrentWords(Editor editor) {
    Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int lineNum = document.getLineNumber(caretOffset);
    int lineStartOffset = document.getLineStartOffset(lineNum);
    int lineEndOffset = document.getLineEndOffset(lineNum);
    String lineContent = document.getText(new TextRange(lineStartOffset, lineEndOffset));
    char[] chars = lineContent.toCharArray();
    int start = 0, end = 0, cursor = caretOffset - lineStartOffset;

    if (!Character.isLetter(chars[cursor])) {
        return null;
    }

    for (int ptr = cursor; ptr >= 0; ptr--) {
        if (!Character.isLetter(chars[ptr])) {
            start = ptr + 1;
            break;
        }
    }

    int lastLetter = 0;
    for (int ptr = cursor; ptr < lineEndOffset - lineStartOffset; ptr++) {
        lastLetter = ptr;
        if (!Character.isLetter(chars[ptr])) {
            end = ptr;
            break;
        }
    }
    if (end == 0) {
        end = lastLetter + 1;
    }

    return new String(chars, start, end - start);
}
 
Example 16
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 17
Source File: SmartIndentingBackspaceHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void doBeforeCharDeleted(char c, PsiFile file, Editor editor) {
  Project project = file.getProject();
  Document document = editor.getDocument();
  CharSequence charSequence = document.getImmutableCharSequence();
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  LogicalPosition pos = caretModel.getLogicalPosition();
  int lineStartOffset = document.getLineStartOffset(pos.line);
  int beforeWhitespaceOffset = CharArrayUtil.shiftBackward(charSequence, caretOffset - 1, " \t") + 1;
  if (beforeWhitespaceOffset != lineStartOffset) {
    myReplacement = null;
    return;
  }
  PsiDocumentManager.getInstance(project).commitDocument(document);
  CodeStyleFacade codeStyleFacade = CodeStyleFacade.getInstance(project);
  myReplacement = codeStyleFacade.getLineIndent(document, lineStartOffset);
  if (myReplacement == null) {
    return;
  }
  int tabSize = codeStyleFacade.getTabSize(file.getFileType());
  int targetColumn = getWidth(myReplacement, tabSize);
  int endOffset = CharArrayUtil.shiftForward(charSequence, caretOffset, " \t");
  LogicalPosition logicalPosition = caretOffset < endOffset ? editor.offsetToLogicalPosition(endOffset) : pos;
  int currentColumn = logicalPosition.column;
  if (currentColumn > targetColumn) {
    myStartOffset = lineStartOffset;
  }
  else if (logicalPosition.line == 0) {
    myStartOffset = 0;
    myReplacement = "";
  }
  else {
    int prevLineEndOffset = document.getLineEndOffset(logicalPosition.line - 1);
    myStartOffset = CharArrayUtil.shiftBackward(charSequence, prevLineEndOffset - 1, " \t") + 1;
    if (myStartOffset != document.getLineStartOffset(logicalPosition.line - 1)) {
      int spacing = CodeStyleManager.getInstance(project).getSpacing(file, endOffset);
      myReplacement = StringUtil.repeatSymbol(' ', Math.max(0, spacing));
    }
  }
}
 
Example 18
Source File: SuppressIntentionAction.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: 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 20
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);
}