Search in sources :

Example 51 with IndexedRegion

use of org.eclipse.wst.sse.core.internal.provisional.IndexedRegion in project webtools.sourceediting by eclipse.

the class JSPTemplateCompletionProcessor method computeCompletionProposals.

/*
	 * Copied from super class except instead of calling createContext(viewer,
	 * region) call createContext(viewer, region, offset) instead
	 */
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
    ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection();
    // adjust offset to end of normalized selection
    if (selection.getOffset() == offset)
        offset = selection.getOffset() + selection.getLength();
    String prefix = extractPrefix(viewer, offset);
    Region region = new Region(offset - prefix.length(), prefix.length());
    // If there's no prefix, check if we're in a tag open region
    if (prefix.trim().length() == 0) {
        IndexedRegion treeNode = ContentAssistUtils.getNodeAt(viewer, offset);
        if (treeNode instanceof IDOMText) {
            IDOMNode node = (IDOMNode) treeNode;
            // Check each region in the node, if the offset is after a tag region, replace it with the template
            IStructuredDocumentRegion cursor = node.getFirstStructuredDocumentRegion();
            IStructuredDocumentRegion end = node.getLastStructuredDocumentRegion();
            do {
                if (cursor != null && DOMRegionContext.XML_TAG_OPEN.equals(cursor.getType()) && cursor.getStartOffset() == offset - 1) {
                    // We have a tag to replace
                    offset = cursor.getStartOffset();
                    region = new Region(cursor.getStartOffset(), cursor.getLength());
                    break;
                }
            } while (cursor != end && (cursor = cursor.getNext()) != null);
        }
    }
    TemplateContext context = createContext(viewer, region, offset);
    if (context == null)
        return new ICompletionProposal[0];
    // name of the selection variables {line, word}_selection
    // //$NON-NLS-1$
    context.setVariable("selection", selection.getText());
    Template[] templates = getTemplates(context.getContextType().getId());
    List matches = new ArrayList();
    for (int i = 0; i < templates.length; i++) {
        Template template = templates[i];
        try {
            context.getContextType().validate(template.getPattern());
        } catch (TemplateException e) {
            continue;
        }
        if (template.matches(prefix, context.getContextType().getId()))
            matches.add(createProposal(template, context, (IRegion) region, getRelevance(template, prefix)));
    }
    Collections.sort(matches, fgProposalComparator);
    return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]);
}
Also used : IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) TemplateException(org.eclipse.jface.text.templates.TemplateException) ArrayList(java.util.ArrayList) TemplateContext(org.eclipse.jface.text.templates.TemplateContext) ReplaceNameTemplateContext(org.eclipse.wst.xml.ui.internal.contentassist.ReplaceNameTemplateContext) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) ITextSelection(org.eclipse.jface.text.ITextSelection) Template(org.eclipse.jface.text.templates.Template) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) IDOMText(org.eclipse.wst.xml.core.internal.provisional.document.IDOMText) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) ArrayList(java.util.ArrayList) List(java.util.List)

Example 52 with IndexedRegion

use of org.eclipse.wst.sse.core.internal.provisional.IndexedRegion in project webtools.sourceediting by eclipse.

the class JSPContentAssistProcessor method addAttributeValueProposals.

/**
 * add proposals for tags in attribute values
 */
