org.eclipse.xtext.ui.editor.model.IXtextDocument Java Examples

The following examples show how to use org.eclipse.xtext.ui.editor.model.IXtextDocument. 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: ContentFormatterFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void format(IDocument document, IRegion region) {
	IXtextDocument doc = xtextDocumentUtil.getXtextDocument(document);
	ReplaceRegion r = doc.priorityReadOnly(new FormattingUnitOfWork(region));
	try {
		if (r != null) {
			TextEdit edit = createTextEdit(doc, r);
			if (edit != null) {
				edit.apply(doc);
			}
			
		}
	} catch (BadLocationException e) {
		throw new RuntimeException(e);
	}
}
 
Example #2
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 6 votes vote down vote up
private void addAbstractKeyword(XtendTypeDeclaration typeDeclaration, IXtextDocument document,
		String declarationKeyword) throws BadLocationException {
	final ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(typeDeclaration);
	if (clazzNode == null) {
		throw new IllegalStateException("Cannot determine node for the type declaration" //$NON-NLS-1$
				+ typeDeclaration.getName());
	}
	int offset = -1;
	final Iterator<ILeafNode> nodes = clazzNode.getLeafNodes().iterator();
	while (offset == -1 && nodes.hasNext()) {
		final ILeafNode leafNode  = nodes.next();
		if (leafNode.getText().equals(declarationKeyword)) {
			offset = leafNode.getOffset();
		}
	}
	final ReplacingAppendable appendable = this.appendableFactory.create(document,
			(XtextResource) typeDeclaration.eResource(),
			offset, 0);
	appendable.append(getGrammarAccess()
			.getAbstractKeyword())
			.append(" "); //$NON-NLS-1$
	appendable.commitChanges();
}
 
Example #3
Source File: MarkerResolutionGenerator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Deprecated
public IXtextDocument getXtextDocument(IResource resource) {
	IXtextDocument result = xtextDocumentUtil.getXtextDocument(resource);
	if(result == null) {
		IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
		try {
			IFile file = ResourceUtil.getFile(resource);
			IEditorInput input = new FileEditorInput(file);
			IEditorPart newEditor = page.openEditor(input, getEditorId());
			return xtextDocumentUtil.getXtextDocument(newEditor);
		} catch (PartInitException e) {
			return null;
		}
	}
	return result;
}
 
Example #4
Source File: DocumentAutoFormatter.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Called for formatting a region.
 *
 * @param document the document to format.
 * @param offset the offset of the text to format.
 * @param length the length of the text.
 */
protected void formatRegion(IXtextDocument document, int offset, int length) {
	try {
		final int startLineIndex = document.getLineOfOffset(previousSiblingChar(document, offset));
		final int endLineIndex = document.getLineOfOffset(offset + length);
		int regionLength = 0;
		for (int i = startLineIndex; i <= endLineIndex; ++i) {
			regionLength += document.getLineLength(i);
		}
		if (regionLength > 0) {
			final int startOffset = document.getLineOffset(startLineIndex);
			for (final IRegion region : document.computePartitioning(startOffset, regionLength)) {
				this.contentFormatter.format(document, region);
			}
		}
	} catch (BadLocationException exception) {
		Exceptions.sneakyThrow(exception);
	}
}
 
Example #5
Source File: ActionAddModification.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(EObject element, IModificationContext context) throws Exception {
	final XtendTypeDeclaration container = EcoreUtil2.getContainerOfType(element, XtendTypeDeclaration.class);
	if (container != null) {
		final int insertOffset = getTools().getInsertOffset(container);
		final IXtextDocument document = context.getXtextDocument();
		final int length = getTools().getSpaceSize(document, insertOffset);
		final ReplacingAppendable appendable = getTools().getAppendableFactory().create(document,
				(XtextResource) element.eResource(), insertOffset, length);
		final boolean changeIndentation = container.getMembers().isEmpty();
		if (changeIndentation) {
			appendable.increaseIndentation();
		}
		appendable.newLine();
		appendable.append(
				getTools().getGrammarAccess().getDefKeyword());
		appendable.append(" "); //$NON-NLS-1$
		appendable.append(this.actionName);
		if (changeIndentation) {
			appendable.decreaseIndentation();
		}
		appendable.newLine();
		appendable.commitChanges();
	}
}
 
