Java Code Examples for org.eclipse.jface.text.source.ISourceViewer#getSelectedRange()

The following examples show how to use org.eclipse.jface.text.source.ISourceViewer#getSelectedRange() . 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: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Remember current selection.
 */
public void remember() {
	/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
	 * This method may be called inside an asynchronous call posted
	 * to the UI thread, so protect against intermediate disposal
	 * of the editor.
	 */
	ISourceViewer viewer= getSourceViewer();
	if (viewer != null) {
		Point selection= viewer.getSelectedRange();
		int startOffset= selection.x;
		int endOffset= startOffset + selection.y;

		fStartOffset.setOffset(startOffset);
		fEndOffset.setOffset(endOffset);
	}
}
 
Example 2
Source File: XtextEditor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setCaretPosition(int position) {
	if (!validateEditorInputState())
		return;

	final int length;
	final ISourceViewer viewer = getSourceViewer();
	StyledText text = viewer.getTextWidget();
	Point widgetSelection = text.getSelection();
	if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
		final int caret = text.getCaretOffset();
		final int offset = modelOffset2WidgetOffset(viewer, position);

		if (caret == widgetSelection.x)
			text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
		else
			text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
		text.invokeAction(ST.DELETE_PREVIOUS);
	} else {
		Point selection = viewer.getSelectedRange();
		if (selection.y != 0) {
			position = selection.x;
			length = selection.y;
		} else {
			length = widgetOffset2ModelOffset(viewer, text.getCaretOffset()) - position;
		}

		try {
			viewer.getDocument().replace(position, length, ""); //$NON-NLS-1$
		} catch (BadLocationException exception) {
			// Should not happen
		}
	}
}
 
Example 3
Source File: SubWordActions.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setCaretPosition(int position) {
    if (!validateEditorInputState()) {
        return;
    }

    final int length;
    final ISourceViewer viewer = getSourceViewer();
    StyledText text = viewer.getTextWidget();
    Point widgetSelection = text.getSelection();
    if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
        final int caret = text.getCaretOffset();
        final int offset = modelOffset2WidgetOffset(viewer, position);

        if (caret == widgetSelection.x) {
            text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
        } else {
            text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
        }
        text.invokeAction(ST.DELETE_PREVIOUS);
    } else {
        Point selection = viewer.getSelectedRange();
        if (selection.y != 0) {
            position = selection.x;
            length = selection.y;
        } else {
            length = widgetOffset2ModelOffset(viewer, text.getCaretOffset()) - position;
        }

        try {
            viewer.getDocument().replace(position, length, ""); //$NON-NLS-1$
        } catch (BadLocationException exception) {
            // Should not happen
        }
    }
}
 
Example 4
Source File: SubWordActions.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setCaretPosition(final int position) {
    if (!validateEditorInputState()) {
        return;
    }

    final ISourceViewer viewer = getSourceViewer();
    StyledText text = viewer.getTextWidget();
    Point widgetSelection = text.getSelection();
    if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
        final int caret = text.getCaretOffset();
        final int offset = modelOffset2WidgetOffset(viewer, position);

        if (caret == widgetSelection.x) {
            text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
        } else {
            text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
        }
        text.invokeAction(ST.DELETE_NEXT);
    } else {
        Point selection = viewer.getSelectedRange();
        final int caret, length;
        if (selection.y != 0) {
            caret = selection.x;
            length = selection.y;
        } else {
            caret = widgetOffset2ModelOffset(viewer, text.getCaretOffset());
            length = position - caret;
        }

        try {
            viewer.getDocument().replace(caret, length, ""); //$NON-NLS-1$
        } catch (BadLocationException exception) {
            // Should not happen
        }
    }
}
 
