01: /*******************************************************************************
02: * Copyright (c) 2000, 2006 IBM Corporation and others.
03: * All rights reserved. This program and the accompanying materials
04: * are made available under the terms of the Eclipse Public License v1.0
05: * which accompanies this distribution, and is available at
06: * http://www.eclipse.org/legal/epl-v10.html
07: *
08: * Contributors:
09: * IBM Corporation - initial API and implementation
10: *******************************************************************************/package org.eclipse.text.edits;
11:
12: import org.eclipse.core.runtime.Assert;
13:
14: import org.eclipse.jface.text.BadLocationException;
15: import org.eclipse.jface.text.DocumentEvent;
16: import org.eclipse.jface.text.IDocument;
17: import org.eclipse.jface.text.IDocumentListener;
18:
19: class UndoCollector implements IDocumentListener {
20:
21: protected UndoEdit undo;
22: private int fOffset;
23: private int fLength;
24:
25: /**
26: * @since 3.1
27: */
28: private String fLastCurrentText;
29:
30: public UndoCollector(TextEdit root) {
31: fOffset = root.getOffset();
32: fLength = root.getLength();
33: }
34:
35: public void connect(IDocument document) {
36: document.addDocumentListener(this );
37: undo = new UndoEdit();
38: }
39:
40: public void disconnect(IDocument document) {
41: if (undo != null) {
42: document.removeDocumentListener(this );
43: undo.defineRegion(fOffset, fLength);
44: }
45: }
46:
47: public void documentChanged(DocumentEvent event) {
48: fLength += getDelta(event);
49: }
50:
51: private static int getDelta(DocumentEvent event) {
52: String text = event.getText();
53: return text == null ? -event.getLength()
54: : (text.length() - event.getLength());
55: }
56:
57: public void documentAboutToBeChanged(DocumentEvent event) {
58: int offset = event.getOffset();
59: int currentLength = event.getLength();
60: String currentText = null;
61: try {
62: currentText = event.getDocument()
63: .get(offset, currentLength);
64: } catch (BadLocationException cannotHappen) {
65: Assert.isTrue(false, "Can't happen"); //$NON-NLS-1$
66: }
67:
68: /*
69: * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93634
70: * If the same string is replaced on many documents (e.g. rename
71: * package), the size of the undo can be reduced by using the same
72: * String instance in all edits, instead of using the unique String
73: * returned from IDocument.get(int, int).
74: */
75: if (fLastCurrentText != null
76: && fLastCurrentText.equals(currentText))
77: currentText = fLastCurrentText;
78: else
79: fLastCurrentText = currentText;
80:
81: String newText = event.getText();
82: undo.add(new ReplaceEdit(offset, newText != null ? newText
83: .length() : 0, currentText));
84: }
85: }
|