Saved and restored logging._handlerList at the same time as saving/restoring logging...
[python.git] / Modules / readline.c
blob8fda2281339af121643c6e2c313ebdd562b3aa82
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 /* GNU readline definitions */
24 #undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
25 #include <readline/readline.h>
26 #include <readline/history.h>
28 #ifdef HAVE_RL_COMPLETION_MATCHES
29 #define completion_matches(x, y) \
30 rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
31 #endif
34 /* Exported function to send one line to readline's init file parser */
36 static PyObject *
37 parse_and_bind(PyObject *self, PyObject *args)
39 char *s, *copy;
40 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
41 return NULL;
42 /* Make a copy -- rl_parse_and_bind() modifies its argument */
43 /* Bernard Herzog */
44 copy = malloc(1 + strlen(s));
45 if (copy == NULL)
46 return PyErr_NoMemory();
47 strcpy(copy, s);
48 rl_parse_and_bind(copy);
49 free(copy); /* Free the copy */
50 Py_INCREF(Py_None);
51 return Py_None;
54 PyDoc_STRVAR(doc_parse_and_bind,
55 "parse_and_bind(string) -> None\n\
56 Parse and execute single line of a readline init file.");
59 /* Exported function to parse a readline init file */
61 static PyObject *
62 read_init_file(PyObject *self, PyObject *args)
64 char *s = NULL;
65 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
66 return NULL;
67 errno = rl_read_init_file(s);
68 if (errno)
69 return PyErr_SetFromErrno(PyExc_IOError);
70 Py_INCREF(Py_None);
71 return Py_None;
74 PyDoc_STRVAR(doc_read_init_file,
75 "read_init_file([filename]) -> None\n\
76 Parse a readline initialization file.\n\
77 The default filename is the last filename used.");
80 /* Exported function to load a readline history file */
82 static PyObject *
83 read_history_file(PyObject *self, PyObject *args)
85 char *s = NULL;
86 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
87 return NULL;
88 errno = read_history(s);
89 if (errno)
90 return PyErr_SetFromErrno(PyExc_IOError);
91 Py_INCREF(Py_None);
92 return Py_None;
95 static int _history_length = -1; /* do not truncate history by default */
96 PyDoc_STRVAR(doc_read_history_file,
97 "read_history_file([filename]) -> None\n\
98 Load a readline history file.\n\
99 The default filename is ~/.history.");
102 /* Exported function to save a readline history file */
104 static PyObject *
105 write_history_file(PyObject *self, PyObject *args)
107 char *s = NULL;
108 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
109 return NULL;
110 errno = write_history(s);
111 if (!errno && _history_length >= 0)
112 history_truncate_file(s, _history_length);
113 if (errno)
114 return PyErr_SetFromErrno(PyExc_IOError);
115 Py_INCREF(Py_None);
116 return Py_None;
119 PyDoc_STRVAR(doc_write_history_file,
120 "write_history_file([filename]) -> None\n\
121 Save a readline history file.\n\
122 The default filename is ~/.history.");
125 /* Set history length */
127 static PyObject*
128 set_history_length(PyObject *self, PyObject *args)
130 int length = _history_length;
131 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
132 return NULL;
133 _history_length = length;
134 Py_INCREF(Py_None);
135 return Py_None;
138 PyDoc_STRVAR(set_history_length_doc,
139 "set_history_length(length) -> None\n\
140 set the maximal number of items which will be written to\n\
141 the history file. A negative length is used to inhibit\n\
142 history truncation.");
145 /* Get history length */
147 static PyObject*
148 get_history_length(PyObject *self, PyObject *noarg)
150 return PyInt_FromLong(_history_length);
153 PyDoc_STRVAR(get_history_length_doc,
154 "get_history_length() -> int\n\
155 return the maximum number of items that will be written to\n\
156 the history file.");
159 /* Generic hook function setter */
161 static PyObject *
162 set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
164 PyObject *function = Py_None;
165 char buf[80];
166 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
167 if (!PyArg_ParseTuple(args, buf, &function))
168 return NULL;
169 if (function == Py_None) {
170 Py_XDECREF(*hook_var);
171 *hook_var = NULL;
173 else if (PyCallable_Check(function)) {
174 PyObject *tmp = *hook_var;
175 Py_INCREF(function);
176 *hook_var = function;
177 Py_XDECREF(tmp);
179 else {
180 PyOS_snprintf(buf, sizeof(buf),
181 "set_%.50s(func): argument not callable",
182 funcname);
183 PyErr_SetString(PyExc_TypeError, buf);
184 return NULL;
186 Py_INCREF(Py_None);
187 return Py_None;
191 /* Exported functions to specify hook functions in Python */
193 static PyObject *startup_hook = NULL;
195 #ifdef HAVE_RL_PRE_INPUT_HOOK
196 static PyObject *pre_input_hook = NULL;
197 #endif
199 static PyObject *
200 set_startup_hook(PyObject *self, PyObject *args)
202 return set_hook("startup_hook", &startup_hook, args);
205 PyDoc_STRVAR(doc_set_startup_hook,
206 "set_startup_hook([function]) -> None\n\
207 Set or remove the startup_hook function.\n\
208 The function is called with no arguments just\n\
209 before readline prints the first prompt.");
212 #ifdef HAVE_RL_PRE_INPUT_HOOK
214 /* Set pre-input hook */
216 static PyObject *
217 set_pre_input_hook(PyObject *self, PyObject *args)
219 return set_hook("pre_input_hook", &pre_input_hook, args);
222 PyDoc_STRVAR(doc_set_pre_input_hook,
223 "set_pre_input_hook([function]) -> None\n\
224 Set or remove the pre_input_hook function.\n\
225 The function is called with no arguments after the first prompt\n\
226 has been printed and just before readline starts reading input\n\
227 characters.");
229 #endif
232 /* Exported function to specify a word completer in Python */
234 static PyObject *completer = NULL;
236 static PyObject *begidx = NULL;
237 static PyObject *endidx = NULL;
240 /* Get the beginning index for the scope of the tab-completion */
242 static PyObject *
243 get_begidx(PyObject *self, PyObject *noarg)
245 Py_INCREF(begidx);
246 return begidx;
249 PyDoc_STRVAR(doc_get_begidx,
250 "get_begidx() -> int\n\
251 get the beginning index of the readline tab-completion scope");
254 /* Get the ending index for the scope of the tab-completion */
256 static PyObject *
257 get_endidx(PyObject *self, PyObject *noarg)
259 Py_INCREF(endidx);
260 return endidx;
263 PyDoc_STRVAR(doc_get_endidx,
264 "get_endidx() -> int\n\
265 get the ending index of the readline tab-completion scope");
268 /* Set the tab-completion word-delimiters that readline uses */
270 static PyObject *
271 set_completer_delims(PyObject *self, PyObject *args)
273 char *break_chars;
275 if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
276 return NULL;
278 free((void*)rl_completer_word_break_characters);
279 rl_completer_word_break_characters = strdup(break_chars);
280 Py_INCREF(Py_None);
281 return Py_None;
284 PyDoc_STRVAR(doc_set_completer_delims,
285 "set_completer_delims(string) -> None\n\
286 set the readline word delimiters for tab-completion");
288 static PyObject *
289 py_remove_history(PyObject *self, PyObject *args)
291 int entry_number;
292 HIST_ENTRY *entry;
294 if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
295 return NULL;
296 if (entry_number < 0) {
297 PyErr_SetString(PyExc_ValueError,
298 "History index cannot be negative");
299 return NULL;
301 entry = remove_history(entry_number);
302 if (!entry) {
303 PyErr_Format(PyExc_ValueError,
304 "No history item at position %d",
305 entry_number);
306 return NULL;
308 /* free memory allocated for the history entry */
309 if (entry->line)
310 free(entry->line);
311 if (entry->data)
312 free(entry->data);
313 free(entry);
315 Py_INCREF(Py_None);
316 return Py_None;
319 PyDoc_STRVAR(doc_remove_history,
320 "remove_history_item(pos) -> None\n\
321 remove history item given by its position");
323 static PyObject *
324 py_replace_history(PyObject *self, PyObject *args)
326 int entry_number;
327 char *line;
328 HIST_ENTRY *old_entry;
330 if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, &line)) {
331 return NULL;
333 if (entry_number < 0) {
334 PyErr_SetString(PyExc_ValueError,
335 "History index cannot be negative");
336 return NULL;
338 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
339 if (!old_entry) {
340 PyErr_Format(PyExc_ValueError,
341 "No history item at position %d",
342 entry_number);
343 return NULL;
345 /* free memory allocated for the old history entry */
346 if (old_entry->line)
347 free(old_entry->line);
348 if (old_entry->data)
349 free(old_entry->data);
350 free(old_entry);
352 Py_INCREF(Py_None);
353 return Py_None;
356 PyDoc_STRVAR(doc_replace_history,
357 "replace_history_item(pos, line) -> None\n\
358 replaces history item given by its position with contents of line");
360 /* Add a line to the history buffer */
362 static PyObject *
363 py_add_history(PyObject *self, PyObject *args)
365 char *line;
367 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
368 return NULL;
370 add_history(line);
371 Py_INCREF(Py_None);
372 return Py_None;
375 PyDoc_STRVAR(doc_add_history,
376 "add_history(string) -> None\n\
377 add a line to the history buffer");
380 /* Get the tab-completion word-delimiters that readline uses */
382 static PyObject *
383 get_completer_delims(PyObject *self, PyObject *noarg)
385 return PyString_FromString(rl_completer_word_break_characters);
388 PyDoc_STRVAR(doc_get_completer_delims,
389 "get_completer_delims() -> string\n\
390 get the readline word delimiters for tab-completion");
393 /* Set the completer function */
395 static PyObject *
396 set_completer(PyObject *self, PyObject *args)
398 return set_hook("completer", &completer, args);
401 PyDoc_STRVAR(doc_set_completer,
402 "set_completer([function]) -> None\n\
403 Set or remove the completer function.\n\
404 The function is called as function(text, state),\n\
405 for state in 0, 1, 2, ..., until it returns a non-string.\n\
406 It should return the next possible completion starting with 'text'.");
409 static PyObject *
410 get_completer(PyObject *self, PyObject *noargs)
412 if (completer == NULL) {
413 Py_INCREF(Py_None);
414 return Py_None;
416 Py_INCREF(completer);
417 return completer;
420 PyDoc_STRVAR(doc_get_completer,
421 "get_completer() -> function\n\
423 Returns current completer function.");
425 /* Exported function to get any element of history */
427 static PyObject *
428 get_history_item(PyObject *self, PyObject *args)
430 int idx = 0;
431 HIST_ENTRY *hist_ent;
433 if (!PyArg_ParseTuple(args, "i:index", &idx))
434 return NULL;
435 if ((hist_ent = history_get(idx)))
436 return PyString_FromString(hist_ent->line);
437 else {
438 Py_INCREF(Py_None);
439 return Py_None;
443 PyDoc_STRVAR(doc_get_history_item,
444 "get_history_item() -> string\n\
445 return the current contents of history item at index.");
448 /* Exported function to get current length of history */
450 static PyObject *
451 get_current_history_length(PyObject *self, PyObject *noarg)
453 HISTORY_STATE *hist_st;
455 hist_st = history_get_history_state();
456 return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
459 PyDoc_STRVAR(doc_get_current_history_length,
460 "get_current_history_length() -> integer\n\
461 return the current (not the maximum) length of history.");
464 /* Exported function to read the current line buffer */
466 static PyObject *
467 get_line_buffer(PyObject *self, PyObject *noarg)
469 return PyString_FromString(rl_line_buffer);
472 PyDoc_STRVAR(doc_get_line_buffer,
473 "get_line_buffer() -> string\n\
474 return the current contents of the line buffer.");
477 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
479 /* Exported function to clear the current history */
481 static PyObject *
482 py_clear_history(PyObject *self, PyObject *noarg)
484 clear_history();
485 Py_INCREF(Py_None);
486 return Py_None;
489 PyDoc_STRVAR(doc_clear_history,
490 "clear_history() -> None\n\
491 Clear the current readline history.");
492 #endif
495 /* Exported function to insert text into the line buffer */
497 static PyObject *
498 insert_text(PyObject *self, PyObject *args)
500 char *s;
501 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
502 return NULL;
503 rl_insert_text(s);
504 Py_INCREF(Py_None);
505 return Py_None;
508 PyDoc_STRVAR(doc_insert_text,
509 "insert_text(string) -> None\n\
510 Insert text into the command line.");
513 /* Redisplay the line buffer */
515 static PyObject *
516 redisplay(PyObject *self, PyObject *noarg)
518 rl_redisplay();
519 Py_INCREF(Py_None);
520 return Py_None;
523 PyDoc_STRVAR(doc_redisplay,
524 "redisplay() -> None\n\
525 Change what's displayed on the screen to reflect the current\n\
526 contents of the line buffer.");
529 /* Table of functions exported by the module */
531 static struct PyMethodDef readline_methods[] =
533 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
534 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
535 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
536 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
537 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
538 {"read_history_file", read_history_file,
539 METH_VARARGS, doc_read_history_file},
540 {"write_history_file", write_history_file,
541 METH_VARARGS, doc_write_history_file},
542 {"get_history_item", get_history_item,
543 METH_VARARGS, doc_get_history_item},
544 {"get_current_history_length", (PyCFunction)get_current_history_length,
545 METH_NOARGS, doc_get_current_history_length},
546 {"set_history_length", set_history_length,
547 METH_VARARGS, set_history_length_doc},
548 {"get_history_length", get_history_length,
549 METH_NOARGS, get_history_length_doc},
550 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
551 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
552 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
553 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
555 {"set_completer_delims", set_completer_delims,
556 METH_VARARGS, doc_set_completer_delims},
557 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
558 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
559 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
560 {"get_completer_delims", get_completer_delims,
561 METH_NOARGS, doc_get_completer_delims},
563 {"set_startup_hook", set_startup_hook,
564 METH_VARARGS, doc_set_startup_hook},
565 #ifdef HAVE_RL_PRE_INPUT_HOOK
566 {"set_pre_input_hook", set_pre_input_hook,
567 METH_VARARGS, doc_set_pre_input_hook},
568 #endif
569 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
570 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
571 #endif
572 {0, 0}
576 /* C function to call the Python hooks. */
578 static int
579 on_hook(PyObject *func)
581 int result = 0;
582 if (func != NULL) {
583 PyObject *r;
584 #ifdef WITH_THREAD
585 PyGILState_STATE gilstate = PyGILState_Ensure();
586 #endif
587 r = PyObject_CallFunction(func, NULL);
588 if (r == NULL)
589 goto error;
590 if (r == Py_None)
591 result = 0;
592 else {
593 result = PyInt_AsLong(r);
594 if (result == -1 && PyErr_Occurred())
595 goto error;
597 Py_DECREF(r);
598 goto done;
599 error:
600 PyErr_Clear();
601 Py_XDECREF(r);
602 done:
603 #ifdef WITH_THREAD
604 PyGILState_Release(gilstate);
605 #endif
606 return result;
608 return result;
611 static int
612 on_startup_hook(void)
614 return on_hook(startup_hook);
617 #ifdef HAVE_RL_PRE_INPUT_HOOK
618 static int
619 on_pre_input_hook(void)
621 return on_hook(pre_input_hook);
623 #endif
626 /* C function to call the Python completer. */
628 static char *
629 on_completion(char *text, int state)
631 char *result = NULL;
632 if (completer != NULL) {
633 PyObject *r;
634 #ifdef WITH_THREAD
635 PyGILState_STATE gilstate = PyGILState_Ensure();
636 #endif
637 rl_attempted_completion_over = 1;
638 r = PyObject_CallFunction(completer, "si", text, state);
639 if (r == NULL)
640 goto error;
641 if (r == Py_None) {
642 result = NULL;
644 else {
645 char *s = PyString_AsString(r);
646 if (s == NULL)
647 goto error;
648 result = strdup(s);
650 Py_DECREF(r);
651 goto done;
652 error:
653 PyErr_Clear();
654 Py_XDECREF(r);
655 done:
656 #ifdef WITH_THREAD
657 PyGILState_Release(gilstate);
658 #endif
659 return result;
661 return result;
665 /* A more flexible constructor that saves the "begidx" and "endidx"
666 * before calling the normal completer */
668 static char **
669 flex_complete(char *text, int start, int end)
671 Py_XDECREF(begidx);
672 Py_XDECREF(endidx);
673 begidx = PyInt_FromLong((long) start);
674 endidx = PyInt_FromLong((long) end);
675 return completion_matches(text, *on_completion);
679 /* Helper to initialize GNU readline properly. */
681 static void
682 setup_readline(void)
684 #ifdef SAVE_LOCALE
685 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
686 if (!saved_locale)
687 Py_FatalError("not enough memory to save locale");
688 #endif
690 using_history();
692 rl_readline_name = "python";
693 #if defined(PYOS_OS2) && defined(PYCC_GCC)
694 /* Allow $if term= in .inputrc to work */
695 rl_terminal_name = getenv("TERM");
696 #endif
697 /* Force rebind of TAB to insert-tab */
698 rl_bind_key('\t', rl_insert);
699 /* Bind both ESC-TAB and ESC-ESC to the completion function */
700 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
701 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
702 /* Set our hook functions */
703 rl_startup_hook = (Function *)on_startup_hook;
704 #ifdef HAVE_RL_PRE_INPUT_HOOK
705 rl_pre_input_hook = (Function *)on_pre_input_hook;
706 #endif
707 /* Set our completion function */
708 rl_attempted_completion_function = (CPPFunction *)flex_complete;
709 /* Set Python word break characters */
710 rl_completer_word_break_characters =
711 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
712 /* All nonalphanums except '.' */
713 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
714 rl_completion_append_character ='\0';
715 #endif
717 begidx = PyInt_FromLong(0L);
718 endidx = PyInt_FromLong(0L);
719 /* Initialize (allows .inputrc to override)
721 * XXX: A bug in the readline-2.2 library causes a memory leak
722 * inside this function. Nothing we can do about it.
724 rl_initialize();
726 #ifdef SAVE_LOCALE
727 setlocale(LC_CTYPE, saved_locale); /* Restore locale */
728 free(saved_locale);
729 #endif
732 /* Wrapper around GNU readline that handles signals differently. */
735 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
737 static char *completed_input_string;
738 static void
739 rlhandler(char *text)
741 completed_input_string = text;
742 rl_callback_handler_remove();
745 extern PyThreadState* _PyOS_ReadlineTState;
747 static char *
748 readline_until_enter_or_signal(char *prompt, int *signal)
750 char * not_done_reading = "";
751 fd_set selectset;
753 *signal = 0;
754 #ifdef HAVE_RL_CATCH_SIGNAL
755 rl_catch_signals = 0;
756 #endif
758 rl_callback_handler_install (prompt, rlhandler);
759 FD_ZERO(&selectset);
761 completed_input_string = not_done_reading;
763 while (completed_input_string == not_done_reading) {
764 int has_input = 0;
766 while (!has_input)
767 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
768 FD_SET(fileno(rl_instream), &selectset);
769 /* select resets selectset if no input was available */
770 has_input = select(fileno(rl_instream) + 1, &selectset,
771 NULL, NULL, &timeout);
772 if(PyOS_InputHook) PyOS_InputHook();
775 if(has_input > 0) {
776 rl_callback_read_char();
778 else if (errno == EINTR) {
779 int s;
780 #ifdef WITH_THREAD
781 PyEval_RestoreThread(_PyOS_ReadlineTState);
782 #endif
783 s = PyErr_CheckSignals();
784 #ifdef WITH_THREAD
785 PyEval_SaveThread();
786 #endif
787 if (s < 0) {
788 rl_free_line_state();
789 rl_cleanup_after_signal();
790 rl_callback_handler_remove();
791 *signal = 1;
792 completed_input_string = NULL;
797 return completed_input_string;
801 #else
803 /* Interrupt handler */
805 static jmp_buf jbuf;
807 /* ARGSUSED */
808 static void
809 onintr(int sig)
811 longjmp(jbuf, 1);
815 static char *
816 readline_until_enter_or_signal(char *prompt, int *signal)
818 PyOS_sighandler_t old_inthandler;
819 char *p;
821 *signal = 0;
823 old_inthandler = PyOS_setsig(SIGINT, onintr);
824 if (setjmp(jbuf)) {
825 #ifdef HAVE_SIGRELSE
826 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
827 sigrelse(SIGINT);
828 #endif
829 PyOS_setsig(SIGINT, old_inthandler);
830 *signal = 1;
831 return NULL;
833 rl_event_hook = PyOS_InputHook;
834 p = readline(prompt);
835 PyOS_setsig(SIGINT, old_inthandler);
837 return p;
839 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
842 static char *
843 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
845 size_t n;
846 char *p, *q;
847 int signal;
849 #ifdef SAVE_LOCALE
850 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
851 if (!saved_locale)
852 Py_FatalError("not enough memory to save locale");
853 setlocale(LC_CTYPE, "");
854 #endif
856 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
857 rl_instream = sys_stdin;
858 rl_outstream = sys_stdout;
859 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
860 rl_prep_terminal (1);
861 #endif
864 p = readline_until_enter_or_signal(prompt, &signal);
866 /* we got an interrupt signal */
867 if(signal) {
868 return NULL;
871 /* We got an EOF, return a empty string. */
872 if (p == NULL) {
873 p = PyMem_Malloc(1);
874 if (p != NULL)
875 *p = '\0';
876 return p;
879 /* we have a valid line */
880 n = strlen(p);
881 if (n > 0) {
882 char *line;
883 HISTORY_STATE *state = history_get_history_state();
884 if (state->length > 0)
885 line = history_get(state->length)->line;
886 else
887 line = "";
888 if (strcmp(p, line))
889 add_history(p);
890 /* the history docs don't say so, but the address of state
891 changes each time history_get_history_state is called
892 which makes me think it's freshly malloc'd memory...
893 on the other hand, the address of the last line stays the
894 same as long as history isn't extended, so it appears to
895 be malloc'd but managed by the history package... */
896 free(state);
898 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
899 release the original. */
900 q = p;
901 p = PyMem_Malloc(n+2);
902 if (p != NULL) {
903 strncpy(p, q, n);
904 p[n] = '\n';
905 p[n+1] = '\0';
907 free(q);
908 #ifdef SAVE_LOCALE
909 setlocale(LC_CTYPE, saved_locale); /* Restore locale */
910 free(saved_locale);
911 #endif
912 return p;
916 /* Initialize the module */
918 PyDoc_STRVAR(doc_module,
919 "Importing this module enables command line editing using GNU readline.");
921 PyMODINIT_FUNC
922 initreadline(void)
924 PyObject *m;
926 m = Py_InitModule4("readline", readline_methods, doc_module,
927 (PyObject *)NULL, PYTHON_API_VERSION);
928 if (m == NULL)
929 return;
931 PyOS_ReadlineFunctionPointer = call_readline;
932 setup_readline();