org.eclipse.jface.text.TextSelection Java Examples

The following examples show how to use org.eclipse.jface.text.TextSelection. 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: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public ITextViewer getSourceViewer(final String currentModelToParse, final IXtextDocument xtextDocument) {
	ITextViewer result = new MockableTextViewer() {
		@Override
		public IDocument getDocument() {
			return xtextDocument;
		}
		
		@Override
		public ISelectionProvider getSelectionProvider() {
			return new MockableSelectionProvider() {
				@Override
				public ISelection getSelection() {
					return TextSelection.emptySelection();
				}
			};
		}
		
		@Override
		public StyledText getTextWidget() {
			return null;
		}
	};
	return result;
}
 
Example #2
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
private void addLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
		throws BadLocationException {
	int lineNumber = selection.getStartLine();
	int endLineNumber = selection.getEndLine();
	int insertedChars = 0;

	while (lineNumber <= endLineNumber) {
		document.replace(document.getLineOffset(lineNumber), 0, comment);
		if (lineNumber != endLineNumber) {
			insertedChars += comment.length();
		}
		lineNumber++;
	}
	ITextSelection newSelection = new TextSelection(selection.getOffset() + comment.length(),
			selection.getLength() + insertedChars);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example #3
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
private void removeBlockComment(IDocument document, ITextSelection selection, IRegion existingBlock,
		CharacterPair blockComment, ITextEditor editor) throws BadLocationException {
	int openOffset = existingBlock.getOffset();
	int openLength = blockComment.getKey().length();
	int closeOffset = existingBlock.getOffset() + existingBlock.getLength();
	int closeLength = blockComment.getValue().length();
	document.replace(openOffset, openLength, "");
	document.replace(closeOffset - openLength, closeLength, "");

	int offsetFix = openLength;
	int lengthFix = 0;
	if (selection.getOffset() < openOffset + openLength) {
		offsetFix = selection.getOffset() - openOffset;
		lengthFix = openLength - offsetFix;
	}
	if (selection.getOffset() + selection.getLength() > closeOffset) {
		lengthFix += selection.getOffset() + selection.getLength() - closeOffset;
	}
	ITextSelection newSelection = new TextSelection(selection.getOffset() - offsetFix,
			selection.getLength() - lengthFix);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example #4
Source File: RepositionHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * A semi-hack... This uses stuff that may change at any time in Eclipse.  
 * In the java editor, the projection annotation model contains the collapsible regions which correspond to methods (and other areas
 * such as import groups).
 * 
 * This may work in other editor types as well... TBD
 */
protected int transform(ITextEditor editor, IDocument document, ITextSelection currentSelection,
		ExecutionEvent event) throws BadLocationException {

	ITextViewerExtension viewer = MarkUtils.getITextViewer(editor);
	if (viewer instanceof ProjectionViewer) {
		ProjectionAnnotationModel projection = ((ProjectionViewer)viewer).getProjectionAnnotationModel();
		Iterator<Annotation> pit = projection.getAnnotationIterator();
		while (pit.hasNext()) {
			Position p = projection.getPosition(pit.next());
			if (p.includes(currentSelection.getOffset())) {
				if (isUniversalPresent()) {
					// Do this here to prevent subsequent scrolling once range is revealed
					MarkUtils.setSelection(editor, new TextSelection(document, p.offset, 0));
				}
				// the viewer is pretty much guaranteed to be a TextViewer
				if (viewer instanceof TextViewer) {
					((TextViewer)viewer).revealRange(p.offset, p.length);
				}
				break;
			}
		}
	}
	return NO_OFFSET;		
}
 
Example #5
Source File: Implementations.java    From corrosion with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	IEditorPart part = HandlerUtil.getActiveEditor(event);
	if (part instanceof ITextEditor) {
		Collection<LSPDocumentInfo> infos = LanguageServiceAccessor.getLSPDocumentInfosFor(
				LSPEclipseUtils.getDocument((ITextEditor) part),
				capabilities -> Boolean.TRUE.equals(capabilities.getReferencesProvider()));
		if (!infos.isEmpty()) {
			LSPDocumentInfo info = infos.iterator().next();
			ISelection sel = ((AbstractTextEditor) part).getSelectionProvider().getSelection();

			if (sel instanceof TextSelection) {
				try {
					int offset = ((TextSelection) sel).getOffset();
					ImplementationsSearchQuery query = new ImplementationsSearchQuery(offset, info);
					NewSearchUI.runQueryInBackground(query);
				} catch (BadLocationException e) {
					LanguageServerPlugin.logError(e);
				}
			}
		}
	}
	return null;
}
 
Example #6
Source File: LinkWithEditorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testTextToTree() throws Exception {
	outlinePage.getSite().getSelectionProvider().addSelectionChangedListener(selectionSyncer);

	activate(outlineView);
	try {
		selectionSyncer.start();
		editor.getSelectionProvider().setSelection(new TextSelection(1, 1));
		selectionSyncer.awaitSignal(EXPECTED_TIMEOUT);
		fail("Selection from inactive part should not be linked");
	} catch (TimeoutException e) {
	}

	activate(editor);
	try {
		for (int offset = 0; offset < modelAsText.length(); ++offset) {
			selectionSyncer.start();
			editor.getSelectionProvider().setSelection(new TextSelection(offset, 1));
			selectionSyncer.awaitSignal(ERROR_TIMEOUT);
			assertSelected(treeViewer, expectedNodeAt(offset));
		}
	} finally {
		outlinePage.getSite().getSelectionProvider().removeSelectionChangedListener(selectionSyncer);
	}
}
 
Example #7
Source File: EditorSearchControls.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void modifyText(final ModifyEvent e) {

	boolean wrap = true;
	final String text = find.getText();
	if (lastText.startsWith(text)) {
		wrap = false;
	}
	lastText = text;
	if (EMPTY.equals(text) || "".equals(text)) {
		adjustEnablement(false, null);
		final ISelectionProvider selectionProvider = editor.getSelectionProvider();
		if (selectionProvider != null) {
			final ISelection selection = selectionProvider.getSelection();
			if (selection instanceof TextSelection) {
				final ITextSelection textSelection = (ITextSelection) selection;
				selectionProvider.setSelection(new TextSelection(textSelection.getOffset(), 0));
			}
		}
	} else {
		find(true, true, wrap);
	}
}
 
Example #8
Source File: AbstractNewSarlElementWizard.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public boolean performFinish() {
	final int size = this.page.asyncCreateType();
	final IResource resource = this.page.getResource();
	if (resource != null) {
		selectAndReveal(resource);
		final Display display = getShell().getDisplay();
		display.asyncExec(() -> {
			final IEditorPart editor;
			try {
				editor = IDE.openEditor(JavaPlugin.getActivePage(), (IFile) resource);
				if (editor instanceof ITextEditor) {
					final ITextEditor textEditor = (ITextEditor) editor;
					final ISelectionProvider selectionProvider = textEditor.getSelectionProvider();
					final ISelection selection = new TextSelection(size - 2, 0);
					selectionProvider.setSelection(selection);
				}
			} catch (PartInitException e) {
				throw new RuntimeException(e);
			}
		});
		return true;
	}
	return false;
}
 
Example #9
Source File: GamlSearchField.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public void search() {
	final IWorkbenchPart part = WorkbenchHelper.getActivePart();
	if (part instanceof IEditorPart) {
		final IEditorPart editor = (IEditorPart) part;
		final IWorkbenchPartSite site = editor.getSite();
		if (site != null) {
			final ISelectionProvider provider = site.getSelectionProvider();
			if (provider != null) {
				final ISelection viewSiteSelection = provider.getSelection();
				if (viewSiteSelection instanceof TextSelection) {
					final TextSelection textSelection = (TextSelection) viewSiteSelection;
					text.setText(textSelection.getText());
				}
			}
		}

	}
	activate(null);
	text.setFocus();

}
 
Example #10
Source File: ToggleLineCommentHandler.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
private void removeLineComments(IDocument document, ITextSelection selection, String comment, ITextEditor editor)
		throws BadLocationException {
	int lineNumber = selection.getStartLine();
	int endLineNumber = selection.getEndLine();
	String oldText = document.get();
	int deletedChars = 0;
	Boolean isStartBeforeComment = false;

	while (lineNumber <= endLineNumber) {
		int commentOffset = oldText.indexOf(comment, document.getLineOffset(lineNumber) + deletedChars);
		document.replace(commentOffset - deletedChars, comment.length(), "");
		if (deletedChars == 0) {
			isStartBeforeComment = commentOffset > selection.getOffset();
		}
		if (lineNumber != endLineNumber) {
			deletedChars += comment.length();
		}
		lineNumber++;
	}
	ITextSelection newSelection = new TextSelection(
			selection.getOffset() - (isStartBeforeComment ? 0 : comment.length()),
			selection.getLength() - deletedChars);
	editor.selectAndReveal(newSelection.getOffset(), newSelection.getLength());
}
 
Example #11
Source File: TestXML.java    From wildwebdeveloper with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testComplexXML() throws Exception {
	final IFile file = project.getFile("blah.xml");
	String content = "<layout:BlockLayoutCell\n" +
			"	xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"	\n" +
			"    xsi:schemaLocation=\"sap.ui.layout https://openui5.hana.ondemand.com/downloads/schemas/sap.ui.layout.xsd\"\n" +
			"	xmlns:layout=\"sap.ui.layout\">\n" +
			"    |\n" +
			"</layout:BlockLayoutCell>";
	int offset = content.indexOf('|');
	content = content.replace("|", "");
	file.create(new ByteArrayInputStream(content.getBytes()), true, null);
	AbstractTextEditor editor = (AbstractTextEditor) IDE
			.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, "org.eclipse.ui.genericeditor.GenericEditor");
	editor.getSelectionProvider().setSelection(new TextSelection(offset, 0));
	LSContentAssistProcessor processor = new LSContentAssistProcessor();
	proposals = processor.computeCompletionProposals(Utils.getViewer(editor), offset);
	DisplayHelper.sleep(editor.getSite().getShell().getDisplay(), 2000);
	assertTrue(proposals.length > 1);
}
 
