Search in sources :

Example 36 with ITextReplacement

use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.

the class FormatterTester method assertAllWhitespaceIsFormatted.

protected void assertAllWhitespaceIsFormatted(ITextRegionAccess access, List<ITextReplacement> replacements) {
    List<ITextSegment> expected = Lists.newArrayList();
    IHiddenRegion current = access.regionForRootEObject().getPreviousHiddenRegion();
    while (current != null) {
        expected.addAll(current.getMergedSpaces());
        current = current.getNextHiddenRegion();
    }
    List<ITextSegment> missing = TextRegions.difference(expected, replacements);
    if (!missing.isEmpty()) {
        TextRegionsToString toString = new TextRegionsToString().setTextRegionAccess(access);
        for (ITextSegment region : missing) toString.add(region, region.getClass().getSimpleName());
        String msg = "The following regions are not formatted:\n" + toString;
        System.err.println(msg);
        Assert.fail(msg);
    }
}
Also used : IHiddenRegion(org.eclipse.xtext.formatting2.regionaccess.IHiddenRegion) ITextSegment(org.eclipse.xtext.formatting2.regionaccess.ITextSegment) TextRegionAccessToString(org.eclipse.xtext.formatting2.debug.TextRegionAccessToString) TextRegionsToString(org.eclipse.xtext.formatting2.debug.TextRegionsToString) TextRegionsToString(org.eclipse.xtext.formatting2.debug.TextRegionsToString)

Example 37 with ITextReplacement

use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.

the class FormatterTester method assertFormatted.

public void assertFormatted(FormatterTestRequest req) {
    checkNotNull(req);
    checkNotNull(req.getToBeFormatted());
    FormatterRequest request = req.getRequest();
    checkArgument(request.getTextRegionAccess() == null);
    String document = req.getToBeFormatted().toString();
    XtextResource parsed = parse(document);
    if (req.isAllowSyntaxErrors()) {
        request.setExceptionHandler(ExceptionAcceptor.IGNORING);
    } else {
        assertNoSyntaxErrors(parsed);
        request.setExceptionHandler(ExceptionAcceptor.THROWING);
    }
    request.setTextRegionAccess(createRegionAccess(parsed, req));
    if (request.getPreferences() == null)
        request.setPreferences(new MapBasedPreferenceValues(Maps.<String, String>newLinkedHashMap()));
    List<ITextReplacement> replacements = createFormatter(req).format(request);
    assertReplacementsAreInRegion(replacements, request.getRegions(), document);
    if (!req.isAllowUnformattedWhitespace())
        assertAllWhitespaceIsFormatted(request.getTextRegionAccess(), replacements);
    String formatted = request.getTextRegionAccess().getRewriter().renderToString(replacements);
    Assert.assertEquals(req.getExpectationOrToBeFormatted().toString(), formatted);
// TODO: assert formatting a second time only produces identity replacements
// TODO: assert formatting with undefined whitespace only
}
Also used : ITextReplacement(org.eclipse.xtext.formatting2.regionaccess.ITextReplacement) MapBasedPreferenceValues(org.eclipse.xtext.preferences.MapBasedPreferenceValues) XtextResource(org.eclipse.xtext.resource.XtextResource) TextRegionAccessToString(org.eclipse.xtext.formatting2.debug.TextRegionAccessToString) TextRegionsToString(org.eclipse.xtext.formatting2.debug.TextRegionsToString) FormatterRequest(org.eclipse.xtext.formatting2.FormatterRequest)

Example 38 with ITextReplacement

use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.

the class DefaultLinkedPositionGroupCalculator2 method getLinkedPositionGroup.

