Path: blob/master/src/java.base/share/classes/java/text/BreakIterator.java
41152 views
/*1* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved27* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved28*29* The original version of this source code and documentation30* is copyrighted and owned by Taligent, Inc., a wholly-owned31* subsidiary of IBM. These materials are provided under terms32* of a License Agreement between Taligent and Sun. This technology33* is protected by multiple US and International patents.34*35* This notice and attribution to Taligent may not be removed.36* Taligent is a registered trademark of Taligent, Inc.37*38*/3940package java.text;4142import java.lang.ref.SoftReference;43import java.text.spi.BreakIteratorProvider;44import java.util.Locale;45import sun.util.locale.provider.LocaleProviderAdapter;46import sun.util.locale.provider.LocaleServiceProviderPool;474849/**50* The {@code BreakIterator} class implements methods for finding51* the location of boundaries in text. Instances of {@code BreakIterator}52* maintain a current position and scan over text53* returning the index of characters where boundaries occur.54* Internally, {@code BreakIterator} scans text using a55* {@code CharacterIterator}, and is thus able to scan text held56* by any object implementing that protocol. A {@code StringCharacterIterator}57* is used to scan {@code String} objects passed to {@code setText}.58*59* <p>60* You use the factory methods provided by this class to create61* instances of various types of break iterators. In particular,62* use {@code getWordInstance}, {@code getLineInstance},63* {@code getSentenceInstance}, and {@code getCharacterInstance}64* to create {@code BreakIterator}s that perform65* word, line, sentence, and character boundary analysis respectively.66* A single {@code BreakIterator} can work only on one unit67* (word, line, sentence, and so on). You must use a different iterator68* for each unit boundary analysis you wish to perform.69*70* <p><a id="line"></a>71* Line boundary analysis determines where a text string can be72* broken when line-wrapping. The mechanism correctly handles73* punctuation and hyphenated words. Actual line breaking needs74* to also consider the available line width and is handled by75* higher-level software.76*77* <p><a id="sentence"></a>78* Sentence boundary analysis allows selection with correct interpretation79* of periods within numbers and abbreviations, and trailing punctuation80* marks such as quotation marks and parentheses.81*82* <p><a id="word"></a>83* Word boundary analysis is used by search and replace functions, as84* well as within text editing applications that allow the user to85* select words with a double click. Word selection provides correct86* interpretation of punctuation marks within and following87* words. Characters that are not part of a word, such as symbols88* or punctuation marks, have word-breaks on both sides.89*90* <p><a id="character"></a>91* Character boundary analysis allows users to interact with characters92* as they expect to, for example, when moving the cursor through a text93* string. Character boundary analysis provides correct navigation94* through character strings, regardless of how the character is stored.95* The boundaries returned may be those of supplementary characters,96* combining character sequences, or ligature clusters.97* For example, an accented character might be stored as a base character98* and a diacritical mark. What users consider to be a character can99* differ between languages.100*101* <p>102* The {@code BreakIterator} instances returned by the factory methods103* of this class are intended for use with natural languages only, not for104* programming language text. It is however possible to define subclasses105* that tokenize a programming language.106*107* <P>108* <strong>Examples</strong>:<P>109* Creating and using text boundaries:110* <blockquote>111* <pre>112* public static void main(String args[]) {113* if (args.length == 1) {114* String stringToExamine = args[0];115* //print each word in order116* BreakIterator boundary = BreakIterator.getWordInstance();117* boundary.setText(stringToExamine);118* printEachForward(boundary, stringToExamine);119* //print each sentence in reverse order120* boundary = BreakIterator.getSentenceInstance(Locale.US);121* boundary.setText(stringToExamine);122* printEachBackward(boundary, stringToExamine);123* printFirst(boundary, stringToExamine);124* printLast(boundary, stringToExamine);125* }126* }127* </pre>128* </blockquote>129*130* Print each element in order:131* <blockquote>132* <pre>133* public static void printEachForward(BreakIterator boundary, String source) {134* int start = boundary.first();135* for (int end = boundary.next();136* end != BreakIterator.DONE;137* start = end, end = boundary.next()) {138* System.out.println(source.substring(start,end));139* }140* }141* </pre>142* </blockquote>143*144* Print each element in reverse order:145* <blockquote>146* <pre>147* public static void printEachBackward(BreakIterator boundary, String source) {148* int end = boundary.last();149* for (int start = boundary.previous();150* start != BreakIterator.DONE;151* end = start, start = boundary.previous()) {152* System.out.println(source.substring(start,end));153* }154* }155* </pre>156* </blockquote>157*158* Print first element:159* <blockquote>160* <pre>161* public static void printFirst(BreakIterator boundary, String source) {162* int start = boundary.first();163* int end = boundary.next();164* System.out.println(source.substring(start,end));165* }166* </pre>167* </blockquote>168*169* Print last element:170* <blockquote>171* <pre>172* public static void printLast(BreakIterator boundary, String source) {173* int end = boundary.last();174* int start = boundary.previous();175* System.out.println(source.substring(start,end));176* }177* </pre>178* </blockquote>179*180* Print the element at a specified position:181* <blockquote>182* <pre>183* public static void printAt(BreakIterator boundary, int pos, String source) {184* int end = boundary.following(pos);185* int start = boundary.previous();186* System.out.println(source.substring(start,end));187* }188* </pre>189* </blockquote>190*191* Find the next word:192* <blockquote>193* <pre>{@code194* public static int nextWordStartAfter(int pos, String text) {195* BreakIterator wb = BreakIterator.getWordInstance();196* wb.setText(text);197* int last = wb.following(pos);198* int current = wb.next();199* while (current != BreakIterator.DONE) {200* for (int p = last; p < current; p++) {201* if (Character.isLetter(text.codePointAt(p)))202* return last;203* }204* last = current;205* current = wb.next();206* }207* return BreakIterator.DONE;208* }209* }</pre>210* (The iterator returned by BreakIterator.getWordInstance() is unique in that211* the break positions it returns don't represent both the start and end of the212* thing being iterated over. That is, a sentence-break iterator returns breaks213* that each represent the end of one sentence and the beginning of the next.214* With the word-break iterator, the characters between two boundaries might be a215* word, or they might be the punctuation or whitespace between two words. The216* above code uses a simple heuristic to determine which boundary is the beginning217* of a word: If the characters between this boundary and the next boundary218* include at least one letter (this can be an alphabetical letter, a CJK ideograph,219* a Hangul syllable, a Kana character, etc.), then the text between this boundary220* and the next is a word; otherwise, it's the material between words.)221* </blockquote>222*223* @since 1.1224* @see CharacterIterator225*226*/227228public abstract class BreakIterator implements Cloneable229{230/**231* Constructor. BreakIterator is stateless and has no default behavior.232*/233protected BreakIterator()234{235}236237/**238* Create a copy of this iterator239* @return A copy of this240*/241@Override242public Object clone()243{244try {245return super.clone();246}247catch (CloneNotSupportedException e) {248throw new InternalError(e);249}250}251252/**253* DONE is returned by previous(), next(), next(int), preceding(int)254* and following(int) when either the first or last text boundary has been255* reached.256*/257public static final int DONE = -1;258259/**260* Returns the first boundary. The iterator's current position is set261* to the first text boundary.262* @return The character index of the first text boundary.263*/264public abstract int first();265266/**267* Returns the last boundary. The iterator's current position is set268* to the last text boundary.269* @return The character index of the last text boundary.270*/271public abstract int last();272273/**274* Returns the nth boundary from the current boundary. If either275* the first or last text boundary has been reached, it returns276* {@code BreakIterator.DONE} and the current position is set to either277* the first or last text boundary depending on which one is reached. Otherwise,278* the iterator's current position is set to the new boundary.279* For example, if the iterator's current position is the mth text boundary280* and three more boundaries exist from the current boundary to the last text281* boundary, the next(2) call will return m + 2. The new text position is set282* to the (m + 2)th text boundary. A next(4) call would return283* {@code BreakIterator.DONE} and the last text boundary would become the284* new text position.285* @param n which boundary to return. A value of 0286* does nothing. Negative values move to previous boundaries287* and positive values move to later boundaries.288* @return The character index of the nth boundary from the current position289* or {@code BreakIterator.DONE} if either first or last text boundary290* has been reached.291*/292public abstract int next(int n);293294/**295* Returns the boundary following the current boundary. If the current boundary296* is the last text boundary, it returns {@code BreakIterator.DONE} and297* the iterator's current position is unchanged. Otherwise, the iterator's298* current position is set to the boundary following the current boundary.299* @return The character index of the next text boundary or300* {@code BreakIterator.DONE} if the current boundary is the last text301* boundary.302* Equivalent to next(1).303* @see #next(int)304*/305public abstract int next();306307/**308* Returns the boundary preceding the current boundary. If the current boundary309* is the first text boundary, it returns {@code BreakIterator.DONE} and310* the iterator's current position is unchanged. Otherwise, the iterator's311* current position is set to the boundary preceding the current boundary.312* @return The character index of the previous text boundary or313* {@code BreakIterator.DONE} if the current boundary is the first text314* boundary.315*/316public abstract int previous();317318/**319* Returns the first boundary following the specified character offset. If the320* specified offset is equal to the last text boundary, it returns321* {@code BreakIterator.DONE} and the iterator's current position is unchanged.322* Otherwise, the iterator's current position is set to the returned boundary.323* The value returned is always greater than the offset or the value324* {@code BreakIterator.DONE}.325* @param offset the character offset to begin scanning.326* @return The first boundary after the specified offset or327* {@code BreakIterator.DONE} if the last text boundary is passed in328* as the offset.329* @throws IllegalArgumentException if the specified offset is less than330* the first text boundary or greater than the last text boundary.331*/332public abstract int following(int offset);333334/**335* Returns the last boundary preceding the specified character offset. If the336* specified offset is equal to the first text boundary, it returns337* {@code BreakIterator.DONE} and the iterator's current position is unchanged.338* Otherwise, the iterator's current position is set to the returned boundary.339* The value returned is always less than the offset or the value340* {@code BreakIterator.DONE}.341* @param offset the character offset to begin scanning.342* @return The last boundary before the specified offset or343* {@code BreakIterator.DONE} if the first text boundary is passed in344* as the offset.345* @throws IllegalArgumentException if the specified offset is less than346* the first text boundary or greater than the last text boundary.347* @since 1.2348*/349public int preceding(int offset) {350// NOTE: This implementation is here solely because we can't add new351// abstract methods to an existing class. There is almost ALWAYS a352// better, faster way to do this.353int pos = following(offset);354while (pos >= offset && pos != DONE) {355pos = previous();356}357return pos;358}359360/**361* Returns true if the specified character offset is a text boundary.362* @param offset the character offset to check.363* @return {@code true} if "offset" is a boundary position,364* {@code false} otherwise.365* @throws IllegalArgumentException if the specified offset is less than366* the first text boundary or greater than the last text boundary.367* @since 1.2368*/369public boolean isBoundary(int offset) {370// NOTE: This implementation probably is wrong for most situations371// because it fails to take into account the possibility that a372// CharacterIterator passed to setText() may not have a begin offset373// of 0. But since the abstract BreakIterator doesn't have that374// knowledge, it assumes the begin offset is 0. If you subclass375// BreakIterator, copy the SimpleTextBoundary implementation of this376// function into your subclass. [This should have been abstract at377// this level, but it's too late to fix that now.]378if (offset == 0) {379return true;380}381int boundary = following(offset - 1);382if (boundary == DONE) {383throw new IllegalArgumentException();384}385return boundary == offset;386}387388/**389* Returns character index of the text boundary that was most390* recently returned by next(), next(int), previous(), first(), last(),391* following(int) or preceding(int). If any of these methods returns392* {@code BreakIterator.DONE} because either first or last text boundary393* has been reached, it returns the first or last text boundary depending on394* which one is reached.395* @return The text boundary returned from the above methods, first or last396* text boundary.397* @see #next()398* @see #next(int)399* @see #previous()400* @see #first()401* @see #last()402* @see #following(int)403* @see #preceding(int)404*/405public abstract int current();406407/**408* Get the text being scanned409* @return the text being scanned410*/411public abstract CharacterIterator getText();412413/**414* Set a new text string to be scanned. The current scan415* position is reset to first().416* @param newText new text to scan.417*/418public void setText(String newText)419{420setText(new StringCharacterIterator(newText));421}422423/**424* Set a new text for scanning. The current scan425* position is reset to first().426* @param newText new text to scan.427*/428public abstract void setText(CharacterIterator newText);429430private static final int CHARACTER_INDEX = 0;431private static final int WORD_INDEX = 1;432private static final int LINE_INDEX = 2;433private static final int SENTENCE_INDEX = 3;434435@SuppressWarnings("unchecked")436private static final SoftReference<BreakIteratorCache>[] iterCache = (SoftReference<BreakIteratorCache>[]) new SoftReference<?>[4];437438/**439* Returns a new {@code BreakIterator} instance440* for <a href="BreakIterator.html#word">word breaks</a>441* for the {@linkplain Locale#getDefault() default locale}.442* @return A break iterator for word breaks443*/444public static BreakIterator getWordInstance()445{446return getWordInstance(Locale.getDefault());447}448449/**450* Returns a new {@code BreakIterator} instance451* for <a href="BreakIterator.html#word">word breaks</a>452* for the given locale.453* @param locale the desired locale454* @return A break iterator for word breaks455* @throws NullPointerException if {@code locale} is null456*/457public static BreakIterator getWordInstance(Locale locale)458{459return getBreakInstance(locale, WORD_INDEX);460}461462/**463* Returns a new {@code BreakIterator} instance464* for <a href="BreakIterator.html#line">line breaks</a>465* for the {@linkplain Locale#getDefault() default locale}.466* @return A break iterator for line breaks467*/468public static BreakIterator getLineInstance()469{470return getLineInstance(Locale.getDefault());471}472473/**474* Returns a new {@code BreakIterator} instance475* for <a href="BreakIterator.html#line">line breaks</a>476* for the given locale.477* @param locale the desired locale478* @return A break iterator for line breaks479* @throws NullPointerException if {@code locale} is null480*/481public static BreakIterator getLineInstance(Locale locale)482{483return getBreakInstance(locale, LINE_INDEX);484}485486/**487* Returns a new {@code BreakIterator} instance488* for <a href="BreakIterator.html#character">character breaks</a>489* for the {@linkplain Locale#getDefault() default locale}.490* @return A break iterator for character breaks491*/492public static BreakIterator getCharacterInstance()493{494return getCharacterInstance(Locale.getDefault());495}496497/**498* Returns a new {@code BreakIterator} instance499* for <a href="BreakIterator.html#character">character breaks</a>500* for the given locale.501* @param locale the desired locale502* @return A break iterator for character breaks503* @throws NullPointerException if {@code locale} is null504*/505public static BreakIterator getCharacterInstance(Locale locale)506{507return getBreakInstance(locale, CHARACTER_INDEX);508}509510/**511* Returns a new {@code BreakIterator} instance512* for <a href="BreakIterator.html#sentence">sentence breaks</a>513* for the {@linkplain Locale#getDefault() default locale}.514* @return A break iterator for sentence breaks515*/516public static BreakIterator getSentenceInstance()517{518return getSentenceInstance(Locale.getDefault());519}520521/**522* Returns a new {@code BreakIterator} instance523* for <a href="BreakIterator.html#sentence">sentence breaks</a>524* for the given locale.525* @param locale the desired locale526* @return A break iterator for sentence breaks527* @throws NullPointerException if {@code locale} is null528*/529public static BreakIterator getSentenceInstance(Locale locale)530{531return getBreakInstance(locale, SENTENCE_INDEX);532}533534private static BreakIterator getBreakInstance(Locale locale, int type) {535if (iterCache[type] != null) {536BreakIteratorCache cache = iterCache[type].get();537if (cache != null) {538if (cache.getLocale().equals(locale)) {539return cache.createBreakInstance();540}541}542}543544BreakIterator result = createBreakInstance(locale, type);545BreakIteratorCache cache = new BreakIteratorCache(locale, result);546iterCache[type] = new SoftReference<>(cache);547return result;548}549550private static BreakIterator createBreakInstance(Locale locale,551int type) {552LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(BreakIteratorProvider.class, locale);553BreakIterator iterator = createBreakInstance(adapter, locale, type);554if (iterator == null) {555iterator = createBreakInstance(LocaleProviderAdapter.forJRE(), locale, type);556}557return iterator;558}559560private static BreakIterator createBreakInstance(LocaleProviderAdapter adapter, Locale locale, int type) {561BreakIteratorProvider breakIteratorProvider = adapter.getBreakIteratorProvider();562return switch (type) {563case CHARACTER_INDEX -> breakIteratorProvider.getCharacterInstance(locale);564case WORD_INDEX -> breakIteratorProvider.getWordInstance(locale);565case LINE_INDEX -> breakIteratorProvider.getLineInstance(locale);566case SENTENCE_INDEX -> breakIteratorProvider.getSentenceInstance(locale);567default -> null;568};569}570571/**572* Returns an array of all locales for which the573* {@code get*Instance} methods of this class can return574* localized instances.575* The returned array represents the union of locales supported by the Java576* runtime and by installed577* {@link java.text.spi.BreakIteratorProvider BreakIteratorProvider} implementations.578* It must contain at least a {@code Locale}579* instance equal to {@link java.util.Locale#US Locale.US}.580*581* @return An array of locales for which localized582* {@code BreakIterator} instances are available.583*/584public static synchronized Locale[] getAvailableLocales()585{586LocaleServiceProviderPool pool =587LocaleServiceProviderPool.getPool(BreakIteratorProvider.class);588return pool.getAvailableLocales();589}590591private static final class BreakIteratorCache {592593private BreakIterator iter;594private Locale locale;595596BreakIteratorCache(Locale locale, BreakIterator iter) {597this.locale = locale;598this.iter = (BreakIterator) iter.clone();599}600601Locale getLocale() {602return locale;603}604605BreakIterator createBreakInstance() {606return (BreakIterator) iter.clone();607}608}609}610611612