Example usage for com.intellij.openapi.actionSystem IdeActions ACTION_EDITOR_ENTER

List of usage examples for com.intellij.openapi.actionSystem IdeActions ACTION_EDITOR_ENTER

Introduction

In this page you can find the example usage for com.intellij.openapi.actionSystem IdeActions ACTION_EDITOR_ENTER.

Prototype

String ACTION_EDITOR_ENTER

To view the source code for com.intellij.openapi.actionSystem IdeActions ACTION_EDITOR_ENTER.

Click Source Link

Usage

From source file:com.google.idea.blaze.base.lang.buildfile.editor.BuildIndentOnEnterTest.java

License:Open Source License

private void pressEnterAndAssertResult(String... resultingFileContents) {
    editorTest.pressButton(IdeActions.ACTION_EDITOR_ENTER);
    testFixture.getFile().getText();/*ww  w .  j  a  v a  2s  .  c o  m*/
    testFixture.checkResult(Joiner.on("\n").join(resultingFileContents));
}

From source file:com.hp.alm.ali.idea.ui.dialog.RestErrorDetailDialog.java

License:Apache License

public RestErrorDetailDialog(Project project, Exception exception) {
    super(project, "Error Detail", true, true, Arrays.asList(Button.Close));

    final JPanel areaPanel = new JPanel(new BorderLayout());
    areaPanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(20, 20, 20, 20),
            BorderFactory.createEtchedBorder()));
    JTextPane area = new JTextPane();
    area.setCaret(new NonAdjustingCaret());
    boolean showArea = true;

    if (exception.getMessage().startsWith("<?xml ") || exception.getMessage().startsWith("<QCRestException>")) {
        Matcher matcher = Pattern.compile("^.*?<Title>(.*?)</Title>.*", Pattern.MULTILINE | Pattern.DOTALL)
                .matcher(exception.getMessage());
        if (matcher.matches()) {
            JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            labelPanel.setBorder(new EmptyBorder(10, 15, 5, 15));
            JLabel label = new JLabel(matcher.group(1));
            // message can be very long, make sure we fit into the dialog
            Dimension size = label.getPreferredSize();
            size.width = Math.min(700, size.width);
            label.setPreferredSize(size);
            labelPanel.add(label);//  w  w w .  j  a  va2s  .  c  om
            labelPanel.add(new LinkLabel("(detail)", null, new LinkListener() {
                public void linkSelected(LinkLabel aSource, Object aLinkData) {
                    if (areaPanel.getParent() == null) {
                        getContentPane().add(areaPanel, BorderLayout.CENTER);
                    } else {
                        getContentPane().remove(areaPanel);
                    }
                    packAndCenter(800, 600, false);
                }
            }));
            getContentPane().add(labelPanel, BorderLayout.NORTH);
            showArea = false;
            // adjust the area panel border to reflect our own
            areaPanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(5, 20, 20, 20),
                    BorderFactory.createEtchedBorder()));
        }
    } else {
        // assume ALM 12 HTML format
        area.setEditorKit(new HTMLEditorKit());
        if (exception instanceof RestException) {
            try {
                ((HTMLDocument) area.getDocument()).setBase(new URL(((RestException) exception).getLocation()));
            } catch (MalformedURLException mfe) {
                // formatting will be broken
            }
        }
    }

    area.setEditable(false);
    area.setText(exception.getMessage());
    JBScrollPane scrollPane = new JBScrollPane(area);
    areaPanel.add(scrollPane, BorderLayout.CENTER);
    if (showArea) {
        getContentPane().add(areaPanel, BorderLayout.CENTER);
    }

    getRootPane().setDefaultButton(getButton(Button.Close));
    // although close is default button, hitting enter doesn't close the dialog when JTextPane holds the focus - override this
    new AnAction() {
        public void actionPerformed(AnActionEvent e) {
            buttonPerformed(Button.Close);
        }
    }.registerCustomShortcutSet(
            new CustomShortcutSet(
                    KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_EDITOR_ENTER)),
            area);

    pack();
    Dimension size = getSize();
    size.width = Math.min(800, size.width);
    size.height = Math.min(600, size.height);
    setSize(size);
    centerOnOwner();
}

From source file:com.intellij.codeInsight.CodeInsightTestCase.java

License:Apache License

protected static void type(char c, Editor editor) {
    EditorActionManager actionManager = EditorActionManager.getInstance();
    DataContext dataContext = DataManager.getInstance().getDataContext();
    if (c == '\n') {
        actionManager.getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor, dataContext);
        return;/* ww  w . j  a v a2s . co m*/
    }
    TypedAction action = actionManager.getTypedAction();
    action.actionPerformed(editor, c, dataContext);
}

