Java Code Examples for org.eclipse.ui.texteditor.ITextEditor#getDocumentProvider()

The following examples show how to use org.eclipse.ui.texteditor.ITextEditor#getDocumentProvider() . 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: JavaSourceViewerConfiguration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IJavaProject getProject() {
	ITextEditor editor= getEditor();
	if (editor == null)
		return null;

	IJavaElement element= null;
	IEditorInput input= editor.getEditorInput();
	IDocumentProvider provider= editor.getDocumentProvider();
	if (provider instanceof ICompilationUnitDocumentProvider) {
		ICompilationUnitDocumentProvider cudp= (ICompilationUnitDocumentProvider) provider;
		element= cudp.getWorkingCopy(input);
	} else if (input instanceof IClassFileEditorInput) {
		IClassFileEditorInput cfei= (IClassFileEditorInput) input;
		element= cfei.getClassFile();
	}

	if (element == null)
		return null;

	return element.getJavaProject();
}
 
Example 2
Source File: TestResultHyperlink.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void revealLocationInFile(IEditorPart editorPart)
		throws CoreException {
	if (editorPart instanceof ITextEditor && locationText.line > 0) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocumentProvider provider = textEditor.getDocumentProvider();
		IEditorInput editorInput = editorPart.getEditorInput();
		provider.connect(editorInput);
		IDocument document = provider.getDocument(editorInput);
		try {
			IRegion regionOfLine = document.getLineInformation(locationText.line - 1);
			// only used to reveal the location
			textEditor.selectAndReveal(regionOfLine.getOffset(), regionOfLine.getLength());
			int startOffset = regionOfLine.getOffset() + locationText.column - 1;
			int length = regionOfLine.getLength() - locationText.column;
			if (startOffset >= document.getLength()) {
				startOffset = document.getLength() - 1;
			}
			if (length + startOffset >= document.getLength()) {
				length = document.getLength() - startOffset - 1;
			}
			textEditor.setHighlightRange(startOffset, length, true);
		} catch (BadLocationException e) {
			MessageDialog.openInformation(N4JSGracefulActivator.getActiveWorkbenchShell(),
					ConsoleMessages.msgInvalidLineNumberTitle(),
					ConsoleMessages.msgInvalidLineNumberIn(
							(locationText.line) + "",
							locationText.fileName));
		}
		provider.disconnect(editorInput);
	}
}
 
Example 3
Source File: EditorPool.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private static void findAndLogDocumentProviderIssues(final IEditorPart editorPart) {

    final IDocumentProvider defaultDocumentProvider =
        EditorAPI.getDocumentProvider(editorPart.getEditorInput());

    if (!(defaultDocumentProvider instanceof TextFileDocumentProvider)) {
      log.warn(
          "The default document provider "
              + defaultDocumentProvider
              + " for editor with title '"
              + editorPart.getTitle()
              + "' might not support shared access. It is likely that the editor content is not properly synchronized!");

      return;
    }

    final ITextEditor textEditor = editorPart.getAdapter(ITextEditor.class);

    if (textEditor == null) return;

    final IDocumentProvider editorDocumentProvider = textEditor.getDocumentProvider();

    if (!(editorDocumentProvider instanceof TextFileDocumentProvider)) {
      log.warn(
          "The document provider "
              + editorDocumentProvider
              + " for editor with title '"
              + editorPart.getTitle()
              + "' might not support shared access. It is likely that the editor content is not properly synchronized!");
    }
  }
 
Example 4
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 5
Source File: EditorUtils.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public static IDocument getDocument(ITextEditor editor) {
    IDocumentProvider documentProvider = editor.getDocumentProvider();
    if (documentProvider != null) {
        return documentProvider.getDocument(editor.getEditorInput());
    }
    return null;
}
 
Example 6
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 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: IndentAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the document currently displayed in the editor, or <code>null</code> if none can be
 * obtained.
 *
 * @return the current document or <code>null</code>
 */
private IDocument getDocument() {

	ITextEditor editor= getTextEditor();
	if (editor != null) {

		IDocumentProvider provider= editor.getDocumentProvider();
		IEditorInput input= editor.getEditorInput();
		if (provider != null && input != null)
			return provider.getDocument(input);

	}
	return null;
}
 
