下面列出了javax.swing.text.Document#remove ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void processDocumentLocked(Document doc, Difference diff) throws BadLocationException {
switch (diff.getKind()) {
case INSERT:
doc.insertString(diff.getStartPosition().getOffset(), diff.getNewText(), null);
break;
case REMOVE:
doc.remove(diff.getStartPosition().getOffset(), diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset());
break;
case CHANGE: {
// first insert the new content, THEN remove the old one. In situations where the content AFTER the
// change is not writable this ordering allows to replace the content, but if we first delete,
// replacement cannot be inserted into the nonwritable area.
int offs = diff.getStartPosition().getOffset();
int removeLen = diff.getEndPosition().getOffset() - offs;
// [NETBEANS-4270] Can't use "delta = diff.getNewText().length()".
// doc.insertString may filter chars, e.g. '\r', and change length.
int initialLength = doc.getLength();
doc.insertString(offs, diff.getNewText(), null);
int delta = doc.getLength() - initialLength;
doc.remove(delta + offs, removeLen);
break;
}
}
}
@Override
public void defaultAction(JTextComponent component) {
if (component == null) {
return;
}
Completion.get().hideAll();
Document doc = component.getDocument();
if (doc == null) {
return;
}
int caret = component.getCaretPosition();
int l = caret - fromOffset;
try {
doc.insertString(fromOffset, "/" + command + " ", null); // NOI18N
doc.remove(fromOffset + command.length() + 2, l);
} catch (BadLocationException ex) {
// ignore
}
}
/** Show only the first n lines. */
public static void trimLines(final Document doc, final int lineCount) {
if (doc.getLength() < lineCount) {
return;
}
try {
final String text = doc.getText(0, doc.getLength());
int returnsFound = 0;
for (int i = text.length() - 1; i >= 0; i--) {
if (text.charAt(i) == '\n') {
returnsFound++;
}
if (returnsFound == lineCount) {
doc.remove(0, i);
return;
}
}
} catch (final BadLocationException e) {
log.log(Level.SEVERE, "There was an Error whilst trying trimming Chat", e);
}
}
@Test
public void testNonJavaChangesOpenedInEditor214197() throws Exception {
HintTest ht = HintTest.create()
.input("package test;\n" +
"public class Test { }\n")
.input("test/test.txt", "1\n#foobar\n\n2", false);
FileObject resource = ht.getSourceRoot().getFileObject("test/test.txt");
DataObject od = DataObject.find(resource);
EditorCookie ec = od.getLookup().lookup(EditorCookie.class);
Document doc = ec.openDocument();
doc.remove(0, doc.getLength());
doc.insertString(0, "5\n6\n", null);
ht.run(NonJavaChanges.class)
.findWarning("1:13-1:17:verifier:Test")
.applyFix(false)
.assertVerbatimOutput("test/test.txt", "6\n7\n");
Assert.assertEquals("1\n#foobar\n\n2", resource.asText("UTF-8"));
Assert.assertEquals("6\n7\n", doc.getText(0, doc.getLength()));
}
/**
* Creates a PositionRef biased backwards and verifies it behaves correctly,
* then closes and reopens the document and checks again
*/
public void testBiasSurvivesStateChanges() throws Exception {
// open the document
Document doc = support.openDocument();
PositionRef back = support.createPositionRef(3, Position.Bias.Backward);
PositionRef forw = support.createPositionRef(3, Position.Bias.Forward);
doc.insertString(3, "_", null);
assertEquals("Backwards position should not move for insert at its position",
3, back.getOffset());
assertEquals("Forwards position should move for insert at its position",
4, forw.getOffset());
// move positions at the same offset again
doc.remove(3, 1);
support.close();
doc = support.openDocument();
doc.insertString(3, "_", null);
assertEquals("Backwards position should not move for insert at its position",
3, back.getOffset());
assertEquals("Forwards position should move for insert at its position",
4, forw.getOffset());
}
public static Document setDocumentContentTo(Document doc, InputStream in) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer sbuf = new StringBuffer();
try {
String line = null;
while ((line = br.readLine()) != null) {
sbuf.append(line);
sbuf.append(System.getProperty("line.separator"));
}
} finally {
br.close();
}
doc.remove(0, doc.getLength());
doc.insertString(0,sbuf.toString(),null);
return doc;
}
public static Document setDocumentContentTo(Document doc, InputStream in) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer sbuf = new StringBuffer();
try {
String line = null;
while ((line = br.readLine()) != null) {
sbuf.append(line);
sbuf.append(System.getProperty("line.separator"));
}
} finally {
br.close();
}
doc.remove(0, doc.getLength());
doc.insertString(0,sbuf.toString(),null);
return doc;
}
private static boolean expand(CodeTemplateManagerOperation op, JTextComponent component, int abbrevStartOffset, CharSequence abbrev) {
op.waitLoaded();
CodeTemplate ct = op.findByAbbreviation(abbrev.toString());
if (ct != null) {
if (accept(ct, CodeTemplateManagerOperation.getTemplateFilters(component, abbrevStartOffset))) {
Document doc = component.getDocument();
sendUndoableEdit(doc, CloneableEditorSupport.BEGIN_COMMIT_GROUP);
try {
// Remove the abbrev text
doc.remove(abbrevStartOffset, abbrev.length());
ct.insert(component);
} catch (BadLocationException ble) {
} finally {
sendUndoableEdit(doc, CloneableEditorSupport.END_COMMIT_GROUP);
}
return true;
}
}
return false;
}
@Override
public void remove(Context context) throws BadLocationException {
Document doc = context.getDocument();
int dotPos = context.getOffset();
char ch = context.getText().charAt(0);
if (ch == '\'' || ch == '"') { //NOI18N
TokenSequence<HTMLTokenId> ts = LexUtilities.getTokenSequence((BaseDocument) doc, dotPos, HTMLTokenId.language());
if (ts != null) {
int diff = ts.move(dotPos);
if (diff != 1) {
//we only handle situation where leading quote is removed from an attribute value -- the diff must be 1
return;
}
if (!ts.moveNext()) {
return;
}
Token<HTMLTokenId> token = ts.token();
if (token.id() == HTMLTokenId.VALUE || token.id() == HTMLTokenId.VALUE_CSS || token.id() == HTMLTokenId.VALUE_JAVASCRIPT) {
char first = token.text().charAt(0);
if (first == ch) {
//user pressed backspace in empty value: <div class="|" + BACKSPACE
//now the text is: <div class=|"
//expected result: remove the second quote
doc.remove(dotPos - 1, 1);
}
}
}
}
}
private Document getDocument(FileObject fo){
Document result = null;
if (documentPooling) {
result = documentPool().get(fo);
}
if (result != null) return result;
try {
File file = FileUtil.toFile(fo);
FileInputStream fis = new FileInputStream(file);
byte buffer[] = new byte[fis.available()];
result = new org.netbeans.editor.BaseDocument(
org.netbeans.modules.xml.text.syntax.XMLKit.class, false);
result.remove(0, result.getLength());
fis.read(buffer);
fis.close();
String str = new String(buffer);
result.insertString(0,str,null);
} catch (Exception dObjEx) {
return null;
}
if (documentPooling) {
documentPool().put(fo, result);
}
return result;
}
private void remove(Document document, EditHistory history, int offset, int length) throws Exception {
try {
document.addDocumentListener(history);
document.remove(offset, length);
} finally {
document.removeDocumentListener(history);
}
}
private static void completeAsUser(JTextComponent comp, String what, int where) {
Document doc = comp.getDocument();
try {
int end = comp.getSelectionEnd();
int len = end - where;
if (len > 0) {
doc.remove(where, len);
}
doc.insertString(where, what, null);
comp.setCaretPosition(where + what.length());
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
public void actionPerformed(ActionEvent evt)
{
try
{
Document doc = MessagePanel.this.getDocument();
doc.remove(0, doc.getLength());
_lastMessage = null;
}
catch (BadLocationException ex)
{
s_log.error("Error clearing document", ex);
}
}
private void imageReplaceSelection(String content) {
Document doc = getStyledDocument();
if (doc != null) {
try {
Caret caret = getCaret();
boolean composedTextSaved = saveComposedText(caret.getDot());
int p0 = Math.min(caret.getDot(), caret.getMark());
int p1 = Math.max(caret.getDot(), caret.getMark());
AttributeSet attr = getInputAttributes().copyAttributes();
if (doc instanceof AbstractDocument) {
((AbstractDocument) doc).replace(p0, p1 - p0, content, attr);
} else {
if (p0 != p1) {
doc.remove(p0, p1 - p0);
}
if (content != null && !content.isEmpty()) {
doc.insertString(p0, content, attr);
}
}
if (composedTextSaved) {
restoreComposedText();
}
} catch (BadLocationException e) {
IOHandler.writeErrorLog(e);
UIManager.getLookAndFeel().provideErrorFeedback(PGrammarPane.this);
}
}
}
protected int insert(String s, int start, int end, Document doc, boolean reformat)
throws BadLocationException {
try {
doc.remove(start, end - start);
doc.insertString(start, s, null);
} catch (BadLocationException ble) {}
if(reformat)
reformat(doc, 0, doc.getLength());
return start;
}
/**
* Removes the lines.
*
* @param e the e
*/
private void removeLines(DocumentEvent e) {
Document document = e.getDocument();
Element root = document.getDefaultRootElement();
while (root.getElementCount() > maximumLines) {
Element line = root.getElement(0);
int end = line.getEndOffset();
try {
document.remove(0, end);
} catch(BadLocationException ble) {
//System.out.println(ble);
}
}
}
public void testTokenCountWasCalledInUpdater() throws Exception {
Document doc = new ModificationTextDocument();
String text = "+/* */";
doc.insertString(0, text, null);
doc.putProperty(Language.class, TestTokenId.language());
TokenHierarchy<?> hi = TokenHierarchy.get(doc);
TokenSequence<?> ts;
((AbstractDocument)doc).readLock();
try {
ts = hi.tokenSequence();
assertTrue(ts.moveNext());
LexerTestUtilities.assertTokenEquals(ts,TestTokenId.PLUS, "+", -1);
} finally {
((AbstractDocument)doc).readUnlock();
}
doc.remove(1, 3); // Remove "/* "
((AbstractDocument)doc).readLock();
try {
ts = hi.tokenSequence();
ts.moveEnd();
// Extra ending '\n' of the document returned by DocumentUtilities.getText(doc) and lexed
assertTrue(ts.movePrevious());
LexerTestUtilities.assertTokenEquals(ts,TestTokenId.WHITESPACE, "\n", -1);
assertTrue(ts.movePrevious());
LexerTestUtilities.assertTokenEquals(ts,TestTokenId.DIV, "/", -1);
} finally {
((AbstractDocument)doc).readUnlock();
}
}
@Override
public void keyTyped(KeyEvent e)
{
if (!hiscoreConfig.autocomplete())
{
return;
}
final JTextComponent input = (JTextComponent) e.getSource();
final String inputText = input.getText();
// Only autocomplete if the selection end is at the end of the text.
if (input.getSelectionEnd() != inputText.length())
{
return;
}
// Character to be inserted at the selection start.
final String charToInsert = Character.toString(e.getKeyChar());
// Don't attempt to autocomplete if the name is invalid.
// This condition is also true when the user presses a key like backspace.
if (INVALID_CHARS.matcher(charToInsert).find()
|| INVALID_CHARS.matcher(inputText).find())
{
return;
}
// Check if we are already autocompleting.
if (autocompleteName != null && autocompleteNamePattern.matcher(inputText).matches())
{
if (isExpectedNext(input, charToInsert))
{
try
{
// Insert the character and move the selection.
final int insertIndex = input.getSelectionStart();
Document doc = input.getDocument();
doc.remove(insertIndex, 1);
doc.insertString(insertIndex, charToInsert, null);
input.select(insertIndex + 1, input.getSelectionEnd());
}
catch (BadLocationException ex)
{
log.warn("Could not insert character.", ex);
}
// Prevent default behavior.
e.consume();
}
else // Character to insert does not match current autocompletion. Look for another name.
{
newAutocomplete(e);
}
}
else // Search for a name to autocomplete
{
newAutocomplete(e);
}
}
public List<Difference> compareXML(String firstDoc,
String secondDoc, ComparisonCriteria type, boolean filterWhiteSpace)
throws BadLocationException, IOException {
Document sd1 = new BaseDocument(true, "text/xml"); //NOI18N
XDMModel m1 = createXDMModel(sd1);
sd1.remove(0, XML_PROLOG.length());
sd1.insertString(0, firstDoc, null);
m1.sync();
fDoc = m1.getDocument();
Document sd2 = new BaseDocument(true, "text/xml"); //NOI18N
sd2.getText(0, sd2.getLength());
XDMModel m2 = createXDMModel(sd2);
sd2.remove(0, XML_PROLOG.length());
sd2.insertString(0, secondDoc, null);
m2.setPretty(true);
m2.sync();
sDoc = m2.getDocument();
XDUDiffFinder dif = new XDUDiffFinder(createElementIdentity());
List<Difference> diffs = dif.findDiff(m1.getDocument(), m2.getDocument());
if(filterWhiteSpace)
diffs = XDUDiffFinder.filterWhitespace(diffs);//filter whitespace diffs
if(type == ComparisonCriteria.EQUAL) {//remove order change diffs
List<Difference> filteredDiffs = new ArrayList<Difference>();
for(Difference d:diffs) {
if(d instanceof Change) {
Change c = (Change)d;
if(c.isPositionChanged())//node (element/text) pos change
if(!c.isTokenChanged() && !c.isAttributeChanged())
continue;
if(c.isAttributeChanged() && !c.isTokenChanged()) {//attr change only
List<Change.AttributeDiff> removeList =
new ArrayList<Change.AttributeDiff>();
List<Change.AttributeDiff> attrChanges = c.getAttrChanges();
for(int i=0;i<attrChanges.size();i++) {
if(attrChanges.get(i) instanceof Change.AttributeChange) {
Change.AttributeChange ac =
(Change.AttributeChange) attrChanges.get(i);
if(ac.isPositionChanged() && !ac.isTokenChanged())//attr pos change only
removeList.add(ac);
}
}
for(int i=0;i<removeList.size();i++)
c.removeAttrChanges(removeList.get(i));
if(c.getAttrChanges().size() == 0) //filter this diff
continue;
}
filteredDiffs.add(d);
} else {
filteredDiffs.add(d);
}
}
return filteredDiffs;
}
//remove pseudo attr position changes
removePseudoAttrPosChanges(diffs);
filterSchemaLocationDiffs(diffs);
return diffs;
}
public void testRestart() throws Exception {
clearWorkDir();
FileObject grammar = FileUtil.createData(FileUtil.getConfigRoot(), "Editors/text/test/grammar.json");
try (OutputStream out = grammar.getOutputStream();
Writer w = new OutputStreamWriter(out)) {
w.write("{ \"scopeName\": \"test\", " +
" \"patterns\": [\n" +
" { \"name\": \"string.test\",\n" +
" \"begin\": \"x([^x]+)x\",\n" +
" \"end\": \"x\\\\1x\"\n" +
" },\n" +
" { \"name\": \"whitespace.test\",\n" +
" \"match\": \" +\"\n" +
" }\n" +
"]}\n");
}
grammar.setAttribute(LanguageHierarchyImpl.GRAMMAR_MARK, "test");
Document doc = new PlainDocument();
doc.insertString(0, " xaax xbbx\nxccx xaax ", null);
doc.putProperty(Language.class, new LanguageHierarchyImpl("text/test", "test").language());
TokenHierarchy<Document> hi = TokenHierarchy.get(doc);
TokenSequence<?> ts = hi.tokenSequence();
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbx\n");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xccx ");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.UNTOKENIZED, "\n");
assertFalse(ts.moveNext());
doc.insertString(8, "b", null);
ts = hi.tokenSequence();
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbbx\n");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xccx ");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.UNTOKENIZED, "\n");
assertFalse(ts.moveNext());
doc.insertString(14, "c", null);
ts = hi.tokenSequence();
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbbx\n");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xcccx ");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.UNTOKENIZED, "\n");
assertFalse(ts.moveNext());
doc.insertString(3, "a", null);
ts = hi.tokenSequence();
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbbx\n");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xcccx xaax \n");
assertFalse(ts.moveNext());
doc.remove(3, 1);
ts = hi.tokenSequence();
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " xbbbx\n");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xcccx ");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, "xaax");
assertTokenProperties(ts, "test", "string.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.TEXTMATE, " ");
assertTokenProperties(ts, "test", "whitespace.test");
LexerTestUtilities.assertNextTokenEquals(ts, TextmateTokenId.UNTOKENIZED, "\n");
assertFalse(ts.moveNext());
}