下面列出了javax.swing.text.Document#getText ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void close() throws IOException {
indentImpl.reformatLock();
try {
Document doc = indentImpl.document();
String text = buffer.toString();
if (text.length() > 0 && offset <= doc.getLength()) {
try {
doc.insertString(offset, text, null);
Position startPos = doc.createPosition(offset);
Position endPos = doc.createPosition(offset + text.length());
indentImpl.reformat(startPos.getOffset(), endPos.getOffset(), startPos.getOffset());
int len = endPos.getOffset() - startPos.getOffset();
String reformattedText = doc.getText(startPos.getOffset(), len);
doc.remove(startPos.getOffset(), len);
writer.write(reformattedText);
} catch (BadLocationException e) {
Exceptions.printStackTrace(e);
}
}
} finally {
indentImpl.reformatUnlock();
}
}
/**
* Given some html, extracts its text.
*/
public static String extractTextFromHTML(String html) {
try {
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
// The Document class does not yet handle charset's properly.
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
// Create a reader on the HTML content.
Reader rd = new StringReader(html);
// Parse the HTML.
kit.read(rd, doc, 0);
// The HTML text is now stored in the document
return doc.getText(0, doc.getLength());
} catch (Exception e) {
}
return "";
}
public int bufferOffsetForLineNumber(int lineNumber) {
final Document document = editPane.getDocument();
String documentText;
try {
documentText = document.getText(0, document.getLength());
} catch (BadLocationException e) {
e.printStackTrace();
return 1;
}
int walker = 0;
// It is "-1" because we want the newline that terminates
// the *preceding* line
for (int i = 0; i < lineNumber - 1; i++) {
int nextNewlineIndex = documentText.indexOf("\n", walker);
if (-1 == nextNewlineIndex) {
break;
} else {
walker = nextNewlineIndex + 1;
}
}
return walker;
}
@Override
public void performTask() {
try {
Document document = context.getDocument();
String content = document.getText(0, document.getLength());
DataObject dataObject = NbEditorUtilities.getDataObject(context.getDocument());
if(dataObject.getPrimaryFile().getMIMEType().equals("text/html") && MinifyProperty.getInstance().isAutoMinifyHTML()){
HTMLMinify.execute(dataObject,content,false);
} else if(dataObject.getPrimaryFile().getMIMEType().equals("text/javascript") && MinifyProperty.getInstance().isAutoMinifyJS()){
JSMinify.execute(dataObject,content,false);
} else if(dataObject.getPrimaryFile().getMIMEType().equals("text/css") && MinifyProperty.getInstance().isAutoMinifyCSS()){
CSSMinify.execute(dataObject,content,false);
} else if(dataObject.getPrimaryFile().getMIMEType().equals("text/x-json") && MinifyProperty.getInstance().isAutoMinifyJSON()){
JSONMinify.execute(dataObject,content,false);
} else if(dataObject.getPrimaryFile().getMIMEType().equals("text/xml-mime") && MinifyProperty.getInstance().isAutoMinifyXML()){
XMLMinify.execute(dataObject,content,false);
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
public static boolean canFilter(Document doc, int invocationOffset, int caretOffset, int anchorOffset, Acceptor acceptor) {
if(anchorOffset == -1 || caretOffset < invocationOffset) {
return false;
}
try {
String prefix = doc.getText(anchorOffset, caretOffset - anchorOffset);
if(acceptor.accept(prefix)) {
return true;
} else {
return false;
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
return false;
}
}
@Override
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
// line coordinates
Document doc = getDocument();
Element map = getElement();
int lineIndex = map.getElementIndex(pos);
if (lineIndex < 0) {
return lineToRect(a, 0);
}
Rectangle lineArea = lineToRect(a, lineIndex);
// determine span from the start of the line
int tabBase = lineArea.x;
Element line = map.getElement(lineIndex);
int p0 = line.getStartOffset();
Segment s = new Segment();
doc.getText(p0, pos - p0, s);
int xOffs = UniTools.getTabbedTextWidth(s, metrics, tabBase, this,p0);
// fill in the results and return
lineArea.x += xOffs;
lineArea.width = 1;
lineArea.height = metrics.getHeight();
return lineArea;
}
@Override
public void execute() {
Document doc = getDocument();
if (doc == null) {
return;
}
String sql;
try {
sql = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
// should not happen
Logger.getLogger("global").log(Level.INFO, null, e);
sql = ""; // NOI18N
}
execute(sql, 0, sql.length(), null);
}
public void testMixed2() throws Exception {
EditHistory history = new EditHistory();
String original = " HelloWorld";
Document doc = getDocument(original);
//012345678901234567890
// HelloWorld
// He__lloWorld
insert(doc, history, 5, "__");
//012345678901234567890
// He__lloWorld
// He__llorld
remove(doc, history, 10, 2);
String modified = doc.getText(0, doc.getLength());
assertEquals(" He__llorld", modified);
assertEquals(5, history.getStart());
assertEquals(10, history.getOriginalEnd());
assertEquals(10, history.getEditedEnd());
assertEquals(5, history.getOriginalSize());
assertEquals(5, history.getEditedSize());
assertEquals(0, history.getSizeDelta());
validateHistory(original, modified, history);
}
private void retreiveGuardedBlock(CodeCategory category, int index) {
GuardedBlock gBlock = codeData.getGuardedBlock(category, index);
if (!gBlock.isCustomizable())
return;
if (getGuardInfos(category)[index].customized) {
Document doc = getDocument(category);
int[] blockBounds = getGuardBlockBounds(category, index);
try {
int startPos = blockBounds[0] + gBlock.getHeaderLength();
String code = doc.getText(startPos,
blockBounds[1] - gBlock.getFooterLength() - startPos);
gBlock.setCustomizedCode(code);
}
catch (BadLocationException ex) { // should not happen
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
}
}
else { // reset to default code
gBlock.setCustomizedCode(null);
}
}
public void testMultipleInserts1() throws Exception {
EditHistory history = new EditHistory();
String original = " HelloWorld";
Document doc = getDocument(original);
//012345678901234567890
// HelloWorld
// He__lloWorld
insert(doc, history, 5, "__");
//012345678901234567890
// He__lloWorld
// He__llo__World
insert(doc, history, 10, "__");
String modified = doc.getText(0, doc.getLength());
assertEquals(" He__llo__World", modified);
assertEquals(5, history.getStart());
assertEquals(8, history.getOriginalEnd());
assertEquals(12, history.getEditedEnd());
assertEquals(3, history.getOriginalSize());
assertEquals(7, history.getEditedSize());
assertEquals(4, history.getSizeDelta());
validateHistory(original, modified, history);
}
/**Return code after the fix has been applied.
*
* @param fileName file for which the code should be returned
* @return the code after the fix has been applied
*/
public String getOutput(String fileName) throws Exception {
FileObject toCheck = sourceRoot.getFileObject(fileName);
assertNotNull(toCheck);
DataObject toCheckDO = DataObject.find(toCheck);
EditorCookie ec = toCheckDO.getLookup().lookup(EditorCookie.class);
Document toCheckDocument = ec.openDocument();
return toCheckDocument.getText(0, toCheckDocument.getLength());
}
public static int findText(Document document, String searchText, boolean firstToLast) throws BadLocationException {
int len = document.getLength();
String content = document.getText(0, len);
if(firstToLast)
return content.indexOf(searchText);
else
return content.lastIndexOf(searchText);
}
/** Stores all models created in the StoreGroup into given
* EditableProperties.
* @param editableProperties The properties where to store the
* values.
*/
public void store( EditableProperties editableProperties ) {
for (Map.Entry<String,Object[]> entry : models.entrySet()) {
String key = entry.getKey();
Object[] params = entry.getValue();
if ( params[0] instanceof ButtonModel ) {
ButtonModel model = (ButtonModel)params[0];
boolean value = model.isSelected();
if ( params[2] == Boolean.TRUE ) {
value = !value;
}
editableProperties.setProperty( key, encodeBoolean( value, (Integer)params[1] ) );
}
else if ( params[0] instanceof Document && modifiedDocuments.contains(params[0])) {
Document doc = (Document)params[0];
String txt;
try {
txt = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
txt = ""; // NOI18N
}
editableProperties.setProperty( key, txt );
}
}
}
/**
*
* @param upToOffset If set, complete only up to the given caret offset, otherwise complete
* the full symbol at the offset
*/
private Env getCompletionEnvironment(ParserResult controller, boolean upToOffset)
throws IOException {
// If you invoke code completion while indexing is in progress, the
// completion job (which stores the caret offset) will be delayed until
// indexing is complete - potentially minutes later. When the job
// is finally run we need to make sure the caret position is still valid. (93017)
Document doc = controller.getSnapshot ().getSource ().getDocument (false);
int length = doc != null ? doc.getLength() : (int)controller.getSnapshot ().getSource ().getFileObject().getSize();
if (caretOffset > length) {
caretOffset = length;
}
int offset = caretOffset;
String prefix = null;
//
// TODO - handle the upToOffset parameter
// Look at the parse tree, and find the corresponding end node
// offset...
CodeCompletionHandler completer = getCompletable(controller);
try {
// TODO: use the completion helper to get the contxt
if (completer != null && offset != -1) {
prefix = completer.getPrefix(controller, offset, upToOffset);
}
if (prefix == null && doc != null) {
int[] blk =
org.netbeans.editor.Utilities.getIdentifierBlock((BaseDocument)doc,
offset);
if (blk != null) {
int start = blk[0];
if (start < offset ) {
if (upToOffset) {
prefix = doc.getText(start, offset - start);
} else {
prefix = doc.getText(start, blk[1]-start);
}
}
}
}
} catch (BadLocationException ex) {
ErrorManager.getDefault().notify(ex);
}
return new Env(offset, prefix, controller, completer);
}
/**
* Replace the path component under the caret with the file selected from the completion list.
*
* @param file the selected file.
* @param caretPos
* @param start the start offset of the path component under the caret.
* @param end the end offset of the path component under the caret.
* @throws BadLocationException
*/
private void replacePathComponent(LookupFile file, int caretPos, int start, int end) throws BadLocationException {
final Document doc = myPathTextField.getDocument();
myPathTextField.setSelectionStart(0);
myPathTextField.setSelectionEnd(0);
final String name = file.getName();
boolean toRemoveExistingName;
String prefix = "";
if (caretPos >= start) {
prefix = doc.getText(start, caretPos - start);
if (prefix.length() == 0) {
prefix = doc.getText(start, end - start);
}
if (SystemInfo.isFileSystemCaseSensitive) {
toRemoveExistingName = name.startsWith(prefix) && prefix.length() > 0;
}
else {
toRemoveExistingName = StringUtil.toUpperCase(name).startsWith(StringUtil.toUpperCase(prefix)) && prefix.length() > 0;
}
}
else {
toRemoveExistingName = true;
}
int newPos;
if (toRemoveExistingName) {
doc.remove(start, end - start);
doc.insertString(start, name, doc.getDefaultRootElement().getAttributes());
newPos = start + name.length();
}
else {
doc.insertString(caretPos, name, doc.getDefaultRootElement().getAttributes());
newPos = caretPos + name.length();
}
if (file.isDirectory()) {
if (!myFinder.getSeparator().equals(doc.getText(newPos, 1))) {
doc.insertString(newPos, myFinder.getSeparator(), doc.getDefaultRootElement().getAttributes());
newPos++;
}
}
if (newPos < doc.getLength()) {
if (myFinder.getSeparator().equals(doc.getText(newPos, 1))) {
newPos++;
}
}
myPathTextField.setCaretPosition(newPos);
}
@Override
protected boolean canFilter(JTextComponent component) {
filterPrefix = null;
if (component.getCaret() == null) {
return false;
}
int newOffset = component.getSelectionStart();
if ((queryType & COMPLETION_QUERY_TYPE) != 0) {
if (isTruncated || !isFilterable) {
return false;
}
int offset = Math.min(anchorOffset, caretOffset);
if (offset > -1) {
if (newOffset < offset)
return true;
if (newOffset >= caretOffset) {
try {
Document doc = component.getDocument();
Language language = getCompletableLanguage(doc, caretOffset);
String prefix = doc.getText(offset, newOffset - offset);
filterPrefix = isJavaIdentifierPart(language, prefix) ? prefix : null;
if (filterPrefix != null && filterPrefix.length() == 0)
anchorOffset = newOffset;
} catch (BadLocationException e) {}
return true;
}
}
return false;
} else if (queryType == TOOLTIP_QUERY_TYPE) {
try {
if (newOffset == caretOffset)
filterPrefix = "";
else if (newOffset - caretOffset > 0)
filterPrefix = component.getDocument().getText(caretOffset, newOffset - caretOffset);
else if (newOffset - caretOffset < 0)
//filterPrefix = newOffset > toolTipOffset ? component.getDocument().getText(newOffset, caretOffset - newOffset) : null;
filterPrefix = component.getDocument().getText(newOffset, caretOffset - newOffset);
} catch (BadLocationException ex) {}
return (filterPrefix != null && filterPrefix.indexOf(',') == -1 && filterPrefix.indexOf('(') == -1 && filterPrefix.indexOf(')') == -1); // NOI18N
}
return false;
}
/**
* 文本内容查找定位
* @param key 要查找的字符串
* @param ignoreCase 是否区分大小写
* @param down 查找方向(向上false,向下true)
* @param isFirst 是否从开头开始查找
* @return
*/
public boolean startSegmentFindOrReplaceOperation(JTextArea textArea, String key, boolean ignoreCase, boolean down,boolean isFirst) {
int length = key.length();
Document doc = textArea.getDocument();
int offset = textArea.getCaretPosition();
int charsLeft = doc.getLength() - offset;
if(charsLeft <=0 ){
offset = 0;
charsLeft = doc.getLength() - offset;
}
if (!down) {
offset -= length;
offset--;
charsLeft = offset;
}
if(isFirst){
offset = 0;
charsLeft = doc.getLength() - offset;
}
Segment text = new Segment();
text.setPartialReturn(true);
try {
while (charsLeft > 0) {
doc.getText(offset, length, text);
if ((ignoreCase == true && text.toString().equalsIgnoreCase(key))
|| (ignoreCase == false && text.toString().equals(key))) {
textArea.requestFocus();////焦点,才能能看到效果
textArea.setSelectionStart(offset);
textArea.setSelectionEnd(offset + length);
return true;
}
charsLeft--;
if (down) {
offset++;
} else {
offset--;
}
}
} catch (Exception e) {
}
return false;
}
private void retreiveEditableBlock(CodeCategory category, int index) {
CodeEntry[] entries = codeData.getEditableBlock(category, index).getEntries();
for (CodeEntry e : entries) {
e.setCode(null);
}
int[] blockBounds = getEditBlockBounds(category, index);
Document doc = getDocument(category);
try {
String allCode = doc.getText(blockBounds[0], blockBounds[1]-blockBounds[0]);
if (allCode.trim().equals("")) // NOI18N
return;
StringBuilder buf = new StringBuilder();
int selIndex = -1;
EditableLine nextLine = null;
Iterator<EditableLine> it = getEditInfos(category)[index].lines.iterator();
while (it.hasNext() || nextLine != null) {
EditableLine l = nextLine != null ? nextLine : it.next();
int startPos = l.getPosition().getOffset();
int endPos;
if (it.hasNext()) {
nextLine = it.next();
endPos = nextLine.getPosition().getOffset();
}
else {
nextLine = null;
endPos = blockBounds[1];
}
buf.append(doc.getText(startPos, endPos-startPos));
if (nextLine == null || nextLine.getSelectedIndex() != l.getSelectedIndex()) {
String code = buf.toString().trim();
if (!code.equals("")) // NOI18N
entries[l.getSelectedIndex()].setCode(code);
buf.delete(0, buf.length());
}
}
}
catch (BadLocationException ex) { // should not happen
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
}
}
public void testAddParamValueInXmlView() throws IOException {
initDataObject();
openInXmlView(dObj);
Helper.waitForDispatchThread();
XmlMultiViewEditorSupport editor = (XmlMultiViewEditorSupport)dObj.getCookie(EditorCookie.class);
final Document document = editor.getDocument();
Helper.waitForDispatchThread();
// wait to see the changes in XML view
new StepIterator() {
private int index;
public boolean step() throws Exception {
//test the editor document
String text = document.getText(0,document.getLength());
index = text.lastIndexOf("</context-param>");
return index >= 0;
}
@Override
public void finalCheck() {
assertEquals("Cannot find new context param element in XML view (editor document)", true, index > 0);
try {
document.insertString(index + 16, CONTEXT_PARAM_CYLINDERS, null);
} catch (BadLocationException ex) {
throw new AssertionFailedErrorException("Failed to read the document: ", ex);
}
}
};
openInDesignView(dObj);
Helper.waitForDispatchThread();
new StepIterator() {
private String paramValue;
public boolean step() throws Exception {
// get context params table model
DDBeanTableModel model = getDDBeanModel();
if (model.getRowCount() == 2) {
paramValue = (String) model.getValueAt(1, 0);
return "cylinders".equals(paramValue);
} else {
return false;
}
}
@Override
public void finalCheck() {
assertEquals("Context Params Table wasn't changed: ", "cylinders", paramValue);
}
};
// check if save cookie was created
SaveCookie cookie = (SaveCookie) dObj.getCookie(SaveCookie.class);
assertNotNull("Data Object Not Modified",cookie);
cookie.save();
}
protected String performFixTest(String fileName, String code, int pos, String errorDescriptionToString, String fixDebugString, String goldenFileName, String golden) throws Exception {
prepareTest(fileName, code);
TreePath path = info.getTreeUtilities().pathFor(pos);
List<ErrorDescription> errors = computeErrors(info, path, pos);
ErrorDescription toFix = null;
for (ErrorDescription d : errors) {
if (errorDescriptionToString.equals(d.toString())) {
toFix = d;
break;
}
}
assertNotNull("Error: \"" + errorDescriptionToString + "\" not found. All ErrorDescriptions: " + errors.toString(), toFix);
assertTrue("Must be computed", toFix.getFixes().isComputed());
List<Fix> fixes = toFix.getFixes().getFixes();
List<String> fixNames = new LinkedList<String>();
Fix toApply = null;
for (Fix f : fixes) {
if (fixDebugString.equals(toDebugString(info, f))) {
toApply = f;
}
fixNames.add(toDebugString(info, f));
}
assertNotNull("Cannot find fix to invoke: " + fixNames.toString(), toApply);
toApply.implement();
FileObject toCheck = sourceRoot.getFileObject(goldenFileName);
assertNotNull(toCheck);
DataObject toCheckDO = DataObject.find(toCheck);
EditorCookie ec = toCheckDO.getLookup().lookup(EditorCookie.class);
Document toCheckDocument = ec.openDocument();
String realCode = toCheckDocument.getText(0, toCheckDocument.getLength());
//ignore whitespaces:
realCode = realCode.replaceAll("[ \t\n]+", " ");
if (golden != null) {
assertEquals("The output code does not match the expected code.", golden, realCode);
}
LifecycleManager.getDefault().saveAll();
return realCode;
}