1/* 2 * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved. 3 * 4 * This software is distributable under the BSD license. See the terms of the 5 * BSD license in the documentation provided with this software. 6 */ 7package jline; 8 9/** 10 * A CursorBuffer is a holder for a {@link StringBuffer} that also contains the 11 * current cursor position. 12 * 13 * @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a> 14 */ 15public class CursorBuffer { 16 public int cursor = 0; 17 18 StringBuffer buffer = new StringBuffer(); 19 20 private boolean overtyping = false; 21 22 public int length() { 23 return buffer.length(); 24 } 25 26 public char current() { 27 if (cursor <= 0) { 28 return 0; 29 } 30 31 return buffer.charAt(cursor - 1); 32 } 33 34 public boolean clearBuffer() { 35 if (buffer.length() == 0) { 36 return false; 37 } 38 39 buffer.delete(0, buffer.length()); 40 cursor = 0; 41 return true; 42 } 43 44 /** 45 * Write the specific character into the buffer, setting the cursor position 46 * ahead one. The text may overwrite or insert based on the current setting 47 * of isOvertyping(). 48 * 49 * @param c 50 * the character to insert 51 */ 52 public void write(final char c) { 53 buffer.insert(cursor++, c); 54 if (isOvertyping() && cursor < buffer.length()) { 55 buffer.deleteCharAt(cursor); 56 } 57 } 58 59 /** 60 * Insert the specified {@link String} into the buffer, setting the cursor 61 * to the end of the insertion point. 62 * 63 * @param str 64 * the String to insert. Must not be null. 65 */ 66 public void write(final String str) { 67 if (buffer.length() == 0) { 68 buffer.append(str); 69 } else { 70 buffer.insert(cursor, str); 71 } 72 73 cursor += str.length(); 74 75 if (isOvertyping() && cursor < buffer.length()) { 76 buffer.delete(cursor, (cursor + str.length())); 77 } 78 } 79 80 public String toString() { 81 return buffer.toString(); 82 } 83 84 public boolean isOvertyping() { 85 return overtyping; 86 } 87 88 public void setOvertyping(boolean b) { 89 overtyping = b; 90 } 91 92 public StringBuffer getBuffer() { 93 return buffer; 94 } 95 96 public void setBuffer(StringBuffer buffer) { 97 buffer.setLength(0); 98 buffer.append(this.buffer.toString()); 99 100 this.buffer = buffer; 101 } 102 103 104} 105