com.intellij.ide.fileTemplates.FileTemplateUtil Java Examples

The following examples show how to use com.intellij.ide.fileTemplates.FileTemplateUtil. 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: SelectFileTemplateDialog.java    From PackageTemplates with Apache License 2.0 6 votes vote down vote up
@NotNull
private ComboBox getSelector() {
    ArrayList<TemplateForSearch> listTemplateForSearch = FileTemplateHelper.getTemplates(
            project,
            cbAddInternal.isSelected(),
            cbAddJ2EE.isSelected(),
            ptWrapper.getPackageTemplate().getFileTemplateSource()
    );

    ComboBox comboBox = new ComboBox(listTemplateForSearch.toArray());
    comboBox.setRenderer(new ListCellRendererWrapper<TemplateForSearch>() {
        @Override
        public void customize(JList list, TemplateForSearch template, int index, boolean selected, boolean hasFocus) {
            if (template != null) {
                setIcon(FileTemplateUtil.getIcon(template.getTemplate()));
                setText(template.getTemplate().getName());
            }
        }
    });

    new ComboboxSpeedSearch(comboBox);
    return comboBox;
}
 
Example #2
Source File: CSharpCreateFileAction.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
@RequiredReadAction
protected PsiFile createFile(String name, String templateName, final PsiDirectory dir)
{
	FileTemplate template = FileTemplateManager.getInstance(dir.getProject()).getInternalTemplate(templateName);
	try
	{
		Map<String, Object> map = new HashMap<>();
		map.put("psiDirectory", dir);

		return (PsiFile) FileTemplateUtil.createFromTemplate(template, name, map, dir, getClass().getClassLoader());
	}
	catch(Exception e)
	{
		LOG.error(e);
		return null;
	}
}
 
Example #3
Source File: CreateFromTemplateDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doCreate(@Nullable String fileName) {
  try {
    String newName = fileName;
    PsiDirectory directory = myDirectory;
    if (fileName != null) {
      final String finalFileName = fileName;
      CreateFileAction.MkDirs mkDirs = WriteAction.compute(() -> new CreateFileAction.MkDirs(finalFileName, myDirectory));
      newName = mkDirs.newName;
      directory = mkDirs.directory;
    }
    myCreatedElement = FileTemplateUtil.createFromTemplate(myTemplate, newName, myAttrPanel.getVariables(myDefaultProperties), directory);
  }
  catch (Exception e) {
    showErrorDialog(e);
  }
}
 
Example #4
Source File: FileTemplateTabAsList.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void customizeCellRenderer(@Nonnull JList<? extends FileTemplate> list, FileTemplate value, int index, boolean selected, boolean hasFocus) {
  Image icon;
  icon = FileTemplateUtil.getIcon(value);
  final boolean internalTemplate = AllFileTemplatesConfigurable.isInternalTemplate(value.getName(), getTitle());
  if (internalTemplate) {
    setFont(getFont().deriveFont(Font.BOLD));
    append(value.getName());
  }
  else {
    setFont(getFont().deriveFont(Font.PLAIN));
    append(value.getName());
  }

  if (!value.isDefault()) {
    if (!selected) {
      setForeground(MODIFIED_FOREGROUND);
    }
  }
  setIcon(icon);
}
 
Example #5
Source File: FileWriter.java    From PackageTemplates with Apache License 2.0 5 votes vote down vote up
public static PsiElement createFileFromTemplate(CreateFileFromTemplateAction action, Project project, FileTemplate template, String fileName, Properties properties, String parentPath) {
        final PsiElement[] psiElement = {null};

        ApplicationManager.getApplication().invokeAndWait(() -> {
                    Runnable runnable = () -> {
                        psiElement[0] = ApplicationManager.getApplication().runWriteAction((Computable<PsiElement>) () -> {
                            PsiDirectory psiParentDir = VFSHelper.findPsiDirByPath(project, parentPath);
                            if (psiParentDir == null) {
                                return null;
                            }

                            try {
                                return FileTemplateUtil.createFromTemplate(template, fileName, properties, psiParentDir);
                            } catch (Exception e) {
                                Logger.logAndPrintStack("createFileFromTemplate", e);
                                ReportHelper.putReport(new FailedActionReport(action, e.getMessage()));
                                return null;
                            }
                        });
                    };
                    CommandProcessor.getInstance().executeCommand(project, runnable, "testId", "testId");
                }
                , ModalityState.defaultModalityState());

//        try {
//            Thread.sleep(1000L);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        return psiElement[0];
    }
 
