Java Code Examples for com.intellij.openapi.util.text.StringUtil#repeatSymbol()

The following examples show how to use com.intellij.openapi.util.text.StringUtil#repeatSymbol() . 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: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ForLoopThatDoesntUseLoopVariable")
private static void indentPlainTextBlock(final Document document, final int startOffset, final int endOffset, final int indentLevel) {
  CharSequence chars = document.getCharsSequence();
  int spaceEnd = CharArrayUtil.shiftForward(chars, startOffset, " \t");
  int line = document.getLineNumber(startOffset);
  if (spaceEnd > endOffset || indentLevel <= 0 || line >= document.getLineCount() - 1 || chars.charAt(spaceEnd) == '\n') {
    return;
  }

  int linesToAdjustIndent = 0;
  for (int i = line + 1; i < document.getLineCount(); i++) {
    if (document.getLineStartOffset(i) >= endOffset) {
      break;
    }
    linesToAdjustIndent++;
  }

  String indentString = StringUtil.repeatSymbol(' ', indentLevel);

  for (; linesToAdjustIndent > 0; linesToAdjustIndent--) {
    int lineStartOffset = document.getLineStartOffset(++line);
    document.insertString(lineStartOffset, indentString);
  }
}
 
Example 2
Source File: VersionComparatorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int compareNumbers(String n1, String n2) {
  // trim leading zeros
  while(n1.length() > 0 && n2.length() > 0 && n1.charAt(0) == '0' && n2.charAt(0) == '0') {
    n1 = n1.substring(1);
    n2 = n2.substring(1);
  }

  // starts with zero => less
  if (n1.length() > 0 && n1.charAt(0) == '0') {
    return -1;
  } else if (n2.length() > 0 && n2.charAt(0) == '0') {
    return 1;
  }

  // compare as numbers
  final int n1len = n1.length();
  final int n2len = n2.length();

  if (n1len > n2len) {
    n2 = StringUtil.repeatSymbol('0', n1len - n2len) + n2;
  } else if (n2len > n1len) {
    n1 = StringUtil.repeatSymbol('0', n2len - n1len) + n1;
  }

  return n1.compareTo(n2);
}
 
