c9ebf1312604a00bdc4f9e802e554fbdaf266704
[MacVim.git] / src / if_python.c
blobc9ebf1312604a00bdc4f9e802e554fbdaf266704
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
40 #ifdef _POSIX_C_SOURCE
41 # undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
42 #endif
43 #ifdef _XOPEN_SOURCE
44 # undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
45 #endif
47 #define PY_SSIZE_T_CLEAN
49 #include <Python.h>
50 #if defined(MACOS) && !defined(MACOS_X_UNIX)
51 # include "macglue.h"
52 # include <CodeFragments.h>
53 #endif
54 #undef main /* Defined in python.h - aargh */
55 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
57 #if !defined(FEAT_PYTHON) && defined(PROTO)
58 /* Use this to be able to generate prototypes without python being used. */
59 # define PyObject Py_ssize_t
60 # define PyThreadState Py_ssize_t
61 # define PyTypeObject Py_ssize_t
62 struct PyMethodDef { Py_ssize_t a; };
63 # define PySequenceMethods Py_ssize_t
64 #endif
66 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
67 # define PyInt Py_ssize_t
68 # define PyInquiry lenfunc
69 # define PyIntArgFunc ssizeargfunc
70 # define PyIntIntArgFunc ssizessizeargfunc
71 # define PyIntObjArgProc ssizeobjargproc
72 # define PyIntIntObjArgProc ssizessizeobjargproc
73 # define Py_ssize_t_fmt "n"
74 #else
75 # define PyInt int
76 # define PyInquiry inquiry
77 # define PyIntArgFunc intargfunc
78 # define PyIntIntArgFunc intintargfunc
79 # define PyIntObjArgProc intobjargproc
80 # define PyIntIntObjArgProc intintobjargproc
81 # define Py_ssize_t_fmt "i"
82 #endif
84 /* Parser flags */
85 #define single_input 256
86 #define file_input 257
87 #define eval_input 258
89 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
90 /* Python 2.3: can invoke ":python" recursively. */
91 # define PY_CAN_RECURSE
92 #endif
94 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
95 # ifndef DYNAMIC_PYTHON
96 # define HINSTANCE long_u /* for generating prototypes */
97 # endif
99 /* This makes if_python.c compile without warnings against Python 2.5
100 * on Win32 and Win64. */
101 #undef PyRun_SimpleString
102 #undef PyArg_Parse
103 #undef PyArg_ParseTuple
104 #undef Py_BuildValue
105 #undef Py_InitModule4
106 #undef Py_InitModule4_64
109 * Wrapper defines
111 # define PyArg_Parse dll_PyArg_Parse
112 # define PyArg_ParseTuple dll_PyArg_ParseTuple
113 # define PyDict_SetItemString dll_PyDict_SetItemString
114 # define PyErr_BadArgument dll_PyErr_BadArgument
115 # define PyErr_Clear dll_PyErr_Clear
116 # define PyErr_NoMemory dll_PyErr_NoMemory
117 # define PyErr_Occurred dll_PyErr_Occurred
118 # define PyErr_SetNone dll_PyErr_SetNone
119 # define PyErr_SetString dll_PyErr_SetString
120 # define PyEval_InitThreads dll_PyEval_InitThreads
121 # define PyEval_RestoreThread dll_PyEval_RestoreThread
122 # define PyEval_SaveThread dll_PyEval_SaveThread
123 # ifdef PY_CAN_RECURSE
124 # define PyGILState_Ensure dll_PyGILState_Ensure
125 # define PyGILState_Release dll_PyGILState_Release
126 # endif
127 # define PyInt_AsLong dll_PyInt_AsLong
128 # define PyInt_FromLong dll_PyInt_FromLong
129 # define PyInt_Type (*dll_PyInt_Type)
130 # define PyList_GetItem dll_PyList_GetItem
131 # define PyList_Append dll_PyList_Append
132 # define PyList_New dll_PyList_New
133 # define PyList_SetItem dll_PyList_SetItem
134 # define PyList_Size dll_PyList_Size
135 # define PyList_Type (*dll_PyList_Type)
136 # define PyImport_ImportModule dll_PyImport_ImportModule
137 # define PyDict_New dll_PyDict_New
138 # define PyDict_GetItemString dll_PyDict_GetItemString
139 # define PyModule_GetDict dll_PyModule_GetDict
140 # define PyRun_SimpleString dll_PyRun_SimpleString
141 # define PyString_AsString dll_PyString_AsString
142 # define PyString_FromString dll_PyString_FromString
143 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
144 # define PyString_Size dll_PyString_Size
145 # define PyString_Type (*dll_PyString_Type)
146 # define PySys_SetObject dll_PySys_SetObject
147 # define PySys_SetArgv dll_PySys_SetArgv
148 # define PyType_Type (*dll_PyType_Type)
149 # define Py_BuildValue dll_Py_BuildValue
150 # define Py_FindMethod dll_Py_FindMethod
151 # define Py_InitModule4 dll_Py_InitModule4
152 # define Py_Initialize dll_Py_Initialize
153 # define Py_Finalize dll_Py_Finalize
154 # define Py_IsInitialized dll_Py_IsInitialized
155 # define _PyObject_New dll__PyObject_New
156 # define _Py_NoneStruct (*dll__Py_NoneStruct)
157 # define PyObject_Init dll__PyObject_Init
158 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
159 # define PyType_IsSubtype dll_PyType_IsSubtype
160 # endif
161 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
162 # define PyObject_Malloc dll_PyObject_Malloc
163 # define PyObject_Free dll_PyObject_Free
164 # endif
167 * Pointers for dynamic link
169 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
170 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
171 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
172 static int(*dll_PyErr_BadArgument)(void);
173 static void(*dll_PyErr_Clear)(void);
174 static PyObject*(*dll_PyErr_NoMemory)(void);
175 static PyObject*(*dll_PyErr_Occurred)(void);
176 static void(*dll_PyErr_SetNone)(PyObject *);
177 static void(*dll_PyErr_SetString)(PyObject *, const char *);
178 static void(*dll_PyEval_InitThreads)(void);
179 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
180 static PyThreadState*(*dll_PyEval_SaveThread)(void);
181 # ifdef PY_CAN_RECURSE
182 static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
183 static void (*dll_PyGILState_Release)(PyGILState_STATE);
184 #endif
185 static long(*dll_PyInt_AsLong)(PyObject *);
186 static PyObject*(*dll_PyInt_FromLong)(long);
187 static PyTypeObject* dll_PyInt_Type;
188 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
189 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
190 static PyObject*(*dll_PyList_New)(PyInt size);
191 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
192 static PyInt(*dll_PyList_Size)(PyObject *);
193 static PyTypeObject* dll_PyList_Type;
194 static PyObject*(*dll_PyImport_ImportModule)(const char *);
195 static PyObject*(*dll_PyDict_New)(void);
196 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
197 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
198 static int(*dll_PyRun_SimpleString)(char *);
199 static char*(*dll_PyString_AsString)(PyObject *);
200 static PyObject*(*dll_PyString_FromString)(const char *);
201 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
202 static PyInt(*dll_PyString_Size)(PyObject *);
203 static PyTypeObject* dll_PyString_Type;
204 static int(*dll_PySys_SetObject)(char *, PyObject *);
205 static int(*dll_PySys_SetArgv)(int, char **);
206 static PyTypeObject* dll_PyType_Type;
207 static PyObject*(*dll_Py_BuildValue)(char *, ...);
208 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
209 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
210 static void(*dll_Py_Initialize)(void);
211 static void(*dll_Py_Finalize)(void);
212 static int(*dll_Py_IsInitialized)(void);
213 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
214 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
215 static PyObject* dll__Py_NoneStruct;
216 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
217 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
218 # endif
219 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
220 static void* (*dll_PyObject_Malloc)(size_t);
221 static void (*dll_PyObject_Free)(void*);
222 # endif
224 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
226 /* Imported exception objects */
227 static PyObject *imp_PyExc_AttributeError;
228 static PyObject *imp_PyExc_IndexError;
229 static PyObject *imp_PyExc_KeyboardInterrupt;
230 static PyObject *imp_PyExc_TypeError;
231 static PyObject *imp_PyExc_ValueError;
233 # define PyExc_AttributeError imp_PyExc_AttributeError
234 # define PyExc_IndexError imp_PyExc_IndexError
235 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
236 # define PyExc_TypeError imp_PyExc_TypeError
237 # define PyExc_ValueError imp_PyExc_ValueError
240 * Table of name to function pointer of python.
242 # define PYTHON_PROC FARPROC
243 static struct
245 char *name;
246 PYTHON_PROC *ptr;
247 } python_funcname_table[] =
249 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
250 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
251 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
252 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
253 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
254 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
255 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
256 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
257 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
258 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
259 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
260 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
261 # ifdef PY_CAN_RECURSE
262 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
263 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
264 # endif
265 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
266 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
267 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
268 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
269 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
270 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
271 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
272 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
273 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
274 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
275 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
276 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
277 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
278 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
279 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
280 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
281 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
282 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
283 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
284 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
285 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
286 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
287 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
288 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
289 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
290 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
291 # else
292 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
293 # endif
294 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
295 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
296 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
297 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
298 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
299 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
300 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
301 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
302 # endif
303 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
304 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
305 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
306 # endif
307 {"", NULL},
311 * Free python.dll
313 static void
314 end_dynamic_python(void)
316 if (hinstPython)
318 FreeLibrary(hinstPython);
319 hinstPython = 0;
324 * Load library and get all pointers.
325 * Parameter 'libname' provides name of DLL.
326 * Return OK or FAIL.
328 static int
329 python_runtime_link_init(char *libname, int verbose)
331 int i;
333 if (hinstPython)
334 return OK;
335 hinstPython = LoadLibrary(libname);
336 if (!hinstPython)
338 if (verbose)
339 EMSG2(_(e_loadlib), libname);
340 return FAIL;
343 for (i = 0; python_funcname_table[i].ptr; ++i)
345 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
346 python_funcname_table[i].name)) == NULL)
348 FreeLibrary(hinstPython);
349 hinstPython = 0;
350 if (verbose)
351 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
352 return FAIL;
355 return OK;
359 * If python is enabled (there is installed python on Windows system) return
360 * TRUE, else FALSE.
363 python_enabled(int verbose)
365 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
368 /* Load the standard Python exceptions - don't import the symbols from the
369 * DLL, as this can cause errors (importing data symbols is not reliable).
371 static void get_exceptions __ARGS((void));
373 static void
374 get_exceptions()
376 PyObject *exmod = PyImport_ImportModule("exceptions");
377 PyObject *exdict = PyModule_GetDict(exmod);
378 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
379 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
380 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
381 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
382 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
383 Py_XINCREF(imp_PyExc_AttributeError);
384 Py_XINCREF(imp_PyExc_IndexError);
385 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
386 Py_XINCREF(imp_PyExc_TypeError);
387 Py_XINCREF(imp_PyExc_ValueError);
388 Py_XDECREF(exmod);
390 #endif /* DYNAMIC_PYTHON */
392 /******************************************************
393 * Internal function prototypes.
396 static void DoPythonCommand(exarg_T *, const char *);
397 static PyInt RangeStart;
398 static PyInt RangeEnd;
400 static void PythonIO_Flush(void);
401 static int PythonIO_Init(void);
402 static int PythonMod_Init(void);
404 /* Utility functions for the vim/python interface
405 * ----------------------------------------------
407 static PyObject *GetBufferLine(buf_T *, PyInt);
408 static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
410 static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
411 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
412 static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
414 static PyObject *LineToString(const char *);
415 static char *StringToLine(PyObject *);
417 static int VimErrorCheck(void);
419 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
421 /******************************************************
422 * 1. Python interpreter main program.
425 static int initialised = 0;
427 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
428 typedef PyObject PyThreadState;
429 #endif
431 #ifdef PY_CAN_RECURSE
432 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
433 #else
434 static PyThreadState *saved_python_thread = NULL;
435 #endif
438 * Suspend a thread of the Python interpreter, other threads are allowed to
439 * run.
441 static void
442 Python_SaveThread(void)
444 #ifdef PY_CAN_RECURSE
445 PyGILState_Release(pygilstate);
446 #else
447 saved_python_thread = PyEval_SaveThread();
448 #endif
452 * Restore a thread of the Python interpreter, waits for other threads to
453 * block.
455 static void
456 Python_RestoreThread(void)
458 #ifdef PY_CAN_RECURSE
459 pygilstate = PyGILState_Ensure();
460 #else
461 PyEval_RestoreThread(saved_python_thread);
462 saved_python_thread = NULL;
463 #endif
467 * obtain a lock on the Vim data structures
469 static void Python_Lock_Vim(void)
474 * release a lock on the Vim data structures
476 static void Python_Release_Vim(void)
480 void
481 python_end()
483 static int recurse = 0;
485 /* If a crash occurs while doing this, don't try again. */
486 if (recurse != 0)
487 return;
489 ++recurse;
491 #ifdef DYNAMIC_PYTHON
492 if (hinstPython && Py_IsInitialized())
494 Python_RestoreThread(); /* enter python */
495 Py_Finalize();
497 end_dynamic_python();
498 #else
499 if (Py_IsInitialized())
501 Python_RestoreThread(); /* enter python */
502 Py_Finalize();
504 #endif
506 --recurse;
509 static int
510 Python_Init(void)
512 if (!initialised)
514 #ifdef DYNAMIC_PYTHON
515 if (!python_enabled(TRUE))
517 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
518 goto fail;
520 #endif
522 #if !defined(MACOS) || defined(MACOS_X_UNIX)
523 Py_Initialize();
524 #else
525 PyMac_Initialize();
526 #endif
527 /* initialise threads */
528 PyEval_InitThreads();
530 #ifdef DYNAMIC_PYTHON
531 get_exceptions();
532 #endif
534 if (PythonIO_Init())
535 goto fail;
537 if (PythonMod_Init())
538 goto fail;
540 /* Remove the element from sys.path that was added because of our
541 * argv[0] value in PythonMod_Init(). Previously we used an empty
542 * string, but dependinding on the OS we then get an empty entry or
543 * the current directory in sys.path. */
544 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
546 /* the first python thread is vim's, release the lock */
547 Python_SaveThread();
549 initialised = 1;
552 return 0;
554 fail:
555 /* We call PythonIO_Flush() here to print any Python errors.
556 * This is OK, as it is possible to call this function even
557 * if PythonIO_Init() has not completed successfully (it will
558 * not do anything in this case).
560 PythonIO_Flush();
561 return -1;
565 * External interface
567 static void
568 DoPythonCommand(exarg_T *eap, const char *cmd)
570 #ifndef PY_CAN_RECURSE
571 static int recursive = 0;
572 #endif
573 #if defined(MACOS) && !defined(MACOS_X_UNIX)
574 GrafPtr oldPort;
575 #endif
576 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
577 char *saved_locale;
578 #endif
580 #ifndef PY_CAN_RECURSE
581 if (recursive)
583 EMSG(_("E659: Cannot invoke Python recursively"));
584 return;
586 ++recursive;
587 #endif
589 #if defined(MACOS) && !defined(MACOS_X_UNIX)
590 GetPort(&oldPort);
591 /* Check if the Python library is available */
592 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
593 goto theend;
594 #endif
595 if (Python_Init())
596 goto theend;
598 RangeStart = eap->line1;
599 RangeEnd = eap->line2;
600 Python_Release_Vim(); /* leave vim */
602 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
603 /* Python only works properly when the LC_NUMERIC locale is "C". */
604 saved_locale = setlocale(LC_NUMERIC, NULL);
605 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
606 saved_locale = NULL;
607 else
609 /* Need to make a copy, value may change when setting new locale. */
610 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
611 (void)setlocale(LC_NUMERIC, "C");
613 #endif
615 Python_RestoreThread(); /* enter python */
617 PyRun_SimpleString((char *)(cmd));
619 Python_SaveThread(); /* leave python */
621 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
622 if (saved_locale != NULL)
624 (void)setlocale(LC_NUMERIC, saved_locale);
625 vim_free(saved_locale);
627 #endif
629 Python_Lock_Vim(); /* enter vim */
630 PythonIO_Flush();
631 #if defined(MACOS) && !defined(MACOS_X_UNIX)
632 SetPort(oldPort);
633 #endif
635 theend:
636 #ifndef PY_CAN_RECURSE
637 --recursive;
638 #endif
639 return; /* keeps lint happy */
643 * ":python"
645 void
646 ex_python(exarg_T *eap)
648 char_u *script;
650 script = script_get(eap, eap->arg);
651 if (!eap->skip)
653 if (script == NULL)
654 DoPythonCommand(eap, (char *)eap->arg);
655 else
656 DoPythonCommand(eap, (char *)script);
658 vim_free(script);
661 #define BUFFER_SIZE 1024
664 * ":pyfile"
666 void
667 ex_pyfile(exarg_T *eap)
669 static char buffer[BUFFER_SIZE];
670 const char *file = (char *)eap->arg;
671 char *p;
673 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
674 * stdio file pointer, but Vim and the Python DLL are compiled with
675 * different options under Windows, meaning that stdio pointers aren't
676 * compatible between the two. Yuk.
678 * Put the string "execfile('file')" into buffer. But, we need to
679 * escape any backslashes or single quotes in the file name, so that
680 * Python won't mangle the file name.
682 strcpy(buffer, "execfile('");
683 p = buffer + 10; /* size of "execfile('" */
685 while (*file && p < buffer + (BUFFER_SIZE - 3))
687 if (*file == '\\' || *file == '\'')
688 *p++ = '\\';
689 *p++ = *file++;
692 /* If we didn't finish the file name, we hit a buffer overflow */
693 if (*file != '\0')
694 return;
696 /* Put in the terminating "')" and a null */
697 *p++ = '\'';
698 *p++ = ')';
699 *p++ = '\0';
701 /* Execute the file */
702 DoPythonCommand(eap, buffer);
705 /******************************************************
706 * 2. Python output stream: writes output via [e]msg().
709 /* Implementation functions
712 static PyObject *OutputGetattr(PyObject *, char *);
713 static int OutputSetattr(PyObject *, char *, PyObject *);
715 static PyObject *OutputWrite(PyObject *, PyObject *);
716 static PyObject *OutputWritelines(PyObject *, PyObject *);
718 typedef void (*writefn)(char_u *);
719 static void writer(writefn fn, char_u *str, PyInt n);
721 /* Output object definition
724 typedef struct
726 PyObject_HEAD
727 long softspace;
728 long error;
729 } OutputObject;
731 static struct PyMethodDef OutputMethods[] = {
732 /* name, function, calling, documentation */
733 {"write", OutputWrite, 1, "" },
734 {"writelines", OutputWritelines, 1, "" },
735 { NULL, NULL, 0, NULL }
738 static PyTypeObject OutputType = {
739 PyObject_HEAD_INIT(0)
741 "message",
742 sizeof(OutputObject),
745 (destructor) 0,
746 (printfunc) 0,
747 (getattrfunc) OutputGetattr,
748 (setattrfunc) OutputSetattr,
749 (cmpfunc) 0,
750 (reprfunc) 0,
752 0, /* as number */
753 0, /* as sequence */
754 0, /* as mapping */
756 (hashfunc) 0,
757 (ternaryfunc) 0,
758 (reprfunc) 0
761 /*************/
763 static PyObject *
764 OutputGetattr(PyObject *self, char *name)
766 if (strcmp(name, "softspace") == 0)
767 return PyInt_FromLong(((OutputObject *)(self))->softspace);
769 return Py_FindMethod(OutputMethods, self, name);
772 static int
773 OutputSetattr(PyObject *self, char *name, PyObject *val)
775 if (val == NULL) {
776 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
777 return -1;
780 if (strcmp(name, "softspace") == 0)
782 if (!PyInt_Check(val)) {
783 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
784 return -1;
787 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
788 return 0;
791 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
792 return -1;
795 /*************/
797 static PyObject *
798 OutputWrite(PyObject *self, PyObject *args)
800 int len;
801 char *str;
802 int error = ((OutputObject *)(self))->error;
804 if (!PyArg_ParseTuple(args, "s#", &str, &len))
805 return NULL;
807 Py_BEGIN_ALLOW_THREADS
808 Python_Lock_Vim();
809 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
810 Python_Release_Vim();
811 Py_END_ALLOW_THREADS
813 Py_INCREF(Py_None);
814 return Py_None;
817 static PyObject *
818 OutputWritelines(PyObject *self, PyObject *args)
820 PyInt n;
821 PyInt i;
822 PyObject *list;
823 int error = ((OutputObject *)(self))->error;
825 if (!PyArg_ParseTuple(args, "O", &list))
826 return NULL;
827 Py_INCREF(list);
829 if (!PyList_Check(list)) {
830 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
831 Py_DECREF(list);
832 return NULL;
835 n = PyList_Size(list);
837 for (i = 0; i < n; ++i)
839 PyObject *line = PyList_GetItem(list, i);
840 char *str;
841 PyInt len;
843 if (!PyArg_Parse(line, "s#", &str, &len)) {
844 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
845 Py_DECREF(list);
846 return NULL;
849 Py_BEGIN_ALLOW_THREADS
850 Python_Lock_Vim();
851 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
852 Python_Release_Vim();
853 Py_END_ALLOW_THREADS
856 Py_DECREF(list);
857 Py_INCREF(Py_None);
858 return Py_None;
861 /* Output buffer management
864 static char_u *buffer = NULL;
865 static PyInt buffer_len = 0;
866 static PyInt buffer_size = 0;
868 static writefn old_fn = NULL;
870 static void
871 buffer_ensure(PyInt n)
873 PyInt new_size;
874 char_u *new_buffer;
876 if (n < buffer_size)
877 return;
879 new_size = buffer_size;
880 while (new_size < n)
881 new_size += 80;
883 if (new_size != buffer_size)
885 new_buffer = alloc((unsigned)new_size);
886 if (new_buffer == NULL)
887 return;
889 if (buffer)
891 memcpy(new_buffer, buffer, buffer_len);
892 vim_free(buffer);
895 buffer = new_buffer;
896 buffer_size = new_size;
900 static void
901 PythonIO_Flush(void)
903 if (old_fn && buffer_len)
905 buffer[buffer_len] = 0;
906 old_fn(buffer);
909 buffer_len = 0;
912 static void
913 writer(writefn fn, char_u *str, PyInt n)
915 char_u *ptr;
917 if (fn != old_fn && old_fn != NULL)
918 PythonIO_Flush();
920 old_fn = fn;
922 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
924 PyInt len = ptr - str;
926 buffer_ensure(buffer_len + len + 1);
928 memcpy(buffer + buffer_len, str, len);
929 buffer_len += len;
930 buffer[buffer_len] = 0;
931 fn(buffer);
932 str = ptr + 1;
933 n -= len + 1;
934 buffer_len = 0;
937 /* Put the remaining text into the buffer for later printing */
938 buffer_ensure(buffer_len + n + 1);
939 memcpy(buffer + buffer_len, str, n);
940 buffer_len += n;
943 /***************/
945 static OutputObject Output =
947 PyObject_HEAD_INIT(&OutputType)
952 static OutputObject Error =
954 PyObject_HEAD_INIT(&OutputType)
959 static int
960 PythonIO_Init(void)
962 /* Fixups... */
963 OutputType.ob_type = &PyType_Type;
965 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
966 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
968 if (PyErr_Occurred())
970 EMSG(_("E264: Python: Error initialising I/O objects"));
971 return -1;
974 return 0;
977 /******************************************************
978 * 3. Implementation of the Vim module for Python
981 /* Vim module - Implementation functions
982 * -------------------------------------
985 static PyObject *VimError;
987 static PyObject *VimCommand(PyObject *, PyObject *);
988 static PyObject *VimEval(PyObject *, PyObject *);
990 /* Window type - Implementation functions
991 * --------------------------------------
994 typedef struct
996 PyObject_HEAD
997 win_T *win;
999 WindowObject;
1001 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1003 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1005 static PyObject *WindowNew(win_T *);
1007 static void WindowDestructor(PyObject *);
1008 static PyObject *WindowGetattr(PyObject *, char *);
1009 static int WindowSetattr(PyObject *, char *, PyObject *);
1010 static PyObject *WindowRepr(PyObject *);
1012 /* Buffer type - Implementation functions
1013 * --------------------------------------
1016 typedef struct
1018 PyObject_HEAD
1019 buf_T *buf;
1021 BufferObject;
1023 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1025 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1027 static PyObject *BufferNew (buf_T *);
1029 static void BufferDestructor(PyObject *);
1030 static PyObject *BufferGetattr(PyObject *, char *);
1031 static PyObject *BufferRepr(PyObject *);
1033 static PyInt BufferLength(PyObject *);
1034 static PyObject *BufferItem(PyObject *, PyInt);
1035 static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1036 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1037 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1039 static PyObject *BufferAppend(PyObject *, PyObject *);
1040 static PyObject *BufferMark(PyObject *, PyObject *);
1041 static PyObject *BufferRange(PyObject *, PyObject *);
1043 /* Line range type - Implementation functions
1044 * --------------------------------------
1047 typedef struct
1049 PyObject_HEAD
1050 BufferObject *buf;
1051 PyInt start;
1052 PyInt end;
1054 RangeObject;
1056 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1058 static PyObject *RangeNew(buf_T *, PyInt, PyInt);
1060 static void RangeDestructor(PyObject *);
1061 static PyObject *RangeGetattr(PyObject *, char *);
1062 static PyObject *RangeRepr(PyObject *);
1064 static PyInt RangeLength(PyObject *);
1065 static PyObject *RangeItem(PyObject *, PyInt);
1066 static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1067 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1068 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1070 static PyObject *RangeAppend(PyObject *, PyObject *);
1072 /* Window list type - Implementation functions
1073 * -------------------------------------------
1076 static PyInt WinListLength(PyObject *);
1077 static PyObject *WinListItem(PyObject *, PyInt);
1079 /* Buffer list type - Implementation functions
1080 * -------------------------------------------
1083 static PyInt BufListLength(PyObject *);
1084 static PyObject *BufListItem(PyObject *, PyInt);
1086 /* Current objects type - Implementation functions
1087 * -----------------------------------------------
1090 static PyObject *CurrentGetattr(PyObject *, char *);
1091 static int CurrentSetattr(PyObject *, char *, PyObject *);
1093 /* Vim module - Definitions
1096 static struct PyMethodDef VimMethods[] = {
1097 /* name, function, calling, documentation */
1098 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1099 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
1100 { NULL, NULL, 0, NULL }
1103 /* Vim module - Implementation
1105 static PyObject *
1106 VimCommand(PyObject *self UNUSED, PyObject *args)
1108 char *cmd;
1109 PyObject *result;
1111 if (!PyArg_ParseTuple(args, "s", &cmd))
1112 return NULL;
1114 PyErr_Clear();
1116 Py_BEGIN_ALLOW_THREADS
1117 Python_Lock_Vim();
1119 do_cmdline_cmd((char_u *)cmd);
1120 update_screen(VALID);
1122 Python_Release_Vim();
1123 Py_END_ALLOW_THREADS
1125 if (VimErrorCheck())
1126 result = NULL;
1127 else
1128 result = Py_None;
1130 Py_XINCREF(result);
1131 return result;
1134 #ifdef FEAT_EVAL
1136 * Function to translate a typval_T into a PyObject; this will recursively
1137 * translate lists/dictionaries into their Python equivalents.
1139 * The depth parameter is to avoid infinite recursion, set it to 1 when
1140 * you call VimToPython.
1142 static PyObject *
1143 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1145 PyObject *result;
1146 PyObject *newObj;
1147 char ptrBuf[NUMBUFLEN];
1149 /* Avoid infinite recursion */
1150 if (depth > 100)
1152 Py_INCREF(Py_None);
1153 result = Py_None;
1154 return result;
1157 /* Check if we run into a recursive loop. The item must be in lookupDict
1158 * then and we can use it again. */
1159 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1160 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1162 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
1163 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1164 : (long_u)our_tv->vval.v_dict);
1165 result = PyDict_GetItemString(lookupDict, ptrBuf);
1166 if (result != NULL)
1168 Py_INCREF(result);
1169 return result;
1173 if (our_tv->v_type == VAR_STRING)
1175 result = Py_BuildValue("s", our_tv->vval.v_string);
1177 else if (our_tv->v_type == VAR_NUMBER)
1179 char buf[NUMBUFLEN];
1181 /* For backwards compatibility numbers are stored as strings. */
1182 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1183 result = Py_BuildValue("s", buf);
1185 # ifdef FEAT_FLOAT
1186 else if (our_tv->v_type == VAR_FLOAT)
1188 char buf[NUMBUFLEN];
1190 sprintf(buf, "%f", our_tv->vval.v_float);
1191 result = Py_BuildValue("s", buf);
1193 # endif
1194 else if (our_tv->v_type == VAR_LIST)
1196 list_T *list = our_tv->vval.v_list;
1197 listitem_T *curr;
1199 result = PyList_New(0);
1201 if (list != NULL)
1203 PyDict_SetItemString(lookupDict, ptrBuf, result);
1205 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1207 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1208 PyList_Append(result, newObj);
1209 Py_DECREF(newObj);
1213 else if (our_tv->v_type == VAR_DICT)
1215 result = PyDict_New();
1217 if (our_tv->vval.v_dict != NULL)
1219 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1220 long_u todo = ht->ht_used;
1221 hashitem_T *hi;
1222 dictitem_T *di;
1224 PyDict_SetItemString(lookupDict, ptrBuf, result);
1226 for (hi = ht->ht_array; todo > 0; ++hi)
1228 if (!HASHITEM_EMPTY(hi))
1230 --todo;
1232 di = dict_lookup(hi);
1233 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1234 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1235 Py_DECREF(newObj);
1240 else
1242 Py_INCREF(Py_None);
1243 result = Py_None;
1246 return result;
1248 #endif
1250 static PyObject *
1251 VimEval(PyObject *self UNUSED, PyObject *args)
1253 #ifdef FEAT_EVAL
1254 char *expr;
1255 typval_T *our_tv;
1256 PyObject *result;
1257 PyObject *lookup_dict;
1259 if (!PyArg_ParseTuple(args, "s", &expr))
1260 return NULL;
1262 Py_BEGIN_ALLOW_THREADS
1263 Python_Lock_Vim();
1264 our_tv = eval_expr((char_u *)expr, NULL);
1266 Python_Release_Vim();
1267 Py_END_ALLOW_THREADS
1269 if (our_tv == NULL)
1271 PyErr_SetVim(_("invalid expression"));
1272 return NULL;
1275 /* Convert the Vim type into a Python type. Create a dictionary that's
1276 * used to check for recursive loops. */
1277 lookup_dict = PyDict_New();
1278 result = VimToPython(our_tv, 1, lookup_dict);
1279 Py_DECREF(lookup_dict);
1282 Py_BEGIN_ALLOW_THREADS
1283 Python_Lock_Vim();
1284 free_tv(our_tv);
1285 Python_Release_Vim();
1286 Py_END_ALLOW_THREADS
1288 return result;
1289 #else
1290 PyErr_SetVim(_("expressions disabled at compile time"));
1291 return NULL;
1292 #endif
1295 /* Common routines for buffers and line ranges
1296 * -------------------------------------------
1298 static int
1299 CheckBuffer(BufferObject *this)
1301 if (this->buf == INVALID_BUFFER_VALUE)
1303 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1304 return -1;
1307 return 0;
1310 static PyObject *
1311 RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
1313 if (CheckBuffer(self))
1314 return NULL;
1316 if (n < 0 || n > end - start)
1318 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1319 return NULL;
1322 return GetBufferLine(self->buf, n+start);
1325 static PyObject *
1326 RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
1328 PyInt size;
1330 if (CheckBuffer(self))
1331 return NULL;
1333 size = end - start + 1;
1335 if (lo < 0)
1336 lo = 0;
1337 else if (lo > size)
1338 lo = size;
1339 if (hi < 0)
1340 hi = 0;
1341 if (hi < lo)
1342 hi = lo;
1343 else if (hi > size)
1344 hi = size;
1346 return GetBufferLineList(self->buf, lo+start, hi+start);
1349 static PyInt
1350 RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1352 PyInt len_change;
1354 if (CheckBuffer(self))
1355 return -1;
1357 if (n < 0 || n > end - start)
1359 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1360 return -1;
1363 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1364 return -1;
1366 if (new_end)
1367 *new_end = end + len_change;
1369 return 0;
1372 static PyInt
1373 RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1375 PyInt size;
1376 PyInt len_change;
1378 /* Self must be a valid buffer */
1379 if (CheckBuffer(self))
1380 return -1;
1382 /* Sort out the slice range */
1383 size = end - start + 1;
1385 if (lo < 0)
1386 lo = 0;
1387 else if (lo > size)
1388 lo = size;
1389 if (hi < 0)
1390 hi = 0;
1391 if (hi < lo)
1392 hi = lo;
1393 else if (hi > size)
1394 hi = size;
1396 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1397 return -1;
1399 if (new_end)
1400 *new_end = end + len_change;
1402 return 0;
1405 static PyObject *
1406 RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
1408 PyObject *lines;
1409 PyInt len_change;
1410 PyInt max;
1411 PyInt n;
1413 if (CheckBuffer(self))
1414 return NULL;
1416 max = n = end - start + 1;
1418 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
1419 return NULL;
1421 if (n < 0 || n > max)
1423 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1424 return NULL;
1427 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1428 return NULL;
1430 if (new_end)
1431 *new_end = end + len_change;
1433 Py_INCREF(Py_None);
1434 return Py_None;
1438 /* Buffer object - Definitions
1441 static struct PyMethodDef BufferMethods[] = {
1442 /* name, function, calling, documentation */
1443 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1444 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1445 {"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1446 { NULL, NULL, 0, NULL }
1449 static PySequenceMethods BufferAsSeq = {
1450 (PyInquiry) BufferLength, /* sq_length, len(x) */
1451 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1452 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1453 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1454 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1455 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1456 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1459 static PyTypeObject BufferType = {
1460 PyObject_HEAD_INIT(0)
1462 "buffer",
1463 sizeof(BufferObject),
1466 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1467 (printfunc) 0, /* tp_print, print x */
1468 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1469 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1470 (cmpfunc) 0, /* tp_compare, x>y */
1471 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1473 0, /* as number */
1474 &BufferAsSeq, /* as sequence */
1475 0, /* as mapping */
1477 (hashfunc) 0, /* tp_hash, dict(x) */
1478 (ternaryfunc) 0, /* tp_call, x() */
1479 (reprfunc) 0, /* tp_str, str(x) */
1482 /* Buffer object - Implementation
1485 static PyObject *
1486 BufferNew(buf_T *buf)
1488 /* We need to handle deletion of buffers underneath us.
1489 * If we add a "b_python_ref" field to the buf_T structure,
1490 * then we can get at it in buf_freeall() in vim. We then
1491 * need to create only ONE Python object per buffer - if
1492 * we try to create a second, just INCREF the existing one
1493 * and return it. The (single) Python object referring to
1494 * the buffer is stored in "b_python_ref".
1495 * Question: what to do on a buf_freeall(). We'll probably
1496 * have to either delete the Python object (DECREF it to
1497 * zero - a bad idea, as it leaves dangling refs!) or
1498 * set the buf_T * value to an invalid value (-1?), which
1499 * means we need checks in all access functions... Bah.
1502 BufferObject *self;
1504 if (buf->b_python_ref != NULL)
1506 self = buf->b_python_ref;
1507 Py_INCREF(self);
1509 else
1511 self = PyObject_NEW(BufferObject, &BufferType);
1512 if (self == NULL)
1513 return NULL;
1514 self->buf = buf;
1515 buf->b_python_ref = self;
1518 return (PyObject *)(self);
1521 static void
1522 BufferDestructor(PyObject *self)
1524 BufferObject *this = (BufferObject *)(self);
1526 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1527 this->buf->b_python_ref = NULL;
1529 Py_DECREF(self);
1532 static PyObject *
1533 BufferGetattr(PyObject *self, char *name)
1535 BufferObject *this = (BufferObject *)(self);
1537 if (CheckBuffer(this))
1538 return NULL;
1540 if (strcmp(name, "name") == 0)
1541 return Py_BuildValue("s", this->buf->b_ffname);
1542 else if (strcmp(name, "number") == 0)
1543 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
1544 else if (strcmp(name,"__members__") == 0)
1545 return Py_BuildValue("[ss]", "name", "number");
1546 else
1547 return Py_FindMethod(BufferMethods, self, name);
1550 static PyObject *
1551 BufferRepr(PyObject *self)
1553 static char repr[100];
1554 BufferObject *this = (BufferObject *)(self);
1556 if (this->buf == INVALID_BUFFER_VALUE)
1558 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
1559 return PyString_FromString(repr);
1561 else
1563 char *name = (char *)this->buf->b_fname;
1564 PyInt len;
1566 if (name == NULL)
1567 name = "";
1568 len = strlen(name);
1570 if (len > 35)
1571 name = name + (35 - len);
1573 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1575 return PyString_FromString(repr);
1579 /******************/
1581 static PyInt
1582 BufferLength(PyObject *self)
1584 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1585 if (CheckBuffer((BufferObject *)(self)))
1586 return -1; /* ??? */
1588 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1591 static PyObject *
1592 BufferItem(PyObject *self, PyInt n)
1594 return RBItem((BufferObject *)(self), n, 1,
1595 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1598 static PyObject *
1599 BufferSlice(PyObject *self, PyInt lo, PyInt hi)
1601 return RBSlice((BufferObject *)(self), lo, hi, 1,
1602 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1605 static PyInt
1606 BufferAssItem(PyObject *self, PyInt n, PyObject *val)
1608 return RBAssItem((BufferObject *)(self), n, val, 1,
1609 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1610 NULL);
1613 static PyInt
1614 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1616 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1617 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1618 NULL);
1621 static PyObject *
1622 BufferAppend(PyObject *self, PyObject *args)
1624 return RBAppend((BufferObject *)(self), args, 1,
1625 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1626 NULL);
1629 static PyObject *
1630 BufferMark(PyObject *self, PyObject *args)
1632 pos_T *posp;
1633 char mark;
1634 buf_T *curbuf_save;
1636 if (CheckBuffer((BufferObject *)(self)))
1637 return NULL;
1639 if (!PyArg_ParseTuple(args, "c", &mark))
1640 return NULL;
1642 curbuf_save = curbuf;
1643 curbuf = ((BufferObject *)(self))->buf;
1644 posp = getmark(mark, FALSE);
1645 curbuf = curbuf_save;
1647 if (posp == NULL)
1649 PyErr_SetVim(_("invalid mark name"));
1650 return NULL;
1653 /* Ckeck for keyboard interrupt */
1654 if (VimErrorCheck())
1655 return NULL;
1657 if (posp->lnum <= 0)
1659 /* Or raise an error? */
1660 Py_INCREF(Py_None);
1661 return Py_None;
1664 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1667 static PyObject *
1668 BufferRange(PyObject *self, PyObject *args)
1670 PyInt start;
1671 PyInt end;
1673 if (CheckBuffer((BufferObject *)(self)))
1674 return NULL;
1676 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
1677 return NULL;
1679 return RangeNew(((BufferObject *)(self))->buf, start, end);
1682 /* Line range object - Definitions
1685 static struct PyMethodDef RangeMethods[] = {
1686 /* name, function, calling, documentation */
1687 {"append", RangeAppend, 1, "Append data to the Vim range" },
1688 { NULL, NULL, 0, NULL }
1691 static PySequenceMethods RangeAsSeq = {
1692 (PyInquiry) RangeLength, /* sq_length, len(x) */
1693 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1694 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1695 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1696 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1697 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1698 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1701 static PyTypeObject RangeType = {
1702 PyObject_HEAD_INIT(0)
1704 "range",
1705 sizeof(RangeObject),
1708 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1709 (printfunc) 0, /* tp_print, print x */
1710 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1711 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1712 (cmpfunc) 0, /* tp_compare, x>y */
1713 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1715 0, /* as number */
1716 &RangeAsSeq, /* as sequence */
1717 0, /* as mapping */
1719 (hashfunc) 0, /* tp_hash, dict(x) */
1720 (ternaryfunc) 0, /* tp_call, x() */
1721 (reprfunc) 0, /* tp_str, str(x) */
1724 /* Line range object - Implementation
1727 static PyObject *
1728 RangeNew(buf_T *buf, PyInt start, PyInt end)
1730 BufferObject *bufr;
1731 RangeObject *self;
1732 self = PyObject_NEW(RangeObject, &RangeType);
1733 if (self == NULL)
1734 return NULL;
1736 bufr = (BufferObject *)BufferNew(buf);
1737 if (bufr == NULL)
1739 Py_DECREF(self);
1740 return NULL;
1742 Py_INCREF(bufr);
1744 self->buf = bufr;
1745 self->start = start;
1746 self->end = end;
1748 return (PyObject *)(self);
1751 static void
1752 RangeDestructor(PyObject *self)
1754 Py_DECREF(((RangeObject *)(self))->buf);
1755 Py_DECREF(self);
1758 static PyObject *
1759 RangeGetattr(PyObject *self, char *name)
1761 if (strcmp(name, "start") == 0)
1762 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
1763 else if (strcmp(name, "end") == 0)
1764 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
1765 else
1766 return Py_FindMethod(RangeMethods, self, name);
1769 static PyObject *
1770 RangeRepr(PyObject *self)
1772 static char repr[100];
1773 RangeObject *this = (RangeObject *)(self);
1775 if (this->buf->buf == INVALID_BUFFER_VALUE)
1777 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1778 (self));
1779 return PyString_FromString(repr);
1781 else
1783 char *name = (char *)this->buf->buf->b_fname;
1784 int len;
1786 if (name == NULL)
1787 name = "";
1788 len = (int)strlen(name);
1790 if (len > 45)
1791 name = name + (45 - len);
1793 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1794 len > 45 ? "..." : "", name,
1795 this->start, this->end);
1797 return PyString_FromString(repr);
1801 /****************/
1803 static PyInt
1804 RangeLength(PyObject *self)
1806 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1807 if (CheckBuffer(((RangeObject *)(self))->buf))
1808 return -1; /* ??? */
1810 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1813 static PyObject *
1814 RangeItem(PyObject *self, PyInt n)
1816 return RBItem(((RangeObject *)(self))->buf, n,
1817 ((RangeObject *)(self))->start,
1818 ((RangeObject *)(self))->end);
1821 static PyObject *
1822 RangeSlice(PyObject *self, PyInt lo, PyInt hi)
1824 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1825 ((RangeObject *)(self))->start,
1826 ((RangeObject *)(self))->end);
1829 static PyInt
1830 RangeAssItem(PyObject *self, PyInt n, PyObject *val)
1832 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1833 ((RangeObject *)(self))->start,
1834 ((RangeObject *)(self))->end,
1835 &((RangeObject *)(self))->end);
1838 static PyInt
1839 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1841 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1842 ((RangeObject *)(self))->start,
1843 ((RangeObject *)(self))->end,
1844 &((RangeObject *)(self))->end);
1847 static PyObject *
1848 RangeAppend(PyObject *self, PyObject *args)
1850 return RBAppend(((RangeObject *)(self))->buf, args,
1851 ((RangeObject *)(self))->start,
1852 ((RangeObject *)(self))->end,
1853 &((RangeObject *)(self))->end);
1856 /* Buffer list object - Definitions
1859 typedef struct
1861 PyObject_HEAD
1863 BufListObject;
1865 static PySequenceMethods BufListAsSeq = {
1866 (PyInquiry) BufListLength, /* sq_length, len(x) */
1867 (binaryfunc) 0, /* sq_concat, x+y */
1868 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1869 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1870 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1871 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1872 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1875 static PyTypeObject BufListType = {
1876 PyObject_HEAD_INIT(0)
1878 "buffer list",
1879 sizeof(BufListObject),
1882 (destructor) 0, /* tp_dealloc, refcount==0 */
1883 (printfunc) 0, /* tp_print, print x */
1884 (getattrfunc) 0, /* tp_getattr, x.attr */
1885 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1886 (cmpfunc) 0, /* tp_compare, x>y */
1887 (reprfunc) 0, /* tp_repr, `x`, print x */
1889 0, /* as number */
1890 &BufListAsSeq, /* as sequence */
1891 0, /* as mapping */
1893 (hashfunc) 0, /* tp_hash, dict(x) */
1894 (ternaryfunc) 0, /* tp_call, x() */
1895 (reprfunc) 0, /* tp_str, str(x) */
1898 /* Buffer list object - Implementation
1901 static PyInt
1902 BufListLength(PyObject *self UNUSED)
1904 buf_T *b = firstbuf;
1905 PyInt n = 0;
1907 while (b)
1909 ++n;
1910 b = b->b_next;
1913 return n;
1916 static PyObject *
1917 BufListItem(PyObject *self UNUSED, PyInt n)
1919 buf_T *b;
1921 for (b = firstbuf; b; b = b->b_next, --n)
1923 if (n == 0)
1924 return BufferNew(b);
1927 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1928 return NULL;
1931 /* Window object - Definitions
1934 static struct PyMethodDef WindowMethods[] = {
1935 /* name, function, calling, documentation */
1936 { NULL, NULL, 0, NULL }
1939 static PyTypeObject WindowType = {
1940 PyObject_HEAD_INIT(0)
1942 "window",
1943 sizeof(WindowObject),
1946 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1947 (printfunc) 0, /* tp_print, print x */
1948 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1949 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1950 (cmpfunc) 0, /* tp_compare, x>y */
1951 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1953 0, /* as number */
1954 0, /* as sequence */
1955 0, /* as mapping */
1957 (hashfunc) 0, /* tp_hash, dict(x) */
1958 (ternaryfunc) 0, /* tp_call, x() */
1959 (reprfunc) 0, /* tp_str, str(x) */
1962 /* Window object - Implementation
1965 static PyObject *
1966 WindowNew(win_T *win)
1968 /* We need to handle deletion of windows underneath us.
1969 * If we add a "w_python_ref" field to the win_T structure,
1970 * then we can get at it in win_free() in vim. We then
1971 * need to create only ONE Python object per window - if
1972 * we try to create a second, just INCREF the existing one
1973 * and return it. The (single) Python object referring to
1974 * the window is stored in "w_python_ref".
1975 * On a win_free() we set the Python object's win_T* field
1976 * to an invalid value. We trap all uses of a window
1977 * object, and reject them if the win_T* field is invalid.
1980 WindowObject *self;
1982 if (win->w_python_ref)
1984 self = win->w_python_ref;
1985 Py_INCREF(self);
1987 else
1989 self = PyObject_NEW(WindowObject, &WindowType);
1990 if (self == NULL)
1991 return NULL;
1992 self->win = win;
1993 win->w_python_ref = self;
1996 return (PyObject *)(self);
1999 static void
2000 WindowDestructor(PyObject *self)
2002 WindowObject *this = (WindowObject *)(self);
2004 if (this->win && this->win != INVALID_WINDOW_VALUE)
2005 this->win->w_python_ref = NULL;
2007 Py_DECREF(self);
2010 static int
2011 CheckWindow(WindowObject *this)
2013 if (this->win == INVALID_WINDOW_VALUE)
2015 PyErr_SetVim(_("attempt to refer to deleted window"));
2016 return -1;
2019 return 0;
2022 static PyObject *
2023 WindowGetattr(PyObject *self, char *name)
2025 WindowObject *this = (WindowObject *)(self);
2027 if (CheckWindow(this))
2028 return NULL;
2030 if (strcmp(name, "buffer") == 0)
2031 return (PyObject *)BufferNew(this->win->w_buffer);
2032 else if (strcmp(name, "cursor") == 0)
2034 pos_T *pos = &this->win->w_cursor;
2036 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2038 else if (strcmp(name, "height") == 0)
2039 return Py_BuildValue("l", (long)(this->win->w_height));
2040 #ifdef FEAT_VERTSPLIT
2041 else if (strcmp(name, "width") == 0)
2042 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2043 #endif
2044 else if (strcmp(name,"__members__") == 0)
2045 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2046 else
2047 return Py_FindMethod(WindowMethods, self, name);
2050 static int
2051 WindowSetattr(PyObject *self, char *name, PyObject *val)
2053 WindowObject *this = (WindowObject *)(self);
2055 if (CheckWindow(this))
2056 return -1;
2058 if (strcmp(name, "buffer") == 0)
2060 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2061 return -1;
2063 else if (strcmp(name, "cursor") == 0)
2065 long lnum;
2066 long col;
2067 long len;
2069 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2070 return -1;
2072 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2074 PyErr_SetVim(_("cursor position outside buffer"));
2075 return -1;
2078 /* Check for keyboard interrupts */
2079 if (VimErrorCheck())
2080 return -1;
2082 /* When column is out of range silently correct it. */
2083 len = STRLEN(ml_get_buf(this->win->w_buffer, lnum, FALSE));
2084 if (col > len)
2085 col = len;
2087 this->win->w_cursor.lnum = lnum;
2088 this->win->w_cursor.col = col;
2089 #ifdef FEAT_VIRTUALEDIT
2090 this->win->w_cursor.coladd = 0;
2091 #endif
2092 update_screen(VALID);
2094 return 0;
2096 else if (strcmp(name, "height") == 0)
2098 int height;
2099 win_T *savewin;
2101 if (!PyArg_Parse(val, "i", &height))
2102 return -1;
2104 #ifdef FEAT_GUI
2105 need_mouse_correct = TRUE;
2106 #endif
2107 savewin = curwin;
2108 curwin = this->win;
2109 win_setheight(height);
2110 curwin = savewin;
2112 /* Check for keyboard interrupts */
2113 if (VimErrorCheck())
2114 return -1;
2116 return 0;
2118 #ifdef FEAT_VERTSPLIT
2119 else if (strcmp(name, "width") == 0)
2121 int width;
2122 win_T *savewin;
2124 if (!PyArg_Parse(val, "i", &width))
2125 return -1;
2127 #ifdef FEAT_GUI
2128 need_mouse_correct = TRUE;
2129 #endif
2130 savewin = curwin;
2131 curwin = this->win;
2132 win_setwidth(width);
2133 curwin = savewin;
2135 /* Check for keyboard interrupts */
2136 if (VimErrorCheck())
2137 return -1;
2139 return 0;
2141 #endif
2142 else
2144 PyErr_SetString(PyExc_AttributeError, name);
2145 return -1;
2149 static PyObject *
2150 WindowRepr(PyObject *self)
2152 static char repr[100];
2153 WindowObject *this = (WindowObject *)(self);
2155 if (this->win == INVALID_WINDOW_VALUE)
2157 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
2158 return PyString_FromString(repr);
2160 else
2162 int i = 0;
2163 win_T *w;
2165 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2166 ++i;
2168 if (w == NULL)
2169 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2170 (self));
2171 else
2172 vim_snprintf(repr, 100, _("<window %d>"), i);
2174 return PyString_FromString(repr);
2178 /* Window list object - Definitions
2181 typedef struct
2183 PyObject_HEAD
2185 WinListObject;
2187 static PySequenceMethods WinListAsSeq = {
2188 (PyInquiry) WinListLength, /* sq_length, len(x) */
2189 (binaryfunc) 0, /* sq_concat, x+y */
2190 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2191 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2192 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2193 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2194 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
2197 static PyTypeObject WinListType = {
2198 PyObject_HEAD_INIT(0)
2200 "window list",
2201 sizeof(WinListObject),
2204 (destructor) 0, /* tp_dealloc, refcount==0 */
2205 (printfunc) 0, /* tp_print, print x */
2206 (getattrfunc) 0, /* tp_getattr, x.attr */
2207 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2208 (cmpfunc) 0, /* tp_compare, x>y */
2209 (reprfunc) 0, /* tp_repr, `x`, print x */
2211 0, /* as number */
2212 &WinListAsSeq, /* as sequence */
2213 0, /* as mapping */
2215 (hashfunc) 0, /* tp_hash, dict(x) */
2216 (ternaryfunc) 0, /* tp_call, x() */
2217 (reprfunc) 0, /* tp_str, str(x) */
2220 /* Window list object - Implementation
2222 static PyInt
2223 WinListLength(PyObject *self UNUSED)
2225 win_T *w = firstwin;
2226 PyInt n = 0;
2228 while (w != NULL)
2230 ++n;
2231 w = W_NEXT(w);
2234 return n;
2237 static PyObject *
2238 WinListItem(PyObject *self UNUSED, PyInt n)
2240 win_T *w;
2242 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2243 if (n == 0)
2244 return WindowNew(w);
2246 PyErr_SetString(PyExc_IndexError, _("no such window"));
2247 return NULL;
2250 /* Current items object - Definitions
2253 typedef struct
2255 PyObject_HEAD
2257 CurrentObject;
2259 static PyTypeObject CurrentType = {
2260 PyObject_HEAD_INIT(0)
2262 "current data",
2263 sizeof(CurrentObject),
2266 (destructor) 0, /* tp_dealloc, refcount==0 */
2267 (printfunc) 0, /* tp_print, print x */
2268 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2269 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2270 (cmpfunc) 0, /* tp_compare, x>y */
2271 (reprfunc) 0, /* tp_repr, `x`, print x */
2273 0, /* as number */
2274 0, /* as sequence */
2275 0, /* as mapping */
2277 (hashfunc) 0, /* tp_hash, dict(x) */
2278 (ternaryfunc) 0, /* tp_call, x() */
2279 (reprfunc) 0, /* tp_str, str(x) */
2282 /* Current items object - Implementation
2284 static PyObject *
2285 CurrentGetattr(PyObject *self UNUSED, char *name)
2287 if (strcmp(name, "buffer") == 0)
2288 return (PyObject *)BufferNew(curbuf);
2289 else if (strcmp(name, "window") == 0)
2290 return (PyObject *)WindowNew(curwin);
2291 else if (strcmp(name, "line") == 0)
2292 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2293 else if (strcmp(name, "range") == 0)
2294 return RangeNew(curbuf, RangeStart, RangeEnd);
2295 else if (strcmp(name,"__members__") == 0)
2296 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2297 else
2299 PyErr_SetString(PyExc_AttributeError, name);
2300 return NULL;
2304 static int
2305 CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2307 if (strcmp(name, "line") == 0)
2309 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2310 return -1;
2312 return 0;
2314 else
2316 PyErr_SetString(PyExc_AttributeError, name);
2317 return -1;
2321 /* External interface
2324 void
2325 python_buffer_free(buf_T *buf)
2327 if (buf->b_python_ref != NULL)
2329 BufferObject *bp = buf->b_python_ref;
2330 bp->buf = INVALID_BUFFER_VALUE;
2331 buf->b_python_ref = NULL;
2335 #if defined(FEAT_WINDOWS) || defined(PROTO)
2336 void
2337 python_window_free(win_T *win)
2339 if (win->w_python_ref != NULL)
2341 WindowObject *wp = win->w_python_ref;
2342 wp->win = INVALID_WINDOW_VALUE;
2343 win->w_python_ref = NULL;
2346 #endif
2348 static BufListObject TheBufferList =
2350 PyObject_HEAD_INIT(&BufListType)
2353 static WinListObject TheWindowList =
2355 PyObject_HEAD_INIT(&WinListType)
2358 static CurrentObject TheCurrent =
2360 PyObject_HEAD_INIT(&CurrentType)
2363 static int
2364 PythonMod_Init(void)
2366 PyObject *mod;
2367 PyObject *dict;
2368 /* The special value is removed from sys.path in Python_Init(). */
2369 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
2371 /* Fixups... */
2372 BufferType.ob_type = &PyType_Type;
2373 RangeType.ob_type = &PyType_Type;
2374 WindowType.ob_type = &PyType_Type;
2375 BufListType.ob_type = &PyType_Type;
2376 WinListType.ob_type = &PyType_Type;
2377 CurrentType.ob_type = &PyType_Type;
2379 /* Set sys.argv[] to avoid a crash in warn(). */
2380 PySys_SetArgv(1, argv);
2382 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
2383 dict = PyModule_GetDict(mod);
2385 VimError = Py_BuildValue("s", "vim.error");
2387 PyDict_SetItemString(dict, "error", VimError);
2388 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2389 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2390 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
2392 if (PyErr_Occurred())
2393 return -1;
2395 return 0;
2398 /*************************************************************************
2399 * 4. Utility functions for handling the interface between Vim and Python.
2402 /* Get a line from the specified buffer. The line number is
2403 * in Vim format (1-based). The line is returned as a Python
2404 * string object.
2406 static PyObject *
2407 GetBufferLine(buf_T *buf, PyInt n)
2409 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2412 /* Get a list of lines from the specified buffer. The line numbers
2413 * are in Vim format (1-based). The range is from lo up to, but not
2414 * including, hi. The list is returned as a Python list of string objects.
2416 static PyObject *
2417 GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2419 PyInt i;
2420 PyInt n = hi - lo;
2421 PyObject *list = PyList_New(n);
2423 if (list == NULL)
2424 return NULL;
2426 for (i = 0; i < n; ++i)
2428 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2430 /* Error check - was the Python string creation OK? */
2431 if (str == NULL)
2433 Py_DECREF(list);
2434 return NULL;
2437 /* Set the list item */
2438 if (PyList_SetItem(list, i, str))
2440 Py_DECREF(str);
2441 Py_DECREF(list);
2442 return NULL;
2446 /* The ownership of the Python list is passed to the caller (ie,
2447 * the caller should Py_DECREF() the object when it is finished
2448 * with it).
2451 return list;
2455 * Check if deleting lines made the cursor position invalid.
2456 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2457 * deleted).
2459 static void
2460 py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2462 if (curwin->w_cursor.lnum >= lo)
2464 /* Adjust the cursor position if it's in/after the changed
2465 * lines. */
2466 if (curwin->w_cursor.lnum >= hi)
2468 curwin->w_cursor.lnum += extra;
2469 check_cursor_col();
2471 else if (extra < 0)
2473 curwin->w_cursor.lnum = lo;
2474 check_cursor();
2476 else
2477 check_cursor_col();
2478 changed_cline_bef_curs();
2480 invalidate_botline();
2483 /* Replace a line in the specified buffer. The line number is
2484 * in Vim format (1-based). The replacement line is given as
2485 * a Python string object. The object is checked for validity
2486 * and correct format. Errors are returned as a value of FAIL.
2487 * The return value is OK on success.
2488 * If OK is returned and len_change is not NULL, *len_change
2489 * is set to the change in the buffer length.
2491 static int
2492 SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2494 /* First of all, we check the thpe of the supplied Python object.
2495 * There are three cases:
2496 * 1. NULL, or None - this is a deletion.
2497 * 2. A string - this is a replacement.
2498 * 3. Anything else - this is an error.
2500 if (line == Py_None || line == NULL)
2502 buf_T *savebuf = curbuf;
2504 PyErr_Clear();
2505 curbuf = buf;
2507 if (u_savedel((linenr_T)n, 1L) == FAIL)
2508 PyErr_SetVim(_("cannot save undo information"));
2509 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2510 PyErr_SetVim(_("cannot delete line"));
2511 else
2513 if (buf == curwin->w_buffer)
2514 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2515 deleted_lines_mark((linenr_T)n, 1L);
2518 curbuf = savebuf;
2520 if (PyErr_Occurred() || VimErrorCheck())
2521 return FAIL;
2523 if (len_change)
2524 *len_change = -1;
2526 return OK;
2528 else if (PyString_Check(line))
2530 char *save = StringToLine(line);
2531 buf_T *savebuf = curbuf;
2533 if (save == NULL)
2534 return FAIL;
2536 /* We do not need to free "save" if ml_replace() consumes it. */
2537 PyErr_Clear();
2538 curbuf = buf;
2540 if (u_savesub((linenr_T)n) == FAIL)
2542 PyErr_SetVim(_("cannot save undo information"));
2543 vim_free(save);
2545 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2547 PyErr_SetVim(_("cannot replace line"));
2548 vim_free(save);
2550 else
2551 changed_bytes((linenr_T)n, 0);
2553 curbuf = savebuf;
2555 /* Check that the cursor is not beyond the end of the line now. */
2556 if (buf == curwin->w_buffer)
2557 check_cursor_col();
2559 if (PyErr_Occurred() || VimErrorCheck())
2560 return FAIL;
2562 if (len_change)
2563 *len_change = 0;
2565 return OK;
2567 else
2569 PyErr_BadArgument();
2570 return FAIL;
2574 /* Replace a range of lines in the specified buffer. The line numbers are in
2575 * Vim format (1-based). The range is from lo up to, but not including, hi.
2576 * The replacement lines are given as a Python list of string objects. The
2577 * list is checked for validity and correct format. Errors are returned as a
2578 * value of FAIL. The return value is OK on success.
2579 * If OK is returned and len_change is not NULL, *len_change
2580 * is set to the change in the buffer length.
2582 static int
2583 SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2585 /* First of all, we check the thpe of the supplied Python object.
2586 * There are three cases:
2587 * 1. NULL, or None - this is a deletion.
2588 * 2. A list - this is a replacement.
2589 * 3. Anything else - this is an error.
2591 if (list == Py_None || list == NULL)
2593 PyInt i;
2594 PyInt n = (int)(hi - lo);
2595 buf_T *savebuf = curbuf;
2597 PyErr_Clear();
2598 curbuf = buf;
2600 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2601 PyErr_SetVim(_("cannot save undo information"));
2602 else
2604 for (i = 0; i < n; ++i)
2606 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2608 PyErr_SetVim(_("cannot delete line"));
2609 break;
2612 if (buf == curwin->w_buffer)
2613 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2614 deleted_lines_mark((linenr_T)lo, (long)i);
2617 curbuf = savebuf;
2619 if (PyErr_Occurred() || VimErrorCheck())
2620 return FAIL;
2622 if (len_change)
2623 *len_change = -n;
2625 return OK;
2627 else if (PyList_Check(list))
2629 PyInt i;
2630 PyInt new_len = PyList_Size(list);
2631 PyInt old_len = hi - lo;
2632 PyInt extra = 0; /* lines added to text, can be negative */
2633 char **array;
2634 buf_T *savebuf;
2636 if (new_len == 0) /* avoid allocating zero bytes */
2637 array = NULL;
2638 else
2640 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2641 if (array == NULL)
2643 PyErr_NoMemory();
2644 return FAIL;
2648 for (i = 0; i < new_len; ++i)
2650 PyObject *line = PyList_GetItem(list, i);
2652 array[i] = StringToLine(line);
2653 if (array[i] == NULL)
2655 while (i)
2656 vim_free(array[--i]);
2657 vim_free(array);
2658 return FAIL;
2662 savebuf = curbuf;
2664 PyErr_Clear();
2665 curbuf = buf;
2667 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2668 PyErr_SetVim(_("cannot save undo information"));
2670 /* If the size of the range is reducing (ie, new_len < old_len) we
2671 * need to delete some old_len. We do this at the start, by
2672 * repeatedly deleting line "lo".
2674 if (!PyErr_Occurred())
2676 for (i = 0; i < old_len - new_len; ++i)
2677 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2679 PyErr_SetVim(_("cannot delete line"));
2680 break;
2682 extra -= i;
2685 /* For as long as possible, replace the existing old_len with the
2686 * new old_len. This is a more efficient operation, as it requires
2687 * less memory allocation and freeing.
2689 if (!PyErr_Occurred())
2691 for (i = 0; i < old_len && i < new_len; ++i)
2692 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2693 == FAIL)
2695 PyErr_SetVim(_("cannot replace line"));
2696 break;
2699 else
2700 i = 0;
2702 /* Now we may need to insert the remaining new old_len. If we do, we
2703 * must free the strings as we finish with them (we can't pass the
2704 * responsibility to vim in this case).
2706 if (!PyErr_Occurred())
2708 while (i < new_len)
2710 if (ml_append((linenr_T)(lo + i - 1),
2711 (char_u *)array[i], 0, FALSE) == FAIL)
2713 PyErr_SetVim(_("cannot insert line"));
2714 break;
2716 vim_free(array[i]);
2717 ++i;
2718 ++extra;
2722 /* Free any left-over old_len, as a result of an error */
2723 while (i < new_len)
2725 vim_free(array[i]);
2726 ++i;
2729 /* Free the array of old_len. All of its contents have now
2730 * been dealt with (either freed, or the responsibility passed
2731 * to vim.
2733 vim_free(array);
2735 /* Adjust marks. Invalidate any which lie in the
2736 * changed range, and move any in the remainder of the buffer.
2738 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2739 (long)MAXLNUM, (long)extra);
2740 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2742 if (buf == curwin->w_buffer)
2743 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2745 curbuf = savebuf;
2747 if (PyErr_Occurred() || VimErrorCheck())
2748 return FAIL;
2750 if (len_change)
2751 *len_change = new_len - old_len;
2753 return OK;
2755 else
2757 PyErr_BadArgument();
2758 return FAIL;
2762 /* Insert a number of lines into the specified buffer after the specifed line.
2763 * The line number is in Vim format (1-based). The lines to be inserted are
2764 * given as a Python list of string objects or as a single string. The lines
2765 * to be added are checked for validity and correct format. Errors are
2766 * returned as a value of FAIL. The return value is OK on success.
2767 * If OK is returned and len_change is not NULL, *len_change
2768 * is set to the change in the buffer length.
2770 static int
2771 InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2773 /* First of all, we check the type of the supplied Python object.
2774 * It must be a string or a list, or the call is in error.
2776 if (PyString_Check(lines))
2778 char *str = StringToLine(lines);
2779 buf_T *savebuf;
2781 if (str == NULL)
2782 return FAIL;
2784 savebuf = curbuf;
2786 PyErr_Clear();
2787 curbuf = buf;
2789 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2790 PyErr_SetVim(_("cannot save undo information"));
2791 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2792 PyErr_SetVim(_("cannot insert line"));
2793 else
2794 appended_lines_mark((linenr_T)n, 1L);
2796 vim_free(str);
2797 curbuf = savebuf;
2798 update_screen(VALID);
2800 if (PyErr_Occurred() || VimErrorCheck())
2801 return FAIL;
2803 if (len_change)
2804 *len_change = 1;
2806 return OK;
2808 else if (PyList_Check(lines))
2810 PyInt i;
2811 PyInt size = PyList_Size(lines);
2812 char **array;
2813 buf_T *savebuf;
2815 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2816 if (array == NULL)
2818 PyErr_NoMemory();
2819 return FAIL;
2822 for (i = 0; i < size; ++i)
2824 PyObject *line = PyList_GetItem(lines, i);
2825 array[i] = StringToLine(line);
2827 if (array[i] == NULL)
2829 while (i)
2830 vim_free(array[--i]);
2831 vim_free(array);
2832 return FAIL;
2836 savebuf = curbuf;
2838 PyErr_Clear();
2839 curbuf = buf;
2841 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2842 PyErr_SetVim(_("cannot save undo information"));
2843 else
2845 for (i = 0; i < size; ++i)
2847 if (ml_append((linenr_T)(n + i),
2848 (char_u *)array[i], 0, FALSE) == FAIL)
2850 PyErr_SetVim(_("cannot insert line"));
2852 /* Free the rest of the lines */
2853 while (i < size)
2854 vim_free(array[i++]);
2856 break;
2858 vim_free(array[i]);
2860 if (i > 0)
2861 appended_lines_mark((linenr_T)n, (long)i);
2864 /* Free the array of lines. All of its contents have now
2865 * been freed.
2867 vim_free(array);
2869 curbuf = savebuf;
2870 update_screen(VALID);
2872 if (PyErr_Occurred() || VimErrorCheck())
2873 return FAIL;
2875 if (len_change)
2876 *len_change = size;
2878 return OK;
2880 else
2882 PyErr_BadArgument();
2883 return FAIL;
2887 /* Convert a Vim line into a Python string.
2888 * All internal newlines are replaced by null characters.
2890 * On errors, the Python exception data is set, and NULL is returned.
2892 static PyObject *
2893 LineToString(const char *str)
2895 PyObject *result;
2896 PyInt len = strlen(str);
2897 char *p;
2899 /* Allocate an Python string object, with uninitialised contents. We
2900 * must do it this way, so that we can modify the string in place
2901 * later. See the Python source, Objects/stringobject.c for details.
2903 result = PyString_FromStringAndSize(NULL, len);
2904 if (result == NULL)
2905 return NULL;
2907 p = PyString_AsString(result);
2909 while (*str)
2911 if (*str == '\n')
2912 *p = '\0';
2913 else
2914 *p = *str;
2916 ++p;
2917 ++str;
2920 return result;
2923 /* Convert a Python string into a Vim line.
2925 * The result is in allocated memory. All internal nulls are replaced by
2926 * newline characters. It is an error for the string to contain newline
2927 * characters.
2929 * On errors, the Python exception data is set, and NULL is returned.
2931 static char *
2932 StringToLine(PyObject *obj)
2934 const char *str;
2935 char *save;
2936 PyInt len;
2937 PyInt i;
2938 char *p;
2940 if (obj == NULL || !PyString_Check(obj))
2942 PyErr_BadArgument();
2943 return NULL;
2946 str = PyString_AsString(obj);
2947 len = PyString_Size(obj);
2950 * Error checking: String must not contain newlines, as we
2951 * are replacing a single line, and we must replace it with
2952 * a single line.
2953 * A trailing newline is removed, so that append(f.readlines()) works.
2955 p = memchr(str, '\n', len);
2956 if (p != NULL)
2958 if (p == str + len - 1)
2959 --len;
2960 else
2962 PyErr_SetVim(_("string cannot contain newlines"));
2963 return NULL;
2967 /* Create a copy of the string, with internal nulls replaced by
2968 * newline characters, as is the vim convention.
2970 save = (char *)alloc((unsigned)(len+1));
2971 if (save == NULL)
2973 PyErr_NoMemory();
2974 return NULL;
2977 for (i = 0; i < len; ++i)
2979 if (str[i] == '\0')
2980 save[i] = '\n';
2981 else
2982 save[i] = str[i];
2985 save[i] = '\0';
2987 return save;
2990 /* Check to see whether a Vim error has been reported, or a keyboard
2991 * interrupt has been detected.
2993 static int
2994 VimErrorCheck(void)
2996 if (got_int)
2998 PyErr_SetNone(PyExc_KeyboardInterrupt);
2999 return 1;
3001 else if (did_emsg && !PyErr_Occurred())
3003 PyErr_SetNone(VimError);
3004 return 1;
3007 return 0;
3011 /* Don't generate a prototype for the next function, it generates an error on
3012 * newer Python versions. */
3013 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3015 char *
3016 Py_GetProgramName(void)
3018 return "vim";
3020 #endif /* Python 1.4 */