xref: /vim-8.2.3635/src/if_python.c (revision 57e4ee4d)
1 /* vi:set ts=8 sts=4 sw=4 noet:
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 <limits.h>
23 
24 /* Python.h defines _POSIX_THREADS itself (if needed) */
25 #ifdef _POSIX_THREADS
26 # undef _POSIX_THREADS
27 #endif
28 
29 #if defined(_WIN32) && defined(HAVE_FCNTL_H)
30 # undef HAVE_FCNTL_H
31 #endif
32 
33 #ifdef _DEBUG
34 # undef _DEBUG
35 #endif
36 
37 #ifdef HAVE_STDARG_H
38 # undef HAVE_STDARG_H	/* Python's config.h defines it as well. */
39 #endif
40 #ifdef _POSIX_C_SOURCE
41 # undef _POSIX_C_SOURCE	/* pyconfig.h defines it as well. */
42 #endif
43 #ifdef _XOPEN_SOURCE
44 # undef _XOPEN_SOURCE	/* pyconfig.h defines it as well. */
45 #endif
46 
47 #include <Python.h>
48 #if defined(MACOS) && !defined(MACOS_X_UNIX)
49 # include "macglue.h"
50 # include <CodeFragments.h>
51 #endif
52 #undef main /* Defined in python.h - aargh */
53 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
54 
55 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
56 # define PY_SSIZE_T_CLEAN
57 #endif
58 
59 static void init_structs(void);
60 
61 #define PyBytes_FromString PyString_FromString
62 
63 /* No-op conversion functions, use with care! */
64 #define PyString_AsBytes(obj) (obj)
65 #define PyString_FreeBytes(obj)
66 
67 #if !defined(FEAT_PYTHON) && defined(PROTO)
68 /* Use this to be able to generate prototypes without python being used. */
69 # define PyObject Py_ssize_t
70 # define PyThreadState Py_ssize_t
71 # define PyTypeObject Py_ssize_t
72 struct PyMethodDef { Py_ssize_t a; };
73 # define PySequenceMethods Py_ssize_t
74 #endif
75 
76 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
77 # define PY_USE_CAPSULE
78 #endif
79 
80 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
81 # define PyInt Py_ssize_t
82 # define PyInquiry lenfunc
83 # define PyIntArgFunc ssizeargfunc
84 # define PyIntIntArgFunc ssizessizeargfunc
85 # define PyIntObjArgProc ssizeobjargproc
86 # define PyIntIntObjArgProc ssizessizeobjargproc
87 # define Py_ssize_t_fmt "n"
88 #else
89 # define PyInt int
90 # define PyInquiry inquiry
91 # define PyIntArgFunc intargfunc
92 # define PyIntIntArgFunc intintargfunc
93 # define PyIntObjArgProc intobjargproc
94 # define PyIntIntObjArgProc intintobjargproc
95 # define Py_ssize_t_fmt "i"
96 #endif
97 
98 /* Parser flags */
99 #define single_input	256
100 #define file_input	257
101 #define eval_input	258
102 
103 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
104   /* Python 2.3: can invoke ":python" recursively. */
105 # define PY_CAN_RECURSE
106 #endif
107 
108 # if defined(DYNAMIC_PYTHON) || defined(PROTO)
109 #  ifndef DYNAMIC_PYTHON
110 #   define HINSTANCE long_u		/* for generating prototypes */
111 #  endif
112 
113 # ifndef WIN3264
114 #  include <dlfcn.h>
115 #  define FARPROC void*
116 #  define HINSTANCE void*
117 #  if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
118 #   define load_dll(n) dlopen((n), RTLD_LAZY)
119 #  else
120 #   define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
121 #  endif
122 #  define close_dll dlclose
123 #  define symbol_from_dll dlsym
124 # else
125 #  define load_dll vimLoadLib
126 #  define close_dll FreeLibrary
127 #  define symbol_from_dll GetProcAddress
128 # endif
129 
130 /* This makes if_python.c compile without warnings against Python 2.5
131  * on Win32 and Win64. */
132 # undef PyRun_SimpleString
133 # undef PyRun_String
134 # undef PyArg_Parse
135 # undef PyArg_ParseTuple
136 # undef Py_BuildValue
137 # undef Py_InitModule4
138 # undef Py_InitModule4_64
139 # undef PyObject_CallMethod
140 
141 /*
142  * Wrapper defines
143  */
144 # define PyArg_Parse dll_PyArg_Parse
145 # define PyArg_ParseTuple dll_PyArg_ParseTuple
146 # define PyMem_Free dll_PyMem_Free
147 # define PyMem_Malloc dll_PyMem_Malloc
148 # define PyDict_SetItemString dll_PyDict_SetItemString
149 # define PyErr_BadArgument dll_PyErr_BadArgument
150 # define PyErr_Clear dll_PyErr_Clear
151 # define PyErr_NoMemory dll_PyErr_NoMemory
152 # define PyErr_Occurred dll_PyErr_Occurred
153 # define PyErr_SetNone dll_PyErr_SetNone
154 # define PyErr_SetString dll_PyErr_SetString
155 # define PyEval_InitThreads dll_PyEval_InitThreads
156 # define PyEval_RestoreThread dll_PyEval_RestoreThread
157 # define PyEval_SaveThread dll_PyEval_SaveThread
158 # ifdef PY_CAN_RECURSE
159 #  define PyGILState_Ensure dll_PyGILState_Ensure
160 #  define PyGILState_Release dll_PyGILState_Release
161 # endif
162 # define PyInt_AsLong dll_PyInt_AsLong
163 # define PyInt_FromLong dll_PyInt_FromLong
164 # define PyLong_AsLong dll_PyLong_AsLong
165 # define PyLong_FromLong dll_PyLong_FromLong
166 # define PyBool_Type (*dll_PyBool_Type)
167 # define PyInt_Type (*dll_PyInt_Type)
168 # define PyLong_Type (*dll_PyLong_Type)
169 # define PyList_GetItem dll_PyList_GetItem
170 # define PyList_Append dll_PyList_Append
171 # define PyList_New dll_PyList_New
172 # define PyList_SetItem dll_PyList_SetItem
173 # define PyList_Size dll_PyList_Size
174 # define PyList_Type (*dll_PyList_Type)
175 # define PySequence_Check dll_PySequence_Check
176 # define PySequence_Size dll_PySequence_Size
177 # define PySequence_GetItem dll_PySequence_GetItem
178 # define PyTuple_Size dll_PyTuple_Size
179 # define PyTuple_GetItem dll_PyTuple_GetItem
180 # define PyTuple_Type (*dll_PyTuple_Type)
181 # define PyImport_ImportModule dll_PyImport_ImportModule
182 # define PyDict_New dll_PyDict_New
183 # define PyDict_GetItemString dll_PyDict_GetItemString
184 # define PyDict_Next dll_PyDict_Next
185 # ifdef PyMapping_Items
186 #  define PY_NO_MAPPING_ITEMS
187 # else
188 #  define PyMapping_Items dll_PyMapping_Items
189 # endif
190 # define PyObject_CallMethod dll_PyObject_CallMethod
191 # define PyMapping_Check dll_PyMapping_Check
192 # define PyIter_Next dll_PyIter_Next
193 # define PyModule_GetDict dll_PyModule_GetDict
194 # define PyRun_SimpleString dll_PyRun_SimpleString
195 # define PyRun_String dll_PyRun_String
196 # define PyString_AsString dll_PyString_AsString
197 # define PyString_AsStringAndSize dll_PyString_AsStringAndSize
198 # define PyString_FromString dll_PyString_FromString
199 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
200 # define PyString_Size dll_PyString_Size
201 # define PyString_Type (*dll_PyString_Type)
202 # define PyUnicode_Type (*dll_PyUnicode_Type)
203 # undef PyUnicode_AsEncodedString
204 # define PyUnicode_AsEncodedString py_PyUnicode_AsEncodedString
205 # define PyFloat_AsDouble dll_PyFloat_AsDouble
206 # define PyFloat_FromDouble dll_PyFloat_FromDouble
207 # define PyFloat_Type (*dll_PyFloat_Type)
208 # define PyImport_AddModule (*dll_PyImport_AddModule)
209 # define PySys_SetObject dll_PySys_SetObject
210 # define PySys_SetArgv dll_PySys_SetArgv
211 # define PyType_Type (*dll_PyType_Type)
212 # define PyType_Ready (*dll_PyType_Ready)
213 # define Py_BuildValue dll_Py_BuildValue
214 # define Py_FindMethod dll_Py_FindMethod
215 # define Py_InitModule4 dll_Py_InitModule4
216 # define Py_SetPythonHome dll_Py_SetPythonHome
217 # define Py_Initialize dll_Py_Initialize
218 # define Py_Finalize dll_Py_Finalize
219 # define Py_IsInitialized dll_Py_IsInitialized
220 # define _PyObject_New dll__PyObject_New
221 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
222 #  define _PyObject_NextNotImplemented (*dll__PyObject_NextNotImplemented)
223 # endif
224 # define _Py_NoneStruct (*dll__Py_NoneStruct)
225 # define _Py_ZeroStruct (*dll__Py_ZeroStruct)
226 # define _Py_TrueStruct (*dll__Py_TrueStruct)
227 # define PyObject_Init dll__PyObject_Init
228 # define PyObject_GetIter dll_PyObject_GetIter
229 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
230 #  define PyType_IsSubtype dll_PyType_IsSubtype
231 # endif
232 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
233 #  define PyObject_Malloc dll_PyObject_Malloc
234 #  define PyObject_Free dll_PyObject_Free
235 # endif
236 # ifdef PY_USE_CAPSULE
237 #  define PyCapsule_New dll_PyCapsule_New
238 #  define PyCapsule_GetPointer dll_PyCapsule_GetPointer
239 # else
240 #  define PyCObject_FromVoidPtr dll_PyCObject_FromVoidPtr
241 #  define PyCObject_AsVoidPtr dll_PyCObject_AsVoidPtr
242 # endif
243 
244 /*
245  * Pointers for dynamic link
246  */
247 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
248 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
249 static int(*dll_PyMem_Free)(void *);
250 static void* (*dll_PyMem_Malloc)(size_t);
251 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
252 static int(*dll_PyErr_BadArgument)(void);
253 static void(*dll_PyErr_Clear)(void);
254 static PyObject*(*dll_PyErr_NoMemory)(void);
255 static PyObject*(*dll_PyErr_Occurred)(void);
256 static void(*dll_PyErr_SetNone)(PyObject *);
257 static void(*dll_PyErr_SetString)(PyObject *, const char *);
258 static void(*dll_PyEval_InitThreads)(void);
259 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
260 static PyThreadState*(*dll_PyEval_SaveThread)(void);
261 # ifdef PY_CAN_RECURSE
262 static PyGILState_STATE	(*dll_PyGILState_Ensure)(void);
263 static void (*dll_PyGILState_Release)(PyGILState_STATE);
264 # endif
265 static long(*dll_PyInt_AsLong)(PyObject *);
266 static PyObject*(*dll_PyInt_FromLong)(long);
267 static long(*dll_PyLong_AsLong)(PyObject *);
268 static PyObject*(*dll_PyLong_FromLong)(long);
269 static PyTypeObject* dll_PyBool_Type;
270 static PyTypeObject* dll_PyInt_Type;
271 static PyTypeObject* dll_PyLong_Type;
272 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
273 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
274 static PyObject*(*dll_PyList_New)(PyInt size);
275 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
276 static PyInt(*dll_PyList_Size)(PyObject *);
277 static PyTypeObject* dll_PyList_Type;
278 static int (*dll_PySequence_Check)(PyObject *);
279 static PyInt(*dll_PySequence_Size)(PyObject *);
280 static PyObject*(*dll_PySequence_GetItem)(PyObject *, PyInt);
281 static PyInt(*dll_PyTuple_Size)(PyObject *);
282 static PyObject*(*dll_PyTuple_GetItem)(PyObject *, PyInt);
283 static PyTypeObject* dll_PyTuple_Type;
284 static PyObject*(*dll_PyImport_ImportModule)(const char *);
285 static PyObject*(*dll_PyDict_New)(void);
286 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
287 static int (*dll_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
288 # ifndef PY_NO_MAPPING_ITEMS
289 static PyObject* (*dll_PyMapping_Items)(PyObject *);
290 # endif
291 static PyObject* (*dll_PyObject_CallMethod)(PyObject *, char *, PyObject *);
292 static int (*dll_PyMapping_Check)(PyObject *);
293 static PyObject* (*dll_PyIter_Next)(PyObject *);
294 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
295 static int(*dll_PyRun_SimpleString)(char *);
296 static PyObject *(*dll_PyRun_String)(char *, int, PyObject *, PyObject *);
297 static char*(*dll_PyString_AsString)(PyObject *);
298 static int(*dll_PyString_AsStringAndSize)(PyObject *, char **, int *);
299 static PyObject*(*dll_PyString_FromString)(const char *);
300 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
301 static PyInt(*dll_PyString_Size)(PyObject *);
302 static PyTypeObject* dll_PyString_Type;
303 static PyTypeObject* dll_PyUnicode_Type;
304 static PyObject *(*py_PyUnicode_AsEncodedString)(PyObject *, char *, char *);
305 static double(*dll_PyFloat_AsDouble)(PyObject *);
306 static PyObject*(*dll_PyFloat_FromDouble)(double);
307 static PyTypeObject* dll_PyFloat_Type;
308 static int(*dll_PySys_SetObject)(char *, PyObject *);
309 static int(*dll_PySys_SetArgv)(int, char **);
310 static PyTypeObject* dll_PyType_Type;
311 static int (*dll_PyType_Ready)(PyTypeObject *type);
312 static PyObject*(*dll_Py_BuildValue)(char *, ...);
313 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
314 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
315 static PyObject*(*dll_PyImport_AddModule)(char *);
316 static void(*dll_Py_SetPythonHome)(char *home);
317 static void(*dll_Py_Initialize)(void);
318 static void(*dll_Py_Finalize)(void);
319 static int(*dll_Py_IsInitialized)(void);
320 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
321 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
322 static PyObject* (*dll_PyObject_GetIter)(PyObject *);
323 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
324 static iternextfunc dll__PyObject_NextNotImplemented;
325 # endif
326 static PyObject* dll__Py_NoneStruct;
327 static PyObject* _Py_ZeroStruct;
328 static PyObject* dll__Py_TrueStruct;
329 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
330 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
331 # endif
332 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
333 static void* (*dll_PyObject_Malloc)(size_t);
334 static void (*dll_PyObject_Free)(void*);
335 # endif
336 # ifdef PY_USE_CAPSULE
337 static PyObject* (*dll_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
338 static void* (*dll_PyCapsule_GetPointer)(PyObject *, char *);
339 # else
340 static PyObject* (*dll_PyCObject_FromVoidPtr)(void *cobj, void (*destr)(void *));
341 static void* (*dll_PyCObject_AsVoidPtr)(PyObject *);
342 # endif
343 
344 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
345 
346 /* Imported exception objects */
347 static PyObject *imp_PyExc_AttributeError;
348 static PyObject *imp_PyExc_IndexError;
349 static PyObject *imp_PyExc_KeyboardInterrupt;
350 static PyObject *imp_PyExc_TypeError;
351 static PyObject *imp_PyExc_ValueError;
352 
353 # define PyExc_AttributeError imp_PyExc_AttributeError
354 # define PyExc_IndexError imp_PyExc_IndexError
355 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
356 # define PyExc_TypeError imp_PyExc_TypeError
357 # define PyExc_ValueError imp_PyExc_ValueError
358 
359 /*
360  * Table of name to function pointer of python.
361  */
362 # define PYTHON_PROC FARPROC
363 static struct
364 {
365     char *name;
366     PYTHON_PROC *ptr;
367 } python_funcname_table[] =
368 {
369 #ifndef PY_SSIZE_T_CLEAN
370     {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
371     {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
372     {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
373 #else
374     {"_PyArg_Parse_SizeT", (PYTHON_PROC*)&dll_PyArg_Parse},
375     {"_PyArg_ParseTuple_SizeT", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
376     {"_Py_BuildValue_SizeT", (PYTHON_PROC*)&dll_Py_BuildValue},
377 #endif
378     {"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free},
379     {"PyMem_Malloc", (PYTHON_PROC*)&dll_PyMem_Malloc},
380     {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
381     {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
382     {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
383     {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
384     {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
385     {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
386     {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
387     {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
388     {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
389     {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
390 # ifdef PY_CAN_RECURSE
391     {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
392     {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
393 # endif
394     {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
395     {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
396     {"PyLong_AsLong", (PYTHON_PROC*)&dll_PyLong_AsLong},
397     {"PyLong_FromLong", (PYTHON_PROC*)&dll_PyLong_FromLong},
398     {"PyBool_Type", (PYTHON_PROC*)&dll_PyBool_Type},
399     {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
400     {"PyLong_Type", (PYTHON_PROC*)&dll_PyLong_Type},
401     {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
402     {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
403     {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
404     {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
405     {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
406     {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
407     {"PySequence_GetItem", (PYTHON_PROC*)&dll_PySequence_GetItem},
408     {"PySequence_Size", (PYTHON_PROC*)&dll_PySequence_Size},
409     {"PySequence_Check", (PYTHON_PROC*)&dll_PySequence_Check},
410     {"PyTuple_GetItem", (PYTHON_PROC*)&dll_PyTuple_GetItem},
411     {"PyTuple_Size", (PYTHON_PROC*)&dll_PyTuple_Size},
412     {"PyTuple_Type", (PYTHON_PROC*)&dll_PyTuple_Type},
413     {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
414     {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
415     {"PyDict_Next", (PYTHON_PROC*)&dll_PyDict_Next},
416     {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
417 # ifndef PY_NO_MAPPING_ITEMS
418     {"PyMapping_Items", (PYTHON_PROC*)&dll_PyMapping_Items},
419 # endif
420     {"PyObject_CallMethod", (PYTHON_PROC*)&dll_PyObject_CallMethod},
421     {"PyMapping_Check", (PYTHON_PROC*)&dll_PyMapping_Check},
422     {"PyIter_Next", (PYTHON_PROC*)&dll_PyIter_Next},
423     {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
424     {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
425     {"PyRun_String", (PYTHON_PROC*)&dll_PyRun_String},
426     {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
427     {"PyString_AsStringAndSize", (PYTHON_PROC*)&dll_PyString_AsStringAndSize},
428     {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
429     {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
430     {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
431     {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
432     {"PyUnicode_Type", (PYTHON_PROC*)&dll_PyUnicode_Type},
433     {"PyFloat_Type", (PYTHON_PROC*)&dll_PyFloat_Type},
434     {"PyFloat_AsDouble", (PYTHON_PROC*)&dll_PyFloat_AsDouble},
435     {"PyFloat_FromDouble", (PYTHON_PROC*)&dll_PyFloat_FromDouble},
436     {"PyImport_AddModule", (PYTHON_PROC*)&dll_PyImport_AddModule},
437     {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
438     {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
439     {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
440     {"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready},
441     {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
442 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000 \
443 	&& SIZEOF_SIZE_T != SIZEOF_INT
444     {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
445 # else
446     {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
447 # endif
448     {"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome},
449     {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
450     {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
451     {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
452     {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
453     {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
454     {"PyObject_GetIter", (PYTHON_PROC*)&dll_PyObject_GetIter},
455 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
456     {"_PyObject_NextNotImplemented", (PYTHON_PROC*)&dll__PyObject_NextNotImplemented},
457 # endif
458     {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
459     {"_Py_ZeroStruct", (PYTHON_PROC*)&dll__Py_ZeroStruct},
460     {"_Py_TrueStruct", (PYTHON_PROC*)&dll__Py_TrueStruct},
461 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
462     {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
463 # endif
464 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
465     {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
466     {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
467 # endif
468 # ifdef PY_USE_CAPSULE
469     {"PyCapsule_New", (PYTHON_PROC*)&dll_PyCapsule_New},
470     {"PyCapsule_GetPointer", (PYTHON_PROC*)&dll_PyCapsule_GetPointer},
471 # else
472     {"PyCObject_FromVoidPtr", (PYTHON_PROC*)&dll_PyCObject_FromVoidPtr},
473     {"PyCObject_AsVoidPtr", (PYTHON_PROC*)&dll_PyCObject_AsVoidPtr},
474 # endif
475     {"", NULL},
476 };
477 
478 /*
479  * Free python.dll
480  */
481     static void
482 end_dynamic_python(void)
483 {
484     if (hinstPython)
485     {
486 	close_dll(hinstPython);
487 	hinstPython = 0;
488     }
489 }
490 
491 /*
492  * Load library and get all pointers.
493  * Parameter 'libname' provides name of DLL.
494  * Return OK or FAIL.
495  */
496     static int
497 python_runtime_link_init(char *libname, int verbose)
498 {
499     int i;
500     void *ucs_as_encoded_string;
501 
502 #if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
503     /* Can't have Python and Python3 loaded at the same time.
504      * It cause a crash, because RTLD_GLOBAL is needed for
505      * standard C extension libraries of one or both python versions. */
506     if (python3_loaded())
507     {
508 	if (verbose)
509 	    EMSG(_("E836: This Vim cannot execute :python after using :py3"));
510 	return FAIL;
511     }
512 #endif
513 
514     if (hinstPython)
515 	return OK;
516     hinstPython = load_dll(libname);
517     if (!hinstPython)
518     {
519 	if (verbose)
520 	    EMSG2(_(e_loadlib), libname);
521 	return FAIL;
522     }
523 
524     for (i = 0; python_funcname_table[i].ptr; ++i)
525     {
526 	if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
527 			python_funcname_table[i].name)) == NULL)
528 	{
529 	    close_dll(hinstPython);
530 	    hinstPython = 0;
531 	    if (verbose)
532 		EMSG2(_(e_loadfunc), python_funcname_table[i].name);
533 	    return FAIL;
534 	}
535     }
536 
537     /* Load unicode functions separately as only the ucs2 or the ucs4 functions
538      * will be present in the library. */
539     ucs_as_encoded_string = symbol_from_dll(hinstPython,
540 					     "PyUnicodeUCS2_AsEncodedString");
541     if (ucs_as_encoded_string == NULL)
542 	ucs_as_encoded_string = symbol_from_dll(hinstPython,
543 					     "PyUnicodeUCS4_AsEncodedString");
544     if (ucs_as_encoded_string != NULL)
545 	py_PyUnicode_AsEncodedString = ucs_as_encoded_string;
546     else
547     {
548 	close_dll(hinstPython);
549 	hinstPython = 0;
550 	if (verbose)
551 	    EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*");
552 	return FAIL;
553     }
554 
555     return OK;
556 }
557 
558 /*
559  * If python is enabled (there is installed python on Windows system) return
560  * TRUE, else FALSE.
561  */
562     int
563 python_enabled(int verbose)
564 {
565     return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
566 }
567 
568 /*
569  * Load the standard Python exceptions - don't import the symbols from the
570  * DLL, as this can cause errors (importing data symbols is not reliable).
571  */
572     static void
573 get_exceptions(void)
574 {
575     PyObject *exmod = PyImport_ImportModule("exceptions");
576     PyObject *exdict = PyModule_GetDict(exmod);
577     imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
578     imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
579     imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
580     imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
581     imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
582     Py_XINCREF(imp_PyExc_AttributeError);
583     Py_XINCREF(imp_PyExc_IndexError);
584     Py_XINCREF(imp_PyExc_KeyboardInterrupt);
585     Py_XINCREF(imp_PyExc_TypeError);
586     Py_XINCREF(imp_PyExc_ValueError);
587     Py_XDECREF(exmod);
588 }
589 #endif /* DYNAMIC_PYTHON */
590 
591 static PyObject *BufferNew (buf_T *);
592 static PyObject *WindowNew(win_T *);
593 static PyObject *DictionaryNew(dict_T *);
594 static PyObject *LineToString(const char *);
595 
596 static PyTypeObject RangeType;
597 
598 static int initialised = 0;
599 #define PYINITIALISED initialised
600 
601 #define DICTKEY_GET(err) \
602     if (!PyString_Check(keyObject)) \
603     { \
604 	PyErr_SetString(PyExc_TypeError, _("only string keys are allowed")); \
605 	return err; \
606     } \
607     if (PyString_AsStringAndSize(keyObject, (char **) &key, NULL) == -1) \
608 	return err;
609 
610 #define DICTKEY_UNREF
611 #define DICTKEY_DECL
612 
613 /*
614  * Include the code shared with if_python3.c
615  */
616 #include "if_py_both.h"
617 
618 
619 /******************************************************
620  * Internal function prototypes.
621  */
622 
623 static PyInt RangeStart;
624 static PyInt RangeEnd;
625 
626 static PyObject *globals;
627 
628 static void PythonIO_Flush(void);
629 static int PythonIO_Init(void);
630 static int PythonMod_Init(void);
631 
632 /* Utility functions for the vim/python interface
633  * ----------------------------------------------
634  */
635 
636 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
637 
638 
639 /******************************************************
640  * 1. Python interpreter main program.
641  */
642 
643 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
644 typedef PyObject PyThreadState;
645 #endif
646 
647 #ifdef PY_CAN_RECURSE
648 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
649 #else
650 static PyThreadState *saved_python_thread = NULL;
651 #endif
652 
653 /*
654  * Suspend a thread of the Python interpreter, other threads are allowed to
655  * run.
656  */
657     static void
658 Python_SaveThread(void)
659 {
660 #ifdef PY_CAN_RECURSE
661     PyGILState_Release(pygilstate);
662 #else
663     saved_python_thread = PyEval_SaveThread();
664 #endif
665 }
666 
667 /*
668  * Restore a thread of the Python interpreter, waits for other threads to
669  * block.
670  */
671     static void
672 Python_RestoreThread(void)
673 {
674 #ifdef PY_CAN_RECURSE
675     pygilstate = PyGILState_Ensure();
676 #else
677     PyEval_RestoreThread(saved_python_thread);
678     saved_python_thread = NULL;
679 #endif
680 }
681 
682     void
683 python_end()
684 {
685     static int recurse = 0;
686 
687     /* If a crash occurs while doing this, don't try again. */
688     if (recurse != 0)
689 	return;
690 
691     ++recurse;
692 
693 #ifdef DYNAMIC_PYTHON
694     if (hinstPython && Py_IsInitialized())
695     {
696 	Python_RestoreThread();	    /* enter python */
697 	Py_Finalize();
698     }
699     end_dynamic_python();
700 #else
701     if (Py_IsInitialized())
702     {
703 	Python_RestoreThread();	    /* enter python */
704 	Py_Finalize();
705     }
706 #endif
707 
708     --recurse;
709 }
710 
711 #if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
712     int
713 python_loaded()
714 {
715     return (hinstPython != 0);
716 }
717 #endif
718 
719     static int
720 Python_Init(void)
721 {
722     if (!initialised)
723     {
724 #ifdef DYNAMIC_PYTHON
725 	if (!python_enabled(TRUE))
726 	{
727 	    EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
728 	    goto fail;
729 	}
730 #endif
731 
732 #ifdef PYTHON_HOME
733 	Py_SetPythonHome(PYTHON_HOME);
734 #endif
735 
736 	init_structs();
737 
738 #if !defined(MACOS) || defined(MACOS_X_UNIX)
739 	Py_Initialize();
740 #else
741 	PyMac_Initialize();
742 #endif
743 	/* Initialise threads, and save the state using PyGILState_Ensure.
744 	 * Without the call to PyGILState_Ensure, thread specific state (such
745 	 * as the system trace hook), will be lost between invocations of
746 	 * Python code. */
747 	PyEval_InitThreads();
748 	pygilstate = PyGILState_Ensure();
749 #ifdef DYNAMIC_PYTHON
750 	get_exceptions();
751 #endif
752 
753 	if (PythonIO_Init())
754 	    goto fail;
755 
756 	if (PythonMod_Init())
757 	    goto fail;
758 
759 	globals = PyModule_GetDict(PyImport_AddModule("__main__"));
760 
761 	/* Remove the element from sys.path that was added because of our
762 	 * argv[0] value in PythonMod_Init().  Previously we used an empty
763 	 * string, but dependinding on the OS we then get an empty entry or
764 	 * the current directory in sys.path. */
765 	PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
766 
767 	/* the first python thread is vim's, release the lock */
768 	Python_SaveThread();
769 
770 	initialised = 1;
771     }
772 
773     return 0;
774 
775 fail:
776     /* We call PythonIO_Flush() here to print any Python errors.
777      * This is OK, as it is possible to call this function even
778      * if PythonIO_Init() has not completed successfully (it will
779      * not do anything in this case).
780      */
781     PythonIO_Flush();
782     return -1;
783 }
784 
785 /*
786  * External interface
787  */
788     static void
789 DoPythonCommand(exarg_T *eap, const char *cmd, typval_T *rettv)
790 {
791 #ifndef PY_CAN_RECURSE
792     static int		recursive = 0;
793 #endif
794 #if defined(MACOS) && !defined(MACOS_X_UNIX)
795     GrafPtr		oldPort;
796 #endif
797 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
798     char		*saved_locale;
799 #endif
800 
801 #ifndef PY_CAN_RECURSE
802     if (recursive)
803     {
804 	EMSG(_("E659: Cannot invoke Python recursively"));
805 	return;
806     }
807     ++recursive;
808 #endif
809 
810 #if defined(MACOS) && !defined(MACOS_X_UNIX)
811     GetPort(&oldPort);
812     /* Check if the Python library is available */
813     if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
814 	goto theend;
815 #endif
816     if (Python_Init())
817 	goto theend;
818 
819     if (rettv == NULL)
820     {
821 	RangeStart = eap->line1;
822 	RangeEnd = eap->line2;
823     }
824     else
825     {
826 	RangeStart = (PyInt) curwin->w_cursor.lnum;
827 	RangeEnd = RangeStart;
828     }
829     Python_Release_Vim();	    /* leave vim */
830 
831 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
832     /* Python only works properly when the LC_NUMERIC locale is "C". */
833     saved_locale = setlocale(LC_NUMERIC, NULL);
834     if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
835 	saved_locale = NULL;
836     else
837     {
838 	/* Need to make a copy, value may change when setting new locale. */
839 	saved_locale = (char *)vim_strsave((char_u *)saved_locale);
840 	(void)setlocale(LC_NUMERIC, "C");
841     }
842 #endif
843 
844     Python_RestoreThread();	    /* enter python */
845 
846     if (rettv == NULL)
847 	PyRun_SimpleString((char *)(cmd));
848     else
849     {
850 	PyObject	*r;
851 
852 	r = PyRun_String((char *)(cmd), Py_eval_input, globals, globals);
853 	if (r == NULL)
854 	    EMSG(_("E858: Eval did not return a valid python object"));
855 	else
856 	{
857 	    if (ConvertFromPyObject(r, rettv) == -1)
858 		EMSG(_("E859: Failed to convert returned python object to vim value"));
859 	    Py_DECREF(r);
860 	}
861 	PyErr_Clear();
862     }
863 
864     Python_SaveThread();	    /* leave python */
865 
866 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
867     if (saved_locale != NULL)
868     {
869 	(void)setlocale(LC_NUMERIC, saved_locale);
870 	vim_free(saved_locale);
871     }
872 #endif
873 
874     Python_Lock_Vim();		    /* enter vim */
875     PythonIO_Flush();
876 #if defined(MACOS) && !defined(MACOS_X_UNIX)
877     SetPort(oldPort);
878 #endif
879 
880 theend:
881 #ifndef PY_CAN_RECURSE
882     --recursive;
883 #endif
884     return;
885 }
886 
887 /*
888  * ":python"
889  */
890     void
891 ex_python(exarg_T *eap)
892 {
893     char_u *script;
894 
895     script = script_get(eap, eap->arg);
896     if (!eap->skip)
897     {
898 	if (script == NULL)
899 	    DoPythonCommand(eap, (char *)eap->arg, NULL);
900 	else
901 	    DoPythonCommand(eap, (char *)script, NULL);
902     }
903     vim_free(script);
904 }
905 
906 #define BUFFER_SIZE 1024
907 
908 /*
909  * ":pyfile"
910  */
911     void
912 ex_pyfile(exarg_T *eap)
913 {
914     static char buffer[BUFFER_SIZE];
915     const char *file = (char *)eap->arg;
916     char *p;
917 
918     /* Have to do it like this. PyRun_SimpleFile requires you to pass a
919      * stdio file pointer, but Vim and the Python DLL are compiled with
920      * different options under Windows, meaning that stdio pointers aren't
921      * compatible between the two. Yuk.
922      *
923      * Put the string "execfile('file')" into buffer. But, we need to
924      * escape any backslashes or single quotes in the file name, so that
925      * Python won't mangle the file name.
926      */
927     strcpy(buffer, "execfile('");
928     p = buffer + 10; /* size of "execfile('" */
929 
930     while (*file && p < buffer + (BUFFER_SIZE - 3))
931     {
932 	if (*file == '\\' || *file == '\'')
933 	    *p++ = '\\';
934 	*p++ = *file++;
935     }
936 
937     /* If we didn't finish the file name, we hit a buffer overflow */
938     if (*file != '\0')
939 	return;
940 
941     /* Put in the terminating "')" and a null */
942     *p++ = '\'';
943     *p++ = ')';
944     *p++ = '\0';
945 
946     /* Execute the file */
947     DoPythonCommand(eap, buffer, NULL);
948 }
949 
950 /******************************************************
951  * 2. Python output stream: writes output via [e]msg().
952  */
953 
954 /* Implementation functions
955  */
956 
957     static PyObject *
958 OutputGetattr(PyObject *self, char *name)
959 {
960     if (strcmp(name, "softspace") == 0)
961 	return PyInt_FromLong(((OutputObject *)(self))->softspace);
962 
963     return Py_FindMethod(OutputMethods, self, name);
964 }
965 
966 /***************/
967 
968     static int
969 PythonIO_Init(void)
970 {
971     /* Fixups... */
972     PyType_Ready(&OutputType);
973 
974     return PythonIO_Init_io();
975 }
976 
977 /******************************************************
978  * 3. Implementation of the Vim module for Python
979  */
980 
981 static PyObject *ConvertToPyObject(typval_T *);
982 static int ConvertFromPyObject(PyObject *, typval_T *);
983 
984 /* Window type - Implementation functions
985  * --------------------------------------
986  */
987 
988 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
989 
990 static void WindowDestructor(PyObject *);
991 static PyObject *WindowGetattr(PyObject *, char *);
992 
993 /* Buffer type - Implementation functions
994  * --------------------------------------
995  */
996 
997 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
998 
999 static void BufferDestructor(PyObject *);
1000 static PyObject *BufferGetattr(PyObject *, char *);
1001 static PyObject *BufferRepr(PyObject *);
1002 
1003 static PyInt BufferLength(PyObject *);
1004 static PyObject *BufferItem(PyObject *, PyInt);
1005 static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1006 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1007 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1008 
1009 /* Line range type - Implementation functions
1010  * --------------------------------------
1011  */
1012 
1013 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1014 
1015 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1016 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1017 
1018 /* Current objects type - Implementation functions
1019  * -----------------------------------------------
1020  */
1021 
1022 static PyObject *CurrentGetattr(PyObject *, char *);
1023 static int CurrentSetattr(PyObject *, char *, PyObject *);
1024 
1025 static PySequenceMethods BufferAsSeq = {
1026     (PyInquiry)		BufferLength,	    /* sq_length,    len(x)   */
1027     (binaryfunc)	0,		    /* BufferConcat, sq_concat, x+y */
1028     (PyIntArgFunc)	0,		    /* BufferRepeat, sq_repeat, x*n */
1029     (PyIntArgFunc)	BufferItem,	    /* sq_item,      x[i]     */
1030     (PyIntIntArgFunc)	BufferSlice,	    /* sq_slice,     x[i:j]   */
1031     (PyIntObjArgProc)	BufferAssItem,	    /* sq_ass_item,  x[i]=v   */
1032     (PyIntIntObjArgProc)	BufferAssSlice,     /* sq_ass_slice, x[i:j]=v */
1033 };
1034 
1035 static PyTypeObject BufferType = {
1036     PyObject_HEAD_INIT(0)
1037     0,
1038     "buffer",
1039     sizeof(BufferObject),
1040     0,
1041 
1042     (destructor)    BufferDestructor,	/* tp_dealloc,	refcount==0  */
1043     (printfunc)     0,			/* tp_print,	print x      */
1044     (getattrfunc)   BufferGetattr,	/* tp_getattr,	x.attr	     */
1045     (setattrfunc)   0,			/* tp_setattr,	x.attr=v     */
1046     (cmpfunc)	    0,			/* tp_compare,	x>y	     */
1047     (reprfunc)	    BufferRepr,		/* tp_repr,	`x`, print x */
1048 
1049     0,		    /* as number */
1050     &BufferAsSeq,   /* as sequence */
1051     0,		    /* as mapping */
1052 
1053     (hashfunc) 0,			/* tp_hash, dict(x) */
1054     (ternaryfunc) 0,			/* tp_call, x()     */
1055     (reprfunc) 0,			/* tp_str,  str(x)  */
1056 };
1057 
1058 /* Buffer object - Implementation
1059  */
1060 
1061     static PyObject *
1062 BufferNew(buf_T *buf)
1063 {
1064     /* We need to handle deletion of buffers underneath us.
1065      * If we add a "b_python_ref" field to the buf_T structure,
1066      * then we can get at it in buf_freeall() in vim. We then
1067      * need to create only ONE Python object per buffer - if
1068      * we try to create a second, just INCREF the existing one
1069      * and return it. The (single) Python object referring to
1070      * the buffer is stored in "b_python_ref".
1071      * Question: what to do on a buf_freeall(). We'll probably
1072      * have to either delete the Python object (DECREF it to
1073      * zero - a bad idea, as it leaves dangling refs!) or
1074      * set the buf_T * value to an invalid value (-1?), which
1075      * means we need checks in all access functions... Bah.
1076      */
1077 
1078     BufferObject *self;
1079 
1080     if (buf->b_python_ref != NULL)
1081     {
1082 	self = buf->b_python_ref;
1083 	Py_INCREF(self);
1084     }
1085     else
1086     {
1087 	self = PyObject_NEW(BufferObject, &BufferType);
1088 	if (self == NULL)
1089 	    return NULL;
1090 	self->buf = buf;
1091 	buf->b_python_ref = self;
1092     }
1093 
1094     return (PyObject *)(self);
1095 }
1096 
1097     static void
1098 BufferDestructor(PyObject *self)
1099 {
1100     BufferObject *this = (BufferObject *)(self);
1101 
1102     if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1103 	this->buf->b_python_ref = NULL;
1104 
1105     Py_DECREF(self);
1106 }
1107 
1108     static PyObject *
1109 BufferGetattr(PyObject *self, char *name)
1110 {
1111     BufferObject *this = (BufferObject *)(self);
1112 
1113     if (CheckBuffer(this))
1114 	return NULL;
1115 
1116     if (strcmp(name, "name") == 0)
1117 	return Py_BuildValue("s", this->buf->b_ffname);
1118     else if (strcmp(name, "number") == 0)
1119 	return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
1120     else if (strcmp(name,"__members__") == 0)
1121 	return Py_BuildValue("[ss]", "name", "number");
1122     else
1123 	return Py_FindMethod(BufferMethods, self, name);
1124 }
1125 
1126     static PyObject *
1127 BufferRepr(PyObject *self)
1128 {
1129     static char repr[100];
1130     BufferObject *this = (BufferObject *)(self);
1131 
1132     if (this->buf == INVALID_BUFFER_VALUE)
1133     {
1134 	vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
1135 	return PyString_FromString(repr);
1136     }
1137     else
1138     {
1139 	char *name = (char *)this->buf->b_fname;
1140 	PyInt len;
1141 
1142 	if (name == NULL)
1143 	    name = "";
1144 	len = strlen(name);
1145 
1146 	if (len > 35)
1147 	    name = name + (35 - len);
1148 
1149 	vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1150 
1151 	return PyString_FromString(repr);
1152     }
1153 }
1154 
1155 /******************/
1156 
1157     static PyInt
1158 BufferLength(PyObject *self)
1159 {
1160     /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1161     if (CheckBuffer((BufferObject *)(self)))
1162 	return -1; /* ??? */
1163 
1164     return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1165 }
1166 
1167     static PyObject *
1168 BufferItem(PyObject *self, PyInt n)
1169 {
1170     return RBItem((BufferObject *)(self), n, 1,
1171 		  (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1172 }
1173 
1174     static PyObject *
1175 BufferSlice(PyObject *self, PyInt lo, PyInt hi)
1176 {
1177     return RBSlice((BufferObject *)(self), lo, hi, 1,
1178 		   (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1179 }
1180 
1181     static PyInt
1182 BufferAssItem(PyObject *self, PyInt n, PyObject *val)
1183 {
1184     return RBAsItem((BufferObject *)(self), n, val, 1,
1185 		     (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1186 		     NULL);
1187 }
1188 
1189     static PyInt
1190 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1191 {
1192     return RBAsSlice((BufferObject *)(self), lo, hi, val, 1,
1193 		      (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1194 		      NULL);
1195 }
1196 
1197 static PySequenceMethods RangeAsSeq = {
1198     (PyInquiry)		RangeLength,	    /* sq_length,    len(x)   */
1199     (binaryfunc)	0, /* RangeConcat, */	     /* sq_concat,    x+y      */
1200     (PyIntArgFunc)	0, /* RangeRepeat, */	     /* sq_repeat,    x*n      */
1201     (PyIntArgFunc)	RangeItem,	    /* sq_item,      x[i]     */
1202     (PyIntIntArgFunc)	RangeSlice,	    /* sq_slice,     x[i:j]   */
1203     (PyIntObjArgProc)	RangeAssItem,	    /* sq_ass_item,  x[i]=v   */
1204     (PyIntIntObjArgProc)	RangeAssSlice,	    /* sq_ass_slice, x[i:j]=v */
1205 };
1206 
1207 /* Line range object - Implementation
1208  */
1209 
1210     static void
1211 RangeDestructor(PyObject *self)
1212 {
1213     Py_DECREF(((RangeObject *)(self))->buf);
1214     Py_DECREF(self);
1215 }
1216 
1217     static PyObject *
1218 RangeGetattr(PyObject *self, char *name)
1219 {
1220     if (strcmp(name, "start") == 0)
1221 	return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
1222     else if (strcmp(name, "end") == 0)
1223 	return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
1224     else
1225 	return Py_FindMethod(RangeMethods, self, name);
1226 }
1227 
1228 /****************/
1229 
1230     static PyInt
1231 RangeAssItem(PyObject *self, PyInt n, PyObject *val)
1232 {
1233     return RBAsItem(((RangeObject *)(self))->buf, n, val,
1234 		     ((RangeObject *)(self))->start,
1235 		     ((RangeObject *)(self))->end,
1236 		     &((RangeObject *)(self))->end);
1237 }
1238 
1239     static PyInt
1240 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1241 {
1242     return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
1243 		      ((RangeObject *)(self))->start,
1244 		      ((RangeObject *)(self))->end,
1245 		      &((RangeObject *)(self))->end);
1246 }
1247 
1248 /* Buffer list object - Definitions
1249  */
1250 
1251 typedef struct
1252 {
1253     PyObject_HEAD
1254 } BufListObject;
1255 
1256 static PySequenceMethods BufListAsSeq = {
1257     (PyInquiry)		BufListLength,	    /* sq_length,    len(x)   */
1258     (binaryfunc)	0,		    /* sq_concat,    x+y      */
1259     (PyIntArgFunc)	0,		    /* sq_repeat,    x*n      */
1260     (PyIntArgFunc)	BufListItem,	    /* sq_item,      x[i]     */
1261     (PyIntIntArgFunc)	0,		    /* sq_slice,     x[i:j]   */
1262     (PyIntObjArgProc)	0,		    /* sq_ass_item,  x[i]=v   */
1263     (PyIntIntObjArgProc)	0,		    /* sq_ass_slice, x[i:j]=v */
1264 };
1265 
1266 static PyTypeObject BufListType = {
1267     PyObject_HEAD_INIT(0)
1268     0,
1269     "buffer list",
1270     sizeof(BufListObject),
1271     0,
1272 
1273     (destructor)    0,			/* tp_dealloc,	refcount==0  */
1274     (printfunc)     0,			/* tp_print,	print x      */
1275     (getattrfunc)   0,			/* tp_getattr,	x.attr	     */
1276     (setattrfunc)   0,			/* tp_setattr,	x.attr=v     */
1277     (cmpfunc)	    0,			/* tp_compare,	x>y	     */
1278     (reprfunc)	    0,			/* tp_repr,	`x`, print x */
1279 
1280     0,		    /* as number */
1281     &BufListAsSeq,  /* as sequence */
1282     0,		    /* as mapping */
1283 
1284     (hashfunc) 0,			/* tp_hash, dict(x) */
1285     (ternaryfunc) 0,			/* tp_call, x()     */
1286     (reprfunc) 0,			/* tp_str,  str(x)  */
1287 };
1288 
1289 /* Window object - Definitions
1290  */
1291 
1292 static struct PyMethodDef WindowMethods[] = {
1293     /* name,	    function,		calling,    documentation */
1294     { NULL,	    NULL,		0,	    NULL }
1295 };
1296 
1297 static PyTypeObject WindowType = {
1298     PyObject_HEAD_INIT(0)
1299     0,
1300     "window",
1301     sizeof(WindowObject),
1302     0,
1303 
1304     (destructor)    WindowDestructor,	/* tp_dealloc,	refcount==0  */
1305     (printfunc)     0,			/* tp_print,	print x      */
1306     (getattrfunc)   WindowGetattr,	/* tp_getattr,	x.attr	     */
1307     (setattrfunc)   WindowSetattr,	/* tp_setattr,	x.attr=v     */
1308     (cmpfunc)	    0,			/* tp_compare,	x>y	     */
1309     (reprfunc)	    WindowRepr,		/* tp_repr,	`x`, print x */
1310 
1311     0,		    /* as number */
1312     0,		    /* as sequence */
1313     0,		    /* as mapping */
1314 
1315     (hashfunc) 0,			/* tp_hash, dict(x) */
1316     (ternaryfunc) 0,			/* tp_call, x()     */
1317     (reprfunc) 0,			/* tp_str,  str(x)  */
1318 };
1319 
1320 /* Window object - Implementation
1321  */
1322 
1323     static PyObject *
1324 WindowNew(win_T *win)
1325 {
1326     /* We need to handle deletion of windows underneath us.
1327      * If we add a "w_python_ref" field to the win_T structure,
1328      * then we can get at it in win_free() in vim. We then
1329      * need to create only ONE Python object per window - if
1330      * we try to create a second, just INCREF the existing one
1331      * and return it. The (single) Python object referring to
1332      * the window is stored in "w_python_ref".
1333      * On a win_free() we set the Python object's win_T* field
1334      * to an invalid value. We trap all uses of a window
1335      * object, and reject them if the win_T* field is invalid.
1336      */
1337 
1338     WindowObject *self;
1339 
1340     if (win->w_python_ref)
1341     {
1342 	self = win->w_python_ref;
1343 	Py_INCREF(self);
1344     }
1345     else
1346     {
1347 	self = PyObject_NEW(WindowObject, &WindowType);
1348 	if (self == NULL)
1349 	    return NULL;
1350 	self->win = win;
1351 	win->w_python_ref = self;
1352     }
1353 
1354     return (PyObject *)(self);
1355 }
1356 
1357     static void
1358 WindowDestructor(PyObject *self)
1359 {
1360     WindowObject *this = (WindowObject *)(self);
1361 
1362     if (this->win && this->win != INVALID_WINDOW_VALUE)
1363 	this->win->w_python_ref = NULL;
1364 
1365     Py_DECREF(self);
1366 }
1367 
1368     static PyObject *
1369 WindowGetattr(PyObject *self, char *name)
1370 {
1371     WindowObject *this = (WindowObject *)(self);
1372 
1373     if (CheckWindow(this))
1374 	return NULL;
1375 
1376     if (strcmp(name, "buffer") == 0)
1377 	return (PyObject *)BufferNew(this->win->w_buffer);
1378     else if (strcmp(name, "cursor") == 0)
1379     {
1380 	pos_T *pos = &this->win->w_cursor;
1381 
1382 	return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1383     }
1384     else if (strcmp(name, "height") == 0)
1385 	return Py_BuildValue("l", (long)(this->win->w_height));
1386 #ifdef FEAT_VERTSPLIT
1387     else if (strcmp(name, "width") == 0)
1388 	return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1389 #endif
1390     else if (strcmp(name,"__members__") == 0)
1391 	return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1392     else
1393 	return Py_FindMethod(WindowMethods, self, name);
1394 }
1395 
1396 /* Window list object - Definitions
1397  */
1398 
1399 typedef struct
1400 {
1401     PyObject_HEAD
1402 }
1403 WinListObject;
1404 
1405 static PySequenceMethods WinListAsSeq = {
1406     (PyInquiry)		WinListLength,	    /* sq_length,    len(x)   */
1407     (binaryfunc)	0,		    /* sq_concat,    x+y      */
1408     (PyIntArgFunc)	0,		    /* sq_repeat,    x*n      */
1409     (PyIntArgFunc)	WinListItem,	    /* sq_item,      x[i]     */
1410     (PyIntIntArgFunc)	0,		    /* sq_slice,     x[i:j]   */
1411     (PyIntObjArgProc)	0,		    /* sq_ass_item,  x[i]=v   */
1412     (PyIntIntObjArgProc)	0,		    /* sq_ass_slice, x[i:j]=v */
1413 };
1414 
1415 static PyTypeObject WinListType = {
1416     PyObject_HEAD_INIT(0)
1417     0,
1418     "window list",
1419     sizeof(WinListObject),
1420     0,
1421 
1422     (destructor)    0,			/* tp_dealloc,	refcount==0  */
1423     (printfunc)     0,			/* tp_print,	print x      */
1424     (getattrfunc)   0,			/* tp_getattr,	x.attr	     */
1425     (setattrfunc)   0,			/* tp_setattr,	x.attr=v     */
1426     (cmpfunc)	    0,			/* tp_compare,	x>y	     */
1427     (reprfunc)	    0,			/* tp_repr,	`x`, print x */
1428 
1429     0,		    /* as number */
1430     &WinListAsSeq,  /* as sequence */
1431     0,		    /* as mapping */
1432 
1433     (hashfunc) 0,			/* tp_hash, dict(x) */
1434     (ternaryfunc) 0,			/* tp_call, x()     */
1435     (reprfunc) 0,			/* tp_str,  str(x)  */
1436 };
1437 
1438 /* Current items object - Definitions
1439  */
1440 
1441 typedef struct
1442 {
1443     PyObject_HEAD
1444 } CurrentObject;
1445 
1446 static PyTypeObject CurrentType = {
1447     PyObject_HEAD_INIT(0)
1448     0,
1449     "current data",
1450     sizeof(CurrentObject),
1451     0,
1452 
1453     (destructor)    0,			/* tp_dealloc,	refcount==0  */
1454     (printfunc)     0,			/* tp_print,	print x      */
1455     (getattrfunc)   CurrentGetattr,	/* tp_getattr,	x.attr	     */
1456     (setattrfunc)   CurrentSetattr,	/* tp_setattr,	x.attr=v     */
1457     (cmpfunc)	    0,			/* tp_compare,	x>y	     */
1458     (reprfunc)	    0,			/* tp_repr,	`x`, print x */
1459 
1460     0,		    /* as number */
1461     0,		    /* as sequence */
1462     0,		    /* as mapping */
1463 
1464     (hashfunc) 0,			/* tp_hash, dict(x) */
1465     (ternaryfunc) 0,			/* tp_call, x()     */
1466     (reprfunc) 0,			/* tp_str,  str(x)  */
1467 };
1468 
1469 /* Current items object - Implementation
1470  */
1471     static PyObject *
1472 CurrentGetattr(PyObject *self UNUSED, char *name)
1473 {
1474     if (strcmp(name, "buffer") == 0)
1475 	return (PyObject *)BufferNew(curbuf);
1476     else if (strcmp(name, "window") == 0)
1477 	return (PyObject *)WindowNew(curwin);
1478     else if (strcmp(name, "line") == 0)
1479 	return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
1480     else if (strcmp(name, "range") == 0)
1481 	return RangeNew(curbuf, RangeStart, RangeEnd);
1482     else if (strcmp(name,"__members__") == 0)
1483 	return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
1484     else
1485     {
1486 	PyErr_SetString(PyExc_AttributeError, name);
1487 	return NULL;
1488     }
1489 }
1490 
1491     static int
1492 CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
1493 {
1494     if (strcmp(name, "line") == 0)
1495     {
1496 	if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
1497 	    return -1;
1498 
1499 	return 0;
1500     }
1501     else
1502     {
1503 	PyErr_SetString(PyExc_AttributeError, name);
1504 	return -1;
1505     }
1506 }
1507 
1508 /* External interface
1509  */
1510 
1511     void
1512 python_buffer_free(buf_T *buf)
1513 {
1514     if (buf->b_python_ref != NULL)
1515     {
1516 	BufferObject *bp = buf->b_python_ref;
1517 	bp->buf = INVALID_BUFFER_VALUE;
1518 	buf->b_python_ref = NULL;
1519     }
1520 }
1521 
1522 #if defined(FEAT_WINDOWS) || defined(PROTO)
1523     void
1524 python_window_free(win_T *win)
1525 {
1526     if (win->w_python_ref != NULL)
1527     {
1528 	WindowObject *wp = win->w_python_ref;
1529 	wp->win = INVALID_WINDOW_VALUE;
1530 	win->w_python_ref = NULL;
1531     }
1532 }
1533 #endif
1534 
1535 static BufListObject TheBufferList =
1536 {
1537     PyObject_HEAD_INIT(&BufListType)
1538 };
1539 
1540 static WinListObject TheWindowList =
1541 {
1542     PyObject_HEAD_INIT(&WinListType)
1543 };
1544 
1545 static CurrentObject TheCurrent =
1546 {
1547     PyObject_HEAD_INIT(&CurrentType)
1548 };
1549 
1550     static int
1551 PythonMod_Init(void)
1552 {
1553     PyObject *mod;
1554     PyObject *dict;
1555     /* The special value is removed from sys.path in Python_Init(). */
1556     static char *(argv[2]) = {"/must>not&exist/foo", NULL};
1557 
1558     /* Fixups... */
1559     PyType_Ready(&BufferType);
1560     PyType_Ready(&RangeType);
1561     PyType_Ready(&WindowType);
1562     PyType_Ready(&BufListType);
1563     PyType_Ready(&WinListType);
1564     PyType_Ready(&CurrentType);
1565 
1566     /* Set sys.argv[] to avoid a crash in warn(). */
1567     PySys_SetArgv(1, argv);
1568 
1569     mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
1570     dict = PyModule_GetDict(mod);
1571 
1572     VimError = Py_BuildValue("s", "vim.error");
1573 
1574     PyDict_SetItemString(dict, "error", VimError);
1575     PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
1576     PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
1577     PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
1578     PyDict_SetItemString(dict, "VAR_LOCKED",    PyInt_FromLong(VAR_LOCKED));
1579     PyDict_SetItemString(dict, "VAR_FIXED",     PyInt_FromLong(VAR_FIXED));
1580     PyDict_SetItemString(dict, "VAR_SCOPE",     PyInt_FromLong(VAR_SCOPE));
1581     PyDict_SetItemString(dict, "VAR_DEF_SCOPE", PyInt_FromLong(VAR_DEF_SCOPE));
1582 
1583     if (PyErr_Occurred())
1584 	return -1;
1585 
1586     return 0;
1587 }
1588 
1589 /*************************************************************************
1590  * 4. Utility functions for handling the interface between Vim and Python.
1591  */
1592 
1593 /* Convert a Vim line into a Python string.
1594  * All internal newlines are replaced by null characters.
1595  *
1596  * On errors, the Python exception data is set, and NULL is returned.
1597  */
1598     static PyObject *
1599 LineToString(const char *str)
1600 {
1601     PyObject *result;
1602     PyInt len = strlen(str);
1603     char *p;
1604 
1605     /* Allocate an Python string object, with uninitialised contents. We
1606      * must do it this way, so that we can modify the string in place
1607      * later. See the Python source, Objects/stringobject.c for details.
1608      */
1609     result = PyString_FromStringAndSize(NULL, len);
1610     if (result == NULL)
1611 	return NULL;
1612 
1613     p = PyString_AsString(result);
1614 
1615     while (*str)
1616     {
1617 	if (*str == '\n')
1618 	    *p = '\0';
1619 	else
1620 	    *p = *str;
1621 
1622 	++p;
1623 	++str;
1624     }
1625 
1626     return result;
1627 }
1628 
1629 static void DictionaryDestructor(PyObject *);
1630 static PyObject *DictionaryGetattr(PyObject *, char*);
1631 
1632 static PyMappingMethods DictionaryAsMapping = {
1633     (PyInquiry)		DictionaryLength,
1634     (binaryfunc)	DictionaryItem,
1635     (objobjargproc)	DictionaryAssItem,
1636 };
1637 
1638 static PyTypeObject DictionaryType = {
1639     PyObject_HEAD_INIT(0)
1640     0,
1641     "vimdictionary",
1642     sizeof(DictionaryObject),
1643     0,
1644 
1645     (destructor)  DictionaryDestructor,
1646     (printfunc)   0,
1647     (getattrfunc) DictionaryGetattr,
1648     (setattrfunc) DictionarySetattr,
1649     (cmpfunc)     0,
1650     (reprfunc)    0,
1651 
1652     0,			    /* as number */
1653     0,			    /* as sequence */
1654     &DictionaryAsMapping,   /* as mapping */
1655 
1656     (hashfunc)    0,
1657     (ternaryfunc) 0,
1658     (reprfunc)    0,
1659 };
1660 
1661     static void
1662 DictionaryDestructor(PyObject *self)
1663 {
1664     DictionaryObject	*this = ((DictionaryObject *) (self));
1665 
1666     pyll_remove(&this->ref, &lastdict);
1667     dict_unref(this->dict);
1668 
1669     Py_DECREF(self);
1670 }
1671 
1672     static PyObject *
1673 DictionaryGetattr(PyObject *self, char *name)
1674 {
1675     DictionaryObject	*this = ((DictionaryObject *) (self));
1676 
1677     if (strcmp(name, "locked") == 0)
1678 	return PyInt_FromLong(this->dict->dv_lock);
1679     else if (strcmp(name, "scope") == 0)
1680 	return PyInt_FromLong(this->dict->dv_scope);
1681 
1682     return Py_FindMethod(DictionaryMethods, self, name);
1683 }
1684 
1685 static void ListDestructor(PyObject *);
1686 static PyObject *ListGetattr(PyObject *, char *);
1687 
1688 static PySequenceMethods ListAsSeq = {
1689     (PyInquiry)			ListLength,
1690     (binaryfunc)		0,
1691     (PyIntArgFunc)		0,
1692     (PyIntArgFunc)		ListItem,
1693     (PyIntIntArgFunc)		ListSlice,
1694     (PyIntObjArgProc)		ListAssItem,
1695     (PyIntIntObjArgProc)	ListAssSlice,
1696     (objobjproc)		0,
1697 #if PY_MAJOR_VERSION >= 2
1698     (binaryfunc)		ListConcatInPlace,
1699     0,
1700 #endif
1701 };
1702 
1703 static PyTypeObject ListType = {
1704     PyObject_HEAD_INIT(0)
1705     0,
1706     "vimlist",
1707     sizeof(ListObject),
1708     0,
1709 
1710     (destructor)  ListDestructor,
1711     (printfunc)   0,
1712     (getattrfunc) ListGetattr,
1713     (setattrfunc) ListSetattr,
1714     (cmpfunc)     0,
1715     (reprfunc)    0,
1716 
1717     0,			    /* as number */
1718     &ListAsSeq,		    /* as sequence */
1719     0,			    /* as mapping */
1720 
1721     (hashfunc)    0,
1722     (ternaryfunc) 0,
1723     (reprfunc)    0,
1724 };
1725 
1726     static void
1727 ListDestructor(PyObject *self)
1728 {
1729     ListObject	*this = ((ListObject *) (self));
1730 
1731     pyll_remove(&this->ref, &lastlist);
1732     list_unref(this->list);
1733 
1734     Py_DECREF(self);
1735 }
1736 
1737     static PyObject *
1738 ListGetattr(PyObject *self, char *name)
1739 {
1740     if (strcmp(name, "locked") == 0)
1741 	return PyInt_FromLong(((ListObject *)(self))->list->lv_lock);
1742 
1743     return Py_FindMethod(ListMethods, self, name);
1744 }
1745 
1746 static void FunctionDestructor(PyObject *);
1747 static PyObject *FunctionGetattr(PyObject *, char *);
1748 
1749 static PyTypeObject FunctionType = {
1750     PyObject_HEAD_INIT(0)
1751     0,
1752     "vimfunction",
1753     sizeof(FunctionObject),
1754     0,
1755 
1756     (destructor)  FunctionDestructor,
1757     (printfunc)   0,
1758     (getattrfunc) FunctionGetattr,
1759     (setattrfunc) 0,
1760     (cmpfunc)     0,
1761     (reprfunc)    0,
1762 
1763     0,			    /* as number */
1764     0,			    /* as sequence */
1765     0,			    /* as mapping */
1766 
1767     (hashfunc)    0,
1768     (ternaryfunc) FunctionCall,
1769     (reprfunc)    0,
1770 };
1771 
1772     static void
1773 FunctionDestructor(PyObject *self)
1774 {
1775     FunctionObject	*this = (FunctionObject *) (self);
1776 
1777     func_unref(this->name);
1778     PyMem_Del(this->name);
1779 
1780     Py_DECREF(self);
1781 }
1782 
1783     static PyObject *
1784 FunctionGetattr(PyObject *self, char *name)
1785 {
1786     FunctionObject	*this = (FunctionObject *)(self);
1787 
1788     if (strcmp(name, "name") == 0)
1789 	return PyString_FromString((char *)(this->name));
1790     else
1791 	return Py_FindMethod(FunctionMethods, self, name);
1792 }
1793 
1794     void
1795 do_pyeval (char_u *str, typval_T *rettv)
1796 {
1797     DoPythonCommand(NULL, (char *) str, rettv);
1798     switch(rettv->v_type)
1799     {
1800 	case VAR_DICT: ++rettv->vval.v_dict->dv_refcount; break;
1801 	case VAR_LIST: ++rettv->vval.v_list->lv_refcount; break;
1802 	case VAR_FUNC: func_ref(rettv->vval.v_string);    break;
1803 	case VAR_UNKNOWN:
1804 	    rettv->v_type = VAR_NUMBER;
1805 	    rettv->vval.v_number = 0;
1806 	    break;
1807     }
1808 }
1809 
1810 /* Don't generate a prototype for the next function, it generates an error on
1811  * newer Python versions. */
1812 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
1813 
1814     char *
1815 Py_GetProgramName(void)
1816 {
1817     return "vim";
1818 }
1819 #endif /* Python 1.4 */
1820 
1821     void
1822 set_ref_in_python (int copyID)
1823 {
1824     set_ref_in_py(copyID);
1825 }
1826 
1827     static void
1828 init_structs(void)
1829 {
1830     vim_memset(&OutputType, 0, sizeof(OutputType));
1831     OutputType.tp_name = "message";
1832     OutputType.tp_basicsize = sizeof(OutputObject);
1833     OutputType.tp_getattr = OutputGetattr;
1834     OutputType.tp_setattr = OutputSetattr;
1835 
1836     vim_memset(&RangeType, 0, sizeof(RangeType));
1837     RangeType.tp_name = "range";
1838     RangeType.tp_basicsize = sizeof(RangeObject);
1839     RangeType.tp_dealloc = RangeDestructor;
1840     RangeType.tp_getattr = RangeGetattr;
1841     RangeType.tp_repr = RangeRepr;
1842     RangeType.tp_as_sequence = &RangeAsSeq;
1843 }
1844