Example #6
Source File: GoToMatchingBracketAction.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void run() {
	IXtextDocument document = editor.getDocument();
	ISelection selection = editor.getSelectionProvider().getSelection();
	if (selection instanceof ITextSelection) {
		ITextSelection textSelection = (ITextSelection) selection;
		if (textSelection.getLength()==0) {
			IRegion region = matcher.match(document, textSelection.getOffset());
			if (region != null) {
				if (region.getOffset()+1==textSelection.getOffset()) {
					editor.selectAndReveal(region.getOffset()+region.getLength(),0);
				} else {
					editor.selectAndReveal(region.getOffset()+1,0);
				}
			}
		}
	}
}
 
Example #7
Source File: JSONProposalFactory.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private ICompletionProposal createProposal(ContentAssistContext context, String name, String value,
		String description, String rawTemplate, Image image, boolean isGenericProposal) {

	TemplateContextType contextType = getTemplateContextType();
	IXtextDocument document = context.getDocument();
	TemplateContext tContext = new DocumentTemplateContext(contextType, document, context.getOffset(), 0);
	Region replaceRegion = context.getReplaceRegion();

	// pre-populate ${name} and ${value} with given args
	if (isGenericProposal) {
		tContext.setVariable("name", name);
	}
	tContext.setVariable("value", value);

	return new StyledTemplateProposal(context, name, description, rawTemplate, isGenericProposal, tContext,
			replaceRegion, image);
}
 
Example #8
Source File: LinkingErrorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug361509() throws Exception {
	IFile dslFile = dslFile(MODEL_WITH_LINKING_ERROR_361509);
	XtextEditor xtextEditor = openEditor(dslFile);
	IXtextDocument document = xtextEditor.getDocument();

	List<Issue> issues = getAllValidationIssues(document);
	assertFalse(issues.isEmpty());
	Issue issue = issues.get(0);
	assertNotNull(issue);
	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);

	assertEquals(1, resolutions.size());
	IssueResolution resolution = resolutions.get(0);
	assertEquals("Change to 'ref'", resolution.getLabel());
	resolution.apply();
	issues = getAllValidationIssues(document);
	assertTrue(issues.isEmpty());
	assertEquals(MODEL_WITH_LINKING_ERROR_361509.replace("raf", "^ref"), document.get());
}
 
Example #9
Source File: DefaultFoldingRegionProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSignificantPartOfMlComment_01() throws Exception {
	IFile iFile = createFile("foo/bar.foldingtestlanguage",
			"\n/**\n *\n */\n element foo end");
	IXtextDocument document = openFileAndReturnDocument(iFile);
	DefaultFoldingRegionProvider reg = createFoldingRegionProvider();
	Collection<FoldedPosition> regions = reg.getFoldingRegions(document);
	assertEquals(1, regions.size());
	FoldedPosition position = Iterables.getOnlyElement(regions);
	assertEquals(1, position.getOffset());
	assertEquals("/**\n *\n */\n".length(), position.getLength());
	assertEquals(0, position.computeCaptionOffset(document));
	IRegion[] projectionRegions = position.computeProjectionRegions(document);
	assertEquals(1, projectionRegions.length);
	assertEquals("\n/**\n".length(), projectionRegions[0].getOffset());
	assertEquals(" *\n */\n".length(), projectionRegions[0].getLength());
}
 
Example #10
Source File: ContentFormatter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected TextEdit exec(IXtextDocument document, IRegion region, XtextResource resource) throws Exception {
	try {
		IParseResult parseResult = resource.getParseResult();
		if (parseResult != null && parseResult.getRootASTElement() != null) {
			FormatterRequest request = requestProvider.get();
			initRequest(document, region, resource, request);
			IFormatter2 formatter = formatterProvider.get();
			List<ITextReplacement> replacements = formatter.format(request);
			final TextEdit mte = createTextEdit(replacements);
			return mte;
		}
	} catch (Exception e) {
		LOG.error("Error formatting " + resource.getURI() + ": " + e.getMessage(), e);
	}
	return new MultiTextEdit();
}
 
