public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception {
    String text =
        "import java.awt.List;\n"
            + "[import java.util.ArrayList;\n]"
            + "import java.util.HashMap;\n"
            + "import java.util.Map;";
    RangeMarker marker = createMarker(text);
    synchronizer.startTransaction(getProject(), document, psiFile);

    String newText = StringUtil.replaceSubstring(document.getText(), TextRange.create(marker), "");
    synchronizer.replaceString(document, 0, document.getTextLength(), newText);

    final List<DocumentEvent> events = new ArrayList<DocumentEvent>();
    document.addDocumentListener(
        new DocumentAdapter() {
          @Override
          public void documentChanged(DocumentEvent e) {
            events.add(e);
          }
        });
    synchronizer.commitTransaction(document);

    assertEquals(newText, document.getText());
    DocumentEvent event = assertOneElement(events);
    assertEquals(
        "DocumentEventImpl[myOffset=22, myOldLength=28, myNewLength=0, myOldString='import java.util.ArrayList;\n', myNewString=''].",
        event.toString());
  }
示例#2
0
 private void analyseDocument(Document document, int lineNum, PythonIndentation indentationLogic)
     throws BadLocationException {
   Element map = document.getDefaultRootElement();
   int endPos = map.getElement(lineNum).getEndOffset();
   indentationLogic.reset();
   indentationLogic.addText(document.getText(0, endPos));
 }
示例#3
0
  /**
   * Attempts to find the next subsequence of the input sequence that matches the pattern.
   *
   * <p>This method starts at the beginning of the input sequence or, if a previous invocation of
   * the method was successful and the matcher has not since been reset, at the first character not
   * matched by the previous match.
   *
   * @return the index of the first occurrence of the search string, starting at the specified
   *     offset, or -1 if no occurrence was found.
   */
  public int findNext() {
    // Don't match empty strings and don't match if we are at the end of the document.
    if (findString.length() == 0 || document.getLength() - findString.length() < startIndex) {
      return -1;
    }

    try {
      int nextMatch = 0; // index of next matching character

      // Iterate through all segments of the document starting from offset
      Segment text = new Segment();
      text.setPartialReturn(true);
      int offset = startIndex;
      int nleft = document.getLength() - startIndex;
      while (nleft > 0) {
        document.getText(offset, nleft, text);

        // Iterate through the characters in the current segment
        char next = text.first();
        for (text.first(); next != Segment.DONE; next = text.next()) {

          // Check if the current character matches with the next
          // search character.
          char current = text.current();
          if (current == matchUpperCase[nextMatch] || current == matchLowerCase[nextMatch]) {
            nextMatch++;

            // Did we match all search characters?
            if (nextMatch == matchLowerCase.length) {
              int foundIndex =
                  text.getIndex() - text.getBeginIndex() + offset - matchLowerCase.length + 1;
              if (matchType == MatchType.CONTAINS) {
                return foundIndex;
                // break; <- never reached
              } else if (matchType == MatchType.STARTS_WITH) {
                if (!isWordChar(foundIndex - 1)) {
                  return foundIndex;
                }
              } else if (matchType == MatchType.FULL_WORD) {
                if (!isWordChar(foundIndex - 1)
                    && !isWordChar(foundIndex + matchLowerCase.length)) {
                  return foundIndex;
                }
              }
              nextMatch = 0;
            }
          } else {
            nextMatch = 0;
          }
        }

        // Move forward to the next segment
        nleft -= text.count;
        offset += text.count;
      }
      return -1;
    } catch (BadLocationException e) {
      throw new IndexOutOfBoundsException();
    }
  }
  public void testPsi2DocSurround() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.replaceString(document, 3, 5, "3a4");
    buffer.replace(3, 5, "3a4");

    synchronizer.insertString(document, 3, "b");
    buffer.insert(3, "b");

    synchronizer.insertString(document, 7, "d");
    buffer.insert(7, "d");

    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();
    assertEquals(3, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 7);
  }
  public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);
    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();

    for (int i = 0; i < 10; i++) {
      synchronizer.insertString(document, i, "" + i);
      buffer.insert(i, "" + i);
    }

    assertEquals(1, affectedFragments.size());
    synchronizer.replaceString(document, 0, 20, "0123456789");
    buffer.replace(0, 20, "0123456789");

    assertEquals(1, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 5);
  }
  /**
   * Updates the AttributedCharacterIterator by invoking <code>formatToCharacterIterator</code> on
   * the <code>Format</code>. If this is successful, <code>updateMask(AttributedCharacterIterator)
   * </code> is then invoked to update the internal bitmask.
   */
  void updateMask() {
    if (getFormat() != null) {
      Document doc = getFormattedTextField().getDocument();

      validMask = false;
      if (doc != null) {
        try {
          string = doc.getText(0, doc.getLength());
        } catch (BadLocationException ble) {
          string = null;
        }
        if (string != null) {
          try {
            Object value = stringToValue(string);
            AttributedCharacterIterator iterator = getFormat().formatToCharacterIterator(value);

            updateMask(iterator);
          } catch (ParseException pe) {
          } catch (IllegalArgumentException iae) {
          } catch (NullPointerException npe) {
          }
        }
      }
    }
  }
