Tagging 3.0a4.
[python/dscho.git] / Modules / readline.c
blobd42998ef46d83ffd5fecd61ae179963743289e65
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 PyLong_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 PyLong_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 PyUnicode_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 PyUnicode_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 PyLong_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 PyUnicode_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 = PyLong_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 = PyUnicode_FromString(matches[i+1]);
680 if (s == NULL)
681 goto error;
682 if (PyList_SetItem(m, i, s) == -1)
683 goto error;
685 r = PyObject_CallFunction(completion_display_matches_hook,
686 "sOi", matches[0], m, max_length);
688 Py_DECREF(m), m=NULL;
690 if (r == NULL ||
691 (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
692 goto error;
694 Py_XDECREF(r), r=NULL;
696 if (0) {
697 error:
698 PyErr_Clear();
699 Py_XDECREF(m);
700 Py_XDECREF(r);
702 #ifdef WITH_THREAD
703 PyGILState_Release(gilstate);
704 #endif
708 /* C function to call the Python completer. */
710 static char *
711 on_completion(const char *text, int state)
713 char *result = NULL;
714 if (completer != NULL) {
715 PyObject *r;
716 #ifdef WITH_THREAD
717 PyGILState_STATE gilstate = PyGILState_Ensure();
718 #endif
719 rl_attempted_completion_over = 1;
720 r = PyObject_CallFunction(completer, "si", text, state);
721 if (r == NULL)
722 goto error;
723 if (r == Py_None) {
724 result = NULL;
726 else {
727 char *s = PyUnicode_AsString(r);
728 if (s == NULL)
729 goto error;
730 result = strdup(s);
732 Py_DECREF(r);
733 goto done;
734 error:
735 PyErr_Clear();
736 Py_XDECREF(r);
737 done:
738 #ifdef WITH_THREAD
739 PyGILState_Release(gilstate);
740 #endif
741 return result;
743 return result;
747 /* A more flexible constructor that saves the "begidx" and "endidx"
748 * before calling the normal completer */
750 static char **
751 flex_complete(char *text, int start, int end)
753 Py_XDECREF(begidx);
754 Py_XDECREF(endidx);
755 begidx = PyLong_FromLong((long) start);
756 endidx = PyLong_FromLong((long) end);
757 return completion_matches(text, *on_completion);
761 /* Helper to initialize GNU readline properly. */
763 static void
764 setup_readline(void)
766 #ifdef SAVE_LOCALE
767 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
768 if (!saved_locale)
769 Py_FatalError("not enough memory to save locale");
770 #endif
772 using_history();
774 rl_readline_name = "python";
775 #if defined(PYOS_OS2) && defined(PYCC_GCC)
776 /* Allow $if term= in .inputrc to work */
777 rl_terminal_name = getenv("TERM");
778 #endif
779 /* Force rebind of TAB to insert-tab */
780 rl_bind_key('\t', rl_insert);
781 /* Bind both ESC-TAB and ESC-ESC to the completion function */
782 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
783 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
784 /* Set our hook functions */
785 rl_startup_hook = (Function *)on_startup_hook;
786 #ifdef HAVE_RL_PRE_INPUT_HOOK
787 rl_pre_input_hook = (Function *)on_pre_input_hook;
788 #endif
789 /* Set our completion function */
790 rl_attempted_completion_function = (CPPFunction *)flex_complete;
791 /* Set Python word break characters */
792 rl_completer_word_break_characters =
793 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
794 /* All nonalphanums except '.' */
795 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
796 rl_completion_append_character ='\0';
797 #endif
799 begidx = PyLong_FromLong(0L);
800 endidx = PyLong_FromLong(0L);
801 /* Initialize (allows .inputrc to override)
803 * XXX: A bug in the readline-2.2 library causes a memory leak
804 * inside this function. Nothing we can do about it.
806 rl_initialize();
808 RESTORE_LOCALE(saved_locale)
811 /* Wrapper around GNU readline that handles signals differently. */
814 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
816 static char *completed_input_string;
817 static void
818 rlhandler(char *text)
820 completed_input_string = text;
821 rl_callback_handler_remove();
824 extern PyThreadState* _PyOS_ReadlineTState;
826 static char *
827 readline_until_enter_or_signal(char *prompt, int *signal)
829 char * not_done_reading = "";
830 fd_set selectset;
832 *signal = 0;
833 #ifdef HAVE_RL_CATCH_SIGNAL
834 rl_catch_signals = 0;
835 #endif
837 rl_callback_handler_install (prompt, rlhandler);
838 FD_ZERO(&selectset);
840 completed_input_string = not_done_reading;
842 while (completed_input_string == not_done_reading) {
843 int has_input = 0;
845 while (!has_input)
846 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
848 /* [Bug #1552726] Only limit the pause if an input hook has been
849 defined. */
850 struct timeval *timeoutp = NULL;
851 if (PyOS_InputHook)
852 timeoutp = &timeout;
853 FD_SET(fileno(rl_instream), &selectset);
854 /* select resets selectset if no input was available */
855 has_input = select(fileno(rl_instream) + 1, &selectset,
856 NULL, NULL, timeoutp);
857 if(PyOS_InputHook) PyOS_InputHook();
860 if(has_input > 0) {
861 rl_callback_read_char();
863 else if (errno == EINTR) {
864 int s;
865 #ifdef WITH_THREAD
866 PyEval_RestoreThread(_PyOS_ReadlineTState);
867 #endif
868 s = PyErr_CheckSignals();
869 #ifdef WITH_THREAD
870 PyEval_SaveThread();
871 #endif
872 if (s < 0) {
873 rl_free_line_state();
874 rl_cleanup_after_signal();
875 rl_callback_handler_remove();
876 *signal = 1;
877 completed_input_string = NULL;
882 return completed_input_string;
886 #else
888 /* Interrupt handler */
890 static jmp_buf jbuf;
892 /* ARGSUSED */
893 static void
894 onintr(int sig)
896 longjmp(jbuf, 1);
900 static char *
901 readline_until_enter_or_signal(char *prompt, int *signal)
903 PyOS_sighandler_t old_inthandler;
904 char *p;
906 *signal = 0;
908 old_inthandler = PyOS_setsig(SIGINT, onintr);
909 if (setjmp(jbuf)) {
910 #ifdef HAVE_SIGRELSE
911 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
912 sigrelse(SIGINT);
913 #endif
914 PyOS_setsig(SIGINT, old_inthandler);
915 *signal = 1;
916 return NULL;
918 rl_event_hook = PyOS_InputHook;
919 p = readline(prompt);
920 PyOS_setsig(SIGINT, old_inthandler);
922 return p;
924 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
927 static char *
928 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
930 size_t n;
931 char *p, *q;
932 int signal;
934 #ifdef SAVE_LOCALE
935 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
936 if (!saved_locale)
937 Py_FatalError("not enough memory to save locale");
938 setlocale(LC_CTYPE, "");
939 #endif
941 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
942 rl_instream = sys_stdin;
943 rl_outstream = sys_stdout;
944 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
945 rl_prep_terminal (1);
946 #endif
949 p = readline_until_enter_or_signal(prompt, &signal);
951 /* we got an interrupt signal */
952 if (signal) {
953 RESTORE_LOCALE(saved_locale)
954 return NULL;
957 /* We got an EOF, return a empty string. */
958 if (p == NULL) {
959 p = PyMem_Malloc(1);
960 if (p != NULL)
961 *p = '\0';
962 RESTORE_LOCALE(saved_locale)
963 return p;
966 /* we have a valid line */
967 n = strlen(p);
968 if (n > 0) {
969 char *line;
970 HISTORY_STATE *state = history_get_history_state();
971 if (state->length > 0)
972 line = history_get(state->length)->line;
973 else
974 line = "";
975 if (strcmp(p, line))
976 add_history(p);
977 /* the history docs don't say so, but the address of state
978 changes each time history_get_history_state is called
979 which makes me think it's freshly malloc'd memory...
980 on the other hand, the address of the last line stays the
981 same as long as history isn't extended, so it appears to
982 be malloc'd but managed by the history package... */
983 free(state);
985 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
986 release the original. */
987 q = p;
988 p = PyMem_Malloc(n+2);
989 if (p != NULL) {
990 strncpy(p, q, n);
991 p[n] = '\n';
992 p[n+1] = '\0';
994 free(q);
995 RESTORE_LOCALE(saved_locale)
996 return p;
1000 /* Initialize the module */
1002 PyDoc_STRVAR(doc_module,
1003 "Importing this module enables command line editing using GNU readline.");
1005 PyMODINIT_FUNC
1006 initreadline(void)
1008 PyObject *m;
1010 m = Py_InitModule4("readline", readline_methods, doc_module,
1011 (PyObject *)NULL, PYTHON_API_VERSION);
1012 if (m == NULL)
1013 return;
1015 PyOS_ReadlineFunctionPointer = call_readline;
1016 setup_readline();