Skip to content

Commit 59fa9b0

Browse files
committed
[repl] Autocomplete builtin modules
1 parent 1d55dee commit 59fa9b0

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

py/repl.c

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
#include <string.h>
2828
#include "py/obj.h"
29+
#include "py/objmodule.h"
2930
#include "py/runtime.h"
3031
#include "py/builtin.h"
3132
#include "py/repl.h"
@@ -144,10 +145,16 @@ bool mp_repl_continue_with_input(const char *input) {
144145
}
145146

146147
STATIC bool test_qstr(mp_obj_t obj, qstr name) {
147-
// try object member
148-
mp_obj_t dest[2];
149-
mp_load_method_protected(obj, name, dest, true);
150-
return dest[0] != MP_OBJ_NULL;
148+
if (obj) {
149+
// try object member
150+
mp_obj_t dest[2];
151+
mp_load_method_protected(obj, name, dest, true);
152+
return dest[0] != MP_OBJ_NULL;
153+
} else {
154+
// try builtin module
155+
return mp_map_lookup((mp_map_t *)&mp_builtin_module_map,
156+
MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP);
157+
}
151158
}
152159

153160
STATIC const char *find_completions(const char *s_start, size_t s_len,
@@ -282,21 +289,25 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print
282289

283290
// nothing found
284291
if (q_first == 0) {
285-
if (s_len == 0) {
286-
*compl_str = " ";
287-
return 4;
288-
}
289292
// If there're no better alternatives, and if it's first word
290293
// in the line, try to complete "import".
291-
if (s_start == org_str) {
292-
static const char import_str[] = "import ";
294+
static const char import_str[] = "import ";
295+
if (s_start == org_str && s_len > 0) {
293296
if (memcmp(s_start, import_str, s_len) == 0) {
294297
*compl_str = import_str + s_len;
295298
return sizeof(import_str) - 1 - s_len;
296299
}
297300
}
298-
299-
return 0;
301+
// after "import", suggest built-in modules
302+
if (len >= 7 && !memcmp(org_str, import_str, 7)) {
303+
obj = NULL;
304+
match_str = find_completions(
305+
s_start, s_len, obj, &match_len, &q_first, &q_last);
306+
}
307+
if (q_first == 0) {
308+
*compl_str = " ";
309+
return s_len ? 0 : 4;
310+
}
300311
}
301312

302313
// 1 match found, or multiple matches with a common prefix

0 commit comments

Comments
 (0)