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
/**
 * {@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
/**
 * @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
/**
    * 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
/**
    * 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
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
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
/**
 * 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 8
Source Project: typescript.java   File: IndentAction.java    License: 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 9
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 10
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 11
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 12
/**
 * 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 13
protected IProject getCurrentProject(ITextEditor editor) {
	if (editor != null) {
		IEditorInput input = editor.getEditorInput();
		if (input instanceof IFileEditorInput) {
			return ((IFileEditorInput) input).getFile().getProject();
		}
	}
	return null;
}
 
Example 14
Source Project: e4macs   File: MarkRing.java    License: 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 15
Source Project: Pydev   File: PyMarkerUIUtils.java    License: 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 16
Source Project: scava   File: PartEventListener.java    License: 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 17
/**
 * 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 18
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
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 20
@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");
    //        }
}