com.intellij.psi.codeStyle.CodeStyleManager Java Examples

The following examples show how to use com.intellij.psi.codeStyle.CodeStyleManager. 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: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void reformatBlock(final Project project, final Editor editor, final int startOffset, final int endOffset) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  Runnable task = new Runnable() {
    @Override
    public void run() {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      try {
        CodeStyleManager.getInstance(project).reformatRange(file, startOffset, endOffset, true);
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  };

  if (endOffset - startOffset > 1000) {
    DocumentUtil.executeInBulk(editor.getDocument(), true, task);
  }
  else {
    task.run();
  }
}
 
Example #2
Source File: HaxeDocumentModel.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 * Replace the text within the given range and reformat it according to the user's
 * code style/formatting rules.
 *
 * NOTE: The PSI may be entirely invalidated and re-created by this call.
 *
 * @param range Range of text or PsiElements to replace.
 * @param text Replacement text (may be null).
 */
public void replaceAndFormat(@NotNull final TextRange range, @Nullable String text) {
  if (null == text) {
    text = "";
  }

  // Mark the beginning and end so that we have the proper range after adding text.
  // Greedy means that the text immediately added at the beginning/end of the marker are included.
  RangeMarker marker = document.createRangeMarker(range);
  marker.setGreedyToLeft(true);
  marker.setGreedyToRight(true);

  try {

    document.replaceString(range.getStartOffset(), range.getEndOffset(), text);

    //PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); // force update PSI.

    if (marker.isValid()) { // If the range wasn't reduced to zero.
      CodeStyleManager.getInstance(file.getProject()).reformatText(file, marker.getStartOffset(), marker.getEndOffset());
    }
  }
  finally {
    marker.dispose();
  }
}
 
Example #3
Source File: CsvFormatterTest.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
/**
 * This function should be executed (remove the underscore) if the current results are correct (manual testing).
 *
 * @throws Exception
 */
public void _testResultGenerator() throws Exception {
    for (int binarySettings = 0; binarySettings < 128; ++binarySettings) {
        tearDown();
        setUp();

        myFixture.configureByFiles("/generated/TestData.csv");

        initCsvCodeStyleSettings(binarySettings);

        new WriteCommandAction.Simple(getProject()) {
            @Override
            protected void run() throws Throwable {
                CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
                        ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
            }
        }.execute();

        try (PrintWriter writer = new PrintWriter(getTestDataPath() + String.format("/generated/TestResult%08d.csv", binarySettings))
        ) {
            writer.print(myFixture.getFile().getText());
        }
    }
}
 
Example #4
Source File: ExtractIncludeFileBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
protected String doExtract(final PsiDirectory targetDirectory,
                           final String targetfileName,
                           final T first,
                           final T last,
                           final Language includingLanguage) throws IncorrectOperationException {
  final PsiFile file = targetDirectory.createFile(targetfileName);
  Project project = targetDirectory.getProject();
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final Document document = documentManager.getDocument(file);
  document.replaceString(0, document.getTextLength(), first.getText().trim());
  documentManager.commitDocument(document);
  CodeStyleManager.getInstance(PsiManager.getInstance(project).getProject()).reformat(file);  //TODO: adjustLineIndent

  final String relativePath = PsiFileSystemItemUtil.getRelativePath(first.getContainingFile(), file);
  if (relativePath == null) throw new IncorrectOperationException("Cannot extract!");
  return relativePath;
}
 
Example #5
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 #6
Source File: ClosingTagHandler.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
  myOriginalHandler.execute(editor, charTyped, dataContext);
  if (isMatchForClosingTag(editor, charTyped)) {
    PsiFile file = dataContext.getData(LangDataKeys.PSI_FILE);
    if (file == null) {
      return;
    }
    int offset = editor.getCaretModel().getOffset();
    TagBlockElement block = findEnclosingTagBlockElement(file, offset);
    if (block == null) {
      return;
    }
    insertClosingTag(editor, offset, block.getOpeningTag().generateClosingTag());
    if (editor.getProject() != null) {
      PsiDocumentManager.getInstance(editor.getProject()).commitDocument(editor.getDocument());
      TagBlockElement completedBlock = findEnclosingTagBlockElement(file, editor.getCaretModel().getOffset());
      if (completedBlock == null) {
        return;
      }
      CodeStyleManager.getInstance(editor.getProject()).reformat(completedBlock);
    }
  }
}
 
