Search in sources :

Example 1 with FormattingContext

use of org.eclipse.jface.text.formatter.FormattingContext in project tdi-studio-se by Talend.

the class JavaProcessor method formatCode.

/**
     * DOC nrousseau Comment method "formatCode".
     *
     * from SourceViewer.doOperation for FORMAT.
     *
     * @param processCode
     * @return
     */
@SuppressWarnings({ "unchecked" })
private String formatCode(String processCode) {
    // we cannot make calls to Ui in headless mode
    if (ProcessorUtilities.isExportConfig() || CommonsPlugin.isHeadless()) {
        // nothing to do
        return processCode;
    }
    final IDocument document = new Document(processCode);
    JavaTextTools tools = JavaPlugin.getDefault().getJavaTextTools();
    tools.setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
    IFormattingContext context = null;
    DocumentRewriteSession rewriteSession = null;
    if (document instanceof IDocumentExtension4) {
        rewriteSession = ((IDocumentExtension4) document).startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
    }
    try {
        final String rememberedContents = document.get();
        try {
            final MultiPassContentFormatter formatter = new MultiPassContentFormatter(IJavaPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE);
            formatter.setMasterStrategy(new JavaFormattingStrategy());
            // formatter.setSlaveStrategy(new CommentFormattingStrategy(),
            // IJavaPartitions.JAVA_DOC);
            // formatter.setSlaveStrategy(new CommentFormattingStrategy(),
            // IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
            // formatter.setSlaveStrategy(new CommentFormattingStrategy(),
            // IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
            context = new FormattingContext();
            context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE);
            Map<String, String> preferences;
            if (this.getTalendJavaProject() == null) {
                preferences = new HashMap<String, String>(JavaCore.getOptions());
            } else {
                // use project options
                preferences = new HashMap<String, String>(this.getTalendJavaProject().getJavaProject().getOptions(true));
            }
            context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);
            formatter.format(document, context);
        } catch (RuntimeException x) {
            // fire wall for
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472
            // if something went wrong we undo the changes we just did
            // TODO to be removed after 3.0 M8
            document.set(rememberedContents);
            throw x;
        }
    } finally {
        if (rewriteSession != null && document instanceof IDocumentExtension4) {
            ((IDocumentExtension4) document).stopRewriteSession(rewriteSession);
        }
        if (context != null) {
            context.dispose();
        }
    }
    return document.get();
}
Also used : IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext) FormattingContext(org.eclipse.jface.text.formatter.FormattingContext) IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext) IDocumentExtension4(org.eclipse.jface.text.IDocumentExtension4) JavaTextTools(org.eclipse.jdt.ui.text.JavaTextTools) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) DocumentRewriteSession(org.eclipse.jface.text.DocumentRewriteSession) MultiPassContentFormatter(org.eclipse.jface.text.formatter.MultiPassContentFormatter) JavaFormattingStrategy(org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy) IDocument(org.eclipse.jface.text.IDocument)

Example 2 with FormattingContext

use of org.eclipse.jface.text.formatter.FormattingContext in project webtools.sourceediting by eclipse.

the class StructuredTextViewer method doOperation.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.text.ITextOperationTarget#doOperation(int)
	 */
