com.intellij.application.options.CodeStyle Java Examples

The following examples show how to use com.intellij.application.options.CodeStyle. 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: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent e) {
  final Document document = e.getDocument();
  if (!ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.ExternalDocumentChange.class)) {
    myUnsavedDocuments.add(document);
  }
  final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand();
  Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject();
  if (project == null) project = ProjectUtil.guessProjectForFile(getFile(document));
  String lineSeparator = CodeStyle.getProjectOrDefaultSettings(project).getLineSeparator();
  document.putUserData(LINE_SEPARATOR_KEY, lineSeparator);

  // avoid documents piling up during batch processing
  if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) {
    saveAllDocumentsLater();
  }
}
 
Example #2
Source File: IndentCalculator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
String getIndentString(@Nullable Language language, @Nonnull SemanticEditorPosition currPosition) {
  String baseIndent = getBaseIndent(currPosition);
  Document document = myEditor.getDocument();
  PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
  if (file != null) {
    CommonCodeStyleSettings.IndentOptions fileOptions = CodeStyle.getIndentOptions(file);
    CommonCodeStyleSettings.IndentOptions options =
            !fileOptions.isOverrideLanguageOptions() && language != null && !(language.is(file.getLanguage()) || language.is(Language.ANY)) ? CodeStyle.getLanguageSettings(file, language)
                    .getIndentOptions() : fileOptions;
    if (options != null) {
      return baseIndent + new IndentInfo(0, indentToSize(myIndent, options), 0, false).generateNewWhiteSpace(options);
    }
  }
  return null;
}
 
Example #3
Source File: CommentByLineCommentHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private IndentData computeMinIndent(Editor editor, PsiFile psiFile, int line1, int line2) {
  Document document = editor.getDocument();
  IndentData minIndent = CommentUtil.getMinLineIndent(document, line1, line2, psiFile);
  if (line1 > 0) {
    int commentOffset = getCommentStart(editor, psiFile, line1 - 1);
    if (commentOffset >= 0) {
      int lineStart = document.getLineStartOffset(line1 - 1);
      IndentData indent = IndentData.createFrom(document.getCharsSequence(), lineStart, commentOffset, CodeStyle.getIndentOptions(psiFile).TAB_SIZE);
      minIndent = IndentData.min(minIndent, indent);
    }
  }
  if (minIndent == null) {
    minIndent = new IndentData(0);
  }
  return minIndent;
}
 
Example #4
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 #5
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 #6
Source File: CommentUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static IndentData getMinLineIndent(Document document, int line1, int line2, @Nonnull PsiFile file) {
  CharSequence chars = document.getCharsSequence();
  IndentData minIndent = null;
  for (int line = line1; line <= line2; line++) {
    int lineStart = document.getLineStartOffset(line);
    int textStart = CharArrayUtil.shiftForward(chars, lineStart, " \t");
    if (textStart >= document.getTextLength()) {
      textStart = document.getTextLength();
    }
    else {
      char c = chars.charAt(textStart);
      if (c == '\n' || c == '\r') continue; // empty line
    }
    IndentData indent = IndentData.createFrom(chars, lineStart, textStart, CodeStyle.getIndentOptions(file).TAB_SIZE);
    minIndent = IndentData.min(minIndent, indent);
  }
  if (minIndent == null && line1 == line2 && line1 < document.getLineCount() - 1) {
    return getMinLineIndent(document, line1 + 1, line1 + 1, file);
  }
  return minIndent;
}
 
Example #7
Source File: SimpleCodeInsightTest.java    From intellij-sdk-docs with Apache License 2.0 5 votes vote down vote up
public void testFormatter() {
  myFixture.configureByFile("FormatterTestData.simple");
  CodeStyle.getLanguageSettings(myFixture.getFile()).SPACE_AROUND_ASSIGNMENT_OPERATORS = true;
  CodeStyle.getLanguageSettings(myFixture.getFile()).KEEP_BLANK_LINES_IN_CODE = 2;
  WriteCommandAction.writeCommandAction(getProject()).run(() ->
          CodeStyleManager.getInstance(getProject()).reformatText(
                  myFixture.getFile(),
                  ContainerUtil.newArrayList(myFixture.getFile().getTextRange())
          )
  );
  myFixture.checkResultByFile("DefaultTestData.simple");
}
 
