readline.c 22 KB
Newer Older
1 2
/* This module makes GNU readline available to Python.  It has ideas
 * contributed by Lee Busby, LLNL, and William Magro, Cornell Theory
3 4
 * Center.  The completer interface was inspired by Lele Gaifax.  More
 * recently, it was largely rewritten by Guido van Rossum.
5 6
 */

7
/* Standard definitions */
8 9 10
#include "Python.h"
#include <setjmp.h>
#include <signal.h>
11
#include <errno.h>
12
#include <sys/time.h>
13

14
#if defined(HAVE_SETLOCALE)
15 16 17 18 19 20 21 22
/* GNU readline() mistakenly sets the LC_CTYPE locale.
 * This is evil.  Only the user or the app's main() should do this!
 * We must save and restore the locale around the rl_initialize() call.
 */
#define SAVE_LOCALE
#include <locale.h>
#endif

23
/* GNU readline definitions */
24
#undef HAVE_CONFIG_H /* Else readline/chardefs.h includes strings.h */
25 26
#include <readline/readline.h>
#include <readline/history.h>
27

28
#ifdef HAVE_RL_COMPLETION_MATCHES
Guido van Rossum's avatar
Guido van Rossum committed
29 30
#define completion_matches(x, y) \
	rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
31 32
#endif

33

34 35 36
/* Exported function to send one line to readline's init file parser */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
37
parse_and_bind(PyObject *self, PyObject *args)
38
{
39
	char *s, *copy;
40
	if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
41
		return NULL;
42 43 44 45 46 47 48 49
	/* Make a copy -- rl_parse_and_bind() modifies its argument */
	/* Bernard Herzog */
	copy = malloc(1 + strlen(s));
	if (copy == NULL)
		return PyErr_NoMemory();
	strcpy(copy, s);
	rl_parse_and_bind(copy);
	free(copy); /* Free the copy */
50 51 52 53
	Py_INCREF(Py_None);
	return Py_None;
}

54 55 56
PyDoc_STRVAR(doc_parse_and_bind,
"parse_and_bind(string) -> None\n\
Parse and execute single line of a readline init file.");
57 58 59 60 61


/* Exported function to parse a readline init file */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
62
read_init_file(PyObject *self, PyObject *args)
63 64
{
	char *s = NULL;
65
	if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
66 67 68 69 70 71 72 73
		return NULL;
	errno = rl_read_init_file(s);
	if (errno)
		return PyErr_SetFromErrno(PyExc_IOError);
	Py_INCREF(Py_None);
	return Py_None;
}