protected void addAttributeValueProposals(ContentAssistRequest contentAssistRequest) {
    addTemplates(contentAssistRequest, TemplateContextTypeIdsJSP.ATTRIBUTE_VALUE);
    IDOMNode node = (IDOMNode) contentAssistRequest.getNode();
    // add JSP extra proposals from JSPBeanInfoContentAssistProcessor
    // JSPPropertyContentAssistProcessor
    // 2.1
    // get results from JSPUseBean and JSPProperty here
    // (look up processor in a map based on node name)
    JSPDummyContentAssistProcessor extraProcessor = (JSPDummyContentAssistProcessor) fNameToProcessorMap.get(node.getNodeName());
    if (extraProcessor != null && contentAssistRequest != null) {
        extraProcessor.addAttributeValueProposals(contentAssistRequest);
    }
    ModelQuery mq = ModelQueryUtil.getModelQuery(node.getOwnerDocument());
    if (mq != null) {
        CMDocument doc = mq.getCorrespondingCMDocument(node);
        // this shouldn't have to have the prefix coded in
        if (// $NON-NLS-1$
        doc instanceof JSPCMDocument || doc instanceof CMNodeWrapper || node.getNodeName().startsWith("jsp:"))
            return;
    }
    // Find the attribute name for which this position should have a value
    IStructuredDocumentRegion open = node.getFirstStructuredDocumentRegion();
    ITextRegionList openRegions = open.getRegions();
    int i = openRegions.indexOf(contentAssistRequest.getRegion());
    if (i < 0)
        return;
    ITextRegion nameRegion = null;
    while (i >= 0) {
        nameRegion = openRegions.get(i--);
        if (nameRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME)
            break;
    }
    // on an empty value, add all the JSP and taglib tags
    CMElementDeclaration elementDecl = getCMElementDeclaration(node);
    if (nameRegion != null && elementDecl != null) {
        String attributeName = open.getText(nameRegion);
        if (attributeName != null) {
            String currentValue = node.getAttributes().getNamedItem(attributeName).getNodeValue();
            if (currentValue == null || currentValue.length() == 0) {
                // $NON-NLS-1$
                List additionalElements = ModelQueryUtil.getModelQuery(node.getOwnerDocument()).getAvailableContent((Element) node, elementDecl, ModelQuery.INCLUDE_ATTRIBUTES);
                for (i = 0; i < additionalElements.size(); i++) {
                    Object additionalElement = additionalElements.get(i);
                    if (additionalElement instanceof CMElementDeclaration) {
                        CMElementDeclaration ed = (CMElementDeclaration) additionalElement;
                        String tagname = getContentGenerator().getRequiredName(node, ed);
                        // $NON-NLS-1$
                        StringBuffer contents = new StringBuffer("\"");
                        getContentGenerator().generateTag(node, ed, contents);
                        // $NON-NLS-1$
                        contents.append('"');
                        CustomCompletionProposal proposal = new CustomCompletionProposal(contents.toString(), contentAssistRequest.getReplacementBeginPosition(), contentAssistRequest.getReplacementLength(), contents.length(), JSPEditorPluginImageHelper.getInstance().getImage(JSPEditorPluginImages.IMG_OBJ_TAG_GENERIC), tagname, null, null, XMLRelevanceConstants.R_JSP_ATTRIBUTE_VALUE);
                        contentAssistRequest.addProposal(proposal);
                    }
                }
            }
        }
    } else if (contentAssistRequest.getRegion().getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) {
        try {
            // Create a new model for Content Assist to operate on. This
            // will simulate
            // a full Document and then adjust the offset numbers in the
            // list of results.
            IStructuredModel internalModel = null;
            IModelManager mmanager = StructuredModelManager.getModelManager();
            internalModel = mmanager.createUnManagedStructuredModelFor(ContentTypeIdForJSP.ContentTypeID_JSP);
            IDOMNode xmlNode = null;
            IDOMModel xmlOuterModel = null;
            if (contentAssistRequest.getNode() instanceof IDOMNode) {
                xmlNode = (IDOMNode) contentAssistRequest.getNode();
                xmlOuterModel = xmlNode.getModel();
                internalModel.setResolver(xmlOuterModel.getResolver());
                internalModel.setBaseLocation(xmlOuterModel.getBaseLocation());
            }
            String contents = StringUtils.strip(contentAssistRequest.getText());
            if (xmlNode != null && contents != null) {
                int additionalShifts = 0;
                // Be sure that custom tags from taglibs also show up
                // by
                // adding taglib declarations to the internal model.
                TLDCMDocumentManager mgr = TaglibController.getTLDCMDocumentManager(xmlOuterModel.getStructuredDocument());
                if (mgr != null) {
                    List trackers = mgr.getCMDocumentTrackers(contentAssistRequest.getReplacementBeginPosition());
                    if (trackers != null) {
                        for (i = 0; i < trackers.size(); i++) {
                            CMDocumentTracker tracker = (CMDocumentTracker) trackers.get(i);
                            String declaration = tracker.getStructuredDocumentRegion().getText();
                            if (declaration != null) {
                                contents = declaration + contents;
                                additionalShifts += declaration.length();
                            }
                        }
                    }
                }
                // Also copy any jsp:useBean tags so that
                // jsp:[gs]etProperty will function
                Document doc = null;
                if (contentAssistRequest.getNode().getNodeType() == Node.DOCUMENT_NODE)
                    doc = (Document) node;
                else
                    doc = node.getOwnerDocument();
                NodeList useBeans = doc.getElementsByTagName(JSP12Namespace.ElementName.USEBEAN);
                for (int k = 0; k < useBeans.getLength(); k++) {
                    IDOMNode useBean = (IDOMNode) useBeans.item(k);
                    if (useBean.getStartOffset() < contentAssistRequest.getReplacementBeginPosition()) {
                        // $NON-NLS-1$
                        StringBuffer useBeanText = new StringBuffer("<jsp:useBean");
                        for (int j = 0; j < useBean.getAttributes().getLength(); j++) {
                            Attr attr = (Attr) useBean.getAttributes().item(j);
                            useBeanText.append(' ');
                            useBeanText.append(attr.getName());
                            // $NON-NLS-1$
                            useBeanText.append("=\"");
                            useBeanText.append(attr.getValue());
                            useBeanText.append('"');
                        }
                        // $NON-NLS-1$
                        useBeanText.append("/>");
                        additionalShifts += useBeanText.length();
                        contents = useBeanText.toString() + contents;
                    }
                }
                internalModel.getStructuredDocument().set(contents);
                int internalOffset = 0;
                boolean quoted = false;
                // if quoted, use position inside and shift by one
                if (contentAssistRequest.getMatchString().length() > 0 && (contentAssistRequest.getMatchString().charAt(0) == '\'' || contentAssistRequest.getMatchString().charAt(0) == '"')) {
                    internalOffset = contentAssistRequest.getMatchString().length() - 1 + additionalShifts;
                    quoted = true;
                } else // if unquoted, use position inside
                if (contentAssistRequest.getMatchString().length() > 0 && contentAssistRequest.getMatchString().charAt(0) == '<')
                    internalOffset = contentAssistRequest.getMatchString().length() + additionalShifts;
                else
                    internalOffset = contentAssistRequest.getReplacementBeginPosition() - contentAssistRequest.getStartOffset() + additionalShifts;
                depthCount++;
                IndexedRegion internalNode = null;
                int tmpOffset = internalOffset;
                while (internalNode == null && tmpOffset >= 0) internalNode = internalModel.getIndexedRegion(tmpOffset--);
                if (internalModel.getFactoryRegistry() != null) {
                    // set up the internal model
                    if (internalModel.getFactoryRegistry().getFactoryFor(PageDirectiveAdapter.class) == null) {
                        internalModel.getFactoryRegistry().addFactory(new PageDirectiveAdapterFactory());
                    }
                    PageDirectiveAdapter outerEmbeddedTypeAdapter = (PageDirectiveAdapter) xmlOuterModel.getDocument().getAdapterFor(PageDirectiveAdapter.class);
                    PageDirectiveAdapter internalEmbeddedTypeAdapter = (PageDirectiveAdapter) ((INodeNotifier) ((Node) internalNode).getOwnerDocument()).getAdapterFor(PageDirectiveAdapter.class);
                    internalEmbeddedTypeAdapter.setEmbeddedType(outerEmbeddedTypeAdapter.getEmbeddedType());
                }
                AdapterFactoryRegistry adapterRegistry = JSPUIPlugin.getDefault().getAdapterFactoryRegistry();
                Iterator adapterList = adapterRegistry.getAdapterFactories();
                // of content
                while (adapterList.hasNext()) {
                    try {
                        AdapterFactoryProvider provider = (AdapterFactoryProvider) adapterList.next();
                        if (provider.isFor(internalModel.getModelHandler())) {
                            provider.addAdapterFactories(internalModel);
                        }
                    } catch (Exception e) {
                        Logger.logException(e);
                    }
                }
                /**
                 * the internal adapter does all the real work of using
                 * the JSP content model to form proposals
                 */
                ICompletionProposal[] results = null;
                depthCount--;
                if (results != null) {
                    for (i = 0; i < results.length; i++) {
                        contentAssistRequest.addProposal(new CustomCompletionProposal(((CustomCompletionProposal) results[i]).getReplacementString(), ((CustomCompletionProposal) results[i]).getReplacementOffset() - additionalShifts + contentAssistRequest.getStartOffset() + (quoted ? 1 : 0), ((CustomCompletionProposal) results[i]).getReplacementLength(), ((CustomCompletionProposal) results[i]).getCursorPosition(), results[i].getImage(), results[i].getDisplayString(), ((CustomCompletionProposal) results[i]).getContextInformation(), ((CustomCompletionProposal) results[i]).getAdditionalProposalInfo(), (results[i] instanceof IRelevanceCompletionProposal) ? ((IRelevanceCompletionProposal) results[i]).getRelevance() : IRelevanceConstants.R_NONE));
                    }
                }
            }
        } catch (Exception e) {
            // $NON-NLS-1$
            Logger.logException("Error in embedded JSP Content Assist", e);
        }
    }
}
Also used : IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) CMNodeWrapper(org.eclipse.wst.xml.core.internal.provisional.contentmodel.CMNodeWrapper) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) PageDirectiveAdapterFactory(org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapterFactory) CustomCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal) IModelManager(org.eclipse.wst.sse.core.internal.provisional.IModelManager) PageDirectiveAdapter(org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapter) Document(org.w3c.dom.Document) JSPCMDocument(org.eclipse.wst.html.core.internal.contentmodel.JSPCMDocument) IDocument(org.eclipse.jface.text.IDocument) CMDocument(org.eclipse.wst.xml.core.internal.contentmodel.CMDocument) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) Attr(org.w3c.dom.Attr) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) CMDocumentTracker(org.eclipse.wst.xml.core.internal.provisional.contentmodel.CMDocumentTracker) IRelevanceCompletionProposal(org.eclipse.wst.sse.ui.internal.contentassist.IRelevanceCompletionProposal) Iterator(java.util.Iterator) List(java.util.List) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) INodeNotifier(org.eclipse.wst.sse.core.internal.provisional.INodeNotifier) JSPCMDocument(org.eclipse.wst.html.core.internal.contentmodel.JSPCMDocument) CMDocument(org.eclipse.wst.xml.core.internal.contentmodel.CMDocument) AdapterFactoryProvider(org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryProvider) TLDCMDocumentManager(org.eclipse.jst.jsp.core.internal.contentmodel.tld.TLDCMDocumentManager) NodeList(org.w3c.dom.NodeList) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) BadLocationException(org.eclipse.jface.text.BadLocationException) ITextRegionList(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList) CMElementDeclaration(org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration) ITextRegion(org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion) JSPCMDocument(org.eclipse.wst.html.core.internal.contentmodel.JSPCMDocument) ModelQuery(org.eclipse.wst.xml.core.internal.contentmodel.modelquery.ModelQuery) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) AdapterFactoryRegistry(org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryRegistry)

