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

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