Example 3
Source File: DebugUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void stubTreeToBuffer(final Stub node, final Appendable buffer, final int indent) {
  StringUtil.repeatSymbol(buffer, ' ', indent);
  try {
    final ObjectStubSerializer stubType = node.getStubType();
    if (stubType != null) {
      buffer.append(stubType.toString()).append(':');
    }
    buffer.append(node.toString()).append('\n');

    @SuppressWarnings({"unchecked"})
    final List<? extends Stub> children = node.getChildrenStubs();
    for (final Stub child : children) {
      stubTreeToBuffer(child, buffer, indent + 2);
    }
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
 
Example 4
Source File: SoftWrapEngine.java    From consulo with Apache License 2.0 6 votes vote down vote up
private SoftWrap createSoftWrap(SoftWrap lastSoftWrap, int minWrapOffset, int maxWrapOffset, boolean preferMinOffset, int nonWhitespaceStartOffset, float nonWhitespaceStartX) {
  int wrapOffset = minWrapOffset >= maxWrapOffset ? minWrapOffset : calcSoftWrapOffset(minWrapOffset, maxWrapOffset, preferMinOffset);
  int indentInColumns = 1;
  int indentInPixels = mySoftWrapWidth;
  if (myRelativeIndent >= 0) {
    if (lastSoftWrap == null) {
      if (nonWhitespaceStartOffset >= 0 && nonWhitespaceStartOffset < wrapOffset) {
        indentInColumns += myEditor.offsetToLogicalPosition(nonWhitespaceStartOffset).column;
        indentInPixels += nonWhitespaceStartX;
      }
      indentInColumns += myRelativeIndent;
      indentInPixels += myRelativeIndent * myView.getPlainSpaceWidth();
    }
    else {
      indentInColumns = lastSoftWrap.getIndentInColumns();
      indentInPixels = lastSoftWrap.getIndentInPixels();
    }
  }
  SoftWrapImpl result = new SoftWrapImpl(new TextChangeImpl("\n" + StringUtil.repeatSymbol(' ', indentInColumns - 1), wrapOffset), indentInColumns, indentInPixels);
  myStorage.storeOrReplace(result);
  return result;
}
 
Example 5
Source File: GroupNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String tree2string(int indent, String lineSeparator) {
  StringBuffer result = new StringBuffer();
  StringUtil.repeatSymbol(result, ' ', indent);

  if (getGroup() != null) result.append(getGroup());
  result.append("[");
  result.append(lineSeparator);

  for (Node node : myChildren) {
    result.append(node.tree2string(indent + 4, lineSeparator));
    result.append(lineSeparator);
  }

  StringUtil.repeatSymbol(result, ' ', indent);
  result.append("]");
  result.append(lineSeparator);

  return result.toString();
}
 
Example 6
Source File: ArtifactsTestUtil.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static String printToString(PackagingElement element, int level) {
  StringBuilder builder = new StringBuilder(StringUtil.repeatSymbol(' ', level));
  if (element instanceof ArchivePackagingElement) {
    builder.append(((ArchivePackagingElement)element).getArchiveFileName());
  }
  else if (element instanceof DirectoryPackagingElement) {
    builder.append(((DirectoryPackagingElement)element).getDirectoryName()).append("/");
  }
  else {
    builder.append(element.toString());
  }
  builder.append("\n");
  if (element instanceof CompositePackagingElement) {
    for (PackagingElement<?> child : ((CompositePackagingElement<?>)element).getChildren()) {
      builder.append(printToString(child, level + 1));
    }
  }
  return builder.toString();
}
 
Example 7
Source File: CSharpChangeSignatureDialog.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredUIAccess
protected JComponent getRowPresentation(ParameterTableModelItemBase<CSharpParameterInfo> item, boolean selected, final boolean focused)
{
	final String typeText = item.typeCodeFragment.getText();
	CSharpModifier modifier = item.parameter.getModifier();
	String text = "";
	if(modifier != null)
	{
		text = modifier.getPresentableText() + " ";
	}
	final String separator = StringUtil.repeatSymbol(' ', getTypesMaxLength() - typeText.length() + 1);

	text += typeText + separator + item.parameter.getName();
	final String defaultValue = item.defaultValueCodeFragment.getText();
	String tail = "";
	if(StringUtil.isNotEmpty(defaultValue))
	{
		tail += " argument value = " + defaultValue;
	}
	if(!StringUtil.isEmpty(tail))
	{
		text += " //" + tail;
	}
	return JBListTable.createEditorTextFieldPresentation(getProject(), getFileType(), " " + text, selected, focused);
}
 
Example 8
Source File: TableAction.java    From idea-latex with MIT License 6 votes vote down vote up
@NotNull
@Override
protected String getContent(@NotNull TableEditorActionDialog dialog) {
    StringBuilder sb = new StringBuilder();
    int rows = dialog.getRows();
    int columns = dialog.getColumns();
    String alignmentValue = StringUtil.repeatSymbol(dialog.getAlignment().getValue(), columns);
    String tableBorder = dialog.getBorder().isNone() ? "" : "|";
    String cellBorder = dialog.getBorder().isCell() ? "\\hline\n" : "";

    sb.append(String.format("\\begin{tabular}{%s%s%s}\n", tableBorder, alignmentValue, tableBorder));
    sb.append(cellBorder);
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= columns; j++) {
            sb.append(String.format("%d%d%s", i, j, j == columns ? "\\\\\n" : " & "));
        }
        sb.append(cellBorder);
    }
    sb.append("\\end{tabular}");

    return sb.toString();
}
 
Example 9
Source File: PlatformTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int doPrint(StringBuilder buffer,
                           int currentLevel,
                           Object node,
                           AbstractTreeStructure structure,
                           @javax.annotation.Nullable Comparator comparator,
                           int maxRowCount,
                           int currentLine,
                           char paddingChar,
                           @javax.annotation.Nullable Queryable.PrintInfo printInfo) {
  if (currentLine >= maxRowCount && maxRowCount != -1) return currentLine;

  StringUtil.repeatSymbol(buffer, paddingChar, currentLevel);
  buffer.append(toString(node, printInfo)).append("\n");
  currentLine++;
  Object[] children = structure.getChildElements(node);

  if (comparator != null) {
    ArrayList<?> list = new ArrayList<Object>(Arrays.asList(children));
    @SuppressWarnings({"UnnecessaryLocalVariable", "unchecked"}) Comparator<Object> c = comparator;
    Collections.sort(list, c);
    children = ArrayUtil.toObjectArray(list);
  }
  for (Object child : children) {
    currentLine = doPrint(buffer, currentLevel + 1, child, structure, comparator, maxRowCount, currentLine, paddingChar, printInfo);
  }

  return currentLine;
}
 
