Java 类com.intellij.psi.impl.source.codeStyle.CodeEditUtil 实例源码

项目:intellij-ce-playground    文件:CodeBlockReformattingProcessor.java   
@Override
public void processText(Project project,
                        Template template,
                        Document document,
                        RangeMarker templateRange,
                        Editor editor) {
  if (!template.isToReformat()) return;

  PsiDocumentManager.getInstance(project).commitDocument(document);
  PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (!(file instanceof PsiJavaFile)) return;

  CharSequence text = document.getImmutableCharSequence();
  int prevChar = CharArrayUtil.shiftBackward(text, templateRange.getStartOffset() - 1, " \t");
  int nextChar = CharArrayUtil.shiftForward(text, templateRange.getEndOffset(), " \t");
  if (prevChar > 0 && text.charAt(prevChar) == '{' && nextChar < text.length() && text.charAt(nextChar) == '}') {
    PsiCodeBlock codeBlock = PsiTreeUtil.findElementOfClassAtOffset(file, prevChar, PsiCodeBlock.class, false);
    if (codeBlock != null && codeBlock.getTextRange().getStartOffset() == prevChar) {
      PsiJavaToken rBrace = codeBlock.getRBrace();
      if (rBrace != null && rBrace.getTextRange().getStartOffset() == nextChar) {
        CodeEditUtil.markToReformat(rBrace.getNode(), true);
      }
    }
  }
}
项目:intellij-ce-playground    文件:PsiFileFactoryImpl.java   
@Override
@NotNull
public PsiFile createFileFromText(@NotNull String name,
                                  @NotNull FileType fileType,
                                  @NotNull CharSequence text,
                                  long modificationStamp,
                                  final boolean eventSystemEnabled,
                                  boolean markAsCopy) {
  final LightVirtualFile virtualFile = new LightVirtualFile(name, fileType, text, modificationStamp);
  if(fileType instanceof LanguageFileType){
    final Language language =
        LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), virtualFile, myManager.getProject());
    final PsiFile file = trySetupPsiForFile(virtualFile, language, eventSystemEnabled, markAsCopy);
    if (file != null) return file;
  }
  final SingleRootFileViewProvider singleRootFileViewProvider =
    new SingleRootFileViewProvider(myManager, virtualFile, eventSystemEnabled);
  final PsiPlainTextFileImpl plainTextFile = new PsiPlainTextFileImpl(singleRootFileViewProvider);
  if(markAsCopy) CodeEditUtil.setNodeGenerated(plainTextFile.getNode(), true);
  return plainTextFile;
}
项目:intellij-ce-playground    文件:PostprocessReformattingAspect.java   
private void postponeFormatting(@NotNull FileViewProvider viewProvider, @NotNull ASTNode child) {
  if (!CodeEditUtil.isNodeGenerated(child) && child.getElementType() != TokenType.WHITE_SPACE) {
    final int oldIndent = CodeEditUtil.getOldIndentation(child);
    LOG.assertTrue(oldIndent >= 0,
                   "for not generated items old indentation must be defined: element=" + child + ", text=" + child.getText());
  }
  List<ASTNode> list = getContext().myReformatElements.get(viewProvider);
  if (list == null) {
    list = new ArrayList<ASTNode>();
    getContext().myReformatElements.put(viewProvider, list);
    if (Holder.STORE_REFORMAT_ORIGINATOR_STACKTRACE) {
      viewProvider.putUserData(REFORMAT_ORIGINATOR, new Throwable());
    }
  }
  list.add(child);
}
项目:intellij-ce-playground    文件:PostprocessReformattingAspect.java   
private static void handleReformatMarkers(@NotNull final FileViewProvider key, @NotNull final Set<PostprocessFormattingTask> rangesToProcess) {
  final Document document = key.getDocument();
  if (document == null) {
    return;
  }
  for (final FileElement fileElement : ((SingleRootFileViewProvider)key).getKnownTreeRoots()) {
    fileElement.acceptTree(new RecursiveTreeElementWalkingVisitor() {
      @Override
      protected void visitNode(TreeElement element) {
        if (CodeEditUtil.isMarkedToReformatBefore(element)) {
          CodeEditUtil.markToReformatBefore(element, false);
          rangesToProcess.add(new ReformatWithHeadingWhitespaceTask(
            document.createRangeMarker(element.getStartOffset(), element.getStartOffset()))
          );
        }
        else if (CodeEditUtil.isMarkedToReformat(element)) {
          CodeEditUtil.markToReformat(element, false);
          rangesToProcess.add(new ReformatWithHeadingWhitespaceTask(
            document.createRangeMarker(element.getStartOffset(), element.getStartOffset() + element.getTextLength()))
          );
        }
        super.visitNode(element);
      }
    });
  }
}
项目:intellij-ce-playground    文件:XmlAttributeImpl.java   
@Override
public PsiElement setName(@NotNull final String nameText) throws IncorrectOperationException {
  final ASTNode name = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(this);
  final String oldName = name.getText();
  final PomModel model = PomManager.getModel(getProject());
  final XmlAttribute attribute = XmlElementFactory.getInstance(getProject()).createXmlAttribute(nameText, "");
  final ASTNode newName = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild((ASTNode)attribute);
  final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
  model.runTransaction(new PomTransactionBase(getParent(), aspect) {
    @Override
    public PomModelEvent runInner() {
      final PomModelEvent event = new PomModelEvent(model);
      PsiFile file = getContainingFile();
      XmlChangeSet xmlAspectChangeSet = new XmlAspectChangeSetImpl(model, file instanceof XmlFile ? (XmlFile)file : null);
      xmlAspectChangeSet.add(new XmlAttributeSetImpl(getParent(), oldName, null));
      xmlAspectChangeSet.add(new XmlAttributeSetImpl(getParent(), nameText, getValue()));
      event.registerChangeSet(model.getModelAspect(XmlAspect.class), xmlAspectChangeSet);
      CodeEditUtil.replaceChild(XmlAttributeImpl.this, name, newName);
      return event;
    }
  });
  return this;
}
项目:intellij-ce-playground    文件:XmlTextTest.java   
public void testInsertAtOffset() throws Exception {
  new WriteCommandAction(getProject()) {

    @Override
    protected void run(@NotNull final Result result) throws Throwable {
      String xml = "<root>0123456789</root>";
      XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject())
        .createFileFromText("foo.xml", StdFileTypes.XML, xml, (long)1, true, false);
      //System.out.println(DebugUtil.psiToString(file, false));
      XmlTag root = file.getDocument().getRootTag();
      final XmlText text1 = root.getValue().getTextElements()[0];

      assertFalse(CodeEditUtil.isNodeGenerated(root.getNode()));
      final XmlText text = text1;

      final XmlElement element = text.insertAtOffset(XmlElementFactory.getInstance(getProject()).createTagFromText("<bar/>"), 5);
      assertNotNull(element);
      assertTrue(element instanceof XmlText);
      assertEquals("01234", element.getText());
      assertEquals("<root>01234<bar/>56789</root>", text.getContainingFile().getText());
    }
  }.execute();
}
项目:tools-idea    文件:PsiReferenceExpressionImpl.java   
@Override
public void subtreeChanged() {
  super.subtreeChanged();

  // We want to reformat method call arguments on method name change because there is a possible situation that they are aligned
  // and method change breaks the alignment.
  // Example:
  //     test(1,
  //          2);
  // Suppose we're renaming the method to test123. We get the following if parameter list is not reformatted:
  //     test123(1,
  //          2);
  PsiElement methodCallCandidate = getParent();
  if (methodCallCandidate instanceof PsiMethodCallExpression) {
    PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)methodCallCandidate;
    CodeEditUtil.markToReformat(methodCallExpression.getArgumentList().getNode(), true);
  }
}
项目:tools-idea    文件:PsiIdentifierImpl.java   
@Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
  PsiElement result = super.replace(newElement);

  // We want to reformat method parameters on method name change as well because there is a possible situation that they are aligned
  // and method name change breaks the alignment.
  // Example:
  //     public void test(int i,
  //                      int j) {}
  // Suppose we're renaming the method to test123. We get the following if parameter list is not reformatted:
  //     public void test123(int i,
  //                     int j) {}
  PsiElement methodCandidate = result.getParent();
  if (methodCandidate instanceof PsiMethod) {
    PsiMethod method = (PsiMethod)methodCandidate;
    CodeEditUtil.markToReformat(method.getParameterList().getNode(), true);
  }

  return result;
}
项目:tools-idea    文件:PsiFileFactoryImpl.java   
@Override
@NotNull
public PsiFile createFileFromText(@NotNull String name,
                                  @NotNull FileType fileType,
                                  @NotNull CharSequence text,
                                  long modificationStamp,
                                  final boolean physical,
                                  boolean markAsCopy) {
  final LightVirtualFile virtualFile = new LightVirtualFile(name, fileType, text, modificationStamp);
  if(fileType instanceof LanguageFileType){
    final Language language =
        LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), virtualFile, myManager.getProject());
    final PsiFile file = trySetupPsiForFile(virtualFile, language, physical, markAsCopy);
    if (file != null) return file;
  }
  final SingleRootFileViewProvider singleRootFileViewProvider =
    new SingleRootFileViewProvider(myManager, virtualFile, physical);
  final PsiPlainTextFileImpl plainTextFile = new PsiPlainTextFileImpl(singleRootFileViewProvider);
  if(markAsCopy) CodeEditUtil.setNodeGenerated(plainTextFile.getNode(), true);
  return plainTextFile;
}
项目:tools-idea    文件:PostprocessReformattingAspect.java   
private static void handleReformatMarkers(final FileViewProvider key, final TreeSet<PostprocessFormattingTask> rangesToProcess) {
  final Document document = key.getDocument();
  if (document == null) {
    return;
  }
  for (final FileElement fileElement : ((SingleRootFileViewProvider)key).getKnownTreeRoots()) {
    fileElement.acceptTree(new RecursiveTreeElementWalkingVisitor() {
      @Override
      protected void visitNode(TreeElement element) {
        if (CodeEditUtil.isMarkedToReformatBefore(element)) {
          CodeEditUtil.markToReformatBefore(element, false);
          rangesToProcess.add(new ReformatWithHeadingWhitespaceTask(
            document.createRangeMarker(element.getStartOffset(), element.getStartOffset()))
          );
        }
        else if (CodeEditUtil.isMarkedToReformat(element)) {
          CodeEditUtil.markToReformat(element, false);
          rangesToProcess.add(new ReformatWithHeadingWhitespaceTask(
            document.createRangeMarker(element.getStartOffset(), element.getStartOffset() + element.getTextLength()))
          );
        }
        super.visitNode(element);
      }
    });
  }
}
项目:tools-idea    文件:XmlAttributeImpl.java   
public PsiElement setName(@NotNull final String nameText) throws IncorrectOperationException {
  final ASTNode name = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(this);
  final String oldName = name.getText();
  final PomModel model = PomManager.getModel(getProject());
  final XmlAttribute attribute = XmlElementFactory.getInstance(getProject()).createXmlAttribute(nameText, "");
  final ASTNode newName = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild((ASTNode)attribute);
  final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
  model.runTransaction(new PomTransactionBase(getParent(), aspect) {
    public PomModelEvent runInner() {
      final PomModelEvent event = new PomModelEvent(model);
      final XmlAspectChangeSetImpl xmlAspectChangeSet = new XmlAspectChangeSetImpl(model, (XmlFile)getContainingFile());
      xmlAspectChangeSet.add(new XmlAttributeSetImpl(getParent(), oldName, null));
      xmlAspectChangeSet.add(new XmlAttributeSetImpl(getParent(), nameText, getValue()));
      event.registerChangeSet(model.getModelAspect(XmlAspect.class), xmlAspectChangeSet);
      CodeEditUtil.replaceChild(XmlAttributeImpl.this, name, newName);
      return event;
    }
  });
  return this;
}
项目:tools-idea    文件:XmlTextTest.java   
public void testInsertAtOffset() throws Exception {
  new WriteCommandAction(getProject()) {

    @Override
    protected void run(final Result result) throws Throwable {
      String xml = "<root>0123456789</root>";
      XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject())
        .createFileFromText("foo.xml", StdFileTypes.XML, xml, (long)1, true, false);
      //System.out.println(DebugUtil.psiToString(file, false));
      XmlTag root = file.getDocument().getRootTag();
      final XmlText text1 = root.getValue().getTextElements()[0];

      assertFalse(CodeEditUtil.isNodeGenerated(root.getNode()));
      final XmlText text = text1;

      final XmlElement element = text.insertAtOffset(XmlElementFactory.getInstance(getProject()).createTagFromText("<bar/>"), 5);
      assertNotNull(element);
      assertTrue(element instanceof XmlText);
      assertEquals("01234", element.getText());
      assertEquals("<root>01234<bar/>56789</root>", text.getContainingFile().getText());
    }
  }.execute();
}
项目:consulo    文件:PsiFileFactoryImpl.java   
@Override
@Nonnull
public PsiFile createFileFromText(@Nonnull String name,
                                  @Nonnull FileType fileType,
                                  @Nonnull CharSequence text,
                                  long modificationStamp,
                                  final boolean physical,
                                  boolean markAsCopy) {
  final LightVirtualFile virtualFile = new LightVirtualFile(name, fileType, text, modificationStamp);
  if (fileType instanceof LanguageFileType) {
    final Language language =
      LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), virtualFile, myManager.getProject());
    final PsiFile file = trySetupPsiForFile(virtualFile, language, LanguageVersionUtil.findDefaultVersion(language), physical, markAsCopy);
    if (file != null) return file;
  }
  final SingleRootFileViewProvider singleRootFileViewProvider = new SingleRootFileViewProvider(myManager, virtualFile, physical);
  final PsiPlainTextFileImpl plainTextFile = new PsiPlainTextFileImpl(singleRootFileViewProvider);
  if (markAsCopy) CodeEditUtil.setNodeGenerated(plainTextFile.getNode(), true);
  return plainTextFile;
}
项目:consulo    文件:PostprocessReformattingAspect.java   
private static void handleReformatMarkers(@Nonnull final FileViewProvider key, @Nonnull final Set<PostprocessFormattingTask> rangesToProcess) {
  final Document document = key.getDocument();
  if (document == null) {
    return;
  }
  for (final FileElement fileElement : ((AbstractFileViewProvider)key).getKnownTreeRoots()) {
    fileElement.acceptTree(new RecursiveTreeElementWalkingVisitor() {
      @Override
      protected void visitNode(TreeElement element) {
        if (CodeEditUtil.isMarkedToReformatBefore(element)) {
          CodeEditUtil.markToReformatBefore(element, false);
          rangesToProcess.add(new ReformatWithHeadingWhitespaceTask(document.createRangeMarker(element.getStartOffset(), element.getStartOffset())));
        }
        else if (CodeEditUtil.isMarkedToReformat(element)) {
          CodeEditUtil.markToReformat(element, false);
          rangesToProcess.add(new ReformatWithHeadingWhitespaceTask(document.createRangeMarker(element.getStartOffset(), element.getStartOffset() + element.getTextLength())));
        }
        super.visitNode(element);
      }
    });
  }
}
项目:consulo-xml    文件:XmlAttributeImpl.java   
@Override
public PsiElement setName(@NotNull final String nameText) throws IncorrectOperationException
{
    final ASTNode name = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(this);
    final String oldName = name.getText();
    final PomModel model = PomManager.getModel(getProject());
    final XmlAttribute attribute = XmlElementFactory.getInstance(getProject()).createXmlAttribute(nameText, "");
    final ASTNode newName = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild((ASTNode) attribute);
    final XmlAspect aspect = model.getModelAspect(XmlAspect.class);
    model.runTransaction(new PomTransactionBase(getParent(), aspect)
    {
        @Override
        public PomModelEvent runInner()
        {
            final PomModelEvent event = new PomModelEvent(model);
            PsiFile file = getContainingFile();
            XmlChangeSet xmlAspectChangeSet = new XmlAspectChangeSetImpl(model, file instanceof XmlFile ? (XmlFile) file : null);
            xmlAspectChangeSet.add(new XmlAttributeSetImpl(getParent(), oldName, null));
            xmlAspectChangeSet.add(new XmlAttributeSetImpl(getParent(), nameText, getValue()));
            event.registerChangeSet(model.getModelAspect(XmlAspect.class), xmlAspectChangeSet);
            CodeEditUtil.replaceChild(XmlAttributeImpl.this, name, newName);
            return event;
        }
    });
    return this;
}
项目:consulo-java    文件:PsiIdentifierImpl.java   
@Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
  PsiElement result = super.replace(newElement);

  // We want to reformat method parameters on method name change as well because there is a possible situation that they are aligned
  // and method name change breaks the alignment.
  // Example:
  //     public void test(int i,
  //                      int j) {}
  // Suppose we're renaming the method to test123. We get the following if parameter list is not reformatted:
  //     public void test123(int i,
  //                     int j) {}
  PsiElement methodCandidate = result.getParent();
  if (methodCandidate instanceof PsiMethod) {
    PsiMethod method = (PsiMethod)methodCandidate;
    CodeEditUtil.markToReformat(method.getParameterList().getNode(), true);
  }

  return result;
}
项目:consulo-java    文件:JavaStubPsiElement.java   
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException
{
    CheckUtil.checkWritable(this);
    if(first == null)
    {
        LOG.assertTrue(last == null);
        return;
    }
    ASTNode firstElement = SourceTreeToPsiMap.psiElementToTree(first);
    ASTNode lastElement = SourceTreeToPsiMap.psiElementToTree(last);
    CompositeElement treeElement = calcTreeElement();
    LOG.assertTrue(firstElement.getTreeParent() == treeElement);
    LOG.assertTrue(lastElement.getTreeParent() == treeElement);
    CodeEditUtil.removeChildren(treeElement, firstElement, lastElement);
}
项目:intellij-ce-playground    文件:PsiElementFactoryImpl.java   
@NotNull
@Override
public PsiTypeElement createTypeElement(@NotNull final PsiType psiType) {
  final LightTypeElement element = new LightTypeElement(myManager, psiType);
  CodeEditUtil.setNodeGenerated(element.getNode(), true);
  return element;
}
项目:intellij-ce-playground    文件:JavaStubPsiElement.java   
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
  CheckUtil.checkWritable(this);
  if (first == null) {
    LOG.assertTrue(last == null);
    return;
  }
  ASTNode firstElement = SourceTreeToPsiMap.psiElementToTree(first);
  ASTNode lastElement = SourceTreeToPsiMap.psiElementToTree(last);
  CompositeElement treeElement = calcTreeElement();
  LOG.assertTrue(firstElement.getTreeParent() == treeElement);
  LOG.assertTrue(lastElement.getTreeParent() == treeElement);
  CodeEditUtil.removeChildren(treeElement, firstElement, lastElement);
}
项目:intellij-ce-playground    文件:PsiFieldImpl.java   
@Override
public void normalizeDeclaration() throws IncorrectOperationException{
  CheckUtil.checkWritable(this);

  final PsiTypeElement type = getTypeElement();
  PsiElement modifierList = getModifierList();
  ASTNode field = SourceTreeToPsiMap.psiElementToTree(type.getParent());
  while(true){
    ASTNode comma = PsiImplUtil.skipWhitespaceAndComments(field.getTreeNext());
    if (comma == null || comma.getElementType() != JavaTokenType.COMMA) break;
    ASTNode nextField = PsiImplUtil.skipWhitespaceAndComments(comma.getTreeNext());
    if (nextField == null || nextField.getElementType() != JavaElementType.FIELD) break;

    TreeElement semicolon = Factory.createSingleLeafElement(JavaTokenType.SEMICOLON, ";", 0, 1, null, getManager());
    CodeEditUtil.addChild(field, semicolon, null);

    CodeEditUtil.removeChild(comma.getTreeParent(), comma);

    PsiElement typeClone = type.copy();
    CodeEditUtil.addChild(nextField, SourceTreeToPsiMap.psiElementToTree(typeClone), nextField.getFirstChildNode());

    PsiElement modifierListClone = modifierList.copy();
    CodeEditUtil.addChild(nextField, SourceTreeToPsiMap.psiElementToTree(modifierListClone), nextField.getFirstChildNode());

    field = nextField;
  }

  JavaSharedImplUtil.normalizeBrackets(this);
}
项目:intellij-ce-playground    文件:BaseExpressionToFieldHandler.java   
public static PsiField appendField(final PsiClass destClass,
                                   final PsiField psiField,
                                   final PsiElement anchorMember,
                                   final PsiField forwardReference) {
  final PsiClass parentClass = PsiTreeUtil.getParentOfType(anchorMember, PsiClass.class);

  if (anchorMember instanceof PsiField &&
      anchorMember.getParent() == parentClass &&
      destClass == parentClass &&
      ((PsiField)anchorMember).hasModifierProperty(PsiModifier.STATIC) == psiField.hasModifierProperty(PsiModifier.STATIC)) {
    return (PsiField)destClass.addBefore(psiField, anchorMember);
  }
  else if (anchorMember instanceof PsiClassInitializer &&
           anchorMember.getParent() == parentClass &&
           destClass == parentClass) {
    PsiField field = (PsiField)destClass.addBefore(psiField, anchorMember);
    destClass.addBefore(CodeEditUtil.createLineFeed(field.getManager()), anchorMember);
    return field;
  }
  else {
    if (forwardReference != null ) {
      return forwardReference.getParent() == destClass ?
             (PsiField)destClass.addAfter(psiField, forwardReference) :
             (PsiField)forwardReference.getParent().addAfter(psiField, forwardReference);
    } else {
      return (PsiField)destClass.add(psiField);
    }
  }
}
项目:intellij-ce-playground    文件:ASTDelegatePsiElement.java   
@Override
public void deleteChildRange(final PsiElement first, final PsiElement last) throws IncorrectOperationException {
  CheckUtil.checkWritable(this);
  ASTNode firstElement = SourceTreeToPsiMap.psiElementToTree(first);
  ASTNode lastElement = SourceTreeToPsiMap.psiElementToTree(last);

  LOG.assertTrue(firstElement.getTreeParent() == getNode());
  LOG.assertTrue(lastElement.getTreeParent() == getNode());
  CodeEditUtil.removeChildren(getNode(), firstElement, lastElement);
}
项目:intellij-ce-playground    文件:ASTDelegatePsiElement.java   
@Override
public PsiElement replace(@NotNull final PsiElement newElement) throws IncorrectOperationException {
  CheckUtil.checkWritable(this);
  TreeElement elementCopy = ChangeUtil.copyToElement(newElement);
  if (getParent() instanceof ASTDelegatePsiElement) {
    final ASTDelegatePsiElement parentElement = (ASTDelegatePsiElement)getParent();
    parentElement.replaceChildInternal(this, elementCopy);
  }
  else {
    CodeEditUtil.replaceChild(getParent().getNode(), getNode(), elementCopy);
  }
  elementCopy = ChangeUtil.decodeInformation(elementCopy);
  return SourceTreeToPsiMap.treeElementToPsi(elementCopy);
}
项目:intellij-ce-playground    文件:Factory.java   
@NotNull
public static LeafElement createSingleLeafElement(@NotNull IElementType type, CharSequence buffer, int startOffset, int endOffset, CharTable table, PsiManager manager, PsiFile originalFile) {
  DummyHolder dummyHolder = DummyHolderFactory.createHolder(manager, table, type.getLanguage());
  dummyHolder.setOriginalFile(originalFile);

  FileElement holderElement = dummyHolder.getTreeElement();

  LeafElement newElement = ASTFactory.leaf(type, holderElement.getCharTable().intern(
    buffer, startOffset, endOffset));
  holderElement.rawAddChildren(newElement);
  CodeEditUtil.setNodeGenerated(newElement, true);
  return newElement;
}
项目:intellij-ce-playground    文件:Factory.java   
@NotNull
public static LeafElement createSingleLeafElement(@NotNull IElementType type, CharSequence buffer, int startOffset, int endOffset, CharTable table, PsiManager manager, boolean generatedFlag) {
  final FileElement holderElement = DummyHolderFactory.createHolder(manager, table, type.getLanguage()).getTreeElement();
  final LeafElement newElement = ASTFactory.leaf(type, holderElement.getCharTable().intern(
    buffer, startOffset, endOffset));
  holderElement.rawAddChildren(newElement);
  if(generatedFlag) CodeEditUtil.setNodeGenerated(newElement, true);
  return newElement;
}
项目:intellij-ce-playground    文件:CompositeElement.java   
/**
 * @return First element that was appended (for example whitespaces could be skipped)
 */
