#include "localhist.h"
#include "line.h"
#include "xmalloc.h"
#include <readline/history.h>
#include <stdlib.h>
static struct linebuf_struct local_history_end_linebuf;
static struct linebuf_struct *fetch_history(HIST_ENTRY *hist_entry)
{
if (!hist_entry->data) {
hist_entry->data = xmalloc(sizeof (struct linebuf_struct));
linebuf_init(hist_entry->data, hist_entry->line);
}
return hist_entry->data;
}
static void cleanup_hist_entry(HIST_ENTRY *hist_entry)
{
if (hist_entry->data) {
linebuf_destroy(hist_entry->data);
free(hist_entry->data);
hist_entry->data = NULL;
}
}
void local_history_init()
{
using_history();
linebuf_init(&local_history_end_linebuf, "");
}
struct linebuf_struct *local_history_current()
{
HIST_ENTRY *hist_entry;
return (hist_entry = current_history()) ? current_history()->data : &local_history_end_linebuf;
}
struct linebuf_struct *local_history_previous()
{
HIST_ENTRY *hist_entry;
if (!(hist_entry = previous_history()))
return NULL;
return fetch_history(hist_entry);
}
struct linebuf_struct *local_history_next()
{
HIST_ENTRY *hist_entry;
if (!current_history())
return NULL;
return (hist_entry = next_history()) ? fetch_history(hist_entry) : &local_history_end_linebuf;
}
struct linebuf_struct *local_history_begin()
{
if (where_history() == 0)
return NULL;
history_set_pos(0);
return fetch_history(current_history());
}
struct linebuf_struct *local_history_end()
{
if (!current_history())
return NULL;
using_history();
return &local_history_end_linebuf;
}
void local_history_destroy()
{
HIST_ENTRY *hist_entry;
using_history();
linebuf_destroy(&local_history_end_linebuf);
while ((hist_entry = previous_history()))
cleanup_hist_entry(hist_entry);
}