home *** CD-ROM | disk | FTP | other *** search
/ vim.ftp.fu-berlin.de / 2015-02-03.vim.ftp.fu-berlin.de.tar / vim.ftp.fu-berlin.de / unix / vim-6.2.tar.bz2 / vim-6.2.tar / vim62 / src / if_python.c < prev    next >
Encoding:
C/C++ Source or Header  |  2003-04-19  |  62.3 KB  |  2,688 lines

  1. /* vi:set ts=8 sts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved    by Bram Moolenaar
  4.  *
  5.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  6.  * Do ":help credits" in Vim to see a list of people who contributed.
  7.  * See README.txt for an overview of the Vim source code.
  8.  */
  9. /*
  10.  * Python extensions by Paul Moore.
  11.  * Changes for Unix by David Leonard.
  12.  *
  13.  * This consists of four parts:
  14.  * 1. Python interpreter main program
  15.  * 2. Python output stream: writes output via [e]msg().
  16.  * 3. Implementation of the Vim module for Python
  17.  * 4. Utility functions for handling the interface between Vim and Python.
  18.  */
  19.  
  20. #include "vim.h"
  21.  
  22. #include <stdio.h>
  23. #include <stdarg.h>
  24. #include <limits.h>
  25.  
  26. /* Python.h defines _POSIX_THREADS itself (if needed) */
  27. #ifdef _POSIX_THREADS
  28. # undef _POSIX_THREADS
  29. #endif
  30.  
  31. #if defined(_WIN32) && defined (HAVE_FCNTL_H)
  32. # undef HAVE_FCNTL_H
  33. #endif
  34.  
  35. #ifdef _DEBUG
  36. # undef _DEBUG
  37. #endif
  38.  
  39. #ifdef HAVE_STDARG_H
  40. # undef HAVE_STDARG_H    /* Python's config.h defines it as well. */
  41. #endif
  42.  
  43. #include <Python.h>
  44. #ifdef MACOS
  45. # include "macglue.h"
  46. # include <CodeFragments.h>
  47. #endif
  48. #undef main /* Defined in python.h - aargh */
  49. #undef HAVE_FCNTL_H /* Clash with os_win32.h */
  50.  
  51. #if !defined(FEAT_PYTHON) && defined(PROTO)
  52. /* Use this to be able to generate prototypes without python being used. */
  53. # define PyObject int
  54. # define PyThreadState int
  55. # define PyTypeObject int
  56. struct PyMethodDef { int a; };
  57. # define PySequenceMethods int
  58. #endif
  59.  
  60. /* Parser flags */
  61. #define single_input    256
  62. #define file_input    257
  63. #define eval_input    258
  64.  
  65. #if defined(DYNAMIC_PYTHON) || defined(PROTO)
  66. # ifndef DYNAMIC_PYTHON
  67. #  define HINSTANCE int        /* for generating prototypes */
  68. # endif
  69.  
  70. /*
  71.  * Wrapper defines
  72.  */
  73. # define PyArg_Parse dll_PyArg_Parse
  74. # define PyArg_ParseTuple dll_PyArg_ParseTuple
  75. # define PyDict_SetItemString dll_PyDict_SetItemString
  76. # define PyErr_BadArgument dll_PyErr_BadArgument
  77. # define PyErr_Clear dll_PyErr_Clear
  78. # define PyErr_NoMemory dll_PyErr_NoMemory
  79. # define PyErr_Occurred dll_PyErr_Occurred
  80. # define PyErr_SetNone dll_PyErr_SetNone
  81. # define PyErr_SetString dll_PyErr_SetString
  82. # define PyEval_InitThreads dll_PyEval_InitThreads
  83. # define PyEval_RestoreThread dll_PyEval_RestoreThread
  84. # define PyEval_SaveThread dll_PyEval_SaveThread
  85. # define PyInt_AsLong dll_PyInt_AsLong
  86. # define PyInt_FromLong dll_PyInt_FromLong
  87. # define PyInt_Type (*dll_PyInt_Type)
  88. # define PyList_GetItem dll_PyList_GetItem
  89. # define PyList_New dll_PyList_New
  90. # define PyList_SetItem dll_PyList_SetItem
  91. # define PyList_Size dll_PyList_Size
  92. # define PyList_Type (*dll_PyList_Type)
  93. # define PyImport_ImportModule dll_PyImport_ImportModule
  94. # define PyDict_GetItemString dll_PyDict_GetItemString
  95. # define PyModule_GetDict dll_PyModule_GetDict
  96. # define PyRun_SimpleString dll_PyRun_SimpleString
  97. # define PyString_AsString dll_PyString_AsString
  98. # define PyString_FromString dll_PyString_FromString
  99. # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
  100. # define PyString_Size dll_PyString_Size
  101. # define PyString_Type (*dll_PyString_Type)
  102. # define PySys_SetObject dll_PySys_SetObject
  103. # define PyType_Type (*dll_PyType_Type)
  104. # define Py_BuildValue dll_Py_BuildValue
  105. # define Py_FindMethod dll_Py_FindMethod
  106. # define Py_InitModule4 dll_Py_InitModule4
  107. # define Py_Initialize dll_Py_Initialize
  108. # define _PyObject_New dll__PyObject_New
  109. # define _Py_NoneStruct (*dll__Py_NoneStruct)
  110. # define PyObject_Init dll__PyObject_Init
  111. # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
  112. #  define PyType_IsSubtype dll_PyType_IsSubtype
  113. # endif
  114.  
  115. /*
  116.  * Pointers for dynamic link
  117.  */
  118. static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
  119. static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
  120. static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
  121. static int(*dll_PyErr_BadArgument)(void);
  122. static void(*dll_PyErr_Clear)(void);
  123. static PyObject*(*dll_PyErr_NoMemory)(void);
  124. static PyObject*(*dll_PyErr_Occurred)(void);
  125. static void(*dll_PyErr_SetNone)(PyObject *);
  126. static void(*dll_PyErr_SetString)(PyObject *, const char *);
  127. static void(*dll_PyEval_InitThreads)(void);
  128. static void(*dll_PyEval_RestoreThread)(PyThreadState *);
  129. static PyThreadState*(*dll_PyEval_SaveThread)(void);
  130. static long(*dll_PyInt_AsLong)(PyObject *);
  131. static PyObject*(*dll_PyInt_FromLong)(long);
  132. static PyTypeObject* dll_PyInt_Type;
  133. static PyObject*(*dll_PyList_GetItem)(PyObject *, int);
  134. static PyObject*(*dll_PyList_New)(int size);
  135. static int(*dll_PyList_SetItem)(PyObject *, int, PyObject *);
  136. static int(*dll_PyList_Size)(PyObject *);
  137. static PyTypeObject* dll_PyList_Type;
  138. static PyObject*(*dll_PyImport_ImportModule)(const char *);
  139. static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
  140. static PyObject*(*dll_PyModule_GetDict)(PyObject *);
  141. static int(*dll_PyRun_SimpleString)(char *);
  142. static char*(*dll_PyString_AsString)(PyObject *);
  143. static PyObject*(*dll_PyString_FromString)(const char *);
  144. static PyObject*(*dll_PyString_FromStringAndSize)(const char *, int);
  145. static int(*dll_PyString_Size)(PyObject *);
  146. static PyTypeObject* dll_PyString_Type;
  147. static int(*dll_PySys_SetObject)(char *, PyObject *);
  148. static PyTypeObject* dll_PyType_Type;
  149. static PyObject*(*dll_Py_BuildValue)(char *, ...);
  150. static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
  151. static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
  152. static void(*dll_Py_Initialize)(void);
  153. static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
  154. static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
  155. static PyObject* dll__Py_NoneStruct;
  156. # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
  157. static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
  158. # endif
  159.  
  160. static HINSTANCE hinstPython = 0; /* Instance of python.dll */
  161.  
  162. /* Imported exception objects */
  163. static PyObject *imp_PyExc_AttributeError;
  164. static PyObject *imp_PyExc_IndexError;
  165. static PyObject *imp_PyExc_KeyboardInterrupt;
  166. static PyObject *imp_PyExc_TypeError;
  167. static PyObject *imp_PyExc_ValueError;
  168.  
  169. # define PyExc_AttributeError imp_PyExc_AttributeError
  170. # define PyExc_IndexError imp_PyExc_IndexError
  171. # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
  172. # define PyExc_TypeError imp_PyExc_TypeError
  173. # define PyExc_ValueError imp_PyExc_ValueError
  174.  
  175. /*
  176.  * Table of name to function pointer of python.
  177.  */
  178. # define PYTHON_PROC FARPROC
  179. static struct
  180. {
  181.     char *name;
  182.     PYTHON_PROC *ptr;
  183. } python_funcname_table[] =
  184. {
  185.     {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
  186.     {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
  187.     {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
  188.     {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
  189.     {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
  190.     {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
  191.     {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
  192.     {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
  193.     {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
  194.     {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
  195.     {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
  196.     {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
  197.     {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
  198.     {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
  199.     {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
  200.     {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
  201.     {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
  202.     {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
  203.     {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
  204.     {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
  205.     {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
  206.     {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
  207.     {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
  208.     {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
  209.     {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
  210.     {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
  211.     {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
  212.     {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
  213.     {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
  214.     {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
  215.     {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
  216.     {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
  217.     {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
  218.     {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
  219.     {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
  220.     {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
  221.     {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
  222.     {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
  223. # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
  224.     {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
  225. # endif
  226.     {"", NULL},
  227. };
  228.  
  229. /*
  230.  * Free python.dll
  231.  */
  232.     static void
  233. end_dynamic_python()
  234. {
  235.     if (hinstPython)
  236.     {
  237.     FreeLibrary(hinstPython);
  238.     hinstPython = 0;
  239.     }
  240. }
  241.  
  242. /*
  243.  * Load library and get all pointers.
  244.  * Parameter 'libname' provides name of DLL.
  245.  * Return OK or FAIL.
  246.  */
  247.     static int
  248. python_runtime_link_init(char *libname, int verbose)
  249. {
  250.     int i;
  251.  
  252.     if (hinstPython)
  253.     return OK;
  254.     hinstPython = LoadLibrary(libname);
  255.     if (!hinstPython)
  256.     {
  257.     if (verbose)
  258.         EMSG2(_(e_loadlib), libname);
  259.     return FAIL;
  260.     }
  261.  
  262.     for (i = 0; python_funcname_table[i].ptr; ++i)
  263.     {
  264.     if (!(*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
  265.             python_funcname_table[i].name)))
  266.     {
  267.         FreeLibrary(hinstPython);
  268.         hinstPython = 0;
  269.         if (verbose)
  270.         EMSG2(_(e_loadfunc), python_funcname_table[i].name);
  271.         return FAIL;
  272.     }
  273.     }
  274.     return OK;
  275. }
  276.  
  277. /*
  278.  * If python is enabled (there is installed python on Windows system) return
  279.  * TRUE, else FALSE.
  280.  */
  281.     int
  282. python_enabled(verbose)
  283.     int        verbose;
  284. {
  285.     return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
  286. }
  287.  
  288. /* Load the standard Python exceptions - don't import the symbols from the
  289.  * DLL, as this can cause errors (importing data symbols is not reliable).
  290.  */
  291. static void get_exceptions __ARGS((void));
  292.  
  293.     static void
  294. get_exceptions()
  295. {
  296.     PyObject *exmod = PyImport_ImportModule("exceptions");
  297.     PyObject *exdict = PyModule_GetDict(exmod);
  298.     imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
  299.     imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
  300.     imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
  301.     imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
  302.     imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
  303.     Py_XINCREF(imp_PyExc_AttributeError);
  304.     Py_XINCREF(imp_PyExc_IndexError);
  305.     Py_XINCREF(imp_PyExc_KeyboardInterrupt);
  306.     Py_XINCREF(imp_PyExc_TypeError);
  307.     Py_XINCREF(imp_PyExc_ValueError);
  308.     Py_XDECREF(exmod);
  309. }
  310. #endif /* DYNAMIC_PYTHON */
  311.  
  312. /******************************************************
  313.  * Internal function prototypes.
  314.  */
  315.  
  316. static void DoPythonCommand(exarg_T *, const char *);
  317. static int RangeStart;
  318. static int RangeEnd;
  319.  
  320. static void PythonIO_Flush(void);
  321. static int PythonIO_Init(void);
  322. static int PythonMod_Init(void);
  323.  
  324. /* Utility functions for the vim/python interface
  325.  * ----------------------------------------------
  326.  */
  327. static PyObject *GetBufferLine(buf_T *, int);
  328. static PyObject *GetBufferLineList(buf_T *, int, int);
  329.  
  330. static int SetBufferLine(buf_T *, int, PyObject *, int *);
  331. static int SetBufferLineList(buf_T *, int, int, PyObject *, int *);
  332. static int InsertBufferLines(buf_T *, int, PyObject *, int *);
  333.  
  334. static PyObject *LineToString(const char *);
  335. static char *StringToLine(PyObject *);
  336.  
  337. static int VimErrorCheck(void);
  338.  
  339. #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
  340.  
  341. /******************************************************
  342.  * 1. Python interpreter main program.
  343.  */
  344.  
  345. static int initialised = 0;
  346.  
  347. #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
  348. typedef PyObject PyThreadState;
  349. #endif /* Python 1.4 */
  350.  
  351. static PyThreadState* saved_python_thread = NULL;
  352.  
  353. /* suspend a thread of the python interpreter
  354.    - other threads are allowed to run */
  355.  
  356. static void Python_SaveThread() {
  357.     saved_python_thread = PyEval_SaveThread();
  358. }
  359.  
  360. /* restore a thread of the python interpreter
  361.    - waits for other threads to block */
  362.  
  363. static void Python_RestoreThread() {
  364.     PyEval_RestoreThread( saved_python_thread );
  365.     saved_python_thread = NULL;
  366. }
  367.  
  368. /* obtain a lock on the Vim data structures */
  369.  
  370. static void Python_Lock_Vim() {
  371. }
  372.  
  373. /* release a lock on the Vim data structures */
  374.  
  375. static void Python_Release_Vim() {
  376. }
  377.  
  378.     void
  379. python_end()
  380. {
  381. #ifdef DYNAMIC_PYTHON
  382.     end_dynamic_python();
  383. #endif
  384. }
  385.  
  386.     static int
  387. Python_Init(void)
  388. {
  389.     if (!initialised)
  390.     {
  391. #ifdef DYNAMIC_PYTHON
  392.     if (!python_enabled(TRUE))
  393.     {
  394.         EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
  395.         goto fail;
  396.     }
  397. #endif
  398.  
  399. #ifndef MACOS
  400.     Py_Initialize();
  401. #else
  402.     PyMac_Initialize();
  403. #endif
  404.     /* initialise threads */
  405.     PyEval_InitThreads();
  406.  
  407. #ifdef DYNAMIC_PYTHON
  408.     get_exceptions();
  409. #endif
  410.  
  411.     if (PythonIO_Init())
  412.         goto fail;
  413.  
  414.     if (PythonMod_Init())
  415.         goto fail;
  416.  
  417.     /* the first python thread is vim's */
  418.     Python_SaveThread();
  419.  
  420.     initialised = 1;
  421.     }
  422.  
  423.     return 0;
  424.  
  425. fail:
  426.     /* We call PythonIO_Flush() here to print any Python errors.
  427.      * This is OK, as it is possible to call this function even
  428.      * if PythonIO_Init() has not completed successfully (it will
  429.      * not do anything in this case).
  430.      */
  431.     PythonIO_Flush();
  432.     return -1;
  433. }
  434.  
  435. /* External interface
  436.  */
  437.     static void
  438. DoPythonCommand(exarg_T *eap, const char *cmd)
  439. {
  440. #ifdef MACOS
  441.     GrafPtr oldPort;
  442.     GetPort (&oldPort);
  443.     /* Check if the Python library is available */
  444.     if ( (Ptr) PyMac_Initialize == (Ptr) kUnresolvedCFragSymbolAddress)
  445.     return;
  446. #endif
  447.     if (Python_Init())
  448.     return;
  449.  
  450.     RangeStart = eap->line1;
  451.     RangeEnd = eap->line2;
  452.     Python_Release_Vim();        /* leave vim */
  453.     Python_RestoreThread();        /* enter python */
  454.     PyRun_SimpleString((char *)(cmd));
  455.     Python_SaveThread();        /* leave python */
  456.     Python_Lock_Vim();            /* enter vim */
  457.     PythonIO_Flush();
  458. #ifdef MACOS
  459.     SetPort (oldPort);
  460. #endif
  461. }
  462.  
  463. /*
  464.  * ":python"
  465.  */
  466.     void
  467. ex_python(exarg_T *eap)
  468. {
  469.     char_u *script;
  470.  
  471.     script = script_get(eap, eap->arg);
  472.     if (script == NULL)
  473.     DoPythonCommand(eap, (char *)eap->arg);
  474.     else
  475.     {
  476.     DoPythonCommand(eap, (char *)script);
  477.     vim_free(script);
  478.     }
  479. }
  480.  
  481. #define BUFFER_SIZE 1024
  482.  
  483. /*
  484.  * ":pyfile"
  485.  */
  486.     void
  487. ex_pyfile(exarg_T *eap)
  488. {
  489.     static char buffer[BUFFER_SIZE];
  490.     const char *file = (char *)eap->arg;
  491.     char *p;
  492.  
  493.     /* Have to do it like this. PyRun_SimpleFile requires you to pass a
  494.      * stdio file pointer, but Vim and the Python DLL are compiled with
  495.      * different options under Windows, meaning that stdio pointers aren't
  496.      * compatible between the two. Yuk.
  497.      *
  498.      * Put the string "execfile('file')" into buffer. But, we need to
  499.      * escape any backslashes or single quotes in the file name, so that
  500.      * Python won't mangle the file name.
  501.      */
  502.     strcpy(buffer, "execfile('");
  503.     p = buffer + 10; /* size of "execfile('" */
  504.  
  505.     while (*file && p < buffer + (BUFFER_SIZE - 3))
  506.     {
  507.     if (*file == '\\' || *file == '\'')
  508.         *p++ = '\\';
  509.     *p++ = *file++;
  510.     }
  511.  
  512.     /* If we didn't finish the file name, we hit a buffer overflow */
  513.     if (*file != '\0')
  514.     return;
  515.  
  516.     /* Put in the terminating "')" and a null */
  517.     *p++ = '\'';
  518.     *p++ = ')';
  519.     *p++ = '\0';
  520.  
  521.     /* Execute the file */
  522.     DoPythonCommand(eap, buffer);
  523. }
  524.  
  525. /******************************************************
  526.  * 2. Python output stream: writes output via [e]msg().
  527.  */
  528.  
  529. /* Implementation functions
  530.  */
  531.  
  532. static PyObject *OutputGetattr(PyObject *, char *);
  533. static int OutputSetattr(PyObject *, char *, PyObject *);
  534.  
  535. static PyObject *OutputWrite(PyObject *, PyObject *);
  536. static PyObject *OutputWritelines(PyObject *, PyObject *);
  537.  
  538. typedef void (*writefn)(char_u *);
  539. static void writer(writefn fn, char_u *str, int n);
  540.  
  541. /* Output object definition
  542.  */
  543.  
  544. typedef struct
  545. {
  546.     PyObject_HEAD
  547.     long softspace;
  548.     long error;
  549. } OutputObject;
  550.  
  551. static struct PyMethodDef OutputMethods[] = {
  552.     /* name,        function,        calling,    documentation */
  553.     {"write",        OutputWrite,    1,        "" },
  554.     {"writelines",  OutputWritelines,    1,        "" },
  555.     { NULL,        NULL,        0,        NULL }
  556. };
  557.  
  558. static PyTypeObject OutputType = {
  559.     PyObject_HEAD_INIT(0)
  560.     0,
  561.     "message",
  562.     sizeof(OutputObject),
  563.     0,
  564.  
  565.     (destructor) 0,
  566.     (printfunc) 0,
  567.     (getattrfunc) OutputGetattr,
  568.     (setattrfunc) OutputSetattr,
  569.     (cmpfunc) 0,
  570.     (reprfunc) 0,
  571.  
  572.     0, /* as number */
  573.     0, /* as sequence */
  574.     0, /* as mapping */
  575.  
  576.     (hashfunc) 0,
  577.     (ternaryfunc) 0,
  578.     (reprfunc) 0
  579. };
  580.  
  581. /*************/
  582.  
  583.     static PyObject *
  584. OutputGetattr(PyObject *self, char *name)
  585. {
  586.     if (strcmp(name, "softspace") == 0)
  587.     return PyInt_FromLong(((OutputObject *)(self))->softspace);
  588.  
  589.     return Py_FindMethod(OutputMethods, self, name);
  590. }
  591.  
  592.     static int
  593. OutputSetattr(PyObject *self, char *name, PyObject *val)
  594. {
  595.     if (val == NULL) {
  596.     PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
  597.     return -1;
  598.     }
  599.  
  600.     if (strcmp(name, "softspace") == 0)
  601.     {
  602.     if (!PyInt_Check(val)) {
  603.         PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
  604.         return -1;
  605.     }
  606.  
  607.     ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
  608.     return 0;
  609.     }
  610.  
  611.     PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
  612.     return -1;
  613. }
  614.  
  615. /*************/
  616.  
  617.     static PyObject *
  618. OutputWrite(PyObject *self, PyObject *args)
  619. {
  620.     int len;
  621.     char *str;
  622.     int error = ((OutputObject *)(self))->error;
  623.  
  624.     if (!PyArg_ParseTuple(args, "s#", &str, &len))
  625.     return NULL;
  626.  
  627.     Py_BEGIN_ALLOW_THREADS
  628.     Python_Lock_Vim();
  629.     writer((writefn)(error ? emsg : msg), (char_u *)str, len);
  630.     Python_Release_Vim();
  631.     Py_END_ALLOW_THREADS
  632.  
  633.     Py_INCREF(Py_None);
  634.     return Py_None;
  635. }
  636.  
  637.     static PyObject *
  638. OutputWritelines(PyObject *self, PyObject *args)
  639. {
  640.     int n;
  641.     int i;
  642.     PyObject *list;
  643.     int error = ((OutputObject *)(self))->error;
  644.  
  645.     if (!PyArg_ParseTuple(args, "O", &list))
  646.     return NULL;
  647.     Py_INCREF(list);
  648.  
  649.     if (!PyList_Check(list)) {
  650.     PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
  651.     Py_DECREF(list);
  652.     return NULL;
  653.     }
  654.  
  655.     n = PyList_Size(list);
  656.  
  657.     for (i = 0; i < n; ++i)
  658.     {
  659.     PyObject *line = PyList_GetItem(list, i);
  660.     char *str;
  661.     int len;
  662.  
  663.     if (!PyArg_Parse(line, "s#", &str, &len)) {
  664.         PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
  665.         Py_DECREF(list);
  666.         return NULL;
  667.     }
  668.  
  669.     Py_BEGIN_ALLOW_THREADS
  670.     Python_Lock_Vim();
  671.     writer((writefn)(error ? emsg : msg), (char_u *)str, len);
  672.     Python_Release_Vim();
  673.     Py_END_ALLOW_THREADS
  674.     }
  675.  
  676.     Py_DECREF(list);
  677.     Py_INCREF(Py_None);
  678.     return Py_None;
  679. }
  680.  
  681. /* Output buffer management
  682.  */
  683.  
  684. static char_u *buffer = NULL;
  685. static int buffer_len = 0;
  686. static int buffer_size = 0;
  687.  
  688. static writefn old_fn = NULL;
  689.  
  690.     static void
  691. buffer_ensure(int n)
  692. {
  693.     int new_size;
  694.     char_u *new_buffer;
  695.  
  696.     if (n < buffer_size)
  697.     return;
  698.  
  699.     new_size = buffer_size;
  700.     while (new_size < n)
  701.     new_size += 80;
  702.  
  703.     if (new_size != buffer_size)
  704.     {
  705.     new_buffer = alloc((unsigned)new_size);
  706.     if (new_buffer == NULL)
  707.         return;
  708.  
  709.     if (buffer)
  710.     {
  711.         memcpy(new_buffer, buffer, buffer_len);
  712.         vim_free(buffer);
  713.     }
  714.  
  715.     buffer = new_buffer;
  716.     buffer_size = new_size;
  717.     }
  718. }
  719.  
  720.     static void
  721. PythonIO_Flush(void)
  722. {
  723.     if (old_fn && buffer_len)
  724.     {
  725.     buffer[buffer_len] = 0;
  726.     old_fn(buffer);
  727.     }
  728.  
  729.     buffer_len = 0;
  730. }
  731.  
  732.     static void
  733. writer(writefn fn, char_u *str, int n)
  734. {
  735.     char_u *ptr;
  736.  
  737.     if (fn != old_fn && old_fn != NULL)
  738.     PythonIO_Flush();
  739.  
  740.     old_fn = fn;
  741.  
  742.     while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
  743.     {
  744.     int len = ptr - str;
  745.  
  746.     buffer_ensure(buffer_len + len + 1);
  747.  
  748.     memcpy(buffer + buffer_len, str, len);
  749.     buffer_len += len;
  750.     buffer[buffer_len] = 0;
  751.     fn(buffer);
  752.     str = ptr + 1;
  753.     n -= len + 1;
  754.     buffer_len = 0;
  755.     }
  756.  
  757.     /* Put the remaining text into the buffer for later printing */
  758.     buffer_ensure(buffer_len + n + 1);
  759.     memcpy(buffer + buffer_len, str, n);
  760.     buffer_len += n;
  761. }
  762.  
  763. /***************/
  764.  
  765. static OutputObject Output =
  766. {
  767.     PyObject_HEAD_INIT(&OutputType)
  768.     0,
  769.     0
  770. };
  771.  
  772. static OutputObject Error =
  773. {
  774.     PyObject_HEAD_INIT(&OutputType)
  775.     0,
  776.     1
  777. };
  778.  
  779.     static int
  780. PythonIO_Init(void)
  781. {
  782.     /* Fixups... */
  783.     OutputType.ob_type = &PyType_Type;
  784.  
  785.     PySys_SetObject("stdout", (PyObject *)(&Output));
  786.     PySys_SetObject("stderr", (PyObject *)(&Error));
  787.  
  788.     if (PyErr_Occurred())
  789.     {
  790.     EMSG(_("E264: Python: Error initialising I/O objects"));
  791.     return -1;
  792.     }
  793.  
  794.     return 0;
  795. }
  796.  
  797. /******************************************************
  798.  * 3. Implementation of the Vim module for Python
  799.  */
  800.  
  801. /* Vim module - Implementation functions
  802.  * -------------------------------------
  803.  */
  804.  
  805. static PyObject *VimError;
  806.  
  807. static PyObject *VimCommand(PyObject *, PyObject *);
  808. static PyObject *VimEval(PyObject *, PyObject *);
  809.  
  810. /* Window type - Implementation functions
  811.  * --------------------------------------
  812.  */
  813.  
  814. typedef struct
  815. {
  816.     PyObject_HEAD
  817.     win_T    *win;
  818. }
  819. WindowObject;
  820.  
  821. #define INVALID_WINDOW_VALUE ((win_T *)(-1))
  822.  
  823. #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
  824.  
  825. static PyObject *WindowNew(win_T *);
  826.  
  827. static void WindowDestructor(PyObject *);
  828. static PyObject *WindowGetattr(PyObject *, char *);
  829. static int WindowSetattr(PyObject *, char *, PyObject *);
  830. static PyObject *WindowRepr(PyObject *);
  831.  
  832. /* Buffer type - Implementation functions
  833.  * --------------------------------------
  834.  */
  835.  
  836. typedef struct
  837. {
  838.     PyObject_HEAD
  839.     buf_T *buf;
  840. }
  841. BufferObject;
  842.  
  843. #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
  844.  
  845. #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
  846.  
  847. static PyObject *BufferNew (buf_T *);
  848.  
  849. static void BufferDestructor(PyObject *);
  850. static PyObject *BufferGetattr(PyObject *, char *);
  851. static PyObject *BufferRepr(PyObject *);
  852.  
  853. static int BufferLength(PyObject *);
  854. static PyObject *BufferItem(PyObject *, int);
  855. static PyObject *BufferSlice(PyObject *, int, int);
  856. static int BufferAssItem(PyObject *, int, PyObject *);
  857. static int BufferAssSlice(PyObject *, int, int, PyObject *);
  858.  
  859. static PyObject *BufferAppend(PyObject *, PyObject *);
  860. static PyObject *BufferMark(PyObject *, PyObject *);
  861. static PyObject *BufferRange(PyObject *, PyObject *);
  862.  
  863. /* Line range type - Implementation functions
  864.  * --------------------------------------
  865.  */
  866.  
  867. typedef struct
  868. {
  869.     PyObject_HEAD
  870.     BufferObject *buf;
  871.     int start;
  872.     int end;
  873. }
  874. RangeObject;
  875.  
  876. #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
  877.  
  878. static PyObject *RangeNew(buf_T *, int, int);
  879.  
  880. static void RangeDestructor(PyObject *);
  881. static PyObject *RangeGetattr(PyObject *, char *);
  882. static PyObject *RangeRepr(PyObject *);
  883.  
  884. static int RangeLength(PyObject *);
  885. static PyObject *RangeItem(PyObject *, int);
  886. static PyObject *RangeSlice(PyObject *, int, int);
  887. static int RangeAssItem(PyObject *, int, PyObject *);
  888. static int RangeAssSlice(PyObject *, int, int, PyObject *);
  889.  
  890. static PyObject *RangeAppend(PyObject *, PyObject *);
  891.  
  892. /* Window list type - Implementation functions
  893.  * -------------------------------------------
  894.  */
  895.  
  896. static int WinListLength(PyObject *);
  897. static PyObject *WinListItem(PyObject *, int);
  898.  
  899. /* Buffer list type - Implementation functions
  900.  * -------------------------------------------
  901.  */
  902.  
  903. static int BufListLength(PyObject *);
  904. static PyObject *BufListItem(PyObject *, int);
  905.  
  906. /* Current objects type - Implementation functions
  907.  * -----------------------------------------------
  908.  */
  909.  
  910. static PyObject *CurrentGetattr(PyObject *, char *);
  911. static int CurrentSetattr(PyObject *, char *, PyObject *);
  912.  
  913. /* Vim module - Definitions
  914.  */
  915.  
  916. static struct PyMethodDef VimMethods[] = {
  917.     /* name,         function,        calling,    documentation */
  918.     {"command",         VimCommand,    1,        "" },
  919.     {"eval",         VimEval,        1,        "" },
  920.     { NULL,         NULL,        0,        NULL }
  921. };
  922.  
  923. /* Vim module - Implementation
  924.  */
  925. /*ARGSUSED*/
  926.     static PyObject *
  927. VimCommand(PyObject *self, PyObject *args)
  928. {
  929.     char *cmd;
  930.     PyObject *result;
  931.  
  932.     if (!PyArg_ParseTuple(args, "s", &cmd))
  933.     return NULL;
  934.  
  935.     PyErr_Clear();
  936.  
  937.     Py_BEGIN_ALLOW_THREADS
  938.     Python_Lock_Vim();
  939.  
  940.     do_cmdline_cmd((char_u *)cmd);
  941.     update_screen(VALID);
  942.  
  943.     Python_Release_Vim();
  944.     Py_END_ALLOW_THREADS
  945.  
  946.     if (VimErrorCheck())
  947.     result = NULL;
  948.     else
  949.     result = Py_None;
  950.  
  951.     Py_XINCREF(result);
  952.     return result;
  953. }
  954.  
  955. /*ARGSUSED*/
  956.     static PyObject *
  957. VimEval(PyObject *self, PyObject *args)
  958. {
  959. #ifdef FEAT_EVAL
  960.     char    *expr;
  961.     char    *str;
  962.     PyObject    *result;
  963.  
  964.     if (!PyArg_ParseTuple(args, "s", &expr))
  965.     return NULL;
  966.  
  967.     Py_BEGIN_ALLOW_THREADS
  968.     Python_Lock_Vim();
  969.     str = (char *)eval_to_string((char_u *)expr, NULL);
  970.     Python_Release_Vim();
  971.     Py_END_ALLOW_THREADS
  972.  
  973.     if (str == NULL)
  974.     {
  975.     PyErr_SetVim(_("invalid expression"));
  976.     return NULL;
  977.     }
  978.  
  979.     result = Py_BuildValue("s", str);
  980.  
  981.     Py_BEGIN_ALLOW_THREADS
  982.     Python_Lock_Vim();
  983.     vim_free(str);
  984.     Python_Release_Vim();
  985.     Py_END_ALLOW_THREADS
  986.  
  987.     return result;
  988. #else
  989.     PyErr_SetVim(_("expressions disabled at compile time"));
  990.     return NULL;
  991. #endif
  992. }
  993.  
  994. /* Common routines for buffers and line ranges
  995.  * -------------------------------------------
  996.  */
  997.     static int
  998. CheckBuffer(BufferObject *this)
  999. {
  1000.     if (this->buf == INVALID_BUFFER_VALUE)
  1001.     {
  1002.     PyErr_SetVim(_("attempt to refer to deleted buffer"));
  1003.     return -1;
  1004.     }
  1005.  
  1006.     return 0;
  1007. }
  1008.  
  1009.     static PyObject *
  1010. RBItem(BufferObject *self, int n, int start, int end)
  1011. {
  1012.     if (CheckBuffer(self))
  1013.     return NULL;
  1014.  
  1015.     if (n < 0 || n > end - start)
  1016.     {
  1017.     PyErr_SetString(PyExc_IndexError, _("line number out of range"));
  1018.     return NULL;
  1019.     }
  1020.  
  1021.     return GetBufferLine(self->buf, n+start);
  1022. }
  1023.  
  1024.     static PyObject *
  1025. RBSlice(BufferObject *self, int lo, int hi, int start, int end)
  1026. {
  1027.     int size;
  1028.  
  1029.     if (CheckBuffer(self))
  1030.     return NULL;
  1031.  
  1032.     size = end - start + 1;
  1033.  
  1034.     if (lo < 0)
  1035.     lo = 0;
  1036.     else if (lo > size)
  1037.     lo = size;
  1038.     if (hi < 0)
  1039.     hi = 0;
  1040.     if (hi < lo)
  1041.     hi = lo;
  1042.     else if (hi > size)
  1043.     hi = size;
  1044.  
  1045.     return GetBufferLineList(self->buf, lo+start, hi+start);
  1046. }
  1047.  
  1048.     static int
  1049. RBAssItem(BufferObject *self, int n, PyObject *val, int start, int end, int *new_end)
  1050. {
  1051.     int len_change;
  1052.  
  1053.     if (CheckBuffer(self))
  1054.     return -1;
  1055.  
  1056.     if (n < 0 || n > end - start)
  1057.     {
  1058.     PyErr_SetString(PyExc_IndexError, _("line number out of range"));
  1059.     return -1;
  1060.     }
  1061.  
  1062.     if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
  1063.     return -1;
  1064.  
  1065.     if (new_end)
  1066.     *new_end = end + len_change;
  1067.  
  1068.     return 0;
  1069. }
  1070.  
  1071.     static int
  1072. RBAssSlice(BufferObject *self, int lo, int hi, PyObject *val, int start, int end, int *new_end)
  1073. {
  1074.     int size;
  1075.     int len_change;
  1076.  
  1077.     /* Self must be a valid buffer */
  1078.     if (CheckBuffer(self))
  1079.     return -1;
  1080.  
  1081.     /* Sort out the slice range */
  1082.     size = end - start + 1;
  1083.  
  1084.     if (lo < 0)
  1085.     lo = 0;
  1086.     else if (lo > size)
  1087.     lo = size;
  1088.     if (hi < 0)
  1089.     hi = 0;
  1090.     if (hi < lo)
  1091.     hi = lo;
  1092.     else if (hi > size)
  1093.     hi = size;
  1094.  
  1095.     if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
  1096.     return -1;
  1097.  
  1098.     if (new_end)
  1099.     *new_end = end + len_change;
  1100.  
  1101.     return 0;
  1102. }
  1103.  
  1104.     static PyObject *
  1105. RBAppend(BufferObject *self, PyObject *args, int start, int end, int *new_end)
  1106. {
  1107.     PyObject *lines;
  1108.     int len_change;
  1109.     int max;
  1110.     int n;
  1111.  
  1112.     if (CheckBuffer(self))
  1113.     return NULL;
  1114.  
  1115.     max = n = end - start + 1;
  1116.  
  1117.     if (!PyArg_ParseTuple(args, "O|i", &lines, &n))
  1118.     return NULL;
  1119.  
  1120.     if (n < 0 || n > max)
  1121.     {
  1122.     PyErr_SetString(PyExc_ValueError, _("line number out of range"));
  1123.     return NULL;
  1124.     }
  1125.  
  1126.     if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
  1127.     return NULL;
  1128.  
  1129.     if (new_end)
  1130.     *new_end = end + len_change;
  1131.  
  1132.     Py_INCREF(Py_None);
  1133.     return Py_None;
  1134. }
  1135.  
  1136.  
  1137. /* Buffer object - Definitions
  1138.  */
  1139.  
  1140. static struct PyMethodDef BufferMethods[] = {
  1141.     /* name,        function,        calling,    documentation */
  1142.     {"append",        BufferAppend,    1,        "" },
  1143.     {"mark",        BufferMark,        1,        "" },
  1144.     {"range",        BufferRange,    1,        "" },
  1145.     { NULL,        NULL,        0,        NULL }
  1146. };
  1147.  
  1148. static PySequenceMethods BufferAsSeq = {
  1149.     (inquiry)        BufferLength,        /* sq_length,    len(x)   */
  1150.     (binaryfunc)    0, /* BufferConcat, */         /* sq_concat,    x+y      */
  1151.     (intargfunc)    0, /* BufferRepeat, */         /* sq_repeat,    x*n      */
  1152.     (intargfunc)    BufferItem,        /* sq_item,      x[i]     */
  1153.     (intintargfunc)    BufferSlice,        /* sq_slice,     x[i:j]   */
  1154.     (intobjargproc)    BufferAssItem,        /* sq_ass_item,  x[i]=v   */
  1155.     (intintobjargproc)    BufferAssSlice,     /* sq_ass_slice, x[i:j]=v */
  1156. };
  1157.  
  1158. static PyTypeObject BufferType = {
  1159.     PyObject_HEAD_INIT(0)
  1160.     0,
  1161.     "buffer",
  1162.     sizeof(BufferObject),
  1163.     0,
  1164.  
  1165.     (destructor)    BufferDestructor,    /* tp_dealloc,    refcount==0  */
  1166.     (printfunc)     0,            /* tp_print,    print x      */
  1167.     (getattrfunc)   BufferGetattr,    /* tp_getattr,    x.attr         */
  1168.     (setattrfunc)   0,            /* tp_setattr,    x.attr=v     */
  1169.     (cmpfunc)        0,            /* tp_compare,    x>y         */
  1170.     (reprfunc)        BufferRepr,        /* tp_repr,    `x`, print x */
  1171.  
  1172.     0,            /* as number */
  1173.     &BufferAsSeq,   /* as sequence */
  1174.     0,            /* as mapping */
  1175.  
  1176.     (hashfunc) 0,            /* tp_hash, dict(x) */
  1177.     (ternaryfunc) 0,            /* tp_call, x()     */
  1178.     (reprfunc) 0,            /* tp_str,  str(x)  */
  1179. };
  1180.  
  1181. /* Buffer object - Implementation
  1182.  */
  1183.  
  1184.     static PyObject *
  1185. BufferNew(buf_T *buf)
  1186. {
  1187.     /* We need to handle deletion of buffers underneath us.
  1188.      * If we add a "python_ref" field to the buf_T structure,
  1189.      * then we can get at it in buf_freeall() in vim. We then
  1190.      * need to create only ONE Python object per buffer - if
  1191.      * we try to create a second, just INCREF the existing one
  1192.      * and return it. The (single) Python object referring to
  1193.      * the buffer is stored in "python_ref".
  1194.      * Question: what to do on a buf_freeall(). We'll probably
  1195.      * have to either delete the Python object (DECREF it to
  1196.      * zero - a bad idea, as it leaves dangling refs!) or
  1197.      * set the buf_T * value to an invalid value (-1?), which
  1198.      * means we need checks in all access functions... Bah.
  1199.      */
  1200.  
  1201.     BufferObject *self;
  1202.  
  1203.     if (buf->python_ref)
  1204.     {
  1205.     self = buf->python_ref;
  1206.     Py_INCREF(self);
  1207.     }
  1208.     else
  1209.     {
  1210.     self = PyObject_NEW(BufferObject, &BufferType);
  1211.     if (self == NULL)
  1212.         return NULL;
  1213.     self->buf = buf;
  1214.     buf->python_ref = self;
  1215.     }
  1216.  
  1217.     return (PyObject *)(self);
  1218. }
  1219.  
  1220.     static void
  1221. BufferDestructor(PyObject *self)
  1222. {
  1223.     BufferObject *this = (BufferObject *)(self);
  1224.  
  1225.     if (this->buf && this->buf != INVALID_BUFFER_VALUE)
  1226.     this->buf->python_ref = NULL;
  1227.  
  1228.     PyMem_DEL(self);
  1229. }
  1230.  
  1231.     static PyObject *
  1232. BufferGetattr(PyObject *self, char *name)
  1233. {
  1234.     BufferObject *this = (BufferObject *)(self);
  1235.  
  1236.     if (CheckBuffer(this))
  1237.     return NULL;
  1238.  
  1239.     if (strcmp(name, "name") == 0)
  1240.     return Py_BuildValue("s",this->buf->b_ffname);
  1241.     else if (strcmp(name, "number") == 0)
  1242.     return Py_BuildValue("i",this->buf->b_fnum);
  1243.     else if (strcmp(name,"__members__") == 0)
  1244.     return Py_BuildValue("[ss]", "name", "number");
  1245.     else
  1246.     return Py_FindMethod(BufferMethods, self, name);
  1247. }
  1248.  
  1249.     static PyObject *
  1250. BufferRepr(PyObject *self)
  1251. {
  1252.     static char repr[50];
  1253.     BufferObject *this = (BufferObject *)(self);
  1254.  
  1255.     if (this->buf == INVALID_BUFFER_VALUE)
  1256.     {
  1257.     sprintf(repr, _("<buffer object (deleted) at %8lX>"), (long)(self));
  1258.     return PyString_FromString(repr);
  1259.     }
  1260.     else
  1261.     {
  1262.     char *name = (char *)this->buf->b_fname;
  1263.     int len;
  1264.  
  1265.     if (name == NULL)
  1266.         name = "";
  1267.     len = strlen(name);
  1268.  
  1269.     if (len > 35)
  1270.         name = name + (35 - len);
  1271.  
  1272.     sprintf(repr, "<buffer %s%s>", len > 35 ? "..." : "", name);
  1273.  
  1274.     return PyString_FromString(repr);
  1275.     }
  1276. }
  1277.  
  1278. /******************/
  1279.  
  1280.     static int
  1281. BufferLength(PyObject *self)
  1282. {
  1283.     /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
  1284.     if (CheckBuffer((BufferObject *)(self)))
  1285.     return -1; /* ??? */
  1286.  
  1287.     return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
  1288. }
  1289.  
  1290.     static PyObject *
  1291. BufferItem(PyObject *self, int n)
  1292. {
  1293.     return RBItem((BufferObject *)(self), n, 1,
  1294.           (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
  1295. }
  1296.  
  1297.     static PyObject *
  1298. BufferSlice(PyObject *self, int lo, int hi)
  1299. {
  1300.     return RBSlice((BufferObject *)(self), lo, hi, 1,
  1301.            (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
  1302. }
  1303.  
  1304.     static int
  1305. BufferAssItem(PyObject *self, int n, PyObject *val)
  1306. {
  1307.     return RBAssItem((BufferObject *)(self), n, val, 1,
  1308.              (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
  1309.              NULL);
  1310. }
  1311.  
  1312.     static int
  1313. BufferAssSlice(PyObject *self, int lo, int hi, PyObject *val)
  1314. {
  1315.     return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
  1316.               (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
  1317.               NULL);
  1318. }
  1319.  
  1320.     static PyObject *
  1321. BufferAppend(PyObject *self, PyObject *args)
  1322. {
  1323.     return RBAppend((BufferObject *)(self), args, 1,
  1324.             (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
  1325.             NULL);
  1326. }
  1327.  
  1328.     static PyObject *
  1329. BufferMark(PyObject *self, PyObject *args)
  1330. {
  1331.     pos_T    *posp;
  1332.     char    mark;
  1333.     buf_T    *curbuf_save;
  1334.  
  1335.     if (CheckBuffer((BufferObject *)(self)))
  1336.     return NULL;
  1337.  
  1338.     if (!PyArg_ParseTuple(args, "c", &mark))
  1339.     return NULL;
  1340.  
  1341.     curbuf_save = curbuf;
  1342.     curbuf = ((BufferObject *)(self))->buf;
  1343.     posp = getmark(mark, FALSE);
  1344.     curbuf = curbuf_save;
  1345.  
  1346.     if (posp == NULL)
  1347.     {
  1348.     PyErr_SetVim(_("invalid mark name"));
  1349.     return NULL;
  1350.     }
  1351.  
  1352.     /* Ckeck for keyboard interrupt */
  1353.     if (VimErrorCheck())
  1354.     return NULL;
  1355.  
  1356.     if (posp->lnum <= 0)
  1357.     {
  1358.     /* Or raise an error? */
  1359.     Py_INCREF(Py_None);
  1360.     return Py_None;
  1361.     }
  1362.  
  1363.     return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
  1364. }
  1365.  
  1366.     static PyObject *
  1367. BufferRange(PyObject *self, PyObject *args)
  1368. {
  1369.     int start;
  1370.     int end;
  1371.  
  1372.     if (CheckBuffer((BufferObject *)(self)))
  1373.     return NULL;
  1374.  
  1375.     if (!PyArg_ParseTuple(args, "ii", &start, &end))
  1376.     return NULL;
  1377.  
  1378.     return RangeNew(((BufferObject *)(self))->buf, start, end);
  1379. }
  1380.  
  1381. /* Line range object - Definitions
  1382.  */
  1383.  
  1384. static struct PyMethodDef RangeMethods[] = {
  1385.     /* name,        function,        calling,    documentation */
  1386.     {"append",        RangeAppend,    1,        "" },
  1387.     { NULL,        NULL,        0,        NULL }
  1388. };
  1389.  
  1390. static PySequenceMethods RangeAsSeq = {
  1391.     (inquiry)        RangeLength,        /* sq_length,    len(x)   */
  1392.     (binaryfunc)    0, /* RangeConcat, */         /* sq_concat,    x+y      */
  1393.     (intargfunc)    0, /* RangeRepeat, */         /* sq_repeat,    x*n      */
  1394.     (intargfunc)    RangeItem,        /* sq_item,      x[i]     */
  1395.     (intintargfunc)    RangeSlice,        /* sq_slice,     x[i:j]   */
  1396.     (intobjargproc)    RangeAssItem,        /* sq_ass_item,  x[i]=v   */
  1397.     (intintobjargproc)    RangeAssSlice,        /* sq_ass_slice, x[i:j]=v */
  1398. };
  1399.  
  1400. static PyTypeObject RangeType = {
  1401.     PyObject_HEAD_INIT(0)
  1402.     0,
  1403.     "range",
  1404.     sizeof(RangeObject),
  1405.     0,
  1406.  
  1407.     (destructor)    RangeDestructor,    /* tp_dealloc,    refcount==0  */
  1408.     (printfunc)     0,            /* tp_print,    print x      */
  1409.     (getattrfunc)   RangeGetattr,    /* tp_getattr,    x.attr         */
  1410.     (setattrfunc)   0,            /* tp_setattr,    x.attr=v     */
  1411.     (cmpfunc)        0,            /* tp_compare,    x>y         */
  1412.     (reprfunc)        RangeRepr,        /* tp_repr,    `x`, print x */
  1413.  
  1414.     0,            /* as number */
  1415.     &RangeAsSeq,    /* as sequence */
  1416.     0,            /* as mapping */
  1417.  
  1418.     (hashfunc) 0,            /* tp_hash, dict(x) */
  1419.     (ternaryfunc) 0,            /* tp_call, x()     */
  1420.     (reprfunc) 0,            /* tp_str,  str(x)  */
  1421. };
  1422.  
  1423. /* Line range object - Implementation
  1424.  */
  1425.  
  1426.     static PyObject *
  1427. RangeNew(buf_T *buf, int start, int end)
  1428. {
  1429.     BufferObject *bufr;
  1430.     RangeObject *self;
  1431.     self = PyObject_NEW(RangeObject, &RangeType);
  1432.     if (self == NULL)
  1433.     return NULL;
  1434.  
  1435.     bufr = (BufferObject *)BufferNew(buf);
  1436.     if (bufr == NULL)
  1437.     {
  1438.     PyMem_DEL(self);
  1439.     return NULL;
  1440.     }
  1441.     Py_INCREF(bufr);
  1442.  
  1443.     self->buf = bufr;
  1444.     self->start = start;
  1445.     self->end = end;
  1446.  
  1447.     return (PyObject *)(self);
  1448. }
  1449.  
  1450.     static void
  1451. RangeDestructor(PyObject *self)
  1452. {
  1453.     Py_DECREF(((RangeObject *)(self))->buf);
  1454.     PyMem_DEL(self);
  1455. }
  1456.  
  1457.     static PyObject *
  1458. RangeGetattr(PyObject *self, char *name)
  1459. {
  1460.     return Py_FindMethod(RangeMethods, self, name);
  1461. }
  1462.  
  1463.     static PyObject *
  1464. RangeRepr(PyObject *self)
  1465. {
  1466.     static char repr[75];
  1467.     RangeObject *this = (RangeObject *)(self);
  1468.  
  1469.     if (this->buf->buf == INVALID_BUFFER_VALUE)
  1470.     {
  1471.     sprintf(repr, "<range object (for deleted buffer) at %8lX>",
  1472.                                 (long)(self));
  1473.     return PyString_FromString(repr);
  1474.     }
  1475.     else
  1476.     {
  1477.     char *name = (char *)this->buf->buf->b_fname;
  1478.     int len;
  1479.  
  1480.     if (name == NULL)
  1481.         name = "";
  1482.     len = strlen(name);
  1483.  
  1484.     if (len > 45)
  1485.         name = name + (45 - len);
  1486.  
  1487.     sprintf(repr, "<range %s%s (%d:%d)>",
  1488.         len > 45 ? "..." : "", name,
  1489.         this->start, this->end);
  1490.  
  1491.     return PyString_FromString(repr);
  1492.     }
  1493. }
  1494.  
  1495. /****************/
  1496.  
  1497.     static int
  1498. RangeLength(PyObject *self)
  1499. {
  1500.     /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
  1501.     if (CheckBuffer(((RangeObject *)(self))->buf))
  1502.     return -1; /* ??? */
  1503.  
  1504.     return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
  1505. }
  1506.  
  1507.     static PyObject *
  1508. RangeItem(PyObject *self, int n)
  1509. {
  1510.     return RBItem(((RangeObject *)(self))->buf, n,
  1511.           ((RangeObject *)(self))->start,
  1512.           ((RangeObject *)(self))->end);
  1513. }
  1514.  
  1515.     static PyObject *
  1516. RangeSlice(PyObject *self, int lo, int hi)
  1517. {
  1518.     return RBSlice(((RangeObject *)(self))->buf, lo, hi,
  1519.            ((RangeObject *)(self))->start,
  1520.            ((RangeObject *)(self))->end);
  1521. }
  1522.  
  1523.     static int
  1524. RangeAssItem(PyObject *self, int n, PyObject *val)
  1525. {
  1526.     return RBAssItem(((RangeObject *)(self))->buf, n, val,
  1527.              ((RangeObject *)(self))->start,
  1528.              ((RangeObject *)(self))->end,
  1529.              &((RangeObject *)(self))->end);
  1530. }
  1531.  
  1532.     static int
  1533. RangeAssSlice(PyObject *self, int lo, int hi, PyObject *val)
  1534. {
  1535.     return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
  1536.               ((RangeObject *)(self))->start,
  1537.               ((RangeObject *)(self))->end,
  1538.               &((RangeObject *)(self))->end);
  1539. }
  1540.  
  1541.     static PyObject *
  1542. RangeAppend(PyObject *self, PyObject *args)
  1543. {
  1544.     return RBAppend(((RangeObject *)(self))->buf, args,
  1545.             ((RangeObject *)(self))->start,
  1546.             ((RangeObject *)(self))->end,
  1547.             &((RangeObject *)(self))->end);
  1548. }
  1549.  
  1550. /* Buffer list object - Definitions
  1551.  */
  1552.  
  1553. typedef struct
  1554. {
  1555.     PyObject_HEAD
  1556. }
  1557. BufListObject;
  1558.  
  1559. static PySequenceMethods BufListAsSeq = {
  1560.     (inquiry)        BufListLength,        /* sq_length,    len(x)   */
  1561.     (binaryfunc)    0,            /* sq_concat,    x+y      */
  1562.     (intargfunc)    0,            /* sq_repeat,    x*n      */
  1563.     (intargfunc)    BufListItem,        /* sq_item,      x[i]     */
  1564.     (intintargfunc)    0,            /* sq_slice,     x[i:j]   */
  1565.     (intobjargproc)    0,            /* sq_ass_item,  x[i]=v   */
  1566.     (intintobjargproc)    0,            /* sq_ass_slice, x[i:j]=v */
  1567. };
  1568.  
  1569. static PyTypeObject BufListType = {
  1570.     PyObject_HEAD_INIT(0)
  1571.     0,
  1572.     "buffer list",
  1573.     sizeof(BufListObject),
  1574.     0,
  1575.  
  1576.     (destructor)    0,            /* tp_dealloc,    refcount==0  */
  1577.     (printfunc)     0,            /* tp_print,    print x      */
  1578.     (getattrfunc)   0,            /* tp_getattr,    x.attr         */
  1579.     (setattrfunc)   0,            /* tp_setattr,    x.attr=v     */
  1580.     (cmpfunc)        0,            /* tp_compare,    x>y         */
  1581.     (reprfunc)        0,            /* tp_repr,    `x`, print x */
  1582.  
  1583.     0,            /* as number */
  1584.     &BufListAsSeq,  /* as sequence */
  1585.     0,            /* as mapping */
  1586.  
  1587.     (hashfunc) 0,            /* tp_hash, dict(x) */
  1588.     (ternaryfunc) 0,            /* tp_call, x()     */
  1589.     (reprfunc) 0,            /* tp_str,  str(x)  */
  1590. };
  1591.  
  1592. /* Buffer list object - Implementation
  1593.  */
  1594.  
  1595. /*ARGSUSED*/
  1596.     static int
  1597. BufListLength(PyObject *self)
  1598. {
  1599.     buf_T    *b = firstbuf;
  1600.     int        n = 0;
  1601.  
  1602.     while (b)
  1603.     {
  1604.     ++n;
  1605.     b = b->b_next;
  1606.     }
  1607.  
  1608.     return n;
  1609. }
  1610.  
  1611. /*ARGSUSED*/
  1612.     static PyObject *
  1613. BufListItem(PyObject *self, int n)
  1614. {
  1615.     buf_T *b;
  1616.  
  1617.     for (b = firstbuf; b; b = b->b_next, --n)
  1618.     {
  1619.     if (n == 0)
  1620.         return BufferNew(b);
  1621.     }
  1622.  
  1623.     PyErr_SetString(PyExc_IndexError, _("no such buffer"));
  1624.     return NULL;
  1625. }
  1626.  
  1627. /* Window object - Definitions
  1628.  */
  1629.  
  1630. static struct PyMethodDef WindowMethods[] = {
  1631.     /* name,        function,        calling,    documentation */
  1632.     { NULL,        NULL,        0,        NULL }
  1633. };
  1634.  
  1635. static PyTypeObject WindowType = {
  1636.     PyObject_HEAD_INIT(0)
  1637.     0,
  1638.     "window",
  1639.     sizeof(WindowObject),
  1640.     0,
  1641.  
  1642.     (destructor)    WindowDestructor,    /* tp_dealloc,    refcount==0  */
  1643.     (printfunc)     0,            /* tp_print,    print x      */
  1644.     (getattrfunc)   WindowGetattr,    /* tp_getattr,    x.attr         */
  1645.     (setattrfunc)   WindowSetattr,    /* tp_setattr,    x.attr=v     */
  1646.     (cmpfunc)        0,            /* tp_compare,    x>y         */
  1647.     (reprfunc)        WindowRepr,        /* tp_repr,    `x`, print x */
  1648.  
  1649.     0,            /* as number */
  1650.     0,            /* as sequence */
  1651.     0,            /* as mapping */
  1652.  
  1653.     (hashfunc) 0,            /* tp_hash, dict(x) */
  1654.     (ternaryfunc) 0,            /* tp_call, x()     */
  1655.     (reprfunc) 0,            /* tp_str,  str(x)  */
  1656. };
  1657.  
  1658. /* Window object - Implementation
  1659.  */
  1660.  
  1661.     static PyObject *
  1662. WindowNew(win_T *win)
  1663. {
  1664.     /* We need to handle deletion of windows underneath us.
  1665.      * If we add a "python_ref" field to the win_T structure,
  1666.      * then we can get at it in win_free() in vim. We then
  1667.      * need to create only ONE Python object per window - if
  1668.      * we try to create a second, just INCREF the existing one
  1669.      * and return it. The (single) Python object referring to
  1670.      * the window is stored in "python_ref".
  1671.      * On a win_free() we set the Python object's win_T* field
  1672.      * to an invalid value. We trap all uses of a window
  1673.      * object, and reject them if the win_T* field is invalid.
  1674.      */
  1675.  
  1676.     WindowObject *self;
  1677.  
  1678.     if (win->python_ref)
  1679.     {
  1680.     self = win->python_ref;
  1681.     Py_INCREF(self);
  1682.     }
  1683.     else
  1684.     {
  1685.     self = PyObject_NEW(WindowObject, &WindowType);
  1686.     if (self == NULL)
  1687.         return NULL;
  1688.     self->win = win;
  1689.     win->python_ref = self;
  1690.     }
  1691.  
  1692.     return (PyObject *)(self);
  1693. }
  1694.  
  1695.     static void
  1696. WindowDestructor(PyObject *self)
  1697. {
  1698.     WindowObject *this = (WindowObject *)(self);
  1699.  
  1700.     if (this->win && this->win != INVALID_WINDOW_VALUE)
  1701.     this->win->python_ref = NULL;
  1702.  
  1703.     PyMem_DEL(self);
  1704. }
  1705.  
  1706.     static int
  1707. CheckWindow(WindowObject *this)
  1708. {
  1709.     if (this->win == INVALID_WINDOW_VALUE)
  1710.     {
  1711.     PyErr_SetVim(_("attempt to refer to deleted window"));
  1712.     return -1;
  1713.     }
  1714.  
  1715.     return 0;
  1716. }
  1717.  
  1718.     static PyObject *
  1719. WindowGetattr(PyObject *self, char *name)
  1720. {
  1721.     WindowObject *this = (WindowObject *)(self);
  1722.  
  1723.     if (CheckWindow(this))
  1724.     return NULL;
  1725.  
  1726.     if (strcmp(name, "buffer") == 0)
  1727.     return (PyObject *)BufferNew(this->win->w_buffer);
  1728.     else if (strcmp(name, "cursor") == 0)
  1729.     {
  1730.     pos_T *pos = &this->win->w_cursor;
  1731.  
  1732.     return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
  1733.     }
  1734.     else if (strcmp(name, "height") == 0)
  1735.     return Py_BuildValue("l", (long)(this->win->w_height));
  1736. #ifdef FEAT_VERTSPLIT
  1737.     else if (strcmp(name, "width") == 0)
  1738.     return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
  1739. #endif
  1740.     else if (strcmp(name,"__members__") == 0)
  1741.     return Py_BuildValue("[sss]", "buffer", "cursor", "height");
  1742.     else
  1743.     return Py_FindMethod(WindowMethods, self, name);
  1744. }
  1745.  
  1746.     static int
  1747. WindowSetattr(PyObject *self, char *name, PyObject *val)
  1748. {
  1749.     WindowObject *this = (WindowObject *)(self);
  1750.  
  1751.     if (CheckWindow(this))
  1752.     return -1;
  1753.  
  1754.     if (strcmp(name, "buffer") == 0)
  1755.     {
  1756.     PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
  1757.     return -1;
  1758.     }
  1759.     else if (strcmp(name, "cursor") == 0)
  1760.     {
  1761.     long lnum;
  1762.     long col;
  1763.  
  1764.     if (!PyArg_Parse(val, "(ll)", &lnum, &col))
  1765.         return -1;
  1766.  
  1767.     if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
  1768.     {
  1769.         PyErr_SetVim(_("cursor position outside buffer"));
  1770.         return -1;
  1771.     }
  1772.  
  1773.     /* Check for keyboard interrupts */
  1774.     if (VimErrorCheck())
  1775.         return -1;
  1776.  
  1777.     /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
  1778.  
  1779.     this->win->w_cursor.lnum = lnum;
  1780.     this->win->w_cursor.col = col;
  1781.     update_screen(VALID);
  1782.  
  1783.     return 0;
  1784.     }
  1785.     else if (strcmp(name, "height") == 0)
  1786.     {
  1787.     int    height;
  1788.     win_T    *savewin;
  1789.  
  1790.     if (!PyArg_Parse(val, "i", &height))
  1791.         return -1;
  1792.  
  1793. #ifdef FEAT_GUI
  1794.     need_mouse_correct = TRUE;
  1795. #endif
  1796.     savewin = curwin;
  1797.     curwin = this->win;
  1798.     win_setheight(height);
  1799.     curwin = savewin;
  1800.  
  1801.     /* Check for keyboard interrupts */
  1802.     if (VimErrorCheck())
  1803.         return -1;
  1804.  
  1805.     return 0;
  1806.     }
  1807. #ifdef FEAT_VERTSPLIT
  1808.     else if (strcmp(name, "width") == 0)
  1809.     {
  1810.     int    width;
  1811.     win_T    *savewin;
  1812.  
  1813.     if (!PyArg_Parse(val, "i", &width))
  1814.         return -1;
  1815.  
  1816. #ifdef FEAT_GUI
  1817.     need_mouse_correct = TRUE;
  1818. #endif
  1819.     savewin = curwin;
  1820.     curwin = this->win;
  1821.     win_setwidth(width);
  1822.     curwin = savewin;
  1823.  
  1824.     /* Check for keyboard interrupts */
  1825.     if (VimErrorCheck())
  1826.         return -1;
  1827.  
  1828.     return 0;
  1829.     }
  1830. #endif
  1831.     else
  1832.     {
  1833.     PyErr_SetString(PyExc_AttributeError, name);
  1834.     return -1;
  1835.     }
  1836. }
  1837.  
  1838.     static PyObject *
  1839. WindowRepr(PyObject *self)
  1840. {
  1841.     static char repr[50];
  1842.     WindowObject *this = (WindowObject *)(self);
  1843.  
  1844.     if (this->win == INVALID_WINDOW_VALUE)
  1845.     {
  1846.     sprintf(repr, _("<window object (deleted) at %.8lX>"), (long)(self));
  1847.     return PyString_FromString(repr);
  1848.     }
  1849.     else
  1850.     {
  1851.     int    i = 0;
  1852.     win_T    *w;
  1853.  
  1854.     for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
  1855.         ++i;
  1856.  
  1857.     if (w == NULL)
  1858.         sprintf(repr, _("<window object (unknown) at %.8lX>"), (long)(self));
  1859.     else
  1860.         sprintf(repr, _("<window %d>"), i);
  1861.  
  1862.     return PyString_FromString(repr);
  1863.     }
  1864. }
  1865.  
  1866. /* Window list object - Definitions
  1867.  */
  1868.  
  1869. typedef struct
  1870. {
  1871.     PyObject_HEAD
  1872. }
  1873. WinListObject;
  1874.  
  1875. static PySequenceMethods WinListAsSeq = {
  1876.     (inquiry)        WinListLength,        /* sq_length,    len(x)   */
  1877.     (binaryfunc)    0,            /* sq_concat,    x+y      */
  1878.     (intargfunc)    0,            /* sq_repeat,    x*n      */
  1879.     (intargfunc)    WinListItem,        /* sq_item,      x[i]     */
  1880.     (intintargfunc)    0,            /* sq_slice,     x[i:j]   */
  1881.     (intobjargproc)    0,            /* sq_ass_item,  x[i]=v   */
  1882.     (intintobjargproc)    0,            /* sq_ass_slice, x[i:j]=v */
  1883. };
  1884.  
  1885. static PyTypeObject WinListType = {
  1886.     PyObject_HEAD_INIT(0)
  1887.     0,
  1888.     "window list",
  1889.     sizeof(WinListObject),
  1890.     0,
  1891.  
  1892.     (destructor)    0,            /* tp_dealloc,    refcount==0  */
  1893.     (printfunc)     0,            /* tp_print,    print x      */
  1894.     (getattrfunc)   0,            /* tp_getattr,    x.attr         */
  1895.     (setattrfunc)   0,            /* tp_setattr,    x.attr=v     */
  1896.     (cmpfunc)        0,            /* tp_compare,    x>y         */
  1897.     (reprfunc)        0,            /* tp_repr,    `x`, print x */
  1898.  
  1899.     0,            /* as number */
  1900.     &WinListAsSeq,  /* as sequence */
  1901.     0,            /* as mapping */
  1902.  
  1903.     (hashfunc) 0,            /* tp_hash, dict(x) */
  1904.     (ternaryfunc) 0,            /* tp_call, x()     */
  1905.     (reprfunc) 0,            /* tp_str,  str(x)  */
  1906. };
  1907.  
  1908. /* Window list object - Implementation
  1909.  */
  1910. /*ARGSUSED*/
  1911.     static int
  1912. WinListLength(PyObject *self)
  1913. {
  1914.     win_T    *w = firstwin;
  1915.     int        n = 0;
  1916.  
  1917.     while (w)
  1918.     {
  1919.     ++n;
  1920.     w = W_NEXT(w);
  1921.     }
  1922.  
  1923.     return n;
  1924. }
  1925.  
  1926. /*ARGSUSED*/
  1927.     static PyObject *
  1928. WinListItem(PyObject *self, int n)
  1929. {
  1930.     win_T *w;
  1931.  
  1932.     for (w = firstwin; w; w = W_NEXT(w), --n)
  1933.     if (n == 0)
  1934.         return WindowNew(w);
  1935.  
  1936.     PyErr_SetString(PyExc_IndexError, _("no such window"));
  1937.     return NULL;
  1938. }
  1939.  
  1940. /* Current items object - Definitions
  1941.  */
  1942.  
  1943. typedef struct
  1944. {
  1945.     PyObject_HEAD
  1946. }
  1947. CurrentObject;
  1948.  
  1949. static PyTypeObject CurrentType = {
  1950.     PyObject_HEAD_INIT(0)
  1951.     0,
  1952.     "current data",
  1953.     sizeof(CurrentObject),
  1954.     0,
  1955.  
  1956.     (destructor)    0,            /* tp_dealloc,    refcount==0  */
  1957.     (printfunc)     0,            /* tp_print,    print x      */
  1958.     (getattrfunc)   CurrentGetattr,    /* tp_getattr,    x.attr         */
  1959.     (setattrfunc)   CurrentSetattr,    /* tp_setattr,    x.attr=v     */
  1960.     (cmpfunc)        0,            /* tp_compare,    x>y         */
  1961.     (reprfunc)        0,            /* tp_repr,    `x`, print x */
  1962.  
  1963.     0,            /* as number */
  1964.     0,            /* as sequence */
  1965.     0,            /* as mapping */
  1966.  
  1967.     (hashfunc) 0,            /* tp_hash, dict(x) */
  1968.     (ternaryfunc) 0,            /* tp_call, x()     */
  1969.     (reprfunc) 0,            /* tp_str,  str(x)  */
  1970. };
  1971.  
  1972. /* Current items object - Implementation
  1973.  */
  1974. /*ARGSUSED*/
  1975.     static PyObject *
  1976. CurrentGetattr(PyObject *self, char *name)
  1977. {
  1978.     if (strcmp(name, "buffer") == 0)
  1979.     return (PyObject *)BufferNew(curbuf);
  1980.     else if (strcmp(name, "window") == 0)
  1981.     return (PyObject *)WindowNew(curwin);
  1982.     else if (strcmp(name, "line") == 0)
  1983.     return GetBufferLine(curbuf, (int)curwin->w_cursor.lnum);
  1984.     else if (strcmp(name, "range") == 0)
  1985.     return RangeNew(curbuf, RangeStart, RangeEnd);
  1986.     else if (strcmp(name,"__members__") == 0)
  1987.     return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
  1988.     else
  1989.     {
  1990.     PyErr_SetString(PyExc_AttributeError, name);
  1991.     return NULL;
  1992.     }
  1993. }
  1994.  
  1995. /*ARGSUSED*/
  1996.     static int
  1997. CurrentSetattr(PyObject *self, char *name, PyObject *value)
  1998. {
  1999.     if (strcmp(name, "line") == 0)
  2000.     {
  2001.     if (SetBufferLine(curbuf, (int)curwin->w_cursor.lnum, value, NULL) == FAIL)
  2002.         return -1;
  2003.  
  2004.     return 0;
  2005.     }
  2006.     else
  2007.     {
  2008.     PyErr_SetString(PyExc_AttributeError, name);
  2009.     return -1;
  2010.     }
  2011. }
  2012.  
  2013. /* External interface
  2014.  */
  2015.  
  2016.     void
  2017. python_buffer_free(buf_T *buf)
  2018. {
  2019.     if (buf->python_ref)
  2020.     {
  2021.     BufferObject *bp = buf->python_ref;
  2022.     bp->buf = INVALID_BUFFER_VALUE;
  2023.     buf->python_ref = NULL;
  2024.     }
  2025. }
  2026.  
  2027. #if defined(FEAT_WINDOWS) || defined(PROTO)
  2028.     void
  2029. python_window_free(win_T *win)
  2030. {
  2031.     if (win->python_ref)
  2032.     {
  2033.     WindowObject *wp = win->python_ref;
  2034.     wp->win = INVALID_WINDOW_VALUE;
  2035.     win->python_ref = NULL;
  2036.     }
  2037. }
  2038. #endif
  2039.  
  2040. static BufListObject TheBufferList =
  2041. {
  2042.     PyObject_HEAD_INIT(&BufListType)
  2043. };
  2044.  
  2045. static WinListObject TheWindowList =
  2046. {
  2047.     PyObject_HEAD_INIT(&WinListType)
  2048. };
  2049.  
  2050. static CurrentObject TheCurrent =
  2051. {
  2052.     PyObject_HEAD_INIT(&CurrentType)
  2053. };
  2054.  
  2055.     static int
  2056. PythonMod_Init(void)
  2057. {
  2058.     PyObject *mod;
  2059.     PyObject *dict;
  2060.  
  2061.     /* Fixups... */
  2062.     BufferType.ob_type = &PyType_Type;
  2063.     RangeType.ob_type = &PyType_Type;
  2064.     WindowType.ob_type = &PyType_Type;
  2065.     BufListType.ob_type = &PyType_Type;
  2066.     WinListType.ob_type = &PyType_Type;
  2067.     CurrentType.ob_type = &PyType_Type;
  2068.  
  2069.     mod = Py_InitModule("vim", VimMethods);
  2070.     dict = PyModule_GetDict(mod);
  2071.  
  2072.     VimError = Py_BuildValue("s", "vim.error");
  2073.  
  2074.     PyDict_SetItemString(dict, "error", VimError);
  2075.     PyDict_SetItemString(dict, "buffers", (PyObject *)(&TheBufferList));
  2076.     PyDict_SetItemString(dict, "current", (PyObject *)(&TheCurrent));
  2077.     PyDict_SetItemString(dict, "windows", (PyObject *)(&TheWindowList));
  2078.  
  2079.     if (PyErr_Occurred())
  2080.     return -1;
  2081.  
  2082.     return 0;
  2083. }
  2084.  
  2085. /*************************************************************************
  2086.  * 4. Utility functions for handling the interface between Vim and Python.
  2087.  */
  2088.  
  2089. /* Get a line from the specified buffer. The line number is
  2090.  * in Vim format (1-based). The line is returned as a Python
  2091.  * string object.
  2092.  */
  2093.     static PyObject *
  2094. GetBufferLine(buf_T *buf, int n)
  2095. {
  2096.     return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
  2097. }
  2098.  
  2099. /* Get a list of lines from the specified buffer. The line numbers
  2100.  * are in Vim format (1-based). The range is from lo up to, but not
  2101.  * including, hi. The list is returned as a Python list of string objects.
  2102.  */
  2103.     static PyObject *
  2104. GetBufferLineList(buf_T *buf, int lo, int hi)
  2105. {
  2106.     int i;
  2107.     int n = hi - lo;
  2108.     PyObject *list = PyList_New(n);
  2109.  
  2110.     if (list == NULL)
  2111.     return NULL;
  2112.  
  2113.     for (i = 0; i < n; ++i)
  2114.     {
  2115.     PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
  2116.  
  2117.     /* Error check - was the Python string creation OK? */
  2118.     if (str == NULL)
  2119.     {
  2120.         Py_DECREF(list);
  2121.         return NULL;
  2122.     }
  2123.  
  2124.     /* Set the list item */
  2125.     if (PyList_SetItem(list, i, str))
  2126.     {
  2127.         Py_DECREF(str);
  2128.         Py_DECREF(list);
  2129.         return NULL;
  2130.     }
  2131.     }
  2132.  
  2133.     /* The ownership of the Python list is passed to the caller (ie,
  2134.      * the caller should Py_DECREF() the object when it is finished
  2135.      * with it).
  2136.      */
  2137.  
  2138.     return list;
  2139. }
  2140.  
  2141. /*
  2142.  * Check if deleting lines made the cursor position invalid.
  2143.  * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
  2144.  * deleted).
  2145.  */
  2146.     static void
  2147. py_fix_cursor(int lo, int hi, int extra)
  2148. {
  2149.     if (curwin->w_cursor.lnum >= lo)
  2150.     {
  2151.     /* Adjust the cursor position if it's in/after the changed
  2152.      * lines. */
  2153.     if (curwin->w_cursor.lnum >= hi)
  2154.     {
  2155.         curwin->w_cursor.lnum += extra;
  2156.         check_cursor_col();
  2157.     }
  2158.     else if (extra < 0)
  2159.     {
  2160.         curwin->w_cursor.lnum = lo;
  2161.         check_cursor();
  2162.     }
  2163.     changed_cline_bef_curs();
  2164.     }
  2165.     invalidate_botline();
  2166. }
  2167.  
  2168. /* Replace a line in the specified buffer. The line number is
  2169.  * in Vim format (1-based). The replacement line is given as
  2170.  * a Python string object. The object is checked for validity
  2171.  * and correct format. Errors are returned as a value of FAIL.
  2172.  * The return value is OK on success.
  2173.  * If OK is returned and len_change is not NULL, *len_change
  2174.  * is set to the change in the buffer length.
  2175.  */
  2176.     static int
  2177. SetBufferLine(buf_T *buf, int n, PyObject *line, int *len_change)
  2178. {
  2179.     /* First of all, we check the thpe of the supplied Python object.
  2180.      * There are three cases:
  2181.      *      1. NULL, or None - this is a deletion.
  2182.      *      2. A string       - this is a replacement.
  2183.      *      3. Anything else - this is an error.
  2184.      */
  2185.     if (line == Py_None || line == NULL)
  2186.     {
  2187.     buf_T *savebuf = curbuf;
  2188.  
  2189.     PyErr_Clear();
  2190.     curbuf = buf;
  2191.  
  2192.     if (u_savedel((linenr_T)n, 1L) == FAIL)
  2193.         PyErr_SetVim(_("cannot save undo information"));
  2194.     else if (ml_delete((linenr_T)n, FALSE) == FAIL)
  2195.         PyErr_SetVim(_("cannot delete line"));
  2196.     else
  2197.     {
  2198.         deleted_lines_mark((linenr_T)n, 1L);
  2199.         if (buf == curwin->w_buffer)
  2200.         py_fix_cursor(n, n + 1, -1);
  2201.     }
  2202.  
  2203.     curbuf = savebuf;
  2204.  
  2205.     if (PyErr_Occurred() || VimErrorCheck())
  2206.         return FAIL;
  2207.  
  2208.     if (len_change)
  2209.         *len_change = -1;
  2210.  
  2211.     return OK;
  2212.     }
  2213.     else if (PyString_Check(line))
  2214.     {
  2215.     char *save = StringToLine(line);
  2216.     buf_T *savebuf = curbuf;
  2217.  
  2218.     if (save == NULL)
  2219.         return FAIL;
  2220.  
  2221.     /* We do not need to free save, as we pass responsibility for
  2222.      * it to vim, via the final parameter of ml_replace().
  2223.      */
  2224.     PyErr_Clear();
  2225.     curbuf = buf;
  2226.  
  2227.     if (u_savesub((linenr_T)n) == FAIL)
  2228.         PyErr_SetVim(_("cannot save undo information"));
  2229.     else if (ml_replace((linenr_T)n, (char_u *)save, TRUE) == FAIL)
  2230.         PyErr_SetVim(_("cannot replace line"));
  2231.     else
  2232.         changed_bytes((linenr_T)n, 0);
  2233.  
  2234.     curbuf = savebuf;
  2235.  
  2236.     if (PyErr_Occurred() || VimErrorCheck())
  2237.         return FAIL;
  2238.  
  2239.     if (len_change)
  2240.         *len_change = 0;
  2241.  
  2242.     return OK;
  2243.     }
  2244.     else
  2245.     {
  2246.     PyErr_BadArgument();
  2247.     return FAIL;
  2248.     }
  2249. }
  2250.  
  2251. /* Replace a range of lines in the specified buffer. The line numbers are in
  2252.  * Vim format (1-based). The range is from lo up to, but not including, hi.
  2253.  * The replacement lines are given as a Python list of string objects. The
  2254.  * list is checked for validity and correct format. Errors are returned as a
  2255.  * value of FAIL.  The return value is OK on success.
  2256.  * If OK is returned and len_change is not NULL, *len_change
  2257.  * is set to the change in the buffer length.
  2258.  */
  2259.     static int
  2260. SetBufferLineList(buf_T *buf, int lo, int hi, PyObject *list, int *len_change)
  2261. {
  2262.     /* First of all, we check the thpe of the supplied Python object.
  2263.      * There are three cases:
  2264.      *      1. NULL, or None - this is a deletion.
  2265.      *      2. A list       - this is a replacement.
  2266.      *      3. Anything else - this is an error.
  2267.      */
  2268.     if (list == Py_None || list == NULL)
  2269.     {
  2270.     int    i;
  2271.     int    n = hi - lo;
  2272.     buf_T    *savebuf = curbuf;
  2273.  
  2274.     PyErr_Clear();
  2275.     curbuf = buf;
  2276.  
  2277.     if (u_savedel((linenr_T)lo, (long)n) == FAIL)
  2278.         PyErr_SetVim(_("cannot save undo information"));
  2279.     else
  2280.     {
  2281.         for (i = 0; i < n; ++i)
  2282.         {
  2283.         if (ml_delete((linenr_T)lo, FALSE) == FAIL)
  2284.         {
  2285.             PyErr_SetVim(_("cannot delete line"));
  2286.             break;
  2287.         }
  2288.         }
  2289.         deleted_lines_mark((linenr_T)lo, (long)i);
  2290.  
  2291.         if (buf == curwin->w_buffer)
  2292.         py_fix_cursor(lo, hi, -n);
  2293.     }
  2294.  
  2295.     curbuf = savebuf;
  2296.  
  2297.     if (PyErr_Occurred() || VimErrorCheck())
  2298.         return FAIL;
  2299.  
  2300.     if (len_change)
  2301.         *len_change = -n;
  2302.  
  2303.     return OK;
  2304.     }
  2305.     else if (PyList_Check(list))
  2306.     {
  2307.     int    i;
  2308.     int    new_len = PyList_Size(list);
  2309.     int    old_len = hi - lo;
  2310.     int    extra = 0;    /* lines added to text, can be negative */
  2311.     char    **array;
  2312.     buf_T    *savebuf;
  2313.  
  2314.     if (new_len == 0)    /* avoid allocating zero bytes */
  2315.         array = NULL;
  2316.     else
  2317.     {
  2318.         array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
  2319.         if (array == NULL)
  2320.         {
  2321.         PyErr_NoMemory();
  2322.         return FAIL;
  2323.         }
  2324.     }
  2325.  
  2326.     for (i = 0; i < new_len; ++i)
  2327.     {
  2328.         PyObject *line = PyList_GetItem(list, i);
  2329.  
  2330.         array[i] = StringToLine(line);
  2331.         if (array[i] == NULL)
  2332.         {
  2333.         while (i)
  2334.             vim_free(array[--i]);
  2335.         vim_free(array);
  2336.         return FAIL;
  2337.         }
  2338.     }
  2339.  
  2340.     savebuf = curbuf;
  2341.  
  2342.     PyErr_Clear();
  2343.     curbuf = buf;
  2344.  
  2345.     if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
  2346.         PyErr_SetVim(_("cannot save undo information"));
  2347.  
  2348.     /* If the size of the range is reducing (ie, new_len < old_len) we
  2349.      * need to delete some old_len. We do this at the start, by
  2350.      * repeatedly deleting line "lo".
  2351.      */
  2352.     if (!PyErr_Occurred())
  2353.     {
  2354.         for (i = 0; i < old_len - new_len; ++i)
  2355.         if (ml_delete((linenr_T)lo, FALSE) == FAIL)
  2356.         {
  2357.             PyErr_SetVim(_("cannot delete line"));
  2358.             break;
  2359.         }
  2360.         extra -= i;
  2361.     }
  2362.  
  2363.     /* For as long as possible, replace the existing old_len with the
  2364.      * new old_len. This is a more efficient operation, as it requires
  2365.      * less memory allocation and freeing.
  2366.      */
  2367.     if (!PyErr_Occurred())
  2368.     {
  2369.         for (i = 0; i < old_len && i < new_len; ++i)
  2370.         if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], TRUE)
  2371.                                       == FAIL)
  2372.         {
  2373.             PyErr_SetVim(_("cannot replace line"));
  2374.             break;
  2375.         }
  2376.     }
  2377.  
  2378.     /* Now we may need to insert the remaining new old_len. If we do, we
  2379.      * must free the strings as we finish with them (we can't pass the
  2380.      * responsibility to vim in this case).
  2381.      */
  2382.     if (!PyErr_Occurred())
  2383.     {
  2384.         while (i < new_len)
  2385.         {
  2386.         if (ml_append((linenr_T)(lo + i - 1),
  2387.                     (char_u *)array[i], 0, FALSE) == FAIL)
  2388.         {
  2389.             PyErr_SetVim(_("cannot insert line"));
  2390.             break;
  2391.         }
  2392.         vim_free(array[i]);
  2393.         ++i;
  2394.         ++extra;
  2395.         }
  2396.     }
  2397.  
  2398.     /* Free any left-over old_len, as a result of an error */
  2399.     while (i < new_len)
  2400.     {
  2401.         vim_free(array[i]);
  2402.         ++i;
  2403.     }
  2404.  
  2405.     /* Free the array of old_len. All of its contents have now
  2406.      * been dealt with (either freed, or the responsibility passed
  2407.      * to vim.
  2408.      */
  2409.     vim_free(array);
  2410.  
  2411.     /* Adjust marks. Invalidate any which lie in the
  2412.      * changed range, and move any in the remainder of the buffer.
  2413.      */
  2414.     mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
  2415.                           (long)MAXLNUM, (long)extra);
  2416.     changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
  2417.  
  2418.     if (buf == curwin->w_buffer)
  2419.         py_fix_cursor(lo, hi, extra);
  2420.  
  2421.     curbuf = savebuf;
  2422.  
  2423.     if (PyErr_Occurred() || VimErrorCheck())
  2424.         return FAIL;
  2425.  
  2426.     if (len_change)
  2427.         *len_change = new_len - old_len;
  2428.  
  2429.     return OK;
  2430.     }
  2431.     else
  2432.     {
  2433.     PyErr_BadArgument();
  2434.     return FAIL;
  2435.     }
  2436. }
  2437.  
  2438. /* Insert a number of lines into the specified buffer after the specifed line.
  2439.  * The line number is in Vim format (1-based). The lines to be inserted are
  2440.  * given as a Python list of string objects or as a single string. The lines
  2441.  * to be added are checked for validity and correct format. Errors are
  2442.  * returned as a value of FAIL.  The return value is OK on success.
  2443.  * If OK is returned and len_change is not NULL, *len_change
  2444.  * is set to the change in the buffer length.
  2445.  */
  2446.     static int
  2447. InsertBufferLines(buf_T *buf, int n, PyObject *lines, int *len_change)
  2448. {
  2449.     /* First of all, we check the type of the supplied Python object.
  2450.      * It must be a string or a list, or the call is in error.
  2451.      */
  2452.     if (PyString_Check(lines))
  2453.     {
  2454.     char    *str = StringToLine(lines);
  2455.     buf_T    *savebuf;
  2456.  
  2457.     if (str == NULL)
  2458.         return FAIL;
  2459.  
  2460.     savebuf = curbuf;
  2461.  
  2462.     PyErr_Clear();
  2463.     curbuf = buf;
  2464.  
  2465.     if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
  2466.         PyErr_SetVim(_("cannot save undo information"));
  2467.     else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
  2468.         PyErr_SetVim(_("cannot insert line"));
  2469.     else
  2470.         appended_lines_mark((linenr_T)n, 1L);
  2471.  
  2472.     vim_free(str);
  2473.     curbuf = savebuf;
  2474.     update_screen(VALID);
  2475.  
  2476.     if (PyErr_Occurred() || VimErrorCheck())
  2477.         return FAIL;
  2478.  
  2479.     if (len_change)
  2480.         *len_change = 1;
  2481.  
  2482.     return OK;
  2483.     }
  2484.     else if (PyList_Check(lines))
  2485.     {
  2486.     int    i;
  2487.     int    size = PyList_Size(lines);
  2488.     char    **array;
  2489.     buf_T    *savebuf;
  2490.  
  2491.     array = (char **)alloc((unsigned)(size * sizeof(char *)));
  2492.     if (array == NULL)
  2493.     {
  2494.         PyErr_NoMemory();
  2495.         return FAIL;
  2496.     }
  2497.  
  2498.     for (i = 0; i < size; ++i)
  2499.     {
  2500.         PyObject *line = PyList_GetItem(lines, i);
  2501.         array[i] = StringToLine(line);
  2502.  
  2503.         if (array[i] == NULL)
  2504.         {
  2505.         while (i)
  2506.             vim_free(array[--i]);
  2507.         vim_free(array);
  2508.         return FAIL;
  2509.         }
  2510.     }
  2511.  
  2512.     savebuf = curbuf;
  2513.  
  2514.     PyErr_Clear();
  2515.     curbuf = buf;
  2516.  
  2517.     if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
  2518.         PyErr_SetVim(_("cannot save undo information"));
  2519.     else
  2520.     {
  2521.         for (i = 0; i < size; ++i)
  2522.         {
  2523.         if (ml_append((linenr_T)(n + i),
  2524.                     (char_u *)array[i], 0, FALSE) == FAIL)
  2525.         {
  2526.             PyErr_SetVim(_("cannot insert line"));
  2527.  
  2528.             /* Free the rest of the lines */
  2529.             while (i < size)
  2530.             vim_free(array[i++]);
  2531.  
  2532.             break;
  2533.         }
  2534.         vim_free(array[i]);
  2535.         }
  2536.         if (i > 0)
  2537.         appended_lines_mark((linenr_T)n, (long)i);
  2538.     }
  2539.  
  2540.     /* Free the array of lines. All of its contents have now
  2541.      * been freed.
  2542.      */
  2543.     vim_free(array);
  2544.  
  2545.     curbuf = savebuf;
  2546.     update_screen(VALID);
  2547.  
  2548.     if (PyErr_Occurred() || VimErrorCheck())
  2549.         return FAIL;
  2550.  
  2551.     if (len_change)
  2552.         *len_change = size;
  2553.  
  2554.     return OK;
  2555.     }
  2556.     else
  2557.     {
  2558.     PyErr_BadArgument();
  2559.     return FAIL;
  2560.     }
  2561. }
  2562.  
  2563. /* Convert a Vim line into a Python string.
  2564.  * All internal newlines are replaced by null characters.
  2565.  *
  2566.  * On errors, the Python exception data is set, and NULL is returned.
  2567.  */
  2568.     static PyObject *
  2569. LineToString(const char *str)
  2570. {
  2571.     PyObject *result;
  2572.     int len = strlen(str);
  2573.     char *p;
  2574.  
  2575.     /* Allocate an Python string object, with uninitialised contents. We
  2576.      * must do it this way, so that we can modify the string in place
  2577.      * later. See the Python source, Objects/stringobject.c for details.
  2578.      */
  2579.     result = PyString_FromStringAndSize(NULL, len);
  2580.     if (result == NULL)
  2581.     return NULL;
  2582.  
  2583.     p = PyString_AsString(result);
  2584.  
  2585.     while (*str)
  2586.     {
  2587.     if (*str == '\n')
  2588.         *p = '\0';
  2589.     else
  2590.         *p = *str;
  2591.  
  2592.     ++p;
  2593.     ++str;
  2594.     }
  2595.  
  2596.     return result;
  2597. }
  2598.  
  2599. /* Convert a Python string into a Vim line.
  2600.  *
  2601.  * The result is in allocated memory. All internal nulls are replaced by
  2602.  * newline characters. It is an error for the string to contain newline
  2603.  * characters.
  2604.  *
  2605.  * On errors, the Python exception data is set, and NULL is returned.
  2606.  */
  2607.     static char *
  2608. StringToLine(PyObject *obj)
  2609. {
  2610.     const char *str;
  2611.     char *save;
  2612.     int len;
  2613.     int i;
  2614.  
  2615.     if (obj == NULL || !PyString_Check(obj))
  2616.     {
  2617.     PyErr_BadArgument();
  2618.     return NULL;
  2619.     }
  2620.  
  2621.     str = PyString_AsString(obj);
  2622.     len = PyString_Size(obj);
  2623.  
  2624.     /* Error checking: String must not contain newlines, as we
  2625.      * are replacing a single line, and we must replace it with
  2626.      * a single line.
  2627.      */
  2628.     if (memchr(str, '\n', len))
  2629.     {
  2630.     PyErr_SetVim(_("string cannot contain newlines"));
  2631.     return NULL;
  2632.     }
  2633.  
  2634.     /* Create a copy of the string, with internal nulls replaced by
  2635.      * newline characters, as is the vim convention.
  2636.      */
  2637.     save = (char *)alloc((unsigned)(len+1));
  2638.     if (save == NULL)
  2639.     {
  2640.     PyErr_NoMemory();
  2641.     return NULL;
  2642.     }
  2643.  
  2644.     for (i = 0; i < len; ++i)
  2645.     {
  2646.     if (str[i] == '\0')
  2647.         save[i] = '\n';
  2648.     else
  2649.         save[i] = str[i];
  2650.     }
  2651.  
  2652.     save[i] = '\0';
  2653.  
  2654.     return save;
  2655. }
  2656.  
  2657. /* Check to see whether a Vim error has been reported, or a keyboard
  2658.  * interrupt has been detected.
  2659.  */
  2660.     static int
  2661. VimErrorCheck(void)
  2662. {
  2663.     if (got_int)
  2664.     {
  2665.     PyErr_SetNone(PyExc_KeyboardInterrupt);
  2666.     return 1;
  2667.     }
  2668.     else if (did_emsg && !PyErr_Occurred())
  2669.     {
  2670.     PyErr_SetNone(VimError);
  2671.     return 1;
  2672.     }
  2673.  
  2674.     return 0;
  2675. }
  2676.  
  2677.  
  2678. /* Don't generate a prototype for the next function, it generates an error on
  2679.  * newer Python versions. */
  2680. #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
  2681.  
  2682.     char *
  2683. Py_GetProgramName(void)
  2684. {
  2685.     return "vim";
  2686. }
  2687. #endif /* Python 1.4 */
  2688.