Java Code Examples for com.intellij.psi.PsiFileFactory#getInstance()

The following examples show how to use com.intellij.psi.PsiFileFactory#getInstance() . 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: PromptConsole.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
PromptConsole(@NotNull Project project, ConsoleViewImpl consoleView) {
    m_consoleView = consoleView;

    EditorFactory editorFactory = EditorFactory.getInstance();
    PsiFileFactory fileFactory = PsiFileFactory.getInstance(project);

    Document outputDocument = ((EditorFactoryImpl) editorFactory).createDocument(true);
    UndoUtil.disableUndoFor(outputDocument);
    m_outputEditor = (EditorImpl) editorFactory.createViewer(outputDocument, project, CONSOLE);

    PsiFile file = fileFactory.createFileFromText("PromptConsoleDocument.ml", OclLanguage.INSTANCE, "");
    Document promptDocument = file.getViewProvider().getDocument();
    m_promptEditor = (EditorImpl) editorFactory.createEditor(promptDocument, project, CONSOLE);

    setupOutputEditor();
    setupPromptEditor();

    m_consoleView.print("(* ctrl+enter to send a command, ctrl+up/down to cycle through history *)\r\n", USER_INPUT);

    m_mainPanel.add(m_outputEditor.getComponent(), BorderLayout.CENTER);
    m_mainPanel.add(m_promptEditor.getComponent(), BorderLayout.SOUTH);
}
 
Example 2
Source File: IgnoreTemplatesFactory.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * Creates new Gitignore file or uses an existing one.
 *
 * @param directory working directory
 * @return file
 */
@Nullable
public PsiFile createFromTemplate(final PsiDirectory directory) throws IncorrectOperationException {
    final String filename = fileType.getIgnoreLanguage().getFilename();
    final PsiFile currentFile = directory.findFile(filename);
    if (currentFile != null) {
        return currentFile;
    }
    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());
    final IgnoreLanguage language = fileType.getIgnoreLanguage();

    String content = StringUtil.join(TEMPLATE_NOTE, Constants.NEWLINE);
    if (language.isSyntaxSupported() && !IgnoreBundle.Syntax.GLOB.equals(language.getDefaultSyntax())) {
        content = StringUtil.join(
                content,
                IgnoreBundle.Syntax.GLOB.getPresentation(),
                Constants.NEWLINE,
                Constants.NEWLINE
        );
    }
    final PsiFile file = factory.createFileFromText(filename, fileType, content);
    return (PsiFile) directory.add(file);
}
 
Example 3
Source File: AbstractDartElementTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates the syntax tree for a Dart file at a specific path and returns the innermost element with the given text.
 */
@NotNull
protected <E extends PsiElement> E setUpDartElement(String filePath, String fileText, String elementText, Class<E> expectedClass) {
  final int offset = fileText.indexOf(elementText);
  if (offset < 0) {
    throw new IllegalArgumentException("'" + elementText + "' not found in '" + fileText + "'");
  }

  final PsiFileFactory factory = PsiFileFactory.getInstance(fixture.getProject());
  final PsiFile file = filePath != null
                       ? factory.createFileFromText(filePath, DartLanguage.INSTANCE, fileText)
                       : factory.createFileFromText(DartLanguage.INSTANCE, fileText);

  PsiElement elt = file.findElementAt(offset);
  while (elt != null) {
    if (elementText.equals(elt.getText())) {
      return expectedClass.cast(elt);
    }
    elt = elt.getParent();
  }

  throw new RuntimeException("unable to find element with text: " + elementText);
}
 
