Updated documentation for findCaller() to indicate that a 3-tuple is now returned...
[python.git] / Modules / readline.c
blob853874be2506e78b65bcab6a970542a2d9dc80ad
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 #endif
40 /* Exported function to send one line to readline's init file parser */
42 static PyObject *
43 parse_and_bind(PyObject *self, PyObject *args)
45 char *s, *copy;
46 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
47 return NULL;
48 /* Make a copy -- rl_parse_and_bind() modifies its argument */
49 /* Bernard Herzog */
50 copy = malloc(1 + strlen(s));
51 if (copy == NULL)
52 return PyErr_NoMemory();
53 strcpy(copy, s);
54 rl_parse_and_bind(copy);
55 free(copy); /* Free the copy */
56 Py_INCREF(Py_None);
57 return Py_None;
60 PyDoc_STRVAR(doc_parse_and_bind,
61 "parse_and_bind(string) -> None\n\
62 Parse and execute single line of a readline init file.");
65 /* Exported function to parse a readline init file */
67 static PyObject *
68 read_init_file(PyObject *self, PyObject *args)
70 char *s = NULL;
71 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
72 return NULL;
73 errno = rl_read_init_file(s);
74 if (errno)
75 return PyErr_SetFromErrno(PyExc_IOError);
76 Py_INCREF(Py_None);
77 return Py_None;
80 PyDoc_STRVAR(doc_read_init_file,
81 "read_init_file([filename]) -> None\n\
82 Parse a readline initialization file.\n\
83 The default filename is the last filename used.");
86 /* Exported function to load a readline history file */
88 static PyObject *
89 read_history_file(PyObject *self, PyObject *args)
91 char *s = NULL;
92 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
93 return NULL;
94 errno = read_history(s);
95 if (errno)
96 return PyErr_SetFromErrno(PyExc_IOError);
97 Py_INCREF(Py_None);
98 return Py_None;
101 static int _history_length = -1; /* do not truncate history by default */
102 PyDoc_STRVAR(doc_read_history_file,
103 "read_history_file([filename]) -> None\n\
104 Load a readline history file.\n\
105 The default filename is ~/.history.");
108 /* Exported function to save a readline history file */
110 static PyObject *
111 write_history_file(PyObject *self, PyObject *args)
113 char *s = NULL;
114 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
115 return NULL;
116 errno = write_history(s);
117 if (!errno && _history_length >= 0)
118 history_truncate_file(s, _history_length);
119 if (errno)
120 return PyErr_SetFromErrno(PyExc_IOError);
121 Py_INCREF(Py_None);
122 return Py_None;
125 PyDoc_STRVAR(doc_write_history_file,
126 "write_history_file([filename]) -> None\n\
127 Save a readline history file.\n\
128 The default filename is ~/.history.");
131 /* Set history length */
133 static PyObject*
134 set_history_length(PyObject *self, PyObject *args)
136 int length = _history_length;
137 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
138 return NULL;
139 _history_length = length;
140 Py_INCREF(Py_None);
141 return Py_None;
144 PyDoc_STRVAR(set_history_length_doc,
145 "set_history_length(length) -> None\n\
146 set the maximal number of items which will be written to\n\
147 the history file. A negative length is used to inhibit\n\
148 history truncation.");
151 /* Get history length */
153 static PyObject*
154 get_history_length(PyObject *self, PyObject *noarg)
156 return PyInt_FromLong(_history_length);
159 PyDoc_STRVAR(get_history_length_doc,
160 "get_history_length() -> int\n\
161 return the maximum number of items that will be written to\n\
162 the history file.");
165 /* Generic hook function setter */
167 static PyObject *
168 set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
170 PyObject *function = Py_None;
171 char buf[80];
172 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
173 if (!PyArg_ParseTuple(args, buf, &function))
174 return NULL;
175 if (function == Py_None) {
176 Py_XDECREF(*hook_var);
177 *hook_var = NULL;
179 else if (PyCallable_Check(function)) {
180 PyObject *tmp = *hook_var;
181 Py_INCREF(function);
182 *hook_var = function;
183 Py_XDECREF(tmp);
185 else {
186 PyOS_snprintf(buf, sizeof(buf),
187 "set_%.50s(func): argument not callable",
188 funcname);
189 PyErr_SetString(PyExc_TypeError, buf);
190 return NULL;
192 Py_INCREF(Py_None);
193 return Py_None;
197 /* Exported functions to specify hook functions in Python */
199 static PyObject *startup_hook = NULL;
201 #ifdef HAVE_RL_PRE_INPUT_HOOK
202 static PyObject *pre_input_hook = NULL;
203 #endif
205 static PyObject *
206 set_startup_hook(PyObject *self, PyObject *args)
208 return set_hook("startup_hook", &startup_hook, args);
211 PyDoc_STRVAR(doc_set_startup_hook,
212 "set_startup_hook([function]) -> None\n\
213 Set or remove the startup_hook function.\n\
214 The function is called with no arguments just\n\
215 before readline prints the first prompt.");
218 #ifdef HAVE_RL_PRE_INPUT_HOOK
220 /* Set pre-input hook */
222 static PyObject *
223 set_pre_input_hook(PyObject *self, PyObject *args)
225 return set_hook("pre_input_hook", &pre_input_hook, args);
228 PyDoc_STRVAR(doc_set_pre_input_hook,
229 "set_pre_input_hook([function]) -> None\n\
230 Set or remove the pre_input_hook function.\n\
231 The function is called with no arguments after the first prompt\n\
232 has been printed and just before readline starts reading input\n\
233 characters.");
235 #endif
238 /* Exported function to specify a word completer in Python */
240 static PyObject *completer = NULL;
242 static PyObject *begidx = NULL;
243 static PyObject *endidx = NULL;
246 /* Get the beginning index for the scope of the tab-completion */
248 static PyObject *
249 get_begidx(PyObject *self, PyObject *noarg)
251 Py_INCREF(begidx);
252 return begidx;
255 PyDoc_STRVAR(doc_get_begidx,
256 "get_begidx() -> int\n\
257 get the beginning index of the readline tab-completion scope");
260 /* Get the ending index for the scope of the tab-completion */
262 static PyObject *
263 get_endidx(PyObject *self, PyObject *noarg)
265 Py_INCREF(endidx);
266 return endidx;
269 PyDoc_STRVAR(doc_get_endidx,
270 "get_endidx() -> int\n\
271 get the ending index of the readline tab-completion scope");
274 /* Set the tab-completion word-delimiters that readline uses */
276 static PyObject *
277 set_completer_delims(PyObject *self, PyObject *args)
279 char *break_chars;
281 if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
282 return NULL;
284 free((void*)rl_completer_word_break_characters);
285 rl_completer_word_break_characters = strdup(break_chars);
286 Py_INCREF(Py_None);
287 return Py_None;
290 PyDoc_STRVAR(doc_set_completer_delims,
291 "set_completer_delims(string) -> None\n\
292 set the readline word delimiters for tab-completion");
294 static PyObject *
295 py_remove_history(PyObject *self, PyObject *args)
297 int entry_number;
298 HIST_ENTRY *entry;
300 if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
301 return NULL;
302 if (entry_number < 0) {
303 PyErr_SetString(PyExc_ValueError,
304 "History index cannot be negative");
305 return NULL;
307 entry = remove_history(entry_number);
308 if (!entry) {
309 PyErr_Format(PyExc_ValueError,
310 "No history item at position %d",
311 entry_number);
312 return NULL;
314 /* free memory allocated for the history entry */
315 if (entry->line)
316 free(entry->line);
317 if (entry->data)
318 free(entry->data);
319 free(entry);
321 Py_INCREF(Py_None);
322 return Py_None;
325 PyDoc_STRVAR(doc_remove_history,
326 "remove_history_item(pos) -> None\n\
327 remove history item given by its position");
329 static PyObject *
330 py_replace_history(PyObject *self, PyObject *args)
332 int entry_number;
333 char *line;
334 HIST_ENTRY *old_entry;
336 if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, &line)) {
337 return NULL;
339 if (entry_number < 0) {
340 PyErr_SetString(PyExc_ValueError,
341 "History index cannot be negative");
342 return NULL;
344 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
345 if (!old_entry) {
346 PyErr_Format(PyExc_ValueError,
347 "No history item at position %d",
348 entry_number);
349 return NULL;
351 /* free memory allocated for the old history entry */
352 if (old_entry->line)
353 free(old_entry->line);
354 if (old_entry->data)
355 free(old_entry->data);
356 free(old_entry);
358 Py_INCREF(Py_None);
359 return Py_None;
362 PyDoc_STRVAR(doc_replace_history,
363 "replace_history_item(pos, line) -> None\n\
364 replaces history item given by its position with contents of line");
366 /* Add a line to the history buffer */
368 static PyObject *
369 py_add_history(PyObject *self, PyObject *args)
371 char *line;
373 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
374 return NULL;
376 add_history(line);
377 Py_INCREF(Py_None);
378 return Py_None;
381 PyDoc_STRVAR(doc_add_history,
382 "add_history(string) -> None\n\
383 add a line to the history buffer");
386 /* Get the tab-completion word-delimiters that readline uses */
388 static PyObject *
389 get_completer_delims(PyObject *self, PyObject *noarg)
391 return PyString_FromString(rl_completer_word_break_characters);
394 PyDoc_STRVAR(doc_get_completer_delims,
395 "get_completer_delims() -> string\n\
396 get the readline word delimiters for tab-completion");
399 /* Set the completer function */
401 static PyObject *
402 set_completer(PyObject *self, PyObject *args)
404 return set_hook("completer", &completer, args);
407 PyDoc_STRVAR(doc_set_completer,
408 "set_completer([function]) -> None\n\
409 Set or remove the completer function.\n\
410 The function is called as function(text, state),\n\
411 for state in 0, 1, 2, ..., until it returns a non-string.\n\
412 It should return the next possible completion starting with 'text'.");
415 static PyObject *
416 get_completer(PyObject *self, PyObject *noargs)
418 if (completer == NULL) {
419 Py_INCREF(Py_None);
420 return Py_None;
422 Py_INCREF(completer);
423 return completer;
426 PyDoc_STRVAR(doc_get_completer,
427 "get_completer() -> function\n\
429 Returns current completer function.");
431 /* Exported function to get any element of history */
433 static PyObject *
434 get_history_item(PyObject *self, PyObject *args)
436 int idx = 0;
437 HIST_ENTRY *hist_ent;
439 if (!PyArg_ParseTuple(args, "i:index", &idx))
440 return NULL;
441 if ((hist_ent = history_get(idx)))
442 return PyString_FromString(hist_ent->line);
443 else {
444 Py_INCREF(Py_None);
445 return Py_None;
449 PyDoc_STRVAR(doc_get_history_item,
450 "get_history_item() -> string\n\
451 return the current contents of history item at index.");
454 /* Exported function to get current length of history */
456 static PyObject *
457 get_current_history_length(PyObject *self, PyObject *noarg)
459 HISTORY_STATE *hist_st;
461 hist_st = history_get_history_state();
462 return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
465 PyDoc_STRVAR(doc_get_current_history_length,
466 "get_current_history_length() -> integer\n\
467 return the current (not the maximum) length of history.");
470 /* Exported function to read the current line buffer */
472 static PyObject *
473 get_line_buffer(PyObject *self, PyObject *noarg)
475 return PyString_FromString(rl_line_buffer);
478 PyDoc_STRVAR(doc_get_line_buffer,
479 "get_line_buffer() -> string\n\
480 return the current contents of the line buffer.");
483 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
485 /* Exported function to clear the current history */
487 static PyObject *
488 py_clear_history(PyObject *self, PyObject *noarg)
490 clear_history();
491 Py_INCREF(Py_None);
492 return Py_None;
495 PyDoc_STRVAR(doc_clear_history,
496 "clear_history() -> None\n\
497 Clear the current readline history.");
498 #endif
501 /* Exported function to insert text into the line buffer */
503 static PyObject *
504 insert_text(PyObject *self, PyObject *args)
506 char *s;
507 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
508 return NULL;
509 rl_insert_text(s);
510 Py_INCREF(Py_None);
511 return Py_None;
514 PyDoc_STRVAR(doc_insert_text,
515 "insert_text(string) -> None\n\
516 Insert text into the command line.");
519 /* Redisplay the line buffer */
521 static PyObject *
522 redisplay(PyObject *self, PyObject *noarg)
524 rl_redisplay();
525 Py_INCREF(Py_None);
526 return Py_None;
529 PyDoc_STRVAR(doc_redisplay,
530 "redisplay() -> None\n\
531 Change what's displayed on the screen to reflect the current\n\
532 contents of the line buffer.");
535 /* Table of functions exported by the module */
537 static struct PyMethodDef readline_methods[] =
539 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
540 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
541 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
542 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
543 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
544 {"read_history_file", read_history_file,
545 METH_VARARGS, doc_read_history_file},
546 {"write_history_file", write_history_file,
547 METH_VARARGS, doc_write_history_file},
548 {"get_history_item", get_history_item,
549 METH_VARARGS, doc_get_history_item},
550 {"get_current_history_length", (PyCFunction)get_current_history_length,
551 METH_NOARGS, doc_get_current_history_length},
552 {"set_history_length", set_history_length,
553 METH_VARARGS, set_history_length_doc},
554 {"get_history_length", get_history_length,
555 METH_NOARGS, get_history_length_doc},
556 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
557 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
558 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
559 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
561 {"set_completer_delims", set_completer_delims,
562 METH_VARARGS, doc_set_completer_delims},
563 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
564 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
565 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
566 {"get_completer_delims", get_completer_delims,
567 METH_NOARGS, doc_get_completer_delims},
569 {"set_startup_hook", set_startup_hook,
570 METH_VARARGS, doc_set_startup_hook},
571 #ifdef HAVE_RL_PRE_INPUT_HOOK
572 {"set_pre_input_hook", set_pre_input_hook,
573 METH_VARARGS, doc_set_pre_input_hook},
574 #endif
575 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
576 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
577 #endif
578 {0, 0}
582 /* C function to call the Python hooks. */
584 static int
585 on_hook(PyObject *func)
587 int result = 0;
588 if (func != NULL) {
589 PyObject *r;
590 #ifdef WITH_THREAD
591 PyGILState_STATE gilstate = PyGILState_Ensure();
592 #endif
593 r = PyObject_CallFunction(func, NULL);
594 if (r == NULL)
595 goto error;
596 if (r == Py_None)
597 result = 0;
598 else {
599 result = PyInt_AsLong(r);
600 if (result == -1 && PyErr_Occurred())
601 goto error;
603 Py_DECREF(r);
604 goto done;
605 error:
606 PyErr_Clear();
607 Py_XDECREF(r);
608 done:
609 #ifdef WITH_THREAD
610 PyGILState_Release(gilstate);
611 #endif
612 return result;
614 return result;
617 static int
618 on_startup_hook(void)
620 return on_hook(startup_hook);
623 #ifdef HAVE_RL_PRE_INPUT_HOOK
624 static int
625 on_pre_input_hook(void)
627 return on_hook(pre_input_hook);
629 #endif
632 /* C function to call the Python completer. */
634 static char *
635 on_completion(char *text, int state)
637 char *result = NULL;
638 if (completer != NULL) {
639 PyObject *r;
640 #ifdef WITH_THREAD
641 PyGILState_STATE gilstate = PyGILState_Ensure();
642 #endif
643 rl_attempted_completion_over = 1;
644 r = PyObject_CallFunction(completer, "si", text, state);
645 if (r == NULL)
646 goto error;
647 if (r == Py_None) {
648 result = NULL;
650 else {
651 char *s = PyString_AsString(r);
652 if (s == NULL)
653 goto error;
654 result = strdup(s);
656 Py_DECREF(r);
657 goto done;
658 error:
659 PyErr_Clear();
660 Py_XDECREF(r);
661 done:
662 #ifdef WITH_THREAD
663 PyGILState_Release(gilstate);
664 #endif
665 return result;
667 return result;
671 /* A more flexible constructor that saves the "begidx" and "endidx"
672 * before calling the normal completer */
674 static char **
675 flex_complete(char *text, int start, int end)
677 Py_XDECREF(begidx);
678 Py_XDECREF(endidx);
679 begidx = PyInt_FromLong((long) start);
680 endidx = PyInt_FromLong((long) end);
681 return completion_matches(text, *on_completion);
685 /* Helper to initialize GNU readline properly. */
687 static void
688 setup_readline(void)
690 #ifdef SAVE_LOCALE
691 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
692 if (!saved_locale)
693 Py_FatalError("not enough memory to save locale");
694 #endif
696 using_history();
698 rl_readline_name = "python";
699 #if defined(PYOS_OS2) && defined(PYCC_GCC)
700 /* Allow $if term= in .inputrc to work */
701 rl_terminal_name = getenv("TERM");
702 #endif
703 /* Force rebind of TAB to insert-tab */
704 rl_bind_key('\t', rl_insert);
705 /* Bind both ESC-TAB and ESC-ESC to the completion function */
706 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
707 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
708 /* Set our hook functions */
709 rl_startup_hook = (Function *)on_startup_hook;
710 #ifdef HAVE_RL_PRE_INPUT_HOOK
711 rl_pre_input_hook = (Function *)on_pre_input_hook;
712 #endif
713 /* Set our completion function */
714 rl_attempted_completion_function = (CPPFunction *)flex_complete;
715 /* Set Python word break characters */
716 rl_completer_word_break_characters =
717 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
718 /* All nonalphanums except '.' */
719 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
720 rl_completion_append_character ='\0';
721 #endif
723 begidx = PyInt_FromLong(0L);
724 endidx = PyInt_FromLong(0L);
725 /* Initialize (allows .inputrc to override)
727 * XXX: A bug in the readline-2.2 library causes a memory leak
728 * inside this function. Nothing we can do about it.
730 rl_initialize();
732 RESTORE_LOCALE(saved_locale)
735 /* Wrapper around GNU readline that handles signals differently. */
738 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
740 static char *completed_input_string;
741 static void
742 rlhandler(char *text)
744 completed_input_string = text;
745 rl_callback_handler_remove();
748 extern PyThreadState* _PyOS_ReadlineTState;
750 static char *
751 readline_until_enter_or_signal(char *prompt, int *signal)
753 char * not_done_reading = "";
754 fd_set selectset;
756 *signal = 0;
757 #ifdef HAVE_RL_CATCH_SIGNAL
758 rl_catch_signals = 0;
759 #endif
761 rl_callback_handler_install (prompt, rlhandler);
762 FD_ZERO(&selectset);
764 completed_input_string = not_done_reading;
766 while (completed_input_string == not_done_reading) {
767 int has_input = 0;
769 while (!has_input)
770 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
772 /* [Bug #1552726] Only limit the pause if an input hook has been
773 defined. */
774 struct timeval *timeoutp = NULL;
775 if (PyOS_InputHook)
776 timeoutp = &timeout;
777 FD_SET(fileno(rl_instream), &selectset);
778 /* select resets selectset if no input was available */
779 has_input = select(fileno(rl_instream) + 1, &selectset,
780 NULL, NULL, timeoutp);
781 if(PyOS_InputHook) PyOS_InputHook();
784 if(has_input > 0) {
785 rl_callback_read_char();
787 else if (errno == EINTR) {
788 int s;
789 #ifdef WITH_THREAD
790 PyEval_RestoreThread(_PyOS_ReadlineTState);
791 #endif
792 s = PyErr_CheckSignals();
793 #ifdef WITH_THREAD
794 PyEval_SaveThread();
795 #endif
796 if (s < 0) {
797 rl_free_line_state();
798 rl_cleanup_after_signal();
799 rl_callback_handler_remove();
800 *signal = 1;
801 completed_input_string = NULL;
806 return completed_input_string;
810 #else
812 /* Interrupt handler */
814 static jmp_buf jbuf;
816 /* ARGSUSED */
817 static void
818 onintr(int sig)
820 longjmp(jbuf, 1);
824 static char *
825 readline_until_enter_or_signal(char *prompt, int *signal)
827 PyOS_sighandler_t old_inthandler;
828 char *p;
830 *signal = 0;
832 old_inthandler = PyOS_setsig(SIGINT, onintr);
833 if (setjmp(jbuf)) {
834 #ifdef HAVE_SIGRELSE
835 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
836 sigrelse(SIGINT);
837 #endif
838 PyOS_setsig(SIGINT, old_inthandler);
839 *signal = 1;
840 return NULL;
842 rl_event_hook = PyOS_InputHook;
843 p = readline(prompt);
844 PyOS_setsig(SIGINT, old_inthandler);
846 return p;
848 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
851 static char *
852 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
854 size_t n;
855 char *p, *q;
856 int signal;
858 #ifdef SAVE_LOCALE
859 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
860 if (!saved_locale)
861 Py_FatalError("not enough memory to save locale");
862 setlocale(LC_CTYPE, "");
863 #endif
865 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
866 rl_instream = sys_stdin;
867 rl_outstream = sys_stdout;
868 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
869 rl_prep_terminal (1);
870 #endif
873 p = readline_until_enter_or_signal(prompt, &signal);
875 /* we got an interrupt signal */
876 if (signal) {
877 RESTORE_LOCALE(saved_locale)
878 return NULL;
881 /* We got an EOF, return a empty string. */
882 if (p == NULL) {
883 p = PyMem_Malloc(1);
884 if (p != NULL)
885 *p = '\0';
886 RESTORE_LOCALE(saved_locale)
887 return p;
890 /* we have a valid line */
891 n = strlen(p);
892 if (n > 0) {
893 char *line;
894 HISTORY_STATE *state = history_get_history_state();
895 if (state->length > 0)
896 line = history_get(state->length)->line;
897 else
898 line = "";
899 if (strcmp(p, line))
900 add_history(p);
901 /* the history docs don't say so, but the address of state
902 changes each time history_get_history_state is called
903 which makes me think it's freshly malloc'd memory...
904 on the other hand, the address of the last line stays the
905 same as long as history isn't extended, so it appears to
906 be malloc'd but managed by the history package... */
907 free(state);
909 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
910 release the original. */
911 q = p;
912 p = PyMem_Malloc(n+2);
913 if (p != NULL) {
914 strncpy(p, q, n);
915 p[n] = '\n';
916 p[n+1] = '\0';
918 free(q);
919 RESTORE_LOCALE(saved_locale)
920 return p;
924 /* Initialize the module */
926 PyDoc_STRVAR(doc_module,
927 "Importing this module enables command line editing using GNU readline.");
929 PyMODINIT_FUNC
930 initreadline(void)
932 PyObject *m;
934 m = Py_InitModule4("readline", readline_methods, doc_module,
935 (PyObject *)NULL, PYTHON_API_VERSION);
936 if (m == NULL)
937 return;
939 PyOS_ReadlineFunctionPointer = call_readline;
940 setup_readline();