Java Code Examples for com.intellij.openapi.fileTypes.FileType

The following are top voted examples for showing how to use com.intellij.openapi.fileTypes.FileType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AppleScript-IDEA   File: AppleScriptPairedBraceMatcher.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isRBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
  BracePair pair = findPair(false, iterator, fileText, fileType);
  if (pair == null) return false;
  if (pair.getRightBraceType() != AppleScriptTypes.END)
    return super.isRBraceToken(iterator, fileText, fileType);//true;

  boolean result = false;
  int count = 0;
  while (true) {
    iterator.retreat();
    count++;
    if (iterator.atEnd()) break;
    IElementType eType = iterator.getTokenType();
    if (eType == AppleScriptTypes.NLS || eType == AppleScriptTypes.BLOCK_BODY)
      result = true;
    else break;
  }
  while (count-- > 0) iterator.advance();
  return result;
}
 
Example 2
Project: bamboo-soy   File: SoyLayeredHighlighter.java   Source Code and License 6 votes vote down vote up
public SoyLayeredHighlighter(
    @Nullable Project project,
    @Nullable VirtualFile virtualFile,
    @NotNull EditorColorsScheme colors) {
  // Creating main highlighter.
  super(new SoySyntaxHighlighter(), colors);

  // Highlighter for the outer language.
  FileType type = null;
  if (project == null || virtualFile == null) {
    type = StdFileTypes.PLAIN_TEXT;
  } else {
    Language language = TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile);
    if (language != null) type = language.getAssociatedFileType();
    if (type == null) type = SoyLanguage.getDefaultTemplateLang();
  }

  SyntaxHighlighter outerHighlighter =
      SyntaxHighlighterFactory.getSyntaxHighlighter(type, project, virtualFile);

  registerLayer(OTHER, new LayerDescriptor(outerHighlighter, ""));
}
 
Example 3
Project: intellij-ce-playground   File: XmlSyncTagTest.java   Source Code and License 6 votes vote down vote up
protected void doTestCompletion(final FileType fileType,
                                final String text,
                                final String toType,
                                final String result) {
  myFixture.configureByText(fileType, text);
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          myFixture.completeBasic();
          if (toType != null) myFixture.type(toType);
        }
      });
    }
  }, "Typing", DocCommandGroupId.noneGroupId(myFixture.getEditor().getDocument()), myFixture.getEditor().getDocument());
  myFixture.checkResult(result);
}
 
Example 4
Project: intellij-ce-playground   File: SyntaxInfoConstructionTest.java   Source Code and License 6 votes vote down vote up
public void testNonPhysicalFile() throws Exception {
  String fileName = "Test.java";
  FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName);
  PsiFile psiFile = PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, fileType, "class Test {}", 0, false);
  VirtualFile virtualFile = psiFile.getViewProvider().getVirtualFile();
  Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
  assertNotNull(document);
  EditorFactory editorFactory = EditorFactory.getInstance();
  Editor editor = editorFactory.createViewer(document, getProject());
  try {
    editor.getSelectionModel().setSelection(0, document.getTextLength());
    String syntaxInfo = getSyntaxInfo(editor, psiFile);
    assertEquals("foreground=java.awt.Color[r=0,g=0,b=128],fontStyle=1,text=class \n" +
                 "foreground=java.awt.Color[r=0,g=0,b=0],fontStyle=0,text=Test {}\n", syntaxInfo);
  }
  finally {
    editorFactory.releaseEditor(editor);
  }
}
 
Example 5
Project: intellij-ce-playground   File: FindDialog.java   Source Code and License 6 votes vote down vote up
private void updateFileTypeForEditorComponent(@NotNull ComboBox inputComboBox) {
  final Component editorComponent = inputComboBox.getEditor().getEditorComponent();

  if (editorComponent instanceof EditorTextField) {
    boolean isRegexp = myCbRegularExpressions.isSelectedWhenSelectable();
    FileType fileType = PlainTextFileType.INSTANCE;
    if (isRegexp) {
      Language regexpLanguage = Language.findLanguageByID("RegExp");
      if (regexpLanguage != null) {
        LanguageFileType regexpFileType = regexpLanguage.getAssociatedFileType();
        if (regexpFileType != null) {
          fileType = regexpFileType;
        }
      }
    }
    String fileName = isRegexp ? "a.regexp" : "a.txt";
    final PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(fileName, fileType, ((EditorTextField)editorComponent).getText(), -1, true);

    ((EditorTextField)editorComponent).setNewDocumentAndFileType(fileType, PsiDocumentManager.getInstance(myProject).getDocument(file));
  }
}
 