Example 9
Source File: EditorUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean mustSaveDirtyEditor(IEditorPart ep, IEditorInput input, boolean saveUnknownEditors) {
	/*
	 * Goal: save all editors that could interfere with refactoring operations.
	 *
	 * Always save all editors for compilation units that are not working copies.
	 * (Leaving them dirty would cause problems, since the file buffer could have been
	 * modified but the Java model is not reconciled.)
	 *
	 * If <code>saveUnknownEditors</code> is <code>true</code>, save all editors
	 * whose implementation is probably not based on file buffers.
	 */
	IResource resource= (IResource) input.getAdapter(IResource.class);
	if (resource == null)
		return saveUnknownEditors;

	IJavaElement javaElement= JavaCore.create(resource);
	if (javaElement instanceof ICompilationUnit) {
		ICompilationUnit cu= (ICompilationUnit) javaElement;
		if (!cu.isWorkingCopy()) {
			return true;
		}
	}

	if (! (ep instanceof ITextEditor))
		return saveUnknownEditors;

	ITextEditor textEditor= (ITextEditor) ep;
	IDocumentProvider documentProvider= textEditor.getDocumentProvider();
	if (! (documentProvider instanceof TextFileDocumentProvider))
		return saveUnknownEditors;

	return false;
}
 
Example 10
Source File: IndentAction.java    From typescript.java with MIT License 5 votes vote down vote up
/**
 * Returns the document currently displayed in the editor, or
 * <code>null</code> if none can be obtained.
 * 
 * @return the current document or <code>null</code>
 */
private IDocument getDocument() {

	ITextEditor editor = getTextEditor();
	if (editor != null) {

		IDocumentProvider provider = editor.getDocumentProvider();
		IEditorInput input = editor.getEditorInput();
		if (provider != null && input != null)
			return provider.getDocument(input);

	}
	return null;
}
 
Example 11
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 12
Source File: HasLanguageConfigurationPropertyTester.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
	if (!(receiver instanceof ITextEditor)) {
		return false;
	}
	ITextEditor editor = (ITextEditor) receiver;

	IEditorInput input = editor.getEditorInput();
	IDocumentProvider docProvider = editor.getDocumentProvider();
	if (docProvider == null || input == null) {
		return false;
	}

	IDocument document = docProvider.getDocument(input);
	if (document == null) {
		return false;
	}

	IContentType[] contentTypes;
	try {
		ContentTypeInfo info = ContentTypeHelper.findContentTypes(document);
		if(info == null) {
			return false;
		}
		contentTypes = info.getContentTypes();
	} catch (CoreException e) {
		return false;
	}

	LanguageConfigurationRegistryManager registry = LanguageConfigurationRegistryManager.getInstance();
	return registry.getLanguageConfigurationFor(contentTypes) != null;
}
 
Example 13
Source File: N4JSStackTraceHyperlink.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void revealLocationInFile(String typeName, int line, int column, IEditorPart editorPart)
		throws CoreException {
	if (editorPart instanceof ITextEditor && line >= 0) {
		ITextEditor textEditor = (ITextEditor) editorPart;
		IDocumentProvider provider = textEditor.getDocumentProvider();
		IEditorInput editorInput = editorPart.getEditorInput();
		provider.connect(editorInput);
		IDocument document = provider.getDocument(editorInput);
		try {
			IRegion regionOfLine = document.getLineInformation(line);
			// only used to reveal the location
			textEditor.selectAndReveal(regionOfLine.getOffset(), regionOfLine.getLength());
			int startOffset = regionOfLine.getOffset() + column;
			int length = regionOfLine.getLength() - column;
			if (startOffset >= document.getLength()) {
				startOffset = document.getLength() - 1;
			}
			if (length + startOffset >= document.getLength()) {
				length = document.getLength() - startOffset - 1;
			}
			textEditor.setHighlightRange(startOffset, length, true);
		} catch (BadLocationException e) {
			MessageDialog.openInformation(N4JSGracefulActivator.getActiveWorkbenchShell(),
					ConsoleMessages.msgInvalidLineNumberTitle(),
					ConsoleMessages.msgInvalidLineNumberIn(
							(line + 1) + "",
							typeName));
		}
		provider.disconnect(editorInput);
	}
}
 
