blob: 0774503d9084dd20cef69a5c4b59ce80bfa952b4 [file] [log] [blame]
Dave Hylands117c46d2014-05-07 07:15:00 -07001/*
2 * This file is part of the Micro Python 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
27#include <stdint.h>
28#include <stdlib.h>
29#include <string.h>
30
31#include "mpconfig.h"
32#include "nlr.h"
33#include "misc.h"
34#include "qstr.h"
35#include "obj.h"
36#include "input.h"
37
38#if MICROPY_USE_READLINE
39#include <readline/readline.h>
40#include <readline/history.h>
41#endif
42
43#define CTRL_D '\x04'
44
45char *prompt(char *p) {
46#if MICROPY_USE_READLINE
47 char *line = readline(p);
48 if (line) {
49 add_history(line);
50 }
51#else
52 static char buf[256];
53 fputs(p, stdout);
54 char *s = fgets(buf, sizeof(buf), stdin);
55 if (!s) {
56 return NULL;
57 }
58 int l = strlen(buf);
59 if (buf[l - 1] == '\n') {
60 buf[l - 1] = 0;
61 } else {
62 l++;
63 }
64 char *line = malloc(l);
65 memcpy(line, buf, l);
66#endif
67 return line;
68}
69
70STATIC mp_obj_t mp_builtin_input(uint n_args, const mp_obj_t *args) {
71 if (n_args == 1) {
72 mp_obj_print(args[0], PRINT_STR);
73 }
74
75 char *line = prompt("");
76 if (line == NULL) {
77 nlr_raise(mp_obj_new_exception(&mp_type_EOFError));
78 }
79 mp_obj_t o = mp_obj_new_str((const byte*)line, strlen(line), false);
80 free(line);
81 return o;
82}
83
84MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_input_obj, 0, 1, mp_builtin_input);