Example 53 with IndexedRegion

use of org.eclipse.wst.sse.core.internal.provisional.IndexedRegion in project webtools.sourceediting by eclipse.

the class TestCSSDecl method testInsertPropertyInExistingRule.

/**
 * To test https://bugs.eclipse.org/298111
 */
public void testInsertPropertyInExistingRule() {
    ICSSModel model = FileUtil.createModel();
    try {
        String originalDocument = "@CHARSET \"ISO-8859-1\";\r\n" + ".test {\r\n" + "}";
        IStructuredDocument structuredDocument = model.getStructuredDocument();
        structuredDocument.set(originalDocument);
        IndexedRegion indexedRegion = model.getIndexedRegion(28);
        assertTrue("Indexed region should be an ICSSStyleRule", indexedRegion instanceof ICSSStyleRule);
        ICSSStyleRule rule = (ICSSStyleRule) indexedRegion;
        ICSSStyleDeclaration declaration = (ICSSStyleDeclaration) rule.getStyle();
        declaration.setProperty("color", "#008040", null);
        CSSPropertyContext context = new CSSPropertyContext(declaration);
        context.applyModified(declaration);
        String newDocument = structuredDocument.get();
        String expectedNewDocument = "@CHARSET \"ISO-8859-1\";\r\n" + ".test {\r\n" + "\tcolor: #008040\r\n" + "}";
        assertEquals("The updated CSS document does not equal the expected", expectedNewDocument, newDocument);
    } finally {
        if (model != null) {
            model.releaseFromEdit();
        }
    }
}
Also used : ICSSModel(org.eclipse.wst.css.core.internal.provisional.document.ICSSModel) ICSSStyleDeclaration(org.eclipse.wst.css.core.internal.provisional.document.ICSSStyleDeclaration) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) ICSSStyleRule(org.eclipse.wst.css.core.internal.provisional.document.ICSSStyleRule) CSSPropertyContext(org.eclipse.wst.css.core.internal.util.declaration.CSSPropertyContext)

