Project: JDT
Bug 117694 [api] Applying edits to a ICompilationUnit
Reported: 2005-11-23 05:36:22 | Status: verified fixed

20051123 It is currently quite difficult to apply a text edit to a compilation unit. Text edits are the result of the code formatter or the import rewriter. Currently edits can only be applied to IDocument. Having a compilation unit in hand, it is a lot of work or inefficient to get the corresponding document: - If the compilation unit is a primary working copy, you go the FileBuffers to get the document: ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager(); IPath path= compilationUnit.getPath(); bufferManager.connect(path, monitor); document= bufferManager.getTextFileBuffer(path).getDocument(); ... textEdit.apply(document).... bufferManager.disconnect(path, monitor); - If the compilation unit is a non-primary working copy then you have to build a document yourself, which is very inefficient (copying content): Document document= new Document(compilationUnit.getSource()) ... textEdit.apply(document).... compilationUnit.getBuffer().setContents(document.get()) We need an easier way to apply edits on documents, to offer a nicer story to clients. Here are some suggestions: a.) Get a document from the compilation unit: openable.getDocument(). The compilation builds a wrapper that implements IDocument but redirects to IBuffer. + simple API - Users must understand that the returned document is not the document managed by filebuffers: Some of the API would be 'not supported', e.g. you don't get positions and have no partitions. Regarding of funtionality, this is not a problem (to apply a change you don't need these features), but could be confusing. b.) Add a method apply(textEdit) to IBuffer. Problem is IBuffer in implemented by clients, so it can not be extended. A new 'extension' could be added, IRichBuffer or abstract class RichBuffer, where clients can check for with a cast. Implementors of WorkingCopyOwner would return such 'rich buffers' and can e.g. forward a call apply(textEdit) directly to the underlying document. + most efficient, no additional indirection + at the same time line position API could be added to the rich buffers, solving the biggest usability problem with buffers. - Extra cast is not so nice. Maybe IOpenable should offer getRichBuffer that replaces getBuffer

Files changed in fix:
org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/DocumentAdapter.java