Skip to content

Commit

Permalink
patched getCursorPosition to strip ANSI codes from the prompt to calc…
Browse files Browse the repository at this point in the history
…ulate its display length
  • Loading branch information
jkuipers committed Apr 11, 2011
1 parent 8509b65 commit 3d98170
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/main/java/jline/ConsoleReader.java
Expand Up @@ -424,7 +424,33 @@ StringBuffer getPrintableCharacters(char ch) {
int getCursorPosition() {
// FIXME: does not handle anything but a line with a prompt
// absolute position
return ((prompt == null) ? 0 : prompt.length()) + buf.cursor;
return getStrippedAnsiLength(prompt) + buf.cursor;
}

/**
* Strips ANSI escape sequences starting with CSI and ending with char in range 64-126
* @param ansiString String possibly containing ANSI codes, may be null
* @return length after stripping ANSI codes
*/
int getStrippedAnsiLength(String ansiString) {
if (ansiString == null) return 0;
boolean inAnsi = false;
int strippedLength = 0;
char[] chars = ansiString.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (!inAnsi && c == 27 && i < chars.length - 1 && chars[i+1] == '[') {
i++; // skip '['
inAnsi = true;
} else if (inAnsi) {
if (64 <= c && c <= 126) {
inAnsi = false;
}
} else {
strippedLength++;
}
}
return strippedLength;
}

public String readLine(final String prompt) throws IOException {
Expand Down

0 comments on commit 3d98170

Please sign in to comment.