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.
23 /* GNU readline definitions */
24 #undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
25 #include <readline/readline.h>
26 #include <readline/history.h>
28 #ifdef HAVE_RL_COMPLETION_MATCHES
29 #define completion_matches(x, y) \
30 rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
34 /* Exported function to send one line to readline's init file parser */
37 parse_and_bind(PyObject
*self
, PyObject
*args
)
40 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
42 /* Make a copy -- rl_parse_and_bind() modifies its argument */
44 copy
= malloc(1 + strlen(s
));
46 return PyErr_NoMemory();
48 rl_parse_and_bind(copy
);
49 free(copy
); /* Free the copy */
54 PyDoc_STRVAR(doc_parse_and_bind
,
55 "parse_and_bind(string) -> None\n\
56 Parse and execute single line of a readline init file.");
59 /* Exported function to parse a readline init file */
62 read_init_file(PyObject
*self
, PyObject
*args
)
65 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
67 errno
= rl_read_init_file(s
);
69 return PyErr_SetFromErrno(PyExc_IOError
);
74 PyDoc_STRVAR(doc_read_init_file
,
75 "read_init_file([filename]) -> None\n\
76 Parse a readline initialization file.\n\
77 The default filename is the last filename used.");
80 /* Exported function to load a readline history file */
83 read_history_file(PyObject
*self
, PyObject
*args
)
86 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
88 errno
= read_history(s
);
90 return PyErr_SetFromErrno(PyExc_IOError
);
95 static int _history_length
= -1; /* do not truncate history by default */
96 PyDoc_STRVAR(doc_read_history_file
,
97 "read_history_file([filename]) -> None\n\
98 Load a readline history file.\n\
99 The default filename is ~/.history.");
102 /* Exported function to save a readline history file */
105 write_history_file(PyObject
*self
, PyObject
*args
)
108 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
110 errno
= write_history(s
);
111 if (!errno
&& _history_length
>= 0)
112 history_truncate_file(s
, _history_length
);
114 return PyErr_SetFromErrno(PyExc_IOError
);
119 PyDoc_STRVAR(doc_write_history_file
,
120 "write_history_file([filename]) -> None\n\
121 Save a readline history file.\n\
122 The default filename is ~/.history.");
125 /* Set history length */
128 set_history_length(PyObject
*self
, PyObject
*args
)
130 int length
= _history_length
;
131 if (!PyArg_ParseTuple(args
, "i:set_history_length", &length
))
133 _history_length
= length
;
138 PyDoc_STRVAR(set_history_length_doc
,
139 "set_history_length(length) -> None\n\
140 set the maximal number of items which will be written to\n\
141 the history file. A negative length is used to inhibit\n\
142 history truncation.");
145 /* Get history length */
148 get_history_length(PyObject
*self
, PyObject
*noarg
)
150 return PyInt_FromLong(_history_length
);
153 PyDoc_STRVAR(get_history_length_doc
,
154 "get_history_length() -> int\n\
155 return the maximum number of items that will be written to\n\
159 /* Generic hook function setter */
162 set_hook(const char *funcname
, PyObject
**hook_var
, PyObject
*args
)
164 PyObject
*function
= Py_None
;
166 PyOS_snprintf(buf
, sizeof(buf
), "|O:set_%.50s", funcname
);
167 if (!PyArg_ParseTuple(args
, buf
, &function
))
169 if (function
== Py_None
) {
170 Py_XDECREF(*hook_var
);
173 else if (PyCallable_Check(function
)) {
174 PyObject
*tmp
= *hook_var
;
176 *hook_var
= function
;
180 PyOS_snprintf(buf
, sizeof(buf
),
181 "set_%.50s(func): argument not callable",
183 PyErr_SetString(PyExc_TypeError
, buf
);
191 /* Exported functions to specify hook functions in Python */
193 static PyObject
*startup_hook
= NULL
;
195 #ifdef HAVE_RL_PRE_INPUT_HOOK
196 static PyObject
*pre_input_hook
= NULL
;
200 set_startup_hook(PyObject
*self
, PyObject
*args
)
202 return set_hook("startup_hook", &startup_hook
, args
);
205 PyDoc_STRVAR(doc_set_startup_hook
,
206 "set_startup_hook([function]) -> None\n\
207 Set or remove the startup_hook function.\n\
208 The function is called with no arguments just\n\
209 before readline prints the first prompt.");
212 #ifdef HAVE_RL_PRE_INPUT_HOOK
214 /* Set pre-input hook */
217 set_pre_input_hook(PyObject
*self
, PyObject
*args
)
219 return set_hook("pre_input_hook", &pre_input_hook
, args
);
222 PyDoc_STRVAR(doc_set_pre_input_hook
,
223 "set_pre_input_hook([function]) -> None\n\
224 Set or remove the pre_input_hook function.\n\
225 The function is called with no arguments after the first prompt\n\
226 has been printed and just before readline starts reading input\n\
232 /* Exported function to specify a word completer in Python */
234 static PyObject
*completer
= NULL
;
236 static PyObject
*begidx
= NULL
;
237 static PyObject
*endidx
= NULL
;
240 /* Get the beginning index for the scope of the tab-completion */
243 get_begidx(PyObject
*self
, PyObject
*noarg
)
249 PyDoc_STRVAR(doc_get_begidx
,
250 "get_begidx() -> int\n\
251 get the beginning index of the readline tab-completion scope");
254 /* Get the ending index for the scope of the tab-completion */
257 get_endidx(PyObject
*self
, PyObject
*noarg
)
263 PyDoc_STRVAR(doc_get_endidx
,
264 "get_endidx() -> int\n\
265 get the ending index of the readline tab-completion scope");
268 /* Set the tab-completion word-delimiters that readline uses */
271 set_completer_delims(PyObject
*self
, PyObject
*args
)
275 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
278 free((void*)rl_completer_word_break_characters
);
279 rl_completer_word_break_characters
= strdup(break_chars
);
284 PyDoc_STRVAR(doc_set_completer_delims
,
285 "set_completer_delims(string) -> None\n\
286 set the readline word delimiters for tab-completion");
289 py_remove_history(PyObject
*self
, PyObject
*args
)
294 if (!PyArg_ParseTuple(args
, "i:remove_history", &entry_number
))
296 if (entry_number
< 0) {
297 PyErr_SetString(PyExc_ValueError
,
298 "History index cannot be negative");
301 entry
= remove_history(entry_number
);
303 PyErr_Format(PyExc_ValueError
,
304 "No history item at position %d",
308 /* free memory allocated for the history entry */
319 PyDoc_STRVAR(doc_remove_history
,
320 "remove_history_item(pos) -> None\n\
321 remove history item given by its position");
324 py_replace_history(PyObject
*self
, PyObject
*args
)
328 HIST_ENTRY
*old_entry
;
330 if (!PyArg_ParseTuple(args
, "is:replace_history", &entry_number
, &line
)) {
333 if (entry_number
< 0) {
334 PyErr_SetString(PyExc_ValueError
,
335 "History index cannot be negative");
338 old_entry
= replace_history_entry(entry_number
, line
, (void *)NULL
);
340 PyErr_Format(PyExc_ValueError
,
341 "No history item at position %d",
345 /* free memory allocated for the old history entry */
347 free(old_entry
->line
);
349 free(old_entry
->data
);
356 PyDoc_STRVAR(doc_replace_history
,
357 "replace_history_item(pos, line) -> None\n\
358 replaces history item given by its position with contents of line");
360 /* Add a line to the history buffer */
363 py_add_history(PyObject
*self
, PyObject
*args
)
367 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
375 PyDoc_STRVAR(doc_add_history
,
376 "add_history(string) -> None\n\
377 add a line to the history buffer");
380 /* Get the tab-completion word-delimiters that readline uses */
383 get_completer_delims(PyObject
*self
, PyObject
*noarg
)
385 return PyString_FromString(rl_completer_word_break_characters
);
388 PyDoc_STRVAR(doc_get_completer_delims
,
389 "get_completer_delims() -> string\n\
390 get the readline word delimiters for tab-completion");
393 /* Set the completer function */
396 set_completer(PyObject
*self
, PyObject
*args
)
398 return set_hook("completer", &completer
, args
);
401 PyDoc_STRVAR(doc_set_completer
,
402 "set_completer([function]) -> None\n\
403 Set or remove the completer function.\n\
404 The function is called as function(text, state),\n\
405 for state in 0, 1, 2, ..., until it returns a non-string.\n\
406 It should return the next possible completion starting with 'text'.");
410 get_completer(PyObject
*self
, PyObject
*noargs
)
412 if (completer
== NULL
) {
416 Py_INCREF(completer
);
420 PyDoc_STRVAR(doc_get_completer
,
421 "get_completer() -> function\n\
423 Returns current completer function.");
425 /* Exported function to get any element of history */
428 get_history_item(PyObject
*self
, PyObject
*args
)
431 HIST_ENTRY
*hist_ent
;
433 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
435 if ((hist_ent
= history_get(idx
)))
436 return PyString_FromString(hist_ent
->line
);
443 PyDoc_STRVAR(doc_get_history_item
,
444 "get_history_item() -> string\n\
445 return the current contents of history item at index.");
448 /* Exported function to get current length of history */
451 get_current_history_length(PyObject
*self
, PyObject
*noarg
)
453 HISTORY_STATE
*hist_st
;
455 hist_st
= history_get_history_state();
456 return PyInt_FromLong(hist_st
? (long) hist_st
->length
: (long) 0);
459 PyDoc_STRVAR(doc_get_current_history_length
,
460 "get_current_history_length() -> integer\n\
461 return the current (not the maximum) length of history.");
464 /* Exported function to read the current line buffer */
467 get_line_buffer(PyObject
*self
, PyObject
*noarg
)
469 return PyString_FromString(rl_line_buffer
);
472 PyDoc_STRVAR(doc_get_line_buffer
,
473 "get_line_buffer() -> string\n\
474 return the current contents of the line buffer.");
477 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
479 /* Exported function to clear the current history */
482 py_clear_history(PyObject
*self
, PyObject
*noarg
)
489 PyDoc_STRVAR(doc_clear_history
,
490 "clear_history() -> None\n\
491 Clear the current readline history.");
495 /* Exported function to insert text into the line buffer */
498 insert_text(PyObject
*self
, PyObject
*args
)
501 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
508 PyDoc_STRVAR(doc_insert_text
,
509 "insert_text(string) -> None\n\
510 Insert text into the command line.");
513 /* Redisplay the line buffer */
516 redisplay(PyObject
*self
, PyObject
*noarg
)
523 PyDoc_STRVAR(doc_redisplay
,
524 "redisplay() -> None\n\
525 Change what's displayed on the screen to reflect the current\n\
526 contents of the line buffer.");
529 /* Table of functions exported by the module */
531 static struct PyMethodDef readline_methods
[] =
533 {"parse_and_bind", parse_and_bind
, METH_VARARGS
, doc_parse_and_bind
},
534 {"get_line_buffer", get_line_buffer
, METH_NOARGS
, doc_get_line_buffer
},
535 {"insert_text", insert_text
, METH_VARARGS
, doc_insert_text
},
536 {"redisplay", redisplay
, METH_NOARGS
, doc_redisplay
},
537 {"read_init_file", read_init_file
, METH_VARARGS
, doc_read_init_file
},
538 {"read_history_file", read_history_file
,
539 METH_VARARGS
, doc_read_history_file
},
540 {"write_history_file", write_history_file
,
541 METH_VARARGS
, doc_write_history_file
},
542 {"get_history_item", get_history_item
,
543 METH_VARARGS
, doc_get_history_item
},
544 {"get_current_history_length", (PyCFunction
)get_current_history_length
,
545 METH_NOARGS
, doc_get_current_history_length
},
546 {"set_history_length", set_history_length
,
547 METH_VARARGS
, set_history_length_doc
},
548 {"get_history_length", get_history_length
,
549 METH_NOARGS
, get_history_length_doc
},
550 {"set_completer", set_completer
, METH_VARARGS
, doc_set_completer
},
551 {"get_completer", get_completer
, METH_NOARGS
, doc_get_completer
},
552 {"get_begidx", get_begidx
, METH_NOARGS
, doc_get_begidx
},
553 {"get_endidx", get_endidx
, METH_NOARGS
, doc_get_endidx
},
555 {"set_completer_delims", set_completer_delims
,
556 METH_VARARGS
, doc_set_completer_delims
},
557 {"add_history", py_add_history
, METH_VARARGS
, doc_add_history
},
558 {"remove_history_item", py_remove_history
, METH_VARARGS
, doc_remove_history
},
559 {"replace_history_item", py_replace_history
, METH_VARARGS
, doc_replace_history
},
560 {"get_completer_delims", get_completer_delims
,
561 METH_NOARGS
, doc_get_completer_delims
},
563 {"set_startup_hook", set_startup_hook
,
564 METH_VARARGS
, doc_set_startup_hook
},
565 #ifdef HAVE_RL_PRE_INPUT_HOOK
566 {"set_pre_input_hook", set_pre_input_hook
,
567 METH_VARARGS
, doc_set_pre_input_hook
},
569 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
570 {"clear_history", py_clear_history
, METH_NOARGS
, doc_clear_history
},
576 /* C function to call the Python hooks. */
579 on_hook(PyObject
*func
)
585 PyGILState_STATE gilstate
= PyGILState_Ensure();
587 r
= PyObject_CallFunction(func
, NULL
);
593 result
= PyInt_AsLong(r
);
594 if (result
== -1 && PyErr_Occurred())
604 PyGILState_Release(gilstate
);
612 on_startup_hook(void)
614 return on_hook(startup_hook
);
617 #ifdef HAVE_RL_PRE_INPUT_HOOK
619 on_pre_input_hook(void)
621 return on_hook(pre_input_hook
);
626 /* C function to call the Python completer. */
629 on_completion(char *text
, int state
)
632 if (completer
!= NULL
) {
635 PyGILState_STATE gilstate
= PyGILState_Ensure();
637 rl_attempted_completion_over
= 1;
638 r
= PyObject_CallFunction(completer
, "si", text
, state
);
645 char *s
= PyString_AsString(r
);
657 PyGILState_Release(gilstate
);
665 /* A more flexible constructor that saves the "begidx" and "endidx"
666 * before calling the normal completer */
669 flex_complete(char *text
, int start
, int end
)
673 begidx
= PyInt_FromLong((long) start
);
674 endidx
= PyInt_FromLong((long) end
);
675 return completion_matches(text
, *on_completion
);
679 /* Helper to initialize GNU readline properly. */
685 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
687 Py_FatalError("not enough memory to save locale");
692 rl_readline_name
= "python";
693 #if defined(PYOS_OS2) && defined(PYCC_GCC)
694 /* Allow $if term= in .inputrc to work */
695 rl_terminal_name
= getenv("TERM");
697 /* Force rebind of TAB to insert-tab */
698 rl_bind_key('\t', rl_insert
);
699 /* Bind both ESC-TAB and ESC-ESC to the completion function */
700 rl_bind_key_in_map ('\t', rl_complete
, emacs_meta_keymap
);
701 rl_bind_key_in_map ('\033', rl_complete
, emacs_meta_keymap
);
702 /* Set our hook functions */
703 rl_startup_hook
= (Function
*)on_startup_hook
;
704 #ifdef HAVE_RL_PRE_INPUT_HOOK
705 rl_pre_input_hook
= (Function
*)on_pre_input_hook
;
707 /* Set our completion function */
708 rl_attempted_completion_function
= (CPPFunction
*)flex_complete
;
709 /* Set Python word break characters */
710 rl_completer_word_break_characters
=
711 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
712 /* All nonalphanums except '.' */
713 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
714 rl_completion_append_character
='\0';
717 begidx
= PyInt_FromLong(0L);
718 endidx
= PyInt_FromLong(0L);
719 /* Initialize (allows .inputrc to override)
721 * XXX: A bug in the readline-2.2 library causes a memory leak
722 * inside this function. Nothing we can do about it.
727 setlocale(LC_CTYPE
, saved_locale
); /* Restore locale */
732 /* Wrapper around GNU readline that handles signals differently. */
735 #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
737 static char *completed_input_string
;
739 rlhandler(char *text
)
741 completed_input_string
= text
;
742 rl_callback_handler_remove();
745 extern PyThreadState
* _PyOS_ReadlineTState
;
748 readline_until_enter_or_signal(char *prompt
, int *signal
)
750 char * not_done_reading
= "";
754 #ifdef HAVE_RL_CATCH_SIGNAL
755 rl_catch_signals
= 0;
758 rl_callback_handler_install (prompt
, rlhandler
);
761 completed_input_string
= not_done_reading
;
763 while (completed_input_string
== not_done_reading
) {
767 { struct timeval timeout
= {0, 100000}; /* 0.1 seconds */
768 FD_SET(fileno(rl_instream
), &selectset
);
769 /* select resets selectset if no input was available */
770 has_input
= select(fileno(rl_instream
) + 1, &selectset
,
771 NULL
, NULL
, &timeout
);
772 if(PyOS_InputHook
) PyOS_InputHook();
776 rl_callback_read_char();
778 else if (errno
== EINTR
) {
781 PyEval_RestoreThread(_PyOS_ReadlineTState
);
783 s
= PyErr_CheckSignals();
788 rl_free_line_state();
789 rl_cleanup_after_signal();
790 rl_callback_handler_remove();
792 completed_input_string
= NULL
;
797 return completed_input_string
;
803 /* Interrupt handler */
816 readline_until_enter_or_signal(char *prompt
, int *signal
)
818 PyOS_sighandler_t old_inthandler
;
823 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
826 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
829 PyOS_setsig(SIGINT
, old_inthandler
);
833 rl_event_hook
= PyOS_InputHook
;
834 p
= readline(prompt
);
835 PyOS_setsig(SIGINT
, old_inthandler
);
839 #endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
843 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
850 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
852 Py_FatalError("not enough memory to save locale");
853 setlocale(LC_CTYPE
, "");
856 if (sys_stdin
!= rl_instream
|| sys_stdout
!= rl_outstream
) {
857 rl_instream
= sys_stdin
;
858 rl_outstream
= sys_stdout
;
859 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
860 rl_prep_terminal (1);
864 p
= readline_until_enter_or_signal(prompt
, &signal
);
866 /* we got an interrupt signal */
871 /* We got an EOF, return a empty string. */
879 /* we have a valid line */
883 HISTORY_STATE
*state
= history_get_history_state();
884 if (state
->length
> 0)
885 line
= history_get(state
->length
)->line
;
890 /* the history docs don't say so, but the address of state
891 changes each time history_get_history_state is called
892 which makes me think it's freshly malloc'd memory...
893 on the other hand, the address of the last line stays the
894 same as long as history isn't extended, so it appears to
895 be malloc'd but managed by the history package... */
898 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
899 release the original. */
901 p
= PyMem_Malloc(n
+2);
909 setlocale(LC_CTYPE
, saved_locale
); /* Restore locale */
916 /* Initialize the module */
918 PyDoc_STRVAR(doc_module
,
919 "Importing this module enables command line editing using GNU readline.");
926 m
= Py_InitModule4("readline", readline_methods
, doc_module
,
927 (PyObject
*)NULL
, PYTHON_API_VERSION
);
929 PyOS_ReadlineFunctionPointer
= call_readline
;