com.intellij.psi.PsiFileFactory Java Examples

The following examples show how to use com.intellij.psi.PsiFileFactory. 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: CreateFileAction.java    From PackageTemplates with 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 #2
Source File: BashTemplatesFactory.java    From BashSupport with 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 #3
Source File: ExtJsUtilTest.java    From idea-php-shopware-plugin with 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 #4
Source File: TaskUtils.java    From JHelper with 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 #5
Source File: ExternalSystemTasksPanel.java    From consulo with 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 #6
Source File: FormatterTestCase.java    From consulo with 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 #7
Source File: XSDToRAMLAction.java    From mule-intellij-plugins with 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 #8
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 #9
Source File: HaxelibClasspathUtils.java    From intellij-haxe with 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 #10
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 #11
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 #12
Source File: TwigTypeResolveUtilTest.java    From idea-php-symfony2-plugin with 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 #13
Source File: TranslationUtilTest.java    From idea-php-symfony2-plugin with 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 #14
Source File: TranslationUtilTest.java    From idea-php-symfony2-plugin with 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 #15
Source File: TranslationUtilTest.java    From idea-php-symfony2-plugin with 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 #16
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 #17
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 #18
Source File: ShaderLabElementColorProvider.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredReadAction
private static ShaderPropertyValue createValue(Project project, String text)
{
	String full = "Shader \"dummy\" { Properties { _dummy(\"dummy\", Color)  = " + text + " } }";
	ShaderLabFile psiFile = (ShaderLabFile) PsiFileFactory.getInstance(project).createFileFromText(full, ShaderLabFileType.INSTANCE, full);

	return psiFile.getProperties().get(0).getValue();
}
 
Example #19
Source File: LightGLSLTestCase.java    From glsl4idea with GNU Lesser General Public License v3.0 5 votes vote down vote up
public GLSLFile parseFile(String filePath){
    final String testFileContent;
    try {
        testFileContent = FileUtil.loadFile(getTestFile(filePath), "UTF-8", true);
        assertNotNull(testFileContent);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return ((GLSLFile) PsiFileFactory.getInstance(getProject()).createFileFromText("dummy.glsl", GLSLSupportLoader.GLSL, testFileContent));
}
 
Example #20
Source File: ThriftKeywordCompletionContributor.java    From intellij-thrift with Apache License 2.0 5 votes vote down vote up
private Collection<String> suggestKeywords(@NotNull PsiElement position) {
  PsiFile psiFile = position.getContainingFile();
  PsiElement topLevelElement = position;
  while (!(topLevelElement.getParent() instanceof PsiFile)) {
    topLevelElement = topLevelElement.getParent();
  }
  PsiFile file = PsiFileFactory.getInstance(psiFile.getProject())
    .createFileFromText("a.thrift", ThriftLanguage.INSTANCE, topLevelElement.getText(), true, false);
  GeneratedParserUtilBase.CompletionState state =
    new GeneratedParserUtilBase.CompletionState(position.getTextOffset() - topLevelElement.getTextOffset());
  file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state);
  TreeUtil.ensureParsed(file.getNode());
  return state.items;
}
 
Example #21
Source File: TranslationInsertUtilTest.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void testInsertTranslationForXlf20() {
    PsiFile xmlFile = PsiFileFactory.getInstance(getProject()).createFileFromText("foo.xml", XmlFileType.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" +
        "            <unit id=\"foobar\">\n" +
        "                <segment>\n" +
        "                    <source>foo</source>\n" +
        "                </segment>\n" +
        "            </unit>\n" +
        "        </group>\n" +
        "    </file>\n" +
        "</xliff>"
    );

    CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> {
        TranslationInsertUtil.invokeTranslation((XmlFile) xmlFile, "foobar", "value");
    }), null, null);

    String text = xmlFile.getText();

    assertTrue(text.contains("<unit id=\"2\">"));
    assertTrue(text.contains("<source>foobar</source>"));
    assertTrue(text.contains("<target>value</target>"));
}
 