Example 5
Source File: JavaCorrectionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext quickAssistContext) {
	ISourceViewer viewer= quickAssistContext.getSourceViewer();
	int documentOffset= quickAssistContext.getOffset();

	IEditorPart part= fAssistant.getEditor();

	ICompilationUnit cu= JavaUI.getWorkingCopyManager().getWorkingCopy(part.getEditorInput());
	IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(part.getEditorInput());

	AssistContext context= null;
	if (cu != null) {
		int length= viewer != null ? viewer.getSelectedRange().y : 0;
		context= new AssistContext(cu, viewer, part, documentOffset, length);
	}
	
	Annotation[] annotations= fAssistant.getAnnotationsAtOffset();

	fErrorMessage= null;

	ICompletionProposal[] res= null;
	if (model != null && context != null && annotations != null) {
		ArrayList<IJavaCompletionProposal> proposals= new ArrayList<IJavaCompletionProposal>(10);
		IStatus status= collectProposals(context, model, annotations, true, !fAssistant.isUpdatedOffset(), proposals);
		res= proposals.toArray(new ICompletionProposal[proposals.size()]);
		if (!status.isOK()) {
			fErrorMessage= status.getMessage();
			JavaPlugin.log(status);
		}
	}

	if (res == null || res.length == 0) {
		return new ICompletionProposal[] { new ChangeCorrectionProposal(CorrectionMessages.NoCorrectionProposal_description, new NullChange(""), IProposalRelevance.NO_SUGGESSTIONS_AVAILABLE, null) }; //$NON-NLS-1$
	}
	if (res.length > 1) {
		Arrays.sort(res, new CompletionProposalComparator());
	}
	return res;
}
 
Example 6
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static final IRegion getSignedSelection(ISourceViewer sourceViewer) {
	Point viewerSelection= sourceViewer.getSelectedRange();

	StyledText text= sourceViewer.getTextWidget();
	Point selection= text.getSelectionRange();
	if (text.getCaretOffset() == selection.x) {
		viewerSelection.x= viewerSelection.x + viewerSelection.y;
		viewerSelection.y= -viewerSelection.y;
	}

	return new Region(viewerSelection.x, viewerSelection.y);
}
 
Example 7
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setCaretPosition(int position) {
	if (!validateEditorInputState())
		return;

	final int length;
	final ISourceViewer viewer= getSourceViewer();
	StyledText text= viewer.getTextWidget();
	Point widgetSelection= text.getSelection();
	if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
		final int caret= text.getCaretOffset();
		final int offset= modelOffset2WidgetOffset(viewer, position);

		if (caret == widgetSelection.x)
			text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
		else
			text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
		text.invokeAction(ST.DELETE_PREVIOUS);
	} else {
		Point selection= viewer.getSelectedRange();
		if (selection.y != 0) {
			position= selection.x;
			length= selection.y;
		} else {
			length= widgetOffset2ModelOffset(viewer, text.getCaretOffset()) - position;
		}

		try {
			viewer.getDocument().replace(position, length, ""); //$NON-NLS-1$
		} catch (BadLocationException exception) {
			// Should not happen
		}
	}
}
 
Example 8
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setCaretPosition(final int position) {
	if (!validateEditorInputState())
		return;

	final ISourceViewer viewer= getSourceViewer();
	StyledText text= viewer.getTextWidget();
	Point widgetSelection= text.getSelection();
	if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
		final int caret= text.getCaretOffset();
		final int offset= modelOffset2WidgetOffset(viewer, position);

		if (caret == widgetSelection.x)
			text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
		else
			text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
		text.invokeAction(ST.DELETE_NEXT);
	} else {
		Point selection= viewer.getSelectedRange();
		final int caret, length;
		if (selection.y != 0) {
			caret= selection.x;
			length= selection.y;
		} else {
			caret= widgetOffset2ModelOffset(viewer, text.getCaretOffset());
			length= position - caret;
		}

		try {
			viewer.getDocument().replace(caret, length, ""); //$NON-NLS-1$
		} catch (BadLocationException exception) {
			// Should not happen
		}
	}
}
 
Example 9
Source File: PasteJavaCodeHandler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
void doFormat(ISourceViewer sourceViewer, final String xtendCode, Point selection) {
	int offset = selection.x;
	int length = xtendCode.length();
	if (offset - 1 >= 0) {
		offset--;
		length++;
	}
	sourceViewer.setSelectedRange(offset, length);
	sourceViewer.getTextOperationTarget().doOperation(ISourceViewer.FORMAT);
	int restoreCaretAtOffset = sourceViewer.getSelectedRange().x + sourceViewer.getSelectedRange().y;
	sourceViewer.setSelectedRange(restoreCaretAtOffset, 0);
}
 
