Java Code Examples for com.intellij.application.options.CodeStyle#getSettings()

The following examples show how to use com.intellij.application.options.CodeStyle#getSettings() . 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: JoinLinesHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int[] getSpacesToAdd(List<RangeMarker> markers) {
  int size = markers.size();
  int[] spacesToAdd = new int[size];
  Arrays.fill(spacesToAdd, -1);
  CharSequence text = myDoc.getCharsSequence();
  FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(myFile);
  CodeStyleSettings settings = CodeStyle.getSettings(myFile);
  FormattingModel model = builder == null ? null : builder.createModel(myFile, settings);
  FormatterEx formatter = FormatterEx.getInstance();
  for (int i = 0; i < size; i++) {
    myIndicator.checkCanceled();
    myIndicator.setFraction(0.7 + 0.25 * i / size);
    RangeMarker marker = markers.get(i);
    if (!marker.isValid()) continue;
    int end = StringUtil.skipWhitespaceForward(text, marker.getStartOffset());
    int spacesToCreate = end >= text.length() || text.charAt(end) == '\n' ? 0 : model == null ? 1 : formatter.getSpacingForBlockAtOffset(model, end);
    spacesToAdd[i] = spacesToCreate < 0 ? 1 : spacesToCreate;
  }
  return spacesToAdd;
}
 
Example 2
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String fillIndent(Indent indent, FileType fileType) {
  IndentImpl indent1 = (IndentImpl)indent;
  int indentLevel = indent1.getIndentLevel();
  int spaceCount = indent1.getSpaceCount();
  final CodeStyleSettings settings = CodeStyle.getSettings(myProject);
  if (indentLevel < 0) {
    spaceCount += indentLevel * settings.getIndentSize(fileType);
    indentLevel = 0;
    if (spaceCount < 0) {
      spaceCount = 0;
    }
  }
  else {
    if (spaceCount < 0) {
      int v = (-spaceCount + settings.getIndentSize(fileType) - 1) / settings.getIndentSize(fileType);
      indentLevel -= v;
      spaceCount += v * settings.getIndentSize(fileType);
      if (indentLevel < 0) {
        indentLevel = 0;
      }
    }
  }
  return IndentHelperImpl.fillIndent(myProject, fileType, indentLevel * IndentHelperImpl.INDENT_FACTOR + spaceCount);
}
 
Example 3
Source File: FormatterTest.java    From protobuf-jetbrains-plugin with Apache License 2.0 5 votes vote down vote up
private void run(String test, Consumer<CommonCodeStyleSettings> settings) {
    myFixture.configureByFiles(test + "/Source.proto");
    CodeStyleSettings codeStyleSettings = CodeStyle.getSettings(getProject());
    CommonCodeStyleSettings protoSettings = codeStyleSettings.getCommonSettings(ProtoLanguage.INSTANCE);
    settings.accept(protoSettings);
    WriteCommandAction.writeCommandAction(getProject())
            .run(() -> CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile()));
    myFixture.checkResultByFile(test + "/Expected.proto");
}
 
Example 4
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Indent getIndent(String text, FileType fileType) {
  int indent = IndentHelperImpl.getIndent(CodeStyle.getSettings(myProject).getIndentOptions(fileType), text, true);
  int indentLevel = indent / IndentHelperImpl.INDENT_FACTOR;
  int spaceCount = indent - indentLevel * IndentHelperImpl.INDENT_FACTOR;
  return new IndentImpl(CodeStyle.getSettings(myProject), indentLevel, spaceCount, fileType);
}
 
Example 5
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static FormattingModel createFormattingModel(@Nonnull PsiFile file) {
  FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file);
  if (builder == null) return null;
  CodeStyleSettings settings = CodeStyle.getSettings(file);
  return builder.createModel(file, settings);
}
 
Example 6
Source File: ExcludedFileFormattingRestriction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isFormatterAllowed(@Nonnull PsiElement context) {
  try {
    PsiFile file = context.getContainingFile();
    CodeStyleSettings settings = CodeStyle.getSettings(file);
    return !settings.getExcludedFiles().contains(file);
  }
  catch (PsiInvalidElementAccessException e) {
    return false;
  }
}
 