Example 6
Project: intellij-ce-playground   File: FileSystemTreeImpl.java   Source Code and License 6 votes vote down vote up
public Exception createNewFile(final VirtualFile parentDirectory, final String newFileName, final FileType fileType, final String initialContent) {
  final Exception[] failReason = new Exception[] { null };
  CommandProcessor.getInstance().executeCommand(
      myProject, new Runnable() {
        public void run() {
          ApplicationManager.getApplication().runWriteAction(new Runnable() {
            public void run() {
              try {
                final String newFileNameWithExtension = newFileName.endsWith('.'+fileType.getDefaultExtension())? newFileName : newFileName+'.'+fileType.getDefaultExtension();
                final VirtualFile file = parentDirectory.createChildData(this, newFileNameWithExtension);
                VfsUtil.saveText(file, initialContent != null ? initialContent : "");
                updateTree();
                select(file, null);
              }
              catch (IOException e) {
                failReason[0] = e;
              }
            }
          });
        }
      },
      UIBundle.message("file.chooser.create.new.file.command.name"),
      null
  );
  return failReason[0];
}
 
Example 7
Project: intellij-ce-playground   File: PyKeywordTypedHandler.java   Source Code and License 6 votes vote down vote up
@Override
public Result beforeCharTyped(char character, Project project, Editor editor, PsiFile file, FileType fileType) {
  if (!(fileType instanceof PythonFileType)) return Result.CONTINUE; // else we'd mess up with other file types!
  if (character == ':') {
    final Document document = editor.getDocument();
    final int offset = editor.getCaretModel().getOffset();

    PsiElement token = file.findElementAt(offset - 1);
    if (token == null || offset >= document.getTextLength()) return Result.CONTINUE; // sanity check: beyond EOL

    PsiElement here_elt = file.findElementAt(offset);
    if (here_elt == null) return Result.CONTINUE; 
    if (here_elt instanceof PyStringLiteralExpression || here_elt.getParent() instanceof PyStringLiteralExpression) return Result.CONTINUE;

    // double colons aren't found in Python's syntax, so we can safely overtype a colon everywhere but strings.
    String here_text = here_elt.getText();
    if (":".equals(here_text)) {
      editor.getCaretModel().moveToOffset(offset + 1); // overtype, that is, jump over
      return Result.STOP;
    }
    PyUnindentingInsertHandler.unindentAsNeeded(project, editor, file);
  }

  return Result.CONTINUE; // the default
}
 
Example 8
Project: intellij-ce-playground   File: CreateTaskFileDialog.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public CreateTaskFileDialog(@Nullable Project project, String generatedFileName, @NotNull final Course course) {
  super(project);
  myCourse = course;
  FileType[] fileTypes = FileTypeManager.getInstance().getRegisteredFileTypes();

  DefaultListModel model = new DefaultListModel();
  for (FileType type : fileTypes) {
    if (!type.isReadOnly() && !type.getDefaultExtension().isEmpty()) {
      model.addElement(type);
    }
  }
  myList.setModel(model);
  myTextField.setText(generatedFileName);
  setTitle("Create New Task File");
  init();
}
 
Example 9
Project: intellij-ce-playground   File: CompositeDiffTool.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 10
Project: intellij-ce-playground   File: CumulativeStubVersion.java   Source Code and License 6 votes vote down vote up
public static int getCumulativeVersion() {
  int version = VERSION;
  for (final FileType fileType : FileTypeRegistry.getInstance().getRegisteredFileTypes()) {
    if (fileType instanceof LanguageFileType) {
      Language l = ((LanguageFileType)fileType).getLanguage();
      ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l);
      if (parserDefinition != null) {
        final IFileElementType type = parserDefinition.getFileNodeType();
        if (type instanceof IStubFileElementType) {
          version += ((IStubFileElementType)type).getStubVersion();
        }
      }
    }

    BinaryFileStubBuilder builder = BinaryFileStubBuilders.INSTANCE.forFileType(fileType);
    if (builder != null) {
      version += builder.getStubVersion();
    }
  }
  return version;
}
 
