Java Code Examples for org.eclipse.ui.texteditor.IDocumentProvider#getDocument()

The following examples show how to use org.eclipse.ui.texteditor.IDocumentProvider#getDocument() . 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: EditorUtils.java    From typescript.java with MIT License 6 votes vote down vote up
public static Position getPosition(IFile file, TextSpan textSpan) throws BadLocationException {
	ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
	ITextFileBuffer buffer = bufferManager.getTextFileBuffer(file.getLocation(), LocationKind.IFILE);
	if (buffer != null) {
		return getPosition(buffer.getDocument(), textSpan);
	}
	IDocumentProvider provider = new TextFileDocumentProvider();
	try {
		provider.connect(file);
		IDocument document = provider.getDocument(file);
		if (document != null) {
			return getPosition(document, textSpan);
		}
	} catch (CoreException e) {
	} finally {
		provider.disconnect(file);
	}
	return null;
}
 
Example 2
Source File: TestEditor.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
private void initializeSourceViewer(IEditorInput input) {

		IDocumentProvider documentProvider = getDocumentProvider();
		IAnnotationModel model = documentProvider.getAnnotationModel(input);
		IDocument document = documentProvider.getDocument(input);

		if (document != null) {
			fSourceViewer.setDocument(document, model);
			fSourceViewer.setEditable(isEditable());
			fSourceViewer.showAnnotations(model != null);
		}

		if (fElementStateListener instanceof IElementStateListenerExtension) {
			boolean isStateValidated = false;
			if (documentProvider instanceof IDocumentProviderExtension)
				isStateValidated = ((IDocumentProviderExtension) documentProvider)
						.isStateValidated(input);

			IElementStateListenerExtension extension = (IElementStateListenerExtension) fElementStateListener;
			extension.elementStateValidationChanged(input, isStateValidated);
		}

	}
 
Example 3
Source File: MarkUtils.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
private static void removeDocumentListeners(ITextEditor editor) {
	if (docListener != null) {
		IDocumentProvider idp = editor.getDocumentProvider();
		IDocument document;
		// add null check for document, due to an unreproducible NPE reported by a clojure user
		if (idp != null && (document = idp.getDocument(editor.getEditorInput())) != null) {
			document.removeDocumentListener(docListener);
		}
	}
	docListener = null;
}
 
Example 4
Source File: DecoratedScriptEditor.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void setScript( String script )
{
	try
	{
		IDocumentProvider provider = getDocumentProvider( );

		if ( provider != null )
		{
			IDocument document = provider.getDocument( getEditorInput( ) );

			if ( document != null )
			{
				document.set( script == null ? "" : script ); //$NON-NLS-1$
				return;
			}
		}
		input = createScriptInput( script );
	}
	finally
	{
		ISourceViewer viewer = getSourceViewer( );

		if ( viewer instanceof SourceViewer )
		{
			IUndoManager undoManager = ( (SourceViewer) viewer ).getUndoManager( );

			if ( undoManager != null )
			{
				undoManager.reset( );
			}
		}
	}
}
 
Example 5
Source File: BaseOutlinePage.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parsed partition creates an outline that shows imports/classes/methods
 */
protected void createParsedOutline() {
    final TreeViewer tree = getTreeViewer();
    IDocumentProvider provider = editorView.getDocumentProvider();
    document = provider.getDocument(editorView.getEditorInput());
    tree.setAutoExpandLevel(2);
    tree.setContentProvider(new ParsedContentProvider());
    tree.setLabelProvider(new ParsedLabelProvider(imageCache));
    tree.setInput(getOutlineModel().getRoot());
}
 
Example 6
Source File: TypeScriptEditor.java    From typescript.java with MIT License 5 votes vote down vote up
public void uninstall() {
	ISourceViewer sourceViewer = getSourceViewer();
	if (sourceViewer != null)
		sourceViewer.removeTextInputListener(this);

	IDocumentProvider documentProvider = getDocumentProvider();
	if (documentProvider != null) {
		IDocument document = documentProvider.getDocument(getEditorInput());
		if (document != null)
			document.removeDocumentListener(this);
	}
}
 
Example 7
Source File: JavaCorrectionAssistant.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IRegion getRegionOfInterest(ITextEditor editor, int invocationLocation) throws BadLocationException {
	IDocumentProvider documentProvider= editor.getDocumentProvider();
	if (documentProvider == null) {
		return null;
	}
	IDocument document= documentProvider.getDocument(editor.getEditorInput());
	if (document == null) {
		return null;
	}
	return document.getLineInformationOfOffset(invocationLocation);
}
 
