home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / readline.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  12.1 KB  |  506 lines

  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.
  4.  *
  5.  * More recently, it was largely rewritten by Guido van Rossum who is
  6.  * now maintaining it.
  7.  */
  8.  
  9. /* Standard definitions */
  10. #include "Python.h"
  11. #include <setjmp.h>
  12. #include <signal.h>
  13. #include <errno.h>
  14.  
  15. #ifdef HAVE_UNISTD_H
  16. #include <unistd.h> /* For isatty() */
  17. #endif
  18.  
  19. /* GNU readline definitions */
  20. /* If you have string.h, you might need to add yourself to this #if... [cjh] */
  21. #if defined(__BEOS__)
  22. #undef HAVE_CONFIG_H
  23. /* At max warnings, we need protos for everything. [cjh] */
  24. #include <readline/readline.h>
  25. #include <readline/history.h>
  26. #include <unistd.h>
  27. #else
  28. #include <readline/readline.h> /* You may need to add an -I option to Setup */
  29.  
  30. extern int rl_parse_and_bind(char *);
  31. extern int rl_read_init_file(char *);
  32. extern int rl_insert_text(char *);
  33. extern int rl_bind_key(int, Function *);
  34. extern int rl_bind_key_in_map(int, Function *, Keymap);
  35. extern int rl_initialize(void);
  36. extern int add_history(char *);
  37. extern int read_history(char *);
  38. extern int write_history(char *);
  39. 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. /* Exported function to send one line to readline's init file parser */
  49.  
  50. static PyObject *
  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.     /* Make a copy -- rl_parse_and_bind() modifies its argument */
  57.     /* Bernard Herzog */
  58.     copy = malloc(1 + strlen(s));
  59.     if (copy == NULL)
  60.         return PyErr_NoMemory();
  61.     strcpy(copy, s);
  62.     rl_parse_and_bind(copy);
  63.     free(copy); /* Free the copy */
  64.     Py_INCREF(Py_None);
  65.     return Py_None;
  66. }
  67.  
  68. static char doc_parse_and_bind[] = "\
  69. parse_and_bind(string) -> None\n\
  70. Parse and execute single line of a readline init file.\
  71. ";
  72.  
  73.  
  74. /* Exported function to parse a readline init file */
  75.  
  76. static PyObject *
  77. read_init_file(PyObject *self, PyObject *args)
  78. {
  79.     char *s = NULL;
  80.     if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
  81.         return NULL;
  82.     errno = rl_read_init_file(s);
  83.     if (errno)
  84.         return PyErr_SetFromErrno(PyExc_IOError);
  85.     Py_INCREF(Py_None);
  86.     return Py_None;
  87. }
  88.  
  89. static char doc_read_init_file[] = "\
  90. read_init_file([filename]) -> None\n\
  91. Parse a readline initialization file.\n\
  92. The default filename is the last filename used.\
  93. ";
  94.  
  95.  
  96. /* Exported function to load a readline history file */
  97.  
  98. static PyObject *
  99. read_history_file(PyObject *self, PyObject *args)
  100. {
  101.     char *s = NULL;
  102.     if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
  103.         return NULL;
  104.     errno = read_history(s);
  105.     if (errno)
  106.         return PyErr_SetFromErrno(PyExc_IOError);
  107.     Py_INCREF(Py_None);
  108.     return Py_None;
  109. }
  110.  
  111. static int history_length = -1; /* do not truncate history by default */
  112. static char doc_read_history_file[] = "\
  113. read_history_file([filename]) -> None\n\
  114. Load a readline history file.\n\
  115. The default filename is ~/.history.\
  116. ";
  117.  
  118.  
  119. /* Exported function to save a readline history file */
  120.  
  121. static PyObject *
  122. write_history_file(PyObject *self, PyObject *args)
  123. {
  124.     char *s = NULL;
  125.     if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
  126.         return NULL;
  127.     errno = write_history(s);
  128.     if (!errno && history_length >= 0)
  129.         history_truncate_file(s, history_length);
  130.     if (errno)
  131.         return PyErr_SetFromErrno(PyExc_IOError);
  132.     Py_INCREF(Py_None);
  133.     return Py_None;
  134. }
  135.  
  136. static char doc_write_history_file[] = "\
  137. write_history_file([filename]) -> None\n\
  138. Save a readline history file.\n\
  139. The default filename is ~/.history.\
  140. ";
  141.  
  142.  
  143. static char set_history_length_doc[] = "\
  144. set_history_length(length) -> None\n\
  145. set the maximal number of items which will be written to\n\
  146. the history file. A negative length is used to inhibit\n\
  147. history truncation.\n\
  148. ";
  149.  
  150. static PyObject*
  151. set_history_length(PyObject *self, PyObject *args)
  152. {
  153.     int length = history_length;
  154.     if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
  155.     return NULL;
  156.     history_length = length;
  157.     Py_INCREF(Py_None);
  158.     return Py_None;
  159. }
  160.  
  161.  
  162.  
  163. static char get_history_length_doc[] = "\
  164. get_history_length() -> int\n\
  165. return the current history length value.\n\
  166. ";
  167.  
  168. static PyObject*
  169. get_history_length(PyObject *self, PyObject *args)
  170. {
  171.     if (!PyArg_ParseTuple(args, ":get_history_length"))
  172.         return NULL;
  173.     return Py_BuildValue("i", history_length);
  174. }
  175.  
  176.  
  177.  
  178. /* Exported function to specify a word completer in Python */
  179.  
  180. static PyObject *completer = NULL;
  181. static PyThreadState *tstate = NULL;
  182.  
  183. static PyObject *begidx = NULL;
  184. static PyObject *endidx = NULL;
  185.  
  186. /* get the beginning index for the scope of the tab-completion */
  187. static PyObject *
  188. get_begidx(PyObject *self, PyObject *args)
  189. {
  190.     if(!PyArg_NoArgs(args)) {
  191.         return NULL;
  192.     } 
  193.     Py_INCREF(begidx);
  194.     return begidx;
  195. }
  196.  
  197. static char doc_get_begidx[] = "\
  198. get_begidx() -> int\n\
  199. get the beginning index of the readline tab-completion scope";
  200.  
  201. /* get the ending index for the scope of the tab-completion */
  202. static PyObject *
  203. get_endidx(PyObject *self, PyObject *args)
  204. {
  205.      if(!PyArg_NoArgs(args)) {
  206.         return NULL;
  207.     } 
  208.     Py_INCREF(endidx);
  209.     return endidx;
  210. }
  211.  
  212. static char doc_get_endidx[] = "\
  213. get_endidx() -> int\n\
  214. get the ending index of the readline tab-completion scope";
  215.  
  216.  
  217. /* set the tab-completion word-delimiters that readline uses */
  218.  
  219. static PyObject *
  220. set_completer_delims(PyObject *self, PyObject *args)
  221. {
  222.     char *break_chars;
  223.  
  224.     if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
  225.         return NULL;
  226.     }
  227.     free(rl_completer_word_break_characters);
  228.     rl_completer_word_break_characters = strdup(break_chars);
  229.     Py_INCREF(Py_None);
  230.     return Py_None;
  231. }
  232.  
  233. static char doc_set_completer_delims[] = "\
  234. set_completer_delims(string) -> None\n\
  235. set the readline word delimiters for tab-completion";
  236.  
  237.  
  238. /* get the tab-completion word-delimiters that readline uses */
  239.  
  240. static PyObject *
  241. get_completer_delims(PyObject *self, PyObject *args)
  242. {
  243.     if(!PyArg_NoArgs(args)) {
  244.         return NULL;
  245.     }
  246.     return PyString_FromString(rl_completer_word_break_characters);
  247. }
  248.     
  249. static char doc_get_completer_delims[] = "\
  250. get_completer_delims() -> string\n\
  251. get the readline word delimiters for tab-completion";
  252.  
  253. static PyObject *
  254. set_completer(PyObject *self, PyObject *args)
  255. {
  256.     PyObject *function = Py_None;
  257.     if (!PyArg_ParseTuple(args, "|O:set_completer", &function))
  258.         return NULL;
  259.     if (function == Py_None) {
  260.         Py_XDECREF(completer);
  261.         completer = NULL;
  262.         tstate = NULL;
  263.     }
  264.     else if (PyCallable_Check(function)) {
  265.         PyObject *tmp = completer;
  266.         Py_INCREF(function);
  267.         completer = function;
  268.         Py_XDECREF(tmp);
  269.         tstate = PyThreadState_Get();
  270.     }
  271.     else {
  272.         PyErr_SetString(PyExc_TypeError,
  273.                 "set_completer(func): argument not callable");
  274.         return NULL;
  275.     }
  276.     Py_INCREF(Py_None);
  277.     return Py_None;
  278. }
  279.  
  280. static char doc_set_completer[] = "\
  281. set_completer([function]) -> None\n\
  282. Set or remove the completer function.\n\
  283. The function is called as function(text, state),\n\
  284. for i in [0, 1, 2, ...] until it returns a non-string.\n\
  285. It should return the next possible completion starting with 'text'.\
  286. ";
  287.  
  288. /* Exported function to read the current line buffer */
  289.  
  290. static PyObject *
  291. get_line_buffer(PyObject *self, PyObject *args)
  292. {
  293.     if (!PyArg_NoArgs(args))
  294.         return NULL;
  295.     return PyString_FromString(rl_line_buffer);
  296. }
  297.  
  298. static char doc_get_line_buffer[] = "\
  299. get_line_buffer() -> string\n\
  300. return the current contents of the line buffer.\
  301. ";
  302.  
  303. /* Exported function to insert text into the line buffer */
  304.  
  305. static PyObject *
  306. insert_text(PyObject *self, PyObject *args)
  307. {
  308.     char *s;
  309.     if (!PyArg_ParseTuple(args, "s:insert_text", &s))
  310.         return NULL;
  311.     rl_insert_text(s);
  312.     Py_INCREF(Py_None);
  313.     return Py_None;
  314. }
  315.  
  316.  
  317. static char doc_insert_text[] = "\
  318. insert_text(string) -> None\n\
  319. Insert text into the command line.\
  320. ";
  321.  
  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.     {"get_line_buffer", get_line_buffer, 
  329.      METH_OLDARGS, doc_get_line_buffer},
  330.     {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
  331.     {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
  332.     {"read_history_file", read_history_file, 
  333.      METH_VARARGS, doc_read_history_file},
  334.     {"write_history_file", write_history_file, 
  335.      METH_VARARGS, doc_write_history_file},
  336.      {"set_history_length", set_history_length, 
  337.      METH_VARARGS, set_history_length_doc},
  338.      {"get_history_length", get_history_length, 
  339.      METH_VARARGS, get_history_length_doc},
  340.     {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
  341.     {"get_begidx", get_begidx, METH_OLDARGS, doc_get_begidx},
  342.     {"get_endidx", get_endidx, METH_OLDARGS, doc_get_endidx},
  343.  
  344.     {"set_completer_delims", set_completer_delims, 
  345.      METH_VARARGS, doc_set_completer_delims},
  346.     {"get_completer_delims", get_completer_delims, 
  347.      METH_OLDARGS, doc_get_completer_delims},
  348.     {0, 0}
  349. };
  350.  
  351. /* C function to call the Python completer. */
  352.  
  353. static char *
  354. on_completion(char *text, int state)
  355. {
  356.     char *result = NULL;
  357.     if (completer != NULL) {
  358.         PyObject *r;
  359.         PyThreadState *save_tstate;
  360.         /* Note that readline is called with the interpreter
  361.            lock released! */
  362.         save_tstate = PyThreadState_Swap(NULL);
  363.         PyEval_RestoreThread(tstate);
  364.         r = PyObject_CallFunction(completer, "si", text, state);
  365.         if (r == NULL)
  366.             goto error;
  367.         if (r == Py_None) {
  368.             result = NULL;
  369.         }
  370.         else {
  371.             char *s = PyString_AsString(r);
  372.             if (s == NULL)
  373.                 goto error;
  374.             result = strdup(s);
  375.         }
  376.         Py_DECREF(r);
  377.         goto done;
  378.       error:
  379.         PyErr_Clear();
  380.         Py_XDECREF(r);
  381.       done:
  382.         PyEval_SaveThread();
  383.         PyThreadState_Swap(save_tstate);
  384.     }
  385.     return result;
  386. }
  387.  
  388.  
  389. /* a more flexible constructor that saves the "begidx" and "endidx"
  390.  * before calling the normal completer */
  391.  
  392. char **
  393. flex_complete(char *text, int start, int end)
  394. {
  395.     Py_XDECREF(begidx);
  396.     Py_XDECREF(endidx);
  397.     begidx = PyInt_FromLong((long) start);
  398.     endidx = PyInt_FromLong((long) end);
  399.     return completion_matches(text, *on_completion);
  400. }
  401.  
  402. /* Helper to initialize GNU readline properly. */
  403.  
  404. static void
  405. setup_readline(void)
  406. {
  407.     rl_readline_name = "python";
  408.     /* Force rebind of TAB to insert-tab */
  409.     rl_bind_key('\t', rl_insert);
  410.     /* Bind both ESC-TAB and ESC-ESC to the completion function */
  411.     rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
  412.     rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
  413.     /* Set our completion function */
  414.     rl_attempted_completion_function = (CPPFunction *)flex_complete;
  415.     /* Set Python word break characters */
  416.     rl_completer_word_break_characters =
  417.         strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
  418.         /* All nonalphanums except '.' */
  419.  
  420.     begidx = PyInt_FromLong(0L);
  421.     endidx = PyInt_FromLong(0L);
  422.     /* Initialize (allows .inputrc to override)
  423.      *
  424.      * XXX: A bug in the readline-2.2 library causes a memory leak
  425.      * inside this function.  Nothing we can do about it.
  426.      */
  427.     rl_initialize();
  428. }
  429.  
  430.  
  431. /* Interrupt handler */
  432.  
  433. static jmp_buf jbuf;
  434.  
  435. /* ARGSUSED */
  436. static void
  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 *
  446. call_readline(char *prompt)
  447. {
  448.     size_t n;
  449.     char *p, *q;
  450.     PyOS_sighandler_t old_inthandler;
  451.     
  452.     old_inthandler = PyOS_setsig(SIGINT, onintr);
  453.     if (setjmp(jbuf)) {
  454. #ifdef HAVE_SIGRELSE
  455.         /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
  456.         sigrelse(SIGINT);
  457. #endif
  458.         PyOS_setsig(SIGINT, old_inthandler);
  459.         return NULL;
  460.     }
  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.         if (p != NULL)
  469.             *p = '\0';
  470.         return p;
  471.     }
  472.     n = strlen(p);
  473.     if (n > 0)
  474.         add_history(p);
  475.     /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
  476.        release the original. */
  477.     q = p;
  478.     p = PyMem_Malloc(n+2);
  479.     if (p != NULL) {
  480.         strncpy(p, q, n);
  481.         p[n] = '\n';
  482.         p[n+1] = '\0';
  483.     }
  484.     free(q);
  485.     return p;
  486. }
  487.  
  488.  
  489. /* Initialize the module */
  490.  
  491. static char doc_module[] =
  492. "Importing this module enables command line editing using GNU readline.";
  493.  
  494. DL_EXPORT(void)
  495. initreadline(void)
  496. {
  497.     PyObject *m;
  498.  
  499.     m = Py_InitModule4("readline", readline_methods, doc_module,
  500.                (PyObject *)NULL, PYTHON_API_VERSION);
  501.     if (isatty(fileno(stdin))) {
  502.         PyOS_ReadlineFunctionPointer = call_readline;
  503.         setup_readline();
  504.     }
  505. }
  506.