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

The following examples show how to use org.eclipse.ui.texteditor.ITextEditor#getEditorInput() . 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: FixCheckstyleMarkersHandler.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object execute(ExecutionEvent arg0) throws ExecutionException {

  ITextEditor editor = getActiveEditor();
  IEditorInput input = editor.getEditorInput();

  if (input instanceof FileEditorInput) {

    IFile file = ((FileEditorInput) input).getFile();

    // call the fixing job
    Job job = new FixCheckstyleMarkersJob(file);
    job.setUser(true);
    job.schedule();
  }
  return null;
}
 
Example 2
Source File: AbstractBreakpointRulerAction.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return the IEditorInput if we're dealing with an external file (or null otherwise)
 */
public static IEditorInput getExternalFileEditorInput(ITextEditor editor) {
    IEditorInput input = editor.getEditorInput();

    //only return not null if it's an external file (IFileEditorInput marks a workspace file, not external file)
    if (input instanceof IFileEditorInput) {
        return null;
    }

    if (input instanceof IPathEditorInput) { //PydevFileEditorInput would enter here
        return input;
    }

    try {
        if (input instanceof IURIEditorInput) {
            return input;
        }
    } catch (Throwable e) {
        //IURIEditorInput not added until eclipse 3.3
    }

    //Note that IStorageEditorInput is not handled for external files (files from zip)

    return input;
}
 
Example 3
Source File: SpellUncheckAction.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
    * Clear the spelling error markers.
    * @param action the action
 */
public void run(IAction action) {
       
       if (targetEditor == null) {
           return;
       }
       if (!(targetEditor instanceof ITextEditor)) {
           return;
       }
       
       ITextEditor textEditor = (ITextEditor) targetEditor;
       IEditorInput input = textEditor.getEditorInput();
       
       if (input instanceof FileEditorInput) {
           SpellChecker.clearMarkers(((FileEditorInput)input).getFile());
       }
}
 
Example 4
Source File: SpellCheckAction.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
    * Run the spell check action.
    * @param action the action
 */
public void run(IAction action) {
       
       if (targetEditor == null) {
           return;
       }
       if (!(targetEditor instanceof ITextEditor)) {
           return;
       }
       
       ITextEditor textEditor = (ITextEditor) targetEditor;
       IEditorInput input = textEditor.getEditorInput();
       
       IFile file = ((FileEditorInput) input).getFile();
       
       SpellChecker.checkSpelling(textEditor.getDocumentProvider().getDocument(input), file);
}
 
Example 5
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 6
Source File: EditorDocumentUndoChange.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public EditorDocumentUndoChange(String name, ITextEditor editor, UndoEdit undoEdit, boolean doSave) {
	this.name = name;
	IWorkbenchPartSite site = editor.getSite();
	this.page = site.getPage();
	this.editorID = site.getId();
	this.editorInput = editor.getEditorInput();
	this.undoEdit = undoEdit;
	this.doSave = doSave;
}
 
Example 7
Source File: PyMarkerUIUtils.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the resource for which to create the marker or <code>null</code>
 *
 * If the editor maps to a workspace file, it will return that file. Otherwise, it will return the
 * workspace root (so, markers from external files will be created in the workspace root).
 */
public static IResource getResourceForTextEditor(ITextEditor textEditor) {
    IEditorInput input = textEditor.getEditorInput();
    IResource resource = input.getAdapter(IFile.class);
    if (resource == null) {
        resource = input.getAdapter(IResource.class);
    }
    if (resource == null) {
        resource = ResourcesPlugin.getWorkspace().getRoot();
    }
    return resource;
}
 
Example 8
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 9
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 10
Source File: SVNPristineCopyQuickDiffProvider.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void setActiveEditor(ITextEditor targetEditor) {
	if(! (targetEditor.getEditorInput() instanceof IFileEditorInput)) return;
	editor = targetEditor;
	documentProvider= editor.getDocumentProvider();
	
	if(documentProvider != null) {
		SVNWorkspaceSubscriber.getInstance().addListener(teamChangeListener);
		((IDocumentProvider)documentProvider).addElementStateListener(documentListener);
	}	
	isReferenceInitialized= true;
}
 
Example 11
Source File: PropertyKeyHyperlinkDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static boolean checkEnabled(ITextEditor textEditor, int offset) {
	if (offset < 0)
		return false;

	IEditorInput editorInput= textEditor.getEditorInput();
	return editorInput instanceof IFileEditorInput || (editorInput instanceof IStorageEditorInput && isEclipseNLSAvailable((IStorageEditorInput) editorInput));
}
 