Example #11
Source File: DefaultFoldingRegionProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSignificantPartOfMlComment_02() throws Exception {
	IFile iFile = createFile("foo/bar.foldingtestlanguage",
			"\n/** foo\n *\n */\n element foo end");
	IXtextDocument document = openFileAndReturnDocument(iFile);
	DefaultFoldingRegionProvider reg = createFoldingRegionProvider();
	Collection<FoldedPosition> regions = reg.getFoldingRegions(document);
	assertEquals(1, regions.size());
	FoldedPosition position = Iterables.getOnlyElement(regions);
	assertEquals(1, position.getOffset());
	assertEquals("/** foo\n *\n */\n".length(), position.getLength());
	assertEquals("/** ".length(), position.computeCaptionOffset(document));
	IRegion[] projectionRegions = position.computeProjectionRegions(document);
	assertEquals(1, projectionRegions.length);
	assertEquals("\n/** foo\n".length(), projectionRegions[0].getOffset());
	assertEquals(" *\n */\n".length(), projectionRegions[0].getLength());
}
 
Example #12
Source File: OrganizeImportsHandler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void doOrganizeImports(final IXtextDocument document) {
	List<ReplaceRegion> result = document.priorityReadOnly(new IUnitOfWork<List<ReplaceRegion>, XtextResource>() {
		@Override
		public List<ReplaceRegion> exec(XtextResource state) throws Exception {
			return importOrganizer.getOrganizedImportChanges(state);
		}
	});
	if (result == null || result.isEmpty())
		return;
	try {
		DocumentRewriteSession session = null;
		if(document instanceof IDocumentExtension4) {
			session = ((IDocumentExtension4)document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
		}
		replaceConverter.convertToTextEdit(result).apply(document);
		if(session != null) {
			((IDocumentExtension4)document).stopRewriteSession(session);
		}
	} catch (BadLocationException e) {
		LOG.error(Messages.OrganizeImportsHandler_organizeImportsErrorMessage, e);
	}
}
 
Example #13
Source File: HighlightingReconciler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Uninstall this reconciler from the editor
 */
public void uninstall() {
	if (presenter != null)
		presenter.setCanceled(true);

	if (sourceViewer.getDocument() != null) {
		if (oldCalculator != null || newCalculator != null) {
			IXtextDocument document = xtextDocumentUtil.getXtextDocument(sourceViewer);
			if (document != null) {
				document.removeModelListener(this);
			}
			sourceViewer.removeTextInputListener(this);
		}
	}
	editor = null;
	sourceViewer = null;
	presenter = null;
}
 
Example #14
Source File: DefaultFoldingRegionProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSignificantPartOfModel_01() throws Exception {
	IFile iFile = createFile("foo/bar.foldingtestlanguage",
			"\n" +
			"element foo\n" +
			"end\n");
	IXtextDocument document = openFileAndReturnDocument(iFile);
	DefaultFoldingRegionProvider reg = createFoldingRegionProvider();
	Collection<FoldedPosition> regions = reg.getFoldingRegions(document);
	assertEquals(1, regions.size());
	FoldedPosition position = Iterables.getOnlyElement(regions);
	assertEquals("\n".length(), position.getOffset());
	assertEquals("element foo\nend\n".length(), position.getLength());
	assertEquals("element ".length(), position.computeCaptionOffset(document));
	IRegion[] projectionRegions = position.computeProjectionRegions(document);
	assertEquals(1, projectionRegions.length);
	assertEquals("\nelement foo\n".length(), projectionRegions[0].getOffset());
	assertEquals("end\n".length(), projectionRegions[0].getLength());
}
 
Example #15
Source File: XtendQuickfixProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.UNNECESSARY_MODIFIER)
public void removeUnnecessaryModifier(final Issue issue, IssueResolutionAcceptor acceptor) {
	String[] issueData = issue.getData();
	if(issueData==null || issueData.length==0) {
		return;
	}
	// use the same label, description and image
	// to be able to use the quickfixes (issue resolution) in batch mode
	String label = "Remove the unnecessary modifier.";
	String description = "The modifier is unnecessary and could be removed.";
	String image = "fix_indent.gif";
	
	acceptor.accept(issue, label, description, image, new ITextualMultiModification() {
		
		@Override
		public void apply(IModificationContext context) throws Exception {
			if (context instanceof IssueModificationContext) {
				Issue theIssue = ((IssueModificationContext) context).getIssue();
				Integer offset = theIssue.getOffset();
				IXtextDocument document = context.getXtextDocument();
				document.replace(offset, theIssue.getLength(), "");
				while (Character.isWhitespace(document.getChar(offset))) {
					document.replace(offset, 1, "");
				}
			}
		}
	});
}
 