@Override
public Provider<LinkedPositionGroup> getLinkedPositionGroup(final IRenameElementContext renameElementContext, final IProgressMonitor monitor) {
    final SubMonitor progress = SubMonitor.convert(monitor, 100);
    IEditorPart _triggeringEditor = renameElementContext.getTriggeringEditor();
    final XtextEditor editor = ((XtextEditor) _triggeringEditor);
    final IProject project = this.projectUtil.getProject(renameElementContext.getContextResourceURI());
    if ((project == null)) {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("Could not determine project for context resource ");
        URI _contextResourceURI = renameElementContext.getContextResourceURI();
        _builder.append(_contextResourceURI);
        String _string = _builder.toString();
        throw new IllegalStateException(_string);
    }
    final CachingResourceSetProvider resourceSetProvider = new CachingResourceSetProvider(this.resourceSetProvider);
    final ResourceSet resourceSet = resourceSetProvider.get(project);
    final EObject targetElement = resourceSet.getEObject(renameElementContext.getTargetElementURI(), true);
    if ((targetElement == null)) {
        throw new IllegalStateException("Target element could not be loaded");
    }
    boolean _isCanceled = monitor.isCanceled();
    if (_isCanceled) {
        throw new OperationCanceledException();
    }
    IRenameStrategy2 renameStrategy = this.globalServiceProvider.<IRenameStrategy2>findService(targetElement, IRenameStrategy2.class);
    if ((renameStrategy == null)) {
        StringConcatenation _builder_1 = new StringConcatenation();
        _builder_1.append("Cannot find a rename strategy for ");
        URI _targetElementURI = renameElementContext.getTargetElementURI();
        _builder_1.append(_targetElementURI);
        throw new IllegalArgumentException(_builder_1.toString());
    }
    final String oldName = this.simpleNameProvider.getSimpleName(targetElement);
    final String newName = this.getNewDummyName(oldName);
    final IResourceServiceProvider resourceServiceProvider = this.resourceServiceProviderRegistry.getResourceServiceProvider(renameElementContext.getTargetElementURI());
    final LtkIssueAcceptor issues = resourceServiceProvider.<LtkIssueAcceptor>get(LtkIssueAcceptor.class);
    final IChangeSerializer changeSerializer = resourceServiceProvider.<IChangeSerializer>get(IChangeSerializer.class);
    changeSerializer.setUpdateRelatedFiles(false);
    URI _targetElementURI_1 = renameElementContext.getTargetElementURI();
    final RenameChange change = new RenameChange(newName, _targetElementURI_1);
    final RenameContext renameContext = new RenameContext(Collections.<RenameChange>unmodifiableList(CollectionLiterals.<RenameChange>newArrayList(change)), resourceSet, changeSerializer, issues);
    renameStrategy.applyRename(renameContext);
    final ArrayList<ReplaceEdit> replaceEdits = CollectionLiterals.<ReplaceEdit>newArrayList();
    final IAcceptor<IEmfResourceChange> _function = (IEmfResourceChange c) -> {
        if ((c instanceof ITextDocumentChange)) {
            final Function1<ITextReplacement, ReplaceEdit> _function_1 = (ITextReplacement replacement) -> {
                int _offset = replacement.getOffset();
                int _length = replacement.getLength();
                String _replacementText = replacement.getReplacementText();
                return new ReplaceEdit(_offset, _length, _replacementText);
            };
            List<ReplaceEdit> _map = ListExtensions.<ITextReplacement, ReplaceEdit>map(((ITextDocumentChange) c).getReplacements(), _function_1);
            Iterables.<ReplaceEdit>addAll(replaceEdits, _map);
        }
    };
    changeSerializer.applyModifications(_function);
    boolean _isCanceled_1 = monitor.isCanceled();
    if (_isCanceled_1) {
        throw new OperationCanceledException();
    }
    final Provider<LinkedPositionGroup> _function_1 = () -> {
        return this.createLinkedGroupFromReplaceEdits(replaceEdits, editor, oldName, progress.newChild(10));
    };
    return _function_1;
}
Also used : ITextReplacement(org.eclipse.xtext.formatting2.regionaccess.ITextReplacement) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) URI(org.eclipse.emf.common.util.URI) IResourceServiceProvider(org.eclipse.xtext.resource.IResourceServiceProvider) IRenameStrategy2(org.eclipse.xtext.ide.refactoring.IRenameStrategy2) EObject(org.eclipse.emf.ecore.EObject) ArrayList(java.util.ArrayList) List(java.util.List) CachingResourceSetProvider(org.eclipse.xtext.ui.refactoring.impl.CachingResourceSetProvider) RenameChange(org.eclipse.xtext.ide.refactoring.RenameChange) RenameContext(org.eclipse.xtext.ide.refactoring.RenameContext) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) SubMonitor(org.eclipse.core.runtime.SubMonitor) Function1(org.eclipse.xtext.xbase.lib.Functions.Function1) ITextDocumentChange(org.eclipse.xtext.ide.serializer.ITextDocumentChange) IEditorPart(org.eclipse.ui.IEditorPart) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) LtkIssueAcceptor(org.eclipse.xtext.ui.refactoring2.LtkIssueAcceptor) IProject(org.eclipse.core.resources.IProject) LinkedPositionGroup(org.eclipse.jface.text.link.LinkedPositionGroup) IChangeSerializer(org.eclipse.xtext.ide.serializer.IChangeSerializer) StringConcatenation(org.eclipse.xtend2.lib.StringConcatenation) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IEmfResourceChange(org.eclipse.xtext.ide.serializer.IEmfResourceChange)

