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

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