Example 7
Source File: CodeFormatterFacade.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Inspects all lines of the given document and wraps all of them that exceed {@link CodeStyleSettings#getRightMargin(Language)}
 * right margin}.
 * <p/>
 * I.e. the algorithm is to do the following for every line:
 * <p/>
 * <pre>
 * <ol>
 *   <li>
 *      Check if the line exceeds {@link CodeStyleSettings#getRightMargin(Language)}  right margin}. Go to the next line in the case of
 *      negative answer;
 *   </li>
 *   <li>Determine line wrap position; </li>
 *   <li>
 *      Perform 'smart wrap', i.e. not only wrap the line but insert additional characters over than line feed if necessary.
 *      For example consider that we wrap a single-line comment - we need to insert comment symbols on a start of the wrapped
 *      part as well. Generally, we get the same behavior as during pressing 'Enter' at wrap position during editing document;
 *   </li>
 * </ol>
 * </pre>
 *
 * @param file        file that holds parsed document tree
 * @param document    target document
 * @param startOffset start offset of the first line to check for wrapping (inclusive)
 * @param endOffset   end offset of the first line to check for wrapping (exclusive)
 */
private void wrapLongLinesIfNecessary(@Nonnull final PsiFile file, @Nullable final Document document, final int startOffset, final int endOffset) {
  if (!mySettings.getCommonSettings(file.getLanguage()).WRAP_LONG_LINES ||
      PostprocessReformattingAspect.getInstance(file.getProject()).isViewProviderLocked(file.getViewProvider()) ||
      document == null) {
    return;
  }

  FormatterTagHandler formatterTagHandler = new FormatterTagHandler(CodeStyle.getSettings(file));
  List<TextRange> enabledRanges = formatterTagHandler.getEnabledRanges(file.getNode(), new TextRange(startOffset, endOffset));

  final VirtualFile vFile = FileDocumentManager.getInstance().getFile(document);
  if ((vFile == null || vFile instanceof LightVirtualFile) && !ApplicationManager.getApplication().isUnitTestMode()) {
    // we assume that control flow reaches this place when the document is backed by a "virtual" file so any changes made by
    // a formatter affect only PSI and it is out of sync with a document text
    return;
  }

  Editor editor = PsiUtilBase.findEditor(file);
  EditorFactory editorFactory = null;
  if (editor == null) {
    if (!ApplicationManager.getApplication().isDispatchThread()) {
      return;
    }
    editorFactory = EditorFactory.getInstance();
    editor = editorFactory.createEditor(document, file.getProject(), file.getVirtualFile(), false);
  }
  try {
    final Editor editorToUse = editor;
    ApplicationManager.getApplication().runWriteAction(() -> {
      final CaretModel caretModel = editorToUse.getCaretModel();
      final int caretOffset = caretModel.getOffset();
      final RangeMarker caretMarker = editorToUse.getDocument().createRangeMarker(caretOffset, caretOffset);
      doWrapLongLinesIfNecessary(editorToUse, file.getProject(), editorToUse.getDocument(), startOffset, endOffset, enabledRanges);
      if (caretMarker.isValid() && caretModel.getOffset() != caretMarker.getStartOffset()) {
        caretModel.moveToOffset(caretMarker.getStartOffset());
      }
    });
  }
  finally {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());
    if (documentManager.isUncommited(document)) documentManager.commitDocument(document);
    if (editorFactory != null) {
      editorFactory.releaseEditor(editor);
    }
  }
}
 
Example 8
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Indent zeroIndent() {
  return new IndentImpl(CodeStyle.getSettings(myProject), 0, 0, null);
}
 
Example 9
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static CodeStyleSettings getSettings(@Nonnull PsiFile file) {
  return CodeStyle.getSettings(file);
}
 
Example 10
Source File: CodeStyleManagerRunnable.java    From consulo with Apache License 2.0 4 votes vote down vote up
public T perform(PsiFile file, int offset, @Nullable TextRange range, T defaultValue) {
  if (file instanceof PsiCompiledFile) {
    file = ((PsiCompiledFile)file).getDecompiledPsiFile();
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myCodeStyleManager.getProject());
  Document document = documentManager.getDocument(file);
  if (document instanceof DocumentWindow) {
    final DocumentWindow documentWindow = (DocumentWindow)document;
    final PsiFile topLevelFile = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    if (!file.equals(topLevelFile)) {
      if (range != null) {
        range = documentWindow.injectedToHost(range);
      }
      if (offset != -1) {
        offset = documentWindow.injectedToHost(offset);
      }
      return adjustResultForInjected(perform(topLevelFile, offset, range, defaultValue), documentWindow);
    }
  }

  final PsiFile templateFile = PsiUtilCore.getTemplateLanguageFile(file);
  if (templateFile != null) {
    file = templateFile;
    document = documentManager.getDocument(templateFile);
  }

  PsiElement element = null;
  if (offset != -1) {
    element = CodeStyleManagerImpl.findElementInTreeWithFormatterEnabled(file, offset);
    if (element == null && offset != file.getTextLength()) {
      return defaultValue;
    }
    if (isInsidePlainComment(offset, element)) {
      return computeValueInsidePlainComment(file, offset, defaultValue);
    }
  }

  final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file);
  FormattingModelBuilder elementBuilder = element != null ? LanguageFormatting.INSTANCE.forContext(element) : builder;
  if (builder != null && elementBuilder != null) {
    mySettings = CodeStyle.getSettings(file);

    mySignificantRange = offset != -1 ? getSignificantRange(file, offset) : null;
    myIndentOptions = mySettings.getIndentOptionsByFile(file, mySignificantRange);

    FormattingMode currentMode = myCodeStyleManager.getCurrentFormattingMode();
    myCodeStyleManager.setCurrentFormattingMode(myMode);
    try {
      myModel = buildModel(builder, file, document);
      T result = doPerform(offset, range);
      if (result != null) {
        return result;
      }
    }
    finally {
      myCodeStyleManager.setCurrentFormattingMode(currentMode);
    }
  }
  return defaultValue;
}