com.intellij.psi.javadoc.PsiDocComment Java Examples

The following examples show how to use com.intellij.psi.javadoc.PsiDocComment. 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: FieldDocGenerator.java    From easy_javadoc with Apache License 2.0 6 votes vote down vote up
/**
 * 生成正常的文档
 *
 * @param psiField 属性
 * @param name     名字
 * @return {@link java.lang.String}
 */
private String genNormalDoc(PsiField psiField, String name) {
    PsiDocComment comment = psiField.getDocComment();
    if (comment != null) {
        List<PsiElement> elements = Lists.newArrayList(comment.getChildren());

        // 注释
        String desc = translatorService.translate(name);
        List<String> commentItems = Lists.newLinkedList();
        for (PsiElement element : elements) {
            commentItems.add(element.getText());
        }
        commentItems.add(1, buildDesc(elements, desc));
        return Joiner.on(StringUtils.EMPTY).skipNulls().join(commentItems);
    }
    return String.format("/**%s* %s%s */%s", "\n", translatorService.translate(name), "\n",
        "\n");
}
 
Example #2
Source File: PsiCustomUtil.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
@Nullable
public static String computeDocumentation(PsiMember member) {
  PsiDocComment docComment;
  if (member instanceof PsiField) {
    docComment = PsiField.class.cast(member).getDocComment();
  } else if (member instanceof PsiMethod) {
    docComment = PsiMethod.class.cast(member).getDocComment();
  } else {
    throw new RuntimeException("Method supports targets of type PsiField & PsiMethod only");
  }
  if (docComment != null) {
    StringBuilder builder = new StringBuilder();
    new JavaDocInfoGenerator(member.getProject(), member)
        .generateCommonSection(builder, docComment);
    return builder.toString().trim();
  }
  return null;
}
 
Example #3
Source File: DocCommentProcessor.java    From markdown-doclet with GNU General Public License v3.0 6 votes vote down vote up
PsiDocComment apply() {
    if ( docContext == null ) {
        return originalDocComment;
    }
    docTextPosition = 0;
    buffer = null;
    originalDocComment.acceptChildren(LinkExpander.this);
    if ( buffer == null ) {
        return originalDocComment;
    }
    else {
        buffer.append(docText, docTextPosition, docText.length());
        String text = buffer.toString();
        Plugin.print("After expanding links", text);
        return docCommentFromText(docContext, text);
    }
}
 
Example #4
Source File: DocGenerateAction.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
/**
 * Create doc for method.
 *
 * @param psiMethod the psi method
 * @param psiElementFactory the psi element factory
 */
private void createDocForMethod(PsiMethod psiMethod, PsiElementFactory psiElementFactory) {
    try {
        checkFilesAccess(psiMethod);
        PsiDocComment psiDocComment = psiMethod.getDocComment();
        //return if the method has comment
        if (psiDocComment != null) {
            return;
        }
        String interfaceName = CodeMakerUtil.findClassNameOfSuperMethod(psiMethod);
        if (interfaceName == null) {
            return;
        }
        String methodName = psiMethod.getName();
        Map<String, Object> map = Maps.newHashMap();
        map.put("interface", interfaceName);
        map.put("method", methodName);
        map.put("paramsType", generateMethodParamsType(psiMethod));
        String seeDoc = VelocityUtil.evaluate(seeDocTemplate, map);
        PsiDocComment seeDocComment = psiElementFactory.createDocCommentFromText(seeDoc);
        WriteCommandAction writeCommandAction = new DocWriteAction(psiMethod.getProject(), seeDocComment, psiMethod,
                psiMethod.getContainingFile());
        RunResult result = writeCommandAction.execute();
        if (result.hasException()) {
            LOGGER.error(result.getThrowable());
            Messages.showErrorDialog("CodeMaker plugin is not available, cause: " + result.getThrowable().getMessage(),
                    "CodeMaker plugin");
        }
    } catch (Exception e) {
        LOGGER.error("Create @see Doc failed", e);
    }
}
 
Example #5
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
private void setStringComment(final PsiMethod method, final String strComment) {
    PsiComment comment = psiElementFactory.createCommentFromText(strComment, null);
    PsiDocComment doc = method.getDocComment();
    if (doc != null) {
        doc.replace(comment);
    } else {
        method.addBefore(comment, method.getFirstChild());
    }
}
 
Example #6
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
private void setStringComment(final PsiClass clazz, final String strComment) {
    PsiComment comment = psiElementFactory.createCommentFromText(strComment, null);
    PsiDocComment doc = clazz.getDocComment();
    if (doc != null) {
        doc.replace(comment);
    } else {
        clazz.addBefore(comment, clazz.getFirstChild());
    }
}
 