public TreeElement addInternal(TreeElement first, ASTNode last, ASTNode anchor, Boolean before) {
  ASTNode anchorBefore;
  if (anchor != null) {
    anchorBefore = before.booleanValue() ? anchor : anchor.getTreeNext();
  }
  else {
    anchorBefore = before == null || before.booleanValue() ? null : getFirstChildNode();
  }
  return (TreeElement)CodeEditUtil.addChildren(this, first, last, anchorBefore);
}
项目:intellij-ce-playground    文件:CompositeElement.java   
@Override
public void addLeaf(@NotNull final IElementType leafType, final CharSequence leafText, final ASTNode anchorBefore) {
  FileElement holder = new DummyHolder(getManager(), null).getTreeElement();
  final LeafElement leaf = ASTFactory.leaf(leafType, holder.getCharTable().intern(leafText));
  CodeEditUtil.setNodeGenerated(leaf, true);
  holder.rawAddChildren(leaf);

  addChild(leaf, anchorBefore);
}
项目:intellij-ce-playground    文件:SharedImplUtil.java   
public static PsiElement addRange(PsiElement thisElement,
                                  PsiElement first,
                                  PsiElement last,
                                  ASTNode anchor,
                                  Boolean before) throws IncorrectOperationException {
  CheckUtil.checkWritable(thisElement);
  final CharTable table = findCharTableByTree(SourceTreeToPsiMap.psiElementToTree(thisElement));

  TreeElement copyFirst = null;
  ASTNode copyLast = null;
  ASTNode next = SourceTreeToPsiMap.psiElementToTree(last).getTreeNext();
  ASTNode parent = null;
  for (ASTNode element = SourceTreeToPsiMap.psiElementToTree(first); element != next; element = element.getTreeNext()) {
    TreeElement elementCopy = ChangeUtil.copyElement((TreeElement)element, table);
    if (element == first.getNode()) {
      copyFirst = elementCopy;
    }
    if (element == last.getNode()) {
      copyLast = elementCopy;
    }
    if (parent == null) {
      parent = elementCopy.getTreeParent();
    }
    else {
      if(elementCopy.getElementType() == TokenType.WHITE_SPACE)
        CodeEditUtil.setNodeGenerated(elementCopy, true);
      parent.addChild(elementCopy, null);
    }
  }
  if (copyFirst == null) return null;
  copyFirst = ((CompositeElement)SourceTreeToPsiMap.psiElementToTree(thisElement)).addInternal(copyFirst, copyLast, anchor, before);
  for (TreeElement element = copyFirst; element != null; element = element.getTreeNext()) {
    element = ChangeUtil.decodeInformation(element);
    if (element.getTreePrev() == null) {
      copyFirst = element;
    }
  }
  return SourceTreeToPsiMap.treeElementToPsi(copyFirst);
}
项目:intellij-ce-playground    文件:LazyParseablePsiElement.java   
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
  CheckUtil.checkWritable(this);
  ASTNode firstElement = SourceTreeToPsiMap.psiElementToTree(first);
  ASTNode lastElement = SourceTreeToPsiMap.psiElementToTree(last);
  LOG.assertTrue(firstElement.getTreeParent() == this);
  LOG.assertTrue(lastElement.getTreeParent() == this);
  CodeEditUtil.removeChildren(this, firstElement, lastElement);
}
项目:intellij-ce-playground    文件:CompositePsiElement.java   
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
  CheckUtil.checkWritable(this);
  ASTNode firstElement = first.getNode();
  ASTNode lastElement = last.getNode();
  LOG.assertTrue(firstElement.getTreeParent() == this);
  LOG.assertTrue(lastElement.getTreeParent() == this);
  CodeEditUtil.removeChildren(this, firstElement, lastElement);
}
项目:intellij-ce-playground    文件:ChangeUtil.java   
private static void saveIndentationToCopy(final TreeElement original, final TreeElement element) {
  if(original == null || element == null || CodeEditUtil.isNodeGenerated(original)) return;
  final int indentation = CodeEditUtil.getOldIndentation(original);
  if(indentation < 0) CodeEditUtil.saveWhitespacesInfo(original);
  CodeEditUtil.setOldIndentation(element, CodeEditUtil.getOldIndentation(original));
  if(indentation < 0) CodeEditUtil.setOldIndentation(original, -1);
}
项目:intellij-ce-playground    文件:PsiFileImpl.java   
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
  CheckUtil.checkWritable(this);
  if (first == null) {
    LOG.assertTrue(last == null);
    return;
  }
  ASTNode firstElement = SourceTreeToPsiMap.psiElementToTree(first);
  ASTNode lastElement = SourceTreeToPsiMap.psiElementToTree(last);
  CompositeElement treeElement = calcTreeElement();
  LOG.assertTrue(firstElement.getTreeParent() == treeElement);
  LOG.assertTrue(lastElement.getTreeParent() == treeElement);
  CodeEditUtil.removeChildren(treeElement, firstElement, lastElement);
}
项目:intellij-ce-playground    文件:PsiFileFactoryImpl.java   
@NotNull
public PsiFile createFileFromText(@NotNull String name,
                                  @NotNull FileType fileType, final Language language, @NotNull Language targetLanguage, @NotNull CharSequence text,
                                  long modificationStamp,
                                  final boolean physical,
                                  boolean markAsCopy) {
  final LightVirtualFile virtualFile = new LightVirtualFile(name, fileType, text, modificationStamp);

  final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
  final FileViewProviderFactory factory = LanguageFileViewProviders.INSTANCE.forLanguage(language);
  FileViewProvider viewProvider = factory != null ? factory.createFileViewProvider(virtualFile, language, myManager, physical) : null;
  if (viewProvider == null) viewProvider = new SingleRootFileViewProvider(myManager, virtualFile, physical);

  if (parserDefinition != null){
    final PsiFile psiFile = viewProvider.getPsi(targetLanguage);
    if (psiFile != null) {
      if(markAsCopy) {
        markGenerated(psiFile);
      }
      return psiFile;
    }
  }

  final SingleRootFileViewProvider singleRootFileViewProvider =
      new SingleRootFileViewProvider(myManager, virtualFile, physical);
  final PsiPlainTextFileImpl plainTextFile = new PsiPlainTextFileImpl(singleRootFileViewProvider);
  if(markAsCopy) CodeEditUtil.setNodeGenerated(plainTextFile.getNode(), true);
  return plainTextFile;
}
项目:intellij-ce-playground    文件:DocumentBasedFormattingModel.java   
@Override
public void commitChanges() {
  CodeEditUtil.allowToMarkNodesForPostponedFormatting(false);
  try {
    PsiDocumentManager.getInstance(myProject).commitDocument(myDocument);
  }
  finally {
    CodeEditUtil.allowToMarkNodesForPostponedFormatting(true);
  }
}
项目:intellij-ce-playground    文件:PyUnwrapper.java   
@Override
public List<PsiElement> unwrap(Editor editor, PsiElement element) throws IncorrectOperationException {
  List<PsiElement> res = super.unwrap(editor, element);
  for (PsiElement e : res) {
    CodeEditUtil.markToReformat(e.getNode(), true);
  }
  return res;
}
项目:intellij-ce-playground    文件:GrStringUtil.java   
public static void wrapInjection(GrStringInjection injection) {
  final GrExpression expression = injection.getExpression();
  LOG.assertTrue(expression != null);
  final GroovyPsiElementFactory instance = GroovyPsiElementFactory.getInstance(injection.getProject());
  final GrClosableBlock closure = instance.createClosureFromText("{foo}");
  closure.getNode().replaceChild(closure.getStatements()[0].getNode(), expression.getNode());
  injection.getNode().addChild(closure.getNode());
  CodeEditUtil.setNodeGeneratedRecursively(expression.getNode(), true);
}
项目:intellij-ce-playground    文件:GroovyBraceEnforcer.java   
private void replaceWithBlock(@NotNull GrStatement statement, GrStatement blockCandidate) {
  if (!statement.isValid()) {
    LOG.assertTrue(false);
  }

  if (!checkRangeContainsElement(blockCandidate)) return;

  final PsiManager manager = statement.getManager();
  LOG.assertTrue(manager != null);
  GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(manager.getProject());

  String oldText = blockCandidate.getText();
  // There is a possible case that target block to wrap ends with single-line comment. Example:
  //     if (true) i = 1; // Cool assignment
  // We can't just surround target block of code with curly braces because the closing one will be treated as comment as well.
  // Hence, we perform a check if we have such situation at the moment and insert new line before the closing brace.
  StringBuilder buf = new StringBuilder(oldText.length() + 5);
  buf.append("{\n").append(oldText);
  buf.append("\n}");
  final int oldTextLength = statement.getTextLength();
  try {
    ASTNode newChild = SourceTreeToPsiMap.psiElementToTree(factory.createBlockStatementFromText(buf.toString(), null));
    ASTNode parent = SourceTreeToPsiMap.psiElementToTree(statement);
    ASTNode childToReplace = SourceTreeToPsiMap.psiElementToTree(blockCandidate);
    CodeEditUtil.replaceChild(parent, childToReplace, newChild);

    removeTailSemicolon(newChild, parent);
    CodeStyleManager.getInstance(statement.getProject()).reformat(statement, true);
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
  finally {
    updateResultRange(oldTextLength, statement.getTextLength());
  }
}
项目:intellij-ce-playground    文件:GroovyUnwrapper.java   
@Override
public List<PsiElement> unwrap(Editor editor, PsiElement element) throws IncorrectOperationException {
  List<PsiElement> res = super.unwrap(editor, element);

  for (PsiElement e : res) {
    if (PsiImplUtil.isLeafElementOfType(e, GroovyTokenTypes.mNLS)) {
      CodeEditUtil.setNodeGenerated(e.getNode(), true);
    }
  }

  return res;
}
项目:intellij-ocaml    文件:OCamlASTNodeUtil.java   
@NotNull
public static ASTNode createLeaf(@NotNull final IElementType elementType, @NotNull final String token) {
    final LeafElement createdNode = LanguageASTFactory.INSTANCE.forLanguage(elementType.getLanguage()).createLeaf(elementType, token);
    CodeEditUtil.setNodeGenerated(createdNode, true);
    //noinspection ConstantConditions
    return createdNode;
}
项目:tools-idea    文件:PsiElementFactoryImpl.java   
@NotNull
@Override
public PsiTypeElement createTypeElement(@NotNull final PsiType psiType) {
  final LightTypeElement element = new LightTypeElement(myManager, psiType);
  CodeEditUtil.setNodeGenerated(element.getNode(), true);
  return element;
}