This commit was manufactured by cvs2svn to create tag 'r234'.
[python/dscho.git] / Modules / readline.c
blob1f1b32708721586a0b317bdb3e11db5d3214a53a
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
6 * now maintaining it.
7 */
9 /* Standard definitions */
10 #include "Python.h"
11 #include <setjmp.h>
12 #include <signal.h>
13 #include <errno.h>
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.
20 #define SAVE_LOCALE
21 #include <locale.h>
22 #endif
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)))
32 #endif
35 /* Exported function to send one line to readline's init file parser */
37 static PyObject *
38 parse_and_bind(PyObject *self, PyObject *args)
40 char *s, *copy;
41 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
42 return NULL;
43 /* Make a copy -- rl_parse_and_bind() modifies its argument */
44 /* Bernard Herzog */
45 copy = malloc(1 + strlen(s));
46 if (copy == NULL)
47 return PyErr_NoMemory();
48 strcpy(copy, s);
49 rl_parse_and_bind(copy);
50 free(copy); /* Free the copy */
51 Py_INCREF(Py_None);
52 return Py_None;
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 */
62 static PyObject *
63 read_init_file(PyObject *self, PyObject *args)
65 char *s = NULL;
66 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
67 return NULL;
68 errno = rl_read_init_file(s);
69 if (errno)
70 return PyErr_SetFromErrno(PyExc_IOError);
71 Py_INCREF(Py_None);
72 return Py_None;
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 */
83 static PyObject *
84 read_history_file(PyObject *self, PyObject *args)
86 char *s = NULL;
87 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
88 return NULL;
89 errno = read_history(s);
90 if (errno)
91 return PyErr_SetFromErrno(PyExc_IOError);
92 Py_INCREF(Py_None);
93 return Py_None;
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 */
105 static PyObject *
106 write_history_file(PyObject *self, PyObject *args)
108 char *s = NULL;
109 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
110 return NULL;
111 errno = write_history(s);
112 if (!errno && history_length >= 0)
113 history_truncate_file(s, history_length);
114 if (errno)
115 return PyErr_SetFromErrno(PyExc_IOError);
116 Py_INCREF(Py_None);
117 return Py_None;
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 */
128 static PyObject*
129 set_history_length(PyObject *self, PyObject *args)
131 int length = history_length;
132 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
133 return NULL;
134 history_length = length;
135 Py_INCREF(Py_None);
136 return Py_None;
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 */
148 static PyObject*
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\
157 the history file.");
160 /* Generic hook function setter */
162 static PyObject *
163 set_hook(const char *funcname, PyObject **hook_var,
164 PyThreadState **tstate, PyObject *args)
166 PyObject *function = Py_None;
167 char buf[80];
168 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
169 if (!PyArg_ParseTuple(args, buf, &function))
170 return NULL;
171 if (function == Py_None) {
172 Py_XDECREF(*hook_var);
173 *hook_var = NULL;
174 *tstate = NULL;
176 else if (PyCallable_Check(function)) {
177 PyObject *tmp = *hook_var;
178 Py_INCREF(function);
179 *hook_var = function;
180 Py_XDECREF(tmp);
181 *tstate = PyThreadState_Get();
183 else {
184 PyOS_snprintf(buf, sizeof(buf),
185 "set_%.50s(func): argument not callable",
186 funcname);
187 PyErr_SetString(PyExc_TypeError, buf);
188 return NULL;
190 Py_INCREF(Py_None);
191 return Py_None;
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;
203 #endif
205 static PyObject *
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 */
223 static PyObject *
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\
235 characters.");
237 #endif
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 */
251 static PyObject *
252 get_begidx(PyObject *self, PyObject *noarg)
254 Py_INCREF(begidx);
255 return begidx;
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 */
265 static PyObject *
266 get_endidx(PyObject *self, PyObject *noarg)
268 Py_INCREF(endidx);
269 return endidx;
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 */
279 static PyObject *
280 set_completer_delims(PyObject *self, PyObject *args)
282 char *break_chars;
284 if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
285 return NULL;
287 free((void*)rl_completer_word_break_characters);
288 rl_completer_word_break_characters = strdup(break_chars);
289 Py_INCREF(Py_None);
290 return Py_None;
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 */
300 static PyObject *
301 py_add_history(PyObject *self, PyObject *args)
303 char *line;
305 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
306 return NULL;
308 add_history(line);
309 Py_INCREF(Py_None);
310 return Py_None;
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 */
320 static PyObject *
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 */
333 static PyObject *
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'.");
347 static PyObject *
348 get_completer(PyObject *self, PyObject *noargs)
350 if (completer == NULL) {
351 Py_INCREF(Py_None);
352 return Py_None;
354 Py_INCREF(completer);
355 return 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 */
365 static PyObject *
366 get_history_item(PyObject *self, PyObject *args)
368 int idx = 0;
369 HIST_ENTRY *hist_ent;
371 if (!PyArg_ParseTuple(args, "i:index", &idx))
372 return NULL;
373 if ((hist_ent = history_get(idx)))
374 return PyString_FromString(hist_ent->line);
375 else {
376 Py_INCREF(Py_None);
377 return Py_None;
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 */
388 static PyObject *
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 */
404 static PyObject *
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 */
417 static PyObject *
418 insert_text(PyObject *self, PyObject *args)
420 char *s;
421 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
422 return NULL;
423 rl_insert_text(s);
424 Py_INCREF(Py_None);
425 return Py_None;
428 PyDoc_STRVAR(doc_insert_text,
429 "insert_text(string) -> None\n\
430 Insert text into the command line.");
433 /* Redisplay the line buffer */
435 static PyObject *
436 redisplay(PyObject *self, PyObject *noarg)
438 rl_redisplay();
439 Py_INCREF(Py_None);
440 return Py_None;
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},
486 #endif
487 {0, 0}
491 /* C function to call the Python hooks. */
493 static int
494 on_hook(PyObject *func, PyThreadState **tstate)
496 int result = 0;
497 if (func != NULL) {
498 PyObject *r;
499 /* Note that readline is called with the interpreter
500 lock released! */
501 PyEval_RestoreThread(*tstate);
502 r = PyObject_CallFunction(func, NULL);
503 if (r == NULL)
504 goto error;
505 if (r == Py_None)
506 result = 0;
507 else
508 result = PyInt_AsLong(r);
509 Py_DECREF(r);
510 goto done;
511 error:
512 PyErr_Clear();
513 Py_XDECREF(r);
514 done:
515 *tstate = PyEval_SaveThread();
517 return result;
520 static int
521 on_startup_hook(void)
523 return on_hook(startup_hook, &startup_hook_tstate);
526 #ifdef HAVE_RL_PRE_INPUT_HOOK
527 static int
528 on_pre_input_hook(void)
530 return on_hook(pre_input_hook, &pre_input_hook_tstate);
532 #endif
535 /* C function to call the Python completer. */
537 static char *
538 on_completion(char *text, int state)
540 char *result = NULL;
541 if (completer != NULL) {
542 PyObject *r;
543 /* Note that readline is called with the interpreter
544 lock released! */
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);
550 if (r == NULL)
551 goto error;
552 if (r == Py_None) {
553 result = NULL;
555 else {
556 char *s = PyString_AsString(r);
557 if (s == NULL)
558 goto error;
559 result = strdup(s);
561 Py_DECREF(r);
562 goto done;
563 error:
564 PyErr_Clear();
565 Py_XDECREF(r);
566 done:
567 completer_tstate = PyEval_SaveThread();
569 return result;
573 /* A more flexible constructor that saves the "begidx" and "endidx"
574 * before calling the normal completer */
576 static char **
577 flex_complete(char *text, int start, int end)
579 Py_XDECREF(begidx);
580 Py_XDECREF(endidx);
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. */
589 static void
590 setup_readline(void)
592 #ifdef SAVE_LOCALE
593 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
594 #endif
596 using_history();
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");
602 #endif
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;
612 #endif
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';
621 #endif
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.
630 rl_initialize();
632 #ifdef SAVE_LOCALE
633 setlocale(LC_CTYPE, saved_locale); /* Restore locale */
634 free(saved_locale);
635 #endif
639 /* Interrupt handler */
641 static jmp_buf jbuf;
643 /* ARGSUSED */
644 static void
645 onintr(int sig)
647 longjmp(jbuf, 1);
651 /* Wrapper around GNU readline that handles signals differently. */
653 static char *
654 call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
656 size_t n;
657 char *p, *q;
658 PyOS_sighandler_t old_inthandler;
660 old_inthandler = PyOS_setsig(SIGINT, onintr);
661 if (setjmp(jbuf)) {
662 #ifdef HAVE_SIGRELSE
663 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
664 sigrelse(SIGINT);
665 #endif
666 PyOS_setsig(SIGINT, old_inthandler);
667 return NULL;
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);
676 #endif
679 p = readline(prompt);
680 PyOS_setsig(SIGINT, old_inthandler);
682 /* We must return a buffer allocated with PyMem_Malloc. */
683 if (p == NULL) {
684 p = PyMem_Malloc(1);
685 if (p != NULL)
686 *p = '\0';
687 return p;
689 n = strlen(p);
690 if (n > 0) {
691 char *line;
692 HISTORY_STATE *state = history_get_history_state();
693 if (state->length > 0)
694 line = history_get(state->length)->line;
695 else
696 line = "";
697 if (strcmp(p, line))
698 add_history(p);
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... */
705 free(state);
707 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
708 release the original. */
709 q = p;
710 p = PyMem_Malloc(n+2);
711 if (p != NULL) {
712 strncpy(p, q, n);
713 p[n] = '\n';
714 p[n+1] = '\0';
716 free(q);
717 return p;
721 /* Initialize the module */
723 PyDoc_STRVAR(doc_module,
724 "Importing this module enables command line editing using GNU readline.");
726 PyMODINIT_FUNC
727 initreadline(void)
729 PyObject *m;
731 m = Py_InitModule4("readline", readline_methods, doc_module,
732 (PyObject *)NULL, PYTHON_API_VERSION);
734 PyOS_ReadlineFunctionPointer = call_readline;
735 setup_readline();