Example usage for com.intellij.openapi.editor EditorModificationUtil moveCaretRelatively

List of usage examples for com.intellij.openapi.editor EditorModificationUtil moveCaretRelatively

Introduction

In this page you can find the example usage for com.intellij.openapi.editor EditorModificationUtil moveCaretRelatively.

Prototype

public static void moveCaretRelatively(@NotNull Editor editor, final int caretShift) 

Source Link

Usage

From source file:com.goide.completion.GoKeywordCompletionProvider.java

License:Apache License

@Nullable
public static InsertHandler<LookupElement> createTemplateBasedInsertHandler(@Nonnull String templateId) {
    return (context, item) -> {
        Template template = TemplateSettings.getInstance().getTemplateById(templateId);
        Editor editor = context.getEditor();
        if (template != null) {
            editor.getDocument().deleteString(context.getStartOffset(), context.getTailOffset());
            TemplateManager.getInstance(context.getProject()).startTemplate(editor, template);
        } else {/*from  w w w .  j  ava2s  .c  o  m*/
            int currentOffset = editor.getCaretModel().getOffset();
            CharSequence documentText = editor.getDocument().getImmutableCharSequence();
            if (documentText.length() <= currentOffset || documentText.charAt(currentOffset) != ' ') {
                EditorModificationUtil.insertStringAtCaret(editor, " ");
            } else {
                EditorModificationUtil.moveCaretRelatively(editor, 1);
            }
        }
    };
}

From source file:com.google.bamboo.soy.insight.completion.PostfixInsertHandler.java

License:Apache License

public void handleInsert(InsertionContext context, LookupElement item) {
    Editor editor = context.getEditor();
    Project project = editor.getProject();

    if (project != null) {
        EditorModificationUtil.insertStringAtCaret(editor, closingTagBeforeCaret + closingTagAfterCaret);
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
        EditorModificationUtil.moveCaretRelatively(editor, -closingTagAfterCaret.length());
    }/*  ww w . j a va2  s  .  c om*/
}

From source file:io.ballerina.plugins.idea.completion.BallerinaCompletionUtils.java

License:Open Source License

@NotNull
private static InsertHandler<LookupElement> createTemplateBasedInsertHandler(@NotNull String templateId,
        @Nullable String traileringString) {
    return (context, item) -> {
        Template template = TemplateSettings.getInstance().getTemplateById(templateId);
        Editor editor = context.getEditor();
        if (template != null) {
            editor.getDocument().deleteString(context.getStartOffset(), context.getTailOffset());
            TemplateManager.getInstance(context.getProject()).startTemplate(editor, template);
        } else {//from w w  w. ja v a  2 s.c o  m
            int currentOffset = editor.getCaretModel().getOffset();
            CharSequence documentText = editor.getDocument().getImmutableCharSequence();
            if (documentText.length() <= currentOffset || documentText.charAt(currentOffset) != ' ') {
                if (traileringString != null) {
                    EditorModificationUtil.insertStringAtCaret(editor, traileringString);
                }
            } else {
                EditorModificationUtil.moveCaretRelatively(editor, 1);
            }
        }
    };
}

From source file:io.ballerina.plugins.idea.editor.inserthandlers.BallerinaEnterBetweenBracesHandler.java

License:Open Source License

@Override
public Result postProcessEnter(@NotNull PsiFile file, @NotNull Editor editor,
        @NotNull DataContext dataContext) {
    if (!file.getLanguage().is(BallerinaLanguage.INSTANCE)) {
        return Result.Continue;
    }//  w  w  w  .ja v a2  s.  com
    // We need to save the file before checking. Otherwise issues can occur when we press enter in a string.
    Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());

    // Get the offset of the caret.
    int caretOffset = editor.getCaretModel().getOffset();
    // Get the element at the offset.
    PsiElement element = file.findElementAt(caretOffset);
    // If the element is null, return.
    if (element == null) {
        return Result.Continue;
    }
    // Check whether the semicolon is needed.
    if (needToInsertSemicolon(element)) {
        PsiElement definition = PsiTreeUtil.getParentOfType(element, BallerinaTypeDefinition.class);

        if (definition == null) {
            return Result.Continue;
        }
        // Get the end offset of the type definition.
        int endOffset = definition.getTextRange().getEndOffset();
        // Calculate the caret shift.
        int caretShift = endOffset - caretOffset;
        // Move the caret to the right.
        EditorModificationUtil.moveCaretRelatively(editor, caretShift);
        // Insert the semicolon and move the caret back to the original position.
        EditorModificationUtil.insertStringAtCaret(editor, ";", false, -(caretShift + 1));
        // Commit the document.
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    }

    Document doc = editor.getDocument();
    LogicalPosition position = editor.getCaretModel().getLogicalPosition();
    int lineStartOff = doc.getLineStartOffset(position.line - 1);
    int lineEndOff = doc.getLineEndOffset(position.line - 1);
    // If the previous line ends with left brace.
    if (doc.getText(new TextRange(lineStartOff, lineEndOff)).trim().endsWith("{")) {
        // Adds indentation to the caret.
        EditorModificationUtil.insertStringAtCaret(editor, "    ", false, 4);
        // Commit the document.
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    }

    return Result.Continue;
}

