Java Code Examples for com.intellij.psi.PsiFileFactory

The following examples show how to use com.intellij.psi.PsiFileFactory. These examples are extracted from open source projects. 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 Project: reasonml-idea-plugin   Source File: PromptConsole.java    License: 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 Project: mule-intellij-plugins   Source File: XSDToRAMLAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent)
{
    final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext());
    final Project project = anActionEvent.getProject();

    Xsd2Raml xsd2Raml = new Xsd2Raml(file.getUrl());
    String raml = xsd2Raml.getRaml();

    PsiFile psiFile = PsiFileFactory.getInstance(anActionEvent.getProject()).createFileFromText(RamlLanguage.INSTANCE, raml);

    new WriteCommandAction.Simple(project, psiFile) {
        @Override
        protected void run() throws Throwable {
            psiFile.setName(file.getNameWithoutExtension() + "." + RamlFileType.INSTANCE.getDefaultExtension());

            PsiDirectory directory = CommonDataKeys.PSI_FILE.getData(anActionEvent.getDataContext()).getContainingDirectory();
            directory.add(psiFile);
        }
    }.execute();

}
 
Example 3
Source Project: weex-language-support   Source File: WeexTemplateFactory.java    License: 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 4
Source Project: PackageTemplates   Source File: CreateFileAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void doRun() {
        PsiDirectory psiParent = VFSHelper.findPsiDirByPath(project, file.getParentFile().getPath());
        if(psiParent==null){
            ReportHelper.setState(ExecutionState.FAILED);
            return;
        }

        try {
            PsiFile psiResultFile = PsiFileFactory.getInstance(project).createFileFromText(file.getName(), PlainTextFileType.INSTANCE, content);
//            PsiFile psiFile = psiDirectory.createFile(psiDirectory.createFile(file.getName()).getName());
//            psiFile.getVirtualFile().
            psiParent.add(psiResultFile);
        } catch (IncorrectOperationException ex){
            Logger.log("CreateFileAction " + ex.getMessage());
            Logger.printStack(ex);
            ReportHelper.setState(ExecutionState.FAILED);
            return;
        }
    }
 
Example 5
/**
 * 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 Project: consulo   Source File: ExternalSystemTasksPanel.java    License: Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
private Location buildLocation() {
  if (mySelectedTaskProvider == null) {
    return null;
  }
  ExternalTaskExecutionInfo task = mySelectedTaskProvider.produce();
  if (task == null) {
    return null;
  }

  String projectPath = task.getSettings().getExternalProjectPath();
  String name = myExternalSystemId.getReadableName() + projectPath + StringUtil.join(task.getSettings().getTaskNames(), " ");
  // We create a dummy text file instead of re-using external system file in order to avoid clashing with other configuration producers.
  // For example gradle files are enhanced groovy scripts but we don't want to run them via regular IJ groovy script runners.
  // Gradle tooling api should be used for running gradle tasks instead. IJ execution sub-system operates on Location objects
  // which encapsulate PsiElement and groovy runners are automatically applied if that PsiElement IS-A GroovyFile.
  PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(name, PlainTextFileType.INSTANCE, "nichts");

  return new ExternalSystemTaskLocation(myProject, file, task);
}
 
Example 7
Source Project: BashSupport   Source File: BashTemplatesFactory.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
static PsiFile createFromTemplate(final PsiDirectory directory, String fileName, String templateName) throws IncorrectOperationException {
    Project project = directory.getProject();
    FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
    FileTemplate template = templateManager.getInternalTemplate(templateName);

    Properties properties = new Properties(templateManager.getDefaultProperties());

    String templateText;
    try {
        templateText = template.getText(properties);
    } catch (IOException e) {
        throw new RuntimeException("Unable to load template for " + templateManager.internalTemplateToSubject(templateName), e);
    }

    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, BashFileType.BASH_FILE_TYPE, templateText);
    return (PsiFile) directory.add(file);
}
 
Example 8
Source Project: idea-php-shopware-plugin   Source File: ExtJsUtilTest.java    License: MIT License 6 votes vote down vote up
/**
 * @see ExtJsUtil#getSnippetNamespaceFromFile
 */
