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