From source file:io.ballerina.plugins.idea.editor.inserthandlers.BallerinaQuotesInsertHandler.java

License:Open Source License

@NotNull
@Override/*from   www  . j a v a2 s  .co m*/
public Result beforeCharTyped(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file,
        @NotNull FileType fileType) {

    if (c != '\"' || !file.getLanguage().is(BallerinaLanguage.INSTANCE)) {
        return Result.CONTINUE;
    }

    // We need to save the file before checking. Otherwise issues can occur when we press enter in a string.
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());

    // Checks whether the cursor is already placed inside a ballerina string.
    int caretOff = editor.getCaretModel().getOffset();
    if (!isInStringLiteral(file, caretOff)) {
        // If the cursor is already placed inside a string, auto closing shouldn't be triggered.
        char prevChar = editor.getDocument().getText(new TextRange(caretOff - 1, caretOff)).charAt(0);
        char nextChar = editor.getDocument().getText(new TextRange(caretOff, caretOff + 1)).charAt(0);

        if (c == prevChar && c == nextChar) {
            EditorModificationUtil.moveCaretRelatively(editor, 1);
            return Result.STOP;
        } else {
            return Result.CONTINUE;
        }
    } else {
        // Adds the closing quotes and places the cursor in-between the quotes.
        EditorModificationUtil.insertStringAtCaret(editor, "\"", false, 0);
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
        return Result.CONTINUE;
    }
}

From source file:io.ballerina.plugins.idea.extensions.client.BallerinaEditorEventManager.java

License:Open Source License

private void prepareAndRunSnippet(String insertText) {
    // Holds variable text (including the snippet syntax) against the starting index.
    List<SnippetVariable> variables = new ArrayList<>();
    // Fetches variables with place holders.
    Matcher varMatcher = Pattern.compile(LSP_SNIPPET_VAR_REGEX).matcher(insertText);
    while (varMatcher.find()) {
        variables.add(new SnippetVariable(varMatcher.group(), varMatcher.start(), varMatcher.end()));
    }/*from   w ww  .  j  a  v  a  2  s .  c  om*/
    variables.sort(Comparator.comparingInt(o -> o.startIndex));

    final String[] finalInsertText = { insertText };
    variables.forEach(var -> finalInsertText[0] = finalInsertText[0].replace(var.lspSnippetText, "$"));

    String[] splittedInsertText = finalInsertText[0].split("\\$");
    finalInsertText[0] = String.join("", splittedInsertText);

    // Creates and constructs a intellij live template using the LSP snippet text.
    TemplateImpl template = (TemplateImpl) TemplateManager.getInstance(getProject())
            .createTemplate(finalInsertText[0], "lsp4intellij");

    final int[] varIndex = { 0 };
    variables.forEach(var -> {
        template.addTextSegment(splittedInsertText[varIndex[0]]);
        template.addVariable(varIndex[0] + "_" + var.variableValue, new TextExpression(var.variableValue),
                new TextExpression(var.variableValue), true, false);
        varIndex[0]++;
    });
    template.addTextSegment(splittedInsertText[splittedInsertText.length - 1]);
    template.setInline(true);
    EditorModificationUtil.moveCaretRelatively(editor, -template.getTemplateText().length());

    // Runs the constructed live template.
    isSnippetRunning = true;
    TemplateManager.getInstance(getProject()).startTemplate(editor, template, new TemplateEditingListener() {
        @Override
        public void beforeTemplateFinished(@NotNull TemplateState state, Template template) {
        }

        @Override
        public void templateFinished(@NotNull Template template, boolean brokenOff) {
            isSnippetRunning = false;
        }

        @Override
        public void templateCancelled(Template template) {
            isSnippetRunning = false;
        }

        @Override
        public void currentVariableChanged(@NotNull TemplateState templateState, Template template,
                int oldIndex, int newIndex) {
        }

        @Override
        public void waitingForInput(Template template) {

        }
    });
}

From source file:io.ballerina.plugins.idea.formatter.BallerinaEnterBetweenBracesHandler.java

License:Open Source License

@Override
public Result postProcessEnter(@NotNull PsiFile file, @NotNull Editor editor,
        @NotNull DataContext dataContext) {
    if (!file.getLanguage().is(BallerinaLanguage.INSTANCE)) {
        return Result.Continue;
    }/*from   w w w . j  av a2s . c  o m*/
    // We need to save the file before checking. Otherwise issues can occur when we press enter in a string.
    Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());

    // Get the offset of the caret.
    int caretOffset = editor.getCaretModel().getOffset();
    // Get the element at the offset.
    PsiElement element = file.findElementAt(caretOffset);
    // If the element is null, return.
    if (element == null) {
        return Result.Continue;
    }
    // Check whether the semicolon is needed.
    if (needToInsertSemicolon(element)) {
        PsiElement definition = PsiTreeUtil.getParentOfType(element, BallerinaTypeDefinition.class);

        if (definition == null) {
            return Result.Continue;
        }
        // Get the end offset of the type definition.
        int endOffset = definition.getTextRange().getEndOffset();
        // Calculate the caret shift.
        int caretShift = endOffset - caretOffset;
        // Move the caret to the right.
        EditorModificationUtil.moveCaretRelatively(editor, caretShift);
        // Insert the semicolon and move the caret back to the original position.
        EditorModificationUtil.insertStringAtCaret(editor, ";", false, -(caretShift + 1));
        // Commit the document.
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    }
    return Result.Continue;
}