Example #12
Source File: PyToggleBreakpointsTarget.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void toggleBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
    if (part instanceof PyEdit && selection instanceof TextSelection) {
        TextSelection textSelection = (TextSelection) selection;
        PyEdit pyEdit = (PyEdit) part;
        int startLine = textSelection.getStartLine();

        List<IMarker> markersFromCurrentFile = PyBreakpointRulerAction.getMarkersFromCurrentFile(pyEdit, startLine);
        if (markersFromCurrentFile.size() > 0) {
            PyBreakpointRulerAction.removeMarkers(markersFromCurrentFile);
        } else {
            PyBreakpointRulerAction.addBreakpointMarker(pyEdit.getDocument(), startLine + 1, pyEdit,
                    PyBreakpoint.PY_BREAK_TYPE_PYTHON);
        }

    }

}
 
Example #13
Source File: TextViewerMoveLinesAction.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Given a selection on a document, computes the lines fully or partially covered by
 * <code>selection</code>. A line in the document is considered covered if
 * <code>selection</code> comprises any characters on it, including the terminating delimiter.
 * <p>Note that the last line in a selection is not considered covered if the selection only
 * comprises the line delimiter at its beginning (that is considered part of the second last
 * line).
 * As a special case, if the selection is empty, a line is considered covered if the caret is
 * at any position in the line, including between the delimiter and the start of the line. The
 * line containing the delimiter is not considered covered in that case.
 * </p>
 *
 * @param document the document <code>selection</code> refers to
 * @param selection a selection on <code>document</code>
 * @param viewer the <code>ISourceViewer</code> displaying <code>document</code>
 * @return a selection describing the range of lines (partially) covered by
 * <code>selection</code>, without any terminating line delimiters
 * @throws BadLocationException if the selection is out of bounds (when the underlying document has changed during the call)
 */