Example #16
Source File: GamlHyperlinkDetector.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private IRegion importUriRegion(final IXtextDocument document, final int offset, final String importUri)
		throws BadLocationException {
	final int lineNumber = document.getLineOfOffset(offset);
	final int lineLength = document.getLineLength(lineNumber);
	final int lineOffset = document.getLineOffset(lineNumber);
	final String line = document.get(lineOffset, lineLength);
	final int uriIndex = line.indexOf(importUri);
	return new Region(lineOffset + uriIndex, importUri.length());
}
 
Example #17
Source File: XtextUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Provides the Xtext resource from a Xtext Document.
 *
 * @param document
 *          The XtextDocument
 * @return XtexRessource
 */
public static XtextResource getXtextRessource(final IXtextDocument document) {
  return document.readOnly(new IUnitOfWork<XtextResource, XtextResource>() {
    @Override
    public XtextResource exec(final XtextResource state) {
      return state;
    }
  });
}
 
Example #18
Source File: DotEditorUtils.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * The implementation of the following helper methods are taken from the
 * org.eclipse.xtext.junit4.ui.ContentAssistProcessorTestBuilder java class.
 */
public static IXtextDocument getDocument(final Injector injector,
		final String currentModelToParse) throws Exception {
	XtextResource xtextResource = getXtextResource(injector,
			currentModelToParse);
	return getDocument(injector, xtextResource, currentModelToParse);
}
 
Example #19
Source File: DefaultOutlineTreeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.7
 */
@Override
public IOutlineNode createRoot(IXtextDocument document, CancelIndicator cancelIndicator) {
	try {
		this.cancelIndicator = cancelIndicator;
		return createRoot(document);
	} finally {
		this.cancelIndicator = CancelIndicator.NullImpl;
	}
}
 
Example #20
Source File: ExtractMethodHandler.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	try {
		syncUtil.totalSync(false);
		final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
		if (editor != null) {
			final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
			final IXtextDocument document = editor.getDocument();
			XtextResource copiedResource = document.priorityReadOnly(new IUnitOfWork<XtextResource, XtextResource>() {
				@Override
				public XtextResource exec(XtextResource state) throws Exception {
					return resourceCopier.loadIntoNewResourceSet(state);
				}
			});
			List<XExpression> expressions = expressionUtil.findSelectedSiblingExpressions(copiedResource,
					selection);
			if (!expressions.isEmpty()) {
				ExtractMethodRefactoring extractMethodRefactoring = refactoringProvider.get();
				if (extractMethodRefactoring.initialize(editor, expressions, true)) {
					updateSelection(editor, expressions);
					ExtractMethodWizard wizard = wizardFactory.create(extractMethodRefactoring);
					RefactoringWizardOpenOperation_NonForking openOperation = new RefactoringWizardOpenOperation_NonForking(
							wizard);
					openOperation.run(editor.getSite().getShell(), "Extract Method");
				}
			}
		}
	} catch (InterruptedException e) {
		return null;
	} catch (Exception exc) {
		LOG.error("Error during refactoring", exc);
		MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error during refactoring", exc.getMessage()
				+ "\nSee log for details");
	}
	return null;
}
 
