Line data Source code
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)
45 : extern char **completion_matches(char *, rl_compentry_func_t *);
46 : #else
47 :
48 : #if !defined(__APPLE__)
49 : extern 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 : */
69 : static int using_libedit_emulation = 0;
70 : static const char libedit_version_tag[] = "EditLine wrapper";
71 :
72 : static int8_t libedit_history_start = 0;
73 : static int8_t libedit_append_replace_history_offset = 0;
74 :
75 : #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
76 : static void
77 : on_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). */
83 : static char *completer_word_break_characters;
84 :
85 : typedef 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 :
96 : static inline readlinestate*
97 1293 : get_readline_state(PyObject *module)
98 : {
99 1293 : void *state = PyModule_GetState(module);
100 1293 : assert(state != NULL);
101 1293 : return (readlinestate *)state;
102 : }
103 :
104 : /*[clinic input]
105 : module readline
106 : [clinic start generated code]*/
107 : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ad49da781b9c8721]*/
108 :
109 : static int
110 99 : readline_clear(PyObject *m)
111 : {
112 99 : readlinestate *state = get_readline_state(m);
113 99 : Py_CLEAR(state->completion_display_matches_hook);
114 99 : Py_CLEAR(state->startup_hook);
115 99 : Py_CLEAR(state->pre_input_hook);
116 99 : Py_CLEAR(state->completer);
117 99 : Py_CLEAR(state->begidx);
118 99 : Py_CLEAR(state->endidx);
119 99 : return 0;
120 : }
121 :
122 : static int
123 1194 : readline_traverse(PyObject *m, visitproc visit, void *arg)
124 : {
125 1194 : readlinestate *state = get_readline_state(m);
126 1194 : Py_VISIT(state->completion_display_matches_hook);
127 1194 : Py_VISIT(state->startup_hook);
128 1194 : Py_VISIT(state->pre_input_hook);
129 1194 : Py_VISIT(state->completer);
130 1194 : Py_VISIT(state->begidx);
131 1194 : Py_VISIT(state->endidx);
132 1194 : return 0;
133 : }
134 :
135 : static void
136 93 : readline_free(void *m)
137 : {
138 93 : readline_clear((PyObject *)m);
139 93 : }
140 :
141 : static PyModuleDef readlinemodule;
142 :
143 : #define readlinestate_global ((readlinestate *)PyModule_GetState(PyState_FindModule(&readlinemodule)))
144 :
145 :
146 : /* Convert to/from multibyte C strings */
147 :
148 : static PyObject *
149 1392 : encode(PyObject *b)
150 : {
151 1392 : return PyUnicode_EncodeLocale(b, "surrogateescape");
152 : }
153 :
154 : static PyObject *
155 26 : decode(const char *s)
156 : {
157 26 : return PyUnicode_DecodeLocale(s, "surrogateescape");
158 : }
159 :
160 :
161 : /*
162 : Explicitly disable bracketed paste in the interactive interpreter, even if it's
163 : set in the inputrc, is enabled by default (eg GNU Readline 8.1), or a user calls
164 : readline.read_init_file(). The Python REPL has not implemented bracketed
165 : paste support. Also, bracketed mode writes the "\x1b[?2004h" escape sequence
166 : into stdout which causes test failures in applications that don't support it.
167 : It can still be explicitly enabled by calling readline.parse_and_bind("set
168 : enable-bracketed-paste on"). See bpo-42819 for more details.
169 :
170 : This should be removed if bracketed paste mode is implemented (bpo-39820).
171 : */
172 :
173 : static void
174 106 : disable_bracketed_paste(void)
175 : {
176 106 : if (!using_libedit_emulation) {
177 106 : rl_variable_bind ("enable-bracketed-paste", "off");
178 : }
179 106 : }
180 :
181 : /* Exported function to send one line to readline's init file parser */
182 :
183 : /*[clinic input]
184 : readline.parse_and_bind
185 :
186 : string: object
187 : /
188 :
189 : Execute the init line provided in the string argument.
190 : [clinic start generated code]*/
191 :
192 : static PyObject *
193 196 : readline_parse_and_bind(PyObject *module, PyObject *string)
194 : /*[clinic end generated code: output=1a1ede8afb9546c1 input=8a28a00bb4d61eec]*/
195 : {
196 : char *copy;
197 196 : PyObject *encoded = encode(string);
198 196 : if (encoded == NULL) {
199 0 : return NULL;
200 : }
201 : /* Make a copy -- rl_parse_and_bind() modifies its argument */
202 : /* Bernard Herzog */
203 196 : copy = PyMem_Malloc(1 + PyBytes_GET_SIZE(encoded));
204 196 : if (copy == NULL) {
205 0 : Py_DECREF(encoded);
206 0 : return PyErr_NoMemory();
207 : }
208 196 : strcpy(copy, PyBytes_AS_STRING(encoded));
209 196 : Py_DECREF(encoded);
210 196 : rl_parse_and_bind(copy);
211 196 : PyMem_Free(copy); /* Free the copy */
212 196 : Py_RETURN_NONE;
213 : }
214 :
215 : /* Exported function to parse a readline init file */
216 :
217 : /*[clinic input]
218 : readline.read_init_file
219 :
220 : filename as filename_obj: object = None
221 : /
222 :
223 : Execute a readline initialization file.
224 :
225 : The default filename is the last filename used.
226 : [clinic start generated code]*/
227 :
228 : static PyObject *
229 13 : readline_read_init_file_impl(PyObject *module, PyObject *filename_obj)
230 : /*[clinic end generated code: output=8e059b676142831e input=4c80c473e448139d]*/
231 : {
232 : PyObject *filename_bytes;
233 13 : if (filename_obj != Py_None) {
234 0 : if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
235 0 : return NULL;
236 0 : errno = rl_read_init_file(PyBytes_AS_STRING(filename_bytes));
237 0 : Py_DECREF(filename_bytes);
238 : } else
239 13 : errno = rl_read_init_file(NULL);
240 13 : if (errno)
241 0 : return PyErr_SetFromErrno(PyExc_OSError);
242 13 : disable_bracketed_paste();
243 13 : Py_RETURN_NONE;
244 : }
245 :
246 : /* Exported function to load a readline history file */
247 :
248 : /*[clinic input]
249 : readline.read_history_file
250 :
251 : filename as filename_obj: object = None
252 : /
253 :
254 : Load a readline history file.
255 :
256 : The default filename is ~/.history.
257 : [clinic start generated code]*/
258 :
259 : static PyObject *
260 17 : readline_read_history_file_impl(PyObject *module, PyObject *filename_obj)
261 : /*[clinic end generated code: output=66a951836fb54fbb input=3d29d755b7e6932e]*/
262 : {
263 : PyObject *filename_bytes;
264 17 : if (filename_obj != Py_None) {
265 17 : if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
266 0 : return NULL;
267 17 : errno = read_history(PyBytes_AS_STRING(filename_bytes));
268 17 : Py_DECREF(filename_bytes);
269 : } else
270 0 : errno = read_history(NULL);
271 17 : if (errno)
272 1 : return PyErr_SetFromErrno(PyExc_OSError);
273 16 : Py_RETURN_NONE;
274 : }
275 :
276 : static int _history_length = -1; /* do not truncate history by default */
277 :
278 : /* Exported function to save a readline history file */
279 :
280 : /*[clinic input]
281 : readline.write_history_file
282 :
283 : filename as filename_obj: object = None
284 : /
285 :
286 : Save a readline history file.
287 :
288 : The default filename is ~/.history.
289 : [clinic start generated code]*/
290 :
291 : static PyObject *
292 17 : readline_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 17 : if (filename_obj != Py_None) {
299 17 : if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
300 1 : return NULL;
301 16 : filename = PyBytes_AS_STRING(filename_bytes);
302 : } else {
303 0 : filename_bytes = NULL;
304 0 : filename = NULL;
305 : }
306 16 : errno = err = write_history(filename);
307 16 : if (!err && _history_length >= 0)
308 0 : history_truncate_file(filename, _history_length);
309 16 : Py_XDECREF(filename_bytes);
310 16 : errno = err;
311 16 : if (errno)
312 0 : return PyErr_SetFromErrno(PyExc_OSError);
313 16 : 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]
320 : readline.append_history_file
321 :
322 : nelements: int
323 : filename as filename_obj: object = None
324 : /
325 :
326 : Append the last nelements items of the history list to file.
327 :
328 : The default filename is ~/.history.
329 : [clinic start generated code]*/
330 :
331 : static PyObject *
332 2 : readline_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 2 : if (filename_obj != Py_None) {
340 2 : if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
341 0 : return NULL;
342 2 : filename = PyBytes_AS_STRING(filename_bytes);
343 : } else {
344 0 : filename_bytes = NULL;
345 0 : filename = NULL;
346 : }
347 2 : errno = err = append_history(
348 : nelements - libedit_append_replace_history_offset, filename);
349 2 : if (!err && _history_length >= 0)
350 0 : history_truncate_file(filename, _history_length);
351 2 : Py_XDECREF(filename_bytes);
352 2 : errno = err;
353 2 : if (errno)
354 1 : return PyErr_SetFromErrno(PyExc_OSError);
355 1 : Py_RETURN_NONE;
356 : }
357 : #endif
358 :
359 :
360 : /* Set history length */
361 :
362 : /*[clinic input]
363 : readline.set_history_length
364 :
365 : length: int
366 : /
367 :
368 : Set the maximal number of lines which will be written to the history file.
369 :
370 : A negative length is used to inhibit history truncation.
371 : [clinic start generated code]*/
372 :
373 : static PyObject *
374 0 : readline_set_history_length_impl(PyObject *module, int length)
375 : /*[clinic end generated code: output=e161a53e45987dc7 input=b8901bf16488b760]*/
376 : {
377 0 : _history_length = length;
378 0 : Py_RETURN_NONE;
379 : }
380 :
381 : /* Get history length */
382 :
383 : /*[clinic input]
384 : readline.get_history_length
385 :
386 : Return the maximum number of lines that will be written to the history file.
387 : [clinic start generated code]*/
388 :
389 : static PyObject *
390 0 : readline_get_history_length_impl(PyObject *module)
391 : /*[clinic end generated code: output=83a2eeae35b6d2b9 input=5dce2eeba4327817]*/
392 : {
393 0 : return PyLong_FromLong(_history_length);
394 : }
395 :
396 : /* Generic hook function setter */
397 :
398 : static PyObject *
399 387 : set_hook(const char *funcname, PyObject **hook_var, PyObject *function)
400 : {
401 387 : if (function == Py_None) {
402 98 : Py_CLEAR(*hook_var);
403 : }
404 289 : else if (PyCallable_Check(function)) {
405 289 : Py_INCREF(function);
406 289 : Py_XSETREF(*hook_var, function);
407 : }
408 : else {
409 0 : PyErr_Format(PyExc_TypeError,
410 : "set_%.50s(func): argument not callable",
411 : funcname);
412 0 : return NULL;
413 : }
414 387 : Py_RETURN_NONE;
415 : }
416 :
417 : /*[clinic input]
418 : readline.set_completion_display_matches_hook
419 :
420 : function: object = None
421 : /
422 :
423 : Set or remove the completion display function.
424 :
425 : The function is called as
426 : function(substitution, [matches], longest_match_length)
427 : once each time matches need to be displayed.
428 : [clinic start generated code]*/
429 :
430 : static PyObject *
431 1 : readline_set_completion_display_matches_hook_impl(PyObject *module,
432 : PyObject *function)
433 : /*[clinic end generated code: output=516e5cb8db75a328 input=4f0bfd5ab0179a26]*/
434 : {
435 1 : PyObject *result = set_hook("completion_display_matches_hook",
436 1 : &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 1 : rl_completion_display_matches_hook =
442 1 : readlinestate_global->completion_display_matches_hook ?
443 : #if defined(_RL_FUNCTION_TYPEDEF)
444 1 : (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 1 : return result;
450 :
451 : }
452 :
453 : /*[clinic input]
454 : readline.set_startup_hook
455 :
456 : function: object = None
457 : /
458 :
459 : Set or remove the function invoked by the rl_startup_hook callback.
460 :
461 : The function is called with no arguments just
462 : before readline prints the first prompt.
463 : [clinic start generated code]*/
464 :
465 : static PyObject *
466 0 : readline_set_startup_hook_impl(PyObject *module, PyObject *function)
467 : /*[clinic end generated code: output=02cd0e0c4fa082ad input=7783b4334b26d16d]*/
468 : {
469 0 : 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]
478 : readline.set_pre_input_hook
479 :
480 : function: object = None
481 : /
482 :
483 : Set or remove the function invoked by the rl_pre_input_hook callback.
484 :
485 : The function is called with no arguments after the first prompt
486 : has been printed and just before readline starts reading input
487 : characters.
488 : [clinic start generated code]*/
489 :
490 : static PyObject *
491 1 : readline_set_pre_input_hook_impl(PyObject *module, PyObject *function)
492 : /*[clinic end generated code: output=fe1a96505096f464 input=4f3eaeaf7ce1fdbe]*/
493 : {
494 1 : 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]
503 : readline.get_completion_type
504 :
505 : Get the type of completion being attempted.
506 : [clinic start generated code]*/
507 :
508 : static PyObject *
509 0 : readline_get_completion_type_impl(PyObject *module)
510 : /*[clinic end generated code: output=5c54d58a04997c07 input=04b92bc7a82dac91]*/
511 : {
512 0 : return PyLong_FromLong(rl_completion_type);
513 : }
514 :
515 : /* Get the beginning index for the scope of the tab-completion */
516 :
517 : /*[clinic input]
518 : readline.get_begidx
519 :
520 : Get the beginning index of the completion scope.
521 : [clinic start generated code]*/
522 :
523 : static PyObject *
524 2 : readline_get_begidx_impl(PyObject *module)
525 : /*[clinic end generated code: output=362616ee8ed1b2b1 input=e083b81c8eb4bac3]*/
526 : {
527 2 : Py_INCREF(readlinestate_global->begidx);
528 2 : return readlinestate_global->begidx;
529 : }
530 :
531 : /* Get the ending index for the scope of the tab-completion */
532 :
533 : /*[clinic input]
534 : readline.get_endidx
535 :
536 : Get the ending index of the completion scope.
537 : [clinic start generated code]*/
538 :
539 : static PyObject *
540 2 : readline_get_endidx_impl(PyObject *module)
541 : /*[clinic end generated code: output=7f763350b12d7517 input=d4c7e34a625fd770]*/
542 : {
543 2 : Py_INCREF(readlinestate_global->endidx);
544 2 : return readlinestate_global->endidx;
545 : }
546 :
547 : /* Set the tab-completion word-delimiters that readline uses */
548 :
549 : /*[clinic input]
550 : readline.set_completer_delims
551 :
552 : string: object
553 : /
554 :
555 : Set the word delimiters for completion.
556 : [clinic start generated code]*/
557 :
558 : static PyObject *
559 1173 : readline_set_completer_delims(PyObject *module, PyObject *string)
560 : /*[clinic end generated code: output=4305b266106c4f1f input=ae945337ebd01e20]*/
561 : {
562 : char *break_chars;
563 1173 : PyObject *encoded = encode(string);
564 1173 : if (encoded == NULL) {
565 0 : 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 1173 : break_chars = strdup(PyBytes_AS_STRING(encoded));
571 1173 : Py_DECREF(encoded);
572 1173 : if (break_chars) {
573 1173 : free(completer_word_break_characters);
574 1173 : completer_word_break_characters = break_chars;
575 1173 : rl_completer_word_break_characters = break_chars;
576 1173 : Py_RETURN_NONE;
577 : }
578 : else
579 0 : 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 :
591 : static void
592 96 : _py_free_history_entry(HIST_ENTRY *entry)
593 : {
594 96 : histdata_t data = free_history_entry(entry);
595 96 : free(data);
596 96 : }
597 :
598 : #else
599 :
600 : /* No free_history_entry function; free everything manually. */
601 :
602 : static 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]
615 : readline.remove_history_item
616 :
617 : pos as entry_number: int
618 : /
619 :
620 : Remove history item given by its zero-based position.
621 : [clinic start generated code]*/
622 :
623 : static PyObject *
624 1 : readline_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 1 : if (entry_number < 0) {
630 0 : PyErr_SetString(PyExc_ValueError,
631 : "History index cannot be negative");
632 0 : return NULL;
633 : }
634 1 : entry = remove_history(entry_number);
635 1 : if (!entry) {
636 0 : PyErr_Format(PyExc_ValueError,
637 : "No history item at position %d",
638 : entry_number);
639 0 : return NULL;
640 : }
641 : /* free memory allocated for the history entry */
642 1 : _py_free_history_entry(entry);
643 1 : Py_RETURN_NONE;
644 : }
645 :
646 : /*[clinic input]
647 : readline.replace_history_item
648 :
649 : pos as entry_number: int
650 : line: unicode
651 : /
652 :
653 : Replaces history item given by its position with contents of line.
654 :
655 : pos is zero-based.
656 : [clinic start generated code]*/
657 :
658 : static PyObject *
659 2 : readline_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 2 : if (entry_number < 0) {
667 0 : PyErr_SetString(PyExc_ValueError,
668 : "History index cannot be negative");
669 0 : return NULL;
670 : }
671 2 : encoded = encode(line);
672 2 : if (encoded == NULL) {
673 0 : return NULL;
674 : }
675 2 : old_entry = replace_history_entry(
676 : entry_number + libedit_append_replace_history_offset,
677 2 : PyBytes_AS_STRING(encoded), (void *)NULL);
678 2 : Py_DECREF(encoded);
679 2 : if (!old_entry) {
680 0 : PyErr_Format(PyExc_ValueError,
681 : "No history item at position %d",
682 : entry_number);
683 0 : return NULL;
684 : }
685 : /* free memory allocated for the old history entry */
686 2 : _py_free_history_entry(old_entry);
687 2 : Py_RETURN_NONE;
688 : }
689 :
690 : /* Add a line to the history buffer */
691 :
692 : /*[clinic input]
693 : readline.add_history
694 :
695 : string: object
696 : /
697 :
698 : Add an item to the history buffer.
699 : [clinic start generated code]*/
700 :
701 : static PyObject *
702 7 : readline_add_history(PyObject *module, PyObject *string)
703 : /*[clinic end generated code: output=b107b7e8106e803d input=e57c1cf6bc68d7e3]*/
704 : {
705 7 : PyObject *encoded = encode(string);
706 7 : if (encoded == NULL) {
707 0 : return NULL;
708 : }
709 7 : add_history(PyBytes_AS_STRING(encoded));
710 7 : Py_DECREF(encoded);
711 7 : Py_RETURN_NONE;
712 : }
713 :
714 : static int should_auto_add_history = 1;
715 :
716 : /* Enable or disable automatic history */
717 :
718 : /*[clinic input]
719 : readline.set_auto_history
720 :
721 : enabled as _should_auto_add_history: bool
722 : /
723 :
724 : Enables or disables automatic history.
725 : [clinic start generated code]*/
726 :
727 : static PyObject *
728 2 : readline_set_auto_history_impl(PyObject *module,
729 : int _should_auto_add_history)
730 : /*[clinic end generated code: output=619c6968246fd82b input=3d413073a1a03355]*/
731 : {
732 2 : should_auto_add_history = _should_auto_add_history;
733 2 : Py_RETURN_NONE;
734 : }
735 :
736 :
737 : /* Get the tab-completion word-delimiters that readline uses */
738 :
739 : /*[clinic input]
740 : readline.get_completer_delims
741 :
742 : Get the word delimiters for completion.
743 : [clinic start generated code]*/
744 :
745 : static PyObject *
746 0 : readline_get_completer_delims_impl(PyObject *module)
747 : /*[clinic end generated code: output=6b060280fa68ef43 input=e36eb14fb8a1f08a]*/
748 : {
749 0 : return decode(rl_completer_word_break_characters);
750 : }
751 :
752 : /* Set the completer function */
753 :
754 : /*[clinic input]
755 : readline.set_completer
756 :
757 : function: object = None
758 : /
759 :
760 : Set or remove the completer function.
761 :
762 : The function is called as function(text, state),
763 : for state in 0, 1, 2, ..., until it returns a non-string.
764 : It should return the next possible completion starting with 'text'.
765 : [clinic start generated code]*/
766 :
767 : static PyObject *
768 385 : readline_set_completer_impl(PyObject *module, PyObject *function)
769 : /*[clinic end generated code: output=171a2a60f81d3204 input=51e81e13118eb877]*/
770 : {
771 385 : return set_hook("completer", &readlinestate_global->completer, function);
772 : }
773 :
774 : /*[clinic input]
775 : readline.get_completer
776 :
777 : Get the current completer function.
778 : [clinic start generated code]*/
779 :
780 : static PyObject *
781 177 : readline_get_completer_impl(PyObject *module)
782 : /*[clinic end generated code: output=6e6bbd8226d14475 input=6457522e56d70d13]*/
783 : {
784 177 : if (readlinestate_global->completer == NULL) {
785 84 : Py_RETURN_NONE;
786 : }
787 93 : Py_INCREF(readlinestate_global->completer);
788 93 : 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 :
796 : static int
797 23 : _py_get_history_length(void)
798 : {
799 23 : HISTORY_STATE *hist_st = history_get_history_state();
800 23 : 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 23 : free(hist_st);
807 23 : return length;
808 : }
809 :
810 : /* Exported function to get any element of history */
811 :
812 : /*[clinic input]
813 : readline.get_history_item
814 :
815 : index as idx: int
816 : /
817 :
818 : Return the current contents of history item at one-based index.
819 : [clinic start generated code]*/
820 :
821 : static PyObject *
822 16 : readline_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 16 : 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 0 : int length = _py_get_history_length();
833 :
834 0 : 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 0 : if (idx < (0 + libedit_history_start)
842 0 : || idx >= (length + libedit_history_start)) {
843 0 : Py_RETURN_NONE;
844 : }
845 : }
846 16 : if ((hist_ent = history_get(idx)))
847 13 : return decode(hist_ent->line);
848 : else {
849 3 : Py_RETURN_NONE;
850 : }
851 : }
852 :
853 : /* Exported function to get current length of history */
854 :
855 : /*[clinic input]
856 : readline.get_current_history_length
857 :
858 : Return the current (not the maximum) length of history.
859 : [clinic start generated code]*/
860 :
861 : static PyObject *
862 20 : readline_get_current_history_length_impl(PyObject *module)
863 : /*[clinic end generated code: output=436b294f12ba1e3f input=9cb3f431a68d071f]*/
864 : {
865 20 : return PyLong_FromLong((long)_py_get_history_length());
866 : }
867 :
868 : /* Exported function to read the current line buffer */
869 :
870 : /*[clinic input]
871 : readline.get_line_buffer
872 :
873 : Return the current contents of the line buffer.
874 : [clinic start generated code]*/
875 :
876 : static PyObject *
877 2 : readline_get_line_buffer_impl(PyObject *module)
878 : /*[clinic end generated code: output=d22f9025ecad80e4 input=5f5fbc0d12c69412]*/
879 : {
880 2 : 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]
888 : readline.clear_history
889 :
890 : Clear the current readline history.
891 : [clinic start generated code]*/
892 :
893 : static PyObject *
894 6 : readline_clear_history_impl(PyObject *module)
895 : /*[clinic end generated code: output=1f2dbb0dfa5d5ebb input=208962c4393f5d16]*/
896 : {
897 6 : clear_history();
898 6 : Py_RETURN_NONE;
899 : }
900 : #endif
901 :
902 :
903 : /* Exported function to insert text into the line buffer */
904 :
905 : /*[clinic input]
906 : readline.insert_text
907 :
908 : string: object
909 : /
910 :
911 : Insert text into the line buffer at the cursor position.
912 : [clinic start generated code]*/
913 :
914 : static PyObject *
915 9 : readline_insert_text(PyObject *module, PyObject *string)
916 : /*[clinic end generated code: output=23d792821d320c19 input=bc96c3c848d5ccb5]*/
917 : {
918 9 : PyObject *encoded = encode(string);
919 9 : if (encoded == NULL) {
920 0 : return NULL;
921 : }
922 9 : rl_insert_text(PyBytes_AS_STRING(encoded));
923 9 : Py_DECREF(encoded);
924 9 : Py_RETURN_NONE;
925 : }
926 :
927 : /* Redisplay the line buffer */
928 :
929 : /*[clinic input]
930 : readline.redisplay
931 :
932 : Change what's displayed on the screen to reflect contents of the line buffer.
933 : [clinic start generated code]*/
934 :
935 : static PyObject *
936 9 : readline_redisplay_impl(PyObject *module)
937 : /*[clinic end generated code: output=a8b9725827c3c34b input=b485151058d75edc]*/
938 : {
939 9 : rl_redisplay();
940 9 : Py_RETURN_NONE;
941 : }
942 :
943 : #include "clinic/readline.c.h"
944 :
945 : /* Table of functions exported by the module */
946 :
947 : static 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 :
988 : static int
989 8 : on_hook(PyObject *func)
990 : {
991 8 : int result = 0;
992 8 : if (func != NULL) {
993 : PyObject *r;
994 1 : r = PyObject_CallNoArgs(func);
995 1 : if (r == NULL)
996 0 : goto error;
997 1 : if (r == Py_None)
998 1 : result = 0;
999 : else {
1000 0 : result = _PyLong_AsInt(r);
1001 0 : if (result == -1 && PyErr_Occurred())
1002 0 : goto error;
1003 : }
1004 1 : Py_DECREF(r);
1005 1 : goto done;
1006 0 : error:
1007 0 : PyErr_Clear();
1008 0 : Py_XDECREF(r);
1009 1 : done:
1010 1 : return result;
1011 : }
1012 7 : return result;
1013 : }
1014 :
1015 : static int
1016 : #if defined(_RL_FUNCTION_TYPEDEF)
1017 4 : on_startup_hook(void)
1018 : #else
1019 : on_startup_hook()
1020 : #endif
1021 : {
1022 : int r;
1023 4 : PyGILState_STATE gilstate = PyGILState_Ensure();
1024 4 : r = on_hook(readlinestate_global->startup_hook);
1025 4 : PyGILState_Release(gilstate);
1026 4 : return r;
1027 : }
1028 :
1029 : #ifdef HAVE_RL_PRE_INPUT_HOOK
1030 : static int
1031 : #if defined(_RL_FUNCTION_TYPEDEF)
1032 4 : on_pre_input_hook(void)
1033 : #else
1034 : on_pre_input_hook()
1035 : #endif
1036 : {
1037 : int r;
1038 4 : PyGILState_STATE gilstate = PyGILState_Ensure();
1039 4 : r = on_hook(readlinestate_global->pre_input_hook);
1040 4 : PyGILState_Release(gilstate);
1041 4 : 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
1049 : static void
1050 1 : on_completion_display_matches_hook(char **matches,
1051 : int num_matches, int max_length)
1052 : {
1053 : int i;
1054 1 : PyObject *sub, *m=NULL, *s=NULL, *r=NULL;
1055 1 : PyGILState_STATE gilstate = PyGILState_Ensure();
1056 1 : m = PyList_New(num_matches);
1057 1 : if (m == NULL)
1058 0 : goto error;
1059 3 : for (i = 0; i < num_matches; i++) {
1060 2 : s = decode(matches[i+1]);
1061 2 : if (s == NULL)
1062 0 : goto error;
1063 2 : PyList_SET_ITEM(m, i, s);
1064 : }
1065 1 : sub = decode(matches[0]);
1066 1 : r = PyObject_CallFunction(readlinestate_global->completion_display_matches_hook,
1067 : "NNi", sub, m, max_length);
1068 :
1069 1 : m=NULL;
1070 :
1071 1 : if (r == NULL ||
1072 0 : (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
1073 0 : goto error;
1074 : }
1075 1 : Py_CLEAR(r);
1076 :
1077 : if (0) {
1078 0 : error:
1079 0 : PyErr_Clear();
1080 0 : Py_XDECREF(m);
1081 0 : Py_XDECREF(r);
1082 : }
1083 1 : PyGILState_Release(gilstate);
1084 1 : }
1085 :
1086 : #endif
1087 :
1088 : #ifdef HAVE_RL_RESIZE_TERMINAL
1089 : static volatile sig_atomic_t sigwinch_received;
1090 : static PyOS_sighandler_t sigwinch_ohandler;
1091 :
1092 : static void
1093 0 : readline_sigwinch_handler(int signum)
1094 : {
1095 0 : sigwinch_received = 1;
1096 0 : if (sigwinch_ohandler &&
1097 0 : sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
1098 0 : 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 0 : }
1106 : #endif
1107 :
1108 : /* C function to call the Python completer. */
1109 :
1110 : static char *
1111 8 : on_completion(const char *text, int state)
1112 : {
1113 8 : char *result = NULL;
1114 8 : if (readlinestate_global->completer != NULL) {
1115 8 : PyObject *r = NULL, *t;
1116 8 : PyGILState_STATE gilstate = PyGILState_Ensure();
1117 8 : rl_attempted_completion_over = 1;
1118 8 : t = decode(text);
1119 8 : r = PyObject_CallFunction(readlinestate_global->completer, "Ni", t, state);
1120 8 : if (r == NULL)
1121 0 : goto error;
1122 8 : if (r == Py_None) {
1123 3 : result = NULL;
1124 : }
1125 : else {
1126 5 : PyObject *encoded = encode(r);
1127 5 : if (encoded == NULL)
1128 0 : goto error;
1129 5 : result = strdup(PyBytes_AS_STRING(encoded));
1130 5 : Py_DECREF(encoded);
1131 : }
1132 8 : Py_DECREF(r);
1133 8 : goto done;
1134 0 : error:
1135 0 : PyErr_Clear();
1136 0 : Py_XDECREF(r);
1137 8 : done:
1138 8 : PyGILState_Release(gilstate);
1139 8 : return result;
1140 : }
1141 0 : return result;
1142 : }
1143 :
1144 :
1145 : /* A more flexible constructor that saves the "begidx" and "endidx"
1146 : * before calling the normal completer */
1147 :
1148 : static char **
1149 3 : flex_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 3 : PyGILState_STATE gilstate = PyGILState_Ensure();
1156 : #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1157 3 : rl_completion_append_character ='\0';
1158 : #endif
1159 : #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
1160 3 : rl_completion_suppress_append = 0;
1161 : #endif
1162 :
1163 3 : saved = rl_line_buffer[start];
1164 3 : rl_line_buffer[start] = 0;
1165 3 : s = Py_DecodeLocale(rl_line_buffer, &start_size);
1166 3 : rl_line_buffer[start] = saved;
1167 3 : if (s == NULL) {
1168 0 : goto done;
1169 : }
1170 3 : PyMem_RawFree(s);
1171 3 : saved = rl_line_buffer[end];
1172 3 : rl_line_buffer[end] = 0;
1173 3 : s = Py_DecodeLocale(rl_line_buffer + start, &end_size);
1174 3 : rl_line_buffer[end] = saved;
1175 3 : if (s == NULL) {
1176 0 : goto done;
1177 : }
1178 3 : PyMem_RawFree(s);
1179 3 : start = (int)start_size;
1180 3 : end = start + (int)end_size;
1181 :
1182 3 : done:
1183 3 : Py_XDECREF(readlinestate_global->begidx);
1184 3 : Py_XDECREF(readlinestate_global->endidx);
1185 3 : readlinestate_global->begidx = PyLong_FromLong((long) start);
1186 3 : readlinestate_global->endidx = PyLong_FromLong((long) end);
1187 3 : result = completion_matches((char *)text, *on_completion);
1188 3 : PyGILState_Release(gilstate);
1189 3 : return result;
1190 : }
1191 :
1192 :
1193 : /* Helper to initialize GNU readline properly.
1194 : Return -1 on memory allocation failure, return 0 on success. */
1195 : static int
1196 93 : setup_readline(readlinestate *mod_state)
1197 : {
1198 : #ifdef SAVE_LOCALE
1199 93 : char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1200 93 : if (!saved_locale) {
1201 0 : return -1;
1202 : }
1203 : #endif
1204 :
1205 : /* The name must be defined before initialization */
1206 93 : 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 93 : if (using_libedit_emulation)
1212 0 : rl_initialize();
1213 :
1214 : /* Detect if libedit's readline emulation uses 0-based
1215 : * indexing or 1-based indexing.
1216 : */
1217 93 : add_history("1");
1218 93 : if (history_get(1) == NULL) {
1219 0 : libedit_history_start = 0;
1220 : } else {
1221 93 : 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 93 : add_history("2");
1230 93 : HIST_ENTRY *old_entry = replace_history_entry(1, "X", NULL);
1231 93 : _py_free_history_entry(old_entry);
1232 93 : HIST_ENTRY *item = history_get(libedit_history_start);
1233 93 : if (item && item->line && strcmp(item->line, "X")) {
1234 93 : libedit_append_replace_history_offset = 0;
1235 : } else {
1236 0 : libedit_append_replace_history_offset = 1;
1237 : }
1238 : }
1239 93 : clear_history();
1240 :
1241 93 : using_history();
1242 :
1243 : /* Force rebind of TAB to insert-tab */
1244 93 : rl_bind_key('\t', rl_insert);
1245 : /* Bind both ESC-TAB and ESC-ESC to the completion function */
1246 93 : rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1247 93 : 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 93 : sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1251 : #endif
1252 : /* Set our hook functions */
1253 93 : rl_startup_hook = on_startup_hook;
1254 : #ifdef HAVE_RL_PRE_INPUT_HOOK
1255 93 : rl_pre_input_hook = on_pre_input_hook;
1256 : #endif
1257 : /* Set our completion function */
1258 93 : rl_attempted_completion_function = flex_complete;
1259 : /* Set Python word break characters */
1260 93 : completer_word_break_characters =
1261 93 : rl_completer_word_break_characters =
1262 93 : strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1263 : /* All nonalphanums except '.' */
1264 :
1265 93 : mod_state->begidx = PyLong_FromLong(0L);
1266 93 : mod_state->endidx = PyLong_FromLong(0L);
1267 :
1268 93 : if (!using_libedit_emulation)
1269 : {
1270 93 : 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 89 : 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 93 : if (using_libedit_emulation)
1289 0 : rl_read_init_file(NULL);
1290 : else
1291 93 : rl_initialize();
1292 :
1293 93 : disable_bracketed_paste();
1294 :
1295 93 : RESTORE_LOCALE(saved_locale)
1296 93 : return 0;
1297 : }
1298 :
1299 : /* Wrapper around GNU readline that handles signals differently. */
1300 :
1301 : static char *completed_input_string;
1302 : static void
1303 4 : rlhandler(char *text)
1304 : {
1305 4 : completed_input_string = text;
1306 4 : rl_callback_handler_remove();
1307 4 : }
1308 :
1309 : static char *
1310 4 : readline_until_enter_or_signal(const char *prompt, int *signal)
1311 : {
1312 4 : char * not_done_reading = "";
1313 : fd_set selectset;
1314 :
1315 4 : *signal = 0;
1316 : #ifdef HAVE_RL_CATCH_SIGNAL
1317 4 : rl_catch_signals = 0;
1318 : #endif
1319 :
1320 4 : rl_callback_handler_install (prompt, rlhandler);
1321 4 : FD_ZERO(&selectset);
1322 :
1323 4 : completed_input_string = not_done_reading;
1324 :
1325 18 : while (completed_input_string == not_done_reading) {
1326 14 : int has_input = 0, err = 0;
1327 :
1328 28 : while (!has_input)
1329 14 : { 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 14 : struct timeval *timeoutp = NULL;
1334 14 : if (PyOS_InputHook)
1335 0 : timeoutp = &timeout;
1336 : #ifdef HAVE_RL_RESIZE_TERMINAL
1337 : /* Update readline's view of the window size after SIGWINCH */
1338 14 : if (sigwinch_received) {
1339 0 : sigwinch_received = 0;
1340 0 : rl_resize_terminal();
1341 : }
1342 : #endif
1343 14 : FD_SET(fileno(rl_instream), &selectset);
1344 : /* select resets selectset if no input was available */
1345 14 : has_input = select(fileno(rl_instream) + 1, &selectset,
1346 : NULL, NULL, timeoutp);
1347 14 : err = errno;
1348 14 : if(PyOS_InputHook) PyOS_InputHook();
1349 : }
1350 :
1351 14 : if (has_input > 0) {
1352 14 : rl_callback_read_char();
1353 : }
1354 0 : else if (err == EINTR) {
1355 : int s;
1356 0 : PyEval_RestoreThread(_PyOS_ReadlineTState);
1357 0 : s = PyErr_CheckSignals();
1358 0 : PyEval_SaveThread();
1359 0 : if (s < 0) {
1360 0 : rl_free_line_state();
1361 : #if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1362 0 : rl_callback_sigcleanup();
1363 : #endif
1364 0 : rl_cleanup_after_signal();
1365 0 : rl_callback_handler_remove();
1366 0 : *signal = 1;
1367 0 : completed_input_string = NULL;
1368 : }
1369 : }
1370 : }
1371 :
1372 4 : return completed_input_string;
1373 : }
1374 :
1375 :
1376 : static char *
1377 4 : call_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 4 : char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1385 4 : if (!saved_locale)
1386 0 : Py_FatalError("not enough memory to save locale");
1387 4 : _Py_SetLocaleFromEnv(LC_CTYPE);
1388 : #endif
1389 :
1390 4 : if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1391 0 : rl_instream = sys_stdin;
1392 0 : rl_outstream = sys_stdout;
1393 : #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1394 0 : rl_prep_terminal (1);
1395 : #endif
1396 : }
1397 :
1398 4 : p = readline_until_enter_or_signal(prompt, &signal);
1399 :
1400 : /* we got an interrupt signal */
1401 4 : if (signal) {
1402 0 : RESTORE_LOCALE(saved_locale)
1403 0 : return NULL;
1404 : }
1405 :
1406 : /* We got an EOF, return an empty string. */
1407 4 : if (p == NULL) {
1408 0 : p = PyMem_RawMalloc(1);
1409 0 : if (p != NULL)
1410 0 : *p = '\0';
1411 0 : RESTORE_LOCALE(saved_locale)
1412 0 : return p;
1413 : }
1414 :
1415 : /* we have a valid line */
1416 4 : n = strlen(p);
1417 4 : if (should_auto_add_history && n > 0) {
1418 : const char *line;
1419 3 : int length = _py_get_history_length();
1420 3 : if (length > 0) {
1421 : HIST_ENTRY *hist_ent;
1422 1 : if (using_libedit_emulation) {
1423 : /* handle older 0-based or newer 1-based indexing */
1424 0 : hist_ent = history_get(length + libedit_history_start - 1);
1425 : } else
1426 1 : hist_ent = history_get(length);
1427 1 : line = hist_ent ? hist_ent->line : "";
1428 : } else
1429 2 : line = "";
1430 3 : if (strcmp(p, line))
1431 3 : add_history(p);
1432 : }
1433 : /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1434 : release the original. */
1435 4 : char *q = p;
1436 4 : p = PyMem_RawMalloc(n+2);
1437 4 : if (p != NULL) {
1438 4 : memcpy(p, q, n);
1439 4 : p[n] = '\n';
1440 4 : p[n+1] = '\0';
1441 : }
1442 4 : free(q);
1443 4 : RESTORE_LOCALE(saved_locale)
1444 4 : return p;
1445 : }
1446 :
1447 :
1448 : /* Initialize the module */
1449 :
1450 : PyDoc_STRVAR(doc_module,
1451 : "Importing this module enables command line editing using GNU readline.");
1452 :
1453 : PyDoc_STRVAR(doc_module_le,
1454 : "Importing this module enables command line editing using libedit readline.");
1455 :
1456 : static 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 :
1469 : PyMODINIT_FUNC
1470 93 : PyInit_readline(void)
1471 : {
1472 : PyObject *m;
1473 : readlinestate *mod_state;
1474 :
1475 93 : if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1476 0 : using_libedit_emulation = 1;
1477 : }
1478 :
1479 93 : if (using_libedit_emulation)
1480 0 : readlinemodule.m_doc = doc_module_le;
1481 :
1482 :
1483 93 : m = PyModule_Create(&readlinemodule);
1484 :
1485 93 : if (m == NULL)
1486 0 : return NULL;
1487 :
1488 93 : if (PyModule_AddIntConstant(m, "_READLINE_VERSION",
1489 : RL_READLINE_VERSION) < 0) {
1490 0 : goto error;
1491 : }
1492 93 : if (PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION",
1493 : rl_readline_version) < 0) {
1494 0 : goto error;
1495 : }
1496 93 : if (PyModule_AddStringConstant(m, "_READLINE_LIBRARY_VERSION",
1497 : rl_library_version) < 0)
1498 : {
1499 0 : goto error;
1500 : }
1501 :
1502 93 : mod_state = (readlinestate *) PyModule_GetState(m);
1503 93 : PyOS_ReadlineFunctionPointer = call_readline;
1504 93 : if (setup_readline(mod_state) < 0) {
1505 0 : PyErr_NoMemory();
1506 0 : goto error;
1507 : }
1508 :
1509 93 : return m;
1510 :
1511 0 : error:
1512 0 : Py_DECREF(m);
1513 0 : return NULL;
1514 : }
|