private ITextSelection getMovingSelection(IDocument document, ITextSelection selection, ITextViewer viewer) throws BadLocationException {
	int low= document.getLineOffset(selection.getStartLine());
	int endLine= selection.getEndLine();
	int high= document.getLineOffset(endLine) + document.getLineLength(endLine);

	// get everything up to last line without its delimiter
	String delim= document.getLineDelimiter(endLine);
	if (delim != null)
		high -= delim.length();

	// the new selection will cover the entire lines being moved, except for the last line's
	// delimiter. The exception to this rule is an empty last line, which will stay covered
	// including its delimiter
	if (delim != null && document.getLineLength(endLine) == delim.length())
		fAddDelimiter= true;
	else
		fAddDelimiter= false;

	return new TextSelection(document, low, high - low);
}
 
Example #14
Source File: SexpBaseForwardHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.IConsoleDispatch#consoleDispatch(org.eclipse.ui.console.TextConsoleViewer, org.eclipse.ui.console.IConsoleView, org.eclipse.core.commands.ExecutionEvent)
 */
public Object consoleDispatch(TextConsoleViewer viewer, IConsoleView activePart, ExecutionEvent event) {

	IDocument document = viewer.getDocument();
	ITextSelection currentSelection = (ITextSelection)viewer.getSelectionProvider().getSelection();
	ITextSelection selection = new TextSelection(document, viewer.getTextWidget().getCaretOffset(), 0);
	try {
		selection = getNextSexp(document, selection);
		if (selection == null) {
			selection = currentSelection;
			unbalanced(activePart,true);
			return null;
		} else {
			return endTransform(viewer, selection.getOffset() + selection.getLength(), currentSelection, selection);
		}
	} catch (BadLocationException e) {
	}
	return null;
}
 
