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