public void testDeletePoint() throws Exception {
    RangeMarker marker = createMarker("0123456789", 2, 2);

    marker.getDocument().deleteString(1, 3);

    assertFalse(marker.isValid());
  }
  private static void restoreBlockSelection(
      Editor editor, List<RangeMarker> caretsAfter, int caretLine) {
    int column = -1;
    int minLine = Integer.MAX_VALUE;
    int maxLine = -1;
    for (RangeMarker marker : caretsAfter) {
      if (marker.isValid()) {
        LogicalPosition lp = editor.offsetToLogicalPosition(marker.getStartOffset());
        if (column == -1) {
          column = lp.column;
        } else if (column != lp.column) {
          return;
        }
        minLine = Math.min(minLine, lp.line);
        maxLine = Math.max(maxLine, lp.line);

        if (lp.line == caretLine) {
          editor.getCaretModel().moveToLogicalPosition(lp);
        }
      }
    }
    editor
        .getSelectionModel()
        .setBlockSelection(
            new LogicalPosition(minLine, column), new LogicalPosition(maxLine, column));
  }
 @Override
 protected void moveOffsetAfter(boolean success) {
   if (getLocalVariable() != null && getLocalVariable().isValid()) {
     myEditor.getCaretModel().moveToOffset(getLocalVariable().getTextOffset());
     myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
   } else if (getExprMarker() != null) {
     final RangeMarker exprMarker = getExprMarker();
     if (exprMarker.isValid()) {
       myEditor.getCaretModel().moveToOffset(exprMarker.getStartOffset());
       myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
     }
   }
   super.moveOffsetAfter(success);
   if (myLocalMarker != null && !isRestart()) {
     myLocalMarker.dispose();
   }
   if (success) {
     performPostIntroduceTasks();
     final String refactoringId = getRefactoringId();
     if (refactoringId != null) {
       final RefactoringEventData afterData = new RefactoringEventData();
       afterData.addElement(getVariable());
       myProject
           .getMessageBus()
           .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
           .refactoringDone(refactoringId, afterData);
     }
   }
 }
  public void testCreation() throws Exception {
    RangeMarker marker = createMarker("0123456789", 2, 5);

    assertEquals(2, marker.getStartOffset());
    assertEquals(5, marker.getEndOffset());
    assertTrue(marker.isValid());
  }
  protected void restoreState(@NotNull final V psiField) {
    if (!ReadonlyStatusHandler.ensureDocumentWritable(
        myProject, InjectedLanguageUtil.getTopLevelEditor(myEditor).getDocument())) return;
    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              final PsiFile containingFile = psiField.getContainingFile();
              final RangeMarker exprMarker = getExprMarker();
              if (exprMarker != null) {
                myExpr = restoreExpression(containingFile, psiField, exprMarker, myExprText);
              }

              if (myLocalMarker != null) {
                final PsiElement refVariableElement =
                    containingFile.findElementAt(myLocalMarker.getStartOffset());
                if (refVariableElement != null) {
                  final PsiElement parent = refVariableElement.getParent();
                  if (parent instanceof PsiNamedElement) {
                    ((PsiNamedElement) parent).setName(myLocalName);
                  }
                }

                final V localVariable = getLocalVariable();
                if (localVariable != null && localVariable.isPhysical()) {
                  myLocalVariable = localVariable;
                  final PsiElement nameIdentifier = localVariable.getNameIdentifier();
                  if (nameIdentifier != null) {
                    myLocalMarker = createMarker(nameIdentifier);
                  }
                }
              }
              final List<RangeMarker> occurrenceMarkers = getOccurrenceMarkers();
              for (int i = 0, occurrenceMarkersSize = occurrenceMarkers.size();
                  i < occurrenceMarkersSize;
                  i++) {
                RangeMarker marker = occurrenceMarkers.get(i);
                if (getExprMarker() != null
                    && marker.getStartOffset() == getExprMarker().getStartOffset()
                    && myExpr != null) {
                  myOccurrences[i] = myExpr;
                  continue;
                }
                final E psiExpression =
                    restoreExpression(
                        containingFile,
                        psiField,
                        marker,
                        getLocalVariable() != null ? myLocalName : myExprText);
                if (psiExpression != null) {
                  myOccurrences[i] = psiExpression;
                }
              }

              if (myExpr != null && myExpr.isPhysical()) {
                myExprMarker = createMarker(myExpr);
              }
              myOccurrenceMarkers = null;
              deleteTemplateField(psiField);
            });
  }
  public void testDeleteRightPart2() throws Exception {
    RangeMarker marker = createMarker("0123456789", 2, 5);

    marker.getDocument().deleteString(4, 5);

    assertValidMarker(marker, 2, 4);
  }
  public void testDeleteRangeInside() throws Exception {
    RangeMarker marker = createMarker("0123456789", 1, 7);

    marker.getDocument().deleteString(2, 5);

    assertTrue(marker.isValid());
  }
  public void testDeleteFirstChar() throws Exception {
    RangeMarker marker = createMarker("0123456789", 0, 5);

    marker.getDocument().deleteString(0, 1);

    assertValidMarker(marker, 0, 4);
  }
  public void testReplaceRangeToSingleChar() throws Exception {
    RangeMarker marker = createMarker("0123456789", 1, 7);

    marker.getDocument().replaceString(2, 5, " ");

    assertTrue(marker.isValid());
  }
  public void testInsertIntoStart() throws Exception {
    RangeMarker marker = createMarker("0123456789", 2, 5);

    marker.getDocument().insertString(2, "xxx");

    assertValidMarker(marker, 5, 8);
  }
  public void testReplaceRightPartInvalid() throws Exception {
    RangeMarker marker = createMarker("0123456789", 2, 5);

    marker.getDocument().replaceString(4, 6, "xxx");

    assertValidMarker(marker, 2, 4);
  }
  public void testReplaceRightIncludingFirstChar() throws Exception {
    String s = "12345\n \n12345";
    RangeMarker marker = createMarker(s, 6, 8);

    marker.getDocument().replaceString(0, s.length(), s.replaceAll(" ", ""));

    assertValidMarker(marker, 6, 7);
  }
  public void testInsertIntoEnd() throws Exception {
    RangeMarker marker = createMarker("0123456789", 2, 5);

    marker.getDocument().insertString(5, "xxx");

    assertEquals(2, marker.getStartOffset());
    assertEquals(5, marker.getEndOffset());
    assertTrue(marker.isValid());
  }
  public void testDeleteBeforeStart() throws Exception {
    RangeMarker marker = createMarker("01[234]56789");

    marker.getDocument().deleteString(0, 1);

    assertEquals(1, marker.getStartOffset());
    assertEquals(4, marker.getEndOffset());
    assertTrue(marker.isValid());
  }
  public void testPersistentMarkerDoesntImpactNormalMarkers() {
    Document doc = new DocumentImpl("text");
    RangeMarker normal = doc.createRangeMarker(1, 3);
    RangeMarker persistent = doc.createRangeMarker(1, 3, true);

    doc.replaceString(0, 4, "before\ntext\nafter");

    assertTrue(persistent.isValid());
    assertFalse(normal.isValid());
  }
  public void testPersistent() throws Exception {
    String text = "xxx\nzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
    Document document = EditorFactory.getInstance().createDocument(text);
    int startOffset = text.indexOf('z');
    int endOffset = text.lastIndexOf('z');
    RangeMarker marker = document.createRangeMarker(startOffset, endOffset, true);

    document.replaceString(startOffset + 1, endOffset - 1, "ccc");

    assertTrue(marker.isValid());
  }
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
 static TextRange processDocument(
     Document document, RangeMarker marker, Commenter commenter, boolean escape) {
   if (commenter instanceof EscapingCommenter) {
     if (escape) {
       ((EscapingCommenter) commenter).escape(document, marker);
     } else {
       ((EscapingCommenter) commenter).unescape(document, marker);
     }
   }
   return TextRange.create(marker.getStartOffset(), marker.getEndOffset());
 }
  public void testLL() {
    RangeMarker marker1 = createMarker("012345678901234567", 5, 6);
    DocumentEx document = (DocumentEx) marker1.getDocument();
    document.createRangeMarker(4, 5);
    document.createRangeMarker(6, 7);
    document.createRangeMarker(0, 4);
    document.deleteString(1, 2);

    document.createRangeMarker(0, 7);
    document.createRangeMarker(0, 7);
  }
 public boolean changesRange(TextRange range) {
   if (myAltFullRange != null) {
     return range.intersects(myAltFullRange.getStartOffset(), myAltFullRange.getEndOffset());
   } else if (!myMarkers.isEmpty()) {
     TextRange hostRange =
         TextRange.create(
             myMarkers.get(0).first.getStartOffset(),
             myMarkers.get(myMarkers.size() - 1).first.getEndOffset());
     return range.intersects(hostRange);
   }
   return false;
 }
 public void testBranched() {
   RangeMarker marker1 = createMarker("01234567890123456", 0, 1);
   DocumentEx document = (DocumentEx) marker1.getDocument();
   RangeMarker marker2 = document.createRangeMarker(2, 3);
   RangeMarker marker3 = document.createRangeMarker(4, 5);
   RangeMarker marker4 = document.createRangeMarker(6, 7);
   RangeMarker marker5 = document.createRangeMarker(8, 9);
   RangeMarker marker6 = document.createRangeMarker(10, 11);
   RangeMarker marker7 = document.createRangeMarker(12, 13);
   RangeMarker marker8 = document.createRangeMarker(14, 15);
   document.deleteString(1, 2);
 }
  public void testRangeHighlighterDisposeVsRemoveAllConflict() throws Exception {
    Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");

    MarkupModel markupModel = DocumentMarkupModel.forDocument(document, ourProject, true);
    RangeMarker m =
        markupModel.addRangeHighlighter(1, 6, 0, null, HighlighterTargetArea.EXACT_RANGE);
    assertTrue(m.isValid());
    markupModel.removeAllHighlighters();
    assertFalse(m.isValid());
    assertEmpty(markupModel.getAllHighlighters());
    m.dispose();
    assertFalse(m.isValid());
  }
  public void testNoNegative() throws Exception {
    RangeMarker marker =
        createMarker(
            "package safd;\n\n[import javax.swing.JPanel;]\nimport java.util.ArrayList;\n\nclass T{}");

    marker
        .getDocument()
        .replaceString(
            15,
            15 + "import javax.swing.JPanel;\nimport java.util.ArrayList;".length(),
            "import java.util.ArrayList;");

    assertEquals(15, marker.getStartOffset());
  }
  public void initMarkers(Place shreds) {
    SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject);
    int curOffset = -1;
    for (PsiLanguageInjectionHost.Shred shred : shreds) {
      final RangeMarker rangeMarker =
          myNewDocument.createRangeMarker(
              shred.getRange().getStartOffset() + shred.getPrefix().length(),
              shred.getRange().getEndOffset() - shred.getSuffix().length());
      final TextRange rangeInsideHost = shred.getRangeInsideHost();
      PsiLanguageInjectionHost host = shred.getHost();
      RangeMarker origMarker =
          myOrigDocument.createRangeMarker(
              rangeInsideHost.shiftRight(host.getTextRange().getStartOffset()));
      SmartPsiElementPointer<PsiLanguageInjectionHost> elementPointer =
          smartPointerManager.createSmartPsiElementPointer(host);
      Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> markers =
          Trinity.<RangeMarker, RangeMarker, SmartPsiElementPointer>create(
              origMarker, rangeMarker, elementPointer);
      myMarkers.add(markers);

      origMarker.setGreedyToRight(true);
      rangeMarker.setGreedyToRight(true);
      if (origMarker.getStartOffset() > curOffset) {
        origMarker.setGreedyToLeft(true);
        rangeMarker.setGreedyToLeft(true);
      }
      curOffset = origMarker.getEndOffset();
    }
    initGuardedBlocks(shreds);
  }
 protected int getCaretOffset() {
   RangeMarker r;
   if (myLocalMarker != null) {
     final PsiReference reference = myExpr != null ? myExpr.getReference() : null;
     if (reference != null && reference.resolve() == myLocalVariable) {
       r = myExprMarker;
     } else {
       r = myLocalMarker;
     }
   } else {
     r = myExprMarker;
   }
   return r != null ? r.getStartOffset() : 0;
 }
  public boolean startsOnTheSameElement(E expr, V localVariable) {
    if (myExprMarker != null
        && myExprMarker.isValid()
        && expr != null
        && myExprMarker.getStartOffset() == expr.getTextOffset()) {
      return true;
    }

    if (myLocalMarker != null
        && myLocalMarker.isValid()
        && localVariable != null
        && myLocalMarker.getStartOffset() == localVariable.getTextOffset()) {
      return true;
    }
    return isRestart();
  }
 @Override
 public void documentChanged(DocumentEvent e) {
   UndoManager undoManager = UndoManager.getInstance(myProject);
   boolean undoOrRedo = undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
   if (undoOrRedo) {
     // allow undo/redo up until 'creation stamp' back in time
     // and check it after action is completed
     if (e.getDocument() == myOrigDocument) {
       //noinspection SSBasedInspection
       SwingUtilities.invokeLater(
           () -> {
             if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) {
               closeEditor();
             }
           });
     }
   } else if (e.getDocument() == myNewDocument) {
     commitToOriginal(e);
     if (!isValid()) {
       ApplicationManager.getApplication()
           .invokeLater(() -> closeEditor(), myProject.getDisposed());
     }
   } else if (e.getDocument() == myOrigDocument) {
     if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid()) return;
     ApplicationManager.getApplication().invokeLater(() -> closeEditor(), myProject.getDisposed());
   }
 }
  @Override
  protected void addHighlights(
      @NotNull Map<TextRange, TextAttributes> ranges,
      @NotNull Editor editor,
      @NotNull Collection<RangeHighlighter> highlighters,
      @NotNull HighlightManager highlightManager) {
    final TextAttributes attributes =
        EditorColorsManager.getInstance()
            .getGlobalScheme()
            .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final V variable = getVariable();
    if (variable != null) {
      final String name = variable.getName();
      LOG.assertTrue(name != null, variable);
      final int variableNameLength = name.length();
      if (isReplaceAllOccurrences()) {
        for (RangeMarker marker : getOccurrenceMarkers()) {
          final int startOffset = marker.getStartOffset();
          highlightManager.addOccurrenceHighlight(
              editor,
              startOffset,
              startOffset + variableNameLength,
              attributes,
              0,
              highlighters,
              null);
        }
      } else if (getExpr() != null) {
        final int startOffset = getExprMarker().getStartOffset();
        highlightManager.addOccurrenceHighlight(
            editor,
            startOffset,
            startOffset + variableNameLength,
            attributes,
            0,
            highlighters,
            null);
      }
    }

    for (RangeHighlighter highlighter : highlighters) {
      highlighter.setGreedyToLeft(true);
      highlighter.setGreedyToRight(true);
    }
  }
  private static void indentLinesIn(
      final Editor editor,
      final PsiFile file,
      final Document document,
      final Project project,
      RangeMarker range) {
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    int line1 = editor.offsetToLogicalPosition(range.getStartOffset()).line;
    int line2 = editor.offsetToLogicalPosition(range.getEndOffset()).line;

    while (!lineContainsNonSpaces(document, line1) && line1 < line2) line1++;
    while (!lineContainsNonSpaces(document, line2) && line1 < line2) line2--;

    final FileViewProvider provider = file.getViewProvider();
    PsiFile rootToAdjustIndentIn = provider.getPsi(provider.getBaseLanguage());
    codeStyleManager.adjustLineIndent(
        rootToAdjustIndentIn,
        new TextRange(document.getLineStartOffset(line1), document.getLineStartOffset(line2)));
  }
  public void testNested3() {
    RangeMarker marker1 = createMarker("01[23]4567890123");
    DocumentEx document = (DocumentEx) marker1.getDocument();
    RangeMarker marker2 = document.createRangeMarker(9, 11);
    RangeMarker marker3 = document.createRangeMarker(1, 12);
    marker3.dispose();

    document.deleteString(marker1.getEndOffset(), marker2.getStartOffset());
  }