下面列出了com.intellij.psi.PsiInvalidElementAccessException#com.intellij.openapi.fileTypes.FileType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nullable
private static EditorHighlighter createEditorHighlighter(@Nullable Project project, @Nonnull DocumentContent content) {
FileType type = content.getContentType();
VirtualFile file = content.getHighlightFile();
Language language = content.getUserData(DiffUserDataKeys.LANGUAGE);
EditorHighlighterFactory highlighterFactory = EditorHighlighterFactory.getInstance();
if (language != null) {
SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, file);
return highlighterFactory.createEditorHighlighter(syntaxHighlighter, EditorColorsManager.getInstance().getGlobalScheme());
}
if (file != null) {
if ((type == null || type == PlainTextFileType.INSTANCE) || file.getFileType() == type || file instanceof LightVirtualFile) {
return highlighterFactory.createEditorHighlighter(project, file);
}
}
if (type != null) {
return highlighterFactory.createEditorHighlighter(project, type);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int compare(final FileType o1, final FileType o2) {
if (o1 == o2) {
return 0;
}
if (o1 == UnknownFileType.INSTANCE) {
return 1;
}
if (o2 == UnknownFileType.INSTANCE) {
return -1;
}
if (o1.isBinary() && !o2.isBinary()) {
return 1;
}
if (!o1.isBinary() && o2.isBinary()) {
return -1;
}
return o1.getName().compareToIgnoreCase(o2.getName());
}
private static boolean isInStringLiteral(@Nonnull Editor editor, @Nonnull DataContext dataContext, int offset) {
Language language = EnterHandler.getLanguage(dataContext);
if (offset > 0 && language != null) {
QuoteHandler quoteHandler = TypedHandler.getLanguageQuoteHandler(language);
if (quoteHandler == null) {
FileType fileType = language.getAssociatedFileType();
quoteHandler = fileType != null ? TypedHandler.getQuoteHandlerForType(fileType) : null;
}
if (quoteHandler != null) {
EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
HighlighterIterator iterator = highlighter.createIterator(offset - 1);
return StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(iterator.getTokenType()) || quoteHandler.isInsideLiteral(iterator);
}
}
return false;
}
@Nonnull
@Override
public MergeRequest createMergeRequest(@Nullable Project project,
@Nullable FileType fileType,
@Nonnull Document outputDocument,
@Nonnull List<String> textContents,
@Nullable String title,
@Nonnull List<String> titles,
@Nullable Consumer<MergeResult> applyCallback) throws InvalidDiffRequestException {
if (textContents.size() != 3) throw new IllegalArgumentException();
if (titles.size() != 3) throw new IllegalArgumentException();
if (!DiffUtil.canMakeWritable(outputDocument)) throw new InvalidDiffRequestException("Output is read only");
DocumentContent outputContent = myContentFactory.create(project, outputDocument, fileType);
CharSequence originalContent = outputDocument.getImmutableCharSequence();
List<DocumentContent> contents = new ArrayList<>(3);
for (String text : textContents) {
contents.add(myContentFactory.create(project, text, fileType));
}
return new TextMergeRequestImpl(project, outputContent, originalContent, contents, title, titles, applyCallback);
}
@Override
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
VirtualFile newFile = event.getNewFile();
if (newFile != null) {
FileType fileType = newFile.getFileType();
if (FileHelper.isReason(fileType) || FileHelper.isOCaml(fileType)) {
// On tab change, we redo the background compilation
Document document = FileDocumentManager.getInstance().getDocument(newFile);
InsightUpdateQueue insightUpdateQueue = document == null ? null : document.getUserData(INSIGHT_QUEUE);
if (insightUpdateQueue != null) {
insightUpdateQueue.queue(m_project, document);
}
// and refresh inferred types
InferredTypesService.queryForSelectedTextEditor(m_project);
}
}
}
@Nonnull
private static DocumentContent createImpl(@javax.annotation.Nullable Project project,
@Nonnull String text,
@Nullable FileType fileType,
@Nullable String fileName,
@Nullable VirtualFile highlightFile,
@javax.annotation.Nullable Charset charset,
@javax.annotation.Nullable Boolean bom,
boolean respectLineSeparators,
boolean readOnly) {
if (UnknownFileType.INSTANCE == fileType) fileType = PlainTextFileType.INSTANCE;
// TODO: detect invalid (different across the file) separators ?
LineSeparator separator = respectLineSeparators ? StringUtil.detectSeparators(text) : null;
String correctedContent = StringUtil.convertLineSeparators(text);
Document document = createDocument(project, correctedContent, fileType, fileName, readOnly);
DocumentContent content = new DocumentContentImpl(project, document, fileType, highlightFile, separator, charset, bom);
if (fileName != null) content.putUserData(DiffUserDataKeysEx.FILE_NAME, fileName);
return content;
}
@Nonnull
public static FileType substituteFileType(VirtualFile file, @Nonnull FileType fileType, Project project) {
if (project == null) {
return fileType;
}
if (fileType instanceof LanguageFileType) {
final Language language = ((LanguageFileType)fileType).getLanguage();
final Language substitutedLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(language, file, project);
LanguageFileType substFileType = substitutedLanguage.getAssociatedFileType();
if (!substitutedLanguage.equals(language) && substFileType != null) {
return new SubstitutedFileType(fileType, substFileType, substitutedLanguage);
}
}
return fileType;
}
@Nonnull
private static DocumentContent createFromBytesImpl(@Nullable Project project,
@Nonnull byte[] content,
@Nonnull FileType fileType,
@Nonnull String fileName,
@javax.annotation.Nullable VirtualFile highlightFile,
@Nonnull Charset charset) {
Charset bomCharset = CharsetToolkit.guessFromBOM(content);
boolean isBOM = bomCharset != null;
if (isBOM) charset = bomCharset;
boolean malformedContent = false;
String text = CharsetToolkit.tryDecodeString(content, charset);
LineSeparator separator = StringUtil.detectSeparators(text);
String correctedContent = StringUtil.convertLineSeparators(text);
DocumentContent documentContent = createImpl(project, correctedContent, fileType, fileName, highlightFile, charset, isBOM, true, true);
if (malformedContent) {
String notificationText = "Content was decoded with errors (using " + "'" + charset.name() + "' charset)";
DiffUtil.addNotification(DiffNotifications.createNotification(notificationText, LightColors.RED), documentContent);
}
return documentContent;
}
@Nullable
private DiffTool chooseTool(DiffRequest data) {
final DiffContent[] contents = data.getContents();
if (contents.length == 2) {
final FileType type1 = contents[0].getContentType();
final FileType type2 = contents[1].getContentType();
if (type1 == type2 && type1 instanceof UIBasedFileType) {
return BinaryDiffTool.INSTANCE;
}
//todo[kb] register or not this instance in common diff tools ?
if (type1 == type2 && type1 instanceof ArchiveFileType) {
return ArchiveDiffTool.INSTANCE;
}
}
for (DiffTool tool : myTools) {
if (tool.canShow(data)) return tool;
}
return null;
}
@Override
public void update(AnActionEvent e) {
DataContext dataContext = e.getDataContext();
final VirtualFile[] selectedFiles = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
final Presentation presentation = e.getPresentation();
final EnforcedPlainTextFileTypeManager typeManager = EnforcedPlainTextFileTypeManager.getInstance();
presentation.setVisible(false);
if (typeManager == null || selectedFiles == null || selectedFiles.length == 0) {
return;
}
FileType originalType = null;
for (VirtualFile file : selectedFiles) {
if (typeManager.isMarkedAsPlainText(file)) {
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(file.getName());
if (originalType == null) {
originalType = fileType;
}
else if (fileType != originalType) {
return;
}
}
else {
return;
}
}
if (originalType == null) return;
presentation.setVisible(true);
presentation.setText(ActionsBundle.actionText("MarkAsOriginalTypeAction") + " " + originalType.getName());
presentation.setIcon(originalType.getIcon());
}
@Override
@Nonnull
protected List<FileType> getAllFilterValues() {
List<FileType> elements = new ArrayList<>();
ContainerUtil.addAll(elements, FileTypeManager.getInstance().getRegisteredFileTypes());
Collections.sort(elements, FileTypeComparator.INSTANCE);
return elements;
}
public NameSuggestionsField(final String[] suggestedNames, final Project project, final FileType fileType, @Nullable final Editor editor) {
this(suggestedNames, project, fileType);
if (editor == null) return;
// later here because EditorTextField creates Editor during addNotify()
final Runnable selectionRunnable = new Runnable() {
@Override
public void run() {
final int offset = editor.getCaretModel().getOffset();
List<TextRange> ranges = new ArrayList<TextRange>();
SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editor.getDocument().getCharsSequence(), offset, ranges);
Editor myEditor = getEditor();
if (myEditor == null) return;
for (TextRange wordRange : ranges) {
String word = editor.getDocument().getText(wordRange);
if (!word.equals(getEnteredName())) continue;
final SelectionModel selectionModel = editor.getSelectionModel();
myEditor.getSelectionModel().removeSelection();
final int wordRangeStartOffset = wordRange.getStartOffset();
int myOffset = offset - wordRangeStartOffset;
myEditor.getCaretModel().moveToOffset(myOffset);
TextRange selected = new TextRange(Math.max(0, selectionModel.getSelectionStart() - wordRangeStartOffset),
Math.max(0, selectionModel.getSelectionEnd() - wordRangeStartOffset));
selected = selected.intersection(new TextRange(0, myEditor.getDocument().getTextLength()));
if (selectionModel.hasSelection() && selected != null && !selected.isEmpty()) {
myEditor.getSelectionModel().setSelection(selected.getStartOffset(), selected.getEndOffset());
}
else if (shouldSelectAll()) {
myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength());
}
break;
}
}
};
SwingUtilities.invokeLater(selectionRunnable);
}
private void applyCodeStyleSettings(final List<OutPair> outPairs, final CodeStyleSettings codeStyleSettings,
final VirtualFile file) {
// Apply indent options
final String indentSize = Utils.configValueForKey(outPairs, indentSizeKey);
final String tabWidth = Utils.configValueForKey(outPairs, tabWidthKey);
final String indentStyle = Utils.configValueForKey(outPairs, indentStyleKey);
final FileType fileType = file.getFileType();
final Language language = fileType instanceof LanguageFileType ? ((LanguageFileType)fileType).getLanguage() :
PlainTextLanguage.INSTANCE;
final CommonCodeStyleSettings commonSettings = codeStyleSettings.getCommonSettings(language);
final CommonCodeStyleSettings.IndentOptions indentOptions = commonSettings.getIndentOptions();
applyIndentOptions(indentOptions, indentSize, tabWidth, indentStyle, file.getCanonicalPath());
}
/**
* TODO we need a similar method for generic IDocument (enabling non-IFiles)
*
* @param file
* @param request
* @return
* @throws IOException
* @noreference This method is currently internal and should only be referenced
* for testing
*/
@Nonnull
public Collection<LanguageServerWrapper> getLSWrappers(@Nonnull VirtualFile file,
@Nullable Predicate<ServerCapabilities> request) throws IOException {
LinkedHashSet<LanguageServerWrapper> res = new LinkedHashSet<>();
Module project = LSPIJUtils.getProject(file);
if (project == null) {
return res;
}
res.addAll(getMatchingStartedWrappers(file, request));
// look for running language servers via content-type
Queue<FileType> contentTypes = new LinkedList<>();
Set<FileType> addedContentTypes = new HashSet<>();
contentTypes.addAll(LSPIJUtils.getFileContentTypes(file));
addedContentTypes.addAll(contentTypes);
while (!contentTypes.isEmpty()) {
FileType contentType = contentTypes.poll();
if (contentType == null) {
continue;
}
for (ContentTypeToLanguageServerDefinition mapping : LanguageServersRegistry.getInstance().findProviderFor(contentType)) {
if (mapping != null && mapping.getValue() != null && mapping.isEnabled()) {
LanguageServerWrapper wrapper = getLSWrapperForConnection(project, mapping.getValue(), LSPIJUtils.toUri(file));
if (request == null
|| wrapper.getServerCapabilities() == null /* null check is workaround for https://github.com/TypeFox/ls-api/issues/47 */
|| request.test(wrapper.getServerCapabilities())) {
res.add(wrapper);
}
}
}
}
return res;
}
@Nonnull
private static DetectResult detectHardCharset(@Nonnull VirtualFile virtualFile, @Nonnull byte[] content, int length, @Nonnull FileType fileType) {
String charsetName = fileType.getCharset(virtualFile, content);
DetectResult guessed = guessFromContent(virtualFile, content, length);
Charset hardCodedCharset = charsetName == null ? guessed.hardCodedCharset : CharsetToolkit.forName(charsetName);
if (hardCodedCharset == null && guessed.guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
return new DetectResult(StandardCharsets.UTF_8, guessed.guessed, guessed.BOM);
}
return new DetectResult(hardCodedCharset, guessed.guessed, guessed.BOM);
}
@Nullable
private static CompletionData getCompletionDataByFileType(FileType fileType) {
for (CompletionDataEP ep : CompletionDataEP.EP_NAME.getExtensionList()) {
if (ep.fileType.equals(fileType.getName())) {
return ep.getHandler();
}
}
return null;
}
@Override
@Nonnull
public VirtualFile[] getFiles(final FileType fileType, final boolean inSourceOnly) {
final List<VirtualFile> files = new ArrayList<VirtualFile>();
final FileIndex[] fileIndices = getFileIndices();
for (final FileIndex fileIndex : fileIndices) {
fileIndex.iterateContent(new ModuleRootCompilerContentIterator(fileType, files));
}
return VfsUtil.toVirtualFileArray(files);
}
@Override
public Result beforeCharTyped(final char charTyped, final Project project, final Editor editor, final PsiFile file, final FileType fileType) {
// TODO[oleg] remove this hack when API changes
if (myReplacedTextRange != null) {
if (myReplacedTextRange.getEndOffset() <= editor.getDocument().getTextLength()) {
if (myRestoreStickySelection && editor instanceof EditorEx) {
EditorEx editorEx = (EditorEx)editor;
CaretModel caretModel = editorEx.getCaretModel();
caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getStartOffset() : myReplacedTextRange.getEndOffset());
editorEx.setStickySelection(true);
caretModel.moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
}
else {
if (myLtrSelection || editor instanceof EditorWindow) {
editor.getSelectionModel().setSelection(myReplacedTextRange.getStartOffset(), myReplacedTextRange.getEndOffset());
}
else {
editor.getSelectionModel().setSelection(myReplacedTextRange.getEndOffset(), myReplacedTextRange.getStartOffset());
}
if (Registry.is("editor.smarterSelectionQuoting")) {
editor.getCaretModel().moveToOffset(myLtrSelection ? myReplacedTextRange.getEndOffset() : myReplacedTextRange.getStartOffset());
}
}
}
myReplacedTextRange = null;
return Result.STOP;
}
return Result.CONTINUE;
}
public CombinedEditorData(@Nonnull CharSequence text,
@Nullable EditorHighlighter highlighter,
@Nullable UnifiedEditorRangeHighlighter rangeHighlighter,
@Nullable FileType fileType,
@Nonnull TIntFunction convertor1,
@Nonnull TIntFunction convertor2) {
myText = text;
myHighlighter = highlighter;
myRangeHighlighter = rangeHighlighter;
myFileType = fileType;
myLineConvertor1 = convertor1;
myLineConvertor2 = convertor2;
}
@SuppressWarnings({"HardCodedStringLiteral"})
private void writeString(Writer writer, CharSequence charArray, int start, int length, FileType fileType) throws IOException {
for(int i=start; i<start+length; i++) {
char c = charArray.charAt(i);
if(c=='<') {
writeChar(writer, "<");
}
else if(c=='>') {
writeChar(writer, ">");
}
else if (c=='&') {
writeChar(writer, "&");
}
else if (c=='\"') {
writeChar(writer, """);
}
else if (c == '\t') {
int tabSize = CodeStyleSettingsManager.getSettings(myProject).getTabSize(fileType);
if (tabSize <= 0) tabSize = 1;
int nSpaces = tabSize - myColumn % tabSize;
for (int j = 0; j < nSpaces; j++) {
writeChar(writer, " ");
}
}
else if (c == '\n' || c == '\r') {
if (c == '\r' && i+1 < start+length && charArray.charAt(i+1) == '\n') {
writeChar(writer, " \r");
i++;
}
else if (c == '\n') {
writeChar(writer, " ");
}
writeLineNumber(writer);
}
else {
writeChar(writer, String.valueOf(c));
}
}
}
@Override
@RequiredUIAccess
public Result beforeCharTyped(char c, Project project, Editor editor, PsiFile file, FileType fileType)
{
if(!(file instanceof CSharpFile))
{
return Result.CONTINUE;
}
if(c == '.')
{
if(handleDotAtPointerType(editor, file))
{
return Result.STOP;
}
autoPopupMemberLookup(project, editor);
}
if(c == '#')
{
autoPopupMemberLookup(project, editor);
}
if(c == ';')
{
if(handleSemicolon(editor))
{
return Result.STOP;
}
}
return Result.CONTINUE;
}
@Override
@Nonnull
public PsiFile createFileFromText(@Nonnull String name, @Nonnull String text) {
FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(name);
if (type.isBinary()) {
throw new RuntimeException("Cannot create binary files from text: name " + name + ", file type " + type);
}
return createFileFromText(name, type, text);
}
private void configureByText(final String usageText, FileType fileType) {
Document document = myEditor.getDocument();
String text = StringUtil.convertLineSeparators(usageText);
document.replaceString(0, document.getTextLength(), text);
final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
myEditor.setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(fileType, scheme, null));
setupSpots(document);
}
@Override
public EditorHighlighter getEditorHighlighter(@Nullable Project project,
@NotNull FileType type,
@Nullable VirtualFile file,
@NotNull EditorColorsScheme scheme) {
return new FluidTemplateHighlighter(project, file, scheme);
}
public Self withFileType(final ElementPattern<? extends FileType> fileTypePattern) {
return with(new PatternCondition<T>("withFileType") {
@Override
public boolean accepts(@Nonnull T file, ProcessingContext context) {
return fileTypePattern.accepts(file.getFileType(), context);
}
});
}
@Nonnull
public FileType getFileType(@Nonnull String fileName) {
return FileTypeManager.getInstance().getFileTypeByFileName(fileName);
}
private static boolean isBinaryWithoutDecompiler(VirtualFile file) {
final FileType ft = file.getFileType();
return ft.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) == null;
}
/**
* @deprecated Use {@link #getIndent(PsiFile, ASTNode)}
*/
@Deprecated
public final int getIndent(Project project, FileType fileType, ASTNode element) {
return getIndent(getFile(element), element);
}
@Override
public boolean isLBraceToken(final HighlighterIterator iterator, final CharSequence fileText, final FileType fileType) {
return false;
}
@Nullable
public FileType getContentType() {
FileType type = myFile.getFileType();
return isUnknown(type) ? myType : type;
}