org.eclipse.jface.text.DocumentRewriteSessionType Java Examples

The following examples show how to use org.eclipse.jface.text.DocumentRewriteSessionType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChangeManager.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Applies all given changes to the given document. This method assumes that 'changes' contains only changes
 * intended for the given document; the actual URI stored in the changes is ignored.
 */
public void applyAllInSameDocument(Collection<? extends IAtomicChange> changes, IDocument document)
		throws BadLocationException {
	DocumentRewriteSession rewriteSession = null;
	try {
		// prepare
		if (document instanceof IDocumentExtension4) {
			rewriteSession = ((IDocumentExtension4) document).startRewriteSession(
					DocumentRewriteSessionType.UNRESTRICTED);
		}
		// perform replacements
		for (IAtomicChange currRepl : changes) {
			currRepl.apply(document);
		}
	} finally {
		// cleanup
		if (rewriteSession != null)
			((IDocumentExtension4) document).stopRewriteSession(rewriteSession);
	}
}
 
Example #2
Source File: XtextTemplateProposal.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
	IDocument document = viewer.getDocument();
	// ImportsVariableResolver may add imports, so start a rewrite session if possible. 
	// This will compound all document changes in one Undo entry.
	if (document instanceof IDocumentExtension4) {
		IDocumentExtension4 docExt4 = (IDocumentExtension4) document;
		DocumentRewriteSession session = docExt4.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
		super.apply(viewer, trigger, stateMask, offset);
		if (session != null) {
			docExt4.stopRewriteSession(session);
		}
	} else {
		super.apply(viewer, trigger, stateMask, offset);
	}
}
 
