Browse Source

Functioning readline()

tags/v0.9.3
Michael Brown 17 years ago
parent
commit
22289ca8f6
1 changed files with 47 additions and 2 deletions
  1. 47
    2
      src/hci/readline.c

+ 47
- 2
src/hci/readline.c View File

@@ -30,6 +30,44 @@
30 30
 
31 31
 #define READLINE_MAX 256
32 32
 
33
+/**
34
+ * Synchronise console with edited string
35
+ *
36
+ * @v string		Editable string
37
+ */
38
+static void sync_console ( struct edit_string *string ) {
39
+	unsigned int mod_start = string->mod_start;
40
+	unsigned int mod_end = string->mod_end;
41
+	unsigned int cursor = string->last_cursor;
42
+	size_t len = strlen ( string->buf );
43
+
44
+	/* Expand region back to old cursor position if applicable */
45
+	if ( mod_start > string->last_cursor )
46
+		mod_start = string->last_cursor;
47
+
48
+	/* Expand region forward to new cursor position if applicable */
49
+	if ( mod_end < string->cursor )
50
+		mod_end = string->cursor;
51
+
52
+	/* Backspace to start of region */
53
+	while ( cursor > mod_start ) {
54
+		putchar ( '\b' );
55
+		cursor--;
56
+	}
57
+
58
+	/* Print modified region */
59
+	while ( cursor < mod_end ) {
60
+		putchar ( ( cursor >= len ) ? ' ' : string->buf[cursor] );
61
+		cursor++;
62
+	}
63
+
64
+	/* Backspace to new cursor position */
65
+	while ( cursor > string->cursor ) {
66
+		putchar ( '\b' );
67
+		cursor--;
68
+	}
69
+}
70
+
33 71
 /**
34 72
  * Read line from console
35 73
  *
@@ -47,6 +85,7 @@ char * readline ( const char *prompt ) {
47 85
 		.cursor = 0,
48 86
 	};
49 87
 	int key;
88
+	char *line = NULL;
50 89
 
51 90
 	if ( prompt )
52 91
 		printf ( "%s", prompt );
@@ -54,15 +93,21 @@ char * readline ( const char *prompt ) {
54 93
 	buf[0] = '\0';
55 94
 	while ( 1 ) {
56 95
 		key = edit_string ( &string, getchar() );
96
+		sync_console ( &string );
57 97
 		switch ( key ) {
58 98
 		case 0x0d: /* Carriage return */
59 99
 		case 0x0a: /* Line feed */
60
-			return ( strdup ( buf ) );
100
+			line = strdup ( buf );
101
+			goto out;
61 102
 		case 0x03: /* Ctrl-C */
62
-			return NULL;
103
+			goto out;
63 104
 		default:
64 105
 			/* Do nothing */
65 106
 			break;
66 107
 		}
67 108
 	}
109
+
110
+ out:
111
+	putchar ( '\n' );
112
+	return line;
68 113
 }

Loading…
Cancel
Save