In a readline buffer I want to provide an initial value the user can edit. This can either be a default value or the old value of the field already saved to my database. The entered value shall not be added to the readline-history as it is only "data" not a command.
From the samples here and on the internet I have learned that this code should do the job:
char *deftext;
int MatCustom::set_deftext ()
{
// cout << "set_deftext called ... deftext: " << deftext << endl;
if (deftext)
{
// cout << "inserting..." << endl;
rl_insert_text(deftext);
// rl_line_buffer = deftext;
// cout << rl_stuff_char('J') << endl;
rl_redisplay();
deftext = (char *)NULL;
rl_startup_hook = (rl_hook_func_t *)NULL;
// rl_pre_input_hook = (rl_hook_func_t *)NULL;
};
return 0;
}
string MatCustom::getlineWithoutHistory(const string &field) {
string returnString;
const char *buffer;
char *cstr = new char[field.length() + 1];
strcpy(cstr, field.c_str());
deftext = cstr;
// cout << "Deftext in getLineWithoutHistory: " << deftext << endl;
rl_startup_hook = set_deftext;
// rl_pre_input_hook = set_deftext;
buffer = :: readline("");
if (buffer != nullptr) {
returnString = buffer;
} else {
returnString = "";
}
free((void *) buffer);
delete [] cstr;
return returnString;
}
It works perfectly well to convert my old value to a char* and pass it to the global variable deftext, because a parameter cannot be given to the readline-hook-functions.
I am experiencing problems: Whenever I use the rl_startup_hook, which is said to be called before the prompt gets printed, I find this this hook never gets executed. However, when I use the rl_pre_input_hook, which is called prior to the input to begin, my function set_deftext actually gets called. This functions finds deftext set.
Still, I don't get any text inserted into the input buffer. The function rl_insert_text produces no change – even when I use rl_redisplay(). Directly changing the buffer with rl_line_buffer = deftext; also has no effect. When I try cout << rl_stuff_char('J') << endl; for debugging just to insert a single char, nothing happens and the function returns 0 indicating an unsuccessful insert.
Both functions are static member functions. I usually call my function with
input = MatCustom::getlineWithoutHistory(rawValue);
to edit to provided value (rawValue).