Example #7
Source File: HaxeMethodPsiMixinImpl.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public PsiDocComment getDocComment() {
  // TODO: Fix 'public PsiDocComment getDocComment()'
  //PsiComment psiComment = HaxeResolveUtil.findDocumentation(this);
  //return ((psiComment != null)? new HaxePsiDocComment(this, psiComment) : null);
  return null;
}
 
Example #8
Source File: HaxePsiFieldImpl.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public PsiDocComment getDocComment() {
  // TODO:  Implement 'public PsiDocComment getDocComment()'
  //PsiComment psiComment = HaxeResolveUtil.findDocumentation(this);
  //return ((psiComment != null)? new HaxePsiDocComment(getDelegate(), psiComment) : null);
  return null;
}
 
Example #9
Source File: AbstractHaxePsiClass.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public PsiDocComment getDocComment() {
  // TODO: Fix 'public PsiDocComment getDocComment()'
  //PsiComment psiComment = HaxeResolveUtil.findDocumentation(this);
  //return ((psiComment != null)? new HaxePsiDocComment(this, psiComment) : null);
  return null;
}
 
Example #10
Source File: FlatJUnitGenerator.java    From java2typescript with Apache License 2.0 5 votes vote down vote up
private String generateTestSuite(StringBuilder sb, StringBuilder sbDev, PsiClass clazz) {
    boolean classInstanciated = false;
    for (PsiMethod method : clazz.getAllMethods()) {
        boolean ignore = false;
        PsiDocComment comment = method.getDocComment();
        if (comment != null) {
            PsiDocTag[] tags = comment.getTags();
            if (tags != null) {
                for (PsiDocTag tag : tags) {
                    if (tag.getName().equals(DocTagTranslator.IGNORE) && tag.getValueElement() != null && tag.getValueElement().getText().equals(DocTagTranslator.TS)) {
                        ignore = true;
                    }
                }
            }
        }
        if (!ignore) {
            PsiAnnotation testAnnot = method.getModifierList().findAnnotation("Test");
            if (testAnnot != null) {
                if (!classInstanciated) {
                    sb.append(instanciateClass(clazz));
                    sbDev.append(instanciateClassDev(clazz));
                    classInstanciated = true;
                }
                generateTestCall(sb, clazz, method);
                generateTestCallDev(sbDev, clazz, method);
            }
        }
    }
    if (classInstanciated) {
        sb.append("});\n\n");
        sbDev.append("} catch(err) {\n" +
                "\tconsole.error(err.stack);\n" +
                "}\n\n");
    }

    return sb.toString();
}
 
Example #11
Source File: CodeMakerUtil.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
private static int findJavaDocTextOffset(PsiElement theElement) {
    PsiElement javadocElement = theElement.getFirstChild();
    if (!(javadocElement instanceof PsiDocComment)) {
        throw new IllegalStateException("Cannot find element of type PsiDocComment");
    }
    return javadocElement.getTextOffset();
}
 
Example #12
Source File: DocCommentProcessor.java    From markdown-doclet with GNU General Public License v3.0 5 votes vote down vote up
private int getStartOffsetInComment(PsiElement element) {
    int offset = 0;
    while ( element != null && !(element instanceof PsiDocComment) ) {
        offset += element.getStartOffsetInParent();
        element = element.getParent();
    }
    return offset;
}
 
Example #13
Source File: JavadocContentAccess.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private static Reader getHTMLContentReader(PsiMember member, boolean allowInherited, boolean useAttachedJavadoc) {
    PsiDocComment doc = ((PsiDocCommentOwner) member).getDocComment();
    PsiElement sourceMember = member.getNavigationElement();
    if (sourceMember instanceof PsiDocCommentOwner) {
        doc = ((PsiDocCommentOwner) sourceMember).getDocComment();
    }
    return doc == null ? null : new JavaDocCommentReader(doc.getText());
}
 
Example #14
Source File: GenerateAllJavadocAction.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
/**
 * 保存Javadoc
 *
 * @param project    工程
 * @param psiElement 当前元素
 */
private void saveJavadoc(Project project, PsiElement psiElement) {
    if (psiElement == null) {
        return;
    }
    String comment = docGeneratorService.generate(psiElement);
    if (StringUtils.isBlank(comment)) {
        return;
    }
    PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(project);
    PsiDocComment psiDocComment = factory.createDocCommentFromText(comment);

    writerService.write(project, psiElement, psiDocComment);
}
 
