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