/* New for v2.0: readline support -- daw */

/* random code to save history, expand !'s, etc */

#include "tintin.h"
#include <readline/readline.h>
#include <readline/history.h>

extern HIST_ENTRY	**history_list();

extern char		*mystrdup();

void
rlhist_show(/* void */)
{
	HIST_ENTRY	**a;
	int		i;
	char		msg[256];

	a = history_list();
	if (a == 0 || *a == 0) {
		tintin_puts("#No history.", 0);
		return;
	}
	for (i=0; *a; i++) {
		sprintf(msg, "%2d %s", i, (*a++)->line);
		tintin_puts(msg, 0);
	}
}

char *
rlhist_expand(line)
	char	*line;
{
	char	error_msg[256];
	char	*expansion;

	if (*line == '\0')
		return(line);

	/* don't try to do history expansion on "say hi there!; bow" */
	if (*line != '!') {
		add_history(line);
		return(line);
	}

	/* hack to make "!" work as it used to */
	if (strcmp(line, "!") == 0) {
		free(line);
		line = mystrdup("!!");
	}

	if (history_expand(line, &expansion) < 0) {
		strcpy(error_msg, "Expansion error. ");
		if (expansion)
			strcat(error_msg, expansion);
		tintin_puts(error_msg, (struct session *) 0);
		free(line);
		free(expansion);
		return((char *) 0);
	}
	free(line);
	add_history(expansion);
	return(expansion);
}