public void doOperation(int operation) {
    Point selection = getTextWidget().getSelection();
    int cursorPosition = selection.x;
    int selectionLength = selection.y - selection.x;
    switch(operation) {
        case CUT:
            beginRecording(TEXT_CUT, TEXT_CUT, cursorPosition, selectionLength);
            super.doOperation(operation);
            selection = getTextWidget().getSelection();
            cursorPosition = selection.x;
            selectionLength = selection.y - selection.x;
            endRecording(cursorPosition, selectionLength);
            break;
        case PASTE:
            beginRecording(TEXT_PASTE, TEXT_PASTE, cursorPosition, selectionLength);
            super.doOperation(operation);
            selection = getTextWidget().getSelection();
            cursorPosition = selection.x;
            selectionLength = selection.y - selection.x;
            endRecording(cursorPosition, selectionLength);
            break;
        case CONTENTASSIST_PROPOSALS:
            // maybe not configured?
            if (fContentAssistant != null && isEditable()) {
                // position
                if (canDoOperation(CONTENTASSIST_PROPOSALS)) {
                    String err = fContentAssistant.showPossibleCompletions();
                    if (err != null) {
                        // don't wanna beep if there is no error
                        PlatformStatusLineUtil.displayTemporaryErrorMessage(this, err);
                    }
                } else
                    beep();
            }
            break;
        case CONTENTASSIST_CONTEXT_INFORMATION:
            if (fContentAssistant != null) {
                String err = fContentAssistant.showContextInformation();
                if (err != null) {
                    // don't wanna beep if there is no error
                    PlatformStatusLineUtil.displayTemporaryErrorMessage(this, err);
                }
            }
            break;
        case SHIFT_RIGHT:
            beginRecording(TEXT_SHIFT_RIGHT, TEXT_SHIFT_RIGHT, cursorPosition, selectionLength);
            updateIndentationPrefixes();
            doModelOperation(SHIFT_RIGHT);
            selection = getTextWidget().getSelection();
            cursorPosition = selection.x;
            selectionLength = selection.y - selection.x;
            endRecording(cursorPosition, selectionLength);
            break;
        case SHIFT_LEFT:
            beginRecording(TEXT_SHIFT_LEFT, TEXT_SHIFT_LEFT, cursorPosition, selectionLength);
            updateIndentationPrefixes();
            doModelOperation(SHIFT_LEFT);
            selection = getTextWidget().getSelection();
            cursorPosition = selection.x;
            selectionLength = selection.y - selection.x;
            endRecording(cursorPosition, selectionLength);
            break;
        case FORMAT_DOCUMENT:
            DocumentRewriteSession rewriteSession = null;
            IDocument document = getDocument();
            try {
                /*
					 * This command will actually format selection if text is
					 * selected, otherwise format entire document
					 */
                // begin recording
                beginRecording(FORMAT_DOCUMENT_TEXT, FORMAT_DOCUMENT_TEXT, cursorPosition, selectionLength);
                boolean formatDocument = false;
                IRegion region = null;
                Point s = getSelectedRange();
                if (s.y > 0) {
                    // only format currently selected text
                    region = new Region(s.x, s.y);
                } else {
                    // no selection, so format entire document
                    region = getModelCoverage();
                    formatDocument = true;
                }
                if (document instanceof IDocumentExtension4) {
                    IDocumentExtension4 extension = (IDocumentExtension4) document;
                    DocumentRewriteSessionType type = (selection.y == 0 || selection.y > MAX_SMALL_FORMAT_LENGTH) ? DocumentRewriteSessionType.UNRESTRICTED : DocumentRewriteSessionType.UNRESTRICTED_SMALL;
                    rewriteSession = (extension.getActiveRewriteSession() != null) ? null : extension.startRewriteSession(type);
                } else {
                    setRedraw(false);
                }
                if (fContentFormatter instanceof IContentFormatterExtension) {
                    IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter;
                    IFormattingContext context = new FormattingContext();
                    context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(formatDocument));
                    context.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
                    extension.format(document, context);
                } else {
                    fContentFormatter.format(document, region);
                }
            } finally {
                try {
                    if (rewriteSession != null) {
                        IDocumentExtension4 extension = (IDocumentExtension4) document;
                        extension.stopRewriteSession(rewriteSession);
                    } else {
                        setRedraw(true);
                    }
                } finally {
                    // end recording
                    selection = getTextWidget().getSelection();
                    cursorPosition = selection.x;
                    selectionLength = selection.y - selection.x;
                    endRecording(cursorPosition, selectionLength);
                }
            }
            break;
        case FORMAT_ACTIVE_ELEMENTS:
            rewriteSession = null;
            document = getDocument();
            try {
                /*
					 * This command will format the node at cursor position
					 * (and all its children)
					 */
                // begin recording
                beginRecording(FORMAT_ACTIVE_ELEMENTS_TEXT, FORMAT_ACTIVE_ELEMENTS_TEXT, cursorPosition, selectionLength);
                IRegion region = null;
                Point s = getSelectedRange();
                if (s.y > -1) {
                    // only format node at cursor position
                    region = new Region(s.x, s.y);
                }
                if (document instanceof IDocumentExtension4) {
                    IDocumentExtension4 extension = (IDocumentExtension4) document;
                    DocumentRewriteSessionType type = (selection.y == 0 || selection.y > MAX_SMALL_FORMAT_LENGTH) ? DocumentRewriteSessionType.UNRESTRICTED : DocumentRewriteSessionType.UNRESTRICTED_SMALL;
                    rewriteSession = (extension.getActiveRewriteSession() != null) ? null : extension.startRewriteSession(type);
                } else {
                    setRedraw(false);
                }
                if (fContentFormatter instanceof IContentFormatterExtension) {
                    IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter;
                    IFormattingContext context = new FormattingContext();
                    context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE);
                    context.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
                    extension.format(getDocument(), context);
                } else {
                    fContentFormatter.format(getDocument(), region);
                }
            } finally {
                try {
                    if (rewriteSession != null) {
                        IDocumentExtension4 extension = (IDocumentExtension4) document;
                        extension.stopRewriteSession(rewriteSession);
                    } else {
                        setRedraw(true);
                    }
                } finally {
                    // end recording
                    selection = getTextWidget().getSelection();
                    cursorPosition = selection.x;
                    selectionLength = selection.y - selection.x;
                    endRecording(cursorPosition, selectionLength);
                }
            }
            break;
        default:
            super.doOperation(operation);
    }
}
Also used : IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext) FormattingContext(org.eclipse.jface.text.formatter.FormattingContext) IDocumentExtension4(org.eclipse.jface.text.IDocumentExtension4) DocumentRewriteSessionType(org.eclipse.jface.text.DocumentRewriteSessionType) IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) IRegion(org.eclipse.jface.text.IRegion) DocumentRewriteSession(org.eclipse.jface.text.DocumentRewriteSession) IRegion(org.eclipse.jface.text.IRegion) Region(org.eclipse.jface.text.Region) IDocument(org.eclipse.jface.text.IDocument) IContentFormatterExtension(org.eclipse.jface.text.formatter.IContentFormatterExtension)