Example 8
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void uninstall() {
	ISourceViewer sourceViewer= getSourceViewer();
	if (sourceViewer != null)
		sourceViewer.removeTextInputListener(this);

	IDocumentProvider documentProvider= getDocumentProvider();
	if (documentProvider != null) {
		IDocument document= documentProvider.getDocument(getEditorInput());
		if (document != null)
			document.removeDocumentListener(this);
	}
}
 
Example 9
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the line base selection values for the given editor part.
 *
 * <p>The given editor part must not be <code>null</code>.
 *
 * @param editorPart the editorPart for which to get the text selection
 * @return the line base selection values for the given editor part or {@link
 *     TextSelection#EMPTY_SELECTION} if the given editor part is is <code>null</code> or not a
 *     text editor, the editor does not have a valid selection provider or document provider, a
 *     valid IDocument could not be obtained form the document provider, or the correct line
 *     numbers or in-lin offsets could not be calculated
 */
public static TextSelection getSelection(IEditorPart editorPart) {
  if (!(editorPart instanceof ITextEditor)) {
    return TextSelection.EMPTY_SELECTION;
  }

  ITextEditor textEditor = (ITextEditor) editorPart;
  ISelectionProvider selectionProvider = textEditor.getSelectionProvider();

  if (selectionProvider == null) {
    return TextSelection.EMPTY_SELECTION;
  }

  IDocumentProvider documentProvider = textEditor.getDocumentProvider();

  if (documentProvider == null) {
    return TextSelection.EMPTY_SELECTION;
  }

  IDocument document = documentProvider.getDocument(editorPart.getEditorInput());

  if (document == null) {
    return TextSelection.EMPTY_SELECTION;
  }

  ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection();
  int offset = textSelection.getOffset();
  int length = textSelection.getLength();

  return calculateSelection(document, offset, length);
}
 
Example 10
Source File: UndoManager.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
protected void fireActivity(TextEditActivity activity) {

    expectedActivities.add(activity);

    List<ITextOperation> textOps = activity.toOperation().getTextOperations();

    org.eclipse.core.resources.IFile file = ((EclipseFileImpl) currentActiveEditor).getDelegate();

    FileEditorInput input = new FileEditorInput(file);
    IDocumentProvider provider = EditorAPI.connect(input);

    if (provider == null) return;

    try {

      IDocument doc = provider.getDocument(input);
      if (doc == null) {
        log.error(
            "Could not connect to a document provider on file '" + file.toString() + "':",
            new StackTrace());
        return;
      }

      for (ITextOperation textOp : textOps) {
        int offset = EditorAPI.calculateOffset(doc, textOp.getStartPosition());

        try {
          if (textOp instanceof DeleteOperation) doc.replace(offset, textOp.getText().length(), "");
          if (textOp instanceof InsertOperation) doc.replace(offset, 0, textOp.getText());
        } catch (BadLocationException e) {
          log.error("Invalid location for " + textOp);
        }
      }
    } finally {
      provider.disconnect(input);
    }
  }
 
Example 11
Source File: QuickXFind.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchRegion getSearchRegion(IFindReplaceTarget target, IEditorPart editorPart) 
    {
        SearchRegion searchRegion = null;
        
        String text = target.getSelectionText();
        Point range = target.getSelection();
        if (range.y > 0) {
            searchRegion = new SearchRegion(text, range.x, range.y);
        }
        else if (editorPart instanceof ITextEditor) {
            ISelection selection = ((ITextEditor) editorPart).getSelectionProvider().getSelection();
            if (selection instanceof ITextSelection) {
                int offset = ((ITextSelection)selection).getOffset();
                IDocumentProvider provider = ((ITextEditor) editorPart).getDocumentProvider();
                IEditorInput input = editorPart.getEditorInput();
                if ((provider != null) && (input != null)) {
                    IDocument document = provider.getDocument(input);
                    if (document != null) {
                        searchRegion = getSearchRegion(document, offset);
                        if (searchRegion != null) {
//                            ITextSelection textSelection = new TextSelection(
//                                document, searchRegion.offset, searchRegion.length
//                            );
//                            ((ITextEditor) editorPart).getSelectionProvider().setSelection(textSelection);
                            searchRegion = new SearchRegion(
                                searchRegion.text, 
                                searchRegion.offset + (range.x - offset), 
                                searchRegion.length  
                            );
                        }
                    }
                }
            }
        }
        
        return searchRegion;
    }
 
Example 12
Source File: ModulaTextFormatter.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Calculates max() indent level for the given lines
 */
public int calcMaxIndentLevel(ITextEditor editor, List<Integer> lineNums) {
    try {
        IDocument doc = null;
        ModulaAst ast = null;
        IDocumentProvider provider = ((ITextEditor) editor).getDocumentProvider();
        IEditorInput input = editor.getEditorInput();
        if ((provider != null) && (input instanceof IFileEditorInput)) {
            IFile ifile = ((IFileEditorInput)input).getFile();
            doc = provider.getDocument(input);
            XdsSourceType sourceType = ModulaFileUtils.getSourceType(input.getName());
            BuildSettings buildSettings = BuildSettingsCache.createBuildSettings(ifile);
            ParserCriticalErrorReporter errorReporter = ParserCriticalErrorReporter.getInstance();
IImportResolver defaultImportResolver = new DefaultImportResolver(buildSettings, errorReporter, null);
            XdsParser parser = new XdsParser(null, doc.get(), new XdsSettings(buildSettings, sourceType), defaultImportResolver, errorReporter);
            ast = parser.parseModule();
        }
        if (ast == null) { 
            return -1;  // Nothing to do
        }

        buildChunksModel(doc, ast, doc.getLength());
        if (chunks.size() == 0) {
            return -1; // Nothing to do
        }
        
        int max = -1;
        for (int lnum : lineNums) {
            int chunkIdx = chunkIdxAtPos(doc.getLineOffset(lnum));
            int il = calcIndentLevel(chunkIdx);
            if (il > max) max = il;
        }
        return max;
        
    } catch (Exception e) {}

    return -1;
}
 
Example 13
Source File: ModulaEditor.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private static IDocument getEditorDocument(ITextEditor editor) {
	IDocument document = null;
	IDocumentProvider documentProvider = editor.getDocumentProvider();
	if (documentProvider != null) {
		document = documentProvider.getDocument(editor.getEditorInput());
	}
	return document;
}
 
Example 14
Source File: XtextDocumentUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.19
 */
public IXtextDocument getXtextDocument(IEditorInput editorInput) {
	IDocumentProvider documentProvider = DocumentProviderRegistry.getDefault().getDocumentProvider(editorInput);
	if (documentProvider == null) {
		return null;
	}
	IDocument document = documentProvider.getDocument(editorInput);
	if (document != null) {
		return getXtextDocument(document);
	}
	return null;
}
 
Example 15
Source File: TestEditor.java    From ermaster-b with Apache License 2.0 4 votes vote down vote up
public void elementMoved(final Object originalElement,
		final Object movedElement) {
	if (originalElement != null
			&& originalElement.equals(getEditorInput())) {
		final boolean doValidationAsync = Display.getCurrent() != null;
		Runnable r = new Runnable() {
			public void run() {
				enableSanityChecking(true);

				if (fSourceViewer == null)
					return;

				if (movedElement == null
						|| movedElement instanceof IEditorInput) {

					final IDocumentProvider d = getDocumentProvider();
					final String previousContent;
					IDocumentUndoManager previousUndoManager = null;
					IDocument changed = null;
					boolean wasDirty = isDirty();
					changed = d.getDocument(getEditorInput());
					if (changed != null) {
						if (wasDirty)
							previousContent = changed.get();
						else
							previousContent = null;

						previousUndoManager = DocumentUndoManagerRegistry
								.getDocumentUndoManager(changed);
						if (previousUndoManager != null)
							previousUndoManager.connect(this);
					} else
						previousContent = null;

					setInput((IEditorInput) movedElement);

					// The undo manager needs to be replaced with one
					// for the new document.
					// Transfer the undo history and then disconnect
					// from the old undo manager.
					if (previousUndoManager != null) {
						IDocument newDocument = getDocumentProvider()
								.getDocument(movedElement);
						if (newDocument != null) {
							IDocumentUndoManager newUndoManager = DocumentUndoManagerRegistry
									.getDocumentUndoManager(newDocument);
							if (newUndoManager != null)
								newUndoManager
										.transferUndoHistory(previousUndoManager);
						}
						previousUndoManager.disconnect(this);
					}

					if (wasDirty && changed != null) {
						Runnable r2 = new Runnable() {
							public void run() {
								validateState(getEditorInput());
								d.getDocument(getEditorInput()).set(
										previousContent);

							}
						};
						execute(r2, doValidationAsync);
					}

				}
			}
		};
		execute(r, false);
	}
}
 
Example 16
Source File: EditorManager.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Programmatically saves the given editor IF and only if the file is registered as a connected
 * file.
 *
 * <p>Calling this method will trigger a call to all registered SharedEditorListeners (independent
 * of the success of this method) BEFORE the file is actually saved.
 *
 * <p>Calling this method will NOT trigger a {@link EditorActivity} of type Save to be sent to the
 * other clients.
 *
 * @param wrappedFile the file that is supposed to be saved to disk.
 * @swt This method must be called from the SWT thread
 * @nonReentrant This method cannot be called twice at the same time.
 */
public void saveEditor(saros.filesystem.IFile wrappedFile) {
  checkThreadAccess();

  IFile file = ((EclipseFileImpl) wrappedFile).getDelegate();

  log.trace(".saveEditor (" + file.getName() + ") invoked");

  if (!file.exists()) {
    log.warn("File not found for saving: " + wrappedFile.toString(), new StackTrace());
    return;
  }

  FileEditorInput input = new FileEditorInput(file);
  IDocumentProvider provider = EditorAPI.connect(input);

  if (provider == null) return;

  if (!provider.canSaveDocument(input)) {
    /*
     * This happens when a file which is already saved is saved again by
     * a user.
     */
    log.debug(".saveEditor File " + file.getName() + " does not need to be saved");
    provider.disconnect(input);
    return;
  }

  log.trace(".saveEditor File " + file.getName() + " will be saved");

  final boolean isConnected = isManaged(file);

  /*
   * connect to the file so the SharedResourceManager /
   * ProjectDeltaVisitor will ignore the file change because it is
   * possible that no editor is open for this file
   */
  if (!isConnected) connect(file);

  IDocument doc = provider.getDocument(input);

  // TODO Why do we need to connect to the annotation model here?
  IAnnotationModel model = provider.getAnnotationModel(input);
  if (model != null) model.connect(doc);

  log.trace(".saveEditor Annotations on the IDocument are set");

  editorPool.setElementStateListenerEnabled(false);

  try {
    provider.saveDocument(new NullProgressMonitor(), input, doc, true);
    log.debug("Saved document: " + wrappedFile);
  } catch (CoreException e) {
    log.error("Failed to save document: " + wrappedFile, e);
  }

  editorPool.setElementStateListenerEnabled(true);

  if (model != null) model.disconnect(doc);

  provider.disconnect(input);

  if (!isConnected) disconnect(file);
}
 
Example 17
Source File: AbstractFormEditor.java    From typescript.java with MIT License 4 votes vote down vote up
public IDocument getDocument() {
	IDocumentProvider provider = jsonEditor.getDocumentProvider();
	return provider.getDocument(getEditorInput());
}
 
Example 18
Source File: JavaElementHyperlinkDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
	ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
	if (region == null || !(textEditor instanceof JavaEditor))
		return null;

	IAction openAction= textEditor.getAction("OpenEditor"); //$NON-NLS-1$
	if (!(openAction instanceof SelectionDispatchAction))
		return null;

	int offset= region.getOffset();

	ITypeRoot input= EditorUtility.getEditorInputJavaElement(textEditor, false);
	if (input == null)
		return null;

	try {
		IDocumentProvider documentProvider= textEditor.getDocumentProvider();
		IEditorInput editorInput= textEditor.getEditorInput();
		IDocument document= documentProvider.getDocument(editorInput);
		IRegion wordRegion= JavaWordFinder.findWord(document, offset);
		if (wordRegion == null || wordRegion.getLength() == 0)
			return null;

		if (isInheritDoc(document, wordRegion) && getClass() != JavaElementHyperlinkDetector.class)
			return null;

		if (JavaElementHyperlinkDetector.class == getClass() && findBreakOrContinueTarget(input, region) != null)
			return new IHyperlink[] { new JavaElementHyperlink(wordRegion, (SelectionDispatchAction)openAction, null, false) };
		
		IJavaElement[] elements;
		long modStamp= documentProvider.getModificationStamp(editorInput);
		if (input.equals(fLastInput) && modStamp == fLastModStamp && wordRegion.equals(fLastWordRegion)) {
			elements= fLastElements;
		} else {
			elements= ((ICodeAssist) input).codeSelect(wordRegion.getOffset(), wordRegion.getLength());
			elements= selectOpenableElements(elements);
			fLastInput= input;
			fLastModStamp= modStamp;
			fLastWordRegion= wordRegion;
			fLastElements= elements;
		}
		if (elements.length == 0)
			return null;
		
		ArrayList<IHyperlink> links= new ArrayList<IHyperlink>(elements.length);
		for (int i= 0; i < elements.length; i++) {
			addHyperlinks(links, wordRegion, (SelectionDispatchAction)openAction, elements[i], elements.length > 1, (JavaEditor)textEditor);
		}
		if (links.size() == 0)
			return null;
		
		return CollectionsUtil.toArray(links, IHyperlink.class);

	} catch (JavaModelException e) {
		return null;
	}
}
 