Example 11
Project: intellij-ce-playground   File: FileTypeRenderer.java   Source Code and License 6 votes vote down vote up
@Override
public void customize(JList list, FileType type, int index, boolean selected, boolean hasFocus) {
  LayeredIcon layeredIcon = new LayeredIcon(2);
  layeredIcon.setIcon(EMPTY_ICON, 0);
  final Icon icon = type.getIcon();
  if (icon != null) {
    layeredIcon.setIcon(icon, 1, (- icon.getIconWidth() + EMPTY_ICON.getIconWidth())/2, (EMPTY_ICON.getIconHeight() - icon.getIconHeight())/2);
  }

  setIcon(layeredIcon);

  String description = type.getDescription();
  String trimmedDescription = StringUtil.capitalizeWords(description.replaceAll("(?i)\\s*file(?:s)?$", ""), true);
  if (isDuplicated(description)) {
    setText(trimmedDescription + " (" + type.getName() + ")");

  }
  else {
    setText(trimmedDescription);
  }
}
 
Example 12
Project: intellij-ce-playground   File: UnknownFileTypeDiffRequest.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public JComponent getComponent(@NotNull final DiffContext context) {
  final SimpleColoredComponent label = new SimpleColoredComponent();
  label.append("Can't show diff for unknown file type. ",
               new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getInactiveTextColor()));
  if (myFileName != null) {
    label.append("Associate", SimpleTextAttributes.LINK_ATTRIBUTES, new Runnable() {
      @Override
      public void run() {
        DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, new Runnable() {
          @Override
          public void run() {
            FileType type = FileTypeChooser.associateFileType(myFileName);
            if (type != null) onSuccess(context);
          }
        });
      }
    });
    LinkMouseListenerBase.installSingleTagOn(label);
  }
  return DiffUtil.createMessagePanel(label);
}
 
Example 13
Project: intellij-ce-playground   File: ChangeDiffRequestPresentable.java   Source Code and License 6 votes vote down vote up
public static boolean checkAssociate(final Project project, String fileName, DiffChainContext context) {
  final String pattern = FileUtilRt.getExtension(fileName).toLowerCase();
  if (context.contains(pattern)) return false;
  int rc = Messages.showOkCancelDialog(project,
                               VcsBundle.message("diff.unknown.file.type.prompt", fileName),
                               VcsBundle.message("diff.unknown.file.type.title"),
                                 VcsBundle.message("diff.unknown.file.type.associate"),
                                 CommonBundle.getCancelButtonText(),
                               Messages.getQuestionIcon());
  if (rc == Messages.OK) {
    FileType fileType = FileTypeChooser.associateFileType(fileName);
    return fileType != null && !fileType.isBinary();
  } else {
    context.add(pattern);
  }
  return false;
}
 
Example 14
Project: intellij-ce-playground   File: NameSuggestionsField.java   Source Code and License 6 votes vote down vote up
private void setupComboBox(final ComboBox combobox, FileType fileType) {
  final EditorComboBoxEditor comboEditor = new StringComboboxEditor(myProject, fileType, combobox) {
    @Override
    public void setItem(Object anObject) {
      myNonHumanChange = true;
      super.setItem(anObject);
    }
  };

  combobox.setEditor(comboEditor);
  combobox.setRenderer(new EditorComboBoxRenderer(comboEditor));

  combobox.setEditable(true);
  combobox.setMaximumRowCount(8);

  comboEditor.selectAll();
}
 
Example 15
Project: reasonml-idea-plugin   File: BucklescriptProjectComponent.java   Source Code and License 5 votes vote down vote up
@Override
public void run(FileType fileType) {
    if (m_compiler != null && (fileType instanceof RmlFileType || fileType instanceof OclFileType)) {
        ProcessHandler recreate = m_compiler.recreate();
        if (recreate != null) {
            getBsbConsole().attachToProcess(recreate);
            m_compiler.startNotify();
        }
    }
}
 