From source file:com.intellij.codeInsight.completion.simple.BracesTailType.java

License:Apache License

@Override
public int processTail(final Editor editor, int tailOffset) {
    int startOffset = tailOffset;

    CharSequence seq = editor.getDocument().getCharsSequence();
    int nextNonWs = CharArrayUtil.shiftForward(seq, tailOffset, " \t");
    if (nextNonWs < seq.length() && seq.charAt(nextNonWs) == '{') {
        tailOffset = nextNonWs + 1;/*www  .j  a v a 2  s .c o m*/
    } else {
        tailOffset = insertChar(editor, startOffset, '{');
    }

    tailOffset = reformatBrace(editor, tailOffset, startOffset);

    if (EnterAfterUnmatchedBraceHandler.isAfterUnmatchedLBrace(editor, tailOffset, getFileType(editor))) {
        new EnterHandler(EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER))
                .executeWriteAction(editor,
                        DataManager.getInstance().getDataContext(editor.getContentComponent()));
        return editor.getCaretModel().getOffset();
    }
    return tailOffset;
}

From source file:com.intellij.codeInsight.editorActions.AutoHardWrapHandler.java

License:Apache License

/**
 * The user is allowed to configured IJ in a way that it automatically wraps line on right margin exceeding on typing
 * (check {@link EditorSettings#isWrapWhenTypingReachesRightMargin(Project)}).
 * <p/>//from www. j  a  va 2s.  c  om
 * This method encapsulates that functionality, i.e. it performs the following logical actions:
 * <pre>
 * <ol>
 *   <li>Check if IJ is configured to perform automatic line wrapping on typing. Return in case of the negative answer;</li>
 *   <li>Check if right margin is exceeded. Return in case of the negative answer;</li>
 *   <li>Perform line wrapping;</li>
 * </ol>
 </pre>
 *
 * @param editor                          active editor
 * @param dataContext                     current data context
 * @param modificationStampBeforeTyping   document modification stamp before the current symbols typing
 */
