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