Example 4
Source File: WeexTemplateFactory.java    From weex-language-support with MIT License 6 votes vote down vote up
public static PsiFile createFromTemplate(final PsiDirectory directory, final String name,
                                         String fileName, String templateName,
                                         @NonNls String... parameters) throws IncorrectOperationException {

    final FileTemplate template = FileTemplateManager.getInstance(directory.getProject()).getInternalTemplate(templateName);
    String text;

    try {
        text = template.getText();
    } catch (Exception e) {
        throw new RuntimeException("Unable to load template for " +
                FileTemplateManager.getInstance().internalTemplateToSubject(templateName), e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    final PsiFile file = factory.createFileFromText(fileName, WeexFileType.INSTANCE, text);
    CodeStyleManager.getInstance(directory.getProject()).reformat(file);
    return (PsiFile) directory.add(file);
}
 
Example 5
Source File: AbstractDartElementTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates the syntax tree for a Dart file at a specific path and returns the innermost element with the given text.
 */
@NotNull
protected <E extends PsiElement> E setUpDartElement(String filePath, String fileText, String elementText, Class<E> expectedClass) {
  final int offset = fileText.indexOf(elementText);
  if (offset < 0) {
    throw new IllegalArgumentException("'" + elementText + "' not found in '" + fileText + "'");
  }

  final PsiFileFactory factory = PsiFileFactory.getInstance(fixture.getProject());
  final PsiFile file = filePath != null
                       ? factory.createFileFromText(filePath, DartLanguage.INSTANCE, fileText)
                       : factory.createFileFromText(DartLanguage.INSTANCE, fileText);

  PsiElement elt = file.findElementAt(offset);
  while (elt != null) {
    if (elementText.equals(elt.getText())) {
      return expectedClass.cast(elt);
    }
    elt = elt.getParent();
  }

  throw new RuntimeException("unable to find element with text: " + elementText);
}
 
Example 6
Source File: SaveFile.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 构建对象
 *
 * @param path     路径
 * @param fileName 文件没
 * @param reformat 是否重新格式化代码
 */
public SaveFile(Project project, String path, String fileName, String content, boolean reformat, boolean operateTitle) {
    this.path = path;
    this.project = project;
    // 构建文件对象
    PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
    LOG.assertTrue(content != null);
    FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
    // 换行符统一使用\n
    this.file = psiFileFactory.createFileFromText(fileName, fileType, content.replace("\r", ""));
    this.virtualFile = new LightVirtualFile(fileName, fileType, content.replace("\r", ""));
    this.reformat = reformat;
    this.operateTitle = operateTitle;
}
 
Example 7
Source File: MyPsiUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static PsiElement createLeafFromText(Project project, PsiElement context,
											String text, IElementType type)
{
	PsiFileFactoryImpl factory = (PsiFileFactoryImpl)PsiFileFactory.getInstance(project);
	PsiElement el = factory.createElementFromText(text,
												  ANTLRv4Language.INSTANCE,
												  type,
												  context);
	return PsiTreeUtil.getDeepestFirst(el); // forces parsing of file!!
	// start rule depends on root passed in
}
 
Example 8
Source File: Trees.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static PsiFile createFile(Project project, Language language, String text) {
	LanguageFileType ftype = language.getAssociatedFileType();
	if ( ftype==null ) return null;
	String ext = ftype.getDefaultExtension();
	String fileName = "___fubar___."+ext; // random name but must have correct extension
	PsiFileFactoryImpl factory = (PsiFileFactoryImpl)PsiFileFactory.getInstance(project);
	return factory.createFileFromText(fileName, language, text, false, false);
}
 
Example 9
Source File: Trees.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static PsiElement createLeafFromText(Project project, Language language, PsiElement context,
											String text, IElementType type)
{
	PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project);
	PsiElement el = factory.createElementFromText(text, language, type, context);
	if ( el==null ) return null;
	return PsiTreeUtil.getDeepestFirst(el); // forces parsing of file!!
	// start rule depends on root passed in
}
 
Example 10
Source File: FormatterTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final Project project = getProject();
    fileFactory = PsiFileFactory.getInstance(project);
}
 
Example 11
Source File: NewClassCommandAction.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Inject
public NewClassCommandAction(@Nonnull Project project,
                             @Nonnull @Assisted("Name") String name,
                             @Nonnull @Assisted("Json") String json,
                             @Nonnull @Assisted PsiDirectory directory,
                             @Nonnull @Assisted JavaConverter converter) {
    super(project);
    this.fileFactory = PsiFileFactory.getInstance(project);
    this.directoryService = JavaDirectoryService.getInstance();
    this.name = Preconditions.checkNotNull(name);
    this.json = Preconditions.checkNotNull(json);
    this.directory = Preconditions.checkNotNull(directory);
    this.converter = Preconditions.checkNotNull(converter);
}
 
