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)))
40 /* Exported function to send one line to readline's init file parser */
43 parse_and_bind(PyObject
*self
, PyObject
*args
)
46 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
48 /* Make a copy -- rl_parse_and_bind() modifies its argument */
50 copy
= malloc(1 + strlen(s
));
52 return PyErr_NoMemory();
54 rl_parse_and_bind(copy
);
55 free(copy
); /* Free the copy */
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 */
68 read_init_file(PyObject
*self
, PyObject
*args
)
71 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
73 errno
= rl_read_init_file(s
);
75 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
89 read_history_file(PyObject
*self
, PyObject
*args
)
92 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
94 errno
= read_history(s
);
96 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
111 write_history_file(PyObject
*self
, PyObject
*args
)
114 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
116 errno
= write_history(s
);
117 if (!errno
&& _history_length
>= 0)
118 history_truncate_file(s
, _history_length
);
120 return PyErr_SetFromErrno(PyExc_IOError
);
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 */
134 set_history_length(PyObject
*self
, PyObject
*args
)
136 int length
= _history_length
;
137 if (!PyArg_ParseTuple(args
, "i:set_history_length", &length
))
139 _history_length
= length
;
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 */
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\
165 /* Generic hook function setter */
168 set_hook(const char *funcname
, PyObject
**hook_var
, PyObject
*args
)
170 PyObject
*function
= Py_None
;
172 PyOS_snprintf(buf
, sizeof(buf
), "|O:set_%.50s", funcname
);
173 if (!PyArg_ParseTuple(args
, buf
, &function
))
175 if (function
== Py_None
) {
176 Py_XDECREF(*hook_var
);
179 else if (PyCallable_Check(function
)) {
180 PyObject
*tmp
= *hook_var
;
182 *hook_var
= function
;
186 PyOS_snprintf(buf
, sizeof(buf
),
187 "set_%.50s(func): argument not callable",
189 PyErr_SetString(PyExc_TypeError
, buf
);
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
;
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 */
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\
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 */
249 get_begidx(PyObject
*self
, PyObject
*noarg
)
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 */
263 get_endidx(PyObject
*self
, PyObject
*noarg
)
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 */
277 set_completer_delims(PyObject
*self
, PyObject
*args
)
281 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
284 free((void*)rl_completer_word_break_characters
);
285 rl_completer_word_break_characters
= strdup(break_chars
);
290 PyDoc_STRVAR(doc_set_completer_delims
,
291 "set_completer_delims(string) -> None\n\
292 set the readline word delimiters for tab-completion");
295 py_remove_history(PyObject
*self
, PyObject
*args
)
300 if (!PyArg_ParseTuple(args
, "i:remove_history", &entry_number
))
302 if (entry_number
< 0) {
303 PyErr_SetString(PyExc_ValueError
,
304 "History index cannot be negative");
307 entry
= remove_history(entry_number
);
309 PyErr_Format(PyExc_ValueError
,
310 "No history item at position %d",
314 /* free memory allocated for the history entry */
325 PyDoc_STRVAR(doc_remove_history
,
326 "remove_history_item(pos) -> None\n\
327 remove history item given by its position");
330 py_replace_history(PyObject
*self
, PyObject
*args
)
334 HIST_ENTRY
*old_entry
;
336 if (!PyArg_ParseTuple(args
, "is:replace_history", &entry_number
, &line
)) {
339 if (entry_number
< 0) {
340 PyErr_SetString(PyExc_ValueError
,
341 "History index cannot be negative");
344 old_entry
= replace_history_entry(entry_number
, line
, (void *)NULL
);
346 PyErr_Format(PyExc_ValueError
,
347 "No history item at position %d",
351 /* free memory allocated for the old history entry */
353 free(old_entry
->line
);
355 free(old_entry
->data
);
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 */
369 py_add_history(PyObject
*self
, PyObject
*args
)
373 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
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 */
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 */
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'.");
416 get_completer(PyObject
*self
, PyObject
*noargs
)
418 if (completer
== NULL
) {
422 Py_INCREF(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 */
434 get_history_item(PyObject
*self
, PyObject
*args
)
437 HIST_ENTRY
*hist_ent
;
439 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
441 if ((hist_ent
= history_get(idx
)))
442 return PyString_FromString(hist_ent
->line
);
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 */
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 */
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 */
488 py_clear_history(PyObject
*self
, PyObject
*noarg
)
495 PyDoc_STRVAR(doc_clear_history
,
496 "clear_history() -> None\n\
497 Clear the current readline history.");
501 /* Exported function to insert text into the line buffer */
504 insert_text(PyObject
*self
, PyObject
*args
)
507 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
514 PyDoc_STRVAR(doc_insert_text
,
515 "insert_text(string) -> None\n\
516 Insert text into the command line.");
519 /* Redisplay the line buffer */
522 redisplay(PyObject
*self
, PyObject
*noarg
)
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
},
575 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
576 {"clear_history", py_clear_history
, METH_NOARGS
, doc_clear_history
},
582 /* C function to call the Python hooks. */
585 on_hook(PyObject
*func
)
591 PyGILState_STATE gilstate
= PyGILState_Ensure();
593 r
= PyObject_CallFunction(func
, NULL
);
599 result
= PyInt_AsLong(r
);
600 if (result
== -1 && PyErr_Occurred())
610 PyGILState_Release(gilstate
);
618 on_startup_hook(void)
620 return on_hook(startup_hook
);
623 #ifdef HAVE_RL_PRE_INPUT_HOOK
625 on_pre_input_hook(void)
627 return on_hook(pre_input_hook
);
632 /* C function to call the Python completer. */
635 on_completion(char *text
, int state
)
638 if (completer
!= NULL
) {
641 PyGILState_STATE gilstate
= PyGILState_Ensure();
643 rl_attempted_completion_over
= 1;
644 r
= PyObject_CallFunction(completer
, "si", text
, state
);
651 char *s
= PyString_AsString(r
);
663 PyGILState_Release(gilstate
);
671 /* A more flexible constructor that saves the "begidx" and "endidx"
672 * before calling the normal completer */
675 flex_complete(char *text
, int start
, int end
)
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. */
691 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
693 Py_FatalError("not enough memory to save locale");
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");
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
;
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';
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.
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
;
742 rlhandler(char *text
)
744 completed_input_string
= text
;
745 rl_callback_handler_remove();
748 extern PyThreadState
* _PyOS_ReadlineTState
;
751 readline_until_enter_or_signal(char *prompt
, int *signal
)
753 char * not_done_reading
= "";
757 #ifdef HAVE_RL_CATCH_SIGNAL
758 rl_catch_signals
= 0;
761 rl_callback_handler_install (prompt
, rlhandler
);
764 completed_input_string
= not_done_reading
;
766 while (completed_input_string
== not_done_reading
) {
770 { struct timeval timeout
= {0, 100000}; /* 0.1 seconds */
772 /* [Bug #1552726] Only limit the pause if an input hook has been
774 struct timeval
*timeoutp
= NULL
;
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();
785 rl_callback_read_char();
787 else if (errno
== EINTR
) {
790 PyEval_RestoreThread(_PyOS_ReadlineTState
);
792 s
= PyErr_CheckSignals();
797 rl_free_line_state();
798 rl_cleanup_after_signal();
799 rl_callback_handler_remove();
801 completed_input_string
= NULL
;
806 return completed_input_string
;
812 /* Interrupt handler */
825 readline_until_enter_or_signal(char *prompt
, int *signal
)
827 PyOS_sighandler_t old_inthandler
;
832 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
835 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
838 PyOS_setsig(SIGINT
, old_inthandler
);
842 rl_event_hook
= PyOS_InputHook
;
843 p
= readline(prompt
);
844 PyOS_setsig(SIGINT
, old_inthandler
);
848 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
852 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
859 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
861 Py_FatalError("not enough memory to save locale");
862 setlocale(LC_CTYPE
, "");
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);
873 p
= readline_until_enter_or_signal(prompt
, &signal
);
875 /* we got an interrupt signal */
877 RESTORE_LOCALE(saved_locale
)
881 /* We got an EOF, return a empty string. */
886 RESTORE_LOCALE(saved_locale
)
890 /* we have a valid line */
894 HISTORY_STATE
*state
= history_get_history_state();
895 if (state
->length
> 0)
896 line
= history_get(state
->length
)->line
;
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... */
909 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
910 release the original. */
912 p
= PyMem_Malloc(n
+2);
919 RESTORE_LOCALE(saved_locale
)
924 /* Initialize the module */
926 PyDoc_STRVAR(doc_module
,
927 "Importing this module enables command line editing using GNU readline.");
934 m
= Py_InitModule4("readline", readline_methods
, doc_module
,
935 (PyObject
*)NULL
, PYTHON_API_VERSION
);
939 PyOS_ReadlineFunctionPointer
= call_readline
;