示例#7
0
 /**
  * Determines the preferred span for this view along an axis.
  *
  * @param axis may be either View.X_AXIS or View.Y_AXIS
  * @return the span the view would like to be rendered into &gt;= 0. Typically the view is told to
  *     render into the span that is returned, although there is no guarantee. The parent may
  *     choose to resize or break the view.
  */
 public float getPreferredSpan(int axis) {
   switch (axis) {
     case View.X_AXIS:
       Segment buff = SegmentCache.getSharedSegment();
       Document doc = getDocument();
       int width;
       try {
         FontMetrics fm = getFontMetrics();
         doc.getText(0, doc.getLength(), buff);
         width = Utilities.getTabbedTextWidth(buff, fm, 0, this, 0);
         if (buff.count > 0) {
           Component c = getContainer();
           firstLineOffset =
               j86.sun.swing.SwingUtilities2.getLeftSideBearing(
                   (c instanceof JComponent) ? (JComponent) c : null, fm, buff.array[buff.offset]);
           firstLineOffset = Math.max(0, -firstLineOffset);
         } else {
           firstLineOffset = 0;
         }
       } catch (BadLocationException bl) {
         width = 0;
       }
       SegmentCache.releaseSharedSegment(buff);
       return width + firstLineOffset;
     default:
       return super.getPreferredSpan(axis);
   }
 }
 private void initGuardedBlocks(Place shreds) {
   int origOffset = -1;
   int curOffset = 0;
   for (PsiLanguageInjectionHost.Shred shred : shreds) {
     Segment hostRangeMarker = shred.getHostRangeMarker();
     int start = shred.getRange().getStartOffset() + shred.getPrefix().length();
     int end = shred.getRange().getEndOffset() - shred.getSuffix().length();
     if (curOffset < start) {
       RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, start);
       if (curOffset == 0 && shred == shreds.get(0)) guard.setGreedyToLeft(true);
       String padding =
           origOffset < 0
               ? ""
               : myOrigDocument.getText().substring(origOffset, hostRangeMarker.getStartOffset());
       guard.putUserData(REPLACEMENT_KEY, fixQuotes(padding));
     }
     curOffset = end;
     origOffset = hostRangeMarker.getEndOffset();
   }
   if (curOffset < myNewDocument.getTextLength()) {
     RangeMarker guard =
         myNewDocument.createGuardedBlock(curOffset, myNewDocument.getTextLength());
     guard.setGreedyToRight(true);
     guard.putUserData(REPLACEMENT_KEY, "");
   }
 }