Example #3
Source File: OrganizeImportsHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void doOrganizeImports(final IXtextDocument document) {
	List<ReplaceRegion> result = document.priorityReadOnly(new IUnitOfWork<List<ReplaceRegion>, XtextResource>() {
		@Override
		public List<ReplaceRegion> exec(XtextResource state) throws Exception {
			return importOrganizer.getOrganizedImportChanges(state);
		}
	});
	if (result == null || result.isEmpty())
		return;
	try {
		DocumentRewriteSession session = null;
		if(document instanceof IDocumentExtension4) {
			session = ((IDocumentExtension4)document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
		}
		replaceConverter.convertToTextEdit(result).apply(document);
		if(session != null) {
			((IDocumentExtension4)document).stopRewriteSession(session);
		}
	} catch (BadLocationException e) {
		LOG.error(Messages.OrganizeImportsHandler_organizeImportsErrorMessage, e);
	}
}
 
Example #4
Source File: TLCModelLaunchDataProvider.java    From tlaplus with MIT License 6 votes vote down vote up
/**
    * Sets text to a document
    * @param document
    * @param message
    * @param append
    * @throws BadLocationException
    * Has to be run from non-UI thread
    */
public static synchronized void setDocumentText(final Document document, final String message,
		final boolean append) {

	UIHelper.runUIAsync(new Runnable() {
		public void run() {
			try {
				DocumentRewriteSession rewriteSession;
				if (append && !isDefaultLabel(document)) {
					rewriteSession = document.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
					// append to existing document (0 length is valid and means message is going to be appended)
					document.replace(document.getLength(), 0, message + ((message.endsWith(CR)) ? EMPTY : CR));
				} else {
					rewriteSession = document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
					// replace of complete document
					document.replace(0, document.getLength(), message + ((message.endsWith(CR)) ? EMPTY : CR));
				}
				document.stopRewriteSession(rewriteSession);
			} catch (BadLocationException ignored) {
			}
		}
	});
}
 
Example #5
Source File: BusinessDataModelFormPart.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void commit(boolean onSave) {
    BusinessObjectModel workingCopy = formPage.observeWorkingCopy().getValue();
    JobSafeStructuredDocument document = (JobSafeStructuredDocument) formPage.getDocument();
    DocumentRewriteSession session = null;
    try {
        session = document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
        document.set(new String(formPage.getParser().marshall(formPage.getConverter().toEngineModel(workingCopy))));
        BDMArtifactDescriptor bdmArtifactDescriptor = new BDMArtifactDescriptor();
        bdmArtifactDescriptor.setGroupId(workingCopy.getGroupId());
        formPage.getEditorContribution().saveBdmArtifactDescriptor(bdmArtifactDescriptor);
    } catch (final JAXBException | IOException | SAXException e) {
        throw new RuntimeException("Fail to update the document", e);
    } finally {
        if (session != null) {
            document.stopRewriteSession(session);
        }
    }
    super.commit(onSave);
    if (onSave) {
        getManagedForm().dirtyStateChanged();
    }
}
 
Example #6
Source File: EditorDocumentUndoChange.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected UndoEdit performEdits(IDocument document) throws BadLocationException, MalformedTreeException {
	DocumentRewriteSession session = null;
	try {
		if (document instanceof IDocumentExtension4) {
			session = ((IDocumentExtension4) document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
		}
		return undoEdit.apply(document);
	} finally {
		if (session != null) {
			((IDocumentExtension4) document).stopRewriteSession(session);
		}
	}
}
 
Example #7
Source File: TextSelectionUtils.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Starts a rewrite session (keep things in a single undo/redo)
 */
public static DocumentRewriteSession startWrite(IDocument doc) {
    if (doc instanceof IDocumentExtension4) {
        IDocumentExtension4 d = (IDocumentExtension4) doc;
        return d.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
    }
    return null;
}
 
Example #8
Source File: AddBlockCommentHandler.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
        IDocument      doc       = WorkbenchUtils.getActiveDocument();
        IEditorInput   input     = WorkbenchUtils.getActiveInput();
        IEditorPart    editor    = WorkbenchUtils.getActiveEditor(false);

        boolean isTextOperationAllowed = (selection != null) && (doc != null) 
                                      && (input != null)     && (editor != null) 
                                      && (editor instanceof ModulaEditor);

        if (isTextOperationAllowed) {
            ITextEditor iTextEditor = (ITextEditor)editor;
            final ITextOperationTarget operationTarget = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
            String commentPrefix = ((SourceCodeTextEditor)editor).getEOLCommentPrefix();
            isTextOperationAllowed = (operationTarget != null)
                                  && (operationTarget instanceof TextViewer)
                                  && (validateEditorInputState(iTextEditor))
                                  && (commentPrefix != null);
            
            if ((isTextOperationAllowed)) {
                int startLine = selection.getStartLine();
                int endLine = selection.getEndLine(); 
                int selOffset = selection.getOffset();
                int selLen = selection.getLength();
                int realEndLine = doc.getLineOfOffset(selOffset + selLen); // for selection end at pos=0 (endLine is line before here) 
                
                // Are cursor and anchor at 0 positions?
                boolean is0pos = false;
                if (doc.getLineOffset(startLine) == selOffset) {
                    if ((doc.getLineOffset(endLine) + doc.getLineLength(endLine) == selOffset + selLen)) {
                        is0pos = true;
                    }
                }
                
                
                ArrayList<ReplaceEdit> edits = null;
                int offsAfter[] = {0};
                if (is0pos || selLen == 0) {
                    edits = commentWholeLines(startLine, (selLen == 0) ? startLine : endLine, realEndLine, doc, offsAfter);
                } else {
                    edits = commentRange(selOffset, selLen, "(*", "*)", offsAfter); //$NON-NLS-1$ //$NON-NLS-2$
                }
                
                if (edits != null && !edits.isEmpty()) {
                    DocumentRewriteSession drws = null;
                    try {
                        if (doc instanceof IDocumentExtension4) {
                            drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
                        }
                        MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
                        edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
                        edit.apply(doc, TextEdit.CREATE_UNDO);
                        iTextEditor.getSelectionProvider().setSelection(new TextSelection(offsAfter[0], 0));
                    }
                    finally {
                        if (doc instanceof IDocumentExtension4 && drws != null) {
                            ((IDocumentExtension4)doc).stopRewriteSession(drws);
                        }
                    }
                    
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #9
Source File: ModulaTextFormatter.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 
 * @param document
 * @param ast
 * @param begPos begin offset of the formatted area (0 to format all)
 * @param endPos end offset of the formatted area (doc.getLength() to format all)
 */
public void doFormat(IDocument doc, ModulaAst ast, int begPos, int endPos, boolean indentOnly) throws Exception {
    buildChunksModel(doc, ast, doc.getLength());
    if (chunks.size() == 0) {
        return; // Nothing to do
    }
    
    int firstChunkIdx = chunkIdxAtPos(begPos);
    int lastChunkIdx  = chunkIdxAtPos(endPos-1);

    { // Fix selection margins to include whole chunks:
        begPos = chunks.get(firstChunkIdx).getOffsetInDoc();
        Chunk c = chunks.get(lastChunkIdx);
        endPos = c.getOffsetInDoc() + c.getLengthInDoc();
    }


    if (lastChunkIdx == chunks.size()-1) {
        // chunks[lastChunkIdx+1] should always be some chunk with offset,
        // it will be required to build format edits from chunk model
        chunks.add(Chunk.createNoPlnChunkFromDoc(doc, doc.getLength(), 0));
    }
    
    // lastChunkIdx may be changed with model so use terminalChunk:
    Chunk terminalChunk = chunks.get(lastChunkIdx+1);  
   
    if (!indentOnly) {
        processNewLines(doc, firstChunkIdx, terminalChunk);
    }

    processWhitespaces(doc, firstChunkIdx, terminalChunk, indentOnly);

    if (!indentOnly) {
        processWrapLines(doc, firstChunkIdx, terminalChunk);
    }

    ArrayList<ReplaceEdit> edits = buildEditsFromModel(doc, firstChunkIdx, terminalChunk);
    
    DocumentRewriteSession drws = null;
    try {
        if (doc instanceof IDocumentExtension4) {
            drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
        }
        MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
        edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
        edit.apply(doc, TextEdit.CREATE_UNDO);
    }
    finally {
        if (doc instanceof IDocumentExtension4 && drws != null) {
            ((IDocumentExtension4)doc).stopRewriteSession(drws);
        }
    }
}
 
Example #10
Source File: TagBasedTLCOutputIncrementalParser.java    From tlaplus with MIT License 4 votes vote down vote up
public TagBasedTLCOutputIncrementalParser(Model model, int prio, boolean isTraceExplorer, Mode mode, final long size)
  {
// create the document
      document = new LargeTextStoreDocument(size);

      this.analyzer = new TagBasedTLCAnalyzer(document);
      this.source = new CachingTLCOutputSource(model, prio);

      // set up the partitioner
      FastPartitioner partitioner = new FastPartitioner(new TagBasedTLCOutputTokenScanner(),
              TagBasedTLCOutputTokenScanner.CONTENT_TYPES);
      partitioner.connect(document);
      document.setDocumentPartitioner(partitioner);
      

      // now register the listener, responsible for evaluating the partitioning information
      document.addDocumentPartitioningListener(new TLCOutputPartitionChangeListener(mode));

      /*
       *  Register the process source
       *  
       *  There are two different source registries, one for trace exploration
       *  and one for model checking. The source must be added to the
       *  appropriate registry.
       */
      if (isTraceExplorer)
      {
          TLCOutputSourceRegistry.getTraceExploreSourceRegistry().addTLCOutputSource(this.source);
      } else
      {
      	if (mode == Mode.BATCH) {
      		// TLC always appends to the document. Therefore, we can tell the
      		// document to use a more efficient rewrite mode which reduces the time
      		// taken to execute replace operations from minutes and hours to
      		// seconds.
		// Its down side is that the ResultPage is only updated when the
		// complete log file is fully parsed, whereas in incremental
		// mode, it (potentially) updates after each line.
      		document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
      	}
      	
          TLCOutputSourceRegistry.getModelCheckSourceRegistry().addTLCOutputSource(this.source);
      }
  }
 
Example #11
Source File: DocCopy.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public DocumentRewriteSession startRewriteSession(DocumentRewriteSessionType sessionType)
        throws IllegalStateException {
    throw new RuntimeException("not implemented");
}