com.intellij.formatting.Block Java Examples

The following examples show how to use com.intellij.formatting.Block. 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: BashBlockGenerator.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
public static List<Block> generateSubBlocks(ASTNode node,
                                            Alignment _myAlignment,
                                            Wrap _myWrap,
                                            CodeStyleSettings _mySettings,
                                            BashBlock block) {
    myWrap = _myWrap;
    mySettings = _mySettings;
    myAlignment = _myAlignment;

    // For other cases
    final List<Block> subBlocks = new ArrayList<Block>();
    ASTNode children[] = getBashChildren(node);
    ASTNode prevChildNode = null;
    for (ASTNode childNode : children) {
        if (canBeCorrectBlock(childNode)) {
            final Indent indent = BashIndentProcessor.getChildIndent(block, prevChildNode, childNode);
            subBlocks.add(new BashBlock(childNode, myAlignment, indent, myWrap, mySettings));
            prevChildNode = childNode;
        }
    }
    return subBlocks;
}
 
Example #2
Source File: DocumentBasedFormattingModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Deprecated
public DocumentBasedFormattingModel(final Block rootBlock,
                                    @Nonnull final Document document,
                                    final Project project,
                                    final CodeStyleSettings settings,
                                    final FileType fileType,
                                    final PsiFile file) {
  myRootBlock = rootBlock;
  myDocument = document;
  myProject = project;
  mySettings = settings;
  myFileType = fileType;
  myFile = file;
  myDocumentModel = new FormattingDocumentModelImpl(document,file);
  myOriginalFormattingModel = null;
}
 
Example #3
Source File: NewLineBlocksIterator.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void popUntilTopBlockStartsNewLine() {
  popUntilTopBlockStartOffsetGreaterOrEqual(myCurrentLineStartOffset);
  if (myStack.isEmpty()) return;

  Block block = myStack.peek();
  while (block != null && !isStartingNewLine(block)) {
    myCurrentDocumentLine++;
    if (myCurrentDocumentLine >= myTotalLines) {
      myStack.clear();
      break;
    }
    myCurrentLineStartOffset = myDocument.getLineStartOffset(myCurrentDocumentLine);
    popUntilTopBlockStartOffsetGreaterOrEqual(myCurrentLineStartOffset);
    block = myStack.isEmpty() ? null : myStack.peek();
  }
}
 
Example #4
Source File: CypherBlock.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public List<Block> getSubBlocks() {
    if (subBlocks == null) {
        Predicate<ASTNode> isWhitespaceOrEmpty = CypherBlock::isWhitespaceOrEmpty;
        AlignmentStrategy.AlignmentPerTypeStrategy strategy = createStrategy(getNode());

        subBlocks = new ArrayList<>();
        for (ASTNode subNode = node.getFirstChildNode(); subNode != null; subNode = subNode.getTreeNext()) {
            if (isWhitespaceOrEmpty.test(subNode)) {
                continue;
            }

            Alignment alignment = strategy != null
                        ? strategy.getAlignment(getNode().getElementType(), subNode.getElementType())
                        : null;

            CypherBlock block = makeSubBlock(subNode, alignment);
            subBlocks.add(block);
        }
    }
    return subBlocks;
}
 
Example #5
Source File: NewLineBlocksIterator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Block next() {
  popUntilTopBlockStartsNewLine();

  Block current = myStack.peek();
  TextRange currentBlockRange = current.getTextRange();

  myCurrentDocumentLine = myDocument.getLineNumber(currentBlockRange.getStartOffset());
  myCurrentDocumentLine++;
  if (myCurrentDocumentLine < myTotalLines) {
    myCurrentLineStartOffset = myDocument.getLineStartOffset(myCurrentDocumentLine);
    if (currentBlockRange.getEndOffset() < myCurrentLineStartOffset) {
      myStack.pop();
    }
    else {
      pushAll(current);
    }
  }

  return current;
}
 
