Java Code Examples for org.eclipse.xtext.ide.server.Document#getOffSet()

The following examples show how to use org.eclipse.xtext.ide.server.Document#getOffSet() . 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: XContentAssistService.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create the completion proposals.
 */
public CompletionList createCompletionList(Document document, XtextResource resource,
		TextDocumentPositionParams params, CancelIndicator cancelIndicator) {
	CompletionList result = new CompletionList();
	result.setIsIncomplete(false);
	// we set isInComplete to true, so we get asked always, which is the best match to the expected behavior in
	// Xtext
	XIdeContentProposalAcceptor acceptor = new XIdeContentProposalAcceptor(cancelIndicator);
	int caretOffset = document.getOffSet(params.getPosition());
	Position caretPosition = params.getPosition();
	TextRegion position = new TextRegion(caretOffset, 0);
	try {
		createProposals(document.getContents(), position, caretOffset, resource, acceptor);
	} catch (Throwable t) {
		if (!operationCanceledManager.isOperationCanceledException(t)) {
			throw t;
		}
	}
	operationCanceledManager.checkCanceled(cancelIndicator);
	IterableExtensions.forEach(acceptor.getEntries(), (it, idx) -> {
		CompletionItem item = toCompletionItem(it, caretOffset, caretPosition, document);
		item.setSortText(Strings.padStart(Integer.toString(idx.intValue()), 5, '0'));
		result.getItems().add(item);
	});
	return result;
}
 