Example 14
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 15
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 16
Source File: ToggleBreakpointAdapter.java    From typescript.java with MIT License 4 votes vote down vote up
void toggleLineBreakpoint(final IWorkbenchPart part, final ITextSelection selection, final int linenumber) {
	Job job = new Job("Toggle Line Breakpoints") {
           protected IStatus run(IProgressMonitor monitor) {
           	try {
           		ITextEditor editor = getTextEditor(part);
				if(editor != null && part instanceof IEditorPart) {
					IResource resource = getResource((IEditorPart)part);
					if(resource == null) {
						resource = getResource((IEditorPart)part);
						reportToStatusLine(part, "Failed to create Javascript line breakpoint - the resource could no be computed");
						return Status.CANCEL_STATUS;
					}
					IBreakpoint bp = lineBreakpointExists(resource, linenumber);
					if(bp != null) {
						DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(bp, true);
						return Status.OK_STATUS;
					}
					IDocumentProvider documentProvider = editor.getDocumentProvider();
					IDocument document = documentProvider.getDocument(editor.getEditorInput());
					int charstart = -1, charend = -1;
					try {
						IRegion line = document.getLineInformation(linenumber - 1);
						charstart = line.getOffset();
						charend = charstart + line.getLength();
					}
					catch (BadLocationException ble) {}
					HashMap<String, String> attributes = new HashMap<String, String>();
					attributes.put(IJavaScriptBreakpoint.TYPE_NAME, null);
					attributes.put(IJavaScriptBreakpoint.SCRIPT_PATH, resource.getFullPath().makeAbsolute().toString());
					attributes.put(IJavaScriptBreakpoint.ELEMENT_HANDLE, null);
					JavaScriptDebugModel.createLineBreakpoint(resource, linenumber, charstart, charend, attributes, true);
					return Status.OK_STATUS;
				}
				reportToStatusLine(part, "Failed to create Javascript line breakpoint");
				return Status.CANCEL_STATUS;
            }
        	catch(CoreException ce) {
        		return ce.getStatus();
       		}
       	}
	};
	job.setPriority(Job.INTERACTIVE);
       job.setSystem(true);
       job.schedule();
}
 
Example 17
Source File: EditIgnoredCaughtExceptions.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void run() {
    IPath ignoreThrownExceptionsPath = PyExceptionBreakPointManager
            .getInstance().ignoreCaughtExceptionsWhenThrownFrom
                    .getIgnoreThrownExceptionsPath();
    File file = ignoreThrownExceptionsPath.toFile();
    IEditorPart openFile = EditorUtils.openFile(file);

    if (openFile instanceof ITextEditor) {
        final ITextEditor textEditor = (ITextEditor) openFile;
        IDocumentProvider documentProvider = textEditor.getDocumentProvider();
        final IEditorInput input = openFile.getEditorInput();
        if (documentProvider instanceof IStorageDocumentProvider) {
            IStorageDocumentProvider storageDocumentProvider = (IStorageDocumentProvider) documentProvider;

            // Make sure the file is seen as UTF-8.
            storageDocumentProvider.setEncoding(input, "utf-8");
            textEditor.doRevertToSaved();
        }
        if (textEditor instanceof ISaveablePart) {
            IPropertyListener listener = new IPropertyListener() {

                @Override
                public void propertyChanged(Object source, int propId) {
                    if (propId == IWorkbenchPartConstants.PROP_DIRTY) {
                        if (source == textEditor) {
                            if (textEditor.getEditorInput() == input) {
                                if (!textEditor.isDirty()) {
                                    PyExceptionBreakPointManager.getInstance().ignoreCaughtExceptionsWhenThrownFrom
                                            .updateIgnoreThrownExceptions();
                                }
                            }
                        }
                    }
                }
            };
            textEditor.addPropertyListener(listener);

        }
    }

    //        Code to provide a dialog to edit it (decided on opening the file instead).
    //        Collection<IgnoredExceptionInfo> ignoreThrownExceptionsForEdition = PyExceptionBreakPointManager.getInstance()
    //                .getIgnoreThrownExceptionsForEdition();
    //        HashMap<String, String> map = new HashMap<>();
    //        for (IgnoredExceptionInfo ignoredExceptionInfo : ignoreThrownExceptionsForEdition) {
    //            map.put(ignoredExceptionInfo.filename + ": " + ignoredExceptionInfo.line, ignoredExceptionInfo.contents);
    //        }
    //
    //        EditIgnoredCaughtExceptionsDialog dialog = new EditIgnoredCaughtExceptionsDialog(EditorUtils.getShell(), map);
    //        int open = dialog.open();
    //        if (open == dialog.OK) {
    //            Map<String, String> result = dialog.getResult();
    //
    //        } else {
    //            System.out.println("Cancel");
    //        }
}
 
Example 18
Source File: PartEventListener.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
private void saveListener(ITextEditor textEditor) {
	IDocumentProvider provider = textEditor.getDocumentProvider();
	IEditorInput input = textEditor.getEditorInput();

	provider.addElementStateListener(new ResourceElementEventListener(input));
}
 
