4 * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
5 * Copyright 2004 Giovanni Bajo
9 * \brief Line editing support with history
11 * Rationale for basic implementation choices:
13 * \li The history is implemented storing consecutive ASCIIZ strings within an array of memory. When
14 * the history is full, the first (oldest) line is cancelled and the whole buffer is memmoved to
15 * overwrite it and make room. while this is is obviously not the fastest algorithm (which would
16 * require the use of a circular buffer) it is surely good enough for this module, which does not
17 * aim at fast performances (line editing does not require to be blazingly fast).
19 * \li The first character in the history is always \c \\0, and it is used as a guard. By 'wasting' it
20 * in this way, the code actually gets much simpler in that we remove many checks when moving
21 * backward (\c i>0 and similar).
23 * \li While editing, the current index points to the position of the buffer which contains the
24 * last character typed in (exactly like a stack pointer). This also allows to simplify calculations
25 * and to make easier using the last byte of history.
27 * \li While editing, the current line is always kept null-terminated. This is important because
28 * if the user press ENTER, we must have room to add a \c \\0 to terminate the line. If the line
29 * is as long as the whole history buffer, there would not be space for it. By always keeping the
30 * \c \\0 at the end, we properly ensure this without making index checks harder.
32 * \li When removing a line from the history (see \c pop_history()), instead of updating all the
33 * indices we have around, we move backward the pointer to the history we use. This way, we don't
34 * have to update anything. This means that we keep two pointers to the history: \c real_history
35 * always points to the physical start, while \c history is the adjusted pointer (that is
36 * dereference to read/write to it).
38 * \todo Use up/down to move through history The history line will be copied to the current line,
39 * making sure there is room for it.
43 * \author Giovanni Bajo <rasky@develer.com>
48 *#* Revision 1.1 2006/06/01 12:27:39 marco
49 *#* Added utilities for protocols
55 #include <cfg/compiler.h>
56 #include <cfg/debug.h>
61 //! Enable compilation of the unit test code
62 #define DEBUG_UNIT_TEST 0
64 //! Enable dump of the history after each line
65 #define DEBUG_DUMP_HISTORY 0
68 /*! Special keys (escape sequences converted to a single code) */
70 SPECIAL_KEYS = 0x1000,
75 * UpArrow: 0x1B 0x5B 0X41
76 * DownArrow: 0x1B 0x5B 0X42
77 * RightArrow: 0x1B 0x5B 0x43
78 * LeftArrow: 0x1b 0x5B 0x44
79 * Beak(Pause): 0x1b 0x5B 0x50
90 * F1: 0x1b 0x5B 0x5B 0x41
91 * F2: 0x1b 0x5B 0x5B 0x42
92 * F3: 0x1b 0x5B 0x5B 0x43
93 * F4: 0x1b 0x5B 0x5B 0x44
94 * F5: 0x1b 0x5B 0x5B 0x45
95 * Ins: 0x1b 0x5B 0x32 0x7E
96 * Home: 0x1b 0x5B 0x31 0x7E
97 * PgUp: 0x1b 0x5B 0x35 0x7E
98 * Del: 0x1b 0x5B 0x33 0x7E
99 * End: 0x1b 0x5B 0x34 0x7E
100 * PgDn: 0x1b 0x5B 0x36 0x7E
102 KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5,
103 KEY_INS, KEY_HOME, KEY_PGUP, KEY_DEL, KEY_END, KEY_PGDN,
108 * F6: 0x1b 0x5B 0x31 0x37 0x7E
109 * F7: 0x1b 0x5B 0x31 0x38 0x7E
110 * F8: 0x1b 0x5B 0x31 0x39 0x7E
111 * F9: 0x1b 0x5B 0x32 0x30 0x7E
112 * F10: 0x1b 0x5B 0x32 0x31 0x7E
113 * F11: 0x1b 0x5B 0x32 0x33 0x7E
114 * F12: 0x1b 0x5B 0x32 0x34 0x7E
116 KEY_F6, KEY_F7, KEY_F8, KEY_F9,
117 KEY_F10, KEY_F11, KEY_F12,
120 /*! Check if \a c is a separator between words.
121 * \note Parameter \a c is evaluated multiple times
123 #define IS_WORD_SEPARATOR(c) ((c) == ' ' || (c) == '\0')
125 //! Write the string \a txt to the IO output (without any kind of termination)
126 INLINE void rl_puts(const struct RLContext* ctx, const char* txt)
132 ctx->put(*txt++, ctx->put_param);
135 //! Write character \a ch to the IO output.
136 INLINE void rl_putc(const struct RLContext* ctx, char ch)
139 ctx->put(ch, ctx->put_param);
142 /*! Read a character from the IO into \a ch. This function also takes
143 * care of converting the ANSI escape sequences into one of the codes
144 * defined in \c RL_KEYS.
146 static bool rl_getc(const struct RLContext* ctx, int* ch)
148 int c = ctx->get(ctx->get_param);
154 // Unknown ESC sequence. Ignore it and read
155 // return next character.
156 if (ctx->get(ctx->get_param) != 0x5B)
157 return rl_getc(ctx, ch);
160 * Home: 0x1b 0x5B 0x31 0x7E
161 * F6: 0x1b 0x5B 0x31 0x37 0x7E
162 * F7: 0x1b 0x5B 0x31 0x38 0x7E
163 * F8: 0x1b 0x5B 0x31 0x39 0x7E
164 * Ins: 0x1b 0x5B 0x32 0x7E
165 * F9: 0x1b 0x5B 0x32 0x30 0x7E
166 * F10: 0x1b 0x5B 0x32 0x31 0x7E
167 * F11: 0x1b 0x5B 0x32 0x33 0x7E
168 * F12: 0x1b 0x5B 0x32 0x34 0x7E
169 * Del: 0x1b 0x5B 0x33 0x7E
170 * End: 0x1b 0x5B 0x34 0x7E
171 * PgUp: 0x1b 0x5B 0x35 0x7E
172 * PgDn: 0x1b 0x5B 0x36 0x7E
175 c = ctx->get(ctx->get_param);
178 case 0x41: c = KEY_UP_ARROW; break;
179 case 0x42: c = KEY_DOWN_ARROW; break;
180 case 0x43: c = KEY_RIGHT_ARROW; break;
181 case 0x44: c = KEY_LEFT_ARROW; break;
182 case 0x50: c = KEY_PAUSE; break;
184 c = ctx->get(ctx->get_param);
187 case 0x41: c = KEY_F1; break;
188 case 0x42: c = KEY_F2; break;
189 case 0x43: c = KEY_F3; break;
190 case 0x44: c = KEY_F4; break;
191 case 0x45: c = KEY_F5; break;
192 default: return rl_getc(ctx, ch);
195 default: return rl_getc(ctx, ch);
203 INLINE void beep(struct RLContext* ctx)
208 static bool pop_history(struct RLContext* ctx, int total_len)
210 // Compute the length of the first command (including terminator).
211 int len = strlen(ctx->real_history+1)+1;
213 // (the first byte of the history should always be 0)
214 ASSERT(ctx->real_history[0] == '\0');
216 // If it is the only one in the history, do nothing
217 if (len == total_len)
220 // Overwrite the first command with the second one
221 memmove(ctx->real_history, ctx->real_history+len, HISTORY_SIZE-len);
223 // Move back the ctx->buffer pointer so that all the indices are still valid
229 //! Check if index \a i points to the begin of the history.
230 INLINE bool is_history_begin(struct RLContext* ctx, int i)
231 { return ctx->history + i == ctx->real_history; }
233 //! Check if index \a i points to the (exclusive) end of history
234 INLINE bool is_history_end(struct RLContext* ctx, int i)
235 { return ctx->history + i == ctx->real_history + HISTORY_SIZE; }
237 //! Check if index \a i points to the (exclusive) end of history, or somewhere past the end.
238 INLINE bool is_history_past_end(struct RLContext* ctx, int i)
239 { return ctx->history + i >= ctx->real_history + HISTORY_SIZE; }
241 /*! Insert \a num_chars characters from \a ch into the history buffer at the
242 * position indicated by \a curpos. If needed, remove old history to make room.
243 * Returns true if everything was successful, false if there was no room to
244 * add the characters.
245 * \note \a num_chars can be 0, in which case we just make sure the line is
246 * correctly zero-terminated (ASCIIZ format).
248 static bool insert_chars(struct RLContext* ctx, size_t *curpos, const char* ch, int num_chars)
250 ASSERT(!is_history_past_end(ctx, *curpos));
252 while (is_history_past_end(ctx, *curpos+num_chars+1))
254 if (!pop_history(ctx, *curpos))
259 ctx->history[++(*curpos)] = *ch++;
261 ASSERT(!is_history_past_end(ctx, *curpos + 1));
262 ctx->history[*curpos+1] = '\0';
266 //! Insert a single character \a ch into the buffer (with the same semantic of \c insert_chars())
267 static bool insert_char(struct RLContext* ctx, size_t *curpos, char ch)
269 return insert_chars(ctx, curpos, &ch, 1);
272 #if DEBUG_DUMP_HISTORY
273 //! Dump the internal history of a context (used only for debug purposes)
274 static void dump_history(struct RLContext* ctx)
278 ASSERT(ctx->real_history[0] == '\0');
279 rl_puts(ctx, "History dump:");
280 rl_puts(ctx, "\r\n");
282 ctx->real_history + k != ctx->history + ctx->history_pos + 1;
283 k += strlen(&ctx->real_history[k]) + 1)
285 rl_puts(ctx, &ctx->real_history[k]);
286 rl_puts(ctx, "\r\n");
289 sprintf(buf, "%d\r\n", ctx->history_pos + (ctx->history - ctx->real_history));
292 #endif /* DEBUG_DUMP_HISTORY */
294 //! Complete the current word. Return false if no unambiguous completion was found
295 static bool complete_word(struct RLContext *ctx, size_t *curpos)
297 const char* completed_word;
300 // If the current character is a separator,
301 // there is nothing to complete
303 if (IS_WORD_SEPARATOR(ctx->history[wstart]))
309 // Find the separator before the current word
312 while (!IS_WORD_SEPARATOR(ctx->history[wstart]));
314 // Complete the word through the hook
315 completed_word = ctx->match(ctx->match_param, ctx->history + wstart + 1, *curpos - wstart);
319 // Move back the terminal cursor to the separator
320 while (*curpos != wstart)
326 // Insert the completed command
327 insert_chars(ctx, curpos, completed_word, strlen(completed_word));
328 rl_puts(ctx, completed_word);
329 insert_char(ctx, curpos, ' ');
335 void rl_refresh(struct RLContext* ctx)
337 rl_puts(ctx, "\r\n");
339 rl_puts(ctx, ctx->prompt);
340 rl_puts(ctx, ctx->history + ctx->history_pos + 1);
343 const char* rl_readline(struct RLContext* ctx)
345 size_t i = ctx->history_pos;
348 rl_puts(ctx, ctx->prompt);
350 insert_chars(ctx, &i, NULL, 0);
357 ASSERT(ctx->history - ctx->real_history + i < HISTORY_SIZE);
359 if (!rl_getc(ctx, &c))
362 // Just ignore special keys for now
363 if (c > SPECIAL_KEYS)
368 // Ask the match hook if available
372 complete_word(ctx, &i);
376 if (c == '\r' || c == '\n')
378 rl_puts(ctx, "\r\n");
382 // Backspace cancels a character, or it is ignored if at
383 // the start of the line
386 if (ctx->history[i] != '\0')
389 rl_puts(ctx, "\b \b");
394 // Add a character to the buffer, if possible
396 ASSERT2(ch == c, "a special key was not properly handled");
397 if (insert_chars(ctx, &i, &ch, 1))
403 ctx->history_pos = i+1;
404 while (ctx->history[i] != '\0')
407 // Do not store empty lines in the history
408 if (i == ctx->history_pos - 1)
409 ctx->history_pos -= 1;
411 #if DEBUG_DUMP_HISTORY
415 // Since the current pointer now points to the separator, we need
416 // to return the first character
417 return &ctx->history[i+1];
423 /*! Perform the unit test for the readline library */
426 #if HISTORY_SIZE != 32
427 #error This test needs HISTORY_SIZE to be set at 32
430 static struct RLContext test_ctx;
432 static char* test_getc_ptr;
433 static int test_getc(void* data)
435 return *test_getc_ptr++;
438 /*! Perform a readline test. The function pipes the characters from \a input_buffer
439 * through the I/O to \c rl_readline(). After the whole string is sent, \c do_test()
440 * checks if the current history within the context match \a expected_history.
442 static bool do_test(char* input_buffer, char* expected_history)
444 rl_init_ctx(&test_ctx);
445 rl_sethook_get(&test_ctx, test_getc, NULL);
447 test_getc_ptr = input_buffer;
448 while (*test_getc_ptr)
449 rl_readline(&test_ctx);
451 if (memcmp(test_ctx.real_history, expected_history, HISTORY_SIZE) != 0)
453 ASSERT2(0, "history compare failed");
462 char* test1_in = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\n";
463 char test1_hist[HISTORY_SIZE] = "\0l\0m\0n\0o\0p\0q\0r\0s\0t\0u\0v\0w\0x\0y\0z";
465 if (!do_test(test1_in, test1_hist))
468 kprintf("rl_test successful\n");
471 #endif /* DEBUG_UNIT_TEST */