Example 10
Source File: RenameLinkedMode.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public boolean start(IRenameElementContext renameElementContext, Provider<LinkedPositionGroup> provider, IProgressMonitor monitor) {
	if (renameElementContext == null)
		throw new IllegalArgumentException("RenameElementContext is null");
	this.linkedPositionGroup = provider.get();
	if (linkedPositionGroup == null || linkedPositionGroup.isEmpty())
		return false;
	this.editor = (XtextEditor) renameElementContext.getTriggeringEditor();
	this.focusEditingSupport = new FocusEditingSupport();
	ISourceViewer viewer = editor.getInternalSourceViewer();
	IDocument document = viewer.getDocument();
	originalSelection = viewer.getSelectedRange();
	currentPosition = linkedPositionGroup.getPositions()[0];
	originalName = getCurrentName();
	try {
		linkedModeModel = new LinkedModeModel();
		linkedModeModel.addGroup(linkedPositionGroup);
		linkedModeModel.forceInstall();
		linkedModeModel.addLinkingListener(new EditorSynchronizer());
		LinkedModeUI ui = new EditorLinkedModeUI(linkedModeModel, viewer);
		ui.setExitPolicy(new ExitPolicy(document));
		if (currentPosition.includes(originalSelection.x))
			ui.setExitPosition(viewer, originalSelection.x, 0, Integer.MAX_VALUE);
		ui.enter();
		if (currentPosition.includes(originalSelection.x)
				&& currentPosition.includes(originalSelection.x + originalSelection.y))
			viewer.setSelectedRange(originalSelection.x, originalSelection.y);
		if (viewer instanceof IEditingSupportRegistry) {
			IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer;
			registry.register(focusEditingSupport);
		}
		openPopup();
		return true;
	} catch (BadLocationException e) {
		throw new WrappedException(e);
	}
}
 
Example 11
Source File: XtextEditor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setCaretPosition(final int position) {
	if (!validateEditorInputState())
		return;

	final ISourceViewer viewer = getSourceViewer();
	StyledText text = viewer.getTextWidget();
	Point widgetSelection = text.getSelection();
	if (isBlockSelectionModeEnabled() && widgetSelection.y != widgetSelection.x) {
		final int caret = text.getCaretOffset();
		final int offset = modelOffset2WidgetOffset(viewer, position);

		if (caret == widgetSelection.x)
			text.setSelectionRange(widgetSelection.y, offset - widgetSelection.y);
		else
			text.setSelectionRange(widgetSelection.x, offset - widgetSelection.x);
		text.invokeAction(ST.DELETE_NEXT);
	} else {
		Point selection = viewer.getSelectedRange();
		final int caret, length;
		if (selection.y != 0) {
			caret = selection.x;
			length = selection.y;
		} else {
			caret = widgetOffset2ModelOffset(viewer, text.getCaretOffset());
			length = position - caret;
		}

		try {
			viewer.getDocument().replace(caret, length, ""); //$NON-NLS-1$
		} catch (BadLocationException exception) {
			// Should not happen
		}
	}
}
 
Example 12
Source File: PropertiesQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getEscapeUnescapeBackslashProposals(IQuickAssistInvocationContext invocationContext, ArrayList<ICompletionProposal> resultingCollections) throws BadLocationException,
		BadPartitioningException {
	ISourceViewer sourceViewer= invocationContext.getSourceViewer();
	IDocument document= sourceViewer.getDocument();
	Point selectedRange= sourceViewer.getSelectedRange();
	int selectionOffset= selectedRange.x;
	int selectionLength= selectedRange.y;
	int proposalOffset;
	int proposalLength;
	String text;
	if (selectionLength == 0) {
		if (selectionOffset != document.getLength()) {
			char ch= document.getChar(selectionOffset);
			if (ch == '=' || ch == ':') { //see PropertiesFilePartitionScanner()
				return false;
			}
		}

		ITypedRegion partition= null;
		if (document instanceof IDocumentExtension3)
			partition= ((IDocumentExtension3)document).getPartition(IPropertiesFilePartitions.PROPERTIES_FILE_PARTITIONING, invocationContext.getOffset(), false);
		if (partition == null)
			return false;

		String type= partition.getType();
		if (!(type.equals(IPropertiesFilePartitions.PROPERTY_VALUE) || type.equals(IDocument.DEFAULT_CONTENT_TYPE))) {
			return false;
		}
		proposalOffset= partition.getOffset();
		proposalLength= partition.getLength();
		text= document.get(proposalOffset, proposalLength);

		if (type.equals(IPropertiesFilePartitions.PROPERTY_VALUE)) {
			text= text.substring(1); //see PropertiesFilePartitionScanner()
			proposalOffset++;
			proposalLength--;
		}
	} else {
		proposalOffset= selectionOffset;
		proposalLength= selectionLength;
		text= document.get(proposalOffset, proposalLength);
	}

	if (PropertiesFileEscapes.containsUnescapedBackslash(text)) {
		if (resultingCollections == null)
			return true;
		resultingCollections.add(new EscapeBackslashCompletionProposal(PropertiesFileEscapes.escape(text, false, true, false), proposalOffset, proposalLength,
				PropertiesFileEditorMessages.EscapeBackslashCompletionProposal_escapeBackslashes));
		return true;
	}
	if (PropertiesFileEscapes.containsEscapedBackslashes(text)) {
		if (resultingCollections == null)
			return true;
		resultingCollections.add(new EscapeBackslashCompletionProposal(PropertiesFileEscapes.unescapeBackslashes(text), proposalOffset, proposalLength,
				PropertiesFileEditorMessages.EscapeBackslashCompletionProposal_unescapeBackslashes));
		return true;
	}
	return false;
}
 