Example 54 with IndexedRegion

use of org.eclipse.wst.sse.core.internal.provisional.IndexedRegion in project webtools.sourceediting by eclipse.

the class StructuredSelectEnclosingXMLActionDelegate method getNewSelectionRegion.

protected Region getNewSelectionRegion(IndexedRegion indexedRegion, ITextSelection textSelection) {
    Region newRegion = null;
    if (indexedRegion instanceof Node) {
        Node cursorNode = (Node) indexedRegion;
        // use parent node for empty text node
        if ((cursorNode.getNodeType() == Node.TEXT_NODE) && (cursorNode.getNodeValue().trim().length() == 0)) {
            cursorNode = cursorNode.getParentNode();
            if (cursorNode instanceof IndexedRegion) {
                indexedRegion = (IndexedRegion) cursorNode;
            }
        }
        Region cursorNodeRegion = new Region(indexedRegion.getStartOffset(), indexedRegion.getEndOffset() - indexedRegion.getStartOffset());
        if ((cursorNodeRegion.getOffset() >= textSelection.getOffset()) && (cursorNodeRegion.getOffset() <= textSelection.getOffset() + textSelection.getLength()) && (cursorNodeRegion.getOffset() + cursorNodeRegion.getLength() >= textSelection.getOffset()) && (cursorNodeRegion.getOffset() + cursorNodeRegion.getLength() <= textSelection.getOffset() + textSelection.getLength())) {
            Node newNode = cursorNode.getParentNode();
            if (newNode instanceof IndexedRegion) {
                IndexedRegion newIndexedRegion = (IndexedRegion) newNode;
                newRegion = new Region(newIndexedRegion.getStartOffset(), newIndexedRegion.getEndOffset() - newIndexedRegion.getStartOffset());
            }
        } else {
            newRegion = cursorNodeRegion;
        }
    }
    return newRegion;
}
Also used : Node(org.w3c.dom.Node) Region(org.eclipse.jface.text.Region) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion)

