public static PsiFile createFromTemplate(
      final PsiDirectory directory,
      final String name,
      String fileName,
      String templateName,
      @NonNls String... parameters)
      throws IncorrectOperationException {
    log.debug("createFromTemplate: dir:" + directory + ", filename: " + fileName);

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

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

    String text;

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

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

    log.debug("Create file from text");
    final PsiFile file = factory.createFileFromText(fileName, MoonFileType.MOON_FILE_TYPE, text);

    log.debug("Adding file to directory");
    return (PsiFile) directory.add(file);
  }
  @Override
  protected void buildDialog(
      final Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
    builder
        .setTitle(JavaCoreBundle.message("action.create.new.class"))
        .addKind("Class", PlatformIcons.CLASS_ICON, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME)
        .addKind(
            "Interface",
            PlatformIcons.INTERFACE_ICON,
            JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME);

    Module module = ModuleUtilCore.findModuleForPsiElement(directory);
    assert module != null;
    JavaModuleExtensionImpl moduleExtension =
        ModuleRootManager.getInstance(module).getExtension(JavaModuleExtensionImpl.class);

    assert moduleExtension != null;
    if (moduleExtension.getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) {
      builder.addKind(
          "Enum", PlatformIcons.ENUM_ICON, JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME);
      builder.addKind(
          "Annotation",
          PlatformIcons.ANNOTATION_TYPE_ICON,
          JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME);
    }

    for (FileTemplate template : FileTemplateManager.getInstance().getAllTemplates()) {
      final JavaCreateFromTemplateHandler handler = new JavaCreateFromTemplateHandler();
      if (handler.handlesTemplate(template) && JavaCreateFromTemplateHandler.canCreate(directory)) {
        builder.addKind(template.getName(), JavaFileType.INSTANCE.getIcon(), template.getName());
      }
    }

    builder.setValidator(
        new InputValidatorEx() {
          @Override
          public String getErrorText(String inputString) {
            if (inputString.length() > 0
                && !JavaPsiFacade.getInstance(project)
                    .getNameHelper()
                    .isQualifiedName(inputString)) {
              return "This is not a valid Java qualified name";
            }
            return null;
          }

          @Override
          public boolean checkInput(String inputString) {
            return true;
          }

          @Override
          public boolean canClose(String inputString) {
            return !StringUtil.isEmptyOrSpaces(inputString) && getErrorText(inputString) == null;
          }
        });
  }
 public CreateFromTemplateAction(FileTemplate template) {
   super(
       template.getName(),
       null,
       FileTypeManagerEx.getInstanceEx()
           .getFileTypeByExtension(template.getExtension())
           .getIcon());
   myTemplate = template;
 }
 private void registerScalaScriptTemplate() {
   String templateText = ScalaBundle.message("template.file.text");
   if (FileTemplateManager.getInstance().getTemplate(SCALA_FILE_TEMPLATE) == null) {
     FileTemplate scalaTemplate =
         FileTemplateManager.getInstance()
             .addTemplate(
                 SCALA_FILE_TEMPLATE, ScalaFileType.SCALA_FILE_TYPE.getDefaultExtension());
     ((FileTemplateImpl) scalaTemplate).setInternal(true);
     scalaTemplate.setText(templateText);
   }
 }
 private static String getText(final String templateName, @Nullable Project project)
     throws IOException {
   final FileTemplateManager templateManager =
       project == null
           ? FileTemplateManager.getDefaultInstance()
           : FileTemplateManager.getInstance(project);
   final FileTemplate template = templateManager.getJ2eeTemplate(templateName);
   if (template == null) {
     return "";
   }
   return template.getText(templateManager.getDefaultProperties());
 }
 public void testSurroundWithTryCatchProperties() {
   FileTemplate template =
       FileTemplateManager.getInstance(getProject())
           .getCodeTemplate(JavaTemplateUtil.TEMPLATE_CATCH_BODY);
   String old = template.getText();
   template.setText("// ${DS} \n" + "${EXCEPTION}.printStackTrace();");
   try {
     doTest(new JavaWithTryCatchSurrounder());
   } finally {
     template.setText(old);
   }
 }
  @Override
  public void setupRootModel(ModifiableRootModel model) throws ConfigurationException {
    String contentPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentPath)) {
      return;
    }
    File contentRootDir = new File(contentPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile vContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (vContentRootDir == null) {
      return;
    }

    model.addContentEntry(vContentRootDir);

    VirtualFile configFile = getExternalProjectConfigFile(vContentRootDir);
    if (configFile != null && myTemplateConfigName != null) {
      FileTemplateManager manager = FileTemplateManager.getInstance();
      FileTemplate template = manager.getInternalTemplate(myTemplateConfigName);
      try {
        VfsUtil.saveText(configFile, template.getText());
      } catch (IOException e) {
        LOG.warn(
            String.format(
                "Unexpected exception on applying template %s config",
                myExternalSystemId.getReadableName()),
            e);
        throw new ConfigurationException(
            e.getMessage(),
            String.format(
                "Can't apply %s template config text", myExternalSystemId.getReadableName()));
      }
    }

    AbstractExternalSystemSettings settings =
        ExternalSystemApiUtil.getSettings(model.getProject(), myExternalSystemId);
    S externalProjectSettings = createSettings();
    if (myExternalProjectSettingsControl != null) {
      String errorMessage = myExternalProjectSettingsControl.apply(externalProjectSettings);
      myExternalProjectSettingsControl.disposeUIResources();
      if (errorMessage != null) {
        throw new ConfigurationException(errorMessage);
      }
    }
    //noinspection unchecked
    settings.linkProject(externalProjectSettings);
  }
  @SuppressWarnings("DialogTitleCapitalization")
  @Nullable
  public static PsiFile createFileFromTemplate(
      @SuppressWarnings("NullableProblems") @NotNull String name,
      @NotNull FileTemplate template,
      @NotNull PsiDirectory dir,
      @Nullable String defaultTemplateProperty) {
    // TODO: Do we *have* to hack the IntelliJ source?
    // This is a roughly a copy/paste then slight adaptation from the IntelliJ definition of this
    // method.
    // We can't override it directly, and more importantly we can't override its call to
    // FileTemplateUtil.createFromTemplate()
    List<String> pathItems = FileUtil.getPathFromSourceRoot(dir.getProject(), dir.getVirtualFile());
    // modulePrefix is the empty string if the module is either in the top
    // level directory or one of the subdirectories start with a lower-case
    // letter.
    final String modulePrefix =
        pathItems == null || invalidPathItems(pathItems) ? "" : StringUtil.join(pathItems, ".");

    // Adapted from super definition.
    CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(name, dir);
    name = mkdirs.newName;
    dir = mkdirs.directory;
    PsiElement element;
    Project project = dir.getProject();
    try {
      // Patch props with custom property.
      Properties props = FileTemplateManager.getInstance().getDefaultProperties(project);
      props.setProperty(
          "HASKELL_MODULE_NAME", modulePrefix.isEmpty() ? name : modulePrefix + '.' + name);
      element = FileTemplateUtil.createFromTemplate(template, name, props, dir);

      final PsiFile psiFile = element.getContainingFile();

      final VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile != null) {
        FileEditorManager.getInstance(project).openFile(virtualFile, true);
        if (defaultTemplateProperty != null) {
          PropertiesComponent.getInstance(project)
              .setValue(defaultTemplateProperty, template.getName());
        }
        return psiFile;
      }
    } catch (ParseException e) {
      Messages.showErrorDialog(
          project,
          "Error parsing Velocity template: " + e.getMessage(),
          "Create File from Template");
      return null;
    } catch (IncorrectOperationException e) {
      throw e;
    } catch (Exception e) {
      LOG.error(e);
    }

    return null;
  }
 @Nullable
 public static VirtualFile createFileFromTemplate(
     final String templateName, final VirtualFile parent, final String fileName) {
   parent.refresh(false, false);
   final FileTemplate template = FileTemplateManager.getInstance().getJ2eeTemplate(templateName);
   try {
     final String text =
         template.getText(FileTemplateManager.getInstance().getDefaultProperties());
     VirtualFile file = parent.findChild(fileName);
     if (file == null) {
       file = parent.createChildData(AppEngineSupportProvider.class, fileName);
     }
     VfsUtil.saveText(file, text);
     return file;
   } catch (IOException e) {
     LOG.error(e);
     return null;
   }
 }