Example #8
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 #9
Source File: JavaLikeLangLineIndentProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Contract("_, null -> null")
private static Type getBlockIndentType(@Nonnull Editor editor, @Nullable Language language) {
  if (language != null) {
    CommonCodeStyleSettings settings = CodeStyle.getSettings(editor).getCommonSettings(language);
    if (settings.BRACE_STYLE == CommonCodeStyleSettings.NEXT_LINE || settings.BRACE_STYLE == CommonCodeStyleSettings.END_OF_LINE) {
      return NONE;
    }
  }
  return null;
}
 
Example #10
Source File: JavaLikeLangLineIndentProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
protected Indent getIndentInBlock(@Nonnull Project project, @Nullable Language language, @Nonnull SemanticEditorPosition blockStartPosition) {
  if (language != null) {
    CommonCodeStyleSettings settings = CodeStyle.getSettings(blockStartPosition.getEditor()).getCommonSettings(language);
    if (settings.BRACE_STYLE == CommonCodeStyleSettings.NEXT_LINE_SHIFTED) {
      return getDefaultIndentFromType(settings.METHOD_BRACE_STYLE == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ? NONE : null);
    }
  }
  return getDefaultIndentFromType(NORMAL);
}
 
Example #11
Source File: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public DocCommentSettings getDocCommentSettings(@Nonnull PsiFile file) {
  Language language = file.getLanguage();
  LanguageCodeStyleSettingsProvider settingsProvider = LanguageCodeStyleSettingsProvider.forLanguage(language);
  if (settingsProvider != null) {
    return settingsProvider.getDocCommentSettings(CodeStyle.getSettings(file));
  }
  return DocCommentSettings.DEFAULTS;
}
 
Example #12
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 #13
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 #14
Source File: FixDocCommentAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void reformatCommentKeepingEmptyTags(@Nonnull PsiFile file, @Nonnull Project project, int start, int end) {
  CodeStyleSettings tempSettings = CodeStyle.getSettings(file).clone();
  LanguageCodeStyleSettingsProvider langProvider = LanguageCodeStyleSettingsProvider.forLanguage(file.getLanguage());
  if (langProvider != null) {
    DocCommentSettings docCommentSettings = langProvider.getDocCommentSettings(tempSettings);
    docCommentSettings.setRemoveEmptyTags(false);
  }
  CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
  CodeStyle.doWithTemporarySettings(project, tempSettings, () -> codeStyleManager.reformatText(file, start, end));
}
 
Example #15
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 #16
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public String getLineSeparator(@Nullable VirtualFile file, @Nullable Project project) {
  String lineSeparator = file == null ? null : LoadTextUtil.getDetectedLineSeparator(file);
  if (lineSeparator == null) {
    lineSeparator = CodeStyle.getProjectOrDefaultSettings(project).getLineSeparator();
  }
  return lineSeparator;
}
 
Example #17
Source File: SettingsImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<Integer> getSoftMargins() {
  if (mySoftMargins != null) return mySoftMargins;
  return
          myEditor == null ?
          CodeStyle.getDefaultSettings().getSoftMargins(myLanguage) :
          CodeStyle.getSettings(myEditor).getSoftMargins(myLanguage);
}
 
Example #18
Source File: SearchableOptionsRegistrarImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Set<String>> findPossibleExtension(@Nonnull String prefix, final Project project) {
  loadHugeFilesIfNecessary();
  final boolean perProject = CodeStyle.usesOwnSettings(project);
  final Map<String, Set<String>> result = new THashMap<>();
  int count = 0;
  final Set<String> prefixes = getProcessedWordsWithoutStemming(prefix);
  for (String opt : prefixes) {
    Set<OptionDescription> configs = getAcceptableDescriptions(opt);
    if (configs == null) continue;
    for (OptionDescription description : configs) {
      String groupName = myId2Name.get(description.getConfigurableId());
      if (perProject) {
        if (Comparing.strEqual(groupName, ApplicationBundle.message("title.global.code.style"))) {
          groupName = ApplicationBundle.message("title.project.code.style");
        }
      }
      else {
        if (Comparing.strEqual(groupName, ApplicationBundle.message("title.project.code.style"))) {
          groupName = ApplicationBundle.message("title.global.code.style");
        }
      }
      Set<String> foundHits = result.get(groupName);
      if (foundHits == null) {
        foundHits = new THashSet<>();
        result.put(groupName, foundHits);
      }
      foundHits.add(description.getHit());
      count++;
    }
  }
  if (count > LOAD_FACTOR) {
    result.clear();
  }
  return result;
}
 
