2 * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include <gpxe/editstring.h>
23 #include <readline/readline.h>
31 #define READLINE_MAX 256
34 * Synchronise console with edited string
36 * @v string Editable string
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 );
44 /* Expand region back to old cursor position if applicable */
45 if ( mod_start > string->last_cursor )
46 mod_start = string->last_cursor;
48 /* Expand region forward to new cursor position if applicable */
49 if ( mod_end < string->cursor )
50 mod_end = string->cursor;
52 /* Backspace to start of region */
53 while ( cursor > mod_start ) {
58 /* Print modified region */
59 while ( cursor < mod_end ) {
60 putchar ( ( cursor >= len ) ? ' ' : string->buf[cursor] );
64 /* Backspace to new cursor position */
65 while ( cursor > string->cursor ) {
72 * Read line from console
74 * @v prompt Prompt string
75 * @ret line Line read from console (excluding terminating newline)
77 * The returned line is allocated with malloc(); the caller must
78 * eventually call free() to release the storage.
80 char * readline ( const char *prompt ) {
81 char buf[READLINE_MAX];
82 struct edit_string string = {
84 .len = sizeof ( buf ),
91 printf ( "%s", prompt );
95 key = edit_string ( &string, getchar() );
96 sync_console ( &string );
98 case 0x0d: /* Carriage return */
99 case 0x0a: /* Line feed */
101 line = strdup ( buf );
103 printf ( "Out of memory\n" );
105 case 0x03: /* Ctrl-C */