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