Example #6
Source File: ParentBlock.java    From protobuf-jetbrains-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
    if (child2 instanceof ASTBlock) {
        ASTBlock block = (ASTBlock) child2;
        // Do not move semicolon after '}' to new line.
        IElementType elementType = block.getNode().getElementType();
        if (SEMICOLON.equals(elementType)) {
            return NONE;
        }
        // Do not move trailing comments to new line.
        if (LINE_COMMENT.equals(elementType)
                || COMMENT.equals(elementType)) {
            return SPACE_OR_NEW_LINE;
        }
    }
    if (headerBlocks.contains(child1)) {
        return super.getSpacing(child1, child2);
    }
    return NEW_LINE;
}
 
Example #7
Source File: XQueryFormattingBlock.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@Nullable
private IElementType getIElementType(int newChildIndex) {
    Block block = getSubBlocks().get(newChildIndex - 1);
    while (block instanceof XQueryFormattingBlock && ! block.getSubBlocks().isEmpty()) {
        List<Block> subBlocks = block.getSubBlocks();
        Block childBlock = subBlocks.get(subBlocks.size() - 1);
        if (! (childBlock instanceof XQueryFormattingBlock)) break;
        else {
            ASTNode node = ((XQueryFormattingBlock) childBlock).getNode();
            PsiElement psi = node.getPsi();
            IElementType elementType = node.getElementType();
            if (elementType instanceof XQueryTokenType) break;
            if (psi instanceof LeafPsiElement || psi instanceof XQueryFunctionName || psi instanceof
                    XQueryVarName || psi instanceof XQueryNamespacePrefix)
                break;
        }
        block = childBlock;
    }
    return block instanceof XQueryFormattingBlock ? ((XQueryFormattingBlock) block).getNode().getElementType() :
            null;
}
 
Example #8
Source File: GraphQLInjectedFormattingModelBuilder.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
    if(element instanceof JSFile || element.getContainingFile() instanceof JSFile) {
        final JSFile file = (JSFile)(element instanceof JSFile ? element : element.getContainingFile());
        file.putUserData(WANT_DEFAULT_FORMATTER_KEY, true);
        try {
            final FormattingModelBuilder formattingModelBuilder = LanguageFormatting.INSTANCE.forContext(file.getLanguage(), element);
            if (formattingModelBuilder != null) {
                final FormattingModel model = formattingModelBuilder.createModel(element, settings);
                final Block rootBlock = model.getRootBlock();
                return new DelegatingFormattingModel(model, new GraphQLBlockWrapper(rootBlock, null, element.getNode(), rootBlock.getWrap(), rootBlock.getAlignment(), createSpaceBuilder(settings, element), settings));
            }
        } finally {
            file.putUserData(WANT_DEFAULT_FORMATTER_KEY, null);
        }
    }
    throw new IllegalArgumentException("Unsupported element '" + element + "'. It must be an element in a JSFile with its own default formatter to support injected GraphQL formatting");
}
 
Example #9
Source File: ProtoFileBlock.java    From protobuf-jetbrains-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
    if (child1 == null) {
        return StatementBlock.NONE;
    }
    if (child2 instanceof ASTBlock) {
        ASTBlock block = (ASTBlock) child2;
        IElementType elementType = block.getNode().getElementType();

        // Do not move trailing comments to new line.
        if (LINE_COMMENT.equals(elementType)
                || COMMENT.equals(elementType)) {
            return SPACE_OR_NEW_LINE;
        }
    }
    return StatementBlock.NEW_LINE;
}
 
Example #10
Source File: FormatterBasedLineIndentInfoBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
public List<LineIndentInfo> build() {
  List<Block> newLineBlocks = getBlocksStartingNewLine();

  return ContainerUtil.map(newLineBlocks, new Function<Block, LineIndentInfo>() {
    @Override
    public LineIndentInfo fun(Block newLineBlock) {
      int blockStartOffset = newLineBlock.getTextRange().getStartOffset();
      int line = myDocument.getLineNumber(blockStartOffset);
      int lineStartOffset = myDocument.getLineStartOffset(line);

      if (rangeHasTabs(lineStartOffset, blockStartOffset)) {
        return LineIndentInfo.LINE_WITH_TABS;
      }

      if (hasNormalIndent(newLineBlock)) {
        return LineIndentInfo.newNormalIndent(blockStartOffset - lineStartOffset);
      }
      else {
        return LineIndentInfo.LINE_WITH_NOT_COUNTABLE_INDENT;
      }
    }
  });
}
 