Example #6
Source File: CreateFileTemplateAction.java    From PackageTemplates with Apache License 2.0 5 votes vote down vote up
private void doRunInWrite() {
        String text = FileReaderUtil.readFile(fileFrom);

        if (text == null) {
            ReportHelper.setState(ExecutionState.FAILED);
            ReportHelper.putReport(new FailedActionReport(this, Localizer.get("error.ReadFileContent"), "FileReaderUtil.readFile return null"));
            return;
        }


        FileTemplateManager ftm = FileTemplateHelper.getManagerInstance(project);
        FileTemplate oldTemplate = ftm.getTemplate(StringTools.getNameWithoutExtension(fileFrom.getName()));

        if (oldTemplate != null) {
            ftm.removeTemplate(oldTemplate);
//            ftm.saveAllTemplates();
        }

        FileTemplate[] templates = ftm.getAllTemplates();

        FileTemplate template = FileTemplateUtil.createTemplate(
                StringTools.getNameWithoutExtension(fileFrom.getName()),
                StringTools.getExtensionFromName(fileFrom.getName()),
                text, templates
        );
        ftm.setTemplates(FileTemplateManager.DEFAULT_TEMPLATES_CATEGORY, Arrays.asList(ArrayUtil.append(templates, template)));


        ReportHelper.putReport(new SuccessActionReport(this, toString()));
    }
 
Example #7
Source File: HaxeFileTemplateUtil.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static PsiElement createClass(String className, String packageName, PsiDirectory directory, String templateName, @org.jetbrains.annotations.Nullable java.lang.ClassLoader classLoader)
  throws Exception {
  final Properties props = new Properties(FileTemplateManager.getInstance().getDefaultProperties(directory.getProject()));
  props.setProperty(FileTemplate.ATTRIBUTE_NAME, className);
  props.setProperty(FileTemplate.ATTRIBUTE_PACKAGE_NAME, packageName);

  final FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);

  return FileTemplateUtil.createFromTemplate(template, className, props, directory, classLoader);
}
 
Example #8
Source File: CreateFromTemplateGroup.java    From consulo with Apache License 2.0 5 votes vote down vote up
static boolean canCreateFromTemplate(AnActionEvent e, FileTemplate template) {
  if (e == null) return false;
  DataContext dataContext = e.getDataContext();
  IdeView view = dataContext.getData(LangDataKeys.IDE_VIEW);
  if (view == null) return false;

  PsiDirectory[] dirs = view.getDirectories();
  if (dirs.length == 0) return false;

  return FileTemplateUtil.canCreateFromTemplate(dirs, template);
}
 
Example #9
Source File: CreateFromTemplateDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Deprecated
@DeprecationInfo("Use constructor with Map parameter instead of Properties")
public CreateFromTemplateDialog(@Nonnull Project project,
                                @Nonnull PsiDirectory directory,
                                @Nonnull FileTemplate template,
                                @Nullable final AttributesDefaults attributesDefaults,
                                @Nullable final Properties defaultProperties) {
  this(directory, template, attributesDefaults, defaultProperties == null ? null : FileTemplateUtil.convert2Map(defaultProperties));
}
 