public void wrapLineIfNecessary(@NotNull Editor editor, @NotNull DataContext dataContext,
        long modificationStampBeforeTyping) {
    Project project = editor.getProject();
    Document document = editor.getDocument();
    AutoWrapChange change = myAutoWrapChanges.get(document);
    if (change != null) {
        change.charTyped(editor, modificationStampBeforeTyping);
    }

    // Return eagerly if we don't need to auto-wrap line, e.g. because of right margin exceeding.
    if (/*editor.isOneLineMode()
        || */project == null || !editor.getSettings().isWrapWhenTypingReachesRightMargin(project)
            || (TemplateManager.getInstance(project) != null
                    && TemplateManager.getInstance(project).getActiveTemplate(editor) != null)) {
        return;
    }

    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int line = document.getLineNumber(caretOffset);
    int startOffset = document.getLineStartOffset(line);
    int endOffset = document.getLineEndOffset(line);

    final CharSequence endOfString = document.getCharsSequence().subSequence(caretOffset, endOffset);
    final boolean endsWithSpaces = StringUtil.isEmptyOrSpaces(String.valueOf(endOfString));
    // Check if right margin is exceeded.
    int margin = editor.getSettings().getRightMargin(project);
    if (margin <= 0) {
        return;
    }

    VisualPosition visEndLinePosition = editor.offsetToVisualPosition(endOffset);
    if (margin >= visEndLinePosition.column) {
        if (change != null) {
            change.modificationStamp = document.getModificationStamp();
        }
        return;
    }

    // We assume that right margin is exceeded if control flow reaches this place. Hence, we define wrap position and perform
    // smart line break there.
    LineWrapPositionStrategy strategy = LanguageLineWrapPositionStrategy.INSTANCE.forEditor(editor);

    // There is a possible case that user starts typing in the middle of the long string. Hence, there is a possible case that
    // particular symbols were already wrapped because of typing. Example:
    //    a b c d e f g <caret>h i j k l m n o p| <- right margin
    // Suppose the user starts typing at caret:
    //    type '1': a b c d e f g 1<caret>h i j k l m n o | <- right margin
    //              p                                     | <- right margin
    //    type '2': a b c d e f g 12<caret>h i j k l m n o| <- right margin
    //                                                    | <- right margin
    //              p                                     | <- right margin
    //    type '3': a b c d e f g 123<caret>h i j k l m n | <- right margin
    //              o                                     | <- right margin
    //                                                    | <- right margin
    //              p                                     | <- right margin
    // We want to prevent such behavior, hence, we remove automatically generated wraps and wrap the line as a whole.
    if (change == null) {
        change = new AutoWrapChange();
        myAutoWrapChanges.put(document, change);
    } else {
        final int start = change.change.getStart();
        final int end = change.change.getEnd();
        if (!change.isEmpty() && start < end) {
            document.replaceString(start, end, change.change.getText());
        }
        change.reset();
    }
    change.update(editor);

    // Is assumed to be max possible number of characters inserted on the visual line with caret.
    int maxPreferredOffset = editor.logicalPositionToOffset(
            editor.visualToLogicalPosition(new VisualPosition(caretModel.getVisualPosition().line,
                    margin - FormatConstants.RESERVED_LINE_WRAP_WIDTH_IN_COLUMNS)));

    int wrapOffset = strategy.calculateWrapPosition(document, project, startOffset, endOffset,
            maxPreferredOffset, true, false);
    if (wrapOffset < 0) {
        return;
    }

    WhiteSpaceFormattingStrategy formattingStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(editor);
    if (wrapOffset <= startOffset || wrapOffset > maxPreferredOffset
            || formattingStrategy.check(document.getCharsSequence(), startOffset, wrapOffset) >= wrapOffset) {
        // Don't perform hard line wrapping if it doesn't makes sense (no point to wrap at first position and no point to wrap
        // on first non-white space symbol because wrapped part will have the same indent value).
        return;
    }

    final int[] wrapIntroducedSymbolsNumber = new int[1];
    final int[] caretOffsetDiff = new int[1];
    final int baseCaretOffset = caretModel.getOffset();
    DocumentListener listener = new DocumentListener() {
        @Override
        public void beforeDocumentChange(DocumentEvent event) {
            if (event.getOffset() < baseCaretOffset + caretOffsetDiff[0]) {
                caretOffsetDiff[0] += event.getNewLength() - event.getOldLength();
            }

            if (autoFormatted(event)) {
                return;
            }
            wrapIntroducedSymbolsNumber[0] += event.getNewLength() - event.getOldLength();
        }

        private boolean autoFormatted(DocumentEvent event) {
            return event.getNewLength() <= event.getOldLength() && endsWithSpaces;
        }

        @Override
        public void documentChanged(DocumentEvent event) {
        }
    };

    caretModel.moveToOffset(wrapOffset);
    DataManager.getInstance().saveInDataContext(dataContext, AUTO_WRAP_LINE_IN_PROGRESS_KEY, true);
    document.addDocumentListener(listener);
    try {
        EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor,
                dataContext);
    } finally {
        DataManager.getInstance().saveInDataContext(dataContext, AUTO_WRAP_LINE_IN_PROGRESS_KEY, null);
        document.removeDocumentListener(listener);
    }

    change.modificationStamp = document.getModificationStamp();
    change.change.setStart(wrapOffset);
    change.change.setEnd(wrapOffset + wrapIntroducedSymbolsNumber[0]);

    caretModel.moveToOffset(baseCaretOffset + caretOffsetDiff[0]);
}

From source file:com.intellij.codeInsight.editorActions.smartEnter.PlainEnterProcessor.java

License:Apache License

@Override
public boolean doEnter(Editor editor, PsiElement psiElement, boolean isModified) {
    PsiCodeBlock block = getControlStatementBlock(editor.getCaretModel().getOffset(), psiElement);
    if (processExistingBlankLine(editor, block, psiElement)) {
        return true;
    }/*w ww. j a  v a  2 s.  c  om*/
    EditorActionHandler enterHandler = getEnterHandler(IdeActions.ACTION_EDITOR_START_NEW_LINE);
    if (block != null) {
        PsiElement firstElement = block.getFirstBodyElement();
        if (firstElement == null) {
            firstElement = block.getRBrace();
            // Plain enter processor inserts enter after the end of line, hence, we don't want to use it here because the line ends with 
            // the empty braces block. So, we get the following in case of default handler usage:
            //     Before:
            //         if (condition[caret]) {}
            //     After:
            //         if (condition) {}
            //             [caret]
            enterHandler = getEnterHandler(IdeActions.ACTION_EDITOR_ENTER);
        }
        editor.getCaretModel().moveToOffset(firstElement != null ? firstElement.getTextRange().getStartOffset()
                : block.getTextRange().getEndOffset());
    }

    enterHandler.execute(editor, ((EditorEx) editor).getDataContext());
    return true;
}

From source file:com.intellij.lang.properties.PropertiesEnterTest.java

License:Apache License

private static void typeEnter() {
    EditorActionManager actionManager = EditorActionManager.getInstance();
    EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_ENTER);
    actionHandler.execute(getEditor(), DataManager.getInstance().getDataContext());
}

From source file:com.intellij.psi.impl.source.codeStyle.CodeFormatterFacade.java

License:Apache License