Example #15
Source File: GenerateJavadocAction.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
    Project project = anActionEvent.getData(LangDataKeys.PROJECT);
    if (project == null) {
        return;
    }

    // 选中翻译功能
    Editor editor = anActionEvent.getData(LangDataKeys.EDITOR);
    if (editor != null) {
        String selectedText = editor.getSelectionModel().getSelectedText(true);
        if (StringUtils.isNotBlank(selectedText)) {
            // 中译英
            if (LanguageUtil.isAllChinese(selectedText)) {
                writerService.write(project, editor, translatorService.translateCh2En(selectedText));
            }
            // 自动翻译
            else {
                String result = translatorService.autoTranslate(selectedText);
                new TranslateResultView(result).show();
            }
            return;
        }
    }

    PsiElement psiElement = anActionEvent.getData(LangDataKeys.PSI_ELEMENT);
    if (psiElement == null || psiElement.getNode() == null) {
        return;
    }

    String comment = docGeneratorService.generate(psiElement);
    if (StringUtils.isEmpty(comment)) {
        return;
    }

    PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(project);
    PsiDocComment psiDocComment = factory.createDocCommentFromText(comment);

    writerService.write(project, psiElement, psiDocComment);
}
 
Example #16
Source File: WriterService.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
public void write(Project project, PsiElement psiElement, PsiDocComment comment) {
    try {
        WriteCommandAction.writeCommandAction(project).run(
            (ThrowableRunnable<Throwable>)() -> {
                if (psiElement.getContainingFile() == null) {
                    return;
                }

                // 写入文档注释
                if (psiElement instanceof PsiJavaDocumentedElement) {
                    PsiDocComment psiDocComment = ((PsiJavaDocumentedElement)psiElement).getDocComment();
                    if (psiDocComment == null) {
                        psiElement.getNode().addChild(comment.getNode(), psiElement.getFirstChild().getNode());
                    } else {
                        psiDocComment.replace(comment);
                    }
                }

                // 格式化文档注释
                CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(psiElement.getProject());
                PsiElement javadocElement = psiElement.getFirstChild();
                int startOffset = javadocElement.getTextOffset();
                int endOffset = javadocElement.getTextOffset() + javadocElement.getText().length();
                codeStyleManager.reformatText(psiElement.getContainingFile(), startOffset, endOffset + 1);
            });
    } catch (Throwable throwable) {
        LOGGER.error("写入错误", throwable);
    }
}
 
Example #17
Source File: MarkdownJavaDocInfoGenerator.java    From markdown-doclet with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void generateCommonSection(StringBuilder buffer, PsiDocComment docComment) {
    docComment = processor.processDocComment(docComment);
    super.generateCommonSection(buffer, docComment);
}
 
Example #18
Source File: DocCommentProcessor.java    From markdown-doclet with GNU General Public License v3.0 4 votes vote down vote up
LinkExpander(PsiDocCommentOwner docContext, PsiDocComment originalDocComment, String docText) {
    this.docContext = docContext;
    this.originalDocComment = originalDocComment;
    this.docText = docText;
}
 
Example #19
Source File: DocCommentProcessor.java    From markdown-doclet with GNU General Public License v3.0 4 votes vote down vote up
private PsiDocComment docCommentFromText(PsiElement context, CharSequence text) {
    return psiElementFactory.createDocCommentFromText(text.toString(), context);
}
 
Example #20
Source File: HaxeTypeListPartPsiMixinImpl.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Override
public PsiDocComment getDocComment() {
  return getDelegate().getDocComment();
}
 
Example #21
Source File: FlatJUnitGenerator.java    From java2typescript with Apache License 2.0 4 votes vote down vote up
public void generate(File sourceDir, File targetDir) {
    try {

        StringBuilder sb = new StringBuilder();
        StringBuilder sbDev = new StringBuilder();

        if (headers != null) {
            for (String s : headers) {
                sb.append(s + "\n");
                sbDev.append(s + "\n");
            }
        }

        JavaAnalyzer javaAnalyzer = new JavaAnalyzer();
        PsiDirectory parsedDir = javaAnalyzer.analyze(sourceDir);
        parsedDir.acceptChildren(new PsiElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                boolean ignore = false;
                if (element instanceof PsiClass) {
                    PsiClass clazz = (PsiClass) element;

                    PsiDocComment comment = clazz.getDocComment();
                    if (comment != null) {
                        PsiDocTag[] tags = comment.getTags();
                        if (tags != null) {
                            for (PsiDocTag tag : tags) {
                                if (tag.getName().equals(DocTagTranslator.IGNORE) && tag.getValueElement() != null && tag.getValueElement().getText().equals(DocTagTranslator.TS)) {
                                    ignore = true;
                                }
                            }
                        }
                    }


                    if (!ignore && !clazz.isInterface() && !clazz.hasModifierProperty(PsiModifier.ABSTRACT)) {
                        generateTestSuite(sb, sbDev, clazz);
                    }
                } else {
                    element.acceptChildren(this);
                }
            }
        });


        targetDir.mkdirs();
        File generatedTS = new File(targetDir, "testsRunner.js");
        FileUtil.writeToFile(generatedTS, sb.toString().getBytes());

        File generatedDevTS = new File(targetDir, "testsRunnerDev.js");
        FileUtil.writeToFile(generatedDevTS, sbDev.toString().getBytes());

    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example #22