Example #7
Source File: HaxeSurroundTest.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
protected void doTest(final Surrounder surrounder) throws Exception {
  myFixture.configureByFile(getTestName(false) + ".hx");

  WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
    @Override
    public void run() {
      SurroundWithHandler.invoke(getProject(), myFixture.getEditor(), myFixture.getFile(), surrounder);
      PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(myFixture.getDocument(myFixture.getFile()));
      CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
    }
  });
    /*CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
            SurroundWithHandler.invoke(getProject(), myFixture.getEditor(), myFixture.getFile(), surrounder);
            PsiDocumentManager.getInstance(getProject()).doPostponedOperationsAndUnblockDocument(myFixture.getDocument(myFixture.getFile()));
            CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
        }
    }, null, null);*/

  myFixture.checkResultByFile(getTestName(false) + "_after.hx");
}
 
Example #8
Source File: ExtensionFileGenerationUtil.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
/**
 * @param templateFile           Name of the generated file
 * @param destinationPath        Relative path to the target file system entry
 * @param extensionRootDirectory Extension definition containing all relevant metadata
 * @param context                Template Context variables
 * @param project                Project in context
 */
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull PsiDirectory extensionRootDirectory, @NotNull Map<String, String> context, Project project) {
    String template = readTemplateToString(templateFile, context);

    VirtualFile targetDirectory = getOrCreateDestinationPath(extensionRootDirectory.getVirtualFile(), destinationPath);

    LanguageFileType fileType = FileTypes.PLAIN_TEXT;
    if (templateFile.endsWith(".php")) {
        fileType = PhpFileType.INSTANCE;
    }

    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory
            .getInstance(project)
            .createDirectory(targetDirectory)
            .add(fileFromText);
}
 
Example #9
Source File: ExtensionFileGenerationUtil.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
/**
 * @param templateFile        Name of the generated file
 * @param destinationPath     Relative path to the target file system entry
 * @param extensionDefinition Extension definition containing all relevant metadata
 * @param context             Template Context variables
 * @param project             Project in context
 */
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull TYPO3ExtensionDefinition extensionDefinition, @NotNull Map<String, String> context, Project project) {
    String template = readTemplateToString(templateFile, context);

    VirtualFile targetDirectory = getOrCreateDestinationPath(extensionDefinition.getRootDirectory(), destinationPath);

    LanguageFileType fileType = FileTypes.PLAIN_TEXT;
    if (templateFile.endsWith(".php")) {
        fileType = PhpFileType.INSTANCE;
    }

    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory
            .getInstance(project)
            .createDirectory(targetDirectory)
            .add(fileFromText);
}
 
Example #10
Source File: HaxeLiveTemplatesTest.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private void doTest(String... files) throws Exception {
  myFixture.configureByFiles(files);
  if (IdeaTarget.IS_VERSION_17_COMPATIBLE) {
    // The implementation of finishLookup in IDEA 2017 requires that it run OUTSIDE of a write command,
    // while previous versions require that is run inside of one.
    expandTemplate(myFixture.getEditor());
  }
  WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
    @Override
    public void run() {
      if (!IdeaTarget.IS_VERSION_17_COMPATIBLE) {
        expandTemplate(myFixture.getEditor());
      }
      CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
    }
  });
  myFixture.getEditor().getSelectionModel().removeSelection();
  myFixture.checkResultByFile(getTestName(false) + "_after.hx");
}
 
Example #11
Source File: CustomizableLanguageCodeStylePanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected PsiFile doReformat(final Project project, final PsiFile psiFile) {
  final String text = psiFile.getText();
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
  final Document doc = manager.getDocument(psiFile);
  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    if (doc != null) {
      doc.replaceString(0, doc.getTextLength(), text);
      manager.commitDocument(doc);
    }
    try {
      CodeStyleManager.getInstance(project).reformat(psiFile);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }), "", "");
  if (doc != null) {
    manager.commitDocument(doc);
  }
  return psiFile;
}
 
