static Editor createPreviewEditor(String text, int column, int line, int selectedLine, ColorAndFontOptions options, boolean editable) { EditorFactory editorFactory = EditorFactory.getInstance(); Document editorDocument = editorFactory.createDocument(text); EditorEx editor = (EditorEx) (editable ? editorFactory.createEditor(editorDocument) : editorFactory.createViewer(editorDocument)); editor.setColorsScheme(options.getSelectedScheme()); EditorSettings settings = editor.getSettings(); settings.setLineNumbersShown(true); settings.setWhitespacesShown(true); settings.setLineMarkerAreaShown(false); settings.setIndentGuidesShown(false); settings.setFoldingOutlineShown(false); settings.setAdditionalColumnsCount(0); settings.setAdditionalLinesCount(0); settings.setRightMarginShown(true); settings.setRightMargin(60); LogicalPosition pos = new LogicalPosition(line, column); editor.getCaretModel().moveToLogicalPosition(pos); if (selectedLine >= 0) { editor.getSelectionModel().setSelection(editorDocument.getLineStartOffset(selectedLine), editorDocument.getLineEndOffset(selectedLine)); } return editor; }
public static void attachTo(ArrayList<EditorPlace> editorPlaces) { final FontSizeSynchronizer synchronizer = new FontSizeSynchronizer(); for (EditorPlace editorPlace : editorPlaces) { editorPlace.addListener(new EditorPlace.EditorListener() { public void onEditorCreated(EditorPlace place) { synchronizer.synchronize((EditorEx)place.getEditor()); } public void onEditorReleased(Editor releasedEditor) { synchronizer.stopSynchronize((EditorEx)releasedEditor); } }); EditorEx editor = (EditorEx)editorPlace.getEditor(); if (editor != null) synchronizer.synchronize(editor); } }
public void testRuby7852ErrantEditor() { myFixture.configureByText(FileTypes.PLAIN_TEXT, "\"aaa\"\nbbb\n\n"); myFixture.getEditor().getCaretModel().moveToOffset(0); myFixture.getEditor().getSelectionModel().setSelection(0, 5); final TypedAction typedAction = EditorActionManager.getInstance().getTypedAction(); performAction(myFixture.getProject(), new Runnable() { @Override public void run() { typedAction.actionPerformed(myFixture.getEditor(), '\'', ((EditorEx)myFixture.getEditor()).getDataContext()); } }); myFixture.getEditor().getSelectionModel().removeSelection(); myFixture.checkResult("'aaa'\nbbb\n\n"); myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getDocument().getLineStartOffset(3)); performAction(myFixture.getProject(), new Runnable() { @Override public void run() { typedAction.actionPerformed(myFixture.getEditor(), 'A', ((EditorEx)myFixture.getEditor()).getDataContext()); typedAction.actionPerformed(myFixture.getEditor(), 'B', ((EditorEx)myFixture.getEditor()).getDataContext()); } }); myFixture.checkResult("'aaa'\nbbb\n\nAB"); }
private void createUIComponents(Project project) { final EditorTextField editorTextField = new LanguageTextField(PlainTextLanguage.INSTANCE, project, "") { @Override protected EditorEx createEditor() { final EditorEx editor = super.createEditor(); final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file != null) { DaemonCodeAnalyzer.getInstance(project).setHighlightingEnabled(file, false); } editor.putUserData( ACTIVITY_CLASS_TEXT_FIELD_KEY, BlazeAndroidBinaryRunConfigurationStateEditor.this); return editor; } }; activityField = new ComponentWithBrowseButton<EditorTextField>(editorTextField, null); }
@NotNull public static EditorEx createEditor(@NotNull Document document, @Nullable Project project, boolean isViewer, boolean enableFolding) { EditorFactory factory = EditorFactory.getInstance(); EditorEx editor = (EditorEx)(isViewer ? factory.createViewer(document, project) : factory.createEditor(document, project)); editor.putUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY, Boolean.TRUE); editor.getSettings().setLineNumbersShown(true); ((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeVisible(true); editor.getGutterComponentEx().setShowDefaultGutterPopup(false); if (enableFolding) { setFoldingModelSupport(editor); } else { editor.getSettings().setFoldingOutlineShown(false); editor.getFoldingModel().setFoldingEnabled(false); } UIUtil.removeScrollBorder(editor.getComponent()); return editor; }
public void testInfoTestAttributes() throws Exception { LanguageExtensionPoint<Annotator> extension = new LanguageExtensionPoint<Annotator>(); extension.language="TEXT"; extension.implementationClass = TestAnnotator.class.getName(); PlatformTestUtil.registerExtension(ExtensionPointName.create(LanguageAnnotators.EP_NAME), extension, getTestRootDisposable()); myFixture.configureByText(PlainTextFileType.INSTANCE, "foo"); EditorColorsScheme scheme = new EditorColorsSchemeImpl(new DefaultColorsScheme()){{initFonts();}}; scheme.setAttributes(HighlighterColors.TEXT, new TextAttributes(Color.black, Color.white, null, null, Font.PLAIN)); ((EditorEx)myFixture.getEditor()).setColorsScheme(scheme); myFixture.doHighlighting(); MarkupModel model = DocumentMarkupModel.forDocument(myFixture.getEditor().getDocument(), getProject(), false); RangeHighlighter[] highlighters = model.getAllHighlighters(); assertEquals(1, highlighters.length); TextAttributes attributes = highlighters[0].getTextAttributes(); assertNotNull(attributes); assertNull(attributes.getBackgroundColor()); assertNull(attributes.getForegroundColor()); }
private void setupHighlighterSettings(Editor left, Editor base, Editor right) { Editor[] editors = new Editor[]{left, base, right}; DiffContent[] contents = myData.getContents(); FileType[] types = DiffUtil.chooseContentTypes(contents); VirtualFile fallbackFile = contents[1].getFile(); FileType fallbackType = contents[1].getContentType(); for (int i = 0; i < 3; i++) { Editor editor = editors[i]; DiffContent content = contents[i]; EditorHighlighter highlighter = createHighlighter(types[i], content.getFile(), fallbackFile, fallbackType, myData.getProject()).createHighlighter(); if (highlighter != null) { ((EditorEx)editor).setHighlighter(highlighter); } } }
private boolean isSomeChangeSelected(@NotNull ThreeSide side) { EditorEx editor = getEditor(side); List<Caret> carets = editor.getCaretModel().getAllCarets(); if (carets.size() != 1) return true; Caret caret = carets.get(0); if (caret.hasSelection()) return true; int line = editor.getDocument().getLineNumber(editor.getExpectedCaretOffset()); List<TextMergeChange> changes = getAllChanges(); for (TextMergeChange change : changes) { if (!isEnabled(change)) continue; int line1 = change.getStartLine(side); int line2 = change.getEndLine(side); if (DiffUtil.isSelectedByLine(line, line1, line2)) return true; } return false; }
@Override public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) { List<TextRange> superResult = super.select(e, editorText, cursorOffset, editor); HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(cursorOffset); if (CustomFileTypeQuoteHandler.isQuotedToken(iterator.getTokenType())) { List<TextRange> result = ContainerUtil.newArrayList(); int start = iterator.getStart(); int end = iterator.getEnd(); if (end - start > 2) { result.add(new TextRange(start + 1, end - 1)); } result.add(new TextRange(start, end)); if (superResult != null) { result.addAll(superResult); } return result; } return superResult; }
private static boolean compareLeftAndRight(@NotNull MergeLineFragment fragment, @NotNull List<? extends EditorEx> editors, @NotNull ComparisonPolicy policy) { CharSequence content1 = getRangeContent(fragment, editors, ThreeSide.LEFT); CharSequence content2 = getRangeContent(fragment, editors, ThreeSide.RIGHT); if (policy == ComparisonPolicy.IGNORE_WHITESPACES) { if (content1 == null) content1 = ""; if (content2 == null) content2 = ""; } if (content1 == null && content2 == null) return true; if (content1 == null ^ content2 == null) return false; return ComparisonManager.getInstance().isEquals(content1, content2, policy); }
@Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { if (element.getNode().getElementType() == TokenType.WHITE_SPACE) element = PsiTreeUtil.prevVisibleLeaf(element); SchemaValueTypeRef valueTypeRef = PsiTreeUtil.getParentOfType(element, SchemaValueTypeRef.class); if (valueTypeRef != null) { int endOffset = valueTypeRef.getNode().getTextRange().getEndOffset(); editor.getCaretModel().moveToOffset(endOffset); EditorModificationUtil.insertStringAtCaret(editor, " default "); ApplicationManager.getApplication().invokeLater(() -> { AnActionEvent event = AnActionEvent.createFromDataContext("AddDefaultAction", new Presentation(), ((EditorEx) editor).getDataContext()); new CodeCompletionAction().actionPerformed(event); }); } }
public LanguageConsoleImpl(@NotNull Helper helper) { super(helper.project, GlobalSearchScope.allScope(helper.project), true, true); myHelper = helper; EditorFactory editorFactory = EditorFactory.getInstance(); myEditorDocument = helper.getDocument(); myConsoleEditor = (EditorEx)editorFactory.createEditor(myEditorDocument, getProject()); myConsoleEditor.addFocusListener(myFocusListener); myCurrentEditor = myConsoleEditor; myHistoryViewer = (EditorEx)editorFactory.createViewer(((EditorFactoryImpl)editorFactory).createDocument(true), getProject()); myBusConnection = getProject().getMessageBus().connect(); // action shortcuts are not yet registered ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { installEditorFactoryListener(); } }, getProject().getDisposed()); }
private static Editor createEditor(final Project project, final String text, final String fileName) { final FileType fileType = getFileType(fileName); final Document doc = createDocument(fileName, fileType, text); final Editor editor = EditorFactory.getInstance().createEditor(doc, project); ((EditorEx)editor).setEmbeddedIntoDialogWrapper(true); final EditorSettings settings = editor.getSettings(); settings.setLineNumbersShown(false); settings.setFoldingOutlineShown(false); settings.setRightMarginShown(false); settings.setLineMarkerAreaShown(false); settings.setIndentGuidesShown(false); ((EditorEx)editor).setHighlighter(HighlighterFactory.createHighlighter(fileType, DefaultColorSchemesManager.getInstance().getFirstScheme(), project)); return editor; }
@Override public void actionPerformed(@NotNull AnActionEvent e) { Side currentSide = getCurrentSide(); Side targetSide = currentSide.other(); EditorEx currentEditor = getEditor(currentSide); EditorEx targetEditor = getEditor(targetSide); if (myScrollToPosition) { LogicalPosition position = transferPosition(currentSide, currentEditor.getCaretModel().getLogicalPosition()); targetEditor.getCaretModel().moveToLogicalPosition(position); } setCurrentSide(targetSide); myContext.requestFocus(); currentEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); }
private static void showPreviewDialog(@NotNull Project project, @NotNull TaskFile taskFile) { final FrameWrapper showPreviewFrame = new FrameWrapper(project); final LightVirtualFile userFile = new LightVirtualFile(taskFile.name, taskFile.text); showPreviewFrame.setTitle(userFile.getName()); LabeledEditor labeledEditor = new LabeledEditor(null); final EditorFactory factory = EditorFactory.getInstance(); Document document = FileDocumentManager.getInstance().getDocument(userFile); if (document == null) { return; } final EditorEx createdEditor = (EditorEx)factory.createEditor(document, project, userFile, true); Disposer.register(project, () -> factory.releaseEditor(createdEditor)); for (AnswerPlaceholder answerPlaceholder : taskFile.getActivePlaceholders()) { if (answerPlaceholder.getActiveSubtaskInfo().isNeedInsertText()) { answerPlaceholder.setLength(answerPlaceholder.getTaskText().length()); } Integer minIndex = Collections.min(answerPlaceholder.getSubtaskInfos().keySet()); answerPlaceholder.setUseLength(minIndex >= answerPlaceholder.getActiveSubtaskIndex()); EduAnswerPlaceholderPainter.drawAnswerPlaceholder(createdEditor, answerPlaceholder, JBColor.BLUE); } JPanel header = new JPanel(); header.setLayout(new BoxLayout(header, BoxLayout.Y_AXIS)); header.setBorder(new EmptyBorder(10, 10, 10, 10)); header.add(new JLabel("Read-only preview.")); String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); header.add(new JLabel(String.format("Created %s.", timeStamp))); JComponent editorComponent = createdEditor.getComponent(); labeledEditor.setComponent(editorComponent, header); createdEditor.setCaretVisible(false); createdEditor.setCaretEnabled(false); showPreviewFrame.setComponent(labeledEditor); if (!ApplicationManager.getApplication().isUnitTestMode()) { showPreviewFrame.setSize(new Dimension(500, 500)); showPreviewFrame.show(); } }
private void updatePreviewHighlighter(EditorEx editor) { EditorColorsScheme scheme = editor.getColorsScheme(); editor.getSettings().setCaretRowShown(false); EditorHighlighter highlighter = this.createHighlighter(scheme); if (highlighter != null) { editor.setHighlighter(highlighter); } }
@Override protected PsiFile createFileFromText(final Project project, final String text) { // the highlighter is not properly updated - do it manually Editor editor = this.getEditor(); if (editor != null) { updatePreviewHighlighter((EditorEx) editor); } return super.createFileFromText(project, applySettingsToText(project, text)); }
public ColorPreviewPanel() { final EditorFactory editorFactory = EditorFactory.getInstance(); myEditor = (EditorEx) editorFactory.createViewer(editorFactory.createDocument("")); final EditorSettings settings = myEditor.getSettings(); settings.setLineNumbersShown(true); settings.setWhitespacesShown(true); settings.setLineMarkerAreaShown(false); settings.setIndentGuidesShown(false); settings.setFoldingOutlineShown(false); settings.setAdditionalColumnsCount(0); settings.setAdditionalLinesCount(0); settings.setRightMarginShown(true); settings.setRightMargin(60); /** {@link FontEditorPreview#installTrafficLights(EditorEx)} */ TrafficLightRenderer renderer = new TrafficLightRenderer(null, null, null) { private final DaemonCodeAnalyzerStatus status = new DaemonCodeAnalyzerStatus(); { status.errorAnalyzingFinished = true; status.errorCount = new int[]{ 0 }; } @NotNull @Override protected DaemonCodeAnalyzerStatus getDaemonCodeAnalyzerStatus( @NotNull SeverityRegistrar severityRegistrar) { return status; } }; Disposer.register((Disposable) myEditor.getCaretModel(), renderer); EditorMarkupModel markupModel = (EditorMarkupModel) myEditor.getMarkupModel(); markupModel.setErrorStripeRenderer(renderer); markupModel.setErrorStripeVisible(true); }
@Nullable private static String findUrlAtCaret(@NotNull AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor == null) return null; int offset = editor.getCaretModel().getOffset(); String url = findUrl(editor, offset); if (url != null) return url; int expectedCaretOffset = ((EditorEx)editor).getExpectedCaretOffset(); return expectedCaretOffset == offset ? null : findUrl(editor, expectedCaretOffset); }
public void testBlockSelectionStateAfterUndo() throws Exception { init("a"); ((EditorEx)myEditor).setColumnMode(true); mouse().clickAt(0, 2); type('b'); undo(); executeAction("EditorRightWithSelection"); verifyCaretsAndSelections(0, 3, 2, 3); }
@Override public void focusGained(Editor editor) { myCurrentEditor = (EditorEx)editor; if (GeneralSettings.getInstance().isSaveOnFrameDeactivation()) { FileDocumentManager.getInstance().saveAllDocuments(); // PY-12487 } }
private static void setupEditor(@NotNull final EditorEx editor) { editor.setBackgroundColor(getEditablePanelBackground()); noScrolling(editor); editor.getScrollPane().setBorder(null); final EditorSettings editorSettings = editor.getSettings(); editorSettings.setLineMarkerAreaShown(false); editorSettings.setIndentGuidesShown(false); editorSettings.setLineNumbersShown(false); editorSettings.setFoldingOutlineShown(false); editorSettings.setAdditionalPageAtBottom(false); editorSettings.setAdditionalColumnsCount(0); editorSettings.setAdditionalLinesCount(0); editorSettings.setRightMarginShown(false); }
@Override public void customize(@NotNull EditorEx editor) { if (isEnabled()) { editor.getSettings().setRightMarginShown(true); editor.getSettings().setRightMargin(getRightMarginColumns()); // ensure we've got a monospace font by loading up the global editor scheme editor.setColorsScheme(EditorColorsManager.getInstance().getGlobalScheme()); } else { editor.getSettings().setRightMarginShown(false); } }
private void switchEditor() { if (myOldEditor != null) { myOldEditor.removePropertyChangeListener(this); myOldEditor = null; } EditorEx editor = (EditorEx)getEditor(); if (editor != null) { editor.addPropertyChangeListener(this); myOldEditor = editor; } }
private static boolean isOpeningQuote(@NotNull Editor editor, @NotNull QuoteHandler quoteHandler, int offset) { HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(offset); if (iterator.atEnd()){ LOG.assertTrue(false); return false; } return quoteHandler.isOpeningQuote(iterator, offset); }
public void testSwapSelectionBoundariesWithStickySelection() throws IOException { initText("a<selection>b<caret></selection>c"); ((EditorEx)myEditor).setStickySelection(true); executeAction(IdeActions.ACTION_EDITOR_SWAP_SELECTION_BOUNDARIES); left(); checkResultByText("<selection><caret>ab</selection>c"); }
public static void moveCaretPageDown(@NotNull Editor editor, boolean isWithSelection) { int lineHeight = editor.getLineHeight(); Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); int linesIncrement = visibleArea.height / lineHeight; int allowedBottom = ((EditorEx)editor).getContentSize().height - visibleArea.height; editor.getScrollingModel().scrollVertically( Math.min(allowedBottom, visibleArea.y - visibleArea.y % lineHeight + linesIncrement * lineHeight)); editor.getCaretModel().moveCaretRelatively(0, linesIncrement, isWithSelection, editor.isColumnMode(), true); }
@Override public void update(AnActionEvent e) { EditorEx editor = getEditor(e); if (editor == null || editor.isOneLineMode()) { e.getPresentation().setEnabled(false); e.getPresentation().setVisible(true); } else { e.getPresentation().setEnabled(editor.getCaretModel().supportsMultipleCarets() && editor.getSelectionModel().hasSelection() || editor.getCaretModel().getCaretCount() > 1); e.getPresentation().setVisible(true); super.update(e); } }
/** * Enables/disables left border {@link #BORDER_SIZE_PX} width for certain editors. * * @param editors editors to enable/disable border * @param enable whether border should be enabled */ private static void configureLeftBorder(final boolean enable, @NotNull final EditorEx... editors) { for (final EditorEx editor : editors) { final Color backgroundColor = editor.getBackgroundColor(); // Border have the same color console background has final int thickness = enable ? BORDER_SIZE_PX : 0; final Border border = BorderFactory.createMatteBorder(0, thickness, 0, 0, backgroundColor); editor.getComponent().setBorder(border); } }
@Override public final void update(@NotNull AnActionEvent e) { EditorEx editor = myConsoleView.getConsoleEditor(); boolean enabled = !editor.isRendererMode() && isEnabled() && (myExecuteActionHandler.isEmptyCommandExecutionAllowed() || !StringUtil.isEmptyOrSpaces(editor.getDocument().getCharsSequence())); if (enabled) { Lookup lookup = LookupManager.getActiveLookup(editor); // we should check getCurrentItem() also - fast typing could produce outdated lookup, such lookup reports isCompletion() true enabled = lookup == null || !lookup.isCompletion() || lookup.getCurrentItem() == null || (lookup instanceof LookupImpl && ((LookupImpl)lookup).getFocusDegree() == LookupImpl.FocusDegree.UNFOCUSED); } e.getPresentation().setEnabled(enabled); }
public void testPasteInOneLineMode() throws Exception { init("", TestFileType.TEXT); ((EditorEx)myEditor).setOneLineMode(true); CopyPasteManager.getInstance().setContents(new StringSelection("a\rb")); executeAction(IdeActions.ACTION_EDITOR_PASTE); checkResultByText("a b<caret>"); }
@Nullable public static HashMap<String, String> getOnPasteReplacements(final @NotNull Editor editor) { final ApplicationSettings settings = ApplicationSettings.getInstance(); if (settings.isReplaceMacroVariables() && editor instanceof EditorEx) { final EditorEx editorEx = (EditorEx) editor; final Project project = editorEx.getProject(); final PsiFile psiFile = project == null ? null : PsiManager.getInstance(project).findFile(editorEx.getVirtualFile()); HashMap<String, String> map = new HashMap<>(); StudiedWord word = new StudiedWord(editorEx.getVirtualFile().getNameWithoutExtension(), StudiedWord.DOT | StudiedWord.DASH | StudiedWord.UNDER | StudiedWord.SLASH | StudiedWord.SPACE); final String pascalCase = word.makePascalCase(); map.put("__Filename__", word.getWord().toString()); map.put("__FILENAME__", pascalCase.toUpperCase()); map.put("__filename__", pascalCase.toLowerCase()); map.put("__FileName__", pascalCase); map.put("__fileName__", word.makeProperCamelCase()); map.put("__file-name__", word.makeDashCase()); map.put("__FILE-NAME__", word.makeScreamingDashCase()); map.put("__file.name__", word.makeDotCase()); map.put("__FILE.NAME__", word.makeScreamingDotCase()); map.put("__file_name__", word.makeSnakeCase()); map.put("__FILE_NAME__", word.makeScreamingSnakeCase()); map.put("__file/name__", word.makeSlashCase()); map.put("__FILE/NAME__", word.makeScreamingSlashCase()); return map; } return null; }
private static boolean isAtTokenNeeded(InsertionContext myContext) { HighlighterIterator iterator = ((EditorEx)myContext.getEditor()).getHighlighter().createIterator(myContext.getStartOffset()); LOG.assertTrue(iterator.getTokenType() == JavaTokenType.IDENTIFIER); iterator.retreat(); if (iterator.getTokenType() == TokenType.WHITE_SPACE) iterator.retreat(); return iterator.getTokenType() != JavaTokenType.AT && iterator.getTokenType() != JavaTokenType.DOT; }
private static int getExistingRParenthOffset(final Editor editor, final int tailOffset) { final Document document = editor.getDocument(); if (tailOffset >= document.getTextLength()) return -1; final CharSequence charsSequence = document.getCharsSequence(); EditorHighlighter highlighter = ((EditorEx) editor).getHighlighter(); int existingRParenthOffset = -1; for(HighlighterIterator iterator = highlighter.createIterator(tailOffset); !iterator.atEnd(); iterator.advance()){ final IElementType tokenType = iterator.getTokenType(); if ((!(tokenType instanceof IJavaElementType) || !ElementType.JAVA_COMMENT_OR_WHITESPACE_BIT_SET.contains(tokenType)) && tokenType != TokenType.WHITE_SPACE) { final int start = iterator.getStart(); if (iterator.getEnd() == start + 1 && ')' == charsSequence.charAt(start)) { existingRParenthOffset = start; } break; } } if (existingRParenthOffset >= 0){ final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(editor.getProject()); psiDocumentManager.commitDocument(document); TextRange range = getRangeToCheckParensBalance(psiDocumentManager.getPsiFile(document), document, editor.getCaretModel().getOffset()); int balance = calcParensBalance(document, highlighter, range.getStartOffset(), range.getEndOffset()); if (balance > 0){ return -1; } } return existingRParenthOffset; }
public void updateEditor(EditorEx editor) { try { myDuringUpdate = true; editor.setFontSize(myLastFontSize); } finally { myDuringUpdate = false; } }
public static void handleLTDeletion(final Editor editor, final int offset, final IElementType lt, final IElementType gt, final TokenSet invalidInsideReference) { HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(offset); while (iterator.getStart() > 0 && !invalidInsideReference.contains(iterator.getTokenType())) { iterator.retreat(); } if (invalidInsideReference.contains(iterator.getTokenType())) iterator.advance(); int balance = 0; while (!iterator.atEnd() && balance >= 0) { final IElementType tokenType = iterator.getTokenType(); if (tokenType == lt) { balance++; } else if (tokenType == gt) { balance--; } else if (invalidInsideReference.contains(tokenType)) { break; } iterator.advance(); } if (balance < 0) { editor.getDocument().deleteString(offset, offset + 1); } }
public static void handleAfterJavaLT(final Editor editor, final IElementType lt, final IElementType gt, final TokenSet invalidInsideReference) { if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) return; int offset = editor.getCaretModel().getOffset(); HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset); while (iterator.getStart() > 0 && !invalidInsideReference.contains(iterator.getTokenType())) { iterator.retreat(); } if (invalidInsideReference.contains(iterator.getTokenType())) iterator.advance(); int balance = 0; while (!iterator.atEnd() && balance >= 0) { final IElementType tokenType = iterator.getTokenType(); if (tokenType == lt) { balance++; } else if (tokenType == gt) { balance--; } else if (invalidInsideReference.contains(tokenType)) { break; } iterator.advance(); } if (balance == 1) { editor.getDocument().insertString(offset, ">"); } }
public void testBlockSelectionStateAfterUndo2() throws Exception { init("a"); ((EditorEx)myEditor).setColumnMode(true); mouse().clickAt(0, 0).dragTo(0, 2).release(); type('b'); undo(); verifyCaretsAndSelections(0, 2, 0, 2); }
public void testBackspaceWithStickySelection() throws Exception { init("te<caret>xt", TestFileType.TEXT); executeAction(IdeActions.ACTION_EDITOR_TOGGLE_STICKY_SELECTION); executeAction(IdeActions.ACTION_EDITOR_MOVE_CARET_RIGHT); executeAction(IdeActions.ACTION_EDITOR_BACKSPACE); checkResultByText("te<caret>t"); assertFalse(((EditorEx)myEditor).isStickySelection()); }
private void doTest(final Runnable run, boolean shouldShow, final String hint) { myFixture.configureByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + ".java"); myFixture.enableInspections(new UnusedDeclarationInspection()); final ChangeSignatureGestureDetector detector = ChangeSignatureGestureDetector.getInstance(getProject()); final EditorEx editor = (EditorEx)myFixture.getEditor(); final Document document = editor.getDocument(); try { PsiManager.getInstance(getProject()).addPsiTreeChangeListener(detector); detector.addDocListener(document); new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { run.run(); } }.execute().throwException(); myFixture.doHighlighting(); if (shouldShow) { final IntentionAction intention = myFixture.findSingleIntention(hint); myFixture.launchAction(intention); myFixture.checkResultByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + "_after.java"); } else { final List<IntentionAction> intentionActions = myFixture.filterAvailableIntentions(hint); assertEmpty(intentionActions); } } finally { detector.removeDocListener(document, editor.getVirtualFile()); PsiManager.getInstance(getProject()).removePsiTreeChangeListener(detector); } }