/** Replaces the current word token * @param newWord The new word to replace the misspelled one */ public void replaceWord(String newWord) { if (currentWordPos != -1) { try { document.remove(currentWordPos, currentWordEnd - currentWordPos); document.insertString(currentWordPos, newWord, null); //Need to reset the segment document.getText(0, document.getLength(), text); } catch (BadLocationException ex) { throw new RuntimeException(ex.getMessage()); } //Position after the newly replaced word(s) first = true; currentWordPos = getNextWordStart(text, currentWordPos + newWord.length()); if (currentWordPos != -1) { currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd); sentenceIterator.setText(text); sentenceIterator.following(currentWordPos); } else moreTokens = false; } }
/** * Creates a new DocumentWordTokenizer to work on a document * @param document The document to spell check */ public DocumentWordTokenizer(Document document) { this.document = document; //Create a text segment over the entire document text = new Segment(); sentenceIterator = BreakIterator.getSentenceInstance(); try { document.getText(0, document.getLength(), text); sentenceIterator.setText(text); // robert: use text.getBeginIndex(), not 0, for segment's first offset currentWordPos = getNextWordStart(text, text.getBeginIndex()); //If the current word pos is -1 then the string was all white space if (currentWordPos != -1) { currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd); } else { moreTokens = false; } } catch (BadLocationException ex) { moreTokens = false; } }
if (!first) { currentWordPos = nextWordPos; currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd + 1);
/** * Sets the current word position at the start of the word containing * the char at position pos. This way a call to nextWord() will return * this word. * * @param pos position in the word we want to set as current. */ public void posStartFullWordFrom(int pos){ currentWordPos=text.getBeginIndex(); if(pos>text.getEndIndex()) pos=text.getEndIndex(); for (char ch = text.setIndex(pos); ch != Segment.DONE; ch = text.previous()) { if (!Character.isLetterOrDigit(ch)) { if (ch == '-' || ch == '\'') { // handle ' and - inside words char ch2 = text.previous(); text.next(); if (ch2 != Segment.DONE && Character.isLetterOrDigit(ch2)) continue; } currentWordPos=text.getIndex()+1; break; } } //System.out.println("CurPos:"+currentWordPos); if(currentWordPos==0) first=true; moreTokens=true; currentWordEnd = getNextWordEnd(text, currentWordPos); nextWordPos = getNextWordStart(text, currentWordEnd + 1); }