Example 39 with ITextReplacement

use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project xtext-eclipse by eclipse.

the class ContentFormatter method exec.

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();
}
Also used : IFormatter2(org.eclipse.xtext.formatting2.IFormatter2) ITextReplacement(org.eclipse.xtext.formatting2.regionaccess.ITextReplacement) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) IParseResult(org.eclipse.xtext.parser.IParseResult) FormatterRequest(org.eclipse.xtext.formatting2.FormatterRequest) BadLocationException(org.eclipse.jface.text.BadLocationException) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 40 with ITextReplacement

use of org.eclipse.xtext.formatting2.regionaccess.ITextReplacement in project n4js by eclipse.

the class FormatterXpectMethod method formattedLines.

/**
 */
@Xpect
@ParameterParser(syntax = "arg1=INT")
public void formattedLines(@StringExpectation(whitespaceSensitive = true) IStringExpectation exp, // arg1
int lines, XpectInvocation inv, TargetSyntaxSupport syntax, ITextRegionAccess reg, ISetupInitializer<Preferences> prefInit) {
    ITextSegment region = getRegionForLines(reg, syntax.findFirstSemanticCharAfterStatement(inv), lines);
    Preferences prefs = new Preferences();
    // First put some defaults
    prefs.put(N4JSFormatterPreferenceKeys.FORMAT_PARENTHESIS, true);
    prefs.put(FormatterPreferenceKeys.lineSeparator, "\n");
    // Second init from concrete tests - will override defaults.
    prefInit.initialize(prefs);
    IFormatter2 formatter = formatterProvider.get();
    FormatterRequest request = formatterRequestProvider.get();
    request.setTextRegionAccess(reg);
    request.setExceptionHandler(ExceptionAcceptor.THROWING);
    // needed in case a check like this will be implemented:
    // org.eclipse.xtext.testing.formatter.FormatterTester.assertAllWhitespaceIsFormatted()
    request.setAllowIdentityEdits(true);
    request.setFormatUndefinedHiddenRegionsOnly(false);
    request.addRegion(region);
    request.setPreferences(prefs);
    List<ITextReplacement> replacements = formatter.format(request);
    String fmt = reg.getRewriter().renderToString(replacements);
    ITextSegment doc = reg.regionForDocument();
    int endIndex = region.getEndOffset() + (fmt.length() - doc.getLength()) - 1;
    String selection = fmt.substring(region.getOffset(), endIndex);
    exp.assertEquals(selection);
}
Also used : IFormatter2(org.eclipse.xtext.formatting2.IFormatter2) ITextReplacement(org.eclipse.xtext.formatting2.regionaccess.ITextReplacement) ITextSegment(org.eclipse.xtext.formatting2.regionaccess.ITextSegment) Preferences(org.eclipse.n4js.xpect.config.Preferences) FormatterRequest(org.eclipse.xtext.formatting2.FormatterRequest) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Aggregations

ITextReplacement (org.eclipse.xtext.formatting2.regionaccess.ITextReplacement)35 FormatterRequest (org.eclipse.xtext.formatting2.FormatterRequest)13 ITextSegment (org.eclipse.xtext.formatting2.regionaccess.ITextSegment)12 XtextResource (org.eclipse.xtext.resource.XtextResource)11 ITextRegionAccess (org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess)9 TextRegionAccessToString (org.eclipse.xtext.formatting2.debug.TextRegionAccessToString)7 TextRegionsToString (org.eclipse.xtext.formatting2.debug.TextRegionsToString)7 Resource (org.eclipse.emf.ecore.resource.Resource)5 IFormatter2 (org.eclipse.xtext.formatting2.IFormatter2)5 String (java.lang.String)4 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)4 StringConcatenation (org.eclipse.xtend2.lib.StringConcatenation)4 ITextReplacerContext (org.eclipse.xtext.formatting2.ITextReplacerContext)4 IHiddenRegion (org.eclipse.xtext.formatting2.regionaccess.IHiddenRegion)4 ITextRegion (org.eclipse.xtext.util.ITextRegion)4 URI (org.eclipse.emf.common.util.URI)3 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)3 MapBasedPreferenceValues (org.eclipse.xtext.preferences.MapBasedPreferenceValues)3 Procedure1 (org.eclipse.xtext.xbase.lib.Procedures.Procedure1)3 List (java.util.List)2