Example #15
Source File: AbstractLangStructureEditor.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
protected void setSelectedElementField() {
	ISelectionProvider selectionProvider = getSelectionProvider();
	if(selectionProvider == null) {
		return; // Can happen during dispose 
	}
	
	ISelection selection = selectionProvider.getSelection();
	if(selection instanceof TextSelection) {
		TextSelection textSelection = (TextSelection) selection;
		int caretOffset = textSelection.getOffset();
		
		SourceFileStructure structure;
		try {
			structure = getSourceStructure();
		} catch(CommonException e) {
			return;
		}
		if(structure != null) {
			StructureElement selectedElement = structure.getStructureElementAt(caretOffset);
			selectedElementField.setFieldValue(selectedElement);
		}
	}
}
 
Example #16
Source File: BoxedCommentHandler.java    From tlaplus with MIT License 6 votes vote down vote up
private void startBoxedComment()
		throws org.eclipse.jface.text.BadLocationException {
	int indent = offset - lineInfo.getOffset() + 1;

	// set dontAddNewLine to true iff the rest of the line, starting from offset
	// consists entirely of // space characters.
	int restOfLineLength = lineInfo.getOffset() -  offset + lineInfo.getLength();
	String restOfLine = doc.get(offset, restOfLineLength);
	boolean dontAddNewLine = StringHelper.onlySpaces(restOfLine);

	String asterisks = StringHelper.copyString("*", Math.max(3, RightMargin
			- indent - 1));
	String newText = "(" + asterisks + StringHelper.PLATFORM_NEWLINE
			+ StringHelper.PLATFORM_NEWLINE + StringHelper.copyString(" ", indent)
			+ asterisks + ")" + (dontAddNewLine ? "" : StringHelper.PLATFORM_NEWLINE);
	doc.replace(selection.getOffset(), selection.getLength(), newText);
	selectionProvider.setSelection(new TextSelection(offset + 1
			+ asterisks.length() + StringHelper.PLATFORM_NEWLINE.length(), 0));
}
 
