下面列出了com.intellij.psi.codeStyle.CodeStyleManager# getInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void update(State state) {
this.lock.lock();
try {
CodeStyleManager manager = CodeStyleManager.getInstance(this.project);
if (manager == null) {
logger.warn("Unable to find exiting CodeStyleManager");
return;
}
if (state == State.ACTIVE && !(manager instanceof SpringCodeStyleManager)) {
logger.debug("Enabling SpringCodeStyleManager");
registerCodeStyleManager(new SpringCodeStyleManager(manager));
this.properties.setValue(ACTIVE_PROPERTY, true);
}
if (state == State.NOT_ACTIVE && (manager instanceof SpringCodeStyleManager)) {
logger.debug("Disabling SpringCodeStyleManager");
registerCodeStyleManager(((SpringCodeStyleManager) manager).getDelegate());
this.properties.setValue(ACTIVE_PROPERTY, false);
}
ApplicationManager.getApplication().invokeLater(() -> this.statusIndicator.update(state));
}
finally {
this.lock.unlock();
}
}
@Override
public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr) throws IncorrectOperationException {
PsiManager manager = expr.getManager();
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
@NonNls String text = "if(a){\nst;\n}elseif(){else{\n}";
PsiIfStatement ifStatement = (PsiIfStatement)factory.createStatementFromText(text, null);
ifStatement = (PsiIfStatement)codeStyleManager.reformat(ifStatement);
ifStatement.getCondition().replace(expr);
PsiExpressionStatement statement = (PsiExpressionStatement)expr.getParent();
ifStatement = (PsiIfStatement)statement.replace(ifStatement);
PsiCodeBlock block = ((PsiBlockStatement)ifStatement.getThenBranch()).getCodeBlock();
PsiStatement afterStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(block.getStatements()[0]);
TextRange range = afterStatement.getTextRange();
editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
return new TextRange(range.getStartOffset(), range.getStartOffset());
}
public EclipseCodeStyleManager install(@NotNull Settings settings) {
CodeStyleManager currentManager = CodeStyleManager.getInstance(project);
EclipseCodeStyleManager overridingObject;
if (compatibleWith_2016_3_API()) {
overridingObject = new EclipseCodeStyleManager_IJ_2016_3plus(currentManager, settings);
} else {
overridingObject = new EclipseCodeStyleManager(currentManager, settings);
}
CodeStyleManager proxy = createProxy(currentManager, overridingObject);
// CodeStyleManager proxy = new ManualCodeStyleManagerDelegator(currentManager, overridingObject);
LOG.info("Overriding " + currentManager.getClass().getCanonicalName() + " with "
+ overridingObject.getClass().getCanonicalName() + "' for project '" + project.getName()
+ "' using CGLIB proxy");
registerCodeStyleManager(project, proxy);
return overridingObject;
}
/**
* When appropriate, automatically reduce the indentation for else tags "{:else}"
*/
private void adjustFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
PsiElement elementAtCaret = provider.findElementAt(offset - 1, DustLanguage.class);
PsiElement elseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement element) {
return element != null
&& (element instanceof DustElseTag);
}
});
// run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
if (elseParent != null) {
// grab the current caret position (AutoIndentLinesHandler is about to mess with it)
PsiDocumentManager.getInstance(project).commitAllDocuments();
CaretModel caretModel = editor.getCaretModel();
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
}
}
public GodClassPreviewResultDialog(@NotNull Project project, @NotNull MutableDiffRequestChain requestChain,
@NotNull DiffDialogHints hints, ExtractClassPreviewProcessor previewProcessor) {
super(project, requestChain, hints);
this.myChain = requestChain;
this.project = project;
this.diffContentFactory = DiffContentFactory.getInstance();
this.previewProcessor = previewProcessor;
this.javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
this.codeStyleManager = CodeStyleManager.getInstance(project);
}
public PolymorphismRefactoring(PsiFile sourceFile,
Project project,
PsiClass sourceTypeDeclaration,
TypeCheckElimination typeCheckElimination) {
this.sourceFile = sourceFile;
this.sourceTypeDeclaration = sourceTypeDeclaration;
this.typeCheckElimination = typeCheckElimination;
elementFactory = PsiElementFactory.getInstance(project);
codeStyleManager = CodeStyleManager.getInstance(project);
this.project = project;
semicolon = (PsiJavaToken) elementFactory.createStatementFromText(";", null).getFirstChild();
}
@NotNull
@CheckReturnValue
public String format(@Nonnull String text) {
final String name = Extensions.append(NAME, fileType);
final PsiFile file = fileFactory.createFileFromText(name, fileType, text);
final CodeStyleManager styleManager = CodeStyleManager.getInstance(file.getProject());
styleManager.reformat(file);
return file.getText();
}
public static void reformatJavaDoc(PsiElement theElement) {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(theElement.getProject());
try {
int javadocTextOffset = findJavaDocTextOffset(theElement);
int javaCodeTextOffset = findJavaCodeTextOffset(theElement);
codeStyleManager.reformatText(theElement.getContainingFile(), javadocTextOffset,
javaCodeTextOffset + 1);
} catch (Exception e) {
LOGGER.error("reformat code failed", e);
}
}
public static void reformatJavaFile(PsiElement theElement) {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(theElement.getProject());
try {
codeStyleManager.reformat(theElement);
} catch (Exception e) {
LOGGER.error("reformat code failed", e);
}
}
private static void installFormatter(Project project) {
CodeStyleManager currentManager = CodeStyleManager.getInstance(project);
if (currentManager instanceof GoogleJavaFormatCodeStyleManager) {
currentManager = ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate();
}
setManager(project, new GoogleJavaFormatCodeStyleManager(currentManager));
}
private static void adjustLineIndent(PsiFile file,
Document document,
int startOffset, int endOffset, int line, Project project) {
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
if (startOffset == endOffset) {
int lineStart = document.getLineStartOffset(line);
if (codeStyleManager.isLineToBeIndented(file, lineStart)) {
codeStyleManager.adjustLineIndent(file, lineStart);
}
} else {
codeStyleManager.adjustLineIndent(file, new TextRange(startOffset, endOffset));
}
}
private static void indentEachLine(Project project, Editor editor, int startOffset, int endOffset) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
final CharSequence text = editor.getDocument().getCharsSequence();
if (startOffset > 0 && endOffset > startOffset + 1 && text.charAt(endOffset - 1) == '\n' && text.charAt(startOffset - 1) == '\n') {
// There is a possible situation that pasted text ends by a line feed. We don't want to proceed it when a text is
// pasted at the first line column.
// Example:
// text to paste:
//'if (true) {
//'
// source:
// if (true) {
// int i = 1;
// int j = 1;
// }
//
//
// We get the following on paste then:
// if (true) {
// if (true) {
// int i = 1;
// int j = 1;
// }
//
// We don't want line 'int i = 1;' to be indented here.
endOffset--;
}
try {
codeStyleManager.adjustLineIndent(file, new TextRange(startOffset, endOffset));
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private static void indentLinesIn(final Editor editor, final PsiFile file, final Document document, final Project project, RangeMarker range) {
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
int line1 = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int line2 = editor.offsetToLogicalPosition(range.getEndOffset()).line;
while (!lineContainsNonSpaces(document, line1) && line1 < line2) line1++;
while (!lineContainsNonSpaces(document, line2) && line1 < line2) line2--;
final FileViewProvider provider = file.getViewProvider();
PsiFile rootToAdjustIndentIn = provider.getPsi(provider.getBaseLanguage());
codeStyleManager.adjustLineIndent(rootToAdjustIndentIn, new TextRange(document.getLineStartOffset(line1), document.getLineStartOffset(line2)));
}
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));
}
@Nullable
private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings) throws IncorrectOperationException {
myDocument.insertString(myOffset, buffer);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
CodeStyleManager.getInstance(getProject()).adjustLineIndent(myFile, myOffset + buffer.length() - 2);
PsiComment comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
comment = createJavaDocStub(settings, comment, getProject());
if (comment == null) {
return null;
}
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
final Ref<PsiComment> commentRef = Ref.create(comment);
codeStyleManager.runWithDocCommentFormattingDisabled(myFile, () -> formatComment(commentRef, codeStyleManager));
comment = commentRef.get();
PsiElement next = comment.getNextSibling();
if (next == null && comment.getParent().getClass() == comment.getClass()) {
next = comment.getParent().getNextSibling(); // expanding chameleon comment produces comment under comment
}
if (next != null) {
next = myFile.findElementAt(next.getTextRange().getStartOffset()); // maybe switch to another tree
}
if (next != null && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode()) || !next.getText().contains(LINE_SEPARATOR))) {
int lineBreakOffset = comment.getTextRange().getEndOffset();
myDocument.insertString(lineBreakOffset, LINE_SEPARATOR);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1);
comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
}
return comment;
}
JoinLineProcessor(@Nonnull DocumentEx doc, @Nonnull PsiFile file, int line, @Nonnull ProgressIndicator indicator) {
myDoc = doc;
myFile = file;
myLine = line;
myIndicator = indicator;
Project project = file.getProject();
myManager = PsiDocumentManager.getInstance(project);
myStyleManager = CodeStyleManager.getInstance(project);
}
/**
* Replace the existing formatter with one produced from the given {@link CodeStyleManagerFactory}
*/
public static void replaceFormatter(Project project, CodeStyleManagerFactory newFormatter) {
CodeStyleManager currentManager = CodeStyleManager.getInstance(project);
ServiceHelperCompat.registerService(
project, CodeStyleManager.class, newFormatter.createFormatter(currentManager), project);
}
protected static PsiFile createFromTemplateInternal( @NotNull PsiDirectory directory,
@NotNull String name,
@NotNull String fileName,
@NotNull String templateName,
@NonNls String... parameters )
throws IncorrectOperationException
{
// Load template
FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
FileTemplate template = fileTemplateManager.getJ2eeTemplate( templateName );
// Process template properties
Properties properties = new Properties( fileTemplateManager.getDefaultProperties() );
JavaTemplateUtil.setPackageNameAttribute( properties, directory );
properties.setProperty( NAME_TEMPLATE_PROPERTY, name );
// Add parameters
for( int i = 0; i < parameters.length; i += 2 )
{
properties.setProperty( parameters[ i ], parameters[ i + 1 ] );
}
// Create text from template with specified properties
String text;
try
{
text = template.getText( properties );
}
catch( Exception e )
{
String message = "Unable to load template for " +
fileTemplateManager.internalTemplateToSubject( templateName );
throw new RuntimeException( message, e );
}
// Serialized text to file
PsiManager psiManager = PsiManager.getInstance( directory.getProject() );
PsiFileFactory fileFactory = PsiFileFactory.getInstance( directory.getProject() );
PsiFile file = fileFactory.createFileFromText( fileName, text );
// Reformat the file according to project/default style
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance( psiManager );
codeStyleManager.reformat( file );
// Add newly created file to directory
return (PsiFile) directory.add( file );
}
@Override
protected void doExecute(@Nonnull final Editor editor, Caret caret, DataContext dataContext) {
CodeInsightSettings settings = CodeInsightSettings.getInstance();
if (!settings.SMART_END_ACTION) {
if (myOriginalHandler != null) {
myOriginalHandler.execute(editor, caret, dataContext);
}
return;
}
final Project project = DataManager.getInstance().getDataContext(editor.getComponent()).getData(CommonDataKeys.PROJECT);
if (project == null) {
if (myOriginalHandler != null) {
myOriginalHandler.execute(editor, caret, dataContext);
}
return;
}
final Document document = editor.getDocument();
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (file == null) {
if (myOriginalHandler != null){
myOriginalHandler.execute(editor, caret, dataContext);
}
return;
}
final EditorNavigationDelegate[] extensions = EditorNavigationDelegate.EP_NAME.getExtensions();
for (EditorNavigationDelegate delegate : extensions) {
if (delegate.navigateToLineEnd(editor, dataContext) == EditorNavigationDelegate.Result.STOP) {
return;
}
}
final CaretModel caretModel = editor.getCaretModel();
final int caretOffset = caretModel.getOffset();
CharSequence chars = editor.getDocument().getCharsSequence();
int length = editor.getDocument().getTextLength();
if (caretOffset < length) {
final int offset1 = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t");
if (offset1 < 0 || chars.charAt(offset1) == '\n' || chars.charAt(offset1) == '\r') {
final int offset2 = CharArrayUtil.shiftForward(chars, offset1 + 1, " \t");
boolean isEmptyLine = offset2 >= length || chars.charAt(offset2) == '\n' || chars.charAt(offset2) == '\r';
if (isEmptyLine) {
// There is a possible case that indent string is not calculated for particular document (that is true at least for plain text
// documents). Hence, we check that and don't finish processing in case we have such a situation.
boolean stopProcessing = true;
PsiDocumentManager.getInstance(project).commitAllDocuments();
CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
final String lineIndent = styleManager.getLineIndent(file, caretOffset);
if (lineIndent != null) {
int col = calcColumnNumber(lineIndent, editor.getSettings().getTabSize(project));
int line = caretModel.getVisualPosition().line;
caretModel.moveToVisualPosition(new VisualPosition(line, col));
if (caretModel.getLogicalPosition().column != col){
if (!ApplicationManager.getApplication().isWriteAccessAllowed() &&
!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
return;
}
editor.getSelectionModel().removeSelection();
WriteAction.run(() -> document.replaceString(offset1 + 1, offset2, lineIndent));
}
}
else {
stopProcessing = false;
}
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
if (stopProcessing) {
return;
}
}
}
}
if (myOriginalHandler != null){
myOriginalHandler.execute(editor, caret, dataContext);
}
}
private void reformat(RangeMarker rangeMarkerToReformat) {
final PsiFile file = getPsiFile();
if (file != null) {
CodeStyleManager style = CodeStyleManager.getInstance(myProject);
DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> {
for (TemplateOptionalProcessor optionalProcessor : Extensions.getExtensions(TemplateOptionalProcessor.EP_NAME)) {
optionalProcessor.processText(myProject, myTemplate, myDocument, myTemplateRange, myEditor);
}
});
PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myDocument);
// for Python, we need to indent the template even if reformatting is enabled, because otherwise indents would be broken
// and reformat wouldn't be able to fix them
if (myTemplate.isToIndent()) {
if (!myTemplateIndented) {
LOG.assertTrue(myTemplateRange.isValid(), presentTemplate(myTemplate));
smartIndent(myTemplateRange.getStartOffset(), myTemplateRange.getEndOffset());
myTemplateIndented = true;
}
}
if (myTemplate.isToReformat()) {
try {
int endSegmentNumber = myTemplate.getEndSegmentNumber();
PsiDocumentManager.getInstance(myProject).commitDocument(myDocument);
RangeMarker dummyAdjustLineMarkerRange = null;
int endVarOffset = -1;
if (endSegmentNumber >= 0) {
endVarOffset = mySegments.getSegmentStart(endSegmentNumber);
TextRange range = CodeStyleManagerImpl.insertNewLineIndentMarker(file, myDocument, endVarOffset);
if (range != null) dummyAdjustLineMarkerRange = myDocument.createRangeMarker(range);
}
int reformatStartOffset = myTemplateRange.getStartOffset();
int reformatEndOffset = myTemplateRange.getEndOffset();
if (rangeMarkerToReformat != null) {
reformatStartOffset = rangeMarkerToReformat.getStartOffset();
reformatEndOffset = rangeMarkerToReformat.getEndOffset();
}
if (dummyAdjustLineMarkerRange == null && endVarOffset >= 0) {
// There is a possible case that indent marker element was not inserted (e.g. because there is no blank line
// at the target offset). However, we want to reformat white space adjacent to the current template (if any).
PsiElement whiteSpaceElement = CodeStyleManagerImpl.findWhiteSpaceNode(file, endVarOffset);
if (whiteSpaceElement != null) {
TextRange whiteSpaceRange = whiteSpaceElement.getTextRange();
if (whiteSpaceElement.getContainingFile() != null) {
// Support injected white space nodes.
whiteSpaceRange = InjectedLanguageManager.getInstance(file.getProject()).injectedToHost(whiteSpaceElement, whiteSpaceRange);
}
reformatStartOffset = Math.min(reformatStartOffset, whiteSpaceRange.getStartOffset());
reformatEndOffset = Math.max(reformatEndOffset, whiteSpaceRange.getEndOffset());
}
}
style.reformatText(file, reformatStartOffset, reformatEndOffset);
PsiDocumentManager.getInstance(myProject).commitDocument(myDocument);
PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myDocument);
if (dummyAdjustLineMarkerRange != null && dummyAdjustLineMarkerRange.isValid()) {
//[ven] TODO: [max] correct javadoc reformatting to eliminate isValid() check!!!
mySegments.replaceSegmentAt(endSegmentNumber, dummyAdjustLineMarkerRange.getStartOffset(), dummyAdjustLineMarkerRange.getEndOffset());
myDocument.deleteString(dummyAdjustLineMarkerRange.getStartOffset(), dummyAdjustLineMarkerRange.getEndOffset());
PsiDocumentManager.getInstance(myProject).commitDocument(myDocument);
}
if (endSegmentNumber >= 0) {
final int offset = mySegments.getSegmentStart(endSegmentNumber);
final int lineStart = myDocument.getLineStartOffset(myDocument.getLineNumber(offset));
// if $END$ is at line start, put it at correct indentation
if (myDocument.getCharsSequence().subSequence(lineStart, offset).toString().trim().isEmpty()) {
final int adjustedOffset = style.adjustLineIndent(file, offset);
mySegments.replaceSegmentAt(endSegmentNumber, adjustedOffset, adjustedOffset);
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
}