Example #12
Source File: DustTypedHandler.java    From Intellij-Dust with MIT License 6 votes vote down vote up
/**
 * When appropriate, automatically reduce the indentation for else tags "{:else}"
 */
private void adjustFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
  PsiElement elementAtCaret = provider.findElementAt(offset - 1, DustLanguage.class);
  PsiElement elseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
    @Override
    public boolean value(PsiElement element) {
      return element != null
          && (element instanceof DustElseTag);
    }
  });

  // run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
  if (elseParent != null) {
    // grab the current caret position (AutoIndentLinesHandler is about to mess with it)
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    CaretModel caretModel = editor.getCaretModel();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
  }
}
 
Example #13
Source File: PomModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void reparseParallelTrees(PsiFile changedFile, PsiToDocumentSynchronizer synchronizer) {
  List<PsiFile> allFiles = changedFile.getViewProvider().getAllFiles();
  if (allFiles.size() <= 1) {
    return;
  }

  CharSequence newText = changedFile.getNode().getChars();
  for (final PsiFile file : allFiles) {
    FileElement fileElement = file == changedFile ? null : ((PsiFileImpl)file).getTreeElement();
    Runnable changeAction = fileElement == null ? null : reparseFile(file, fileElement, newText);
    if (changeAction == null) continue;

    synchronizer.setIgnorePsiEvents(true);
    try {
      CodeStyleManager.getInstance(file.getProject()).performActionWithFormatterDisabled(changeAction);
    }
    finally {
      synchronizer.setIgnorePsiEvents(false);
    }
  }
}
 
Example #14
Source File: SpringFormatComponent.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
private void registerCodeStyleManager(CodeStyleManager manager) {
	if (ApplicationInfo.getInstance().getBuild().getBaselineVersion() >= 193) {
		IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(PluginId.getId("spring-javaformat"));
		try {
			((ComponentManagerImpl) this.project).registerServiceInstance(CodeStyleManager.class, manager, plugin);
		}
		catch (NoSuchMethodError ex) {
			Method method = findRegisterServiceInstanceMethod(this.project.getClass());
			invokeRegisterServiceInstanceMethod(manager, plugin, method);
		}
	}
	else {
		MutablePicoContainer container = (MutablePicoContainer) this.project.getPicoContainer();
		container.unregisterComponent(CODE_STYLE_MANAGER_KEY);
		container.registerComponentInstance(CODE_STYLE_MANAGER_KEY, manager);
	}
}
 
Example #15
Source File: SpringFormatComponent.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
private void update(State state) {
	this.lock.lock();
	try {
		CodeStyleManager manager = CodeStyleManager.getInstance(this.project);
		if (manager == null) {
			logger.warn("Unable to find exiting CodeStyleManager");
			return;
		}
		if (state == State.ACTIVE && !(manager instanceof SpringCodeStyleManager)) {
			logger.debug("Enabling SpringCodeStyleManager");
			registerCodeStyleManager(new SpringCodeStyleManager(manager));
			this.properties.setValue(ACTIVE_PROPERTY, true);
		}
		if (state == State.NOT_ACTIVE && (manager instanceof SpringCodeStyleManager)) {
			logger.debug("Disabling SpringCodeStyleManager");
			registerCodeStyleManager(((SpringCodeStyleManager) manager).getDelegate());
			this.properties.setValue(ACTIVE_PROPERTY, false);
		}
		ApplicationManager.getApplication().invokeLater(() -> this.statusIndicator.update(state));
	}
	finally {
		this.lock.unlock();
	}
}
 
Example #16
Source File: BashFormatterTestCase.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
protected void checkFormatting(String expected) throws IOException {
    CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() {
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    try {
                        final PsiFile file = myFixture.getFile();
                        TextRange myTextRange = file.getTextRange();
                        CodeStyleManager.getInstance(file.getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                }
            });
        }
    }, null, null);
    myFixture.checkResult(expected);
}
 
