Remove tuple parameter unpacking in aifc to silence warnings under -3.
[python.git] / Modules / readline.c
blob90904ab434faac37f7ade09030df7f285bb2d695
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 extern char **completion_matches(char *, rl_compentry_func_t *);
39 #endif
41 static void
42 on_completion_display_matches_hook(char **matches,
43 int num_matches, int max_length);
46 /* Exported function to send one line to readline's init file parser */
48 static PyObject *
49 parse_and_bind(PyObject *self, PyObject *args)
51 char *s, *copy;
52 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
53 return NULL;
54 /* Make a copy -- rl_parse_and_bind() modifies its argument */
55 /* Bernard Herzog */
56 copy = malloc(1 + strlen(s));
57 if (copy == NULL)
58 return PyErr_NoMemory();
59 strcpy(copy, s);
60 rl_parse_and_bind(copy);
61 free(copy); /* Free the copy */
62 Py_RETURN_NONE;
65 PyDoc_STRVAR(doc_parse_and_bind,
66 "parse_and_bind(string) -> None\n\
67 Parse and execute single line of a readline init file.");
70 /* Exported function to parse a readline init file */
72 static PyObject *
73 read_init_file(PyObject *self, PyObject *args)
75 char *s = NULL;
76 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
77 return NULL;
78 errno = rl_read_init_file(s);
79 if (errno)
80 return PyErr_SetFromErrno(PyExc_IOError);
81 Py_RETURN_NONE;
84 PyDoc_STRVAR(doc_read_init_file,
85 "read_init_file([filename]) -> None\n\
86 Parse a readline initialization file.\n\
87 The default filename is the last filename used.");
90 /* Exported function to load a readline history file */
92 static PyObject *
93 read_history_file(PyObject *self, PyObject *args)
95 char *s = NULL;
96 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
97 return NULL;
98 errno = read_history(s);
99 if (errno)
100 return PyErr_SetFromErrno(PyExc_IOError);
101 Py_RETURN_NONE;
104 static int _history_length = -1; /* do not truncate history by default */
105 PyDoc_STRVAR(doc_read_history_file,
106 "read_history_file([filename]) -> None\n\
107 Load a readline history file.\n\
108 The default filename is ~/.history.");
111 /* Exported function to save a readline history file */
113 static PyObject *
114 write_history_file(PyObject *self, PyObject *args)
116 char *s = NULL;
117 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
118 return NULL;
119 errno = write_history(s);
120 if (!errno && _history_length >= 0)
121 history_truncate_file(s, _history_length);
122 if (errno)
123 return PyErr_SetFromErrno(PyExc_IOError);
124 Py_RETURN_NONE;
127 PyDoc_STRVAR(doc_write_history_file,
128 "write_history_file([filename]) -> None\n\
129 Save a readline history file.\n\
130 The default filename is ~/.history.");
133 /* Set history length */
135 static PyObject*
136 set_history_length(PyObject *self, PyObject *args)
138 int length = _history_length;
139 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
140 return NULL;
141 _history_length = length;
142 Py_RETURN_NONE;
145 PyDoc_STRVAR(set_history_length_doc,
146 "set_history_length(length) -> None\n\
147 set the maximal number of items which will be written to\n\
148 the history file. A negative length is used to inhibit\n\
149 history truncation.");
152 /* Get history length */
154 static PyObject*
155 get_history_length(PyObject *self, PyObject *noarg)
157 return PyInt_FromLong(_history_length);
160 PyDoc_STRVAR(get_history_length_doc,
161 "get_history_length() -> int\n\
162 return the maximum number of items that will be written to\n\
163 the history file.");
166 /* Generic hook function setter */
168 static PyObject *
169 set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
171 PyObject *function = Py_None;
172 char buf[80];
173 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
174 if (!PyArg_ParseTuple(args, buf, &function))
175 return NULL;
176 if (function == Py_None) {
177 Py_XDECREF(*hook_var);
178 *hook_var = NULL;
180 else if (PyCallable_Check(function)) {
181 PyObject *tmp = *hook_var;
182 Py_INCREF(function);
183 *hook_var = function;
184 Py_XDECREF(tmp);
186 else {
187 PyOS_snprintf(buf, sizeof(buf),
188 "set_%.50s(func): argument not callable",
189 funcname);
190 PyErr_SetString(PyExc_TypeError, buf);
191 return NULL;
193 Py_RETURN_NONE;
197 /* Exported functions to specify hook functions in Python */
199 static PyObject *completion_display_matches_hook = NULL;
200 static PyObject *startup_hook = NULL;
202 #ifdef HAVE_RL_PRE_INPUT_HOOK
203 static PyObject *pre_input_hook = NULL;
204 #endif
206 static PyObject *
207 set_completion_display_matches_hook(PyObject *self, PyObject *args)
209 PyObject *result = set_hook("completion_display_matches_hook",
210 &completion_display_matches_hook, args);
211 #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
212 /* We cannot set this hook globally, since it replaces the
213 default completion display. */
214 rl_completion_display_matches_hook =
215 completion_display_matches_hook ?
216 (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
217 #endif
218 return result;
222 PyDoc_STRVAR(doc_set_completion_display_matches_hook,
223 "set_completion_display_matches_hook([function]) -> None\n\
224 Set or remove the completion display function.\n\
225 The function is called as\n\
226 function(substitution, [matches], longest_match_length)\n\
227 once each time matches need to be displayed.");
229 static PyObject *
230 set_startup_hook(PyObject *self, PyObject *args)
232 return set_hook("startup_hook", &startup_hook, args);
235 PyDoc_STRVAR(doc_set_startup_hook,
236 "set_startup_hook([function]) -> None\n\
237 Set or remove the startup_hook function.\n\
238 The function is called with no arguments just\n\
239 before readline prints the first prompt.");
242 #ifdef HAVE_RL_PRE_INPUT_HOOK
244 /* Set pre-input hook */
246 static PyObject *
247 set_pre_input_hook(PyObject *self, PyObject *args)
249 return set_hook("pre_input_hook", &pre_input_hook, args);
252 PyDoc_STRVAR(doc_set_pre_input_hook,
253 "set_pre_input_hook([function]) -> None\n\
254 Set or remove the pre_input_hook function.\n\
255 The function is called with no arguments after the first prompt\n\
256 has been printed and just before readline starts reading input\n\
257 characters.");
259 #endif
262 /* Exported function to specify a word completer in Python */
264 static PyObject *completer = NULL;
266 static PyObject *begidx = NULL;
267 static PyObject *endidx = NULL;
270 /* Get the completion type for the scope of the tab-completion */
271 static PyObject *
272 get_completion_type(PyObject *self, PyObject *noarg)
274 return PyInt_FromLong(rl_completion_type);
277 PyDoc_STRVAR(doc_get_completion_type,
278 "get_completion_type() -> int\n\
279 Get the type of completion being attempted.");
282 /* Get the beginning index for the scope of the tab-completion */
284 static PyObject *
285 get_begidx(PyObject *self, PyObject *noarg)
287 Py_INCREF(begidx);
288 return begidx;
291 PyDoc_STRVAR(doc_get_begidx,
292 "get_begidx() -> int\n\
293 get the beginning index of the readline tab-completion scope");
296 /* Get the ending index for the scope of the tab-completion */
298 static PyObject *
299 get_endidx(PyObject *self, PyObject *noarg)
301 Py_INCREF(endidx);
302 return endidx;
305 PyDoc_STRVAR(doc_get_endidx,
306 "get_endidx() -> int\n\
307 get the ending index of the readline tab-completion scope");
310 /* Set the tab-completion word-delimiters that readline uses */
312 static PyObject *
313 set_completer_delims(PyObject *self, PyObject *args)
315 char *break_chars;
317 if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
318 return NULL;
320 free((void*)rl_completer_word_break_characters);
321 rl_completer_word_break_characters = strdup(break_chars);
322 Py_RETURN_NONE;
325 PyDoc_STRVAR(doc_set_completer_delims,
326 "set_completer_delims(string) -> None\n\
327 set the readline word delimiters for tab-completion");
329 static PyObject *
330 py_remove_history(PyObject *self, PyObject *args)
332 int entry_number;
333 HIST_ENTRY *entry;
335 if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
336 return NULL;
337 if (entry_number < 0) {
338 PyErr_SetString(PyExc_ValueError,
339 "History index cannot be negative");
340 return NULL;
342 entry = remove_history(entry_number);
343 if (!entry) {
344 PyErr_Format(PyExc_ValueError,
345 "No history item at position %d",
346 entry_number);
347 return NULL;
349 /* free memory allocated for the history entry */
350 if (entry->line)
351 free(entry->line);
352 if (entry->data)
353 free(entry->data);
354 free(entry);
356 Py_RETURN_NONE;
359 PyDoc_STRVAR(doc_remove_history,
360 "remove_history_item(pos) -> None\n\
361 remove history item given by its position");
363 static PyObject *
364 py_replace_history(PyObject *self, PyObject *args)
366 int entry_number;
367 char *line;
368 HIST_ENTRY *old_entry;
370 if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
371 &line)) {
372 return NULL;
374 if (entry_number < 0) {
375 PyErr_SetString(PyExc_ValueError,
376 "History index cannot be negative");
377 return NULL;
379 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
380 if (!old_entry) {
381 PyErr_Format(PyExc_ValueError,
382 "No history item at position %d",
383 entry_number);
384 return NULL;
386 /* free memory allocated for the old history entry */
387 if (old_entry->line)
388 free(old_entry->line);
389 if (old_entry->data)
390 free(old_entry->data);
391 free(old_entry);
393 Py_RETURN_NONE;
396 PyDoc_STRVAR(doc_replace_history,
397 "replace_history_item(pos, line) -> None\n\
398 replaces history item given by its position with contents of line");
400 /* Add a line to the history buffer */
402 static PyObject *
403 py_add_history(PyObject *self, PyObject *args)
405 char *line;
407 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
408 return NULL;
410 add_history(line);
411 Py_RETURN_NONE;
414 PyDoc_STRVAR(doc_add_history,
415 "add_history(string) -> None\n\
416 add a line to the history buffer");
419 /* Get the tab-completion word-delimiters that readline uses */
421 static PyObject *
422 get_completer_delims(PyObject *self, PyObject *noarg)
424 return PyString_FromString(rl_completer_word_break_characters);
427 PyDoc_STRVAR(doc_get_completer_delims,
428 "get_completer_delims() -> string\n\
429 get the readline word delimiters for tab-completion");
432 /* Set the completer function */
434 static PyObject *
435 set_completer(PyObject *self, PyObject *args)
437 return set_hook("completer", &completer, args);
440 PyDoc_STRVAR(doc_set_completer,
441 "set_completer([function]) -> None\n\
442 Set or remove the completer function.\n\
443 The function is called as function(text, state),\n\
444 for state in 0, 1, 2, ..., until it returns a non-string.\n\
445 It should return the next possible completion starting with 'text'.");
448 static PyObject *
449 get_completer(PyObject *self, PyObject *noargs)
451 if (completer == NULL) {
452 Py_RETURN_NONE;
454 Py_INCREF(completer);
455 return completer;
458 PyDoc_STRVAR(doc_get_completer,
459 "get_completer() -> function\n\
461 Returns current completer function.");
463 /* Exported function to get any element of history */
465 static PyObject *
466 get_history_item(PyObject *self, PyObject *args)
468 int idx = 0;
469 HIST_ENTRY *hist_ent;
471 if (!PyArg_ParseTuple(args, "i:index", &idx))
472 return NULL;
473 if ((hist_ent = history_get(idx)))
474 return PyString_FromString(hist_ent->line);
475 else {
476 Py_RETURN_NONE;
480 PyDoc_STRVAR(doc_get_history_item,
481 "get_history_item() -> string\n\
482 return the current contents of history item at index.");
485 /* Exported function to get current length of history */
487 static PyObject *
488 get_current_history_length(PyObject *self, PyObject *noarg)
490 HISTORY_STATE *hist_st;
492 hist_st = history_get_history_state();
493 return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
496 PyDoc_STRVAR(doc_get_current_history_length,
497 "get_current_history_length() -> integer\n\
498 return the current (not the maximum) length of history.");
501 /* Exported function to read the current line buffer */
503 static PyObject *
504 get_line_buffer(PyObject *self, PyObject *noarg)
506 return PyString_FromString(rl_line_buffer);
509 PyDoc_STRVAR(doc_get_line_buffer,
510 "get_line_buffer() -> string\n\
511 return the current contents of the line buffer.");
514 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
516 /* Exported function to clear the current history */
518 static PyObject *
519 py_clear_history(PyObject *self, PyObject *noarg)
521 clear_history();
522 Py_RETURN_NONE;
525 PyDoc_STRVAR(doc_clear_history,
526 "clear_history() -> None\n\
527 Clear the current readline history.");
528 #endif
531 /* Exported function to insert text into the line buffer */
533 static PyObject *
534 insert_text(PyObject *self, PyObject *args)
536 char *s;
537 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
538 return NULL;
539 rl_insert_text(s);
540 Py_RETURN_NONE;
543 PyDoc_STRVAR(doc_insert_text,
544 "insert_text(string) -> None\n\
545 Insert text into the command line.");
548 /* Redisplay the line buffer */
550 static PyObject *
551 redisplay(PyObject *self, PyObject *noarg)
553 rl_redisplay();
554 Py_RETURN_NONE;
557 PyDoc_STRVAR(doc_redisplay,
558 "redisplay() -> None\n\
559 Change what's displayed on the screen to reflect the current\n\
560 contents of the line buffer.");
563 /* Table of functions exported by the module */
565 static struct PyMethodDef readline_methods[] =
567 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
568 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
569 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
570 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
571 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
572 {"read_history_file", read_history_file,
573 METH_VARARGS, doc_read_history_file},
574 {"write_history_file", write_history_file,
575 METH_VARARGS, doc_write_history_file},
576 {"get_history_item", get_history_item,
577 METH_VARARGS, doc_get_history_item},
578 {"get_current_history_length", (PyCFunction)get_current_history_length,
579 METH_NOARGS, doc_get_current_history_length},
580 {"set_history_length", set_history_length,
581 METH_VARARGS, set_history_length_doc},
582 {"get_history_length", get_history_length,
583 METH_NOARGS, get_history_length_doc},
584 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
585 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
586 {"get_completion_type", get_completion_type,
587 METH_NOARGS, doc_get_completion_type},
588 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
589 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
591 {"set_completer_delims", set_completer_delims,
592 METH_VARARGS, doc_set_completer_delims},
593 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
594 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
595 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
596 {"get_completer_delims", get_completer_delims,
597 METH_NOARGS, doc_get_completer_delims},
599 {"set_completion_display_matches_hook", set_completion_display_matches_hook,
600 METH_VARARGS, doc_set_completion_display_matches_hook},
601 {"set_startup_hook", set_startup_hook,
602 METH_VARARGS, doc_set_startup_hook},
603 #ifdef HAVE_RL_PRE_INPUT_HOOK
604 {"set_pre_input_hook", set_pre_input_hook,
605 METH_VARARGS, doc_set_pre_input_hook},
606 #endif
607 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
608 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
609 #endif
610 {0, 0}
614 /* C function to call the Python hooks. */
616 static int
617 on_hook(PyObject *func)
619 int result = 0;
620 if (func != NULL) {
621 PyObject *r;
622 #ifdef WITH_THREAD
623 PyGILState_STATE gilstate = PyGILState_Ensure();
624 #endif
625 r = PyObject_CallFunction(func, NULL);
626 if (r == NULL)
627 goto error;
628 if (r == Py_None)
629 result = 0;
630 else {
631 result = PyInt_AsLong(r);
632 if (result == -1 && PyErr_Occurred())
633 goto error;
635 Py_DECREF(r);
636 goto done;
637 error:
638 PyErr_Clear();
639 Py_XDECREF(r);
640 done:
641 #ifdef WITH_THREAD
642 PyGILState_Release(gilstate);
643 #endif
644 return result;
646 return result;
649 static int
650 on_startup_hook(void)
652 return on_hook(startup_hook);
655 #ifdef HAVE_RL_PRE_INPUT_HOOK
656 static int
657 on_pre_input_hook(void)
659 return on_hook(pre_input_hook);
661 #endif
664 /* C function to call the Python completion_display_matches */
666 static void
667 on_completion_display_matches_hook(char **matches,
668 int num_matches, int max_length)
670 int i;
671 PyObject *m=NULL, *s=NULL, *r=NULL;
672 #ifdef WITH_THREAD
673 PyGILState_STATE gilstate = PyGILState_Ensure();
674 #endif
675 m = PyList_New(num_matches);
676 if (m == NULL)
677 goto error;
678 for (i = 0; i < num_matches; i++) {
679 s = PyString_FromString(matches[i+1]);
680 if (s == NULL)
681 goto error;
682 if (PyList_SetItem(m, i, s) == -1)
683 goto error;
686 r = PyObject_CallFunction(completion_display_matches_hook,
687 "sOi", matches[0], m, max_length);
689 Py_DECREF(m), m=NULL;
691 if (r == NULL ||
692 (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
693 goto error;
695 Py_XDECREF(r), r=NULL;
697 if (0) {
698 error:
699 PyErr_Clear();
700 Py_XDECREF(m);
701 Py_XDECREF(r);
703 #ifdef WITH_THREAD
704 PyGILState_Release(gilstate);
705 #endif
709 /* C function to call the Python completer. */
711 static char *
712 on_completion(const char *text, int state)
714 char *result = NULL;
715 if (completer != NULL) {
716 PyObject *r;
717 #ifdef WITH_THREAD
718 PyGILState_STATE gilstate = PyGILState_Ensure();
719 #endif
720 rl_attempted_completion_over = 1;
721 r = PyObject_CallFunction(completer, "si", text, state);
722 if (r == NULL)
723 goto error;
724 if (r == Py_None) {
725 result = NULL;
727 else {
728 char *s = PyString_AsString(r);
729 if (s == NULL)
730 goto error;
731 result = strdup(s);
733 Py_DECREF(r);
734 goto done;
735 error:
736 PyErr_Clear();
737 Py_XDECREF(r);
738 done:
739 #ifdef WITH_THREAD
740 PyGILState_Release(gilstate);
741 #endif
742 return result;
744 return result;
748 /* A more flexible constructor that saves the "begidx" and "endidx"
749 * before calling the normal completer */
751 static char **
752 flex_complete(char *text, int start, int end)
754 Py_XDECREF(begidx);
755 Py_XDECREF(endidx);
756 begidx = PyInt_FromLong((long) start);
757 endidx = PyInt_FromLong((long) end);
758 return completion_matches(text, *on_completion);
762 /* Helper to initialize GNU readline properly. */
764 static void
765 setup_readline(void)
767 #ifdef SAVE_LOCALE
768 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
769 if (!saved_locale)
770 Py_FatalError("not enough memory to save locale");
771 #endif
773 using_history();
775 rl_readline_name = "python";
776 #if defined(PYOS_OS2) && defined(PYCC_GCC)
777 /* Allow $if term= in .inputrc to work */
778 rl_terminal_name = getenv("TERM");
779 #endif
780 /* Force rebind of TAB to insert-tab */
781 rl_bind_key('\t', rl_insert);
782 /* Bind both ESC-TAB and ESC-ESC to the completion function */
783 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
784 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
785 /* Set our hook functions */
786 rl_startup_hook = (Function *)on_startup_hook;
787 #ifdef HAVE_RL_PRE_INPUT_HOOK
788 rl_pre_input_hook = (Function *)on_pre_input_hook;
789 #endif
790 /* Set our completion function */
791 rl_attempted_completion_function = (CPPFunction *)flex_complete;
792 /* Set Python word break characters */
793 rl_completer_word_break_characters =
794 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
795 /* All nonalphanums except '.' */
796 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
797 rl_completion_append_character ='\0';
798 #endif
800 begidx = PyInt_FromLong(0L);
801 endidx = PyInt_FromLong(0L);
802 /* Initialize (allows .inputrc to override)
804 * XXX: A bug in the readline-2.2 library causes a memory leak
805 * inside this function. Nothing we can do about it.
807 rl_initialize();
809 RESTORE_LOCALE(saved_locale)
812 /* Wrapper around GNU readline that handles signals differently. */
815 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
817 static char *completed_input_string;
818 static void
819 rlhandler(char *text)
821 completed_input_string = text;
822 rl_callback_handler_remove();
825 extern PyThreadState* _PyOS_ReadlineTState;
827 static char *
828 readline_until_enter_or_signal(char *prompt, int *signal)
830 char * not_done_reading = "";
831 fd_set selectset;
833 *signal = 0;
834 #ifdef HAVE_RL_CATCH_SIGNAL
835 rl_catch_signals = 0;
836 #endif
838 rl_callback_handler_install (prompt, rlhandler);
839 FD_ZERO(&selectset);
841 completed_input_string = not_done_reading;
843 while (completed_input_string == not_done_reading) {
844 int has_input = 0;
846 while (!has_input)
847 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
849 /* [Bug #1552726] Only limit the pause if an input hook has been
850 defined. */
851 struct timeval *timeoutp = NULL;
852 if (PyOS_InputHook)
853 timeoutp = &timeout;
854 FD_SET(fileno(rl_instream), &selectset);
855 /* select resets selectset if no input was available */
856 has_input = select(fileno(rl_instream) + 1, &selectset,
857 NULL, NULL, timeoutp);
858 if(PyOS_InputHook) PyOS_InputHook();
861 if(has_input > 0) {
862 rl_callback_read_char();
864 else if (errno == EINTR) {
865 int s;
866 #ifdef WITH_THREAD
867 PyEval_RestoreThread(_PyOS_ReadlineTState);
868 #endif
869 s = PyErr_CheckSignals();
870 #ifdef WITH_THREAD
871 PyEval_SaveThread();
872 #endif
873 if (s < 0) {
874 rl_free_line_state();
875 rl_cleanup_after_signal();
876 rl_callback_handler_remove();
877 *signal = 1;
878 completed_input_string = NULL;
883 return completed_input_string;
887 #else
889 /* Interrupt handler */
891 static jmp_buf jbuf;
893 /* ARGSUSED */
894 static void
895 onintr(int sig)
897 longjmp(jbuf, 1);
901 static char *
902 readline_until_enter_or_signal(char *prompt, int *signal)
904 PyOS_sighandler_t old_inthandler;
905 char *p;
907 *signal = 0;
909 old_inthandler = PyOS_setsig(SIGINT, onintr);
910 if (setjmp(jbuf)) {
911 #ifdef HAVE_SIGRELSE
912 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
913 sigrelse(SIGINT);
914 #endif
915 PyOS_setsig(SIGINT, old_inthandler);
916 *signal = 1;
917 return NULL;
919 rl_event_hook = PyOS_InputHook;
920 p = readline(prompt);
921 PyOS_setsig(SIGINT, old_inthandler);
923 return p;
925 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
928 static char *
929 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
931 size_t n;
932 char *p, *q;
933 int signal;
935 #ifdef SAVE_LOCALE
936 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
937 if (!saved_locale)
938 Py_FatalError("not enough memory to save locale");
939 setlocale(LC_CTYPE, "");
940 #endif
942 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
943 rl_instream = sys_stdin;
944 rl_outstream = sys_stdout;
945 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
946 rl_prep_terminal (1);
947 #endif
950 p = readline_until_enter_or_signal(prompt, &signal);
952 /* we got an interrupt signal */
953 if (signal) {
954 RESTORE_LOCALE(saved_locale)
955 return NULL;
958 /* We got an EOF, return a empty string. */
959 if (p == NULL) {
960 p = PyMem_Malloc(1);
961 if (p != NULL)
962 *p = '\0';
963 RESTORE_LOCALE(saved_locale)
964 return p;
967 /* we have a valid line */
968 n = strlen(p);
969 if (n > 0) {
970 char *line;
971 HISTORY_STATE *state = history_get_history_state();
972 if (state->length > 0)
973 line = history_get(state->length)->line;
974 else
975 line = "";
976 if (strcmp(p, line))
977 add_history(p);
978 /* the history docs don't say so, but the address of state
979 changes each time history_get_history_state is called
980 which makes me think it's freshly malloc'd memory...
981 on the other hand, the address of the last line stays the
982 same as long as history isn't extended, so it appears to
983 be malloc'd but managed by the history package... */
984 free(state);
986 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
987 release the original. */
988 q = p;
989 p = PyMem_Malloc(n+2);
990 if (p != NULL) {
991 strncpy(p, q, n);
992 p[n] = '\n';
993 p[n+1] = '\0';
995 free(q);
996 RESTORE_LOCALE(saved_locale)
997 return p;
1001 /* Initialize the module */
1003 PyDoc_STRVAR(doc_module,
1004 "Importing this module enables command line editing using GNU readline.");
1006 PyMODINIT_FUNC
1007 initreadline(void)
1009 PyObject *m;
1011 m = Py_InitModule4("readline", readline_methods, doc_module,
1012 (PyObject *)NULL, PYTHON_API_VERSION);
1013 if (m == NULL)
1014 return;
1016 PyOS_ReadlineFunctionPointer = call_readline;
1017 setup_readline();