Example 19
Source File: AnnotateView.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Show the annotation view.
 * @param svnFile
 * @param svnAnnotateBlocks
 * @param contents
 * @param useHistoryView
 * @throws PartInitException
 */
public void showAnnotations(ISVNRemoteFile svnFile, Collection svnAnnotateBlocks, InputStream contents, boolean useHistoryView) throws PartInitException {

	// Disconnect from old annotation editor
	disconnect();
	
	// Remove old viewer
	Control[] oldChildren = top.getChildren();
	if (oldChildren != null) {
		for (int i = 0; i < oldChildren.length; i++) {
			oldChildren[i].dispose();
		}
	}

	viewer = new ListViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL);
	viewer.setContentProvider(new ArrayContentProvider());
	viewer.setLabelProvider(new LabelProvider());
	viewer.addSelectionChangedListener(this);
	viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));

	PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), IHelpContextIds.ANNOTATIONS_VIEW);

	top.layout();
	
	this.svnFile = svnFile;
	this.contents = contents;
	this.svnAnnotateBlocks = svnAnnotateBlocks;
	page = SVNUIPlugin.getActivePage();
	viewer.setInput(svnAnnotateBlocks);
	editor = (ITextEditor) openEditor();
	IDocumentProvider provider = editor.getDocumentProvider();
	document = provider.getDocument(editor.getEditorInput());

	setPartName(Policy.bind("SVNAnnotateView.showFileAnnotation", new Object[] {svnFile.getName()})); //$NON-NLS-1$
	setTitleToolTip(svnFile.getName());
	
	if (!useHistoryView) {
		return;
	}

	// Get hook to the HistoryView
	historyView = (IHistoryView)page.showView(ISVNUIConstants.HISTORY_VIEW_ID);
	if (historyView != null) {
		historyView.showHistoryFor(svnFile);
	}
}
 
