private ArrayList<Change> buildChanges() throws FilesTooBigForDiffException { Document base = getDocument(FragmentSide.SIDE1); DiffString[] baseLines = DiffUtil.convertToLines(base.getText()); Document version = getDocument(FragmentSide.SIDE2); DiffString[] versionLines = DiffUtil.convertToLines(version.getText()); DiffFragment[] fragments = ComparisonPolicy.DEFAULT.buildDiffFragmentsFromLines(baseLines, versionLines); final ArrayList<Change> result = new ArrayList<>(); new DiffFragmentsEnumerator(fragments) { @Override protected void process(DiffFragment fragment) { if (fragment.isEqual()) return; Context context = getContext(); TextRange range1 = context.createRange(FragmentSide.SIDE1); TextRange range2 = context.createRange(FragmentSide.SIDE2); result.add( new SimpleChange( ChangeType.fromDiffFragment(context.getFragment()), range1, range2, ChangeList.this)); } }.execute(); return result; }
public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception { String text = "import java.awt.List;\n" + "[import java.util.ArrayList;\n]" + "import java.util.HashMap;\n" + "import java.util.Map;"; RangeMarker marker = createMarker(text); synchronizer.startTransaction(getProject(), document, psiFile); String newText = StringUtil.replaceSubstring(document.getText(), TextRange.create(marker), ""); synchronizer.replaceString(document, 0, document.getTextLength(), newText); final List<DocumentEvent> events = new ArrayList<DocumentEvent>(); document.addDocumentListener( new DocumentAdapter() { @Override public void documentChanged(DocumentEvent e) { events.add(e); } }); synchronizer.commitTransaction(document); assertEquals(newText, document.getText()); DocumentEvent event = assertOneElement(events); assertEquals( "DocumentEventImpl[myOffset=22, myOldLength=28, myNewLength=0, myOldString='import java.util.ArrayList;\n', myNewString=''].", event.toString()); }
@Override public String getText() { VirtualFile file = getVirtualFile(); Document document = FileDocumentManager.getInstance().getDocument(file); assert document != null : file.getUrl(); return document.getText(); }
@Override public void documentChanged(DocumentEvent e) { if (!myTaskFile.isTrackChanges()) { return; } if (myAnswerPlaceholders.isEmpty()) return; if (e instanceof DocumentEventImpl) { DocumentEventImpl event = (DocumentEventImpl) e; Document document = e.getDocument(); int offset = e.getOffset(); int change = event.getNewLength() - event.getOldLength(); for (AnswerPlaceholderWrapper answerPlaceholderWrapper : myAnswerPlaceholders) { int twStart = answerPlaceholderWrapper.getTwStart(); if (twStart > offset) { twStart += change; } int twEnd = answerPlaceholderWrapper.getTwEnd(); if (twEnd >= offset) { twEnd += change; } AnswerPlaceholder answerPlaceholder = answerPlaceholderWrapper.getAnswerPlaceholder(); int line = document.getLineNumber(twStart); int start = twStart - document.getLineStartOffset(line); int length = twEnd - twStart; answerPlaceholder.setLine(line); answerPlaceholder.setStart(start); if (usePossibleAnswerLength) { answerPlaceholder.setPossibleAnswer( document.getText(TextRange.create(twStart, twStart + length))); } else if (myTrackLength) { answerPlaceholder.setLength(length); } } } }
protected void assertIntentionApplication( final String intentionId, final String source, final String after) { final PsiFile file = this.configureByText(source); final IntentionAction intention = this.myFixture.findSingleIntention(intentionId); CommandProcessor _instance = CommandProcessor.getInstance(); Project _project = this.getProject(); final Runnable _function = new Runnable() { @Override public void run() { Application _application = ApplicationManager.getApplication(); final Runnable _function = new Runnable() { @Override public void run() { Project _project = file.getProject(); Editor _editor = IntentionsTest.this.getEditor(); intention.invoke(_project, _editor, file); Project _project_1 = IntentionsTest.this.getProject(); PsiDocumentManager _instance = PsiDocumentManager.getInstance(_project_1); _instance.commitAllDocuments(); } }; _application.runWriteAction(_function); } }; _instance.executeCommand(_project, _function, "", ""); Editor _editor = this.myFixture.getEditor(); Document _document = _editor.getDocument(); String _text = _document.getText(); TestCase.assertEquals(after, _text); }
/** * remove highlights (bounded with <marker>...</marker>) from test case file * * @param document document to process */ private void extractExpectedHighlightsSet(final Document document) { final String text = document.getText(); final Set<String> markers = myHighlightingTypes.keySet(); final String typesRx = "(?:" + StringUtil.join(markers, ")|(?:") + ")"; final String openingTagRx = "<(" + typesRx + ")" + "(?:\\s+descr=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\\\])*)\")?" + "(?:\\s+type=\"([0-9A-Z_]+)\")?" + "(?:\\s+foreground=\"([0-9xa-f]+)\")?" + "(?:\\s+background=\"([0-9xa-f]+)\")?" + "(?:\\s+effectcolor=\"([0-9xa-f]+)\")?" + "(?:\\s+effecttype=\"([A-Z]+)\")?" + "(?:\\s+fonttype=\"([0-9]+)\")?" + "(?:\\s+textAttributesKey=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\\\])*)\")?" + "(?:\\s+bundleMsg=\"((?:[^\"]|\\\\\"|\\\\\\\\\")*)\")?" + "(/)?>"; final Matcher matcher = Pattern.compile(openingTagRx).matcher(text); int pos = 0; final Ref<Integer> textOffset = Ref.create(0); while (matcher.find(pos)) { textOffset.set(textOffset.get() + matcher.start() - pos); pos = extractExpectedHighlight(matcher, text, document, textOffset); } }
public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception { StringBuilder buffer = new StringBuilder("0123456789"); RangeMarker marker = createMarker(buffer.toString(), 2, 5); synchronizer.startTransaction(getProject(), document, psiFile); final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document); final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments(); for (int i = 0; i < 10; i++) { synchronizer.insertString(document, i, "" + i); buffer.insert(i, "" + i); } assertEquals(1, affectedFragments.size()); synchronizer.replaceString(document, 0, 20, "0123456789"); buffer.replace(0, 20, "0123456789"); assertEquals(1, affectedFragments.size()); synchronizer.commitTransaction(document); assertEquals(buffer.toString(), document.getText()); assertValidMarker(marker, 2, 5); }
@Override public void actionPerformed(AnActionEvent e) { Project project = e.getData(PlatformDataKeys.PROJECT); Editor editor = e.getData(PlatformDataKeys.EDITOR); if (editor == null) { return; } if (!editor.getDocument().isWritable()) { return; } Document document = editor.getDocument(); SelectionModel selection = editor.getSelectionModel(); String selectedText = selection.getSelectedText(); String autoAlignedText; int startOffset; int endOffset; if (selectedText != null) { // just align the selected text autoAlignedText = aligner.align(selectedText); startOffset = selection.getSelectionStart(); endOffset = selection.getSelectionEnd(); } else { // auto-align the whole document autoAlignedText = aligner.align(document.getText()); startOffset = 0; endOffset = document.getTextLength(); } replaceString(project, document, autoAlignedText, startOffset, endOffset); }
private boolean getStringToReplace( int textOffset, int textEndOffset, Document document, FindModel findModel, Ref<String> stringToReplace) throws FindManager.MalformedReplacementStringException { if (textOffset < 0 || textOffset >= document.getTextLength()) { return false; } if (textEndOffset < 0 || textOffset > document.getTextLength()) { return false; } FindManager findManager = FindManager.getInstance(myProject); final CharSequence foundString = document.getCharsSequence().subSequence(textOffset, textEndOffset); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); FindResult findResult = findManager.findString( document.getCharsSequence(), textOffset, findModel, file != null ? file.getVirtualFile() : null); if (!findResult.isStringFound()) { return false; } stringToReplace.set( FindManager.getInstance(myProject) .getStringToReplace(foundString.toString(), findModel, textOffset, document.getText())); return true; }
@SuppressWarnings("deprecation") public ExpectedHighlightingData(@NotNull Document document, @Nullable PsiFile file) { myDocument = document; myFile = file; myText = document.getText(); registerHighlightingType( ERROR_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, false, true)); registerHighlightingType( WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, false)); registerHighlightingType( WEAK_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WEAK_WARNING, false, false)); registerHighlightingType( INJECT_MARKER, new ExpectedHighlightingSet(HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, false)); registerHighlightingType( INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, false)); registerHighlightingType( SYMBOL_NAME_MARKER, new ExpectedHighlightingSet(HighlightInfoType.SYMBOL_TYPE_SEVERITY, false, false)); for (SeveritiesProvider provider : Extensions.getExtensions(SeveritiesProvider.EP_NAME)) { for (HighlightInfoType type : provider.getSeveritiesHighlightInfoTypes()) { HighlightSeverity severity = type.getSeverity(null); registerHighlightingType( severity.getName(), new ExpectedHighlightingSet(severity, false, true)); } } registerHighlightingType( END_LINE_HIGHLIGHT_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, true, true)); registerHighlightingType( END_LINE_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, false)); }
private void initGuardedBlocks(Place shreds) { int origOffset = -1; int curOffset = 0; for (PsiLanguageInjectionHost.Shred shred : shreds) { Segment hostRangeMarker = shred.getHostRangeMarker(); int start = shred.getRange().getStartOffset() + shred.getPrefix().length(); int end = shred.getRange().getEndOffset() - shred.getSuffix().length(); if (curOffset < start) { RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, start); if (curOffset == 0 && shred == shreds.get(0)) guard.setGreedyToLeft(true); String padding = origOffset < 0 ? "" : myOrigDocument.getText().substring(origOffset, hostRangeMarker.getStartOffset()); guard.putUserData(REPLACEMENT_KEY, fixQuotes(padding)); } curOffset = end; origOffset = hostRangeMarker.getEndOffset(); } if (curOffset < myNewDocument.getTextLength()) { RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, myNewDocument.getTextLength()); guard.setGreedyToRight(true); guard.putUserData(REPLACEMENT_KEY, ""); } }
public void testPsi2DocSurround() throws Exception { StringBuilder buffer = new StringBuilder("0123456789"); RangeMarker marker = createMarker(buffer.toString(), 2, 5); synchronizer.startTransaction(getProject(), document, psiFile); synchronizer.replaceString(document, 3, 5, "3a4"); buffer.replace(3, 5, "3a4"); synchronizer.insertString(document, 3, "b"); buffer.insert(3, "b"); synchronizer.insertString(document, 7, "d"); buffer.insert(7, "d"); final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = synchronizer.getTransaction(document); final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments = transaction.getAffectedFragments(); assertEquals(3, affectedFragments.size()); synchronizer.commitTransaction(document); assertEquals(buffer.toString(), document.getText()); assertValidMarker(marker, 2, 7); }
private void altCommitToOriginal(@NotNull DocumentEvent e) { final PsiFile origPsiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument); String newText = myNewDocument.getText(); // prepare guarded blocks LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>(); int count = 0; for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) { String replacement = o.getUserData(REPLACEMENT_KEY); String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement)); newText = newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset()); replacementMap.put(tempText, replacement); } // run preformat processors final int hostStartOffset = myAltFullRange.getStartOffset(); myEditor.getCaretModel().moveToOffset(hostStartOffset); for (CopyPastePreProcessor preProcessor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) { newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null); } myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText); // replace temp strings for guarded blocks for (String tempText : replacementMap.keySet()) { int idx = CharArrayUtil.indexOf( myOrigDocument.getCharsSequence(), tempText, hostStartOffset, myAltFullRange.getEndOffset()); myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText)); } // JAVA: fix occasional char literal concatenation fixDocumentQuotes(myOrigDocument, hostStartOffset - 1); fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset()); // reformat PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument); Runnable task = () -> { try { CodeStyleManager.getInstance(myProject) .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true); } catch (IncorrectOperationException e1) { // LOG.error(e); } }; DocumentUtil.executeInBulk(myOrigDocument, true, task); PsiElement newInjected = InjectedLanguageManager.getInstance(myProject) .findInjectedElementAt(origPsiFile, hostStartOffset); DocumentWindow documentWindow = newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected); if (documentWindow != null) { myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset())); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } }
public void send_patch(VirtualFile virtualFile) { Document d = Buf.getDocumentForVirtualFile(virtualFile); if (d == null) { Flog.warn("Can't get document to read from disk for sending patch %s", path); return; } send_patch(d.getText()); }
private void commitToOriginalInner() { final String text = myNewDocument.getText(); final Map< PsiLanguageInjectionHost, Set<Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>>> map = ContainerUtil.classify( myMarkers.iterator(), new Convertor< Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>, PsiLanguageInjectionHost>() { @Override public PsiLanguageInjectionHost convert( final Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> o) { final PsiElement element = o.third.getElement(); return (PsiLanguageInjectionHost) element; } }); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); documentManager.commitDocument(myOrigDocument); // commit here and after each manipulator update int localInsideFileCursor = 0; for (PsiLanguageInjectionHost host : map.keySet()) { if (host == null) continue; String hostText = host.getText(); ProperTextRange insideHost = null; StringBuilder sb = new StringBuilder(); for (Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> entry : map.get(host)) { RangeMarker origMarker = entry.first; // check for validity? int hostOffset = host.getTextRange().getStartOffset(); ProperTextRange localInsideHost = new ProperTextRange( origMarker.getStartOffset() - hostOffset, origMarker.getEndOffset() - hostOffset); RangeMarker rangeMarker = entry.second; ProperTextRange localInsideFile = new ProperTextRange( Math.max(localInsideFileCursor, rangeMarker.getStartOffset()), rangeMarker.getEndOffset()); if (insideHost != null) { // append unchanged inter-markers fragment sb.append( hostText.substring(insideHost.getEndOffset(), localInsideHost.getStartOffset())); } sb.append( localInsideFile.getEndOffset() <= text.length() && !localInsideFile.isEmpty() ? localInsideFile.substring(text) : ""); localInsideFileCursor = localInsideFile.getEndOffset(); insideHost = insideHost == null ? localInsideHost : insideHost.union(localInsideHost); } assert insideHost != null; ElementManipulators.getManipulator(host).handleContentChange(host, insideHost, sb.toString()); documentManager.commitDocument(myOrigDocument); } }
@TestOnly public void checkAllTreesEqual() { Collection<PsiFile> roots = myRoots.values(); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getManager().getProject()); documentManager.commitAllDocuments(); for (PsiFile root : roots) { Document document = documentManager.getDocument(root); PsiDocumentManagerImpl.checkConsistency(root, document); assert root.getText().equals(document.getText()); } }
@NotNull private String replaceAndProcessDocument( @NotNull final Action action, @NotNull final String text, @NotNull final PsiFile file, @Nullable final Document document) throws IncorrectOperationException { if (document == null) { fail("Don't expect the document to be null"); return null; } if (myLineRange != null) { final DocumentImpl doc = new DocumentImpl(text); myTextRange = new TextRange( doc.getLineStartOffset(myLineRange.getStartOffset()), doc.getLineEndOffset(myLineRange.getEndOffset())); } final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject()); CommandProcessor.getInstance() .executeCommand( getProject(), new Runnable() { @Override public void run() { ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { document.replaceString(0, document.getTextLength(), text); manager.commitDocument(document); try { TextRange rangeToUse = myTextRange; if (rangeToUse == null) { rangeToUse = file.getTextRange(); } ACTIONS .get(action) .run( file, rangeToUse.getStartOffset(), rangeToUse.getEndOffset()); } catch (IncorrectOperationException e) { assertTrue(e.getLocalizedMessage(), false); } } }); } }, action == Action.REFORMAT ? ReformatCodeProcessor.COMMAND_NAME : "", ""); return document.getText(); }
public static void assertFilesEqual(VirtualFile fileAfter, VirtualFile fileBefore) throws IOException { try { assertJarFilesEqual( VfsUtilCore.virtualToIoFile(fileAfter), VfsUtilCore.virtualToIoFile(fileBefore)); } catch (IOException e) { FileDocumentManager manager = FileDocumentManager.getInstance(); Document docBefore = manager.getDocument(fileBefore); boolean canLoadBeforeText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN; String textB = docBefore != null ? docBefore.getText() : !canLoadBeforeText ? null : LoadTextUtil.getTextByBinaryPresentation( fileBefore.contentsToByteArray(false), fileBefore) .toString(); Document docAfter = manager.getDocument(fileAfter); boolean canLoadAfterText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN; String textA = docAfter != null ? docAfter.getText() : !canLoadAfterText ? null : LoadTextUtil.getTextByBinaryPresentation( fileAfter.contentsToByteArray(false), fileAfter) .toString(); if (textA != null && textB != null) { assertEquals(fileAfter.getPath(), textA, textB); } else { Assert.assertArrayEquals( fileAfter.getPath(), fileAfter.contentsToByteArray(), fileBefore.contentsToByteArray()); } } }
private static void assertAfterCommit( Document document, final PsiFile file, String oldPsiText, FileElement myTreeElementBeingReparsedSoItWontBeCollected) { if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) { final String documentText = document.getText(); if (ApplicationManagerEx.getApplicationEx().isInternal()) { String fileText = file.getText(); LOG.error( "commitDocument left PSI inconsistent; file len=" + myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() + "; doc len=" + document.getTextLength() + "; doc.getText() == file.getText(): " + Comparing.equal(fileText, documentText) + ";\n file psi text=" + fileText + ";\n doc text=" + documentText + ";\n old psi file text=" + oldPsiText); } else { LOG.error("commitDocument left PSI inconsistent: " + file); } file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE); try { BlockSupport blockSupport = BlockSupport.getInstance(file.getProject()); final DiffLog diffLog = blockSupport.reparseRange( file, 0, documentText.length(), 0, documentText, new ProgressIndicatorBase()); CodeStyleManager.getInstance(file.getProject()) .performActionWithFormatterDisabled( new Runnable() { @Override public void run() { synchronized (PsiLock.LOCK) { doActualPsiChange(file, diffLog); } } }); if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) { LOG.error("PSI is broken beyond repair in: " + file); } } finally { file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null); } } }
private void extractExpectedLineMarkerSet(Document document) { String text = document.getText(); String pat = ".*?((<" + LINE_MARKER + ")(?: descr=\"((?:[^\"\\\\]|\\\\\")*)\")?>)(.*)"; final Pattern p = Pattern.compile(pat, Pattern.DOTALL); final Pattern pat2 = Pattern.compile("(.*?)(</" + LINE_MARKER + ">)(.*)", Pattern.DOTALL); while (true) { Matcher m = p.matcher(text); if (!m.matches()) break; int startOffset = m.start(1); final String descr = m.group(3) != null ? m.group(3) : ANY_TEXT; String rest = m.group(4); document.replaceString(startOffset, m.end(1), ""); final Matcher matcher2 = pat2.matcher(rest); LOG.assertTrue(matcher2.matches(), "Cannot find closing </" + LINE_MARKER + ">"); String content = matcher2.group(1); int endOffset = startOffset + matcher2.start(3); String endTag = matcher2.group(2); document.replaceString(startOffset, endOffset, content); endOffset -= endTag.length(); LineMarkerInfo markerInfo = new LineMarkerInfo<PsiElement>( myFile, new TextRange(startOffset, endOffset), null, Pass.LINE_MARKERS, new ConstantFunction<>(descr), null, GutterIconRenderer.Alignment.RIGHT); myLineMarkerInfos.put(document.createRangeMarker(startOffset, endOffset), markerInfo); text = document.getText(); } }
public void testPsi2Doc1() throws Exception { StringBuilder buffer = new StringBuilder("0123456789"); RangeMarker marker = createMarker(buffer.toString(), 2, 5); synchronizer.startTransaction(getProject(), document, psiFile); synchronizer.insertString(document, 3, "a"); buffer.insert(3, "a"); synchronizer.commitTransaction(this.document); assertEquals(buffer.toString(), document.getText()); assertValidMarker(marker, 2, 6); }
protected Set<AbstractElement> computeFollowElements(final CompletionParameters parameters) { Editor _editor = parameters.getEditor(); Document _document = _editor.getDocument(); PsiElement _position = parameters.getPosition(); ASTNode _node = _position.getNode(); int _startOffset = _node.getStartOffset(); TextRange _textRange = new TextRange(0, _startOffset); final String text = _document.getText(_textRange); final Collection<FollowElement> followElements = this.contentAssistParser.getFollowElements(text, false); final HashSet<AbstractElement> allElements = CollectionLiterals.<AbstractElement>newHashSet(); this.followElementComputer.computeFollowElements(followElements, allElements); return allElements; }
public void read() { VirtualFile virtualFile = this.getVirtualFile(); if (virtualFile == null) { Flog.warn("Can't get virtual file to read from disk %s", this); return; } Document d = Buf.getDocumentForVirtualFile(virtualFile); if (d == null) { Flog.warn("Can't get document to read from disk %s", this); return; } this.buf = d.getText(); this.md5 = DigestUtils.md5Hex(this.buf); }
private static PsiElement itIsTheClosingCurlyBraceWeAreMoving( final PsiFile file, final Editor editor) { LineRange range = getLineRangeFromSelection(editor); if (range.endLine - range.startLine != 1) return null; int offset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); int line = document.getLineNumber(offset); int lineStartOffset = document.getLineStartOffset(line); String lineText = document.getText().substring(lineStartOffset, document.getLineEndOffset(line)); if (!lineText.trim().equals("}")) return null; return file.findElementAt(lineStartOffset + lineText.indexOf('}')); }
public void doTextTest( @NotNull final Action action, @NotNull String text, @NotNull String textAfter) throws IncorrectOperationException { final PsiFile file = createFile("A.java", text); final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject()); final Document document = manager.getDocument(file); if (document == null) { fail("Document is null"); return; } replaceAndProcessDocument(action, text, file, document); assertEquals(textAfter, document.getText()); manager.commitDocument(document); assertEquals(textAfter, file.getText()); }
private void surroundWithCodeBlock(@NotNull final MoveInfo info, final boolean down) { try { final Document document = PsiDocumentManager.getInstance(statementToSurroundWithCodeBlock.getProject()) .getDocument(statementToSurroundWithCodeBlock.getContainingFile()); int startOffset = document.getLineStartOffset(info.toMove.startLine); int endOffset = getLineStartSafeOffset(document, info.toMove.endLine); if (document.getText().charAt(endOffset - 1) == '\n') endOffset--; final RangeMarker lineRangeMarker = document.createRangeMarker(startOffset, endOffset); final PsiElementFactory factory = JavaPsiFacade.getInstance(statementToSurroundWithCodeBlock.getProject()) .getElementFactory(); PsiCodeBlock codeBlock = factory.createCodeBlock(); codeBlock.add(statementToSurroundWithCodeBlock); final PsiBlockStatement blockStatement = (PsiBlockStatement) factory.createStatementFromText("{}", statementToSurroundWithCodeBlock); blockStatement.getCodeBlock().replace(codeBlock); PsiBlockStatement newStatement = (PsiBlockStatement) statementToSurroundWithCodeBlock.replace(blockStatement); newStatement = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(newStatement); info.toMove = new LineRange( document.getLineNumber(lineRangeMarker.getStartOffset()), document.getLineNumber(lineRangeMarker.getEndOffset()) + 1); PsiCodeBlock newCodeBlock = newStatement.getCodeBlock(); if (down) { PsiElement blockChild = firstNonWhiteElement(newCodeBlock.getFirstBodyElement(), true); if (blockChild == null) blockChild = newCodeBlock.getRBrace(); info.toMove2 = new LineRange( info.toMove2 .startLine, // document.getLineNumber(newCodeBlock.getParent().getTextRange().getStartOffset()), document.getLineNumber(blockChild.getTextRange().getStartOffset())); } else { int start = document.getLineNumber(newCodeBlock.getRBrace().getTextRange().getStartOffset()); int end = info.toMove.startLine; if (start > end) end = start; info.toMove2 = new LineRange(start, end); } } catch (IncorrectOperationException e) { LOG.error(e); } }
public boolean process( @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile psiFile) { final Document document = editor.getDocument(); final String textForRollback = document.getText(); try { editor.putUserData(SMART_ENTER_TIMESTAMP, editor.getDocument().getModificationStamp()); myFirstErrorOffset = Integer.MAX_VALUE; process(project, editor, psiFile, 0); } catch (TooManyAttemptsException e) { document.replaceString(0, document.getTextLength(), textForRollback); } finally { editor.putUserData(SMART_ENTER_TIMESTAMP, null); } return true; }
public ExpectedHighlightingData(@NotNull final Document document, PsiFile file) { myDocument = document; myFile = file; myText = document.getText(); highlightingTypes = new LinkedHashMap<String, ExpectedHighlightingSet>(); new WriteCommandAction.Simple(file == null ? null : file.getProject()) { public void run() { boolean checkWarnings = false; boolean checkWeakWarnings = false; boolean checkInfos = false; highlightingTypes.put( ERROR_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, false, true)); highlightingTypes.put( WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, checkWarnings)); highlightingTypes.put( WEAK_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WEAK_WARNING, false, checkWeakWarnings)); highlightingTypes.put( "inject", new ExpectedHighlightingSet( HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, checkInfos)); highlightingTypes.put( INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, checkInfos)); highlightingTypes.put( "symbolName", new ExpectedHighlightingSet(HighlightInfoType.SYMBOL_TYPE_SEVERITY, false, false)); for (SeveritiesProvider provider : Extensions.getExtensions(SeveritiesProvider.EP_NAME)) { for (HighlightInfoType type : provider.getSeveritiesHighlightInfoTypes()) { final HighlightSeverity severity = type.getSeverity(null); highlightingTypes.put( severity.getName(), new ExpectedHighlightingSet(severity, false, true)); } } highlightingTypes.put( END_LINE_HIGHLIGHT_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, true, true)); highlightingTypes.put( END_LINE_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, checkWarnings)); initAdditionalHighlightingTypes(); } }.execute().throwException(); }
@Override public Result preprocessEnter( @NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffsetRef, @NotNull final Ref<Integer> caretAdvance, @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) { int caretOffset = caretOffsetRef.get().intValue(); PsiElement psiAtOffset = file.findElementAt(caretOffset); if (psiAtOffset != null && psiAtOffset.getTextOffset() < caretOffset) { ASTNode token = psiAtOffset.getNode(); Document document = editor.getDocument(); CharSequence text = document.getText(); final Language language = psiAtOffset.getLanguage(); final Commenter languageCommenter = LanguageCommenters.INSTANCE.forLanguage(language); final CodeDocumentationAwareCommenter commenter = languageCommenter instanceof CodeDocumentationAwareCommenter ? (CodeDocumentationAwareCommenter) languageCommenter : null; if (commenter != null && token.getElementType() == commenter.getLineCommentTokenType()) { final int offset = CharArrayUtil.shiftForward(text, caretOffset, " \t"); if (offset < document.getTextLength() && text.charAt(offset) != '\n') { String prefix = commenter.getLineCommentPrefix(); assert prefix != null : "Line Comment type is set but Line Comment Prefix is null!"; if (!StringUtil.startsWith(text, offset, prefix)) { if (text.charAt(caretOffset) != ' ' && !prefix.endsWith(" ")) { prefix += " "; } document.insertString(caretOffset, prefix); return Result.Default; } else { int afterPrefix = offset + prefix.length(); if (afterPrefix < document.getTextLength() && text.charAt(afterPrefix) != ' ') { document.insertString(afterPrefix, " "); // caretAdvance.set(0); } caretOffsetRef.set(offset); } return Result.Default; } } } return Result.Continue; }
@Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } for (StudyActionListener listener : Extensions.getExtensions(StudyActionListener.EP_NAME)) { listener.beforeCheck(e); } final AnswerPlaceholder answerPlaceholder = getAnswerPlaceholder(e); if (answerPlaceholder == null) { return; } StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project); final StudyState studyState = new StudyState(studyEditor); if (answerPlaceholder.getTaskFile().getTask().hasSubtasks()) { StudySubtaskUtils.refreshPlaceholder(studyState.getEditor(), answerPlaceholder); return; } Document patternDocument = StudyUtils.getPatternDocument( answerPlaceholder.getTaskFile(), studyState.getVirtualFile().getName()); if (patternDocument == null) { return; } AnswerPlaceholder.MyInitialState initialState = answerPlaceholder.getInitialState(); int startOffset = initialState.getOffset(); final String text = patternDocument.getText(new TextRange(startOffset, startOffset + initialState.getLength())); CommandProcessor.getInstance() .executeCommand( project, () -> ApplicationManager.getApplication() .runWriteAction( () -> { Document document = studyState.getEditor().getDocument(); int offset = answerPlaceholder.getOffset(); document.deleteString(offset, offset + answerPlaceholder.getRealLength()); document.insertString(offset, text); }), NAME, null); }