Example 16
Project: reasonml-idea-plugin   File: VirtualFileListener.java   Source Code and License 5 votes vote down vote up
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
    VirtualFile file = event.getFile();
    FileType fileType = file.getFileType();

    if (fileType instanceof JsonFileType) {
        if (file.getName().equals("bsconfig.json")) {
            m_bucklescript.refresh();
        }
    } else if (event.isFromSave()) {
        m_bucklescript.run(fileType);
    }
}
 
Example 17
Project: SmartQQ4IntelliJ   File: VFSUtils.java   Source Code and License 5 votes vote down vote up
private static FileType getArchiveFileType() {
    FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(".zip");
    if (fileType == FileTypeManager.getInstance().getFileTypeByExtension(".kokoko")) {
        fileType = FileTypeManager.getInstance().getFileTypeByExtension("zip");
    }
    return fileType;
}
 
Example 18
Project: yii2inspections   File: TranslationCallsIndexer.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public FileBasedIndex.InputFilter getInputFilter() {
    return file -> {
        final FileType fileType = file.getFileType();
        if (PhpFileType.INSTANCE == fileType) {
            return !file.getPath().matches(".*/(translations|messages)/([a-zA-z]{2}(-[a-zA-z]{2})?)/[^/]+\\.php$");
        }

        return HtmlFileType.INSTANCE == fileType || TwigFileType.INSTANCE == fileType;
    };
}
 
Example 19
Project: bamboo-soy   File: SoyFileType.java   Source Code and License 5 votes vote down vote up
private SoyFileType() {
  super(SoyLanguage.INSTANCE);
  FileTypeEditorHighlighterProviders.INSTANCE.addExplicitExtension(
      this,
      (@Nullable Project project,
          @NotNull FileType fileType,
          @Nullable VirtualFile virtualFile,
          @NotNull EditorColorsScheme editorColorsScheme) ->
          new SoyLayeredHighlighter(project, virtualFile, editorColorsScheme));
}
 
Example 20
Project: json2java4idea   File: Extensions.java   Source Code and License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public static String remove(@Nonnull String fileName, @Nonnull FileType fileType) {
    final String extension = fileType.getDefaultExtension();
    if (fileName.endsWith(DELIMITER + extension)) {
        return fileName.substring(0, fileName.length() - (extension.length() + 1));
    }
    return fileName;
}
 
Example 21
Project: json2java4idea   File: Extensions.java   Source Code and License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public static String append(@Nonnull String fileName, @Nonnull FileType fileType) {
    final String extension = fileType.getDefaultExtension();
    if (fileName.endsWith(DELIMITER + extension)) {
        return fileName;
    }
    return fileName + DELIMITER + extension;
}
 
Example 22
Project: intellij-bpmn-editor   File: BPMNFileTypeFactory.java   Source Code and License 5 votes vote down vote up
public static boolean isBPMN(@NotNull VirtualFile virtualFile) {
    if (BPMN_EXTENSION.equals(virtualFile.getExtension())) {
        final FileType fileType = virtualFile.getFileType();
        if (fileType == getFileType() && !fileType.isBinary()) {
            return virtualFile.getName().endsWith(DOT_BPMN_EXTENSION);
        }
    }
    return false;
}
 
Example 23
Project: educational-plugin   File: StudyTypeHandlerDelegate.java   Source Code and License 5 votes vote down vote up
@Override
public Result beforeCharTyped(char c,
                              Project project,
                              Editor editor,
                              PsiFile file,
                              FileType fileType) {
  return handleTyping(project, editor, file, true);
}
 
