use environment variables.
[MacVim/KaoriYa.git] / src / if_python.c
blob07f5cdffc09b3ee7359ca66862c7ace83b2922bc
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 #include <Python.h>
44 #if defined(MACOS) && !defined(MACOS_X_UNIX)
45 # include "macglue.h"
46 # include <CodeFragments.h>
47 #endif
48 #undef main /* Defined in python.h - aargh */
49 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
51 #if !defined(FEAT_PYTHON) && defined(PROTO)
52 /* Use this to be able to generate prototypes without python being used. */
53 # define PyObject Py_ssize_t
54 # define PyThreadState Py_ssize_t
55 # define PyTypeObject Py_ssize_t
56 struct PyMethodDef { Py_ssize_t a; };
57 # define PySequenceMethods Py_ssize_t
58 #endif
60 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
61 # define PyInt Py_ssize_t
62 # define PyInquiry lenfunc
63 # define PyIntArgFunc ssizeargfunc
64 # define PyIntIntArgFunc ssizessizeargfunc
65 # define PyIntObjArgProc ssizeobjargproc
66 # define PyIntIntObjArgProc ssizessizeobjargproc
67 # define Py_ssize_t_fmt "n"
68 #else
69 # define PyInt int
70 # define PyInquiry inquiry
71 # define PyIntArgFunc intargfunc
72 # define PyIntIntArgFunc intintargfunc
73 # define PyIntObjArgProc intobjargproc
74 # define PyIntIntObjArgProc intintobjargproc
75 # define Py_ssize_t_fmt "i"
76 #endif
78 /* Parser flags */
79 #define single_input 256
80 #define file_input 257
81 #define eval_input 258
83 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
84 /* Python 2.3: can invoke ":python" recursively. */
85 # define PY_CAN_RECURSE
86 #endif
88 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
89 # ifndef DYNAMIC_PYTHON
90 # define HINSTANCE long_u /* for generating prototypes */
91 # endif
93 # if defined(MACOS_X_UNIX)
94 typedef void * HINSTANCE;
95 typedef void * FARPROC;
96 # include <dlfcn.h>
97 # define LoadLibrary(a) dlopen(a,RTLD_NOW|RTLD_LOCAL)
98 # define FreeLibrary(a) dlclose(a)
99 # define GetProcAddress dlsym
100 # endif
102 /* This makes if_python.c compile without warnings against Python 2.5
103 * on Win32 and Win64. */
104 #undef PyRun_SimpleString
105 #undef PyArg_Parse
106 #undef PyArg_ParseTuple
107 #undef Py_BuildValue
108 #undef Py_InitModule4
109 #undef Py_InitModule4_64
112 * Wrapper defines
114 # define PyArg_Parse dll_PyArg_Parse
115 # define PyArg_ParseTuple dll_PyArg_ParseTuple
116 # define PyDict_SetItemString dll_PyDict_SetItemString
117 # define PyErr_BadArgument dll_PyErr_BadArgument
118 # define PyErr_Clear dll_PyErr_Clear
119 # define PyErr_NoMemory dll_PyErr_NoMemory
120 # define PyErr_Occurred dll_PyErr_Occurred
121 # define PyErr_SetNone dll_PyErr_SetNone
122 # define PyErr_SetString dll_PyErr_SetString
123 # define PyEval_InitThreads dll_PyEval_InitThreads
124 # define PyEval_RestoreThread dll_PyEval_RestoreThread
125 # define PyEval_SaveThread dll_PyEval_SaveThread
126 # ifdef PY_CAN_RECURSE
127 # define PyGILState_Ensure dll_PyGILState_Ensure
128 # define PyGILState_Release dll_PyGILState_Release
129 # endif
130 # define PyInt_AsLong dll_PyInt_AsLong
131 # define PyInt_FromLong dll_PyInt_FromLong
132 # define PyInt_Type (*dll_PyInt_Type)
133 # define PyList_GetItem dll_PyList_GetItem
134 # define PyList_Append dll_PyList_Append
135 # define PyList_New dll_PyList_New
136 # define PyList_SetItem dll_PyList_SetItem
137 # define PyList_Size dll_PyList_Size
138 # define PyList_Type (*dll_PyList_Type)
139 # define PyImport_ImportModule dll_PyImport_ImportModule
140 # define PyDict_New dll_PyDict_New
141 # define PyDict_GetItemString dll_PyDict_GetItemString
142 # define PyModule_GetDict dll_PyModule_GetDict
143 # define PyRun_SimpleString dll_PyRun_SimpleString
144 # define PyString_AsString dll_PyString_AsString
145 # define PyString_FromString dll_PyString_FromString
146 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
147 # define PyString_Size dll_PyString_Size
148 # define PyString_Type (*dll_PyString_Type)
149 # define PySys_SetObject dll_PySys_SetObject
150 # define PySys_SetArgv dll_PySys_SetArgv
151 # define PyType_Type (*dll_PyType_Type)
152 # define Py_BuildValue dll_Py_BuildValue
153 # define Py_FindMethod dll_Py_FindMethod
154 # define Py_InitModule4 dll_Py_InitModule4
155 # define Py_Initialize dll_Py_Initialize
156 # define Py_Finalize dll_Py_Finalize
157 # define Py_IsInitialized dll_Py_IsInitialized
158 # define _PyObject_New dll__PyObject_New
159 # define _Py_NoneStruct (*dll__Py_NoneStruct)
160 # define PyObject_Init dll__PyObject_Init
161 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
162 # define PyType_IsSubtype dll_PyType_IsSubtype
163 # endif
164 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
165 # define PyObject_Malloc dll_PyObject_Malloc
166 # define PyObject_Free dll_PyObject_Free
167 # endif
170 * Pointers for dynamic link
172 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
173 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
174 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
175 static int(*dll_PyErr_BadArgument)(void);
176 static void(*dll_PyErr_Clear)(void);
177 static PyObject*(*dll_PyErr_NoMemory)(void);
178 static PyObject*(*dll_PyErr_Occurred)(void);
179 static void(*dll_PyErr_SetNone)(PyObject *);
180 static void(*dll_PyErr_SetString)(PyObject *, const char *);
181 static void(*dll_PyEval_InitThreads)(void);
182 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
183 static PyThreadState*(*dll_PyEval_SaveThread)(void);
184 # ifdef PY_CAN_RECURSE
185 static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
186 static void (*dll_PyGILState_Release)(PyGILState_STATE);
187 #endif
188 static long(*dll_PyInt_AsLong)(PyObject *);
189 static PyObject*(*dll_PyInt_FromLong)(long);
190 static PyTypeObject* dll_PyInt_Type;
191 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
192 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
193 static PyObject*(*dll_PyList_New)(PyInt size);
194 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
195 static PyInt(*dll_PyList_Size)(PyObject *);
196 static PyTypeObject* dll_PyList_Type;
197 static PyObject*(*dll_PyImport_ImportModule)(const char *);
198 static PyObject*(*dll_PyDict_New)(void);
199 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
200 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
201 static int(*dll_PyRun_SimpleString)(char *);
202 static char*(*dll_PyString_AsString)(PyObject *);
203 static PyObject*(*dll_PyString_FromString)(const char *);
204 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
205 static PyInt(*dll_PyString_Size)(PyObject *);
206 static PyTypeObject* dll_PyString_Type;
207 static int(*dll_PySys_SetObject)(char *, PyObject *);
208 static int(*dll_PySys_SetArgv)(int, char **);
209 static PyTypeObject* dll_PyType_Type;
210 static PyObject*(*dll_Py_BuildValue)(char *, ...);
211 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
212 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
213 static void(*dll_Py_Initialize)(void);
214 static void(*dll_Py_Finalize)(void);
215 static int(*dll_Py_IsInitialized)(void);
216 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
217 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
218 static PyObject* dll__Py_NoneStruct;
219 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
220 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
221 # endif
222 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
223 static void* (*dll_PyObject_Malloc)(size_t);
224 static void (*dll_PyObject_Free)(void*);
225 # endif
227 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
229 /* Imported exception objects */
230 static PyObject *imp_PyExc_AttributeError;
231 static PyObject *imp_PyExc_IndexError;
232 static PyObject *imp_PyExc_KeyboardInterrupt;
233 static PyObject *imp_PyExc_TypeError;
234 static PyObject *imp_PyExc_ValueError;
236 # define PyExc_AttributeError imp_PyExc_AttributeError
237 # define PyExc_IndexError imp_PyExc_IndexError
238 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
239 # define PyExc_TypeError imp_PyExc_TypeError
240 # define PyExc_ValueError imp_PyExc_ValueError
243 * Table of name to function pointer of python.
245 # define PYTHON_PROC FARPROC
246 static struct
248 char *name;
249 PYTHON_PROC *ptr;
250 } python_funcname_table[] =
252 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
253 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
254 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
255 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
256 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
257 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
258 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
259 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
260 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
261 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
262 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
263 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
264 # ifdef PY_CAN_RECURSE
265 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
266 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
267 # endif
268 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
269 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
270 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
271 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
272 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
273 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
274 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
275 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
276 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
277 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
278 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
279 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
280 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
281 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
282 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
283 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
284 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
285 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
286 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
287 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
288 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
289 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
290 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
291 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
292 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
293 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
294 # else
295 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
296 # endif
297 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
298 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
299 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
300 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
301 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
302 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
303 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
304 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
305 # endif
306 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
307 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
308 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
309 # endif
310 {"", NULL},
314 * Free python.dll
316 static void
317 end_dynamic_python(void)
319 if (hinstPython)
321 FreeLibrary(hinstPython);
322 hinstPython = 0;
327 * Load library and get all pointers.
328 * Parameter 'libname' provides name of DLL.
329 * Return OK or FAIL.
331 static int
332 python_runtime_link_init(char *libname, int verbose)
334 int i;
336 if (hinstPython)
337 return OK;
338 hinstPython = LoadLibrary(libname);
339 if (!hinstPython)
341 if (verbose)
342 EMSG2(_(e_loadlib), libname);
343 return FAIL;
346 for (i = 0; python_funcname_table[i].ptr; ++i)
348 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
349 python_funcname_table[i].name)) == NULL)
351 FreeLibrary(hinstPython);
352 hinstPython = 0;
353 if (verbose)
354 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
355 return FAIL;
358 return OK;
362 * If python is enabled (there is installed python on Windows system) return
363 * TRUE, else FALSE.
366 python_enabled(int verbose)
368 #if defined(MACOS_X_UNIX)
369 int ret;
370 int mustfree = FALSE;
371 char_u *s = vim_getenv("PYTHON_DLL", &mustfree);
372 if (s != NULL)
373 ret = python_runtime_link_init(s, verbose) == OK;
374 if (mustfree)
375 vim_free(s);
376 if (ret == FALSE) {
377 ret = python_runtime_link_init(
378 "/System/Library/Frameworks/Python.framework/Versions/Current/Python",
379 verbose) == OK;
381 return ret;
382 #else
383 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
384 #endif
387 /* Load the standard Python exceptions - don't import the symbols from the
388 * DLL, as this can cause errors (importing data symbols is not reliable).
390 static void get_exceptions __ARGS((void));
392 static void
393 get_exceptions()
395 PyObject *exmod = PyImport_ImportModule("exceptions");
396 PyObject *exdict = PyModule_GetDict(exmod);
397 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
398 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
399 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
400 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
401 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
402 Py_XINCREF(imp_PyExc_AttributeError);
403 Py_XINCREF(imp_PyExc_IndexError);
404 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
405 Py_XINCREF(imp_PyExc_TypeError);
406 Py_XINCREF(imp_PyExc_ValueError);
407 Py_XDECREF(exmod);
409 #endif /* DYNAMIC_PYTHON */
411 /******************************************************
412 * Internal function prototypes.
415 static void DoPythonCommand(exarg_T *, const char *);
416 static PyInt RangeStart;
417 static PyInt RangeEnd;
419 static void PythonIO_Flush(void);
420 static int PythonIO_Init(void);
421 static int PythonMod_Init(void);
423 /* Utility functions for the vim/python interface
424 * ----------------------------------------------
426 static PyObject *GetBufferLine(buf_T *, PyInt);
427 static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
429 static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
430 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
431 static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
433 static PyObject *LineToString(const char *);
434 static char *StringToLine(PyObject *);
436 static int VimErrorCheck(void);
438 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
440 /******************************************************
441 * 1. Python interpreter main program.
444 static int initialised = 0;
446 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
447 typedef PyObject PyThreadState;
448 #endif
450 #ifdef PY_CAN_RECURSE
451 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
452 #else
453 static PyThreadState *saved_python_thread = NULL;
454 #endif
457 * Suspend a thread of the Python interpreter, other threads are allowed to
458 * run.
460 static void
461 Python_SaveThread(void)
463 #ifdef PY_CAN_RECURSE
464 PyGILState_Release(pygilstate);
465 #else
466 saved_python_thread = PyEval_SaveThread();
467 #endif
471 * Restore a thread of the Python interpreter, waits for other threads to
472 * block.
474 static void
475 Python_RestoreThread(void)
477 #ifdef PY_CAN_RECURSE
478 pygilstate = PyGILState_Ensure();
479 #else
480 PyEval_RestoreThread(saved_python_thread);
481 saved_python_thread = NULL;
482 #endif
486 * obtain a lock on the Vim data structures
488 static void Python_Lock_Vim(void)
493 * release a lock on the Vim data structures
495 static void Python_Release_Vim(void)
499 void
500 python_end()
502 static int recurse = 0;
504 /* If a crash occurs while doing this, don't try again. */
505 if (recurse != 0)
506 return;
508 ++recurse;
510 #ifdef DYNAMIC_PYTHON
511 if (hinstPython && Py_IsInitialized())
513 Python_RestoreThread(); /* enter python */
514 Py_Finalize();
516 end_dynamic_python();
517 #else
518 if (Py_IsInitialized())
520 Python_RestoreThread(); /* enter python */
521 Py_Finalize();
523 #endif
525 --recurse;
528 static int
529 Python_Init(void)
531 if (!initialised)
533 #ifdef DYNAMIC_PYTHON
534 if (!python_enabled(TRUE))
536 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
537 goto fail;
539 #endif
541 #if !defined(MACOS) || defined(MACOS_X_UNIX)
542 Py_Initialize();
543 #else
544 PyMac_Initialize();
545 #endif
546 /* initialise threads */
547 PyEval_InitThreads();
549 #ifdef DYNAMIC_PYTHON
550 get_exceptions();
551 #endif
553 if (PythonIO_Init())
554 goto fail;
556 if (PythonMod_Init())
557 goto fail;
559 /* Remove the element from sys.path that was added because of our
560 * argv[0] value in PythonMod_Init(). Previously we used an empty
561 * string, but dependinding on the OS we then get an empty entry or
562 * the current directory in sys.path. */
563 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
565 /* the first python thread is vim's, release the lock */
566 Python_SaveThread();
568 initialised = 1;
571 return 0;
573 fail:
574 /* We call PythonIO_Flush() here to print any Python errors.
575 * This is OK, as it is possible to call this function even
576 * if PythonIO_Init() has not completed successfully (it will
577 * not do anything in this case).
579 PythonIO_Flush();
580 return -1;
584 * External interface
586 static void
587 DoPythonCommand(exarg_T *eap, const char *cmd)
589 #ifndef PY_CAN_RECURSE
590 static int recursive = 0;
591 #endif
592 #if defined(MACOS) && !defined(MACOS_X_UNIX)
593 GrafPtr oldPort;
594 #endif
595 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
596 char *saved_locale;
597 #endif
599 #ifndef PY_CAN_RECURSE
600 if (recursive)
602 EMSG(_("E659: Cannot invoke Python recursively"));
603 return;
605 ++recursive;
606 #endif
608 #if defined(MACOS) && !defined(MACOS_X_UNIX)
609 GetPort(&oldPort);
610 /* Check if the Python library is available */
611 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
612 goto theend;
613 #endif
614 if (Python_Init())
615 goto theend;
617 RangeStart = eap->line1;
618 RangeEnd = eap->line2;
619 Python_Release_Vim(); /* leave vim */
621 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
622 /* Python only works properly when the LC_NUMERIC locale is "C". */
623 saved_locale = setlocale(LC_NUMERIC, NULL);
624 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
625 saved_locale = NULL;
626 else
628 /* Need to make a copy, value may change when setting new locale. */
629 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
630 (void)setlocale(LC_NUMERIC, "C");
632 #endif
634 Python_RestoreThread(); /* enter python */
636 PyRun_SimpleString((char *)(cmd));
638 Python_SaveThread(); /* leave python */
640 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
641 if (saved_locale != NULL)
643 (void)setlocale(LC_NUMERIC, saved_locale);
644 vim_free(saved_locale);
646 #endif
648 Python_Lock_Vim(); /* enter vim */
649 PythonIO_Flush();
650 #if defined(MACOS) && !defined(MACOS_X_UNIX)
651 SetPort(oldPort);
652 #endif
654 theend:
655 #ifndef PY_CAN_RECURSE
656 --recursive;
657 #endif
658 return; /* keeps lint happy */
662 * ":python"
664 void
665 ex_python(exarg_T *eap)
667 char_u *script;
669 script = script_get(eap, eap->arg);
670 if (!eap->skip)
672 if (script == NULL)
673 DoPythonCommand(eap, (char *)eap->arg);
674 else
675 DoPythonCommand(eap, (char *)script);
677 vim_free(script);
680 #define BUFFER_SIZE 1024
683 * ":pyfile"
685 void
686 ex_pyfile(exarg_T *eap)
688 static char buffer[BUFFER_SIZE];
689 const char *file = (char *)eap->arg;
690 char *p;
692 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
693 * stdio file pointer, but Vim and the Python DLL are compiled with
694 * different options under Windows, meaning that stdio pointers aren't
695 * compatible between the two. Yuk.
697 * Put the string "execfile('file')" into buffer. But, we need to
698 * escape any backslashes or single quotes in the file name, so that
699 * Python won't mangle the file name.
701 strcpy(buffer, "execfile('");
702 p = buffer + 10; /* size of "execfile('" */
704 while (*file && p < buffer + (BUFFER_SIZE - 3))
706 if (*file == '\\' || *file == '\'')
707 *p++ = '\\';
708 *p++ = *file++;
711 /* If we didn't finish the file name, we hit a buffer overflow */
712 if (*file != '\0')
713 return;
715 /* Put in the terminating "')" and a null */
716 *p++ = '\'';
717 *p++ = ')';
718 *p++ = '\0';
720 /* Execute the file */
721 DoPythonCommand(eap, buffer);
724 /******************************************************
725 * 2. Python output stream: writes output via [e]msg().
728 /* Implementation functions
731 static PyObject *OutputGetattr(PyObject *, char *);
732 static int OutputSetattr(PyObject *, char *, PyObject *);
734 static PyObject *OutputWrite(PyObject *, PyObject *);
735 static PyObject *OutputWritelines(PyObject *, PyObject *);
737 typedef void (*writefn)(char_u *);
738 static void writer(writefn fn, char_u *str, PyInt n);
740 /* Output object definition
743 typedef struct
745 PyObject_HEAD
746 long softspace;
747 long error;
748 } OutputObject;
750 static struct PyMethodDef OutputMethods[] = {
751 /* name, function, calling, documentation */
752 {"write", OutputWrite, 1, "" },
753 {"writelines", OutputWritelines, 1, "" },
754 { NULL, NULL, 0, NULL }
757 static PyTypeObject OutputType = {
758 PyObject_HEAD_INIT(0)
760 "message",
761 sizeof(OutputObject),
764 (destructor) 0,
765 (printfunc) 0,
766 (getattrfunc) OutputGetattr,
767 (setattrfunc) OutputSetattr,
768 (cmpfunc) 0,
769 (reprfunc) 0,
771 0, /* as number */
772 0, /* as sequence */
773 0, /* as mapping */
775 (hashfunc) 0,
776 (ternaryfunc) 0,
777 (reprfunc) 0
780 /*************/
782 static PyObject *
783 OutputGetattr(PyObject *self, char *name)
785 if (strcmp(name, "softspace") == 0)
786 return PyInt_FromLong(((OutputObject *)(self))->softspace);
788 return Py_FindMethod(OutputMethods, self, name);
791 static int
792 OutputSetattr(PyObject *self, char *name, PyObject *val)
794 if (val == NULL) {
795 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
796 return -1;
799 if (strcmp(name, "softspace") == 0)
801 if (!PyInt_Check(val)) {
802 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
803 return -1;
806 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
807 return 0;
810 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
811 return -1;
814 /*************/
816 static PyObject *
817 OutputWrite(PyObject *self, PyObject *args)
819 int len;
820 char *str;
821 int error = ((OutputObject *)(self))->error;
823 if (!PyArg_ParseTuple(args, "s#", &str, &len))
824 return NULL;
826 Py_BEGIN_ALLOW_THREADS
827 Python_Lock_Vim();
828 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
829 Python_Release_Vim();
830 Py_END_ALLOW_THREADS
832 Py_INCREF(Py_None);
833 return Py_None;
836 static PyObject *
837 OutputWritelines(PyObject *self, PyObject *args)
839 PyInt n;
840 PyInt i;
841 PyObject *list;
842 int error = ((OutputObject *)(self))->error;
844 if (!PyArg_ParseTuple(args, "O", &list))
845 return NULL;
846 Py_INCREF(list);
848 if (!PyList_Check(list)) {
849 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
850 Py_DECREF(list);
851 return NULL;
854 n = PyList_Size(list);
856 for (i = 0; i < n; ++i)
858 PyObject *line = PyList_GetItem(list, i);
859 char *str;
860 PyInt len;
862 if (!PyArg_Parse(line, "s#", &str, &len)) {
863 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
864 Py_DECREF(list);
865 return NULL;
868 Py_BEGIN_ALLOW_THREADS
869 Python_Lock_Vim();
870 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
871 Python_Release_Vim();
872 Py_END_ALLOW_THREADS
875 Py_DECREF(list);
876 Py_INCREF(Py_None);
877 return Py_None;
880 /* Output buffer management
883 static char_u *buffer = NULL;
884 static PyInt buffer_len = 0;
885 static PyInt buffer_size = 0;
887 static writefn old_fn = NULL;
889 static void
890 buffer_ensure(PyInt n)
892 PyInt new_size;
893 char_u *new_buffer;
895 if (n < buffer_size)
896 return;
898 new_size = buffer_size;
899 while (new_size < n)
900 new_size += 80;
902 if (new_size != buffer_size)
904 new_buffer = alloc((unsigned)new_size);
905 if (new_buffer == NULL)
906 return;
908 if (buffer)
910 memcpy(new_buffer, buffer, buffer_len);
911 vim_free(buffer);
914 buffer = new_buffer;
915 buffer_size = new_size;
919 static void
920 PythonIO_Flush(void)
922 if (old_fn && buffer_len)
924 buffer[buffer_len] = 0;
925 old_fn(buffer);
928 buffer_len = 0;
931 static void
932 writer(writefn fn, char_u *str, PyInt n)
934 char_u *ptr;
936 if (fn != old_fn && old_fn != NULL)
937 PythonIO_Flush();
939 old_fn = fn;
941 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
943 PyInt len = ptr - str;
945 buffer_ensure(buffer_len + len + 1);
947 memcpy(buffer + buffer_len, str, len);
948 buffer_len += len;
949 buffer[buffer_len] = 0;
950 fn(buffer);
951 str = ptr + 1;
952 n -= len + 1;
953 buffer_len = 0;
956 /* Put the remaining text into the buffer for later printing */
957 buffer_ensure(buffer_len + n + 1);
958 memcpy(buffer + buffer_len, str, n);
959 buffer_len += n;
962 /***************/
964 static OutputObject Output =
966 PyObject_HEAD_INIT(&OutputType)
971 static OutputObject Error =
973 PyObject_HEAD_INIT(&OutputType)
978 static int
979 PythonIO_Init(void)
981 /* Fixups... */
982 OutputType.ob_type = &PyType_Type;
984 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
985 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
987 if (PyErr_Occurred())
989 EMSG(_("E264: Python: Error initialising I/O objects"));
990 return -1;
993 return 0;
996 /******************************************************
997 * 3. Implementation of the Vim module for Python
1000 /* Vim module - Implementation functions
1001 * -------------------------------------
1004 static PyObject *VimError;
1006 static PyObject *VimCommand(PyObject *, PyObject *);
1007 static PyObject *VimEval(PyObject *, PyObject *);
1009 /* Window type - Implementation functions
1010 * --------------------------------------
1013 typedef struct
1015 PyObject_HEAD
1016 win_T *win;
1018 WindowObject;
1020 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1022 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1024 static PyObject *WindowNew(win_T *);
1026 static void WindowDestructor(PyObject *);
1027 static PyObject *WindowGetattr(PyObject *, char *);
1028 static int WindowSetattr(PyObject *, char *, PyObject *);
1029 static PyObject *WindowRepr(PyObject *);
1031 /* Buffer type - Implementation functions
1032 * --------------------------------------
1035 typedef struct
1037 PyObject_HEAD
1038 buf_T *buf;
1040 BufferObject;
1042 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1044 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1046 static PyObject *BufferNew (buf_T *);
1048 static void BufferDestructor(PyObject *);
1049 static PyObject *BufferGetattr(PyObject *, char *);
1050 static PyObject *BufferRepr(PyObject *);
1052 static PyInt BufferLength(PyObject *);
1053 static PyObject *BufferItem(PyObject *, PyInt);
1054 static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1055 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1056 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1058 static PyObject *BufferAppend(PyObject *, PyObject *);
1059 static PyObject *BufferMark(PyObject *, PyObject *);
1060 static PyObject *BufferRange(PyObject *, PyObject *);
1062 /* Line range type - Implementation functions
1063 * --------------------------------------
1066 typedef struct
1068 PyObject_HEAD
1069 BufferObject *buf;
1070 PyInt start;
1071 PyInt end;
1073 RangeObject;
1075 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1077 static PyObject *RangeNew(buf_T *, PyInt, PyInt);
1079 static void RangeDestructor(PyObject *);
1080 static PyObject *RangeGetattr(PyObject *, char *);
1081 static PyObject *RangeRepr(PyObject *);
1083 static PyInt RangeLength(PyObject *);
1084 static PyObject *RangeItem(PyObject *, PyInt);
1085 static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1086 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1087 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1089 static PyObject *RangeAppend(PyObject *, PyObject *);
1091 /* Window list type - Implementation functions
1092 * -------------------------------------------
1095 static PyInt WinListLength(PyObject *);
1096 static PyObject *WinListItem(PyObject *, PyInt);
1098 /* Buffer list type - Implementation functions
1099 * -------------------------------------------
1102 static PyInt BufListLength(PyObject *);
1103 static PyObject *BufListItem(PyObject *, PyInt);
1105 /* Current objects type - Implementation functions
1106 * -----------------------------------------------
1109 static PyObject *CurrentGetattr(PyObject *, char *);
1110 static int CurrentSetattr(PyObject *, char *, PyObject *);
1112 /* Vim module - Definitions
1115 static struct PyMethodDef VimMethods[] = {
1116 /* name, function, calling, documentation */
1117 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1118 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
1119 { NULL, NULL, 0, NULL }
1122 /* Vim module - Implementation
1124 /*ARGSUSED*/
1125 static PyObject *
1126 VimCommand(PyObject *self, PyObject *args)
1128 char *cmd;
1129 PyObject *result;
1131 if (!PyArg_ParseTuple(args, "s", &cmd))
1132 return NULL;
1134 PyErr_Clear();
1136 Py_BEGIN_ALLOW_THREADS
1137 Python_Lock_Vim();
1139 do_cmdline_cmd((char_u *)cmd);
1140 update_screen(VALID);
1142 Python_Release_Vim();
1143 Py_END_ALLOW_THREADS
1145 if (VimErrorCheck())
1146 result = NULL;
1147 else
1148 result = Py_None;
1150 Py_XINCREF(result);
1151 return result;
1154 #ifdef FEAT_EVAL
1156 * Function to translate a typval_T into a PyObject; this will recursively
1157 * translate lists/dictionaries into their Python equivalents.
1159 * The depth parameter is to avoid infinite recursion, set it to 1 when
1160 * you call VimToPython.
1162 static PyObject *
1163 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1165 PyObject *result;
1166 PyObject *newObj;
1167 char ptrBuf[NUMBUFLEN];
1169 /* Avoid infinite recursion */
1170 if (depth > 100)
1172 Py_INCREF(Py_None);
1173 result = Py_None;
1174 return result;
1177 /* Check if we run into a recursive loop. The item must be in lookupDict
1178 * then and we can use it again. */
1179 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1180 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1182 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
1183 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1184 : (long_u)our_tv->vval.v_dict);
1185 result = PyDict_GetItemString(lookupDict, ptrBuf);
1186 if (result != NULL)
1188 Py_INCREF(result);
1189 return result;
1193 if (our_tv->v_type == VAR_STRING)
1195 result = Py_BuildValue("s", our_tv->vval.v_string);
1197 else if (our_tv->v_type == VAR_NUMBER)
1199 char buf[NUMBUFLEN];
1201 /* For backwards compatibility numbers are stored as strings. */
1202 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1203 result = Py_BuildValue("s", buf);
1205 # ifdef FEAT_FLOAT
1206 else if (our_tv->v_type == VAR_FLOAT)
1208 char buf[NUMBUFLEN];
1210 sprintf(buf, "%f", our_tv->vval.v_float);
1211 result = Py_BuildValue("s", buf);
1213 # endif
1214 else if (our_tv->v_type == VAR_LIST)
1216 list_T *list = our_tv->vval.v_list;
1217 listitem_T *curr;
1219 result = PyList_New(0);
1221 if (list != NULL)
1223 PyDict_SetItemString(lookupDict, ptrBuf, result);
1225 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1227 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1228 PyList_Append(result, newObj);
1229 Py_DECREF(newObj);
1233 else if (our_tv->v_type == VAR_DICT)
1235 result = PyDict_New();
1237 if (our_tv->vval.v_dict != NULL)
1239 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1240 long_u todo = ht->ht_used;
1241 hashitem_T *hi;
1242 dictitem_T *di;
1244 PyDict_SetItemString(lookupDict, ptrBuf, result);
1246 for (hi = ht->ht_array; todo > 0; ++hi)
1248 if (!HASHITEM_EMPTY(hi))
1250 --todo;
1252 di = dict_lookup(hi);
1253 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1254 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1255 Py_DECREF(newObj);
1260 else
1262 Py_INCREF(Py_None);
1263 result = Py_None;
1266 return result;
1268 #endif
1270 /*ARGSUSED*/
1271 static PyObject *
1272 VimEval(PyObject *self, PyObject *args)
1274 #ifdef FEAT_EVAL
1275 char *expr;
1276 typval_T *our_tv;
1277 PyObject *result;
1278 PyObject *lookup_dict;
1280 if (!PyArg_ParseTuple(args, "s", &expr))
1281 return NULL;
1283 Py_BEGIN_ALLOW_THREADS
1284 Python_Lock_Vim();
1285 our_tv = eval_expr((char_u *)expr, NULL);
1287 Python_Release_Vim();
1288 Py_END_ALLOW_THREADS
1290 if (our_tv == NULL)
1292 PyErr_SetVim(_("invalid expression"));
1293 return NULL;
1296 /* Convert the Vim type into a Python type. Create a dictionary that's
1297 * used to check for recursive loops. */
1298 lookup_dict = PyDict_New();
1299 result = VimToPython(our_tv, 1, lookup_dict);
1300 Py_DECREF(lookup_dict);
1303 Py_BEGIN_ALLOW_THREADS
1304 Python_Lock_Vim();
1305 free_tv(our_tv);
1306 Python_Release_Vim();
1307 Py_END_ALLOW_THREADS
1309 return result;
1310 #else
1311 PyErr_SetVim(_("expressions disabled at compile time"));
1312 return NULL;
1313 #endif
1316 /* Common routines for buffers and line ranges
1317 * -------------------------------------------
1319 static int
1320 CheckBuffer(BufferObject *this)
1322 if (this->buf == INVALID_BUFFER_VALUE)
1324 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1325 return -1;
1328 return 0;
1331 static PyObject *
1332 RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
1334 if (CheckBuffer(self))
1335 return NULL;
1337 if (n < 0 || n > end - start)
1339 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1340 return NULL;
1343 return GetBufferLine(self->buf, n+start);
1346 static PyObject *
1347 RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
1349 PyInt size;
1351 if (CheckBuffer(self))
1352 return NULL;
1354 size = end - start + 1;
1356 if (lo < 0)
1357 lo = 0;
1358 else if (lo > size)
1359 lo = size;
1360 if (hi < 0)
1361 hi = 0;
1362 if (hi < lo)
1363 hi = lo;
1364 else if (hi > size)
1365 hi = size;
1367 return GetBufferLineList(self->buf, lo+start, hi+start);
1370 static PyInt
1371 RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1373 PyInt len_change;
1375 if (CheckBuffer(self))
1376 return -1;
1378 if (n < 0 || n > end - start)
1380 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1381 return -1;
1384 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1385 return -1;
1387 if (new_end)
1388 *new_end = end + len_change;
1390 return 0;
1393 static PyInt
1394 RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1396 PyInt size;
1397 PyInt len_change;
1399 /* Self must be a valid buffer */
1400 if (CheckBuffer(self))
1401 return -1;
1403 /* Sort out the slice range */
1404 size = end - start + 1;
1406 if (lo < 0)
1407 lo = 0;
1408 else if (lo > size)
1409 lo = size;
1410 if (hi < 0)
1411 hi = 0;
1412 if (hi < lo)
1413 hi = lo;
1414 else if (hi > size)
1415 hi = size;
1417 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1418 return -1;
1420 if (new_end)
1421 *new_end = end + len_change;
1423 return 0;
1426 static PyObject *
1427 RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
1429 PyObject *lines;
1430 PyInt len_change;
1431 PyInt max;
1432 PyInt n;
1434 if (CheckBuffer(self))
1435 return NULL;
1437 max = n = end - start + 1;
1439 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
1440 return NULL;
1442 if (n < 0 || n > max)
1444 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1445 return NULL;
1448 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1449 return NULL;
1451 if (new_end)
1452 *new_end = end + len_change;
1454 Py_INCREF(Py_None);
1455 return Py_None;
1459 /* Buffer object - Definitions
1462 static struct PyMethodDef BufferMethods[] = {
1463 /* name, function, calling, documentation */
1464 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1465 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1466 {"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1467 { NULL, NULL, 0, NULL }
1470 static PySequenceMethods BufferAsSeq = {
1471 (PyInquiry) BufferLength, /* sq_length, len(x) */
1472 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1473 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1474 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1475 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1476 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1477 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1480 static PyTypeObject BufferType = {
1481 PyObject_HEAD_INIT(0)
1483 "buffer",
1484 sizeof(BufferObject),
1487 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1488 (printfunc) 0, /* tp_print, print x */
1489 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1490 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1491 (cmpfunc) 0, /* tp_compare, x>y */
1492 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1494 0, /* as number */
1495 &BufferAsSeq, /* as sequence */
1496 0, /* as mapping */
1498 (hashfunc) 0, /* tp_hash, dict(x) */
1499 (ternaryfunc) 0, /* tp_call, x() */
1500 (reprfunc) 0, /* tp_str, str(x) */
1503 /* Buffer object - Implementation
1506 static PyObject *
1507 BufferNew(buf_T *buf)
1509 /* We need to handle deletion of buffers underneath us.
1510 * If we add a "b_python_ref" field to the buf_T structure,
1511 * then we can get at it in buf_freeall() in vim. We then
1512 * need to create only ONE Python object per buffer - if
1513 * we try to create a second, just INCREF the existing one
1514 * and return it. The (single) Python object referring to
1515 * the buffer is stored in "b_python_ref".
1516 * Question: what to do on a buf_freeall(). We'll probably
1517 * have to either delete the Python object (DECREF it to
1518 * zero - a bad idea, as it leaves dangling refs!) or
1519 * set the buf_T * value to an invalid value (-1?), which
1520 * means we need checks in all access functions... Bah.
1523 BufferObject *self;
1525 if (buf->b_python_ref != NULL)
1527 self = buf->b_python_ref;
1528 Py_INCREF(self);
1530 else
1532 self = PyObject_NEW(BufferObject, &BufferType);
1533 if (self == NULL)
1534 return NULL;
1535 self->buf = buf;
1536 buf->b_python_ref = self;
1539 return (PyObject *)(self);
1542 static void
1543 BufferDestructor(PyObject *self)
1545 BufferObject *this = (BufferObject *)(self);
1547 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1548 this->buf->b_python_ref = NULL;
1550 Py_DECREF(self);
1553 static PyObject *
1554 BufferGetattr(PyObject *self, char *name)
1556 BufferObject *this = (BufferObject *)(self);
1558 if (CheckBuffer(this))
1559 return NULL;
1561 if (strcmp(name, "name") == 0)
1562 return Py_BuildValue("s", this->buf->b_ffname);
1563 else if (strcmp(name, "number") == 0)
1564 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
1565 else if (strcmp(name,"__members__") == 0)
1566 return Py_BuildValue("[ss]", "name", "number");
1567 else
1568 return Py_FindMethod(BufferMethods, self, name);
1571 static PyObject *
1572 BufferRepr(PyObject *self)
1574 static char repr[100];
1575 BufferObject *this = (BufferObject *)(self);
1577 if (this->buf == INVALID_BUFFER_VALUE)
1579 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
1580 return PyString_FromString(repr);
1582 else
1584 char *name = (char *)this->buf->b_fname;
1585 PyInt len;
1587 if (name == NULL)
1588 name = "";
1589 len = strlen(name);
1591 if (len > 35)
1592 name = name + (35 - len);
1594 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1596 return PyString_FromString(repr);
1600 /******************/
1602 static PyInt
1603 BufferLength(PyObject *self)
1605 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1606 if (CheckBuffer((BufferObject *)(self)))
1607 return -1; /* ??? */
1609 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1612 static PyObject *
1613 BufferItem(PyObject *self, PyInt n)
1615 return RBItem((BufferObject *)(self), n, 1,
1616 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1619 static PyObject *
1620 BufferSlice(PyObject *self, PyInt lo, PyInt hi)
1622 return RBSlice((BufferObject *)(self), lo, hi, 1,
1623 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1626 static PyInt
1627 BufferAssItem(PyObject *self, PyInt n, PyObject *val)
1629 return RBAssItem((BufferObject *)(self), n, val, 1,
1630 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1631 NULL);
1634 static PyInt
1635 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1637 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1638 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1639 NULL);
1642 static PyObject *
1643 BufferAppend(PyObject *self, PyObject *args)
1645 return RBAppend((BufferObject *)(self), args, 1,
1646 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1647 NULL);
1650 static PyObject *
1651 BufferMark(PyObject *self, PyObject *args)
1653 pos_T *posp;
1654 char mark;
1655 buf_T *curbuf_save;
1657 if (CheckBuffer((BufferObject *)(self)))
1658 return NULL;
1660 if (!PyArg_ParseTuple(args, "c", &mark))
1661 return NULL;
1663 curbuf_save = curbuf;
1664 curbuf = ((BufferObject *)(self))->buf;
1665 posp = getmark(mark, FALSE);
1666 curbuf = curbuf_save;
1668 if (posp == NULL)
1670 PyErr_SetVim(_("invalid mark name"));
1671 return NULL;
1674 /* Ckeck for keyboard interrupt */
1675 if (VimErrorCheck())
1676 return NULL;
1678 if (posp->lnum <= 0)
1680 /* Or raise an error? */
1681 Py_INCREF(Py_None);
1682 return Py_None;
1685 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1688 static PyObject *
1689 BufferRange(PyObject *self, PyObject *args)
1691 PyInt start;
1692 PyInt end;
1694 if (CheckBuffer((BufferObject *)(self)))
1695 return NULL;
1697 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
1698 return NULL;
1700 return RangeNew(((BufferObject *)(self))->buf, start, end);
1703 /* Line range object - Definitions
1706 static struct PyMethodDef RangeMethods[] = {
1707 /* name, function, calling, documentation */
1708 {"append", RangeAppend, 1, "Append data to the Vim range" },
1709 { NULL, NULL, 0, NULL }
1712 static PySequenceMethods RangeAsSeq = {
1713 (PyInquiry) RangeLength, /* sq_length, len(x) */
1714 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1715 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1716 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1717 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1718 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1719 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1722 static PyTypeObject RangeType = {
1723 PyObject_HEAD_INIT(0)
1725 "range",
1726 sizeof(RangeObject),
1729 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1730 (printfunc) 0, /* tp_print, print x */
1731 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1732 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1733 (cmpfunc) 0, /* tp_compare, x>y */
1734 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1736 0, /* as number */
1737 &RangeAsSeq, /* as sequence */
1738 0, /* as mapping */
1740 (hashfunc) 0, /* tp_hash, dict(x) */
1741 (ternaryfunc) 0, /* tp_call, x() */
1742 (reprfunc) 0, /* tp_str, str(x) */
1745 /* Line range object - Implementation
1748 static PyObject *
1749 RangeNew(buf_T *buf, PyInt start, PyInt end)
1751 BufferObject *bufr;
1752 RangeObject *self;
1753 self = PyObject_NEW(RangeObject, &RangeType);
1754 if (self == NULL)
1755 return NULL;
1757 bufr = (BufferObject *)BufferNew(buf);
1758 if (bufr == NULL)
1760 Py_DECREF(self);
1761 return NULL;
1763 Py_INCREF(bufr);
1765 self->buf = bufr;
1766 self->start = start;
1767 self->end = end;
1769 return (PyObject *)(self);
1772 static void
1773 RangeDestructor(PyObject *self)
1775 Py_DECREF(((RangeObject *)(self))->buf);
1776 Py_DECREF(self);
1779 static PyObject *
1780 RangeGetattr(PyObject *self, char *name)
1782 if (strcmp(name, "start") == 0)
1783 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
1784 else if (strcmp(name, "end") == 0)
1785 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
1786 else
1787 return Py_FindMethod(RangeMethods, self, name);
1790 static PyObject *
1791 RangeRepr(PyObject *self)
1793 static char repr[100];
1794 RangeObject *this = (RangeObject *)(self);
1796 if (this->buf->buf == INVALID_BUFFER_VALUE)
1798 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1799 (self));
1800 return PyString_FromString(repr);
1802 else
1804 char *name = (char *)this->buf->buf->b_fname;
1805 int len;
1807 if (name == NULL)
1808 name = "";
1809 len = (int)strlen(name);
1811 if (len > 45)
1812 name = name + (45 - len);
1814 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1815 len > 45 ? "..." : "", name,
1816 this->start, this->end);
1818 return PyString_FromString(repr);
1822 /****************/
1824 static PyInt
1825 RangeLength(PyObject *self)
1827 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1828 if (CheckBuffer(((RangeObject *)(self))->buf))
1829 return -1; /* ??? */
1831 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1834 static PyObject *
1835 RangeItem(PyObject *self, PyInt n)
1837 return RBItem(((RangeObject *)(self))->buf, n,
1838 ((RangeObject *)(self))->start,
1839 ((RangeObject *)(self))->end);
1842 static PyObject *
1843 RangeSlice(PyObject *self, PyInt lo, PyInt hi)
1845 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1846 ((RangeObject *)(self))->start,
1847 ((RangeObject *)(self))->end);
1850 static PyInt
1851 RangeAssItem(PyObject *self, PyInt n, PyObject *val)
1853 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1854 ((RangeObject *)(self))->start,
1855 ((RangeObject *)(self))->end,
1856 &((RangeObject *)(self))->end);
1859 static PyInt
1860 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1862 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1863 ((RangeObject *)(self))->start,
1864 ((RangeObject *)(self))->end,
1865 &((RangeObject *)(self))->end);
1868 static PyObject *
1869 RangeAppend(PyObject *self, PyObject *args)
1871 return RBAppend(((RangeObject *)(self))->buf, args,
1872 ((RangeObject *)(self))->start,
1873 ((RangeObject *)(self))->end,
1874 &((RangeObject *)(self))->end);
1877 /* Buffer list object - Definitions
1880 typedef struct
1882 PyObject_HEAD
1884 BufListObject;
1886 static PySequenceMethods BufListAsSeq = {
1887 (PyInquiry) BufListLength, /* sq_length, len(x) */
1888 (binaryfunc) 0, /* sq_concat, x+y */
1889 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1890 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1891 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1892 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1893 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1896 static PyTypeObject BufListType = {
1897 PyObject_HEAD_INIT(0)
1899 "buffer list",
1900 sizeof(BufListObject),
1903 (destructor) 0, /* tp_dealloc, refcount==0 */
1904 (printfunc) 0, /* tp_print, print x */
1905 (getattrfunc) 0, /* tp_getattr, x.attr */
1906 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1907 (cmpfunc) 0, /* tp_compare, x>y */
1908 (reprfunc) 0, /* tp_repr, `x`, print x */
1910 0, /* as number */
1911 &BufListAsSeq, /* as sequence */
1912 0, /* as mapping */
1914 (hashfunc) 0, /* tp_hash, dict(x) */
1915 (ternaryfunc) 0, /* tp_call, x() */
1916 (reprfunc) 0, /* tp_str, str(x) */
1919 /* Buffer list object - Implementation
1922 /*ARGSUSED*/
1923 static PyInt
1924 BufListLength(PyObject *self)
1926 buf_T *b = firstbuf;
1927 PyInt n = 0;
1929 while (b)
1931 ++n;
1932 b = b->b_next;
1935 return n;
1938 /*ARGSUSED*/
1939 static PyObject *
1940 BufListItem(PyObject *self, PyInt n)
1942 buf_T *b;
1944 for (b = firstbuf; b; b = b->b_next, --n)
1946 if (n == 0)
1947 return BufferNew(b);
1950 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1951 return NULL;
1954 /* Window object - Definitions
1957 static struct PyMethodDef WindowMethods[] = {
1958 /* name, function, calling, documentation */
1959 { NULL, NULL, 0, NULL }
1962 static PyTypeObject WindowType = {
1963 PyObject_HEAD_INIT(0)
1965 "window",
1966 sizeof(WindowObject),
1969 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1970 (printfunc) 0, /* tp_print, print x */
1971 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1972 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1973 (cmpfunc) 0, /* tp_compare, x>y */
1974 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1976 0, /* as number */
1977 0, /* as sequence */
1978 0, /* as mapping */
1980 (hashfunc) 0, /* tp_hash, dict(x) */
1981 (ternaryfunc) 0, /* tp_call, x() */
1982 (reprfunc) 0, /* tp_str, str(x) */
1985 /* Window object - Implementation
1988 static PyObject *
1989 WindowNew(win_T *win)
1991 /* We need to handle deletion of windows underneath us.
1992 * If we add a "w_python_ref" field to the win_T structure,
1993 * then we can get at it in win_free() in vim. We then
1994 * need to create only ONE Python object per window - if
1995 * we try to create a second, just INCREF the existing one
1996 * and return it. The (single) Python object referring to
1997 * the window is stored in "w_python_ref".
1998 * On a win_free() we set the Python object's win_T* field
1999 * to an invalid value. We trap all uses of a window
2000 * object, and reject them if the win_T* field is invalid.
2003 WindowObject *self;
2005 if (win->w_python_ref)
2007 self = win->w_python_ref;
2008 Py_INCREF(self);
2010 else
2012 self = PyObject_NEW(WindowObject, &WindowType);
2013 if (self == NULL)
2014 return NULL;
2015 self->win = win;
2016 win->w_python_ref = self;
2019 return (PyObject *)(self);
2022 static void
2023 WindowDestructor(PyObject *self)
2025 WindowObject *this = (WindowObject *)(self);
2027 if (this->win && this->win != INVALID_WINDOW_VALUE)
2028 this->win->w_python_ref = NULL;
2030 Py_DECREF(self);
2033 static int
2034 CheckWindow(WindowObject *this)
2036 if (this->win == INVALID_WINDOW_VALUE)
2038 PyErr_SetVim(_("attempt to refer to deleted window"));
2039 return -1;
2042 return 0;
2045 static PyObject *
2046 WindowGetattr(PyObject *self, char *name)
2048 WindowObject *this = (WindowObject *)(self);
2050 if (CheckWindow(this))
2051 return NULL;
2053 if (strcmp(name, "buffer") == 0)
2054 return (PyObject *)BufferNew(this->win->w_buffer);
2055 else if (strcmp(name, "cursor") == 0)
2057 pos_T *pos = &this->win->w_cursor;
2059 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2061 else if (strcmp(name, "height") == 0)
2062 return Py_BuildValue("l", (long)(this->win->w_height));
2063 #ifdef FEAT_VERTSPLIT
2064 else if (strcmp(name, "width") == 0)
2065 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2066 #endif
2067 else if (strcmp(name,"__members__") == 0)
2068 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2069 else
2070 return Py_FindMethod(WindowMethods, self, name);
2073 static int
2074 WindowSetattr(PyObject *self, char *name, PyObject *val)
2076 WindowObject *this = (WindowObject *)(self);
2078 if (CheckWindow(this))
2079 return -1;
2081 if (strcmp(name, "buffer") == 0)
2083 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2084 return -1;
2086 else if (strcmp(name, "cursor") == 0)
2088 long lnum;
2089 long col;
2091 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2092 return -1;
2094 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2096 PyErr_SetVim(_("cursor position outside buffer"));
2097 return -1;
2100 /* Check for keyboard interrupts */
2101 if (VimErrorCheck())
2102 return -1;
2104 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2106 this->win->w_cursor.lnum = lnum;
2107 this->win->w_cursor.col = col;
2108 update_screen(VALID);
2110 return 0;
2112 else if (strcmp(name, "height") == 0)
2114 int height;
2115 win_T *savewin;
2117 if (!PyArg_Parse(val, "i", &height))
2118 return -1;
2120 #ifdef FEAT_GUI
2121 need_mouse_correct = TRUE;
2122 #endif
2123 savewin = curwin;
2124 curwin = this->win;
2125 win_setheight(height);
2126 curwin = savewin;
2128 /* Check for keyboard interrupts */
2129 if (VimErrorCheck())
2130 return -1;
2132 return 0;
2134 #ifdef FEAT_VERTSPLIT
2135 else if (strcmp(name, "width") == 0)
2137 int width;
2138 win_T *savewin;
2140 if (!PyArg_Parse(val, "i", &width))
2141 return -1;
2143 #ifdef FEAT_GUI
2144 need_mouse_correct = TRUE;
2145 #endif
2146 savewin = curwin;
2147 curwin = this->win;
2148 win_setwidth(width);
2149 curwin = savewin;
2151 /* Check for keyboard interrupts */
2152 if (VimErrorCheck())
2153 return -1;
2155 return 0;
2157 #endif
2158 else
2160 PyErr_SetString(PyExc_AttributeError, name);
2161 return -1;
2165 static PyObject *
2166 WindowRepr(PyObject *self)
2168 static char repr[100];
2169 WindowObject *this = (WindowObject *)(self);
2171 if (this->win == INVALID_WINDOW_VALUE)
2173 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
2174 return PyString_FromString(repr);
2176 else
2178 int i = 0;
2179 win_T *w;
2181 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2182 ++i;
2184 if (w == NULL)
2185 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2186 (self));
2187 else
2188 vim_snprintf(repr, 100, _("<window %d>"), i);
2190 return PyString_FromString(repr);
2194 /* Window list object - Definitions
2197 typedef struct
2199 PyObject_HEAD
2201 WinListObject;
2203 static PySequenceMethods WinListAsSeq = {
2204 (PyInquiry) WinListLength, /* sq_length, len(x) */
2205 (binaryfunc) 0, /* sq_concat, x+y */
2206 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2207 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2208 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2209 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2210 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
2213 static PyTypeObject WinListType = {
2214 PyObject_HEAD_INIT(0)
2216 "window list",
2217 sizeof(WinListObject),
2220 (destructor) 0, /* tp_dealloc, refcount==0 */
2221 (printfunc) 0, /* tp_print, print x */
2222 (getattrfunc) 0, /* tp_getattr, x.attr */
2223 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2224 (cmpfunc) 0, /* tp_compare, x>y */
2225 (reprfunc) 0, /* tp_repr, `x`, print x */
2227 0, /* as number */
2228 &WinListAsSeq, /* as sequence */
2229 0, /* as mapping */
2231 (hashfunc) 0, /* tp_hash, dict(x) */
2232 (ternaryfunc) 0, /* tp_call, x() */
2233 (reprfunc) 0, /* tp_str, str(x) */
2236 /* Window list object - Implementation
2238 /*ARGSUSED*/
2239 static PyInt
2240 WinListLength(PyObject *self)
2242 win_T *w = firstwin;
2243 PyInt n = 0;
2245 while (w != NULL)
2247 ++n;
2248 w = W_NEXT(w);
2251 return n;
2254 /*ARGSUSED*/
2255 static PyObject *
2256 WinListItem(PyObject *self, PyInt n)
2258 win_T *w;
2260 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2261 if (n == 0)
2262 return WindowNew(w);
2264 PyErr_SetString(PyExc_IndexError, _("no such window"));
2265 return NULL;
2268 /* Current items object - Definitions
2271 typedef struct
2273 PyObject_HEAD
2275 CurrentObject;
2277 static PyTypeObject CurrentType = {
2278 PyObject_HEAD_INIT(0)
2280 "current data",
2281 sizeof(CurrentObject),
2284 (destructor) 0, /* tp_dealloc, refcount==0 */
2285 (printfunc) 0, /* tp_print, print x */
2286 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2287 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2288 (cmpfunc) 0, /* tp_compare, x>y */
2289 (reprfunc) 0, /* tp_repr, `x`, print x */
2291 0, /* as number */
2292 0, /* as sequence */
2293 0, /* as mapping */
2295 (hashfunc) 0, /* tp_hash, dict(x) */
2296 (ternaryfunc) 0, /* tp_call, x() */
2297 (reprfunc) 0, /* tp_str, str(x) */
2300 /* Current items object - Implementation
2302 /*ARGSUSED*/
2303 static PyObject *
2304 CurrentGetattr(PyObject *self, char *name)
2306 if (strcmp(name, "buffer") == 0)
2307 return (PyObject *)BufferNew(curbuf);
2308 else if (strcmp(name, "window") == 0)
2309 return (PyObject *)WindowNew(curwin);
2310 else if (strcmp(name, "line") == 0)
2311 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2312 else if (strcmp(name, "range") == 0)
2313 return RangeNew(curbuf, RangeStart, RangeEnd);
2314 else if (strcmp(name,"__members__") == 0)
2315 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2316 else
2318 PyErr_SetString(PyExc_AttributeError, name);
2319 return NULL;
2323 /*ARGSUSED*/
2324 static int
2325 CurrentSetattr(PyObject *self, char *name, PyObject *value)
2327 if (strcmp(name, "line") == 0)
2329 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2330 return -1;
2332 return 0;
2334 else
2336 PyErr_SetString(PyExc_AttributeError, name);
2337 return -1;
2341 /* External interface
2344 void
2345 python_buffer_free(buf_T *buf)
2347 if (buf->b_python_ref != NULL)
2349 BufferObject *bp = buf->b_python_ref;
2350 bp->buf = INVALID_BUFFER_VALUE;
2351 buf->b_python_ref = NULL;
2355 #if defined(FEAT_WINDOWS) || defined(PROTO)
2356 void
2357 python_window_free(win_T *win)
2359 if (win->w_python_ref != NULL)
2361 WindowObject *wp = win->w_python_ref;
2362 wp->win = INVALID_WINDOW_VALUE;
2363 win->w_python_ref = NULL;
2366 #endif
2368 static BufListObject TheBufferList =
2370 PyObject_HEAD_INIT(&BufListType)
2373 static WinListObject TheWindowList =
2375 PyObject_HEAD_INIT(&WinListType)
2378 static CurrentObject TheCurrent =
2380 PyObject_HEAD_INIT(&CurrentType)
2383 static int
2384 PythonMod_Init(void)
2386 PyObject *mod;
2387 PyObject *dict;
2388 /* The special value is removed from sys.path in Python_Init(). */
2389 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
2391 /* Fixups... */
2392 BufferType.ob_type = &PyType_Type;
2393 RangeType.ob_type = &PyType_Type;
2394 WindowType.ob_type = &PyType_Type;
2395 BufListType.ob_type = &PyType_Type;
2396 WinListType.ob_type = &PyType_Type;
2397 CurrentType.ob_type = &PyType_Type;
2399 /* Set sys.argv[] to avoid a crash in warn(). */
2400 PySys_SetArgv(1, argv);
2402 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
2403 dict = PyModule_GetDict(mod);
2405 VimError = Py_BuildValue("s", "vim.error");
2407 PyDict_SetItemString(dict, "error", VimError);
2408 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2409 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2410 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
2412 if (PyErr_Occurred())
2413 return -1;
2415 return 0;
2418 /*************************************************************************
2419 * 4. Utility functions for handling the interface between Vim and Python.
2422 /* Get a line from the specified buffer. The line number is
2423 * in Vim format (1-based). The line is returned as a Python
2424 * string object.
2426 static PyObject *
2427 GetBufferLine(buf_T *buf, PyInt n)
2429 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2432 /* Get a list of lines from the specified buffer. The line numbers
2433 * are in Vim format (1-based). The range is from lo up to, but not
2434 * including, hi. The list is returned as a Python list of string objects.
2436 static PyObject *
2437 GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2439 PyInt i;
2440 PyInt n = hi - lo;
2441 PyObject *list = PyList_New(n);
2443 if (list == NULL)
2444 return NULL;
2446 for (i = 0; i < n; ++i)
2448 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2450 /* Error check - was the Python string creation OK? */
2451 if (str == NULL)
2453 Py_DECREF(list);
2454 return NULL;
2457 /* Set the list item */
2458 if (PyList_SetItem(list, i, str))
2460 Py_DECREF(str);
2461 Py_DECREF(list);
2462 return NULL;
2466 /* The ownership of the Python list is passed to the caller (ie,
2467 * the caller should Py_DECREF() the object when it is finished
2468 * with it).
2471 return list;
2475 * Check if deleting lines made the cursor position invalid.
2476 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2477 * deleted).
2479 static void
2480 py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2482 if (curwin->w_cursor.lnum >= lo)
2484 /* Adjust the cursor position if it's in/after the changed
2485 * lines. */
2486 if (curwin->w_cursor.lnum >= hi)
2488 curwin->w_cursor.lnum += extra;
2489 check_cursor_col();
2491 else if (extra < 0)
2493 curwin->w_cursor.lnum = lo;
2494 check_cursor();
2496 else
2497 check_cursor_col();
2498 changed_cline_bef_curs();
2500 invalidate_botline();
2503 /* Replace a line in the specified buffer. The line number is
2504 * in Vim format (1-based). The replacement line is given as
2505 * a Python string object. The object is checked for validity
2506 * and correct format. Errors are returned as a value of FAIL.
2507 * The return value is OK on success.
2508 * If OK is returned and len_change is not NULL, *len_change
2509 * is set to the change in the buffer length.
2511 static int
2512 SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2514 /* First of all, we check the thpe of the supplied Python object.
2515 * There are three cases:
2516 * 1. NULL, or None - this is a deletion.
2517 * 2. A string - this is a replacement.
2518 * 3. Anything else - this is an error.
2520 if (line == Py_None || line == NULL)
2522 buf_T *savebuf = curbuf;
2524 PyErr_Clear();
2525 curbuf = buf;
2527 if (u_savedel((linenr_T)n, 1L) == FAIL)
2528 PyErr_SetVim(_("cannot save undo information"));
2529 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2530 PyErr_SetVim(_("cannot delete line"));
2531 else
2533 deleted_lines_mark((linenr_T)n, 1L);
2534 if (buf == curwin->w_buffer)
2535 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2538 curbuf = savebuf;
2540 if (PyErr_Occurred() || VimErrorCheck())
2541 return FAIL;
2543 if (len_change)
2544 *len_change = -1;
2546 return OK;
2548 else if (PyString_Check(line))
2550 char *save = StringToLine(line);
2551 buf_T *savebuf = curbuf;
2553 if (save == NULL)
2554 return FAIL;
2556 /* We do not need to free "save" if ml_replace() consumes it. */
2557 PyErr_Clear();
2558 curbuf = buf;
2560 if (u_savesub((linenr_T)n) == FAIL)
2562 PyErr_SetVim(_("cannot save undo information"));
2563 vim_free(save);
2565 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2567 PyErr_SetVim(_("cannot replace line"));
2568 vim_free(save);
2570 else
2571 changed_bytes((linenr_T)n, 0);
2573 curbuf = savebuf;
2575 /* Check that the cursor is not beyond the end of the line now. */
2576 if (buf == curwin->w_buffer)
2577 check_cursor_col();
2579 if (PyErr_Occurred() || VimErrorCheck())
2580 return FAIL;
2582 if (len_change)
2583 *len_change = 0;
2585 return OK;
2587 else
2589 PyErr_BadArgument();
2590 return FAIL;
2594 /* Replace a range of lines in the specified buffer. The line numbers are in
2595 * Vim format (1-based). The range is from lo up to, but not including, hi.
2596 * The replacement lines are given as a Python list of string objects. The
2597 * list is checked for validity and correct format. Errors are returned as a
2598 * value of FAIL. The return value is OK on success.
2599 * If OK is returned and len_change is not NULL, *len_change
2600 * is set to the change in the buffer length.
2602 static int
2603 SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2605 /* First of all, we check the thpe of the supplied Python object.
2606 * There are three cases:
2607 * 1. NULL, or None - this is a deletion.
2608 * 2. A list - this is a replacement.
2609 * 3. Anything else - this is an error.
2611 if (list == Py_None || list == NULL)
2613 PyInt i;
2614 PyInt n = (int)(hi - lo);
2615 buf_T *savebuf = curbuf;
2617 PyErr_Clear();
2618 curbuf = buf;
2620 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2621 PyErr_SetVim(_("cannot save undo information"));
2622 else
2624 for (i = 0; i < n; ++i)
2626 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2628 PyErr_SetVim(_("cannot delete line"));
2629 break;
2632 deleted_lines_mark((linenr_T)lo, (long)i);
2634 if (buf == curwin->w_buffer)
2635 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2638 curbuf = savebuf;
2640 if (PyErr_Occurred() || VimErrorCheck())
2641 return FAIL;
2643 if (len_change)
2644 *len_change = -n;
2646 return OK;
2648 else if (PyList_Check(list))
2650 PyInt i;
2651 PyInt new_len = PyList_Size(list);
2652 PyInt old_len = hi - lo;
2653 PyInt extra = 0; /* lines added to text, can be negative */
2654 char **array;
2655 buf_T *savebuf;
2657 if (new_len == 0) /* avoid allocating zero bytes */
2658 array = NULL;
2659 else
2661 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2662 if (array == NULL)
2664 PyErr_NoMemory();
2665 return FAIL;
2669 for (i = 0; i < new_len; ++i)
2671 PyObject *line = PyList_GetItem(list, i);
2673 array[i] = StringToLine(line);
2674 if (array[i] == NULL)
2676 while (i)
2677 vim_free(array[--i]);
2678 vim_free(array);
2679 return FAIL;
2683 savebuf = curbuf;
2685 PyErr_Clear();
2686 curbuf = buf;
2688 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2689 PyErr_SetVim(_("cannot save undo information"));
2691 /* If the size of the range is reducing (ie, new_len < old_len) we
2692 * need to delete some old_len. We do this at the start, by
2693 * repeatedly deleting line "lo".
2695 if (!PyErr_Occurred())
2697 for (i = 0; i < old_len - new_len; ++i)
2698 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2700 PyErr_SetVim(_("cannot delete line"));
2701 break;
2703 extra -= i;
2706 /* For as long as possible, replace the existing old_len with the
2707 * new old_len. This is a more efficient operation, as it requires
2708 * less memory allocation and freeing.
2710 if (!PyErr_Occurred())
2712 for (i = 0; i < old_len && i < new_len; ++i)
2713 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2714 == FAIL)
2716 PyErr_SetVim(_("cannot replace line"));
2717 break;
2720 else
2721 i = 0;
2723 /* Now we may need to insert the remaining new old_len. If we do, we
2724 * must free the strings as we finish with them (we can't pass the
2725 * responsibility to vim in this case).
2727 if (!PyErr_Occurred())
2729 while (i < new_len)
2731 if (ml_append((linenr_T)(lo + i - 1),
2732 (char_u *)array[i], 0, FALSE) == FAIL)
2734 PyErr_SetVim(_("cannot insert line"));
2735 break;
2737 vim_free(array[i]);
2738 ++i;
2739 ++extra;
2743 /* Free any left-over old_len, as a result of an error */
2744 while (i < new_len)
2746 vim_free(array[i]);
2747 ++i;
2750 /* Free the array of old_len. All of its contents have now
2751 * been dealt with (either freed, or the responsibility passed
2752 * to vim.
2754 vim_free(array);
2756 /* Adjust marks. Invalidate any which lie in the
2757 * changed range, and move any in the remainder of the buffer.
2759 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2760 (long)MAXLNUM, (long)extra);
2761 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2763 if (buf == curwin->w_buffer)
2764 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2766 curbuf = savebuf;
2768 if (PyErr_Occurred() || VimErrorCheck())
2769 return FAIL;
2771 if (len_change)
2772 *len_change = new_len - old_len;
2774 return OK;
2776 else
2778 PyErr_BadArgument();
2779 return FAIL;
2783 /* Insert a number of lines into the specified buffer after the specifed line.
2784 * The line number is in Vim format (1-based). The lines to be inserted are
2785 * given as a Python list of string objects or as a single string. The lines
2786 * to be added are checked for validity and correct format. Errors are
2787 * returned as a value of FAIL. The return value is OK on success.
2788 * If OK is returned and len_change is not NULL, *len_change
2789 * is set to the change in the buffer length.
2791 static int
2792 InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2794 /* First of all, we check the type of the supplied Python object.
2795 * It must be a string or a list, or the call is in error.
2797 if (PyString_Check(lines))
2799 char *str = StringToLine(lines);
2800 buf_T *savebuf;
2802 if (str == NULL)
2803 return FAIL;
2805 savebuf = curbuf;
2807 PyErr_Clear();
2808 curbuf = buf;
2810 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2811 PyErr_SetVim(_("cannot save undo information"));
2812 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2813 PyErr_SetVim(_("cannot insert line"));
2814 else
2815 appended_lines_mark((linenr_T)n, 1L);
2817 vim_free(str);
2818 curbuf = savebuf;
2819 update_screen(VALID);
2821 if (PyErr_Occurred() || VimErrorCheck())
2822 return FAIL;
2824 if (len_change)
2825 *len_change = 1;
2827 return OK;
2829 else if (PyList_Check(lines))
2831 PyInt i;
2832 PyInt size = PyList_Size(lines);
2833 char **array;
2834 buf_T *savebuf;
2836 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2837 if (array == NULL)
2839 PyErr_NoMemory();
2840 return FAIL;
2843 for (i = 0; i < size; ++i)
2845 PyObject *line = PyList_GetItem(lines, i);
2846 array[i] = StringToLine(line);
2848 if (array[i] == NULL)
2850 while (i)
2851 vim_free(array[--i]);
2852 vim_free(array);
2853 return FAIL;
2857 savebuf = curbuf;
2859 PyErr_Clear();
2860 curbuf = buf;
2862 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2863 PyErr_SetVim(_("cannot save undo information"));
2864 else
2866 for (i = 0; i < size; ++i)
2868 if (ml_append((linenr_T)(n + i),
2869 (char_u *)array[i], 0, FALSE) == FAIL)
2871 PyErr_SetVim(_("cannot insert line"));
2873 /* Free the rest of the lines */
2874 while (i < size)
2875 vim_free(array[i++]);
2877 break;
2879 vim_free(array[i]);
2881 if (i > 0)
2882 appended_lines_mark((linenr_T)n, (long)i);
2885 /* Free the array of lines. All of its contents have now
2886 * been freed.
2888 vim_free(array);
2890 curbuf = savebuf;
2891 update_screen(VALID);
2893 if (PyErr_Occurred() || VimErrorCheck())
2894 return FAIL;
2896 if (len_change)
2897 *len_change = size;
2899 return OK;
2901 else
2903 PyErr_BadArgument();
2904 return FAIL;
2908 /* Convert a Vim line into a Python string.
2909 * All internal newlines are replaced by null characters.
2911 * On errors, the Python exception data is set, and NULL is returned.
2913 static PyObject *
2914 LineToString(const char *str)
2916 PyObject *result;
2917 PyInt len = strlen(str);
2918 char *p;
2920 /* Allocate an Python string object, with uninitialised contents. We
2921 * must do it this way, so that we can modify the string in place
2922 * later. See the Python source, Objects/stringobject.c for details.
2924 result = PyString_FromStringAndSize(NULL, len);
2925 if (result == NULL)
2926 return NULL;
2928 p = PyString_AsString(result);
2930 while (*str)
2932 if (*str == '\n')
2933 *p = '\0';
2934 else
2935 *p = *str;
2937 ++p;
2938 ++str;
2941 return result;
2944 /* Convert a Python string into a Vim line.
2946 * The result is in allocated memory. All internal nulls are replaced by
2947 * newline characters. It is an error for the string to contain newline
2948 * characters.
2950 * On errors, the Python exception data is set, and NULL is returned.
2952 static char *
2953 StringToLine(PyObject *obj)
2955 const char *str;
2956 char *save;
2957 PyInt len;
2958 PyInt i;
2959 char *p;
2961 if (obj == NULL || !PyString_Check(obj))
2963 PyErr_BadArgument();
2964 return NULL;
2967 str = PyString_AsString(obj);
2968 len = PyString_Size(obj);
2971 * Error checking: String must not contain newlines, as we
2972 * are replacing a single line, and we must replace it with
2973 * a single line.
2974 * A trailing newline is removed, so that append(f.readlines()) works.
2976 p = memchr(str, '\n', len);
2977 if (p != NULL)
2979 if (p == str + len - 1)
2980 --len;
2981 else
2983 PyErr_SetVim(_("string cannot contain newlines"));
2984 return NULL;
2988 /* Create a copy of the string, with internal nulls replaced by
2989 * newline characters, as is the vim convention.
2991 save = (char *)alloc((unsigned)(len+1));
2992 if (save == NULL)
2994 PyErr_NoMemory();
2995 return NULL;
2998 for (i = 0; i < len; ++i)
3000 if (str[i] == '\0')
3001 save[i] = '\n';
3002 else
3003 save[i] = str[i];
3006 save[i] = '\0';
3008 return save;
3011 /* Check to see whether a Vim error has been reported, or a keyboard
3012 * interrupt has been detected.
3014 static int
3015 VimErrorCheck(void)
3017 if (got_int)
3019 PyErr_SetNone(PyExc_KeyboardInterrupt);
3020 return 1;
3022 else if (did_emsg && !PyErr_Occurred())
3024 PyErr_SetNone(VimError);
3025 return 1;
3028 return 0;
3032 /* Don't generate a prototype for the next function, it generates an error on
3033 * newer Python versions. */
3034 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3036 char *
3037 Py_GetProgramName(void)
3039 return "vim";
3041 #endif /* Python 1.4 */