Example 2
Source File: DocumentTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testOffSet_empty() {
  Document _document = new Document(Integer.valueOf(1), "");
  final Procedure1<Document> _function = (Document it) -> {
    Assert.assertEquals(0, it.getOffSet(this.position(0, 0)));
    try {
      it.getOffSet(this.position(0, 12));
      Assert.fail();
    } catch (final Throwable _t) {
      if (_t instanceof IndexOutOfBoundsException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  };
  ObjectExtensions.<Document>operator_doubleArrow(_document, _function);
}
 
Example 3
Source File: SignatureHelpServiceImpl.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public SignatureHelp getSignatureHelp(final Document document, final XtextResource resource, final SignatureHelpParams params, final CancelIndicator cancelIndicator) {
  final int offset = document.getOffSet(params.getPosition());
  Preconditions.<XtextResource>checkNotNull(resource, "resource");
  Preconditions.checkArgument((offset >= 0), ("offset >= 0. Was: " + Integer.valueOf(offset)));
  final EObject object = this.offsetHelper.resolveContainedElementAt(resource, offset);
  if ((object instanceof OperationCall)) {
    final String operationName = this.getOperationName(((OperationCall)object));
    boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(operationName);
    boolean _not = (!_isNullOrEmpty);
    if (_not) {
      return this.getSignatureHelp(((OperationCall)object), operationName, offset);
    }
  }
  return ISignatureHelpService.EMPTY;
}
 
Example 4
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Remove the question mark qualifier from optional fields from the old location and put it at the new location.
 */
@Fix(IssueCodes.CLF_FIELD_OPTIONAL_OLD_SYNTAX)
public void fixOldSyntaxForOptionalFields(QuickfixContext context, ICodeActionAcceptor acceptor) {
	Document doc = context.options.getDocument();
	int offsetNameEnd = getOffsetOfNameEnd(getEObject(context).eContainer());
	List<TextEdit> textEdits = new ArrayList<>();
	// removes the ? at the old location
	int endOffset = doc.getOffSet(context.getDiagnostic().getRange().getEnd());
	textEdits.add(replace(doc, endOffset - 1, 1, ""));
	// inserts a ? at the new location (behind the field or accessor name)
	if (offsetNameEnd != -1) {
		textEdits.add(replace(doc, offsetNameEnd, 0, "?"));
	}
	acceptor.acceptQuickfixCodeAction(context, "Change to new syntax", textEdits);
}
 
Example 5
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Update the syntax for optional function parameters.
 */
@Fix(IssueCodes.FUN_PARAM_OPTIONAL_WRONG_SYNTAX)
public void fixOldSyntaxForOptionalFpars(QuickfixContext context, ICodeActionAcceptor acceptor) {
	Document doc = context.options.getDocument();
	List<TextEdit> textEdits = new ArrayList<>();
	int endOffset = doc.getOffSet(context.getDiagnostic().getRange().getEnd());
	textEdits.add(replace(doc, endOffset - 1, 1, " = undefined"));
	acceptor.acceptQuickfixCodeAction(context, "Change to Default Parameter", textEdits);
}
 
Example 6
Source File: DocumentTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testOffSet() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("hello world");
  _builder.newLine();
  _builder.append("foo");
  _builder.newLine();
  _builder.append("bar");
  _builder.newLine();
  String _normalize = this.normalize(_builder);
  Document _document = new Document(Integer.valueOf(1), _normalize);
  final Procedure1<Document> _function = (Document it) -> {
    Assert.assertEquals(0, it.getOffSet(this.position(0, 0)));
    Assert.assertEquals(11, it.getOffSet(this.position(0, 11)));
    try {
      it.getOffSet(this.position(0, 12));
      Assert.fail();
    } catch (final Throwable _t) {
      if (_t instanceof IndexOutOfBoundsException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
    Assert.assertEquals(12, it.getOffSet(this.position(1, 0)));
    Assert.assertEquals(13, it.getOffSet(this.position(1, 1)));
    Assert.assertEquals(14, it.getOffSet(this.position(1, 2)));
    Assert.assertEquals(16, it.getOffSet(this.position(2, 0)));
    Assert.assertEquals(19, it.getOffSet(this.position(2, 3)));
  };
  ObjectExtensions.<Document>operator_doubleArrow(_document, _function);
}
 
Example 7
Source File: ContentAssistService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public CompletionList createCompletionList(Document document, XtextResource resource, CompletionParams params,
		CancelIndicator cancelIndicator) {
	try {
		CompletionList result = new CompletionList();
		result.setIsIncomplete(true);
		IdeContentProposalAcceptor acceptor = proposalAcceptorProvider.get();
		int caretOffset = document.getOffSet(params.getPosition());
		Position caretPosition = params.getPosition();
		TextRegion position = new TextRegion(caretOffset, 0);
		try {
			createProposals(document.getContents(), position, caretOffset, resource, acceptor);
		} catch (Throwable t) {
			if (!operationCanceledManager.isOperationCanceledException(t)) {
				throw t;
			}
		}
		int idx = 0;
		for (ContentAssistEntry it : acceptor.getEntries()) {
			CompletionItem item = toCompletionItem(it, caretOffset, caretPosition, document);
			item.setSortText(Strings.padStart(Integer.toString(idx), 5, '0'));
			result.getItems().add(item);
			idx++;
		}
		return result;
	} catch (Throwable e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example 8
Source File: RenameService2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected EObject getElementAtOffset(XtextResource xtextResource, Document document, Position caretPosition) {
	int caretOffset = document.getOffSet(caretPosition);
	EObject element = getElementWithIdentifierAt(xtextResource, caretOffset);
	if (element != null) {
		return element;
	} else {
		return getElementWithIdentifierAt(xtextResource, caretOffset - 1);
	}
}
 
Example 9
Source File: DocumentSymbolService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public List<? extends Location> getReferences(Document document, XtextResource resource, ReferenceParams params,
		IReferenceFinder.IResourceAccess resourceAccess, IResourceDescriptions indexData,
		CancelIndicator cancelIndicator) {
	int offset = document.getOffSet(params.getPosition());
	List<? extends Location> definitions = Collections.emptyList();
	if (params.getContext().isIncludeDeclaration()) {
		definitions = getDefinitions(resource, offset, resourceAccess, cancelIndicator);
	}
	List<? extends Location> references = getReferences(resource, offset, resourceAccess, indexData,
			cancelIndicator);
	List<Location> result = new ArrayList<>();
	result.addAll(definitions);
	result.addAll(references);
	return result;
}
 
Example 10
Source File: FormattingService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public List<? extends TextEdit> format(Document document, XtextResource resource,
		DocumentRangeFormattingParams params, CancelIndicator cancelIndicator) {
	int startOffset = document.getOffSet(params.getRange().getStart());
	int endOffset = document.getOffSet(params.getRange().getEnd());
	int length = endOffset - startOffset;
	return format(resource, document, startOffset, length, params.getOptions());
}
 
Example 11
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private EObject getEObject(Document doc, XtextResource resource, Range range) {
	Position start = range.getStart();
	int startOffset = doc.getOffSet(start);
	return eObjectAtOffsetHelper.resolveContainedElementAt(resource, startOffset);
}
 
Example 12
Source File: JSONCodeActionService.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private EObject getEObject(Document doc, XtextResource resource, Range range) {
	Position start = range.getStart();
	int startOffset = doc.getOffSet(start);
	return eObjectAtOffsetHelper.resolveContainedElementAt(resource, startOffset);
}
 
Example 13
Source File: RenameService2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected Either<Range, PrepareRenameResult> doPrepareRename(Resource resource, Document document,
		PrepareRenameParams params, CancelIndicator cancelIndicator) {
	String uri = params.getTextDocument().getUri();
	if (resource instanceof XtextResource) {
		ICompositeNode rootNode = null;
		XtextResource xtextResource = (XtextResource) resource;
		if (xtextResource != null) {
			IParseResult parseResult = xtextResource.getParseResult();
			if (parseResult != null) {
				rootNode = parseResult.getRootNode();
			}
		}
		if (rootNode == null) {
			RenameService2.LOG.trace("Could not retrieve root node for resource. URI: " + uri);
			return null;
		}
		Position caretPosition = params.getPosition();
		try {
			int caretOffset = document.getOffSet(caretPosition);
			EObject element = null;
			int candidateOffset = caretOffset;
			do {
				element = getElementWithIdentifierAt(xtextResource, candidateOffset);
				if (element != null && !element.eIsProxy()) {
					ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, candidateOffset);
					if (leaf != null && isIdentifier(leaf)) {
						String convertedNameValue = getConvertedValue(leaf.getGrammarElement(), leaf);
						String elementName = getElementName(element);
						if (!Strings.isEmpty(convertedNameValue) && !Strings.isEmpty(elementName)
								&& Objects.equal(convertedNameValue, elementName)) {
							Position start = document.getPosition(leaf.getOffset());
							Position end = document.getPosition(leaf.getEndOffset());
							return Either.forLeft(new Range(start, end));
						}
					}
				}
				candidateOffset = (candidateOffset - 1);
			} while (((candidateOffset >= 0) && ((candidateOffset + 1) >= caretOffset)));
		} catch (IndexOutOfBoundsException e) {
			RenameService2.LOG.trace("Invalid document " + toPositionFragment(caretPosition, uri));
			return null;
		}
		RenameService2.LOG.trace("No element found at " + toPositionFragment(caretPosition, uri));
	} else {
		RenameService2.LOG.trace("Loaded resource is not an XtextResource. URI: " + resource.getURI());
	}
	return null;
}
 
Example 14
Source File: DefaultDocumentHighlightService.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public List<? extends DocumentHighlight> getDocumentHighlights(Document document, XtextResource resource, DocumentHighlightParams params, CancelIndicator cancelIndicator) {
	int offset = document.getOffSet(params.getPosition());
	return getDocumentHighlights(resource, offset);
}
 
Example 15
Source File: HoverService.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Hover hover(Document document, XtextResource resource, HoverParams params, CancelIndicator cancelIndicator) {
	int offset = document.getOffSet(params.getPosition());
	HoverContext context = createContext(document, resource, offset);
	return hover(context);
}
 
Example 16
Source File: DocumentSymbolService.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.21
 */
public List<? extends Location> getDefinitions(Document document, XtextResource resource, DefinitionParams params,
		IReferenceFinder.IResourceAccess resourceAccess, CancelIndicator cancelIndicator) {
	int offset = document.getOffSet(params.getPosition());
	return getDefinitions(resource, offset, resourceAccess, cancelIndicator);
}