Example 13
Source File: RenameLinkedMode.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void start() {
		if (getActiveLinkedMode() != null) {
			// for safety; should already be handled in RenameJavaElementAction
			fgActiveLinkedMode.startFullDialog();
			return;
		}

		ISourceViewer viewer= fEditor.getViewer();
		IDocument document= viewer.getDocument();
		fOriginalSelection= viewer.getSelectedRange();
		int offset= fOriginalSelection.x;

		try {
			CompilationUnit root= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

			fLinkedPositionGroup= new LinkedPositionGroup();
			ASTNode selectedNode= NodeFinder.perform(root, fOriginalSelection.x, fOriginalSelection.y);
			if (! (selectedNode instanceof SimpleName)) {
				return; // TODO: show dialog
			}
			SimpleName nameNode= (SimpleName) selectedNode;

			if (viewer instanceof ITextViewerExtension6) {
				IUndoManager undoManager= ((ITextViewerExtension6)viewer).getUndoManager();
				if (undoManager instanceof IUndoManagerExtension) {
					IUndoManagerExtension undoManagerExtension= (IUndoManagerExtension)undoManager;
					IUndoContext undoContext= undoManagerExtension.getUndoContext();
					IOperationHistory operationHistory= OperationHistoryFactory.getOperationHistory();
					fStartingUndoOperation= operationHistory.getUndoOperation(undoContext);
				}
			}
			
			fOriginalName= nameNode.getIdentifier();
			final int pos= nameNode.getStartPosition();
			ASTNode[] sameNodes= LinkedNodeFinder.findByNode(root, nameNode);

			//TODO: copied from LinkedNamesAssistProposal#apply(..):
			// sort for iteration order, starting with the node @ offset
			Arrays.sort(sameNodes, new Comparator<ASTNode>() {
				public int compare(ASTNode o1, ASTNode o2) {
					return rank(o1) - rank(o2);
				}
				/**
				 * Returns the absolute rank of an <code>ASTNode</code>. Nodes
				 * preceding <code>pos</code> are ranked last.
				 *
				 * @param node the node to compute the rank for
				 * @return the rank of the node with respect to the invocation offset
				 */
				private int rank(ASTNode node) {
					int relativeRank= node.getStartPosition() + node.getLength() - pos;
					if (relativeRank < 0)
						return Integer.MAX_VALUE + relativeRank;
					else
						return relativeRank;
				}
			});
			for (int i= 0; i < sameNodes.length; i++) {
				ASTNode elem= sameNodes[i];
				LinkedPosition linkedPosition= new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i);
				if (i == 0)
					fNamePosition= linkedPosition;
				fLinkedPositionGroup.addPosition(linkedPosition);
			}

			fLinkedModeModel= new LinkedModeModel();
			fLinkedModeModel.addGroup(fLinkedPositionGroup);
			fLinkedModeModel.forceInstall();
			fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
			fLinkedModeModel.addLinkingListener(new EditorSynchronizer());

			LinkedModeUI ui= new EditorLinkedModeUI(fLinkedModeModel, viewer);
			ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
			ui.setExitPolicy(new ExitPolicy(document));
			ui.enter();

			viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by default, full word is selected; restore original selection

			if (viewer instanceof IEditingSupportRegistry) {
				IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer;
				registry.register(fFocusEditingSupport);
			}

			openSecondaryPopup();
//			startAnimation();
			fgActiveLinkedMode= this;

		} catch (BadLocationException e) {
			JavaPlugin.log(e);
		}
	}
 
