ยปCore Development>Code coverage>Modules/readline.c

Python code coverage for Modules/readline.c

#countcontent
1n/a/* This module makes GNU readline available to Python. It has ideas
2n/a * contributed by Lee Busby, LLNL, and William Magro, Cornell Theory
3n/a * Center. The completer interface was inspired by Lele Gaifax. More
4n/a * recently, it was largely rewritten by Guido van Rossum.
5n/a */
6n/a
7n/a/* Standard definitions */
8n/a#include "Python.h"
9n/a#include <stddef.h>
10n/a#include <setjmp.h>
11n/a#include <signal.h>
12n/a#include <errno.h>
13n/a#include <sys/time.h>
14n/a
15n/a#if defined(HAVE_SETLOCALE)
16n/a/* GNU readline() mistakenly sets the LC_CTYPE locale.
17n/a * This is evil. Only the user or the app's main() should do this!
18n/a * We must save and restore the locale around the rl_initialize() call.
19n/a */
20n/a#define SAVE_LOCALE
21n/a#include <locale.h>
22n/a#endif
23n/a
24n/a#ifdef SAVE_LOCALE
25n/a# define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); }
26n/a#else
27n/a# define RESTORE_LOCALE(sl)
28n/a#endif
29n/a
30n/a/* GNU readline definitions */
31n/a#undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
32n/a#include <readline/readline.h>
33n/a#include <readline/history.h>
34n/a
35n/a#ifdef HAVE_RL_COMPLETION_MATCHES
36n/a#define completion_matches(x, y) \
37n/a rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
38n/a#else
39n/a#if defined(_RL_FUNCTION_TYPEDEF)
40n/aextern char **completion_matches(char *, rl_compentry_func_t *);
41n/a#else
42n/a
43n/a#if !defined(__APPLE__)
44n/aextern char **completion_matches(char *, CPFunction *);
45n/a#endif
46n/a#endif
47n/a#endif
48n/a
49n/a#ifdef __APPLE__
50n/a/*
51n/a * It is possible to link the readline module to the readline
52n/a * emulation library of editline/libedit.
53n/a *
54n/a * On OSX this emulation library is not 100% API compatible
55n/a * with the "real" readline and cannot be detected at compile-time,
56n/a * hence we use a runtime check to detect if we're using libedit
57n/a *
58n/a * Currently there is one known API incompatibility:
59n/a * - 'get_history' has a 1-based index with GNU readline, and a 0-based
60n/a * index with older versions of libedit's emulation.
61n/a * - Note that replace_history and remove_history use a 0-based index
62n/a * with both implementations.
63n/a */
64n/astatic int using_libedit_emulation = 0;
65n/astatic const char libedit_version_tag[] = "EditLine wrapper";
66n/a
67n/astatic int libedit_history_start = 0;
68n/a#endif /* __APPLE__ */
69n/a
70n/a#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
71n/astatic void
72n/aon_completion_display_matches_hook(char **matches,
73n/a int num_matches, int max_length);
74n/a#endif
75n/a
76n/a/* Memory allocated for rl_completer_word_break_characters
77n/a (see issue #17289 for the motivation). */
78n/astatic char *completer_word_break_characters;
79n/a
80n/atypedef struct {
81n/a /* Specify hook functions in Python */
82n/a PyObject *completion_display_matches_hook;
83n/a PyObject *startup_hook;
84n/a PyObject *pre_input_hook;
85n/a
86n/a PyObject *completer; /* Specify a word completer in Python */
87n/a PyObject *begidx;
88n/a PyObject *endidx;
89n/a} readlinestate;
90n/a
91n/a
92n/a#define readline_state(o) ((readlinestate *)PyModule_GetState(o))
93n/a
94n/astatic int
95n/areadline_clear(PyObject *m)
96n/a{
97n/a readlinestate *state = readline_state(m);
98n/a Py_CLEAR(state->completion_display_matches_hook);
99n/a Py_CLEAR(state->startup_hook);
100n/a Py_CLEAR(state->pre_input_hook);
101n/a Py_CLEAR(state->completer);
102n/a Py_CLEAR(state->begidx);
103n/a Py_CLEAR(state->endidx);
104n/a return 0;
105n/a}
106n/a
107n/astatic int
108n/areadline_traverse(PyObject *m, visitproc visit, void *arg)
109n/a{
110n/a readlinestate *state = readline_state(m);
111n/a Py_VISIT(state->completion_display_matches_hook);
112n/a Py_VISIT(state->startup_hook);
113n/a Py_VISIT(state->pre_input_hook);
114n/a Py_VISIT(state->completer);
115n/a Py_VISIT(state->begidx);
116n/a Py_VISIT(state->endidx);
117n/a return 0;
118n/a}
119n/a
120n/astatic void
121n/areadline_free(void *m)
122n/a{
123n/a readline_clear((PyObject *)m);
124n/a}
125n/a
126n/astatic PyModuleDef readlinemodule;
127n/a
128n/a#define readlinestate_global ((readlinestate *)PyModule_GetState(PyState_FindModule(&readlinemodule)))
129n/a
130n/a
131n/a/* Convert to/from multibyte C strings */
132n/a
133n/astatic PyObject *
134n/aencode(PyObject *b)
135n/a{
136n/a return PyUnicode_EncodeLocale(b, "surrogateescape");
137n/a}
138n/a
139n/astatic PyObject *
140n/adecode(const char *s)
141n/a{
142n/a return PyUnicode_DecodeLocale(s, "surrogateescape");
143n/a}
144n/a
145n/a
146n/a/* Exported function to send one line to readline's init file parser */
147n/a
148n/astatic PyObject *
149n/aparse_and_bind(PyObject *self, PyObject *string)
150n/a{
151n/a char *copy;
152n/a PyObject *encoded = encode(string);
153n/a if (encoded == NULL) {
154n/a return NULL;
155n/a }
156n/a /* Make a copy -- rl_parse_and_bind() modifies its argument */
157n/a /* Bernard Herzog */
158n/a copy = PyMem_Malloc(1 + PyBytes_GET_SIZE(encoded));
159n/a if (copy == NULL) {
160n/a Py_DECREF(encoded);
161n/a return PyErr_NoMemory();
162n/a }
163n/a strcpy(copy, PyBytes_AS_STRING(encoded));
164n/a Py_DECREF(encoded);
165n/a rl_parse_and_bind(copy);
166n/a PyMem_Free(copy); /* Free the copy */
167n/a Py_RETURN_NONE;
168n/a}
169n/a
170n/aPyDoc_STRVAR(doc_parse_and_bind,
171n/a"parse_and_bind(string) -> None\n\
172n/aExecute the init line provided in the string argument.");
173n/a
174n/a
175n/a/* Exported function to parse a readline init file */
176n/a
177n/astatic PyObject *
178n/aread_init_file(PyObject *self, PyObject *args)
179n/a{
180n/a PyObject *filename_obj = Py_None, *filename_bytes;
181n/a if (!PyArg_ParseTuple(args, "|O:read_init_file", &filename_obj))
182n/a return NULL;
183n/a if (filename_obj != Py_None) {
184n/a if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
185n/a return NULL;
186n/a errno = rl_read_init_file(PyBytes_AsString(filename_bytes));
187n/a Py_DECREF(filename_bytes);
188n/a } else
189n/a errno = rl_read_init_file(NULL);
190n/a if (errno)
191n/a return PyErr_SetFromErrno(PyExc_IOError);
192n/a Py_RETURN_NONE;
193n/a}
194n/a
195n/aPyDoc_STRVAR(doc_read_init_file,
196n/a"read_init_file([filename]) -> None\n\
197n/aExecute a readline initialization file.\n\
198n/aThe default filename is the last filename used.");
199n/a
200n/a
201n/a/* Exported function to load a readline history file */
202n/a
203n/astatic PyObject *
204n/aread_history_file(PyObject *self, PyObject *args)
205n/a{
206n/a PyObject *filename_obj = Py_None, *filename_bytes;
207n/a if (!PyArg_ParseTuple(args, "|O:read_history_file", &filename_obj))
208n/a return NULL;
209n/a if (filename_obj != Py_None) {
210n/a if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
211n/a return NULL;
212n/a errno = read_history(PyBytes_AsString(filename_bytes));
213n/a Py_DECREF(filename_bytes);
214n/a } else
215n/a errno = read_history(NULL);
216n/a if (errno)
217n/a return PyErr_SetFromErrno(PyExc_IOError);
218n/a Py_RETURN_NONE;
219n/a}
220n/a
221n/astatic int _history_length = -1; /* do not truncate history by default */
222n/aPyDoc_STRVAR(doc_read_history_file,
223n/a"read_history_file([filename]) -> None\n\
224n/aLoad a readline history file.\n\
225n/aThe default filename is ~/.history.");
226n/a
227n/a
228n/a/* Exported function to save a readline history file */
229n/a
230n/astatic PyObject *
231n/awrite_history_file(PyObject *self, PyObject *args)
232n/a{
233n/a PyObject *filename_obj = Py_None, *filename_bytes;
234n/a char *filename;
235n/a int err;
236n/a if (!PyArg_ParseTuple(args, "|O:write_history_file", &filename_obj))
237n/a return NULL;
238n/a if (filename_obj != Py_None) {
239n/a if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
240n/a return NULL;
241n/a filename = PyBytes_AsString(filename_bytes);
242n/a } else {
243n/a filename_bytes = NULL;
244n/a filename = NULL;
245n/a }
246n/a errno = err = write_history(filename);
247n/a if (!err && _history_length >= 0)
248n/a history_truncate_file(filename, _history_length);
249n/a Py_XDECREF(filename_bytes);
250n/a errno = err;
251n/a if (errno)
252n/a return PyErr_SetFromErrno(PyExc_IOError);
253n/a Py_RETURN_NONE;
254n/a}
255n/a
256n/aPyDoc_STRVAR(doc_write_history_file,
257n/a"write_history_file([filename]) -> None\n\
258n/aSave a readline history file.\n\
259n/aThe default filename is ~/.history.");
260n/a
261n/a
262n/a#ifdef HAVE_RL_APPEND_HISTORY
263n/a/* Exported function to save part of a readline history file */
264n/a
265n/astatic PyObject *
266n/aappend_history_file(PyObject *self, PyObject *args)
267n/a{
268n/a int nelements;
269n/a PyObject *filename_obj = Py_None, *filename_bytes;
270n/a char *filename;
271n/a int err;
272n/a if (!PyArg_ParseTuple(args, "i|O:append_history_file", &nelements, &filename_obj))
273n/a return NULL;
274n/a if (filename_obj != Py_None) {
275n/a if (!PyUnicode_FSConverter(filename_obj, &filename_bytes))
276n/a return NULL;
277n/a filename = PyBytes_AsString(filename_bytes);
278n/a } else {
279n/a filename_bytes = NULL;
280n/a filename = NULL;
281n/a }
282n/a errno = err = append_history(nelements, filename);
283n/a if (!err && _history_length >= 0)
284n/a history_truncate_file(filename, _history_length);
285n/a Py_XDECREF(filename_bytes);
286n/a errno = err;
287n/a if (errno)
288n/a return PyErr_SetFromErrno(PyExc_IOError);
289n/a Py_RETURN_NONE;
290n/a}
291n/a
292n/aPyDoc_STRVAR(doc_append_history_file,
293n/a"append_history_file(nelements[, filename]) -> None\n\
294n/aAppend the last nelements items of the history list to file.\n\
295n/aThe default filename is ~/.history.");
296n/a#endif
297n/a
298n/a
299n/a/* Set history length */
300n/a
301n/astatic PyObject*
302n/aset_history_length(PyObject *self, PyObject *args)
303n/a{
304n/a int length = _history_length;
305n/a if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
306n/a return NULL;
307n/a _history_length = length;
308n/a Py_RETURN_NONE;
309n/a}
310n/a
311n/aPyDoc_STRVAR(set_history_length_doc,
312n/a"set_history_length(length) -> None\n\
313n/aset the maximal number of lines which will be written to\n\
314n/athe history file. A negative length is used to inhibit\n\
315n/ahistory truncation.");
316n/a
317n/a
318n/a/* Get history length */
319n/a
320n/astatic PyObject*
321n/aget_history_length(PyObject *self, PyObject *noarg)
322n/a{
323n/a return PyLong_FromLong(_history_length);
324n/a}
325n/a
326n/aPyDoc_STRVAR(get_history_length_doc,
327n/a"get_history_length() -> int\n\
328n/areturn the maximum number of lines that will be written to\n\
329n/athe history file.");
330n/a
331n/a
332n/a/* Generic hook function setter */
333n/a
334n/astatic PyObject *
335n/aset_hook(const char *funcname, PyObject **hook_var, PyObject *args)
336n/a{
337n/a PyObject *function = Py_None;
338n/a char buf[80];
339n/a PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
340n/a if (!PyArg_ParseTuple(args, buf, &function))
341n/a return NULL;
342n/a if (function == Py_None) {
343n/a Py_CLEAR(*hook_var);
344n/a }
345n/a else if (PyCallable_Check(function)) {
346n/a Py_INCREF(function);
347n/a Py_XSETREF(*hook_var, function);
348n/a }
349n/a else {
350n/a PyErr_Format(PyExc_TypeError,
351n/a "set_%.50s(func): argument not callable",
352n/a funcname);
353n/a return NULL;
354n/a }
355n/a Py_RETURN_NONE;
356n/a}
357n/a
358n/a
359n/astatic PyObject *
360n/aset_completion_display_matches_hook(PyObject *self, PyObject *args)
361n/a{
362n/a PyObject *result = set_hook("completion_display_matches_hook",
363n/a &readlinestate_global->completion_display_matches_hook, args);
364n/a#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
365n/a /* We cannot set this hook globally, since it replaces the
366n/a default completion display. */
367n/a rl_completion_display_matches_hook =
368n/a readlinestate_global->completion_display_matches_hook ?
369n/a#if defined(_RL_FUNCTION_TYPEDEF)
370n/a (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
371n/a#else
372n/a (VFunction *)on_completion_display_matches_hook : 0;
373n/a#endif
374n/a#endif
375n/a return result;
376n/a
377n/a}
378n/a
379n/aPyDoc_STRVAR(doc_set_completion_display_matches_hook,
380n/a"set_completion_display_matches_hook([function]) -> None\n\
381n/aSet or remove the completion display function.\n\
382n/aThe function is called as\n\
383n/a function(substitution, [matches], longest_match_length)\n\
384n/aonce each time matches need to be displayed.");
385n/a
386n/astatic PyObject *
387n/aset_startup_hook(PyObject *self, PyObject *args)
388n/a{
389n/a return set_hook("startup_hook", &readlinestate_global->startup_hook, args);
390n/a}
391n/a
392n/aPyDoc_STRVAR(doc_set_startup_hook,
393n/a"set_startup_hook([function]) -> None\n\
394n/aSet or remove the function invoked by the rl_startup_hook callback.\n\
395n/aThe function is called with no arguments just\n\
396n/abefore readline prints the first prompt.");
397n/a
398n/a
399n/a#ifdef HAVE_RL_PRE_INPUT_HOOK
400n/a
401n/a/* Set pre-input hook */
402n/a
403n/astatic PyObject *
404n/aset_pre_input_hook(PyObject *self, PyObject *args)
405n/a{
406n/a return set_hook("pre_input_hook", &readlinestate_global->pre_input_hook, args);
407n/a}
408n/a
409n/aPyDoc_STRVAR(doc_set_pre_input_hook,
410n/a"set_pre_input_hook([function]) -> None\n\
411n/aSet or remove the function invoked by the rl_pre_input_hook callback.\n\
412n/aThe function is called with no arguments after the first prompt\n\
413n/ahas been printed and just before readline starts reading input\n\
414n/acharacters.");
415n/a
416n/a#endif
417n/a
418n/a
419n/a/* Get the completion type for the scope of the tab-completion */
420n/astatic PyObject *
421n/aget_completion_type(PyObject *self, PyObject *noarg)
422n/a{
423n/a return PyLong_FromLong(rl_completion_type);
424n/a}
425n/a
426n/aPyDoc_STRVAR(doc_get_completion_type,
427n/a"get_completion_type() -> int\n\
428n/aGet the type of completion being attempted.");
429n/a
430n/a
431n/a/* Get the beginning index for the scope of the tab-completion */
432n/a
433n/astatic PyObject *
434n/aget_begidx(PyObject *self, PyObject *noarg)
435n/a{
436n/a Py_INCREF(readlinestate_global->begidx);
437n/a return readlinestate_global->begidx;
438n/a}
439n/a
440n/aPyDoc_STRVAR(doc_get_begidx,
441n/a"get_begidx() -> int\n\
442n/aget the beginning index of the completion scope");
443n/a
444n/a
445n/a/* Get the ending index for the scope of the tab-completion */
446n/a
447n/astatic PyObject *
448n/aget_endidx(PyObject *self, PyObject *noarg)
449n/a{
450n/a Py_INCREF(readlinestate_global->endidx);
451n/a return readlinestate_global->endidx;
452n/a}
453n/a
454n/aPyDoc_STRVAR(doc_get_endidx,
455n/a"get_endidx() -> int\n\
456n/aget the ending index of the completion scope");
457n/a
458n/a
459n/a/* Set the tab-completion word-delimiters that readline uses */
460n/a
461n/astatic PyObject *
462n/aset_completer_delims(PyObject *self, PyObject *string)
463n/a{
464n/a char *break_chars;
465n/a PyObject *encoded = encode(string);
466n/a if (encoded == NULL) {
467n/a return NULL;
468n/a }
469n/a /* Keep a reference to the allocated memory in the module state in case
470n/a some other module modifies rl_completer_word_break_characters
471n/a (see issue #17289). */
472n/a break_chars = strdup(PyBytes_AS_STRING(encoded));
473n/a Py_DECREF(encoded);
474n/a if (break_chars) {
475n/a free(completer_word_break_characters);
476n/a completer_word_break_characters = break_chars;
477n/a rl_completer_word_break_characters = break_chars;
478n/a Py_RETURN_NONE;
479n/a }
480n/a else
481n/a return PyErr_NoMemory();
482n/a}
483n/a
484n/aPyDoc_STRVAR(doc_set_completer_delims,
485n/a"set_completer_delims(string) -> None\n\
486n/aset the word delimiters for completion");
487n/a
488n/a/* _py_free_history_entry: Utility function to free a history entry. */
489n/a
490n/a#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0500
491n/a
492n/a/* Readline version >= 5.0 introduced a timestamp field into the history entry
493n/a structure; this needs to be freed to avoid a memory leak. This version of
494n/a readline also introduced the handy 'free_history_entry' function, which
495n/a takes care of the timestamp. */
496n/a
497n/astatic void
498n/a_py_free_history_entry(HIST_ENTRY *entry)
499n/a{
500n/a histdata_t data = free_history_entry(entry);
501n/a free(data);
502n/a}
503n/a
504n/a#else
505n/a
506n/a/* No free_history_entry function; free everything manually. */
507n/a
508n/astatic void
509n/a_py_free_history_entry(HIST_ENTRY *entry)
510n/a{
511n/a if (entry->line)
512n/a free((void *)entry->line);
513n/a if (entry->data)
514n/a free(entry->data);
515n/a free(entry);
516n/a}
517n/a
518n/a#endif
519n/a
520n/astatic PyObject *
521n/apy_remove_history(PyObject *self, PyObject *args)
522n/a{
523n/a int entry_number;
524n/a HIST_ENTRY *entry;
525n/a
526n/a if (!PyArg_ParseTuple(args, "i:remove_history_item", &entry_number))
527n/a return NULL;
528n/a if (entry_number < 0) {
529n/a PyErr_SetString(PyExc_ValueError,
530n/a "History index cannot be negative");
531n/a return NULL;
532n/a }
533n/a entry = remove_history(entry_number);
534n/a if (!entry) {
535n/a PyErr_Format(PyExc_ValueError,
536n/a "No history item at position %d",
537n/a entry_number);
538n/a return NULL;
539n/a }
540n/a /* free memory allocated for the history entry */
541n/a _py_free_history_entry(entry);
542n/a Py_RETURN_NONE;
543n/a}
544n/a
545n/aPyDoc_STRVAR(doc_remove_history,
546n/a"remove_history_item(pos) -> None\n\
547n/aremove history item given by its position");
548n/a
549n/astatic PyObject *
550n/apy_replace_history(PyObject *self, PyObject *args)
551n/a{
552n/a int entry_number;
553n/a PyObject *line;
554n/a PyObject *encoded;
555n/a HIST_ENTRY *old_entry;
556n/a
557n/a if (!PyArg_ParseTuple(args, "iU:replace_history_item", &entry_number,
558n/a &line)) {
559n/a return NULL;
560n/a }
561n/a if (entry_number < 0) {
562n/a PyErr_SetString(PyExc_ValueError,
563n/a "History index cannot be negative");
564n/a return NULL;
565n/a }
566n/a encoded = encode(line);
567n/a if (encoded == NULL) {
568n/a return NULL;
569n/a }
570n/a old_entry = replace_history_entry(entry_number, PyBytes_AS_STRING(encoded), (void *)NULL);
571n/a Py_DECREF(encoded);
572n/a if (!old_entry) {
573n/a PyErr_Format(PyExc_ValueError,
574n/a "No history item at position %d",
575n/a entry_number);
576n/a return NULL;
577n/a }
578n/a /* free memory allocated for the old history entry */
579n/a _py_free_history_entry(old_entry);
580n/a Py_RETURN_NONE;
581n/a}
582n/a
583n/aPyDoc_STRVAR(doc_replace_history,
584n/a"replace_history_item(pos, line) -> None\n\
585n/areplaces history item given by its position with contents of line");
586n/a
587n/a/* Add a line to the history buffer */
588n/a
589n/astatic PyObject *
590n/apy_add_history(PyObject *self, PyObject *string)
591n/a{
592n/a PyObject *encoded = encode(string);
593n/a if (encoded == NULL) {
594n/a return NULL;
595n/a }
596n/a add_history(PyBytes_AS_STRING(encoded));
597n/a Py_DECREF(encoded);
598n/a Py_RETURN_NONE;
599n/a}
600n/a
601n/aPyDoc_STRVAR(doc_add_history,
602n/a"add_history(string) -> None\n\
603n/aadd an item to the history buffer");
604n/a
605n/astatic int should_auto_add_history = 1;
606n/a
607n/a/* Enable or disable automatic history */
608n/a
609n/astatic PyObject *
610n/apy_set_auto_history(PyObject *self, PyObject *args)
611n/a{
612n/a if (!PyArg_ParseTuple(args, "p:set_auto_history",
613n/a &should_auto_add_history)) {
614n/a return NULL;
615n/a }
616n/a Py_RETURN_NONE;
617n/a}
618n/a
619n/aPyDoc_STRVAR(doc_set_auto_history,
620n/a"set_auto_history(enabled) -> None\n\
621n/aEnables or disables automatic history.");
622n/a
623n/a
624n/a/* Get the tab-completion word-delimiters that readline uses */
625n/a
626n/astatic PyObject *
627n/aget_completer_delims(PyObject *self, PyObject *noarg)
628n/a{
629n/a return decode(rl_completer_word_break_characters);
630n/a}
631n/a
632n/aPyDoc_STRVAR(doc_get_completer_delims,
633n/a"get_completer_delims() -> string\n\
634n/aget the word delimiters for completion");
635n/a
636n/a
637n/a/* Set the completer function */
638n/a
639n/astatic PyObject *
640n/aset_completer(PyObject *self, PyObject *args)
641n/a{
642n/a return set_hook("completer", &readlinestate_global->completer, args);
643n/a}
644n/a
645n/aPyDoc_STRVAR(doc_set_completer,
646n/a"set_completer([function]) -> None\n\
647n/aSet or remove the completer function.\n\
648n/aThe function is called as function(text, state),\n\
649n/afor state in 0, 1, 2, ..., until it returns a non-string.\n\
650n/aIt should return the next possible completion starting with 'text'.");
651n/a
652n/a
653n/astatic PyObject *
654n/aget_completer(PyObject *self, PyObject *noargs)
655n/a{
656n/a if (readlinestate_global->completer == NULL) {
657n/a Py_RETURN_NONE;
658n/a }
659n/a Py_INCREF(readlinestate_global->completer);
660n/a return readlinestate_global->completer;
661n/a}
662n/a
663n/aPyDoc_STRVAR(doc_get_completer,
664n/a"get_completer() -> function\n\
665n/a\n\
666n/aReturns current completer function.");
667n/a
668n/a/* Private function to get current length of history. XXX It may be
669n/a * possible to replace this with a direct use of history_length instead,
670n/a * but it's not clear whether BSD's libedit keeps history_length up to date.
671n/a * See issue #8065.*/
672n/a
673n/astatic int
674n/a_py_get_history_length(void)
675n/a{
676n/a HISTORY_STATE *hist_st = history_get_history_state();
677n/a int length = hist_st->length;
678n/a /* the history docs don't say so, but the address of hist_st changes each
679n/a time history_get_history_state is called which makes me think it's
680n/a freshly malloc'd memory... on the other hand, the address of the last
681n/a line stays the same as long as history isn't extended, so it appears to
682n/a be malloc'd but managed by the history package... */
683n/a free(hist_st);
684n/a return length;
685n/a}
686n/a
687n/a/* Exported function to get any element of history */
688n/a
689n/astatic PyObject *
690n/aget_history_item(PyObject *self, PyObject *args)
691n/a{
692n/a int idx = 0;
693n/a HIST_ENTRY *hist_ent;
694n/a
695n/a if (!PyArg_ParseTuple(args, "i:get_history_item", &idx))
696n/a return NULL;
697n/a#ifdef __APPLE__
698n/a if (using_libedit_emulation) {
699n/a /* Older versions of libedit's readline emulation
700n/a * use 0-based indexes, while readline and newer
701n/a * versions of libedit use 1-based indexes.
702n/a */
703n/a int length = _py_get_history_length();
704n/a
705n/a idx = idx - 1 + libedit_history_start;
706n/a
707n/a /*
708n/a * Apple's readline emulation crashes when
709n/a * the index is out of range, therefore
710n/a * test for that and fail gracefully.
711n/a */
712n/a if (idx < (0 + libedit_history_start)
713n/a || idx >= (length + libedit_history_start)) {
714n/a Py_RETURN_NONE;
715n/a }
716n/a }
717n/a#endif /* __APPLE__ */
718n/a if ((hist_ent = history_get(idx)))
719n/a return decode(hist_ent->line);
720n/a else {
721n/a Py_RETURN_NONE;
722n/a }
723n/a}
724n/a
725n/aPyDoc_STRVAR(doc_get_history_item,
726n/a"get_history_item() -> string\n\
727n/areturn the current contents of history item at index.");
728n/a
729n/a
730n/a/* Exported function to get current length of history */
731n/a
732n/astatic PyObject *
733n/aget_current_history_length(PyObject *self, PyObject *noarg)
734n/a{
735n/a return PyLong_FromLong((long)_py_get_history_length());
736n/a}
737n/a
738n/aPyDoc_STRVAR(doc_get_current_history_length,
739n/a"get_current_history_length() -> integer\n\
740n/areturn the current (not the maximum) length of history.");
741n/a
742n/a
743n/a/* Exported function to read the current line buffer */
744n/a
745n/astatic PyObject *
746n/aget_line_buffer(PyObject *self, PyObject *noarg)
747n/a{
748n/a return decode(rl_line_buffer);
749n/a}
750n/a
751n/aPyDoc_STRVAR(doc_get_line_buffer,
752n/a"get_line_buffer() -> string\n\
753n/areturn the current contents of the line buffer.");
754n/a
755n/a
756n/a#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
757n/a
758n/a/* Exported function to clear the current history */
759n/a
760n/astatic PyObject *
761n/apy_clear_history(PyObject *self, PyObject *noarg)
762n/a{
763n/a clear_history();
764n/a Py_RETURN_NONE;
765n/a}
766n/a
767n/aPyDoc_STRVAR(doc_clear_history,
768n/a"clear_history() -> None\n\
769n/aClear the current readline history.");
770n/a#endif
771n/a
772n/a
773n/a/* Exported function to insert text into the line buffer */
774n/a
775n/astatic PyObject *
776n/ainsert_text(PyObject *self, PyObject *string)
777n/a{
778n/a PyObject *encoded = encode(string);
779n/a if (encoded == NULL) {
780n/a return NULL;
781n/a }
782n/a rl_insert_text(PyBytes_AS_STRING(encoded));
783n/a Py_DECREF(encoded);
784n/a Py_RETURN_NONE;
785n/a}
786n/a
787n/aPyDoc_STRVAR(doc_insert_text,
788n/a"insert_text(string) -> None\n\
789n/aInsert text into the line buffer at the cursor position.");
790n/a
791n/a
792n/a/* Redisplay the line buffer */
793n/a
794n/astatic PyObject *
795n/aredisplay(PyObject *self, PyObject *noarg)
796n/a{
797n/a rl_redisplay();
798n/a Py_RETURN_NONE;
799n/a}
800n/a
801n/aPyDoc_STRVAR(doc_redisplay,
802n/a"redisplay() -> None\n\
803n/aChange what's displayed on the screen to reflect the current\n\
804n/acontents of the line buffer.");
805n/a
806n/a
807n/a/* Table of functions exported by the module */
808n/a
809n/astatic struct PyMethodDef readline_methods[] =
810n/a{
811n/a {"parse_and_bind", parse_and_bind, METH_O, doc_parse_and_bind},
812n/a {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
813n/a {"insert_text", insert_text, METH_O, doc_insert_text},
814n/a {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
815n/a {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
816n/a {"read_history_file", read_history_file,
817n/a METH_VARARGS, doc_read_history_file},
818n/a {"write_history_file", write_history_file,
819n/a METH_VARARGS, doc_write_history_file},
820n/a#ifdef HAVE_RL_APPEND_HISTORY
821n/a {"append_history_file", append_history_file,
822n/a METH_VARARGS, doc_append_history_file},
823n/a#endif
824n/a {"get_history_item", get_history_item,
825n/a METH_VARARGS, doc_get_history_item},
826n/a {"get_current_history_length", (PyCFunction)get_current_history_length,
827n/a METH_NOARGS, doc_get_current_history_length},
828n/a {"set_history_length", set_history_length,
829n/a METH_VARARGS, set_history_length_doc},
830n/a {"get_history_length", get_history_length,
831n/a METH_NOARGS, get_history_length_doc},
832n/a {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
833n/a {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
834n/a {"get_completion_type", get_completion_type,
835n/a METH_NOARGS, doc_get_completion_type},
836n/a {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
837n/a {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
838n/a
839n/a {"set_completer_delims", set_completer_delims,
840n/a METH_O, doc_set_completer_delims},
841n/a {"set_auto_history", py_set_auto_history, METH_VARARGS, doc_set_auto_history},
842n/a {"add_history", py_add_history, METH_O, doc_add_history},
843n/a {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
844n/a {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
845n/a {"get_completer_delims", get_completer_delims,
846n/a METH_NOARGS, doc_get_completer_delims},
847n/a
848n/a {"set_completion_display_matches_hook", set_completion_display_matches_hook,
849n/a METH_VARARGS, doc_set_completion_display_matches_hook},
850n/a {"set_startup_hook", set_startup_hook,
851n/a METH_VARARGS, doc_set_startup_hook},
852n/a#ifdef HAVE_RL_PRE_INPUT_HOOK
853n/a {"set_pre_input_hook", set_pre_input_hook,
854n/a METH_VARARGS, doc_set_pre_input_hook},
855n/a#endif
856n/a#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
857n/a {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
858n/a#endif
859n/a {0, 0}
860n/a};
861n/a
862n/a
863n/a/* C function to call the Python hooks. */
864n/a
865n/astatic int
866n/aon_hook(PyObject *func)
867n/a{
868n/a int result = 0;
869n/a if (func != NULL) {
870n/a PyObject *r;
871n/a r = _PyObject_CallNoArg(func);
872n/a if (r == NULL)
873n/a goto error;
874n/a if (r == Py_None)
875n/a result = 0;
876n/a else {
877n/a result = _PyLong_AsInt(r);
878n/a if (result == -1 && PyErr_Occurred())
879n/a goto error;
880n/a }
881n/a Py_DECREF(r);
882n/a goto done;
883n/a error:
884n/a PyErr_Clear();
885n/a Py_XDECREF(r);
886n/a done:
887n/a return result;
888n/a }
889n/a return result;
890n/a}
891n/a
892n/astatic int
893n/a#if defined(_RL_FUNCTION_TYPEDEF)
894n/aon_startup_hook(void)
895n/a#else
896n/aon_startup_hook()
897n/a#endif
898n/a{
899n/a int r;
900n/a#ifdef WITH_THREAD
901n/a PyGILState_STATE gilstate = PyGILState_Ensure();
902n/a#endif
903n/a r = on_hook(readlinestate_global->startup_hook);
904n/a#ifdef WITH_THREAD
905n/a PyGILState_Release(gilstate);
906n/a#endif
907n/a return r;
908n/a}
909n/a
910n/a#ifdef HAVE_RL_PRE_INPUT_HOOK
911n/astatic int
912n/a#if defined(_RL_FUNCTION_TYPEDEF)
913n/aon_pre_input_hook(void)
914n/a#else
915n/aon_pre_input_hook()
916n/a#endif
917n/a{
918n/a int r;
919n/a#ifdef WITH_THREAD
920n/a PyGILState_STATE gilstate = PyGILState_Ensure();
921n/a#endif
922n/a r = on_hook(readlinestate_global->pre_input_hook);
923n/a#ifdef WITH_THREAD
924n/a PyGILState_Release(gilstate);
925n/a#endif
926n/a return r;
927n/a}
928n/a#endif
929n/a
930n/a
931n/a/* C function to call the Python completion_display_matches */
932n/a
933n/a#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
934n/astatic void
935n/aon_completion_display_matches_hook(char **matches,
936n/a int num_matches, int max_length)
937n/a{
938n/a int i;
939n/a PyObject *sub, *m=NULL, *s=NULL, *r=NULL;
940n/a#ifdef WITH_THREAD
941n/a PyGILState_STATE gilstate = PyGILState_Ensure();
942n/a#endif
943n/a m = PyList_New(num_matches);
944n/a if (m == NULL)
945n/a goto error;
946n/a for (i = 0; i < num_matches; i++) {
947n/a s = decode(matches[i+1]);
948n/a if (s == NULL)
949n/a goto error;
950n/a if (PyList_SetItem(m, i, s) == -1)
951n/a goto error;
952n/a }
953n/a sub = decode(matches[0]);
954n/a r = PyObject_CallFunction(readlinestate_global->completion_display_matches_hook,
955n/a "NNi", sub, m, max_length);
956n/a
957n/a m=NULL;
958n/a
959n/a if (r == NULL ||
960n/a (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
961n/a goto error;
962n/a }
963n/a Py_CLEAR(r);
964n/a
965n/a if (0) {
966n/a error:
967n/a PyErr_Clear();
968n/a Py_XDECREF(m);
969n/a Py_XDECREF(r);
970n/a }
971n/a#ifdef WITH_THREAD
972n/a PyGILState_Release(gilstate);
973n/a#endif
974n/a}
975n/a
976n/a#endif
977n/a
978n/a#ifdef HAVE_RL_RESIZE_TERMINAL
979n/astatic volatile sig_atomic_t sigwinch_received;
980n/astatic PyOS_sighandler_t sigwinch_ohandler;
981n/a
982n/astatic void
983n/areadline_sigwinch_handler(int signum)
984n/a{
985n/a sigwinch_received = 1;
986n/a if (sigwinch_ohandler &&
987n/a sigwinch_ohandler != SIG_IGN && sigwinch_ohandler != SIG_DFL)
988n/a sigwinch_ohandler(signum);
989n/a
990n/a#ifndef HAVE_SIGACTION
991n/a /* If the handler was installed with signal() rather than sigaction(),
992n/a we need to reinstall it. */
993n/a PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
994n/a#endif
995n/a}
996n/a#endif
997n/a
998n/a/* C function to call the Python completer. */
999n/a
1000n/astatic char *
1001n/aon_completion(const char *text, int state)
1002n/a{
1003n/a char *result = NULL;
1004n/a if (readlinestate_global->completer != NULL) {
1005n/a PyObject *r = NULL, *t;
1006n/a#ifdef WITH_THREAD
1007n/a PyGILState_STATE gilstate = PyGILState_Ensure();
1008n/a#endif
1009n/a rl_attempted_completion_over = 1;
1010n/a t = decode(text);
1011n/a r = PyObject_CallFunction(readlinestate_global->completer, "Ni", t, state);
1012n/a if (r == NULL)
1013n/a goto error;
1014n/a if (r == Py_None) {
1015n/a result = NULL;
1016n/a }
1017n/a else {
1018n/a PyObject *encoded = encode(r);
1019n/a if (encoded == NULL)
1020n/a goto error;
1021n/a result = strdup(PyBytes_AS_STRING(encoded));
1022n/a Py_DECREF(encoded);
1023n/a }
1024n/a Py_DECREF(r);
1025n/a goto done;
1026n/a error:
1027n/a PyErr_Clear();
1028n/a Py_XDECREF(r);
1029n/a done:
1030n/a#ifdef WITH_THREAD
1031n/a PyGILState_Release(gilstate);
1032n/a#endif
1033n/a return result;
1034n/a }
1035n/a return result;
1036n/a}
1037n/a
1038n/a
1039n/a/* A more flexible constructor that saves the "begidx" and "endidx"
1040n/a * before calling the normal completer */
1041n/a
1042n/astatic char **
1043n/aflex_complete(const char *text, int start, int end)
1044n/a{
1045n/a char **result;
1046n/a char saved;
1047n/a size_t start_size, end_size;
1048n/a wchar_t *s;
1049n/a#ifdef WITH_THREAD
1050n/a PyGILState_STATE gilstate = PyGILState_Ensure();
1051n/a#endif
1052n/a#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1053n/a rl_completion_append_character ='\0';
1054n/a#endif
1055n/a#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
1056n/a rl_completion_suppress_append = 0;
1057n/a#endif
1058n/a
1059n/a saved = rl_line_buffer[start];
1060n/a rl_line_buffer[start] = 0;
1061n/a s = Py_DecodeLocale(rl_line_buffer, &start_size);
1062n/a rl_line_buffer[start] = saved;
1063n/a if (s == NULL) {
1064n/a goto done;
1065n/a }
1066n/a PyMem_RawFree(s);
1067n/a saved = rl_line_buffer[end];
1068n/a rl_line_buffer[end] = 0;
1069n/a s = Py_DecodeLocale(rl_line_buffer + start, &end_size);
1070n/a rl_line_buffer[end] = saved;
1071n/a if (s == NULL) {
1072n/a goto done;
1073n/a }
1074n/a PyMem_RawFree(s);
1075n/a start = (int)start_size;
1076n/a end = start + (int)end_size;
1077n/a
1078n/adone:
1079n/a Py_XDECREF(readlinestate_global->begidx);
1080n/a Py_XDECREF(readlinestate_global->endidx);
1081n/a readlinestate_global->begidx = PyLong_FromLong((long) start);
1082n/a readlinestate_global->endidx = PyLong_FromLong((long) end);
1083n/a result = completion_matches((char *)text, *on_completion);
1084n/a#ifdef WITH_THREAD
1085n/a PyGILState_Release(gilstate);
1086n/a#endif
1087n/a return result;
1088n/a}
1089n/a
1090n/a
1091n/a/* Helper to initialize GNU readline properly. */
1092n/a
1093n/astatic void
1094n/asetup_readline(readlinestate *mod_state)
1095n/a{
1096n/a#ifdef SAVE_LOCALE
1097n/a char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1098n/a if (!saved_locale)
1099n/a Py_FatalError("not enough memory to save locale");
1100n/a#endif
1101n/a
1102n/a#ifdef __APPLE__
1103n/a /* the libedit readline emulation resets key bindings etc
1104n/a * when calling rl_initialize. So call it upfront
1105n/a */
1106n/a if (using_libedit_emulation)
1107n/a rl_initialize();
1108n/a
1109n/a /* Detect if libedit's readline emulation uses 0-based
1110n/a * indexing or 1-based indexing.
1111n/a */
1112n/a add_history("1");
1113n/a if (history_get(1) == NULL) {
1114n/a libedit_history_start = 0;
1115n/a } else {
1116n/a libedit_history_start = 1;
1117n/a }
1118n/a clear_history();
1119n/a#endif /* __APPLE__ */
1120n/a
1121n/a using_history();
1122n/a
1123n/a rl_readline_name = "python";
1124n/a /* Force rebind of TAB to insert-tab */
1125n/a rl_bind_key('\t', rl_insert);
1126n/a /* Bind both ESC-TAB and ESC-ESC to the completion function */
1127n/a rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
1128n/a rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
1129n/a#ifdef HAVE_RL_RESIZE_TERMINAL
1130n/a /* Set up signal handler for window resize */
1131n/a sigwinch_ohandler = PyOS_setsig(SIGWINCH, readline_sigwinch_handler);
1132n/a#endif
1133n/a /* Set our hook functions */
1134n/a rl_startup_hook = on_startup_hook;
1135n/a#ifdef HAVE_RL_PRE_INPUT_HOOK
1136n/a rl_pre_input_hook = on_pre_input_hook;
1137n/a#endif
1138n/a /* Set our completion function */
1139n/a rl_attempted_completion_function = flex_complete;
1140n/a /* Set Python word break characters */
1141n/a completer_word_break_characters =
1142n/a rl_completer_word_break_characters =
1143n/a strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
1144n/a /* All nonalphanums except '.' */
1145n/a
1146n/a mod_state->begidx = PyLong_FromLong(0L);
1147n/a mod_state->endidx = PyLong_FromLong(0L);
1148n/a
1149n/a#ifdef __APPLE__
1150n/a if (!using_libedit_emulation)
1151n/a#endif
1152n/a {
1153n/a if (!isatty(STDOUT_FILENO)) {
1154n/a /* Issue #19884: stdout is not a terminal. Disable meta modifier
1155n/a keys to not write the ANSI sequence "\033[1034h" into stdout. On
1156n/a terminals supporting 8 bit characters like TERM=xterm-256color
1157n/a (which is now the default Fedora since Fedora 18), the meta key is
1158n/a used to enable support of 8 bit characters (ANSI sequence
1159n/a "\033[1034h").
1160n/a
1161n/a With libedit, this call makes readline() crash. */
1162n/a rl_variable_bind ("enable-meta-key", "off");
1163n/a }
1164n/a }
1165n/a
1166n/a /* Initialize (allows .inputrc to override)
1167n/a *
1168n/a * XXX: A bug in the readline-2.2 library causes a memory leak
1169n/a * inside this function. Nothing we can do about it.
1170n/a */
1171n/a#ifdef __APPLE__
1172n/a if (using_libedit_emulation)
1173n/a rl_read_init_file(NULL);
1174n/a else
1175n/a#endif /* __APPLE__ */
1176n/a rl_initialize();
1177n/a
1178n/a RESTORE_LOCALE(saved_locale)
1179n/a}
1180n/a
1181n/a/* Wrapper around GNU readline that handles signals differently. */
1182n/a
1183n/a
1184n/a#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
1185n/a
1186n/astatic char *completed_input_string;
1187n/astatic void
1188n/arlhandler(char *text)
1189n/a{
1190n/a completed_input_string = text;
1191n/a rl_callback_handler_remove();
1192n/a}
1193n/a
1194n/astatic char *
1195n/areadline_until_enter_or_signal(const char *prompt, int *signal)
1196n/a{
1197n/a char * not_done_reading = "";
1198n/a fd_set selectset;
1199n/a
1200n/a *signal = 0;
1201n/a#ifdef HAVE_RL_CATCH_SIGNAL
1202n/a rl_catch_signals = 0;
1203n/a#endif
1204n/a
1205n/a rl_callback_handler_install (prompt, rlhandler);
1206n/a FD_ZERO(&selectset);
1207n/a
1208n/a completed_input_string = not_done_reading;
1209n/a
1210n/a while (completed_input_string == not_done_reading) {
1211n/a int has_input = 0, err = 0;
1212n/a
1213n/a while (!has_input)
1214n/a { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
1215n/a
1216n/a /* [Bug #1552726] Only limit the pause if an input hook has been
1217n/a defined. */
1218n/a struct timeval *timeoutp = NULL;
1219n/a if (PyOS_InputHook)
1220n/a timeoutp = &timeout;
1221n/a#ifdef HAVE_RL_RESIZE_TERMINAL
1222n/a /* Update readline's view of the window size after SIGWINCH */
1223n/a if (sigwinch_received) {
1224n/a sigwinch_received = 0;
1225n/a rl_resize_terminal();
1226n/a }
1227n/a#endif
1228n/a FD_SET(fileno(rl_instream), &selectset);
1229n/a /* select resets selectset if no input was available */
1230n/a has_input = select(fileno(rl_instream) + 1, &selectset,
1231n/a NULL, NULL, timeoutp);
1232n/a err = errno;
1233n/a if(PyOS_InputHook) PyOS_InputHook();
1234n/a }
1235n/a
1236n/a if (has_input > 0) {
1237n/a rl_callback_read_char();
1238n/a }
1239n/a else if (err == EINTR) {
1240n/a int s;
1241n/a#ifdef WITH_THREAD
1242n/a PyEval_RestoreThread(_PyOS_ReadlineTState);
1243n/a#endif
1244n/a s = PyErr_CheckSignals();
1245n/a#ifdef WITH_THREAD
1246n/a PyEval_SaveThread();
1247n/a#endif
1248n/a if (s < 0) {
1249n/a rl_free_line_state();
1250n/a#if defined(RL_READLINE_VERSION) && RL_READLINE_VERSION >= 0x0700
1251n/a rl_callback_sigcleanup();
1252n/a#endif
1253n/a rl_cleanup_after_signal();
1254n/a rl_callback_handler_remove();
1255n/a *signal = 1;
1256n/a completed_input_string = NULL;
1257n/a }
1258n/a }
1259n/a }
1260n/a
1261n/a return completed_input_string;
1262n/a}
1263n/a
1264n/a
1265n/a#else
1266n/a
1267n/a/* Interrupt handler */
1268n/a
1269n/astatic jmp_buf jbuf;
1270n/a
1271n/a/* ARGSUSED */
1272n/astatic void
1273n/aonintr(int sig)
1274n/a{
1275n/a longjmp(jbuf, 1);
1276n/a}
1277n/a
1278n/a
1279n/astatic char *
1280n/areadline_until_enter_or_signal(const char *prompt, int *signal)
1281n/a{
1282n/a PyOS_sighandler_t old_inthandler;
1283n/a char *p;
1284n/a
1285n/a *signal = 0;
1286n/a
1287n/a old_inthandler = PyOS_setsig(SIGINT, onintr);
1288n/a if (setjmp(jbuf)) {
1289n/a#ifdef HAVE_SIGRELSE
1290n/a /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
1291n/a sigrelse(SIGINT);
1292n/a#endif
1293n/a PyOS_setsig(SIGINT, old_inthandler);
1294n/a *signal = 1;
1295n/a return NULL;
1296n/a }
1297n/a rl_event_hook = PyOS_InputHook;
1298n/a p = readline(prompt);
1299n/a PyOS_setsig(SIGINT, old_inthandler);
1300n/a
1301n/a return p;
1302n/a}
1303n/a#endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */
1304n/a
1305n/a
1306n/astatic char *
1307n/acall_readline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt)
1308n/a{
1309n/a size_t n;
1310n/a char *p, *q;
1311n/a int signal;
1312n/a
1313n/a#ifdef SAVE_LOCALE
1314n/a char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
1315n/a if (!saved_locale)
1316n/a Py_FatalError("not enough memory to save locale");
1317n/a setlocale(LC_CTYPE, "");
1318n/a#endif
1319n/a
1320n/a if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
1321n/a rl_instream = sys_stdin;
1322n/a rl_outstream = sys_stdout;
1323n/a#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
1324n/a rl_prep_terminal (1);
1325n/a#endif
1326n/a }
1327n/a
1328n/a p = readline_until_enter_or_signal(prompt, &signal);
1329n/a
1330n/a /* we got an interrupt signal */
1331n/a if (signal) {
1332n/a RESTORE_LOCALE(saved_locale)
1333n/a return NULL;
1334n/a }
1335n/a
1336n/a /* We got an EOF, return an empty string. */
1337n/a if (p == NULL) {
1338n/a p = PyMem_RawMalloc(1);
1339n/a if (p != NULL)
1340n/a *p = '\0';
1341n/a RESTORE_LOCALE(saved_locale)
1342n/a return p;
1343n/a }
1344n/a
1345n/a /* we have a valid line */
1346n/a n = strlen(p);
1347n/a if (should_auto_add_history && n > 0) {
1348n/a const char *line;
1349n/a int length = _py_get_history_length();
1350n/a if (length > 0)
1351n/a#ifdef __APPLE__
1352n/a if (using_libedit_emulation) {
1353n/a /* handle older 0-based or newer 1-based indexing */
1354n/a line = (const char *)history_get(length + libedit_history_start - 1)->line;
1355n/a } else
1356n/a#endif /* __APPLE__ */
1357n/a line = (const char *)history_get(length)->line;
1358n/a else
1359n/a line = "";
1360n/a if (strcmp(p, line))
1361n/a add_history(p);
1362n/a }
1363n/a /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
1364n/a release the original. */
1365n/a q = p;
1366n/a p = PyMem_RawMalloc(n+2);
1367n/a if (p != NULL) {
1368n/a strncpy(p, q, n);
1369n/a p[n] = '\n';
1370n/a p[n+1] = '\0';
1371n/a }
1372n/a free(q);
1373n/a RESTORE_LOCALE(saved_locale)
1374n/a return p;
1375n/a}
1376n/a
1377n/a
1378n/a/* Initialize the module */
1379n/a
1380n/aPyDoc_STRVAR(doc_module,
1381n/a"Importing this module enables command line editing using GNU readline.");
1382n/a
1383n/a#ifdef __APPLE__
1384n/aPyDoc_STRVAR(doc_module_le,
1385n/a"Importing this module enables command line editing using libedit readline.");
1386n/a#endif /* __APPLE__ */
1387n/a
1388n/astatic struct PyModuleDef readlinemodule = {
1389n/a PyModuleDef_HEAD_INIT,
1390n/a "readline",
1391n/a doc_module,
1392n/a sizeof(readlinestate),
1393n/a readline_methods,
1394n/a NULL,
1395n/a readline_traverse,
1396n/a readline_clear,
1397n/a readline_free
1398n/a};
1399n/a
1400n/a
1401n/aPyMODINIT_FUNC
1402n/aPyInit_readline(void)
1403n/a{
1404n/a PyObject *m;
1405n/a readlinestate *mod_state;
1406n/a
1407n/a#ifdef __APPLE__
1408n/a if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
1409n/a using_libedit_emulation = 1;
1410n/a }
1411n/a
1412n/a if (using_libedit_emulation)
1413n/a readlinemodule.m_doc = doc_module_le;
1414n/a
1415n/a#endif /* __APPLE__ */
1416n/a
1417n/a m = PyModule_Create(&readlinemodule);
1418n/a
1419n/a if (m == NULL)
1420n/a return NULL;
1421n/a
1422n/a mod_state = (readlinestate *) PyModule_GetState(m);
1423n/a PyOS_ReadlineFunctionPointer = call_readline;
1424n/a setup_readline(mod_state);
1425n/a
1426n/a PyModule_AddIntConstant(m, "_READLINE_VERSION", RL_READLINE_VERSION);
1427n/a PyModule_AddIntConstant(m, "_READLINE_RUNTIME_VERSION", rl_readline_version);
1428n/a
1429n/a return m;
1430n/a}