public void testGetSnippetNamespaceFromFile() {
    String[] foo = {
        "//{namespace name=backend/index/view/widgets}",
        "//{namespace name = backend/index/view/widgets}",
        "//{namespace foobar='aaaa' name='backend/index/view/widgets' }",
        "//{namespace name=\"backend/index/view/widgets\" }",
    };

    for (String s : foo) {
        PsiFile fileFromText = PsiFileFactory.getInstance(getProject())
            .createFileFromText("foo.js", JavaScriptFileType.INSTANCE, s);

        assertEquals("backend/index/view/widgets", ExtJsUtil.getSnippetNamespaceFromFile(fileFromText));
    }
}
 
Example 9
Source Project: JHelper   Source File: TaskUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private static PsiElement generateCPP(Project project, TaskData taskData) {
	VirtualFile parent = FileUtils.findOrCreateByRelativePath(project.getBaseDir(), FileUtils.getDirectory(taskData.getCppPath()));
	PsiDirectory psiParent = PsiManager.getInstance(project).findDirectory(parent);
	if (psiParent == null) {
		throw new NotificationException("Couldn't open parent directory as PSI");
	}

	Language objC = Language.findLanguageByID("ObjectiveC");
	if (objC == null) {
		throw new NotificationException("Language not found");
	}

	PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(
			FileUtils.getFilename(taskData.getCppPath()),
			objC,
			getTaskContent(project, taskData.getClassName())
	);
	if (file == null) {
		throw new NotificationException("Couldn't generate file");
	}
	return ApplicationManager.getApplication().runWriteAction(
			(Computable<PsiElement>) () -> psiParent.add(file)
	);

}
 
Example 10
Source Project: consulo   Source File: FormatterTestCase.java    License: Apache License 2.0 6 votes vote down vote up
protected void doTextTest(final String text, final String textAfter, @Nonnull CheckPolicy checkPolicy)
  throws IncorrectOperationException {
  final String fileName = "before." + getFileExtension();
  final PsiFile file = createFileFromText(text, fileName, PsiFileFactory.getInstance(getProject()));

  if (checkPolicy.isCheckDocument()) {
    checkDocument(file, text, textAfter);
  }

  if (checkPolicy.isCheckPsi()) {
    /*
    restoreFileContent(file, text);

    checkPsi(file, textAfter);
    */
  }


}
 
Example 11
Source Project: idea-gitignore   Source File: IgnoreTemplatesFactory.java    License: 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 12
Source Project: intellij-haxe   Source File: HaxelibClasspathUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Turn some text into a file, parse it using the .hxml parser, and
 * return any HXML classpaths.
 *
 * @param project to include created files in.
 * @param text to parse.
 * @return A (possibly empty) list containing all of the classpaths found in the text.
 */
@NotNull
public static List<String> getHXMLFileClasspaths(@NotNull Project project, @NotNull String text) {
  if (text.isEmpty()) {
    return Collections.EMPTY_LIST;
  }

  List<String> strings1;
  strings1 = new ArrayList<String>();
  PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(HXMLFileType.INSTANCE, "data.hxml", text, 0, text.length() - 1);

  Collection<HXMLClasspath> hxmlClasspaths = PsiTreeUtil.findChildrenOfType(psiFile, HXMLClasspath.class);
  for (HXMLClasspath hxmlClasspath : hxmlClasspaths) {
    strings1.add(HXMLPsiImplUtil.getValue(hxmlClasspath));
  }
  return strings1;
}
 
Example 13
Source Project: idea-php-symfony2-plugin   Source File: TwigTypeResolveUtilTest.java    License: MIT License 6 votes vote down vote up
/**
 * @see TwigTypeResolveUtil#findFileVariableDocBlock
 */
