下面列出了怎么用com.intellij.psi.codeStyle.CodeStyleSettingsManager的API类实例代码及写法,或者点击链接到github查看源代码。
private void initCsvCodeStyleSettings(boolean SPACE_BEFORE_SEPARATOR,
boolean SPACE_AFTER_SEPARATOR,
boolean TRIM_LEADING_WHITE_SPACES,
boolean TRIM_TRAILING_WHITE_SPACES,
boolean TABULARIZE,
boolean WHITE_SPACES_OUTSIDE_QUOTES,
boolean LEADING_WHITE_SPACES,
boolean ENABLE_WIDE_CHARACTER_DETECTION,
boolean TREAT_AMBIGUOUS_CHARACTERS_AS_WIDE) {
CsvCodeStyleSettings csvCodeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).getCustomSettings(CsvCodeStyleSettings.class);
csvCodeStyleSettings.SPACE_BEFORE_SEPARATOR = SPACE_BEFORE_SEPARATOR;
csvCodeStyleSettings.SPACE_AFTER_SEPARATOR = SPACE_AFTER_SEPARATOR;
csvCodeStyleSettings.TRIM_LEADING_WHITE_SPACES = TRIM_LEADING_WHITE_SPACES;
csvCodeStyleSettings.TRIM_TRAILING_WHITE_SPACES = TRIM_TRAILING_WHITE_SPACES;
csvCodeStyleSettings.TABULARIZE = TABULARIZE;
csvCodeStyleSettings.WHITE_SPACES_OUTSIDE_QUOTES = WHITE_SPACES_OUTSIDE_QUOTES;
csvCodeStyleSettings.LEADING_WHITE_SPACES = LEADING_WHITE_SPACES;
csvCodeStyleSettings.ENABLE_WIDE_CHARACTER_DETECTION = ENABLE_WIDE_CHARACTER_DETECTION;
csvCodeStyleSettings.TREAT_AMBIGUOUS_CHARACTERS_AS_WIDE = TREAT_AMBIGUOUS_CHARACTERS_AS_WIDE;
}
protected void defaultSettings() {
CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject());
settings.ALIGN_MULTILINE_PARAMETERS = true;
settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = false;
settings.ALIGN_MULTILINE_FOR = true;
settings.ALIGN_MULTILINE_BINARY_OPERATION = false;
settings.ALIGN_MULTILINE_TERNARY_OPERATION = false;
settings.ALIGN_MULTILINE_THROWS_LIST = false;
settings.ALIGN_MULTILINE_EXTENDS_LIST = false;
settings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION = false;
settings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS = false;
getSettings().SPACE_BEFORE_ANOTATION_PARAMETER_LIST = false;
getSettings().SPACE_AROUND_ASSIGNMENT_OPERATORS = true;
getSettings().SPACE_WITHIN_ANNOTATION_PARENTHESES = false;
getSettings().SPACE_AROUND_ASSIGNMENT_OPERATORS = true;
}
private static void indentSelection(Editor editor, Project project) {
int oldSelectionStart = editor.getSelectionModel().getSelectionStart();
int oldSelectionEnd = editor.getSelectionModel().getSelectionEnd();
if(!editor.getSelectionModel().hasSelection()) {
oldSelectionStart = editor.getCaretModel().getOffset();
oldSelectionEnd = oldSelectionStart;
}
Document document = editor.getDocument();
int startIndex = document.getLineNumber(oldSelectionStart);
if(startIndex == -1) {
startIndex = document.getLineCount() - 1;
}
int endIndex = document.getLineNumber(oldSelectionEnd);
if(endIndex > 0 && document.getLineStartOffset(endIndex) == oldSelectionEnd && editor.getSelectionModel().hasSelection()) {
endIndex --;
}
if(endIndex == -1) {
endIndex = document.getLineCount() - 1;
}
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
int blockIndent = CodeStyleSettingsManager.getSettings(project).getIndentOptionsByFile(file).INDENT_SIZE;
doIndent(endIndex, startIndex, document, project, editor, blockIndent);
}
@Override
public int getTabSize(Project project) {
if (myTabSize != null) return myTabSize;
if (myCachedTabSize != null) return myCachedTabSize;
int tabSize;
if (project == null || project.isDisposed()) {
tabSize = CodeStyleSettingsManager.getSettings(null).getTabSize(null);
}
else {
PsiFile file = getPsiFile(project);
if (myEditor != null && myEditor.isViewer()) {
FileType fileType = file != null ? file.getFileType() : null;
tabSize = CodeStyleSettingsManager.getSettings(project).getIndentOptions(fileType).TAB_SIZE;
}
else {
tabSize = CodeStyleSettingsManager.getSettings(project).getIndentOptionsByFile(file).TAB_SIZE;
}
}
myCachedTabSize = Integer.valueOf(tabSize);
return tabSize;
}
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;
}
@Override
protected void fillActions(Project project, @Nonnull DefaultActionGroup group, @Nonnull DataContext dataContext) {
final CodeStyleSettingsManager manager = CodeStyleSettingsManager.getInstance(project);
if (manager.PER_PROJECT_SETTINGS != null) {
//noinspection HardCodedStringLiteral
group.add(new AnAction("<project>", "",
manager.USE_PER_PROJECT_SETTINGS ? ourCurrentAction : ourNotCurrentAction) {
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
manager.USE_PER_PROJECT_SETTINGS = true;
}
});
}
CodeStyleScheme currentScheme = CodeStyleSchemes.getInstance().getCurrentScheme();
for (CodeStyleScheme scheme : CodeStyleSchemes.getInstance().getSchemes()) {
addScheme(group, manager, currentScheme, scheme, false);
}
}
private static String mergeTemplate(String templateContent, final VelocityContext context, boolean useSystemLineSeparators) throws IOException {
final StringWriter stringWriter = new StringWriter();
try {
VelocityWrapper.evaluate(null, context, stringWriter, templateContent);
}
catch (final VelocityException e) {
LOG.error("Error evaluating template:\n" + templateContent, e);
ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), IdeBundle.message("title.velocity.error")));
}
final String result = stringWriter.toString();
if (useSystemLineSeparators) {
final String newSeparator = CodeStyleSettingsManager.getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator();
if (!"\n".equals(newSeparator)) {
return StringUtil.convertLineSeparators(result, newSeparator);
}
}
return result;
}
@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);
}
private static boolean isWhitespaceRequired(Project project, char c) {
CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(project).getCurrentSettings();
FluidCodeStyleSettings options = settings.getCustomSettings(FluidCodeStyleSettings.class);
switch(c) {
case '{':
return options.SPACES_INSIDE_VARIABLE_DELIMITERS;
default:
return false;
}
}
/**
* Create a {@link LookupElementBuilder} for completing the text of a key. Do not use when completing a value.
*
* @param completionObject the object to pass to {@link LookupElementBuilder#create(Object)}.
* @param addLayerOfNesting whether a newline and indent should be added when accepting the completed value - this is used when inserting the value will introduce a level of nesting (i.e. for an
* object or array type).
* @return the created {@code LookupElementBuilder}.
*/
private static LookupElementBuilder createKeyLookupElement(@NotNull final Object completionObject, final boolean addLayerOfNesting) {
return LookupElementBuilder.create(completionObject).withInsertHandler((insertionContext, lookupElement) -> {
// If the caret is at the end of the line, add in the property colon when completing
if (insertionContext.getCompletionChar() != ':' && insertionContext.getCompletionChar() != ' ') {
final Editor editor = insertionContext.getEditor();
final int offset = editor.getCaretModel().getOffset();
final int lineNumber = editor.getDocument().getLineNumber(offset);
final int lineEndOffset = editor.getDocument().getLineEndOffset(lineNumber);
if (lineEndOffset == offset) {
final String autocompleteString;
if (addLayerOfNesting) {
// Copy the indentation characters present on this line, and add one additional level of indentation
final int lineStartOffset = editor.getDocument().getLineStartOffset(lineNumber);
final String lineContent = editor.getDocument().getText().substring(lineStartOffset, lineEndOffset);
final int offsetOfContent = lineContent.length() - StringUtil.trimLeading(lineContent).length();
final String indentToLine = lineContent.substring(0, offsetOfContent);
final CodeStyleSettings currentSettings = CodeStyleSettingsManager.getSettings(insertionContext.getProject());
final CommonCodeStyleSettings.IndentOptions indentOptions = currentSettings.getIndentOptions(insertionContext.getFile().getFileType());
final String additionalIndent = indentOptions.USE_TAB_CHARACTER ? "\t" : StringUtil.repeatSymbol(' ', indentOptions.INDENT_SIZE);
autocompleteString = ":\n" + indentToLine + additionalIndent;
} else {
autocompleteString = ": ";
}
EditorModificationUtil.insertStringAtCaret(editor, autocompleteString);
}
}
});
}
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");
}
@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");
}
@Test
public void testFormatter() {
myFixture.configureByFiles("FormatterTestData.graphqle");
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.graphqle");
}
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);
}
protected void setSettingsBack() {
final CodeStyleSettingsManager manager = CodeStyleSettingsManager.getInstance(myFixture.getProject());
myTempSettings.getIndentOptions(BashFileType.BASH_FILE_TYPE).INDENT_SIZE = 200;
myTempSettings.getIndentOptions(BashFileType.BASH_FILE_TYPE).CONTINUATION_INDENT_SIZE = 200;
myTempSettings.getIndentOptions(BashFileType.BASH_FILE_TYPE).TAB_SIZE = 200;
myTempSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 5;
manager.dropTemporarySettings();
myTempSettings = null;
}
@Before
protected void setUp() throws Exception {
super.setUp();
CodeStyleSettings temp = CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().clone();
temp.WRAP_ON_TYPING = CommonCodeStyleSettings.WrapOnTyping.WRAP.intValue;
CodeStyleSettingsManager.getInstance(myFixture.getProject()).setTemporarySettings(temp);
}
@Override
@After
protected void tearDown() throws Exception {
CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings();
super.tearDown();
}
@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);
}
public void setTestStyleSettings(int indent) {
Project project = getProject();
CodeStyleSettings currSettings = CodeStyleSettingsManager.getSettings(project);
assertNotNull(currSettings);
CodeStyleSettings tempSettings = currSettings.clone();
CodeStyleSettings.IndentOptions indentOptions = tempSettings.getIndentOptions(HaxeFileType.HAXE_FILE_TYPE);
indentOptions.INDENT_SIZE = indent;
assertNotNull(indentOptions);
CodeStyleSettingsManager.getInstance(project).setTemporarySettings(tempSettings);
}
private void setTestStyleSettings() {
CodeStyleSettingsManager settingsManager = CodeStyleSettingsManager.getInstance(getProject());
CodeStyleSettings currSettings = settingsManager.getCurrentSettings();
Assert.assertNotNull(currSettings);
myTemporarySettings = currSettings.clone();
CodeStyleSettings.IndentOptions indentOptions = myTemporarySettings.getIndentOptions(XQueryFileType.INSTANCE);
Assert.assertNotNull(indentOptions);
settingsManager.setTemporarySettings(myTemporarySettings);
}
public DocImpl(ContextImpl context, Document document) {
this.context = context;
this.document = document;
CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(context.project);
// Using deprecated because not all versions and forks of Intellij Have this.
// Replace with settings.getRightMargin(null); one day
editorWidth = settings.RIGHT_MARGIN;
}
/**
* Load field name prefix from code style
*
* @return
*/
public static String getPrefix() {
if (PropertiesComponent.getInstance().isValueSet(Settings.PREFIX)) {
return PropertiesComponent.getInstance().getValue(Settings.PREFIX);
} else {
CodeStyleSettingsManager manager = CodeStyleSettingsManager.getInstance();
CodeStyleSettings settings = manager.getCurrentSettings();
return settings.FIELD_NAME_PREFIX;
}
}
public static CodeStyleSettings getSettings(Project project) {
if (project != null) {
CodeStyleSettingsManager manager = CodeStyleSettingsManager.getInstance(project);
if (manager != null) {
return manager.getCurrentSettings();
}
}
return null;
}
@Override
protected void runTestInternal() throws Throwable {
String name = getName();
assertNotNull("TestCase.fName cannot be null", name); // Some VMs crash when calling getMethod(null,null);
Method runMethod = null;
try {
// use getMethod to get all public inherited
// methods. getDeclaredMethods returns all
// methods of this class but excludes the
// inherited ones.
runMethod = getClass().getMethod(name, (Class[])null);
}
catch (NoSuchMethodException e) {
fail("Method \"" + name + "\" not found");
}
if (!Modifier.isPublic(runMethod.getModifiers())) {
fail("Method \"" + name + "\" should be public");
}
Setup annotation = runMethod.getAnnotation(Setup.class);
CodeStyleSettings codeStyleSettings = new CodeStyleSettings();
if(annotation != null) {
Class<Consumer<CodeStyleSettings>> value = annotation.value();
Consumer<CodeStyleSettings> codeStyleSettingsConsumer = value.newInstance();
codeStyleSettingsConsumer.consume(codeStyleSettings);
}
CodeStyleSettingsManager.getInstance(myProject).setTemporarySettings(codeStyleSettings);
doTest();
CodeStyleSettingsManager.getInstance(myProject).dropTemporarySettings();
}
@Override
protected void tearDown() throws Exception {
Project project = getProject();
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
checkForSettingsDamage();
doTearDown(project, ourApplication, true);
try {
super.tearDown();
}
finally {
myThreadTracker.checkLeak();
}
}
@Override
public void tearDown() throws Exception {
Project project = getProject();
CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
LightPlatformTestCase.doTearDown(project, LightPlatformTestCase.getApplication(), true);
super.tearDown();
InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);
PersistentFS.getInstance().clearIdCache();
}
@Override
protected void setUp() throws Exception {
super.setUp();
if (ourTestCase != null) {
String message = "Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call.";
ourTestCase = null;
fail(message);
}
LOGGER.info(getClass().getName() + ".setUp()");
initApplication();
myEditorListenerTracker = new EditorListenerTracker();
myThreadTracker = new ThreadTracker();
setUpProject();
storeSettings();
ourTestCase = this;
if (myProject != null) {
ProjectManagerEx.getInstanceEx().openTestProject(myProject);
CodeStyleSettingsManager.getInstance(myProject).setTemporarySettings(new CodeStyleSettings());
InjectedLanguageManagerImpl.pushInjectors(getProject());
}
DocumentCommitThread.getInstance().clearQueue();
UIUtil.dispatchAllInvocationEvents();
}
private static void setupCaret(final RangeMarker caretMarker, String fileText) {
if (caretMarker != null) {
int caretLine = StringUtil.offsetToLineNumber(fileText, caretMarker.getStartOffset());
int caretCol = EditorUtil.calcColumnNumber(null, myEditor.getDocument().getText(),
myEditor.getDocument().getLineStartOffset(caretLine), caretMarker.getStartOffset(),
CodeStyleSettingsManager.getSettings(getProject()).getIndentOptions(InternalStdFileTypes.JAVA).TAB_SIZE);
LogicalPosition pos = new LogicalPosition(caretLine, caretCol);
myEditor.getCaretModel().moveToLogicalPosition(pos);
}
}
private static void checkCaretPosition(final RangeMarker caretMarker, String newFileText, String message) {
if (caretMarker != null) {
int caretLine = StringUtil.offsetToLineNumber(newFileText, caretMarker.getStartOffset());
//int caretCol = caretMarker.getStartOffset() - StringUtil.lineColToOffset(newFileText, caretLine, 0);
int caretCol = EditorUtil.calcColumnNumber(null, newFileText,
StringUtil.lineColToOffset(newFileText, caretLine, 0),
caretMarker.getStartOffset(),
CodeStyleSettingsManager.getSettings(getProject()).getIndentOptions(InternalStdFileTypes.JAVA).TAB_SIZE);
assertEquals(getMessage("caretLine", message), caretLine, myEditor.getCaretModel().getLogicalPosition().line);
assertEquals(getMessage("caretColumn", message), caretCol, myEditor.getCaretModel().getLogicalPosition().column);
}
}
@RequiredUIAccess
@Override
protected void setUp() throws Exception {
super.setUp();
assertFalse(CodeStyleSettingsManager.getInstance(getProject()).USE_PER_PROJECT_SETTINGS);
assertNull(CodeStyleSettingsManager.getInstance(getProject()).PER_PROJECT_SETTINGS);
}