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

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

15 16 17 18
#ifdef HAVE_UNISTD_H
#include <unistd.h> /* For isatty() */
#endif

19
/* GNU readline definitions */
20 21 22 23 24 25 26 27
/* If you have string.h, you might need to add yourself to this #if... [cjh] */
#if defined(__BEOS__)
#undef HAVE_CONFIG_H
/* At max warnings, we need protos for everything. [cjh] */
#include <readline/readline.h>
#include <readline/history.h>
#include <unistd.h>
#else
28 29
#include <readline/readline.h> /* You may need to add an -I option to Setup */

30 31 32 33 34 35 36
extern int rl_parse_and_bind(char *);
extern int rl_read_init_file(char *);
extern int rl_insert_text(char *);
extern int rl_bind_key(int, Function *);
extern int rl_bind_key_in_map(int, Function *, Keymap);
extern int rl_initialize(void);
extern int add_history(char *);
37 38 39
extern int read_history(char *);
extern int write_history(char *);
extern int history_truncate_file(char *, int);
40
extern Function *rl_event_hook;
41
#endif
42

43
/* Pointers needed from outside (but not declared in a header file). */
44
extern int (*PyOS_InputHook)(void);
45
extern char *(*PyOS_ReadlineFunctionPointer)(char *);
46 47


48 49 50
/* Exported function to send one line to readline's init file parser */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
51
parse_and_bind(PyObject *self, PyObject *args)
52
{
53
	char *s, *copy;
54
	if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
55
		return NULL;
56 57 58 59 60 61 62 63
	/* 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 */
64 65 66 67 68 69 70 71 72 73 74 75 76
	Py_INCREF(Py_None);
	return Py_None;
}

static char doc_parse_and_bind[] = "\
parse_and_bind(string) -> None\n\
Parse and execute single line of a readline init file.\
";


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

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

static char doc_read_init_file[] = "\
read_init_file([filename]) -> None\n\
Parse a readline initialization file.\n\
The default filename is the last filename used.\
";


96 97 98
/* Exported function to load a readline history file */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
99
read_history_file(PyObject *self, PyObject *args)
100 101 102 103 104 105 106 107 108 109 110
{
	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;
}

111
static int history_length = -1; /* do not truncate history by default */
112 113 114 115 116 117 118 119 120 121
static char doc_read_history_file[] = "\
read_history_file([filename]) -> None\n\
Load a readline history file.\n\
The default filename is ~/.history.\
";


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

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
122
write_history_file(PyObject *self, PyObject *args)
123 124 125 126 127
{
	char *s = NULL;
	if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
		return NULL;
	errno = write_history(s);
128 129
	if (!errno && history_length >= 0)
		history_truncate_file(s, history_length);
130 131 132 133 134 135 136 137 138 139 140 141 142
	if (errno)
		return PyErr_SetFromErrno(PyExc_IOError);
	Py_INCREF(Py_None);
	return Py_None;
}

static char doc_write_history_file[] = "\
write_history_file([filename]) -> None\n\
Save a readline history file.\n\
The default filename is ~/.history.\
";


143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
static char 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.\n\
";

static PyObject*
set_history_length(PyObject *self, PyObject *args)
{
    int length = history_length;
    if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
	return NULL;
    history_length = length;
    Py_INCREF(Py_None);
    return Py_None;
}



static char get_history_length_doc[] = "\
get_history_length() -> int\n\
return the current history length value.\n\
";

static PyObject*
get_history_length(PyObject *self, PyObject *args)
{
	if (!PyArg_ParseTuple(args, ":get_history_length"))
		return NULL;
	return Py_BuildValue("i", history_length);
}



178 179 180 181 182
/* Exported function to specify a word completer in Python */

static PyObject *completer = NULL;
static PyThreadState *tstate = NULL;

183 184 185 186 187
static PyObject *begidx = NULL;
static PyObject *endidx = NULL;

/* get the beginning index for the scope of the tab-completion */
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
188
get_begidx(PyObject *self, PyObject *args)
189 190 191 192 193 194 195 196 197 198 199 200 201 202
{
	if(!PyArg_NoArgs(args)) {
		return NULL;
	} 
	Py_INCREF(begidx);
	return begidx;
}

