@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(); }
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); }
private static Collection<String> suggestKeywords(PsiElement position) { TextRange posRange = position.getTextRange(); CupFile posFile = (CupFile) position.getContainingFile(); TextRange range = new TextRange(0, posRange.getStartOffset()); String text = range.isEmpty() ? CompletionInitializationContext.DUMMY_IDENTIFIER : range.substring(posFile.getText()); int completionOffset = posRange.getStartOffset() - range.getStartOffset(); // = posRange.getStartOffset() ... PsiFile file = PsiFileFactory.getInstance(posFile.getProject()).createFileFromText("a.cup", CupLanguage.INSTANCE, text, true, false); GeneratedParserUtilBase.CompletionState state = new GeneratedParserUtilBase.CompletionState(completionOffset) { @Nullable @Override public String convertItem(Object o) { if (o == CupTypes.IDENTIFIER) { return null; } return o.toString(); } }; file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state); TreeUtil.ensureParsed(file.getNode()); return state.items; }
@Override public void doRun() { PsiDirectory psiParent = PsiHelper.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; } }
@Override public FileReferenceNode handleContentChange(@NotNull FileReferenceNode fileReferenceNode, @NotNull TextRange range, String newContent) throws IncorrectOperationException { String oldText = fileReferenceNode.getText(); String newText = oldText.substring(0, range.getStartOffset()) + newContent + oldText .substring(range.getEndOffset()); Project project = fileReferenceNode.getProject(); PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project); IElementType type = ProtoParserDefinition.rule(ProtoParser.RULE_fileReference); ScopeNode context = fileReferenceNode.getContext(); PsiElement newNode = factory .createElementFromText(newText, ProtoLanguage.INSTANCE, type, context); if (newNode == null) { throw new IncorrectOperationException(); } return (FileReferenceNode) fileReferenceNode.replace(newNode); }
@Override public FieldReferenceNode handleContentChange(@NotNull FieldReferenceNode node, @NotNull TextRange range, String newContent) throws IncorrectOperationException { String oldText = node.getText(); String newText = oldText.substring(0, range.getStartOffset()) + newContent + oldText .substring(range.getEndOffset()); Project project = node.getProject(); PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project); IElementType type = ProtoParserDefinition.rule(ProtoParser.RULE_fieldRerefence); ScopeNode context = node.getContext(); PsiElement newNode = factory .createElementFromText(newText, ProtoLanguage.INSTANCE, type, context); if (newNode == null) { throw new IncorrectOperationException(); } return (FieldReferenceNode) node.replace(newNode); }
@Override public TypeReferenceNode handleContentChange(@NotNull TypeReferenceNode node, @NotNull TextRange range, String newContent) throws IncorrectOperationException { String oldText = node.getText(); String newText = oldText.substring(0, range.getStartOffset()) + newContent + oldText .substring(range.getEndOffset()); Project project = node.getProject(); PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project); IElementType type = ProtoParserDefinition.rule(ProtoParser.RULE_typeReference); ScopeNode context = node.getContext(); PsiElement newNode = factory .createElementFromText(newText, ProtoLanguage.INSTANCE, type, context); if (newNode == null) { throw new IncorrectOperationException(); } return (TypeReferenceNode) node.replace(newNode); }
/** * Set name. */ public PsiElement setName(@NotNull String name) throws IncorrectOperationException { ASTNode node = getNode(); IElementType elementType = node.getElementType(); if (elementType instanceof RuleIElementType) { RuleIElementType ruleElementType = (RuleIElementType) elementType; int ruleIndex = ruleElementType.getRuleIndex(); Project project = getProject(); PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project); IElementType type = ProtoParserDefinition.rule(ruleIndex); ScopeNode context = getContext(); PsiElement newNode = factory.createElementFromText(name, ProtoLanguage.INSTANCE, type, context); if (newNode == null) { throw new IncorrectOperationException(); } return replace(newNode); } throw new IncorrectOperationException(OPERATION_NOT_SUPPORTED); }
public static PsiFile createFromTemplate(PsiDirectory directory, String fileName, String templateName) throws IncorrectOperationException { final FileTemplate template = FileTemplateManager.getInstance(directory.getProject()).getInternalTemplate(templateName); Project project = directory.getProject(); String text; try { text = template.getText(); } catch (Exception e) { throw new RuntimeException("Unable to load template for " + FileTemplateManager.getInstance(project).internalTemplateToSubject(templateName), e); } final PsiFileFactory factory = PsiFileFactory.getInstance(project); PsiFile file = factory.createFileFromText(fileName, NullShaderFileType.INSTANCE, text); file = (PsiFile) directory.add(file); return file; }
protected void doTextTest(final String text, final String textAfter, @NotNull 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); */ } }
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); } }
private PsiElement parseText(String text) { final Object source = getSource(); try { if (source instanceof PsiViewerExtension) { return ((PsiViewerExtension)source).createElement(myProject, text); } if (source instanceof FileType) { final FileType type = (FileType)source; String ext = type.getDefaultExtension(); if (myExtensionComboBox.isVisible()) { ext = myExtensionComboBox.getSelectedItem().toString().toLowerCase(); } if (type instanceof LanguageFileType) { final Language dialect = (Language)myDialectComboBox.getSelectedItem(); if (dialect != null) { return PsiFileFactory.getInstance(myProject).createFileFromText("Dummy." + ext, dialect, text); } } return PsiFileFactory.getInstance(myProject).createFileFromText("Dummy." + ext, type, text); } } catch (IncorrectOperationException e) { Messages.showMessageDialog(myProject, e.getMessage(), "Error", Messages.getErrorIcon()); } return null; }
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)); } }
@NotNull @Override public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, String fileName, final FileTemplate template, final String templateText, @NotNull final Map<String, Object> props) throws IncorrectOperationException { fileName = checkAppendExtension(fileName, template); if (FileTypeManager.getInstance().isFileIgnored(fileName)) { throw new IncorrectOperationException("This filename is ignored (Settings | Editor | File Types | Ignore files and folders)"); } directory.checkCreateFile(fileName); FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName); PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, type, templateText); if (template.isReformatCode()) { CodeStyleManager.getInstance(project).reformat(file); } file = (PsiFile)directory.add(file); return file; }
@Nullable public BuildoutCfgFile getConfigPsiFile() { File cfg = getConfigFile(); if (cfg != null && cfg.exists()) { try { // this method is called before the project initialization is complete, so it has to use createFileFromText() instead // of PsiManager.findFile() String text = FileUtil.loadFile(cfg); final PsiFile configFile = PsiFileFactory .getInstance(getModule().getProject()).createFileFromText("buildout.cfg", BuildoutCfgLanguage.INSTANCE, text); if (configFile != null && configFile instanceof BuildoutCfgFile) { return (BuildoutCfgFile)configFile; } } catch (Exception ignored) { } } return null; }
private static void createInitPy(PsiDirectory directory) { final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(directory.getProject()); final FileTemplate template = fileTemplateManager.getInternalTemplate("Python Script"); if (directory.findFile(PyNames.INIT_DOT_PY) != null) { return; } if (template != null) { try { FileTemplateUtil.createFromTemplate(template, PyNames.INIT_DOT_PY, fileTemplateManager.getDefaultProperties(), directory); } catch (Exception e) { LOG.error(e); } } else { final PsiFile file = PsiFileFactory.getInstance(directory.getProject()).createFileFromText(PyNames.INIT_DOT_PY, ""); directory.add(file); } }
@Override public void configureProject(Project project, @NotNull VirtualFile baseDir, Ref<Module> moduleRef) { VirtualFile setupPy = baseDir.findChild(SETUP_PY); if (setupPy != null) { final CharSequence content = LoadTextUtil.loadText(setupPy); PyFile setupPyFile = (PyFile) PsiFileFactory.getInstance(project).createFileFromText(SETUP_PY, PythonFileType.INSTANCE, content.toString()); final SetupCallVisitor visitor = new SetupCallVisitor(); setupPyFile.accept(visitor); String dir = visitor.getRootPackageDir(); if (dir != null) { final VirtualFile rootPackageVFile = baseDir.findFileByRelativePath(dir); addSourceRoot(project, baseDir, rootPackageVFile, true); } } }
public void testInsertAtOffset() throws Exception { new WriteCommandAction(getProject()) { @Override protected void run(@NotNull final Result result) throws Throwable { String xml = "<root>0123456789</root>"; XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()) .createFileFromText("foo.xml", StdFileTypes.XML, xml, (long)1, true, false); //System.out.println(DebugUtil.psiToString(file, false)); XmlTag root = file.getDocument().getRootTag(); final XmlText text1 = root.getValue().getTextElements()[0]; assertFalse(CodeEditUtil.isNodeGenerated(root.getNode())); final XmlText text = text1; final XmlElement element = text.insertAtOffset(XmlElementFactory.getInstance(getProject()).createTagFromText("<bar/>"), 5); assertNotNull(element); assertTrue(element instanceof XmlText); assertEquals("01234", element.getText()); assertEquals("<root>01234<bar/>56789</root>", text.getContainingFile().getText()); } }.execute(); }
private static String reformatTemplateText(@NotNull final PsiFile file, @NotNull String templateText) { final PsiFile copy = PsiFileFactory.getInstance(file.getProject()).createFileFromText(file.getName(), file.getFileType(), templateText); VirtualFile vFile = copy.getVirtualFile(); if (vFile != null) { vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE); } ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { @Override public void run() { CodeStyleManager.getInstance(file.getProject()).reformat(copy); } }); } }); return copy.getText(); }
private static int gotoChild(Project project, CharSequence text, int offset, int start, int end) { PsiFile file = PsiFileFactory.getInstance(project) .createFileFromText("dummy.xml", StdFileTypes.XML, text, LocalTimeCounter.currentTime(), false); PsiElement element = file.findElementAt(offset); if (offset < end && element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_END_TAG_START) { return offset; } int newOffset = -1; XmlTag tag = PsiTreeUtil.findElementOfClassAtRange(file, start, end, XmlTag.class); if (tag != null) { for (PsiElement child : tag.getChildren()) { if (child instanceof XmlToken && ((XmlToken)child).getTokenType() == XmlTokenType.XML_END_TAG_START) { newOffset = child.getTextOffset(); } } } if (newOffset >= 0) { return newOffset; } return offset; }
@NotNull private static XmlFile parseXmlFileInTemplate(@NotNull TemplateImpl template, @NotNull CustomTemplateCallback callback, @NotNull Map<String, String> attributes) { XmlTag dummyRootTag = null; String templateString = template.getString(); final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(callback.getProject()); if (!containsAttrsVar(template)) { XmlFile dummyFile = (XmlFile)psiFileFactory.createFileFromText("dummy.html", HTMLLanguage.INSTANCE, templateString, false, true); dummyRootTag = dummyFile.getRootTag(); if (dummyRootTag != null) { addMissingAttributes(dummyRootTag, attributes); } } templateString = dummyRootTag != null ? dummyRootTag.getContainingFile().getText() : templateString; XmlFile xmlFile = (XmlFile)psiFileFactory.createFileFromText("dummy.xml", StdFileTypes.XML, templateString, LocalTimeCounter.currentTime(), true); VirtualFile vFile = xmlFile.getVirtualFile(); if (vFile != null) { vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE); } return xmlFile; }
private static void processTags(@NotNull Project project, @Nullable String templateText, @NotNull PairProcessor<XmlTag, Boolean> processor) { if (StringUtil.isNotEmpty(templateText)) { final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project); XmlFile xmlFile = (XmlFile)psiFileFactory.createFileFromText("dummy.xml", StdFileTypes.HTML, templateText); XmlTag tag = xmlFile.getRootTag(); boolean firstTag = true; while (tag != null) { processor.process(tag, firstTag); firstTag = false; tag = PsiTreeUtil.getNextSiblingOfType(tag, XmlTag.class); } } }
private static void doRenameXmlAttributeValue(@NotNull XmlAttributeValue value, String newName, UsageInfo[] infos, @Nullable RefactoringElementListener listener) throws IncorrectOperationException { LOG.assertTrue(value.isValid()); renameAll(value, infos, newName, value.getValue()); PsiManager psiManager = value.getManager(); LOG.assertTrue(psiManager != null); XmlFile file = (XmlFile)PsiFileFactory.getInstance(psiManager.getProject()).createFileFromText("dummy.xml", XMLLanguage.INSTANCE, "<a attr=\"" + newName + "\"/>"); @SuppressWarnings("ConstantConditions") PsiElement element = value.replace(file.getRootTag().getAttributes()[0].getValueElement()); if (listener != null) { listener.elementRenamed(element); } }
@Nullable @Override protected String encodeFileText(final String content, final VirtualFile file, final Project project) throws IOException { if ("pom.xml".equals(file.getName())) { return ApplicationManager.getApplication().runReadAction(new ThrowableComputable<String, IOException>() { @Override public String compute() throws IOException { PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("pom.xml", XmlFileType.INSTANCE, content); final MavenDomProjectModel model = MavenDomUtil.getMavenDomModel(psiFile, MavenDomProjectModel.class); if (model == null) return null; String text = psiFile.getText(); XmlElement element = model.getName().getXmlElement(); if (element instanceof XmlTag) { text = ((XmlTag)element).getValue().getTextRange().replace(text, wrap(ProjectTemplateParameterFactory.IJ_PROJECT_NAME)); } element = model.getArtifactId().getXmlElement(); if (element instanceof XmlTag) { text = ((XmlTag)element).getValue().getTextRange().replace(text, wrap(ProjectTemplateParameterFactory.IJ_PROJECT_NAME)); } return text; } }); } return null; }
@Nullable public static Set<String> getEnumValues(Project project, @NotNull String regExp) { final PsiFileFactory factory = PsiFileFactory.getInstance(project); final PsiFile file = factory.createFileFromText("dummy.regexp", RegExpFileType.INSTANCE, regExp); final RegExpPattern pattern = (RegExpPattern)file.getFirstChild(); if (pattern == null) { return null; } final RegExpBranch[] branches = pattern.getBranches(); final Set<String> values = new HashSet<String>(); for (RegExpBranch branch : branches) { if (analyzeBranch(branch)) { values.add(branch.getUnescapedText()); } } return values; }
public void registerPageLanguage(final Project project, final XmlFile containingFile, final String languageName) { new WriteCommandAction.Simple(project, getFamilyName()) { @Override protected void run() { final PsiFileFactory factory = PsiFileFactory.getInstance(project); final XmlFile dummyFile = (XmlFile)factory.createFileFromText("_Dummy_.fxml", StdFileTypes.XML, "<?language " + languageName + "?>"); final XmlDocument document = dummyFile.getDocument(); if (document != null) { final XmlProlog prolog = document.getProlog(); final Collection<XmlProcessingInstruction> instructions = PsiTreeUtil.findChildrenOfType(prolog, XmlProcessingInstruction.class); LOG.assertTrue(instructions.size() == 1); final XmlDocument xmlDocument = containingFile.getDocument(); if (xmlDocument != null) { final XmlProlog xmlProlog = xmlDocument.getProlog(); if (xmlProlog != null) { final PsiElement element = xmlProlog.addBefore(instructions.iterator().next(), xmlProlog.getFirstChild()); xmlProlog.addAfter(PsiParserFacade.SERVICE.getInstance(project).createWhiteSpaceFromText("\n\n"), element); } } } } }.execute(); }
/** * @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)); } }
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) ); }
@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); }
/** * @return psiFile associated with the content. If the file was not set on FileContentCreation, it will be created on the spot */ @NotNull @Override public PsiFile getPsiFile() { PsiFile psi = getUserData(IndexingDataKeys.PSI_FILE); if (psi == null) { psi = getUserData(CACHED_PSI); } if (psi == null) { Project project = getProject(); if (project == null) { project = DefaultProjectFactory.getInstance().getDefaultProject(); } final Language language = ((LanguageFileType)getFileTypeWithoutSubstitution()).getLanguage(); final Language substitutedLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(language, getFile(), project); psi = PsiFileFactory.getInstance(project).createFileFromText(getFileName(), substitutedLanguage, getContentAsText(), false, false, true); psi.putUserData(IndexingDataKeys.VIRTUAL_FILE, getFile()); putUserData(CACHED_PSI, psi); } return psi; }
private PsiElement parseText(String text) { final Object source = getSource(); try { if (source instanceof PsiViewerExtension) { return ((PsiViewerExtension)source).createElement(myProject, text); } if (source instanceof FileType) { final FileType type = (FileType)source; String ext = type.getDefaultExtension(); if (myExtensionComboBox.isVisible()) { ext = myExtensionComboBox.getSelectedItem().toString().toLowerCase(); } if (type instanceof LanguageFileType) { final Language language = ((LanguageFileType)type).getLanguage(); final Language dialect = (Language)myDialectComboBox.getSelectedItem(); return PsiFileFactory.getInstance(myProject).createFileFromText("Dummy." + ext, dialect == null ? language : dialect, text); } return PsiFileFactory.getInstance(myProject).createFileFromText("Dummy." + ext, type, text); } } catch (IncorrectOperationException e) { Messages.showMessageDialog(myProject, e.getMessage(), "Error", Messages.getErrorIcon()); } return null; }
private void updateFileTypeForEditorComponent(@NotNull ComboBox inputComboBox) { final Component editorComponent = inputComboBox.getEditor().getEditorComponent(); if (editorComponent instanceof EditorTextField) { boolean selected = myCbRegularExpressions.isSelectedWhenSelectable(); @NonNls final String s = selected ? "*.regexp" : "*.txt"; FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(s); if (selected && fileType == FileTypes.UNKNOWN) { fileType = FileTypeManager.getInstance().getFileTypeByFileName("*.txt"); // RegExp plugin is not installed } final PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText(s, fileType, ((EditorTextField)editorComponent).getText(), -1, true); ((EditorTextField)editorComponent).setNewDocumentAndFileType(fileType, PsiDocumentManager.getInstance(myProject).getDocument(file)); } }
@Override public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, String fileName, final FileTemplate template, final String templateText, final Map<String, Object> props) throws IncorrectOperationException { fileName = checkAppendExtension(fileName, template); if (FileTypeManager.getInstance().isFileIgnored(fileName)) { throw new IncorrectOperationException("This filename is ignored (Settings | File Types | Ignore files and folders)"); } directory.checkCreateFile(fileName); FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName); PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, type, templateText); if (template.isReformatCode()) { CodeStyleManager.getInstance(project).reformat(file); } file = (PsiFile)directory.add(file); return file; }
public void testInsertAtOffset() throws Exception { new WriteCommandAction(getProject()) { @Override protected void run(final Result result) throws Throwable { String xml = "<root>0123456789</root>"; XmlFile file = (XmlFile)PsiFileFactory.getInstance(getProject()) .createFileFromText("foo.xml", StdFileTypes.XML, xml, (long)1, true, false); //System.out.println(DebugUtil.psiToString(file, false)); XmlTag root = file.getDocument().getRootTag(); final XmlText text1 = root.getValue().getTextElements()[0]; assertFalse(CodeEditUtil.isNodeGenerated(root.getNode())); final XmlText text = text1; final XmlElement element = text.insertAtOffset(XmlElementFactory.getInstance(getProject()).createTagFromText("<bar/>"), 5); assertNotNull(element); assertTrue(element instanceof XmlText); assertEquals("01234", element.getText()); assertEquals("<root>01234<bar/>56789</root>", text.getContainingFile().getText()); } }.execute(); }
@NotNull private static XmlFile parseXmlFileInTemplate(TemplateImpl template, CustomTemplateCallback callback, List<Pair<String, String>> attributes) { XmlTag dummyRootTag = null; String templateString = template.getString(); final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(callback.getProject()); if (!containsAttrsVar(template)) { XmlFile dummyFile = (XmlFile)psiFileFactory.createFileFromText("dummy.xml", StdFileTypes.XML, templateString); dummyRootTag = dummyFile.getRootTag(); if (dummyRootTag != null) { addMissingAttributes(dummyRootTag, attributes); } } templateString = dummyRootTag != null ? dummyRootTag.getContainingFile().getText() : templateString; XmlFile xmlFile = (XmlFile)psiFileFactory.createFileFromText("dummy.xml", StdFileTypes.XML, templateString, LocalTimeCounter.currentTime(), true); VirtualFile vFile = xmlFile.getVirtualFile(); if (vFile != null) { vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE); } return xmlFile; }
private static void doRenameXmlAttributeValue(@NotNull XmlAttributeValue value, String newName, UsageInfo[] infos, @Nullable RefactoringElementListener listener) throws IncorrectOperationException { LOG.assertTrue(value.isValid()); renameAll(value, infos, newName, value.getValue()); PsiManager psiManager = value.getManager(); LOG.assertTrue(psiManager != null); XmlFile file = (XmlFile)PsiFileFactory.getInstance(psiManager.getProject()).createFileFromText("dummy.xml", "<a attr=\"" + newName + "\"/>"); final PsiElement element = value.replace(file.getDocument().getRootTag().getAttributes()[0].getValueElement()); if (listener != null) { listener.elementRenamed(element); } }