From source file:org.apache.camel.idea.completion.CamelSmartCompletionEndpointValue.java

License:Apache License

/**
 * We need special logic to preserve the suffix when the user selects an option to be inserted
 * and also to remove the old value when pressing enter to a choice
 *///from  w ww. j  ava  2  s .c om
@NotNull
private static LookupElementBuilder addInsertHandler(final Editor editor, final String suffix,
        final LookupElementBuilder builder, final boolean xmlMode) {
    return builder.withInsertHandler(new InsertHandler<LookupElement>() {
        @Override
        public void handleInsert(InsertionContext context, LookupElement item) {
            // enforce using replace select char as we want to replace any existing option
            if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
                // we still want to keep the suffix because they are other options
                String value = suffix;
                int pos = value.indexOf("&");
                if (pos > -1) {
                    // strip out first part of suffix until next option
                    value = value.substring(pos);
                }
                EditorModificationUtil.insertStringAtCaret(editor, value);
                // and move cursor back again
                int offset = -1 * value.length();
                EditorModificationUtil.moveCaretRelatively(editor, offset);
            } else if (context.getCompletionChar() == Lookup.NORMAL_SELECT_CHAR) {
                // we want to remove the old option (which is the first value in the suffix)
                String cut = suffix;
                int pos = suffix.indexOf("&");
                if (pos > 0) {
                    cut = cut.substring(0, pos);
                }
                int len = cut.length();
                if (len > 0) {
                    int offset = editor.getCaretModel().getOffset();
                    editor.getDocument().deleteString(offset, offset + len);
                }
            }
        }
    });
}

From source file:org.apache.camel.idea.completion.endpoint.CamelSmartCompletionEndpointOptions.java

License:Apache License

/**
 * We need special logic to determine when it should insert "=" at the end of the options
 *///from  w  w w.  j  a  v a 2s. co m
@NotNull
private static LookupElementBuilder addInsertHandler(final Editor editor, final LookupElementBuilder builder,
        String suffix) {
    return builder.withInsertHandler((context, item) -> {
        // enforce using replace select char as we want to replace any existing option
        if (context.getCompletionChar() == Lookup.NORMAL_SELECT_CHAR) {
            int endSelectOffBy = 0;
            if (context.getFile() instanceof PropertiesFileImpl) {
                //if it's a property file the PsiElement does not start and end with an quot
                endSelectOffBy = 1;
            }
            final char text = context.getDocument().getCharsSequence()
                    .charAt(context.getSelectionEndOffset() - endSelectOffBy);
            if (text != '=') {
                EditorModificationUtil.insertStringAtCaret(editor, "=");
            }
        } else if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
            // we still want to keep the suffix because they are other options
            String value = suffix;
            int pos = value.indexOf("&");
            if (pos > -1) {
                // strip out first part of suffix until next option
                value = value.substring(pos);
            }
            EditorModificationUtil.insertStringAtCaret(editor, "=" + value);
            // and move cursor back again
            int offset = -1 * value.length();
            EditorModificationUtil.moveCaretRelatively(editor, offset);
        }

    });
}

From source file:org.apache.camel.idea.completion.endpoint.CamelSmartCompletionEndpointValue.java

License:Apache License

/**
 * We need special logic to preserve the suffix when the user selects an option to be inserted
 * and also to remove the old value when pressing enter to a choice
 *//*from   w  w  w.  j  ava  2 s. c  o m*/
@NotNull
private static LookupElementBuilder addInsertHandler(final Editor editor, final String suffix,
        final LookupElementBuilder builder, boolean xmlMode) {
    return builder.withInsertHandler((context, item) -> {
        // enforce using replace select char as we want to replace any existing option
        int pos;
        String separator;
        if (xmlMode) {
            pos = suffix.indexOf("&amp;");
            separator = "&amp;";
        } else {
            pos = suffix.indexOf("&");
            separator = "&";
        }

        if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
            // we still want to keep the suffix because they are other options
            String value = suffix;
            if (pos > -1) {
                // strip out first part of suffix until next option
                value = value.substring(pos);
            }
            EditorModificationUtil.insertStringAtCaret(editor, value);
            // and move cursor back again
            int offset = -1 * value.length();
            EditorModificationUtil.moveCaretRelatively(editor, offset);
        } else if (context.getCompletionChar() == Lookup.NORMAL_SELECT_CHAR) {
            // we want to remove the old option (which is the first value in the suffix)
            String cut = suffix;
            if (pos > 0) {
                cut = cut.substring(0, pos);
            }
            int len = cut.length();
            if (len > 0 && pos != 0) {
                int offset = editor.getCaretModel().getOffset();
                editor.getDocument().deleteString(offset, offset + len);
            }
        }
    });
}