Search in sources :

Example 36 with Document

use of com.intellij.openapi.editor.Document in project intellij-community by JetBrains.

the class DomFileDescriptionTest method testCheckDtdPublicId.

public void testCheckDtdPublicId() throws Throwable {
    getDomManager().registerFileDescription(new DomFileDescription<NamespacedElement>(NamespacedElement.class, "xxx", "bar") {

        @Override
        protected void initializeFileDescription() {
            registerNamespacePolicy("foo", "bar");
        }
    }, myDisposable);
    final PsiFile file = createFile("xxx.xml", "<xxx/>");
    assertFalse(getDomManager().isDomFile(file));
    new WriteCommandAction(getProject()) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            final Document document = getDocument(file);
            document.insertString(0, "<!DOCTYPE xxx PUBLIC \"bar\" \"http://java.sun.com/dtd/ejb-jar_2_0.dtd\">\n");
            commitDocument(document);
        }
    }.execute();
    assertTrue(getDomManager().isDomFile(file));
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) PsiFile(com.intellij.psi.PsiFile) Document(com.intellij.openapi.editor.Document) Result(com.intellij.openapi.application.Result)

Example 37 with Document

use of com.intellij.openapi.editor.Document in project intellij-community by JetBrains.

the class ExternalDocumentValidator method runJaxpValidation.

private void runJaxpValidation(final XmlElement element, Validator.ValidationHost host) {
    final PsiFile file = element.getContainingFile();
    if (myFile == file && file != null && myModificationStamp == file.getModificationStamp() && !ValidateXmlActionHandler.isValidationDependentFilesOutOfDate((XmlFile) file) && // we have validated before
    SoftReference.dereference(myInfos) != null) {
        addAllInfos(host, myInfos.get());
        return;
    }
    if (myHandler == null)
        myHandler = new ValidateXmlActionHandler(false);
    final Project project = element.getProject();
    final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document == null)
        return;
    final List<ValidationInfo> results = new LinkedList<>();
    myHost = new Validator.ValidationHost() {

        @Override
        public void addMessage(PsiElement context, String message, int type) {
            addMessage(context, message, type == ERROR ? ErrorType.ERROR : type == WARNING ? ErrorType.WARNING : ErrorType.INFO);
        }

        @Override
        public void addMessage(final PsiElement context, final String message, @NotNull final ErrorType type) {
            final ValidationInfo o = new ValidationInfo(context, message, type);
            results.add(o);
        }
    };
    myHandler.setErrorReporter(new ErrorReporter(myHandler) {

        @Override
        public boolean isStopOnUndeclaredResource() {
            return true;
        }

        @Override
        public void processError(final SAXParseException e, final ValidateXmlActionHandler.ProblemType warning) {
            try {
                ApplicationManager.getApplication().runReadAction(() -> {
                    if (e.getPublicId() != null) {
                        return;
                    }
                    final VirtualFile errorFile = myHandler.getProblemFile(e);
                    if (!Comparing.equal(errorFile, file.getVirtualFile()) && errorFile != null) {
                        // error in attached schema
                        return;
                    }
                    if (document.getLineCount() < e.getLineNumber() || e.getLineNumber() <= 0) {
                        return;
                    }
                    Validator.ValidationHost.ErrorType problemType = getProblemType(warning);
                    int offset = Math.max(0, document.getLineStartOffset(e.getLineNumber() - 1) + e.getColumnNumber() - 2);
                    if (offset >= document.getTextLength())
                        return;
                    PsiElement currentElement = PsiDocumentManager.getInstance(project).getPsiFile(document).findElementAt(offset);
                    PsiElement originalElement = currentElement;
                    final String elementText = currentElement.getText();
                    if (elementText.equals("</")) {
                        currentElement = currentElement.getNextSibling();
                    } else if (elementText.equals(">") || elementText.equals("=")) {
                        currentElement = currentElement.getPrevSibling();
                    }
                    // Cannot find the declaration of element
                    String localizedMessage = e.getLocalizedMessage();
                    // Ideally would be to switch one messageIds
                    int endIndex = localizedMessage.indexOf(':');
                    if (endIndex < localizedMessage.length() - 1 && localizedMessage.charAt(endIndex + 1) == '/') {
                        // ignore : in http://
                        endIndex = -1;
                    }
                    String messageId = endIndex != -1 ? localizedMessage.substring(0, endIndex) : "";
                    localizedMessage = localizedMessage.substring(endIndex + 1).trim();
                    if (localizedMessage.startsWith(CANNOT_FIND_DECLARATION_ERROR_PREFIX) || localizedMessage.startsWith(ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(ROOT_ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(CONTENT_OF_ELEMENT_TYPE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    //return;
                    } else if (localizedMessage.startsWith(VALUE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    } else {
                        if (messageId.startsWith(ATTRIBUTE_MESSAGE_PREFIX)) {
                            @NonNls String prefix = "of attribute ";
                            final int i = localizedMessage.indexOf(prefix);
                            if (i != -1) {
                                int messagePrefixLength = prefix.length() + i;
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = ((XmlAttribute) currentElement).getValueElement();
                                }
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(ATTRIBUTE_ERROR_PREFIX)) {
                            final int messagePrefixLength = ATTRIBUTE_ERROR_PREFIX.length();
                            if (localizedMessage.charAt(messagePrefixLength) == '"' || localizedMessage.charAt(messagePrefixLength) == '\'') {
                                // extract the attribute name from message and get it from tag!
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = SourceTreeToPsiMap.treeElementToPsi(XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(SourceTreeToPsiMap.psiElementToTree(currentElement)));
                                }
                            } else {
                                currentElement = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class, false);
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(STRING_ERROR_PREFIX)) {
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, Validator.ValidationHost.ErrorType.WARNING);
                            }
                        } else {
                            currentElement = getNodeForMessage(currentElement != null ? currentElement : originalElement);
                            assertValidElement(currentElement, originalElement, localizedMessage);
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            }
                        }
                    }
                });
            } catch (Exception ex) {
                if (ex instanceof ProcessCanceledException)
                    throw (ProcessCanceledException) ex;
                if (ex instanceof XmlResourceResolver.IgnoredResourceException)
                    throw (XmlResourceResolver.IgnoredResourceException) ex;
                LOG.error(ex);
            }
        }
    });
    myHandler.doValidate((XmlFile) element.getContainingFile());
    myFile = file;
    myModificationStamp = myFile.getModificationStamp();
    myInfos = new WeakReference<>(results);
    addAllInfos(host, results);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) XmlResourceResolver(com.intellij.xml.util.XmlResourceResolver) ErrorReporter(com.intellij.xml.actions.validate.ErrorReporter) SAXParseException(org.xml.sax.SAXParseException) PsiFile(com.intellij.psi.PsiFile) ValidateXmlActionHandler(com.intellij.xml.actions.validate.ValidateXmlActionHandler) PsiElement(com.intellij.psi.PsiElement) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NonNls(org.jetbrains.annotations.NonNls) LinkedList(java.util.LinkedList) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) SAXParseException(org.xml.sax.SAXParseException) Project(com.intellij.openapi.project.Project) Validator(com.intellij.codeInsight.daemon.Validator)