示例#9
0
  private boolean replaceWithImage(int startOff, int endOff, Pattern ptn)
      throws BadLocationException {
    Document doc = getDocument();
    String imgStr = doc.getText(startOff, endOff - startOff);
    JComponent comp = null;

    if (ptn == patPatternStr || ptn == patPngStr) {
      if (pref.getPrefMoreImageThumbs()) {
        comp = EditorPatternButton.createFromString(this, imgStr, null);
      } else {
        comp = EditorPatternLabel.labelFromString(this, imgStr);
      }
    } else if (ptn == patRegionStr) {
      if (pref.getPrefMoreImageThumbs()) {
        comp = EditorRegionButton.createFromString(this, imgStr);
      } else {
        comp = EditorRegionLabel.labelFromString(this, imgStr);
      }
    } else if (ptn == patCaptureBtn) {
      comp = EditorPatternLabel.labelFromString(this, "");
    }
    if (comp != null) {
      this.select(startOff, endOff);
      this.insertComponent(comp);
      return true;
    }
    return false;
  }
  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);
    }
  }
示例#11
0
 private boolean isWordChar(int index) {
   try {
     char ch = document.getText(index, 1).charAt(0);
     return Character.isLetterOrDigit(ch);
   } catch (BadLocationException e) {
     return false;
   }
 }
  /**
   * Output the text of the indicated Element, properly clipping it to the range of the Document
   * specified when the AbstractWriter was created.
   */
  protected void text(Element elt) throws BadLocationException, IOException {
    int eltStart = elt.getStartOffset();
    int eltEnd = elt.getEndOffset();

    eltStart = Math.max(eltStart, startOffset);
    eltEnd = Math.min(eltEnd, endOffset);
    write(document.getText(eltStart, eltEnd));
  }
 /*     */ final void loadText(Segment paramSegment, int paramInt1, int paramInt2) /*     */ {
   /*     */ try
   /*     */ {
     /* 308 */ Document localDocument = getDocument();
     /* 309 */ localDocument.getText(paramInt1, paramInt2 - paramInt1, paramSegment);
     /*     */ } catch (BadLocationException localBadLocationException) {
     /* 311 */ throw new StateInvariantError("Can't get line text");
     /*     */ }
   /*     */ }
示例#14
0
 public void insertUpdate(DocumentEvent e) {
   Document doc = e.getDocument();
   try {
     prop.set(doc.getText(0, doc.getLength()));
   } catch (BadLocationException b) {
     // Once again, no idea what this is supposed to be.
     // I don't think I like this interface much :-(.
     System.out.println(b);
   }
 }
示例#15
0
 /**
  * Makes a <code>Segment</code> point to the text in our document between the given positions.
  * Note that the positions MUST be valid positions in the document.
  *
  * @param p0 The first position in the document.
  * @param p1 The second position in the document.
  * @param document The document from which you want to get the text.
  * @param seg The segment in which to load the text.
  */
 private void setSegment(int p0, int p1, Document document, Segment seg) {
   try {
     // System.err.println("... in setSharedSegment, p0/p1==" + p0 + "/" + p1);
     document.getText(p0, p1 - p0, seg);
     // System.err.println("... in setSharedSegment: s=='" + s + "'; line/numLines==" + line + "/"
     // + numLines);
   } catch (BadLocationException ble) { // Never happens
     ble.printStackTrace();
   }
 }
 private void commitToOriginalInner() {
   final String text = myNewDocument.getText();
   final Map<
           PsiLanguageInjectionHost,
           Set<Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>>>
       map =
           ContainerUtil.classify(
               myMarkers.iterator(),
               new Convertor<
                   Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer>,
                   PsiLanguageInjectionHost>() {
                 @Override
                 public PsiLanguageInjectionHost convert(
                     final Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> o) {
                   final PsiElement element = o.third.getElement();
                   return (PsiLanguageInjectionHost) element;
                 }
               });
   PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
   documentManager.commitDocument(myOrigDocument); // commit here and after each manipulator update
   int localInsideFileCursor = 0;
   for (PsiLanguageInjectionHost host : map.keySet()) {
     if (host == null) continue;
     String hostText = host.getText();
     ProperTextRange insideHost = null;
     StringBuilder sb = new StringBuilder();
     for (Trinity<RangeMarker, RangeMarker, SmartPsiElementPointer> entry : map.get(host)) {
       RangeMarker origMarker = entry.first; // check for validity?
       int hostOffset = host.getTextRange().getStartOffset();
       ProperTextRange localInsideHost =
           new ProperTextRange(
               origMarker.getStartOffset() - hostOffset, origMarker.getEndOffset() - hostOffset);
       RangeMarker rangeMarker = entry.second;
       ProperTextRange localInsideFile =
           new ProperTextRange(
               Math.max(localInsideFileCursor, rangeMarker.getStartOffset()),
               rangeMarker.getEndOffset());
       if (insideHost != null) {
         // append unchanged inter-markers fragment
         sb.append(
             hostText.substring(insideHost.getEndOffset(), localInsideHost.getStartOffset()));
       }
       sb.append(
           localInsideFile.getEndOffset() <= text.length() && !localInsideFile.isEmpty()
               ? localInsideFile.substring(text)
               : "");
       localInsideFileCursor = localInsideFile.getEndOffset();
       insideHost = insideHost == null ? localInsideHost : insideHost.union(localInsideHost);
     }
     assert insideHost != null;
     ElementManipulators.getManipulator(host).handleContentChange(host, insideHost, sb.toString());
     documentManager.commitDocument(myOrigDocument);
   }
 }
