Search in sources :

Example 1 with TemplateVariable

use of org.eclipse.jface.text.templates.TemplateVariable in project che by eclipse.

the class StubUtility method fixEmptyVariables.

// remove lines for empty variables
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
    IDocument doc = new Document(buffer.getString());
    int nLines = doc.getNumberOfLines();
    MultiTextEdit edit = new MultiTextEdit();
    HashSet<Integer> removedLines = new HashSet<Integer>();
    for (int i = 0; i < variables.length; i++) {
        // look if Javadoc tags have to be added
        TemplateVariable position = findVariable(buffer, variables[i]);
        if (position == null || position.getLength() > 0) {
            continue;
        }
        int[] offsets = position.getOffsets();
        for (int k = 0; k < offsets.length; k++) {
            int line = doc.getLineOfOffset(offsets[k]);
            IRegion lineInfo = doc.getLineInformation(line);
            int offset = lineInfo.getOffset();
            String str = doc.get(offset, lineInfo.getLength());
            if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
                int nextStart = doc.getLineOffset(line + 1);
                edit.addChild(new DeleteEdit(offset, nextStart - offset));
            }
        }
    }
    edit.apply(doc, 0);
    return doc.get();
}
Also used : TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) DeleteEdit(org.eclipse.text.edits.DeleteEdit) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IRegion(org.eclipse.jface.text.IRegion) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 2 with TemplateVariable

use of org.eclipse.jface.text.templates.TemplateVariable in project che by eclipse.

the class StubUtility method getMethodComment.

/*
	 * Don't use this method directly, use CodeGeneration.
	 * This method should work with all AST levels.
	 * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, boolean, String, String[], String)
	 */
public static String getMethodComment(ICompilationUnit cu, String typeName, MethodDeclaration decl, boolean isDeprecated, String targetName, String targetMethodDeclaringTypeName, String[] targetMethodParameterTypeNames, boolean delegate, String lineDelimiter) throws CoreException {
    boolean needsTarget = targetMethodDeclaringTypeName != null && targetMethodParameterTypeNames != null;
    String templateName = CodeTemplateContextType.METHODCOMMENT_ID;
    if (decl.isConstructor()) {
        templateName = CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
    } else if (needsTarget) {
        if (delegate)
            templateName = CodeTemplateContextType.DELEGATECOMMENT_ID;
        else
            templateName = CodeTemplateContextType.OVERRIDECOMMENT_ID;
    }
    Template template = getCodeTemplate(templateName, cu.getJavaProject());
    if (template == null) {
        return null;
    }
    CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
    context.setCompilationUnitVariables(cu);
    context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
    context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier());
    if (!decl.isConstructor()) {
        context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(getReturnType(decl)));
    }
    if (needsTarget) {
        if (delegate)
            context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
        else
            context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
    }
    TemplateBuffer buffer;
    try {
        buffer = context.evaluate(template);
    } catch (BadLocationException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    } catch (TemplateException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    }
    if (buffer == null)
        return null;
    String str = buffer.getString();
    if (Strings.containsOnlyWhitespaces(str)) {
        return null;
    }
    // look if Javadoc tags have to be added
    TemplateVariable position = findVariable(buffer, CodeTemplateContextType.TAGS);
    if (position == null) {
        return str;
    }
    IDocument textBuffer = new Document(str);
    List<TypeParameter> typeParams = shouldGenerateMethodTypeParameterTags(cu.getJavaProject()) ? decl.typeParameters() : Collections.emptyList();
    String[] typeParamNames = new String[typeParams.size()];
    for (int i = 0; i < typeParamNames.length; i++) {
        TypeParameter elem = typeParams.get(i);
        typeParamNames[i] = elem.getName().getIdentifier();
    }
    List<SingleVariableDeclaration> params = decl.parameters();
    String[] paramNames = new String[params.size()];
    for (int i = 0; i < paramNames.length; i++) {
        SingleVariableDeclaration elem = params.get(i);
        paramNames[i] = elem.getName().getIdentifier();
    }
    String[] exceptionNames = getExceptionNames(decl);
    String returnType = null;
    if (!decl.isConstructor()) {
        returnType = ASTNodes.asString(getReturnType(decl));
    }
    int[] tagOffsets = position.getOffsets();
    for (int i = tagOffsets.length - 1; i >= 0; i--) {
        // from last to first
        try {
            insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, typeParamNames, isDeprecated, lineDelimiter);
        } catch (BadLocationException e) {
            throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
        }
    }
    return textBuffer.get();
}
Also used : TypeParameter(org.eclipse.jdt.core.dom.TypeParameter) ITypeParameter(org.eclipse.jdt.core.ITypeParameter) TemplateException(org.eclipse.jface.text.templates.TemplateException) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) TemplateBuffer(org.eclipse.jface.text.templates.TemplateBuffer) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) Template(org.eclipse.jface.text.templates.Template) CodeTemplateContext(org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext) CoreException(org.eclipse.core.runtime.CoreException) TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) BadLocationException(org.eclipse.jface.text.BadLocationException) IDocument(org.eclipse.jface.text.IDocument)