Example 14
Source File: RenameLinkedMode.java    From typescript.java with MIT License 4 votes vote down vote up
public void start() {
	if (getActiveLinkedMode() != null) {
		// for safety; should already be handled in RenameJavaElementAction
		fgActiveLinkedMode.startFullDialog();
		return;
	}

	ISourceViewer viewer = fEditor.getViewer();
	IDocument document = viewer.getDocument();

	ITypeScriptFile tsFile = fEditor.getTypeScriptFile();
	tsFile.setDisableChanged(true);
	fOriginalSelection = viewer.getSelectedRange();
	int offset = fOriginalSelection.x;

	try {
		fLinkedPositionGroup = new LinkedPositionGroup();
		if (viewer instanceof ITextViewerExtension6) {
			IUndoManager undoManager = ((ITextViewerExtension6) viewer).getUndoManager();
			if (undoManager instanceof IUndoManagerExtension) {
				IUndoManagerExtension undoManagerExtension = (IUndoManagerExtension) undoManager;
				IUndoContext undoContext = undoManagerExtension.getUndoContext();
				IOperationHistory operationHistory = OperationHistoryFactory.getOperationHistory();
				fStartingUndoOperation = operationHistory.getUndoOperation(undoContext);
			}
		}

		// Find occurrences
		List<OccurrencesResponseItem> occurrences = tsFile.occurrences(offset).get(1000, TimeUnit.MILLISECONDS);

		// Create Eclipse linked position from the occurrences list.
		int start, length;
		for (int i = 0; i < occurrences.size(); i++) {
			OccurrencesResponseItem item = occurrences.get(i);
			start = tsFile.getPosition(item.getStart());
			length = tsFile.getPosition(item.getEnd()) - start;
			LinkedPosition linkedPosition = new LinkedPosition(document, start, length, i);
			if (i == 0) {
				fOriginalName = document.get(start, length);
				fNamePosition = linkedPosition;
			}
			fLinkedPositionGroup.addPosition(linkedPosition);
		}

		fLinkedModeModel = new LinkedModeModel();
		fLinkedModeModel.addGroup(fLinkedPositionGroup);
		fLinkedModeModel.forceInstall();
		fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor));
		fLinkedModeModel.addLinkingListener(new EditorSynchronizer());

		LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer);
		ui.setExitPosition(viewer, offset, 0, Integer.MAX_VALUE);
		ui.setExitPolicy(new ExitPolicy(document));
		ui.enter();

		viewer.setSelectedRange(fOriginalSelection.x, fOriginalSelection.y); // by
																				// default,
																				// full
																				// word
																				// is
																				// selected;
																				// restore
																				// original
																				// selection

		if (viewer instanceof IEditingSupportRegistry) {
			IEditingSupportRegistry registry = (IEditingSupportRegistry) viewer;
			registry.register(fFocusEditingSupport);
		}

		openSecondaryPopup();
		// startAnimation();
		fgActiveLinkedMode = this;

	} catch (Exception e) {
		JSDTTypeScriptUIPlugin.log(e);
	}
}
 