示例#17
0
  /**
   * Attempts to find the previous subsequence of the input sequence that matches the pattern.
   *
   * <p>This method starts at the beginning of the input sequence or, if a previous invocation of
   * the method was successful and the matcher has not since been reset, at the first character not
   * matched by the previous match.
   *
   * @return the index of the first occurrence of the search string, starting at the specified
   *     offset, or -1 if no occurrence was found.
   */
  public int findPrevious() {
    // Don't match empty strings and don't match if we are at the beginning of the document.
    if (findString.length() == 0 || startIndex < findString.length() - 1) {
      // System.out.println("too close to start");
      return -1;
    }

    try {
      int nextMatch = matchLowerCase.length - 1; // index of next matching character

      // For simplicity, we request all text of the document in a single
      // segment.
      Segment text = new Segment();
      text.setPartialReturn(false);
      document.getText(0, startIndex + 1, text);

      // Iterate through the characters in the current segment
      char previous = text.last();
      // System.out.println("previus isch "+previous);
      for (text.last(); previous != Segment.DONE; previous = text.previous()) {

        // Check if the current character matches with the next
        // search character.
        char current = text.current();
        if (current == matchUpperCase[nextMatch] || current == matchLowerCase[nextMatch]) {
          nextMatch--;
          // System.out.println("matched "+nextMatch);
          // Did we match all search characters?
          if (nextMatch == -1) {
            int foundIndex = text.getIndex() - text.getBeginIndex();
            // System.out.println("found index:"+foundIndex);
            if (matchType == MatchType.CONTAINS) {
              return foundIndex;
            } else if (matchType == MatchType.STARTS_WITH) {
              if (!isWordChar(foundIndex - 1)) {
                return foundIndex;
              }
            } else if (matchType == MatchType.FULL_WORD) {
              if (!isWordChar(foundIndex - 1) && !isWordChar(foundIndex + matchLowerCase.length)) {
                return foundIndex;
              }
            }
            nextMatch = matchLowerCase.length - 1;
          }
        } else {
          nextMatch = matchLowerCase.length - 1;
        }
      }

      return -1;
    } catch (BadLocationException e) {
      throw new IndexOutOfBoundsException();
    }
  }
示例#18
0
 private void updateBoard(DocumentEvent e) throws BadLocationException {
   Document doc = e.getDocument();
   int index = (int) doc.getProperty("index");
   String valueString = doc.getText(0, doc.getLength());
   if (doc.getLength() == 0) valueString = "0";
   int value = Integer.parseInt(valueString);
   gameBoard.changeCellAt(index, value);
   // gameBoard.out();
   if (gameBoard.checkGameOver()) {
     JOptionPane.showMessageDialog(frame, "NUMBRIX COMPLETED!!!");
   }
 }