Example 3 with TemplateVariable

use of org.eclipse.jface.text.templates.TemplateVariable in project che by eclipse.

the class StubUtility method getTypeComment.

/*
	 * Don't use this method directly, use CodeGeneration.
	 * @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String[], String)
	 */
public static String getTypeComment(ICompilationUnit cu, String typeQualifiedName, String[] typeParameterNames, String lineDelim) throws CoreException {
    Template template = getCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, cu.getJavaProject());
    if (template == null) {
        return null;
    }
    CodeTemplateContext context = new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim);
    context.setCompilationUnitVariables(cu);
    context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature.getQualifier(typeQualifiedName));
    context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getSimpleName(typeQualifiedName));
    TemplateBuffer buffer;
    try {
        buffer = context.evaluate(template);
    } catch (BadLocationException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    } catch (TemplateException e) {
        throw new CoreException(Status.CANCEL_STATUS);
    }
    String str = buffer.getString();
    if (Strings.containsOnlyWhitespaces(str)) {
        return null;
    }
    // look if Javadoc tags have to be added
    TemplateVariable position = findVariable(buffer, CodeTemplateContextType.TAGS);
    if (position == null) {
        return str;
    }
    IDocument document = new Document(str);
    int[] tagOffsets = position.getOffsets();
    for (int i = tagOffsets.length - 1; i >= 0; i--) {
        // from last to first
        try {
            insertTag(document, tagOffsets[i], position.getLength(), EMPTY, EMPTY, null, typeParameterNames, false, lineDelim);
        } catch (BadLocationException e) {
            throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
        }
    }
    return document.get();
}
Also used : CodeTemplateContext(org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext) CoreException(org.eclipse.core.runtime.CoreException) TemplateException(org.eclipse.jface.text.templates.TemplateException) TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) TemplateBuffer(org.eclipse.jface.text.templates.TemplateBuffer) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) IDocument(org.eclipse.jface.text.IDocument) Template(org.eclipse.jface.text.templates.Template)

Example 4 with TemplateVariable

use of org.eclipse.jface.text.templates.TemplateVariable in project che by eclipse.

the class TemplateProposal method apply.

/*
     * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
     */
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    IDocument document = viewer.getDocument();
    try {
        fContext.setReadOnly(false);
        int start;
        TemplateBuffer templateBuffer;
        try {
            beginCompoundChange(viewer);
            int oldReplaceOffset = getReplaceOffset();
            try {
                // this may already modify the document (e.g. add imports)
                templateBuffer = fContext.evaluate(fTemplate);
            } catch (TemplateException e1) {
                fSelectedRegion = fRegion;
                return;
            }
            start = getReplaceOffset();
            int shift = start - oldReplaceOffset;
            int end = Math.max(getReplaceEndOffset(), offset + shift);
            // insert template string
            if (end > document.getLength())
                end = offset;
            String templateString = templateBuffer.getString();
            document.replace(start, end - start, templateString);
        } finally {
            endCompoundChange(viewer);
        }
        // translate positions
        LinkedModeModelImpl model = new LinkedModeModelImpl();
        TemplateVariable[] variables = templateBuffer.getVariables();
        MultiVariableGuess guess = fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext).getMultiVariableGuess() : null;
        boolean hasPositions = false;
        for (int i = 0; i != variables.length; i++) {
            TemplateVariable variable = variables[i];
            if (variable.isUnambiguous())
                continue;
            LinkedPositionGroupImpl group = new LinkedPositionGroupImpl();
            int[] offsets = variable.getOffsets();
            int length = variable.getLength();
            LinkedPosition first;
            if (guess != null && variable instanceof MultiVariable) {
                first = new VariablePosition(document, offsets[0] + start, length, guess, (MultiVariable) variable);
                guess.addSlave((VariablePosition) first);
            } else {
                String[] values = variable.getValues();
                ICompletionProposal[] proposals = new ICompletionProposal[values.length];
                for (int j = 0; j < values.length; j++) {
                    //						ensurePositionCategoryInstalled(document, model);
                    Position pos = new Position(offsets[0] + start, length);
                    //						document.addPosition(getCategory(), pos);
                    proposals[j] = new PositionBasedCompletionProposal(values[j], pos, length);
                }
                if (proposals.length > 1)
                    first = new ProposalPosition(document, offsets[0] + start, length, proposals);
                else
                    first = new LinkedPosition(document, offsets[0] + start, length);
            }
            for (int j = 0; j != offsets.length; j++) if (j == 0) {
                if (first instanceof ProposalPosition) {
                    RegionImpl region = new RegionImpl();
                    region.setLength(first.getLength());
                    region.setOffset(first.getOffset());
                    LinkedDataImpl data = new LinkedDataImpl();
                    ICompletionProposal[] choices = ((ProposalPosition) first).getChoices();
                    if (choices != null) {
                        for (ICompletionProposal choice : choices) {
                            data.addValues(choice.getDisplayString());
                        }
                        group.setData(data);
                    }
                    group.addPositions(region);
                } else {
                    RegionImpl region = new RegionImpl();
                    region.setLength(first.getLength());
                    region.setOffset(first.getOffset());
                    group.addPositions(region);
                }
            } else {
                RegionImpl region = new RegionImpl();
                region.setLength(length);
                region.setOffset(offsets[j] + start);
                group.addPositions(region);
            }
            model.addGroups(group);
            hasPositions = true;
        }
        if (hasPositions) {
            model.setEscapePosition(getCaretOffset(templateBuffer) + start);
            this.linkedModeModel = model;
            //				model.forceInstall();
            //				JavaEditor editor= getJavaEditor();
            //				if (editor != null) {
            //					model.addLinkingListener(new EditorHighlightingSynchronizer(editor));
            //				}
            //
            //				LinkedModeUI ui= new EditorLinkedModeUI(model, viewer);
            //				ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + start, 0, Integer.MAX_VALUE);
            //				ui.enter();
            //ui.getSelectedRegion();
            fSelectedRegion = fRegion;
        } else {
            fSelectedRegion = new Region(getCaretOffset(templateBuffer) + start, 0);
        }
    } catch (BadLocationException e) {
        JavaPlugin.log(e);
        //			openErrorDialog(viewer.getTextWidget().getShell(), e);
        fSelectedRegion = fRegion;
    }
}
Also used : TemplateBuffer(org.eclipse.jface.text.templates.TemplateBuffer) StyledString(org.eclipse.jface.viewers.StyledString) ICompletionProposal(org.eclipse.che.jface.text.contentassist.ICompletionProposal) TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) LinkedPosition(org.eclipse.jface.text.link.LinkedPosition) LinkedPositionGroupImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedPositionGroupImpl) TemplateException(org.eclipse.jface.text.templates.TemplateException) LinkedPosition(org.eclipse.jface.text.link.LinkedPosition) ProposalPosition(org.eclipse.che.jface.text.link.ProposalPosition) Position(org.eclipse.jface.text.Position) LinkedModeModelImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedModeModelImpl) LinkedDataImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedDataImpl) Point(org.eclipse.swt.graphics.Point) ProposalPosition(org.eclipse.che.jface.text.link.ProposalPosition) CompilationUnitContext(org.eclipse.jdt.internal.corext.template.java.CompilationUnitContext) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) RegionImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.RegionImpl) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 5 with TemplateVariable