74 75
PyDoc_STRVAR(doc_read_init_file,
"read_init_file([filename]) -> None\n\
76
Parse a readline initialization file.\n\
77
The default filename is the last filename used.");
78 79


80 81 82
/* Exported function to load a readline history file */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
83
read_history_file(PyObject *self, PyObject *args)
84 85 86 87 88 89 90 91 92 93 94
{
	char *s = NULL;
	if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
		return NULL;
	errno = read_history(s);
	if (errno)
		return PyErr_SetFromErrno(PyExc_IOError);
	Py_INCREF(Py_None);
	return Py_None;
}

95
static int _history_length = -1; /* do not truncate history by default */
96 97
PyDoc_STRVAR(doc_read_history_file,
"read_history_file([filename]) -> None\n\
98
Load a readline history file.\n\
99
The default filename is ~/.history.");
100 101 102 103 104


/* Exported function to save a readline history file */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
105
write_history_file(PyObject *self, PyObject *args)
106 107 108 109 110
{
	char *s = NULL;
	if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
		return NULL;
	errno = write_history(s);
111 112
	if (!errno && _history_length >= 0)
		history_truncate_file(s, _history_length);
113 114 115 116 117 118
	if (errno)
		return PyErr_SetFromErrno(PyExc_IOError);
	Py_INCREF(Py_None);
	return Py_None;
}

119 120
PyDoc_STRVAR(doc_write_history_file,
"write_history_file([filename]) -> None\n\
121
Save a readline history file.\n\
122
The default filename is ~/.history.");
123 124


Guido van Rossum's avatar
Guido van Rossum committed
125
/* Set history length */
126 127 128 129

static PyObject*
set_history_length(PyObject *self, PyObject *args)
{
130
	int length = _history_length;
Guido van Rossum's avatar
Guido van Rossum committed
131 132
	if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
		return NULL;
133
	_history_length = length;
Guido van Rossum's avatar
Guido van Rossum committed
134 135
	Py_INCREF(Py_None);
	return Py_None;
136 137
}

Guido van Rossum's avatar
Guido van Rossum committed
138 139 140 141 142
PyDoc_STRVAR(set_history_length_doc,
"set_history_length(length) -> None\n\
set the maximal number of items which will be written to\n\
the history file. A negative length is used to inhibit\n\
history truncation.");
143 144


Guido van Rossum's avatar
Guido van Rossum committed
145
/* Get history length */
146 147

static PyObject*
148
get_history_length(PyObject *self, PyObject *noarg)
149
{
150
	return PyInt_FromLong(_history_length);
151 152
}

Guido van Rossum's avatar
Guido van Rossum committed
153 154 155 156 157 158
PyDoc_STRVAR(get_history_length_doc,
"get_history_length() -> int\n\
return the maximum number of items that will be written to\n\
the history file.");


159
/* Generic hook function setter */
160

161
static PyObject *
Michael W. Hudson's avatar
Michael W. Hudson committed
162
set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
163 164 165
{
	PyObject *function = Py_None;
	char buf[80];
166
	PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
167 168 169 170 171 172 173 174 175 176 177 178 179
	if (!PyArg_ParseTuple(args, buf, &function))
		return NULL;
	if (function == Py_None) {
		Py_XDECREF(*hook_var);
		*hook_var = NULL;
	}
	else if (PyCallable_Check(function)) {
		PyObject *tmp = *hook_var;
		Py_INCREF(function);
		*hook_var = function;
		Py_XDECREF(tmp);
	}
	else {
180 181 182
		PyOS_snprintf(buf, sizeof(buf),
			      "set_%.50s(func): argument not callable",
			      funcname);
183 184 185 186 187 188 189
		PyErr_SetString(PyExc_TypeError, buf);
		return NULL;
	}
	Py_INCREF(Py_None);
	return Py_None;
}

Guido van Rossum's avatar
Guido van Rossum committed
190

191 192 193 194 195 196 197 198 199 200 201
/* Exported functions to specify hook functions in Python */

static PyObject *startup_hook = NULL;

#ifdef HAVE_RL_PRE_INPUT_HOOK
static PyObject *pre_input_hook = NULL;
#endif

static PyObject *
set_startup_hook(PyObject *self, PyObject *args)
{
Michael W. Hudson's avatar
Michael W. Hudson committed
202
	return set_hook("startup_hook", &startup_hook, args);
203 204
}

205 206
PyDoc_STRVAR(doc_set_startup_hook,
"set_startup_hook([function]) -> None\n\
207 208
Set or remove the startup_hook function.\n\
The function is called with no arguments just\n\
209
before readline prints the first prompt.");
210

Guido van Rossum's avatar
Guido van Rossum committed
211

212
#ifdef HAVE_RL_PRE_INPUT_HOOK
Guido van Rossum's avatar
Guido van Rossum committed
213 214 215

/* Set pre-input hook */

216 217 218
static PyObject *
set_pre_input_hook(PyObject *self, PyObject *args)
{
Michael W. Hudson's avatar
Michael W. Hudson committed
219
	return set_hook("pre_input_hook", &pre_input_hook, args);
220 221
}

222 223
PyDoc_STRVAR(doc_set_pre_input_hook,
"set_pre_input_hook([function]) -> None\n\
224 225 226
Set or remove the pre_input_hook function.\n\
The function is called with no arguments after the first prompt\n\
has been printed and just before readline starts reading input\n\
227
characters.");
Guido van Rossum's avatar
Guido van Rossum committed
228

229
#endif
230

Guido van Rossum's avatar
Guido van Rossum committed
231

232 233 234 235
/* Exported function to specify a word completer in Python */

static PyObject *completer = NULL;

236 237 238
static PyObject *begidx = NULL;
static PyObject *endidx = NULL;

Guido van Rossum's avatar
Guido van Rossum committed
239 240 241

/* Get the beginning index for the scope of the tab-completion */

242
static PyObject *
243
get_begidx(PyObject *self, PyObject *noarg)
244 245 246 247 248
{
	Py_INCREF(begidx);
	return begidx;
}

249 250 251
PyDoc_STRVAR(doc_get_begidx,
"get_begidx() -> int\n\
get the beginning index of the readline tab-completion scope");
252

Guido van Rossum's avatar
Guido van Rossum committed
253 254 255

/* Get the ending index for the scope of the tab-completion */

256
static PyObject *
257
get_endidx(PyObject *self, PyObject *noarg)
258 259 260 261 262
{
	Py_INCREF(endidx);
	return endidx;
}

263 264 265
PyDoc_STRVAR(doc_get_endidx,
"get_endidx() -> int\n\
get the ending index of the readline tab-completion scope");
266 267


Guido van Rossum's avatar
Guido van Rossum committed
268
/* Set the tab-completion word-delimiters that readline uses */
269 270

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
271
set_completer_delims(PyObject *self, PyObject *args)
272 273 274
{
	char *break_chars;

275
	if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
276 277
		return NULL;
	}
278
	free((void*)rl_completer_word_break_characters);
279 280 281 282 283
	rl_completer_word_break_characters = strdup(break_chars);
	Py_INCREF(Py_None);
	return Py_None;
}

284 285 286
PyDoc_STRVAR(doc_set_completer_delims,
"set_completer_delims(string) -> None\n\
set the readline word delimiters for tab-completion");
287

288 289 290 291 292 293 294 295
static PyObject *
py_remove_history(PyObject *self, PyObject *args)
{
        int entry_number;
        HIST_ENTRY *entry;

        if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
                return NULL;
296 297 298 299 300
        if (entry_number < 0) {
                PyErr_SetString(PyExc_ValueError,
                                "History index cannot be negative");
                return NULL;
        }
301 302
        entry = remove_history(entry_number);
        if (!entry) {
303 304 305
                PyErr_Format(PyExc_ValueError,
                             "No history item at position %d",
                             entry_number);
306 307 308 309 310 311 312 313 314 315 316 317 318 319
                return NULL;
        }
        /* free memory allocated for the history entry */
        if (entry->line)
                free(entry->line);
        if (entry->data)
                free(entry->data);
        free(entry);

        Py_INCREF(Py_None);
        return Py_None;
}

PyDoc_STRVAR(doc_remove_history,
320
"remove_history_item(pos) -> None\n\
321 322 323 324 325 326 327 328 329 330 331 332
remove history item given by its position");

static PyObject *
py_replace_history(PyObject *self, PyObject *args)
{
        int entry_number;
        char *line;
        HIST_ENTRY *old_entry;

        if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, &line)) {
                return NULL;
        }
333 334 335 336 337
        if (entry_number < 0) {
                PyErr_SetString(PyExc_ValueError,
                                "History index cannot be negative");
                return NULL;
        }
338 339
        old_entry = replace_history_entry(entry_number, line, (void *)NULL);
        if (!old_entry) {
340 341 342
                PyErr_Format(PyExc_ValueError,
                             "No history item at position %d",
                             entry_number);
343 344 345 346 347 348 349 350 351 352 353 354 355 356
                return NULL;
        }
        /* free memory allocated for the old history entry */
        if (old_entry->line)
            free(old_entry->line);
        if (old_entry->data)
            free(old_entry->data);
        free(old_entry);

        Py_INCREF(Py_None);
        return Py_None;
}

PyDoc_STRVAR(doc_replace_history,
357
"replace_history_item(pos, line) -> None\n\
358
replaces history item given by its position with contents of line");
Guido van Rossum's avatar
Guido van Rossum committed
359 360 361

/* Add a line to the history buffer */

362 363 364 365 366 367 368 369 370 371 372 373 374
static PyObject *
py_add_history(PyObject *self, PyObject *args)
{
	char *line;

	if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
		return NULL;
	}
	add_history(line);
	Py_INCREF(Py_None);
	return Py_None;
}

375 376 377
PyDoc_STRVAR(doc_add_history,
"add_history(string) -> None\n\
add a line to the history buffer");
378

379

Guido van Rossum's avatar
Guido van Rossum committed
380
/* Get the tab-completion word-delimiters that readline uses */
381 382

static PyObject *
383
get_completer_delims(PyObject *self, PyObject *noarg)
384 385 386
{
	return PyString_FromString(rl_completer_word_break_characters);
}
Guido van Rossum's avatar
Guido van Rossum committed
387

388 389 390
PyDoc_STRVAR(doc_get_completer_delims,
"get_completer_delims() -> string\n\
get the readline word delimiters for tab-completion");
391

Guido van Rossum's avatar
Guido van Rossum committed
392 393 394

/* Set the completer function */

395
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
396
set_completer(PyObject *self, PyObject *args)
397
{
Michael W. Hudson's avatar
Michael W. Hudson committed
398
	return set_hook("completer", &completer, args);
399 400
}

401 402
PyDoc_STRVAR(doc_set_completer,
"set_completer([function]) -> None\n\
403 404
Set or remove the completer function.\n\
The function is called as function(text, state),\n\
405
for state in 0, 1, 2, ..., until it returns a non-string.\n\
406
It should return the next possible completion starting with 'text'.");
407

Guido van Rossum's avatar
Guido van Rossum committed
408

409
static PyObject *
410
get_completer(PyObject *self, PyObject *noargs)
411 412 413 414 415 416 417 418 419 420 421 422 423 424
{
	if (completer == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
	Py_INCREF(completer);
	return completer;
}

PyDoc_STRVAR(doc_get_completer,
"get_completer() -> function\n\
\n\
Returns current completer function.");

425 426 427 428 429 430 431 432 433 434 435
/* Exported function to get any element of history */

static PyObject *
get_history_item(PyObject *self, PyObject *args)
{
	int idx = 0;
	HIST_ENTRY *hist_ent;

	if (!PyArg_ParseTuple(args, "i:index", &idx))
		return NULL;
	if ((hist_ent = history_get(idx)))
436
		return PyString_FromString(hist_ent->line);
437 438 439 440 441 442
	else {
		Py_INCREF(Py_None);
		return Py_None;
	}
}

443 444 445
PyDoc_STRVAR(doc_get_history_item,
"get_history_item() -> string\n\
return the current contents of history item at index.");
446

Guido van Rossum's avatar
Guido van Rossum committed
447

448 449 450
/* Exported function to get current length of history */

static PyObject *
451
get_current_history_length(PyObject *self, PyObject *noarg)
452 453 454 455 456 457 458
{
	HISTORY_STATE *hist_st;

	hist_st = history_get_history_state();
	return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
}

459 460 461
PyDoc_STRVAR(doc_get_current_history_length,
"get_current_history_length() -> integer\n\
return the current (not the maximum) length of history.");
462

Guido van Rossum's avatar
Guido van Rossum committed
463

464 465 466
/* Exported function to read the current line buffer */

static PyObject *
467
get_line_buffer(PyObject *self, PyObject *noarg)
468 469 470 471
{
	return PyString_FromString(rl_line_buffer);
}

472 473 474
PyDoc_STRVAR(doc_get_line_buffer,
"get_line_buffer() -> string\n\
return the current contents of the line buffer.");
475

Guido van Rossum's avatar
Guido van Rossum committed
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER

/* Exported function to clear the current history */

static PyObject *
py_clear_history(PyObject *self, PyObject *noarg)
{
	clear_history();
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(doc_clear_history,
"clear_history() -> None\n\
Clear the current readline history.");
#endif


495 496 497
/* Exported function to insert text into the line buffer */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
498
insert_text(PyObject *self, PyObject *args)
499 500
{
	char *s;
501
	if (!PyArg_ParseTuple(args, "s:insert_text", &s))
502 503 504 505 506 507
		return NULL;
	rl_insert_text(s);
	Py_INCREF(Py_None);
	return Py_None;
}

508 509 510
PyDoc_STRVAR(doc_insert_text,
"insert_text(string) -> None\n\
Insert text into the command line.");
511

Guido van Rossum's avatar
Guido van Rossum committed
512 513 514

/* Redisplay the line buffer */

515
static PyObject *
516
redisplay(PyObject *self, PyObject *noarg)
517 518 519 520 521 522
{
	rl_redisplay();
	Py_INCREF(Py_None);
	return Py_None;
}

523 524
PyDoc_STRVAR(doc_redisplay,
"redisplay() -> None\n\
525
Change what's displayed on the screen to reflect the current\n\
526
contents of the line buffer.");
527

Guido van Rossum's avatar
Guido van Rossum committed
528

529
/* Table of functions exported by the module */
530 531

static struct PyMethodDef readline_methods[] =
532
{
533
	{"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
534
	{"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
535
	{"insert_text", insert_text, METH_VARARGS, doc_insert_text},
536
	{"redisplay", redisplay, METH_NOARGS, doc_redisplay},
537
	{"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
Guido van Rossum's avatar
Guido van Rossum committed
538
	{"read_history_file", read_history_file,
539
	 METH_VARARGS, doc_read_history_file},
Guido van Rossum's avatar
Guido van Rossum committed
540
	{"write_history_file", write_history_file,
541
	 METH_VARARGS, doc_write_history_file},
542 543
	{"get_history_item", get_history_item,
	 METH_VARARGS, doc_get_history_item},
544
	{"get_current_history_length", (PyCFunction)get_current_history_length,
545
	 METH_NOARGS, doc_get_current_history_length},
Guido van Rossum's avatar
Guido van Rossum committed
546
 	{"set_history_length", set_history_length,
547
	 METH_VARARGS, set_history_length_doc},
Guido van Rossum's avatar
Guido van Rossum committed
548
 	{"get_history_length", get_history_length,
549
	 METH_NOARGS, get_history_length_doc},
550
	{"set_completer", set_completer, METH_VARARGS, doc_set_completer},
551
	{"get_completer", get_completer, METH_NOARGS, doc_get_completer},
552 553
	{"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
	{"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
554

Guido van Rossum's avatar
Guido van Rossum committed
555
	{"set_completer_delims", set_completer_delims,
556
	 METH_VARARGS, doc_set_completer_delims},
557
	{"add_history", py_add_history, METH_VARARGS, doc_add_history},
558 559
        {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
        {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
560
	{"get_completer_delims", get_completer_delims,
561
	 METH_NOARGS, doc_get_completer_delims},
Guido van Rossum's avatar
Guido van Rossum committed
562 563 564

	{"set_startup_hook", set_startup_hook,
	 METH_VARARGS, doc_set_startup_hook},
565
#ifdef HAVE_RL_PRE_INPUT_HOOK
Guido van Rossum's avatar
Guido van Rossum committed
566 567
	{"set_pre_input_hook", set_pre_input_hook,
	 METH_VARARGS, doc_set_pre_input_hook},
568 569 570
#endif
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
	{"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
571
#endif
572
	{0, 0}
573 574
};

575

576 577 578
/* C function to call the Python hooks. */

static int
Michael W. Hudson's avatar
Michael W. Hudson committed
579
on_hook(PyObject *func)
580 581 582 583
{
	int result = 0;
	if (func != NULL) {
		PyObject *r;
Michael W. Hudson's avatar
Michael W. Hudson committed
584 585 586
#ifdef WITH_THREAD	      
		PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
587 588 589
		r = PyObject_CallFunction(func, NULL);
		if (r == NULL)
			goto error;
Guido van Rossum's avatar
Guido van Rossum committed
590
		if (r == Py_None)
591
			result = 0;
Michael W. Hudson's avatar
Michael W. Hudson committed
592
		else {
593
			result = PyInt_AsLong(r);
Michael W. Hudson's avatar
Michael W. Hudson committed
594 595 596
			if (result == -1 && PyErr_Occurred()) 
				goto error;
		}
597 598 599 600 601 602
		Py_DECREF(r);
		goto done;
	  error:
		PyErr_Clear();
		Py_XDECREF(r);
	  done:
Michael W. Hudson's avatar
Michael W. Hudson committed
603 604 605
#ifdef WITH_THREAD	      
		PyGILState_Release(gilstate);
#endif
606
		return result;
607 608 609 610 611 612 613
	}
	return result;
}

static int
on_startup_hook(void)
{
Michael W. Hudson's avatar
Michael W. Hudson committed
614
	return on_hook(startup_hook);
615 616 617 618 619 620
}

#ifdef HAVE_RL_PRE_INPUT_HOOK
static int
on_pre_input_hook(void)
{
Michael W. Hudson's avatar
Michael W. Hudson committed
621
	return on_hook(pre_input_hook);
622 623 624
}
#endif

625

626 627 628
/* C function to call the Python completer. */

static char *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
629
on_completion(char *text, int state)
630 631 632 633
{
	char *result = NULL;
	if (completer != NULL) {
		PyObject *r;
Michael W. Hudson's avatar
Michael W. Hudson committed
634 635 636
#ifdef WITH_THREAD	      
		PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
637
		rl_attempted_completion_over = 1;
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
		r = PyObject_CallFunction(completer, "si", text, state);
		if (r == NULL)
			goto error;
		if (r == Py_None) {
			result = NULL;
		}
		else {
			char *s = PyString_AsString(r);
			if (s == NULL)
				goto error;
			result = strdup(s);
		}
		Py_DECREF(r);
		goto done;
	  error:
		PyErr_Clear();
		Py_XDECREF(r);
	  done:
Michael W. Hudson's avatar
Michael W. Hudson committed
656 657 658
#ifdef WITH_THREAD	      
		PyGILState_Release(gilstate);
#endif
659
		return result;
660 661 662 663 664
	}
	return result;
}


665
/* A more flexible constructor that saves the "begidx" and "endidx"
666 667
 * before calling the normal completer */

668
static char **
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
669
flex_complete(char *text, int start, int end)
670 671 672 673 674 675 676 677
{
	Py_XDECREF(begidx);
	Py_XDECREF(endidx);
	begidx = PyInt_FromLong((long) start);
	endidx = PyInt_FromLong((long) end);
	return completion_matches(text, *on_completion);
}

678

679
/* Helper to initialize GNU readline properly. */
680

681
static void
682
setup_readline(void)
683
{
684
#ifdef SAVE_LOCALE
685
	char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
686 687
	if (!saved_locale)
		Py_FatalError("not enough memory to save locale");
688 689
#endif

690 691
	using_history();

692
	rl_readline_name = "python";
693 694 695 696
#if defined(PYOS_OS2) && defined(PYCC_GCC)
	/* Allow $if term= in .inputrc to work */
	rl_terminal_name = getenv("TERM");
#endif
697 698 699 700 701
	/* Force rebind of TAB to insert-tab */
	rl_bind_key('\t', rl_insert);
	/* Bind both ESC-TAB and ESC-ESC to the completion function */
	rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
	rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
702 703 704 705 706
	/* Set our hook functions */
	rl_startup_hook = (Function *)on_startup_hook;
#ifdef HAVE_RL_PRE_INPUT_HOOK
	rl_pre_input_hook = (Function *)on_pre_input_hook;
#endif
707
	/* Set our completion function */
708
	rl_attempted_completion_function = (CPPFunction *)flex_complete;
709 710
	/* Set Python word break characters */
	rl_completer_word_break_characters =
711
		strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
712
		/* All nonalphanums except '.' */
713
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
714
	rl_completion_append_character ='\0';
715
#endif
716 717 718

	begidx = PyInt_FromLong(0L);
	endidx = PyInt_FromLong(0L);
719 720 721 722 723
	/* Initialize (allows .inputrc to override)
	 *
	 * XXX: A bug in the readline-2.2 library causes a memory leak
	 * inside this function.  Nothing we can do about it.
	 */
724
	rl_initialize();
725 726 727

#ifdef SAVE_LOCALE
	setlocale(LC_CTYPE, saved_locale); /* Restore locale */
728
	free(saved_locale);
729
#endif
730 731
}

Michael W. Hudson's avatar
Michael W. Hudson committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
/* Wrapper around GNU readline that handles signals differently. */


#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)

static	char *completed_input_string;
static void
rlhandler(char *text)
{
	completed_input_string = text;
	rl_callback_handler_remove();
}

extern PyThreadState* _PyOS_ReadlineTState;

static char *
readline_until_enter_or_signal(char *prompt, int *signal)
{
	char * not_done_reading = "";
	fd_set selectset;

	*signal = 0;
#ifdef HAVE_RL_CATCH_SIGNAL
	rl_catch_signals = 0;
#endif

	rl_callback_handler_install (prompt, rlhandler);
	FD_ZERO(&selectset);
	
	completed_input_string = not_done_reading;

763 764 765 766 767 768 769 770 771 772 773
	while (completed_input_string == not_done_reading) {
		int has_input = 0;

		while (!has_input)
		{	struct timeval timeout = {0, 100000}; /* 0.1 seconds */
			FD_SET(fileno(rl_instream), &selectset);
			/* select resets selectset if no input was available */
			has_input = select(fileno(rl_instream) + 1, &selectset,
					   NULL, NULL, &timeout);
			if(PyOS_InputHook) PyOS_InputHook();
		}
Michael W. Hudson's avatar
Michael W. Hudson committed
774 775 776 777 778 779

		if(has_input > 0) {
			rl_callback_read_char();
		}
		else if (errno == EINTR) {
			int s;
780
#ifdef WITH_THREAD
Michael W. Hudson's avatar
Michael W. Hudson committed
781
			PyEval_RestoreThread(_PyOS_ReadlineTState);
782
#endif
Michael W. Hudson's avatar
Michael W. Hudson committed
783
			s = PyErr_CheckSignals();
784
#ifdef WITH_THREAD
785
			PyEval_SaveThread();	
786
#endif
Michael W. Hudson's avatar
Michael W. Hudson committed
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
			if (s < 0) {
				rl_free_line_state();
				rl_cleanup_after_signal();
				rl_callback_handler_remove();
				*signal = 1;
				completed_input_string = NULL;
			}
		}
	}

	return completed_input_string;
}


#else
802 803 804 805 806

/* Interrupt handler */

static jmp_buf jbuf;

807
/* ARGSUSED */
808
static void
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
809
onintr(int sig)
810
{
811
	longjmp(jbuf, 1);
812 813
}

814

815
static char *
Michael W. Hudson's avatar
Michael W. Hudson committed
816
readline_until_enter_or_signal(char *prompt, int *signal)
817
{
818
	PyOS_sighandler_t old_inthandler;
Michael W. Hudson's avatar
Michael W. Hudson committed
819 820 821
	char *p;
    
	*signal = 0;
Guido van Rossum's avatar
Guido van Rossum committed
822

823
	old_inthandler = PyOS_setsig(SIGINT, onintr);
824 825 826 827 828
	if (setjmp(jbuf)) {
#ifdef HAVE_SIGRELSE
		/* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
		sigrelse(SIGINT);
#endif
829
		PyOS_setsig(SIGINT, old_inthandler);
Michael W. Hudson's avatar
Michael W. Hudson committed
830
		*signal = 1;
831 832
		return NULL;
	}
833
	rl_event_hook = PyOS_InputHook;
Michael W. Hudson's avatar
Michael W. Hudson committed
834 835 836 837 838 839 840 841 842 843 844
	p = readline(prompt);
	PyOS_setsig(SIGINT, old_inthandler);

    return p;
}
#endif /*defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) */


static char *
call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
845 846 847 848
	size_t n;
	char *p, *q;
	int signal;

849 850
#ifdef SAVE_LOCALE
	char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
851 852
	if (!saved_locale)
		Py_FatalError("not enough memory to save locale");
853 854
	setlocale(LC_CTYPE, "");
#endif
Michael W. Hudson's avatar
Michael W. Hudson committed
855

Guido van Rossum's avatar
Guido van Rossum committed
856 857 858
	if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
		rl_instream = sys_stdin;
		rl_outstream = sys_stdout;
859
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
Guido van Rossum's avatar
Guido van Rossum committed
860
		rl_prep_terminal (1);
861
#endif
Guido van Rossum's avatar
Guido van Rossum committed
862 863
	}

Michael W. Hudson's avatar
Michael W. Hudson committed
864 865 866 867 868 869
	p = readline_until_enter_or_signal(prompt, &signal);
	
	/* we got an interrupt signal */
	if(signal) {
		return NULL;
	}
870

Michael W. Hudson's avatar
Michael W. Hudson committed
871
	/* We got an EOF, return a empty string. */
872
	if (p == NULL) {
873
		p = PyMem_Malloc(1);
874 875 876 877
		if (p != NULL)
			*p = '\0';
		return p;
	}
Michael W. Hudson's avatar
Michael W. Hudson committed
878 879

	/* we have a valid line */
880
	n = strlen(p);
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
	if (n > 0) {
		char *line;
		HISTORY_STATE *state = history_get_history_state();
		if (state->length > 0)
			line = history_get(state->length)->line;
		else
			line = "";
		if (strcmp(p, line))
			add_history(p);
		/* the history docs don't say so, but the address of state
		   changes each time history_get_history_state is called
		   which makes me think it's freshly malloc'd memory...
		   on the other hand, the address of the last line stays the
		   same as long as history isn't extended, so it appears to
		   be malloc'd but managed by the history package... */
		free(state);
	}
898 899 900 901 902 903
	/* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
	   release the original. */
	q = p;
	p = PyMem_Malloc(n+2);
	if (p != NULL) {
		strncpy(p, q, n);
904 905 906
		p[n] = '\n';
		p[n+1] = '\0';
	}
907
	free(q);
908 909 910 911
#ifdef SAVE_LOCALE
	setlocale(LC_CTYPE, saved_locale); /* Restore locale */
	free(saved_locale);
#endif
912 913 914
	return p;
}

915 916 917

/* Initialize the module */

918 919
PyDoc_STRVAR(doc_module,
"Importing this module enables command line editing using GNU readline.");
920

921
PyMODINIT_FUNC
922
initreadline(void)
923
{
924
	PyObject *m;
925 926 927

	m = Py_InitModule4("readline", readline_methods, doc_module,
			   (PyObject *)NULL, PYTHON_API_VERSION);
928 929
	if (m == NULL)
		return;
930

Guido van Rossum's avatar
Guido van Rossum committed
931 932
	PyOS_ReadlineFunctionPointer = call_readline;
	setup_readline();
933
}