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.
23 #include <gpxe/keys.h>
24 #include <gpxe/editstring.h>
25 #include <readline/readline.h>
33 #define READLINE_MAX 256
36 * Synchronise console with edited string
38 * @v string Editable string
40 static void sync_console ( struct edit_string *string ) {
41 unsigned int mod_start = string->mod_start;
42 unsigned int mod_end = string->mod_end;
43 unsigned int cursor = string->last_cursor;
44 size_t len = strlen ( string->buf );
46 /* Expand region back to old cursor position if applicable */
47 if ( mod_start > string->last_cursor )
48 mod_start = string->last_cursor;
50 /* Expand region forward to new cursor position if applicable */
51 if ( mod_end < string->cursor )
52 mod_end = string->cursor;
54 /* Backspace to start of region */
55 while ( cursor > mod_start ) {
60 /* Print modified region */
61 while ( cursor < mod_end ) {
62 putchar ( ( cursor >= len ) ? ' ' : string->buf[cursor] );
66 /* Backspace to new cursor position */
67 while ( cursor > string->cursor ) {
74 * Read line from console
76 * @v prompt Prompt string
77 * @ret line Line read from console (excluding terminating newline)
79 * The returned line is allocated with malloc(); the caller must
80 * eventually call free() to release the storage.
82 char * readline ( const char *prompt ) {
83 char buf[READLINE_MAX];
84 struct edit_string string;
89 printf ( "%s", prompt );
91 memset ( &string, 0, sizeof ( string ) );
93 string.len = sizeof ( buf );
97 key = edit_string ( &string, getkey() );
98 sync_console ( &string );
103 line = strdup ( buf );
105 printf ( "Out of memory\n" );