/**
 * Emulates pressing <code>Enter</code> at current caret position.
 *
 * @param editor       target editor//from w w  w .  java  2s .  c om
 * @param project      target project
 * @param shifts       two-elements array which is expected to be filled with the following info:
 *                       1. The first element holds added lines number;
 *                       2. The second element holds added symbols number;
 */
private static void emulateEnter(@NotNull final Editor editor, @NotNull Project project, int[] shifts) {
    final DataContext dataContext = prepareContext(editor.getComponent(), project);
    int caretOffset = editor.getCaretModel().getOffset();
    Document document = editor.getDocument();
    SelectionModel selectionModel = editor.getSelectionModel();
    int startSelectionOffset = 0;
    int endSelectionOffset = 0;
    boolean restoreSelection = selectionModel.hasSelection();
    if (restoreSelection) {
        startSelectionOffset = selectionModel.getSelectionStart();
        endSelectionOffset = selectionModel.getSelectionEnd();
        selectionModel.removeSelection();
    }
    int textLengthBeforeWrap = document.getTextLength();
    int lineCountBeforeWrap = document.getLineCount();

    DataManager.getInstance().saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY,
            true);
    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    try {
        Runnable command = new Runnable() {
            @Override
            public void run() {
                EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER)
                        .execute(editor, dataContext);
            }
        };
        if (commandProcessor.getCurrentCommand() == null) {
            commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null);
        } else {
            command.run();
        }
    } finally {
        DataManager.getInstance().saveInDataContext(dataContext,
                WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null);
    }
    int symbolsDiff = document.getTextLength() - textLengthBeforeWrap;
    if (restoreSelection) {
        int newSelectionStart = startSelectionOffset;
        int newSelectionEnd = endSelectionOffset;
        if (startSelectionOffset >= caretOffset) {
            newSelectionStart += symbolsDiff;
        }
        if (endSelectionOffset >= caretOffset) {
            newSelectionEnd += symbolsDiff;
        }
        selectionModel.setSelection(newSelectionStart, newSelectionEnd);
    }
    shifts[0] = document.getLineCount() - lineCountBeforeWrap;
    shifts[1] = symbolsDiff;
}

From source file:com.intellij.testFramework.EditorTestUtil.java

License:Apache License

public static void performTypingAction(Editor editor, char c) {
    EditorActionManager actionManager = EditorActionManager.getInstance();
    if (c == BACKSPACE_FAKE_CHAR) {
        EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE);
        actionHandler.execute(editor, DataManager.getInstance().getDataContext());
    } else if (c == SMART_ENTER_FAKE_CHAR) {
        EditorActionHandler actionHandler = actionManager
                .getActionHandler(IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT);
        actionHandler.execute(editor, DataManager.getInstance().getDataContext());
    } else if (c == SMART_LINE_SPLIT_CHAR) {
        EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_SPLIT);
        actionHandler.execute(editor, DataManager.getInstance().getDataContext());
    } else if (c == '\n') {
        EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_ENTER);
        actionHandler.execute(editor, DataManager.getInstance().getDataContext());
    } else {//from  w  w w .  j  ava  2  s. c  o m
        TypedAction action = actionManager.getTypedAction();
        action.actionPerformed(editor, c, DataManager.getInstance().getDataContext());
    }
}

From source file:com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl.java

License:Apache License

@Override
public void type(final char c) {
    assertInitialized();/*ww w .ja  v  a 2 s .co m*/
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
        @Override
        public void run() {
            final EditorActionManager actionManager = EditorActionManager.getInstance();
            if (c == '\b') {
                performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE);
                return;
            }
            if (c == '\n') {
                if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM)) {
                    return;
                }

                performEditorAction(IdeActions.ACTION_EDITOR_ENTER);
                return;
            }
            if (c == '\t') {
                if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_REPLACE)) {
                    return;
                }
                if (_performEditorAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_BY_TAB)) {
                    return;
                }
                if (_performEditorAction(IdeActions.ACTION_EDITOR_NEXT_TEMPLATE_VARIABLE)) {
                    return;
                }
                if (_performEditorAction(IdeActions.ACTION_EDITOR_TAB)) {
                    return;
                }
            }
            if (c == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
                if (_performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_COMPLETE_STATEMENT)) {
                    return;
                }
            }

            CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
                @Override
                public void run() {
                    CommandProcessor.getInstance().setCurrentCommandGroupId(myEditor.getDocument());
                    ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, getEditorDataContext());
                    actionManager.getTypedAction().actionPerformed(getEditor(), c, getEditorDataContext());
                }
            }, null, DocCommandGroupId.noneGroupId(myEditor.getDocument()));
        }
    });
}