Example #17
Source File: HaxeFormatterTest.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void doTest() throws Exception {
  myFixture.configureByFile(getTestName(false) + ".hx");
    /*CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
            CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());

        }
    }, null, null);*/
  WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
    @Override
    public void run() {
      CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
    }
  });
  try {
    myFixture.checkResultByFile(getTestName(false) + ".txt");
  }
  catch (RuntimeException e) {
    if (!(e.getCause() instanceof FileNotFoundException)) {
      throw e;
    }
    final String path = getTestDataPath() + getTestName(false) + ".txt";
    FileWriter writer = new FileWriter(FileUtil.toSystemDependentName(path));
    try {
      writer.write(myFixture.getFile().getText().trim());
    }
    finally {
      writer.close();
    }
    fail("No output text found. File " + path + " created.");
  }
}
 
Example #18
Source File: FormatterTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void performFormattingWithDocument(final PsiFile file) {
  try {
    if (myTextRange == null) {
      CodeStyleManager.getInstance(getProject()).reformatText(file, 0, file.getTextLength());
    }
    else {
      CodeStyleManager.getInstance(getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
    }
  }
  catch (IncorrectOperationException e) {
    fail();
  }
}
 
Example #19
Source File: PhpBundleFileFactory.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public static PsiElement createBundleFile(@NotNull PhpClass bundleClass, @NotNull String template, @NotNull String className, Map<String, String> vars) throws Exception {

    VirtualFile directory = bundleClass.getContainingFile().getContainingDirectory().getVirtualFile();
    if(fileExists(directory, new String[] {className})) {
        throw new Exception("File already exists");
    }

    String COMPILER_TEMPLATE = "/fileTemplates/" + template + ".php";
    String fileTemplateContent = getFileTemplateContent(COMPILER_TEMPLATE);
    if(fileTemplateContent == null) {
        throw new Exception("Template content error");
    }

    String[] split = className.split("\\\\");

    String ns = bundleClass.getNamespaceName();
    String join = StringUtils.join(Arrays.copyOf(split, split.length - 1), "/");

    vars.put("ns", (ns.startsWith("\\") ? ns.substring(1) : ns) + join.replace("/", "\\"));
    vars.put("class", split[split.length - 1]);
    for (Map.Entry<String, String> entry : vars.entrySet()) {
        fileTemplateContent = fileTemplateContent.replace("{{ " + entry.getKey() + " }}", entry.getValue());
    }

    VirtualFile compilerDirectory = getAndCreateDirectory(directory, join);
    if(compilerDirectory == null) {
        throw new Exception("Directory creation failed");
    }

    Project project = bundleClass.getProject();
    PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(split[split.length - 1] + ".php", PhpFileType.INSTANCE, fileTemplateContent);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory.getInstance(project).createDirectory(compilerDirectory).add(fileFromText);
}
 
Example #20
Source File: ScratchFileCreationHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String reformat(@Nonnull Project project, @Nonnull Language language, @Nonnull String text) {
  return WriteCommandAction.runWriteCommandAction(project, (Computable<String>)() -> {
    PsiFile psi = parseHeader(project, language, text);
    if (psi != null) CodeStyleManager.getInstance(project).reformat(psi);
    return psi == null ? text : psi.getText();
  });
}
 
Example #21
Source File: XQueryFormattingModelBuilderTest.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
void executeTest(String before, String after) {
    myFixture.configureByText("a.xq", before);
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
        }
    });
    myFixture.checkResult(after);
}
 
Example #22
Source File: FormatterBasedIndentAdjuster.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  int lineStart = myDocument.getLineStartOffset(myLine);
  CommandProcessor.getInstance().runUndoTransparentAction(() -> ApplicationManager.getApplication().runWriteAction(() -> {
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
    if (codeStyleManager instanceof FormattingModeAwareIndentAdjuster) {
      ((FormattingModeAwareIndentAdjuster)codeStyleManager).adjustLineIndent(myDocument, lineStart, FormattingMode.ADJUST_INDENT_ON_ENTER);
    }
  }));
}
 
