Java Code Examples for com.intellij.psi.codeStyle.CodeStyleSettingsManager#getSettings()

The following examples show how to use com.intellij.psi.codeStyle.CodeStyleSettingsManager#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: TextPainter.java    From consulo with Apache License 2.0 6 votes vote down vote up
public TextPainter(DocumentEx editorDocument,
                   EditorHighlighter highlighter,
                   String fileName,
                   final Project project,
                   final FileType fileType, final List<LineMarkerInfo> separators) {
  myCodeStyleSettings = CodeStyleSettingsManager.getSettings(project);
  myDocument = editorDocument;
  myPrintSettings = PrintSettings.getInstance();
  String fontName = myPrintSettings.FONT_NAME;
  int fontSize = myPrintSettings.FONT_SIZE;
  myPlainFont = new Font(fontName, Font.PLAIN, fontSize);
  myBoldFont = new Font(fontName, Font.BOLD, fontSize);
  myItalicFont = new Font(fontName, Font.ITALIC, fontSize);
  myBoldItalicFont = new Font(fontName, Font.BOLD | Font.ITALIC, fontSize);
  myHighlighter = highlighter;
  myHeaderFont = new Font(myPrintSettings.FOOTER_HEADER_FONT_NAME, Font.PLAIN,
                          myPrintSettings.FOOTER_HEADER_FONT_SIZE);
  myFileName = fileName;
  mySegmentEnd = myDocument.getTextLength();
  myFileType = fileType;
  myMethodSeparators = separators != null ? separators.toArray(new LineMarkerInfo[separators.size()]) : new LineMarkerInfo[0];
  myCurrentMethodSeparator = 0;
}
 
Example 2
Source File: CypherFormattingTest.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
public void ignoreNestedWhereOnNewLineAndIndented() {
    CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject());

    settings.setDefaultRightMargin(26);

    doTest("return [x in range(0,10) where x + 2 = 0 | x^3] as result",
            "RETURN [x IN range(0, 10)\n" +
            "         WHERE x + 2 = 0 | x ^ 3]\n" +
            "       AS result");
}
 
Example 3
Source File: BaseIndentEnterHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected String getNewIndent(
        @Nonnull final PsiFile file,
        @Nonnull final Document document,
        @Nonnull final CharSequence oldIndent)
{
  CharSequence nonEmptyIndent = oldIndent;
  final CharSequence editorCharSequence = document.getCharsSequence();
  final int nLines = document.getLineCount();
  for (int line = 0; line < nLines && nonEmptyIndent.length() == 0; ++line) {
    final int lineStart = document.getLineStartOffset(line);
    final int indentEnd = EditorActionUtil.findFirstNonSpaceOffsetOnTheLine(document, line);
    if (lineStart < indentEnd) {
      nonEmptyIndent = editorCharSequence.subSequence(lineStart, indentEnd);
    }
  }

  final boolean usesSpacesForIndentation = nonEmptyIndent.length() > 0 && nonEmptyIndent.charAt(nonEmptyIndent.length() - 1) == ' ';
  final boolean firstIndent = nonEmptyIndent.length() == 0;

  final CodeStyleSettings currentSettings = CodeStyleSettingsManager.getSettings(file.getProject());
  final CommonCodeStyleSettings.IndentOptions indentOptions = currentSettings.getIndentOptions(file.getFileType());
  if (firstIndent && indentOptions.USE_TAB_CHARACTER || !firstIndent && !usesSpacesForIndentation) {
    int nTabsToIndent = indentOptions.INDENT_SIZE / indentOptions.TAB_SIZE;
    if (indentOptions.INDENT_SIZE % indentOptions.TAB_SIZE != 0) {
      ++nTabsToIndent;
    }
    return oldIndent + StringUtil.repeatSymbol('\t', nTabsToIndent);
  }
  return oldIndent + StringUtil.repeatSymbol(' ', indentOptions.INDENT_SIZE);
}
 
Example 4
Source File: CppFormattingModelBuilder.java    From CppTools with Apache License 2.0 5 votes vote down vote up
@Nullable
public Spacing getSpacing(Block block, Block block1) {
  final IElementType type = ((CppBlock) block).myNode.getElementType();
  final IElementType type2 = ((CppBlock) block1).myNode.getElementType();
  if (type == CppTokenTypes.LBRACE || type2 == CppTokenTypes.RBRACE) {
    CodeStyleSettings mySettings = CodeStyleSettingsManager.getSettings((myNode.getPsi().getProject()));
    return Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
  }
  return null;
}
 