Example #22
Source File: TranslationInsertUtilTest.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void testInsertTranslationForXlf20Shortcut() {
    PsiFile xmlFile = PsiFileFactory.getInstance(getProject()).createFileFromText("foo.xml", XmlFileType.INSTANCE, "" +
        "<xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\" version=\"2.0\"\n" +
        " srcLang=\"en-US\" trgLang=\"ja-JP\">\n" +
        " <file id=\"f1\" original=\"Graphic Example.psd\">\n" +
        "  <skeleton href=\"Graphic Example.psd.skl\"/>\n" +
        "  <unit id=\"1\">\n" +
        "   <segment>\n" +
        "    <source>foo</source>\n" +
        "   </segment>\n" +
        "  </unit>\n" +
        "  <unit id=\"foobar\">\n" +
        "   <segment>\n" +
        "    <source>foo</source>\n" +
        "   </segment>\n" +
        "  </unit>\n" +
        " </file>\n" +
        "</xliff>"
    );

    CommandProcessor.getInstance().executeCommand(getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> {
        TranslationInsertUtil.invokeTranslation((XmlFile) xmlFile, "foobar", "value");
    }), null, null);

    String text = xmlFile.getText();

    assertTrue(text.contains("<unit id=\"2\">"));
    assertTrue(text.contains("<source>foobar</source>"));
    assertTrue(text.contains("<target>value</target>"));
}
 
Example #23
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 #24
Source File: ProfilerUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * "_controller" and "_route"
 * "/_profiler/242e61?panel=request"
 *
 * <tr>
 *  <th>_route</th>
 *  <td>foo_route</td>
 * </tr>
 */
@NotNull
public static Map<String, String> getRequestAttributes(@NotNull Project project, @NotNull String html) {
    HtmlFileImpl htmlFile = (HtmlFileImpl) PsiFileFactory.getInstance(project).createFileFromText(HTMLLanguage.INSTANCE, html);

    String[] keys = new String[] {"_controller", "_route"};

    Map<String, String> map = new HashMap<>();
    PsiTreeUtil.processElements(htmlFile, psiElement -> {
        if(!(psiElement instanceof XmlTag) || !"th".equals(((XmlTag) psiElement).getName())) {
            return true;
        }

        XmlTagValue keyTag = ((XmlTag) psiElement).getValue();
        String key = StringUtils.trim(keyTag.getText());
        if(!ArrayUtils.contains(keys, key)) {
            return true;
        }

        XmlTag tdTag = PsiTreeUtil.getNextSiblingOfType(psiElement, XmlTag.class);
        if(tdTag == null || !"td".equals(tdTag.getName())) {
            return true;
        }

        XmlTagValue valueTag = tdTag.getValue();
        String value = valueTag.getText();
        if(StringUtils.isBlank(value)) {
            return true;
        }

        // Symfony 3.2 profiler debug? strip html
        map.put(key, stripHtmlTags(value));

        // exit if all item found
        return map.size() != keys.length;
    });

    return map;
}
 
Example #25
Source File: GLSLPsiElementFactory.java    From glsl4idea with GNU Lesser General Public License v3.0 5 votes vote down vote up
@NotNull
public static PsiElement createLeafElement(Project project, String name) {
    PsiElement element = PsiFileFactory.getInstance(project).
            createFileFromText("dummy.glsl", GLSLSupportLoader.GLSL, name);
    while (element.getFirstChild() != null) element = element.getFirstChild();
    return element;
}
 
Example #26
Source File: TodoForRanges.java    From consulo with 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);
}
 
Example #27
Source File: PsiUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Creates and returns a PsiFile with the given text of the given file type.
 *
 * @throws ClassCastException when the PsiFile created couldn't be cast to T
 */
@NotNull
@SuppressWarnings("unchecked")
public static <T extends PsiFile> T createFile(@NotNull Project project, @NotNull String text, @NotNull FileType fileType) {
	String fileName = "fake_sqf_file.sqf";
	return (T) PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, text);
}
 
Example #28
Source File: GraphQLSchemaErrorNode.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) {
    final SourceLocation location = getLocation();
    if (location != null && location.getSourceName() != null) {
        GraphQLTreeNodeNavigationUtil.openSourceLocation(myProject, location, false);
    } else if (error instanceof GraphQLInternalSchemaError) {
        String stackTrace = ExceptionUtil.getThrowableText(((GraphQLInternalSchemaError) error).getException());
        PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText("graphql-error.txt", PlainTextLanguage.INSTANCE, stackTrace);
        new OpenFileDescriptor(myProject, file.getVirtualFile()).navigate(true);
    }
}
 
Example #29
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 #30
Source File: PsiUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Creates and returns a PsiFile with the given text of the given file type.
 *
 * @throws ClassCastException when the PsiFile created couldn't be cast to T
 */
@NotNull
@SuppressWarnings("unchecked")
public static <T extends PsiFile> T createFile(@NotNull Project project, @NotNull String text, @NotNull FileType fileType) {
	String fileName = "fake_sqf_file.sqf";
	return (T) PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, text);
}