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