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