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 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 */
49 parse_and_bind(PyObject
*self
, PyObject
*args
)
52 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
54 /* Make a copy -- rl_parse_and_bind() modifies its argument */
56 copy
= malloc(1 + strlen(s
));
58 return PyErr_NoMemory();
60 rl_parse_and_bind(copy
);
61 free(copy
); /* Free the copy */
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 */
73 read_init_file(PyObject
*self
, PyObject
*args
)
76 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
78 errno
= rl_read_init_file(s
);
80 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
93 read_history_file(PyObject
*self
, PyObject
*args
)
96 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
98 errno
= read_history(s
);
100 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
114 write_history_file(PyObject
*self
, PyObject
*args
)
117 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
119 errno
= write_history(s
);
120 if (!errno
&& _history_length
>= 0)
121 history_truncate_file(s
, _history_length
);
123 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
;
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 */
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\
166 /* Generic hook function setter */
169 set_hook(const char *funcname
, PyObject
**hook_var
, PyObject
*args
)
171 PyObject
*function
= Py_None
;
173 PyOS_snprintf(buf
, sizeof(buf
), "|O:set_%.50s", funcname
);
174 if (!PyArg_ParseTuple(args
, buf
, &function
))
176 if (function
== Py_None
) {
177 Py_XDECREF(*hook_var
);
180 else if (PyCallable_Check(function
)) {
181 PyObject
*tmp
= *hook_var
;
183 *hook_var
= function
;
187 PyOS_snprintf(buf
, sizeof(buf
),
188 "set_%.50s(func): argument not callable",
190 PyErr_SetString(PyExc_TypeError
, buf
);
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
;
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;
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.");
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 */
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\
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 */
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 */
285 get_begidx(PyObject
*self
, PyObject
*noarg
)
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 */
299 get_endidx(PyObject
*self
, PyObject
*noarg
)
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 */
313 set_completer_delims(PyObject
*self
, PyObject
*args
)
317 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
320 free((void*)rl_completer_word_break_characters
);
321 rl_completer_word_break_characters
= strdup(break_chars
);
325 PyDoc_STRVAR(doc_set_completer_delims
,
326 "set_completer_delims(string) -> None\n\
327 set the readline word delimiters for tab-completion");
330 py_remove_history(PyObject
*self
, PyObject
*args
)
335 if (!PyArg_ParseTuple(args
, "i:remove_history", &entry_number
))
337 if (entry_number
< 0) {
338 PyErr_SetString(PyExc_ValueError
,
339 "History index cannot be negative");
342 entry
= remove_history(entry_number
);
344 PyErr_Format(PyExc_ValueError
,
345 "No history item at position %d",
349 /* free memory allocated for the history entry */
359 PyDoc_STRVAR(doc_remove_history
,
360 "remove_history_item(pos) -> None\n\
361 remove history item given by its position");
364 py_replace_history(PyObject
*self
, PyObject
*args
)
368 HIST_ENTRY
*old_entry
;
370 if (!PyArg_ParseTuple(args
, "is:replace_history", &entry_number
,
374 if (entry_number
< 0) {
375 PyErr_SetString(PyExc_ValueError
,
376 "History index cannot be negative");
379 old_entry
= replace_history_entry(entry_number
, line
, (void *)NULL
);
381 PyErr_Format(PyExc_ValueError
,
382 "No history item at position %d",
386 /* free memory allocated for the old history entry */
388 free(old_entry
->line
);
390 free(old_entry
->data
);
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 */
403 py_add_history(PyObject
*self
, PyObject
*args
)
407 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
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 */
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 */
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'.");
449 get_completer(PyObject
*self
, PyObject
*noargs
)
451 if (completer
== NULL
) {
454 Py_INCREF(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 */
466 get_history_item(PyObject
*self
, PyObject
*args
)
469 HIST_ENTRY
*hist_ent
;
471 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
473 if ((hist_ent
= history_get(idx
)))
474 return PyUnicode_FromString(hist_ent
->line
);
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 */
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 */
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 */
519 py_clear_history(PyObject
*self
, PyObject
*noarg
)
525 PyDoc_STRVAR(doc_clear_history
,
526 "clear_history() -> None\n\
527 Clear the current readline history.");
531 /* Exported function to insert text into the line buffer */
534 insert_text(PyObject
*self
, PyObject
*args
)
537 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
543 PyDoc_STRVAR(doc_insert_text
,
544 "insert_text(string) -> None\n\
545 Insert text into the command line.");
548 /* Redisplay the line buffer */
551 redisplay(PyObject
*self
, PyObject
*noarg
)
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
},
607 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
608 {"clear_history", py_clear_history
, METH_NOARGS
, doc_clear_history
},
614 /* C function to call the Python hooks. */
617 on_hook(PyObject
*func
)
623 PyGILState_STATE gilstate
= PyGILState_Ensure();
625 r
= PyObject_CallFunction(func
, NULL
);
631 result
= PyLong_AsLong(r
);
632 if (result
== -1 && PyErr_Occurred())
642 PyGILState_Release(gilstate
);
650 on_startup_hook(void)
652 return on_hook(startup_hook
);
655 #ifdef HAVE_RL_PRE_INPUT_HOOK
657 on_pre_input_hook(void)
659 return on_hook(pre_input_hook
);
664 /* C function to call the Python completion_display_matches */
667 on_completion_display_matches_hook(char **matches
,
668 int num_matches
, int max_length
)
671 PyObject
*m
=NULL
, *s
=NULL
, *r
=NULL
;
673 PyGILState_STATE gilstate
= PyGILState_Ensure();
675 m
= PyList_New(num_matches
);
678 for (i
= 0; i
< num_matches
; i
++) {
679 s
= PyUnicode_FromString(matches
[i
+1]);
682 if (PyList_SetItem(m
, i
, s
) == -1)
685 r
= PyObject_CallFunction(completion_display_matches_hook
,
686 "sOi", matches
[0], m
, max_length
);
688 Py_DECREF(m
), m
=NULL
;
691 (r
!= Py_None
&& PyLong_AsLong(r
) == -1 && PyErr_Occurred())) {
694 Py_XDECREF(r
), r
=NULL
;
703 PyGILState_Release(gilstate
);
708 /* C function to call the Python completer. */
711 on_completion(const char *text
, int state
)
714 if (completer
!= NULL
) {
717 PyGILState_STATE gilstate
= PyGILState_Ensure();
719 rl_attempted_completion_over
= 1;
720 r
= PyObject_CallFunction(completer
, "si", text
, state
);
727 char *s
= PyUnicode_AsString(r
);
739 PyGILState_Release(gilstate
);
747 /* A more flexible constructor that saves the "begidx" and "endidx"
748 * before calling the normal completer */
751 flex_complete(char *text
, int start
, int end
)
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. */
767 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
769 Py_FatalError("not enough memory to save locale");
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");
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
;
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';
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.
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
;
818 rlhandler(char *text
)
820 completed_input_string
= text
;
821 rl_callback_handler_remove();
824 extern PyThreadState
* _PyOS_ReadlineTState
;
827 readline_until_enter_or_signal(char *prompt
, int *signal
)
829 char * not_done_reading
= "";
833 #ifdef HAVE_RL_CATCH_SIGNAL
834 rl_catch_signals
= 0;
837 rl_callback_handler_install (prompt
, rlhandler
);
840 completed_input_string
= not_done_reading
;
842 while (completed_input_string
== not_done_reading
) {
846 { struct timeval timeout
= {0, 100000}; /* 0.1 seconds */
848 /* [Bug #1552726] Only limit the pause if an input hook has been
850 struct timeval
*timeoutp
= NULL
;
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();
861 rl_callback_read_char();
863 else if (errno
== EINTR
) {
866 PyEval_RestoreThread(_PyOS_ReadlineTState
);
868 s
= PyErr_CheckSignals();
873 rl_free_line_state();
874 rl_cleanup_after_signal();
875 rl_callback_handler_remove();
877 completed_input_string
= NULL
;
882 return completed_input_string
;
888 /* Interrupt handler */
901 readline_until_enter_or_signal(char *prompt
, int *signal
)
903 PyOS_sighandler_t old_inthandler
;
908 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
911 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
914 PyOS_setsig(SIGINT
, old_inthandler
);
918 rl_event_hook
= PyOS_InputHook
;
919 p
= readline(prompt
);
920 PyOS_setsig(SIGINT
, old_inthandler
);
924 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
928 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
935 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
937 Py_FatalError("not enough memory to save locale");
938 setlocale(LC_CTYPE
, "");
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);
949 p
= readline_until_enter_or_signal(prompt
, &signal
);
951 /* we got an interrupt signal */
953 RESTORE_LOCALE(saved_locale
)
957 /* We got an EOF, return a empty string. */
962 RESTORE_LOCALE(saved_locale
)
966 /* we have a valid line */
970 HISTORY_STATE
*state
= history_get_history_state();
971 if (state
->length
> 0)
972 line
= history_get(state
->length
)->line
;
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... */
985 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
986 release the original. */
988 p
= PyMem_Malloc(n
+2);
995 RESTORE_LOCALE(saved_locale
)
1000 /* Initialize the module */
1002 PyDoc_STRVAR(doc_module
,
1003 "Importing this module enables command line editing using GNU readline.");
1010 m
= Py_InitModule4("readline", readline_methods
, doc_module
,
1011 (PyObject
*)NULL
, PYTHON_API_VERSION
);
1015 PyOS_ReadlineFunctionPointer
= call_readline
;