Example 55 with IndexedRegion

use of org.eclipse.wst.sse.core.internal.provisional.IndexedRegion in project webtools.sourceediting by eclipse.

the class XMLQuickAssistProcessor method getNodeAt.

/**
 * Returns the closest IndexedRegion for the offset and viewer allowing
 * for differences between viewer offsets and model positions. note: this
 * method returns an IndexedRegion for read only
 *
 * @param viewer
 *            the viewer whose document is used to compute the proposals
 * @param documentOffset
 *            an offset within the document for which completions should
 *            be computed
 * @return an IndexedRegion
 */
private IndexedRegion getNodeAt(ITextViewer viewer, int documentOffset) {
    // copied from ContentAssistUtils.getNodeAt()
    if (viewer == null)
        return null;
    IndexedRegion node = null;
    IModelManager mm = StructuredModelManager.getModelManager();
    IStructuredModel model = null;
    if (mm != null)
        model = mm.getExistingModelForRead(viewer.getDocument());
    try {
        if (model != null) {
            int lastOffset = documentOffset;
            node = model.getIndexedRegion(documentOffset);
            while (node == null && lastOffset >= 0) {
                lastOffset--;
                node = model.getIndexedRegion(lastOffset);
            }
        }
    } finally {
        if (model != null)
            model.releaseFromRead();
    }
    return node;
}
Also used : IModelManager(org.eclipse.wst.sse.core.internal.provisional.IModelManager) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) IndexedRegion(org.eclipse.wst.sse.core.internal.provisional.IndexedRegion)

Aggregations

IndexedRegion (org.eclipse.wst.sse.core.internal.provisional.IndexedRegion)148 IStructuredDocument (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument)33 IStructuredDocumentRegion (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion)32 IStructuredModel (org.eclipse.wst.sse.core.internal.provisional.IStructuredModel)31 ITextRegion (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion)27 Node (org.w3c.dom.Node)27 Region (org.eclipse.jface.text.Region)21 ICSSNode (org.eclipse.wst.css.core.internal.provisional.document.ICSSNode)21 IDOMNode (org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode)21 CSSCleanupStrategy (org.eclipse.wst.css.core.internal.cleanup.CSSCleanupStrategy)20 RegionIterator (org.eclipse.wst.css.core.internal.util.RegionIterator)17 ArrayList (java.util.ArrayList)11 List (java.util.List)11 ITextSelection (org.eclipse.jface.text.ITextSelection)11 IDOMModel (org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel)10 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)8 ITextEditor (org.eclipse.ui.texteditor.ITextEditor)8 ITextRegionList (org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList)8 Preferences (org.eclipse.core.runtime.Preferences)7 IDocument (org.eclipse.jface.text.IDocument)7