Merge branch 'vim'
[MacVim.git] / src / if_python.c
bloba170787271cc3aedd906bc5f27e2c56207d65b71
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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.
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.
20 #include "vim.h"
22 #include <limits.h>
24 /* Python.h defines _POSIX_THREADS itself (if needed) */
25 #ifdef _POSIX_THREADS
26 # undef _POSIX_THREADS
27 #endif
29 #if defined(_WIN32) && defined (HAVE_FCNTL_H)
30 # undef HAVE_FCNTL_H
31 #endif
33 #ifdef _DEBUG
34 # undef _DEBUG
35 #endif
37 #ifdef HAVE_STDARG_H
38 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */
39 #endif
41 #define PY_SSIZE_T_CLEAN
43 #ifdef FEAT_GUI_MACVIM
44 # include <Python/Python.h>
45 #else
46 # include <Python.h>
47 #endif
49 #if defined(MACOS) && !defined(MACOS_X_UNIX)
50 # include "macglue.h"
51 # include <CodeFragments.h>
52 #endif
53 #undef main /* Defined in python.h - aargh */
54 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
56 #if !defined(FEAT_PYTHON) && defined(PROTO)
57 /* Use this to be able to generate prototypes without python being used. */
58 # define PyObject Py_ssize_t
59 # define PyThreadState Py_ssize_t
60 # define PyTypeObject Py_ssize_t
61 struct PyMethodDef { Py_ssize_t a; };
62 # define PySequenceMethods Py_ssize_t
63 #endif
65 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
66 # define PyInt Py_ssize_t
67 # define PyInquiry lenfunc
68 # define PyIntArgFunc ssizeargfunc
69 # define PyIntIntArgFunc ssizessizeargfunc
70 # define PyIntObjArgProc ssizeobjargproc
71 # define PyIntIntObjArgProc ssizessizeobjargproc
72 # define Py_ssize_t_fmt "n"
73 #else
74 # define PyInt int
75 # define PyInquiry inquiry
76 # define PyIntArgFunc intargfunc
77 # define PyIntIntArgFunc intintargfunc
78 # define PyIntObjArgProc intobjargproc
79 # define PyIntIntObjArgProc intintobjargproc
80 # define Py_ssize_t_fmt "i"
81 #endif
83 /* Parser flags */
84 #define single_input 256
85 #define file_input 257
86 #define eval_input 258
88 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
89 /* Python 2.3: can invoke ":python" recursively. */
90 # define PY_CAN_RECURSE
91 #endif
93 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
94 # ifndef DYNAMIC_PYTHON
95 # define HINSTANCE long_u /* for generating prototypes */
96 # endif
98 /* This makes if_python.c compile without warnings against Python 2.5
99 * on Win32 and Win64. */
100 #undef PyRun_SimpleString
101 #undef PyArg_Parse
102 #undef PyArg_ParseTuple
103 #undef Py_BuildValue
104 #undef Py_InitModule4
105 #undef Py_InitModule4_64
108 * Wrapper defines
110 # define PyArg_Parse dll_PyArg_Parse
111 # define PyArg_ParseTuple dll_PyArg_ParseTuple
112 # define PyDict_SetItemString dll_PyDict_SetItemString
113 # define PyErr_BadArgument dll_PyErr_BadArgument
114 # define PyErr_Clear dll_PyErr_Clear
115 # define PyErr_NoMemory dll_PyErr_NoMemory
116 # define PyErr_Occurred dll_PyErr_Occurred
117 # define PyErr_SetNone dll_PyErr_SetNone
118 # define PyErr_SetString dll_PyErr_SetString
119 # define PyEval_InitThreads dll_PyEval_InitThreads
120 # define PyEval_RestoreThread dll_PyEval_RestoreThread
121 # define PyEval_SaveThread dll_PyEval_SaveThread
122 # ifdef PY_CAN_RECURSE
123 # define PyGILState_Ensure dll_PyGILState_Ensure
124 # define PyGILState_Release dll_PyGILState_Release
125 # endif
126 # define PyInt_AsLong dll_PyInt_AsLong
127 # define PyInt_FromLong dll_PyInt_FromLong
128 # define PyInt_Type (*dll_PyInt_Type)
129 # define PyList_GetItem dll_PyList_GetItem
130 # define PyList_Append dll_PyList_Append
131 # define PyList_New dll_PyList_New
132 # define PyList_SetItem dll_PyList_SetItem
133 # define PyList_Size dll_PyList_Size
134 # define PyList_Type (*dll_PyList_Type)
135 # define PyImport_ImportModule dll_PyImport_ImportModule
136 # define PyDict_New dll_PyDict_New
137 # define PyDict_GetItemString dll_PyDict_GetItemString
138 # define PyModule_GetDict dll_PyModule_GetDict
139 # define PyRun_SimpleString dll_PyRun_SimpleString
140 # define PyString_AsString dll_PyString_AsString
141 # define PyString_FromString dll_PyString_FromString
142 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
143 # define PyString_Size dll_PyString_Size
144 # define PyString_Type (*dll_PyString_Type)
145 # define PySys_SetObject dll_PySys_SetObject
146 # define PySys_SetArgv dll_PySys_SetArgv
147 # define PyType_Type (*dll_PyType_Type)
148 # define Py_BuildValue dll_Py_BuildValue
149 # define Py_FindMethod dll_Py_FindMethod
150 # define Py_InitModule4 dll_Py_InitModule4
151 # define Py_Initialize dll_Py_Initialize
152 # define Py_Finalize dll_Py_Finalize
153 # define Py_IsInitialized dll_Py_IsInitialized
154 # define _PyObject_New dll__PyObject_New
155 # define _Py_NoneStruct (*dll__Py_NoneStruct)
156 # define PyObject_Init dll__PyObject_Init
157 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
158 # define PyType_IsSubtype dll_PyType_IsSubtype
159 # endif
160 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
161 # define PyObject_Malloc dll_PyObject_Malloc
162 # define PyObject_Free dll_PyObject_Free
163 # endif
166 * Pointers for dynamic link
168 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
169 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
170 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
171 static int(*dll_PyErr_BadArgument)(void);
172 static void(*dll_PyErr_Clear)(void);
173 static PyObject*(*dll_PyErr_NoMemory)(void);
174 static PyObject*(*dll_PyErr_Occurred)(void);
175 static void(*dll_PyErr_SetNone)(PyObject *);
176 static void(*dll_PyErr_SetString)(PyObject *, const char *);
177 static void(*dll_PyEval_InitThreads)(void);
178 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
179 static PyThreadState*(*dll_PyEval_SaveThread)(void);
180 # ifdef PY_CAN_RECURSE
181 static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
182 static void (*dll_PyGILState_Release)(PyGILState_STATE);
183 #endif
184 static long(*dll_PyInt_AsLong)(PyObject *);
185 static PyObject*(*dll_PyInt_FromLong)(long);
186 static PyTypeObject* dll_PyInt_Type;
187 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
188 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
189 static PyObject*(*dll_PyList_New)(PyInt size);
190 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
191 static PyInt(*dll_PyList_Size)(PyObject *);
192 static PyTypeObject* dll_PyList_Type;
193 static PyObject*(*dll_PyImport_ImportModule)(const char *);
194 static PyObject*(*dll_PyDict_New)(void);
195 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
196 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
197 static int(*dll_PyRun_SimpleString)(char *);
198 static char*(*dll_PyString_AsString)(PyObject *);
199 static PyObject*(*dll_PyString_FromString)(const char *);
200 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
201 static PyInt(*dll_PyString_Size)(PyObject *);
202 static PyTypeObject* dll_PyString_Type;
203 static int(*dll_PySys_SetObject)(char *, PyObject *);
204 static int(*dll_PySys_SetArgv)(int, char **);
205 static PyTypeObject* dll_PyType_Type;
206 static PyObject*(*dll_Py_BuildValue)(char *, ...);
207 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
208 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
209 static void(*dll_Py_Initialize)(void);
210 static void(*dll_Py_Finalize)(void);
211 static int(*dll_Py_IsInitialized)(void);
212 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
213 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
214 static PyObject* dll__Py_NoneStruct;
215 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
216 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
217 # endif
218 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
219 static void* (*dll_PyObject_Malloc)(size_t);
220 static void (*dll_PyObject_Free)(void*);
221 # endif
223 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
225 /* Imported exception objects */
226 static PyObject *imp_PyExc_AttributeError;
227 static PyObject *imp_PyExc_IndexError;
228 static PyObject *imp_PyExc_KeyboardInterrupt;
229 static PyObject *imp_PyExc_TypeError;
230 static PyObject *imp_PyExc_ValueError;
232 # define PyExc_AttributeError imp_PyExc_AttributeError
233 # define PyExc_IndexError imp_PyExc_IndexError
234 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
235 # define PyExc_TypeError imp_PyExc_TypeError
236 # define PyExc_ValueError imp_PyExc_ValueError
239 * Table of name to function pointer of python.
241 # define PYTHON_PROC FARPROC
242 static struct
244 char *name;
245 PYTHON_PROC *ptr;
246 } python_funcname_table[] =
248 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
249 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
250 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
251 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
252 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
253 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
254 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
255 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
256 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
257 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
258 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
259 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
260 # ifdef PY_CAN_RECURSE
261 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
262 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
263 # endif
264 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
265 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
266 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
267 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
268 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
269 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
270 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
271 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
272 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
273 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
274 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
275 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
276 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
277 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
278 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
279 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
280 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
281 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
282 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
283 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
284 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
285 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
286 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
287 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
288 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
289 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
290 # else
291 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
292 # endif
293 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
294 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
295 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
296 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
297 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
298 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
299 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
300 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
301 # endif
302 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
303 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
304 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
305 # endif
306 {"", NULL},
310 * Free python.dll
312 static void
313 end_dynamic_python(void)
315 if (hinstPython)
317 FreeLibrary(hinstPython);
318 hinstPython = 0;
323 * Load library and get all pointers.
324 * Parameter 'libname' provides name of DLL.
325 * Return OK or FAIL.
327 static int
328 python_runtime_link_init(char *libname, int verbose)
330 int i;
332 if (hinstPython)
333 return OK;
334 hinstPython = LoadLibrary(libname);
335 if (!hinstPython)
337 if (verbose)
338 EMSG2(_(e_loadlib), libname);
339 return FAIL;
342 for (i = 0; python_funcname_table[i].ptr; ++i)
344 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
345 python_funcname_table[i].name)) == NULL)
347 FreeLibrary(hinstPython);
348 hinstPython = 0;
349 if (verbose)
350 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
351 return FAIL;
354 return OK;
358 * If python is enabled (there is installed python on Windows system) return
359 * TRUE, else FALSE.
362 python_enabled(int verbose)
364 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
367 /* Load the standard Python exceptions - don't import the symbols from the
368 * DLL, as this can cause errors (importing data symbols is not reliable).
370 static void get_exceptions __ARGS((void));
372 static void
373 get_exceptions()
375 PyObject *exmod = PyImport_ImportModule("exceptions");
376 PyObject *exdict = PyModule_GetDict(exmod);
377 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
378 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
379 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
380 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
381 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
382 Py_XINCREF(imp_PyExc_AttributeError);
383 Py_XINCREF(imp_PyExc_IndexError);
384 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
385 Py_XINCREF(imp_PyExc_TypeError);
386 Py_XINCREF(imp_PyExc_ValueError);
387 Py_XDECREF(exmod);
389 #endif /* DYNAMIC_PYTHON */
391 /******************************************************
392 * Internal function prototypes.
395 static void DoPythonCommand(exarg_T *, const char *);
396 static PyInt RangeStart;
397 static PyInt RangeEnd;
399 static void PythonIO_Flush(void);
400 static int PythonIO_Init(void);
401 static int PythonMod_Init(void);
403 /* Utility functions for the vim/python interface
404 * ----------------------------------------------
406 static PyObject *GetBufferLine(buf_T *, PyInt);
407 static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
409 static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
410 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
411 static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
413 static PyObject *LineToString(const char *);
414 static char *StringToLine(PyObject *);
416 static int VimErrorCheck(void);
418 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
420 /******************************************************
421 * 1. Python interpreter main program.
424 static int initialised = 0;
426 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
427 typedef PyObject PyThreadState;
428 #endif
430 #ifdef PY_CAN_RECURSE
431 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
432 #else
433 static PyThreadState *saved_python_thread = NULL;
434 #endif
437 * Suspend a thread of the Python interpreter, other threads are allowed to
438 * run.
440 static void
441 Python_SaveThread(void)
443 #ifdef PY_CAN_RECURSE
444 PyGILState_Release(pygilstate);
445 #else
446 saved_python_thread = PyEval_SaveThread();
447 #endif
451 * Restore a thread of the Python interpreter, waits for other threads to
452 * block.
454 static void
455 Python_RestoreThread(void)
457 #ifdef PY_CAN_RECURSE
458 pygilstate = PyGILState_Ensure();
459 #else
460 PyEval_RestoreThread(saved_python_thread);
461 saved_python_thread = NULL;
462 #endif
466 * obtain a lock on the Vim data structures
468 static void Python_Lock_Vim(void)
473 * release a lock on the Vim data structures
475 static void Python_Release_Vim(void)
479 void
480 python_end()
482 static int recurse = 0;
484 /* If a crash occurs while doing this, don't try again. */
485 if (recurse != 0)
486 return;
488 ++recurse;
490 #ifdef DYNAMIC_PYTHON
491 if (hinstPython && Py_IsInitialized())
493 Python_RestoreThread(); /* enter python */
494 Py_Finalize();
496 end_dynamic_python();
497 #else
498 if (Py_IsInitialized())
500 Python_RestoreThread(); /* enter python */
501 Py_Finalize();
503 #endif
505 --recurse;
508 static int
509 Python_Init(void)
511 if (!initialised)
513 #ifdef DYNAMIC_PYTHON
514 if (!python_enabled(TRUE))
516 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
517 goto fail;
519 #endif
521 #if !defined(MACOS) || defined(MACOS_X_UNIX)
522 Py_Initialize();
523 #else
524 PyMac_Initialize();
525 #endif
526 /* initialise threads */
527 PyEval_InitThreads();
529 #ifdef DYNAMIC_PYTHON
530 get_exceptions();
531 #endif
533 if (PythonIO_Init())
534 goto fail;
536 if (PythonMod_Init())
537 goto fail;
539 /* Remove the element from sys.path that was added because of our
540 * argv[0] value in PythonMod_Init(). Previously we used an empty
541 * string, but dependinding on the OS we then get an empty entry or
542 * the current directory in sys.path. */
543 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
545 /* the first python thread is vim's, release the lock */
546 Python_SaveThread();
548 initialised = 1;
551 return 0;
553 fail:
554 /* We call PythonIO_Flush() here to print any Python errors.
555 * This is OK, as it is possible to call this function even
556 * if PythonIO_Init() has not completed successfully (it will
557 * not do anything in this case).
559 PythonIO_Flush();
560 return -1;
564 * External interface
566 static void
567 DoPythonCommand(exarg_T *eap, const char *cmd)
569 #ifndef PY_CAN_RECURSE
570 static int recursive = 0;
571 #endif
572 #if defined(MACOS) && !defined(MACOS_X_UNIX)
573 GrafPtr oldPort;
574 #endif
575 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
576 char *saved_locale;
577 #endif
579 #ifndef PY_CAN_RECURSE
580 if (recursive)
582 EMSG(_("E659: Cannot invoke Python recursively"));
583 return;
585 ++recursive;
586 #endif
588 #if defined(MACOS) && !defined(MACOS_X_UNIX)
589 GetPort(&oldPort);
590 /* Check if the Python library is available */
591 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
592 goto theend;
593 #endif
594 if (Python_Init())
595 goto theend;
597 RangeStart = eap->line1;
598 RangeEnd = eap->line2;
599 Python_Release_Vim(); /* leave vim */
601 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
602 /* Python only works properly when the LC_NUMERIC locale is "C". */
603 saved_locale = setlocale(LC_NUMERIC, NULL);
604 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
605 saved_locale = NULL;
606 else
608 /* Need to make a copy, value may change when setting new locale. */
609 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
610 (void)setlocale(LC_NUMERIC, "C");
612 #endif
614 Python_RestoreThread(); /* enter python */
616 PyRun_SimpleString((char *)(cmd));
618 Python_SaveThread(); /* leave python */
620 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
621 if (saved_locale != NULL)
623 (void)setlocale(LC_NUMERIC, saved_locale);
624 vim_free(saved_locale);
626 #endif
628 Python_Lock_Vim(); /* enter vim */
629 PythonIO_Flush();
630 #if defined(MACOS) && !defined(MACOS_X_UNIX)
631 SetPort(oldPort);
632 #endif
634 theend:
635 #ifndef PY_CAN_RECURSE
636 --recursive;
637 #endif
638 return; /* keeps lint happy */
642 * ":python"
644 void
645 ex_python(exarg_T *eap)
647 char_u *script;
649 script = script_get(eap, eap->arg);
650 if (!eap->skip)
652 if (script == NULL)
653 DoPythonCommand(eap, (char *)eap->arg);
654 else
655 DoPythonCommand(eap, (char *)script);
657 vim_free(script);
660 #define BUFFER_SIZE 1024
663 * ":pyfile"
665 void
666 ex_pyfile(exarg_T *eap)
668 static char buffer[BUFFER_SIZE];
669 const char *file = (char *)eap->arg;
670 char *p;
672 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
673 * stdio file pointer, but Vim and the Python DLL are compiled with
674 * different options under Windows, meaning that stdio pointers aren't
675 * compatible between the two. Yuk.
677 * Put the string "execfile('file')" into buffer. But, we need to
678 * escape any backslashes or single quotes in the file name, so that
679 * Python won't mangle the file name.
681 strcpy(buffer, "execfile('");
682 p = buffer + 10; /* size of "execfile('" */
684 while (*file && p < buffer + (BUFFER_SIZE - 3))
686 if (*file == '\\' || *file == '\'')
687 *p++ = '\\';
688 *p++ = *file++;
691 /* If we didn't finish the file name, we hit a buffer overflow */
692 if (*file != '\0')
693 return;
695 /* Put in the terminating "')" and a null */
696 *p++ = '\'';
697 *p++ = ')';
698 *p++ = '\0';
700 /* Execute the file */
701 DoPythonCommand(eap, buffer);
704 /******************************************************
705 * 2. Python output stream: writes output via [e]msg().
708 /* Implementation functions
711 static PyObject *OutputGetattr(PyObject *, char *);
712 static int OutputSetattr(PyObject *, char *, PyObject *);
714 static PyObject *OutputWrite(PyObject *, PyObject *);
715 static PyObject *OutputWritelines(PyObject *, PyObject *);
717 typedef void (*writefn)(char_u *);
718 static void writer(writefn fn, char_u *str, PyInt n);
720 /* Output object definition
723 typedef struct
725 PyObject_HEAD
726 long softspace;
727 long error;
728 } OutputObject;
730 static struct PyMethodDef OutputMethods[] = {
731 /* name, function, calling, documentation */
732 {"write", OutputWrite, 1, "" },
733 {"writelines", OutputWritelines, 1, "" },
734 { NULL, NULL, 0, NULL }
737 static PyTypeObject OutputType = {
738 PyObject_HEAD_INIT(0)
740 "message",
741 sizeof(OutputObject),
744 (destructor) 0,
745 (printfunc) 0,
746 (getattrfunc) OutputGetattr,
747 (setattrfunc) OutputSetattr,
748 (cmpfunc) 0,
749 (reprfunc) 0,
751 0, /* as number */
752 0, /* as sequence */
753 0, /* as mapping */
755 (hashfunc) 0,
756 (ternaryfunc) 0,
757 (reprfunc) 0
760 /*************/
762 static PyObject *
763 OutputGetattr(PyObject *self, char *name)
765 if (strcmp(name, "softspace") == 0)
766 return PyInt_FromLong(((OutputObject *)(self))->softspace);
768 return Py_FindMethod(OutputMethods, self, name);
771 static int
772 OutputSetattr(PyObject *self, char *name, PyObject *val)
774 if (val == NULL) {
775 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
776 return -1;
779 if (strcmp(name, "softspace") == 0)
781 if (!PyInt_Check(val)) {
782 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
783 return -1;
786 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
787 return 0;
790 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
791 return -1;
794 /*************/
796 static PyObject *
797 OutputWrite(PyObject *self, PyObject *args)
799 int len;
800 char *str;
801 int error = ((OutputObject *)(self))->error;
803 if (!PyArg_ParseTuple(args, "s#", &str, &len))
804 return NULL;
806 Py_BEGIN_ALLOW_THREADS
807 Python_Lock_Vim();
808 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
809 Python_Release_Vim();
810 Py_END_ALLOW_THREADS
812 Py_INCREF(Py_None);
813 return Py_None;
816 static PyObject *
817 OutputWritelines(PyObject *self, PyObject *args)
819 PyInt n;
820 PyInt i;
821 PyObject *list;
822 int error = ((OutputObject *)(self))->error;
824 if (!PyArg_ParseTuple(args, "O", &list))
825 return NULL;
826 Py_INCREF(list);
828 if (!PyList_Check(list)) {
829 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
830 Py_DECREF(list);
831 return NULL;
834 n = PyList_Size(list);
836 for (i = 0; i < n; ++i)
838 PyObject *line = PyList_GetItem(list, i);
839 char *str;
840 PyInt len;
842 if (!PyArg_Parse(line, "s#", &str, &len)) {
843 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
844 Py_DECREF(list);
845 return NULL;
848 Py_BEGIN_ALLOW_THREADS
849 Python_Lock_Vim();
850 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
851 Python_Release_Vim();
852 Py_END_ALLOW_THREADS
855 Py_DECREF(list);
856 Py_INCREF(Py_None);
857 return Py_None;
860 /* Output buffer management
863 static char_u *buffer = NULL;
864 static PyInt buffer_len = 0;
865 static PyInt buffer_size = 0;
867 static writefn old_fn = NULL;
869 static void
870 buffer_ensure(PyInt n)
872 PyInt new_size;
873 char_u *new_buffer;
875 if (n < buffer_size)
876 return;
878 new_size = buffer_size;
879 while (new_size < n)
880 new_size += 80;
882 if (new_size != buffer_size)
884 new_buffer = alloc((unsigned)new_size);
885 if (new_buffer == NULL)
886 return;
888 if (buffer)
890 memcpy(new_buffer, buffer, buffer_len);
891 vim_free(buffer);
894 buffer = new_buffer;
895 buffer_size = new_size;
899 static void
900 PythonIO_Flush(void)
902 if (old_fn && buffer_len)
904 buffer[buffer_len] = 0;
905 old_fn(buffer);
908 buffer_len = 0;
911 static void
912 writer(writefn fn, char_u *str, PyInt n)
914 char_u *ptr;
916 if (fn != old_fn && old_fn != NULL)
917 PythonIO_Flush();
919 old_fn = fn;
921 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
923 PyInt len = ptr - str;
925 buffer_ensure(buffer_len + len + 1);
927 memcpy(buffer + buffer_len, str, len);
928 buffer_len += len;
929 buffer[buffer_len] = 0;
930 fn(buffer);
931 str = ptr + 1;
932 n -= len + 1;
933 buffer_len = 0;
936 /* Put the remaining text into the buffer for later printing */
937 buffer_ensure(buffer_len + n + 1);
938 memcpy(buffer + buffer_len, str, n);
939 buffer_len += n;
942 /***************/
944 static OutputObject Output =
946 PyObject_HEAD_INIT(&OutputType)
951 static OutputObject Error =
953 PyObject_HEAD_INIT(&OutputType)
958 static int
959 PythonIO_Init(void)
961 /* Fixups... */
962 OutputType.ob_type = &PyType_Type;
964 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
965 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
967 if (PyErr_Occurred())
969 EMSG(_("E264: Python: Error initialising I/O objects"));
970 return -1;
973 return 0;
976 /******************************************************
977 * 3. Implementation of the Vim module for Python
980 /* Vim module - Implementation functions
981 * -------------------------------------
984 static PyObject *VimError;
986 static PyObject *VimCommand(PyObject *, PyObject *);
987 static PyObject *VimEval(PyObject *, PyObject *);
989 /* Window type - Implementation functions
990 * --------------------------------------
993 typedef struct
995 PyObject_HEAD
996 win_T *win;
998 WindowObject;
1000 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1002 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1004 static PyObject *WindowNew(win_T *);
1006 static void WindowDestructor(PyObject *);
1007 static PyObject *WindowGetattr(PyObject *, char *);
1008 static int WindowSetattr(PyObject *, char *, PyObject *);
1009 static PyObject *WindowRepr(PyObject *);
1011 /* Buffer type - Implementation functions
1012 * --------------------------------------
1015 typedef struct
1017 PyObject_HEAD
1018 buf_T *buf;
1020 BufferObject;
1022 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1024 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1026 static PyObject *BufferNew (buf_T *);
1028 static void BufferDestructor(PyObject *);
1029 static PyObject *BufferGetattr(PyObject *, char *);
1030 static PyObject *BufferRepr(PyObject *);
1032 static PyInt BufferLength(PyObject *);
1033 static PyObject *BufferItem(PyObject *, PyInt);
1034 static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1035 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1036 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1038 static PyObject *BufferAppend(PyObject *, PyObject *);
1039 static PyObject *BufferMark(PyObject *, PyObject *);
1040 static PyObject *BufferRange(PyObject *, PyObject *);
1042 /* Line range type - Implementation functions
1043 * --------------------------------------
1046 typedef struct
1048 PyObject_HEAD
1049 BufferObject *buf;
1050 PyInt start;
1051 PyInt end;
1053 RangeObject;
1055 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1057 static PyObject *RangeNew(buf_T *, PyInt, PyInt);
1059 static void RangeDestructor(PyObject *);
1060 static PyObject *RangeGetattr(PyObject *, char *);
1061 static PyObject *RangeRepr(PyObject *);
1063 static PyInt RangeLength(PyObject *);
1064 static PyObject *RangeItem(PyObject *, PyInt);
1065 static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1066 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1067 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1069 static PyObject *RangeAppend(PyObject *, PyObject *);
1071 /* Window list type - Implementation functions
1072 * -------------------------------------------
1075 static PyInt WinListLength(PyObject *);
1076 static PyObject *WinListItem(PyObject *, PyInt);
1078 /* Buffer list type - Implementation functions
1079 * -------------------------------------------
1082 static PyInt BufListLength(PyObject *);
1083 static PyObject *BufListItem(PyObject *, PyInt);
1085 /* Current objects type - Implementation functions
1086 * -----------------------------------------------
1089 static PyObject *CurrentGetattr(PyObject *, char *);
1090 static int CurrentSetattr(PyObject *, char *, PyObject *);
1092 /* Vim module - Definitions
1095 static struct PyMethodDef VimMethods[] = {
1096 /* name, function, calling, documentation */
1097 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1098 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
1099 { NULL, NULL, 0, NULL }
1102 /* Vim module - Implementation
1104 static PyObject *
1105 VimCommand(PyObject *self UNUSED, PyObject *args)
1107 char *cmd;
1108 PyObject *result;
1110 if (!PyArg_ParseTuple(args, "s", &cmd))
1111 return NULL;
1113 PyErr_Clear();
1115 Py_BEGIN_ALLOW_THREADS
1116 Python_Lock_Vim();
1118 do_cmdline_cmd((char_u *)cmd);
1119 update_screen(VALID);
1121 Python_Release_Vim();
1122 Py_END_ALLOW_THREADS
1124 if (VimErrorCheck())
1125 result = NULL;
1126 else
1127 result = Py_None;
1129 Py_XINCREF(result);
1130 return result;
1133 #ifdef FEAT_EVAL
1135 * Function to translate a typval_T into a PyObject; this will recursively
1136 * translate lists/dictionaries into their Python equivalents.
1138 * The depth parameter is to avoid infinite recursion, set it to 1 when
1139 * you call VimToPython.
1141 static PyObject *
1142 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1144 PyObject *result;
1145 PyObject *newObj;
1146 char ptrBuf[NUMBUFLEN];
1148 /* Avoid infinite recursion */
1149 if (depth > 100)
1151 Py_INCREF(Py_None);
1152 result = Py_None;
1153 return result;
1156 /* Check if we run into a recursive loop. The item must be in lookupDict
1157 * then and we can use it again. */
1158 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1159 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1161 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
1162 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1163 : (long_u)our_tv->vval.v_dict);
1164 result = PyDict_GetItemString(lookupDict, ptrBuf);
1165 if (result != NULL)
1167 Py_INCREF(result);
1168 return result;
1172 if (our_tv->v_type == VAR_STRING)
1174 result = Py_BuildValue("s", our_tv->vval.v_string);
1176 else if (our_tv->v_type == VAR_NUMBER)
1178 char buf[NUMBUFLEN];
1180 /* For backwards compatibility numbers are stored as strings. */
1181 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1182 result = Py_BuildValue("s", buf);
1184 # ifdef FEAT_FLOAT
1185 else if (our_tv->v_type == VAR_FLOAT)
1187 char buf[NUMBUFLEN];
1189 sprintf(buf, "%f", our_tv->vval.v_float);
1190 result = Py_BuildValue("s", buf);
1192 # endif
1193 else if (our_tv->v_type == VAR_LIST)
1195 list_T *list = our_tv->vval.v_list;
1196 listitem_T *curr;
1198 result = PyList_New(0);
1200 if (list != NULL)
1202 PyDict_SetItemString(lookupDict, ptrBuf, result);
1204 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1206 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1207 PyList_Append(result, newObj);
1208 Py_DECREF(newObj);
1212 else if (our_tv->v_type == VAR_DICT)
1214 result = PyDict_New();
1216 if (our_tv->vval.v_dict != NULL)
1218 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1219 long_u todo = ht->ht_used;
1220 hashitem_T *hi;
1221 dictitem_T *di;
1223 PyDict_SetItemString(lookupDict, ptrBuf, result);
1225 for (hi = ht->ht_array; todo > 0; ++hi)
1227 if (!HASHITEM_EMPTY(hi))
1229 --todo;
1231 di = dict_lookup(hi);
1232 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1233 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1234 Py_DECREF(newObj);
1239 else
1241 Py_INCREF(Py_None);
1242 result = Py_None;
1245 return result;
1247 #endif
1249 static PyObject *
1250 VimEval(PyObject *self UNUSED, PyObject *args)
1252 #ifdef FEAT_EVAL
1253 char *expr;
1254 typval_T *our_tv;
1255 PyObject *result;
1256 PyObject *lookup_dict;
1258 if (!PyArg_ParseTuple(args, "s", &expr))
1259 return NULL;
1261 Py_BEGIN_ALLOW_THREADS
1262 Python_Lock_Vim();
1263 our_tv = eval_expr((char_u *)expr, NULL);
1265 Python_Release_Vim();
1266 Py_END_ALLOW_THREADS
1268 if (our_tv == NULL)
1270 PyErr_SetVim(_("invalid expression"));
1271 return NULL;
1274 /* Convert the Vim type into a Python type. Create a dictionary that's
1275 * used to check for recursive loops. */
1276 lookup_dict = PyDict_New();
1277 result = VimToPython(our_tv, 1, lookup_dict);
1278 Py_DECREF(lookup_dict);
1281 Py_BEGIN_ALLOW_THREADS
1282 Python_Lock_Vim();
1283 free_tv(our_tv);
1284 Python_Release_Vim();
1285 Py_END_ALLOW_THREADS
1287 return result;
1288 #else
1289 PyErr_SetVim(_("expressions disabled at compile time"));
1290 return NULL;
1291 #endif
1294 /* Common routines for buffers and line ranges
1295 * -------------------------------------------
1297 static int
1298 CheckBuffer(BufferObject *this)
1300 if (this->buf == INVALID_BUFFER_VALUE)
1302 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1303 return -1;
1306 return 0;
1309 static PyObject *
1310 RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
1312 if (CheckBuffer(self))
1313 return NULL;
1315 if (n < 0 || n > end - start)
1317 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1318 return NULL;
1321 return GetBufferLine(self->buf, n+start);
1324 static PyObject *
1325 RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
1327 PyInt size;
1329 if (CheckBuffer(self))
1330 return NULL;
1332 size = end - start + 1;
1334 if (lo < 0)
1335 lo = 0;
1336 else if (lo > size)
1337 lo = size;
1338 if (hi < 0)
1339 hi = 0;
1340 if (hi < lo)
1341 hi = lo;
1342 else if (hi > size)
1343 hi = size;
1345 return GetBufferLineList(self->buf, lo+start, hi+start);
1348 static PyInt
1349 RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1351 PyInt len_change;
1353 if (CheckBuffer(self))
1354 return -1;
1356 if (n < 0 || n > end - start)
1358 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1359 return -1;
1362 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1363 return -1;
1365 if (new_end)
1366 *new_end = end + len_change;
1368 return 0;
1371 static PyInt
1372 RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1374 PyInt size;
1375 PyInt len_change;
1377 /* Self must be a valid buffer */
1378 if (CheckBuffer(self))
1379 return -1;
1381 /* Sort out the slice range */
1382 size = end - start + 1;
1384 if (lo < 0)
1385 lo = 0;
1386 else if (lo > size)
1387 lo = size;
1388 if (hi < 0)
1389 hi = 0;
1390 if (hi < lo)
1391 hi = lo;
1392 else if (hi > size)
1393 hi = size;
1395 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1396 return -1;
1398 if (new_end)
1399 *new_end = end + len_change;
1401 return 0;
1404 static PyObject *
1405 RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
1407 PyObject *lines;
1408 PyInt len_change;
1409 PyInt max;
1410 PyInt n;
1412 if (CheckBuffer(self))
1413 return NULL;
1415 max = n = end - start + 1;
1417 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
1418 return NULL;
1420 if (n < 0 || n > max)
1422 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1423 return NULL;
1426 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1427 return NULL;
1429 if (new_end)
1430 *new_end = end + len_change;
1432 Py_INCREF(Py_None);
1433 return Py_None;
1437 /* Buffer object - Definitions
1440 static struct PyMethodDef BufferMethods[] = {
1441 /* name, function, calling, documentation */
1442 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1443 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1444 {"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1445 { NULL, NULL, 0, NULL }
1448 static PySequenceMethods BufferAsSeq = {
1449 (PyInquiry) BufferLength, /* sq_length, len(x) */
1450 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1451 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1452 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1453 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1454 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1455 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1458 static PyTypeObject BufferType = {
1459 PyObject_HEAD_INIT(0)
1461 "buffer",
1462 sizeof(BufferObject),
1465 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1466 (printfunc) 0, /* tp_print, print x */
1467 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1468 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1469 (cmpfunc) 0, /* tp_compare, x>y */
1470 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1472 0, /* as number */
1473 &BufferAsSeq, /* as sequence */
1474 0, /* as mapping */
1476 (hashfunc) 0, /* tp_hash, dict(x) */
1477 (ternaryfunc) 0, /* tp_call, x() */
1478 (reprfunc) 0, /* tp_str, str(x) */
1481 /* Buffer object - Implementation
1484 static PyObject *
1485 BufferNew(buf_T *buf)
1487 /* We need to handle deletion of buffers underneath us.
1488 * If we add a "b_python_ref" field to the buf_T structure,
1489 * then we can get at it in buf_freeall() in vim. We then
1490 * need to create only ONE Python object per buffer - if
1491 * we try to create a second, just INCREF the existing one
1492 * and return it. The (single) Python object referring to
1493 * the buffer is stored in "b_python_ref".
1494 * Question: what to do on a buf_freeall(). We'll probably
1495 * have to either delete the Python object (DECREF it to
1496 * zero - a bad idea, as it leaves dangling refs!) or
1497 * set the buf_T * value to an invalid value (-1?), which
1498 * means we need checks in all access functions... Bah.
1501 BufferObject *self;
1503 if (buf->b_python_ref != NULL)
1505 self = buf->b_python_ref;
1506 Py_INCREF(self);
1508 else
1510 self = PyObject_NEW(BufferObject, &BufferType);
1511 if (self == NULL)
1512 return NULL;
1513 self->buf = buf;
1514 buf->b_python_ref = self;
1517 return (PyObject *)(self);
1520 static void
1521 BufferDestructor(PyObject *self)
1523 BufferObject *this = (BufferObject *)(self);
1525 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1526 this->buf->b_python_ref = NULL;
1528 Py_DECREF(self);
1531 static PyObject *
1532 BufferGetattr(PyObject *self, char *name)
1534 BufferObject *this = (BufferObject *)(self);
1536 if (CheckBuffer(this))
1537 return NULL;
1539 if (strcmp(name, "name") == 0)
1540 return Py_BuildValue("s", this->buf->b_ffname);
1541 else if (strcmp(name, "number") == 0)
1542 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
1543 else if (strcmp(name,"__members__") == 0)
1544 return Py_BuildValue("[ss]", "name", "number");
1545 else
1546 return Py_FindMethod(BufferMethods, self, name);
1549 static PyObject *
1550 BufferRepr(PyObject *self)
1552 static char repr[100];
1553 BufferObject *this = (BufferObject *)(self);
1555 if (this->buf == INVALID_BUFFER_VALUE)
1557 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
1558 return PyString_FromString(repr);
1560 else
1562 char *name = (char *)this->buf->b_fname;
1563 PyInt len;
1565 if (name == NULL)
1566 name = "";
1567 len = strlen(name);
1569 if (len > 35)
1570 name = name + (35 - len);
1572 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1574 return PyString_FromString(repr);
1578 /******************/
1580 static PyInt
1581 BufferLength(PyObject *self)
1583 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1584 if (CheckBuffer((BufferObject *)(self)))
1585 return -1; /* ??? */
1587 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1590 static PyObject *
1591 BufferItem(PyObject *self, PyInt n)
1593 return RBItem((BufferObject *)(self), n, 1,
1594 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1597 static PyObject *
1598 BufferSlice(PyObject *self, PyInt lo, PyInt hi)
1600 return RBSlice((BufferObject *)(self), lo, hi, 1,
1601 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1604 static PyInt
1605 BufferAssItem(PyObject *self, PyInt n, PyObject *val)
1607 return RBAssItem((BufferObject *)(self), n, val, 1,
1608 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1609 NULL);
1612 static PyInt
1613 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1615 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1616 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1617 NULL);
1620 static PyObject *
1621 BufferAppend(PyObject *self, PyObject *args)
1623 return RBAppend((BufferObject *)(self), args, 1,
1624 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1625 NULL);
1628 static PyObject *
1629 BufferMark(PyObject *self, PyObject *args)
1631 pos_T *posp;
1632 char mark;
1633 buf_T *curbuf_save;
1635 if (CheckBuffer((BufferObject *)(self)))
1636 return NULL;
1638 if (!PyArg_ParseTuple(args, "c", &mark))
1639 return NULL;
1641 curbuf_save = curbuf;
1642 curbuf = ((BufferObject *)(self))->buf;
1643 posp = getmark(mark, FALSE);
1644 curbuf = curbuf_save;
1646 if (posp == NULL)
1648 PyErr_SetVim(_("invalid mark name"));
1649 return NULL;
1652 /* Ckeck for keyboard interrupt */
1653 if (VimErrorCheck())
1654 return NULL;
1656 if (posp->lnum <= 0)
1658 /* Or raise an error? */
1659 Py_INCREF(Py_None);
1660 return Py_None;
1663 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1666 static PyObject *
1667 BufferRange(PyObject *self, PyObject *args)
1669 PyInt start;
1670 PyInt end;
1672 if (CheckBuffer((BufferObject *)(self)))
1673 return NULL;
1675 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
1676 return NULL;
1678 return RangeNew(((BufferObject *)(self))->buf, start, end);
1681 /* Line range object - Definitions
1684 static struct PyMethodDef RangeMethods[] = {
1685 /* name, function, calling, documentation */
1686 {"append", RangeAppend, 1, "Append data to the Vim range" },
1687 { NULL, NULL, 0, NULL }
1690 static PySequenceMethods RangeAsSeq = {
1691 (PyInquiry) RangeLength, /* sq_length, len(x) */
1692 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1693 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1694 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1695 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1696 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1697 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1700 static PyTypeObject RangeType = {
1701 PyObject_HEAD_INIT(0)
1703 "range",
1704 sizeof(RangeObject),
1707 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1708 (printfunc) 0, /* tp_print, print x */
1709 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1710 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1711 (cmpfunc) 0, /* tp_compare, x>y */
1712 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1714 0, /* as number */
1715 &RangeAsSeq, /* as sequence */
1716 0, /* as mapping */
1718 (hashfunc) 0, /* tp_hash, dict(x) */
1719 (ternaryfunc) 0, /* tp_call, x() */
1720 (reprfunc) 0, /* tp_str, str(x) */
1723 /* Line range object - Implementation
1726 static PyObject *
1727 RangeNew(buf_T *buf, PyInt start, PyInt end)
1729 BufferObject *bufr;
1730 RangeObject *self;
1731 self = PyObject_NEW(RangeObject, &RangeType);
1732 if (self == NULL)
1733 return NULL;
1735 bufr = (BufferObject *)BufferNew(buf);
1736 if (bufr == NULL)
1738 Py_DECREF(self);
1739 return NULL;
1741 Py_INCREF(bufr);
1743 self->buf = bufr;
1744 self->start = start;
1745 self->end = end;
1747 return (PyObject *)(self);
1750 static void
1751 RangeDestructor(PyObject *self)
1753 Py_DECREF(((RangeObject *)(self))->buf);
1754 Py_DECREF(self);
1757 static PyObject *
1758 RangeGetattr(PyObject *self, char *name)
1760 if (strcmp(name, "start") == 0)
1761 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
1762 else if (strcmp(name, "end") == 0)
1763 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
1764 else
1765 return Py_FindMethod(RangeMethods, self, name);
1768 static PyObject *
1769 RangeRepr(PyObject *self)
1771 static char repr[100];
1772 RangeObject *this = (RangeObject *)(self);
1774 if (this->buf->buf == INVALID_BUFFER_VALUE)
1776 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1777 (self));
1778 return PyString_FromString(repr);
1780 else
1782 char *name = (char *)this->buf->buf->b_fname;
1783 int len;
1785 if (name == NULL)
1786 name = "";
1787 len = (int)strlen(name);
1789 if (len > 45)
1790 name = name + (45 - len);
1792 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1793 len > 45 ? "..." : "", name,
1794 this->start, this->end);
1796 return PyString_FromString(repr);
1800 /****************/
1802 static PyInt
1803 RangeLength(PyObject *self)
1805 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1806 if (CheckBuffer(((RangeObject *)(self))->buf))
1807 return -1; /* ??? */
1809 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1812 static PyObject *
1813 RangeItem(PyObject *self, PyInt n)
1815 return RBItem(((RangeObject *)(self))->buf, n,
1816 ((RangeObject *)(self))->start,
1817 ((RangeObject *)(self))->end);
1820 static PyObject *
1821 RangeSlice(PyObject *self, PyInt lo, PyInt hi)
1823 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1824 ((RangeObject *)(self))->start,
1825 ((RangeObject *)(self))->end);
1828 static PyInt
1829 RangeAssItem(PyObject *self, PyInt n, PyObject *val)
1831 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1832 ((RangeObject *)(self))->start,
1833 ((RangeObject *)(self))->end,
1834 &((RangeObject *)(self))->end);
1837 static PyInt
1838 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1840 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1841 ((RangeObject *)(self))->start,
1842 ((RangeObject *)(self))->end,
1843 &((RangeObject *)(self))->end);
1846 static PyObject *
1847 RangeAppend(PyObject *self, PyObject *args)
1849 return RBAppend(((RangeObject *)(self))->buf, args,
1850 ((RangeObject *)(self))->start,
1851 ((RangeObject *)(self))->end,
1852 &((RangeObject *)(self))->end);
1855 /* Buffer list object - Definitions
1858 typedef struct
1860 PyObject_HEAD
1862 BufListObject;
1864 static PySequenceMethods BufListAsSeq = {
1865 (PyInquiry) BufListLength, /* sq_length, len(x) */
1866 (binaryfunc) 0, /* sq_concat, x+y */
1867 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1868 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1869 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1870 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1871 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1874 static PyTypeObject BufListType = {
1875 PyObject_HEAD_INIT(0)
1877 "buffer list",
1878 sizeof(BufListObject),
1881 (destructor) 0, /* tp_dealloc, refcount==0 */
1882 (printfunc) 0, /* tp_print, print x */
1883 (getattrfunc) 0, /* tp_getattr, x.attr */
1884 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1885 (cmpfunc) 0, /* tp_compare, x>y */
1886 (reprfunc) 0, /* tp_repr, `x`, print x */
1888 0, /* as number */
1889 &BufListAsSeq, /* as sequence */
1890 0, /* as mapping */
1892 (hashfunc) 0, /* tp_hash, dict(x) */
1893 (ternaryfunc) 0, /* tp_call, x() */
1894 (reprfunc) 0, /* tp_str, str(x) */
1897 /* Buffer list object - Implementation
1900 static PyInt
1901 BufListLength(PyObject *self UNUSED)
1903 buf_T *b = firstbuf;
1904 PyInt n = 0;
1906 while (b)
1908 ++n;
1909 b = b->b_next;
1912 return n;
1915 static PyObject *
1916 BufListItem(PyObject *self UNUSED, PyInt n)
1918 buf_T *b;
1920 for (b = firstbuf; b; b = b->b_next, --n)
1922 if (n == 0)
1923 return BufferNew(b);
1926 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1927 return NULL;
1930 /* Window object - Definitions
1933 static struct PyMethodDef WindowMethods[] = {
1934 /* name, function, calling, documentation */
1935 { NULL, NULL, 0, NULL }
1938 static PyTypeObject WindowType = {
1939 PyObject_HEAD_INIT(0)
1941 "window",
1942 sizeof(WindowObject),
1945 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1946 (printfunc) 0, /* tp_print, print x */
1947 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1948 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1949 (cmpfunc) 0, /* tp_compare, x>y */
1950 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1952 0, /* as number */
1953 0, /* as sequence */
1954 0, /* as mapping */
1956 (hashfunc) 0, /* tp_hash, dict(x) */
1957 (ternaryfunc) 0, /* tp_call, x() */
1958 (reprfunc) 0, /* tp_str, str(x) */
1961 /* Window object - Implementation
1964 static PyObject *
1965 WindowNew(win_T *win)
1967 /* We need to handle deletion of windows underneath us.
1968 * If we add a "w_python_ref" field to the win_T structure,
1969 * then we can get at it in win_free() in vim. We then
1970 * need to create only ONE Python object per window - if
1971 * we try to create a second, just INCREF the existing one
1972 * and return it. The (single) Python object referring to
1973 * the window is stored in "w_python_ref".
1974 * On a win_free() we set the Python object's win_T* field
1975 * to an invalid value. We trap all uses of a window
1976 * object, and reject them if the win_T* field is invalid.
1979 WindowObject *self;
1981 if (win->w_python_ref)
1983 self = win->w_python_ref;
1984 Py_INCREF(self);
1986 else
1988 self = PyObject_NEW(WindowObject, &WindowType);
1989 if (self == NULL)
1990 return NULL;
1991 self->win = win;
1992 win->w_python_ref = self;
1995 return (PyObject *)(self);
1998 static void
1999 WindowDestructor(PyObject *self)
2001 WindowObject *this = (WindowObject *)(self);
2003 if (this->win && this->win != INVALID_WINDOW_VALUE)
2004 this->win->w_python_ref = NULL;
2006 Py_DECREF(self);
2009 static int
2010 CheckWindow(WindowObject *this)
2012 if (this->win == INVALID_WINDOW_VALUE)
2014 PyErr_SetVim(_("attempt to refer to deleted window"));
2015 return -1;
2018 return 0;
2021 static PyObject *
2022 WindowGetattr(PyObject *self, char *name)
2024 WindowObject *this = (WindowObject *)(self);
2026 if (CheckWindow(this))
2027 return NULL;
2029 if (strcmp(name, "buffer") == 0)
2030 return (PyObject *)BufferNew(this->win->w_buffer);
2031 else if (strcmp(name, "cursor") == 0)
2033 pos_T *pos = &this->win->w_cursor;
2035 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2037 else if (strcmp(name, "height") == 0)
2038 return Py_BuildValue("l", (long)(this->win->w_height));
2039 #ifdef FEAT_VERTSPLIT
2040 else if (strcmp(name, "width") == 0)
2041 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2042 #endif
2043 else if (strcmp(name,"__members__") == 0)
2044 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2045 else
2046 return Py_FindMethod(WindowMethods, self, name);
2049 static int
2050 WindowSetattr(PyObject *self, char *name, PyObject *val)
2052 WindowObject *this = (WindowObject *)(self);
2054 if (CheckWindow(this))
2055 return -1;
2057 if (strcmp(name, "buffer") == 0)
2059 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2060 return -1;
2062 else if (strcmp(name, "cursor") == 0)
2064 long lnum;
2065 long col;
2067 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2068 return -1;
2070 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2072 PyErr_SetVim(_("cursor position outside buffer"));
2073 return -1;
2076 /* Check for keyboard interrupts */
2077 if (VimErrorCheck())
2078 return -1;
2080 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2082 this->win->w_cursor.lnum = lnum;
2083 this->win->w_cursor.col = col;
2084 update_screen(VALID);
2086 return 0;
2088 else if (strcmp(name, "height") == 0)
2090 int height;
2091 win_T *savewin;
2093 if (!PyArg_Parse(val, "i", &height))
2094 return -1;
2096 #ifdef FEAT_GUI
2097 need_mouse_correct = TRUE;
2098 #endif
2099 savewin = curwin;
2100 curwin = this->win;
2101 win_setheight(height);
2102 curwin = savewin;
2104 /* Check for keyboard interrupts */
2105 if (VimErrorCheck())
2106 return -1;
2108 return 0;
2110 #ifdef FEAT_VERTSPLIT
2111 else if (strcmp(name, "width") == 0)
2113 int width;
2114 win_T *savewin;
2116 if (!PyArg_Parse(val, "i", &width))
2117 return -1;
2119 #ifdef FEAT_GUI
2120 need_mouse_correct = TRUE;
2121 #endif
2122 savewin = curwin;
2123 curwin = this->win;
2124 win_setwidth(width);
2125 curwin = savewin;
2127 /* Check for keyboard interrupts */
2128 if (VimErrorCheck())
2129 return -1;
2131 return 0;
2133 #endif
2134 else
2136 PyErr_SetString(PyExc_AttributeError, name);
2137 return -1;
2141 static PyObject *
2142 WindowRepr(PyObject *self)
2144 static char repr[100];
2145 WindowObject *this = (WindowObject *)(self);
2147 if (this->win == INVALID_WINDOW_VALUE)
2149 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
2150 return PyString_FromString(repr);
2152 else
2154 int i = 0;
2155 win_T *w;
2157 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2158 ++i;
2160 if (w == NULL)
2161 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2162 (self));
2163 else
2164 vim_snprintf(repr, 100, _("<window %d>"), i);
2166 return PyString_FromString(repr);
2170 /* Window list object - Definitions
2173 typedef struct
2175 PyObject_HEAD
2177 WinListObject;
2179 static PySequenceMethods WinListAsSeq = {
2180 (PyInquiry) WinListLength, /* sq_length, len(x) */
2181 (binaryfunc) 0, /* sq_concat, x+y */
2182 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2183 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2184 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2185 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2186 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
2189 static PyTypeObject WinListType = {
2190 PyObject_HEAD_INIT(0)
2192 "window list",
2193 sizeof(WinListObject),
2196 (destructor) 0, /* tp_dealloc, refcount==0 */
2197 (printfunc) 0, /* tp_print, print x */
2198 (getattrfunc) 0, /* tp_getattr, x.attr */
2199 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2200 (cmpfunc) 0, /* tp_compare, x>y */
2201 (reprfunc) 0, /* tp_repr, `x`, print x */
2203 0, /* as number */
2204 &WinListAsSeq, /* as sequence */
2205 0, /* as mapping */
2207 (hashfunc) 0, /* tp_hash, dict(x) */
2208 (ternaryfunc) 0, /* tp_call, x() */
2209 (reprfunc) 0, /* tp_str, str(x) */
2212 /* Window list object - Implementation
2214 static PyInt
2215 WinListLength(PyObject *self UNUSED)
2217 win_T *w = firstwin;
2218 PyInt n = 0;
2220 while (w != NULL)
2222 ++n;
2223 w = W_NEXT(w);
2226 return n;
2229 static PyObject *
2230 WinListItem(PyObject *self UNUSED, PyInt n)
2232 win_T *w;
2234 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2235 if (n == 0)
2236 return WindowNew(w);
2238 PyErr_SetString(PyExc_IndexError, _("no such window"));
2239 return NULL;
2242 /* Current items object - Definitions
2245 typedef struct
2247 PyObject_HEAD
2249 CurrentObject;
2251 static PyTypeObject CurrentType = {
2252 PyObject_HEAD_INIT(0)
2254 "current data",
2255 sizeof(CurrentObject),
2258 (destructor) 0, /* tp_dealloc, refcount==0 */
2259 (printfunc) 0, /* tp_print, print x */
2260 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2261 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2262 (cmpfunc) 0, /* tp_compare, x>y */
2263 (reprfunc) 0, /* tp_repr, `x`, print x */
2265 0, /* as number */
2266 0, /* as sequence */
2267 0, /* as mapping */
2269 (hashfunc) 0, /* tp_hash, dict(x) */
2270 (ternaryfunc) 0, /* tp_call, x() */
2271 (reprfunc) 0, /* tp_str, str(x) */
2274 /* Current items object - Implementation
2276 static PyObject *
2277 CurrentGetattr(PyObject *self UNUSED, char *name)
2279 if (strcmp(name, "buffer") == 0)
2280 return (PyObject *)BufferNew(curbuf);
2281 else if (strcmp(name, "window") == 0)
2282 return (PyObject *)WindowNew(curwin);
2283 else if (strcmp(name, "line") == 0)
2284 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2285 else if (strcmp(name, "range") == 0)
2286 return RangeNew(curbuf, RangeStart, RangeEnd);
2287 else if (strcmp(name,"__members__") == 0)
2288 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2289 else
2291 PyErr_SetString(PyExc_AttributeError, name);
2292 return NULL;
2296 static int
2297 CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2299 if (strcmp(name, "line") == 0)
2301 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2302 return -1;
2304 return 0;
2306 else
2308 PyErr_SetString(PyExc_AttributeError, name);
2309 return -1;
2313 /* External interface
2316 void
2317 python_buffer_free(buf_T *buf)
2319 if (buf->b_python_ref != NULL)
2321 BufferObject *bp = buf->b_python_ref;
2322 bp->buf = INVALID_BUFFER_VALUE;
2323 buf->b_python_ref = NULL;
2327 #if defined(FEAT_WINDOWS) || defined(PROTO)
2328 void
2329 python_window_free(win_T *win)
2331 if (win->w_python_ref != NULL)
2333 WindowObject *wp = win->w_python_ref;
2334 wp->win = INVALID_WINDOW_VALUE;
2335 win->w_python_ref = NULL;
2338 #endif
2340 static BufListObject TheBufferList =
2342 PyObject_HEAD_INIT(&BufListType)
2345 static WinListObject TheWindowList =
2347 PyObject_HEAD_INIT(&WinListType)
2350 static CurrentObject TheCurrent =
2352 PyObject_HEAD_INIT(&CurrentType)
2355 static int
2356 PythonMod_Init(void)
2358 PyObject *mod;
2359 PyObject *dict;
2360 /* The special value is removed from sys.path in Python_Init(). */
2361 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
2363 /* Fixups... */
2364 BufferType.ob_type = &PyType_Type;
2365 RangeType.ob_type = &PyType_Type;
2366 WindowType.ob_type = &PyType_Type;
2367 BufListType.ob_type = &PyType_Type;
2368 WinListType.ob_type = &PyType_Type;
2369 CurrentType.ob_type = &PyType_Type;
2371 /* Set sys.argv[] to avoid a crash in warn(). */
2372 PySys_SetArgv(1, argv);
2374 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
2375 dict = PyModule_GetDict(mod);
2377 VimError = Py_BuildValue("s", "vim.error");
2379 PyDict_SetItemString(dict, "error", VimError);
2380 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2381 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2382 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
2384 if (PyErr_Occurred())
2385 return -1;
2387 return 0;
2390 /*************************************************************************
2391 * 4. Utility functions for handling the interface between Vim and Python.
2394 /* Get a line from the specified buffer. The line number is
2395 * in Vim format (1-based). The line is returned as a Python
2396 * string object.
2398 static PyObject *
2399 GetBufferLine(buf_T *buf, PyInt n)
2401 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2404 /* Get a list of lines from the specified buffer. The line numbers
2405 * are in Vim format (1-based). The range is from lo up to, but not
2406 * including, hi. The list is returned as a Python list of string objects.
2408 static PyObject *
2409 GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2411 PyInt i;
2412 PyInt n = hi - lo;
2413 PyObject *list = PyList_New(n);
2415 if (list == NULL)
2416 return NULL;
2418 for (i = 0; i < n; ++i)
2420 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2422 /* Error check - was the Python string creation OK? */
2423 if (str == NULL)
2425 Py_DECREF(list);
2426 return NULL;
2429 /* Set the list item */
2430 if (PyList_SetItem(list, i, str))
2432 Py_DECREF(str);
2433 Py_DECREF(list);
2434 return NULL;
2438 /* The ownership of the Python list is passed to the caller (ie,
2439 * the caller should Py_DECREF() the object when it is finished
2440 * with it).
2443 return list;
2447 * Check if deleting lines made the cursor position invalid.
2448 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2449 * deleted).
2451 static void
2452 py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2454 if (curwin->w_cursor.lnum >= lo)
2456 /* Adjust the cursor position if it's in/after the changed
2457 * lines. */
2458 if (curwin->w_cursor.lnum >= hi)
2460 curwin->w_cursor.lnum += extra;
2461 check_cursor_col();
2463 else if (extra < 0)
2465 curwin->w_cursor.lnum = lo;
2466 check_cursor();
2468 else
2469 check_cursor_col();
2470 changed_cline_bef_curs();
2472 invalidate_botline();
2475 /* Replace a line in the specified buffer. The line number is
2476 * in Vim format (1-based). The replacement line is given as
2477 * a Python string object. The object is checked for validity
2478 * and correct format. Errors are returned as a value of FAIL.
2479 * The return value is OK on success.
2480 * If OK is returned and len_change is not NULL, *len_change
2481 * is set to the change in the buffer length.
2483 static int
2484 SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2486 /* First of all, we check the thpe of the supplied Python object.
2487 * There are three cases:
2488 * 1. NULL, or None - this is a deletion.
2489 * 2. A string - this is a replacement.
2490 * 3. Anything else - this is an error.
2492 if (line == Py_None || line == NULL)
2494 buf_T *savebuf = curbuf;
2496 PyErr_Clear();
2497 curbuf = buf;
2499 if (u_savedel((linenr_T)n, 1L) == FAIL)
2500 PyErr_SetVim(_("cannot save undo information"));
2501 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2502 PyErr_SetVim(_("cannot delete line"));
2503 else
2505 if (buf == curwin->w_buffer)
2506 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2507 deleted_lines_mark((linenr_T)n, 1L);
2510 curbuf = savebuf;
2512 if (PyErr_Occurred() || VimErrorCheck())
2513 return FAIL;
2515 if (len_change)
2516 *len_change = -1;
2518 return OK;
2520 else if (PyString_Check(line))
2522 char *save = StringToLine(line);
2523 buf_T *savebuf = curbuf;
2525 if (save == NULL)
2526 return FAIL;
2528 /* We do not need to free "save" if ml_replace() consumes it. */
2529 PyErr_Clear();
2530 curbuf = buf;
2532 if (u_savesub((linenr_T)n) == FAIL)
2534 PyErr_SetVim(_("cannot save undo information"));
2535 vim_free(save);
2537 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2539 PyErr_SetVim(_("cannot replace line"));
2540 vim_free(save);
2542 else
2543 changed_bytes((linenr_T)n, 0);
2545 curbuf = savebuf;
2547 /* Check that the cursor is not beyond the end of the line now. */
2548 if (buf == curwin->w_buffer)
2549 check_cursor_col();
2551 if (PyErr_Occurred() || VimErrorCheck())
2552 return FAIL;
2554 if (len_change)
2555 *len_change = 0;
2557 return OK;
2559 else
2561 PyErr_BadArgument();
2562 return FAIL;
2566 /* Replace a range of lines in the specified buffer. The line numbers are in
2567 * Vim format (1-based). The range is from lo up to, but not including, hi.
2568 * The replacement lines are given as a Python list of string objects. The
2569 * list is checked for validity and correct format. Errors are returned as a
2570 * value of FAIL. The return value is OK on success.
2571 * If OK is returned and len_change is not NULL, *len_change
2572 * is set to the change in the buffer length.
2574 static int
2575 SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2577 /* First of all, we check the thpe of the supplied Python object.
2578 * There are three cases:
2579 * 1. NULL, or None - this is a deletion.
2580 * 2. A list - this is a replacement.
2581 * 3. Anything else - this is an error.
2583 if (list == Py_None || list == NULL)
2585 PyInt i;
2586 PyInt n = (int)(hi - lo);
2587 buf_T *savebuf = curbuf;
2589 PyErr_Clear();
2590 curbuf = buf;
2592 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2593 PyErr_SetVim(_("cannot save undo information"));
2594 else
2596 for (i = 0; i < n; ++i)
2598 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2600 PyErr_SetVim(_("cannot delete line"));
2601 break;
2604 if (buf == curwin->w_buffer)
2605 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2606 deleted_lines_mark((linenr_T)lo, (long)i);
2609 curbuf = savebuf;
2611 if (PyErr_Occurred() || VimErrorCheck())
2612 return FAIL;
2614 if (len_change)
2615 *len_change = -n;
2617 return OK;
2619 else if (PyList_Check(list))
2621 PyInt i;
2622 PyInt new_len = PyList_Size(list);
2623 PyInt old_len = hi - lo;
2624 PyInt extra = 0; /* lines added to text, can be negative */
2625 char **array;
2626 buf_T *savebuf;
2628 if (new_len == 0) /* avoid allocating zero bytes */
2629 array = NULL;
2630 else
2632 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2633 if (array == NULL)
2635 PyErr_NoMemory();
2636 return FAIL;
2640 for (i = 0; i < new_len; ++i)
2642 PyObject *line = PyList_GetItem(list, i);
2644 array[i] = StringToLine(line);
2645 if (array[i] == NULL)
2647 while (i)
2648 vim_free(array[--i]);
2649 vim_free(array);
2650 return FAIL;
2654 savebuf = curbuf;
2656 PyErr_Clear();
2657 curbuf = buf;
2659 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2660 PyErr_SetVim(_("cannot save undo information"));
2662 /* If the size of the range is reducing (ie, new_len < old_len) we
2663 * need to delete some old_len. We do this at the start, by
2664 * repeatedly deleting line "lo".
2666 if (!PyErr_Occurred())
2668 for (i = 0; i < old_len - new_len; ++i)
2669 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2671 PyErr_SetVim(_("cannot delete line"));
2672 break;
2674 extra -= i;
2677 /* For as long as possible, replace the existing old_len with the
2678 * new old_len. This is a more efficient operation, as it requires
2679 * less memory allocation and freeing.
2681 if (!PyErr_Occurred())
2683 for (i = 0; i < old_len && i < new_len; ++i)
2684 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2685 == FAIL)
2687 PyErr_SetVim(_("cannot replace line"));
2688 break;
2691 else
2692 i = 0;
2694 /* Now we may need to insert the remaining new old_len. If we do, we
2695 * must free the strings as we finish with them (we can't pass the
2696 * responsibility to vim in this case).
2698 if (!PyErr_Occurred())
2700 while (i < new_len)
2702 if (ml_append((linenr_T)(lo + i - 1),
2703 (char_u *)array[i], 0, FALSE) == FAIL)
2705 PyErr_SetVim(_("cannot insert line"));
2706 break;
2708 vim_free(array[i]);
2709 ++i;
2710 ++extra;
2714 /* Free any left-over old_len, as a result of an error */
2715 while (i < new_len)
2717 vim_free(array[i]);
2718 ++i;
2721 /* Free the array of old_len. All of its contents have now
2722 * been dealt with (either freed, or the responsibility passed
2723 * to vim.
2725 vim_free(array);
2727 /* Adjust marks. Invalidate any which lie in the
2728 * changed range, and move any in the remainder of the buffer.
2730 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2731 (long)MAXLNUM, (long)extra);
2732 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2734 if (buf == curwin->w_buffer)
2735 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2737 curbuf = savebuf;
2739 if (PyErr_Occurred() || VimErrorCheck())
2740 return FAIL;
2742 if (len_change)
2743 *len_change = new_len - old_len;
2745 return OK;
2747 else
2749 PyErr_BadArgument();
2750 return FAIL;
2754 /* Insert a number of lines into the specified buffer after the specifed line.
2755 * The line number is in Vim format (1-based). The lines to be inserted are
2756 * given as a Python list of string objects or as a single string. The lines
2757 * to be added are checked for validity and correct format. Errors are
2758 * returned as a value of FAIL. The return value is OK on success.
2759 * If OK is returned and len_change is not NULL, *len_change
2760 * is set to the change in the buffer length.
2762 static int
2763 InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2765 /* First of all, we check the type of the supplied Python object.
2766 * It must be a string or a list, or the call is in error.
2768 if (PyString_Check(lines))
2770 char *str = StringToLine(lines);
2771 buf_T *savebuf;
2773 if (str == NULL)
2774 return FAIL;
2776 savebuf = curbuf;
2778 PyErr_Clear();
2779 curbuf = buf;
2781 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2782 PyErr_SetVim(_("cannot save undo information"));
2783 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2784 PyErr_SetVim(_("cannot insert line"));
2785 else
2786 appended_lines_mark((linenr_T)n, 1L);
2788 vim_free(str);
2789 curbuf = savebuf;
2790 update_screen(VALID);
2792 if (PyErr_Occurred() || VimErrorCheck())
2793 return FAIL;
2795 if (len_change)
2796 *len_change = 1;
2798 return OK;
2800 else if (PyList_Check(lines))
2802 PyInt i;
2803 PyInt size = PyList_Size(lines);
2804 char **array;
2805 buf_T *savebuf;
2807 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2808 if (array == NULL)
2810 PyErr_NoMemory();
2811 return FAIL;
2814 for (i = 0; i < size; ++i)
2816 PyObject *line = PyList_GetItem(lines, i);
2817 array[i] = StringToLine(line);
2819 if (array[i] == NULL)
2821 while (i)
2822 vim_free(array[--i]);
2823 vim_free(array);
2824 return FAIL;
2828 savebuf = curbuf;
2830 PyErr_Clear();
2831 curbuf = buf;
2833 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2834 PyErr_SetVim(_("cannot save undo information"));
2835 else
2837 for (i = 0; i < size; ++i)
2839 if (ml_append((linenr_T)(n + i),
2840 (char_u *)array[i], 0, FALSE) == FAIL)
2842 PyErr_SetVim(_("cannot insert line"));
2844 /* Free the rest of the lines */
2845 while (i < size)
2846 vim_free(array[i++]);
2848 break;
2850 vim_free(array[i]);
2852 if (i > 0)
2853 appended_lines_mark((linenr_T)n, (long)i);
2856 /* Free the array of lines. All of its contents have now
2857 * been freed.
2859 vim_free(array);
2861 curbuf = savebuf;
2862 update_screen(VALID);
2864 if (PyErr_Occurred() || VimErrorCheck())
2865 return FAIL;
2867 if (len_change)
2868 *len_change = size;
2870 return OK;
2872 else
2874 PyErr_BadArgument();
2875 return FAIL;
2879 /* Convert a Vim line into a Python string.
2880 * All internal newlines are replaced by null characters.
2882 * On errors, the Python exception data is set, and NULL is returned.
2884 static PyObject *
2885 LineToString(const char *str)
2887 PyObject *result;
2888 PyInt len = strlen(str);
2889 char *p;
2891 /* Allocate an Python string object, with uninitialised contents. We
2892 * must do it this way, so that we can modify the string in place
2893 * later. See the Python source, Objects/stringobject.c for details.
2895 result = PyString_FromStringAndSize(NULL, len);
2896 if (result == NULL)
2897 return NULL;
2899 p = PyString_AsString(result);
2901 while (*str)
2903 if (*str == '\n')
2904 *p = '\0';
2905 else
2906 *p = *str;
2908 ++p;
2909 ++str;
2912 return result;
2915 /* Convert a Python string into a Vim line.
2917 * The result is in allocated memory. All internal nulls are replaced by
2918 * newline characters. It is an error for the string to contain newline
2919 * characters.
2921 * On errors, the Python exception data is set, and NULL is returned.
2923 static char *
2924 StringToLine(PyObject *obj)
2926 const char *str;
2927 char *save;
2928 PyInt len;
2929 PyInt i;
2930 char *p;
2932 if (obj == NULL || !PyString_Check(obj))
2934 PyErr_BadArgument();
2935 return NULL;
2938 str = PyString_AsString(obj);
2939 len = PyString_Size(obj);
2942 * Error checking: String must not contain newlines, as we
2943 * are replacing a single line, and we must replace it with
2944 * a single line.
2945 * A trailing newline is removed, so that append(f.readlines()) works.
2947 p = memchr(str, '\n', len);
2948 if (p != NULL)
2950 if (p == str + len - 1)
2951 --len;
2952 else
2954 PyErr_SetVim(_("string cannot contain newlines"));
2955 return NULL;
2959 /* Create a copy of the string, with internal nulls replaced by
2960 * newline characters, as is the vim convention.
2962 save = (char *)alloc((unsigned)(len+1));
2963 if (save == NULL)
2965 PyErr_NoMemory();
2966 return NULL;
2969 for (i = 0; i < len; ++i)
2971 if (str[i] == '\0')
2972 save[i] = '\n';
2973 else
2974 save[i] = str[i];
2977 save[i] = '\0';
2979 return save;
2982 /* Check to see whether a Vim error has been reported, or a keyboard
2983 * interrupt has been detected.
2985 static int
2986 VimErrorCheck(void)
2988 if (got_int)
2990 PyErr_SetNone(PyExc_KeyboardInterrupt);
2991 return 1;
2993 else if (did_emsg && !PyErr_Occurred())
2995 PyErr_SetNone(VimError);
2996 return 1;
2999 return 0;
3003 /* Don't generate a prototype for the next function, it generates an error on
3004 * newer Python versions. */
3005 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3007 char *
3008 Py_GetProgramName(void)
3010 return "vim";
3012 #endif /* Python 1.4 */