Source File: ClassTranslator.java    From java2typescript with Apache License 2.0 4 votes vote down vote up
private static void printClassMembers(PsiClass clazz, TranslationContext ctx, DocMeta classMetas) {
        ctx.increaseIdent();
        PsiField[] fields = clazz.getFields();
        for (PsiField field : fields) {
            FieldTranslator.translate(field, ctx);
        }
        PsiClassInitializer[] initializers = clazz.getInitializers();
        initLoop : for (PsiClassInitializer initializer : initializers) {
            PsiElement p = initializer.getModifierList();
            while(p != null) {
                if(p instanceof PsiDocComment) {
                    DocMeta metas = DocHelper.process((PsiDocComment) p);
                    if (metas.ignored) {
                        continue initLoop;
                    }
                }
                p = p.getPrevSibling();
            }

            if (initializer.hasModifierProperty("static")) {
                ctx.print("//TODO Resolve static initializer\n");
                ctx.print("static {");
            } else {
                ctx.print("//TODO Resolve instance initializer\n");
                ctx.print("{");
            }
            if (initializer.getBody().getStatements().length > 0) {
                ctx.append("\n");
                ctx.increaseIdent();
                CodeBlockTranslator.translate(initializer.getBody(), ctx);
                ctx.decreaseIdent();
                ctx.print("}\n");
            } else {
                ctx.append("}\n");
            }
        }
        PsiMethod[] methods = clazz.getMethods();
        if (TypeHelper.isCallbackClass(clazz)) {
            MethodTranslator.translate(methods[0], ctx, true);
        } else {
            // TODO handle method with same name but different signature
//            Map<String, List<PsiMethod>> methodsByName = new HashMap<>();
//            for (PsiMethod method : methods) {
//                List<PsiMethod> mList = methodsByName.get(method.getName());
//                if (mList == null) {
//                    mList = new ArrayList<>();
//                    methodsByName.put(method.getName(), mList);
//                }
//                mList.add(method);
//            }
            for (PsiMethod method: methods) {
                MethodTranslator.translate(method, ctx, false);
            }
        }

        /*if (clazz.isEnum()) {
            ctx.print("public equals(other: any): boolean {\n");
            ctx.increaseIdent();
            ctx.print("return this == other;\n");
            ctx.decreaseIdent();
            ctx.print("}\n");
            ctx.print("public static _" + clazz.getName() + "VALUES : " + clazz.getName() + "[] = [\n");
            ctx.increaseIdent();
            boolean isFirst = true;
            for (int i = 0; i < clazz.getFields().length; i++) {
                if (clazz.getFields()[i].hasModifierProperty("static")) {
                    if (!isFirst) {
                        ctx.print(",");
                    } else {
                        ctx.print("");
                    }
                    ctx.append(clazz.getName());
                    ctx.append(".");
                    ctx.append(clazz.getFields()[i].getName());
                    ctx.append("\n");
                    isFirst = false;
                }
            }
            ctx.decreaseIdent();
            ctx.print("];\n");

            ctx.print("public static values():");
            ctx.append(clazz.getName());
            ctx.append("[]{\n");
            ctx.increaseIdent();
            ctx.print("return ");
            ctx.append(clazz.getName());
            ctx.append("._");
            ctx.append(clazz.getName());
            ctx.append("VALUES;\n");
            ctx.decreaseIdent();
            ctx.print("}\n");

        }*/
        DocTagTranslator.translate(classMetas, ctx);
        ctx.decreaseIdent();
    }
 
