OILS / pyext / line_input.c View on Github | oils.pub

1805 lines, 1085 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 int binding_result;
119
120 if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
121 return NULL;
122 /* Make a copy -- rl_parse_and_bind() modifies its argument */
123 /* Bernard Herzog */
124 copy = malloc(1 + strlen(s));
125 if (copy == NULL)
126 return PyErr_NoMemory();
127 strcpy(copy, s);
128
129 binding_result = rl_parse_and_bind(copy);
130 free(copy); /* Free the copy */
131
132 if (binding_result != 0) {
133 PyErr_Format(PyExc_ValueError, "'%s': invalid binding", s);
134 return NULL;
135 }
136
137 Py_RETURN_NONE;
138}
139
140PyDoc_STRVAR(doc_parse_and_bind,
141"parse_and_bind(string) -> None\n\
142Bind a key sequence to a readline function (or a variable to a value).");
143
144
145
146/* Exported function to parse a readline init file */
147
148static PyObject *
149read_init_file(PyObject *self, PyObject *args)
150{
151 char *s = NULL;
152 if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
153 return NULL;
154 errno = rl_read_init_file(s);
155 if (errno)
156 return PyErr_SetFromErrno(PyExc_IOError);
157 Py_RETURN_NONE;
158}
159
160PyDoc_STRVAR(doc_read_init_file,
161"read_init_file([filename]) -> None\n\
162Execute a readline initialization file.\n\
163The default filename is the last filename used.");
164
165
166/* Exported function to load a readline history file */
167
168static PyObject *
169read_history_file(PyObject *self, PyObject *args)
170{
171 char *s = NULL;
172 if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
173 return NULL;
174 errno = read_history(s);
175 if (errno)
176 return PyErr_SetFromErrno(PyExc_IOError);
177 Py_RETURN_NONE;
178}
179
180static int _history_length = -1; /* do not truncate history by default */
181PyDoc_STRVAR(doc_read_history_file,
182"read_history_file([filename]) -> None\n\
183Load a readline history file.\n\
184The default filename is ~/.history.");
185
186
187/* Exported function to save a readline history file */
188
189static PyObject *
190write_history_file(PyObject *self, PyObject *args)
191{
192 char *s = NULL;
193 if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
194 return NULL;
195 errno = write_history(s);
196 if (!errno && _history_length >= 0)
197 history_truncate_file(s, _history_length);
198 if (errno)
199 return PyErr_SetFromErrno(PyExc_IOError);
200 Py_RETURN_NONE;
201}
202
203PyDoc_STRVAR(doc_write_history_file,
204"write_history_file([filename]) -> None\n\
205Save a readline history file.\n\
206The default filename is ~/.history.");
207
208
209/* Set history length */
210
211static PyObject*
212set_history_length(PyObject *self, PyObject *args)
213{
214 int length = _history_length;
215 if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
216 return NULL;
217 _history_length = length;
218 Py_RETURN_NONE;
219}
220
221PyDoc_STRVAR(set_history_length_doc,
222"set_history_length(length) -> None\n\
223set the maximal number of lines which will be written to\n\
224the history file. A negative length is used to inhibit\n\
225history truncation.");
226
227
228/* Get history length */
229
230static PyObject*
231get_history_length(PyObject *self, PyObject *noarg)
232{
233 return PyInt_FromLong(_history_length);
234}
235
236PyDoc_STRVAR(get_history_length_doc,
237"get_history_length() -> int\n\
238return the maximum number of lines that will be written to\n\
239the history file.");
240
241
242/* Generic hook function setter */
243
244static PyObject *
245set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
246{
247 PyObject *function = Py_None;
248 char buf[80];
249 PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
250 if (!PyArg_ParseTuple(args, buf, &function))
251 return NULL;
252 if (function == Py_None) {
253 Py_CLEAR(*hook_var);
254 }
255 else if (PyCallable_Check(function)) {
256 PyObject *tmp = *hook_var;
257 Py_INCREF(function);
258 *hook_var = function;
259 Py_XDECREF(tmp);
260 }
261 else {
262 PyOS_snprintf(buf, sizeof(buf),
263 "set_%.50s(func): argument not callable",
264 funcname);
265 PyErr_SetString(PyExc_TypeError, buf);
266 return NULL;
267 }
268 Py_RETURN_NONE;
269}
270
271
272/* Exported functions to specify hook functions in Python */
273
274static PyObject *completion_display_matches_hook = NULL;
275static PyObject *startup_hook = NULL;
276static PyObject *bind_shell_command_hook = NULL;
277
278#ifdef HAVE_RL_PRE_INPUT_HOOK
279static PyObject *pre_input_hook = NULL;
280#endif
281
282static PyObject *
283set_completion_display_matches_hook(PyObject *self, PyObject *args)
284{
285 PyObject *result = set_hook("completion_display_matches_hook",
286 &completion_display_matches_hook, args);
287#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
288 /* We cannot set this hook globally, since it replaces the
289 default completion display. */
290 rl_completion_display_matches_hook =
291 completion_display_matches_hook ?
292#if defined(_RL_FUNCTION_TYPEDEF)
293 (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
294#else
295 (VFunction *)on_completion_display_matches_hook : 0;
296#endif
297#endif
298 return result;
299
300}
301
302PyDoc_STRVAR(doc_set_completion_display_matches_hook,
303"set_completion_display_matches_hook([function]) -> None\n\
304Set or remove the completion display function.\n\
305The function is called as\n\
306 function(substitution, [matches], longest_match_length)\n\
307once each time matches need to be displayed.");
308
309static PyObject *
310set_startup_hook(PyObject *self, PyObject *args)
311{
312 return set_hook("startup_hook", &startup_hook, args);
313}
314
315PyDoc_STRVAR(doc_set_startup_hook,
316"set_startup_hook([function]) -> None\n\
317Set or remove the function invoked by the rl_startup_hook callback.\n\
318The function is called with no arguments just\n\
319before readline prints the first prompt.");
320
321
322#ifdef HAVE_RL_PRE_INPUT_HOOK
323
324/* Set pre-input hook */
325
326static PyObject *
327set_pre_input_hook(PyObject *self, PyObject *args)
328{
329 return set_hook("pre_input_hook", &pre_input_hook, args);
330}
331
332PyDoc_STRVAR(doc_set_pre_input_hook,
333"set_pre_input_hook([function]) -> None\n\
334Set or remove the function invoked by the rl_pre_input_hook callback.\n\
335The function is called with no arguments after the first prompt\n\
336has been printed and just before readline starts reading input\n\
337characters.");
338
339#endif
340
341
342/* Exported function to specify a word completer in Python */
343
344static PyObject *completer = NULL;
345
346static PyObject *begidx = NULL;
347static PyObject *endidx = NULL;
348
349
350/* Get the completion type for the scope of the tab-completion */
351static PyObject *
352get_completion_type(PyObject *self, PyObject *noarg)
353{
354 return PyInt_FromLong(rl_completion_type);
355}
356
357PyDoc_STRVAR(doc_get_completion_type,
358"get_completion_type() -> int\n\
359Get the type of completion being attempted.");
360
361
362/* Set bind -x Python command hook */
363
364static PyObject *
365set_bind_shell_command_hook(PyObject *self, PyObject *args)
366{
367 return set_hook("bind_shell_command_hook", &bind_shell_command_hook, args);
368}
369
370PyDoc_STRVAR(doc_set_bind_shell_command_hook,
371"set_bind_shell_command_hook([function]) -> None\n\
372Set or remove the function invoked by the rl_bind_keyseq_in_map callback.\n\
373The function is called with three arguments: the string to parse and evaluate,\n\
374the contents of the readline buffer to put in the READLINE_LINE env var,\n\
375and the int of the cursor's point in the buffer to put in READLINE_POINT.\n\
376It must return the READLINE_* vars in a tuple.");
377
378
379/* Get the beginning index for the scope of the tab-completion */
380
381static PyObject *
382get_begidx(PyObject *self, PyObject *noarg)
383{
384 Py_INCREF(begidx);
385 return begidx;
386}
387
388PyDoc_STRVAR(doc_get_begidx,
389"get_begidx() -> int\n\
390get the beginning index of the completion scope");
391
392
393/* Get the ending index for the scope of the tab-completion */
394
395static PyObject *
396get_endidx(PyObject *self, PyObject *noarg)
397{
398 Py_INCREF(endidx);
399 return endidx;
400}
401
402PyDoc_STRVAR(doc_get_endidx,
403"get_endidx() -> int\n\
404get the ending index of the completion scope");
405
406
407/* Set the tab-completion word-delimiters that readline uses */
408
409static PyObject *
410set_completer_delims(PyObject *self, PyObject *args)
411{
412 char *break_chars;
413
414 if (!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
415 return NULL;
416 }
417 /* Keep a reference to the allocated memory in the module state in case
418 some other module modifies rl_completer_word_break_characters
419 (see issue #17289). */
420 break_chars = strdup(break_chars);
421 if (break_chars) {
422 free(completer_word_break_characters);
423 completer_word_break_characters = break_chars;
424 rl_completer_word_break_characters = break_chars;
425 Py_RETURN_NONE;
426 }
427 else
428 return PyErr_NoMemory();
429}
430
431PyDoc_STRVAR(doc_set_completer_delims,
432"set_completer_delims(string) -> None\n\
433set the word delimiters for completion");
434
435/* _py_free_history_entry: Utility function to free a history entry. */
436
437#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0500
438
439/* Readline version >= 5.0 introduced a timestamp field into the history entry
440 structure; this needs to be freed to avoid a memory leak. This version of
441 readline also introduced the handy 'free_history_entry' function, which
442 takes care of the timestamp. */
443
444static void
445_py_free_history_entry(HIST_ENTRY *entry)
446{
447 histdata_t data = free_history_entry(entry);
448 free(data);
449}
450
451#else
452
453/* No free_history_entry function; free everything manually. */
454
455static void
456_py_free_history_entry(HIST_ENTRY *entry)
457{
458 if (entry->line)
459 free((void *)entry->line);
460 if (entry->data)
461 free(entry->data);
462 free(entry);
463}
464
465#endif
466
467static PyObject *
468py_remove_history(PyObject *self, PyObject *args)
469{
470 int entry_number;
471 HIST_ENTRY *entry;
472
473 if (!PyArg_ParseTuple(args, "i:remove_history_item", &entry_number))
474 return NULL;
475 if (entry_number < 0) {
476 PyErr_SetString(PyExc_ValueError,
477 "History index cannot be negative");
478 return NULL;
479 }
480 entry = remove_history(entry_number);
481 if (!entry) {
482 PyErr_Format(PyExc_ValueError,
483 "No history item at position %d",
484 entry_number);
485 return NULL;
486 }
487 /* free memory allocated for the history entry */
488 _py_free_history_entry(entry);
489 Py_RETURN_NONE;
490}
491
492PyDoc_STRVAR(doc_remove_history,
493"remove_history_item(pos) -> None\n\
494remove history item given by its position");
495
496static PyObject *
497py_replace_history(PyObject *self, PyObject *args)
498{
499 int entry_number;
500 char *line;
501 HIST_ENTRY *old_entry;
502
503 if (!PyArg_ParseTuple(args, "is:replace_history_item", &entry_number,
504 &line)) {
505 return NULL;
506 }
507 if (entry_number < 0) {
508 PyErr_SetString(PyExc_ValueError,
509 "History index cannot be negative");
510 return NULL;
511 }
512 old_entry = replace_history_entry(entry_number, line, (void *)NULL);
513 if (!old_entry) {
514 PyErr_Format(PyExc_ValueError,
515 "No history item at position %d",
516 entry_number);
517 return NULL;
518 }
519 /* free memory allocated for the old history entry */
520 _py_free_history_entry(old_entry);
521 Py_RETURN_NONE;
522}
523
524PyDoc_STRVAR(doc_replace_history,
525"replace_history_item(pos, line) -> None\n\
526replaces history item given by its position with contents of line");
527
528/* Add a line to the history buffer */
529
530static PyObject *
531py_add_history(PyObject *self, PyObject *args)
532{
533 char *line;
534
535 if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
536 return NULL;
537 }
538 add_history(line);
539 Py_RETURN_NONE;
540}
541
542PyDoc_STRVAR(doc_add_history,
543"add_history(string) -> None\n\
544add an item to the history buffer");
545
546
547/* Get the tab-completion word-delimiters that readline uses */
548
549static PyObject *
550get_completer_delims(PyObject *self, PyObject *noarg)
551{
552 return PyString_FromString(rl_completer_word_break_characters);
553}
554
555PyDoc_STRVAR(doc_get_completer_delims,
556"get_completer_delims() -> string\n\
557get the word delimiters for completion");
558
559
560/* Set the completer function */
561
562static PyObject *
563set_completer(PyObject *self, PyObject *args)
564{
565 return set_hook("completer", &completer, args);
566}
567
568PyDoc_STRVAR(doc_set_completer,
569"set_completer([function]) -> None\n\
570Set or remove the completer function.\n\
571The function is called as function(text, state),\n\
572for state in 0, 1, 2, ..., until it returns a non-string.\n\
573It should return the next possible completion starting with 'text'.");
574
575
576static PyObject *
577get_completer(PyObject *self, PyObject *noargs)
578{
579 if (completer == NULL) {
580 Py_RETURN_NONE;
581 }
582 Py_INCREF(completer);
583 return completer;
584}
585
586PyDoc_STRVAR(doc_get_completer,
587"get_completer() -> function\n\
588\n\
589Returns current completer function.");
590
591/* Private function to get current length of history. XXX It may be
592 * possible to replace this with a direct use of history_length instead,
593 * but it's not clear whether BSD's libedit keeps history_length up to date.
594 * See issue #8065.*/
595
596static int
597_py_get_history_length(void)
598{
599 HISTORY_STATE *hist_st = history_get_history_state();
600 int length = hist_st->length;
601 /* the history docs don't say so, but the address of hist_st changes each
602 time history_get_history_state is called which makes me think it's
603 freshly malloc'd memory... on the other hand, the address of the last
604 line stays the same as long as history isn't extended, so it appears to
605 be malloc'd but managed by the history package... */
606 free(hist_st);
607 return length;
608}
609
610/* Exported function to get any element of history */
611
612static PyObject *
613get_history_item(PyObject *self, PyObject *args)
614{
615 int idx = 0;
616 HIST_ENTRY *hist_ent;
617
618 if (!PyArg_ParseTuple(args, "i:get_history_item", &idx))
619 return NULL;
620#ifdef __APPLE__
621 if (using_libedit_emulation) {
622 /* Older versions of libedit's readline emulation
623 * use 0-based indexes, while readline and newer
624 * versions of libedit use 1-based indexes.
625 */
626 int length = _py_get_history_length();
627
628 idx = idx - 1 + libedit_history_start;
629
630 /*
631 * Apple's readline emulation crashes when
632 * the index is out of range, therefore
633 * test for that and fail gracefully.
634 */
635 if (idx < (0 + libedit_history_start)
636 || idx >= (length + libedit_history_start)) {
637 Py_RETURN_NONE;
638 }
639 }
640#endif /* __APPLE__ */
641 if ((hist_ent = history_get(idx)))
642 return PyString_FromString(hist_ent->line);
643 else {
644 Py_RETURN_NONE;
645 }
646}
647
648PyDoc_STRVAR(doc_get_history_item,
649"get_history_item() -> string\n\
650return the current contents of history item at index.");
651
652
653/* Exported function to get current length of history */
654
655static PyObject *
656get_current_history_length(PyObject *self, PyObject *noarg)
657{
658 return PyInt_FromLong((long)_py_get_history_length());
659}
660
661PyDoc_STRVAR(doc_get_current_history_length,
662"get_current_history_length() -> integer\n\
663return the current (not the maximum) length of history.");
664
665
666/* Exported function to read the current line buffer */
667
668static PyObject *
669get_line_buffer(PyObject *self, PyObject *noarg)
670{
671 return PyString_FromString(rl_line_buffer);
672}
673
674PyDoc_STRVAR(doc_get_line_buffer,
675"get_line_buffer() -> string\n\
676return the current contents of the line buffer.");
677
678
679#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
680
681/* Exported function to clear the current history */
682
683static PyObject *
684py_clear_history(PyObject *self, PyObject *noarg)
685{
686 clear_history();
687 Py_RETURN_NONE;
688}
689
690PyDoc_STRVAR(doc_clear_history,
691"clear_history() -> None\n\
692Clear the current readline history.");
693#endif
694
695/* Added for OSH. We need to call this in our SIGWINCH handler so global
696 * variables in readline get updated. */
697static PyObject *
698py_resize_terminal(PyObject *self, PyObject *noarg)
699{
700 rl_resize_terminal();
701 Py_RETURN_NONE;
702}
703
704/* Exported function to insert text into the line buffer */
705
706static PyObject *
707insert_text(PyObject *self, PyObject *args)
708{
709 char *s;
710 if (!PyArg_ParseTuple(args, "s:insert_text", &s))
711 return NULL;
712 rl_insert_text(s);
713 Py_RETURN_NONE;
714}
715
716PyDoc_STRVAR(doc_insert_text,
717"insert_text(string) -> None\n\
718Insert text into the line buffer at the cursor position.");
719
720
721/* Redisplay the line buffer */
722
723static PyObject *
724redisplay(PyObject *self, PyObject *noarg)
725{
726 rl_redisplay();
727 Py_RETURN_NONE;
728}
729
730PyDoc_STRVAR(doc_redisplay,
731"redisplay() -> None\n\
732Change what's displayed on the screen to reflect the current\n\
733contents of the line buffer.");
734
735
736/* Functions added to implement the 'bind' builtin in OSH */
737
738/* -x/-X command keymaps */
739static Keymap emacs_cmd_map;
740static Keymap vi_insert_cmd_map;
741static Keymap vi_movement_cmd_map;
742
743/*
744 These forcibly cast between a Keymap* and a rl_command_func_t*. Readline
745 uses an additional `.type` field to keep track of the pointer's true type.
746*/
747#define RL_KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)(data)
748#define RL_FUNCTION_TO_KEYMAP(map, key) (Keymap)(map[key].function)
749
750static void
751_init_command_maps(void)
752{
753 emacs_cmd_map = rl_make_bare_keymap();
754 vi_insert_cmd_map = rl_make_bare_keymap();
755 vi_movement_cmd_map = rl_make_bare_keymap();
756
757 /* Ensure that Esc- and Ctrl-X are also keymaps */
758 emacs_cmd_map[CTRL('X')].type = ISKMAP;
759 emacs_cmd_map[CTRL('X')].function = RL_KEYMAP_TO_FUNCTION(rl_make_bare_keymap());
760 emacs_cmd_map[ESC].type = ISKMAP;
761 emacs_cmd_map[ESC].function = RL_KEYMAP_TO_FUNCTION(rl_make_bare_keymap());
762}
763
764static Keymap
765_get_associated_cmd_map(Keymap kmap)
766{
767 if (emacs_cmd_map == NULL)
768 _init_command_maps();
769
770 if (kmap == emacs_standard_keymap)
771 return emacs_cmd_map;
772 else if (kmap == vi_insertion_keymap)
773 return vi_insert_cmd_map;
774 else if (kmap == vi_movement_keymap)
775 return vi_movement_cmd_map;
776 else if (kmap == emacs_meta_keymap)
777 return (RL_FUNCTION_TO_KEYMAP(emacs_cmd_map, ESC));
778 else if (kmap == emacs_ctlx_keymap)
779 return (RL_FUNCTION_TO_KEYMAP(emacs_cmd_map, CTRL('X')));
780
781 return (Keymap) NULL;
782}
783
784/* List binding functions */
785static PyObject*
786list_funmap_names(PyObject *self, PyObject *args)
787{
788 rl_list_funmap_names();
789 Py_RETURN_NONE;
790}
791
792PyDoc_STRVAR(doc_list_funmap_names,
793"list_funmap_names() -> None\n\
794Print all of the available readline functions.");
795
796/* Print readline functions and their bindings */
797
798static PyObject*
799function_dumper(PyObject *self, PyObject *args)
800{
801 int print_readably;
802
803 if (!PyArg_ParseTuple(args, "i:function_dumper", &print_readably))
804 return NULL;
805
806 rl_function_dumper(print_readably);
807 Py_RETURN_NONE;
808}
809
810PyDoc_STRVAR(doc_list_function_dumper,
811"function_dumper(bool) -> None\n\
812Print all readline functions and their bindings.");
813
814/* Print macros, their bindings, and their string outputs */
815
816static PyObject*
817macro_dumper(PyObject *self, PyObject *args)
818{
819 int print_readably;
820
821 if (!PyArg_ParseTuple(args, "i:macro_dumper", &print_readably))
822 return NULL;
823
824 rl_macro_dumper(print_readably);
825 Py_RETURN_NONE;
826}
827
828PyDoc_STRVAR(doc_list_macro_dumper,
829"macro_dumper(bool) -> None\n\
830Print all readline sequences bound to macros and the strings they output.");
831
832
833/* List readline variables */
834
835static PyObject*
836variable_dumper(PyObject *self, PyObject *args)
837{
838 int print_readably;
839
840 if (!PyArg_ParseTuple(args, "i:variable_dumper", &print_readably))
841 return NULL;
842
843 rl_variable_dumper(print_readably);
844 Py_RETURN_NONE;
845}
846
847PyDoc_STRVAR(doc_list_variable_dumper,
848"variable_dumper(bool) -> None\n\
849List readline variables and their values.");
850
851
852/* Query bindings for a function name */
853
854// readline returns null-terminated string arrays
855void _strvec_dispose(char **strvec) {
856 register int i;
857
858 if (strvec == NULL)
859 return;
860
861 for (i = 0; strvec[i]; i++) {
862 free(strvec[i]);
863 }
864
865 free(strvec);
866}
867
868// Nicely prints a strvec with commas and an and
869// like '"foo", "bar", and "moop"'
870void _pprint_strvec_list(char **strvec) {
871 int i;
872
873 for (i = 0; strvec[i]; i++) {
874 printf("\"%s\"", strvec[i]);
875 if (strvec[i + 1]) {
876 printf(", ");
877 if (!strvec[i + 2])
878 printf("and ");
879 }
880 }
881}
882
883/*
884NB: readline (and bash) have a bug where they don't see certain keyseqs, even
885if the bindings work. E.g., if you bind a number key like "\C-7", it will be
886bound, but reporting code like query_bindings and function_dumper won't count it.
887*/
888
889static PyObject*
890query_bindings(PyObject *self, PyObject *args)
891{
892 char *fn_name;
893 rl_command_func_t *cmd_fn;
894 char **key_seqs;
895
896 if (!PyArg_ParseTuple(args, "s:query_bindings", &fn_name))
897 return NULL;
898
899 cmd_fn = rl_named_function(fn_name);
900
901 if (cmd_fn == NULL) {
902 PyErr_Format(PyExc_ValueError, "`%s': unknown function name", fn_name);
903 return NULL;
904 }
905
906 key_seqs = rl_invoking_keyseqs(cmd_fn);
907
908 if (!key_seqs) {
909 // print to stdout, but return an error
910 printf("%s is not bound to any keys.\n", fn_name);
911 PyErr_SetNone(PyExc_ValueError);
912 return NULL;
913 }
914
915 printf("%s can be invoked via ", fn_name);
916 _pprint_strvec_list(key_seqs);
917 printf(".\n");
918
919 _strvec_dispose(key_seqs);
920
921 Py_RETURN_NONE;
922}
923
924PyDoc_STRVAR(doc_query_bindings,
925"query_bindings(str) -> None\n\
926Query bindings to see what's bound to a given function.");
927
928
929static PyObject*
930unbind_rl_function(PyObject *self, PyObject *args)
931{
932 char *fn_name;
933 rl_command_func_t *cmd_fn;
934
935 if (!PyArg_ParseTuple(args, "s:unbind_rl_function", &fn_name))
936 return NULL;
937
938 cmd_fn = rl_named_function(fn_name);
939 if (cmd_fn == NULL) {
940 PyErr_Format(PyExc_ValueError, "`%s': unknown function name", fn_name);
941 return NULL;
942 }
943
944 rl_unbind_function_in_map(cmd_fn, rl_get_keymap());
945 Py_RETURN_NONE;
946}
947
948PyDoc_STRVAR(doc_unbind_rl_function,
949"unbind_rl_function(function_name) -> None\n\
950Unbind all keys bound to the named readline function in the current keymap.");
951
952
953static PyObject*
954print_shell_cmd_map(PyObject *self, PyObject *noarg)
955{
956 Keymap curr_map, cmd_map;
957
958 curr_map = rl_get_keymap();
959 cmd_map = _get_associated_cmd_map(curr_map);
960
961 if (cmd_map == NULL) {
962 PyErr_SetString(PyExc_ValueError, "Could not get shell command map for current keymap");
963 return NULL;
964 }
965
966 rl_set_keymap(cmd_map);
967 rl_macro_dumper(1);
968 rl_set_keymap(curr_map);
969
970 Py_RETURN_NONE;
971}
972
973PyDoc_STRVAR(doc_print_shell_cmd_map,
974"print_shell_cmd_map() -> None\n\
975Print all bindings for shell commands in the current keymap.");
976
977
978/* Support fns for bind -x */
979
980static void
981update_line_if_needed(char *possible_new_line)
982{
983 if (strcmp(possible_new_line, rl_line_buffer) != 0) {
984 rl_point = rl_end;
985
986 rl_add_undo(UNDO_BEGIN, 0, 0, 0);
987 rl_delete_text(0, rl_point);
988 rl_point = 0;
989 rl_end = 0;
990 rl_mark = 0;
991 rl_insert_text(possible_new_line);
992 rl_add_undo(UNDO_END, 0, 0, 0);
993 }
994}
995
996static void
997update_cursor_if_needed(int post_point) {
998 if (post_point != rl_point) {
999 rl_point = post_point;
1000 if (rl_point > rl_end)
1001 rl_point = rl_end;
1002 else if (rl_point < 0)
1003 rl_point = 0;
1004 }
1005}
1006
1007static char*
1008get_bound_command(Keymap cmd_map) {
1009 int type;
1010 char *cmd = (char *)rl_function_of_keyseq(rl_executing_keyseq, cmd_map, &type);
1011
1012 if (cmd == NULL || type != ISMACR) {
1013 PyErr_SetString(PyExc_RuntimeError,
1014 "Cannot find shell command bound to this key sequence");
1015 return NULL;
1016 }
1017
1018 return cmd;
1019}
1020
1021static void
1022clear_current_line(int use_ce) {
1023 if (use_ce) {
1024 rl_clear_visible_line();
1025 fflush(rl_outstream);
1026 } else {
1027 rl_crlf();
1028 }
1029}
1030
1031
1032/* Main entry point for executing shell commands. Based on bash_execute_unix_command */
1033
1034static int
1035on_bind_shell_command_hook(int count /* unused */, int key /* unused */) {
1036 char *cmd;
1037 int use_ce;
1038 Keymap cmd_map;
1039 PyObject *r = NULL;
1040 #ifdef WITH_THREAD
1041 PyGILState_STATE gilstate;
1042 #endif
1043 int cmd_return_code;
1044 char *post_line_buffer;
1045 int post_point;
1046 int result;
1047
1048#ifdef WITH_THREAD
1049 gilstate = PyGILState_Ensure();
1050#endif
1051
1052 if (bind_shell_command_hook == NULL) {
1053 PyErr_SetString(PyExc_RuntimeError, "No bind_shell_command_hook set");
1054 return 1;
1055 }
1056
1057 cmd_map = _get_associated_cmd_map(rl_get_keymap());
1058 cmd = get_bound_command(cmd_map);
1059 if (!cmd) {
1060 PyErr_SetString(PyExc_RuntimeError, "on_bind_shell_command_hook: Cannot find shell command in keymap");
1061 rl_crlf();
1062 rl_forced_update_display();
1063 return 1;
1064 }
1065
1066 use_ce = rl_get_termcap("ce") != NULL;
1067 clear_current_line(use_ce);
1068
1069 r = PyObject_CallFunction(bind_shell_command_hook,
1070 "ssi", cmd, rl_line_buffer, rl_point);
1071 if (r == NULL) {
1072 PyErr_Print();
1073 result = 1;
1074 goto cleanup;
1075 }
1076 if (!PyArg_ParseTuple(r, "isi", &cmd_return_code, &post_line_buffer, &post_point)) {
1077 PyErr_SetString(PyExc_ValueError, "Expected (int, str, int) tuple from bind_shell_command_hook");
1078 result = 1;
1079 goto cleanup;
1080 }
1081
1082 update_line_if_needed(post_line_buffer);
1083 update_cursor_if_needed(post_point);
1084
1085
1086 /* Redraw the prompt */
1087 if (use_ce) // need to handle a `&& return code != 124` somehow
1088 rl_redraw_prompt_last_line();
1089 else
1090 rl_forced_update_display();
1091
1092 result = 0;
1093
1094cleanup:
1095 Py_XDECREF(r);
1096#ifdef WITH_THREAD
1097 PyGILState_Release(gilstate);
1098#endif
1099
1100done:
1101 return result;
1102}
1103
1104
1105/* Binds a key sequence to arbitrary shell code, not readline fns */
1106static PyObject*
1107bind_shell_command(PyObject *self, PyObject *args) {
1108 const char *kseq;
1109 const char *cmd, *cparam;
1110 Keymap kmap, cmd_xmap;
1111
1112 if (!PyArg_ParseTuple(args, "ss:bind_shell_command", &kseq, &cparam)) {
1113 return NULL;
1114 }
1115
1116 /* readline will own the cmd string, so we need to make a copy */
1117 cmd = strdup(cparam);
1118 if (cmd == NULL) {
1119 return PyErr_NoMemory();
1120 }
1121
1122 kmap = rl_get_keymap();
1123 cmd_xmap = _get_associated_cmd_map(kmap);
1124
1125
1126 if (rl_generic_bind(ISMACR, kseq, (char *)cmd, cmd_xmap) != 0
1127 || rl_bind_keyseq_in_map (kseq, on_bind_shell_command_hook, kmap) != 0) {
1128 PyErr_Format(PyExc_RuntimeError, "Failed to bind key sequence '%s' to command '%s'", kseq, cmd);
1129 free(cmd);
1130 return NULL;
1131 }
1132
1133 Py_RETURN_NONE;
1134}
1135
1136PyDoc_STRVAR(doc_bind_shell_command,
1137"bind_shell_command(key_sequence, command) -> None\n\
1138Bind a key sequence to a shell command in the current keymap.");
1139
1140
1141/* Remove all bindings for a given keyseq */
1142
1143int
1144_unbind_shell_cmd(char *keyseq)
1145{
1146/* Unbind a key sequence from the current keymap's associated shell command map. */
1147Keymap cmd_map;
1148
1149 cmd_map = _get_associated_cmd_map(rl_get_keymap());
1150
1151 if (rl_bind_keyseq_in_map(keyseq, (rl_command_func_t *)NULL, cmd_map) != 0) {
1152 PyErr_Format(PyExc_ValueError, "'%s': can't unbind from shell command keymap", keyseq);
1153 return 0;
1154 }
1155
1156 return 1;
1157}
1158
1159static PyObject*
1160unbind_keyseq(PyObject *self, PyObject *args)
1161{
1162 char *seq, *keyseq;
1163 int kslen, type;
1164 rl_command_func_t *fn;
1165
1166 if (!PyArg_ParseTuple(args, "s:unbind_keyseq", &seq))
1167 return NULL;
1168
1169 /* Parse and check validity of keyseq */
1170 keyseq = (char *)malloc((2 * strlen(seq)) + 1);
1171 if (rl_translate_keyseq(seq, keyseq, &kslen) != 0) {
1172 free(keyseq);
1173 PyErr_Format(PyExc_ValueError, "'%s': invalid key sequence", seq);
1174 Py_RETURN_NONE;
1175 }
1176
1177 fn = rl_function_of_keyseq(keyseq, (Keymap)NULL, &type);
1178 free(keyseq);
1179
1180 if (!fn) {
1181 Py_RETURN_NONE;
1182 }
1183
1184 if (type == ISKMAP) {
1185 fn = ((Keymap)fn)[ANYOTHERKEY].function;
1186 }
1187
1188 if (rl_bind_keyseq(seq, (rl_command_func_t *)NULL) != 0) {
1189 PyErr_Format(PyExc_ValueError, "'%s': cannot unbind", seq);
1190 Py_RETURN_NONE;
1191 }
1192
1193 if (fn == on_bind_shell_command_hook) {
1194 _unbind_shell_cmd (seq);
1195 }
1196
1197 Py_RETURN_NONE;
1198}
1199
1200PyDoc_STRVAR(doc_unbind_keyseq,
1201"unbind_keyseq(sequence) -> None\n\
1202Unbind a key sequence from the current keymap.");
1203
1204
1205
1206/* Keymap toggling code */
1207static Keymap orig_keymap = NULL;
1208
1209static PyObject*
1210use_temp_keymap(PyObject *self, PyObject *args)
1211{
1212 char *keymap_name;
1213 Keymap new_keymap;
1214
1215 if (!PyArg_ParseTuple(args, "s:use_temp_keymap", &keymap_name))
1216 return NULL;
1217
1218 new_keymap = rl_get_keymap_by_name(keymap_name);
1219 if (new_keymap == NULL) {
1220 PyErr_Format(PyExc_ValueError, "`%s': unknown keymap name", keymap_name);
1221 return NULL;
1222 }
1223
1224 orig_keymap = rl_get_keymap();
1225 rl_set_keymap(new_keymap);
1226
1227 Py_RETURN_NONE;
1228}
1229
1230PyDoc_STRVAR(doc_use_temp_keymap,
1231"use_temp_keymap(keymap_name) -> None\n\
1232Temporarily switch to named keymap, saving the current one.");
1233
1234static PyObject*
1235restore_orig_keymap(PyObject *self, PyObject *args)
1236{
1237 if (orig_keymap != NULL) {
1238 rl_set_keymap(orig_keymap);
1239 orig_keymap = NULL;
1240 }
1241
1242 Py_RETURN_NONE;
1243}
1244
1245PyDoc_STRVAR(doc_restore_orig_keymap,
1246"restore_orig_keymap() -> None\n\
1247Restore the previously saved keymap if one exists.");
1248
1249/* Table of functions exported by the module */
1250
1251static struct PyMethodDef readline_methods[] = {
1252 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
1253 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
1254 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
1255 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
1256 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
1257 {"read_history_file", read_history_file,
1258 METH_VARARGS, doc_read_history_file},
1259 {"write_history_file", write_history_file,
1260 METH_VARARGS, doc_write_history_file},
1261 {"get_history_item", get_history_item,
1262 METH_VARARGS, doc_get_history_item},
1263 {"get_current_history_length", (PyCFunction)get_current_history_length,
1264 METH_NOARGS, doc_get_current_history_length},
1265 {"set_history_length", set_history_length,
1266 METH_VARARGS, set_history_length_doc},
1267 {"get_history_length", get_history_length,
1268 METH_NOARGS, get_history_length_doc},
1269 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
1270 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
1271 {"get_completion_type", get_completion_type,
1272 METH_NOARGS, doc_get_completion_type},
1273 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
1274 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
1275
1276 {"set_completer_delims", set_completer_delims,
1277 METH_VARARGS, doc_set_completer_delims},
1278 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
1279 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
1280 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
1281 {"get_completer_delims", get_completer_delims,
1282 METH_NOARGS, doc_get_completer_delims},
1283
1284 {"set_completion_display_matches_hook", set_completion_display_matches_hook,
1285 METH_VARARGS, doc_set_completion_display_matches_hook},
1286 {"set_startup_hook", set_startup_hook,
1287 METH_VARARGS, doc_set_startup_hook},
1288 {"set_pre_input_hook", set_pre_input_hook,
1289 METH_VARARGS, doc_set_pre_input_hook},
1290 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
1291 {"resize_terminal", py_resize_terminal, METH_NOARGS, ""},
1292
1293 /* Functions added to implement the 'bind' builtin in OSH */
1294 {"list_funmap_names", list_funmap_names, METH_NOARGS, doc_list_funmap_names},
1295 {"function_dumper", function_dumper, METH_VARARGS, doc_list_function_dumper},
1296 {"macro_dumper", macro_dumper, METH_VARARGS, doc_list_macro_dumper},
1297 {"variable_dumper", variable_dumper, METH_VARARGS, doc_list_variable_dumper},
1298 {"query_bindings", query_bindings, METH_VARARGS, doc_query_bindings},
1299 {"unbind_rl_function", unbind_rl_function, METH_VARARGS, doc_unbind_rl_function},
1300 {"use_temp_keymap", use_temp_keymap, METH_VARARGS, doc_use_temp_keymap},
1301 {"restore_orig_keymap", restore_orig_keymap, METH_NOARGS, doc_restore_orig_keymap},
1302 {"print_shell_cmd_map", print_shell_cmd_map, METH_NOARGS, doc_print_shell_cmd_map},
1303 {"unbind_keyseq", unbind_keyseq, METH_VARARGS, doc_unbind_keyseq},
1304 {"bind_shell_command", bind_shell_command, METH_VARARGS, doc_bind_shell_command},
1305 {"set_bind_shell_command_hook", set_bind_shell_command_hook,
1306 METH_VARARGS, doc_set_bind_shell_command_hook},
1307 {0, 0}
1308};
1309
1310
1311/* C function to call the Python hooks. */
1312
1313static int
1314on_hook(PyObject *func)
1315{
1316 int result = 0;
1317 if (func != NULL) {
1318 PyObject *r;
1319#ifdef WITH_THREAD
1320 PyGILState_STATE gilstate = PyGILState_Ensure();
1321#endif
1322 r = PyObject_CallFunction(func, NULL);
1323 if (r == NULL)
1324 goto error;
1325 if (r == Py_None)
1326 result = 0;
1327 else {
1328 result = PyInt_AsLong(r);
1329 if (result == -1 && PyErr_Occurred())
1330 goto error;
1331 }
1332 Py_DECREF(r);
1333 goto done;
1334 error:
1335 PyErr_Clear();
1336 Py_XDECREF(r);
1337 done:
1338#ifdef WITH_THREAD
1339 PyGILState_Release(gilstate);
1340#endif
1341 return result;
1342 }
1343 return result;
1344}
1345
1346static int
1347#if defined(_RL_FUNCTION_TYPEDEF)
1348on_startup_hook(void)
1349#else
1350on_startup_hook()
1351#endif
1352{
1353 return on_hook(startup_hook);
1354}
1355
1356#ifdef HAVE_RL_PRE_INPUT_HOOK
1357static int
1358#if defined(_RL_FUNCTION_TYPEDEF)
1359on_pre_input_hook(void)
1360#else
1361on_pre_input_hook()
1362#endif
1363{
1364 return on_hook(pre_input_hook);
1365}
1366#endif
1367
1368
1369/* C function to call the Python completion_display_matches */
1370
1371#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
1372static void
1373on_completion_display_matches_hook(char **matches,
1374 int num_matches, int max_length)
1375{
1376 int i;
1377 PyObject *m=NULL, *s=NULL, *r=NULL;
1378#ifdef WITH_THREAD
1379 PyGILState_STATE gilstate = PyGILState_Ensure();
1380#endif
1381 m = PyList_New(num_matches);
1382 if (m == NULL)
1383 goto error;
1384 for (i = 0; i < num_matches; i++) {
1385 s = PyString_FromString(matches[i+1]);
1386 if (s == NULL)
1387 goto error;
1388 if (PyList_SetItem(m, i, s) == -1)
1389 goto error;
1390 }
1391
1392 r = PyObject_CallFunction(completion_display_matches_hook,
1393 "sOi", matches[0], m, max_length);
1394
1395 Py_DECREF(m); m=NULL;
1396
1397 if (r == NULL ||
1398 (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
1399 goto error;
1400 }
1401 Py_XDECREF(r); r=NULL;
1402
1403 if (0) {
1404 error:
1405 PyErr_Clear();
1406 Py_XDECREF(m);
1407 Py_XDECREF(r);
1408 }
1409#ifdef WITH_THREAD
1410 PyGILState_Release(gilstate);
1411#endif
1412}
1413
1414#endif
1415
1416#ifdef HAVE_RL_RESIZE_TERMINAL
1417static volatile sig_atomic_t sigwinch_received;
1418static PyOS_sighandler_t sigwinch_ohandler;
1419
1420static void
1421readline_sigwinch_handler(int signum)
1422{
1423 sigwinch_received = 1;
1424 if (sigwinch_ohandler &&
1425 sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
1426 sigwinch_ohandler(signum);
1427}
1428#endif
1429
1430/* C function to call the Python completer. */
1431
1432static char *
1433on_completion(const char *text, int state)
1434{
1435 char *result = NULL;
1436 if (completer != NULL) {
1437 PyObject *r;
1438#ifdef WITH_THREAD
1439 PyGILState_STATE gilstate = PyGILState_Ensure();
1440#endif
1441 rl_attempted_completion_over = 1;
1442 r = PyObject_CallFunction(completer, "si", text, state);
1443 if (r == NULL)
1444 goto error;
1445 if (r == Py_None) {
1446 result = NULL;
1447 }
1448 else {
1449 char *s = PyString_AsString(r);
1450 if (s == NULL)
1451 goto error;
1452 result = strdup(s);
1453 }
1454 Py_DECREF(r);
1455 goto done;
1456 error:
1457 PyErr_Clear();
1458 Py_XDECREF(r);
1459 done:
1460#ifdef WITH_THREAD
1461 PyGILState_Release(gilstate);
1462#endif
1463 return result;
1464 }
1465 return result;
1466}
1467
1468
1469/* A more flexible constructor that saves the "begidx" and "endidx"
1470 * before calling the normal completer */
1471
1472static char **
1473flex_complete(const char *text, int start, int end)
1474{
1475#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1476 rl_completion_append_character ='\0';
1477#endif
1478#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
1479 rl_completion_suppress_append = 0;
1480#endif
1481 Py_XDECREF(begidx);
1482 Py_XDECREF(endidx);
1483 begidx = PyInt_FromLong((long) start);
1484 endidx = PyInt_FromLong((long) end);
1485 return completion_matches(text, *on_completion);
1486}
1487
1488
1489/* Helper to initialize GNU readline properly. */
1490
1491static void
1492setup_readline(void)
1493{
1494#ifdef SAVE_LOCALE
1495 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1496 if (!saved_locale)
1497 Py_FatalError("not enough memory to save locale");
1498#endif
1499
1500#ifdef __APPLE__
1501 /* the libedit readline emulation resets key bindings etc
1502 * when calling rl_initialize. So call it upfront
1503 */
1504 if (using_libedit_emulation)
1505 rl_initialize();
1506
1507 /* Detect if libedit's readline emulation uses 0-based
1508 * indexing or 1-based indexing.
1509 */
1510 add_history("1");
1511 if (history_get(1) == NULL) {
1512 libedit_history_start = 0;
1513 } else {
1514 libedit_history_start = 1;
1515 }
1516 clear_history();
1517#endif /* __APPLE__ */
1518
1519 using_history();
1520
1521 rl_readline_name = "oils";
1522#if defined(PYOS_OS2) && defined(PYCC_GCC)
1523 /* Allow $if term= in .inputrc to work */
1524 rl_terminal_name = getenv("TERM");
1525#endif
1526 /* Force rebind of TAB to insert-tab */
1527 rl_bind_key('\t', rl_insert);
1528 /* Bind both ESC-TAB and ESC-ESC to the completion function */
1529 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1530 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
1531#ifdef HAVE_RL_RESIZE_TERMINAL
1532 /* Set up signal handler for window resize */
1533 sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1534#endif
1535 /* Set our hook functions */
1536 rl_startup_hook = on_startup_hook;
1537#ifdef HAVE_RL_PRE_INPUT_HOOK
1538 rl_pre_input_hook = on_pre_input_hook;
1539#endif
1540 /* Set our completion function */
1541 rl_attempted_completion_function = flex_complete;
1542 /* Set Python word break characters */
1543 completer_word_break_characters =
1544 rl_completer_word_break_characters =
1545 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1546 /* All nonalphanums except '.' */
1547
1548 begidx = PyInt_FromLong(0L);
1549 endidx = PyInt_FromLong(0L);
1550
1551#ifdef __APPLE__
1552 if (!using_libedit_emulation)
1553#endif
1554 {
1555 if (!isatty(STDOUT_FILENO)) {
1556 /* Issue #19884: stdout is not a terminal. Disable meta modifier
1557 keys to not write the ANSI sequence "\033[1034h" into stdout. On
1558 terminals supporting 8 bit characters like TERM=xterm-256color
1559 (which is now the default Fedora since Fedora 18), the meta key is
1560 used to enable support of 8 bit characters (ANSI sequence
1561 "\033[1034h").
1562
1563 With libedit, this call makes readline() crash. */
1564 rl_variable_bind ("enable-meta-key", "off");
1565 }
1566 }
1567
1568 /* Initialize (allows .inputrc to override)
1569 *
1570 * XXX: A bug in the readline-2.2 library causes a memory leak
1571 * inside this function. Nothing we can do about it.
1572 */
1573#ifdef __APPLE__
1574 if (using_libedit_emulation)
1575 rl_read_init_file(NULL);
1576 else
1577#endif /* __APPLE__ */
1578 rl_initialize();
1579
1580 RESTORE_LOCALE(saved_locale)
1581}
1582
1583/* Wrapper around GNU readline that handles signals differently. */
1584
1585
1586#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
1587
1588static char *completed_input_string;
1589static void
1590rlhandler(char *text)
1591{
1592 completed_input_string = text;
1593 rl_callback_handler_remove();
1594}
1595
1596static char *
1597readline_until_enter_or_signal(char *prompt, int *signal)
1598{
1599 char * not_done_reading = "";
1600 fd_set selectset;
1601
1602 *signal = 0;
1603#ifdef HAVE_RL_CATCH_SIGNAL
1604 rl_catch_signals = 0;
1605#endif
1606 /* OVM_MAIN: Oil is handling SIGWINCH, so readline shouldn't handle it.
1607 * Without this line, strace reveals that GNU readline is constantly
1608 * turning it on and off.
1609 * */
1610 rl_catch_sigwinch = 0;
1611
1612 rl_callback_handler_install (prompt, rlhandler);
1613 FD_ZERO(&selectset);
1614
1615 completed_input_string = not_done_reading;
1616
1617 while (completed_input_string == not_done_reading) {
1618 int has_input = 0;
1619
1620 while (!has_input)
1621 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
1622
1623 /* [Bug #1552726] Only limit the pause if an input hook has been
1624 defined. */
1625 struct timeval *timeoutp = NULL;
1626 if (PyOS_InputHook)
1627 timeoutp = &timeout;
1628#ifdef HAVE_RL_RESIZE_TERMINAL
1629 /* Update readline's view of the window size after SIGWINCH */
1630 if (sigwinch_received) {
1631 sigwinch_received = 0;
1632 rl_resize_terminal();
1633 }
1634#endif
1635 FD_SET(fileno(rl_instream), &selectset);
1636 /* select resets selectset if no input was available */
1637 has_input = select(fileno(rl_instream) + 1, &selectset,
1638 NULL, NULL, timeoutp);
1639 if(PyOS_InputHook) PyOS_InputHook();
1640 }
1641
1642 if(has_input > 0) {
1643 rl_callback_read_char();
1644 }
1645 else if (errno == EINTR) {
1646 int s;
1647#ifdef WITH_THREAD
1648 PyEval_RestoreThread(_PyOS_ReadlineTState);
1649#endif
1650 s = PyErr_CheckSignals();
1651#ifdef WITH_THREAD
1652 PyEval_SaveThread();
1653#endif
1654 if (s < 0) {
1655 rl_free_line_state();
1656#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1657 rl_callback_sigcleanup();
1658#endif
1659 rl_cleanup_after_signal();
1660 rl_callback_handler_remove();
1661 *signal = 1;
1662 completed_input_string = NULL;
1663 }
1664 }
1665 }
1666
1667 return completed_input_string;
1668}
1669
1670
1671#else
1672
1673/* Interrupt handler */
1674
1675static jmp_buf jbuf;
1676
1677/* ARGSUSED */
1678static void
1679onintr(int sig)
1680{
1681 longjmp(jbuf, 1);
1682}
1683
1684
1685static char *
1686readline_until_enter_or_signal(char *prompt, int *signal)
1687{
1688 PyOS_sighandler_t old_inthandler;
1689 char *p;
1690
1691 *signal = 0;
1692
1693 old_inthandler = PyOS_setsig(SIGINT, onintr);
1694 if (setjmp(jbuf)) {
1695#ifdef HAVE_SIGRELSE
1696 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
1697 sigrelse(SIGINT);
1698#endif
1699 PyOS_setsig(SIGINT, old_inthandler);
1700 *signal = 1;
1701 return NULL;
1702 }
1703 rl_event_hook = PyOS_InputHook;
1704 p = readline(prompt);
1705 PyOS_setsig(SIGINT, old_inthandler);
1706
1707 return p;
1708}
1709#endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
1710
1711
1712static char *
1713call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
1714{
1715 size_t n;
1716 char *p, *q;
1717 int signal;
1718
1719#ifdef SAVE_LOCALE
1720 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1721 if (!saved_locale)
1722 Py_FatalError("not enough memory to save locale");
1723 setlocale(LC_CTYPE, "");
1724#endif
1725
1726 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1727 rl_instream = sys_stdin;
1728 rl_outstream = sys_stdout;
1729#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1730 rl_prep_terminal (1);
1731#endif
1732 }
1733
1734 p = readline_until_enter_or_signal(prompt, &signal);
1735
1736 /* we got an interrupt signal */
1737 if (signal) {
1738 RESTORE_LOCALE(saved_locale)
1739 return NULL;
1740 }
1741
1742 /* We got an EOF, return an empty string. */
1743 if (p == NULL) {
1744 p = PyMem_Malloc(1);
1745 if (p != NULL)
1746 *p = '\0';
1747 RESTORE_LOCALE(saved_locale)
1748 return p;
1749 }
1750
1751 /* we have a valid line */
1752 n = strlen(p);
1753 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1754 release the original. */
1755 q = p;
1756 p = PyMem_Malloc(n+2);
1757 if (p != NULL) {
1758 strncpy(p, q, n);
1759 p[n] = '\n';
1760 p[n+1] = '\0';
1761 }
1762 free(q);
1763 RESTORE_LOCALE(saved_locale)
1764 return p;
1765}
1766
1767
1768/* Initialize the module */
1769
1770PyDoc_STRVAR(doc_module,
1771"Importing this module enables command line editing using GNU readline.");
1772
1773#ifdef __APPLE__
1774PyDoc_STRVAR(doc_module_le,
1775"Importing this module enables command line editing using libedit readline.");
1776#endif /* __APPLE__ */
1777
1778PyMODINIT_FUNC
1779initline_input(void)
1780{
1781 PyObject *m;
1782
1783#ifdef __APPLE__
1784 if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1785 using_libedit_emulation = 1;
1786 }
1787
1788 if (using_libedit_emulation)
1789 m = Py_InitModule4("line_input", readline_methods, doc_module_le,
1790 (PyObject *)NULL, PYTHON_API_VERSION);
1791 else
1792
1793#endif /* __APPLE__ */
1794
1795 m = Py_InitModule4("line_input", readline_methods, doc_module,
1796 (PyObject *)NULL, PYTHON_API_VERSION);
1797 if (m == NULL)
1798 return;
1799
1800 PyOS_ReadlineFunctionPointer = call_readline;
1801 setup_readline();
1802
1803 PyModule_AddIntConstant(m, "_READLINE_VERSION", RL_READLINE_VERSION);
1804 PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION", rl_readline_version);
1805}