Example #17
Source File: ExpressionUtilTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void assertInsertionPoint(String modelWithInsertionMarkup, String expectedSuccessor) throws Exception {
	String cleanedModel = modelWithInsertionMarkup.replaceAll("\\$", "");
	XExpression expression = parse(cleanedModel);
	int selectionOffset = modelWithInsertionMarkup.indexOf("$");
	XExpression selectedExpression = util.findSelectedExpression((XtextResource) expression.eResource(),
			new TextSelection(selectionOffset, 0));
	XExpression successor = util.findSuccessorExpressionForVariableDeclaration(selectedExpression);
	if (expectedSuccessor == null) {
		assertNull(successor);
	} else {
		assertNotNull(successor);
		ITextRegion selectedRegion = locationInFileProvider.getFullTextRegion(successor);
		assertEquals(expectedSuccessor,
				cleanedModel.substring(selectedRegion.getOffset(), selectedRegion.getOffset() + selectedRegion.getLength()));
	}
}
 
Example #18
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public ITextViewer getSourceViewer(final String currentModelToParse, final IXtextDocument xtextDocument) {
	ITextViewer result = new MockableTextViewer() {
		@Override
		public IDocument getDocument() {
			return xtextDocument;
		}
		
		@Override
		public ISelectionProvider getSelectionProvider() {
			return new MockableSelectionProvider() {
				@Override
				public ISelection getSelection() {
					return TextSelection.emptySelection();
				}
			};
		}
		
		@Override
		public StyledText getTextWidget() {
			return null;
		}
	};
	return result;
}
 
Example #19
Source File: TexInsertMathSymbolAction.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
public void run() {
    if (editor == null)
        return;
    ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
    IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
    TexCompletionProposal prop = new TexCompletionProposal(entry, selection.getOffset() + 1, 0, 
            editor.getViewer());
    try {
        // insert a backslash first
        doc.replace(selection.getOffset(), 0, "\\");
        prop.apply(doc);
        int newOffset = selection.getOffset() + entry.key.length() + 1;
        if (entry.arguments > 0) {
            newOffset += 1;
        }
        editor.getSelectionProvider().setSelection(new TextSelection(newOffset, 0));
    } catch (BadLocationException e) {
        TexlipsePlugin.log("Error while trying to insert command", e);
    }
}
 
Example #20
Source File: BackwardUpListHandler.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.commands.SexpBaseBackwardHandler#consoleDispatch(TextConsoleViewer, IConsoleView, ExecutionEvent)
 */
public Object consoleDispatch(final TextConsoleViewer viewer, final IConsoleView activePart, ExecutionEvent event) {

	IDocument doc = viewer.getDocument();
	boolean isBackup = getUniversalCount() > 0;  	// normal direction
	ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection();
	try {
		int offset = doTransform(doc, selection, viewer.getTextWidget().getCaretOffset(),isBackup);
		if (offset == NO_OFFSET) {
			unbalanced(activePart,false);
		} else {
			endTransform(viewer, offset, selection, new TextSelection(null,offset,offset - selection.getOffset()));
		}
	} catch (BadLocationException e) {}
	return null;
}
 
Example #21
Source File: EclipseFileUtils.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Return set of selected file(s)
 * 
 * @param selection
 *            current selection
 * @return set of selected files
 */
@SuppressWarnings("unchecked")
public static Set<IFile> getSelectedFiles(final ISelection selection) {
	final Set<IFile> files = new HashSet<>();

	if (selection instanceof IStructuredSelection) {
		final IStructuredSelection structuredSelection = (IStructuredSelection) selection;
		
		structuredSelection.toList().forEach(
		                file -> files.add(Platform.getAdapterManager().getAdapter(file, IFile.class)));
		
	} else if (selection instanceof TextSelection) {
		files.add(getActiveEditorFile());

	}

	return files;
}
 
Example #22
Source File: AbstractFilePropertyTester.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether selected file(s) matches set of extensions 
 * 
 * @param receiver selected file(s)
 * @param fileExtensions set of extensions to compare
 * @return true if selected file(s) matches at least one extensions, false otherwise.
 */