Example #11
Source File: ProtoFileBlock.java    From protobuf-jetbrains-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected List<Block> buildChildren() {
    List<Block> blocks = new ArrayList<>();
    ASTNode child = myNode.getFirstChildNode();
    while (child != null) {
        if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
            IElementType elementType = child.getElementType();
            if (ProtoParserDefinition.rule(ProtoParser.RULE_proto).equals(elementType)) {
                appendProtoBlocks(child, blocks);
            } else {
                // Comments are not part of root rule, we have to append them separately
                blocks.add(new LeafBlock(child, Alignment.createAlignment(), Indent.getNoneIndent(), settings));
            }
        }
        child = child.getTreeNext();
    }
    return blocks;
}
 
Example #12
Source File: FormatterBasedLineIndentInfoBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean hasNormalIndent(Block block) {
  final TextRange range = block.getTextRange();
  final int startOffset = range.getStartOffset();

  List<Indent.Type> allIndents = getIndentOnStartOffset(block, range, startOffset);

  if (hasOnlyNormalOrNoneIndents(allIndents)) {
    int normalIndents = ContainerUtil.filter(allIndents, new Condition<Indent.Type>() {
      @Override
      public boolean value(Indent.Type type) {
        return type == Indent.Type.NORMAL;
      }
    }).size();
    return normalIndents < 2;
  }

  return false;
}
 
Example #13
Source File: FormatterBasedLineIndentInfoBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private List<Block> getBlocksStartingNewLine() {
  NewLineBlocksIterator newLineBlocksIterator = new NewLineBlocksIterator(myRootBlock, myDocument);

  List<Block> newLineBlocks = new ArrayList<Block>();
  int currentLine = 0;
  while (newLineBlocksIterator.hasNext() && currentLine < MAX_NEW_LINE_BLOCKS_TO_PROCESS) {
    Block next = newLineBlocksIterator.next();
    if (next instanceof ASTBlock && ((ASTBlock)next).getNode() instanceof PsiComment) {
      continue;
    }
    newLineBlocks.add(next);
    currentLine++;
  }

  return newLineBlocks;
}
 
Example #14
Source File: BlockUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static List<DataLanguageBlockWrapper> buildChildWrappers(@Nonnull final Block parent) {
  assert !(parent instanceof DataLanguageBlockWrapper) : parent.getClass();
  List<Block> children = parent.getSubBlocks();
  if (children.size() == 0) return Collections.emptyList();
  ArrayList<DataLanguageBlockWrapper> result = new ArrayList<DataLanguageBlockWrapper>(children.size());
  DataLanguageBlockWrapper prevWrapper = null;
  for (Block child : children) {
    DataLanguageBlockWrapper currWrapper = createAndAddBlock(result, child, null);
    if(currWrapper != null && prevWrapper != null) {
      Spacing spacing = parent.getSpacing(prevWrapper.getOriginal(), currWrapper.getOriginal());
      prevWrapper.setRightHandSpacing(currWrapper, spacing);
    }
    prevWrapper = currWrapper;
  }
  return result;
}
 
Example #15
Source File: CsvBlockField.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
    if (!myFormattingInfo.getCsvCodeStyleSettings().TABULARIZE || myFormattingInfo.getCsvCodeStyleSettings().WHITE_SPACES_OUTSIDE_QUOTES || child1 == null) {
        return null;
    }
    int spaces = 0;
    CsvBlockElement block1 = (CsvBlockElement) child1;
    CsvBlockElement block2 = (CsvBlockElement) child2;
    if ((block1.getElementType() == CsvTypes.QUOTE && myFormattingInfo.getCsvCodeStyleSettings().LEADING_WHITE_SPACES) ||
            (block2.getElementType() == CsvTypes.QUOTE && !myFormattingInfo.getCsvCodeStyleSettings().LEADING_WHITE_SPACES)) {
        spaces = getColumnInfo().getMaxLength() - getTextLength();
    } else {
        return myFormattingInfo.getSpacingBuilder().getSpacing(this, child1, child2);
    }
    return Spacing.createSpacing(spaces, spaces, 0, true, 0);
}
 