Example 12
Source File: MarkRing.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Verify that the editor in the location is still in use
 * 
 * @param location
 * @return true if editor is valid
 */
private boolean checkEditor(IBufferLocation location) {
	boolean result = false;
	if (location != null) {
		ITextEditor editor = location.getEditor(); 
		if (editor != null) {
			IEditorInput input = editor.getEditorInput();
			// check all the editor references that match the input for a match
			IEditorReference[] refs = EmacsPlusUtils.getWorkbenchPage().findEditors(input,null, IWorkbenchPage.MATCH_INPUT); 
			for (int i=0; i< refs.length; i++) {
				IEditorPart ed = refs[i].getEditor(false);
				// multi page annoyance
				if (ed instanceof MultiPageEditorPart) {
					IEditorPart[] eds = ((MultiPageEditorPart)ed).findEditors(input);
					for (int j=0; j < eds.length; j++) {
						if (eds[i] == editor) {
							result = true;
							break;
						}
					}
					if (result) {
						break;
					}
				} else {
					if (ed == editor) {
						result = true;
						break;
					}
				}
			}
		}
	}
	return result;
}
 
Example 13
Source File: PyToggleTargetAdapter.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean canToggleFor(ITextEditor iTextEditor) {
    IEditorInput editorInput = iTextEditor.getEditorInput();
    if (editorInput != null) {
        String name = editorInput.getName();
        if (name != null) {
            if (name.endsWith(".html") || name.endsWith(".htm") || name.endsWith(".djhtml")) {
                //System.err.println("PyToggleTargetAdapter.getAdapter: " + iTextEditor);
                return true;
            }
        }
    }
    return false;
}
 
Example 14
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 15
Source File: TagsSearchHandler.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
protected IProject getCurrentProject(ITextEditor editor) {
	if (editor != null) {
		IEditorInput input = editor.getEditorInput();
		if (input instanceof IFileEditorInput) {
			return ((IFileEditorInput) input).getFile().getProject();
		}
	}
	return null;
}
 
Example 16
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 17
Source File: ScriptRunToLineAdapter.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void runToLine( IWorkbenchPart part, ISelection selection,
		ISuspendResume target ) throws CoreException
{
	ITextEditor textEditor = getTextEditor( part );

	if ( textEditor == null )
	{
		return;
	}
	else
	{
		IEditorInput input = textEditor.getEditorInput( );

		if ( input == null || !( input instanceof DebugJsInput ) )
		{
			return;
		}

		DebugJsInput scriptInput = (DebugJsInput) input;
		IResource resource = (IResource) input.getAdapter( IResource.class );
		if ( resource == null )
		{
			resource = ScriptDebugUtil.getDefaultResource( );
		}

		final IDocument document = textEditor.getDocumentProvider( )
				.getDocument( input );
		if ( document == null )
		{
			return;
		}
		else
		{
			final int[] validLine = new int[1];
			// final String[] typeName = new String[1];
			final int[] lineNumber = new int[1];
			final ITextSelection textSelection = (ITextSelection) selection;
			Runnable r = new Runnable( ) {

				public void run( )
				{
					lineNumber[0] = textSelection.getStartLine( ) + 1;
				}
			};
			BusyIndicator.showWhile( DebugUI.getStandardDisplay( ), r );
			// TODO add the validLine to adjust if the line is validLine
			validLine[0] = lineNumber[0];
			if ( validLine[0] == lineNumber[0] )
			{
				ScriptLineBreakpoint point = new RunToLinebreakPoint( resource,
						scriptInput.getFile( ).getAbsolutePath( ),
						scriptInput.getId( ),
						lineNumber[0] );
				point.setType( ScriptLineBreakpoint.RUNTOLINE );
				if ( target instanceof IAdaptable )
				{
					ScriptDebugTarget debugTarget = (ScriptDebugTarget) ( (IAdaptable) target ).getAdapter( IDebugTarget.class );
					if ( debugTarget != null )
					{
						debugTarget.breakpointAdded( point );
						debugTarget.resume( );
					}
				}
			}
			else
			{
				// invalid line
				return;
			}
		}

	}
}
 
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: 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);
  }
}
 
Example 20
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));
}