Example 5
Source File: FormattingDocumentModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FormattingDocumentModelImpl(@Nonnull final Document document, PsiFile file) {
  myDocument = document;
  myFile = file;
  if (file != null) {
    Language language = file.getLanguage();
    myWhiteSpaceStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(language);
  }
  else {
    myWhiteSpaceStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy();
  }
  mySettings = CodeStyleSettingsManager.getSettings(file != null ? file.getProject() : null);
}
 
Example 6
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 7
Source File: HaxeFormatterTest.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void setTestStyleSettings() {
  Project project = getProject();
  CodeStyleSettings currSettings = CodeStyleSettingsManager.getSettings(project);
  assertNotNull(currSettings);
  CodeStyleSettings tempSettings = currSettings.clone();
  CodeStyleSettings.IndentOptions indentOptions = tempSettings.getIndentOptions(HaxeFileType.HAXE_FILE_TYPE);
  assertNotNull(indentOptions);
  defineStyleSettings(tempSettings);
  CodeStyleSettingsManager.getInstance(project).setTemporarySettings(tempSettings);
}
 
Example 8
Source File: BashFormatterTestCase.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
protected void setSettings(Project project) {
    Assert.assertNull(myTempSettings);
    CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project);
    myTempSettings = settings.clone();

    CodeStyleSettings.IndentOptions gr = myTempSettings.getIndentOptions(BashFileType.BASH_FILE_TYPE);
    Assert.assertNotSame(gr, settings.OTHER_INDENT_OPTIONS);
    gr.INDENT_SIZE = 2;
    gr.CONTINUATION_INDENT_SIZE = 4;
    gr.TAB_SIZE = 2;
    myTempSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 3;

    CodeStyleSettingsManager.getInstance(project).setTemporarySettings(myTempSettings);
}
 
Example 9
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;
  }
}
 
Example 10
Source File: JSGraphQLCodeInsightTest.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Test
public void testFormatter() {
    myFixture.configureByFiles("FormatterTestData.graphql");
    CodeStyleSettingsManager.getSettings(getProject()).KEEP_BLANK_LINES_IN_CODE = 2;
    new WriteCommandAction.Simple(getProject()) {
        @Override
        protected void run() throws Throwable {
            CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
        }
    }.execute();
    myFixture.checkResultByFile("FormatterExpectedResult.graphql");
}
 
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: LightPlatformTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected CodeStyleSettings getCurrentCodeStyleSettings() {
  if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings();
  return CodeStyleSettingsManager.getSettings(getProject());
}
 
Example 13
Source File: LightIdeaTestFixtureImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected CodeStyleSettings getCurrentCodeStyleSettings() {
  if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings();
  return CodeStyleSettingsManager.getSettings(getProject());
}
 
Example 14
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected CodeStyleSettings getCurrentCodeStyleSettings() {
  if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings();
  return CodeStyleSettingsManager.getSettings(getProject());
}
 
Example 15
Source File: FormatterTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected CodeStyleSettings getSettings() {
  return CodeStyleSettingsManager.getSettings(getProject());
}
 
Example 16
Source File: TabAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void insertTabAtCaret(Editor editor, @Nonnull Caret caret, @Nullable Project project) {
  EditorUIUtil.hideCursorInEditor(editor);
  int columnNumber;
  if (caret.hasSelection()) {
    columnNumber = editor.visualToLogicalPosition(caret.getSelectionStartPosition()).column;
  }
  else {
    columnNumber = editor.getCaretModel().getLogicalPosition().column;
  }

  CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project);

  final Document doc = editor.getDocument();
  CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptionsByDocument(project, doc);

  int tabSize = indentOptions.INDENT_SIZE;
  int spacesToAddCount = tabSize - columnNumber % Math.max(1,tabSize);

  boolean useTab = editor.getSettings().isUseTabCharacter(project);

  CharSequence chars = doc.getCharsSequence();
  if (useTab && indentOptions.SMART_TABS) {
    int offset = editor.getCaretModel().getOffset();
    while (offset > 0) {
      offset--;
      if (chars.charAt(offset) == '\t') continue;
      if (chars.charAt(offset) == '\n') break;
      useTab = false;
      break;
    }
  }

  doc.startGuardedBlockChecking();
  try {
    EditorModificationUtil.insertStringAtCaret(editor, useTab ? "\t" : StringUtil.repeatSymbol(' ', spacesToAddCount), false, true);
  }
  catch (ReadOnlyFragmentModificationException e) {
    EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e);
  }
  finally {
    doc.stopGuardedBlockChecking();
  }
}
 