Example #23
Source File: GenerateCodeFromApiTableAction.java    From CodeMaker with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) {
        return;
    }
    DumbService dumbService = DumbService.getInstance(project);
    if (dumbService.isDumb()) {
        dumbService
            .showDumbModeNotification("CodeMaker plugin is not available during indexing");
        return;
    }
    PsiFile javaFile = e.getData(CommonDataKeys.PSI_FILE);
    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (javaFile == null || editor == null) {
        return;
    }
    Transferable transferable = CopyPasteManager.getInstance().getContents();
    if (transferable == null) {
        return;
    }
    try {
        String table = (String) transferable.getTransferData(DataFlavor.stringFlavor);
        List<String> tableList = Splitter.onPattern("\n|\t|\r\n").splitToList(table);
        PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(project);
        int mod = tableList.size() % 3;
        int end = tableList.size() - mod;

        for (int i = 0; i < end; i++) {
            String fieldName = tableList.get(i);
            String fieldType = tableList.get(++i);
            String fieldComment = tableList.get(++i);
            PsiField psiField = psiElementFactory.createField(fieldName,
                PsiType.getTypeByName(fieldType, project, GlobalSearchScope.allScope(project)));
            Map<String, Object> map = Maps.newHashMap();
            map.put("comment", fieldComment);
            String vm = "/**\n" + " * ${comment}\n" + " */";
            if (settings.getCodeTemplate("FieldComment.vm") != null) {
                vm = settings.getCodeTemplate("FieldComment.vm").getCodeTemplate();
            }
            String fieldDocComment = VelocityUtil.evaluate(vm, map);
            PsiDocComment docComment = psiElementFactory
                .createDocCommentFromText(fieldDocComment);
            psiField.addBefore(docComment, psiField.getFirstChild());
            WriteCommandAction writeCommandAction = new FieldWriteAction(project,
                CodeMakerUtil.getClasses(javaFile).get(0), psiField, javaFile);
            RunResult result = writeCommandAction.execute();
            if (result.hasException()) {
                LOGGER.error(result.getThrowable());
                Messages.showErrorDialog("CodeMaker plugin is not available, cause: "
                                         + result.getThrowable().getMessage(),
                    "CodeMaker plugin");
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ex);
    }
}
 
Example #24
Source File: DocWriteAction.java    From CodeMaker with Apache License 2.0 4 votes vote down vote up
public DocWriteAction(@Nullable Project project, PsiDocComment psiDocComment,
                      PsiElement psiElement, PsiFile... files) {
    super(project, files);
    this.psiDocComment = psiDocComment;
    this.psiElement = psiElement;
}
 
Example #25
Source File: SystemObject.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
private void inheritanceHierarchyMatchingWithStaticTypes(TypeCheckElimination typeCheckElimination,
                                                         CompleteInheritanceDetection inheritanceDetection) {
    List<PsiField> staticFields = typeCheckElimination.getStaticFields();
    String abstractClassType = typeCheckElimination.getAbstractClassType();
    InheritanceTree tree = null;
    if (abstractClassType != null) {
        tree = inheritanceDetection.getTree(abstractClassType);
    }
    if (tree != null) {
        DefaultMutableTreeNode rootNode = tree.getRootNode();
        DefaultMutableTreeNode leaf = rootNode.getFirstLeaf();
        List<String> inheritanceHierarchySubclassNames = new ArrayList<>();
        while (leaf != null) {
            inheritanceHierarchySubclassNames.add((String) leaf.getUserObject());
            leaf = leaf.getNextLeaf();
        }
        int matchCounter = 0;
        for (PsiField staticField : staticFields) {
            for (String subclassName : inheritanceHierarchySubclassNames) {
                ClassObject classObject = getClassObject(subclassName);
                PsiElement abstractTypeDeclaration = classObject.getAbstractTypeDeclaration();
                if (abstractTypeDeclaration instanceof PsiClass) {
                    PsiClass typeDeclaration = (PsiClass) abstractTypeDeclaration;
                    PsiDocComment javadoc = typeDeclaration.getDocComment();
                    if (javadoc != null) {
                        PsiDocTag[] tagElements = javadoc.getTags();
                        for (PsiDocTag tagElement : tagElements) {
                            tagElement.getName();
                            if ("see".equals(tagElement.getName())) {
                                PsiElement[] fragments = tagElement.getDataElements();
                                for (PsiElement fragment : fragments) {
                                    if (!(fragment instanceof PsiDocMethodOrFieldRef)) {
                                        continue;
                                    }
                                    PsiReference memberRef = fragment.getReference();
                                    if (memberRef == null) {
                                        continue;
                                    }
                                    PsiElement resolvedRef = memberRef.resolve();
                                    if (staticField.equals(resolvedRef)) {
                                        typeCheckElimination.putStaticFieldSubclassTypeMapping(staticField, subclassName);
                                        matchCounter++;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (matchCounter == staticFields.size()) {
            typeCheckElimination.setInheritanceTreeMatchingWithStaticTypes(tree);
        }
    }
}