示例#19
0
 /*
  * public int search(String str){
  * return search(str, true);
  * }
  */
 public int search(String str, int pos, boolean forward) {
   boolean isCaseSensitive = true;
   String toSearch = str;
   if (str.startsWith("!")) {
     str = str.substring(1).toUpperCase();
     isCaseSensitive = false;
   }
   int ret = -1;
   Document doc = getDocument();
   Debug.log(9, "search caret: " + pos + ", " + doc.getLength());
   try {
     String body;
     int begin;
     if (forward) {
       int len = doc.getLength() - pos;
       body = doc.getText(pos, len > 0 ? len : 0);
       begin = pos;
     } else {
       body = doc.getText(0, pos);
       begin = 0;
     }
     if (!isCaseSensitive) {
       body = body.toUpperCase();
     }
     Pattern pattern = Pattern.compile(Pattern.quote(str));
     Matcher matcher = pattern.matcher(body);
     ret = continueSearch(matcher, begin, forward);
     if (ret < 0) {
       if (forward && pos != 0) {
         return search(toSearch, 0, forward);
       }
       if (!forward && pos != doc.getLength()) {
         return search(toSearch, doc.getLength(), forward);
       }
     }
   } catch (BadLocationException e) {
     Debug.log(7, "search caret: " + pos + ", " + doc.getLength() + e.getStackTrace());
   }
   return ret;
 }