Example #21
Source File: DirtyStateEditorSupport.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void initializeDirtyStateSupport(IDirtyStateEditorSupportClient client) {
	if (this.currentClient != null)
		throw new IllegalStateException("editor was already assigned"); //$NON-NLS-1$
	this.currentClient = client;
	this.state = State.CLEAN;
	IXtextDocument document = client.getDocument();
	initDirtyResource(document);
	stateChangeEventBroker.addListener(this);
	client.addVerifyListener(this);
	scheduleValidationJobIfNecessary();
}
 
Example #22
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public ContentAssistProcessorTestBuilder applyProposal(int position, String proposalString) throws Exception {
	IXtextDocument document = getDocument(getModel());
	Shell shell = new Shell();
	try {
		ICompletionProposal[] proposals = computeCompletionProposals(document, position, shell);
		ICompletionProposal proposal = findProposal(proposalString, proposals);
		return applyProposal(proposal, position, document);
	} finally {
		shell.dispose();
	}
}
 
Example #23
Source File: AbstractQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Issue getValidationIssue(IXtextDocument document, String issueCode) {
	List<Issue> issueCandidates = document
			.readOnly(state -> resourceValidator.validate(state, CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl)) //
			.stream() //
			.filter(issue -> issue.getCode().equals(issueCode)) //
			.collect(Collectors.toList());
	assertEquals("There should be one '" + issueCode + "' validation issue!", 1, issueCandidates.size());
	return issueCandidates.get(0);
}
 
Example #24
Source File: XbaseTemplateContext.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private boolean checkImports(final List<String> types, IXtextDocument document) {
	return document.priorityReadOnly(new IUnitOfWork<Boolean, XtextResource>() {
		@Override
		public Boolean exec(XtextResource state) throws Exception {
			for (String fqName : types) {
				JvmDeclaredType jvmType = findJvmDeclaredType(fqName, state.getResourceSet());
				if (jvmType == null) {
					return false;
				}
			}
			return true;
		}
	});
}
 
Example #25
Source File: Bug369087Test.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected Object getContentTypeCategory(IXtextDocument xtextDocument) {
	return find(newArrayList(xtextDocument.getPositionCategories()), new Predicate<Object>() {
		@Override
		public boolean apply(Object input) {
			return input.toString().startsWith("__content_types_category");
		}
	});
}
 
Example #26
Source File: DocumentBasedDirtyResourceTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IXtextDocument getDummyDocument() {
	return (IXtextDocument) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{IXtextDocument.class}, new InvocationHandler() {
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			return null;
		}
	});
}
 
Example #27
Source File: SARLQuickfixProvider.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the size of a sequence of whitespaces.
 *
 * @param document the document.
 * @param offset the offset of the first character of the sequence.
 * @return the number of whitespaces at the given offset.
 * @throws BadLocationException if there is a problem with the location of the element.
 */
public int getSpaceSize(IXtextDocument document, int offset) throws BadLocationException {
	int size = 0;
	char c = document.getChar(offset + size);
	while (Character.isWhitespace(c)) {
		size++;
		c = document.getChar(offset + size);
	}
	return size;
}
 
Example #28
Source File: CompositeModificationWrapper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void apply(IModificationContext ctx) throws Exception {
	IXtextDocument document = ctx.getXtextDocument();
	BatchModification batch = document.tryReadOnly(r -> r.getResourceServiceProvider().get(BatchModification.class));
	if (batch != null) {
		batch.setDocument(document);
		batch.apply(Collections.singleton(this), new NullProgressMonitor());
	}
}
 
Example #29
Source File: RepeatedContentAssistProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.7
 */
protected ICompletionProposal[] computeCompletionProposals(IXtextDocument document, CompletionProposalComputer proposalComputer) {
	if (getContentProposalProvider() == null)
		return null;
	
	ICompletionProposal[] result = document.priorityReadOnly(proposalComputer);
	Arrays.sort(result, getCompletionProposalComparator());
	result = getCompletionProposalPostProcessor().postProcess(result);
	return result;
}
 
Example #30
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected ICompletionProposal[] computeCompletionProposals(final IXtextDocument xtextDocument, int cursorPosition)
		throws BadLocationException {
	Shell shell = new Shell();
	try {
		return computeCompletionProposals(xtextDocument, cursorPosition, shell);
	} finally {
		shell.dispose();
	}
}