Example 17
Source File: TailType.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected boolean isSpaceAroundAssignmentOperators(Editor editor, int tailOffset) {
  return CodeStyleSettingsManager.getSettings(editor.getProject()).SPACE_AROUND_ASSIGNMENT_OPERATORS;
}
 
Example 18
Source File: EnterBetweenBracesHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(@Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull final Ref<Integer> caretOffsetRef, @Nonnull final Ref<Integer> caretAdvance,
                              @Nonnull final DataContext dataContext, final EditorActionHandler originalHandler) {
  Document document = editor.getDocument();
  CharSequence text = document.getCharsSequence();
  int caretOffset = caretOffsetRef.get().intValue();
  if (!CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) {
    return Result.Continue;
  }

  int prevCharOffset = CharArrayUtil.shiftBackward(text, caretOffset - 1, " \t");
  int nextCharOffset = CharArrayUtil.shiftForward(text, caretOffset, " \t");

  if (!isValidOffset(prevCharOffset, text) || !isValidOffset(nextCharOffset, text) ||
      !isBracePair(text.charAt(prevCharOffset), text.charAt(nextCharOffset))) {
    return Result.Continue;
  }

  PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
  if (file.findElementAt(prevCharOffset) == file.findElementAt(nextCharOffset)) {
    return Result.Continue;
  }

  final int line = document.getLineNumber(caretOffset);
  final int start = document.getLineStartOffset(line);
  final CodeDocumentationUtil.CommentContext commentContext =
          CodeDocumentationUtil.tryParseCommentContext(file, text, caretOffset, start);

  // special case: enter inside "()" or "{}"
  String indentInsideJavadoc = isInComment(caretOffset, file) && commentContext.docAsterisk
                               ? CodeDocumentationUtil.getIndentInsideJavadoc(document, caretOffset)
                               : null;

  originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);

  Project project = editor.getProject();
  if (indentInsideJavadoc != null && project != null && CodeStyleSettingsManager.getSettings(project).JD_LEADING_ASTERISKS_ARE_ENABLED) {
    document.insertString(editor.getCaretModel().getOffset(), "*" + indentInsideJavadoc);
  }

  PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);
  try {
    CodeStyleManager.getInstance(file.getProject()).adjustLineIndent(file, editor.getCaretModel().getOffset());
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
  return indentInsideJavadoc == null ? Result.Continue : Result.DefaultForceIndent;
}
 
Example 19
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 20
Source File: EnterAfterJavadocTagHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(@Nonnull PsiFile file,
                              @Nonnull Editor editor,
                              @Nonnull Ref<Integer> caretOffset,
                              @Nonnull Ref<Integer> caretAdvance,
                              @Nonnull DataContext dataContext,
                              EditorActionHandler originalHandler) {
  if (!CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) {
    return Result.Continue;
  }

  Document document = editor.getDocument();
  CharSequence text = document.getCharsSequence();
  int line = document.getLineNumber(caretOffset.get());
  int start = document.getLineStartOffset(line);
  int end = document.getLineEndOffset(line);

  CodeDocumentationUtil.CommentContext commentContext = CodeDocumentationUtil.tryParseCommentContext(file, text, caretOffset.get(), start);
  if (!commentContext.docAsterisk) {
    return Result.Continue;
  }

  Context context = parse(text, start, end, caretOffset.get());
  if (!context.shouldGenerateLine()) {
    return context.shouldIndent() ? Result.DefaultForceIndent : Result.Continue;
  }

  String indentInsideJavadoc = CodeDocumentationUtil.getIndentInsideJavadoc(document, caretOffset.get());

  boolean restoreCaret = false;
  if (caretOffset.get() != context.endTagStartOffset) {
    editor.getCaretModel().moveToOffset(context.endTagStartOffset);
    restoreCaret = true;
  }

  originalHandler.execute(editor, dataContext);
  Project project = editor.getProject();
  if (indentInsideJavadoc != null && project != null && CodeStyleSettingsManager.getSettings(project).JD_LEADING_ASTERISKS_ARE_ENABLED) {
    document.insertString(editor.getCaretModel().getOffset(), "*" + indentInsideJavadoc);
  }

  if (restoreCaret) {
    editor.getCaretModel().moveToOffset(caretOffset.get());
  }

  return Result.DefaultForceIndent;
}