Example 12
Source File: ScratchFileCreationHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static PsiFile parseHeader(@Nonnull Project project, @Nonnull Language language, @Nonnull String text) {
  LanguageFileType fileType = language.getAssociatedFileType();
  CharSequence fileSnippet = StringUtil.first(text, 10 * 1024, false);
  PsiFileFactory fileFactory = PsiFileFactory.getInstance(project);
  return fileFactory.createFileFromText(PathUtil.makeFileName("a", fileType == null ? "" : fileType.getDefaultExtension()), language, fileSnippet);
}
 
Example 13
Source File: ORSignatureTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings({"SameParameterValue", "ConstantConditions"})
@NotNull
private ORSignature makeSignature(@NotNull Language lang, String sig, boolean debug) {
    PsiFileFactory instance = PsiFileFactory.getInstance(getProject());
    PsiFile psiFile = instance.createFileFromText("Dummy." + lang.getAssociatedFileType().getDefaultExtension(), lang, "let x:" + sig);
    if (debug) {
        System.out.println(DebugUtil.psiToString(psiFile, true, true));
    }
    Collection<PsiSignatureItem> items = PsiTreeUtil.findChildrenOfType(psiFile, PsiSignatureItem.class);
    return new ORSignature(RmlLanguage.INSTANCE, items);
}
 
Example 14
Source File: FlutterReduxGen.java    From haystack with MIT License 4 votes vote down vote up
private void genStructure(PageModel pageModel) {
    Project project = directory.getProject();
    PsiFileFactory factory = PsiFileFactory.getInstance(project);
    PsiDirectoryFactory directoryFactory =
            PsiDirectoryFactory.getInstance(directory.getProject());
    String packageName = directoryFactory.getQualifiedName(directory, true);

    FileSaver fileSaver = new IDEFileSaver(factory, directory, DartFileType.INSTANCE);

    fileSaver.setListener(fileName -> {
        int ok = Messages.showOkCancelDialog(
                textResources.getReplaceDialogMessage(fileName),
                textResources.getReplaceDialogTitle(), "OK", "NO",
                UIUtil.getQuestionIcon());
        return ok == 0;
    });

    final String moduleName =
            FileIndexFacade.getInstance(project).getModuleForFile(directory.getVirtualFile()).getName();

    Map<String, Object> rootMap = new HashMap<String, Object>();
    rootMap.put("ProjectName", moduleName);
    rootMap.put("PageType", pageModel.pageType);
    if (pageModel.pageType.equals(CUSTOMSCROLLVIEW)) {
        rootMap.put("GenerateCustomScrollView", true);
    } else {
        rootMap.put("GenerateCustomScrollView", false);
    }
    rootMap.put("PageName", pageModel.pageName);
    rootMap.put("ModelEntryName", pageModel.modelName);
    rootMap.put("GenerateListView", pageModel.genListView);
    rootMap.put("GenerateBottomTabBar", pageModel.genBottomTabBar);
    rootMap.put("GenerateAppBar", pageModel.genAppBar);
    rootMap.put("GenerateDrawer", pageModel.genDrawer);
    rootMap.put("GenerateTopTabBar", pageModel.genTopTabBar);
    rootMap.put("GenerateWebView", pageModel.genWebView);
    rootMap.put("GenerateActionButton", pageModel.genActionButton);

    rootMap.put("viewModelQuery", pageModel.viewModelQuery);
    rootMap.put("viewModelGet", pageModel.viewModelGet);
    rootMap.put("viewModelCreate", pageModel.viewModelCreate);
    rootMap.put("viewModelUpdate", pageModel.viewModelUpdate);
    rootMap.put("viewModelDelete", pageModel.viewModelDelete);

    rootMap.put("GenSliverFixedExtentList", pageModel.genSliverFixedList);
    rootMap.put("GenSliverGrid", pageModel.genSliverGrid);
    rootMap.put("GenSliverToBoxAdapter", pageModel.genSliverToBoxAdapter);
    rootMap.put("FabInAppBar", pageModel.genSliverFab);
    rootMap.put("GenSliverTabBar", pageModel.genSliverTabBar);
    rootMap.put("GenSliverTabView", pageModel.genSliverTabView);
    rootMap.put("IsCustomWidget", pageModel.isCustomWidget);

    if (pageModel.genActionButton) {
        rootMap.put("HasActionSearch", pageModel.hasActionSearch);
        rootMap.put("ActionList", pageModel.actionList);
        rootMap.put("ActionBtnCount", pageModel.actionList.size());
    } else {
        rootMap.put("HasActionSearch", false);
        rootMap.put("ActionList", new ArrayList<String>());
        rootMap.put("ActionBtnCount", 0);
    }
    if (!pageModel.isUIOnly) {
        for (ClassModel classModel : pageModel.classModels) {
            if (classModel.getName().equals(pageModel.modelName)) {
                rootMap.put("genDatabase", classModel.isGenDBModule());

                if (classModel.getUniqueField() != null) {
                    rootMap.put("clsUNName", classModel.getUniqueField());
                    rootMap.put("clsUNNameType", classModel.getUniqueFieldType());
                }
            }
            generateModelEntry(classModel, rootMap);
        }

        generateRepository(rootMap);
        generateRedux(rootMap);
    }
    generateFeature(rootMap, pageModel.isCustomWidget, pageModel.genSliverTabView);
}
 