Example 19
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Calculates the text based offsets in the given editor part for the given text selection.
 *
 * <p>The given editor part must not be <code>null</code> and the given text selection must not be
 * <code>null</code> and must not be empty.
 *
 * @param editorPart the local editor part
 * @param selection the text selection
 * @return the absolute offsets in the given editor part for the given text selection or {@link
 *     org.eclipse.jface.text.TextSelection#emptySelection()} if the given editor is not a text
 *     editor, the editor does not have a valid document provider, a valid IDocument could not be
 *     obtained form the document provider, or the line offsets could not be calculated
 * @throws NullPointerException if the given editor part or selection is <code>null</code>
 * @throws IllegalArgumentException if the given text selection is empty
 */
public static ITextSelection calculateOffsets(IEditorPart editorPart, TextSelection selection) {
  Objects.requireNonNull(editorPart, "The given editor part must not be null");
  Objects.requireNonNull(selection, "The given selection must not be null");

  if (selection.isEmpty()) {
    throw new IllegalArgumentException("The given text selection must not be empty");
  }

  if (!(editorPart instanceof ITextEditor)) {
    return org.eclipse.jface.text.TextSelection.emptySelection();
  }

  ITextEditor textEditor = (ITextEditor) editorPart;

  IDocumentProvider documentProvider = textEditor.getDocumentProvider();

  if (documentProvider == null) {
    return org.eclipse.jface.text.TextSelection.emptySelection();
  }

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

  if (document == null) {
    return org.eclipse.jface.text.TextSelection.emptySelection();
  }

  TextPosition startPosition = selection.getStartPosition();

  int startOffset = calculateOffsetInternal(document, startPosition);

  if (startOffset == -1) {
    return org.eclipse.jface.text.TextSelection.emptySelection();
  }

  TextPosition endPosition = selection.getEndPosition();

  if (startPosition.equals(endPosition)) {
    return new org.eclipse.jface.text.TextSelection(startOffset, 0);
  }

  int endOffset;

  if (endPosition.getLineNumber() == startPosition.getLineNumber()) {
    int endLineOffset = startOffset - startPosition.getInLineOffset();

    endOffset = endLineOffset + endPosition.getInLineOffset();

  } else {
    endOffset = calculateOffsetInternal(document, endPosition);

    if (endOffset == -1) {
      return org.eclipse.jface.text.TextSelection.emptySelection();
    }
  }

  int length = endOffset - startOffset;

  return new org.eclipse.jface.text.TextSelection(startOffset, length);
}
 
Example 20
Source File: LocationAnnotationManager.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create or update annotations related to text selections made by remote users.
 *
 * <p>Such selections consist of a highlight (one character wide, if there is no actual text
 * selection) and a vertical line that resembles the local text cursor. If the selection includes
 * multiple lines an additional element will be created to highlight the space between a line's
 * last character and the right margin.
 *
 * @param source The remote user who made the text selection (or to whom the text cursor belongs).
 * @param selection The selection itself.
 * @param editorPart {@link IEditorPart} that displays the opened document of which the
 *     annotations should be updated.
 */
public void setSelection(IEditorPart editorPart, TextSelection selection, User source) {

  if (!(editorPart instanceof ITextEditor)) return;

  ITextEditor textEditor = (ITextEditor) editorPart;
  IDocumentProvider docProvider = textEditor.getDocumentProvider();

  if (docProvider == null) return;

  IEditorInput input = textEditor.getEditorInput();
  IAnnotationModel model = docProvider.getAnnotationModel(input);

  if (model == null) return;

  if (selection.isEmpty()) {
    clearSelectionForUser(source, editorPart);
    return;
  }

  ITextSelection offsetSelection = EditorAPI.calculateOffsets(editorPart, selection);

  int offset = offsetSelection.getOffset();
  int length = offsetSelection.getLength();
  boolean isCursor = length == 0;

  // TODO For better performance: Currently, all selection-related
  // annotations are created and replaced individually. Since the access
  // to the annotation model tends to be slow and the replacement may take
  // place in batches, one could first create all new selection-related
  // annotations and replace them at once.

  if (isCursor) {
    if (offset > 0) {
      /*
       * Highlight the character left of the cursor in the light color
       * of the user.
       */
      setSelectionAnnotation(source, isCursor, new Position(offset - 1, 1), model);
    } else {
      /*
       * We have to draw this "highlight" even though it's not visible
       * at all. This is to prevent ghosting of the highlight when
       * jumping to the beginning of the file (offset == 0).
       */
      setSelectionAnnotation(source, isCursor, new Position(0, 0), model);
    }
  } else {
    /*
     * Highlight the selection of a remote user in the remote user's
     * light color.
     */
    setSelectionAnnotation(source, isCursor, new Position(offset, length), model);
  }

  /*
   * Draw a cursor at the cursor position of other user in the current
   * session. When there is a selection, the cursor will be shown at the
   * end of it.
   */
  setRemoteCursorAnnotation(source, new Position(offset + length), model);

  if (fillUpEnabled) {
    setFillUpAnnotation(source, new Position(offset, length), model);
  }
}