Example 10
Source File: ProjectViewEnterHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public Result preprocessEnter(
    PsiFile file,
    Editor editor,
    Ref<Integer> caretOffset,
    Ref<Integer> caretAdvance,
    DataContext dataContext,
    EditorActionHandler originalHandler) {
  int offset = caretOffset.get();
  if (editor instanceof EditorWindow) {
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    editor = InjectedLanguageUtil.getTopLevelEditor(editor);
    offset = editor.getCaretModel().getOffset();
  }
  if (!isApplicable(file, dataContext) || !insertIndent(file, offset)) {
    return Result.Continue;
  }
  int indent = SectionParser.INDENT;

  editor.getCaretModel().moveToOffset(offset);
  Document doc = editor.getDocument();
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);

  originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
  LogicalPosition position = editor.getCaretModel().getLogicalPosition();
  if (position.column < indent) {
    String spaces = StringUtil.repeatSymbol(' ', indent - position.column);
    doc.insertString(editor.getCaretModel().getOffset(), spaces);
  }
  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(position.line, indent));
  return Result.Stop;
}
 
Example 11
Source File: GenericUtil.java    From intellij-spring-assistant with MIT License 5 votes vote down vote up
@NotNull
public static String getCodeStyleIntent(InsertionContext insertionContext) {
  final CodeStyleSettings currentSettings =
      CodeStyleSettingsManager.getSettings(insertionContext.getProject());
  final CommonCodeStyleSettings.IndentOptions indentOptions =
      currentSettings.getIndentOptions(insertionContext.getFile().getFileType());
  return indentOptions.USE_TAB_CHARACTER ?
      "\t" :
      StringUtil.repeatSymbol(' ', indentOptions.INDENT_SIZE);
}
 
Example 12
Source File: DebugUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void treeToBufferWithUserData(Appendable buffer, PsiElement root, int indent, boolean skipWhiteSpaces) {
  if (skipWhiteSpaces && root instanceof PsiWhiteSpace) return;

  StringUtil.repeatSymbol(buffer, ' ', indent);
  try {
    if (root instanceof CompositeElement) {
      buffer.append(root.toString());
    }
    else {
      final String text = fixWhiteSpaces(root.getText());
      buffer.append(root.toString()).append("('").append(text).append("')");
    }
    buffer.append(((UserDataHolderBase)root).getUserDataString());
    buffer.append("\n");

    PsiElement[] children = root.getChildren();

    for (PsiElement child : children) {
      treeToBufferWithUserData(buffer, child, indent + 2, skipWhiteSpaces);
    }

    if (children.length == 0) {
      StringUtil.repeatSymbol(buffer, ' ', indent + 2);
      buffer.append("<empty list>\n");
    }
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
 
Example 13
Source File: SmartIndentingBackspaceHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void doBeforeCharDeleted(char c, PsiFile file, Editor editor) {
  Project project = file.getProject();
  Document document = editor.getDocument();
  CharSequence charSequence = document.getImmutableCharSequence();
  CaretModel caretModel = editor.getCaretModel();
  int caretOffset = caretModel.getOffset();
  LogicalPosition pos = caretModel.getLogicalPosition();
  int lineStartOffset = document.getLineStartOffset(pos.line);
  int beforeWhitespaceOffset = CharArrayUtil.shiftBackward(charSequence, caretOffset - 1, " \t") + 1;
  if (beforeWhitespaceOffset != lineStartOffset) {
    myReplacement = null;
    return;
  }
  PsiDocumentManager.getInstance(project).commitDocument(document);
  CodeStyleFacade codeStyleFacade = CodeStyleFacade.getInstance(project);
  myReplacement = codeStyleFacade.getLineIndent(document, lineStartOffset);
  if (myReplacement == null) {
    return;
  }
  int tabSize = codeStyleFacade.getTabSize(file.getFileType());
  int targetColumn = getWidth(myReplacement, tabSize);
  int endOffset = CharArrayUtil.shiftForward(charSequence, caretOffset, " \t");
  LogicalPosition logicalPosition = caretOffset < endOffset ? editor.offsetToLogicalPosition(endOffset) : pos;
  int currentColumn = logicalPosition.column;
  if (currentColumn > targetColumn) {
    myStartOffset = lineStartOffset;
  }
  else if (logicalPosition.line == 0) {
    myStartOffset = 0;
    myReplacement = "";
  }
  else {
    int prevLineEndOffset = document.getLineEndOffset(logicalPosition.line - 1);
    myStartOffset = CharArrayUtil.shiftBackward(charSequence, prevLineEndOffset - 1, " \t") + 1;
    if (myStartOffset != document.getLineStartOffset(logicalPosition.line - 1)) {
      int spacing = CodeStyleManager.getInstance(project).getSpacing(file, endOffset);
      myReplacement = StringUtil.repeatSymbol(' ', Math.max(0, spacing));
    }
  }
}
 
Example 14
Source File: FileHistoryPanelImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public String getPreferredStringValue() {
  return StringUtil.repeatSymbol('m', 80);
}
 
Example 15
Source File: BuildEnterHandler.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(
    PsiFile file,
    Editor editor,
    Ref<Integer> caretOffset,
    Ref<Integer> caretAdvance,
    DataContext dataContext,
    EditorActionHandler originalHandler) {
  int offset = caretOffset.get();
  if (editor instanceof EditorWindow) {
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    editor = InjectedLanguageUtil.getTopLevelEditor(editor);
    offset = editor.getCaretModel().getOffset();
  }
  if (!isApplicable(file, dataContext)) {
    return Result.Continue;
  }

  // Previous enter handler's (e.g. EnterBetweenBracesHandler) can introduce a mismatch
  // between the editor's caret model and the offset we've been provided with.
  editor.getCaretModel().moveToOffset(offset);

  Document doc = editor.getDocument();
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);

  // #api173: get file, language specific settings instead
  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject());
  Integer indent = determineIndent(file, editor, offset, settings);
  if (indent == null) {
    return Result.Continue;
  }

  removeTrailingWhitespace(doc, file, offset);
  originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
  LogicalPosition position = editor.getCaretModel().getLogicalPosition();
  if (position.column == indent) {
    return Result.Stop;
  }
  if (position.column > indent) {
    // default enter handler has added too many spaces -- remove them
    int excess = position.column - indent;
    doc.deleteString(
        editor.getCaretModel().getOffset() - excess, editor.getCaretModel().getOffset());
  } else if (position.column < indent) {
    String spaces = StringUtil.repeatSymbol(' ', indent - position.column);
    doc.insertString(editor.getCaretModel().getOffset(), spaces);
  }
  editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(position.line, indent));
  return Result.Stop;
}
 
