Java Code Examples for com.intellij.openapi.editor.Document#isWritable()

The following examples show how to use com.intellij.openapi.editor.Document#isWritable() . 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: ReadonlyStatusHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean ensureDocumentWritable(@Nonnull Project project, @Nonnull Document document) {
  final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
  boolean okWritable;
  if (psiFile == null) {
    okWritable = document.isWritable();
  }
  else {
    final VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile != null) {
      okWritable = ensureFilesWritable(project, virtualFile);
    }
    else {
      okWritable = psiFile.isWritable();
    }
  }
  return okWritable;
}
 
Example 2
Source File: UndoRedo.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Collection<Document> collectReadOnlyDocuments() {
  Collection<Document> readOnlyDocs = new ArrayList<>();
  for (UndoableAction action : myUndoableGroup.getActions()) {
    if (action instanceof MentionOnlyUndoableAction) continue;

    DocumentReference[] refs = action.getAffectedDocuments();
    if (refs == null) continue;

    for (DocumentReference ref : refs) {
      if (ref instanceof DocumentReferenceByDocument) {
        Document doc = ref.getDocument();
        if (doc != null && !doc.isWritable()) readOnlyDocs.add(doc);
      }
    }
  }
  return readOnlyDocs;
}
 
Example 3
Source File: PsiToDocumentSynchronizer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void doCommitTransaction(@Nonnull Document document, @Nonnull DocumentChangeTransaction documentChangeTransaction) {
  DocumentEx ex = (DocumentEx)document;
  ex.suppressGuardedExceptions();
  try {
    boolean isReadOnly = !document.isWritable();
    ex.setReadOnly(false);

    for (Map.Entry<TextRange, CharSequence> entry : documentChangeTransaction.myAffectedFragments.descendingMap().entrySet()) {
      ex.replaceString(entry.getKey().getStartOffset(), entry.getKey().getEndOffset(), entry.getValue());
    }

    ex.setReadOnly(isReadOnly);
  }
  finally {
    ex.unSuppressGuardedExceptions();
  }
}
 
Example 4
Source File: BuildFileFormatOnSaveHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentSaving(final Document document) {
  if (!BlazeUserSettings.getInstance().getFormatBuildFilesOnSave() || !document.isWritable()) {
    return;
  }
  for (Project project : ProjectManager.getInstance().getOpenProjects()) {
    PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (psiFile != null) {
      formatBuildFile(project, psiFile);
      return;
    }
  }
}
 
Example 5
Source File: ReplaceVarWithParamExpansionQuickfix.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    // Replace this position with the same value, we have to trigger a reparse somehow
    Document document = file.getViewProvider().getDocument();
    if (document != null && document.isWritable()) {
        PsiElement replacement = BashPsiElementFactory.createComposedVar(project, variableName);
        startElement.replace(replacement);
    }
}
 
Example 6
Source File: DoubleBracketsQuickfix.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        // builds 163.x set the read-only flag for unknown reasons, work around it in tests
        return true;
    }

    Document document = file.getViewProvider().getDocument();
    return document != null && document.isWritable();
}
 
Example 7
Source File: BuildifierUtil.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Reformats the given {@link Document} using {@code buildifier}, returning true if reformatting
 * changed the document.
 */
public static boolean doReformat(Project project, Document document) {
  if (!document.isWritable()) {
    LOGGER.warn("Could not reformat because Document is not writable");
    return false;
  }
  Optional<String> formattedText = reformatText(project, document.getText());
  formattedText.ifPresent(text -> WriteAction.run(() -> document.setText(text)));
  return formattedText.isPresent();
}
 
Example 8
Source File: FragmentContent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeListenersAttached(@Nonnull Document original, @Nonnull Document copy) {
  boolean writable = copy.isWritable();
  if (!writable) {
    copy.setReadOnly(false);
  }
  replaceString(copy, 0, copy.getTextLength(), subText(original, myRangeMarker.getStartOffset(), getLength()));
  copy.setReadOnly(!writable);
}
 
Example 9
Source File: FragmentContent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCopyChanged(@Nonnull DocumentEvent event, @Nonnull Document original) {
  final int originalOffset = event.getOffset() + myRangeMarker.getStartOffset();
  LOG.assertTrue(originalOffset >= 0);
  if (!original.isWritable()) return;
  final String newText = subText(event.getDocument(), event.getOffset(), event.getNewLength());
  final int originalEnd = originalOffset + event.getOldLength();
  replaceString(original, originalOffset, originalEnd, newText);
}
 