Example #16
Source File: JSGraphQLEndpointBlock.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@Override
protected List<Block> buildChildren() {

	List<Block> blocks = new ArrayList<>();
	ASTNode child = myNode.getFirstChildNode();
	while (child != null) {
		if (!TokenType.WHITE_SPACE.equals(child.getElementType()) && !TokenType.BAD_CHARACTER.equals(child.getElementType())) {
			if (!child.getTextRange().isEmpty()) {
				JSGraphQLEndpointBlock block = new JSGraphQLEndpointBlock(this, child, null, null, spacingBuilder);
				blocks.add(block);
			}
		}
		child = child.getTreeNext();
	}

	return blocks;
}
 
Example #17
Source File: BlockUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void splitByRightBoundAndCollectBlocks(@Nonnull List<Block> blocks,
                                                      @Nonnull List<DataLanguageBlockWrapper> before,
                                                      @Nonnull List<DataLanguageBlockWrapper> after,
                                                      @Nonnull TextRange bounds) {
  for (Block block : blocks) {
    final TextRange textRange = block.getTextRange();
    if (bounds.contains(textRange)) {
      createAndAddBlock(before, block, null);
    }
    else if (bounds.getEndOffset() <= textRange.getStartOffset()) {
      createAndAddBlock(after, block, null);
    }
    else {
      //assert block.getSubBlocks().size() != 0 : "Block " + block.getTextRange() + " doesn't contain subblocks!";
      splitByRightBoundAndCollectBlocks(block.getSubBlocks(), before, after, bounds);
    }
  }
}
 
Example #18
Source File: FormatterBasedLineIndentInfoBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static List<Indent.Type> getIndentOnStartOffset(Block block, TextRange range, int startOffset) {
  List<Indent.Type> indentsOnStartOffset = new ArrayList<Indent.Type>();

  while (block != null && range.getStartOffset() == startOffset) {
    Indent.Type type = block.getIndent() != null ? block.getIndent().getType() : Indent.Type.CONTINUATION_WITHOUT_FIRST;
    indentsOnStartOffset.add(type);

    if (block instanceof AbstractBlock) {
      ((AbstractBlock)block).setBuildIndentsOnly(true);
    }
    List<Block> subBlocks = block.getSubBlocks();
    block = subBlocks.isEmpty() ? null : subBlocks.get(0);
  }

  return indentsOnStartOffset;
}
 
Example #19
Source File: BlockIndentOptions.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int calcRightMargin(Block rootBlock) {
  Language language = null;
  if (rootBlock instanceof ASTBlock) {
    ASTNode node = ((ASTBlock)rootBlock).getNode();
    if (node != null) {
      PsiElement psiElement = node.getPsi();
      if (psiElement.isValid()) {
        PsiFile psiFile = psiElement.getContainingFile();
        if (psiFile != null) {
          language = psiFile.getViewProvider().getBaseLanguage();
        }
      }
    }
  }
  return mySettings.getRightMargin(language);
}
 
Example #20
Source File: CStyleCommentBlock.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected List<Block> buildChildren() {
  if (!isCommentFormattable.getValue()) {
    return Collections.emptyList();
  }

  return ContainerUtil.<LineInfo, Block>map(lines.getValue(), t -> {
    String text = t.myText;

    Indent indent = null;
    if (!isCommentFormattable.getValue()) {
      indent = null;
    }
    else if (text.startsWith("/*")) {
      indent = Indent.getNoneIndent();
    }
    else {
      indent = Indent.getSpaceIndent(1);
    }

    return new TextLineBlock(text, t.myTextRange, null, indent, null);
  });
}
 
Example #21
Source File: CStyleCommentBlock.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Spacing getSpacing(@Nullable Block child1, @Nonnull Block child2) {
  boolean isLicenseComment = child1 == null && FormatterTreeUtil.prev(getNode()) == null;
  if (isLicenseComment) {
    return Spacing.getReadOnlySpacing();
  }

  return child2.getSpacing(null, this);
}
 
Example #22
Source File: IndentOptionsDetectorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private List<LineIndentInfo> calcLineIndentInfo() {
  if (myDocument == null) return null;
  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(myProject);
  FormattingModelBuilder modelBuilder = LanguageFormatting.INSTANCE.forContext(myFile);
  if (modelBuilder == null) return null;

  FormattingModel model = modelBuilder.createModel(myFile, settings);
  Block rootBlock = model.getRootBlock();
  return new FormatterBasedLineIndentInfoBuilder(myDocument, rootBlock).build();
}
 
