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

1647 lines, 982 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()
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(kmap)
748Keymap kmap;
749{
750 if (emacs_cmd_map == NULL)
751 _init_command_maps();
752
753 if (kmap == emacs_standard_keymap)
754 return emacs_cmd_map;
755 else if (kmap == vi_insertion_keymap)
756 return vi_insert_cmd_map;
757 else if (kmap == vi_movement_keymap)
758 return vi_movement_cmd_map;
759 else if (kmap == emacs_meta_keymap)
760 return (RL_FUNCTION_TO_KEYMAP(emacs_cmd_map, ESC));
761 else if (kmap == emacs_ctlx_keymap)
762 return (RL_FUNCTION_TO_KEYMAP(emacs_cmd_map, CTRL('X')));
763
764 return (Keymap) NULL;
765}
766
767/* List binding functions */
768static PyObject*
769list_funmap_names(PyObject *self, PyObject *args)
770{
771 rl_list_funmap_names();
772 // printf ("Compiled w/ readline version: %s\n", rl_library_version ? rl_library_version : "unknown");
773 Py_RETURN_NONE;
774}
775
776PyDoc_STRVAR(doc_list_funmap_names,
777"list_funmap_names() -> None\n\
778Print all of the available readline functions.");
779
780/* Print readline functions and their bindings */
781
782static PyObject*
783function_dumper(PyObject *self, PyObject *args)
784{
785 int print_readably;
786
787 if (!PyArg_ParseTuple(args, "i:function_dumper", &print_readably))
788 return NULL;
789
790 rl_function_dumper(print_readably);
791 Py_RETURN_NONE;
792}
793
794PyDoc_STRVAR(doc_list_function_dumper,
795"function_dumper(bool) -> None\n\
796Print all readline functions and their bindings.");
797
798/* Print macros, their bindings, and their string outputs */
799
800static PyObject*
801macro_dumper(PyObject *self, PyObject *args)
802{
803 int print_readably;
804
805 if (!PyArg_ParseTuple(args, "i:macro_dumper", &print_readably))
806 return NULL;
807
808 rl_macro_dumper(print_readably);
809 Py_RETURN_NONE;
810}
811
812PyDoc_STRVAR(doc_list_macro_dumper,
813"macro_dumper(bool) -> None\n\
814Print all readline sequences bound to macros and the strings they output.");
815
816/* List readline variables */
817
818static PyObject*
819variable_dumper(PyObject *self, PyObject *args)
820{
821 int print_readably;
822
823 if (!PyArg_ParseTuple(args, "i:variable_dumper", &print_readably))
824 return NULL;
825
826 rl_variable_dumper(print_readably);
827 Py_RETURN_NONE;
828}
829
830PyDoc_STRVAR(doc_list_variable_dumper,
831"variable_dumper(bool) -> None\n\
832List readline variables and their values.");
833
834
835
836/* Query bindings for a function name */
837
838// readline returns null-terminated string arrays
839void _strvec_dispose(char **strvec) {
840 register int i;
841
842 if (strvec == NULL)
843 return;
844
845 for (i = 0; strvec[i]; i++) {
846 free(strvec[i]);
847 }
848
849 free(strvec);
850}
851
852// Nicely prints a strvec with commas and an and
853// like '"foo", "bar", and "moop"'
854void _pprint_strvec_list(char **strvec) {
855 int i;
856
857 for (i = 0; strvec[i]; i++) {
858 printf("\"%s\"", strvec[i]);
859 if (strvec[i + 1]) {
860 printf(", ");
861 if (!strvec[i + 2])
862 printf("and ");
863 }
864 }
865}
866
867/*
868NB: readline (and bash) have a bug where they don't see certain keyseqs, even
869if the bindings work. E.g., if you bind a number key like "\C-7", it will be
870bound, but reporting code like query_bindings and function_dumper won't count it.
871*/
872
873static PyObject*
874query_bindings(PyObject *self, PyObject *args)
875{
876 char *fn_name;
877 rl_command_func_t *cmd_fn;
878 char **key_seqs;
879 int i;
880
881 if (!PyArg_ParseTuple(args, "s:query_bindings", &fn_name))
882 return NULL;
883
884 cmd_fn = rl_named_function(fn_name);
885
886 if (cmd_fn == NULL) {
887 PyErr_Format(PyExc_ValueError, "`%s': unknown function name", fn_name);
888 return NULL;
889 }
890
891 key_seqs = rl_invoking_keyseqs(cmd_fn);
892
893 if (!key_seqs) {
894 PyErr_Format(PyExc_ValueError, "%s is not bound to any keys", fn_name);
895 return NULL;
896 }
897
898 printf("%s can be invoked via ", fn_name);
899 _pprint_strvec_list(key_seqs);
900 printf(".\n");
901
902 _strvec_dispose(key_seqs);
903
904 Py_RETURN_NONE;
905}
906
907PyDoc_STRVAR(doc_query_bindings,
908"query_bindings(str) -> None\n\
909Query bindings to see what's bound to a given function.");
910
911
912static PyObject*
913unbind_rl_function(PyObject *self, PyObject *args)
914{
915 char *fn_name;
916 rl_command_func_t *cmd_fn;
917
918 if (!PyArg_ParseTuple(args, "s:unbind_rl_function", &fn_name))
919 return NULL;
920
921 cmd_fn = rl_named_function(fn_name);
922 if (cmd_fn == NULL) {
923 PyErr_Format(PyExc_ValueError, "`%s': unknown function name", fn_name);
924 return NULL;
925 }
926
927 rl_unbind_function_in_map(cmd_fn, rl_get_keymap());
928 Py_RETURN_NONE;
929}
930
931PyDoc_STRVAR(doc_unbind_rl_function,
932"unbind_rl_function(function_name) -> None\n\
933Unbind all keys bound to the named readline function in the current keymap.");
934
935
936static PyObject*
937unbind_shell_cmd(PyObject *self, PyObject *args)
938{
939 char *keyseq;
940 Keymap cmd_map;
941
942 if (!PyArg_ParseTuple(args, "s:unbind_shell_cmd", &keyseq))
943 return NULL;
944
945 cmd_map = _get_associated_cmd_map(rl_get_keymap());
946 if (cmd_map == NULL) {
947 PyErr_SetString(PyExc_ValueError, "Could not get command map for current keymap");
948 return NULL;
949 }
950
951 if (rl_bind_keyseq_in_map(keyseq, (rl_command_func_t *)NULL, cmd_map) != 0) {
952 PyErr_Format(PyExc_ValueError, "'%s': can't unbind from shell command keymap", keyseq);
953 return NULL;
954 }
955
956 Py_RETURN_NONE;
957}
958
959PyDoc_STRVAR(doc_unbind_shell_cmd,
960"unbind_shell_cmd(key_sequence) -> None\n\
961Unbind a key sequence from the current keymap's associated shell command map.");
962
963
964static PyObject*
965print_shell_cmd_map(PyObject *self, PyObject *noarg)
966{
967 Keymap curr_map, cmd_map;
968
969 curr_map = rl_get_keymap();
970 cmd_map = _get_associated_cmd_map(curr_map);
971
972 if (cmd_map == NULL) {
973 PyErr_SetString(PyExc_ValueError, "Could not get shell command map for current keymap");
974 return NULL;
975 }
976
977 rl_set_keymap(cmd_map);
978 rl_macro_dumper(1);
979 rl_set_keymap(curr_map);
980
981 Py_RETURN_NONE;
982}
983
984PyDoc_STRVAR(doc_print_shell_cmd_map,
985"print_shell_cmd_map() -> None\n\
986Print all bindings for shell commands in the current keymap.");
987
988
989/* Remove all bindings for a given keyseq */
990
991#if 0
992static PyObject*
993unbind_keyseq(PyObject *self, PyObject *args)
994{
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}
1033#endif
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#if 0
1146 {"unbind_keyseq", unbind_keyseq, METH_VARARGS, doc_unbind_keyseq},
1147#endif
1148 {0, 0}
1149};
1150#endif
1151
1152
1153/* C function to call the Python hooks. */
1154
1155static int
1156on_hook(PyObject *func)
1157{
1158 int result = 0;
1159 if (func != NULL) {
1160 PyObject *r;
1161#ifdef WITH_THREAD
1162 PyGILState_STATE gilstate = PyGILState_Ensure();
1163#endif
1164 r = PyObject_CallFunction(func, NULL);
1165 if (r == NULL)
1166 goto error;
1167 if (r == Py_None)
1168 result = 0;
1169 else {
1170 result = PyInt_AsLong(r);
1171 if (result == -1 && PyErr_Occurred())
1172 goto error;
1173 }
1174 Py_DECREF(r);
1175 goto done;
1176 error:
1177 PyErr_Clear();
1178 Py_XDECREF(r);
1179 done:
1180#ifdef WITH_THREAD
1181 PyGILState_Release(gilstate);
1182#endif
1183 return result;
1184 }
1185 return result;
1186}
1187
1188static int
1189#if defined(_RL_FUNCTION_TYPEDEF)
1190on_startup_hook(void)
1191#else
1192on_startup_hook()
1193#endif
1194{
1195 return on_hook(startup_hook);
1196}
1197
1198#ifdef HAVE_RL_PRE_INPUT_HOOK
1199static int
1200#if defined(_RL_FUNCTION_TYPEDEF)
1201on_pre_input_hook(void)
1202#else
1203on_pre_input_hook()
1204#endif
1205{
1206 return on_hook(pre_input_hook);
1207}
1208#endif
1209
1210
1211/* C function to call the Python completion_display_matches */
1212
1213#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
1214static void
1215on_completion_display_matches_hook(char **matches,
1216 int num_matches, int max_length)
1217{
1218 int i;
1219 PyObject *m=NULL, *s=NULL, *r=NULL;
1220#ifdef WITH_THREAD
1221 PyGILState_STATE gilstate = PyGILState_Ensure();
1222#endif
1223 m = PyList_New(num_matches);
1224 if (m == NULL)
1225 goto error;
1226 for (i = 0; i < num_matches; i++) {
1227 s = PyString_FromString(matches[i+1]);
1228 if (s == NULL)
1229 goto error;
1230 if (PyList_SetItem(m, i, s) == -1)
1231 goto error;
1232 }
1233
1234 r = PyObject_CallFunction(completion_display_matches_hook,
1235 "sOi", matches[0], m, max_length);
1236
1237 Py_DECREF(m); m=NULL;
1238
1239 if (r == NULL ||
1240 (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
1241 goto error;
1242 }
1243 Py_XDECREF(r); r=NULL;
1244
1245 if (0) {
1246 error:
1247 PyErr_Clear();
1248 Py_XDECREF(m);
1249 Py_XDECREF(r);
1250 }
1251#ifdef WITH_THREAD
1252 PyGILState_Release(gilstate);
1253#endif
1254}
1255
1256#endif
1257
1258#ifdef HAVE_RL_RESIZE_TERMINAL
1259static volatile sig_atomic_t sigwinch_received;
1260static PyOS_sighandler_t sigwinch_ohandler;
1261
1262static void
1263readline_sigwinch_handler(int signum)
1264{
1265 sigwinch_received = 1;
1266 if (sigwinch_ohandler &&
1267 sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
1268 sigwinch_ohandler(signum);
1269}
1270#endif
1271
1272/* C function to call the Python completer. */
1273
1274static char *
1275on_completion(const char *text, int state)
1276{
1277 char *result = NULL;
1278 if (completer != NULL) {
1279 PyObject *r;
1280#ifdef WITH_THREAD
1281 PyGILState_STATE gilstate = PyGILState_Ensure();
1282#endif
1283 rl_attempted_completion_over = 1;
1284 r = PyObject_CallFunction(completer, "si", text, state);
1285 if (r == NULL)
1286 goto error;
1287 if (r == Py_None) {
1288 result = NULL;
1289 }
1290 else {
1291 char *s = PyString_AsString(r);
1292 if (s == NULL)
1293 goto error;
1294 result = strdup(s);
1295 }
1296 Py_DECREF(r);
1297 goto done;
1298 error:
1299 PyErr_Clear();
1300 Py_XDECREF(r);
1301 done:
1302#ifdef WITH_THREAD
1303 PyGILState_Release(gilstate);
1304#endif
1305 return result;
1306 }
1307 return result;
1308}
1309
1310
1311/* A more flexible constructor that saves the "begidx" and "endidx"
1312 * before calling the normal completer */
1313
1314static char **
1315flex_complete(const char *text, int start, int end)
1316{
1317#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1318 rl_completion_append_character ='\0';
1319#endif
1320#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
1321 rl_completion_suppress_append = 0;
1322#endif
1323 Py_XDECREF(begidx);
1324 Py_XDECREF(endidx);
1325 begidx = PyInt_FromLong((long) start);
1326 endidx = PyInt_FromLong((long) end);
1327 return completion_matches(text, *on_completion);
1328}
1329
1330
1331/* Helper to initialize GNU readline properly. */
1332
1333static void
1334setup_readline(void)
1335{
1336#ifdef SAVE_LOCALE
1337 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1338 if (!saved_locale)
1339 Py_FatalError("not enough memory to save locale");
1340#endif
1341
1342#ifdef __APPLE__
1343 /* the libedit readline emulation resets key bindings etc
1344 * when calling rl_initialize. So call it upfront
1345 */
1346 if (using_libedit_emulation)
1347 rl_initialize();
1348
1349 /* Detect if libedit's readline emulation uses 0-based
1350 * indexing or 1-based indexing.
1351 */
1352 add_history("1");
1353 if (history_get(1) == NULL) {
1354 libedit_history_start = 0;
1355 } else {
1356 libedit_history_start = 1;
1357 }
1358 clear_history();
1359#endif /* __APPLE__ */
1360
1361 using_history();
1362
1363 rl_readline_name = "oils";
1364#if defined(PYOS_OS2) && defined(PYCC_GCC)
1365 /* Allow $if term= in .inputrc to work */
1366 rl_terminal_name = getenv("TERM");
1367#endif
1368 /* Force rebind of TAB to insert-tab */
1369 rl_bind_key('\t', rl_insert);
1370 /* Bind both ESC-TAB and ESC-ESC to the completion function */
1371 rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1372 rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
1373#ifdef HAVE_RL_RESIZE_TERMINAL
1374 /* Set up signal handler for window resize */
1375 sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1376#endif
1377 /* Set our hook functions */
1378 rl_startup_hook = on_startup_hook;
1379#ifdef HAVE_RL_PRE_INPUT_HOOK
1380 rl_pre_input_hook = on_pre_input_hook;
1381#endif
1382 /* Set our completion function */
1383 rl_attempted_completion_function = flex_complete;
1384 /* Set Python word break characters */
1385 completer_word_break_characters =
1386 rl_completer_word_break_characters =
1387 strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1388 /* All nonalphanums except '.' */
1389
1390 begidx = PyInt_FromLong(0L);
1391 endidx = PyInt_FromLong(0L);
1392
1393#ifdef __APPLE__
1394 if (!using_libedit_emulation)
1395#endif
1396 {
1397 if (!isatty(STDOUT_FILENO)) {
1398 /* Issue #19884: stdout is not a terminal. Disable meta modifier
1399 keys to not write the ANSI sequence "\033[1034h" into stdout. On
1400 terminals supporting 8 bit characters like TERM=xterm-256color
1401 (which is now the default Fedora since Fedora 18), the meta key is
1402 used to enable support of 8 bit characters (ANSI sequence
1403 "\033[1034h").
1404
1405 With libedit, this call makes readline() crash. */
1406 rl_variable_bind ("enable-meta-key", "off");
1407 }
1408 }
1409
1410 /* Initialize (allows .inputrc to override)
1411 *
1412 * XXX: A bug in the readline-2.2 library causes a memory leak
1413 * inside this function. Nothing we can do about it.
1414 */
1415#ifdef __APPLE__
1416 if (using_libedit_emulation)
1417 rl_read_init_file(NULL);
1418 else
1419#endif /* __APPLE__ */
1420 rl_initialize();
1421
1422 RESTORE_LOCALE(saved_locale)
1423}
1424
1425/* Wrapper around GNU readline that handles signals differently. */
1426
1427
1428#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
1429
1430static char *completed_input_string;
1431static void
1432rlhandler(char *text)
1433{
1434 completed_input_string = text;
1435 rl_callback_handler_remove();
1436}
1437
1438static char *
1439readline_until_enter_or_signal(char *prompt, int *signal)
1440{
1441 char * not_done_reading = "";
1442 fd_set selectset;
1443
1444 *signal = 0;
1445#ifdef HAVE_RL_CATCH_SIGNAL
1446 rl_catch_signals = 0;
1447#endif
1448 /* OVM_MAIN: Oil is handling SIGWINCH, so readline shouldn't handle it.
1449 * Without this line, strace reveals that GNU readline is constantly
1450 * turning it on and off.
1451 * */
1452 rl_catch_sigwinch = 0;
1453
1454 rl_callback_handler_install (prompt, rlhandler);
1455 FD_ZERO(&selectset);
1456
1457 completed_input_string = not_done_reading;
1458
1459 while (completed_input_string == not_done_reading) {
1460 int has_input = 0;
1461
1462 while (!has_input)
1463 { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
1464
1465 /* [Bug #1552726] Only limit the pause if an input hook has been
1466 defined. */
1467 struct timeval *timeoutp = NULL;
1468 if (PyOS_InputHook)
1469 timeoutp = &timeout;
1470#ifdef HAVE_RL_RESIZE_TERMINAL
1471 /* Update readline's view of the window size after SIGWINCH */
1472 if (sigwinch_received) {
1473 sigwinch_received = 0;
1474 rl_resize_terminal();
1475 }
1476#endif
1477 FD_SET(fileno(rl_instream), &selectset);
1478 /* select resets selectset if no input was available */
1479 has_input = select(fileno(rl_instream) + 1, &selectset,
1480 NULL, NULL, timeoutp);
1481 if(PyOS_InputHook) PyOS_InputHook();
1482 }
1483
1484 if(has_input > 0) {
1485 rl_callback_read_char();
1486 }
1487 else if (errno == EINTR) {
1488 int s;
1489#ifdef WITH_THREAD
1490 PyEval_RestoreThread(_PyOS_ReadlineTState);
1491#endif
1492 s = PyErr_CheckSignals();
1493#ifdef WITH_THREAD
1494 PyEval_SaveThread();
1495#endif
1496 if (s < 0) {
1497 rl_free_line_state();
1498#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1499 rl_callback_sigcleanup();
1500#endif
1501 rl_cleanup_after_signal();
1502 rl_callback_handler_remove();
1503 *signal = 1;
1504 completed_input_string = NULL;
1505 }
1506 }
1507 }
1508
1509 return completed_input_string;
1510}
1511
1512
1513#else
1514
1515/* Interrupt handler */
1516
1517static jmp_buf jbuf;
1518
1519/* ARGSUSED */
1520static void
1521onintr(int sig)
1522{
1523 longjmp(jbuf, 1);
1524}
1525
1526
1527static char *
1528readline_until_enter_or_signal(char *prompt, int *signal)
1529{
1530 PyOS_sighandler_t old_inthandler;
1531 char *p;
1532
1533 *signal = 0;
1534
1535 old_inthandler = PyOS_setsig(SIGINT, onintr);
1536 if (setjmp(jbuf)) {
1537#ifdef HAVE_SIGRELSE
1538 /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
1539 sigrelse(SIGINT);
1540#endif
1541 PyOS_setsig(SIGINT, old_inthandler);
1542 *signal = 1;
1543 return NULL;
1544 }
1545 rl_event_hook = PyOS_InputHook;
1546 p = readline(prompt);
1547 PyOS_setsig(SIGINT, old_inthandler);
1548
1549 return p;
1550}
1551#endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
1552
1553
1554static char *
1555call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
1556{
1557 size_t n;
1558 char *p, *q;
1559 int signal;
1560
1561#ifdef SAVE_LOCALE
1562 char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1563 if (!saved_locale)
1564 Py_FatalError("not enough memory to save locale");
1565 setlocale(LC_CTYPE, "");
1566#endif
1567
1568 if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1569 rl_instream = sys_stdin;
1570 rl_outstream = sys_stdout;
1571#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1572 rl_prep_terminal (1);
1573#endif
1574 }
1575
1576 p = readline_until_enter_or_signal(prompt, &signal);
1577
1578 /* we got an interrupt signal */
1579 if (signal) {
1580 RESTORE_LOCALE(saved_locale)
1581 return NULL;
1582 }
1583
1584 /* We got an EOF, return an empty string. */
1585 if (p == NULL) {
1586 p = PyMem_Malloc(1);
1587 if (p != NULL)
1588 *p = '\0';
1589 RESTORE_LOCALE(saved_locale)
1590 return p;
1591 }
1592
1593 /* we have a valid line */
1594 n = strlen(p);
1595 /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1596 release the original. */
1597 q = p;
1598 p = PyMem_Malloc(n+2);
1599 if (p != NULL) {
1600 strncpy(p, q, n);
1601 p[n] = '\n';
1602 p[n+1] = '\0';
1603 }
1604 free(q);
1605 RESTORE_LOCALE(saved_locale)
1606 return p;
1607}
1608
1609
1610/* Initialize the module */
1611
1612PyDoc_STRVAR(doc_module,
1613"Importing this module enables command line editing using GNU readline.");
1614
1615#ifdef __APPLE__
1616PyDoc_STRVAR(doc_module_le,
1617"Importing this module enables command line editing using libedit readline.");
1618#endif /* __APPLE__ */
1619
1620PyMODINIT_FUNC
1621initline_input(void)
1622{
1623 PyObject *m;
1624
1625#ifdef __APPLE__
1626 if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1627 using_libedit_emulation = 1;
1628 }
1629
1630 if (using_libedit_emulation)
1631 m = Py_InitModule4("line_input", readline_methods, doc_module_le,
1632 (PyObject *)NULL, PYTHON_API_VERSION);
1633 else
1634
1635#endif /* __APPLE__ */
1636
1637 m = Py_InitModule4("line_input", readline_methods, doc_module,
1638 (PyObject *)NULL, PYTHON_API_VERSION);
1639 if (m == NULL)
1640 return;
1641
1642 PyOS_ReadlineFunctionPointer = call_readline;
1643 setup_readline();
1644
1645 PyModule_AddIntConstant(m, "_READLINE_VERSION", RL_READLINE_VERSION);
1646 PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION", rl_readline_version);
1647}