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 #if defined(_RL_FUNCTION_TYPEDEF)
39 extern char **completion_matches(char *, rl_compentry_func_t
*);
41 extern char **completion_matches(char *, CPFunction
*);
46 on_completion_display_matches_hook(char **matches
,
47 int num_matches
, int max_length
);
50 /* Exported function to send one line to readline's init file parser */
53 parse_and_bind(PyObject
*self
, PyObject
*args
)
56 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
58 /* Make a copy -- rl_parse_and_bind() modifies its argument */
60 copy
= malloc(1 + strlen(s
));
62 return PyErr_NoMemory();
64 rl_parse_and_bind(copy
);
65 free(copy
); /* Free the copy */
69 PyDoc_STRVAR(doc_parse_and_bind
,
70 "parse_and_bind(string) -> None\n\
71 Parse and execute single line of a readline init file.");
74 /* Exported function to parse a readline init file */
77 read_init_file(PyObject
*self
, PyObject
*args
)
80 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
82 errno
= rl_read_init_file(s
);
84 return PyErr_SetFromErrno(PyExc_IOError
);
88 PyDoc_STRVAR(doc_read_init_file
,
89 "read_init_file([filename]) -> None\n\
90 Parse a readline initialization file.\n\
91 The default filename is the last filename used.");
94 /* Exported function to load a readline history file */
97 read_history_file(PyObject
*self
, PyObject
*args
)
100 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
102 errno
= read_history(s
);
104 return PyErr_SetFromErrno(PyExc_IOError
);
108 static int _history_length
= -1; /* do not truncate history by default */
109 PyDoc_STRVAR(doc_read_history_file
,
110 "read_history_file([filename]) -> None\n\
111 Load a readline history file.\n\
112 The default filename is ~/.history.");
115 /* Exported function to save a readline history file */
118 write_history_file(PyObject
*self
, PyObject
*args
)
121 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
123 errno
= write_history(s
);
124 if (!errno
&& _history_length
>= 0)
125 history_truncate_file(s
, _history_length
);
127 return PyErr_SetFromErrno(PyExc_IOError
);
131 PyDoc_STRVAR(doc_write_history_file
,
132 "write_history_file([filename]) -> None\n\
133 Save a readline history file.\n\
134 The default filename is ~/.history.");
137 /* Set history length */
140 set_history_length(PyObject
*self
, PyObject
*args
)
142 int length
= _history_length
;
143 if (!PyArg_ParseTuple(args
, "i:set_history_length", &length
))
145 _history_length
= length
;
149 PyDoc_STRVAR(set_history_length_doc
,
150 "set_history_length(length) -> None\n\
151 set the maximal number of items which will be written to\n\
152 the history file. A negative length is used to inhibit\n\
153 history truncation.");
156 /* Get history length */
159 get_history_length(PyObject
*self
, PyObject
*noarg
)
161 return PyLong_FromLong(_history_length
);
164 PyDoc_STRVAR(get_history_length_doc
,
165 "get_history_length() -> int\n\
166 return the maximum number of items that will be written to\n\
170 /* Generic hook function setter */
173 set_hook(const char *funcname
, PyObject
**hook_var
, PyObject
*args
)
175 PyObject
*function
= Py_None
;
177 PyOS_snprintf(buf
, sizeof(buf
), "|O:set_%.50s", funcname
);
178 if (!PyArg_ParseTuple(args
, buf
, &function
))
180 if (function
== Py_None
) {
181 Py_XDECREF(*hook_var
);
184 else if (PyCallable_Check(function
)) {
185 PyObject
*tmp
= *hook_var
;
187 *hook_var
= function
;
191 PyOS_snprintf(buf
, sizeof(buf
),
192 "set_%.50s(func): argument not callable",
194 PyErr_SetString(PyExc_TypeError
, buf
);
201 /* Exported functions to specify hook functions in Python */
203 static PyObject
*completion_display_matches_hook
= NULL
;
204 static PyObject
*startup_hook
= NULL
;
206 #ifdef HAVE_RL_PRE_INPUT_HOOK
207 static PyObject
*pre_input_hook
= NULL
;
211 set_completion_display_matches_hook(PyObject
*self
, PyObject
*args
)
213 PyObject
*result
= set_hook("completion_display_matches_hook",
214 &completion_display_matches_hook
, args
);
215 #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
216 /* We cannot set this hook globally, since it replaces the
217 default completion display. */
218 rl_completion_display_matches_hook
=
219 completion_display_matches_hook
?
220 #if defined(_RL_FUNCTION_TYPEDEF)
221 (rl_compdisp_func_t
*)on_completion_display_matches_hook
: 0;
223 (VFunction
*)on_completion_display_matches_hook
: 0;
230 PyDoc_STRVAR(doc_set_completion_display_matches_hook
,
231 "set_completion_display_matches_hook([function]) -> None\n\
232 Set or remove the completion display function.\n\
233 The function is called as\n\
234 function(substitution, [matches], longest_match_length)\n\
235 once each time matches need to be displayed.");
238 set_startup_hook(PyObject
*self
, PyObject
*args
)
240 return set_hook("startup_hook", &startup_hook
, args
);
243 PyDoc_STRVAR(doc_set_startup_hook
,
244 "set_startup_hook([function]) -> None\n\
245 Set or remove the startup_hook function.\n\
246 The function is called with no arguments just\n\
247 before readline prints the first prompt.");
250 #ifdef HAVE_RL_PRE_INPUT_HOOK
252 /* Set pre-input hook */
255 set_pre_input_hook(PyObject
*self
, PyObject
*args
)
257 return set_hook("pre_input_hook", &pre_input_hook
, args
);
260 PyDoc_STRVAR(doc_set_pre_input_hook
,
261 "set_pre_input_hook([function]) -> None\n\
262 Set or remove the pre_input_hook function.\n\
263 The function is called with no arguments after the first prompt\n\
264 has been printed and just before readline starts reading input\n\
270 /* Exported function to specify a word completer in Python */
272 static PyObject
*completer
= NULL
;
274 static PyObject
*begidx
= NULL
;
275 static PyObject
*endidx
= NULL
;
278 /* Get the completion type for the scope of the tab-completion */
280 get_completion_type(PyObject
*self
, PyObject
*noarg
)
282 return PyLong_FromLong(rl_completion_type
);
285 PyDoc_STRVAR(doc_get_completion_type
,
286 "get_completion_type() -> int\n\
287 Get the type of completion being attempted.");
290 /* Get the beginning index for the scope of the tab-completion */
293 get_begidx(PyObject
*self
, PyObject
*noarg
)
299 PyDoc_STRVAR(doc_get_begidx
,
300 "get_begidx() -> int\n\
301 get the beginning index of the readline tab-completion scope");
304 /* Get the ending index for the scope of the tab-completion */
307 get_endidx(PyObject
*self
, PyObject
*noarg
)
313 PyDoc_STRVAR(doc_get_endidx
,
314 "get_endidx() -> int\n\
315 get the ending index of the readline tab-completion scope");
318 /* Set the tab-completion word-delimiters that readline uses */
321 set_completer_delims(PyObject
*self
, PyObject
*args
)
325 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
328 free((void*)rl_completer_word_break_characters
);
329 rl_completer_word_break_characters
= strdup(break_chars
);
333 PyDoc_STRVAR(doc_set_completer_delims
,
334 "set_completer_delims(string) -> None\n\
335 set the readline word delimiters for tab-completion");
338 py_remove_history(PyObject
*self
, PyObject
*args
)
343 if (!PyArg_ParseTuple(args
, "i:remove_history", &entry_number
))
345 if (entry_number
< 0) {
346 PyErr_SetString(PyExc_ValueError
,
347 "History index cannot be negative");
350 entry
= remove_history(entry_number
);
352 PyErr_Format(PyExc_ValueError
,
353 "No history item at position %d",
357 /* free memory allocated for the history entry */
367 PyDoc_STRVAR(doc_remove_history
,
368 "remove_history_item(pos) -> None\n\
369 remove history item given by its position");
372 py_replace_history(PyObject
*self
, PyObject
*args
)
376 HIST_ENTRY
*old_entry
;
378 if (!PyArg_ParseTuple(args
, "is:replace_history", &entry_number
,
382 if (entry_number
< 0) {
383 PyErr_SetString(PyExc_ValueError
,
384 "History index cannot be negative");
387 old_entry
= replace_history_entry(entry_number
, line
, (void *)NULL
);
389 PyErr_Format(PyExc_ValueError
,
390 "No history item at position %d",
394 /* free memory allocated for the old history entry */
396 free(old_entry
->line
);
398 free(old_entry
->data
);
404 PyDoc_STRVAR(doc_replace_history
,
405 "replace_history_item(pos, line) -> None\n\
406 replaces history item given by its position with contents of line");
408 /* Add a line to the history buffer */
411 py_add_history(PyObject
*self
, PyObject
*args
)
415 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
422 PyDoc_STRVAR(doc_add_history
,
423 "add_history(string) -> None\n\
424 add a line to the history buffer");
427 /* Get the tab-completion word-delimiters that readline uses */
430 get_completer_delims(PyObject
*self
, PyObject
*noarg
)
432 return PyUnicode_FromString(rl_completer_word_break_characters
);
435 PyDoc_STRVAR(doc_get_completer_delims
,
436 "get_completer_delims() -> string\n\
437 get the readline word delimiters for tab-completion");
440 /* Set the completer function */
443 set_completer(PyObject
*self
, PyObject
*args
)
445 return set_hook("completer", &completer
, args
);
448 PyDoc_STRVAR(doc_set_completer
,
449 "set_completer([function]) -> None\n\
450 Set or remove the completer function.\n\
451 The function is called as function(text, state),\n\
452 for state in 0, 1, 2, ..., until it returns a non-string.\n\
453 It should return the next possible completion starting with 'text'.");
457 get_completer(PyObject
*self
, PyObject
*noargs
)
459 if (completer
== NULL
) {
462 Py_INCREF(completer
);
466 PyDoc_STRVAR(doc_get_completer
,
467 "get_completer() -> function\n\
469 Returns current completer function.");
471 /* Exported function to get any element of history */
474 get_history_item(PyObject
*self
, PyObject
*args
)
477 HIST_ENTRY
*hist_ent
;
479 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
481 if ((hist_ent
= history_get(idx
)))
482 return PyUnicode_FromString(hist_ent
->line
);
488 PyDoc_STRVAR(doc_get_history_item
,
489 "get_history_item() -> string\n\
490 return the current contents of history item at index.");
493 /* Exported function to get current length of history */
496 get_current_history_length(PyObject
*self
, PyObject
*noarg
)
498 HISTORY_STATE
*hist_st
;
500 hist_st
= history_get_history_state();
501 return PyLong_FromLong(hist_st
? (long) hist_st
->length
: (long) 0);
504 PyDoc_STRVAR(doc_get_current_history_length
,
505 "get_current_history_length() -> integer\n\
506 return the current (not the maximum) length of history.");
509 /* Exported function to read the current line buffer */
512 get_line_buffer(PyObject
*self
, PyObject
*noarg
)
514 return PyUnicode_FromString(rl_line_buffer
);
517 PyDoc_STRVAR(doc_get_line_buffer
,
518 "get_line_buffer() -> string\n\
519 return the current contents of the line buffer.");
522 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
524 /* Exported function to clear the current history */
527 py_clear_history(PyObject
*self
, PyObject
*noarg
)
533 PyDoc_STRVAR(doc_clear_history
,
534 "clear_history() -> None\n\
535 Clear the current readline history.");
539 /* Exported function to insert text into the line buffer */
542 insert_text(PyObject
*self
, PyObject
*args
)
545 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
551 PyDoc_STRVAR(doc_insert_text
,
552 "insert_text(string) -> None\n\
553 Insert text into the command line.");
556 /* Redisplay the line buffer */
559 redisplay(PyObject
*self
, PyObject
*noarg
)
565 PyDoc_STRVAR(doc_redisplay
,
566 "redisplay() -> None\n\
567 Change what's displayed on the screen to reflect the current\n\
568 contents of the line buffer.");
571 /* Table of functions exported by the module */
573 static struct PyMethodDef readline_methods
[] =
575 {"parse_and_bind", parse_and_bind
, METH_VARARGS
, doc_parse_and_bind
},
576 {"get_line_buffer", get_line_buffer
, METH_NOARGS
, doc_get_line_buffer
},
577 {"insert_text", insert_text
, METH_VARARGS
, doc_insert_text
},
578 {"redisplay", redisplay
, METH_NOARGS
, doc_redisplay
},
579 {"read_init_file", read_init_file
, METH_VARARGS
, doc_read_init_file
},
580 {"read_history_file", read_history_file
,
581 METH_VARARGS
, doc_read_history_file
},
582 {"write_history_file", write_history_file
,
583 METH_VARARGS
, doc_write_history_file
},
584 {"get_history_item", get_history_item
,
585 METH_VARARGS
, doc_get_history_item
},
586 {"get_current_history_length", (PyCFunction
)get_current_history_length
,
587 METH_NOARGS
, doc_get_current_history_length
},
588 {"set_history_length", set_history_length
,
589 METH_VARARGS
, set_history_length_doc
},
590 {"get_history_length", get_history_length
,
591 METH_NOARGS
, get_history_length_doc
},
592 {"set_completer", set_completer
, METH_VARARGS
, doc_set_completer
},
593 {"get_completer", get_completer
, METH_NOARGS
, doc_get_completer
},
594 {"get_completion_type", get_completion_type
,
595 METH_NOARGS
, doc_get_completion_type
},
596 {"get_begidx", get_begidx
, METH_NOARGS
, doc_get_begidx
},
597 {"get_endidx", get_endidx
, METH_NOARGS
, doc_get_endidx
},
599 {"set_completer_delims", set_completer_delims
,
600 METH_VARARGS
, doc_set_completer_delims
},
601 {"add_history", py_add_history
, METH_VARARGS
, doc_add_history
},
602 {"remove_history_item", py_remove_history
, METH_VARARGS
, doc_remove_history
},
603 {"replace_history_item", py_replace_history
, METH_VARARGS
, doc_replace_history
},
604 {"get_completer_delims", get_completer_delims
,
605 METH_NOARGS
, doc_get_completer_delims
},
607 {"set_completion_display_matches_hook", set_completion_display_matches_hook
,
608 METH_VARARGS
, doc_set_completion_display_matches_hook
},
609 {"set_startup_hook", set_startup_hook
,
610 METH_VARARGS
, doc_set_startup_hook
},
611 #ifdef HAVE_RL_PRE_INPUT_HOOK
612 {"set_pre_input_hook", set_pre_input_hook
,
613 METH_VARARGS
, doc_set_pre_input_hook
},
615 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
616 {"clear_history", py_clear_history
, METH_NOARGS
, doc_clear_history
},
622 /* C function to call the Python hooks. */
625 on_hook(PyObject
*func
)
631 PyGILState_STATE gilstate
= PyGILState_Ensure();
633 r
= PyObject_CallFunction(func
, NULL
);
639 result
= PyLong_AsLong(r
);
640 if (result
== -1 && PyErr_Occurred())
650 PyGILState_Release(gilstate
);
658 on_startup_hook(void)
660 return on_hook(startup_hook
);
663 #ifdef HAVE_RL_PRE_INPUT_HOOK
665 on_pre_input_hook(void)
667 return on_hook(pre_input_hook
);
672 /* C function to call the Python completion_display_matches */
675 on_completion_display_matches_hook(char **matches
,
676 int num_matches
, int max_length
)
679 PyObject
*m
=NULL
, *s
=NULL
, *r
=NULL
;
681 PyGILState_STATE gilstate
= PyGILState_Ensure();
683 m
= PyList_New(num_matches
);
686 for (i
= 0; i
< num_matches
; i
++) {
687 s
= PyUnicode_FromString(matches
[i
+1]);
690 if (PyList_SetItem(m
, i
, s
) == -1)
693 r
= PyObject_CallFunction(completion_display_matches_hook
,
694 "sOi", matches
[0], m
, max_length
);
696 Py_DECREF(m
); m
=NULL
;
699 (r
!= Py_None
&& PyLong_AsLong(r
) == -1 && PyErr_Occurred())) {
702 Py_XDECREF(r
); r
=NULL
;
711 PyGILState_Release(gilstate
);
716 /* C function to call the Python completer. */
719 on_completion(const char *text
, int state
)
722 if (completer
!= NULL
) {
725 PyGILState_STATE gilstate
= PyGILState_Ensure();
727 rl_attempted_completion_over
= 1;
728 r
= PyObject_CallFunction(completer
, "si", text
, state
);
735 char *s
= _PyUnicode_AsString(r
);
747 PyGILState_Release(gilstate
);
755 /* A more flexible constructor that saves the "begidx" and "endidx"
756 * before calling the normal completer */
759 flex_complete(char *text
, int start
, int end
)
761 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
762 rl_completion_append_character
='\0';
764 #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
765 rl_completion_suppress_append
= 0;
769 begidx
= PyLong_FromLong((long) start
);
770 endidx
= PyLong_FromLong((long) end
);
771 return completion_matches(text
, *on_completion
);
775 /* Helper to initialize GNU readline properly. */
781 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
783 Py_FatalError("not enough memory to save locale");
788 rl_readline_name
= "python";
789 #if defined(PYOS_OS2) && defined(PYCC_GCC)
790 /* Allow $if term= in .inputrc to work */
791 rl_terminal_name
= getenv("TERM");
793 /* Force rebind of TAB to insert-tab */
794 rl_bind_key('\t', rl_insert
);
795 /* Bind both ESC-TAB and ESC-ESC to the completion function */
796 rl_bind_key_in_map ('\t', rl_complete
, emacs_meta_keymap
);
797 rl_bind_key_in_map ('\033', rl_complete
, emacs_meta_keymap
);
798 /* Set our hook functions */
799 rl_startup_hook
= (Function
*)on_startup_hook
;
800 #ifdef HAVE_RL_PRE_INPUT_HOOK
801 rl_pre_input_hook
= (Function
*)on_pre_input_hook
;
803 /* Set our completion function */
804 rl_attempted_completion_function
= (CPPFunction
*)flex_complete
;
805 /* Set Python word break characters */
806 rl_completer_word_break_characters
=
807 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
808 /* All nonalphanums except '.' */
810 begidx
= PyLong_FromLong(0L);
811 endidx
= PyLong_FromLong(0L);
812 /* Initialize (allows .inputrc to override)
814 * XXX: A bug in the readline-2.2 library causes a memory leak
815 * inside this function. Nothing we can do about it.
819 RESTORE_LOCALE(saved_locale
)
822 /* Wrapper around GNU readline that handles signals differently. */
825 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
827 static char *completed_input_string
;
829 rlhandler(char *text
)
831 completed_input_string
= text
;
832 rl_callback_handler_remove();
835 extern PyThreadState
* _PyOS_ReadlineTState
;
838 readline_until_enter_or_signal(char *prompt
, int *signal
)
840 char * not_done_reading
= "";
844 #ifdef HAVE_RL_CATCH_SIGNAL
845 rl_catch_signals
= 0;
848 rl_callback_handler_install (prompt
, rlhandler
);
851 completed_input_string
= not_done_reading
;
853 while (completed_input_string
== not_done_reading
) {
857 { struct timeval timeout
= {0, 100000}; /* 0.1 seconds */
859 /* [Bug #1552726] Only limit the pause if an input hook has been
861 struct timeval
*timeoutp
= NULL
;
864 FD_SET(fileno(rl_instream
), &selectset
);
865 /* select resets selectset if no input was available */
866 has_input
= select(fileno(rl_instream
) + 1, &selectset
,
867 NULL
, NULL
, timeoutp
);
868 if(PyOS_InputHook
) PyOS_InputHook();
872 rl_callback_read_char();
874 else if (errno
== EINTR
) {
877 PyEval_RestoreThread(_PyOS_ReadlineTState
);
879 s
= PyErr_CheckSignals();
884 rl_free_line_state();
885 rl_cleanup_after_signal();
886 rl_callback_handler_remove();
888 completed_input_string
= NULL
;
893 return completed_input_string
;
899 /* Interrupt handler */
912 readline_until_enter_or_signal(char *prompt
, int *signal
)
914 PyOS_sighandler_t old_inthandler
;
919 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
922 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
925 PyOS_setsig(SIGINT
, old_inthandler
);
929 rl_event_hook
= PyOS_InputHook
;
930 p
= readline(prompt
);
931 PyOS_setsig(SIGINT
, old_inthandler
);
935 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
939 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
946 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
948 Py_FatalError("not enough memory to save locale");
949 setlocale(LC_CTYPE
, "");
952 if (sys_stdin
!= rl_instream
|| sys_stdout
!= rl_outstream
) {
953 rl_instream
= sys_stdin
;
954 rl_outstream
= sys_stdout
;
955 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
956 rl_prep_terminal (1);
960 p
= readline_until_enter_or_signal(prompt
, &signal
);
962 /* we got an interrupt signal */
964 RESTORE_LOCALE(saved_locale
)
968 /* We got an EOF, return a empty string. */
973 RESTORE_LOCALE(saved_locale
)
977 /* we have a valid line */
981 HISTORY_STATE
*state
= history_get_history_state();
982 if (state
->length
> 0)
983 line
= history_get(state
->length
)->line
;
988 /* the history docs don't say so, but the address of state
989 changes each time history_get_history_state is called
990 which makes me think it's freshly malloc'd memory...
991 on the other hand, the address of the last line stays the
992 same as long as history isn't extended, so it appears to
993 be malloc'd but managed by the history package... */
996 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
997 release the original. */
999 p
= PyMem_Malloc(n
+2);
1006 RESTORE_LOCALE(saved_locale
)
1011 /* Initialize the module */
1013 PyDoc_STRVAR(doc_module
,
1014 "Importing this module enables command line editing using GNU readline.");
1017 static struct PyModuleDef readlinemodule
= {
1018 PyModuleDef_HEAD_INIT
,
1030 PyInit_readline(void)
1034 m
= PyModule_Create(&readlinemodule
);
1038 PyOS_ReadlineFunctionPointer
= call_readline
;