Example 38 with Document

use of com.intellij.openapi.editor.Document in project intellij-community by JetBrains.

the class GroovyCompletionUtil method shortenReference.

//need to shorten references in type argument list
public static void shortenReference(final PsiFile file, final int offset) throws IncorrectOperationException {
    final Project project = file.getProject();
    final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
    final Document document = manager.getDocument(file);
    assert document != null;
    manager.commitDocument(document);
    final PsiReference ref = file.findReferenceAt(offset);
    if (ref instanceof GrCodeReferenceElement) {
        JavaCodeStyleManager.getInstance(project).shortenClassReferences((GroovyPsiElement) ref);
    }
}
Also used : Project(com.intellij.openapi.project.Project) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) Document(com.intellij.openapi.editor.Document)

Example 39 with Document

use of com.intellij.openapi.editor.Document in project intellij-community by JetBrains.

the class GrClassBodyFixer method apply.

@Override
public void apply(@NotNull Editor editor, @NotNull GroovySmartEnterProcessor processor, @NotNull PsiElement element) throws IncorrectOperationException {
    if (element instanceof GrTypeDefinition && ((GrTypeDefinition) element).getBody() == null) {
        final Document doc = editor.getDocument();
        doc.insertString(element.getTextRange().getEndOffset(), "{\n}");
    }
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) Document(com.intellij.openapi.editor.Document)

Example 40 with Document

use of com.intellij.openapi.editor.Document in project intellij-community by JetBrains.

the class GrForBodyFixer method apply.

@Override
public void apply(@NotNull Editor editor, @NotNull GroovySmartEnterProcessor processor, @NotNull PsiElement psiElement) {
    GrForStatement forStatement = PsiTreeUtil.getParentOfType(psiElement, GrForStatement.class);
    if (forStatement == null)
        return;
    final Document doc = editor.getDocument();
    PsiElement body = forStatement.getBody();
    if (body instanceof GrBlockStatement)
        return;
    if (body != null && startLine(doc, body) == startLine(doc, forStatement))
        return;
    PsiElement eltToInsertAfter = forStatement.getRParenth();
    String text = "{}";
    if (eltToInsertAfter == null) {
        eltToInsertAfter = forStatement;
        text = "){}";
    }
    doc.insertString(eltToInsertAfter.getTextRange().getEndOffset(), text);
}
Also used : GrForStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement) Document(com.intellij.openapi.editor.Document) GrBlockStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement) PsiElement(com.intellij.psi.PsiElement)

Aggregations

Document (com.intellij.openapi.editor.Document)1075 VirtualFile (com.intellij.openapi.vfs.VirtualFile)246 PsiFile (com.intellij.psi.PsiFile)191 Project (com.intellij.openapi.project.Project)164 NotNull (org.jetbrains.annotations.NotNull)138 Nullable (org.jetbrains.annotations.Nullable)129 TextRange (com.intellij.openapi.util.TextRange)122 PsiDocumentManager (com.intellij.psi.PsiDocumentManager)117 PsiElement (com.intellij.psi.PsiElement)107 Editor (com.intellij.openapi.editor.Editor)104 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)56 FileDocumentManager (com.intellij.openapi.fileEditor.FileDocumentManager)45 IncorrectOperationException (com.intellij.util.IncorrectOperationException)43 IOException (java.io.IOException)42 RangeMarker (com.intellij.openapi.editor.RangeMarker)35 MockVirtualFile (com.intellij.mock.MockVirtualFile)33 File (java.io.File)32 ArrayList (java.util.ArrayList)32 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)30 List (java.util.List)29