示例#20
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
 /**
  * This function inserts or replaces the user's input in a string buffer, to create the text
  * which would be on screen if we allowed it. We declare to throw bad location due to
  * doc.getText, but since the paramters are coming from the farmework, that should never
  * happen.... in theory. If insert is true we insert, if false we replace. Length parameter only
  * used when replacing.
  */
 private StringBuffer getTextPrototype(
     boolean insert, FilterBypass fb, int offs, String str, int length)
     throws BadLocationException {
   Document doc = fb.getDocument();
   String text = doc.getText(0, doc.getLength());
   StringBuffer sb = new StringBuffer(text);
   if (insert) {
     sb.insert(offs, str);
   } else {
     sb.replace(offs, offs + length, str);
   }
   return sb;
 } // end of getTextPrototype
  public void testPsi2Doc1() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.insertString(document, 3, "a");
    buffer.insert(3, "a");

    synchronizer.commitTransaction(this.document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 6);
  }
 /*     */ protected int drawSelectedText(
     Graphics paramGraphics, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
     /*     */ throws BadLocationException
       /*     */ {
   /* 202 */ paramGraphics.setColor(this.selected);
   /* 203 */ Document localDocument = getDocument();
   /* 204 */ Segment localSegment = SegmentCache.getSharedSegment();
   /* 205 */ localDocument.getText(paramInt3, paramInt4 - paramInt3, localSegment);
   /* 206 */ int i =
       Utilities.drawTabbedText(
           this, localSegment, paramInt1, paramInt2, paramGraphics, this, paramInt3);
   /* 207 */ SegmentCache.releaseSharedSegment(localSegment);
   /* 208 */ return i;
   /*     */ }
示例#24
0
  public String getCurrentWordBeforeCursor() {
    Document doc = getDocument();
    if (doc == null) return null;

    int charsToLookBack = 10;
    int docLength = doc.getLength();
    if (docLength < charsToLookBack) charsToLookBack = docLength - 1;
    String allTextBeforeCaretPosition = null;
    String oldContent = null;

    String charsSinceLastWhitespace = null;
    try {
      allTextBeforeCaretPosition = doc.getText(0, getCaretPosition());
      LastWhitespaceInfo info = findLastWhitespaceLocation(allTextBeforeCaretPosition);

      if (info.lastWhitespaceLocation > 0 && doc.getLength() > (charsToLookBack - 1)) {
        // get caret position
        int caretPosition = getCaretPosition();
        // look at last 10 characters
        int scanBackPosition = caretPosition - charsToLookBack;
        if (scanBackPosition <= 0) return null;
        String recentChars = doc.getText(scanBackPosition, charsToLookBack);
        // if any characters are blanks, get the characters since the last blank
        int lastWhitespacePosition = recentChars.lastIndexOf(info.lastWhitespaceString);
        if (lastWhitespacePosition <= 0) return null;
        charsSinceLastWhitespace =
            recentChars.substring(lastWhitespacePosition + 1, charsToLookBack);
        return charsSinceLastWhitespace;
      } else {
        return null;
      }
    } catch (BadLocationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
  @Override
  public void insertString(
      FilterBypass filterBypass, int offset, String text, AttributeSet attributeSet)
      throws BadLocationException {
    text = trimHexadecimal(text);
    Document document = filterBypass.getDocument();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(document.getText(0, document.getLength()));
    stringBuilder.insert(offset, text);

    if (isValidInput(stringBuilder.toString(), 0)) {
      super.insertString(filterBypass, offset, text, attributeSet);
    } else {
      Toolkit.getDefaultToolkit().beep();
    }
  }
示例#26
0
 private void checkCompletion(java.awt.event.KeyEvent ke) throws BadLocationException {
   Document doc = getDocument();
   Element root = doc.getDefaultRootElement();
   int pos = getCaretPosition();
   int lineIdx = root.getElementIndex(pos);
   Element line = root.getElement(lineIdx);
   int start = line.getStartOffset(), len = line.getEndOffset() - start;
   String strLine = doc.getText(start, len - 1);
   Debug.log(9, "[" + strLine + "]");
   if (strLine.endsWith("find") && ke.getKeyChar() == '(') {
     ke.consume();
     doc.insertString(pos, "(", null);
     ButtonCapture btnCapture = new ButtonCapture(this, line);
     insertComponent(btnCapture);
     doc.insertString(pos + 2, ")", null);
   }
 }
    private String addWhiteSpace(Document doc, int offset) throws BadLocationException {
      StringBuilder whiteSpace = new StringBuilder("\n");
      Element rootElement = doc.getDefaultRootElement();
      int line = rootElement.getElementIndex(offset);
      int i = rootElement.getElement(line).getStartOffset();

      while (true) {
        String temp = doc.getText(i, 1);

        if (temp.equals(" ") || temp.equals("\t")) {
          whiteSpace.append(temp);
          i++;
        } else break;
      }

      return whiteSpace.toString();
    }
    /**
     * Updates the shared value instance if updateValue is true. Always forces the redraw of
     * everything.
     */
    protected void doValueUpdate(FilterBypass fb) throws BadLocationException {
      Document doc = fb.getDocument();
      String text = doc.getText(0, doc.getLength());
      if (text.isEmpty()) {
        text = "0";
      }

      if (updateValue == true) {
        try {
          Double value = new Double(text);
          double newValue = multiplier.getValueToBeSet(value.doubleValue());
          cValue.setValue(newValue);
        } catch (NumberFormatException e) {
          // do nothing, since we allow '-'
        }
      }
      topContainer.forceRedraw();
    }
  public void testPsi2DocForwardRangesChanges() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.replaceString(document, 4, 5, "3a4");
    buffer.replace(4, 5, "3a4");

    synchronizer.insertString(document, 7, "b");
    buffer.insert(7, "b");

    synchronizer.insertString(document, 1, "b");
    buffer.insert(1, "b");

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 3, 8);
  }
示例#30
0
 private int getFunctionStartOffset(String func, Element node) throws BadLocationException {
   Document doc = getDocument();
   int count = node.getElementCount();
   Pattern patDef = Pattern.compile("def\\s+" + func + "\\s*\\(");
   for (int i = 0; i < count; i++) {
     Element elm = node.getElement(i);
     if (elm.isLeaf()) {
       int start = elm.getStartOffset(), end = elm.getEndOffset();
       String line = doc.getText(start, end - start);
       Matcher matcher = patDef.matcher(line);
       if (matcher.find()) {
         return start;
       }
     } else {
       int p = getFunctionStartOffset(func, elm);
       if (p >= 0) {
         return p;
       }
     }
   }
   return -1;
 }