private static void doTestLineToIndentMapping(@NotNull String text, int... spacesForLine) { configureFromFileText("x.java", text); Document document = PsiDocumentManager.getInstance(getProject()).getDocument(myFile); FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(myFile); Assert.assertNotNull(document); Assert.assertNotNull(builder); FormattingModel model = builder.createModel(myFile, CodeStyleSettingsManager.getSettings(getProject())); Block block = model.getRootBlock(); List<LineIndentInfo> list = new FormatterBasedLineIndentInfoBuilder(document, block).build(); Assert.assertEquals(list.size(), spacesForLine.length); for (int i = 0; i < spacesForLine.length; i++) { int indentSize = list.get(i).getIndentSize(); Assert.assertEquals("Mismatch on line " + i, spacesForLine[i], indentSize); } }
@Override public void setUp() throws Exception { super.setUp(); myWorkingDirectory = TestFileStructure.createDirectory(getProject(), getSourceRoot(), TEMP_DIR_NAME); myRealChangeListManager = ChangeListManager.getInstance(getProject()); myMockChangeListManager = new MockChangeListManager(); registerChangeListManager(myMockChangeListManager); myRealCodeStyleManger = CodeStyleManager.getInstance(getProject()); myMockCodeStyleManager = new MockCodeStyleManager(); registerCodeStyleManager(myMockCodeStyleManager); myRealVcsContextFactory = ServiceManager.getService(VcsContextFactory.class); registerVcsContextFactory(new MockVcsContextFactory(getSourceRoot().getFileSystem())); myMockPlainTextFormattingModelBuilder = new MockPlainTextFormattingModelBuilder(); LanguageFormatting.INSTANCE.addExplicitExtension(PlainTextLanguage.INSTANCE, myMockPlainTextFormattingModelBuilder); }
private static boolean canBeFormatted(PsiFile file) { if (LanguageFormatting.INSTANCE.forContext(file) == null) { return false; } VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) return true; if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return false; for (GeneratedSourcesFilter filter : GeneratedSourcesFilter.EP_NAME.getExtensions()) { if (filter.isGeneratedSource(virtualFile, file.getProject())) { return false; } } return true; }
@Override public void update(AnActionEvent event) { Presentation presentation = event.getPresentation(); DataContext dataContext = event.getDataContext(); Project project = CommonDataKeys.PROJECT.getData(dataContext); Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (project == null || editor == null) { presentation.setEnabled(false); return; } PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null || file.getVirtualFile() == null) { presentation.setEnabled(false); return; } if (LanguageFormatting.INSTANCE.forContext(file) != null) { presentation.setEnabled(true); } }
static void indentBlock(Project project, Editor editor, final int startOffset, final int endOffset, int originalCaretCol) { final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); documentManager.commitAllDocuments(); final Document document = editor.getDocument(); PsiFile file = documentManager.getPsiFile(document); if (file == null) { return; } if (LanguageFormatting.INSTANCE.forContext(file) != null) { indentBlockWithFormatter(project, document, startOffset, endOffset, file); } else { indentPlainTextBlock(document, startOffset, endOffset, originalCaretCol); } }
public void addInjectedLanguageBlockWrapper(final List<Block> result, final ASTNode injectedNode, final Indent indent, int offset, @Nullable TextRange range) { // // Do not create a block for an empty range // if (range != null) { if (range.getLength() == 0) return; if(StringUtil.isEmptyOrSpaces(range.substring(injectedNode.getText()))) { return; } } final PsiElement childPsi = injectedNode.getPsi(); final Language childLanguage = childPsi.getLanguage(); final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(childLanguage, childPsi); LOG.assertTrue(builder != null); final FormattingModel childModel = builder.createModel(childPsi, getSettings()); Block original = childModel.getRootBlock(); if ((original.isLeaf() && !injectedNode.getText().trim().isEmpty()) || !original.getSubBlocks().isEmpty()) { result.add(createInjectedBlock(injectedNode, original, indent, offset, range, childLanguage)); } }
private static TextRange getSignificantRange(final PsiFile file, final int offset) { final ASTNode elementAtOffset = SourceTreeToPsiMap.psiElementToTree(CodeStyleManagerImpl.findElementInTreeWithFormatterEnabled(file, offset)); if (elementAtOffset == null) { int significantRangeStart = CharArrayUtil.shiftBackward(file.getText(), offset - 1, "\r\t "); return new TextRange(Math.max(significantRangeStart, 0), offset); } final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file); final TextRange textRange = builder.getRangeAffectingIndent(file, offset, elementAtOffset); if (textRange != null) { return textRange; } return elementAtOffset.getTextRange(); }
protected Block getRootBlock(PsiElement element, FileViewProvider viewProvider, CodeStyleSettings settings) { ASTNode node = element.getNode(); if (node == null) { return createDummyBlock(node); } if (viewProvider instanceof TemplateLanguageFileViewProvider) { final Language dataLanguage = ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage(); final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forLanguage(dataLanguage); if (builder instanceof DelegatingFormattingModelBuilder && ((DelegatingFormattingModelBuilder)builder).dontFormatMyModel()) { return createDummyBlock(node); } if (builder != null) { final FormattingModel model = builder.createModel(viewProvider.getPsi(dataLanguage), settings); List<DataLanguageBlockWrapper> childWrappers = buildChildWrappers(model.getRootBlock()); if (childWrappers.size() == 1) { childWrappers = buildChildWrappers(childWrappers.get(0).getOriginal()); } return createTemplateLanguageBlock(node, Wrap.createWrap(WrapType.NONE, false), null, filterBlocksByRange(childWrappers, node.getTextRange()), settings); } } return createTemplateLanguageBlock(node, Wrap.createWrap(WrapType.NONE, false), null, Collections.<DataLanguageBlockWrapper>emptyList(), settings); }
@Override @SuppressWarnings({"StringEquality"}) public void initComponent() { final Language xmlLang = StdFileTypes.XML.getLanguage(); // intentionManager.addAction(new DeleteUnusedParameterFix()); // intentionManager.addAction(new DeleteUnusedVariableFix()); final XsltFormattingModelBuilder builder = new XsltFormattingModelBuilder(LanguageFormatting.INSTANCE.forLanguage(xmlLang)); LanguageFormatting.INSTANCE.addExplicitExtension(xmlLang, builder); try { // TODO: put this into com.intellij.refactoring.actions.IntroduceParameterAction, just like IntroduceVariableAction ActionManager.getInstance().getAction("IntroduceParameter").setInjectedContext(true); } catch (Exception e) { Logger.getInstance(XsltConfigImpl.class.getName()).error(e); } }
@NotNull @Override public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) { if(element instanceof JSFile || element.getContainingFile() instanceof JSFile) { final JSFile file = (JSFile)(element instanceof JSFile ? element : element.getContainingFile()); file.putUserData(WANT_DEFAULT_FORMATTER_KEY, true); try { final FormattingModelBuilder formattingModelBuilder = LanguageFormatting.INSTANCE.forContext(file.getLanguage(), element); if (formattingModelBuilder != null) { final FormattingModel model = formattingModelBuilder.createModel(element, settings); final Block rootBlock = model.getRootBlock(); return new DelegatingFormattingModel(model, new JSGraphQLBlockWrapper(rootBlock, null, element.getNode(), rootBlock.getWrap(), rootBlock.getAlignment(), createSpaceBuilder(settings, element), settings)); } } finally { file.putUserData(WANT_DEFAULT_FORMATTER_KEY, null); } } throw new IllegalArgumentException("Unsupported element '" + element + "'. It must be an element in a JSFile with its own default formatter to support injected GraphQL formatting"); }
public void addInjectedLanguageBlockWrapper(final List<Block> result, final ASTNode injectedNode, final Indent indent, int offset, @Nullable TextRange range) { // // Do not create a block for an empty range // if (range != null) { if (range.getLength() == 0) return; if(StringUtil.isEmptyOrSpaces(range.substring(injectedNode.getText()))) { return; } } final PsiElement childPsi = injectedNode.getPsi(); final Language childLanguage = childPsi.getLanguage(); final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(childLanguage, childPsi); LOG.assertTrue(builder != null); final FormattingModel childModel = builder.createModel(childPsi, getSettings()); Block original = childModel.getRootBlock(); if ((original.isLeaf() && injectedNode.getText().trim().length() > 0) || original.getSubBlocks().size() != 0) { result.add(createInjectedBlock(injectedNode, original, indent, offset, range, childLanguage)); } }
private static TextRange getSignificantRange(final PsiFile file, final int offset) { final ASTNode elementAtOffset = SourceTreeToPsiMap.psiElementToTree(CodeStyleManagerImpl.findElementInTreeWithFormatterEnabled(file, offset)); if (elementAtOffset == null) { int significantRangeStart = CharArrayUtil.shiftBackward(file.getText(), offset - 1, "\r\t "); return new TextRange(significantRangeStart, offset); } final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file); final TextRange textRange = builder.getRangeAffectingIndent(file, offset, elementAtOffset); if (textRange != null) { return textRange; } return elementAtOffset.getTextRange(); }
@SuppressWarnings({ "StringEquality" }) public void initComponent() { final Language xmlLang = StdFileTypes.XML.getLanguage(); // intentionManager.addAction(new DeleteUnusedParameterFix()); // intentionManager.addAction(new DeleteUnusedVariableFix()); final XsltFormattingModelBuilder builder = new XsltFormattingModelBuilder(LanguageFormatting.INSTANCE.forLanguage(xmlLang)); LanguageFormatting.INSTANCE.addExplicitExtension(xmlLang, builder); try { // TODO: put this into com.intellij.refactoring.actions.IntroduceParameterAction, just like IntroduceVariableAction ActionManager.getInstance().getAction("IntroduceParameter").setInjectedContext(true); } catch (Exception e) { Logger.getInstance(XsltConfigImpl.class.getName()).error(e); } }
@Override public void update(AnActionEvent event) { Presentation presentation = event.getPresentation(); DataContext dataContext = event.getDataContext(); Project project = dataContext.getData(CommonDataKeys.PROJECT); Editor editor = dataContext.getData(CommonDataKeys.EDITOR); if (project == null || editor == null) { presentation.setEnabled(false); return; } PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null || file.getVirtualFile() == null) { presentation.setEnabled(false); return; } if (LanguageFormatting.INSTANCE.forContext(file) != null) { presentation.setEnabled(true); } }
@SuppressWarnings({ "StringEquality" }) public void initComponent() { final Language xmlLang = XMLLanguage.INSTANCE; // intentionManager.addAction(new DeleteUnusedParameterFix()); // intentionManager.addAction(new DeleteUnusedVariableFix()); final XsltFormattingModelBuilder builder = new XsltFormattingModelBuilder(LanguageFormatting.INSTANCE.forLanguage(xmlLang)); LanguageFormatting.INSTANCE.addExplicitExtension(xmlLang, builder); try { // TODO: put this into com.intellij.refactoring.actions.IntroduceParameterAction, just like IntroduceVariableAction ActionManager.getInstance().getAction("IntroduceParameter").setInjectedContext(true); } catch (Exception e) { Logger.getInstance(XsltConfigImpl.class.getName()).error(e); } }
@NotNull protected static Iterator<Block> newLineBlockIterator() { FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(myFile); Assert.assertNotNull(builder); CodeStyleSettings settings = CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings(); FormattingModel model = builder.createModel(myFile, settings); Block root = model.getRootBlock(); Document document = PsiDocumentManager.getInstance(getProject()).getDocument(myFile); Assert.assertNotNull(document); return new NewLineBlocksIterator(root, document); }
@Override public void tearDown() throws Exception { registerChangeListManager(myRealChangeListManager); registerCodeStyleManager(myRealCodeStyleManger); registerVcsContextFactory(myRealVcsContextFactory); LanguageFormatting.INSTANCE.removeExplicitExtension(PlainTextLanguage.INSTANCE, myMockPlainTextFormattingModelBuilder); TestFileStructure.delete(myWorkingDirectory.getVirtualFile()); super.tearDown(); }
@Override public void setUp() throws Exception { super.setUp(); myWorkingDirectory = TestFileStructure.createDirectory(getProject(), getSourceRoot(), TEMP_DIR_NAME); myRealCodeStyleManger = CodeStyleManager.getInstance(getProject()); myMockCodeStyleManager = new MockCodeStyleManager(); registerCodeStyleManager(myMockCodeStyleManager); myMockPlainTextFormattingModelBuilder = new MockPlainTextFormattingModelBuilder(); LanguageFormatting.INSTANCE.addExplicitExtension(PlainTextLanguage.INSTANCE, myMockPlainTextFormattingModelBuilder); }
@Override public void tearDown() throws Exception { if (myRealCodeStyleManger != null) registerCodeStyleManager(myRealCodeStyleManger); if (myMockPlainTextFormattingModelBuilder != null) { LanguageFormatting.INSTANCE.removeExplicitExtension(PlainTextLanguage.INSTANCE, myMockPlainTextFormattingModelBuilder); } if (myWorkingDirectory != null) TestFileStructure.delete(myWorkingDirectory.getVirtualFile()); super.tearDown(); }
@NotNull private IndentUsageInfo getMaxUsedIndentInfo() { configureByFile(getFileNameWithExtension()); Document document = getDocument(myFile); FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(myFile); Assert.assertNotNull(builder); FormattingModel model = builder.createModel(myFile, CodeStyleSettingsManager.getSettings(getProject())); List<LineIndentInfo> lines = new FormatterBasedLineIndentInfoBuilder(document, model.getRootBlock()).build(); IndentUsageStatistics statistics = new IndentUsageStatisticsImpl(lines); return statistics.getKMostUsedIndentInfo(0); }
private static String getSpacing(PsiFile file, int offset) { FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file); if (builder == null) { return ""; } CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject()); FormattingModel model = builder.createModel(file, settings); int spacing = FormatterEx.getInstance().getSpacingForBlockAtOffset(model, offset); return StringUtil.repeatSymbol(' ', spacing); }
@Nullable private static Block buildBlocks(@NotNull 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; } }
@Override @NotNull public FormattingModel createModel(final PsiElement element, final CodeStyleSettings settings) { if (element instanceof PsiFile) { final FileViewProvider viewProvider = ((PsiFile)element).getViewProvider(); if (viewProvider instanceof TemplateLanguageFileViewProvider) { final Language language = ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage(); FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forLanguage(language); if (builder != null) { return builder.createModel(viewProvider.getPsi(language), settings); } } } final PsiFile file = element.getContainingFile(); return new DocumentBasedFormattingModel(new AbstractBlock(element.getNode(), Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment()) { @Override protected List<Block> buildChildren() { return Collections.emptyList(); } @Override public Spacing getSpacing(final Block child1, @NotNull final Block child2) { return Spacing.getReadOnlySpacing(); } @Override public boolean isLeaf() { return true; } }, element.getProject(), settings, file.getFileType(), file); }
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(); }
private boolean isEnabled(@NotNull CodeStyleSettings settings, @NotNull PsiFile file) { if (file instanceof PsiCompiledFile) return false; if (ApplicationManager.getApplication().isUnitTestMode()) { return myIsEnabledInTest; } VirtualFile vFile = file.getVirtualFile(); if (vFile == null || vFile instanceof LightVirtualFile || myDisabledFiles.contains(vFile)) return false; return LanguageFormatting.INSTANCE.forContext(file) != null && settings.AUTODETECT_INDENTS; }
private static Throwable makeLanguageStackTrace(@NotNull Throwable currentThrowable, @NotNull PsiFile file) { Throwable langThrowable = new Throwable(); FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file); if (builder == null) return currentThrowable; Class builderClass = builder.getClass(); Class declaringClass = builderClass.getDeclaringClass(); String guessedFileName = (declaringClass == null ? builderClass.getSimpleName() : declaringClass.getSimpleName()) + ".java"; StackTraceElement ste = new StackTraceElement(builder.getClass().getName(), "createModel", guessedFileName, 1); StackTraceElement[] originalStackTrace = currentThrowable.getStackTrace(); StackTraceElement[] modifiedStackTrace = new StackTraceElement[originalStackTrace.length + 1]; System.arraycopy(originalStackTrace, 0, modifiedStackTrace, 1, originalStackTrace.length); modifiedStackTrace[0] = ste; langThrowable.setStackTrace(modifiedStackTrace); return langThrowable; }
private Block createBlockFor(final Pair<PsiElement,Language> root) { final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(root.getSecond(), root.getFirst()); if (builder != null) { final Block result = builder.createModel(root.getFirst(), getSettings()).getRootBlock(); if (result instanceof XmlBlock) { final XmlFormattingPolicy policy = getPolicy((XmlBlock)result); policy.setRootModels(myRootToBlockMap); policy.doNotProcessJsp(); } return result; } else { return null; } }
private static boolean canBeFormatted(PsiFile file) { if (LanguageFormatting.INSTANCE.forContext(file) == null) { return false; } VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) return true; if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return false; return !GeneratedSourcesFilter.isGenerated(file.getProject(), virtualFile); }
@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; } }
@Override @Nonnull public FormattingModel createModel(final PsiElement element, final CodeStyleSettings settings) { if (element instanceof PsiFile) { final FileViewProvider viewProvider = ((PsiFile)element).getViewProvider(); if (viewProvider instanceof TemplateLanguageFileViewProvider) { final Language language = ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage(); FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forLanguage(language); if (builder != null) { return builder.createModel(viewProvider.getPsi(language), settings); } } } final PsiFile file = element.getContainingFile(); return new DocumentBasedFormattingModel(new AbstractBlock(element.getNode(), Wrap.createWrap(WrapType.NONE, false), Alignment.createAlignment()) { @Override protected List<Block> buildChildren() { return Collections.emptyList(); } @Override public Spacing getSpacing(final Block child1, @Nonnull final Block child2) { return Spacing.getReadOnlySpacing(); } @Override public boolean isLeaf() { return true; } }, element.getProject(), settings, file.getFileType(), file); }
private boolean isEnabled(@Nonnull CodeStyleSettings settings, @Nonnull PsiFile file) { if (file instanceof PsiCompiledFile) return false; if (ApplicationManager.getApplication().isUnitTestMode()) { return myIsEnabledInTest; } VirtualFile vFile = file.getVirtualFile(); if (vFile == null || vFile instanceof LightVirtualFile || myDisabledFiles.contains(vFile)) return false; return LanguageFormatting.INSTANCE.forContext(file) != null && settings.AUTODETECT_INDENTS; }