public void testFindFileVariableDocBlock() {
    PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(TwigLanguage.INSTANCE, "" +
        "{# @var foo_1 \\AppBundle\\Entity\\MeterValueDTO #}\n" +
        "{# @var foo_2 \\AppBundle\\Entity\\MeterValueDTO[] #}\n" +
        "{# @var \\AppBundle\\Entity\\MeterValueDTO foo_3 #}\n" +
        "{# @var \\AppBundle\\Entity\\MeterValueDTO[] foo_4 #}\n" +
        "" +
        "{#\n" +
        "@var \\AppBundle\\Entity\\MeterValueDTO foo_5\n" +
        "@var foo_6 \\AppBundle\\Entity\\MeterValueDTO\n" +
        "#}\n"
    );

    Map<String, String> fileVariableDocBlock = TwigTypeResolveUtil.findFileVariableDocBlock((TwigFile) fileFromText);

    assertEquals("\\AppBundle\\Entity\\MeterValueDTO", fileVariableDocBlock.get("foo_1"));
    assertEquals("\\AppBundle\\Entity\\MeterValueDTO[]", fileVariableDocBlock.get("foo_2"));
    assertEquals("\\AppBundle\\Entity\\MeterValueDTO", fileVariableDocBlock.get("foo_3"));
    assertEquals("\\AppBundle\\Entity\\MeterValueDTO[]", fileVariableDocBlock.get("foo_4"));

    assertEquals("\\AppBundle\\Entity\\MeterValueDTO", fileVariableDocBlock.get("foo_5"));
    assertEquals("\\AppBundle\\Entity\\MeterValueDTO", fileVariableDocBlock.get("foo_6"));
}
 
Example 14
Source Project: idea-php-symfony2-plugin   Source File: TranslationUtilTest.java    License: MIT License 6 votes vote down vote up
public void testGetTargetForXlfAsXmlFileInVersion12() {
    PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
        "<?xml version=\"1.0\"?>\n" +
        "<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n" +
        "    <file source-language=\"en\" datatype=\"plaintext\" original=\"file.ext\">\n" +
        "        <body>\n" +
        "            <trans-unit id=\"1\">\n" +
        "                <source>This value should be false.</source>\n" +
        "            </trans-unit>\n" +
        "        </body>\n" +
        "    </file>\n" +
        "</xliff>\n"
    );

    Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "This value should be false.");

    assertNotNull(ContainerUtil.find(files, psiElement ->
        psiElement instanceof XmlTag && "This value should be false.".equals(((XmlTag) psiElement).getValue().getText()))
    );
}
 
Example 15
Source Project: idea-php-symfony2-plugin   Source File: TranslationUtilTest.java    License: MIT License 6 votes vote down vote up
public void testGetTargetForXlfAsXmlFileInVersion20() {
    PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
        "<?xml version=\"1.0\"?>\n" +
        "<xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\"\n" +
        "       version=\"2.0\" srcLang=\"en-US\" trgLang=\"ja-JP\">\n" +
        "    <file id=\"f1\" original=\"Graphic Example.psd\">\n" +
        "        <skeleton href=\"Graphic Example.psd.skl\"/>\n" +
        "        <group id=\"1\">\n" +
        "            <unit id=\"1\">\n" +
        "                <segment>\n" +
        "                    <source>foo</source>\n" +
        "                </segment>\n" +
        "            </unit>\n" +
        "        </group>\n" +
        "    </file>\n" +
        "</xliff>"
    );

    Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "foo");

    assertNotNull(ContainerUtil.find(files, psiElement ->
        psiElement instanceof XmlTag && "foo".equals(((XmlTag) psiElement).getValue().getText()))
    );
}
 
Example 16
Source Project: idea-php-symfony2-plugin   Source File: TranslationUtilTest.java    License: MIT License 6 votes vote down vote up
public void testGetTargetForXlfAsXmlFileInVersion12AndResname() {
    PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
        "<?xml version=\"1.0\"?>\n" +
        "<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n" +
        "    <file source-language=\"en\" datatype=\"plaintext\" original=\"file.ext\">\n" +
        "        <body>\n" +
        "            <trans-unit id=\"1\" resname=\"index.hello_world\">\n" +
        "                <source>foo</source>\n" +
        "            </trans-unit>\n" +
        "        </body>\n" +
        "    </file>\n" +
        "</xliff>\n"
    );

    Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "index.hello_world");

    assertNotNull(ContainerUtil.find(files, psiElement ->
        psiElement instanceof XmlTag && "index.hello_world".equals(((XmlTag) psiElement).getAttributeValue("resname")))
    );
}
 