Example 10
Source File: MergeOperations.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean canMakeWritable(final Document document) {
  if (document.isWritable()) {
    return true;
  }
  final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file != null && file.isInLocalFileSystem()) {
    return true;
  }
  return false;
}
 
Example 11
Source File: Change.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean canHasActions(FragmentSide fromSide) {
  FragmentSide targetSide = fromSide.otherSide();
  Document targetDocument = getChangeList().getDocument(targetSide);
  if (!targetDocument.isWritable()) return false;
  Editor targetEditor = getHighlighterHolder(targetSide).getEditor();
  return !targetEditor.isViewer();
}
 
Example 12
Source File: BaseIndentEnterHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected Result shouldSkipWithResult(@Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull final DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return Result.Continue;
  }

  if (!file.getViewProvider().getLanguages().contains(myLanguage)) {
    return Result.Continue;
  }

  if (editor.isViewer()) {
    return Result.Continue;
  }

  final Document document = editor.getDocument();
  if (!document.isWritable()) {
    return Result.Continue;
  }

  PsiDocumentManager.getInstance(project).commitDocument(document);

  int caret = editor.getCaretModel().getOffset();
  if (caret == 0) {
    return Result.DefaultSkipIndent;
  }
  if (caret <= 0) {
    return Result.Continue;
  }
  return null;
}
 
Example 13
Source File: LocalEditorManipulator.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Replaces the content of the given file with the given content. This is done on the Document
 * level.
 *
 * <p><b>NOTE:</b> This method should only be used as part of the recovery process.
 *
 * @param file the file to recover
 * @param content the new content of the file
 * @param encoding the encoding of the content
 * @param source the user that send the recovery action
 * @see Document
 */
public void handleContentRecovery(IFile file, byte[] content, String encoding, User source) {
  VirtualFile virtualFile = VirtualFileConverter.convertToVirtualFile(file);
  if (virtualFile == null) {
    log.warn(
        "Could not recover file content of "
            + file
            + " as it could not be converted to a virtual file.");

    return;
  }

  Project project = ((IntellijReferencePoint) file.getReferencePoint()).getProject();

  Document document = DocumentAPI.getDocument(virtualFile);
  if (document == null) {
    log.warn(
        "Could not recover file content of "
            + file
            + " as no valid document representation was returned by the Intellij API.");

    return;
  }

  int documentLength = document.getTextLength();

  annotationManager.removeAnnotations(file);

  String text;
  try {
    text = new String(content, encoding);
  } catch (UnsupportedEncodingException e) {
    log.warn("Could not decode text using given encoding. Using default instead.", e);

    text = new String(content);

    String qualifiedResource =
        file.getReferencePoint().getName() + " - " + file.getReferencePointRelativePath();

    NotificationPanel.showWarning(
        String.format(
            Messages.LocalEditorManipulator_incompatible_encoding_message,
            qualifiedResource,
            encoding,
            Charset.defaultCharset()),
        Messages.LocalEditorManipulator_incompatible_encoding_title);
  }

  boolean wasReadOnly = !document.isWritable();
  boolean wasDocumentListenerEnabled = manager.isDocumentModificationHandlerEnabled();

  try {
    // TODO distinguish if read-only was set by the StopManager, abort otherwise
    if (wasReadOnly) {
      document.setReadOnly(false);
    }

    if (wasDocumentListenerEnabled) {
      manager.setLocalDocumentModificationHandlersEnabled(false);
    }

    DocumentAPI.replaceText(project, document, 0, documentLength, text);

  } finally {

    if (wasDocumentListenerEnabled) {
      manager.setLocalDocumentModificationHandlersEnabled(true);
    }

    if (wasReadOnly) {
      document.setReadOnly(true);
    }
  }

  Editor editor = null;
  if (ProjectAPI.isOpen(project, virtualFile)) {
    editor = ProjectAPI.openEditor(project, virtualFile, false);

    if (editor == null) {
      log.warn("Could not obtain text editor for open, recovered file " + virtualFile);

      return;
    }
  }

  annotationManager.addContributionAnnotation(source, file, 0, documentLength, editor);
}
 
Example 14
Source File: DiffUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isWritable(@Nonnull DiffContent content) {
  Document document = content.getDocument();
  return document != null && document.isWritable();
}