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