Beispiel #10
0
  private static void runOrApplyFileTemplate(
      Project project,
      VirtualFile file,
      String templateName,
      Properties properties,
      Properties conditions,
      boolean interactive)
      throws IOException {
    FileTemplateManager manager = FileTemplateManager.getInstance();
    FileTemplate fileTemplate = manager.getJ2eeTemplate(templateName);
    Properties allProperties = manager.getDefaultProperties(project);
    if (!interactive) {
      allProperties.putAll(properties);
    }
    allProperties.putAll(conditions);
    String text = fileTemplate.getText(allProperties);
    Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
    Matcher matcher = pattern.matcher(text);
    StringBuffer builder = new StringBuffer();
    while (matcher.find()) {
      matcher.appendReplacement(builder, "\\$" + matcher.group(1).toUpperCase() + "\\$");
    }
    matcher.appendTail(builder);
    text = builder.toString();

    TemplateImpl template =
        (TemplateImpl) TemplateManager.getInstance(project).createTemplate("", "", text);
    for (int i = 0; i < template.getSegmentsCount(); i++) {
      if (i == template.getEndSegmentNumber()) continue;
      String name = template.getSegmentName(i);
      String value = "\"" + properties.getProperty(name, "") + "\"";
      template.addVariable(name, value, value, true);
    }

    if (interactive) {
      OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
      Editor editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
      editor.getDocument().setText("");
      TemplateManager.getInstance(project).startTemplate(editor, template);
    } else {
      VfsUtil.saveText(file, template.getTemplateText());
    }
  }
 @Override
 public boolean isModified() {
   if (myModified) {
     return true;
   }
   String name = (myTemplate == null) ? "" : myTemplate.getName();
   String extension = (myTemplate == null) ? "" : myTemplate.getExtension();
   if (!Comparing.equal(name, myNameField.getText())) {
     return true;
   }
   if (!Comparing.equal(extension, myExtensionField.getText())) {
     return true;
   }
   if (myTemplate != null) {
     if (myTemplate.isReformatCode() != myAdjustBox.isSelected()) {
       return true;
     }
   }
   return false;
 }
  private EditorHighlighter createHighlighter() {
    if (myTemplate != null && myProject != null && myVelocityFileType != FileTypes.UNKNOWN) {
      return EditorHighlighterFactory.getInstance()
          .createEditorHighlighter(
              myProject, new LightVirtualFile("aaa." + myTemplate.getExtension() + ".ft"));
    }

    FileType fileType = null;
    if (myTemplate != null) {
      fileType = FileTypeManager.getInstance().getFileTypeByExtension(myTemplate.getExtension());
    }
    if (fileType == null) {
      fileType = FileTypes.PLAIN_TEXT;
    }
    SyntaxHighlighter originalHighlighter =
        SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, null, null);
    if (originalHighlighter == null) originalHighlighter = new PlainSyntaxHighlighter();
    return new LexerEditorHighlighter(
        new TemplateHighlighter(originalHighlighter),
        EditorColorsManager.getInstance().getGlobalScheme());
  }
 @Override
 public void apply() throws ConfigurationException {
   if (myTemplate != null) {
     myTemplate.setText(myTemplateEditor.getDocument().getText());
     String name = myNameField.getText();
     String extension = myExtensionField.getText();
     int lastDotIndex = extension.lastIndexOf(".");
     if (lastDotIndex >= 0) {
       name += extension.substring(0, lastDotIndex + 1);
       extension = extension.substring(lastDotIndex + 1);
     }
     if (name.length() == 0 || !isValidFilename(name + "." + extension)) {
       throw new ConfigurationException(
           IdeBundle.message("error.invalid.template.file.name.or.extension"));
     }
     myTemplate.setName(name);
     myTemplate.setExtension(extension);
     myTemplate.setReformatCode(myAdjustBox.isSelected());
   }
   myModified = false;
 }
 private static void saveFile(
     @NotNull VirtualFile file, @NotNull String templateName, @Nullable Map templateAttributes)
     throws ConfigurationException {
   FileTemplateManager manager = FileTemplateManager.getInstance();
   FileTemplate template = manager.getInternalTemplate(templateName);
   try {
     VfsUtil.saveText(
         file,
         templateAttributes != null ? template.getText(templateAttributes) : template.getText());
   } catch (IOException e) {
     LOG.warn(
         String.format(
             "Unexpected exception on applying template %s config",
             GradleConstants.SYSTEM_ID.getReadableName()),
         e);
     throw new ConfigurationException(
         e.getMessage(),
         String.format(
             "Can't apply %s template config text", GradleConstants.SYSTEM_ID.getReadableName()));
   }
 }
  @Override
  public void reset() {
    final String text = (myTemplate == null) ? "" : myTemplate.getText();
    String name = (myTemplate == null) ? "" : myTemplate.getName();
    String extension = (myTemplate == null) ? "" : myTemplate.getExtension();
    String description = (myTemplate == null) ? "" : myTemplate.getDescription();

    if ((description.length() == 0) && (myDefaultDescriptionUrl != null)) {
      try {
        description = UrlUtil.loadText(myDefaultDescriptionUrl);
      } catch (IOException e) {
        LOG.error(e);
      }
    }

    EditorFactory.getInstance().releaseEditor(myTemplateEditor);
    myFile = createFile(text, name);
    myTemplateEditor = createEditor();

    boolean adjust = (myTemplate != null) && myTemplate.isReformatCode();
    myNameField.setText(name);
    myExtensionField.setText(extension);
    myAdjustBox.setSelected(adjust);
    String desc = description.length() > 0 ? description : EMPTY_HTML;

    // [myakovlev] do not delete these stupid lines! Or you get Exception!
    myDescriptionComponent.setContentType(CONTENT_TYPE_PLAIN);
    myDescriptionComponent.setEditable(true);
    myDescriptionComponent.setText(desc);
    myDescriptionComponent.setContentType(UIUtil.HTML_MIME);
    myDescriptionComponent.setText(desc);
    myDescriptionComponent.setCaretPosition(0);
    myDescriptionComponent.setEditable(false);

    myDescriptionPanel.setVisible(StringUtil.isNotEmpty(description));

    myNameField.setEditable((myTemplate != null) && (!myTemplate.isDefault()));
    myExtensionField.setEditable((myTemplate != null) && (!myTemplate.isDefault()));
    myModified = false;
  }
  private Editor createEditor() {
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document doc =
        myFile == null
            ? editorFactory.createDocument(myTemplate == null ? "" : myTemplate.getText())
            : PsiDocumentManager.getInstance(myFile.getProject()).getDocument(myFile);
    Editor editor =
        myProject == null
            ? editorFactory.createEditor(doc)
            : editorFactory.createEditor(doc, myProject);

    EditorSettings editorSettings = editor.getSettings();
    editorSettings.setVirtualSpace(false);
    editorSettings.setLineMarkerAreaShown(false);
    editorSettings.setIndentGuidesShown(false);
    editorSettings.setLineNumbersShown(false);
    editorSettings.setFoldingOutlineShown(false);
    editorSettings.setAdditionalColumnsCount(3);
    editorSettings.setAdditionalLinesCount(3);

    EditorColorsScheme scheme = editor.getColorsScheme();
    scheme.setColor(EditorColors.CARET_ROW_COLOR, null);

    editor
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              @Override
              public void documentChanged(DocumentEvent e) {
                onTextChanged();
              }
            });

    ((EditorEx) editor).setHighlighter(createHighlighter());
    mySplitter.setFirstComponent(editor.getComponent());
    return editor;
  }