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
35 static void sync_console ( struct edit_string *string ) __nonnull;
38 * Synchronise console with edited string
40 * @v string Editable string
42 static void sync_console ( struct edit_string *string ) {
43 unsigned int mod_start = string->mod_start;
44 unsigned int mod_end = string->mod_end;
45 unsigned int cursor = string->last_cursor;
46 size_t len = strlen ( string->buf );
48 /* Expand region back to old cursor position if applicable */
49 if ( mod_start > string->last_cursor )
50 mod_start = string->last_cursor;
52 /* Expand region forward to new cursor position if applicable */
53 if ( mod_end < string->cursor )
54 mod_end = string->cursor;
56 /* Backspace to start of region */
57 while ( cursor > mod_start ) {
62 /* Print modified region */
63 while ( cursor < mod_end ) {
64 putchar ( ( cursor >= len ) ? ' ' : string->buf[cursor] );
68 /* Backspace to new cursor position */
69 while ( cursor > string->cursor ) {
76 * Read line from console
78 * @v prompt Prompt string
79 * @ret line Line read from console (excluding terminating newline)
81 * The returned line is allocated with malloc(); the caller must
82 * eventually call free() to release the storage.
84 char * readline ( const char *prompt ) {
85 char buf[READLINE_MAX];
86 struct edit_string string;
91 printf ( "%s", prompt );
93 memset ( &string, 0, sizeof ( string ) );
95 string.len = sizeof ( buf );
99 key = edit_string ( &string, getkey() );
100 sync_console ( &string );
105 line = strdup ( buf );
107 printf ( "Out of memory\n" );