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.
7 /* Standard definitions */
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.
24 # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
26 # define RESTORE_LOCALE(sl)
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)))
38 extern char **completion_matches(char *, rl_compentry_func_t
*);
42 /* Exported function to send one line to readline's init file parser */
45 parse_and_bind(PyObject
*self
, PyObject
*args
)
48 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
50 /* Make a copy -- rl_parse_and_bind() modifies its argument */
52 copy
= malloc(1 + strlen(s
));
54 return PyErr_NoMemory();
56 rl_parse_and_bind(copy
);
57 free(copy
); /* Free the copy */
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 */
70 read_init_file(PyObject
*self
, PyObject
*args
)
73 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
75 errno
= rl_read_init_file(s
);
77 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
91 read_history_file(PyObject
*self
, PyObject
*args
)
94 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
96 errno
= read_history(s
);
98 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
113 write_history_file(PyObject
*self
, PyObject
*args
)
116 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
118 errno
= write_history(s
);
119 if (!errno
&& _history_length
>= 0)
120 history_truncate_file(s
, _history_length
);
122 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
136 set_history_length(PyObject
*self
, PyObject
*args
)
138 int length
= _history_length
;
139 if (!PyArg_ParseTuple(args
, "i:set_history_length", &length
))
141 _history_length
= length
;
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 */
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\
167 /* Generic hook function setter */
170 set_hook(const char *funcname
, PyObject
**hook_var
, PyObject
*args
)
172 PyObject
*function
= Py_None
;
174 PyOS_snprintf(buf
, sizeof(buf
), "|O:set_%.50s", funcname
);
175 if (!PyArg_ParseTuple(args
, buf
, &function
))
177 if (function
== Py_None
) {
178 Py_XDECREF(*hook_var
);
181 else if (PyCallable_Check(function
)) {
182 PyObject
*tmp
= *hook_var
;
184 *hook_var
= function
;
188 PyOS_snprintf(buf
, sizeof(buf
),
189 "set_%.50s(func): argument not callable",
191 PyErr_SetString(PyExc_TypeError
, buf
);
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
;
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 */
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\
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 */
251 get_begidx(PyObject
*self
, PyObject
*noarg
)
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 */
265 get_endidx(PyObject
*self
, PyObject
*noarg
)
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 */
279 set_completer_delims(PyObject
*self
, PyObject
*args
)
283 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
286 free((void*)rl_completer_word_break_characters
);
287 rl_completer_word_break_characters
= strdup(break_chars
);
292 PyDoc_STRVAR(doc_set_completer_delims
,
293 "set_completer_delims(string) -> None\n\
294 set the readline word delimiters for tab-completion");
297 py_remove_history(PyObject
*self
, PyObject
*args
)
302 if (!PyArg_ParseTuple(args
, "i:remove_history", &entry_number
))
304 if (entry_number
< 0) {
305 PyErr_SetString(PyExc_ValueError
,
306 "History index cannot be negative");
309 entry
= remove_history(entry_number
);
311 PyErr_Format(PyExc_ValueError
,
312 "No history item at position %d",
316 /* free memory allocated for the history entry */
327 PyDoc_STRVAR(doc_remove_history
,
328 "remove_history_item(pos) -> None\n\
329 remove history item given by its position");
332 py_replace_history(PyObject
*self
, PyObject
*args
)
336 HIST_ENTRY
*old_entry
;
338 if (!PyArg_ParseTuple(args
, "is:replace_history", &entry_number
, &line
)) {
341 if (entry_number
< 0) {
342 PyErr_SetString(PyExc_ValueError
,
343 "History index cannot be negative");
346 old_entry
= replace_history_entry(entry_number
, line
, (void *)NULL
);
348 PyErr_Format(PyExc_ValueError
,
349 "No history item at position %d",
353 /* free memory allocated for the old history entry */
355 free(old_entry
->line
);
357 free(old_entry
->data
);
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 */
371 py_add_history(PyObject
*self
, PyObject
*args
)
375 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
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 */
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 */
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'.");
418 get_completer(PyObject
*self
, PyObject
*noargs
)
420 if (completer
== NULL
) {
424 Py_INCREF(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 */
436 get_history_item(PyObject
*self
, PyObject
*args
)
439 HIST_ENTRY
*hist_ent
;
441 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
443 if ((hist_ent
= history_get(idx
)))
444 return PyString_FromString(hist_ent
->line
);
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 */
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 */
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 */
490 py_clear_history(PyObject
*self
, PyObject
*noarg
)
497 PyDoc_STRVAR(doc_clear_history
,
498 "clear_history() -> None\n\
499 Clear the current readline history.");
503 /* Exported function to insert text into the line buffer */
506 insert_text(PyObject
*self
, PyObject
*args
)
509 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
516 PyDoc_STRVAR(doc_insert_text
,
517 "insert_text(string) -> None\n\
518 Insert text into the command line.");
521 /* Redisplay the line buffer */
524 redisplay(PyObject
*self
, PyObject
*noarg
)
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
},
577 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
578 {"clear_history", py_clear_history
, METH_NOARGS
, doc_clear_history
},
584 /* C function to call the Python hooks. */
587 on_hook(PyObject
*func
)
593 PyGILState_STATE gilstate
= PyGILState_Ensure();
595 r
= PyObject_CallFunction(func
, NULL
);
601 result
= PyInt_AsLong(r
);
602 if (result
== -1 && PyErr_Occurred())
612 PyGILState_Release(gilstate
);
620 on_startup_hook(void)
622 return on_hook(startup_hook
);
625 #ifdef HAVE_RL_PRE_INPUT_HOOK
627 on_pre_input_hook(void)
629 return on_hook(pre_input_hook
);
634 /* C function to call the Python completer. */
637 on_completion(const char *text
, int state
)
640 if (completer
!= NULL
) {
643 PyGILState_STATE gilstate
= PyGILState_Ensure();
645 rl_attempted_completion_over
= 1;
646 r
= PyObject_CallFunction(completer
, "si", text
, state
);
653 char *s
= PyString_AsString(r
);
665 PyGILState_Release(gilstate
);
673 /* A more flexible constructor that saves the "begidx" and "endidx"
674 * before calling the normal completer */
677 flex_complete(char *text
, int start
, int end
)
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. */
693 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
695 Py_FatalError("not enough memory to save locale");
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");
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
;
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';
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.
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
;
744 rlhandler(char *text
)
746 completed_input_string
= text
;
747 rl_callback_handler_remove();
750 extern PyThreadState
* _PyOS_ReadlineTState
;
753 readline_until_enter_or_signal(char *prompt
, int *signal
)
755 char * not_done_reading
= "";
759 #ifdef HAVE_RL_CATCH_SIGNAL
760 rl_catch_signals
= 0;
763 rl_callback_handler_install (prompt
, rlhandler
);
766 completed_input_string
= not_done_reading
;
768 while (completed_input_string
== not_done_reading
) {
772 { struct timeval timeout
= {0, 100000}; /* 0.1 seconds */
774 /* [Bug #1552726] Only limit the pause if an input hook has been
776 struct timeval
*timeoutp
= NULL
;
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();
787 rl_callback_read_char();
789 else if (errno
== EINTR
) {
792 PyEval_RestoreThread(_PyOS_ReadlineTState
);
794 s
= PyErr_CheckSignals();
799 rl_free_line_state();
800 rl_cleanup_after_signal();
801 rl_callback_handler_remove();
803 completed_input_string
= NULL
;
808 return completed_input_string
;
814 /* Interrupt handler */
827 readline_until_enter_or_signal(char *prompt
, int *signal
)
829 PyOS_sighandler_t old_inthandler
;
834 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
837 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
840 PyOS_setsig(SIGINT
, old_inthandler
);
844 rl_event_hook
= PyOS_InputHook
;
845 p
= readline(prompt
);
846 PyOS_setsig(SIGINT
, old_inthandler
);
850 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
854 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
861 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
863 Py_FatalError("not enough memory to save locale");
864 setlocale(LC_CTYPE
, "");
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);
875 p
= readline_until_enter_or_signal(prompt
, &signal
);
877 /* we got an interrupt signal */
879 RESTORE_LOCALE(saved_locale
)
883 /* We got an EOF, return a empty string. */
888 RESTORE_LOCALE(saved_locale
)
892 /* we have a valid line */
896 HISTORY_STATE
*state
= history_get_history_state();
897 if (state
->length
> 0)
898 line
= history_get(state
->length
)->line
;
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... */
911 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
912 release the original. */
914 p
= PyMem_Malloc(n
+2);
921 RESTORE_LOCALE(saved_locale
)
926 /* Initialize the module */
928 PyDoc_STRVAR(doc_module
,
929 "Importing this module enables command line editing using GNU readline.");
936 m
= Py_InitModule4("readline", readline_methods
, doc_module
,
937 (PyObject
*)NULL
, PYTHON_API_VERSION
);
941 PyOS_ReadlineFunctionPointer
= call_readline
;