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