Example 3 with FormattingContext

use of org.eclipse.jface.text.formatter.FormattingContext in project webtools.sourceediting by eclipse.

the class TestContentFormatter method setUp.

protected void setUp() throws Exception {
    super.setUp();
    String noninteractive = System.getProperty("wtp.autotest.noninteractive");
    if (noninteractive != null)
        wtp_autotest_noninteractive = noninteractive;
    System.setProperty("wtp.autotest.noninteractive", "true");
    if (!ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME).exists()) {
        ProjectUtil.createProject(PROJECT_NAME, null, new String[] { JavaCore.NATURE_ID });
        ProjectUtil.copyBundleEntriesIntoWorkspace("/testfiles/" + PROJECT_NAME, "/" + PROJECT_NAME);
    }
    assertTrue("project could not be created", ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME).exists());
    fContext = new FormattingContext();
    fContext.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
}
Also used : FormattingContext(org.eclipse.jface.text.formatter.FormattingContext) IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext)

Example 4 with FormattingContext

use of org.eclipse.jface.text.formatter.FormattingContext in project webtools.sourceediting by eclipse.

the class FormattingTests method formatAndAssertEquals.

/**
 * @param beforePath - the path of the before file
 * @param afterPath - the path of the after file, <b>must not be the same as the before file</b>
 * @param configuration
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws CoreException
 *
 * @see org.eclipse.wst.xml.core.tests.format.TestPartitionFormatterXML#formatAndAssertEquals
 */