Example #23
Source File: BlockUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static DataLanguageBlockWrapper createAndAddBlock(List<DataLanguageBlockWrapper> list, Block block, @Nullable final Indent indent) {
  DataLanguageBlockWrapper wrapper = DataLanguageBlockWrapper.create(block, indent);
  if (wrapper != null) {
    list.add(wrapper);
  }
  return wrapper;
}
 
Example #24
Source File: BlockUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>> splitBlocksByRightBound(@Nonnull Block parent, @Nonnull TextRange bounds) {
  final List<Block> subBlocks = parent.getSubBlocks();
  if (subBlocks.size() == 0) return new Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>>(Collections.<DataLanguageBlockWrapper>emptyList(), Collections.<DataLanguageBlockWrapper>emptyList());
  final ArrayList<DataLanguageBlockWrapper> before = new ArrayList<DataLanguageBlockWrapper>(subBlocks.size() / 2);
  final ArrayList<DataLanguageBlockWrapper> after = new ArrayList<DataLanguageBlockWrapper>(subBlocks.size() / 2);
  splitByRightBoundAndCollectBlocks(subBlocks, before, after, bounds);
  return new Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>>(before, after);
}
 
Example #25
Source File: BlockUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
static void printBlocks(@Nullable TextRange textRange, @Nonnull List<Block> list) {
  StringBuilder sb = new StringBuilder(String.valueOf(textRange)).append(": ");
  for (Block block : list) {
    ASTNode node = block instanceof ASTBlock ? ((ASTBlock)block).getNode() : null;
    TextRange r = block.getTextRange();
    sb.append(" [").append(node != null ? node.getElementType() : null)//.append(" ").append(((BlockWithParent)block).getParent() != null)
        .append(r).append(block.getIndent()).append(block.getAlignment()).append("] ");
  }
  System.out.println(sb);
}
 
Example #26
Source File: NewLineBlocksIterator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isStartingNewLine(Block block) {
  TextRange range = block.getTextRange();
  int blockStart = range.getStartOffset();

  int lineNumber = myDocument.getLineNumber(blockStart);
  int lineStartOffset = myDocument.getLineStartOffset(lineNumber);

  CharSequence text = myDocument.getCharsSequence();
  return CharArrayUtil.isEmptyOrSpaces(text, lineStartOffset, blockStart);
}
 
Example #27
Source File: CSharpFormattingModelBuilder.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings)
{
	final PsiFile file = element.getContainingFile();
	FormattingDocumentModelImpl model = FormattingDocumentModelImpl.createOn(element.getContainingFile());
	Block rootBlock = new CSharpFormattingBlock(file.getNode(), null, null, settings);
	return new PsiBasedFormattingModel(file, rootBlock, model);
}
 
Example #28
Source File: BlockTreeNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public BlockTreeNode[] getChildren() {
  return ContainerUtil.map2Array(myBlock.getSubBlocks(), BlockTreeNode.class, new Function<Block, BlockTreeNode>() {
    @Override
    public BlockTreeNode fun(Block block) {
      return new BlockTreeNode(block, BlockTreeNode.this);
    }
  });
}
 
Example #29
Source File: XQueryFormattingBlock.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Block> buildChildren() {
    List<Block> blocks = new ArrayList<Block>();
    ASTNode child = myNode.getFirstChildNode();
    while (child != null) {
        if (child.getElementType() != TokenType.WHITE_SPACE && child.getTextRange().getLength() != 0) {
            Block block = new XQueryFormattingBlock(child, Wrap.createWrap(WrapType.NONE, false), null, settings,
                    spacingBuilder);
            blocks.add(block);
        }
        child = child.getTreeNext();
    }
    return blocks;
}
 
Example #30
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Block buildBlocks(@Nonnull PsiElement rootElement) {
  FormattingModelBuilder formattingModelBuilder = LanguageFormatting.INSTANCE.forContext(rootElement);
  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(rootElement.getProject());
  if (formattingModelBuilder != null) {
    FormattingModel formattingModel = formattingModelBuilder.createModel(rootElement, settings);
    return formattingModel.getRootBlock();
  }
  else {
    return null;
  }
}