Example #23
Source File: JSGraphQLCodeInsightTest.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Test
public void testFormatter() {
    myFixture.configureByFiles("FormatterTestData.graphql");
    CodeStyleSettingsManager.getSettings(getProject()).KEEP_BLANK_LINES_IN_CODE = 2;
    new WriteCommandAction.Simple(getProject()) {
        @Override
        protected void run() throws Throwable {
            CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
        }
    }.execute();
    myFixture.checkResultByFile("FormatterExpectedResult.graphql");
}
 
Example #24
Source File: XQueryFormattingModelBuilderTest.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
void executeTest() {
    myFixture.configureByFiles(getTestName() + ".xq");
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
        }
    });
    myFixture.checkResultByFile(getTestName() + "_after.xq");
}
 
Example #25
Source File: BuildifierFormattingTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private void formattingAction(PsiFile psiFile) {
  ApplicationManager.getApplication()
      .runWriteAction(
          new Runnable() {
            @Override
            public void run() {
              Collection<TextRange> textRanges = Collections.singleton(psiFile.getTextRange());
              CodeStyleManager.getInstance(getProject()).reformatText(psiFile, textRanges);
            }
          });
}
 
Example #26
Source File: AutoIndentLinesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void adjustLineIndent(PsiFile file,
                              Document document,
                              int startOffset, int endOffset, int line, Project project) {
  CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
  if (startOffset == endOffset) {
    int lineStart = document.getLineStartOffset(line);
    if (codeStyleManager.isLineToBeIndented(file, lineStart)) {
      codeStyleManager.adjustLineIndent(file, lineStart);
    }
  } else {
    codeStyleManager.adjustLineIndent(file, new TextRange(startOffset, endOffset));
  }
}
 
Example #27
Source File: FormatterTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void performFormatting(final PsiFile file) {
  try {
    if (myTextRange == null) {
      CodeStyleManager.getInstance(getProject()).reformat(file);
    }
    else {
      CodeStyleManager.getInstance(getProject()).reformatRange(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
    }
  }
  catch (IncorrectOperationException e) {
    fail();
  }
}
 
Example #28
Source File: CodeStyleFacadeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
@Deprecated
public String getLineIndent(@Nonnull final Document document, int offset) {
  if (myProject == null) return null;
  PsiDocumentManager.getInstance(myProject).commitDocument(document);
  return CodeStyleManager.getInstance(myProject).getLineIndent(document, offset);
}
 
Example #29
Source File: BuckFormatterTest.java    From Buck-IntelliJ-Plugin with Apache License 2.0 5 votes vote down vote up
private String doTest(@Nullable Character c, String testName) {
  if (c == null) {
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      @Override
      public void run() {
        CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile());
      }
    });
  }
  else {
    myFixture.type(c);
  }
  return String.format("%s-after.BUCK", testName);
}
 
Example #30
Source File: WriterService.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
public void write(Project project, PsiElement psiElement, PsiDocComment comment) {
    try {
        WriteCommandAction.writeCommandAction(project).run(
            (ThrowableRunnable<Throwable>)() -> {
                if (psiElement.getContainingFile() == null) {
                    return;
                }

                // 写入文档注释
                if (psiElement instanceof PsiJavaDocumentedElement) {
                    PsiDocComment psiDocComment = ((PsiJavaDocumentedElement)psiElement).getDocComment();
                    if (psiDocComment == null) {
                        psiElement.getNode().addChild(comment.getNode(), psiElement.getFirstChild().getNode());
                    } else {
                        psiDocComment.replace(comment);
                    }
                }

                // 格式化文档注释
                CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(psiElement.getProject());
                PsiElement javadocElement = psiElement.getFirstChild();
                int startOffset = javadocElement.getTextOffset();
                int endOffset = javadocElement.getTextOffset() + javadocElement.getText().length();
                codeStyleManager.reformatText(psiElement.getContainingFile(), startOffset, endOffset + 1);
            });
    } catch (Throwable throwable) {
        LOGGER.error("写入错误", throwable);
    }
}