Example #19
Source File: CommentByLineCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void doIndentCommenting(final Block block) {
  final Document document = block.editor.getDocument();
  final CharSequence chars = document.getCharsSequence();
  final IndentData minIndent = computeMinIndent(block.editor, block.psiFile, block.startLine, block.endLine);
  final CommonCodeStyleSettings.IndentOptions indentOptions = CodeStyle.getIndentOptions(block.psiFile);

  DocumentUtil.executeInBulk(document, block.endLine - block.startLine > Registry.intValue("comment.by.line.bulk.lines.trigger"), () -> {
    for (int line = block.endLine; line >= block.startLine; line--) {
      int lineStart = document.getLineStartOffset(line);
      int offset = lineStart;
      final StringBuilder buffer = new StringBuilder();
      while (true) {
        IndentData indent = IndentData.createFrom(buffer, 0, buffer.length(), indentOptions.TAB_SIZE);
        if (indent.getTotalSpaces() >= minIndent.getTotalSpaces()) break;
        char c = chars.charAt(offset);
        if (c != ' ' && c != '\t') {
          String newSpace = minIndent.createIndentInfo().generateNewWhiteSpace(indentOptions);
          document.replaceString(lineStart, offset, newSpace);
          offset = lineStart + newSpace.length();
          break;
        }
        buffer.append(c);
        offset++;
      }
      commentLine(block, line, offset);
    }
  });
}
 
Example #20
Source File: PostprocessReformattingAspect.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void adjustIndentationInRange(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull TextRange[] indents, final int indentAdjustment) {
  final CharSequence charsSequence = document.getCharsSequence();
  for (final TextRange indent : indents) {
    final String oldIndentStr = charsSequence.subSequence(indent.getStartOffset() + 1, indent.getEndOffset()).toString();
    final int oldIndent = IndentHelperImpl.getIndent(file, oldIndentStr, true);
    final String newIndentStr = IndentHelperImpl.fillIndent(CodeStyle.getIndentOptions(file), Math.max(oldIndent + indentAdjustment, 0));
    document.replaceString(indent.getStartOffset() + 1, indent.getEndOffset(), newIndentStr);
  }
}
 
Example #21
Source File: IndentHelperImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @Depreacted Do not use the implementation, see {@link IndentHelper}
 */
@Deprecated
public static int getIndent(Project project, FileType fileType, String text, boolean includeNonSpace) {
  return getIndent(CodeStyle.getSettings(project).getIndentOptions(fileType), text, includeNonSpace);
}
 
Example #22
Source File: IndentHelperImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int getIndent(@Nonnull PsiFile file, String text, boolean includeNonSpace) {
  return getIndent(CodeStyle.getIndentOptions(file), text, includeNonSpace);
}
 
Example #23
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 #24
Source File: IndentHelperImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated Use {@link #fillIndent(CommonCodeStyleSettings.IndentOptions, int)} instead.
 */
@Deprecated
public static String fillIndent(Project project, FileType fileType, int indent) {
  return fillIndent(CodeStyle.getProjectOrDefaultSettings(project).getIndentOptions(fileType), indent);
}
 
Example #25
Source File: CodeStyleFacadeImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean useTabCharacter(final FileType fileType) {
  return CodeStyle.getProjectOrDefaultSettings(myProject).useTabCharacter(fileType);
}
 
Example #26
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 #27
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 #28
Source File: CompletionStyleUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static CommonCodeStyleSettings getCodeStyleSettings(@Nonnull InsertionContext context) {
  Language lang = PsiUtilCore.getLanguageAtOffset(context.getFile(), context.getTailOffset());
  return CodeStyle.getLanguageSettings(context.getFile(), lang);
}
 
Example #29
Source File: CodeStyleFacadeImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int getTabSize(final FileType fileType) {
  return CodeStyle.getProjectOrDefaultSettings(myProject).getTabSize(fileType);
}
 
Example #30
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;
}