2828#include <readline/history.h>
2929
3030#include "config.h"
31+ #include "support.h"
3132
3233#include "fetch_anthropic.h"
3334#include "fetch_hal.h"
@@ -52,6 +53,28 @@ static config_t config;
5253
5354char * (* fetch )(config_t * config , const char * prompt , int history_length );
5455
56+ /*
57+ * Add the specified prompt to the RL history, as a comment if the
58+ * comment prefix is defined.
59+ */
60+ static void
61+ add_prompt_to_history (const char * prompt )
62+ {
63+ if (prompt == NULL )
64+ return ;
65+
66+ if (!config .prompt_comment_set ) {
67+ add_history (prompt );
68+ return ;
69+ }
70+
71+ char * commented_prompt ;
72+ safe_asprintf (& commented_prompt , "%s %s" , config .prompt_comment ,
73+ prompt );
74+ add_history (commented_prompt );
75+ free (commented_prompt );
76+ }
77+
5578/*
5679 * The user has has asked for AI to be queried on the typed text
5780 * Replace the user's text with the queried on
@@ -66,23 +89,30 @@ query_ai(int count, int key)
6689 prev_response = NULL ;
6790 }
6891
69- add_history (* rl_line_buffer_ptr );
92+ add_prompt_to_history (* rl_line_buffer_ptr );
7093 char * response = fetch (& config , * rl_line_buffer_ptr ,
7194 * history_length_ptr );
7295 if (!response )
7396 return -1 ;
7497 rl_crlf ();
7598 rl_on_new_line ();
76- rl_begin_undo_group ();
7799 rl_delete_text (0 , * rl_end_ptr );
78100 * rl_point_ptr = 0 ;
79101 if (config .general_response_prefix_set ) {
80102 rl_insert_text (config .general_response_prefix );
81103 rl_insert_text (" " );
82104 }
83105 rl_insert_text (response );
84- rl_end_undo_group ();
85106 prev_response = response ;
107+ /*
108+ * The readline_internal_teardown() function will restore
109+ * the original history line iff the line being edited
110+ * was originally in the history, AND the line has changed.
111+ * Avoid this by clearing the undo list.
112+ * This results in the commented prompt rather than the
113+ * ucommented prompt being stored in the history.
114+ */
115+ rl_free_undo_list ();
86116 return 0 ;
87117}
88118
0 commit comments