OILS / pyext / line_input.c View on Github | oilshell.org

1325 lines, 798 significant
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.
5 */
6
7/* Standard definitions */
8#include "Python.h"
9#include <setjmp.h>
10#include <signal.h>
11#include <errno.h>
12#include <sys/time.h>
13
14/* ------------------------------------------------------------------------- */
15
16/* OVM_MAIN: This section copied from autotool-generated pyconfig.h.
17 * We're not detecting any of it in Oil's configure script. They are for
18 * ancient readline versions.
19 * */
20
21/* Define if you have readline 2.1 */
22#define HAVE_RL_CALLBACK 1
23
24/* Define if you can turn off readline's signal handling. */
25#define HAVE_RL_CATCH_SIGNAL 1
26
27/* Define if you have readline 2.2 */
28#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1
29
30/* Define if you have readline 4.0 */
31#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1
32
33/* Define if you have readline 4.2 */
34#define HAVE_RL_COMPLETION_MATCHES 1
35
36/* Define if you have rl_completion_suppress_append */
37#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1
38
39/* Define if you have readline 4.0 */
40#define HAVE_RL_PRE_INPUT_HOOK 1
41
42/* Define if you have readline 4.0 */
43#define HAVE_RL_RESIZE_TERMINAL 1
44
45/* ------------------------------------------------------------------------- */
46
47#if defined(HAVE_SETLOCALE)
48/* GNU readline() mistakenly sets the LC_CTYPE locale.
49 * This is evil. Only the user or the app's main() should do this!
50 * We must save and restore the locale around the rl_initialize() call.
51 */
52#define SAVE_LOCALE
53#include <locale.h>
54#endif
55
56#ifdef SAVE_LOCALE
57# define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
58#else
59# define RESTORE_LOCALE(sl)
60#endif
61
62/* GNU readline definitions */
63#undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
64#include <readline/readline.h>
65#include <readline/history.h>
66
67#ifdef HAVE_RL_COMPLETION_MATCHES
68#define completion_matches(x, y) \
69 rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
70#else
71#if defined(_RL_FUNCTION_TYPEDEF)
72extern char **completion_matches(char *, rl_compentry_func_t *);
73#else
74
75#if !defined(__APPLE__)
76extern char **completion_matches(char *, CPFunction *);
77#endif
78#endif
79#endif
80
81#ifdef __APPLE__
82/*
83 * It is possible to link the readline module to the readline
84 * emulation library of editline/libedit.
85 *
86 * On OSX this emulation library is not 100% API compatible
87 * with the "real" readline and cannot be detected at compile-time,
88 * hence we use a runtime check to detect if we're using libedit
89 *
90 * Currently there is one known API incompatibility:
91 * - 'get_history' has a 1-based index with GNU readline, and a 0-based
92 * index with older versions of libedit's emulation.
93 * - Note that replace_history and remove_history use a 0-based index
94 * with both implementations.
95 */
96static int using_libedit_emulation = 0;
97static const char libedit_version_tag[] = "EditLine wrapper";
98
99static int libedit_history_start = 0;
100#endif /* __APPLE__ */
101
102#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
103static void
104on_completion_display_matches_hook(char **matches,
105 int num_matches, int max_length);
106#endif
107
108/* Memory allocated for rl_completer_word_break_characters
109 (see issue #17289 for the motivation). */
110static char *completer_word_break_characters;
111
112/* Exported function to send one line to readline's init file parser */
113
114static PyObject *
115parse_and_bind(PyObject *self, PyObject *args)
116{
117 char *s, *copy;
118 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
119 return NULL;
120 /* Make a copy -- rl_parse_and_bind() modifies its argument */
121 /* Bernard Herzog */
122 copy = malloc(1 + strlen(s));
123 if (copy == NULL)
124 return PyErr_NoMemory();
125 strcpy(copy, s);
126 rl_parse_and_bind(copy);
127 free(copy); /* Free the copy */
128 Py_RETURN_NONE;
129}
130
131PyDoc_STRVAR(doc_parse_and_bind,
132"parse_and_bind(string) -> None\n\
133Execute the init line provided in the string argument.");
134
135
136/* Exported function to parse a readline init file */
137
138static PyObject *
139read_init_file(PyObject *self, PyObject *args)
140{
141 char *s = NULL;
142 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
143 return NULL;
144 errno = rl_read_init_file(s);
145 if (errno)
146 return PyErr_SetFromErrno(PyExc_IOError);
147 Py_RETURN_NONE;
148}
149
150PyDoc_STRVAR(doc_read_init_file,
151"read_init_file([filename]) -> None\n\
152Execute a readline initialization file.\n\
153The default filename is the last filename used.");
154
155
156/* Exported function to load a readline history file */
157
158static PyObject *
159read_history_file(PyObject *self, PyObject *args)
160{
161 char *s = NULL;
162 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
163 return NULL;
164 errno = read_history(s);
165 if (errno)
166 return PyErr_SetFromErrno(PyExc_IOError);
167 Py_RETURN_NONE;
168}
169
170static int _history_length = -1; /* do not truncate history by default */
171PyDoc_STRVAR(doc_read_history_file,
172"read_history_file([filename]) -> None\n\
173Load a readline history file.\n\
174The default filename is ~/.history.");
175
176
177/* Exported function to save a readline history file */
178
179static PyObject *
180write_history_file(PyObject *self, PyObject *args)
181{
182 char *s = NULL;
183 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
184 return NULL;
185 errno = write_history(s);
186 if (!errno && _history_length >= 0)
187 history_truncate_file(s, _history_length);
188 if (errno)
189 return PyErr_SetFromErrno(PyExc_IOError);
190 Py_RETURN_NONE;
191}
192
193PyDoc_STRVAR(doc_write_history_file,
194"write_history_file([filename]) -> None\n\
195Save a readline history file.\n\
196The default filename is ~/.history.");
197
198
199/* Set history length */
200
201static PyObject*
202set_history_length(PyObject *self, PyObject *args)
203{
204 int length = _history_length;
205 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
206 return NULL;
207 _history_length = length;
208 Py_RETURN_NONE;
209}
210
211PyDoc_STRVAR(set_history_length_doc,
212"set_history_length(length) -> None\n\
213set the maximal number of lines which will be written to\n\
214the history file. A negative length is used to inhibit\n\
215history truncation.");
216
217
218/* Get history length */
219
220static PyObject*
221get_history_length(PyObject *self, PyObject *noarg)
222{
223 return PyInt_FromLong(_history_length);
224}
225
226PyDoc_STRVAR(get_history_length_doc,
227"get_history_length() -> int\n\
228return the maximum number of lines that will be written to\n\
229the history file.");
230
231
232/* Generic hook function setter */
233
234static PyObject *
235set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
236{
237 PyObject *function = Py_None;
238 char buf[80];
239 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
240 if (!PyArg_ParseTuple(args, buf, &function))
241 return NULL;
242 if (function == Py_None) {
243 Py_CLEAR(*hook_var);
244 }
245 else if (PyCallable_Check(function)) {
246 PyObject *tmp = *hook_var;
247 Py_INCREF(function);
248 *hook_var = function;
249 Py_XDECREF(tmp);
250 }
251 else {
252 PyOS_snprintf(buf, sizeof(buf),
253 "set_%.50s(func): argument not callable",
254 funcname);
255 PyErr_SetString(PyExc_TypeError, buf);
256 return NULL;
257 }
258 Py_RETURN_NONE;
259}
260
261
262/* Exported functions to specify hook functions in Python */
263
264static PyObject *completion_display_matches_hook = NULL;
265static PyObject *startup_hook = NULL;
266
267#ifdef HAVE_RL_PRE_INPUT_HOOK
268static PyObject *pre_input_hook = NULL;
269#endif
270
271static PyObject *
272set_completion_display_matches_hook(PyObject *self, PyObject *args)
273{
274 PyObject *result = set_hook("completion_display_matches_hook",
275 &completion_display_matches_hook, args);
276#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
277 /* We cannot set this hook globally, since it replaces the
278 default completion display. */
279 rl_completion_display_matches_hook =
280 completion_display_matches_hook ?
281#if defined(_RL_FUNCTION_TYPEDEF)
282 (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
283#else
284 (VFunction *)on_completion_display_matches_hook : 0;
285#endif
286#endif
287 return result;
288
289}
290
291PyDoc_STRVAR(doc_set_completion_display_matches_hook,
292"set_completion_display_matches_hook([function]) -> None\n\
293Set or remove the completion display function.\n\
294The function is called as\n\
295 function(substitution, [matches], longest_match_length)\n\
296once each time matches need to be displayed.");
297
298static PyObject *
299set_startup_hook(PyObject *self, PyObject *args)
300{
301 return set_hook("startup_hook", &startup_hook, args);
302}
303
304PyDoc_STRVAR(doc_set_startup_hook,
305"set_startup_hook([function]) -> None\n\
306Set or remove the function invoked by the rl_startup_hook callback.\n\
307The function is called with no arguments just\n\
308before readline prints the first prompt.");
309
310
311#ifdef HAVE_RL_PRE_INPUT_HOOK
312
313/* Set pre-input hook */
314
315static PyObject *
316set_pre_input_hook(PyObject *self, PyObject *args)
317{
318 return set_hook("pre_input_hook", &pre_input_hook, args);
319}
320
321PyDoc_STRVAR(doc_set_pre_input_hook,
322"set_pre_input_hook([function]) -> None\n\
323Set or remove the function invoked by the rl_pre_input_hook callback.\n\
324The function is called with no arguments after the first prompt\n\
325has been printed and just before readline starts reading input\n\
326characters.");
327
328#endif
329
330
331/* Exported function to specify a word completer in Python */
332
333static PyObject *completer = NULL;
334
335static PyObject *begidx = NULL;
336static PyObject *endidx = NULL;
337
338
339/* Get the completion type for the scope of the tab-completion */
340static PyObject *
341get_completion_type(PyObject *self, PyObject *noarg)
342{
343 return PyInt_FromLong(rl_completion_type);
344}
345
346PyDoc_STRVAR(doc_get_completion_type,
347"get_completion_type() -> int\n\
348Get the type of completion being attempted.");
349
350
351/* Get the beginning index for the scope of the tab-completion */
352
353static PyObject *
354get_begidx(PyObject *self, PyObject *noarg)
355{
356 Py_INCREF(begidx);
357 return begidx;
358}
359
360PyDoc_STRVAR(doc_get_begidx,
361"get_begidx() -> int\n\
362get the beginning index of the completion scope");
363
364
365/* Get the ending index for the scope of the tab-completion */
366
367static PyObject *
368get_endidx(PyObject *self, PyObject *noarg)
369{
370 Py_INCREF(endidx);
371 return endidx;
372}
373
374PyDoc_STRVAR(doc_get_endidx,
375"get_endidx() -> int\n\
376get the ending index of the completion scope");
377
378
379/* Set the tab-completion word-delimiters that readline uses */
380
381static PyObject *
382set_completer_delims(PyObject *self, PyObject *args)
383{
384 char *break_chars;
385
386 if (!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
387 return NULL;
388 }
389 /* Keep a reference to the allocated memory in the module state in case
390 some other module modifies rl_completer_word_break_characters
391 (see issue #17289). */
392 break_chars = strdup(break_chars);
393 if (break_chars) {
394 free(completer_word_break_characters);
395 completer_word_break_characters = break_chars;
396 rl_completer_word_break_characters = break_chars;
397 Py_RETURN_NONE;
398 }
399 else
400 return PyErr_NoMemory();
401}
402
403PyDoc_STRVAR(doc_set_completer_delims,
404"set_completer_delims(string) -> None\n\
405set the word delimiters for completion");
406
407/* _py_free_history_entry: Utility function to free a history entry. */
408
409#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0500
410
411/* Readline version >= 5.0 introduced a timestamp field into the history entry
412 structure; this needs to be freed to avoid a memory leak. This version of
413 readline also introduced the handy 'free_history_entry' function, which
414 takes care of the timestamp. */
415
416static void
417_py_free_history_entry(HIST_ENTRY *entry)
418{
419 histdata_t data = free_history_entry(entry);
420 free(data);
421}
422
423#else
424
425/* No free_history_entry function; free everything manually. */
426
427static void
428_py_free_history_entry(HIST_ENTRY *entry)
429{
430 if (entry->line)
431 free((void *)entry->line);
432 if (entry->data)
433 free(entry->data);
434 free(entry);
435}
436
437#endif
438
439static PyObject *
440py_remove_history(PyObject *self, PyObject *args)
441{
442 int entry_number;
443 HIST_ENTRY *entry;
444
445 if (!PyArg_ParseTuple(args, "i:remove_history_item", &entry_number))
446 return NULL;
447 if (entry_number < 0) {
448 PyErr_SetString(PyExc_ValueError,
449 "History index cannot be negative");
450 return NULL;
451 }
452 entry = remove_history(entry_number);
453 if (!entry) {
454 PyErr_Format(PyExc_ValueError,
455 "No history item at position %d",
456 entry_number);
457 return NULL;
458 }
459 /* free memory allocated for the history entry */
460 _py_free_history_entry(entry);
461 Py_RETURN_NONE;
462}
463
464PyDoc_STRVAR(doc_remove_history,
465"remove_history_item(pos) -> None\n\
466remove history item given by its position");
467
468static PyObject *
469py_replace_history(PyObject *self, PyObject *args)
470{
471 int entry_number;
472 char *line;
473 HIST_ENTRY *old_entry;
474
475 if (!PyArg_ParseTuple(args, "is:replace_history_item", &entry_number,
476 &line)) {
477 return NULL;
478 }
479 if (entry_number < 0) {
480 PyErr_SetString(PyExc_ValueError,
481 "History index cannot be negative");
482 return NULL;
483 }
484 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
485 if (!old_entry) {
486 PyErr_Format(PyExc_ValueError,
487 "No history item at position %d",
488 entry_number);
489 return NULL;
490 }
491 /* free memory allocated for the old history entry */
492 _py_free_history_entry(old_entry);
493 Py_RETURN_NONE;
494}
495
496PyDoc_STRVAR(doc_replace_history,
497"replace_history_item(pos, line) -> None\n\
498replaces history item given by its position with contents of line");
499
500/* Add a line to the history buffer */
501
502static PyObject *
503py_add_history(PyObject *self, PyObject *args)
504{
505 char *line;
506
507 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
508 return NULL;
509 }
510 add_history(line);
511 Py_RETURN_NONE;
512}
513
514PyDoc_STRVAR(doc_add_history,
515"add_history(string) -> None\n\
516add an item to the history buffer");
517
518
519/* Get the tab-completion word-delimiters that readline uses */
520
521static PyObject *
522get_completer_delims(PyObject *self, PyObject *noarg)
523{
524 return PyString_FromString(rl_completer_word_break_characters);
525}
526
527PyDoc_STRVAR(doc_get_completer_delims,
528"get_completer_delims() -> string\n\
529get the word delimiters for completion");
530
531
532/* Set the completer function */
533
534static PyObject *
535set_completer(PyObject *self, PyObject *args)
536{
537 return set_hook("completer", &completer, args);
538}
539
540PyDoc_STRVAR(doc_set_completer,
541"set_completer([function]) -> None\n\
542Set or remove the completer function.\n\
543The function is called as function(text, state),\n\
544for state in 0, 1, 2, ..., until it returns a non-string.\n\
545It should return the next possible completion starting with 'text'.");
546
547
548static PyObject *
549get_completer(PyObject *self, PyObject *noargs)
550{
551 if (completer == NULL) {
552 Py_RETURN_NONE;
553 }
554 Py_INCREF(completer);
555 return completer;
556}
557
558PyDoc_STRVAR(doc_get_completer,
559"get_completer() -> function\n\
560\n\
561Returns current completer function.");
562
563/* Private function to get current length of history. XXX It may be
564 * possible to replace this with a direct use of history_length instead,
565 * but it's not clear whether BSD's libedit keeps history_length up to date.
566 * See issue #8065.*/
567
568static int
569_py_get_history_length(void)
570{
571 HISTORY_STATE *hist_st = history_get_history_state();
572 int length = hist_st->length;
573 /* the history docs don't say so, but the address of hist_st changes each
574 time history_get_history_state is called which makes me think it's
575 freshly malloc'd memory... on the other hand, the address of the last
576 line stays the same as long as history isn't extended, so it appears to
577 be malloc'd but managed by the history package... */
578 free(hist_st);
579 return length;
580}
581
582/* Exported function to get any element of history */
583
584static PyObject *
585get_history_item(PyObject *self, PyObject *args)
586{
587 int idx = 0;
588 HIST_ENTRY *hist_ent;
589
590 if (!PyArg_ParseTuple(args, "i:get_history_item", &idx))
591 return NULL;
592#ifdef __APPLE__
593 if (using_libedit_emulation) {
594 /* Older versions of libedit's readline emulation
595 * use 0-based indexes, while readline and newer
596 * versions of libedit use 1-based indexes.
597 */
598 int length = _py_get_history_length();
599
600 idx = idx - 1 + libedit_history_start;
601
602 /*
603 * Apple's readline emulation crashes when
604 * the index is out of range, therefore
605 * test for that and fail gracefully.
606 */
607 if (idx < (0 + libedit_history_start)
608 || idx >= (length + libedit_history_start)) {
609 Py_RETURN_NONE;
610 }
611 }
612#endif /* __APPLE__ */
613 if ((hist_ent = history_get(idx)))
614 return PyString_FromString(hist_ent->line);
615 else {
616 Py_RETURN_NONE;
617 }
618}
619
620PyDoc_STRVAR(doc_get_history_item,
621"get_history_item() -> string\n\
622return the current contents of history item at index.");
623
624
625/* Exported function to get current length of history */
626
627static PyObject *
628get_current_history_length(PyObject *self, PyObject *noarg)
629{
630 return PyInt_FromLong((long)_py_get_history_length());
631}
632
633PyDoc_STRVAR(doc_get_current_history_length,
634"get_current_history_length() -> integer\n\
635return the current (not the maximum) length of history.");
636
637
638/* Exported function to read the current line buffer */
639
640static PyObject *
641get_line_buffer(PyObject *self, PyObject *noarg)
642{
643 return PyString_FromString(rl_line_buffer);
644}
645
646PyDoc_STRVAR(doc_get_line_buffer,
647"get_line_buffer() -> string\n\
648return the current contents of the line buffer.");
649
650
651#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
652
653/* Exported function to clear the current history */
654
655static PyObject *
656py_clear_history(PyObject *self, PyObject *noarg)
657{
658 clear_history();
659 Py_RETURN_NONE;
660}
661
662PyDoc_STRVAR(doc_clear_history,
663"clear_history() -> None\n\
664Clear the current readline history.");
665#endif
666
667/* Added for OSH. We need to call this in our SIGWINCH handler so global
668 * variables in readline get updated. */
669static PyObject *
670py_resize_terminal(PyObject *self, PyObject *noarg)
671{
672 rl_resize_terminal();
673 Py_RETURN_NONE;
674}
675
676/* Exported function to insert text into the line buffer */
677
678static PyObject *
679insert_text(PyObject *self, PyObject *args)
680{
681 char *s;
682 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
683 return NULL;
684 rl_insert_text(s);
685 Py_RETURN_NONE;
686}
687
688PyDoc_STRVAR(doc_insert_text,
689"insert_text(string) -> None\n\
690Insert text into the line buffer at the cursor position.");
691
692
693/* Redisplay the line buffer */
694
695static PyObject *
696redisplay(PyObject *self, PyObject *noarg)
697{
698 rl_redisplay();
699 Py_RETURN_NONE;
700}
701
702PyDoc_STRVAR(doc_redisplay,
703"redisplay() -> None\n\
704Change what's displayed on the screen to reflect the current\n\
705contents of the line buffer.");
706
707
708/* List binding functions */
709
710static PyObject*
711list_funmap_names(PyObject *self, PyObject *args)
712{
713 rl_list_funmap_names();
714 Py_RETURN_NONE;
715}
716
717PyDoc_STRVAR(doc_list_funmap_names,
718"list_funmap_names() -> None\n\
719Print all of the available readline functions.");
720
721/* Print readline functions and their bindings */
722
723static PyObject*
724function_dumper(PyObject *self, PyObject *args)
725{
726 int print_readably;
727
728 if (!PyArg_ParseTuple(args, "i:function_dumper", &print_readably))
729 return NULL;
730
731 rl_function_dumper(print_readably);
732 Py_RETURN_NONE;
733}
734
735PyDoc_STRVAR(doc_list_function_dumper,
736"function_dumper(bool) -> None\n\
737Print all readline functions and their bindings.");
738
739/* Print macros, their bindings, and their string outputs */
740
741static PyObject*
742macro_dumper(PyObject *self, PyObject *args)
743{
744 int print_readably;
745
746 if (!PyArg_ParseTuple(args, "i:macro_dumper", &print_readably))
747 return NULL;
748
749 rl_macro_dumper(print_readably);
750 Py_RETURN_NONE;
751}
752
753PyDoc_STRVAR(doc_list_macro_dumper,
754"macro_dumper(bool) -> None\n\
755Print all readline sequences bound to macros and the strings they output.");
756
757/* List readline variables */
758
759static PyObject*
760variable_dumper(PyObject *self, PyObject *args)
761{
762 int print_readably;
763
764 if (!PyArg_ParseTuple(args, "i:variable_dumper", &print_readably))
765 return NULL;
766
767 rl_variable_dumper(print_readably);
768 Py_RETURN_NONE;
769}
770
771PyDoc_STRVAR(doc_list_variable_dumper,
772"variable_dumper(bool) -> None\n\
773List readline variables and their values.");
774
775
776/* Table of functions exported by the module */
777
778#ifdef OVM_MAIN
779#include "pyext/line_input.c/readline_methods.def"
780#else
781static struct PyMethodDef readline_methods[] = {
782 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
783 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
784 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
785 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
786 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
787 {"read_history_file", read_history_file,
788 METH_VARARGS, doc_read_history_file},
789 {"write_history_file", write_history_file,
790 METH_VARARGS, doc_write_history_file},
791 {"get_history_item", get_history_item,
792 METH_VARARGS, doc_get_history_item},
793 {"get_current_history_length", (PyCFunction)get_current_history_length,
794 METH_NOARGS, doc_get_current_history_length},
795 {"set_history_length", set_history_length,
796 METH_VARARGS, set_history_length_doc},
797 {"get_history_length", get_history_length,
798 METH_NOARGS, get_history_length_doc},
799 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
800 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
801 {"get_completion_type", get_completion_type,
802 METH_NOARGS, doc_get_completion_type},
803 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
804 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
805
806 {"set_completer_delims", set_completer_delims,
807 METH_VARARGS, doc_set_completer_delims},
808 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
809 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
810 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
811 {"get_completer_delims", get_completer_delims,
812 METH_NOARGS, doc_get_completer_delims},
813
814 {"set_completion_display_matches_hook", set_completion_display_matches_hook,
815 METH_VARARGS, doc_set_completion_display_matches_hook},
816 {"set_startup_hook", set_startup_hook,
817 METH_VARARGS, doc_set_startup_hook},
818 {"set_pre_input_hook", set_pre_input_hook,
819 METH_VARARGS, doc_set_pre_input_hook},
820 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
821 {"resize_terminal", py_resize_terminal, METH_NOARGS, ""},
822 {"list_funmap_names", list_funmap_names, METH_NOARGS, doc_list_funmap_names},
823 {"function_dumper", function_dumper, METH_VARARGS, doc_list_function_dumper},
824 {"macro_dumper", macro_dumper, METH_VARARGS, doc_list_macro_dumper},
825 {"variable_dumper", variable_dumper, METH_VARARGS, doc_list_variable_dumper},
826 {0, 0}
827};
828#endif
829
830
831/* C function to call the Python hooks. */
832
833static int
834on_hook(PyObject *func)
835{
836 int result = 0;
837 if (func != NULL) {
838 PyObject *r;
839#ifdef WITH_THREAD
840 PyGILState_STATE gilstate = PyGILState_Ensure();
841#endif
842 r = PyObject_CallFunction(func, NULL);
843 if (r == NULL)
844 goto error;
845 if (r == Py_None)
846 result = 0;
847 else {
848 result = PyInt_AsLong(r);
849 if (result == -1 && PyErr_Occurred())
850 goto error;
851 }
852 Py_DECREF(r);
853 goto done;
854 error:
855 PyErr_Clear();
856 Py_XDECREF(r);
857 done:
858#ifdef WITH_THREAD
859 PyGILState_Release(gilstate);
860#endif
861 return result;
862 }
863 return result;
864}
865
866static int
867#if defined(_RL_FUNCTION_TYPEDEF)
868on_startup_hook(void)
869#else
870on_startup_hook()
871#endif
872{
873 return on_hook(startup_hook);
874}
875
876#ifdef HAVE_RL_PRE_INPUT_HOOK
877static int
878#if defined(_RL_FUNCTION_TYPEDEF)
879on_pre_input_hook(void)
880#else
881on_pre_input_hook()
882#endif
883{
884 return on_hook(pre_input_hook);
885}
886#endif
887
888
889/* C function to call the Python completion_display_matches */
890
891#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
892static void
893on_completion_display_matches_hook(char **matches,
894 int num_matches, int max_length)
895{
896 int i;
897 PyObject *m=NULL, *s=NULL, *r=NULL;
898#ifdef WITH_THREAD
899 PyGILState_STATE gilstate = PyGILState_Ensure();
900#endif
901 m = PyList_New(num_matches);
902 if (m == NULL)
903 goto error;
904 for (i = 0; i < num_matches; i++) {
905 s = PyString_FromString(matches[i+1]);
906 if (s == NULL)
907 goto error;
908 if (PyList_SetItem(m, i, s) == -1)
909 goto error;
910 }
911
912 r = PyObject_CallFunction(completion_display_matches_hook,
913 "sOi", matches[0], m, max_length);
914
915 Py_DECREF(m); m=NULL;
916
917 if (r == NULL ||
918 (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
919 goto error;
920 }
921 Py_XDECREF(r); r=NULL;
922
923 if (0) {
924 error:
925 PyErr_Clear();
926 Py_XDECREF(m);
927 Py_XDECREF(r);
928 }
929#ifdef WITH_THREAD
930 PyGILState_Release(gilstate);
931#endif
932}
933
934#endif
935
936#ifdef HAVE_RL_RESIZE_TERMINAL
937static volatile sig_atomic_t sigwinch_received;
938static PyOS_sighandler_t sigwinch_ohandler;
939
940static void
941readline_sigwinch_handler(int signum)
942{
943 sigwinch_received = 1;
944 if (sigwinch_ohandler &&
945 sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
946 sigwinch_ohandler(signum);
947}
948#endif
949
950/* C function to call the Python completer. */
951
952static char *
953on_completion(const char *text, int state)
954{
955 char *result = NULL;
956 if (completer != NULL) {
957 PyObject *r;
958#ifdef WITH_THREAD
959 PyGILState_STATE gilstate = PyGILState_Ensure();
960#endif
961 rl_attempted_completion_over = 1;
962 r = PyObject_CallFunction(completer, "si", text, state);
963 if (r == NULL)
964 goto error;
965 if (r == Py_None) {
966 result = NULL;
967 }
968 else {
969 char *s = PyString_AsString(r);
970 if (s == NULL)
971 goto error;
972 result = strdup(s);
973 }
974 Py_DECREF(r);
975 goto done;
976 error:
977 PyErr_Clear();
978 Py_XDECREF(r);
979 done:
980#ifdef WITH_THREAD
981 PyGILState_Release(gilstate);
982#endif
983 return result;
984 }
985 return result;
986}
987
988
989/* A more flexible constructor that saves the "begidx" and "endidx"
990 * before calling the normal completer */
991
992static char **
993flex_complete(const char *text, int start, int end)
994{
995#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
996 rl_completion_append_character ='\0';
997#endif
998#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
999 rl_completion_suppress_append = 0;
1000#endif
1001 Py_XDECREF(begidx);
1002 Py_XDECREF(endidx);
1003 begidx = PyInt_FromLong((long) start);
1004 endidx = PyInt_FromLong((long) end);
1005 return completion_matches(text, *on_completion);
1006}
1007
1008
1009/* Helper to initialize GNU readline properly. */
1010
1011static void
1012setup_readline(void)
1013{
1014#ifdef SAVE_LOCALE
1015 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1016 if (!saved_locale)
1017 Py_FatalError("not enough memory to save locale");
1018#endif
1019
1020#ifdef __APPLE__
1021 /* the libedit readline emulation resets key bindings etc
1022 * when calling rl_initialize. So call it upfront
1023 */
1024 if (using_libedit_emulation)
1025 rl_initialize();
1026
1027 /* Detect if libedit's readline emulation uses 0-based
1028 * indexing or 1-based indexing.
1029 */
1030 add_history("1");
1031 if (history_get(1) == NULL) {
1032 libedit_history_start = 0;
1033 } else {
1034 libedit_history_start = 1;
1035 }
1036 clear_history();
1037#endif /* __APPLE__ */
1038
1039 using_history();
1040
1041 rl_readline_name = "oils";
1042#if defined(PYOS_OS2) && defined(PYCC_GCC)
1043 /* Allow $if term= in .inputrc to work */
1044 rl_terminal_name = getenv("TERM");
1045#endif
1046 /* Force rebind of TAB to insert-tab */
1047 rl_bind_key('\t', rl_insert);
1048 /* Bind both ESC-TAB and ESC-ESC to the completion function */
1049 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1050 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
1051#ifdef HAVE_RL_RESIZE_TERMINAL
1052 /* Set up signal handler for window resize */
1053 sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1054#endif
1055 /* Set our hook functions */
1056 rl_startup_hook = on_startup_hook;
1057#ifdef HAVE_RL_PRE_INPUT_HOOK
1058 rl_pre_input_hook = on_pre_input_hook;
1059#endif
1060 /* Set our completion function */
1061 rl_attempted_completion_function = flex_complete;
1062 /* Set Python word break characters */
1063 completer_word_break_characters =
1064 rl_completer_word_break_characters =
1065 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1066 /* All nonalphanums except '.' */
1067
1068 begidx = PyInt_FromLong(0L);
1069 endidx = PyInt_FromLong(0L);
1070
1071#ifdef __APPLE__
1072 if (!using_libedit_emulation)
1073#endif
1074 {
1075 if (!isatty(STDOUT_FILENO)) {
1076 /* Issue #19884: stdout is not a terminal. Disable meta modifier
1077 keys to not write the ANSI sequence "\033[1034h" into stdout. On
1078 terminals supporting 8 bit characters like TERM=xterm-256color
1079 (which is now the default Fedora since Fedora 18), the meta key is
1080 used to enable support of 8 bit characters (ANSI sequence
1081 "\033[1034h").
1082
1083 With libedit, this call makes readline() crash. */
1084 rl_variable_bind ("enable-meta-key", "off");
1085 }
1086 }
1087
1088 /* Initialize (allows .inputrc to override)
1089 *
1090 * XXX: A bug in the readline-2.2 library causes a memory leak
1091 * inside this function. Nothing we can do about it.
1092 */
1093#ifdef __APPLE__
1094 if (using_libedit_emulation)
1095 rl_read_init_file(NULL);
1096 else
1097#endif /* __APPLE__ */
1098 rl_initialize();
1099
1100 RESTORE_LOCALE(saved_locale)
1101}
1102
1103/* Wrapper around GNU readline that handles signals differently. */
1104
1105
1106#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
1107
1108static char *completed_input_string;
1109static void
1110rlhandler(char *text)
1111{
1112 completed_input_string = text;
1113 rl_callback_handler_remove();
1114}
1115
1116static char *
1117readline_until_enter_or_signal(char *prompt, int *signal)
1118{
1119 char * not_done_reading = "";
1120 fd_set selectset;
1121
1122 *signal = 0;
1123#ifdef HAVE_RL_CATCH_SIGNAL
1124 rl_catch_signals = 0;
1125#endif
1126 /* OVM_MAIN: Oil is handling SIGWINCH, so readline shouldn't handle it.
1127 * Without this line, strace reveals that GNU readline is constantly
1128 * turning it on and off.
1129 * */
1130 rl_catch_sigwinch = 0;
1131
1132 rl_callback_handler_install (prompt, rlhandler);
1133 FD_ZERO(&selectset);
1134
1135 completed_input_string = not_done_reading;
1136
1137 while (completed_input_string == not_done_reading) {
1138 int has_input = 0;
1139
1140 while (!has_input)
1141 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
1142
1143 /* [Bug #1552726] Only limit the pause if an input hook has been
1144 defined. */
1145 struct timeval *timeoutp = NULL;
1146 if (PyOS_InputHook)
1147 timeoutp = &timeout;
1148#ifdef HAVE_RL_RESIZE_TERMINAL
1149 /* Update readline's view of the window size after SIGWINCH */
1150 if (sigwinch_received) {
1151 sigwinch_received = 0;
1152 rl_resize_terminal();
1153 }
1154#endif
1155 FD_SET(fileno(rl_instream), &selectset);
1156 /* select resets selectset if no input was available */
1157 has_input = select(fileno(rl_instream) + 1, &selectset,
1158 NULL, NULL, timeoutp);
1159 if(PyOS_InputHook) PyOS_InputHook();
1160 }
1161
1162 if(has_input > 0) {
1163 rl_callback_read_char();
1164 }
1165 else if (errno == EINTR) {
1166 int s;
1167#ifdef WITH_THREAD
1168 PyEval_RestoreThread(_PyOS_ReadlineTState);
1169#endif
1170 s = PyErr_CheckSignals();
1171#ifdef WITH_THREAD
1172 PyEval_SaveThread();
1173#endif
1174 if (s < 0) {
1175 rl_free_line_state();
1176#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1177 rl_callback_sigcleanup();
1178#endif
1179 rl_cleanup_after_signal();
1180 rl_callback_handler_remove();
1181 *signal = 1;
1182 completed_input_string = NULL;
1183 }
1184 }
1185 }
1186
1187 return completed_input_string;
1188}
1189
1190
1191#else
1192
1193/* Interrupt handler */
1194
1195static jmp_buf jbuf;
1196
1197/* ARGSUSED */
1198static void
1199onintr(int sig)
1200{
1201 longjmp(jbuf, 1);
1202}
1203
1204
1205static char *
1206readline_until_enter_or_signal(char *prompt, int *signal)
1207{
1208 PyOS_sighandler_t old_inthandler;
1209 char *p;
1210
1211 *signal = 0;
1212
1213 old_inthandler = PyOS_setsig(SIGINT, onintr);
1214 if (setjmp(jbuf)) {
1215#ifdef HAVE_SIGRELSE
1216 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
1217 sigrelse(SIGINT);
1218#endif
1219 PyOS_setsig(SIGINT, old_inthandler);
1220 *signal = 1;
1221 return NULL;
1222 }
1223 rl_event_hook = PyOS_InputHook;
1224 p = readline(prompt);
1225 PyOS_setsig(SIGINT, old_inthandler);
1226
1227 return p;
1228}
1229#endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
1230
1231
1232static char *
1233call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
1234{
1235 size_t n;
1236 char *p, *q;
1237 int signal;
1238
1239#ifdef SAVE_LOCALE
1240 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1241 if (!saved_locale)
1242 Py_FatalError("not enough memory to save locale");
1243 setlocale(LC_CTYPE, "");
1244#endif
1245
1246 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1247 rl_instream = sys_stdin;
1248 rl_outstream = sys_stdout;
1249#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1250 rl_prep_terminal (1);
1251#endif
1252 }
1253
1254 p = readline_until_enter_or_signal(prompt, &signal);
1255
1256 /* we got an interrupt signal */
1257 if (signal) {
1258 RESTORE_LOCALE(saved_locale)
1259 return NULL;
1260 }
1261
1262 /* We got an EOF, return an empty string. */
1263 if (p == NULL) {
1264 p = PyMem_Malloc(1);
1265 if (p != NULL)
1266 *p = '\0';
1267 RESTORE_LOCALE(saved_locale)
1268 return p;
1269 }
1270
1271 /* we have a valid line */
1272 n = strlen(p);
1273 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1274 release the original. */
1275 q = p;
1276 p = PyMem_Malloc(n+2);
1277 if (p != NULL) {
1278 strncpy(p, q, n);
1279 p[n] = '\n';
1280 p[n+1] = '\0';
1281 }
1282 free(q);
1283 RESTORE_LOCALE(saved_locale)
1284 return p;
1285}
1286
1287
1288/* Initialize the module */
1289
1290PyDoc_STRVAR(doc_module,
1291"Importing this module enables command line editing using GNU readline.");
1292
1293#ifdef __APPLE__
1294PyDoc_STRVAR(doc_module_le,
1295"Importing this module enables command line editing using libedit readline.");
1296#endif /* __APPLE__ */
1297
1298PyMODINIT_FUNC
1299initline_input(void)
1300{
1301 PyObject *m;
1302
1303#ifdef __APPLE__
1304 if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1305 using_libedit_emulation = 1;
1306 }
1307
1308 if (using_libedit_emulation)
1309 m = Py_InitModule4("line_input", readline_methods, doc_module_le,
1310 (PyObject *)NULL, PYTHON_API_VERSION);
1311 else
1312
1313#endif /* __APPLE__ */
1314
1315 m = Py_InitModule4("line_input", readline_methods, doc_module,
1316 (PyObject *)NULL, PYTHON_API_VERSION);
1317 if (m == NULL)
1318 return;
1319
1320 PyOS_ReadlineFunctionPointer = call_readline;
1321 setup_readline();
1322
1323 PyModule_AddIntConstant(m, "_READLINE_VERSION", RL_READLINE_VERSION);
1324 PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION", rl_readline_version);
1325}