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)))
34 /* Pointers needed from outside (but not declared in a header file). */
35 extern DL_IMPORT(int) (*PyOS_InputHook
)(void);
36 extern DL_IMPORT(char) *(*PyOS_ReadlineFunctionPointer
)(FILE *, FILE *,char *);
39 /* Exported function to send one line to readline's init file parser */
42 parse_and_bind(PyObject
*self
, PyObject
*args
)
45 if (!PyArg_ParseTuple(args
, "s:parse_and_bind", &s
))
47 /* Make a copy -- rl_parse_and_bind() modifies its argument */
49 copy
= malloc(1 + strlen(s
));
51 return PyErr_NoMemory();
53 rl_parse_and_bind(copy
);
54 free(copy
); /* Free the copy */
59 PyDoc_STRVAR(doc_parse_and_bind
,
60 "parse_and_bind(string) -> None\n\
61 Parse and execute single line of a readline init file.");
64 /* Exported function to parse a readline init file */
67 read_init_file(PyObject
*self
, PyObject
*args
)
70 if (!PyArg_ParseTuple(args
, "|z:read_init_file", &s
))
72 errno
= rl_read_init_file(s
);
74 return PyErr_SetFromErrno(PyExc_IOError
);
79 PyDoc_STRVAR(doc_read_init_file
,
80 "read_init_file([filename]) -> None\n\
81 Parse a readline initialization file.\n\
82 The default filename is the last filename used.");
85 /* Exported function to load a readline history file */
88 read_history_file(PyObject
*self
, PyObject
*args
)
91 if (!PyArg_ParseTuple(args
, "|z:read_history_file", &s
))
93 errno
= read_history(s
);
95 return PyErr_SetFromErrno(PyExc_IOError
);
100 static int history_length
= -1; /* do not truncate history by default */
101 PyDoc_STRVAR(doc_read_history_file
,
102 "read_history_file([filename]) -> None\n\
103 Load a readline history file.\n\
104 The default filename is ~/.history.");
107 /* Exported function to save a readline history file */
110 write_history_file(PyObject
*self
, PyObject
*args
)
113 if (!PyArg_ParseTuple(args
, "|z:write_history_file", &s
))
115 errno
= write_history(s
);
116 if (!errno
&& history_length
>= 0)
117 history_truncate_file(s
, history_length
);
119 return PyErr_SetFromErrno(PyExc_IOError
);
124 PyDoc_STRVAR(doc_write_history_file
,
125 "write_history_file([filename]) -> None\n\
126 Save a readline history file.\n\
127 The default filename is ~/.history.");
130 /* Set history length */
133 set_history_length(PyObject
*self
, PyObject
*args
)
135 int length
= history_length
;
136 if (!PyArg_ParseTuple(args
, "i:set_history_length", &length
))
138 history_length
= length
;
143 PyDoc_STRVAR(set_history_length_doc
,
144 "set_history_length(length) -> None\n\
145 set the maximal number of items which will be written to\n\
146 the history file. A negative length is used to inhibit\n\
147 history truncation.");
150 /* Get history length */
153 get_history_length(PyObject
*self
, PyObject
*noarg
)
155 return PyInt_FromLong(history_length
);
158 PyDoc_STRVAR(get_history_length_doc
,
159 "get_history_length() -> int\n\
160 return the maximum number of items that will be written to\n\
164 /* Generic hook function setter */
167 set_hook(const char *funcname
, PyObject
**hook_var
,
168 PyThreadState
**tstate
, 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
);
180 else if (PyCallable_Check(function
)) {
181 PyObject
*tmp
= *hook_var
;
183 *hook_var
= function
;
185 *tstate
= PyThreadState_Get();
188 PyOS_snprintf(buf
, sizeof(buf
),
189 "set_%.50s(func): argument not callable",
191 PyErr_SetString(PyExc_TypeError
, buf
);
199 /* Exported functions to specify hook functions in Python */
201 static PyObject
*startup_hook
= NULL
;
202 static PyThreadState
*startup_hook_tstate
= NULL
;
204 #ifdef HAVE_RL_PRE_INPUT_HOOK
205 static PyObject
*pre_input_hook
= NULL
;
206 static PyThreadState
*pre_input_hook_tstate
= NULL
;
210 set_startup_hook(PyObject
*self
, PyObject
*args
)
212 return set_hook("startup_hook", &startup_hook
,
213 &startup_hook_tstate
, args
);
216 PyDoc_STRVAR(doc_set_startup_hook
,
217 "set_startup_hook([function]) -> None\n\
218 Set or remove the startup_hook function.\n\
219 The function is called with no arguments just\n\
220 before readline prints the first prompt.");
223 #ifdef HAVE_RL_PRE_INPUT_HOOK
225 /* Set pre-input hook */
228 set_pre_input_hook(PyObject
*self
, PyObject
*args
)
230 return set_hook("pre_input_hook", &pre_input_hook
,
231 &pre_input_hook_tstate
, args
);
234 PyDoc_STRVAR(doc_set_pre_input_hook
,
235 "set_pre_input_hook([function]) -> None\n\
236 Set or remove the pre_input_hook function.\n\
237 The function is called with no arguments after the first prompt\n\
238 has been printed and just before readline starts reading input\n\
244 /* Exported function to specify a word completer in Python */
246 static PyObject
*completer
= NULL
;
247 static PyThreadState
*completer_tstate
= NULL
;
249 static PyObject
*begidx
= NULL
;
250 static PyObject
*endidx
= NULL
;
253 /* Get the beginning index for the scope of the tab-completion */
256 get_begidx(PyObject
*self
, PyObject
*noarg
)
262 PyDoc_STRVAR(doc_get_begidx
,
263 "get_begidx() -> int\n\
264 get the beginning index of the readline tab-completion scope");
267 /* Get the ending index for the scope of the tab-completion */
270 get_endidx(PyObject
*self
, PyObject
*noarg
)
276 PyDoc_STRVAR(doc_get_endidx
,
277 "get_endidx() -> int\n\
278 get the ending index of the readline tab-completion scope");
281 /* Set the tab-completion word-delimiters that readline uses */
284 set_completer_delims(PyObject
*self
, PyObject
*args
)
288 if(!PyArg_ParseTuple(args
, "s:set_completer_delims", &break_chars
)) {
291 free((void*)rl_completer_word_break_characters
);
292 rl_completer_word_break_characters
= strdup(break_chars
);
297 PyDoc_STRVAR(doc_set_completer_delims
,
298 "set_completer_delims(string) -> None\n\
299 set the readline word delimiters for tab-completion");
302 /* Add a line to the history buffer */
305 py_add_history(PyObject
*self
, PyObject
*args
)
309 if(!PyArg_ParseTuple(args
, "s:add_history", &line
)) {
317 PyDoc_STRVAR(doc_add_history
,
318 "add_history(string) -> None\n\
319 add a line to the history buffer");
322 /* Get the tab-completion word-delimiters that readline uses */
325 get_completer_delims(PyObject
*self
, PyObject
*noarg
)
327 return PyString_FromString(rl_completer_word_break_characters
);
330 PyDoc_STRVAR(doc_get_completer_delims
,
331 "get_completer_delims() -> string\n\
332 get the readline word delimiters for tab-completion");
335 /* Set the completer function */
338 set_completer(PyObject
*self
, PyObject
*args
)
340 return set_hook("completer", &completer
, &completer_tstate
, args
);
343 PyDoc_STRVAR(doc_set_completer
,
344 "set_completer([function]) -> None\n\
345 Set or remove the completer function.\n\
346 The function is called as function(text, state),\n\
347 for state in 0, 1, 2, ..., until it returns a non-string.\n\
348 It should return the next possible completion starting with 'text'.");
352 get_completer(PyObject
*self
, PyObject
*noargs
)
354 if (completer
== NULL
) {
358 Py_INCREF(completer
);
362 PyDoc_STRVAR(doc_get_completer
,
363 "get_completer() -> function\n\
365 Returns current completer function.");
367 /* Exported function to get any element of history */
370 get_history_item(PyObject
*self
, PyObject
*args
)
373 HIST_ENTRY
*hist_ent
;
375 if (!PyArg_ParseTuple(args
, "i:index", &idx
))
377 if ((hist_ent
= history_get(idx
)))
378 return PyString_FromString(hist_ent
->line
);
385 PyDoc_STRVAR(doc_get_history_item
,
386 "get_history_item() -> string\n\
387 return the current contents of history item at index.");
390 /* Exported function to get current length of history */
393 get_current_history_length(PyObject
*self
, PyObject
*noarg
)
395 HISTORY_STATE
*hist_st
;
397 hist_st
= history_get_history_state();
398 return PyInt_FromLong(hist_st
? (long) hist_st
->length
: (long) 0);
401 PyDoc_STRVAR(doc_get_current_history_length
,
402 "get_current_history_length() -> integer\n\
403 return the current (not the maximum) length of history.");
406 /* Exported function to read the current line buffer */
409 get_line_buffer(PyObject
*self
, PyObject
*noarg
)
411 return PyString_FromString(rl_line_buffer
);
414 PyDoc_STRVAR(doc_get_line_buffer
,
415 "get_line_buffer() -> string\n\
416 return the current contents of the line buffer.");
419 /* Exported function to insert text into the line buffer */
422 insert_text(PyObject
*self
, PyObject
*args
)
425 if (!PyArg_ParseTuple(args
, "s:insert_text", &s
))
432 PyDoc_STRVAR(doc_insert_text
,
433 "insert_text(string) -> None\n\
434 Insert text into the command line.");
437 /* Redisplay the line buffer */
440 redisplay(PyObject
*self
, PyObject
*noarg
)
447 PyDoc_STRVAR(doc_redisplay
,
448 "redisplay() -> None\n\
449 Change what's displayed on the screen to reflect the current\n\
450 contents of the line buffer.");
453 /* Table of functions exported by the module */
455 static struct PyMethodDef readline_methods
[] =
457 {"parse_and_bind", parse_and_bind
, METH_VARARGS
, doc_parse_and_bind
},
458 {"get_line_buffer", get_line_buffer
, METH_NOARGS
, doc_get_line_buffer
},
459 {"insert_text", insert_text
, METH_VARARGS
, doc_insert_text
},
460 {"redisplay", redisplay
, METH_NOARGS
, doc_redisplay
},
461 {"read_init_file", read_init_file
, METH_VARARGS
, doc_read_init_file
},
462 {"read_history_file", read_history_file
,
463 METH_VARARGS
, doc_read_history_file
},
464 {"write_history_file", write_history_file
,
465 METH_VARARGS
, doc_write_history_file
},
466 {"get_history_item", get_history_item
,
467 METH_VARARGS
, doc_get_history_item
},
468 {"get_current_history_length", (PyCFunction
)get_current_history_length
,
469 METH_NOARGS
, doc_get_current_history_length
},
470 {"set_history_length", set_history_length
,
471 METH_VARARGS
, set_history_length_doc
},
472 {"get_history_length", get_history_length
,
473 METH_NOARGS
, get_history_length_doc
},
474 {"set_completer", set_completer
, METH_VARARGS
, doc_set_completer
},
475 {"get_completer", get_completer
, METH_NOARGS
, doc_get_completer
},
476 {"get_begidx", get_begidx
, METH_NOARGS
, doc_get_begidx
},
477 {"get_endidx", get_endidx
, METH_NOARGS
, doc_get_endidx
},
479 {"set_completer_delims", set_completer_delims
,
480 METH_VARARGS
, doc_set_completer_delims
},
481 {"add_history", py_add_history
, METH_VARARGS
, doc_add_history
},
482 {"get_completer_delims", get_completer_delims
,
483 METH_NOARGS
, doc_get_completer_delims
},
485 {"set_startup_hook", set_startup_hook
,
486 METH_VARARGS
, doc_set_startup_hook
},
487 #ifdef HAVE_RL_PRE_INPUT_HOOK
488 {"set_pre_input_hook", set_pre_input_hook
,
489 METH_VARARGS
, doc_set_pre_input_hook
},
495 /* C function to call the Python hooks. */
498 on_hook(PyObject
*func
, PyThreadState
**tstate
)
503 /* Note that readline is called with the interpreter
505 PyEval_RestoreThread(*tstate
);
506 r
= PyObject_CallFunction(func
, NULL
);
512 result
= PyInt_AsLong(r
);
519 *tstate
= PyEval_SaveThread();
525 on_startup_hook(void)
527 return on_hook(startup_hook
, &startup_hook_tstate
);
530 #ifdef HAVE_RL_PRE_INPUT_HOOK
532 on_pre_input_hook(void)
534 return on_hook(pre_input_hook
, &pre_input_hook_tstate
);
539 /* C function to call the Python completer. */
542 on_completion(char *text
, int state
)
545 if (completer
!= NULL
) {
547 /* Note that readline is called with the interpreter
549 PyEval_RestoreThread(completer_tstate
);
550 /* Don't use the default filename completion if we
551 * have a custom completion function... */
552 rl_attempted_completion_over
= 1;
553 r
= PyObject_CallFunction(completer
, "si", text
, state
);
560 char *s
= PyString_AsString(r
);
571 completer_tstate
= PyEval_SaveThread();
577 /* A more flexible constructor that saves the "begidx" and "endidx"
578 * before calling the normal completer */
581 flex_complete(char *text
, int start
, int end
)
585 begidx
= PyInt_FromLong((long) start
);
586 endidx
= PyInt_FromLong((long) end
);
587 return completion_matches(text
, *on_completion
);
591 /* Helper to initialize GNU readline properly. */
597 char *saved_locale
= setlocale(LC_CTYPE
, NULL
);
602 rl_readline_name
= "python";
603 #if defined(PYOS_OS2) && defined(PYCC_GCC)
604 /* Allow $if term= in .inputrc to work */
605 rl_terminal_name
= getenv("TERM");
607 /* Force rebind of TAB to insert-tab */
608 rl_bind_key('\t', rl_insert
);
609 /* Bind both ESC-TAB and ESC-ESC to the completion function */
610 rl_bind_key_in_map ('\t', rl_complete
, emacs_meta_keymap
);
611 rl_bind_key_in_map ('\033', rl_complete
, emacs_meta_keymap
);
612 /* Set our hook functions */
613 rl_startup_hook
= (Function
*)on_startup_hook
;
614 #ifdef HAVE_RL_PRE_INPUT_HOOK
615 rl_pre_input_hook
= (Function
*)on_pre_input_hook
;
617 /* Set our completion function */
618 rl_attempted_completion_function
= (CPPFunction
*)flex_complete
;
619 /* Set Python word break characters */
620 rl_completer_word_break_characters
=
621 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
622 /* All nonalphanums except '.' */
623 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
624 rl_completion_append_character
='\0';
627 begidx
= PyInt_FromLong(0L);
628 endidx
= PyInt_FromLong(0L);
629 /* Initialize (allows .inputrc to override)
631 * XXX: A bug in the readline-2.2 library causes a memory leak
632 * inside this function. Nothing we can do about it.
637 setlocale(LC_CTYPE
, saved_locale
); /* Restore locale */
642 /* Interrupt handler */
654 /* Wrapper around GNU readline that handles signals differently. */
657 call_readline(FILE *sys_stdin
, FILE *sys_stdout
, char *prompt
)
661 PyOS_sighandler_t old_inthandler
;
663 old_inthandler
= PyOS_setsig(SIGINT
, onintr
);
666 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
669 PyOS_setsig(SIGINT
, old_inthandler
);
672 rl_event_hook
= PyOS_InputHook
;
674 if (sys_stdin
!= rl_instream
|| sys_stdout
!= rl_outstream
) {
675 rl_instream
= sys_stdin
;
676 rl_outstream
= sys_stdout
;
677 #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
678 rl_prep_terminal (1);
682 p
= readline(prompt
);
683 PyOS_setsig(SIGINT
, old_inthandler
);
685 /* We must return a buffer allocated with PyMem_Malloc. */
695 HISTORY_STATE
*state
= history_get_history_state();
696 if (state
->length
> 0)
697 line
= history_get(state
->length
)->line
;
702 /* the history docs don't say so, but the address of state
703 changes each time history_get_history_state is called
704 which makes me think it's freshly malloc'd memory...
705 on the other hand, the address of the last line stays the
706 same as long as history isn't extended, so it appears to
707 be malloc'd but managed by the history package... */
710 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
711 release the original. */
713 p
= PyMem_Malloc(n
+2);
724 /* Initialize the module */
726 PyDoc_STRVAR(doc_module
,
727 "Importing this module enables command line editing using GNU readline.");
734 m
= Py_InitModule4("readline", readline_methods
, doc_module
,
735 (PyObject
*)NULL
, PYTHON_API_VERSION
);
737 PyOS_ReadlineFunctionPointer
= call_readline
;