Example 20
Source File: EditorPool.java    From saros with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Removes an {@link IEditorPart} from the pool and makes the editor editable again.
 *
 * <p>This Method also disconnects the editorPart from its data source (identified by associated
 * {@link IFile}) and removes registered listeners:
 *
 * <ul>
 *   <li>{@link IElementStateListener} from {@link IDocumentProvider}
 *   <li>{@link IDocumentListener} from {@link IDocument}
 *   <li>{@link EditorListener} from {@link IEditorPart}
 * </ul>
 *
 * @param editorPart editorPart to be removed
 */
public void remove(final IEditorPart editorPart) {
  log.trace("removing editor part " + editorPart + " [" + editorPart.getTitle() + "]");

  if (!isManaged(editorPart)) {
    log.error("editor part is not managed: " + editorPart);
    return;
  }

  final EditorPartInputReferences inputRefs = editorInputMap.remove(editorPart);

  final IEditorInput input = inputRefs.input;
  final IFile file = inputRefs.file;

  // Unregister and unhook
  setEditable(editorPart, true);

  editorListeners.remove(editorPart).unbind();

  final IDocumentProvider documentProvider = EditorAPI.getDocumentProvider(input);

  dirtyStateListener.unregister(documentProvider, input);

  final IDocument document = documentProvider.getDocument(input);

  if (document == null) {
    log.warn("could not disconnect from document: " + file);
  } else {
    document.removeDocumentListener(documentListener);
  }

  editorManager.disconnect(file);

  final saros.filesystem.IFile wrappedFile = ResourceAdapterFactory.create(file);

  editorParts.get(wrappedFile).remove(editorPart);
}