readline.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include <stdint.h>
  28. #include <string.h>
  29. #include "py/mpstate.h"
  30. #include "py/repl.h"
  31. #include "py/mphal.h"
  32. #include "lib/mp-readline/readline.h"
  33. #if 0 // print debugging info
  34. #define DEBUG_PRINT (1)
  35. #define DEBUG_printf printf
  36. #else // don't print debugging info
  37. #define DEBUG_printf(...) (void)0
  38. #endif
  39. #define READLINE_HIST_SIZE (MP_ARRAY_SIZE(MP_STATE_PORT(readline_hist)))
  40. enum { ESEQ_NONE, ESEQ_ESC, ESEQ_ESC_BRACKET, ESEQ_ESC_BRACKET_DIGIT, ESEQ_ESC_O };
  41. void readline_init0(void) {
  42. memset(MP_STATE_PORT(readline_hist), 0, READLINE_HIST_SIZE * sizeof(const char*));
  43. }
  44. STATIC char *str_dup_maybe(const char *str) {
  45. uint32_t len = strlen(str);
  46. char *s2 = m_new_maybe(char, len + 1);
  47. if (s2 == NULL) {
  48. return NULL;
  49. }
  50. memcpy(s2, str, len + 1);
  51. return s2;
  52. }
  53. // By default assume terminal which implements VT100 commands...
  54. #ifndef MICROPY_HAL_HAS_VT100
  55. #define MICROPY_HAL_HAS_VT100 (1)
  56. #endif
  57. // ...and provide the implementation using them
  58. #if MICROPY_HAL_HAS_VT100
  59. STATIC void mp_hal_move_cursor_back(uint pos) {
  60. if (pos <= 4) {
  61. // fast path for most common case of 1 step back
  62. mp_hal_stdout_tx_strn("\b\b\b\b", pos);
  63. } else {
  64. char vt100_command[6];
  65. // snprintf needs space for the terminating null character
  66. int n = snprintf(&vt100_command[0], sizeof(vt100_command), "\x1b[%u", pos);
  67. if (n > 0) {
  68. vt100_command[n] = 'D'; // replace null char
  69. mp_hal_stdout_tx_strn(vt100_command, n + 1);
  70. }
  71. }
  72. }
  73. STATIC void mp_hal_erase_line_from_cursor(uint n_chars_to_erase) {
  74. (void)n_chars_to_erase;
  75. mp_hal_stdout_tx_strn("\x1b[K", 3);
  76. }
  77. #endif
  78. typedef struct _readline_t {
  79. vstr_t *line;
  80. size_t orig_line_len;
  81. int escape_seq;
  82. int hist_cur;
  83. size_t cursor_pos;
  84. char escape_seq_buf[1];
  85. const char *prompt;
  86. } readline_t;
  87. STATIC readline_t rl;
  88. int readline_process_char(int c) {
  89. size_t last_line_len = rl.line->len;
  90. int redraw_step_back = 0;
  91. bool redraw_from_cursor = false;
  92. int redraw_step_forward = 0;
  93. if (rl.escape_seq == ESEQ_NONE) {
  94. if (CHAR_CTRL_A <= c && c <= CHAR_CTRL_E && vstr_len(rl.line) == rl.orig_line_len) {
  95. // control character with empty line
  96. return c;
  97. } else if (c == CHAR_CTRL_A) {
  98. // CTRL-A with non-empty line is go-to-start-of-line
  99. goto home_key;
  100. #if MICROPY_REPL_EMACS_KEYS
  101. } else if (c == CHAR_CTRL_B) {
  102. // CTRL-B with non-empty line is go-back-one-char
  103. goto left_arrow_key;
  104. #endif
  105. } else if (c == CHAR_CTRL_C) {
  106. // CTRL-C with non-empty line is cancel
  107. return c;
  108. #if MICROPY_REPL_EMACS_KEYS
  109. } else if (c == CHAR_CTRL_D) {
  110. // CTRL-D with non-empty line is delete-at-cursor
  111. goto delete_key;
  112. #endif
  113. } else if (c == CHAR_CTRL_E) {
  114. // CTRL-E is go-to-end-of-line
  115. goto end_key;
  116. #if MICROPY_REPL_EMACS_KEYS
  117. } else if (c == CHAR_CTRL_F) {
  118. // CTRL-F with non-empty line is go-forward-one-char
  119. goto right_arrow_key;
  120. } else if (c == CHAR_CTRL_K) {
  121. // CTRL-K is kill from cursor to end-of-line, inclusive
  122. vstr_cut_tail_bytes(rl.line, last_line_len - rl.cursor_pos);
  123. // set redraw parameters
  124. redraw_from_cursor = true;
  125. } else if (c == CHAR_CTRL_N) {
  126. // CTRL-N is go to next line in history
  127. goto down_arrow_key;
  128. } else if (c == CHAR_CTRL_P) {
  129. // CTRL-P is go to previous line in history
  130. goto up_arrow_key;
  131. } else if (c == CHAR_CTRL_U) {
  132. // CTRL-U is kill from beginning-of-line up to cursor
  133. vstr_cut_out_bytes(rl.line, rl.orig_line_len, rl.cursor_pos - rl.orig_line_len);
  134. // set redraw parameters
  135. redraw_step_back = rl.cursor_pos - rl.orig_line_len;
  136. redraw_from_cursor = true;
  137. #endif
  138. } else if (c == '\r') {
  139. // newline
  140. mp_hal_stdout_tx_str("\r\n");
  141. readline_push_history(vstr_null_terminated_str(rl.line) + rl.orig_line_len);
  142. return 0;
  143. } else if (c == 27) {
  144. // escape sequence
  145. rl.escape_seq = ESEQ_ESC;
  146. } else if (c == 8 || c == 127) {
  147. // backspace/delete
  148. if (rl.cursor_pos > rl.orig_line_len) {
  149. // work out how many chars to backspace
  150. #if MICROPY_REPL_AUTO_INDENT
  151. int nspace = 0;
  152. for (size_t i = rl.orig_line_len; i < rl.cursor_pos; i++) {
  153. if (rl.line->buf[i] != ' ') {
  154. nspace = 0;
  155. break;
  156. }
  157. nspace += 1;
  158. }
  159. if (nspace < 4) {
  160. nspace = 1;
  161. } else {
  162. nspace = 4;
  163. }
  164. #else
  165. int nspace = 1;
  166. #endif
  167. // do the backspace
  168. vstr_cut_out_bytes(rl.line, rl.cursor_pos - nspace, nspace);
  169. // set redraw parameters
  170. redraw_step_back = nspace;
  171. redraw_from_cursor = true;
  172. }
  173. #if MICROPY_HELPER_REPL
  174. } else if (c == 9) {
  175. // tab magic
  176. const char *compl_str;
  177. size_t compl_len = mp_repl_autocomplete(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len, &mp_plat_print, &compl_str);
  178. if (compl_len == 0) {
  179. // no match
  180. } else if (compl_len == (size_t)(-1)) {
  181. // many matches
  182. mp_hal_stdout_tx_str(rl.prompt);
  183. mp_hal_stdout_tx_strn(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len);
  184. redraw_from_cursor = true;
  185. } else {
  186. // one match
  187. for (size_t i = 0; i < compl_len; ++i) {
  188. vstr_ins_byte(rl.line, rl.cursor_pos + i, *compl_str++);
  189. }
  190. // set redraw parameters
  191. redraw_from_cursor = true;
  192. redraw_step_forward = compl_len;
  193. }
  194. #endif
  195. } else if (32 <= c && c <= 126) {
  196. // printable character
  197. vstr_ins_char(rl.line, rl.cursor_pos, c);
  198. // set redraw parameters
  199. redraw_from_cursor = true;
  200. redraw_step_forward = 1;
  201. }
  202. } else if (rl.escape_seq == ESEQ_ESC) {
  203. switch (c) {
  204. case '[':
  205. rl.escape_seq = ESEQ_ESC_BRACKET;
  206. break;
  207. case 'O':
  208. rl.escape_seq = ESEQ_ESC_O;
  209. break;
  210. default:
  211. DEBUG_printf("(ESC %d)", c);
  212. rl.escape_seq = ESEQ_NONE;
  213. }
  214. } else if (rl.escape_seq == ESEQ_ESC_BRACKET) {
  215. if ('0' <= c && c <= '9') {
  216. rl.escape_seq = ESEQ_ESC_BRACKET_DIGIT;
  217. rl.escape_seq_buf[0] = c;
  218. } else {
  219. rl.escape_seq = ESEQ_NONE;
  220. if (c == 'A') {
  221. #if MICROPY_REPL_EMACS_KEYS
  222. up_arrow_key:
  223. #endif
  224. // up arrow
  225. if (rl.hist_cur + 1 < (int)READLINE_HIST_SIZE && MP_STATE_PORT(readline_hist)[rl.hist_cur + 1] != NULL) {
  226. // increase hist num
  227. rl.hist_cur += 1;
  228. // set line to history
  229. rl.line->len = rl.orig_line_len;
  230. vstr_add_str(rl.line, MP_STATE_PORT(readline_hist)[rl.hist_cur]);
  231. // set redraw parameters
  232. redraw_step_back = rl.cursor_pos - rl.orig_line_len;
  233. redraw_from_cursor = true;
  234. redraw_step_forward = rl.line->len - rl.orig_line_len;
  235. }
  236. } else if (c == 'B') {
  237. #if MICROPY_REPL_EMACS_KEYS
  238. down_arrow_key:
  239. #endif
  240. // down arrow
  241. if (rl.hist_cur >= 0) {
  242. // decrease hist num
  243. rl.hist_cur -= 1;
  244. // set line to history
  245. vstr_cut_tail_bytes(rl.line, rl.line->len - rl.orig_line_len);
  246. if (rl.hist_cur >= 0) {
  247. vstr_add_str(rl.line, MP_STATE_PORT(readline_hist)[rl.hist_cur]);
  248. }
  249. // set redraw parameters
  250. redraw_step_back = rl.cursor_pos - rl.orig_line_len;
  251. redraw_from_cursor = true;
  252. redraw_step_forward = rl.line->len - rl.orig_line_len;
  253. }
  254. } else if (c == 'C') {
  255. #if MICROPY_REPL_EMACS_KEYS
  256. right_arrow_key:
  257. #endif
  258. // right arrow
  259. if (rl.cursor_pos < rl.line->len) {
  260. redraw_step_forward = 1;
  261. }
  262. } else if (c == 'D') {
  263. #if MICROPY_REPL_EMACS_KEYS
  264. left_arrow_key:
  265. #endif
  266. // left arrow
  267. if (rl.cursor_pos > rl.orig_line_len) {
  268. redraw_step_back = 1;
  269. }
  270. } else if (c == 'H') {
  271. // home
  272. goto home_key;
  273. } else if (c == 'F') {
  274. // end
  275. goto end_key;
  276. } else {
  277. DEBUG_printf("(ESC [ %d)", c);
  278. }
  279. }
  280. } else if (rl.escape_seq == ESEQ_ESC_BRACKET_DIGIT) {
  281. if (c == '~') {
  282. if (rl.escape_seq_buf[0] == '1' || rl.escape_seq_buf[0] == '7') {
  283. home_key:
  284. redraw_step_back = rl.cursor_pos - rl.orig_line_len;
  285. } else if (rl.escape_seq_buf[0] == '4' || rl.escape_seq_buf[0] == '8') {
  286. end_key:
  287. redraw_step_forward = rl.line->len - rl.cursor_pos;
  288. } else if (rl.escape_seq_buf[0] == '3') {
  289. // delete
  290. #if MICROPY_REPL_EMACS_KEYS
  291. delete_key:
  292. #endif
  293. if (rl.cursor_pos < rl.line->len) {
  294. vstr_cut_out_bytes(rl.line, rl.cursor_pos, 1);
  295. redraw_from_cursor = true;
  296. }
  297. } else {
  298. DEBUG_printf("(ESC [ %c %d)", rl.escape_seq_buf[0], c);
  299. }
  300. } else {
  301. DEBUG_printf("(ESC [ %c %d)", rl.escape_seq_buf[0], c);
  302. }
  303. rl.escape_seq = ESEQ_NONE;
  304. } else if (rl.escape_seq == ESEQ_ESC_O) {
  305. switch (c) {
  306. case 'H':
  307. goto home_key;
  308. case 'F':
  309. goto end_key;
  310. default:
  311. DEBUG_printf("(ESC O %d)", c);
  312. rl.escape_seq = ESEQ_NONE;
  313. }
  314. } else {
  315. rl.escape_seq = ESEQ_NONE;
  316. }
  317. // redraw command prompt, efficiently
  318. if (redraw_step_back > 0) {
  319. mp_hal_move_cursor_back(redraw_step_back);
  320. rl.cursor_pos -= redraw_step_back;
  321. }
  322. if (redraw_from_cursor) {
  323. if (rl.line->len < last_line_len) {
  324. // erase old chars
  325. mp_hal_erase_line_from_cursor(last_line_len - rl.cursor_pos);
  326. }
  327. // draw new chars
  328. mp_hal_stdout_tx_strn(rl.line->buf + rl.cursor_pos, rl.line->len - rl.cursor_pos);
  329. // move cursor forward if needed (already moved forward by length of line, so move it back)
  330. mp_hal_move_cursor_back(rl.line->len - (rl.cursor_pos + redraw_step_forward));
  331. rl.cursor_pos += redraw_step_forward;
  332. } else if (redraw_step_forward > 0) {
  333. // draw over old chars to move cursor forwards
  334. mp_hal_stdout_tx_strn(rl.line->buf + rl.cursor_pos, redraw_step_forward);
  335. rl.cursor_pos += redraw_step_forward;
  336. }
  337. return -1;
  338. }
  339. #if MICROPY_REPL_AUTO_INDENT
  340. STATIC void readline_auto_indent(void) {
  341. vstr_t *line = rl.line;
  342. if (line->len > 1 && line->buf[line->len - 1] == '\n') {
  343. int i;
  344. for (i = line->len - 1; i > 0; i--) {
  345. if (line->buf[i - 1] == '\n') {
  346. break;
  347. }
  348. }
  349. size_t j;
  350. for (j = i; j < line->len; j++) {
  351. if (line->buf[j] != ' ') {
  352. break;
  353. }
  354. }
  355. // i=start of line; j=first non-space
  356. if (i > 0 && j + 1 == line->len) {
  357. // previous line is not first line and is all spaces
  358. for (size_t k = i - 1; k > 0; --k) {
  359. if (line->buf[k - 1] == '\n') {
  360. // don't auto-indent if last 2 lines are all spaces
  361. return;
  362. } else if (line->buf[k - 1] != ' ') {
  363. // 2nd previous line is not all spaces
  364. break;
  365. }
  366. }
  367. }
  368. int n = (j - i) / 4;
  369. if (line->buf[line->len - 2] == ':') {
  370. n += 1;
  371. }
  372. while (n-- > 0) {
  373. vstr_add_strn(line, " ", 4);
  374. mp_hal_stdout_tx_strn(" ", 4);
  375. rl.cursor_pos += 4;
  376. }
  377. }
  378. }
  379. #endif
  380. void readline_note_newline(const char *prompt) {
  381. rl.orig_line_len = rl.line->len;
  382. rl.cursor_pos = rl.orig_line_len;
  383. rl.prompt = prompt;
  384. mp_hal_stdout_tx_str(prompt);
  385. #if MICROPY_REPL_AUTO_INDENT
  386. readline_auto_indent();
  387. #endif
  388. }
  389. void readline_init(vstr_t *line, const char *prompt) {
  390. rl.line = line;
  391. rl.orig_line_len = line->len;
  392. rl.escape_seq = ESEQ_NONE;
  393. rl.escape_seq_buf[0] = 0;
  394. rl.hist_cur = -1;
  395. rl.cursor_pos = rl.orig_line_len;
  396. rl.prompt = prompt;
  397. mp_hal_stdout_tx_str(prompt);
  398. #if MICROPY_REPL_AUTO_INDENT
  399. readline_auto_indent();
  400. #endif
  401. }
  402. int readline(vstr_t *line, const char *prompt) {
  403. readline_init(line, prompt);
  404. for (;;) {
  405. int c = mp_hal_stdin_rx_chr();
  406. int r = readline_process_char(c);
  407. if (r >= 0) {
  408. return r;
  409. }
  410. }
  411. }
  412. void readline_push_history(const char *line) {
  413. if (line[0] != '\0'
  414. && (MP_STATE_PORT(readline_hist)[0] == NULL
  415. || strcmp(MP_STATE_PORT(readline_hist)[0], line) != 0)) {
  416. // a line which is not empty and different from the last one
  417. // so update the history
  418. char *most_recent_hist = str_dup_maybe(line);
  419. if (most_recent_hist != NULL) {
  420. for (int i = READLINE_HIST_SIZE - 1; i > 0; i--) {
  421. MP_STATE_PORT(readline_hist)[i] = MP_STATE_PORT(readline_hist)[i - 1];
  422. }
  423. MP_STATE_PORT(readline_hist)[0] = most_recent_hist;
  424. }
  425. }
  426. }