1 11 package org.eclipse.text.edits; 12 13 import org.eclipse.core.runtime.Assert; 14 15 import org.eclipse.jface.text.BadLocationException; 16 import org.eclipse.jface.text.DocumentEvent; 17 import org.eclipse.jface.text.IDocument; 18 import org.eclipse.jface.text.IDocumentListener; 19 20 21 class UndoCollector implements IDocumentListener { 22 23 protected UndoEdit undo; 24 private int fOffset; 25 private int fLength; 26 27 30 private String fLastCurrentText; 31 32 public UndoCollector(TextEdit root) { 33 fOffset= root.getOffset(); 34 fLength= root.getLength(); 35 } 36 37 public void connect(IDocument document) { 38 document.addDocumentListener(this); 39 undo= new UndoEdit(); 40 } 41 42 public void disconnect(IDocument document) { 43 if (undo != null) { 44 document.removeDocumentListener(this); 45 undo.defineRegion(fOffset, fLength); 46 } 47 } 48 49 public void documentChanged(DocumentEvent event) { 50 fLength+= getDelta(event); 51 } 52 53 private static int getDelta(DocumentEvent event) { 54 String text= event.getText(); 55 return text == null ? -event.getLength() : (text.length() - event.getLength()); 56 } 57 58 public void documentAboutToBeChanged(DocumentEvent event) { 59 int offset= event.getOffset(); 60 int currentLength= event.getLength(); 61 String currentText= null; 62 try { 63 currentText= event.getDocument().get(offset, currentLength); 64 } catch (BadLocationException cannotHappen) { 65 Assert.isTrue(false, "Can't happen"); } 67 68 75 if (fLastCurrentText != null && fLastCurrentText.equals(currentText)) 76 currentText= fLastCurrentText; 77 else 78 fLastCurrentText= currentText; 79 80 String newText= event.getText(); 81 undo.add(new ReplaceEdit(offset, newText != null ? newText.length() : 0, currentText)); 82 } 83 } 84 | Popular Tags |