Example 16
Source File: FileHistoryPanelImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public String getPreferredStringValue() {
  return StringUtil.repeatSymbol('m', 10);
}
 
Example 17
Source File: FileStatusMap.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void log(@NonNls @Nonnull Object... info) {
  if (LOG.isDebugEnabled()) {
    String s = StringUtil.repeatSymbol(' ', getThreadNum() * 4) + Arrays.asList(info) + "\n";
    LOG.debug(s);
  }
}
 
Example 18
Source File: FileHistoryPanelImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@NonNls
public String getPreferredStringValue() {
  return StringUtil.repeatSymbol('m', 14);
}
 
Example 19
Source File: ConvertIndentsActionBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public String buildIndent(int length, int tabSize) {
  return StringUtil.repeatSymbol(' ', length);
}
 
Example 20
Source File: DebugUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void lightTreeToBuffer(@Nonnull final FlyweightCapableTreeStructure<LighterASTNode> tree,
                                     @Nonnull final LighterASTNode node,
                                     @Nonnull final Appendable buffer,
                                     final int indent,
                                     final boolean skipWhiteSpaces) {
  final IElementType tokenType = node.getTokenType();
  if (skipWhiteSpaces && tokenType == TokenType.WHITE_SPACE) return;

  final boolean isLeaf = (node instanceof LighterASTTokenNode);

  StringUtil.repeatSymbol(buffer, ' ', indent);
  try {
    if (tokenType == TokenType.ERROR_ELEMENT) {
      buffer.append("PsiErrorElement:").append(PsiBuilderImpl.getErrorMessage(node));
    }
    else if (tokenType == TokenType.WHITE_SPACE) {
      buffer.append("PsiWhiteSpace");
    }
    else {
      buffer.append(isLeaf ? "PsiElement" : "Element").append('(').append(tokenType.toString()).append(')');
    }

    if (isLeaf) {
      final String text = ((LighterASTTokenNode)node).getText().toString();
      buffer.append("('").append(fixWhiteSpaces(text)).append("')");
    }
    buffer.append('\n');

    if (!isLeaf) {
      final Ref<LighterASTNode[]> kids = new Ref<LighterASTNode[]>();
      final int numKids = tree.getChildren(tree.prepareForGetChildren(node), kids);
      if (numKids == 0) {
        StringUtil.repeatSymbol(buffer, ' ', indent + 2);
        buffer.append("<empty list>\n");
      }
      else {
        for (int i = 0; i < numKids; i++) {
          lightTreeToBuffer(tree, kids.get()[i], buffer, indent + 2, skipWhiteSpaces);
        }
      }
    }
  }
  catch (IOException e) {
    LOG.error(e);
  }
}