Example 15
Source File: CopyQualifiedNameAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Object getSelectedElement(JavaEditor editor) {
	ISourceViewer viewer= editor.getViewer();
	if (viewer == null)
		return null;

	Point selectedRange= viewer.getSelectedRange();
	int length= selectedRange.y;
	int offset= selectedRange.x;

	ITypeRoot element= JavaUI.getEditorInputTypeRoot(editor.getEditorInput());
	if (element == null)
		return null;

	CompilationUnit ast= SharedASTProvider.getAST(element, SharedASTProvider.WAIT_YES, null);
	if (ast == null)
		return null;

	NodeFinder finder= new NodeFinder(ast, offset, length);
	ASTNode node= finder.getCoveringNode();

	IBinding binding= null;
	if (node instanceof Name) {
		binding= getConstructorBindingIfAvailable((Name)node);
		if (binding != null)
			return binding;
		binding= ((Name)node).resolveBinding();
	} else if (node instanceof MethodInvocation) {
		binding= ((MethodInvocation)node).resolveMethodBinding();
	} else if (node instanceof MethodDeclaration) {
		binding= ((MethodDeclaration)node).resolveBinding();
	} else if (node instanceof Type) {
		binding= ((Type)node).resolveBinding();
	} else if (node instanceof AnonymousClassDeclaration) {
		binding= ((AnonymousClassDeclaration)node).resolveBinding();
	} else if (node instanceof TypeDeclaration) {
		binding= ((TypeDeclaration)node).resolveBinding();
	} else if (node instanceof CompilationUnit) {
		return ((CompilationUnit)node).getJavaElement();
	} else if (node instanceof Expression) {
		binding= ((Expression)node).resolveTypeBinding();
	} else if (node instanceof ImportDeclaration) {
		binding= ((ImportDeclaration)node).resolveBinding();
	} else if (node instanceof MemberRef) {
		binding= ((MemberRef)node).resolveBinding();
	} else if (node instanceof MemberValuePair) {
		binding= ((MemberValuePair)node).resolveMemberValuePairBinding();
	} else if (node instanceof PackageDeclaration) {
		binding= ((PackageDeclaration)node).resolveBinding();
	} else if (node instanceof TypeParameter) {
		binding= ((TypeParameter)node).resolveBinding();
	} else if (node instanceof VariableDeclaration) {
		binding= ((VariableDeclaration)node).resolveBinding();
	}

	if (binding != null)
		return binding.getJavaElement();

	return null;
}
 
Example 16
Source File: PasteJavaCodeHandler.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private void doPasteJavaCode(final XtextEditor activeXtextEditor, final String javaCode, final JavaImportData javaImports)
		throws ExecutionException {
	ISourceViewer sourceViewer = activeXtextEditor.getInternalSourceViewer();
	final IXtextDocument xtextDocument = activeXtextEditor.getDocument();
	IJavaProject project = null;
	IProject iProject = null;
	IEditorInput editorInput = activeXtextEditor.getEditorInput();
	if (editorInput instanceof IFileEditorInput) {
		iProject = ((IFileEditorInput) editorInput).getFile().getProject();
		project = JavaCore.create(iProject);
	}
	final int selectionOffset = Math.max(0, sourceViewer.getSelectedRange().x - 1);
	EObject targetElement = xtextDocument.readOnly(new IUnitOfWork<EObject, XtextResource>() {

		@Override
		public EObject exec(XtextResource state) throws Exception {
			IParseResult parseResult = state.getParseResult();
			if (parseResult == null) {
				return null;
			}
			ILeafNode leafNode = NodeModelUtils.findLeafNodeAtOffset(parseResult.getRootNode(), selectionOffset);
			if (leafNode == null) {
				return parseResult.getRootASTElement();
			}
			return leafNode.getSemanticElement();
		}
	});
	JavaConverter javaConverter = javaConverterProvider.get();
	final String xtendCode = javaConverter.toXtend(javaCode, javaImports != null ? javaImports.getImports() : null,
			targetElement, project, conditionalExpressionsAllowed(iProject));
	if (!Strings.isEmpty(xtendCode)) {
		if (javaImports != null) {
			importsUtil.addImports(javaImports.getImports(), javaImports.getStaticImports(), new String[] {}, xtextDocument);
		}
		Point selection = sourceViewer.getSelectedRange();
		try {
			xtextDocument.replace(selection.x, selection.y, xtendCode);
		} catch (BadLocationException e) {
			throw new ExecutionException("Failed to replace content.", e);
		}
		//TODO enable formatting, when performance became better
		//	https://bugs.eclipse.org/bugs/show_bug.cgi?id=457814
		//			doFormat(sourceViewer, xtendCode, selection);
	}
}
 
Example 17
Source File: SelectAllOccurrencesHandler.java    From eclipse-multicursor with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Mostly based on code from {@link org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal}
 */