Example 24
Project: GravSupport   File: FileCreateUtil.java   Source Code and License 5 votes vote down vote up
public static List<VirtualFile> findFileByRelativePath(@NotNull Project project, @NotNull String fileRelativePath) {
    String relativePath = fileRelativePath.startsWith("/") ? fileRelativePath : "/" + fileRelativePath;
    Set<FileType> fileTypes = Collections.singleton(FileTypeManager.getInstance().getFileTypeByFileName(relativePath));
    final List<VirtualFile> fileList = new ArrayList<>();
    FileBasedIndex.getInstance().processFilesContainingAllKeys(FileTypeIndex.NAME, fileTypes, GlobalSearchScope.projectScope(project), null, virtualFile -> {
        if (virtualFile.getPath().endsWith(relativePath)) {
            fileList.add(virtualFile);
        }
        return true;
    });
    return fileList;
}
 
Example 25
Project: GravSupport   File: LanguageFileEditorGUI.java   Source Code and License 5 votes vote down vote up
public Editor createEditor(Document document, Project project, @Nullable FileType fileType) {
    EditorImpl editor = (EditorImpl) EditorFactory.getInstance().createEditor(document, project);
    if (fileType != null) {
        editor.setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(project, fileType));
    }
    return editor;
}
 
Example 26
Project: intellij-ce-playground   File: BraceHighlightingHandler.java   Source Code and License 5 votes vote down vote up
private void doHighlight(int offset, int originalOffset, @NotNull FileType fileType) {
  if (myEditor.getFoldingModel().isOffsetCollapsed(offset)) return;

  HighlighterIterator iterator = getEditorHighlighter().createIterator(offset);
  final CharSequence chars = myDocument.getCharsSequence();

  if (BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) {
    IElementType tokenType = iterator.getTokenType();

    iterator.advance();
    if (!iterator.atEnd() && BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) {
      if (BraceMatchingUtil.isPairBraces(tokenType, iterator.getTokenType(), fileType) &&
          originalOffset == iterator.getStart()) return;
    }

    iterator.retreat();
    highlightLeftBrace(iterator, false, fileType);

    if (offset > 0) {
      iterator = getEditorHighlighter().createIterator(offset - 1);
      if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) {
        highlightRightBrace(iterator, fileType);
      }
    }
  }
  else if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) {
    highlightRightBrace(iterator, fileType);
  }
}
 
Example 27
Project: lua-for-idea   File: LuaTypedInsideBlockDelegate.java   Source Code and License 5 votes vote down vote up
@Override
public Result beforeCharTyped(char c, Project project, Editor editor, PsiFile file, FileType fileType) {
    if (! (file instanceof LuaPsiFile))
        return Result.CONTINUE;
    if (c != ')' && c != '(')
        return Result.CONTINUE;

    int caretOffset = editor.getCaretModel().getOffset();
    PsiElement e1 = file.findElementAt(caretOffset);

    preserveParen = (e1 != null && e1.getText().equals(")"));

    return super.beforeCharTyped(c, project, editor, file,
            fileType);   
}
 
Example 28
Project: intellij-ce-playground   File: SimpleContent.java   Source Code and License 5 votes vote down vote up
public SimpleContent(@NotNull String text, FileType type, EditorFactory f) {
  myOriginalBytes = text.getBytes();
  myOriginalText = myLineSeparators.correctText(text);
  myDocument = f.createDocument(myOriginalText);
  setReadOnly(true);
  myType = type;
}
 
Example 29
Project: intellij-ce-playground   File: TreeClassChooserFactoryImpl.java   Source Code and License 5 votes vote down vote up
@NotNull
public TreeFileChooser createFileChooser(@NotNull String title, @Nullable PsiFile initialFile, @Nullable FileType fileType,
                                         @Nullable TreeFileChooser.PsiFileFilter filter,
                                         boolean disableStructureProviders,
                                         boolean showLibraryContents) {
  return new TreeFileChooserDialog(myProject, title, initialFile, fileType, filter, disableStructureProviders, showLibraryContents);
}
 
Example 30
Project: intellij-ce-playground   File: FragmentContent.java   Source Code and License 5 votes vote down vote up
public FragmentContent(@NotNull DiffContent original, @NotNull TextRange range, Project project, FileType fileType, boolean forceReadOnly) {
  RangeMarker rangeMarker = original.getDocument().createRangeMarker(range.getStartOffset(), range.getEndOffset(), true);
  rangeMarker.setGreedyToLeft(true);
  rangeMarker.setGreedyToRight(true);
  mySynchonizer = new MyDocumentsSynchronizer(project, rangeMarker);
  myOriginal = original;
  myType = fileType;
  myForceReadOnly = forceReadOnly;
}
 