Example #10
Source File: CreateFromTemplateDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CreateFromTemplateDialog(@Nonnull PsiDirectory directory,
                                @Nonnull FileTemplate template,
                                @Nullable final AttributesDefaults attributesDefaults,
                                @Nullable final Map<String, Object> defaultProperties) {
  super(directory.getProject(), true);
  myDirectory = directory;
  myProject = directory.getProject();
  myTemplate = template;
  setTitle(IdeBundle.message("title.new.from.template", template.getName()));

  myDefaultProperties = defaultProperties == null ? FileTemplateManager.getInstance(myProject).getDefaultVariables() : defaultProperties;
  FileTemplateUtil.fillDefaultProperties(myDefaultProperties, directory);
  boolean mustEnterName = FileTemplateUtil.findHandler(template).isNameRequired();
  if (attributesDefaults != null && attributesDefaults.isFixedName()) {
    myDefaultProperties.put(FileTemplate.ATTRIBUTE_NAME, attributesDefaults.getDefaultFileName());
    mustEnterName = false;
  }

  String[] unsetAttributes = null;
  try {
    unsetAttributes = myTemplate.getUnsetAttributes(myDefaultProperties, myProject);
  }
  catch (ParseException e) {
    showErrorDialog(e);
  }

  if (unsetAttributes != null) {
    myAttrPanel = new CreateFromTemplatePanel(unsetAttributes, mustEnterName, attributesDefaults);
    myAttrComponent = myAttrPanel.getComponent();
    init();
  }
  else {
    myAttrPanel = null;
    myAttrComponent = null;
  }
}
 
Example #11
Source File: FileTemplateBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public final String[] getUnsetAttributes(@Nonnull Map<String, Object> properties, Project project) throws ParseException {
  return FileTemplateUtil.calculateAttributes(getText(), properties, false, project);
}
 
Example #12
Source File: FileTemplateBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public final String[] getUnsetAttributes(@Nonnull Properties properties, Project project) throws ParseException {
  return FileTemplateUtil.calculateAttributes(getText(), properties, false, project);
}
 
Example #13
Source File: FileTemplateBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public final String getText(Properties attributes) throws IOException{
  return FileTemplateUtil.mergeTemplate(attributes, getText(), false);
}
 
Example #14
Source File: FileTemplateBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public final String getText(Map attributes) throws IOException{
  return FileTemplateUtil.mergeTemplate(attributes, getText(), false);
}
 
Example #15
Source File: CreateFromTemplateDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
private String getErrorMessage() {
  return FileTemplateUtil.findHandler(myTemplate).getErrorMessage();
}
 
Example #16
Source File: CreateFromTemplateAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public CreateFromTemplateAction(FileTemplate template){
  super(template.getName(), null, FileTemplateUtil.getIcon(template));
  myTemplate = template;
}
 
