Add better error reporting for MemoryErrors caused by str->float conversions.
[python.git] / Modules / readline.c
blob2db6cfb0e35fd867b2aae440426158ac9df74c16
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 */
7 /* Standard definitions */
8 #include "Python.h"
9 #include <setjmp.h>
10 #include <signal.h>
11 #include <errno.h>
12 #include <sys/time.h>
14 #if defined(HAVE_SETLOCALE)
15 /* GNU readline() mistakenly sets the LC_CTYPE locale.
16 * This is evil. Only the user or the app's main() should do this!
17 * We must save and restore the locale around the rl_initialize() call.
19 #define SAVE_LOCALE
20 #include <locale.h>
21 #endif
23 #ifdef SAVE_LOCALE
24 # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
25 #else
26 # define RESTORE_LOCALE(sl)
27 #endif
29 /* GNU readline definitions */
30 #undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
31 #include <readline/readline.h>
32 #include <readline/history.h>
34 #ifdef HAVE_RL_COMPLETION_MATCHES
35 #define completion_matches(x, y) \
36 rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
37 #else
38 #if defined(_RL_FUNCTION_TYPEDEF)
39 extern char **completion_matches(char *, rl_compentry_func_t *);
40 #else
41 extern char **completion_matches(char *, CPFunction *);
42 #endif
43 #endif
45 #ifdef __APPLE__
47 * It is possible to link the readline module to the readline
48 * emulation library of editline/libedit.
50 * On OSX this emulation library is not 100% API compatible
51 * with the "real" readline and cannot be detected at compile-time,
52 * hence we use a runtime check to detect if we're using libedit
54 * Currently there is one know API incompatibility:
55 * - 'get_history' has a 1-based index with GNU readline, and a 0-based
56 * index with libedit's emulation.
57 * - Note that replace_history and remove_history use a 0-based index
58 * with both implementation.
60 static int using_libedit_emulation = 0;
61 static const char libedit_version_tag[] = "EditLine wrapper";
62 #endif /* __APPLE__ */
64 static void
65 on_completion_display_matches_hook(char **matches,
66 int num_matches, int max_length);
69 /* Exported function to send one line to readline's init file parser */
71 static PyObject *
72 parse_and_bind(PyObject *self, PyObject *args)
74 char *s, *copy;
75 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
76 return NULL;
77 /* Make a copy -- rl_parse_and_bind() modifies its argument */
78 /* Bernard Herzog */
79 copy = malloc(1 + strlen(s));
80 if (copy == NULL)
81 return PyErr_NoMemory();
82 strcpy(copy, s);
83 rl_parse_and_bind(copy);
84 free(copy); /* Free the copy */
85 Py_RETURN_NONE;
88 PyDoc_STRVAR(doc_parse_and_bind,
89 "parse_and_bind(string) -> None\n\
90 Parse and execute single line of a readline init file.");
93 /* Exported function to parse a readline init file */
95 static PyObject *
96 read_init_file(PyObject *self, PyObject *args)
98 char *s = NULL;
99 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
100 return NULL;
101 errno = rl_read_init_file(s);
102 if (errno)
103 return PyErr_SetFromErrno(PyExc_IOError);
104 Py_RETURN_NONE;
107 PyDoc_STRVAR(doc_read_init_file,
108 "read_init_file([filename]) -> None\n\
109 Parse a readline initialization file.\n\
110 The default filename is the last filename used.");
113 /* Exported function to load a readline history file */
115 static PyObject *
116 read_history_file(PyObject *self, PyObject *args)
118 char *s = NULL;
119 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
120 return NULL;
121 errno = read_history(s);
122 if (errno)
123 return PyErr_SetFromErrno(PyExc_IOError);
124 Py_RETURN_NONE;
127 static int _history_length = -1; /* do not truncate history by default */
128 PyDoc_STRVAR(doc_read_history_file,
129 "read_history_file([filename]) -> None\n\
130 Load a readline history file.\n\
131 The default filename is ~/.history.");
134 /* Exported function to save a readline history file */
136 static PyObject *
137 write_history_file(PyObject *self, PyObject *args)
139 char *s = NULL;
140 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
141 return NULL;
142 errno = write_history(s);
143 if (!errno && _history_length >= 0)
144 history_truncate_file(s, _history_length);
145 if (errno)
146 return PyErr_SetFromErrno(PyExc_IOError);
147 Py_RETURN_NONE;
150 PyDoc_STRVAR(doc_write_history_file,
151 "write_history_file([filename]) -> None\n\
152 Save a readline history file.\n\
153 The default filename is ~/.history.");
156 /* Set history length */
158 static PyObject*
159 set_history_length(PyObject *self, PyObject *args)
161 int length = _history_length;
162 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
163 return NULL;
164 _history_length = length;
165 Py_RETURN_NONE;
168 PyDoc_STRVAR(set_history_length_doc,
169 "set_history_length(length) -> None\n\
170 set the maximal number of items which will be written to\n\
171 the history file. A negative length is used to inhibit\n\
172 history truncation.");
175 /* Get history length */
177 static PyObject*
178 get_history_length(PyObject *self, PyObject *noarg)
180 return PyInt_FromLong(_history_length);
183 PyDoc_STRVAR(get_history_length_doc,
184 "get_history_length() -> int\n\
185 return the maximum number of items that will be written to\n\
186 the history file.");
189 /* Generic hook function setter */
191 static PyObject *
192 set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
194 PyObject *function = Py_None;
195 char buf[80];
196 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
197 if (!PyArg_ParseTuple(args, buf, &function))
198 return NULL;
199 if (function == Py_None) {
200 Py_XDECREF(*hook_var);
201 *hook_var = NULL;
203 else if (PyCallable_Check(function)) {
204 PyObject *tmp = *hook_var;
205 Py_INCREF(function);
206 *hook_var = function;
207 Py_XDECREF(tmp);
209 else {
210 PyOS_snprintf(buf, sizeof(buf),
211 "set_%.50s(func): argument not callable",
212 funcname);
213 PyErr_SetString(PyExc_TypeError, buf);
214 return NULL;
216 Py_RETURN_NONE;
220 /* Exported functions to specify hook functions in Python */
222 static PyObject *completion_display_matches_hook = NULL;
223 static PyObject *startup_hook = NULL;
225 #ifdef HAVE_RL_PRE_INPUT_HOOK
226 static PyObject *pre_input_hook = NULL;
227 #endif
229 static PyObject *
230 set_completion_display_matches_hook(PyObject *self, PyObject *args)
232 PyObject *result = set_hook("completion_display_matches_hook",
233 &completion_display_matches_hook, args);
234 #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
235 /* We cannot set this hook globally, since it replaces the
236 default completion display. */
237 rl_completion_display_matches_hook =
238 completion_display_matches_hook ?
239 #if defined(_RL_FUNCTION_TYPEDEF)
240 (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
241 #else
242 (VFunction *)on_completion_display_matches_hook : 0;
243 #endif
244 #endif
245 return result;
249 PyDoc_STRVAR(doc_set_completion_display_matches_hook,
250 "set_completion_display_matches_hook([function]) -> None\n\
251 Set or remove the completion display function.\n\
252 The function is called as\n\
253 function(substitution, [matches], longest_match_length)\n\
254 once each time matches need to be displayed.");
256 static PyObject *
257 set_startup_hook(PyObject *self, PyObject *args)
259 return set_hook("startup_hook", &startup_hook, args);
262 PyDoc_STRVAR(doc_set_startup_hook,
263 "set_startup_hook([function]) -> None\n\
264 Set or remove the startup_hook function.\n\
265 The function is called with no arguments just\n\
266 before readline prints the first prompt.");
269 #ifdef HAVE_RL_PRE_INPUT_HOOK
271 /* Set pre-input hook */
273 static PyObject *
274 set_pre_input_hook(PyObject *self, PyObject *args)
276 return set_hook("pre_input_hook", &pre_input_hook, args);
279 PyDoc_STRVAR(doc_set_pre_input_hook,
280 "set_pre_input_hook([function]) -> None\n\
281 Set or remove the pre_input_hook function.\n\
282 The function is called with no arguments after the first prompt\n\
283 has been printed and just before readline starts reading input\n\
284 characters.");
286 #endif
289 /* Exported function to specify a word completer in Python */
291 static PyObject *completer = NULL;
293 static PyObject *begidx = NULL;
294 static PyObject *endidx = NULL;
297 /* Get the completion type for the scope of the tab-completion */
298 static PyObject *
299 get_completion_type(PyObject *self, PyObject *noarg)
301 return PyInt_FromLong(rl_completion_type);
304 PyDoc_STRVAR(doc_get_completion_type,
305 "get_completion_type() -> int\n\
306 Get the type of completion being attempted.");
309 /* Get the beginning index for the scope of the tab-completion */
311 static PyObject *
312 get_begidx(PyObject *self, PyObject *noarg)
314 Py_INCREF(begidx);
315 return begidx;
318 PyDoc_STRVAR(doc_get_begidx,
319 "get_begidx() -> int\n\
320 get the beginning index of the readline tab-completion scope");
323 /* Get the ending index for the scope of the tab-completion */
325 static PyObject *
326 get_endidx(PyObject *self, PyObject *noarg)
328 Py_INCREF(endidx);
329 return endidx;
332 PyDoc_STRVAR(doc_get_endidx,
333 "get_endidx() -> int\n\
334 get the ending index of the readline tab-completion scope");
337 /* Set the tab-completion word-delimiters that readline uses */
339 static PyObject *
340 set_completer_delims(PyObject *self, PyObject *args)
342 char *break_chars;
344 if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
345 return NULL;
347 free((void*)rl_completer_word_break_characters);
348 rl_completer_word_break_characters = strdup(break_chars);
349 Py_RETURN_NONE;
352 PyDoc_STRVAR(doc_set_completer_delims,
353 "set_completer_delims(string) -> None\n\
354 set the readline word delimiters for tab-completion");
356 static PyObject *
357 py_remove_history(PyObject *self, PyObject *args)
359 int entry_number;
360 HIST_ENTRY *entry;
362 if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
363 return NULL;
364 if (entry_number < 0) {
365 PyErr_SetString(PyExc_ValueError,
366 "History index cannot be negative");
367 return NULL;
369 entry = remove_history(entry_number);
370 if (!entry) {
371 PyErr_Format(PyExc_ValueError,
372 "No history item at position %d",
373 entry_number);
374 return NULL;
376 /* free memory allocated for the history entry */
377 if (entry->line)
378 free(entry->line);
379 if (entry->data)
380 free(entry->data);
381 free(entry);
383 Py_RETURN_NONE;
386 PyDoc_STRVAR(doc_remove_history,
387 "remove_history_item(pos) -> None\n\
388 remove history item given by its position");
390 static PyObject *
391 py_replace_history(PyObject *self, PyObject *args)
393 int entry_number;
394 char *line;
395 HIST_ENTRY *old_entry;
397 if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
398 &line)) {
399 return NULL;
401 if (entry_number < 0) {
402 PyErr_SetString(PyExc_ValueError,
403 "History index cannot be negative");
404 return NULL;
406 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
407 if (!old_entry) {
408 PyErr_Format(PyExc_ValueError,
409 "No history item at position %d",
410 entry_number);
411 return NULL;
413 /* free memory allocated for the old history entry */
414 if (old_entry->line)
415 free(old_entry->line);
416 if (old_entry->data)
417 free(old_entry->data);
418 free(old_entry);
420 Py_RETURN_NONE;
423 PyDoc_STRVAR(doc_replace_history,
424 "replace_history_item(pos, line) -> None\n\
425 replaces history item given by its position with contents of line");
427 /* Add a line to the history buffer */
429 static PyObject *
430 py_add_history(PyObject *self, PyObject *args)
432 char *line;
434 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
435 return NULL;
437 add_history(line);
438 Py_RETURN_NONE;
441 PyDoc_STRVAR(doc_add_history,
442 "add_history(string) -> None\n\
443 add a line to the history buffer");
446 /* Get the tab-completion word-delimiters that readline uses */
448 static PyObject *
449 get_completer_delims(PyObject *self, PyObject *noarg)
451 return PyString_FromString(rl_completer_word_break_characters);
454 PyDoc_STRVAR(doc_get_completer_delims,
455 "get_completer_delims() -> string\n\
456 get the readline word delimiters for tab-completion");
459 /* Set the completer function */
461 static PyObject *
462 set_completer(PyObject *self, PyObject *args)
464 return set_hook("completer", &completer, args);
467 PyDoc_STRVAR(doc_set_completer,
468 "set_completer([function]) -> None\n\
469 Set or remove the completer function.\n\
470 The function is called as function(text, state),\n\
471 for state in 0, 1, 2, ..., until it returns a non-string.\n\
472 It should return the next possible completion starting with 'text'.");
475 static PyObject *
476 get_completer(PyObject *self, PyObject *noargs)
478 if (completer == NULL) {
479 Py_RETURN_NONE;
481 Py_INCREF(completer);
482 return completer;
485 PyDoc_STRVAR(doc_get_completer,
486 "get_completer() -> function\n\
488 Returns current completer function.");
490 /* Exported function to get any element of history */
492 static PyObject *
493 get_history_item(PyObject *self, PyObject *args)
495 int idx = 0;
496 HIST_ENTRY *hist_ent;
498 if (!PyArg_ParseTuple(args, "i:index", &idx))
499 return NULL;
500 #ifdef __APPLE__
501 if (using_libedit_emulation) {
502 /* Libedit emulation uses 0-based indexes,
503 * the real one uses 1-based indexes,
504 * adjust the index to ensure that Python
505 * code doesn't have to worry about the
506 * difference.
508 HISTORY_STATE *hist_st;
509 hist_st = history_get_history_state();
511 idx --;
514 * Apple's readline emulation crashes when
515 * the index is out of range, therefore
516 * test for that and fail gracefully.
518 if (idx < 0 || idx >= hist_st->length) {
519 Py_RETURN_NONE;
522 #endif /* __APPLE__ */
523 if ((hist_ent = history_get(idx)))
524 return PyString_FromString(hist_ent->line);
525 else {
526 Py_RETURN_NONE;
530 PyDoc_STRVAR(doc_get_history_item,
531 "get_history_item() -> string\n\
532 return the current contents of history item at index.");
535 /* Exported function to get current length of history */
537 static PyObject *
538 get_current_history_length(PyObject *self, PyObject *noarg)
540 HISTORY_STATE *hist_st;
542 hist_st = history_get_history_state();
543 return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
546 PyDoc_STRVAR(doc_get_current_history_length,
547 "get_current_history_length() -> integer\n\
548 return the current (not the maximum) length of history.");
551 /* Exported function to read the current line buffer */
553 static PyObject *
554 get_line_buffer(PyObject *self, PyObject *noarg)
556 return PyString_FromString(rl_line_buffer);
559 PyDoc_STRVAR(doc_get_line_buffer,
560 "get_line_buffer() -> string\n\
561 return the current contents of the line buffer.");
564 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
566 /* Exported function to clear the current history */
568 static PyObject *
569 py_clear_history(PyObject *self, PyObject *noarg)
571 clear_history();
572 Py_RETURN_NONE;
575 PyDoc_STRVAR(doc_clear_history,
576 "clear_history() -> None\n\
577 Clear the current readline history.");
578 #endif
581 /* Exported function to insert text into the line buffer */
583 static PyObject *
584 insert_text(PyObject *self, PyObject *args)
586 char *s;
587 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
588 return NULL;
589 rl_insert_text(s);
590 Py_RETURN_NONE;
593 PyDoc_STRVAR(doc_insert_text,
594 "insert_text(string) -> None\n\
595 Insert text into the command line.");
598 /* Redisplay the line buffer */
600 static PyObject *
601 redisplay(PyObject *self, PyObject *noarg)
603 rl_redisplay();
604 Py_RETURN_NONE;
607 PyDoc_STRVAR(doc_redisplay,
608 "redisplay() -> None\n\
609 Change what's displayed on the screen to reflect the current\n\
610 contents of the line buffer.");
613 /* Table of functions exported by the module */
615 static struct PyMethodDef readline_methods[] =
617 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
618 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
619 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
620 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
621 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
622 {"read_history_file", read_history_file,
623 METH_VARARGS, doc_read_history_file},
624 {"write_history_file", write_history_file,
625 METH_VARARGS, doc_write_history_file},
626 {"get_history_item", get_history_item,
627 METH_VARARGS, doc_get_history_item},
628 {"get_current_history_length", (PyCFunction)get_current_history_length,
629 METH_NOARGS, doc_get_current_history_length},
630 {"set_history_length", set_history_length,
631 METH_VARARGS, set_history_length_doc},
632 {"get_history_length", get_history_length,
633 METH_NOARGS, get_history_length_doc},
634 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
635 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
636 {"get_completion_type", get_completion_type,
637 METH_NOARGS, doc_get_completion_type},
638 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
639 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
641 {"set_completer_delims", set_completer_delims,
642 METH_VARARGS, doc_set_completer_delims},
643 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
644 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
645 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
646 {"get_completer_delims", get_completer_delims,
647 METH_NOARGS, doc_get_completer_delims},
649 {"set_completion_display_matches_hook", set_completion_display_matches_hook,
650 METH_VARARGS, doc_set_completion_display_matches_hook},
651 {"set_startup_hook", set_startup_hook,
652 METH_VARARGS, doc_set_startup_hook},
653 #ifdef HAVE_RL_PRE_INPUT_HOOK
654 {"set_pre_input_hook", set_pre_input_hook,
655 METH_VARARGS, doc_set_pre_input_hook},
656 #endif
657 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
658 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
659 #endif
660 {0, 0}
664 /* C function to call the Python hooks. */
666 static int
667 on_hook(PyObject *func)
669 int result = 0;
670 if (func != NULL) {
671 PyObject *r;
672 #ifdef WITH_THREAD
673 PyGILState_STATE gilstate = PyGILState_Ensure();
674 #endif
675 r = PyObject_CallFunction(func, NULL);
676 if (r == NULL)
677 goto error;
678 if (r == Py_None)
679 result = 0;
680 else {
681 result = PyInt_AsLong(r);
682 if (result == -1 && PyErr_Occurred())
683 goto error;
685 Py_DECREF(r);
686 goto done;
687 error:
688 PyErr_Clear();
689 Py_XDECREF(r);
690 done:
691 #ifdef WITH_THREAD
692 PyGILState_Release(gilstate);
693 #endif
694 return result;
696 return result;
699 static int
700 on_startup_hook(void)
702 return on_hook(startup_hook);
705 #ifdef HAVE_RL_PRE_INPUT_HOOK
706 static int
707 on_pre_input_hook(void)
709 return on_hook(pre_input_hook);
711 #endif
714 /* C function to call the Python completion_display_matches */
716 static void
717 on_completion_display_matches_hook(char **matches,
718 int num_matches, int max_length)
720 int i;
721 PyObject *m=NULL, *s=NULL, *r=NULL;
722 #ifdef WITH_THREAD
723 PyGILState_STATE gilstate = PyGILState_Ensure();
724 #endif
725 m = PyList_New(num_matches);
726 if (m == NULL)
727 goto error;
728 for (i = 0; i < num_matches; i++) {
729 s = PyString_FromString(matches[i+1]);
730 if (s == NULL)
731 goto error;
732 if (PyList_SetItem(m, i, s) == -1)
733 goto error;
736 r = PyObject_CallFunction(completion_display_matches_hook,
737 "sOi", matches[0], m, max_length);
739 Py_DECREF(m); m=NULL;
741 if (r == NULL ||
742 (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
743 goto error;
745 Py_XDECREF(r); r=NULL;
747 if (0) {
748 error:
749 PyErr_Clear();
750 Py_XDECREF(m);
751 Py_XDECREF(r);
753 #ifdef WITH_THREAD
754 PyGILState_Release(gilstate);
755 #endif
759 /* C function to call the Python completer. */
761 static char *
762 on_completion(const char *text, int state)
764 char *result = NULL;
765 if (completer != NULL) {
766 PyObject *r;
767 #ifdef WITH_THREAD
768 PyGILState_STATE gilstate = PyGILState_Ensure();
769 #endif
770 rl_attempted_completion_over = 1;
771 r = PyObject_CallFunction(completer, "si", text, state);
772 if (r == NULL)
773 goto error;
774 if (r == Py_None) {
775 result = NULL;
777 else {
778 char *s = PyString_AsString(r);
779 if (s == NULL)
780 goto error;
781 result = strdup(s);
783 Py_DECREF(r);
784 goto done;
785 error:
786 PyErr_Clear();
787 Py_XDECREF(r);
788 done:
789 #ifdef WITH_THREAD
790 PyGILState_Release(gilstate);
791 #endif
792 return result;
794 return result;
798 /* A more flexible constructor that saves the "begidx" and "endidx"
799 * before calling the normal completer */
801 static char **
802 flex_complete(char *text, int start, int end)
804 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
805 rl_completion_append_character ='\0';
806 #endif
807 #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
808 rl_completion_suppress_append = 0;
809 #endif
810 Py_XDECREF(begidx);
811 Py_XDECREF(endidx);
812 begidx = PyInt_FromLong((long) start);
813 endidx = PyInt_FromLong((long) end);
814 return completion_matches(text, *on_completion);
818 /* Helper to initialize GNU readline properly. */
820 static void
821 setup_readline(void)
823 #ifdef SAVE_LOCALE
824 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
825 if (!saved_locale)
826 Py_FatalError("not enough memory to save locale");
827 #endif
829 using_history();
831 rl_readline_name = "python";
832 #if defined(PYOS_OS2) && defined(PYCC_GCC)
833 /* Allow $if term= in .inputrc to work */
834 rl_terminal_name = getenv("TERM");
835 #endif
836 /* Force rebind of TAB to insert-tab */
837 rl_bind_key('\t', rl_insert);
838 /* Bind both ESC-TAB and ESC-ESC to the completion function */
839 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
840 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
841 /* Set our hook functions */
842 rl_startup_hook = (Function *)on_startup_hook;
843 #ifdef HAVE_RL_PRE_INPUT_HOOK
844 rl_pre_input_hook = (Function *)on_pre_input_hook;
845 #endif
846 /* Set our completion function */
847 rl_attempted_completion_function = (CPPFunction *)flex_complete;
848 /* Set Python word break characters */
849 rl_completer_word_break_characters =
850 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
851 /* All nonalphanums except '.' */
853 begidx = PyInt_FromLong(0L);
854 endidx = PyInt_FromLong(0L);
855 /* Initialize (allows .inputrc to override)
857 * XXX: A bug in the readline-2.2 library causes a memory leak
858 * inside this function. Nothing we can do about it.
860 rl_initialize();
862 RESTORE_LOCALE(saved_locale)
865 /* Wrapper around GNU readline that handles signals differently. */
868 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
870 static char *completed_input_string;
871 static void
872 rlhandler(char *text)
874 completed_input_string = text;
875 rl_callback_handler_remove();
878 extern PyThreadState* _PyOS_ReadlineTState;
880 static char *
881 readline_until_enter_or_signal(char *prompt, int *signal)
883 char * not_done_reading = "";
884 fd_set selectset;
886 *signal = 0;
887 #ifdef HAVE_RL_CATCH_SIGNAL
888 rl_catch_signals = 0;
889 #endif
891 rl_callback_handler_install (prompt, rlhandler);
892 FD_ZERO(&selectset);
894 completed_input_string = not_done_reading;
896 while (completed_input_string == not_done_reading) {
897 int has_input = 0;
899 while (!has_input)
900 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
902 /* [Bug #1552726] Only limit the pause if an input hook has been
903 defined. */
904 struct timeval *timeoutp = NULL;
905 if (PyOS_InputHook)
906 timeoutp = &timeout;
907 FD_SET(fileno(rl_instream), &selectset);
908 /* select resets selectset if no input was available */
909 has_input = select(fileno(rl_instream) + 1, &selectset,
910 NULL, NULL, timeoutp);
911 if(PyOS_InputHook) PyOS_InputHook();
914 if(has_input > 0) {
915 rl_callback_read_char();
917 else if (errno == EINTR) {
918 int s;
919 #ifdef WITH_THREAD
920 PyEval_RestoreThread(_PyOS_ReadlineTState);
921 #endif
922 s = PyErr_CheckSignals();
923 #ifdef WITH_THREAD
924 PyEval_SaveThread();
925 #endif
926 if (s < 0) {
927 rl_free_line_state();
928 rl_cleanup_after_signal();
929 rl_callback_handler_remove();
930 *signal = 1;
931 completed_input_string = NULL;
936 return completed_input_string;
940 #else
942 /* Interrupt handler */
944 static jmp_buf jbuf;
946 /* ARGSUSED */
947 static void
948 onintr(int sig)
950 longjmp(jbuf, 1);
954 static char *
955 readline_until_enter_or_signal(char *prompt, int *signal)
957 PyOS_sighandler_t old_inthandler;
958 char *p;
960 *signal = 0;
962 old_inthandler = PyOS_setsig(SIGINT, onintr);
963 if (setjmp(jbuf)) {
964 #ifdef HAVE_SIGRELSE
965 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
966 sigrelse(SIGINT);
967 #endif
968 PyOS_setsig(SIGINT, old_inthandler);
969 *signal = 1;
970 return NULL;
972 rl_event_hook = PyOS_InputHook;
973 p = readline(prompt);
974 PyOS_setsig(SIGINT, old_inthandler);
976 return p;
978 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
981 static char *
982 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
984 size_t n;
985 char *p, *q;
986 int signal;
988 #ifdef SAVE_LOCALE
989 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
990 if (!saved_locale)
991 Py_FatalError("not enough memory to save locale");
992 setlocale(LC_CTYPE, "");
993 #endif
995 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
996 rl_instream = sys_stdin;
997 rl_outstream = sys_stdout;
998 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
999 rl_prep_terminal (1);
1000 #endif
1003 p = readline_until_enter_or_signal(prompt, &signal);
1005 /* we got an interrupt signal */
1006 if (signal) {
1007 RESTORE_LOCALE(saved_locale)
1008 return NULL;
1011 /* We got an EOF, return a empty string. */
1012 if (p == NULL) {
1013 p = PyMem_Malloc(1);
1014 if (p != NULL)
1015 *p = '\0';
1016 RESTORE_LOCALE(saved_locale)
1017 return p;
1020 /* we have a valid line */
1021 n = strlen(p);
1022 if (n > 0) {
1023 char *line;
1024 HISTORY_STATE *state = history_get_history_state();
1025 if (state->length > 0)
1026 #ifdef __APPLE__
1027 if (using_libedit_emulation) {
1029 * Libedit's emulation uses 0-based indexes,
1030 * the real readline uses 1-based indexes.
1032 line = history_get(state->length - 1)->line;
1033 } else
1034 #endif /* __APPLE__ */
1035 line = history_get(state->length)->line;
1036 else
1037 line = "";
1038 if (strcmp(p, line))
1039 add_history(p);
1040 /* the history docs don't say so, but the address of state
1041 changes each time history_get_history_state is called
1042 which makes me think it's freshly malloc'd memory...
1043 on the other hand, the address of the last line stays the
1044 same as long as history isn't extended, so it appears to
1045 be malloc'd but managed by the history package... */
1046 free(state);
1048 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1049 release the original. */
1050 q = p;
1051 p = PyMem_Malloc(n+2);
1052 if (p != NULL) {
1053 strncpy(p, q, n);
1054 p[n] = '\n';
1055 p[n+1] = '\0';
1057 free(q);
1058 RESTORE_LOCALE(saved_locale)
1059 return p;
1063 /* Initialize the module */
1065 PyDoc_STRVAR(doc_module,
1066 "Importing this module enables command line editing using GNU readline.");
1068 #ifdef __APPLE__
1069 PyDoc_STRVAR(doc_module_le,
1070 "Importing this module enables command line editing using libedit readline.");
1071 #endif /* __APPLE__ */
1073 PyMODINIT_FUNC
1074 initreadline(void)
1076 PyObject *m;
1078 #ifdef __APPLE__
1079 if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1080 using_libedit_emulation = 1;
1083 if (using_libedit_emulation)
1084 m = Py_InitModule4("readline", readline_methods, doc_module_le,
1085 (PyObject *)NULL, PYTHON_API_VERSION);
1086 else
1088 #endif /* __APPLE__ */
1090 m = Py_InitModule4("readline", readline_methods, doc_module,
1091 (PyObject *)NULL, PYTHON_API_VERSION);
1092 if (m == NULL)
1093 return;
1097 PyOS_ReadlineFunctionPointer = call_readline;
1098 setup_readline();