Java Code Examples for com.intellij.openapi.command.WriteCommandAction#runWriteCommandAction()
The following examples show how to use
com.intellij.openapi.command.WriteCommandAction#runWriteCommandAction() .
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: GoogleJavaFormatCodeStyleManager.java From google-java-format with Apache License 2.0 | 6 votes |
private void performReplacements( final Document document, final Map<TextRange, String> replacements) { if (replacements.isEmpty()) { return; } TreeMap<TextRange, String> sorted = new TreeMap<>(comparing(TextRange::getStartOffset)); sorted.putAll(replacements); WriteCommandAction.runWriteCommandAction( getProject(), () -> { for (Entry<TextRange, String> entry : sorted.descendingMap().entrySet()) { document.replaceString( entry.getKey().getStartOffset(), entry.getKey().getEndOffset(), entry.getValue()); } PsiDocumentManager.getInstance(getProject()).commitDocument(document); }); }
Example 2
Source File: CommandCamelCaseInspection.java From arma-intellij-plugin with MIT License | 6 votes |
@Override public void applyFix(@NotNull Project project, PsiFile file, @Nullable Editor editor) { Runnable runnable = new Runnable() { @Override public void run() { SQFPsiCommand commandElement = commandPointer.getElement(); if (commandElement == null) { return; } for (String command : SQFStatic.COMMANDS_SET) { if (command.equalsIgnoreCase(commandElement.getText())) { SQFPsiCommand c = PsiUtil.createElement(project, command, SQFFileType.INSTANCE, SQFPsiCommand.class); if (c == null) { return; } commandElement.replace(c); return; } } throw new IllegalStateException("command '" + commandElement.getText() + "' should have been matched"); } }; WriteCommandAction.runWriteCommandAction(project, runnable); }
Example 3
Source File: FlutterProjectCreator.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static boolean finalValidityCheckPassed(@NotNull String projectLocation) { // See AS NewProjectModel.ProjectTemplateRenderer.doDryRun() for why this is necessary. boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(null, (Computable<Boolean>)() -> { try { if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) { return true; } } catch (Exception e) { LOG.warn(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e); } return false; }); if (!couldEnsureLocationExists) { String msg = "Could not ensure the target project location exists and is accessible:\n\n%1$s\n\nPlease try to specify another path."; Messages.showErrorDialog(String.format(msg, projectLocation), "Error Creating Project"); return false; } return true; }
Example 4
Source File: HaxeSurroundTest.java From intellij-haxe with Apache License 2.0 | 6 votes |
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 5
Source File: FileDocumentManagerImplTest.java From consulo with Apache License 2.0 | 6 votes |
public void testUnsavedDocument_GcAfterSave() throws Exception { final VirtualFile file = createFile(); Document document = myDocumentManager.getDocument(file); assertNotNull(file.toString(), document); WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { @Override public void run() { myDocumentManager.getDocument(file).insertString(0, "xxx"); } }); int idCode = System.identityHashCode(document); //noinspection UnusedAssignment document = null; myDocumentManager.saveAllDocuments(); System.gc(); System.gc(); document = myDocumentManager.getDocument(file); assertTrue(idCode != System.identityHashCode(document)); }
Example 6
Source File: CreateFromTemplateActionBase.java From consulo with Apache License 2.0 | 6 votes |
public static void startLiveTemplate(@Nonnull PsiFile file, @Nonnull Map<String, String> defaultValues) { Editor editor = EditorHelper.openInEditor(file); if (editor == null) return; TemplateImpl template = new TemplateImpl("", file.getText(), ""); template.setInline(true); int count = template.getSegmentsCount(); if (count == 0) return; Set<String> variables = new HashSet<>(); for (int i = 0; i < count; i++) { variables.add(template.getSegmentName(i)); } variables.removeAll(TemplateImpl.INTERNAL_VARS_SET); for (String variable : variables) { String defaultValue = defaultValues.getOrDefault(variable, variable); template.addVariable(variable, null, '"' + defaultValue + '"', true); } Project project = file.getProject(); WriteCommandAction.runWriteCommandAction(project, () -> editor.getDocument().setText(template.getTemplateText())); editor.getCaretModel().moveToOffset(0); // ensures caret at the start of the template TemplateManager.getInstance(project).startTemplate(editor, template); }
Example 7
Source File: FoldingTest.java From consulo with Apache License 2.0 | 6 votes |
public void testTopLevelRegionRemainsTopLevelAfterMergingIdenticalRegions() { addCollapsedFoldRegion(10, 15, "..."); addCollapsedFoldRegion(10, 14, "..."); WriteCommandAction.runWriteCommandAction(getProject(), () -> myEditor.getDocument().deleteString(14, 15)); FoldRegion region = myModel.getCollapsedRegionAtOffset(10); assertNotNull(region); assertTrue(region.isValid()); assertEquals(10, region.getStartOffset()); assertEquals(14, region.getEndOffset()); addFoldRegion(0, 1, "..."); FoldRegion region2 = myModel.getCollapsedRegionAtOffset(10); assertNotNull(region2); assertTrue(region2.isValid()); assertEquals(10, region2.getStartOffset()); assertEquals(14, region2.getEndOffset()); assertSame(region, region2); }
Example 8
Source File: HaxeFormatterTest.java From intellij-haxe with Apache License 2.0 | 5 votes |
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 9
Source File: InsertToDocumentHandler.java From markdown-image-kit with MIT License | 5 votes |
@Override public void invoke(EventData data, Iterator<MarkdownImage> imageIterator, MarkdownImage markdownImage) { WriteCommandAction.runWriteCommandAction(data.getProject(), () -> EditorModificationUtil .insertStringAtCaret( data.getEditor(), markdownImage.getFinalMark() + ImageContents.LINE_BREAK)); }
Example 10
Source File: ParentDialogFragment.java From CleanArchitecturePlugin with Apache License 2.0 | 5 votes |
public static void create() { if (ParentFragment.getFragmentDirectory().findFile(PARENT_DIALOG_FRAGMENT + ".java") == null) { // Not contains ParentDialogFragment.java // Create Parent Fragment class HashMap<String, String> varTemplate = new HashMap<>(); varTemplate.put("PACKAGE_PRESENTER", getPackageNameProject(Presenter.getPresenterDirectory())); varTemplate.put("PRESENTER", PRESENTER); Runnable runnable = () -> JavaDirectoryService.getInstance().createClass(ParentFragment.getFragmentDirectory(), PARENT_DIALOG_FRAGMENT, BASE_DIALOG_FRAGMENT_TEMPLATE, false, varTemplate); WriteCommandAction.runWriteCommandAction(getProject(), runnable); } }
Example 11
Source File: KotlinBuilder.java From OkHttpParamsGet with Apache License 2.0 | 5 votes |
@Override public void build(PsiFile psiFile, Project project1, Editor editor) { if (psiFile == null) return; WriteCommandAction.runWriteCommandAction(project1, () -> { if (editor == null) return; Project project = editor.getProject(); if (project == null) return; PsiElement mouse = psiFile.findElementAt(editor.getCaretModel().getOffset()); if (mouse == null) return; KtClass ktClass = Utils.getKtClassForElement(mouse); if (ktClass == null) return; if (ktClass.getNameIdentifier() == null) return; String className = ktClass.getNameIdentifier().getText(); KtClassBody body = ktClass.getBody(); if (body == null) return; KtPsiFactory elementFactory = KtPsiFactoryKt.KtPsiFactory(ktClass.getProject()); KtLightClass lightClass = LightClassUtilsKt.toLightClass(ktClass); if (lightClass == null) return; build(editor, mouse, elementFactory, project, ktClass, body, lightClass, psiFile, className); String[] imports = getImports(); if (imports != null) { for (String fqName : imports) { final Collection<DeclarationDescriptor> descriptors = ResolutionUtils.resolveImportReference(ktClass.getContainingKtFile(), new FqName(fqName)); Iterator<DeclarationDescriptor> iterator = descriptors.iterator(); if (iterator.hasNext()) { DeclarationDescriptor descriptor = iterator.next(); ImportInsertHelper.getInstance(project).importDescriptor(ktClass.getContainingKtFile(), descriptor, false); } } } CodeStyleManager styleManager = CodeStyleManager.getInstance(ktClass.getProject()); styleManager.reformatText(ktClass.getContainingFile(), ContainerUtil.newArrayList(ktClass.getTextRange())); }); }
Example 12
Source File: FileDocumentManagerImplTest.java From consulo with Apache License 2.0 | 5 votes |
public void testRememberSeparators() throws Exception { final VirtualFile file = new MockVirtualFile("test.txt", "test\rtest"); final Document document = myDocumentManager.getDocument(file); assertNotNull(file.toString(), document); WriteCommandAction.runWriteCommandAction(myProject, new Runnable() { @Override public void run() { document.insertString(0, "xxx "); } }); myDocumentManager.saveAllDocuments(); assertTrue(Arrays.equals("xxx test\rtest".getBytes("UTF-8"), file.contentsToByteArray())); }
Example 13
Source File: CompletionElementWithTextReplace.java From arma-intellij-plugin with MIT License | 5 votes |
@Override public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) { Runnable runnable = new Runnable() { @Override public void run() { context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), replaceStr); context.getEditor().getCaretModel().getPrimaryCaret().moveToOffset(context.getStartOffset() + newCursorPos); } }; WriteCommandAction.runWriteCommandAction(context.getProject(), runnable); }
Example 14
Source File: EntityCache.java From CleanArchitecturePlugin with Apache License 2.0 | 5 votes |
public static void create() { // Create cache package cacheDirectory = createDirectory(getDataPackage(), CACHE.toLowerCase()); // Create entity cache class String className = getEntityConfig().getEntityName() + CACHE; Runnable runnable = () -> JavaDirectoryService.getInstance().createClass(cacheDirectory, className, CACHE_TEMPLATE); WriteCommandAction.runWriteCommandAction(getProject(), runnable); }
Example 15
Source File: PasteImageFromClipboard.java From pasteimages with BSD 2-Clause "Simplified" License | 4 votes |
private void insertImageElement(final @NotNull Editor editor, File imageFile) { String relImagePath = imageFile.toString().replace('\\', '/'); Runnable r = () -> EditorModificationUtil.insertStringAtCaret(editor, "![](" + relImagePath + ")"); WriteCommandAction.runWriteCommandAction(editor.getProject(), r); }
Example 16
Source File: EntityRepository.java From CleanArchitecturePlugin with Apache License 2.0 | 4 votes |
public static void create() { // Create Repository package PsiDirectory repositoryDirectory = createDirectory(getDataPackage(), REPOSITORY.toLowerCase()); // Create DataSource package PsiDirectory dataSourceDirectory = createDirectory(repositoryDirectory, DATASOURCE.toLowerCase()); // Create Cloud Entity Data Source class String cloudEntityDataSourceName = CLOUD + getEntityConfig().getEntityName() + DATASOURCE; HashMap<String, String> cloudTemplate = new HashMap<>(); cloudTemplate.put("PACKAGE_SERVICE", getPackageNameProject(EntityAPI.getApiDirectory())); cloudTemplate.put("SERVICE", getEntityConfig().getEntityName() + SERVICE); // Create Disk Entity Data Source class String diskEntityDataSourceName = DISK + getEntityConfig().getEntityName() + DATASOURCE; HashMap<String, String> diskTemplate = new HashMap<>(); diskTemplate.put("PACKAGE_BASE_SERVICE", getPackageNameProject(ParentAPI.getApiDirectory())); diskTemplate.put("BASE_SERVICE", BASE_SERVICE); diskTemplate.put("PACKAGE_CACHE", getPackageNameProject(EntityCache.getCacheDirectory())); diskTemplate.put("CACHE", getEntityConfig().getEntityName() + CACHE); // Create Data Store Factory class String dataStoreFactoryName = getEntityConfig().getEntityName() + DATASTOREFACTORY; HashMap<String, String> dataStoreFactoryTemplate = new HashMap<>(); dataStoreFactoryTemplate.put("PACKAGE_ENTITY_SERVICE", getPackageNameProject(EntityAPI.getApiDirectory())); dataStoreFactoryTemplate.put("ENTITY_SERVICE", getEntityConfig().getEntityName() + SERVICE); dataStoreFactoryTemplate.put("PACKAGE_ENTITY_CACHE", getPackageNameProject(EntityCache.getCacheDirectory())); dataStoreFactoryTemplate.put("ENTITY_CACHE", getEntityConfig().getEntityName() + CACHE); dataStoreFactoryTemplate.put("PACKAGE_CLOUD_ENTITY_DATA_SOURCE", getPackageNameProject(dataSourceDirectory)); dataStoreFactoryTemplate.put("CLOUD_ENTITY_DATA_SOURCE", cloudEntityDataSourceName); dataStoreFactoryTemplate.put("PACKAGE_DISK_ENTITY_DATA_SOURCE", getPackageNameProject(dataSourceDirectory)); dataStoreFactoryTemplate.put("DISK_ENTITY_DATA_SOURCE", diskEntityDataSourceName); // Create Repository class String repositoryName = getEntityConfig().getEntityName() + REPOSITORY; HashMap<String, String> repositoryTemplate = new HashMap<>(); repositoryTemplate.put("DATA_STORE_FACTORY", getEntityConfig().getEntityName() + DATASTOREFACTORY); Runnable repositoryRunnable = () -> { JavaDirectoryService.getInstance().createClass(dataSourceDirectory, cloudEntityDataSourceName, CLOUD_ENTITY_DATA_SOURCE_TEMPLATE, false, cloudTemplate); JavaDirectoryService.getInstance().createClass(dataSourceDirectory, diskEntityDataSourceName, DISK_ENTITY_DATA_SOURCE_TEMPLATE, false, diskTemplate); JavaDirectoryService.getInstance().createClass(repositoryDirectory, dataStoreFactoryName, DATA_STORE_FACTORY_TEMPLATE, false, dataStoreFactoryTemplate); JavaDirectoryService.getInstance().createClass(repositoryDirectory, repositoryName, REPOSITORY_TEMPLATE, false, repositoryTemplate); }; WriteCommandAction.runWriteCommandAction(getProject(), repositoryRunnable); }
Example 17
Source File: EntityActivity.java From CleanArchitecturePlugin with Apache License 2.0 | 4 votes |
/** * Create package activity and EntityActivity.class */ public static void create() { // Create activity directory PsiDirectory activityDirectory = createDirectory(getViewPackage(), ACTIVITY.toLowerCase()); // Create activity class String className = getEntityConfig().getEntityName() + ACTIVITY; HashMap<String, String> varTemplate = new HashMap<>(); varTemplate.put("PACKAGE_PROJECT", getPackageNameProject(getProjectDirectory())); varTemplate.put("LAYOUT_NAME", getEntityConfig().getEntityName().toLowerCase()); if (ParentActivity.getActivityDirectory() != null) { // With Parent Activity varTemplate.put("PACKAGE_BASE_ACTIVITY", getPackageNameProject(ParentActivity.getActivityDirectory())); varTemplate.put("BASE_ACTIVITY", PARENT_ACTIVITY); } if (Presenter.getPresenterDirectory() != null) { // With Parent Presenter varTemplate.put("PACKAGE_BASE_PRESENTER", getPackageNameProject(Presenter.getPresenterDirectory())); varTemplate.put("BASE_PRESENTER", PRESENTER); } if (EntityPresenter.getPresenterDirectory() != null && getEntityConfig().isContainsPresenter()) { // With presenter varTemplate.put("PACKAGE_PRESENTER", getPackageNameProject(EntityPresenter.getPresenterDirectory())); varTemplate.put("PRESENTER", getEntityConfig().getEntityName() + PRESENTER); } Runnable runnable = () -> { JavaDirectoryService.getInstance().createClass(activityDirectory, className, ACTIVITY_TEMPLATE, false, varTemplate); try { createLayout(getPackageNameProject(activityDirectory), className, ACTIVITY); } catch (Exception e) { e.printStackTrace(); } }; WriteCommandAction.runWriteCommandAction(getProject(), runnable); }
Example 18
Source File: DocTagNameAnnotationReferenceContributorTest.java From idea-php-annotation-plugin with MIT License | 4 votes |
@NotNull private String optimizeImports(@NotNull String content) { PsiFile psiFile = myFixture.configureByText(PhpFileType.INSTANCE, content); WriteCommandAction.runWriteCommandAction(getProject(), () -> new PhpImportOptimizer().processFile(psiFile).run()); return psiFile.getText(); }
Example 19
Source File: FoldingTest.java From consulo with Apache License 2.0 | 3 votes |
public void testIdenticalRegionsAreRemoved() { addFoldRegion(0, 5, "..."); addFoldRegion(0, 4, "..."); assertNumberOfValidFoldRegions(2); WriteCommandAction.runWriteCommandAction(getProject(), () -> myEditor.getDocument().deleteString(4, 5)); assertNumberOfValidFoldRegions(1); }
Example 20
Source File: PsiDocumentUtils.java From markdown-image-kit with MIT License | 2 votes |
/** * 将字符串插入到光标位置 * * @param marks the marks * @param editor the editor */ public static void insertDocument(String marks, Editor editor){ Runnable r = () -> EditorModificationUtil.insertStringAtCaret(editor, marks); WriteCommandAction.runWriteCommandAction(editor.getProject(), r); }