javax.swing.text.StyledDocument#remove ( )源码实例Demo

下面列出了javax.swing.text.StyledDocument#remove ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: org.alloytools.alloy   文件: SwingLogPanel.java
/**
 * Truncate the log to the given length; if the log is shorter than the number
 * given, then nothing happens.
 */
void setLength(int newLength) {
    if (log == null)
        return;
    clearError();
    StyledDocument doc = log.getStyledDocument();
    int n = doc.getLength();
    if (n <= newLength)
        return;
    try {
        doc.remove(newLength, n - newLength);
    } catch (BadLocationException e) {
        // Harmless
    }
    if (lastSize > doc.getLength()) {
        lastSize = doc.getLength();
    }
}
 
源代码2 项目: netbeans   文件: MemoryTest.java
private void processTest(String testName, String insertionText) throws Exception {
    File testFile = new File(getDataDir(), testName);
    FileObject testObject = FileUtil.createData(testFile);
    DataObject dataObj = DataObject.find(testObject);
    EditorCookie.Observable ed = dataObj.getCookie(Observable.class);
    handler.params.clear();
    handler.latest = null;
    StyledDocument doc = ed.openDocument();
    ed.open();
    Thread.sleep(TIMEOUT);
    handler.params.clear();

    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        doc.insertString(0, insertionText, null);
        Thread.sleep(TIMEOUT);
    }
    for (int i = 0; i < ITERATIONS_COUNT; i++) {
        doc.remove(0, insertionText.length());
        Thread.sleep(TIMEOUT);
    }

    ed.saveDocument();
    ed.close();

    assertClean();
}
 
源代码3 项目: binnavi   文件: BaseTypeTableCellRenderer.java
private static void renderArray(
    final TypeInstance instance, final StyledDocument document, final boolean renderData) {
  final Style arrayStyle = createDeclarationStyle(document);
  try {
    document.remove(0, document.getLength());
    final BaseType baseType = instance.getBaseType();
    appendString(document, baseType.getName(), arrayStyle);
    if (renderData) {
      appendString(document,
          renderInstanceData(baseType, instance.getAddress().getOffset(), instance.getSection()),
          createDataStyle(document));
    }
  } catch (final BadLocationException exception) {
    CUtilityFunctions.logException(exception);
  }
}
 
源代码4 项目: netbeans   文件: DTDActionsTest.java
public void testCheckCSS() throws Exception{
    final String err1 = "\nNEW {";
    final String err2 = "{font-size: 12px; \n _color:black}";
    Node node = WebPagesNode.getInstance(projectName).getChild(cssFileName, Node.class);
    StyledDocument doc = openFile(projectName, cssFileName);
    checkCSS(node);
    doc.insertString(doc.getLength()-1, err1, null);
    checkCSS(node);
    doc.insertString(doc.getLength()-1, err2, null);
    checkCSS(node);
    int errPos = doc.getText(0, doc.getLength()).indexOf("{{");
    doc.remove(errPos, 1);
    checkCSS(node);
    errPos = doc.getText(0, doc.getLength()).indexOf("_");
    doc.remove(errPos, 1);
    checkCSS(node);
    ending();
}
 
源代码5 项目: netbeans   文件: GuardedSectionImpl.java
/** Deletes the text in the section.
 * @exception BadLocationException
 */
final void deleteText() throws BadLocationException {
    if (valid) {
        final StyledDocument doc = guards.getDocument();
        final BadLocationException[] blex = new BadLocationException[1];
        Runnable r = new Runnable() {
            public void run() {
                try {
                    int start = getStartPosition().getOffset();
                    if (start > 0 && "\n".equals(doc.getText(start - 1, 1))) { // NOI18N
                        start--;
                    }
                    doc.remove(start, getEndPosition().getOffset() - start + 1);
                } catch (BadLocationException ex) {
                    blex[0] = ex;
                }
            }
        };
        
        GuardedSectionsImpl.doRunAtomic(doc, r);
        
        if (blex[0] != null) {
            throw blex[0];
        }
    }
}
 
