Adding basic imputil documentation.
[python.git] / Modules / readline.c
blobfd800ffa1aa2d046bef6fcbd52728ac31692347b
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
42 /* Exported function to send one line to readline's init file parser */
44 static PyObject *
45 parse_and_bind(PyObject *self, PyObject *args)
47 char *s, *copy;
48 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
49 return NULL;
50 /* Make a copy -- rl_parse_and_bind() modifies its argument */
51 /* Bernard Herzog */
52 copy = malloc(1 + strlen(s));
53 if (copy == NULL)
54 return PyErr_NoMemory();
55 strcpy(copy, s);
56 rl_parse_and_bind(copy);
57 free(copy); /* Free the copy */
58 Py_INCREF(Py_None);
59 return Py_None;
62 PyDoc_STRVAR(doc_parse_and_bind,
63 "parse_and_bind(string) -> None\n\
64 Parse and execute single line of a readline init file.");
67 /* Exported function to parse a readline init file */
69 static PyObject *
70 read_init_file(PyObject *self, PyObject *args)
72 char *s = NULL;
73 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
74 return NULL;
75 errno = rl_read_init_file(s);
76 if (errno)
77 return PyErr_SetFromErrno(PyExc_IOError);
78 Py_INCREF(Py_None);
79 return Py_None;
82 PyDoc_STRVAR(doc_read_init_file,
83 "read_init_file([filename]) -> None\n\
84 Parse a readline initialization file.\n\
85 The default filename is the last filename used.");
88 /* Exported function to load a readline history file */
90 static PyObject *
91 read_history_file(PyObject *self, PyObject *args)
93 char *s = NULL;
94 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
95 return NULL;
96 errno = read_history(s);
97 if (errno)
98 return PyErr_SetFromErrno(PyExc_IOError);
99 Py_INCREF(Py_None);
100 return Py_None;
103 static int _history_length = -1; /* do not truncate history by default */
104 PyDoc_STRVAR(doc_read_history_file,
105 "read_history_file([filename]) -> None\n\
106 Load a readline history file.\n\
107 The default filename is ~/.history.");
110 /* Exported function to save a readline history file */
112 static PyObject *
113 write_history_file(PyObject *self, PyObject *args)
115 char *s = NULL;
116 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
117 return NULL;
118 errno = write_history(s);
119 if (!errno && _history_length >= 0)
120 history_truncate_file(s, _history_length);
121 if (errno)
122 return PyErr_SetFromErrno(PyExc_IOError);
123 Py_INCREF(Py_None);
124 return Py_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_INCREF(Py_None);
143 return Py_None;
146 PyDoc_STRVAR(set_history_length_doc,
147 "set_history_length(length) -> None\n\
148 set the maximal number of items which will be written to\n\
149 the history file. A negative length is used to inhibit\n\
150 history truncation.");
153 /* Get history length */
155 static PyObject*
156 get_history_length(PyObject *self, PyObject *noarg)
158 return PyInt_FromLong(_history_length);
161 PyDoc_STRVAR(get_history_length_doc,
162 "get_history_length() -> int\n\
163 return the maximum number of items that will be written to\n\
164 the history file.");
167 /* Generic hook function setter */
169 static PyObject *
170 set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
172 PyObject *function = Py_None;
173 char buf[80];
174 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
175 if (!PyArg_ParseTuple(args, buf, &function))
176 return NULL;
177 if (function == Py_None) {
178 Py_XDECREF(*hook_var);
179 *hook_var = NULL;
181 else if (PyCallable_Check(function)) {
182 PyObject *tmp = *hook_var;
183 Py_INCREF(function);
184 *hook_var = function;
185 Py_XDECREF(tmp);
187 else {
188 PyOS_snprintf(buf, sizeof(buf),
189 "set_%.50s(func): argument not callable",
190 funcname);
191 PyErr_SetString(PyExc_TypeError, buf);
192 return NULL;
194 Py_INCREF(Py_None);
195 return Py_None;
199 /* Exported functions to specify hook functions in Python */
201 static PyObject *startup_hook = NULL;
203 #ifdef HAVE_RL_PRE_INPUT_HOOK
204 static PyObject *pre_input_hook = NULL;
205 #endif
207 static PyObject *
208 set_startup_hook(PyObject *self, PyObject *args)
210 return set_hook("startup_hook", &startup_hook, args);
213 PyDoc_STRVAR(doc_set_startup_hook,
214 "set_startup_hook([function]) -> None\n\
215 Set or remove the startup_hook function.\n\
216 The function is called with no arguments just\n\
217 before readline prints the first prompt.");
220 #ifdef HAVE_RL_PRE_INPUT_HOOK
222 /* Set pre-input hook */
224 static PyObject *
225 set_pre_input_hook(PyObject *self, PyObject *args)
227 return set_hook("pre_input_hook", &pre_input_hook, args);
230 PyDoc_STRVAR(doc_set_pre_input_hook,
231 "set_pre_input_hook([function]) -> None\n\
232 Set or remove the pre_input_hook function.\n\
233 The function is called with no arguments after the first prompt\n\
234 has been printed and just before readline starts reading input\n\
235 characters.");
237 #endif
240 /* Exported function to specify a word completer in Python */
242 static PyObject *completer = NULL;
244 static PyObject *begidx = NULL;
245 static PyObject *endidx = NULL;
248 /* Get the beginning index for the scope of the tab-completion */
250 static PyObject *
251 get_begidx(PyObject *self, PyObject *noarg)
253 Py_INCREF(begidx);
254 return begidx;
257 PyDoc_STRVAR(doc_get_begidx,
258 "get_begidx() -> int\n\
259 get the beginning index of the readline tab-completion scope");
262 /* Get the ending index for the scope of the tab-completion */
264 static PyObject *
265 get_endidx(PyObject *self, PyObject *noarg)
267 Py_INCREF(endidx);
268 return endidx;
271 PyDoc_STRVAR(doc_get_endidx,
272 "get_endidx() -> int\n\
273 get the ending index of the readline tab-completion scope");
276 /* Set the tab-completion word-delimiters that readline uses */
278 static PyObject *
279 set_completer_delims(PyObject *self, PyObject *args)
281 char *break_chars;
283 if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
284 return NULL;
286 free((void*)rl_completer_word_break_characters);
287 rl_completer_word_break_characters = strdup(break_chars);
288 Py_INCREF(Py_None);
289 return Py_None;
292 PyDoc_STRVAR(doc_set_completer_delims,
293 "set_completer_delims(string) -> None\n\
294 set the readline word delimiters for tab-completion");
296 static PyObject *
297 py_remove_history(PyObject *self, PyObject *args)
299 int entry_number;
300 HIST_ENTRY *entry;
302 if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
303 return NULL;
304 if (entry_number < 0) {
305 PyErr_SetString(PyExc_ValueError,
306 "History index cannot be negative");
307 return NULL;
309 entry = remove_history(entry_number);
310 if (!entry) {
311 PyErr_Format(PyExc_ValueError,
312 "No history item at position %d",
313 entry_number);
314 return NULL;
316 /* free memory allocated for the history entry */
317 if (entry->line)
318 free(entry->line);
319 if (entry->data)
320 free(entry->data);
321 free(entry);
323 Py_INCREF(Py_None);
324 return Py_None;
327 PyDoc_STRVAR(doc_remove_history,
328 "remove_history_item(pos) -> None\n\
329 remove history item given by its position");
331 static PyObject *
332 py_replace_history(PyObject *self, PyObject *args)
334 int entry_number;
335 char *line;
336 HIST_ENTRY *old_entry;
338 if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, &line)) {
339 return NULL;
341 if (entry_number < 0) {
342 PyErr_SetString(PyExc_ValueError,
343 "History index cannot be negative");
344 return NULL;
346 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
347 if (!old_entry) {
348 PyErr_Format(PyExc_ValueError,
349 "No history item at position %d",
350 entry_number);
351 return NULL;
353 /* free memory allocated for the old history entry */
354 if (old_entry->line)
355 free(old_entry->line);
356 if (old_entry->data)
357 free(old_entry->data);
358 free(old_entry);
360 Py_INCREF(Py_None);
361 return Py_None;
364 PyDoc_STRVAR(doc_replace_history,
365 "replace_history_item(pos, line) -> None\n\
366 replaces history item given by its position with contents of line");
368 /* Add a line to the history buffer */
370 static PyObject *
371 py_add_history(PyObject *self, PyObject *args)
373 char *line;
375 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
376 return NULL;
378 add_history(line);
379 Py_INCREF(Py_None);
380 return Py_None;
383 PyDoc_STRVAR(doc_add_history,
384 "add_history(string) -> None\n\
385 add a line to the history buffer");
388 /* Get the tab-completion word-delimiters that readline uses */
390 static PyObject *
391 get_completer_delims(PyObject *self, PyObject *noarg)
393 return PyString_FromString(rl_completer_word_break_characters);
396 PyDoc_STRVAR(doc_get_completer_delims,
397 "get_completer_delims() -> string\n\
398 get the readline word delimiters for tab-completion");
401 /* Set the completer function */
403 static PyObject *
404 set_completer(PyObject *self, PyObject *args)
406 return set_hook("completer", &completer, args);
409 PyDoc_STRVAR(doc_set_completer,
410 "set_completer([function]) -> None\n\
411 Set or remove the completer function.\n\
412 The function is called as function(text, state),\n\
413 for state in 0, 1, 2, ..., until it returns a non-string.\n\
414 It should return the next possible completion starting with 'text'.");
417 static PyObject *
418 get_completer(PyObject *self, PyObject *noargs)
420 if (completer == NULL) {
421 Py_INCREF(Py_None);
422 return Py_None;
424 Py_INCREF(completer);
425 return completer;
428 PyDoc_STRVAR(doc_get_completer,
429 "get_completer() -> function\n\
431 Returns current completer function.");
433 /* Exported function to get any element of history */
435 static PyObject *
436 get_history_item(PyObject *self, PyObject *args)
438 int idx = 0;
439 HIST_ENTRY *hist_ent;
441 if (!PyArg_ParseTuple(args, "i:index", &idx))
442 return NULL;
443 if ((hist_ent = history_get(idx)))
444 return PyString_FromString(hist_ent->line);
445 else {
446 Py_INCREF(Py_None);
447 return Py_None;
451 PyDoc_STRVAR(doc_get_history_item,
452 "get_history_item() -> string\n\
453 return the current contents of history item at index.");
456 /* Exported function to get current length of history */
458 static PyObject *
459 get_current_history_length(PyObject *self, PyObject *noarg)
461 HISTORY_STATE *hist_st;
463 hist_st = history_get_history_state();
464 return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
467 PyDoc_STRVAR(doc_get_current_history_length,
468 "get_current_history_length() -> integer\n\
469 return the current (not the maximum) length of history.");
472 /* Exported function to read the current line buffer */
474 static PyObject *
475 get_line_buffer(PyObject *self, PyObject *noarg)
477 return PyString_FromString(rl_line_buffer);
480 PyDoc_STRVAR(doc_get_line_buffer,
481 "get_line_buffer() -> string\n\
482 return the current contents of the line buffer.");
485 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
487 /* Exported function to clear the current history */
489 static PyObject *
490 py_clear_history(PyObject *self, PyObject *noarg)
492 clear_history();
493 Py_INCREF(Py_None);
494 return Py_None;
497 PyDoc_STRVAR(doc_clear_history,
498 "clear_history() -> None\n\
499 Clear the current readline history.");
500 #endif
503 /* Exported function to insert text into the line buffer */
505 static PyObject *
506 insert_text(PyObject *self, PyObject *args)
508 char *s;
509 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
510 return NULL;
511 rl_insert_text(s);
512 Py_INCREF(Py_None);
513 return Py_None;
516 PyDoc_STRVAR(doc_insert_text,
517 "insert_text(string) -> None\n\
518 Insert text into the command line.");
521 /* Redisplay the line buffer */
523 static PyObject *
524 redisplay(PyObject *self, PyObject *noarg)
526 rl_redisplay();
527 Py_INCREF(Py_None);
528 return Py_None;
531 PyDoc_STRVAR(doc_redisplay,
532 "redisplay() -> None\n\
533 Change what's displayed on the screen to reflect the current\n\
534 contents of the line buffer.");
537 /* Table of functions exported by the module */
539 static struct PyMethodDef readline_methods[] =
541 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
542 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
543 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
544 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
545 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
546 {"read_history_file", read_history_file,
547 METH_VARARGS, doc_read_history_file},
548 {"write_history_file", write_history_file,
549 METH_VARARGS, doc_write_history_file},
550 {"get_history_item", get_history_item,
551 METH_VARARGS, doc_get_history_item},
552 {"get_current_history_length", (PyCFunction)get_current_history_length,
553 METH_NOARGS, doc_get_current_history_length},
554 {"set_history_length", set_history_length,
555 METH_VARARGS, set_history_length_doc},
556 {"get_history_length", get_history_length,
557 METH_NOARGS, get_history_length_doc},
558 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
559 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
560 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
561 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
563 {"set_completer_delims", set_completer_delims,
564 METH_VARARGS, doc_set_completer_delims},
565 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
566 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
567 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
568 {"get_completer_delims", get_completer_delims,
569 METH_NOARGS, doc_get_completer_delims},
571 {"set_startup_hook", set_startup_hook,
572 METH_VARARGS, doc_set_startup_hook},
573 #ifdef HAVE_RL_PRE_INPUT_HOOK
574 {"set_pre_input_hook", set_pre_input_hook,
575 METH_VARARGS, doc_set_pre_input_hook},
576 #endif
577 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
578 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
579 #endif
580 {0, 0}
584 /* C function to call the Python hooks. */
586 static int
587 on_hook(PyObject *func)
589 int result = 0;
590 if (func != NULL) {
591 PyObject *r;
592 #ifdef WITH_THREAD
593 PyGILState_STATE gilstate = PyGILState_Ensure();
594 #endif
595 r = PyObject_CallFunction(func, NULL);
596 if (r == NULL)
597 goto error;
598 if (r == Py_None)
599 result = 0;
600 else {
601 result = PyInt_AsLong(r);
602 if (result == -1 && PyErr_Occurred())
603 goto error;
605 Py_DECREF(r);
606 goto done;
607 error:
608 PyErr_Clear();
609 Py_XDECREF(r);
610 done:
611 #ifdef WITH_THREAD
612 PyGILState_Release(gilstate);
613 #endif
614 return result;
616 return result;
619 static int
620 on_startup_hook(void)
622 return on_hook(startup_hook);
625 #ifdef HAVE_RL_PRE_INPUT_HOOK
626 static int
627 on_pre_input_hook(void)
629 return on_hook(pre_input_hook);
631 #endif
634 /* C function to call the Python completer. */
636 static char *
637 on_completion(const char *text, int state)
639 char *result = NULL;
640 if (completer != NULL) {
641 PyObject *r;
642 #ifdef WITH_THREAD
643 PyGILState_STATE gilstate = PyGILState_Ensure();
644 #endif
645 rl_attempted_completion_over = 1;
646 r = PyObject_CallFunction(completer, "si", text, state);
647 if (r == NULL)
648 goto error;
649 if (r == Py_None) {
650 result = NULL;
652 else {
653 char *s = PyString_AsString(r);
654 if (s == NULL)
655 goto error;
656 result = strdup(s);
658 Py_DECREF(r);
659 goto done;
660 error:
661 PyErr_Clear();
662 Py_XDECREF(r);
663 done:
664 #ifdef WITH_THREAD
665 PyGILState_Release(gilstate);
666 #endif
667 return result;
669 return result;
673 /* A more flexible constructor that saves the "begidx" and "endidx"
674 * before calling the normal completer */
676 static char **
677 flex_complete(char *text, int start, int end)
679 Py_XDECREF(begidx);
680 Py_XDECREF(endidx);
681 begidx = PyInt_FromLong((long) start);
682 endidx = PyInt_FromLong((long) end);
683 return completion_matches(text, *on_completion);
687 /* Helper to initialize GNU readline properly. */
689 static void
690 setup_readline(void)
692 #ifdef SAVE_LOCALE
693 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
694 if (!saved_locale)
695 Py_FatalError("not enough memory to save locale");
696 #endif
698 using_history();
700 rl_readline_name = "python";
701 #if defined(PYOS_OS2) && defined(PYCC_GCC)
702 /* Allow $if term= in .inputrc to work */
703 rl_terminal_name = getenv("TERM");
704 #endif
705 /* Force rebind of TAB to insert-tab */
706 rl_bind_key('\t', rl_insert);
707 /* Bind both ESC-TAB and ESC-ESC to the completion function */
708 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
709 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
710 /* Set our hook functions */
711 rl_startup_hook = (Function *)on_startup_hook;
712 #ifdef HAVE_RL_PRE_INPUT_HOOK
713 rl_pre_input_hook = (Function *)on_pre_input_hook;
714 #endif
715 /* Set our completion function */
716 rl_attempted_completion_function = (CPPFunction *)flex_complete;
717 /* Set Python word break characters */
718 rl_completer_word_break_characters =
719 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
720 /* All nonalphanums except '.' */
721 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
722 rl_completion_append_character ='\0';
723 #endif
725 begidx = PyInt_FromLong(0L);
726 endidx = PyInt_FromLong(0L);
727 /* Initialize (allows .inputrc to override)
729 * XXX: A bug in the readline-2.2 library causes a memory leak
730 * inside this function. Nothing we can do about it.
732 rl_initialize();
734 RESTORE_LOCALE(saved_locale)
737 /* Wrapper around GNU readline that handles signals differently. */
740 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
742 static char *completed_input_string;
743 static void
744 rlhandler(char *text)
746 completed_input_string = text;
747 rl_callback_handler_remove();
750 extern PyThreadState* _PyOS_ReadlineTState;
752 static char *
753 readline_until_enter_or_signal(char *prompt, int *signal)
755 char * not_done_reading = "";
756 fd_set selectset;
758 *signal = 0;
759 #ifdef HAVE_RL_CATCH_SIGNAL
760 rl_catch_signals = 0;
761 #endif
763 rl_callback_handler_install (prompt, rlhandler);
764 FD_ZERO(&selectset);
766 completed_input_string = not_done_reading;
768 while (completed_input_string == not_done_reading) {
769 int has_input = 0;
771 while (!has_input)
772 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
774 /* [Bug #1552726] Only limit the pause if an input hook has been
775 defined. */
776 struct timeval *timeoutp = NULL;
777 if (PyOS_InputHook)
778 timeoutp = &timeout;
779 FD_SET(fileno(rl_instream), &selectset);
780 /* select resets selectset if no input was available */
781 has_input = select(fileno(rl_instream) + 1, &selectset,
782 NULL, NULL, timeoutp);
783 if(PyOS_InputHook) PyOS_InputHook();
786 if(has_input > 0) {
787 rl_callback_read_char();
789 else if (errno == EINTR) {
790 int s;
791 #ifdef WITH_THREAD
792 PyEval_RestoreThread(_PyOS_ReadlineTState);
793 #endif
794 s = PyErr_CheckSignals();
795 #ifdef WITH_THREAD
796 PyEval_SaveThread();
797 #endif
798 if (s < 0) {
799 rl_free_line_state();
800 rl_cleanup_after_signal();
801 rl_callback_handler_remove();
802 *signal = 1;
803 completed_input_string = NULL;
808 return completed_input_string;
812 #else
814 /* Interrupt handler */
816 static jmp_buf jbuf;
818 /* ARGSUSED */
819 static void
820 onintr(int sig)
822 longjmp(jbuf, 1);
826 static char *
827 readline_until_enter_or_signal(char *prompt, int *signal)
829 PyOS_sighandler_t old_inthandler;
830 char *p;
832 *signal = 0;
834 old_inthandler = PyOS_setsig(SIGINT, onintr);
835 if (setjmp(jbuf)) {
836 #ifdef HAVE_SIGRELSE
837 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
838 sigrelse(SIGINT);
839 #endif
840 PyOS_setsig(SIGINT, old_inthandler);
841 *signal = 1;
842 return NULL;
844 rl_event_hook = PyOS_InputHook;
845 p = readline(prompt);
846 PyOS_setsig(SIGINT, old_inthandler);
848 return p;
850 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
853 static char *
854 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
856 size_t n;
857 char *p, *q;
858 int signal;
860 #ifdef SAVE_LOCALE
861 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
862 if (!saved_locale)
863 Py_FatalError("not enough memory to save locale");
864 setlocale(LC_CTYPE, "");
865 #endif
867 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
868 rl_instream = sys_stdin;
869 rl_outstream = sys_stdout;
870 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
871 rl_prep_terminal (1);
872 #endif
875 p = readline_until_enter_or_signal(prompt, &signal);
877 /* we got an interrupt signal */
878 if (signal) {
879 RESTORE_LOCALE(saved_locale)
880 return NULL;
883 /* We got an EOF, return a empty string. */
884 if (p == NULL) {
885 p = PyMem_Malloc(1);
886 if (p != NULL)
887 *p = '\0';
888 RESTORE_LOCALE(saved_locale)
889 return p;
892 /* we have a valid line */
893 n = strlen(p);
894 if (n > 0) {
895 char *line;
896 HISTORY_STATE *state = history_get_history_state();
897 if (state->length > 0)
898 line = history_get(state->length)->line;
899 else
900 line = "";
901 if (strcmp(p, line))
902 add_history(p);
903 /* the history docs don't say so, but the address of state
904 changes each time history_get_history_state is called
905 which makes me think it's freshly malloc'd memory...
906 on the other hand, the address of the last line stays the
907 same as long as history isn't extended, so it appears to
908 be malloc'd but managed by the history package... */
909 free(state);
911 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
912 release the original. */
913 q = p;
914 p = PyMem_Malloc(n+2);
915 if (p != NULL) {
916 strncpy(p, q, n);
917 p[n] = '\n';
918 p[n+1] = '\0';
920 free(q);
921 RESTORE_LOCALE(saved_locale)
922 return p;
926 /* Initialize the module */
928 PyDoc_STRVAR(doc_module,
929 "Importing this module enables command line editing using GNU readline.");
931 PyMODINIT_FUNC
932 initreadline(void)
934 PyObject *m;
936 m = Py_InitModule4("readline", readline_methods, doc_module,
937 (PyObject *)NULL, PYTHON_API_VERSION);
938 if (m == NULL)
939 return;
941 PyOS_ReadlineFunctionPointer = call_readline;
942 setup_readline();