Example #17
Source File: DoctrineOrmRepositoryIntention.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {

    PhpClass phpClass = getScopedPhpClass(element);
    if(phpClass == null) {
        return;
    }

    String fileName = phpClass.getName() + "Repository.php";
    String namespace = DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName());
    PsiDirectory dir = phpClass.getContainingFile().getContainingDirectory();

    PsiDirectory repositoryDir = dir;
    if (dir.getParentDirectory() != null) {
        PsiDirectory checkDir = dir.getParentDirectory().findSubdirectory("Repository");

        if (dir.findFile(fileName) == null && checkDir != null) {
            repositoryDir = checkDir;
        }
    }

    String repoClass = phpClass.getPresentableFQN() + "Repository";
    PhpClass repoPhpClass = PhpElementsUtil.getClass(project, repoClass);

    if (repoPhpClass == null && dir != repositoryDir) {
        // Entity/../Repository/
        namespace = phpClass.getNamespaceName();
        namespace = namespace.substring(0, namespace.lastIndexOf("\\"));
        namespace = namespace.substring(0, namespace.lastIndexOf("\\"));
        namespace = namespace + "\\Repository";
        namespace = DoctrineUtil.trimBlackSlashes(namespace);

        repoClass = namespace + "\\" + phpClass.getName() + "Repository";
        repoClass = PhpLangUtil.toPresentableFQN(repoClass);

        repoPhpClass = PhpElementsUtil.getClass(project, repoClass);
    }

    if(repoPhpClass == null) {
        if(repositoryDir.findFile(fileName) == null) {
            final FileTemplate fileTemplate = FileTemplateManager.getInstance(project).getTemplate("Doctrine Entity Repository");
            final Properties defaultProperties = FileTemplateManager.getInstance(project).getDefaultProperties();

            Properties properties = new Properties(defaultProperties);

            properties.setProperty("NAMESPACE", namespace);
            properties.setProperty("NAME", phpClass.getName() + "Repository");

            properties.setProperty("ENTITY_NAMESPACE", DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName()));
            properties.setProperty("ENTITY_NAME", phpClass.getName());

            try {
                PsiElement newElement = FileTemplateUtil.createFromTemplate(fileTemplate, fileName, properties, repositoryDir);

                new OpenFileDescriptor(project, newElement.getContainingFile().getVirtualFile(), 0).navigate(true);
            } catch (Exception e) {
                return;
            }
        } else {
            if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
                HintManager.getInstance().showErrorHint(editor, "Repository already exists ");
            }
        }
    }

    PhpDocTagAnnotation ormEntityPhpDocBlock = DoctrineUtil.getOrmEntityPhpDocBlock(phpClass);
    if(ormEntityPhpDocBlock != null) {
        PhpDocTag phpDocTag = ormEntityPhpDocBlock.getPhpDocTag();
        PhpPsiElement firstPsiChild = phpDocTag.getFirstPsiChild();
        insertAttribute(editor, repoClass, phpDocTag, firstPsiChild);
    }

}
 
Example #18
Source File: BxNewSectionAction.java    From bxfs with MIT License 4 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
	IdeView view
		= event.getData(LangDataKeys.IDE_VIEW);

	if (view != null) {
		Project project
			= event.getProject();

		if (project != null) {
			PsiDirectory directory
				= DirectoryChooserUtil.getOrChooseDirectory(view);

			if (directory != null) {
				CreateDirectoryOrPackageHandler validator
					= new CreateDirectoryOrPackageHandler(project, directory, true, "\\/");

				// Сообщение не нужно, так как заголовок окна и так близко. Они резонируют.
				Messages.showInputDialog(project, null, "Битрикс: Создание Нового Раздела", BitrixFramework.bxIcon, "", validator);

				PsiElement result = validator.getCreatedElement();
				if (result instanceof PsiDirectory) {
					PsiDirectory createdDir = (PsiDirectory) result;

					FileTemplateManager templateManager
						= FileTemplateManager.getInstance(project);

					FileTemplate cfgTemplate = templateManager.findInternalTemplate("Битрикс - Раздел (настройки)");
					FileTemplate idxTemplate = templateManager.findInternalTemplate("Битрикс - Раздел (титульная)");

					Properties properties
						= FileTemplateManager.getInstance(project).getDefaultProperties();

					try {
						PsiElement cfgFile = FileTemplateUtil.createFromTemplate(cfgTemplate, ".section", properties, createdDir);
						PsiElement idxFile = FileTemplateUtil.createFromTemplate(idxTemplate, "index", properties, createdDir);

						view.selectElement(idxFile);
					}
					catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
 
Example #19
Source File: TemplateFileUtil.java    From NutzCodeInsight with Apache License 2.0 2 votes vote down vote up
/**
 * 按照idea默认模版引擎生成文件
 *
 * @param fileTemplateName
 * @param fileName
 * @param properties
 * @param directory
 * @return
 * @throws Exception
 */
public static PsiElement createFromTemplate(String fileTemplateName, String fileName, Properties properties, PsiDirectory directory) throws Exception {
    FileTemplateManager fileTemplateManager = FileTemplateManager.getDefaultInstance();
    FileTemplate fileTemplate = fileTemplateManager.getJ2eeTemplate(fileTemplateName);
    return FileTemplateUtil.createFromTemplate(fileTemplate, fileName, properties, directory);
}