@NotNull private int[] fixRanges(@NotNull DocumentEvent e, int line1, int line2) { CharSequence document = myDocument.getCharsSequence(); int offset = e.getOffset(); if (e.getOldLength() == 0 && e.getNewLength() != 0) { if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) { return new int[] {line1, line2 - 1}; } if (StringUtil.startsWithChar(e.getNewFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) { return new int[] {line1 + 1, line2}; } } if (e.getOldLength() != 0 && e.getNewLength() == 0) { if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) { return new int[] {line1, line2 - 1}; } if (StringUtil.startsWithChar(e.getOldFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) { return new int[] {line1 + 1, line2}; } } return new int[] {line1, line2}; }
@Override public void beforeDocumentChange(DocumentEvent event) { if (project.isDisposed()) { return; } if (!isListening) { System.out.println("Ignoring change."); return; } VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument()); // Make sure file exists if (file == null) { return; } // Make sure file is in the project if (!ProjectFileIndex.SERVICE.getInstance(project).isInSource(file)) { return; } String dummyIdentifier = "IntellijIdeaRulezzz"; if (!event.getNewFragment().toString().contains(dummyIdentifier)) { if (!event.isWholeTextReplaced()) { // Get path relative to project root (e.g. src/Sample.java) Path basePath = Paths.get(project.getBasePath()); Path absoluteFilePath = Paths.get(file.getPath()); String relativeFilePath = basePath.relativize(absoluteFilePath).toString(); String documentText = event.getDocument().getText(); String oldFragment = event.getOldFragment().toString(); String newFragment = event.getNewFragment().toString(); int offset = event.getOffset(); IOPatcher patcher = new IOPatcher(); LinkedList<Patch> patches = patcher.makePatchAsList(documentText, oldFragment, newFragment, offset); UserEdit edit = new UserEdit(0, relativeFilePath, patches); for (EditorEvent editorEvent : events) { editorEvent.sendChange(edit); } } } }