Example 17
Source Project: EasyCode   Source File: SaveFile.java    License: 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 18
Source Project: litho   Source File: ComponentGenerateUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static PsiFile createFileFromModel(
    String clsQualifiedName, SpecModel model, Project project) {
  String fileContent = createFileContentFromModel(clsQualifiedName, model);
  return PsiFileFactory.getInstance(project)
      .createFileFromText(
          StringUtil.getShortName(clsQualifiedName) + ".java", StdFileTypes.JAVA, fileContent);
}
 
Example 19
Source Project: consulo   Source File: PostfixLiveTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static PsiFile copyFile(@Nonnull PsiFile file, @Nonnull StringBuilder fileContentWithoutKey) {
  final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(file.getProject());
  PsiFile copy = psiFileFactory.createFileFromText(file.getName(), file.getFileType(), fileContentWithoutKey);
  VirtualFile vFile = copy.getVirtualFile();
  if (vFile != null) {
    vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
  }
  return copy;
}
 
Example 20
Source Project: litho   Source File: LithoPluginIntellijTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts list of class names to the list of psi classes.
 *
 * @param handler calling class should pass handler for the psi classes. Passes null if
 *     conversion was unsuccessful at any step.
 * @param clsNames names of the classes to found in the test root directory (MyClass.java)
 */
public void getPsiClass(Function<List<PsiClass>, Boolean> handler, String... clsNames) {
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            List<PsiClass> psiClasses =
                Stream.of(clsNames)
                    .filter(Objects::nonNull)
                    .map(
                        clsName -> {
                          String content = getContentOrNull(clsName);
                          if (content != null) {
                            return PsiFileFactory.getInstance(fixture.getProject())
                                .createFileFromText(clsName, JavaFileType.INSTANCE, content);
                          }
                          return null;
                        })
                    .filter(PsiJavaFile.class::isInstance)
                    .map(PsiJavaFile.class::cast)
                    .map(PsiClassOwner::getClasses)
                    .filter(fileClasses -> fileClasses.length > 0)
                    .map(fileClasses -> fileClasses[0])
                    .collect(Collectors.toList());
            if (psiClasses.isEmpty()) {
              handler.apply(null);
            } else {
              handler.apply(psiClasses);
            }
          });
}
 
Example 21
Source Project: consulo   Source File: PsiTestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void checkFileStructure(PsiFile file) throws IncorrectOperationException {
  String originalTree = DebugUtil.psiTreeToString(file, false);
  PsiFile dummyFile =
    PsiFileFactory.getInstance(file.getProject()).createFileFromText(file.getName(), file.getFileType(), file.getText());
  String reparsedTree = DebugUtil.psiTreeToString(dummyFile, false);
  Assert.assertEquals(reparsedTree, originalTree);
}
 
Example 22
Source Project: reasonml-idea-plugin   Source File: CmtXmlComponent.java    License: MIT License 5 votes vote down vote up
private void addChildren() {
    PsiFile psiFile = PsiFileFactory.getInstance(m_project).createFileFromText(XHTMLLanguage.INSTANCE, m_xmlDump);
    Document document = PsiDocumentManager.getInstance(m_project).getDocument(psiFile);
    if (document != null) {
        Editor editor = EditorFactory.getInstance().createEditor(document, m_project, HtmlFileType.INSTANCE, true);
        addToCenter(editor.getComponent());
    }
}
 