private void startEditing(ISourceViewer viewer) throws ExecutionException {
	Point selOffsetAndLen = viewer.getSelectedRange();
	int selStart = CoordinatesUtil.fromOffsetAndLengthToStartAndEnd(selOffsetAndLen).x;

	IDocument document = viewer.getDocument();
	try {
		String selectedText;
		if (selOffsetAndLen.y == 0) { // no characters selected
			String documentText = document.get();
			Point wordOffsetAndLen = TextUtil.findWordSurrounding(documentText, selStart);
			if (wordOffsetAndLen != null) {
				selectedText = document.get(wordOffsetAndLen.x, wordOffsetAndLen.y);
			} else {
				IRegion selectedLine = document.getLineInformationOfOffset(selStart);
				selectedText = document.get(selectedLine.getOffset(), selectedLine.getLength());
			}
		} else {
			selectedText = document.get(selOffsetAndLen.x, selOffsetAndLen.y);
		}

		LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup();

		FindReplaceDocumentAdapter findReplaceAdaptor = new FindReplaceDocumentAdapter(document);
		IRegion matchingRegion = findReplaceAdaptor.find(0, selectedText, true, true, false, false);
		while (matchingRegion != null) {
			linkedPositionGroup.addPosition(new LinkedPosition(document, matchingRegion.getOffset(), matchingRegion
					.getLength()));

			matchingRegion = findReplaceAdaptor.find(matchingRegion.getOffset() + matchingRegion.getLength(),
					selectedText, true, true, false, false);
		}

		LinkedModeModel model = new LinkedModeModel();
		model.addGroup(linkedPositionGroup);
		model.forceInstall();

		LinkedModeUI ui = new EditorLinkedModeUI(model, viewer);
		ui.setExitPolicy(new DeleteBlockingExitPolicy(document));
		ui.enter();

		// by default the text being edited is selected so restore original selection
		viewer.setSelectedRange(selOffsetAndLen.x, selOffsetAndLen.y);
	} catch (BadLocationException e) {
		throw new ExecutionException("Editing failed", e);
	}
}
 
Example 18
Source File: SelectNextOccurrenceHandler.java    From eclipse-multicursor with Eclipse Public License 1.0 4 votes vote down vote up
private void startEditing(ISourceViewer viewer) throws ExecutionException {
	final Point selOffsetAndLen = viewer.getSelectedRange();
	final IDocument document = viewer.getDocument();

	try {
		final String searchText;
		final int candidateSearchOffset;
		final int selStart = CoordinatesUtil.fromOffsetAndLengthToStartAndEnd(selOffsetAndLen).x;
		if (selOffsetAndLen.y == 0) { // no characters selected
			final String documentText = document.get();
			final Point wordOffsetAndLen = TextUtil.findWordSurrounding(documentText, selStart);
			if (wordOffsetAndLen != null) {
				searchText = document.get(wordOffsetAndLen.x, wordOffsetAndLen.y);
				candidateSearchOffset = wordOffsetAndLen.x;
			} else {
				final IRegion selectedLine = document.getLineInformationOfOffset(selStart);
				searchText = document.get(selectedLine.getOffset(), selectedLine.getLength());
				candidateSearchOffset = selectedLine.getOffset();
			}
		} else {
			searchText = document.get(selOffsetAndLen.x, selOffsetAndLen.y);
			candidateSearchOffset = selOffsetAndLen.x;
		}

		final int searchOffset;
		final List<IRegion> selections;
		final Point startingSelection;

		final SelectInProgress currentState = getCurrentState();
		if (LinkedModeModel.getModel(document, 0) != null &&
				currentState != null
				&& selOffsetAndLen.equals(currentState.startingSelection)
				&& searchText.equals(currentState.searchText)) {
			startingSelection = currentState.startingSelection;
			selections = new ArrayList<IRegion>(currentState.existingSelections);
			searchOffset = currentState.nextOffset;
		} else {
			startingSelection = selOffsetAndLen;
			selections = new ArrayList<IRegion>();
			searchOffset = candidateSearchOffset;
		}

		final IRegion matchingRegion = new FindReplaceDocumentAdapter(document).find(searchOffset,
				searchText, true, true, false, false);
		if (matchingRegion != null) {
			selections.add(matchingRegion);

			if (selections.size() == 1) {
				// select the next occurrence too; only selecting the current cursor pos isn't useful
				final IRegion secondMatchingRegion = new FindReplaceDocumentAdapter(document).find(
						matchingRegion.getOffset() + matchingRegion.getLength(), searchText, true, true, false, false);
				if (secondMatchingRegion != null) {
					selections.add(secondMatchingRegion);
				}
			}

			if (selections.size() > 1) {
				final IRegion lastSelection = selections.get(selections.size() - 1);
				saveCurrentState(new SelectInProgress(startingSelection, searchText, selections,
						lastSelection.getOffset() + lastSelection.getLength()));

				startLinkedEdit(selections, viewer, selOffsetAndLen);
			}
		}
	} catch (BadLocationException e) {
		throw new ExecutionException("Editing failed", e);
	}
}