@SuppressWarnings({"unchecked", "restriction"})
protected boolean testSelectedFilesByExtensions(final Object receiver, final Set<String> fileExtensions) {
	boolean isValid = false;
	
	if (receiver instanceof Set) {
		final Set<Object> activeEditorSet = (Set<Object>) receiver;

		if (activeEditorSet.size() == 1 && activeEditorSet.iterator().next() instanceof TextSelection) {
			isValid = fileExtensions.contains(EclipseFileUtils.getActiveEditorFile().getFileExtension());
		}
	} else if (receiver instanceof List) {
		final List<Object> fileList = (List<Object>) receiver;
		
		if( !fileList.isEmpty() ) {
			isValid = fileList.stream()
							.filter(file -> file instanceof File)
							.map(File.class::cast)
							.map(File::getFileExtension)
							.allMatch(fileExtensions::contains);
		}
		
	}
	return isValid;
}
 
Example #23
Source File: JsniParserTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testGetEnclosingJsniRegionSelectionInsideJsni() {
  IRegion selRegion = RegionConverter.convertWindowsRegion(169, 3, testClass.getContents());
  ITextSelection sel = new TextSelection(selRegion.getOffset(), selRegion.getLength());
  ITypedRegion jsniRegion = JsniParser.getEnclosingJsniRegion(sel, getTestClassDocument());
  assertNotNull(jsniRegion);
  assertEquals(GWTPartitions.JSNI_METHOD, jsniRegion.getType());

  IRegion expectedJsniRegion = RegionConverter.convertWindowsRegion(121, 234, testClass.getContents());
  assertEquals(expectedJsniRegion.getOffset(), jsniRegion.getOffset());
  assertEquals(expectedJsniRegion.getLength(), jsniRegion.getLength());
}
 
Example #24
Source File: TestData.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private ITextSelection parseSelection(List<Integer> list) {
    if (list.size() == 1) {
        return new TextSelection(list.get(0), 0);
    } else if (list.size() == 2) {
        int start = list.get(0);
        int end = list.get(1);
        return new TextSelection(start, end - start);
    } else {
        return null;
    }
}
 