源代码6 项目: freecol   文件: ReportRequirementsPanel.java
private void insertColonyButtons(StyledDocument doc, List<Colony> colonies) throws Exception {
    for (Colony colony : colonies) {
        StyleConstants.setComponent(doc.getStyle("button"), createColonyButton(colony, false));
        doc.insertString(doc.getLength(), " ", doc.getStyle("button"));
        doc.insertString(doc.getLength(), ", ", doc.getStyle("regular"));
    }
    doc.remove(doc.getLength() - 2, 2);
}
 
源代码7 项目: netbeans   文件: SummaryCellRenderer.java
private void clearSD (JTextPane pane, StyledDocument sd) {
    try {
        Style noindentStyle = createNoindentStyle(pane);
        sd.remove(0, sd.getLength());
        sd.setParagraphAttributes(0, sd.getLength(), noindentStyle, false);
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码8 项目: uima-uimaj   文件: CasAnnotationViewer.java
/**
 * Creates the annotation display.
 */
private void displayAnnotationView() {
  // for speed, detach document from text pane before updating
  StyledDocument doc = (StyledDocument) this.textPane.getDocument();
  Document blank = new DefaultStyledDocument();
  this.textPane.setDocument(blank);

  // make sure annotationCheckboxPanel is showing
  this.typeCheckBoxVerticalScrollPanel.removeAll();

  // add text from CAS
  try {
    doc.remove(0, doc.getLength());
    doc.insertString(0, this.cas.getDocumentText(), new SimpleAttributeSet());
  } catch (BadLocationException e) {
    throw new RuntimeException(e);
  }

  // Iterate over annotations
  AnnotationIndex<AnnotationFS> annotationIndex = this.cas.getAnnotationIndex();
  if (annotationIndex == null) {
    return;
  }
  FSIterator<AnnotationFS> annotationIterator = annotationIndex.iterator();
  if (annotationIterator == null || !annotationIterator.hasNext()) {
    return;
  }
  while (annotationIterator.hasNext()) {
    this.processOneAnnotationInAnnotationView(doc, annotationIterator.next());
  }
  // now populate panel with checkboxes in order specified in user file. JMP
  this.addTypeCheckBoxes();
  // reattach document to text pane
  this.textPane.setDocument(doc);
}
 
源代码9 项目: netbeans   文件: XMLActionsTest.java
public void testXMLWellFormed() throws Exception{
    System.out.println("running testXMLWellFormed");
    String fileName = "well.xml";
    Node node = WebPagesNode.getInstance(projectName).getChild(fileName, Node.class);
    StyledDocument doc = openFile(projectName, fileName);
    checkXML(node);
    int error = doc.getText(0, doc.getLength()).indexOf("notes")+4;
    doc.remove(error, 1);
    checkXML(node);
    validateXML(node);
    error = doc.getText(0, doc.getLength()).indexOf("a=");
    doc.remove(error, 5);
    validateXML(node);
    ending();
}
 
源代码10 项目: nb-springboot   文件: KeyCompletionItem.java
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted key value hint: {0}", hint.toString());
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        int equalSignIndex = -1;
        int colonIndex = -1;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
            equalSignIndex = line.indexOf('=');
            colonIndex = line.indexOf(':');
            if (equalSignIndex >= 0) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        if (equalSignIndex < 0 && colonIndex < 0) {
            logger.log(Level.FINER, "Adding equal sign and continuing completion");
            doc.insertString(dotOffset, hint.getValue().toString().concat("="), null);
        } else {
            logger.log(Level.FINER, "Finish completion with no added chars");
            doc.insertString(dotOffset, hint.getValue().toString(), null);
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码11 项目: MtgDesktopCompanion   文件: MagicTextPane.java
public void updateTextWithIcons() {

		textPane.setText(textPane.getText().replaceAll("(?m)^[ \t]*\r?\n", ""));
		Pattern p = Pattern.compile(CardsPatterns.MANA_PATTERN.getPattern());
		Matcher m = p.matcher(textPane.getText());

		String text = textPane.getText();
		StyleContext context = new StyleContext();
		StyledDocument document = new DefaultStyledDocument(context);

		Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

		Style italic = context.addStyle("italicStyle", labelStyle);
		StyleConstants.setItalic(italic, true);

		int cumule = 0;
		try {
			document.insertString(0, text, null);
			while (m.find()) {
				Image ic = manaPanel.getManaSymbol(m.group());

				int width = 15;
				if (m.group().equals("{100}"))
					width = 30;

				JLabel label = new JLabel(new ImageIcon(ic.getScaledInstance(width, 15, Image.SCALE_DEFAULT)));
				label.setAlignmentY(SwingConstants.TOP);

				StyleConstants.setComponent(labelStyle, label);

				document.remove(m.start() + cumule, (m.end() - m.start()));
				document.insertString(m.start() + cumule, m.group(), labelStyle);
			}

			textPane.setDocument(document);
		} catch (BadLocationException e) {
			textPane.setText(text);
		}
	}
 
源代码12 项目: wpcleaner   文件: MWPaneReplaceAllAction.java
/**
 * @param e Event.
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
@Override
public void actionPerformed(ActionEvent e) {
  MWPane textPane = getMWPane(e);
  if (textPane == null) {
    return;
  }
  StyledDocument doc = textPane.getStyledDocument();
  if (doc == null) {
    return;
  }
  int length = doc.getLength();
  int lastEnd = Integer.MAX_VALUE;
  for (int pos = 0; pos < length; pos = lastEnd) {
    try {
      Element run = doc.getCharacterElement(pos);
      lastEnd = run.getEndOffset();
      if (pos == lastEnd) {
        // offset + length beyond length of document, bail.
        break;
      }
      MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes();
      if ((attr != null) &&
          (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_TYPE) != null) &&
          (attr.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO) != null)) {
        Object attrInfo = attr.getAttribute(MWPaneFormatter.ATTRIBUTE_INFO);
        if (attrInfo instanceof CheckErrorResult) {
          int startOffset = MWPaneFormatter.getUUIDStartOffset(textPane, run);
          int endOffset = MWPaneFormatter.getUUIDEndOffet(textPane, run);
          if (originalText.equals(textPane.getText(startOffset, endOffset - startOffset))) {
            boolean possible = false;
            CheckErrorResult info = (CheckErrorResult) attrInfo;
            List<Actionnable> actionnables = info.getPossibleActions();
            if (actionnables != null) {
              for (Actionnable actionnable : actionnables) {
                possible |= actionnable.isPossibleReplacement(newText);
              }
            }
            if (possible) {
              doc.remove(startOffset, endOffset - startOffset);
              doc.insertString(startOffset, newText, attr);
              lastEnd = startOffset + newText.length();
            }
          }
        }
      }
    } catch (BadLocationException exception) {
      // Nothing to do
    }
  }
}
 
源代码13 项目: netbeans   文件: PositionBounds.java
/** Replaces the text contained in this range.
* This replacement is done atomically, and so is preferable to manual inserts & removes.
* <p>If you are running this from user-oriented code, you may want to wrap it in {@link NbDocument#runAtomicAsUser}.
* @param text new text to insert over existing text
* @exception IOException if any problem occurred during document loading (if that was necessary)
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public void setText(final String text) throws IOException, BadLocationException {
    final CloneableEditorSupport editor = begin.getCloneableEditorSupport();
    final StyledDocument doc = editor.openDocument();
    final BadLocationException[] hold = new BadLocationException[] { null };
    Runnable run = new Runnable() {
            public void run() {
                try {
                    int p1 = begin.getOffset();
                    int p2 = end.getOffset();
                    int len = text.length();

                    if (len == 0) { // 1) set empty string

                        if (p2 > p1) {
                            doc.remove(p1, p2 - p1);
                        }
                    } else { // 2) set non empty string

                        int docLen = doc.getLength();

                        if ((p2 - p1) >= 2) {
                            doc.insertString(p1 + 1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;
                            doc.remove(p1 + 1 + len, p2 - p1 - 1);
                            doc.remove(p1, 1);
                        } else {
                            // zero or exactly one character:
                            // adjust the positions if they are
                            // biased to not absorb the text inserted at the start/end
                            // it would be ridiculous not to have text set by setText
                            // be part of the bounds.
                            doc.insertString(p1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;

                            if (p2 > p1) {
                                doc.remove(p1 + len, p2 - p1);
                            }

                            if (begin.getOffset() != p1) {
                                begin = editor.createPositionRef(p1, begin.getPositionBias());
                            }

                            if ((end.getOffset() - p1) != len) {
                                end = editor.createPositionRef(p1 + len, end.getPositionBias());
                            }
                        }
                    }
                } catch (BadLocationException e) {
                    hold[0] = e;
                }
            }
        };

    NbDocument.runAtomic(doc, run);

    if (hold[0] != null) {
        throw hold[0];
    }
}
 
源代码14 项目: netbeans   文件: UndoRedoWrappingExampleTest.java
public void testDeleteEachTenthCharFromDocument() throws Exception {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 20; i++) {
        for (int j = 0; j < 10; j++) {
            sb.append((char)('0' + j));
        }
    }
    
    content = sb.toString();
    
    StyledDocument doc = support.openDocument();
    assertEquals("200 chars there", 200, doc.getLength());
    
    CompoundEdit bigEdit = new CompoundEdit();
    support.getUndoRedo().undoableEditHappened(new UndoableEditEvent(doc, bigEdit));
    
    assertTrue("Big edit will consume other edits", bigEdit.isInProgress());
    
    for (int i = 199; i >= 0; i -= 10) {
        doc.remove(i, 1);
    }
    
    assertTrue("Big edit was still in consume mode", bigEdit.isInProgress());
    bigEdit.end();
    assertFalse("Big edit is over", bigEdit.isInProgress());
    assertTrue("Document is modified", modified);
    assertTrue("We can undo", support.getUndoRedo().canUndo());
    
    if (doc.getText(0, doc.getLength()).indexOf('9') != -1) {
        fail("There should be no 9 in the doc:\n" + doc.getText(0, doc.getLength()));
    }
    
    support.getUndoRedo().undo();
    
    assertEquals("Again 200", 200, doc.getLength());
    assertFalse("Not modified anymore", modified);

    
    assertTrue("We can redo", support.getUndoRedo().canRedo());
    support.getUndoRedo().redo();
    
    assertTrue("Document is modified", modified);
    assertTrue("We can undo", support.getUndoRedo().canUndo());
    
    if (doc.getText(0, doc.getLength()).indexOf('9') != -1) {
        fail("There should be no 9 in the doc:\n" + doc.getText(0, doc.getLength()));
    }
    
}
 
源代码15 项目: netbeans   文件: UndoRedoWrappingExampleTest.java
public void testDeleteEachTenthCharOnModifiedDocument() throws Exception {
    
    StyledDocument doc = support.openDocument();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 20; i++) {
        for (int j = 0; j < 10; j++) {
            sb.append((char)('0' + j));
        }
    }
    assertEquals("empty", 0, doc.getLength());
    doc.insertString(0, sb.toString(), null);
    assertEquals("200 chars there", 200, doc.getLength());
    
    CompoundEdit bigEdit = new CompoundEdit();
    support.getUndoRedo().undoableEditHappened(new UndoableEditEvent(doc, bigEdit));
    
    assertTrue("Big edit will consume other edits", bigEdit.isInProgress());
    
    for (int i = 199; i >= 0; i -= 10) {
        doc.remove(i, 1);
    }
    
    assertTrue("Big edit was still in consume mode", bigEdit.isInProgress());
    bigEdit.end();
    assertFalse("Big edit is over", bigEdit.isInProgress());
    assertTrue("Document is modified", modified);
    assertTrue("We can undo", support.getUndoRedo().canUndo());
    
    if (doc.getText(0, doc.getLength()).indexOf('9') != -1) {
        fail("There should be no 9 in the doc:\n" + doc.getText(0, doc.getLength()));
    }
    
    support.getUndoRedo().undo();
    
    assertEquals("Again 200", 200, doc.getLength());
    assertTrue("Still modified", modified);

    
    assertTrue("We can redo", support.getUndoRedo().canRedo());
    support.getUndoRedo().redo();
    
    assertTrue("Document is modified", modified);
    assertTrue("We can undo", support.getUndoRedo().canUndo());
    
    if (doc.getText(0, doc.getLength()).indexOf('9') != -1) {
        fail("There should be no 9 in the doc:\n" + doc.getText(0, doc.getLength()));
    }
    
}
 
源代码16 项目: netbeans   文件: XMLJ2eeEditorSupport.java
public void saveDocument () throws IOException {
        final StyledDocument doc = getDocument();
        // dependency on xml/core
        String enc = EncodingUtil.detectEncoding(doc);
        if (enc == null) enc = "UTF8"; //!!! // NOI18N
        
        try {
            //test encoding on dummy stream
            new OutputStreamWriter(new ByteArrayOutputStream(1), enc);
            if (!checkCharsetConversion(enc)) {
                return;
            }
            super.saveDocument();
            //moved from Env.save()
// DataObject.setModified() already called as part of super.saveDocument(). The save action is now asynchronous
// in the IDE and super.saveDocument() checks for possible extra document modifications performed during save
// and sets the DO.modified flag accordingly.
//            getDataObject().setModified (false);
        } catch (UnsupportedEncodingException ex) {
            // ask user what next?
            String message = NbBundle.getMessage(XMLJ2eeEditorSupport.class,"TEXT_SAVE_AS_UTF", enc);
            NotifyDescriptor descriptor = new NotifyDescriptor.Confirmation(message);
            Object res = DialogDisplayer.getDefault().notify(descriptor);

            if (res.equals(NotifyDescriptor.YES_OPTION)) {

                // update prolog to new valid encoding                

                try {
                    final int MAX_PROLOG = 1000;                
                    int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());                
                    final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
                    int prologLen = 0;  // actual prolog length

                    //parse prolog and get prolog end                
                    if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {

                        // look for delimitting ?>
                        for (int i = 3; i<maxPrologLen; i++) {
                            if (prolog[i] == '?' && prolog[i+1] == '>') {
                                prologLen = i + 1;
                                break;
                            }
                        }                                        
                    }

                    final int passPrologLen = prologLen;

                    Runnable edit = new Runnable() {
                         public void run() {
                             try {

                                doc.remove(0, passPrologLen + 1); // +1 it removes exclusive
                                doc.insertString(0, "<?xml version='1.0' encoding='UTF-8' ?> \n<!-- was: " + new String(prolog, 0, passPrologLen + 1) + " -->", null); // NOI18N

                             } catch (BadLocationException e) {
                                 if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                                     e.printStackTrace();
                             }
                         }
                    };

                    NbDocument.runAtomic(doc, edit);

                    super.saveDocument();
                    //moved from Env.save()
// DataObject.setModified() already called as part of super.saveDocument(). The save action is now asynchronous
// and super.saveDocument() checks for possible extra document modifications performed during save
// and sets the DO.modified flag accordingly.
//                    getDataObject().setModified (false);

                } catch (BadLocationException lex) {
                    Exceptions.printStackTrace(lex);
                }

            } else { // NotifyDescriptor != YES_OPTION
                return;
            }
        }
    }
 
源代码17 项目: nb-springboot   文件: JavaTypeCompletionItem.java
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted java type completion: {0} {1}", new Object[]{elementKind.toString(), name});
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from dot up to caret position)
        int lenToRemove = caretOffset - dotOffset;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
            int equalSignIndex = line.indexOf('=');
            int colonIndex = line.indexOf(':');
            int commaIndex = line.indexOf(',', dotOffset - lineElement.getStartOffset());
            if (equalSignIndex >= 0 && dotOffset < equalSignIndex) {
                // from dot to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - dotOffset;
            } else if (colonIndex >= 0 && dotOffset < colonIndex) {
                // from dot to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - dotOffset;
            } else if (commaIndex >= 0) {
                // from dot to comma
                lenToRemove = lineElement.getStartOffset() + commaIndex - dotOffset;
            } else {
                // from dot to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - dotOffset;
            }
        }
        // remove characters from dot then insert new text
        doc.remove(dotOffset, lenToRemove);
        if (isKeyCompletion) {
            // insert and continue completion
            doc.insertString(dotOffset, name.concat("="), null);
        } else {
            // insert and close the code completion box
            doc.insertString(dotOffset, name, null);
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码18 项目: dungeon   文件: SwappingStyledDocument.java
private void clear(StyledDocument document) {
  try {
    document.remove(0, document.getLength());
  } catch (BadLocationException ignored) { // Never happens.
  }
}
 
源代码19 项目: nb-springboot   文件: CfgPropCompletionItem.java
@Override
public void defaultAction(JTextComponent jtc) {
    logger.log(Level.FINER, "Accepted name completion: {0}", configurationMeta.getId());
    try {
        StyledDocument doc = (StyledDocument) jtc.getDocument();
        // calculate the amount of chars to remove (by default from property start up to caret position)
        int lenToRemove = caretOffset - propStartOffset;
        int equalSignIndex = -1;
        if (overwrite) {
            // NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
            // the document state here is different from when the completion was invoked thus we have to
            // find again the offset of the equal sign in the line
            Element lineElement = doc.getParagraphElement(caretOffset);
            String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
            equalSignIndex = line.indexOf('=');
            int colonIndex = line.indexOf(':');
            if (equalSignIndex >= 0) {
                // from property start to equal sign
                lenToRemove = lineElement.getStartOffset() + equalSignIndex - propStartOffset;
            } else if (colonIndex >= 0) {
                // from property start to colon
                lenToRemove = lineElement.getStartOffset() + colonIndex - propStartOffset;
            } else {
                // from property start to end of line (except line terminator)
                lenToRemove = lineElement.getEndOffset() - 1 - propStartOffset;
            }
        }
        // remove characters from the property name start offset
        doc.remove(propStartOffset, lenToRemove);
        // add some useful chars depending on data type and presence of successive equal signs
        final String dataType = configurationMeta.getType();
        final boolean isSequence = dataType.contains("List") || dataType.contains("Set") || dataType.contains("[]");
        final boolean preferArray = NbPreferences.forModule(PrefConstants.class)
                .getBoolean(PrefConstants.PREF_ARRAY_NOTATION, false);
        final boolean needEqualSign = !(overwrite && equalSignIndex >= 0);
        StringBuilder sb = new StringBuilder(getText());
        boolean continueCompletion = false;
        int goBack = 0;
        if (dataType.contains("Map")) {
            sb.append(".");
            continueCompletion = canCompleteKey();
        } else if (isSequence) {
            if (preferArray) {
                sb.append("[]");
                goBack = 1;
                if (needEqualSign) {
                    sb.append("=");
                    goBack++;
                }
            } else {
                if (needEqualSign) {
                    sb.append("=");
                    continueCompletion = canCompleteValue();
                }
            }
        } else if (needEqualSign) {
            sb.append("=");
            continueCompletion = canCompleteValue();
        }
        doc.insertString(propStartOffset, sb.toString(), null);
        if (goBack != 0) {
            jtc.setCaretPosition(jtc.getCaretPosition() - goBack);
        }
        // optinally close the code completion box
        if (!continueCompletion) {
            Completion.get().hideAll();
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码20 项目: netbeans   文件: PositionBounds.java
/** Replaces the text contained in this range.
* This replacement is done atomically, and so is preferable to manual inserts & removes.
* <p>If you are running this from user-oriented code, you may want to wrap it in {@link NbDocument#runAtomicAsUser}.
* @param text new text to insert over existing text
* @exception BadLocationException if the positions are out of the bounds of the document
*/
public void setText(final String text) throws BadLocationException  {
    final StyledDocument doc = guards.getDocument();
    final BadLocationException[] hold = new BadLocationException[] { null };
    Runnable run = new Runnable() {
            public void run() {
                try {
                    int p1 = begin.getOffset();
                    int p2 = end.getOffset();
                    int len = text.length();

                    if (len == 0) { // 1) set empty string

                        if (p2 > p1) {
                            doc.remove(p1, p2 - p1);
                        }
                    } else { // 2) set non empty string

                        int docLen = doc.getLength();

                        if ((p2 - p1) >= 1) {
                            doc.insertString(p1 + 1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;
                            doc.remove(p1 + 1 + len, p2 - p1 - 1);
                            doc.remove(p1, 1);
                        } else {
                            // zero or exactly one character:
                            // adjust the positions if they are
                            // biased to not absorb the text inserted at the start/end
                            // it would be ridiculous not to have text set by setText
                            // be part of the bounds.
                            doc.insertString(p1, text, null);

                            // [MaM] compute length of inserted string
                            len = doc.getLength() - docLen;

                            if (p2 > p1) {
                                doc.remove(p1 + len, p2 - p1);
                            }

                            if (begin.getOffset() != p1) {
                                begin = doc.createPosition(p1);
                            }

                            if ((end.getOffset() - p1) != len) {
                                end = doc.createPosition(p1 + len);
                            }
                            assertPositionBounds();
                        }
                    }
                } catch (BadLocationException e) {
                    hold[0] = e;
                }
            }
        };

    GuardedSectionsImpl.doRunAtomic(doc, run);

    if (hold[0] != null) {
        throw hold[0];
    }
}