Example 23
Source Project: consulo   Source File: CoreProjectEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
public CoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
  myParentDisposable = parentDisposable;
  myEnvironment = applicationEnvironment;
  myProject = new MockProject(myEnvironment.getApplication(), myParentDisposable);

  preregisterServices();

  myFileIndexFacade = createFileIndexFacade();
  myMessageBus = (MessageBusImpl)myProject.getMessageBus();

  PsiModificationTrackerImpl modificationTracker = new PsiModificationTrackerImpl(applicationEnvironment.getApplication(), myProject);
  myProject.registerService(PsiModificationTracker.class, modificationTracker);
  myProject.registerService(FileIndexFacade.class, myFileIndexFacade);
  myProject.registerService(ResolveCache.class, new ResolveCache(myProject));

  registerProjectExtensionPoint(PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor.class);
  myPsiManager = new PsiManagerImpl(myProject, () -> myFileIndexFacade, modificationTracker);
  ((FileManagerImpl)myPsiManager.getFileManager()).markInitialized();
  registerProjectComponent(PsiManager.class, myPsiManager);

  registerProjectComponent(PsiDocumentManager.class, new CorePsiDocumentManager(myProject, new MockDocumentCommitProcessor()));

  myProject.registerService(ResolveScopeManager.class, createResolveScopeManager(myPsiManager));

  myProject.registerService(PsiFileFactory.class, new PsiFileFactoryImpl(myPsiManager));
  myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
  myProject.registerService(ProjectScopeBuilder.class, createProjectScopeBuilder());
  myProject.registerService(DumbService.class, new MockDumbService(myProject));
}
 
Example 24
Source Project: consulo   Source File: FileTemplateConfigurable.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private PsiFile createFile(final String text, final String name) {
  if (myTemplate == null) return null;

  final FileType fileType = myVelocityFileType;
  if (fileType == UnknownFileType.INSTANCE) return null;

  final PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(name + ".txt.ft", fileType, text, 0, true);
  file.getViewProvider().putUserData(FileTemplateManager.DEFAULT_TEMPLATE_PROPERTIES, FileTemplateManager.getInstance(myProject).getDefaultProperties());
  return file;
}
 
Example 25
Source Project: json2java4idea   Source File: NewClassCommandAction.java    License: 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 26
Source Project: json2java4idea   Source File: FormatterTest.java    License: 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 27
Source Project: RIBs   Source File: GenerateAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes a source file generated by a {@link Generator} to disk.
 *
 * @param project   to write file in.
 * @param generator to generate file with.
 * @param directory to write file to.
 */
private static void createSourceFile(
    Project project, Generator generator, PsiDirectory directory) {
  PsiFile file =
      PsiFileFactory.getInstance(project)
          .createFileFromText(
              String.format("%s" + generator.getFileExtension(), generator.getClassName()),
              JavaLanguage.INSTANCE,
              generator.generate());
  directory.add(file);
}
 
Example 28
@NotNull
@Override
public Document createDocument(@NotNull Project project, @NotNull String text, @Nullable XSourcePosition xSourcePosition, @NotNull EvaluationMode evaluationMode)
{

    final PsiFile psiFile = PsiFileFactory.getInstance(project)
                                          .createFileFromText("muleExpr." + getFileType().getDefaultExtension(), getFileType(), text, LocalTimeCounter.currentTime(), true);
    return PsiDocumentManager.getInstance(project).getDocument(psiFile);
}
 
Example 29
@NotNull
@Override
public Document createDocument(@NotNull Project project, @NotNull String text, @Nullable XSourcePosition xSourcePosition, @NotNull EvaluationMode evaluationMode) {

    final PsiFile psiFile = PsiFileFactory.getInstance(project)
            .createFileFromText("muleExpr." + getFileType().getDefaultExtension(), getFileType(), text, LocalTimeCounter.currentTime(), true);
    return PsiDocumentManager.getInstance(project).getDocument(psiFile);
}
 
Example 30
Source Project: consulo   Source File: TodoForRanges.java    License: Apache License 2.0 5 votes vote down vote up
protected TodoItem[] getTodoForText(PsiTodoSearchHelper helper) {
  final PsiFile psiFile = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
    @Override
    public PsiFile compute() {
      return PsiFileFactory.getInstance(myProject).createFileFromText((myOldRevision ? "old" : "") + myFileName, myFileType, myText);
    }
  });
  return helper.findTodoItemsLight(psiFile);
}