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.
5 * More recently, it was largely rewritten by Guido van Rossum who is
9 /* Standard definitions */
15 #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
16 /* GNU readline() mistakenly sets the LC_CTYPE locale.
17 * This is evil. Only the user or the app's main() should do this!
18 * We must save and restore the locale around the rl_initialize() call.
24 /* GNU readline definitions */
25 #undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
26 #include <readline/readline.h>
27 #include <readline/history.h>
29 #ifdef HAVE_RL_COMPLETION_MATCHES
30 #define completion_matches(x, y) \
31 rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
35 /* Exported function to send one line to readline's init file parser */
38 parse_and_bind(PyObject
*self
, PyObject
*args
)
41 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
43 /* Make a copy -- rl_parse_and_bind() modifies its argument */
45 copy
= malloc(1 + strlen(s
));
47 return PyErr_NoMemory();
49 rl_parse_and_bind(copy
);
50 free(copy
); /* Free the copy */
55 PyDoc_STRVAR(doc_parse_and_bind
,
56 "parse_and_bind(string) -> None\n\
57 Parse and execute single line of a readline init file.");
60 /* Exported function to parse a readline init file */
63 read_init_file(PyObject
*self
, PyObject
*args
)
66 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
68 errno
= rl_read_init_file(s
);
70 return PyErr_SetFromErrno(PyExc_IOError
);
75 PyDoc_STRVAR(doc_read_init_file
,
76 "read_init_file([filename]) -> None\n\
77 Parse a readline initialization file.\n\
78 The default filename is the last filename used.");
81 /* Exported function to load a readline history file */
84 read_history_file(PyObject
*self
, PyObject
*args
)
87 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
89 errno
= read_history(s
);
91 return PyErr_SetFromErrno(PyExc_IOError
);
96 static int history_length
= -1; /* do not truncate history by default */
97 PyDoc_STRVAR(doc_read_history_file
,
98 "read_history_file([filename]) -> None\n\
99 Load a readline history file.\n\
100 The default filename is ~/.history.");
103 /* Exported function to save a readline history file */
106 write_history_file(PyObject
*self
, PyObject
*args
)
109 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
111 errno
= write_history(s
);
112 if (!errno
&& history_length
>= 0)
113 history_truncate_file(s
, history_length
);
115 return PyErr_SetFromErrno(PyExc_IOError
);
120 PyDoc_STRVAR(doc_write_history_file
,
121 "write_history_file([filename]) -> None\n\
122 Save a readline history file.\n\
123 The default filename is ~/.history.");
126 /* Set history length */
129 set_history_length(PyObject
*self
, PyObject
*args
)
131 int length
= history_length
;
132 if (!PyArg_ParseTuple(args
, "i:set_history_length", &length
))
134 history_length
= length
;
139 PyDoc_STRVAR(set_history_length_doc
,
140 "set_history_length(length) -> None\n\
141 set the maximal number of items which will be written to\n\
142 the history file. A negative length is used to inhibit\n\
143 history truncation.");
146 /* Get history length */
149 get_history_length(PyObject
*self
, PyObject
*noarg
)
151 return PyInt_FromLong(history_length
);
154 PyDoc_STRVAR(get_history_length_doc
,
155 "get_history_length() -> int\n\
156 return the maximum number of items that will be written to\n\
160 /* Generic hook function setter */
163 set_hook(const char *funcname
, PyObject
**hook_var
,
164 PyThreadState
**tstate
, PyObject
*args
)
166 PyObject
*function
= Py_None
;
168 PyOS_snprintf(buf
, sizeof(buf
), "|O:set_%.50s", funcname
);
169 if (!PyArg_ParseTuple(args
, buf
, &function
))
171 if (function
== Py_None
) {
172 Py_XDECREF(*hook_var
);
176 else if (PyCallable_Check(function
)) {
177 PyObject
*tmp
= *hook_var
;
179 *hook_var
= function
;
181 *tstate
= PyThreadState_Get();
184 PyOS_snprintf(buf
, sizeof(buf
),
185 "set_%.50s(func): argument not callable",
187 PyErr_SetString(PyExc_TypeError
, buf
);
195 /* Exported functions to specify hook functions in Python */
197 static PyObject
*startup_hook
= NULL
;
198 static PyThreadState
*startup_hook_tstate
= NULL
;
200 #ifdef HAVE_RL_PRE_INPUT_HOOK
201 static PyObject
*pre_input_hook
= NULL
;
202 static PyThreadState
*pre_input_hook_tstate
= NULL
;
206 set_startup_hook(PyObject
*self
, PyObject
*args
)
208 return set_hook("startup_hook", &startup_hook
,
209 &startup_hook_tstate
, args
);
212 PyDoc_STRVAR(doc_set_startup_hook
,
213 "set_startup_hook([function]) -> None\n\
214 Set or remove the startup_hook function.\n\
215 The function is called with no arguments just\n\
216 before readline prints the first prompt.");
219 #ifdef HAVE_RL_PRE_INPUT_HOOK
221 /* Set pre-input hook */
224 set_pre_input_hook(PyObject
*self
, PyObject
*args
)
226 return set_hook("pre_input_hook", &pre_input_hook
,
227 &pre_input_hook_tstate
, 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
;
243 static PyThreadState
*completer_tstate
= NULL
;
245 static PyObject
*begidx
= NULL
;
246 static PyObject
*endidx
= NULL
;
249 /* Get the beginning index for the scope of the tab-completion */
252 get_begidx(PyObject
*self
, PyObject
*noarg
)
258 PyDoc_STRVAR(doc_get_begidx
,
259 "get_begidx() -> int\n\
260 get the beginning index of the readline tab-completion scope");
263 /* Get the ending index for the scope of the tab-completion */
266 get_endidx(PyObject
*self
, PyObject
*noarg
)
272 PyDoc_STRVAR(doc_get_endidx
,
273 "get_endidx() -> int\n\
274 get the ending index of the readline tab-completion scope");
277 /* Set the tab-completion word-delimiters that readline uses */
280 set_completer_delims(PyObject
*self
, PyObject
*args
)
284 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
287 free((void*)rl_completer_word_break_characters
);
288 rl_completer_word_break_characters
= strdup(break_chars
);
293 PyDoc_STRVAR(doc_set_completer_delims
,
294 "set_completer_delims(string) -> None\n\
295 set the readline word delimiters for tab-completion");
298 /* Add a line to the history buffer */
301 py_add_history(PyObject
*self
, PyObject
*args
)
305 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
313 PyDoc_STRVAR(doc_add_history
,
314 "add_history(string) -> None\n\
315 add a line to the history buffer");
318 /* Get the tab-completion word-delimiters that readline uses */
321 get_completer_delims(PyObject
*self
, PyObject
*noarg
)
323 return PyString_FromString(rl_completer_word_break_characters
);
326 PyDoc_STRVAR(doc_get_completer_delims
,
327 "get_completer_delims() -> string\n\
328 get the readline word delimiters for tab-completion");
331 /* Set the completer function */
334 set_completer(PyObject
*self
, PyObject
*args
)
336 return set_hook("completer", &completer
, &completer_tstate
, args
);
339 PyDoc_STRVAR(doc_set_completer
,
340 "set_completer([function]) -> None\n\
341 Set or remove the completer function.\n\
342 The function is called as function(text, state),\n\
343 for state in 0, 1, 2, ..., until it returns a non-string.\n\
344 It should return the next possible completion starting with 'text'.");
348 get_completer(PyObject
*self
, PyObject
*noargs
)
350 if (completer
== NULL
) {
354 Py_INCREF(completer
);
358 PyDoc_STRVAR(doc_get_completer
,
359 "get_completer() -> function\n\
361 Returns current completer function.");
363 /* Exported function to get any element of history */
366 get_history_item(PyObject
*self
, PyObject
*args
)
369 HIST_ENTRY
*hist_ent
;
371 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
373 if ((hist_ent
= history_get(idx
)))
374 return PyString_FromString(hist_ent
->line
);
381 PyDoc_STRVAR(doc_get_history_item
,
382 "get_history_item() -> string\n\
383 return the current contents of history item at index.");
386 /* Exported function to get current length of history */
389 get_current_history_length(PyObject
*self
, PyObject
*noarg
)
391 HISTORY_STATE
*hist_st
;
393 hist_st
= history_get_history_state();
394 return PyInt_FromLong(hist_st
? (long) hist_st
->length
: (long) 0);
397 PyDoc_STRVAR(doc_get_current_history_length
,
398 "get_current_history_length() -> integer\n\
399 return the current (not the maximum) length of history.");
402 /* Exported function to read the current line buffer */
405 get_line_buffer(PyObject
*self
, PyObject
*noarg
)
407 return PyString_FromString(rl_line_buffer
);
410 PyDoc_STRVAR(doc_get_line_buffer
,
411 "get_line_buffer() -> string\n\
412 return the current contents of the line buffer.");
415 /* Exported function to insert text into the line buffer */
418 insert_text(PyObject
*self
, PyObject
*args
)
421 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
428 PyDoc_STRVAR(doc_insert_text
,
429 "insert_text(string) -> None\n\
430 Insert text into the command line.");
433 /* Redisplay the line buffer */
436 redisplay(PyObject
*self
, PyObject
*noarg
)
443 PyDoc_STRVAR(doc_redisplay
,
444 "redisplay() -> None\n\
445 Change what's displayed on the screen to reflect the current\n\
446 contents of the line buffer.");
449 /* Table of functions exported by the module */
451 static struct PyMethodDef readline_methods
[] =
453 {"parse_and_bind", parse_and_bind
, METH_VARARGS
, doc_parse_and_bind
},
454 {"get_line_buffer", get_line_buffer
, METH_NOARGS
, doc_get_line_buffer
},
455 {"insert_text", insert_text
, METH_VARARGS
, doc_insert_text
},
456 {"redisplay", redisplay
, METH_NOARGS
, doc_redisplay
},
457 {"read_init_file", read_init_file
, METH_VARARGS
, doc_read_init_file
},
458 {"read_history_file", read_history_file
,
459 METH_VARARGS
, doc_read_history_file
},
460 {"write_history_file", write_history_file
,
461 METH_VARARGS
, doc_write_history_file
},
462 {"get_history_item", get_history_item
,
463 METH_VARARGS
, doc_get_history_item
},
464 {"get_current_history_length", (PyCFunction
)get_current_history_length
,
465 METH_NOARGS
, doc_get_current_history_length
},
466 {"set_history_length", set_history_length
,
467 METH_VARARGS
, set_history_length_doc
},
468 {"get_history_length", get_history_length
,
469 METH_NOARGS
, get_history_length_doc
},
470 {"set_completer", set_completer
, METH_VARARGS
, doc_set_completer
},
471 {"get_completer", get_completer
, METH_NOARGS
, doc_get_completer
},
472 {"get_begidx", get_begidx
, METH_NOARGS
, doc_get_begidx
},
473 {"get_endidx", get_endidx
, METH_NOARGS
, doc_get_endidx
},
475 {"set_completer_delims", set_completer_delims
,
476 METH_VARARGS
, doc_set_completer_delims
},
477 {"add_history", py_add_history
, METH_VARARGS
, doc_add_history
},
478 {"get_completer_delims", get_completer_delims
,
479 METH_NOARGS
, doc_get_completer_delims
},
481 {"set_startup_hook", set_startup_hook
,
482 METH_VARARGS
, doc_set_startup_hook
},
483 #ifdef HAVE_RL_PRE_INPUT_HOOK
484 {"set_pre_input_hook", set_pre_input_hook
,
485 METH_VARARGS
, doc_set_pre_input_hook
},
491 /* C function to call the Python hooks. */
494 on_hook(PyObject
*func
, PyThreadState
**tstate
)
499 /* Note that readline is called with the interpreter
501 PyEval_RestoreThread(*tstate
);
502 r
= PyObject_CallFunction(func
, NULL
);
508 result
= PyInt_AsLong(r
);
515 *tstate
= PyEval_SaveThread();
521 on_startup_hook(void)
523 return on_hook(startup_hook
, &startup_hook_tstate
);
526 #ifdef HAVE_RL_PRE_INPUT_HOOK
528 on_pre_input_hook(void)
530 return on_hook(pre_input_hook
, &pre_input_hook_tstate
);
535 /* C function to call the Python completer. */
538 on_completion(char *text
, int state
)
541 if (completer
!= NULL
) {
543 /* Note that readline is called with the interpreter
545 PyEval_RestoreThread(completer_tstate
);
546 /* Don't use the default filename completion if we
547 * have a custom completion function... */
548 rl_attempted_completion_over
= 1;
549 r
= PyObject_CallFunction(completer
, "si", text
, state
);
556 char *s
= PyString_AsString(r
);
567 completer_tstate
= PyEval_SaveThread();
573 /* A more flexible constructor that saves the "begidx" and "endidx"
574 * before calling the normal completer */
577 flex_complete(char *text
, int start
, int end
)
581 begidx
= PyInt_FromLong((long) start
);
582 endidx
= PyInt_FromLong((long) end
);
583 return completion_matches(text
, *on_completion
);
587 /* Helper to initialize GNU readline properly. */
593 char *saved_locale
= strdup(setlocale(LC_CTYPE
, NULL
));
598 rl_readline_name
= "python";
599 #if defined(PYOS_OS2) && defined(PYCC_GCC)
600 /* Allow $if term= in .inputrc to work */
601 rl_terminal_name
= getenv("TERM");
603 /* Force rebind of TAB to insert-tab */
604 rl_bind_key('\t', rl_insert
);
605 /* Bind both ESC-TAB and ESC-ESC to the completion function */
606 rl_bind_key_in_map ('\t', rl_complete
, emacs_meta_keymap
);
607 rl_bind_key_in_map ('\033', rl_complete
, emacs_meta_keymap
);
608 /* Set our hook functions */
609 rl_startup_hook
= (Function
*)on_startup_hook
;
610 #ifdef HAVE_RL_PRE_INPUT_HOOK
611 rl_pre_input_hook
= (Function
*)on_pre_input_hook
;
613 /* Set our completion function */
614 rl_attempted_completion_function
= (CPPFunction
*)flex_complete
;
615 /* Set Python word break characters */
616 rl_completer_word_break_characters
=
617 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
618 /* All nonalphanums except '.' */
619 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
620 rl_completion_append_character
='\0';
623 begidx
= PyInt_FromLong(0L);
624 endidx
= PyInt_FromLong(0L);
625 /* Initialize (allows .inputrc to override)
627 * XXX: A bug in the readline-2.2 library causes a memory leak
628 * inside this function. Nothing we can do about it.
633 setlocale(LC_CTYPE
, saved_locale
); /* Restore locale */
639 /* Interrupt handler */
651 /* Wrapper around GNU readline that handles signals differently. */
654 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
658 PyOS_sighandler_t old_inthandler
;
660 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
663 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
666 PyOS_setsig(SIGINT
, old_inthandler
);
669 rl_event_hook
= PyOS_InputHook
;
671 if (sys_stdin
!= rl_instream
|| sys_stdout
!= rl_outstream
) {
672 rl_instream
= sys_stdin
;
673 rl_outstream
= sys_stdout
;
674 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
675 rl_prep_terminal (1);
679 p
= readline(prompt
);
680 PyOS_setsig(SIGINT
, old_inthandler
);
682 /* We must return a buffer allocated with PyMem_Malloc. */
692 HISTORY_STATE
*state
= history_get_history_state();
693 if (state
->length
> 0)
694 line
= history_get(state
->length
)->line
;
699 /* the history docs don't say so, but the address of state
700 changes each time history_get_history_state is called
701 which makes me think it's freshly malloc'd memory...
702 on the other hand, the address of the last line stays the
703 same as long as history isn't extended, so it appears to
704 be malloc'd but managed by the history package... */
707 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
708 release the original. */
710 p
= PyMem_Malloc(n
+2);
721 /* Initialize the module */
723 PyDoc_STRVAR(doc_module
,
724 "Importing this module enables command line editing using GNU readline.");
731 m
= Py_InitModule4("readline", readline_methods
, doc_module
,
732 (PyObject
*)NULL
, PYTHON_API_VERSION
);
734 PyOS_ReadlineFunctionPointer
= call_readline
;