2 * This file is part of lanterna (http://code.google.com/p/lanterna/).
4 * lanterna is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 * Copyright (C) 2010-2015 Martin
19 package com
.googlecode
.lanterna
;
21 import java
.util
.ArrayList
;
22 import java
.util
.Arrays
;
23 import java
.util
.LinkedList
;
24 import java
.util
.List
;
27 * This class contains a number of utility methods for analyzing characters and strings in a terminal context. The main
28 * purpose is to make it easier to work with text that may or may not contain double-width text characters, such as CJK
29 * (Chinese, Japanese, Korean) and other special symbols. This class assumes those are all double-width and in case the
30 * terminal (-emulator) chooses to draw them (somehow) as single-column then all the calculations in this class will be
31 * wrong. It seems safe to assume what this class considers double-width really is taking up two columns though.
35 public class TerminalTextUtils
{
36 private TerminalTextUtils() {
40 * Given a character, is this character considered to be a CJK character?
41 * Shamelessly stolen from
42 * <a href="http://stackoverflow.com/questions/1499804/how-can-i-detect-japanese-text-in-a-java-string">StackOverflow</a>
43 * where it was contributed by user Rakesh N
44 * @param c Character to test
45 * @return {@code true} if the character is a CJK character
48 public static boolean isCharCJK(final char c
) {
49 Character
.UnicodeBlock unicodeBlock
= Character
.UnicodeBlock
.of(c
);
50 return (unicodeBlock
== Character
.UnicodeBlock
.HIRAGANA
)
51 || (unicodeBlock
== Character
.UnicodeBlock
.KATAKANA
)
52 || (unicodeBlock
== Character
.UnicodeBlock
.KATAKANA_PHONETIC_EXTENSIONS
)
53 || (unicodeBlock
== Character
.UnicodeBlock
.HANGUL_COMPATIBILITY_JAMO
)
54 || (unicodeBlock
== Character
.UnicodeBlock
.HANGUL_JAMO
)
55 || (unicodeBlock
== Character
.UnicodeBlock
.HANGUL_SYLLABLES
)
56 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_UNIFIED_IDEOGRAPHS
)
57 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
)
58 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
)
59 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_COMPATIBILITY_FORMS
)
60 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_COMPATIBILITY_IDEOGRAPHS
)
61 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_RADICALS_SUPPLEMENT
)
62 || (unicodeBlock
== Character
.UnicodeBlock
.CJK_SYMBOLS_AND_PUNCTUATION
)
63 || (unicodeBlock
== Character
.UnicodeBlock
.ENCLOSED_CJK_LETTERS_AND_MONTHS
)
64 || (unicodeBlock
== Character
.UnicodeBlock
.HALFWIDTH_AND_FULLWIDTH_FORMS
&& c
< 0xFF61); //The magic number here is the separating index between full-width and half-width
68 * Checks if a character is expected to be taking up two columns if printed to a terminal. This will generally be
69 * {@code true} for CJK (Chinese, Japanese and Korean) characters.
70 * @param c Character to test if it's double-width when printed to a terminal
71 * @return {@code true} if this character is expected to be taking up two columns when printed to the terminal,
72 * otherwise {@code false}
74 public static boolean isCharDoubleWidth(final char c
) {
79 * @deprecated Call {@code getColumnWidth(s)} instead
82 public static int getTrueWidth(String s
) {
83 return getColumnWidth(s
);
87 * Given a string, returns how many columns this string would need to occupy in a terminal, taking into account that
88 * CJK characters takes up two columns.
89 * @param s String to check length
90 * @return Number of actual terminal columns the string would occupy
92 public static int getColumnWidth(String s
) {
93 return getColumnIndex(s
, s
.length());
97 * Given a string and a character index inside that string, find out what the column index of that character would
98 * be if printed in a terminal. If the string only contains non-CJK characters then the returned value will be same
99 * as {@code stringCharacterIndex}, but if there are CJK characters the value will be different due to CJK
100 * characters taking up two columns in width. If the character at the index in the string is a CJK character itself,
101 * the returned value will be the index of the left-side of character.
102 * @param s String to translate the index from
103 * @param stringCharacterIndex Index within the string to get the terminal column index of
104 * @return Index of the character inside the String at {@code stringCharacterIndex} when it has been writted to a
106 * @throws StringIndexOutOfBoundsException if the index given is outside the String length or negative
108 public static int getColumnIndex(String s
, int stringCharacterIndex
) throws StringIndexOutOfBoundsException
{
110 for(int i
= 0; i
< stringCharacterIndex
; i
++) {
111 if(isCharCJK(s
.charAt(i
))) {
120 * This method does the reverse of getColumnIndex, given a String and imagining it has been printed out to the
121 * top-left corner of a terminal, in the column specified by {@code columnIndex}, what is the index of that
122 * character in the string. If the string contains no CJK characters, this will always be the same as
123 * {@code columnIndex}. If the index specified is the right column of a CJK character, the index is the same as if
124 * the column was the left column. So calling {@code getStringCharacterIndex("英", 0)} and
125 * {@code getStringCharacterIndex("英", 1)} will both return 0.
126 * @param s String to translate the index to
127 * @param columnIndex Column index of the string written to a terminal
128 * @return The index in the string of the character in terminal column {@code columnIndex}
130 public static int getStringCharacterIndex(String s
, int columnIndex
) {
133 while(counter
< columnIndex
) {
134 if(isCharCJK(s
.charAt(index
++))) {
136 if(counter
== columnIndex
) {
146 * Given a string that may or may not contain CJK characters, returns the substring which will fit inside
147 * <code>availableColumnSpace</code> columns. This method does not handle special cases like tab or new-line.
149 * Calling this method is the same as calling {@code fitString(string, 0, availableColumnSpace)}.
150 * @param string The string to fit inside the availableColumnSpace
151 * @param availableColumnSpace Number of columns to fit the string inside
152 * @return The whole or part of the input string which will fit inside the supplied availableColumnSpace
154 public static String
fitString(String string
, int availableColumnSpace
) {
155 return fitString(string
, 0, availableColumnSpace
);
159 * Given a string that may or may not contain CJK characters, returns the substring which will fit inside
160 * <code>availableColumnSpace</code> columns. This method does not handle special cases like tab or new-line.
162 * This overload has a {@code fromColumn} parameter that specified where inside the string to start fitting. Please
163 * notice that {@code fromColumn} is not a character index inside the string, but a column index as if the string
164 * has been printed from the left-most side of the terminal. So if the string is "日本語", fromColumn set to 1 will
165 * not starting counting from the second character ("本") in the string but from the CJK filler character belonging
166 * to "日". If you want to count from a particular character index inside the string, please pass in a substring
167 * and use fromColumn set to 0.
168 * @param string The string to fit inside the availableColumnSpace
169 * @param fromColumn From what column of the input string to start fitting (see description above!)
170 * @param availableColumnSpace Number of columns to fit the string inside
171 * @return The whole or part of the input string which will fit inside the supplied availableColumnSpace
173 public static String
fitString(String string
, int fromColumn
, int availableColumnSpace
) {
174 if(availableColumnSpace
<= 0) {
178 StringBuilder bob
= new StringBuilder();
181 while(index
< string
.length() && column
< fromColumn
) {
182 char c
= string
.charAt(index
++);
183 column
+= TerminalTextUtils
.isCharCJK(c
) ?
2 : 1;
185 if(column
> fromColumn
) {
187 availableColumnSpace
--;
190 while(availableColumnSpace
> 0 && index
< string
.length()) {
191 char c
= string
.charAt(index
++);
192 availableColumnSpace
-= TerminalTextUtils
.isCharCJK(c
) ?
2 : 1;
193 if(availableColumnSpace
< 0) {
200 return bob
.toString();
204 * This method will calculate word wrappings given a number of lines of text and how wide the text can be printed.
205 * The result is a list of new rows where word-wrapping was applied.
206 * @param maxWidth Maximum number of columns that can be used before word-wrapping is applied, if <= 0 then the
207 * lines will be returned unchanged
208 * @param lines Input text
209 * @return The input text word-wrapped at {@code maxWidth}; this may contain more rows than the input text
211 public static List
<String
> getWordWrappedText(int maxWidth
, String
... lines
) {
214 return Arrays
.asList(lines
);
217 List
<String
> result
= new ArrayList
<String
>();
218 LinkedList
<String
> linesToBeWrapped
= new LinkedList
<String
>(Arrays
.asList(lines
));
219 while(!linesToBeWrapped
.isEmpty()) {
220 String row
= linesToBeWrapped
.removeFirst();
221 int rowWidth
= getColumnWidth(row
);
222 if(rowWidth
<= maxWidth
) {
226 //Now search in reverse and find the first possible line-break
227 final int characterIndexMax
= getStringCharacterIndex(row
, maxWidth
);
228 int characterIndex
= characterIndexMax
;
229 while(characterIndex
>= 0 &&
230 !Character
.isSpaceChar(row
.charAt(characterIndex
)) &&
231 !isCharCJK(row
.charAt(characterIndex
))) {
234 // right *after* a CJK is also a "nice" spot to break the line!
235 if (characterIndex
>= 0 && characterIndex
< characterIndexMax
&&
236 isCharCJK(row
.charAt(characterIndex
))) {
237 characterIndex
++; // with these conditions it fits!
240 if(characterIndex
< 0) {
241 //Failed! There was no 'nice' place to cut so just cut it at maxWidth
242 characterIndex
= Math
.max(characterIndexMax
, 1); // at least 1 char
243 result
.add(row
.substring(0, characterIndex
));
244 linesToBeWrapped
.addFirst(row
.substring(characterIndex
));
247 // characterIndex == 0 only happens, if either
248 // - first char is CJK and maxWidth==1 or
249 // - first char is whitespace
250 // either way: put it in row before break to prevent infinite loop.
251 characterIndex
= Math
.max( characterIndex
, 1); // at least 1 char
253 //Ok, split the row, add it to the result and continue processing the second half on a new line
254 result
.add(row
.substring(0, characterIndex
));
255 while(characterIndex
< row
.length() &&
256 Character
.isSpaceChar(row
.charAt(characterIndex
))) {
259 if (characterIndex
< row
.length()) { // only if rest contains non-whitespace
260 linesToBeWrapped
.addFirst(row
.substring(characterIndex
));