static char doc_get_begidx[] = "\
get_begidx() -> int\n\
get the beginning index of the readline tab-completion scope";

/* get the ending index for the scope of the tab-completion */
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
203
get_endidx(PyObject *self, PyObject *args)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
{
 	if(!PyArg_NoArgs(args)) {
		return NULL;
	} 
	Py_INCREF(endidx);
	return endidx;
}

static char doc_get_endidx[] = "\
get_endidx() -> int\n\
get the ending index of the readline tab-completion scope";


/* set the tab-completion word-delimiters that readline uses */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
220
set_completer_delims(PyObject *self, PyObject *args)
221 222 223
{
	char *break_chars;

224
	if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
		return NULL;
	}
	free(rl_completer_word_break_characters);
	rl_completer_word_break_characters = strdup(break_chars);
	Py_INCREF(Py_None);
	return Py_None;
}

static char doc_set_completer_delims[] = "\
set_completer_delims(string) -> None\n\
set the readline word delimiters for tab-completion";


/* get the tab-completion word-delimiters that readline uses */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
241
get_completer_delims(PyObject *self, PyObject *args)
242 243 244 245 246 247 248 249 250 251 252
{
	if(!PyArg_NoArgs(args)) {
		return NULL;
	}
	return PyString_FromString(rl_completer_word_break_characters);
}
	
static char doc_get_completer_delims[] = "\
get_completer_delims() -> string\n\
get the readline word delimiters for tab-completion";

253
static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
254
set_completer(PyObject *self, PyObject *args)
255 256
{
	PyObject *function = Py_None;
257
	if (!PyArg_ParseTuple(args, "|O:set_completer", &function))
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
		return NULL;
	if (function == Py_None) {
		Py_XDECREF(completer);
		completer = NULL;
		tstate = NULL;
	}
	else if (PyCallable_Check(function)) {
		PyObject *tmp = completer;
		Py_INCREF(function);
		completer = function;
		Py_XDECREF(tmp);
		tstate = PyThreadState_Get();
	}
	else {
		PyErr_SetString(PyExc_TypeError,
				"set_completer(func): argument not callable");
		return NULL;
	}
	Py_INCREF(Py_None);
	return Py_None;
}

static char doc_set_completer[] = "\
set_completer([function]) -> None\n\
Set or remove the completer function.\n\
The function is called as function(text, state),\n\
for i in [0, 1, 2, ...] until it returns a non-string.\n\
It should return the next possible completion starting with 'text'.\
";

288 289 290
/* Exported function to read the current line buffer */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
291
get_line_buffer(PyObject *self, PyObject *args)
292
{
293
	if (!PyArg_NoArgs(args))
294 295 296 297 298
		return NULL;
	return PyString_FromString(rl_line_buffer);
}

static char doc_get_line_buffer[] = "\
299
get_line_buffer() -> string\n\
300 301 302 303 304 305
return the current contents of the line buffer.\
";

/* Exported function to insert text into the line buffer */

static PyObject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
306
insert_text(PyObject *self, PyObject *args)
307 308
{
	char *s;
309
	if (!PyArg_ParseTuple(args, "s:insert_text", &s))
310 311 312 313 314 315 316 317 318 319 320 321
		return NULL;
	rl_insert_text(s);
	Py_INCREF(Py_None);
	return Py_None;
}


static char doc_insert_text[] = "\
insert_text(string) -> None\n\
Insert text into the command line.\
";

322 323

/* Table of functions exported by the module */
324 325

