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