private void formatAndAssertEquals(String beforePath, String afterPath, SourceViewerConfiguration configuration) throws UnsupportedEncodingException, IOException, CoreException {
    IStructuredModel beforeModel = null, afterModel = null;
    ISourceViewer viewer = null;
    try {
        beforeModel = getModelForEdit(beforePath);
        assertNotNull("could not retrieve structured model for : " + beforePath, beforeModel);
        JsTranslationAdapterFactory.setupAdapterFactory(beforeModel);
        afterModel = getModelForEdit(afterPath);
        assertNotNull("could not retrieve structured model for : " + afterPath, afterModel);
        // normalize contents
        IStructuredDocument document = beforeModel.getStructuredDocument();
        String normalizedContents = document.get();
        normalizedContents = StringUtils.replace(normalizedContents, "\r\n", "\n");
        normalizedContents = StringUtils.replace(normalizedContents, "\r", "\n");
        document.set(normalizedContents);
        viewer = getConfiguredViewer(document, configuration);
        assertNotNull("Could not get viewer to run test", viewer);
        // do the format
        IContentFormatterExtension formatter = (IContentFormatterExtension) configuration.getContentFormatter(viewer);
        IFormattingContext fContext = new FormattingContext();
        Region region = new Region(0, document.getLength());
        fContext.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
        fContext.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
        formatter.format(document, fContext);
        // get the contents
        String actualContents = beforeModel.getStructuredDocument().get();
        String expectedContents = afterModel.getStructuredDocument().get();
        /* Make some adjustments to ignore cross platform line delimiter issues */
        expectedContents = StringUtils.replace(expectedContents, "\r\n", "\n");
        expectedContents = StringUtils.replace(expectedContents, "\r", "\n");
        actualContents = StringUtils.replace(actualContents, "\r\n", "\n");
        actualContents = StringUtils.replace(actualContents, "\r", "\n");
        onlyWhiteSpaceDiffers(expectedContents, actualContents);
        assertEquals("Formatted document differs from the expected.", expectedContents, actualContents);
    } finally {
        if (beforeModel != null) {
            try {
                beforeModel.releaseFromEdit();
            } catch (Exception e) {
            // ignore
            }
        }
        if (afterModel != null) {
            try {
                afterModel.releaseFromEdit();
            } catch (Exception e) {
            // ignore
            }
        }
        if (viewer != null) {
            StyledText text = viewer.getTextWidget();
            if (text != null && !text.isDisposed()) {
                text.dispose();
            }
        }
    }
}
Also used : FormattingContext(org.eclipse.jface.text.formatter.FormattingContext) IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext) StyledText(org.eclipse.swt.custom.StyledText) IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext) Region(org.eclipse.jface.text.Region) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) ISourceViewer(org.eclipse.jface.text.source.ISourceViewer) IContentFormatterExtension(org.eclipse.jface.text.formatter.IContentFormatterExtension) CoreException(org.eclipse.core.runtime.CoreException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with FormattingContext

use of org.eclipse.jface.text.formatter.FormattingContext in project webtools.sourceediting by eclipse.

the class TestJSPContentFormatter method setUp.

protected void setUp() throws Exception {
    super.setUp();
    String noninteractive = System.getProperty("wtp.autotest.noninteractive");
    if (noninteractive != null)
        wtp_autotest_noninteractive = noninteractive;
    System.setProperty("wtp.autotest.noninteractive", "true");
    if (!ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME).exists()) {
        ProjectUtil.createProject(PROJECT_NAME, null, new String[] { JavaScriptCore.NATURE_ID });
        ProjectUtil.copyBundleEntriesIntoWorkspace("/testFiles/" + PROJECT_NAME, "/" + PROJECT_NAME);
    }
    assertTrue("project could not be created", ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME).exists());
    fContext = new FormattingContext();
    fContext.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true));
}
Also used : FormattingContext(org.eclipse.jface.text.formatter.FormattingContext) IFormattingContext(org.eclipse.jface.text.formatter.IFormattingContext)

Aggregations

FormattingContext (org.eclipse.jface.text.formatter.FormattingContext)5 IFormattingContext (org.eclipse.jface.text.formatter.IFormattingContext)5 DocumentRewriteSession (org.eclipse.jface.text.DocumentRewriteSession)2 IDocument (org.eclipse.jface.text.IDocument)2 IDocumentExtension4 (org.eclipse.jface.text.IDocumentExtension4)2 Region (org.eclipse.jface.text.Region)2 IContentFormatterExtension (org.eclipse.jface.text.formatter.IContentFormatterExtension)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 CoreException (org.eclipse.core.runtime.CoreException)1 JavaFormattingStrategy (org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy)1 JavaTextTools (org.eclipse.jdt.ui.text.JavaTextTools)1 Document (org.eclipse.jface.text.Document)1 DocumentRewriteSessionType (org.eclipse.jface.text.DocumentRewriteSessionType)1 IRegion (org.eclipse.jface.text.IRegion)1 MultiPassContentFormatter (org.eclipse.jface.text.formatter.MultiPassContentFormatter)1 ISourceViewer (org.eclipse.jface.text.source.ISourceViewer)1 StyledText (org.eclipse.swt.custom.StyledText)1 Point (org.eclipse.swt.graphics.Point)1 IStructuredModel (org.eclipse.wst.sse.core.internal.provisional.IStructuredModel)1