Example 15
Source File: BuckElementFactory.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Create a {@link BuckFile} seeded with the given text. */
public static BuckFile createFile(Project project, String text) {
  PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
  return (BuckFile) psiFileFactory.createFileFromText(BuckLanguage.INSTANCE, text);
}
 
Example 16
Source File: BcfgElementFactoryTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  PsiFileFactory fileFactory = PsiFileFactory.getInstance(getProject());
  assertNotNull(fileFactory);
}
 
Example 17
Source File: BcfgElementFactory.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Create a {@link BcfgFile} seeded with the given text. */
public static BcfgFile createFile(Project project, String text) {
  PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
  return (BcfgFile) psiFileFactory.createFileFromText(BcfgLanguage.INSTANCE, text);
}
 
Example 18
Source File: TodoCheckinHandlerWorker.java    From consulo with Apache License 2.0 4 votes vote down vote up
private MyEditedFileProcessor(final Project project, Acceptor acceptor, final TodoFilter todoFilter) {
  myAcceptor = acceptor;
  myTodoFilter = todoFilter;
  myPsiFileFactory = PsiFileFactory.getInstance(project);
}
 
Example 19
Source File: ProtoElementFactory.java    From protobuf-jetbrains-plugin with Apache License 2.0 4 votes vote down vote up
public ProtoElementFactory(Project project) {
    this.project = project;
    factory = PsiFileFactory.getInstance(project);
}
 
Example 20
Source File: VueTemplatesFactory.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
public static PsiFile createFromTemplate(final PsiDirectory directory, final String name,
                                         String fileName, String templateName,
                                         @NonNls String... parameters) throws IncorrectOperationException {

    final FileTemplate template = FileTemplateManager.getDefaultInstance().getTemplate(templateName);

    Properties properties = new Properties(FileTemplateManager.getDefaultInstance().getDefaultProperties());

    Project project = directory.getProject();
    properties.setProperty("PROJECT_NAME", project.getName());
    properties.setProperty("NAME", fileName);


    String text;

    try {
        text = template.getText(properties);
    } catch (Exception e) {
        throw new RuntimeException("Unable to load template for " +
                FileTemplateManager.getInstance().internalTemplateToSubject(templateName), e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    final PsiFile file = factory.createFileFromText(fileName, VueFileType.INSTANCE, text);

    return (PsiFile) directory.add(file);
}