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

1640 lines, 979 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 PyErr_Format(PyExc_ValueError, "%s is not bound to any keys", fn_name);
892 return NULL;
893 }
894
895 printf("%s can be invoked via ", fn_name);
896 _pprint_strvec_list(key_seqs);
897 printf(".\n");
898
899 _strvec_dispose(key_seqs);
900
901 Py_RETURN_NONE;
902}
903
904PyDoc_STRVAR(doc_query_bindings,
905"query_bindings(str) -> None\n\
906Query bindings to see what's bound to a given function.");
907
908
909static PyObject*
910unbind_rl_function(PyObject *self, PyObject *args)
911{
912 char *fn_name;
913 rl_command_func_t *cmd_fn;
914
915 if (!PyArg_ParseTuple(args, "s:unbind_rl_function", &fn_name))
916 return NULL;
917
918 cmd_fn = rl_named_function(fn_name);
919 if (cmd_fn == NULL) {
920 PyErr_Format(PyExc_ValueError, "`%s': unknown function name", fn_name);
921 return NULL;
922 }
923
924 rl_unbind_function_in_map(cmd_fn, rl_get_keymap());
925 Py_RETURN_NONE;
926}
927
928PyDoc_STRVAR(doc_unbind_rl_function,
929"unbind_rl_function(function_name) -> None\n\
930Unbind all keys bound to the named readline function in the current keymap.");
931
932
933static PyObject*
934unbind_shell_cmd(PyObject *self, PyObject *args)
935{
936 char *keyseq;
937 Keymap cmd_map;
938
939 if (!PyArg_ParseTuple(args, "s:unbind_shell_cmd", &keyseq))
940 return NULL;
941
942 cmd_map = _get_associated_cmd_map(rl_get_keymap());
943 if (cmd_map == NULL) {
944 PyErr_SetString(PyExc_ValueError, "Could not get command map for current keymap");
945 return NULL;
946 }
947
948 if (rl_bind_keyseq_in_map(keyseq, (rl_command_func_t *)NULL, cmd_map) != 0) {
949 PyErr_Format(PyExc_ValueError, "'%s': can't unbind from shell command keymap", keyseq);
950 return NULL;
951 }
952
953 Py_RETURN_NONE;
954}
955
956PyDoc_STRVAR(doc_unbind_shell_cmd,
957"unbind_shell_cmd(key_sequence) -> None\n\
958Unbind a key sequence from the current keymap's associated shell command map.");
959
960
961static PyObject*
962print_shell_cmd_map(PyObject *self, PyObject *noarg)
963{
964 Keymap curr_map, cmd_map;
965
966 curr_map = rl_get_keymap();
967 cmd_map = _get_associated_cmd_map(curr_map);
968
969 if (cmd_map == NULL) {
970 PyErr_SetString(PyExc_ValueError, "Could not get shell command map for current keymap");
971 return NULL;
972 }
973
974 rl_set_keymap(cmd_map);
975 rl_macro_dumper(1);
976 rl_set_keymap(curr_map);
977
978 Py_RETURN_NONE;
979}
980
981PyDoc_STRVAR(doc_print_shell_cmd_map,
982"print_shell_cmd_map() -> None\n\
983Print all bindings for shell commands in the current keymap.");
984
985
986/* Remove all bindings for a given keyseq */
987
988static PyObject*
989unbind_keyseq(PyObject *self, PyObject *args)
990{
991 /* Disabled because of rl_function_of_keyseq_len() error */
992 Py_RETURN_NONE;
993#if 0
994 char *seq, *keyseq;
995 int kslen, type;
996 rl_command_func_t *fn;
997
998 if (!PyArg_ParseTuple(args, "s:unbind_keyseq", &seq))
999 return NULL;
1000
1001 keyseq = (char *)malloc((2 * strlen(seq)) + 1);
1002 if (rl_translate_keyseq(seq, keyseq, &kslen) != 0) {
1003 free(keyseq);
1004 PyErr_Format(PyExc_ValueError, "'%s': cannot translate key sequence", seq);
1005 return NULL;
1006 }
1007
1008 fn = rl_function_of_keyseq_len(keyseq, kslen, (Keymap)NULL, &type);
1009 if (!fn) {
1010 free(keyseq);
1011 Py_RETURN_NONE;
1012 }
1013
1014 if (type == ISKMAP) {
1015 fn = ((Keymap)fn)[ANYOTHERKEY].function;
1016 }
1017
1018 if (rl_bind_keyseq(seq, (rl_command_func_t *)NULL) != 0) {
1019 free(keyseq);
1020 PyErr_Format(PyExc_ValueError, "'%s': cannot unbind", seq);
1021 return NULL;
1022 }
1023
1024 /*
1025 TODO: Handle shell command unbinding if f == bash_execute_unix_command or
1026 rather, whatever the osh equivalent will be
1027 */
1028
1029 free(keyseq);
1030 Py_RETURN_NONE;
1031#endif
1032}
1033
1034PyDoc_STRVAR(doc_unbind_keyseq,
1035"unbind_keyseq(sequence) -> None\n\
1036Unbind a key sequence from the current keymap.");
1037
1038
1039/* Keymap toggling code */
1040static Keymap orig_keymap = NULL;
1041
1042static PyObject*
1043use_temp_keymap(PyObject *self, PyObject *args)
1044{
1045 char *keymap_name;
1046 Keymap new_keymap;
1047
1048 if (!PyArg_ParseTuple(args, "s:use_temp_keymap", &keymap_name))
1049 return NULL;
1050
1051 new_keymap = rl_get_keymap_by_name(keymap_name);
1052 if (new_keymap == NULL) {
1053 PyErr_Format(PyExc_ValueError, "`%s': unknown keymap name", keymap_name);
1054 return NULL;
1055 }
1056
1057 orig_keymap = rl_get_keymap();
1058 rl_set_keymap(new_keymap);
1059
1060 Py_RETURN_NONE;
1061}
1062
1063PyDoc_STRVAR(doc_use_temp_keymap,
1064"use_temp_keymap(keymap_name) -> None\n\
1065Temporarily switch to named keymap, saving the current one.");
1066
1067static PyObject*
1068restore_orig_keymap(PyObject *self, PyObject *args)
1069{
1070 if (orig_keymap != NULL) {
1071 rl_set_keymap(orig_keymap);
1072 orig_keymap = NULL;
1073 }
1074
1075 Py_RETURN_NONE;
1076}
1077
1078PyDoc_STRVAR(doc_restore_orig_keymap,
1079"restore_orig_keymap() -> None\n\
1080Restore the previously saved keymap if one exists.");
1081
1082/* Table of functions exported by the module */
1083
1084#ifdef OVM_MAIN
1085#include "pyext/line_input.c/readline_methods.def"
1086#else
1087static struct PyMethodDef readline_methods[] = {
1088 {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
1089 {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
1090 {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
1091 {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
1092 {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
1093 {"read_history_file", read_history_file,
1094 METH_VARARGS, doc_read_history_file},
1095 {"write_history_file", write_history_file,
1096 METH_VARARGS, doc_write_history_file},
1097 {"get_history_item", get_history_item,
1098 METH_VARARGS, doc_get_history_item},
1099 {"get_current_history_length", (PyCFunction)get_current_history_length,
1100 METH_NOARGS, doc_get_current_history_length},
1101 {"set_history_length", set_history_length,
1102 METH_VARARGS, set_history_length_doc},
1103 {"get_history_length", get_history_length,
1104 METH_NOARGS, get_history_length_doc},
1105 {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
1106 {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
1107 {"get_completion_type", get_completion_type,
1108 METH_NOARGS, doc_get_completion_type},
1109 {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
1110 {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
1111
1112 {"set_completer_delims", set_completer_delims,
1113 METH_VARARGS, doc_set_completer_delims},
1114 {"add_history", py_add_history, METH_VARARGS, doc_add_history},
1115 {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
1116 {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
1117 {"get_completer_delims", get_completer_delims,
1118 METH_NOARGS, doc_get_completer_delims},
1119
1120 {"set_completion_display_matches_hook", set_completion_display_matches_hook,
1121 METH_VARARGS, doc_set_completion_display_matches_hook},
1122 {"set_startup_hook", set_startup_hook,
1123 METH_VARARGS, doc_set_startup_hook},
1124 {"set_pre_input_hook", set_pre_input_hook,
1125 METH_VARARGS, doc_set_pre_input_hook},
1126 {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
1127 {"resize_terminal", py_resize_terminal, METH_NOARGS, ""},
1128
1129 /* Functions added to implement the 'bind' builtin in OSH */
1130 {"list_funmap_names", list_funmap_names, METH_NOARGS, doc_list_funmap_names},
1131 {"function_dumper", function_dumper, METH_VARARGS, doc_list_function_dumper},
1132 {"macro_dumper", macro_dumper, METH_VARARGS, doc_list_macro_dumper},
1133 {"variable_dumper", variable_dumper, METH_VARARGS, doc_list_variable_dumper},
1134 {"query_bindings", query_bindings, METH_VARARGS, doc_query_bindings},
1135 {"unbind_rl_function", unbind_rl_function, METH_VARARGS, doc_unbind_rl_function},
1136 {"use_temp_keymap", use_temp_keymap, METH_VARARGS, doc_use_temp_keymap},
1137 {"restore_orig_keymap", restore_orig_keymap, METH_NOARGS, doc_restore_orig_keymap},
1138 {"unbind_shell_cmd", unbind_shell_cmd, METH_VARARGS, doc_unbind_shell_cmd},
1139 {"print_shell_cmd_map", print_shell_cmd_map, METH_NOARGS, doc_print_shell_cmd_map},
1140 {"unbind_keyseq", unbind_keyseq, METH_VARARGS, doc_unbind_keyseq},
1141 {0, 0}
1142};
1143#endif
1144
1145
1146/* C function to call the Python hooks. */
1147
1148static int
1149on_hook(PyObject *func)
1150{
1151 int result = 0;
1152 if (func != NULL) {
1153 PyObject *r;
1154#ifdef WITH_THREAD
1155 PyGILState_STATE gilstate = PyGILState_Ensure();
1156#endif
1157 r = PyObject_CallFunction(func, NULL);
1158 if (r == NULL)
1159 goto error;
1160 if (r == Py_None)
1161 result = 0;
1162 else {
1163 result = PyInt_AsLong(r);
1164 if (result == -1 && PyErr_Occurred())
1165 goto error;
1166 }
1167 Py_DECREF(r);
1168 goto done;
1169 error:
1170 PyErr_Clear();
1171 Py_XDECREF(r);
1172 done:
1173#ifdef WITH_THREAD
1174 PyGILState_Release(gilstate);
1175#endif
1176 return result;
1177 }
1178 return result;
1179}
1180
1181static int
1182#if defined(_RL_FUNCTION_TYPEDEF)
1183on_startup_hook(void)
1184#else
1185on_startup_hook()
1186#endif
1187{
1188 return on_hook(startup_hook);
1189}
1190
1191#ifdef HAVE_RL_PRE_INPUT_HOOK
1192static int
1193#if defined(_RL_FUNCTION_TYPEDEF)
1194on_pre_input_hook(void)
1195#else
1196on_pre_input_hook()
1197#endif
1198{
1199 return on_hook(pre_input_hook);
1200}
1201#endif
1202
1203
1204/* C function to call the Python completion_display_matches */
1205
1206#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
1207static void
1208on_completion_display_matches_hook(char **matches,
1209 int num_matches, int max_length)
1210{
1211 int i;
1212 PyObject *m=NULL, *s=NULL, *r=NULL;
1213#ifdef WITH_THREAD
1214 PyGILState_STATE gilstate = PyGILState_Ensure();
1215#endif
1216 m = PyList_New(num_matches);
1217 if (m == NULL)
1218 goto error;
1219 for (i = 0; i < num_matches; i++) {
1220 s = PyString_FromString(matches[i+1]);
1221 if (s == NULL)
1222 goto error;
1223 if (PyList_SetItem(m, i, s) == -1)
1224 goto error;
1225 }
1226
1227 r = PyObject_CallFunction(completion_display_matches_hook,
1228 "sOi", matches[0], m, max_length);
1229
1230 Py_DECREF(m); m=NULL;
1231
1232 if (r == NULL ||
1233 (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
1234 goto error;
1235 }
1236 Py_XDECREF(r); r=NULL;
1237
1238 if (0) {
1239 error:
1240 PyErr_Clear();
1241 Py_XDECREF(m);
1242 Py_XDECREF(r);
1243 }
1244#ifdef WITH_THREAD
1245 PyGILState_Release(gilstate);
1246#endif
1247}
1248
1249#endif
1250
1251#ifdef HAVE_RL_RESIZE_TERMINAL
1252static volatile sig_atomic_t sigwinch_received;
1253static PyOS_sighandler_t sigwinch_ohandler;
1254
1255static void
1256readline_sigwinch_handler(int signum)
1257{
1258 sigwinch_received = 1;
1259 if (sigwinch_ohandler &&
1260 sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
1261 sigwinch_ohandler(signum);
1262}
1263#endif
1264
1265/* C function to call the Python completer. */
1266
1267static char *
1268on_completion(const char *text, int state)
1269{
1270 char *result = NULL;
1271 if (completer != NULL) {
1272 PyObject *r;
1273#ifdef WITH_THREAD
1274 PyGILState_STATE gilstate = PyGILState_Ensure();
1275#endif
1276 rl_attempted_completion_over = 1;
1277 r = PyObject_CallFunction(completer, "si", text, state);
1278 if (r == NULL)
1279 goto error;
1280 if (r == Py_None) {
1281 result = NULL;
1282 }
1283 else {
1284 char *s = PyString_AsString(r);
1285 if (s == NULL)
1286 goto error;
1287 result = strdup(s);
1288 }
1289 Py_DECREF(r);
1290 goto done;
1291 error:
1292 PyErr_Clear();
1293 Py_XDECREF(r);
1294 done:
1295#ifdef WITH_THREAD
1296 PyGILState_Release(gilstate);
1297#endif
1298 return result;
1299 }
1300 return result;
1301}
1302
1303
1304/* A more flexible constructor that saves the "begidx" and "endidx"
1305 * before calling the normal completer */
1306
1307static char **
1308flex_complete(const char *text, int start, int end)
1309{
1310#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1311 rl_completion_append_character ='\0';
1312#endif
1313#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
1314 rl_completion_suppress_append = 0;
1315#endif
1316 Py_XDECREF(begidx);
1317 Py_XDECREF(endidx);
1318 begidx = PyInt_FromLong((long) start);
1319 endidx = PyInt_FromLong((long) end);
1320 return completion_matches(text, *on_completion);
1321}
1322
1323
1324/* Helper to initialize GNU readline properly. */
1325
1326static void
1327setup_readline(void)
1328{
1329#ifdef SAVE_LOCALE
1330 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1331 if (!saved_locale)
1332 Py_FatalError("not enough memory to save locale");
1333#endif
1334
1335#ifdef __APPLE__
1336 /* the libedit readline emulation resets key bindings etc
1337 * when calling rl_initialize. So call it upfront
1338 */
1339 if (using_libedit_emulation)
1340 rl_initialize();
1341
1342 /* Detect if libedit's readline emulation uses 0-based
1343 * indexing or 1-based indexing.
1344 */
1345 add_history("1");
1346 if (history_get(1) == NULL) {
1347 libedit_history_start = 0;
1348 } else {
1349 libedit_history_start = 1;
1350 }
1351 clear_history();
1352#endif /* __APPLE__ */
1353
1354 using_history();
1355
1356 rl_readline_name = "oils";
1357#if defined(PYOS_OS2) && defined(PYCC_GCC)
1358 /* Allow $if term= in .inputrc to work */
1359 rl_terminal_name = getenv("TERM");
1360#endif
1361 /* Force rebind of TAB to insert-tab */
1362 rl_bind_key('\t', rl_insert);
1363 /* Bind both ESC-TAB and ESC-ESC to the completion function */
1364 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1365 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
1366#ifdef HAVE_RL_RESIZE_TERMINAL
1367 /* Set up signal handler for window resize */
1368 sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1369#endif
1370 /* Set our hook functions */
1371 rl_startup_hook = on_startup_hook;
1372#ifdef HAVE_RL_PRE_INPUT_HOOK
1373 rl_pre_input_hook = on_pre_input_hook;
1374#endif
1375 /* Set our completion function */
1376 rl_attempted_completion_function = flex_complete;
1377 /* Set Python word break characters */
1378 completer_word_break_characters =
1379 rl_completer_word_break_characters =
1380 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1381 /* All nonalphanums except '.' */
1382
1383 begidx = PyInt_FromLong(0L);
1384 endidx = PyInt_FromLong(0L);
1385
1386#ifdef __APPLE__
1387 if (!using_libedit_emulation)
1388#endif
1389 {
1390 if (!isatty(STDOUT_FILENO)) {
1391 /* Issue #19884: stdout is not a terminal. Disable meta modifier
1392 keys to not write the ANSI sequence "\033[1034h" into stdout. On
1393 terminals supporting 8 bit characters like TERM=xterm-256color
1394 (which is now the default Fedora since Fedora 18), the meta key is
1395 used to enable support of 8 bit characters (ANSI sequence
1396 "\033[1034h").
1397
1398 With libedit, this call makes readline() crash. */
1399 rl_variable_bind ("enable-meta-key", "off");
1400 }
1401 }
1402
1403 /* Initialize (allows .inputrc to override)
1404 *
1405 * XXX: A bug in the readline-2.2 library causes a memory leak
1406 * inside this function. Nothing we can do about it.
1407 */
1408#ifdef __APPLE__
1409 if (using_libedit_emulation)
1410 rl_read_init_file(NULL);
1411 else
1412#endif /* __APPLE__ */
1413 rl_initialize();
1414
1415 RESTORE_LOCALE(saved_locale)
1416}
1417
1418/* Wrapper around GNU readline that handles signals differently. */
1419
1420
1421#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
1422
1423static char *completed_input_string;
1424static void
1425rlhandler(char *text)
1426{
1427 completed_input_string = text;
1428 rl_callback_handler_remove();
1429}
1430
1431static char *
1432readline_until_enter_or_signal(char *prompt, int *signal)
1433{
1434 char * not_done_reading = "";
1435 fd_set selectset;
1436
1437 *signal = 0;
1438#ifdef HAVE_RL_CATCH_SIGNAL
1439 rl_catch_signals = 0;
1440#endif
1441 /* OVM_MAIN: Oil is handling SIGWINCH, so readline shouldn't handle it.
1442 * Without this line, strace reveals that GNU readline is constantly
1443 * turning it on and off.
1444 * */
1445 rl_catch_sigwinch = 0;
1446
1447 rl_callback_handler_install (prompt, rlhandler);
1448 FD_ZERO(&selectset);
1449
1450 completed_input_string = not_done_reading;
1451
1452 while (completed_input_string == not_done_reading) {
1453 int has_input = 0;
1454
1455 while (!has_input)
1456 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
1457
1458 /* [Bug #1552726] Only limit the pause if an input hook has been
1459 defined. */
1460 struct timeval *timeoutp = NULL;
1461 if (PyOS_InputHook)
1462 timeoutp = &timeout;
1463#ifdef HAVE_RL_RESIZE_TERMINAL
1464 /* Update readline's view of the window size after SIGWINCH */
1465 if (sigwinch_received) {
1466 sigwinch_received = 0;
1467 rl_resize_terminal();
1468 }
1469#endif
1470 FD_SET(fileno(rl_instream), &selectset);
1471 /* select resets selectset if no input was available */
1472 has_input = select(fileno(rl_instream) + 1, &selectset,
1473 NULL, NULL, timeoutp);
1474 if(PyOS_InputHook) PyOS_InputHook();
1475 }
1476
1477 if(has_input > 0) {
1478 rl_callback_read_char();
1479 }
1480 else if (errno == EINTR) {
1481 int s;
1482#ifdef WITH_THREAD
1483 PyEval_RestoreThread(_PyOS_ReadlineTState);
1484#endif
1485 s = PyErr_CheckSignals();
1486#ifdef WITH_THREAD
1487 PyEval_SaveThread();
1488#endif
1489 if (s < 0) {
1490 rl_free_line_state();
1491#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1492 rl_callback_sigcleanup();
1493#endif
1494 rl_cleanup_after_signal();
1495 rl_callback_handler_remove();
1496 *signal = 1;
1497 completed_input_string = NULL;
1498 }
1499 }
1500 }
1501
1502 return completed_input_string;
1503}
1504
1505
1506#else
1507
1508/* Interrupt handler */
1509
1510static jmp_buf jbuf;
1511
1512/* ARGSUSED */
1513static void
1514onintr(int sig)
1515{
1516 longjmp(jbuf, 1);
1517}
1518
1519
1520static char *
1521readline_until_enter_or_signal(char *prompt, int *signal)
1522{
1523 PyOS_sighandler_t old_inthandler;
1524 char *p;
1525
1526 *signal = 0;
1527
1528 old_inthandler = PyOS_setsig(SIGINT, onintr);
1529 if (setjmp(jbuf)) {
1530#ifdef HAVE_SIGRELSE
1531 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
1532 sigrelse(SIGINT);
1533#endif
1534 PyOS_setsig(SIGINT, old_inthandler);
1535 *signal = 1;
1536 return NULL;
1537 }
1538 rl_event_hook = PyOS_InputHook;
1539 p = readline(prompt);
1540 PyOS_setsig(SIGINT, old_inthandler);
1541
1542 return p;
1543}
1544#endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
1545
1546
1547static char *
1548call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
1549{
1550 size_t n;
1551 char *p, *q;
1552 int signal;
1553
1554#ifdef SAVE_LOCALE
1555 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1556 if (!saved_locale)
1557 Py_FatalError("not enough memory to save locale");
1558 setlocale(LC_CTYPE, "");
1559#endif
1560
1561 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1562 rl_instream = sys_stdin;
1563 rl_outstream = sys_stdout;
1564#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1565 rl_prep_terminal (1);
1566#endif
1567 }
1568
1569 p = readline_until_enter_or_signal(prompt, &signal);
1570
1571 /* we got an interrupt signal */
1572 if (signal) {
1573 RESTORE_LOCALE(saved_locale)
1574 return NULL;
1575 }
1576
1577 /* We got an EOF, return an empty string. */
1578 if (p == NULL) {
1579 p = PyMem_Malloc(1);
1580 if (p != NULL)
1581 *p = '\0';
1582 RESTORE_LOCALE(saved_locale)
1583 return p;
1584 }
1585
1586 /* we have a valid line */
1587 n = strlen(p);
1588 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1589 release the original. */
1590 q = p;
1591 p = PyMem_Malloc(n+2);
1592 if (p != NULL) {
1593 strncpy(p, q, n);
1594 p[n] = '\n';
1595 p[n+1] = '\0';
1596 }
1597 free(q);
1598 RESTORE_LOCALE(saved_locale)
1599 return p;
1600}
1601
1602
1603/* Initialize the module */
1604
1605PyDoc_STRVAR(doc_module,
1606"Importing this module enables command line editing using GNU readline.");
1607
1608#ifdef __APPLE__
1609PyDoc_STRVAR(doc_module_le,
1610"Importing this module enables command line editing using libedit readline.");
1611#endif /* __APPLE__ */
1612
1613PyMODINIT_FUNC
1614initline_input(void)
1615{
1616 PyObject *m;
1617
1618#ifdef __APPLE__
1619 if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1620 using_libedit_emulation = 1;
1621 }
1622
1623 if (using_libedit_emulation)
1624 m = Py_InitModule4("line_input", readline_methods, doc_module_le,
1625 (PyObject *)NULL, PYTHON_API_VERSION);
1626 else
1627
1628#endif /* __APPLE__ */
1629
1630 m = Py_InitModule4("line_input", readline_methods, doc_module,
1631 (PyObject *)NULL, PYTHON_API_VERSION);
1632 if (m == NULL)
1633 return;
1634
1635 PyOS_ReadlineFunctionPointer = call_readline;
1636 setup_readline();
1637
1638 PyModule_AddIntConstant(m, "_READLINE_VERSION", RL_READLINE_VERSION);
1639 PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION", rl_readline_version);
1640}