static struct PyMethodDef readline_methods[] =
326
{
327
	{"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
328 329
	{"get_line_buffer", get_line_buffer, 
	 METH_OLDARGS, doc_get_line_buffer},
330 331 332 333 334 335 336 337 338 339 340
	{"insert_text", insert_text, METH_VARARGS, doc_insert_text},
	{"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
	{"read_history_file", read_history_file, 
	 METH_VARARGS, doc_read_history_file},
	{"write_history_file", write_history_file, 
	 METH_VARARGS, doc_write_history_file},
 	{"set_history_length", set_history_length, 
	 METH_VARARGS, set_history_length_doc},
 	{"get_history_length", get_history_length, 
	 METH_VARARGS, get_history_length_doc},
	{"set_completer", set_completer, METH_VARARGS, doc_set_completer},
341 342
	{"get_begidx", get_begidx, METH_OLDARGS, doc_get_begidx},
	{"get_endidx", get_endidx, METH_OLDARGS, doc_get_endidx},
343

344 345 346 347
	{"set_completer_delims", set_completer_delims, 
	 METH_VARARGS, doc_set_completer_delims},
	{"get_completer_delims", get_completer_delims, 
	 METH_OLDARGS, doc_get_completer_delims},
348
	{0, 0}
349 350
};

351 352 353
/* C function to call the Python completer. */

static char *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
354
on_completion(char *text, int state)
355 356 357 358
{
	char *result = NULL;
	if (completer != NULL) {
		PyObject *r;
359
		PyThreadState *save_tstate;
360 361
		/* Note that readline is called with the interpreter
		   lock released! */
362
		save_tstate = PyThreadState_Swap(NULL);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
		PyEval_RestoreThread(tstate);
		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:
		PyEval_SaveThread();
383
		PyThreadState_Swap(save_tstate);
384 385 386 387 388
	}
	return result;
}


389 390 391 392
/* a more flexible constructor that saves the "begidx" and "endidx"
 * before calling the normal completer */

char **
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
393
flex_complete(char *text, int start, int end)
394 395 396 397 398 399 400 401
{
	Py_XDECREF(begidx);
	Py_XDECREF(endidx);
	begidx = PyInt_FromLong((long) start);
	endidx = PyInt_FromLong((long) end);
	return completion_matches(text, *on_completion);
}

402
/* Helper to initialize GNU readline properly. */
403

404
static void
405
setup_readline(void)
406
{
407 408 409 410 411 412 413
	rl_readline_name = "python";
	/* 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);
	/* Set our completion function */
414
	rl_attempted_completion_function = (CPPFunction *)flex_complete;
415 416
	/* Set Python word break characters */
	rl_completer_word_break_characters =
417
		strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
418
		/* All nonalphanums except '.' */
419 420 421

	begidx = PyInt_FromLong(0L);
	endidx = PyInt_FromLong(0L);
422 423 424 425 426
	/* 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.
	 */
427
	rl_initialize();
428 429
}

430 431 432 433 434

/* Interrupt handler */

static jmp_buf jbuf;

435
/* ARGSUSED */
436
static void
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
437
onintr(int sig)
438
{
439
	longjmp(jbuf, 1);
440 441
}

442 443

/* Wrapper around GNU readline that handles signals differently. */
444 445

static char *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
446
call_readline(char *prompt)
447
{
448
	size_t n;
449
	char *p, *q;
450 451 452
	PyOS_sighandler_t old_inthandler;
	
	old_inthandler = PyOS_setsig(SIGINT, onintr);
453 454 455 456 457
	if (setjmp(jbuf)) {
#ifdef HAVE_SIGRELSE
		/* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
		sigrelse(SIGINT);
#endif
458
		PyOS_setsig(SIGINT, old_inthandler);
459 460
		return NULL;
	}
461
	rl_event_hook = PyOS_InputHook;
462
	p = readline(prompt);
463
	PyOS_setsig(SIGINT, old_inthandler);
464 465

	/* We must return a buffer allocated with PyMem_Malloc. */
466
	if (p == NULL) {
467
		p = PyMem_Malloc(1);
468 469 470 471 472 473 474
		if (p != NULL)
			*p = '\0';
		return p;
	}
	n = strlen(p);
	if (n > 0)
		add_history(p);
475 476 477 478 479 480
	/* 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);
481 482 483
		p[n] = '\n';
		p[n+1] = '\0';
	}
484
	free(q);
485 486 487
	return p;
}

488 489 490 491 492 493

/* Initialize the module */

static char doc_module[] =
"Importing this module enables command line editing using GNU readline.";

494
DL_EXPORT(void)
495
initreadline(void)
496
{
497
	PyObject *m;
498 499 500 501 502 503 504

	m = Py_InitModule4("readline", readline_methods, doc_module,
			   (PyObject *)NULL, PYTHON_API_VERSION);
	if (isatty(fileno(stdin))) {
		PyOS_ReadlineFunctionPointer = call_readline;
		setup_readline();
	}
505
}