use of org.eclipse.jface.text.templates.TemplateVariable in project che by eclipse.

the class NameResolver method resolve.

/*
	 * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext)
	 */
@Override
public void resolve(TemplateVariable variable, TemplateContext context) {
    List<String> params = variable.getVariableType().getParams();
    String param;
    if (params.size() == 0)
        param = fDefaultType;
    else
        param = params.get(0);
    JavaContext jc = (JavaContext) context;
    TemplateVariable ref = jc.getTemplateVariable(param);
    MultiVariable mv = (MultiVariable) variable;
    if (ref instanceof MultiVariable) {
        // reference is another variable
        MultiVariable refVar = (MultiVariable) ref;
        jc.addDependency(refVar, mv);
        refVar.getAllChoices();
        Object[] types = flatten(refVar.getAllChoices());
        for (int i = 0; i < types.length; i++) {
            String[] names = jc.suggestVariableNames(mv.toString(types[i]));
            mv.setChoices(types[i], names);
        }
        mv.setKey(refVar.getCurrentChoice());
        jc.markAsUsed(mv.getDefaultValue());
    } else {
        // reference is a Java type name
        jc.addImport(param);
        String[] names = jc.suggestVariableNames(param);
        mv.setChoices(names);
        jc.markAsUsed(names[0]);
    }
}
Also used : TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) MultiVariable(org.eclipse.jdt.internal.ui.text.template.contentassist.MultiVariable)

Aggregations

TemplateVariable (org.eclipse.jface.text.templates.TemplateVariable)44 TemplateBuffer (org.eclipse.jface.text.templates.TemplateBuffer)30 IDocument (org.eclipse.jface.text.IDocument)14 Test (org.junit.Test)14 Document (org.eclipse.jface.text.Document)13 BadLocationException (org.eclipse.jface.text.BadLocationException)11 Template (org.eclipse.jface.text.templates.Template)10 TemplateException (org.eclipse.jface.text.templates.TemplateException)10 CoreException (org.eclipse.core.runtime.CoreException)9 CodeTemplateContext (org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext)6 ArrayList (java.util.ArrayList)5 IRegion (org.eclipse.jface.text.IRegion)4 ITypeParameter (org.eclipse.jdt.core.ITypeParameter)3 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)3 TypeParameter (org.eclipse.jdt.core.dom.TypeParameter)3 MultiVariable (org.eclipse.jdt.internal.ui.text.template.contentassist.MultiVariable)3 CodeTemplateContext (org.eclipse.jdt.ls.core.internal.corext.template.java.CodeTemplateContext)3 CodeGenerationTemplate (org.eclipse.jdt.ls.core.internal.preferences.CodeGenerationTemplate)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 HashSet (java.util.HashSet)2