1 /* This module makes GNU readline available to Python. It has ideas
2 * contributed by Lee Busby, LLNL, and William Magro, Cornell Theory
3 * Center. The completer interface was inspired by Lele Gaifax. More
4 * recently, it was largely rewritten by Guido van Rossum.
5 */
6
7 /* Standard definitions */
8 #include "Python.h"
9 #include <stddef.h>
10 #include <signal.h>
11 #include <errno.h>
12 #include <sys/time.h>
13
14 #if defined(HAVE_SETLOCALE)
15 /* GNU readline() mistakenly sets the LC_CTYPE locale.
16 * This is evil. Only the user or the app's main() should do this!
17 * We must save and restore the locale around the rl_initialize() call.
18 */
19 #define SAVE_LOCALE
20 #include <locale.h>
21 #endif
22
23 #ifdef SAVE_LOCALE
24 # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
25 #else
26 # define RESTORE_LOCALE(sl)
27 #endif
28
29 /* GNU readline definitions */
30 #undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
31 #include <readline/readline.h>
32 #include <readline/history.h>
33
34 #ifdef HAVE_RL_COMPLETION_MATCHES
35 #define completion_matches(x, y) \
36 rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
37 #else
38 #if defined(_RL_FUNCTION_TYPEDEF)
39 extern char **completion_matches(char *, rl_compentry_func_t *);
40 #else
41
42 #if !defined(__APPLE__)
43 extern char **completion_matches(char *, CPFunction *);
44 #endif
45 #endif
46 #endif
47
48 /*
49 * It is possible to link the readline module to the readline
50 * emulation library of editline/libedit.
51 *
52 * This emulation library is not 100% API compatible with the "real" readline
53 * and cannot be detected at compile-time,
54 * hence we use a runtime check to detect if the Python readlinke module is
55 * linked to libedit.
56 *
57 * Currently there is one known API incompatibility:
58 * - 'get_history' has a 1-based index with GNU readline, and a 0-based
59 * index with older versions of libedit's emulation.
60 * - Note that replace_history and remove_history use a 0-based index
61 * with both implementations.
62 */
63 static int using_libedit_emulation = 0;
64 static const char libedit_version_tag[] = "EditLine wrapper";
65
66 static int libedit_history_start = 0;
67
68 #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
69 static void
70 on_completion_display_matches_hook(char **matches,
71 int num_matches, int max_length);
72 #endif
73
74 /* Memory allocated for rl_completer_word_break_characters
75 (see issue #17289 for the motivation). */
76 static char *completer_word_break_characters;
77
78 typedef struct {
79 /* Specify hook functions in Python */
80 PyObject *completion_display_matches_hook;
81 PyObject *startup_hook;
82 PyObject *pre_input_hook;
83
84 PyObject *completer; /* Specify a word completer in Python */
85 PyObject *begidx;
86 PyObject *endidx;
87 } readlinestate;
88
89
90 #define readline_state(o) ((readlinestate *)PyModule_GetState(o))
91
92 static int
readline_clear(PyObject * m)93 readline_clear(PyObject *m)
94 {
95 readlinestate *state = readline_state(m);
96 Py_CLEAR(state->completion_display_matches_hook);
97 Py_CLEAR(state->startup_hook);
98 Py_CLEAR(state->pre_input_hook);
99 Py_CLEAR(state->completer);
100 Py_CLEAR(state->begidx);
101 Py_CLEAR(state->endidx);
102 return 0;
103 }
104
105 static int
readline_traverse(PyObject * m,visitproc visit,void * arg)106 readline_traverse(PyObject *m, visitproc visit, void *arg)
107 {
108 readlinestate *state = readline_state(m);
109 Py_VISIT(state->completion_display_matches_hook);
110 Py_VISIT(state->startup_hook);
111 Py_VISIT(state->pre_input_hook);
112 Py_VISIT(state->completer);
113 Py_VISIT(state->begidx);
114 Py_VISIT(state->endidx);
115 return 0;
116 }
117
118 static void
readline_free(void * m)119 readline_free(void *m)
120 {
121 readline_clear((PyObject *)m);
122 }
123
124 static PyModuleDef readlinemodule;
125
126 #define readlinestate_global ((readlinestate *)PyModule_GetState(PyState_FindModule(&readlinemodule)))
127
128
129 /* Convert to/from multibyte C strings */
130
131 static PyObject *
encode(PyObject * b)132 encode(PyObject *b)
133 {
134 return PyUnicode_EncodeLocale(b, "surrogateescape");
135 }
136
137 static PyObject *
decode(const char * s)138 decode(const char *s)
139 {
140 return PyUnicode_DecodeLocale(s, "surrogateescape");
141 }
142
143
144 /* Exported function to send one line to readline's init file parser */
145
146 static PyObject *
parse_and_bind(PyObject * self,PyObject * string)147 parse_and_bind(PyObject *self, PyObject *string)
148 {
149 char *copy;
150 PyObject *encoded = encode(string);
151 if (encoded == NULL) {
152 return NULL;
153 }
154 /* Make a copy -- rl_parse_and_bind() modifies its argument */
155 /* Bernard Herzog */
156 copy = PyMem_Malloc(1 + PyBytes_GET_SIZE(encoded));
157 if (copy == NULL) {
158 Py_DECREF(encoded);
159 return PyErr_NoMemory();
160 }
161 strcpy(copy, PyBytes_AS_STRING(encoded));
162 Py_DECREF(encoded);
163 rl_parse_and_bind(copy);
164 PyMem_Free(copy); /* Free the copy */
165 Py_RETURN_NONE;
166 }
167
168 PyDoc_STRVAR(doc_parse_and_bind,
169 "parse_and_bind(string) -> None\n\
170 Execute the init line provided in the string argument.");
171
172
173 /* Exported function to parse a readline init file */
174
175 static PyObject *
read_init_file(PyObject * self,PyObject * args)176 read_init_file(PyObject *self, PyObject *args)
177 {
178 PyObject *filename_obj = Py_None, *filename_bytes;
179 if (!PyArg_ParseTuple(args, "|O:read_init_file", &filename_obj))
180 return NULL;
181 if (filename_obj != Py_None) {
182 if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
183 return NULL;
184 errno = rl_read_init_file(PyBytes_AsString(filename_bytes));
185 Py_DECREF(filename_bytes);
186 } else
187 errno = rl_read_init_file(NULL);
188 if (errno)
189 return PyErr_SetFromErrno(PyExc_OSError);
190 Py_RETURN_NONE;
191 }
192
193 PyDoc_STRVAR(doc_read_init_file,
194 "read_init_file([filename]) -> None\n\
195 Execute a readline initialization file.\n\
196 The default filename is the last filename used.");
197
198
199 /* Exported function to load a readline history file */
200
201 static PyObject *
read_history_file(PyObject * self,PyObject * args)202 read_history_file(PyObject *self, PyObject *args)
203 {
204 PyObject *filename_obj = Py_None, *filename_bytes;
205 if (!PyArg_ParseTuple(args, "|O:read_history_file", &filename_obj))
206 return NULL;
207 if (filename_obj != Py_None) {
208 if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
209 return NULL;
210 errno = read_history(PyBytes_AsString(filename_bytes));
211 Py_DECREF(filename_bytes);
212 } else
213 errno = read_history(NULL);
214 if (errno)
215 return PyErr_SetFromErrno(PyExc_OSError);
216 Py_RETURN_NONE;
217 }
218
219 static int _history_length = -1; /* do not truncate history by default */
220 PyDoc_STRVAR(doc_read_history_file,
221 "read_history_file([filename]) -> None\n\
222 Load a readline history file.\n\
223 The default filename is ~/.history.");
224
225
226 /* Exported function to save a readline history file */
227
228 static PyObject *
write_history_file(PyObject * self,PyObject * args)229 write_history_file(PyObject *self, PyObject *args)
230 {
231 PyObject *filename_obj = Py_None, *filename_bytes;
232 char *filename;
233 int err;
234 if (!PyArg_ParseTuple(args, "|O:write_history_file", &filename_obj))
235 return NULL;
236 if (filename_obj != Py_None) {
237 if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
238 return NULL;
239 filename = PyBytes_AsString(filename_bytes);
240 } else {
241 filename_bytes = NULL;
242 filename = NULL;
243 }
244 errno = err = write_history(filename);
245 if (!err && _history_length >= 0)
246 history_truncate_file(filename, _history_length);
247 Py_XDECREF(filename_bytes);
248 errno = err;
249 if (errno)
250 return PyErr_SetFromErrno(PyExc_OSError);
251 Py_RETURN_NONE;
252 }
253
254 PyDoc_STRVAR(doc_write_history_file,
255 "write_history_file([filename]) -> None\n\
256 Save a readline history file.\n\
257 The default filename is ~/.history.");
258
259
260 #ifdef HAVE_RL_APPEND_HISTORY
261 /* Exported function to save part of a readline history file */
262
263 static PyObject *
append_history_file(PyObject * self,PyObject * args)264 append_history_file(PyObject *self, PyObject *args)
265 {
266 int nelements;
267 PyObject *filename_obj = Py_None, *filename_bytes;
268 char *filename;
269 int err;
270 if (!PyArg_ParseTuple(args, "i|O:append_history_file", &nelements, &filename_obj))
271 return NULL;
272 if (filename_obj != Py_None) {
273 if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
274 return NULL;
275 filename = PyBytes_AsString(filename_bytes);
276 } else {
277 filename_bytes = NULL;
278 filename = NULL;
279 }
280 errno = err = append_history(nelements, filename);
281 if (!err && _history_length >= 0)
282 history_truncate_file(filename, _history_length);
283 Py_XDECREF(filename_bytes);
284 errno = err;
285 if (errno)
286 return PyErr_SetFromErrno(PyExc_OSError);
287 Py_RETURN_NONE;
288 }
289
290 PyDoc_STRVAR(doc_append_history_file,
291 "append_history_file(nelements[, filename]) -> None\n\
292 Append the last nelements items of the history list to file.\n\
293 The default filename is ~/.history.");
294 #endif
295
296
297 /* Set history length */
298
299 static PyObject*
set_history_length(PyObject * self,PyObject * args)300 set_history_length(PyObject *self, PyObject *args)
301 {
302 int length = _history_length;
303 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
304 return NULL;
305 _history_length = length;
306 Py_RETURN_NONE;
307 }
308
309 PyDoc_STRVAR(set_history_length_doc,
310 "set_history_length(length) -> None\n\
311 set the maximal number of lines which will be written to\n\
312 the history file. A negative length is used to inhibit\n\
313 history truncation.");
314
315
316 /* Get history length */
317
318 static PyObject*
get_history_length(PyObject * self,PyObject * noarg)319 get_history_length(PyObject *self, PyObject *noarg)
320 {
321 return PyLong_FromLong(_history_length);
322 }
323
324 PyDoc_STRVAR(get_history_length_doc,
325 "get_history_length() -> int\n\
326 return the maximum number of lines that will be written to\n\
327 the history file.");
328
329
330 /* Generic hook function setter */
331
332 static PyObject *
set_hook(const char * funcname,PyObject ** hook_var,PyObject * args)333 set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
334 {
335 PyObject *function = Py_None;
336 char buf[80];
337 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
338 if (!PyArg_ParseTuple(args, buf, &function))
339 return NULL;
340 if (function == Py_None) {
341 Py_CLEAR(*hook_var);
342 }
343 else if (PyCallable_Check(function)) {
344 Py_INCREF(function);
345 Py_XSETREF(*hook_var, function);
346 }
347 else {
348 PyErr_Format(PyExc_TypeError,
349 "set_%.50s(func): argument not callable",
350 funcname);
351 return NULL;
352 }
353 Py_RETURN_NONE;
354 }
355
356
357 static PyObject *
set_completion_display_matches_hook(PyObject * self,PyObject * args)358 set_completion_display_matches_hook(PyObject *self, PyObject *args)
359 {
360 PyObject *result = set_hook("completion_display_matches_hook",
361 &readlinestate_global->completion_display_matches_hook, args);
362 #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
363 /* We cannot set this hook globally, since it replaces the
364 default completion display. */
365 rl_completion_display_matches_hook =
366 readlinestate_global->completion_display_matches_hook ?
367 #if defined(_RL_FUNCTION_TYPEDEF)
368 (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
369 #else
370 (VFunction *)on_completion_display_matches_hook : 0;
371 #endif
372 #endif
373 return result;
374
375 }
376
377 PyDoc_STRVAR(doc_set_completion_display_matches_hook,
378 "set_completion_display_matches_hook([function]) -> None\n\
379 Set or remove the completion display function.\n\
380 The function is called as\n\
381 function(substitution, [matches], longest_match_length)\n\
382 once each time matches need to be displayed.");
383
384 static PyObject *
set_startup_hook(PyObject * self,PyObject * args)385 set_startup_hook(PyObject *self, PyObject *args)
386 {
387 return set_hook("startup_hook", &readlinestate_global->startup_hook, args);
388 }
389
390 PyDoc_STRVAR(doc_set_startup_hook,
391 "set_startup_hook([function]) -> None\n\
392 Set or remove the function invoked by the rl_startup_hook callback.\n\
393 The function is called with no arguments just\n\
394 before readline prints the first prompt.");
395
396
397 #ifdef HAVE_RL_PRE_INPUT_HOOK
398
399 /* Set pre-input hook */
400
401 static PyObject *
set_pre_input_hook(PyObject * self,PyObject * args)402 set_pre_input_hook(PyObject *self, PyObject *args)
403 {
404 return set_hook("pre_input_hook", &readlinestate_global->pre_input_hook, args);
405 }
406
407 PyDoc_STRVAR(doc_set_pre_input_hook,
408 "set_pre_input_hook([function]) -> None\n\
409 Set or remove the function invoked by the rl_pre_input_hook callback.\n\
410 The function is called with no arguments after the first prompt\n\
411 has been printed and just before readline starts reading input\n\
412 characters.");
413
414 #endif
415
416
417 /* Get the completion type for the scope of the tab-completion */
418 static PyObject *
get_completion_type(PyObject * self,PyObject * noarg)419 get_completion_type(PyObject *self, PyObject *noarg)
420 {
421 return PyLong_FromLong(rl_completion_type);
422 }
423
424 PyDoc_STRVAR(doc_get_completion_type,
425 "get_completion_type() -> int\n\
426 Get the type of completion being attempted.");
427
428
429 /* Get the beginning index for the scope of the tab-completion */
430
431 static PyObject *
get_begidx(PyObject * self,PyObject * noarg)432 get_begidx(PyObject *self, PyObject *noarg)
433 {
434 Py_INCREF(readlinestate_global->begidx);
435 return readlinestate_global->begidx;
436 }
437
438 PyDoc_STRVAR(doc_get_begidx,
439 "get_begidx() -> int\n\
440 get the beginning index of the completion scope");
441
442
443 /* Get the ending index for the scope of the tab-completion */
444
445 static PyObject *
get_endidx(PyObject * self,PyObject * noarg)446 get_endidx(PyObject *self, PyObject *noarg)
447 {
448 Py_INCREF(readlinestate_global->endidx);
449 return readlinestate_global->endidx;
450 }
451
452 PyDoc_STRVAR(doc_get_endidx,
453 "get_endidx() -> int\n\
454 get the ending index of the completion scope");
455
456
457 /* Set the tab-completion word-delimiters that readline uses */
458
459 static PyObject *
set_completer_delims(PyObject * self,PyObject * string)460 set_completer_delims(PyObject *self, PyObject *string)
461 {
462 char *break_chars;
463 PyObject *encoded = encode(string);
464 if (encoded == NULL) {
465 return NULL;
466 }
467 /* Keep a reference to the allocated memory in the module state in case
468 some other module modifies rl_completer_word_break_characters
469 (see issue #17289). */
470 break_chars = strdup(PyBytes_AS_STRING(encoded));
471 Py_DECREF(encoded);
472 if (break_chars) {
473 free(completer_word_break_characters);
474 completer_word_break_characters = break_chars;
475 rl_completer_word_break_characters = break_chars;
476 Py_RETURN_NONE;
477 }
478 else
479 return PyErr_NoMemory();
480 }
481
482 PyDoc_STRVAR(doc_set_completer_delims,
483 "set_completer_delims(string) -> None\n\
484 set the word delimiters for completion");
485
486 /* _py_free_history_entry: Utility function to free a history entry. */
487
488 #if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0500
489
490 /* Readline version >= 5.0 introduced a timestamp field into the history entry
491 structure; this needs to be freed to avoid a memory leak. This version of
492 readline also introduced the handy 'free_history_entry' function, which
493 takes care of the timestamp. */
494
495 static void
_py_free_history_entry(HIST_ENTRY * entry)496 _py_free_history_entry(HIST_ENTRY *entry)
497 {
498 histdata_t data = free_history_entry(entry);
499 free(data);
500 }
501
502 #else
503
504 /* No free_history_entry function; free everything manually. */
505
506 static void
_py_free_history_entry(HIST_ENTRY * entry)507 _py_free_history_entry(HIST_ENTRY *entry)
508 {
509 if (entry->line)
510 free((void *)entry->line);
511 if (entry->data)
512 free(entry->data);
513 free(entry);
514 }
515
516 #endif
517
518 static PyObject *
py_remove_history(PyObject * self,PyObject * args)519 py_remove_history(PyObject *self, PyObject *args)
520 {
521 int entry_number;
522 HIST_ENTRY *entry;
523
524 if (!PyArg_ParseTuple(args, "i:remove_history_item", &entry_number))
525 return NULL;
526 if (entry_number < 0) {
527 PyErr_SetString(PyExc_ValueError,
528 "History index cannot be negative");
529 return NULL;
530 }
531 entry = remove_history(entry_number);
532 if (!entry) {
533 PyErr_Format(PyExc_ValueError,
534 "No history item at position %d",
535 entry_number);
536 return NULL;
537 }
538 /* free memory allocated for the history entry */
539 _py_free_history_entry(entry);
540 Py_RETURN_NONE;
541 }
542
543 PyDoc_STRVAR(doc_remove_history,
544 "remove_history_item(pos) -> None\n\
545 remove history item given by its position");
546
547 static PyObject *
py_replace_history(PyObject * self,PyObject * args)548 py_replace_history(PyObject *self, PyObject *args)
549 {
550 int entry_number;
551 PyObject *line;
552 PyObject *encoded;
553 HIST_ENTRY *old_entry;
554
555 if (!PyArg_ParseTuple(args, "iU:replace_history_item", &entry_number,
556 &line)) {
557 return NULL;
558 }
559 if (entry_number < 0) {
560 PyErr_SetString(PyExc_ValueError,
561 "History index cannot be negative");
562 return NULL;
563 }
564 encoded = encode(line);
565 if (encoded == NULL) {
566 return NULL;
567 }
568 old_entry = replace_history_entry(entry_number, PyBytes_AS_STRING(encoded), (void *)NULL);
569 Py_DECREF(encoded);
570 if (!old_entry) {
571 PyErr_Format(PyExc_ValueError,
572 "No history item at position %d",
573 entry_number);
574 return NULL;
575 }
576 /* free memory allocated for the old history entry */
577 _py_free_history_entry(old_entry);
578 Py_RETURN_NONE;
579 }
580
581 PyDoc_STRVAR(doc_replace_history,
582 "replace_history_item(pos, line) -> None\n\
583 replaces history item given by its position with contents of line");
584
585 /* Add a line to the history buffer */
586
587 static PyObject *
py_add_history(PyObject * self,PyObject * string)588 py_add_history(PyObject *self, PyObject *string)
589 {
590 PyObject *encoded = encode(string);
591 if (encoded == NULL) {
592 return NULL;
593 }
594 add_history(PyBytes_AS_STRING(encoded));
595 Py_DECREF(encoded);
596 Py_RETURN_NONE;
597 }
598
599 PyDoc_STRVAR(doc_add_history,
600 "add_history(string) -> None\n\
601 add an item to the history buffer");
602
603 static int should_auto_add_history = 1;
604
605 /* Enable or disable automatic history */
606
607 static PyObject *
py_set_auto_history(PyObject * self,PyObject * args)608 py_set_auto_history(PyObject *self, PyObject *args)
609 {
610 if (!PyArg_ParseTuple(args, "p:set_auto_history",
611 &should_auto_add_history)) {
612 return NULL;
613 }
614 Py_RETURN_NONE;
615 }
616
617 PyDoc_STRVAR(doc_set_auto_history,
618 "set_auto_history(enabled) -> None\n\
619 Enables or disables automatic history.");
620
621
622 /* Get the tab-completion word-delimiters that readline uses */
623
624 static PyObject *
get_completer_delims(PyObject * self,PyObject * noarg)625 get_completer_delims(PyObject *self, PyObject *noarg)
626 {
627 return decode(rl_completer_word_break_characters);
628 }
629
630 PyDoc_STRVAR(doc_get_completer_delims,
631 "get_completer_delims() -> string\n\
632 get the word delimiters for completion");
633
634
635 /* Set the completer function */
636
637 static PyObject *
set_completer(PyObject * self,PyObject * args)638 set_completer(PyObject *self, PyObject *args)
639 {
640 return set_hook("completer", &readlinestate_global->completer, args);
641 }
642
643 PyDoc_STRVAR(doc_set_completer,
644 "set_completer([function]) -> None\n\
645 Set or remove the completer function.\n\
646 The function is called as function(text, state),\n\
647 for state in 0, 1, 2, ..., until it returns a non-string.\n\
648 It should return the next possible completion starting with 'text'.");
649
650
651 static PyObject *
get_completer(PyObject * self,PyObject * noargs)652 get_completer(PyObject *self, PyObject *noargs)
653 {
654 if (readlinestate_global->completer == NULL) {
655 Py_RETURN_NONE;
656 }
657 Py_INCREF(readlinestate_global->completer);
658 return readlinestate_global->completer;
659 }
660
661 PyDoc_STRVAR(doc_get_completer,
662 "get_completer() -> function\n\
663 \n\
664 Returns current completer function.");
665
666 /* Private function to get current length of history. XXX It may be
667 * possible to replace this with a direct use of history_length instead,
668 * but it's not clear whether BSD's libedit keeps history_length up to date.
669 * See issue #8065.*/
670
671 static int
_py_get_history_length(void)672 _py_get_history_length(void)
673 {
674 HISTORY_STATE *hist_st = history_get_history_state();
675 int length = hist_st->length;
676 /* the history docs don't say so, but the address of hist_st changes each
677 time history_get_history_state is called which makes me think it's
678 freshly malloc'd memory... on the other hand, the address of the last
679 line stays the same as long as history isn't extended, so it appears to
680 be malloc'd but managed by the history package... */
681 free(hist_st);
682 return length;
683 }
684
685 /* Exported function to get any element of history */
686
687 static PyObject *
get_history_item(PyObject * self,PyObject * args)688 get_history_item(PyObject *self, PyObject *args)
689 {
690 int idx = 0;
691 HIST_ENTRY *hist_ent;
692
693 if (!PyArg_ParseTuple(args, "i:get_history_item", &idx))
694 return NULL;
695 if (using_libedit_emulation) {
696 /* Older versions of libedit's readline emulation
697 * use 0-based indexes, while readline and newer
698 * versions of libedit use 1-based indexes.
699 */
700 int length = _py_get_history_length();
701
702 idx = idx - 1 + libedit_history_start;
703
704 /*
705 * Apple's readline emulation crashes when
706 * the index is out of range, therefore
707 * test for that and fail gracefully.
708 */
709 if (idx < (0 + libedit_history_start)
710 || idx >= (length + libedit_history_start)) {
711 Py_RETURN_NONE;
712 }
713 }
714 if ((hist_ent = history_get(idx)))
715 return decode(hist_ent->line);
716 else {
717 Py_RETURN_NONE;
718 }
719 }
720
721 PyDoc_STRVAR(doc_get_history_item,
722 "get_history_item() -> string\n\
723 return the current contents of history item at index.");
724
725
726 /* Exported function to get current length of history */
727
728 static PyObject *
get_current_history_length(PyObject * self,PyObject * noarg)729 get_current_history_length(PyObject *self, PyObject *noarg)
730 {
731 return PyLong_FromLong((long)_py_get_history_length());
732 }
733
734 PyDoc_STRVAR(doc_get_current_history_length,
735 "get_current_history_length() -> integer\n\
736 return the current (not the maximum) length of history.");
737
738
739 /* Exported function to read the current line buffer */
740
741 static PyObject *
get_line_buffer(PyObject * self,PyObject * noarg)742 get_line_buffer(PyObject *self, PyObject *noarg)
743 {
744 return decode(rl_line_buffer);
745 }
746
747 PyDoc_STRVAR(doc_get_line_buffer,
748 "get_line_buffer() -> string\n\
749 return the current contents of the line buffer.");
750
751
752 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
753
754 /* Exported function to clear the current history */
755
756 static PyObject *
py_clear_history(PyObject * self,PyObject * noarg)757 py_clear_history(PyObject *self, PyObject *noarg)
758 {
759 clear_history();
760 Py_RETURN_NONE;
761 }
762
763 PyDoc_STRVAR(doc_clear_history,
764 "clear_history() -> None\n\
765 Clear the current readline history.");
766 #endif
767
768
769 /* Exported function to insert text into the line buffer */
770
771 static PyObject *
insert_text(PyObject * self,PyObject * string)772 insert_text(PyObject *self, PyObject *string)
773 {
774 PyObject *encoded = encode(string);
775 if (encoded == NULL) {
776 return NULL;
777 }
778 rl_insert_text(PyBytes_AS_STRING(encoded));
779 Py_DECREF(encoded);
780 Py_RETURN_NONE;
781 }
782
783 PyDoc_STRVAR(doc_insert_text,
784 "insert_text(string) -> None\n\
785 Insert text into the line buffer at the cursor position.");
786
787
788 /* Redisplay the line buffer */
789
790 static PyObject *
redisplay(PyObject * self,PyObject * noarg)791 redisplay(PyObject *self, PyObject *noarg)
792 {
793 rl_redisplay();
794 Py_RETURN_NONE;
795 }
796
797 PyDoc_STRVAR(doc_redisplay,
798 "redisplay() -> None\n\
799 Change what's displayed on the screen to reflect the current\n\
800 contents of the line buffer.");
801
802
803 /* Table of functions exported by the module */
804
805 static struct PyMethodDef readline_methods[] =
806 {
807 {"parse_and_bind", parse_and_bind, METH_O, doc_parse_and_bind},
808 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
809 {"insert_text", insert_text, METH_O, doc_insert_text},
810 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
811 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
812 {"read_history_file", read_history_file,
813 METH_VARARGS, doc_read_history_file},
814 {"write_history_file", write_history_file,
815 METH_VARARGS, doc_write_history_file},
816 #ifdef HAVE_RL_APPEND_HISTORY
817 {"append_history_file", append_history_file,
818 METH_VARARGS, doc_append_history_file},
819 #endif
820 {"get_history_item", get_history_item,
821 METH_VARARGS, doc_get_history_item},
822 {"get_current_history_length", (PyCFunction)get_current_history_length,
823 METH_NOARGS, doc_get_current_history_length},
824 {"set_history_length", set_history_length,
825 METH_VARARGS, set_history_length_doc},
826 {"get_history_length", get_history_length,
827 METH_NOARGS, get_history_length_doc},
828 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
829 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
830 {"get_completion_type", get_completion_type,
831 METH_NOARGS, doc_get_completion_type},
832 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
833 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
834
835 {"set_completer_delims", set_completer_delims,
836 METH_O, doc_set_completer_delims},
837 {"set_auto_history", py_set_auto_history, METH_VARARGS, doc_set_auto_history},
838 {"add_history", py_add_history, METH_O, doc_add_history},
839 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
840 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
841 {"get_completer_delims", get_completer_delims,
842 METH_NOARGS, doc_get_completer_delims},
843
844 {"set_completion_display_matches_hook", set_completion_display_matches_hook,
845 METH_VARARGS, doc_set_completion_display_matches_hook},
846 {"set_startup_hook", set_startup_hook,
847 METH_VARARGS, doc_set_startup_hook},
848 #ifdef HAVE_RL_PRE_INPUT_HOOK
849 {"set_pre_input_hook", set_pre_input_hook,
850 METH_VARARGS, doc_set_pre_input_hook},
851 #endif
852 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
853 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
854 #endif
855 {0, 0}
856 };
857
858
859 /* C function to call the Python hooks. */
860
861 static int
on_hook(PyObject * func)862 on_hook(PyObject *func)
863 {
864 int result = 0;
865 if (func != NULL) {
866 PyObject *r;
867 r = _PyObject_CallNoArg(func);
868 if (r == NULL)
869 goto error;
870 if (r == Py_None)
871 result = 0;
872 else {
873 result = _PyLong_AsInt(r);
874 if (result == -1 && PyErr_Occurred())
875 goto error;
876 }
877 Py_DECREF(r);
878 goto done;
879 error:
880 PyErr_Clear();
881 Py_XDECREF(r);
882 done:
883 return result;
884 }
885 return result;
886 }
887
888 static int
889 #if defined(_RL_FUNCTION_TYPEDEF)
on_startup_hook(void)890 on_startup_hook(void)
891 #else
892 on_startup_hook()
893 #endif
894 {
895 int r;
896 PyGILState_STATE gilstate = PyGILState_Ensure();
897 r = on_hook(readlinestate_global->startup_hook);
898 PyGILState_Release(gilstate);
899 return r;
900 }
901
902 #ifdef HAVE_RL_PRE_INPUT_HOOK
903 static int
904 #if defined(_RL_FUNCTION_TYPEDEF)
on_pre_input_hook(void)905 on_pre_input_hook(void)
906 #else
907 on_pre_input_hook()
908 #endif
909 {
910 int r;
911 PyGILState_STATE gilstate = PyGILState_Ensure();
912 r = on_hook(readlinestate_global->pre_input_hook);
913 PyGILState_Release(gilstate);
914 return r;
915 }
916 #endif
917
918
919 /* C function to call the Python completion_display_matches */
920
921 #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
922 static void
on_completion_display_matches_hook(char ** matches,int num_matches,int max_length)923 on_completion_display_matches_hook(char **matches,
924 int num_matches, int max_length)
925 {
926 int i;
927 PyObject *sub, *m=NULL, *s=NULL, *r=NULL;
928 PyGILState_STATE gilstate = PyGILState_Ensure();
929 m = PyList_New(num_matches);
930 if (m == NULL)
931 goto error;
932 for (i = 0; i < num_matches; i++) {
933 s = decode(matches[i+1]);
934 if (s == NULL)
935 goto error;
936 PyList_SET_ITEM(m, i, s);
937 }
938 sub = decode(matches[0]);
939 r = PyObject_CallFunction(readlinestate_global->completion_display_matches_hook,
940 "NNi", sub, m, max_length);
941
942 m=NULL;
943
944 if (r == NULL ||
945 (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
946 goto error;
947 }
948 Py_CLEAR(r);
949
950 if (0) {
951 error:
952 PyErr_Clear();
953 Py_XDECREF(m);
954 Py_XDECREF(r);
955 }
956 PyGILState_Release(gilstate);
957 }
958
959 #endif
960
961 #ifdef HAVE_RL_RESIZE_TERMINAL
962 static volatile sig_atomic_t sigwinch_received;
963 static PyOS_sighandler_t sigwinch_ohandler;
964
965 static void
readline_sigwinch_handler(int signum)966 readline_sigwinch_handler(int signum)
967 {
968 sigwinch_received = 1;
969 if (sigwinch_ohandler &&
970 sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
971 sigwinch_ohandler(signum);
972
973 #ifndef HAVE_SIGACTION
974 /* If the handler was installed with signal() rather than sigaction(),
975 we need to reinstall it. */
976 PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
977 #endif
978 }
979 #endif
980
981 /* C function to call the Python completer. */
982
983 static char *
on_completion(const char * text,int state)984 on_completion(const char *text, int state)
985 {
986 char *result = NULL;
987 if (readlinestate_global->completer != NULL) {
988 PyObject *r = NULL, *t;
989 PyGILState_STATE gilstate = PyGILState_Ensure();
990 rl_attempted_completion_over = 1;
991 t = decode(text);
992 r = PyObject_CallFunction(readlinestate_global->completer, "Ni", t, state);
993 if (r == NULL)
994 goto error;
995 if (r == Py_None) {
996 result = NULL;
997 }
998 else {
999 PyObject *encoded = encode(r);
1000 if (encoded == NULL)
1001 goto error;
1002 result = strdup(PyBytes_AS_STRING(encoded));
1003 Py_DECREF(encoded);
1004 }
1005 Py_DECREF(r);
1006 goto done;
1007 error:
1008 PyErr_Clear();
1009 Py_XDECREF(r);
1010 done:
1011 PyGILState_Release(gilstate);
1012 return result;
1013 }
1014 return result;
1015 }
1016
1017
1018 /* A more flexible constructor that saves the "begidx" and "endidx"
1019 * before calling the normal completer */
1020
1021 static char **
flex_complete(const char * text,int start,int end)1022 flex_complete(const char *text, int start, int end)
1023 {
1024 char **result;
1025 char saved;
1026 size_t start_size, end_size;
1027 wchar_t *s;
1028 PyGILState_STATE gilstate = PyGILState_Ensure();
1029 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1030 rl_completion_append_character ='\0';
1031 #endif
1032 #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
1033 rl_completion_suppress_append = 0;
1034 #endif
1035
1036 saved = rl_line_buffer[start];
1037 rl_line_buffer[start] = 0;
1038 s = Py_DecodeLocale(rl_line_buffer, &start_size);
1039 rl_line_buffer[start] = saved;
1040 if (s == NULL) {
1041 goto done;
1042 }
1043 PyMem_RawFree(s);
1044 saved = rl_line_buffer[end];
1045 rl_line_buffer[end] = 0;
1046 s = Py_DecodeLocale(rl_line_buffer + start, &end_size);
1047 rl_line_buffer[end] = saved;
1048 if (s == NULL) {
1049 goto done;
1050 }
1051 PyMem_RawFree(s);
1052 start = (int)start_size;
1053 end = start + (int)end_size;
1054
1055 done:
1056 Py_XDECREF(readlinestate_global->begidx);
1057 Py_XDECREF(readlinestate_global->endidx);
1058 readlinestate_global->begidx = PyLong_FromLong((long) start);
1059 readlinestate_global->endidx = PyLong_FromLong((long) end);
1060 result = completion_matches((char *)text, *on_completion);
1061 PyGILState_Release(gilstate);
1062 return result;
1063 }
1064
1065
1066 /* Helper to initialize GNU readline properly. */
1067
1068 static void
setup_readline(readlinestate * mod_state)1069 setup_readline(readlinestate *mod_state)
1070 {
1071 #ifdef SAVE_LOCALE
1072 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1073 if (!saved_locale)
1074 Py_FatalError("not enough memory to save locale");
1075 #endif
1076
1077 /* The name must be defined before initialization */
1078 rl_readline_name = "python";
1079
1080 /* the libedit readline emulation resets key bindings etc
1081 * when calling rl_initialize. So call it upfront
1082 */
1083 if (using_libedit_emulation)
1084 rl_initialize();
1085
1086 /* Detect if libedit's readline emulation uses 0-based
1087 * indexing or 1-based indexing.
1088 */
1089 add_history("1");
1090 if (history_get(1) == NULL) {
1091 libedit_history_start = 0;
1092 } else {
1093 libedit_history_start = 1;
1094 }
1095 clear_history();
1096
1097 using_history();
1098
1099 /* Force rebind of TAB to insert-tab */
1100 rl_bind_key('\t', rl_insert);
1101 /* Bind both ESC-TAB and ESC-ESC to the completion function */
1102 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1103 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
1104 #ifdef HAVE_RL_RESIZE_TERMINAL
1105 /* Set up signal handler for window resize */
1106 sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1107 #endif
1108 /* Set our hook functions */
1109 rl_startup_hook = on_startup_hook;
1110 #ifdef HAVE_RL_PRE_INPUT_HOOK
1111 rl_pre_input_hook = on_pre_input_hook;
1112 #endif
1113 /* Set our completion function */
1114 rl_attempted_completion_function = flex_complete;
1115 /* Set Python word break characters */
1116 completer_word_break_characters =
1117 rl_completer_word_break_characters =
1118 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1119 /* All nonalphanums except '.' */
1120
1121 mod_state->begidx = PyLong_FromLong(0L);
1122 mod_state->endidx = PyLong_FromLong(0L);
1123
1124 if (!using_libedit_emulation)
1125 {
1126 if (!isatty(STDOUT_FILENO)) {
1127 /* Issue #19884: stdout is not a terminal. Disable meta modifier
1128 keys to not write the ANSI sequence "\033[1034h" into stdout. On
1129 terminals supporting 8 bit characters like TERM=xterm-256color
1130 (which is now the default Fedora since Fedora 18), the meta key is
1131 used to enable support of 8 bit characters (ANSI sequence
1132 "\033[1034h").
1133
1134 With libedit, this call makes readline() crash. */
1135 rl_variable_bind ("enable-meta-key", "off");
1136 }
1137 }
1138
1139 /* Initialize (allows .inputrc to override)
1140 *
1141 * XXX: A bug in the readline-2.2 library causes a memory leak
1142 * inside this function. Nothing we can do about it.
1143 */
1144 if (using_libedit_emulation)
1145 rl_read_init_file(NULL);
1146 else
1147 rl_initialize();
1148
1149 RESTORE_LOCALE(saved_locale)
1150 }
1151
1152 /* Wrapper around GNU readline that handles signals differently. */
1153
1154 static char *completed_input_string;
1155 static void
rlhandler(char * text)1156 rlhandler(char *text)
1157 {
1158 completed_input_string = text;
1159 rl_callback_handler_remove();
1160 }
1161
1162 static char *
readline_until_enter_or_signal(const char * prompt,int * signal)1163 readline_until_enter_or_signal(const char *prompt, int *signal)
1164 {
1165 char * not_done_reading = "";
1166 fd_set selectset;
1167
1168 *signal = 0;
1169 #ifdef HAVE_RL_CATCH_SIGNAL
1170 rl_catch_signals = 0;
1171 #endif
1172
1173 rl_callback_handler_install (prompt, rlhandler);
1174 FD_ZERO(&selectset);
1175
1176 completed_input_string = not_done_reading;
1177
1178 while (completed_input_string == not_done_reading) {
1179 int has_input = 0, err = 0;
1180
1181 while (!has_input)
1182 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
1183
1184 /* [Bug #1552726] Only limit the pause if an input hook has been
1185 defined. */
1186 struct timeval *timeoutp = NULL;
1187 if (PyOS_InputHook)
1188 timeoutp = &timeout;
1189 #ifdef HAVE_RL_RESIZE_TERMINAL
1190 /* Update readline's view of the window size after SIGWINCH */
1191 if (sigwinch_received) {
1192 sigwinch_received = 0;
1193 rl_resize_terminal();
1194 }
1195 #endif
1196 FD_SET(fileno(rl_instream), &selectset);
1197 /* select resets selectset if no input was available */
1198 has_input = select(fileno(rl_instream) + 1, &selectset,
1199 NULL, NULL, timeoutp);
1200 err = errno;
1201 if(PyOS_InputHook) PyOS_InputHook();
1202 }
1203
1204 if (has_input > 0) {
1205 rl_callback_read_char();
1206 }
1207 else if (err == EINTR) {
1208 int s;
1209 PyEval_RestoreThread(_PyOS_ReadlineTState);
1210 s = PyErr_CheckSignals();
1211 PyEval_SaveThread();
1212 if (s < 0) {
1213 rl_free_line_state();
1214 #if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1215 rl_callback_sigcleanup();
1216 #endif
1217 rl_cleanup_after_signal();
1218 rl_callback_handler_remove();
1219 *signal = 1;
1220 completed_input_string = NULL;
1221 }
1222 }
1223 }
1224
1225 return completed_input_string;
1226 }
1227
1228
1229 static char *
call_readline(FILE * sys_stdin,FILE * sys_stdout,const char * prompt)1230 call_readline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt)
1231 {
1232 size_t n;
1233 char *p;
1234 int signal;
1235
1236 #ifdef SAVE_LOCALE
1237 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1238 if (!saved_locale)
1239 Py_FatalError("not enough memory to save locale");
1240 _Py_SetLocaleFromEnv(LC_CTYPE);
1241 #endif
1242
1243 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1244 rl_instream = sys_stdin;
1245 rl_outstream = sys_stdout;
1246 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1247 rl_prep_terminal (1);
1248 #endif
1249 }
1250
1251 p = readline_until_enter_or_signal(prompt, &signal);
1252
1253 /* we got an interrupt signal */
1254 if (signal) {
1255 RESTORE_LOCALE(saved_locale)
1256 return NULL;
1257 }
1258
1259 /* We got an EOF, return an empty string. */
1260 if (p == NULL) {
1261 p = PyMem_RawMalloc(1);
1262 if (p != NULL)
1263 *p = '\0';
1264 RESTORE_LOCALE(saved_locale)
1265 return p;
1266 }
1267
1268 /* we have a valid line */
1269 n = strlen(p);
1270 if (should_auto_add_history && n > 0) {
1271 const char *line;
1272 int length = _py_get_history_length();
1273 if (length > 0) {
1274 HIST_ENTRY *hist_ent;
1275 if (using_libedit_emulation) {
1276 /* handle older 0-based or newer 1-based indexing */
1277 hist_ent = history_get(length + libedit_history_start - 1);
1278 } else
1279 hist_ent = history_get(length);
1280 line = hist_ent ? hist_ent->line : "";
1281 } else
1282 line = "";
1283 if (strcmp(p, line))
1284 add_history(p);
1285 }
1286 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1287 release the original. */
1288 char *q = p;
1289 p = PyMem_RawMalloc(n+2);
1290 if (p != NULL) {
1291 memcpy(p, q, n);
1292 p[n] = '\n';
1293 p[n+1] = '\0';
1294 }
1295 free(q);
1296 RESTORE_LOCALE(saved_locale)
1297 return p;
1298 }
1299
1300
1301 /* Initialize the module */
1302
1303 PyDoc_STRVAR(doc_module,
1304 "Importing this module enables command line editing using GNU readline.");
1305
1306 PyDoc_STRVAR(doc_module_le,
1307 "Importing this module enables command line editing using libedit readline.");
1308
1309 static struct PyModuleDef readlinemodule = {
1310 PyModuleDef_HEAD_INIT,
1311 "readline",
1312 doc_module,
1313 sizeof(readlinestate),
1314 readline_methods,
1315 NULL,
1316 readline_traverse,
1317 readline_clear,
1318 readline_free
1319 };
1320
1321
1322 PyMODINIT_FUNC
PyInit_readline(void)1323 PyInit_readline(void)
1324 {
1325 PyObject *m;
1326 readlinestate *mod_state;
1327
1328 if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1329 using_libedit_emulation = 1;
1330 }
1331
1332 if (using_libedit_emulation)
1333 readlinemodule.m_doc = doc_module_le;
1334
1335
1336 m = PyModule_Create(&readlinemodule);
1337
1338 if (m == NULL)
1339 return NULL;
1340
1341 if (PyModule_AddIntConstant(m, "_READLINE_VERSION",
1342 RL_READLINE_VERSION) < 0) {
1343 goto error;
1344 }
1345 if (PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION",
1346 rl_readline_version) < 0) {
1347 goto error;
1348 }
1349 if (PyModule_AddStringConstant(m, "_READLINE_LIBRARY_VERSION",
1350 rl_library_version) < 0)
1351 {
1352 goto error;
1353 }
1354
1355 mod_state = (readlinestate *) PyModule_GetState(m);
1356 PyOS_ReadlineFunctionPointer = call_readline;
1357 setup_readline(mod_state);
1358
1359 return m;
1360
1361 error:
1362 Py_DECREF(m);
1363 return NULL;
1364 }
1365