Example 31
Project: intellij-ce-playground   File: MatcherImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the matches of given pattern starting from given tree element.
 * @param source string for search
 * @param pattern to be searched
 * @return list of matches found
 * @throws MalformedPatternException
 * @throws UnsupportedPatternException
 */
protected List<MatchResult> testFindMatches(String source,
                                            String pattern,
                                            MatchOptions options,
                                            boolean filePattern,
                                            FileType sourceFileType,
                                            String sourceExtension,
                                            boolean physicalSourceFile)
  throws MalformedPatternException, UnsupportedPatternException {

  CollectingMatchResultSink sink = new CollectingMatchResultSink();

  try {
    PsiElement[] elements = MatcherImplUtil.createSourceTreeFromText(source,
                                                                     filePattern ? PatternTreeContext.File : PatternTreeContext.Block,
                                                                     sourceFileType,
                                                                     sourceExtension,
                                                                     project, physicalSourceFile);

    options.setSearchPattern(pattern);
    options.setScope(new LocalSearchScope(elements));
    testFindMatches(sink, options);
  }
  catch (IncorrectOperationException e) {
    MalformedPatternException exception = new MalformedPatternException();
    exception.initCause(e);
    throw exception;
  } finally {
    options.setScope(null);
  }

  return sink.getMatches();
}
 
Example 32
Project: intellij-ce-playground   File: JavaVfsSourceRootDetectionUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Scan directory and detect java source roots within it. The source root is detected as the following:
 * <ol>
 * <li>It contains at least one Java file.</li>
 * <li>Java file is located in the sub-folder that matches package statement in the file.</li>
 * </ol>
 *
 * @param dir a directory to scan
 * @param progressIndicator
 * @return a list of found source roots within directory. If no source roots are found, a empty list is returned.
 */
@NotNull
public static List<VirtualFile> suggestRoots(@NotNull VirtualFile dir, @NotNull final ProgressIndicator progressIndicator) {
  if (!dir.isDirectory()) {
    return ContainerUtil.emptyList();
  }

  final FileTypeManager typeManager = FileTypeManager.getInstance();
  final ArrayList<VirtualFile> foundDirectories = new ArrayList<VirtualFile>();
  try {
    VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor() {
      @NotNull
      @Override
      public Result visitFileEx(@NotNull VirtualFile file) {
        progressIndicator.checkCanceled();

        if (file.isDirectory()) {
          if (typeManager.isFileIgnored(file) || StringUtil.startsWithIgnoreCase(file.getName(), "testData")) {
            return SKIP_CHILDREN;
          }
        }
        else {
          FileType type = typeManager.getFileTypeByFileName(file.getName());
          if (StdFileTypes.JAVA == type) {
            VirtualFile root = suggestRootForJavaFile(file);
            if (root != null) {
              foundDirectories.add(root);
              return skipTo(root);
            }
          }
        }

        return CONTINUE;
      }
    });
  }
  catch (ProcessCanceledException ignore) { }

  return foundDirectories;
}
 
Example 33
Project: intellij-ce-playground   File: ExternalResourceManagerExImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String[] getResourceUrls(@Nullable FileType fileType, @Nullable @NonNls String version, boolean includeStandard) {
  List<String> result = new LinkedList<String>();
  addResourcesFromMap(result, version, myResources);

  if (includeStandard) {
    addResourcesFromMap(result, version, myStandardResources.getValue());
  }

  return ArrayUtil.toStringArray(result);
}
 
Example 34
Project: intellij-ce-playground   File: PsiFileFactoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
@NotNull
public PsiFile createFileFromText(@NotNull String name, @NotNull 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);
}
 
