下面列出了javax.swing.text.Position#getOffset ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void generateJavadoc(Document doc, Descriptor desc, Indent ie) throws BadLocationException {
// skip javadoc header /** and tail */ since they were already generated
String content = desc.javadoc;
if(content.endsWith("\n")) {
content = content.substring(0, content.length() - "\n".length());
}
if (content.length() == 0) {
return;
}
Position pos = desc.caret;
int startOffset = pos.getOffset();
doc.insertString(startOffset, content, null);
if (startOffset != pos.getOffset()) {
ie.reindent(startOffset + 1, pos.getOffset());
}
}
public void testGetEndPosition() {
System.out.println("testGetEndPosition");
OutWriter ow = new OutWriter ();
OutputDocument doc = new OutputDocument (ow);
String first = "This is the first string";
String second = "This is the second string, ain't it?";
String third = "This is the third string";
ow.println(first);
ow.println (second);
ow.flush();
Position pos = doc.getEndPosition();
int offset = pos.getOffset();
assertTrue ("End offset should match number of characters written", offset == ow.getLines().getCharCount());
ow.println (third);
ow.flush();
assertTrue ("Document end offset should change after writing more data", offset != pos.getOffset());
assertTrue ("End offset should match number of characters written", pos.getOffset() == ow.getLines().getCharCount());
}
@Override
public void implement() throws Exception {
final BaseDocument doc = context.doc;
final int caretOffset = getOffset(doc);
final String commentText = getCommentText();
final int indexOf = commentText.indexOf(getTypeTemplate());
final EditList editList = getEditList(doc, caretOffset);
final Position typeOffset = editList.createPosition(caretOffset + indexOf);
editList.apply();
if (typeOffset != null && typeOffset.getOffset() != -1) {
JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
if (target != null) {
final int startOffset = typeOffset.getOffset();
final int endOffset = startOffset + getTypeTemplate().length();
if (indexOf != -1 && (endOffset <= doc.getLength())) {
String s = doc.getText(startOffset, getTypeTemplate().length());
if (getTypeTemplate().equals(s)) {
target.select(startOffset, endOffset);
scheduleShowingCompletion();
}
}
}
}
}
static void updateHighlightsOnLine(OffsetsBag bag, BaseDocument doc, Position line, List<ErrorDescription> errorDescriptions) throws IOException {
try {
int rowStart = line.getOffset();
int rowEnd = Utilities.getRowEnd(doc, rowStart);
int rowHighlightStart = Utilities.getRowFirstNonWhite(doc, rowStart);
int rowHighlightEnd = Utilities.getRowLastNonWhite(doc, rowStart) + 1;
if (rowStart <= rowEnd) {
bag.removeHighlights(rowStart, rowEnd, false);
}
if (errorDescriptions != null) {
bag.addAllHighlights(computeHighlights(doc, errorDescriptions).getHighlights(rowHighlightStart, rowHighlightEnd));
}
} catch (BadLocationException ex) {
throw new IOException(ex);
}
}
@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();
}
}
@Override
public void flush() throws IOException {
Reformat reformat = Reformat.get(doc);
reformat.lock();
try {
String text = buffer.toString();
if (text.length() > 0 && offset <= doc.getLength()) {
try {
doc.insertString(offset, text, null);
Position endPos = doc.createPosition(offset + text.length());
reformat.reformat(offset, endPos.getOffset());
int len = endPos.getOffset() - offset;
String reformattedText = doc.getText(offset, len);
doc.remove(offset, len);
writer.write(reformattedText.substring(writtenLen));
writtenLen = len;
} catch (BadLocationException e) {
}
}
} finally {
reformat.unlock();
}
}
AnnotationDescDelegate(BaseDocument doc, Position pos, int length, Annotation anno) {
super(pos.getOffset(),length);
this.pos = pos;
this.delegate = anno;
this.doc = doc;
// update AnnotationDesc.type member
updateAnnotationType();
// forward property changes to AnnotationDesc property changes
l = new PropertyChangeListener() {
public void propertyChange (PropertyChangeEvent evt) {
if (evt.getPropertyName() == null || Annotation.PROP_SHORT_DESCRIPTION.equals(evt.getPropertyName())) {
firePropertyChange(AnnotationDesc.PROP_SHORT_DESCRIPTION, null, null);
}
if (evt.getPropertyName() == null || Annotation.PROP_MOVE_TO_FRONT.equals(evt.getPropertyName())) {
firePropertyChange(AnnotationDesc.PROP_MOVE_TO_FRONT, null, null);
}
if (evt.getPropertyName() == null || Annotation.PROP_ANNOTATION_TYPE.equals(evt.getPropertyName())) {
updateAnnotationType();
firePropertyChange(AnnotationDesc.PROP_ANNOTATION_TYPE, null, null);
}
}
};
delegate.addPropertyChangeListener(l);
}
private int [] addAllHighlightsImpl(PositionsBag bag) {
int changeStart = Integer.MAX_VALUE;
int changeEnd = Integer.MIN_VALUE;
GapList<Position> newMarks = bag.getMarks();
GapList<AttributeSet> newAttributes = bag.getAttributes();
for (int i = 0 ; i + 1 < newMarks.size(); i++) {
Position mark1 = newMarks.get(i);
Position mark2 = newMarks.get(i + 1);
AttributeSet attrSet = newAttributes.get(i);
if (attrSet == null) {
// skip empty highlight
continue;
}
addHighlightImpl(mark1, mark2, attrSet);
if (changeStart == Integer.MAX_VALUE) {
changeStart = mark1.getOffset();
}
changeEnd = mark2.getOffset();
}
if (changeStart != Integer.MAX_VALUE && changeEnd != Integer.MIN_VALUE) {
return new int [] { changeStart, changeEnd };
} else {
return null;
}
}
public void testCustomBounds() throws Exception {
loggingOn();
JEditorPane pane = ViewUpdatesTesting.createPane();
Document doc = pane.getDocument();
doc.insertString(0, "hello\nworld\ngood\nmorning", null);
Position startPos = doc.createPosition(3);
pane.putClientProperty(DocumentView.START_POSITION_PROPERTY, startPos);
pane.modelToView(0); // Force rebuild of VH
doc.insertString(startPos.getOffset(), "a", null);
doc.insertString(startPos.getOffset() - 1, "a", null);
Element line0 = doc.getDefaultRootElement().getElement(0);
Position endPos = doc.createPosition(line0.getEndOffset() + 3); // Middle of line 1
pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, endPos);
pane.modelToView(0); // Force rebuild of VH
TestHighlightsViewFactory testFactory = ViewUpdatesTesting.getTestFactory(pane);
List<TestHighlight> hlts = ViewUpdatesTesting.getHighlightsCopy(testFactory);
int hlStartOffset = startPos.getOffset() + 1;
int hlEndOffset = endPos.getOffset() - 1;
TestHighlight hi = TestHighlight.create(doc, hlStartOffset, hlEndOffset, colorAttrs[0]);
hlts.add(hi);
testFactory.setHighlights(hlts);
testFactory.fireChange(hlStartOffset, hlEndOffset);
pane.modelToView(0); // Force rebuild of VH
doc.insertString(doc.getLength(), "test\ntest2", null);
Position endPos2 = doc.createPosition(doc.getLength() - 3);
pane.putClientProperty(DocumentView.END_POSITION_PROPERTY, endPos2);
pane.modelToView(0); // Force rebuild of VH
doc.remove(endPos2.getOffset() - 2, 3);
pane.putClientProperty(DocumentView.START_POSITION_PROPERTY, null);
pane.modelToView(0); // Force rebuild of VH
}
private static Position[] findTooltipRange(Position[] origin, Position[] matches) {
if (origin == null || matches == null) {
return null;
}
int start = Integer.MAX_VALUE;
int end = -1;
Position sp = null;
Position ep = null;
// See issue #219683: in if-then-elif-else constructs, only the 2 initial pairs
// (start and end of the initial tag/construct) are interesting. For finer control,
// a language SPI has to be created.
for (int i = 0; i < Math.min(matches.length, 4); i += 2) {
Position s = matches[i];
Position e = matches[i+1];
int s2 = s.getOffset();
if (s2 < start) {
sp = s;
start = s2;
}
int e2 = e.getOffset();
if (e2 > end) {
ep = e;
end = e2;
}
}
return new Position[] { sp, ep };
}
public synchronized int getInputEndOffset() {
Position p = inputEndPos;
return p == null ? document.getLength() : p.getOffset();
}
public int compare(Position p1, Position p2) {
return p1.getOffset() - p2.getOffset();
}
public TestAnnotationDesc2(BaseDocument bd, Position position) {
super(position.getOffset(), -1);
this.doc = bd;
this.position = position;
}
private SimpleSection doCreateSimpleSection(final Position pos, final Position end, final String name)
throws /*IllegalArgumentException,*/ BadLocationException {
StyledDocument loadedDoc = null;
loadedDoc = this.editor.getDocument();
final StyledDocument doc = loadedDoc;
final SimpleSectionImpl[] sect = new SimpleSectionImpl[1];
final BadLocationException[] blex = new BadLocationException[1];
Runnable r = new Runnable() {
public void run() {
try {
int where = pos.getOffset();
int offEnd = where +2;
int offStart = where;
if (end != null) {
offEnd = end.getOffset();
offStart = pos.getOffset();
} else {
offStart = where + 1;
offEnd = where + 2;
doc.insertString(where, "\n \n", null); // NOI18N
}
sect[0] = createSimpleSectionImpl(name, PositionBounds.create(offStart, offEnd, GuardedSectionsImpl.this));
sect[0].markGuarded(doc);
} catch (BadLocationException ex) {
blex[0] = ex;
}
}
};
doRunAtomic(doc, r);
if (blex[0] == null) {
synchronized (this.sections) {
sections.put(name, sect[0]);
return (SimpleSection) sect[0].guard;
}
} else {
throw (BadLocationException) new BadLocationException(
"wrong offset", blex[0].offsetRequested() // NOI18N
).initCause(blex[0]);
}
}
private void checkConsistency() {
try {
int docLength = masterDoc.getLength();
assertEquals(docLength, testDoc.getLength());
String masterText = masterDoc.getText(0, docLength);
String testText = testDoc.getText(0, docLength);
assertEquals(masterText, testText);
Element lineRoot = masterDoc.getDefaultRootElement();
Element testLineRoot = testDoc.getDefaultRootElement();
int lineCount = lineRoot.getElementCount();
if (lineCount != testLineRoot.getElementCount()) {
fail("Line count " + testLineRoot.getElementCount()
+ " != " + lineCount);
}
// Compare line boundaries
for (int i = 0; i < lineCount; i++) {
Element masterLine = lineRoot.getElement(i);
Element testLine = testLineRoot.getElement(i);
if (masterLine.getStartOffset() != testLine.getStartOffset()) {
fail("Start of line " + i + ": Offset " + testLine.getStartOffset()
+ " != " + masterLine.getStartOffset());
}
if (masterLine.getEndOffset() != testLine.getEndOffset()) {
fail("End of line " + i + ": Offset " + testLine.getEndOffset()
+ " != " + masterLine.getEndOffset());
}
}
int positionCount = masterPositions.size();
for (int i = 0; i < positionCount; i++) {
Position masterPos = (Position)masterPositions.get(i);
Position testPos = (Position)testPositions.get(i);
if (masterPos.getOffset() != testPos.getOffset()) {
fail("Tested position " + (i + 1) + " of " + positionCount
+ ": " + testPos.getOffset()
+ " != " + masterPos.getOffset());
}
}
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
}
private int getBlockEndOffset(){
Position pos = (Position) getFindProperties().get(FIND_BLOCK_SEARCH_END);
return (pos != null) ? pos.getOffset() : -1;
}
/** Create new interior guarded section at a specified place.
* @param pos section to create the new one after
* @param name the name of the new section
* @exception IllegalArgumentException if the name is already in use
* @exception BadLocationException if it is not possible to create a
* new guarded section here
*/
private InteriorSection doCreateInteriorSection(final Position pos,
final String name)
throws IllegalArgumentException, BadLocationException {
StyledDocument loadedDoc = null;
loadedDoc = this.editor.getDocument();
final StyledDocument doc = loadedDoc;
final InteriorSectionImpl[] sect = new InteriorSectionImpl[1];
final BadLocationException[] blex = new BadLocationException[1];
Runnable r = new Runnable() {
public void run() {
try {
int where = pos.getOffset();
doc.insertString(where, "\n \n \n \n", null); // NOI18N
sect[0] = createInteriorSectionImpl(
name,
PositionBounds.create(where + 1, where + 2, GuardedSectionsImpl.this),
PositionBounds.createBodyBounds(where + 3, where + 4, GuardedSectionsImpl.this),
PositionBounds.create(where + 5, where + 6, GuardedSectionsImpl.this)
);
sections.put(sect[0].getName(), sect[0]);
sect[0].markGuarded(doc);
} catch (BadLocationException ex) {
blex[0] = ex;
}
}
};
doRunAtomic(doc, r);
if (blex[0] == null) {
synchronized (this.sections) {
sections.put(name, sect[0]);
return (InteriorSection) sect[0].guard;
}
} else {
throw (BadLocationException) new BadLocationException(
"wrong offset", blex[0].offsetRequested() // NOI18N
).initCause(blex[0]);
}
}
FindReplaceResult findReplaceImpl(String replaceExp,
Map<String, Object> props, boolean oppositeDir, JTextComponent c) {
incSearchReset();
props = getValidFindProperties(props);
boolean back = isBackSearch(props, oppositeDir);
if (props.get(FIND_WHAT) == null || !(props.get(FIND_WHAT) instanceof String)) {
return null;
}
String findWhat = (String) props.get(FIND_WHAT);
if (c != null) {
ComponentUtils.clearStatusText(c);
Caret caret = c.getCaret();
int dotPos = caret.getDot();
if (findMatches(c.getSelectedText(), props)) {
Object dp = props.get(FIND_BACKWARD_SEARCH);
boolean direction = (dp != null) ? ((Boolean)dp).booleanValue() : false;
if (dotPos == (oppositeDir ^ direction ? c.getSelectionEnd() : c.getSelectionStart())) {
dotPos += (oppositeDir ^ direction ? -1 : 1);
}
if (replaceExp != null) {
if (oppositeDir ^ direction) {
dotPos = c.getSelectionEnd();
} else {
dotPos = c.getSelectionStart();
}
}
}
Boolean b = (Boolean)props.get(FIND_BLOCK_SEARCH);
boolean blockSearch = (b != null && b.booleanValue());
Position blockStartPos = (Position) props.get(FIND_BLOCK_SEARCH_START);
int blockSearchStart = (blockStartPos != null) ? blockStartPos.getOffset() : -1;
int blockSearchEnd = getBlockEndOffset();
boolean backSearch = Boolean.TRUE.equals(props.get(FIND_BACKWARD_SEARCH));
if (backSearch) {
blockSearchEnd = dotPos;
dotPos = 0;
}
try {
FindReplaceResult result = findReplaceInBlock(replaceExp, c, dotPos,
(blockSearch && blockSearchStart > -1) ? blockSearchStart : 0,
(blockSearch && blockSearchEnd > 0) ? blockSearchEnd : backSearch ? blockSearchEnd : -1,
props, oppositeDir);
if (result != null && result.hasErrorMsg()) {
ComponentUtils.setStatusText(c, result.getErrorMsg());
c.getCaret().setDot(c.getCaret().getDot());
return null;
}
int[] blk = null;
if (result != null){
blk = result.getFoundPositions();
}
if (blk != null) {
if (Boolean.TRUE.equals(props.get(EditorFindSupport.ADD_MULTICARET))) {
addCaretSelectText(c, blk[0], blk[1], back);
} else {
selectText(c, blk[0], blk[1], back);
}
String msg = NbBundle.getMessage(EditorFindSupport.class, FOUND_LOCALE, findWhat, DocUtils.debugPosition(c.getDocument(), Integer.valueOf(blk[0])));
// String msg = exp + NbBundle.getMessage(EditorFindSupport.class, FOUND_LOCALE)
// + ' ' + DocUtils.debugPosition(c.getDocument(), blk[0]);
if (blk[2] == 1) { // wrap was done
msg += "; "; // NOI18N
if (blockSearch && blockSearchEnd>0 && blockSearchStart >-1){
msg += back ? NbBundle.getMessage(EditorFindSupport.class, WRAP_BLOCK_END_LOCALE)
: NbBundle.getMessage(EditorFindSupport.class, WRAP_BLOCK_START_LOCALE);
}else{
msg += back ? NbBundle.getMessage(EditorFindSupport.class, WRAP_END_LOCALE)
: NbBundle.getMessage(EditorFindSupport.class, WRAP_START_LOCALE);
}
ComponentUtils.setStatusText(c, msg, IMPORTANCE_FIND_OR_REPLACE);
c.getToolkit().beep();
} else {
ComponentUtils.setStatusText(c, msg, IMPORTANCE_FIND_OR_REPLACE);
}
return result;
} else { // not found
ComponentUtils.setStatusText(c, NbBundle.getMessage(
EditorFindSupport.class, NOT_FOUND_LOCALE, findWhat), IMPORTANCE_FIND_OR_REPLACE);
// issue 14189 - selection was not removed
c.getCaret().setDot(c.getCaret().getDot());
}
} catch (BadLocationException e) {
LOG.log(Level.WARNING, e.getMessage(), e);
}
}
return null;
}
/**
* Starting offset of the area to be reformatted or reindented.
* <br/>
* The value gets updated accordingly when the reformatter performs modifications
* in the affected area.
*/
public int endOffset() {
Position endPos = mimeItem.handler().endPos();
return (endPos != null) ? endPos.getOffset() : -1;
}
/**
* Starting offset of the area to be reformatted or reindented.
* <br/>
* The value gets updated accordingly when the reformatter performs modifications
* in the affected area.
*/
public int startOffset() {
Position startPos = mimeItem.handler().startPos();
return (startPos != null) ? startPos.getOffset() : -1;
}