Example #25
Source File: ExtractVariableIntegrationTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertAfterExtract(final CharSequence input, final CharSequence expected, final boolean isFinal) {
  try {
    final String inputString = input.toString();
    final String model = inputString.replace("$", "");
    final IFile file = this.workbenchTestHelper.createFile("Foo", model);
    final XtextEditor editor = this.workbenchTestHelper.openEditor(file);
    try {
      final IUnitOfWork<Change, XtextResource> _function = (XtextResource it) -> {
        Change _xblockexpression = null;
        {
          final int offset = inputString.indexOf("$");
          int _lastIndexOf = inputString.lastIndexOf("$");
          int _minus = (_lastIndexOf - 1);
          final int length = (_minus - offset);
          final TextSelection textSelection = new TextSelection(offset, length);
          final XExpression selection = this.util.findSelectedExpression(it, textSelection);
          final ExtractVariableRefactoring refactoring = this.refactoringProvider.get();
          refactoring.setFinal(isFinal);
          refactoring.initialize(editor, selection);
          NullProgressMonitor _nullProgressMonitor = new NullProgressMonitor();
          final RefactoringStatus status = refactoring.checkAllConditions(_nullProgressMonitor);
          Assert.assertTrue(status.toString(), status.isOK());
          NullProgressMonitor _nullProgressMonitor_1 = new NullProgressMonitor();
          Change _createChange = refactoring.createChange(_nullProgressMonitor_1);
          NullProgressMonitor _nullProgressMonitor_2 = new NullProgressMonitor();
          _xblockexpression = _createChange.perform(_nullProgressMonitor_2);
        }
        return _xblockexpression;
      };
      editor.getDocument().<Change>readOnly(_function);
      Assert.assertEquals(expected.toString(), editor.getDocument().get());
    } finally {
      editor.close(false);
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #26
Source File: XtendExpressionUtilTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertExpressionSelected(final String modelWithSelectionMarkup, final String expectedSelection) {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("class Foo {");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("def foo() ");
  _builder.append(modelWithSelectionMarkup, "\t");
  _builder.newLineIfNotEmpty();
  _builder.append("}");
  _builder.newLine();
  final String model = _builder.toString();
  final String cleanedModel = model.replaceAll("\\$", "");
  final XtendFile expression = this.parse(cleanedModel);
  final int selectionOffset = model.indexOf("$");
  int _lastIndexOf = model.lastIndexOf("$");
  int _minus = (_lastIndexOf - selectionOffset);
  final int selectionLength = (_minus - 1);
  Resource _eResource = expression.eResource();
  TextSelection _textSelection = new TextSelection(selectionOffset, selectionLength);
  final XExpression selectedExpression = this.util.findSelectedExpression(((XtextResource) _eResource), _textSelection);
  final ITextRegion selectedRegion = this.locationInFileProvider.getFullTextRegion(selectedExpression);
  int _offset = selectedRegion.getOffset();
  int _offset_1 = selectedRegion.getOffset();
  int _length = selectedRegion.getLength();
  int _plus = (_offset_1 + _length);
  Assert.assertEquals(expectedSelection, cleanedModel.substring(_offset, _plus));
}
 
Example #27
Source File: AbstractXtendRenameRefactoringTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected IRenameElementContext createRenameElementContext(final XtextEditor editor, final int offset) {
	IRenameElementContext renameElementContext = editor.getDocument().readOnly(
			new IUnitOfWork<IRenameElementContext, XtextResource>() {
				@Override
				public IRenameElementContext exec(XtextResource state) throws Exception {
					EObject element = eObjectAtOffsetHelper.resolveElementAt(state, offset);
					return renameContextFactory.createRenameElementContext(element, editor, new TextSelection(
							offset, 1), state);
				}
			});
	return renameElementContext;
}
 
Example #28
Source File: CoreEditorUtils.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the current selection for the given range.
 *
 * @param editor the editor to be operated on
 * @param offset the offset of the range, must not be negative
 * @param length the length of the range, must not be negative
 */
public static void setSelection(IEditorPart editor, int offset, int length)
{
    ISelectionProvider provider = editor.getEditorSite().getSelectionProvider();
    if (provider != null) {
        IWorkbenchPart activePart = WorkbenchUtils.getActivePart();
        if (activePart instanceof IEditorPart) {
            IWorkbenchPage page = WorkbenchUtils.getActivePage();
            page.getNavigationHistory().markLocation((IEditorPart) activePart);
        }
        provider.setSelection(new TextSelection(offset, length));
    }
}
 
Example #29
Source File: SelectEnclosingElementHandler.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Called from RestoreLastSelectionHandler.class
 */
public static void restoreSelection() {
    try {
        synchronized (syncObj) {
            ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
            IEditorPart    editor    = WorkbenchUtils.getActiveEditor(false);
    
            if ((selection != null) && (editor instanceof ModulaEditor)) 
            {
                // Is it the same editor?
                if (editor.toString().equals(curEditor) && !stack.isEmpty()){
                    // Is selection preserved since last enclosion selection?
                    SelInfo si = stack.pop();
                    if (selection.getOffset() == si.offs && selection.getLength() == si.len && !stack.isEmpty()) {
                        si = stack.peek();
                        ((ITextEditor)editor).getSelectionProvider().setSelection(new TextSelection(si.offs, si.len));
                        if (stack.size() > 1) {
                            return;
                        } // else - it was last item, clear all
                    }
                }
            }
            stack.clear();
            curEditor = "";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    
}
 
Example #30
Source File: XtextElementSelectionListenerTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Verify that AbstractRule is returned on getRule() if TextSelection and XtextEditor are given.
 */
@Test
public void getRule() {
  ILeafNode mockNode = mockNodeAtSelection(mockActiveEditor());
  AbstractRule mockRule = mock(AbstractRule.class);
  when(mockNode.getGrammarElement()).thenReturn(mockRule);
  selectionListener.selectionChanged(null, mock(TextSelection.class));
  assertSame("Expected mocked AbstractRule", mockRule, selectionListener.getRule());
}