Example 35
Project: intellij-ce-playground   File: XmlSlashTypedHandler.java   Source Code and License 5 votes vote down vote up
@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
  if (c == '/' && XmlGtTypedHandler.fileContainsXmlLanguage(editedFile)) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    final int offset = editor.getCaretModel().getOffset();
    if (file == null) return Result.CONTINUE;
    FileViewProvider provider = file.getViewProvider();
    PsiElement element = provider.findElementAt(offset, XMLLanguage.class);

    if (element instanceof XmlToken) {
      final IElementType tokenType = ((XmlToken)element).getTokenType();

      if (tokenType == XmlTokenType.XML_EMPTY_ELEMENT_END &&
          offset == element.getTextOffset()
         ) {
        editor.getCaretModel().moveToOffset(offset + 1);
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        return Result.STOP;
      } else if (tokenType == XmlTokenType.XML_TAG_END &&
                 offset == element.getTextOffset()
                ) {
        final ASTNode parentNode = element.getParent().getNode();
        final ASTNode child = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(parentNode);

        if (child != null && offset + 1 == child.getTextRange().getStartOffset()) {
          editor.getDocument().replaceString(offset + 1, parentNode.getTextRange().getEndOffset(),"");
        }
      }
    }
  }
  return Result.CONTINUE;
}
 
Example 36
Project: intellij-ce-playground   File: GotoFileAction.java   Source Code and License 5 votes vote down vote up
@Override
@NotNull
protected List<FileType> getAllFilterValues() {
  List<FileType> elements = new ArrayList<FileType>();
  ContainerUtil.addAll(elements, FileTypeManager.getInstance().getRegisteredFileTypes());
  Collections.sort(elements, FileTypeComparator.INSTANCE);
  return elements;
}
 
Example 37
Project: intellij-ce-playground   File: DaemonCodeAnalyzerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isHighlightingAvailable(@Nullable PsiFile file) {
  if (file == null || !file.isPhysical()) return false;
  if (myDisabledHighlightingFiles.contains(PsiUtilCore.getVirtualFile(file))) return false;

  if (file instanceof PsiCompiledElement) return false;
  final FileType fileType = file.getFileType();

  // To enable T.O.D.O. highlighting
  return !fileType.isBinary();
}
 
Example 38
Project: intellij-ce-playground   File: CodeStyleSettings.java   Source Code and License 5 votes vote down vote up
private void registerAdditionalIndentOptions(FileType fileType, IndentOptions options) {
  boolean exist = false;
  for (final FileType existing : myAdditionalIndentOptions.keySet()) {
    if (Comparing.strEqual(existing.getDefaultExtension(), fileType.getDefaultExtension())) {
      exist = true;
      break;
    }
  }

  if (!exist) {
    myAdditionalIndentOptions.put(fileType, options);
  }
}
 
Example 39
Project: intellij-ce-playground   File: LightStubBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public StubElement buildStubTree(@NotNull PsiFile file) {
  LighterAST tree = FORCED_AST.get();
  if (tree == null) {
    FileType fileType = file.getFileType();
    if (!(fileType instanceof LanguageFileType)) {
      LOG.error("File is not of LanguageFileType: " + fileType + ", " + file);
      return null;
    }
    Language language = ((LanguageFileType)fileType).getLanguage();
    final IFileElementType contentType = LanguageParserDefinitions.INSTANCE.forLanguage(language).getFileNodeType();
    if (!(contentType instanceof IStubFileElementType)) {
      LOG.error("File is not of IStubFileElementType: " + contentType + ", " + file);
      return null;
    }

    final FileASTNode node = file.getNode();
    if (contentType instanceof ILightStubFileElementType) {
      tree = node.getLighterAST();
    }
    else {
      tree = new TreeBackedLighterAST(node);
    }
  } else {
    FORCED_AST.set(null);
  }
  if (tree == null) return null;

  final StubElement rootStub = createStubForFile(file, tree);
  buildStubTree(tree, tree.getRoot(), rootStub);
  return rootStub;
}
 
Example 40
Project: intellij-ce-playground   File: CustomizableLanguageCodeStylePanel.java   Source Code and License 5 votes vote down vote up
@Override
@Nullable
protected EditorHighlighter createHighlighter(final EditorColorsScheme scheme) {
  FileType fileType = getFileType();
  return FileTypeEditorHighlighterProviders.INSTANCE.forFileType(fileType).getEditorHighlighter(
    ProjectUtil.guessCurrentProject(getPanel()), fileType, null, scheme);
}