com.intellij.lang.LanguageFormatting Java Examples
The following examples show how to use
com.intellij.lang.LanguageFormatting.
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: JoinLinesHandler.java From consulo with Apache License 2.0 | 6 votes |
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 #2
Source File: TemplateLanguageFormattingModelBuilder.java From consulo with Apache License 2.0 | 6 votes |
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); }
Example #3
Source File: CodeStyleManagerRunnable.java From consulo with Apache License 2.0 | 6 votes |
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, "\n\r\t "); return new TextRange(Math.max(significantRangeStart, 0), offset); } final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file); if (builder != null) { final TextRange textRange = builder.getRangeAffectingIndent(file, offset, elementAtOffset); if (textRange != null) { return textRange; } } final TextRange elementRange = elementAtOffset.getTextRange(); if (isWhiteSpace(elementAtOffset)) { return extendRangeAtStartOffset(file, elementRange); } return elementRange; }
Example #4
Source File: InjectedLanguageBlockBuilder.java From consulo with Apache License 2.0 | 6 votes |
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)); } }
Example #5
Source File: LSPReformatAction.java From lsp4intellij with Apache License 2.0 | 6 votes |
@Override public void actionPerformed(AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor == null || project == null) { return; } PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (LanguageFormatting.INSTANCE.allForLanguage(file.getLanguage()).isEmpty() && IntellijLanguageClient .isExtensionSupported(file.getVirtualFile())) { // if editor hasSelection, only reformat selection, not reformat the whole file if (editor.getSelectionModel().hasSelection()) { ReformatHandler.reformatSelection(editor); } else { ReformatHandler.reformatFile(editor); } } else { super.actionPerformed(e); } }
Example #6
Source File: PasteHandler.java From consulo with Apache License 2.0 | 6 votes |
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); } }
Example #7
Source File: ShowReformatFileDialog.java From consulo with Apache License 2.0 | 6 votes |
@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); } }
Example #8
Source File: GraphQLInjectedFormattingModelBuilder.java From js-graphql-intellij-plugin with MIT License | 6 votes |
@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 GraphQLBlockWrapper(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"); }
Example #9
Source File: AbstractLayoutCodeProcessor.java From consulo with Apache License 2.0 | 5 votes |
private static boolean canBeFormatted(PsiFile file) { if (!file.isValid()) return false; 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); }
Example #10
Source File: PsiViewerDialog.java From consulo with Apache License 2.0 | 5 votes |
@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 #11
Source File: SimpleTemplateLanguageFormattingModelBuilder.java From consulo with Apache License 2.0 | 5 votes |
@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); }
Example #12
Source File: IndentOptionsDetectorImpl.java From consulo with Apache License 2.0 | 5 votes |
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 #13
Source File: DetectableIndentOptionsProvider.java From consulo with Apache License 2.0 | 5 votes |
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; }
Example #14
Source File: LSPShowReformatDialogAction.java From lsp4intellij with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); Project project = e.getData(CommonDataKeys.PROJECT); if (editor != null && project != null) { PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); VirtualFile virFile = FileDocumentManager.getInstance().getFile(editor.getDocument()); boolean alreadySupported = !LanguageFormatting.INSTANCE.allForLanguage(psiFile.getLanguage()).isEmpty(); if (!alreadySupported && IntellijLanguageClient.isExtensionSupported(virFile)) { boolean hasSelection = editor.getSelectionModel().hasSelection(); LayoutCodeDialog dialog = new LayoutCodeDialog(project, psiFile, hasSelection, HELP_ID); dialog.show(); if (dialog.isOK()) { LayoutCodeOptions options = dialog.getRunOptions(); EditorEventManager eventManager = EditorEventManagerBase.forEditor(editor); if (eventManager != null) { if (options.getTextRangeType() == TextRangeType.SELECTED_TEXT) { eventManager.reformatSelection(); } else { eventManager.reformat(); } } } else { // if user chose cancel , the dialog in super.actionPerformed(e) will show again // super.actionPerformed(e); } } else { super.actionPerformed(e); } } else { super.actionPerformed(e); } }
Example #15
Source File: BaseIndentEnterHandler.java From consulo with Apache License 2.0 | 4 votes |
@Override public Result preprocessEnter( @Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull final Ref<Integer> caretOffset, @Nonnull final Ref<Integer> caretAdvance, @Nonnull final DataContext dataContext, final EditorActionHandler originalHandler) { Result res = shouldSkipWithResult(file, editor, dataContext); if (res != null) { return res; } final Document document = editor.getDocument(); int caret = editor.getCaretModel().getOffset(); final int lineNumber = document.getLineNumber(caret); final int lineStartOffset = document.getLineStartOffset(lineNumber); final int previousLineStartOffset = lineNumber > 0 ? document.getLineStartOffset(lineNumber - 1) : lineStartOffset; final EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); final HighlighterIterator iterator = highlighter.createIterator(caret - 1); final IElementType type = getNonWhitespaceElementType(iterator, lineStartOffset, previousLineStartOffset); final CharSequence editorCharSequence = document.getCharsSequence(); final CharSequence lineIndent = editorCharSequence.subSequence(lineStartOffset, EditorActionUtil.findFirstNonSpaceOffsetOnTheLine(document, lineNumber)); // Enter in line comment if (type == myLineCommentType) { final String restString = editorCharSequence.subSequence(caret, document.getLineEndOffset(lineNumber)).toString(); if (!StringUtil.isEmptyOrSpaces(restString)) { final String linePrefix = lineIndent + myLineCommentPrefix; EditorModificationUtil.insertStringAtCaret(editor, "\n" + linePrefix); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, linePrefix.length())); return Result.Stop; } else if (iterator.getStart() < lineStartOffset) { EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent); return Result.Stop; } } if (!myWorksWithFormatter && LanguageFormatting.INSTANCE.forLanguage(myLanguage) != null) { return Result.Continue; } else { if (myIndentTokens.contains(type)) { final String newIndent = getNewIndent(file, document, lineIndent); EditorModificationUtil.insertStringAtCaret(editor, "\n" + newIndent); return Result.Stop; } EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, calcLogicalLength(editor, lineIndent))); return Result.Stop; } }
Example #16
Source File: EmacsStyleIndentAction.java From consulo with Apache License 2.0 | 4 votes |
@Override protected boolean isValidForFile(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { final PsiElement context = file.findElementAt(editor.getCaretModel().getOffset()); return context != null && LanguageFormatting.INSTANCE.forContext(context) != null; }
Example #17
Source File: AutoIndentLinesAction.java From consulo with Apache License 2.0 | 4 votes |
@Override protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull final PsiFile file) { final FileType fileType = file.getFileType(); return fileType instanceof LanguageFileType && LanguageFormatting.INSTANCE.forContext(((LanguageFileType)fileType).getLanguage(), file) != null; }
Example #18
Source File: CodeStyleManagerRunnable.java From consulo with Apache License 2.0 | 4 votes |
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; }