Merge branch 'vim'
[MacVim/KaoriYa.git] / src / if_python.c
bloba14c6304d6c8023aa65c55012bf480f84d99e371
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 #ifdef FEAT_GUI_MACVIM
50 # include <Python/Python.h>
51 #else
52 # include <Python.h>
53 #endif
55 #if defined(MACOS) && !defined(MACOS_X_UNIX)
56 # include "macglue.h"
57 # include <CodeFragments.h>
58 #endif
59 #undef main /* Defined in python.h - aargh */
60 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
62 #if !defined(FEAT_PYTHON) && defined(PROTO)
63 /* Use this to be able to generate prototypes without python being used. */
64 # define PyObject Py_ssize_t
65 # define PyThreadState Py_ssize_t
66 # define PyTypeObject Py_ssize_t
67 struct PyMethodDef { Py_ssize_t a; };
68 # define PySequenceMethods Py_ssize_t
69 #endif
71 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
72 # define PyInt Py_ssize_t
73 # define PyInquiry lenfunc
74 # define PyIntArgFunc ssizeargfunc
75 # define PyIntIntArgFunc ssizessizeargfunc
76 # define PyIntObjArgProc ssizeobjargproc
77 # define PyIntIntObjArgProc ssizessizeobjargproc
78 # define Py_ssize_t_fmt "n"
79 #else
80 # define PyInt int
81 # define PyInquiry inquiry
82 # define PyIntArgFunc intargfunc
83 # define PyIntIntArgFunc intintargfunc
84 # define PyIntObjArgProc intobjargproc
85 # define PyIntIntObjArgProc intintobjargproc
86 # define Py_ssize_t_fmt "i"
87 #endif
89 /* Parser flags */
90 #define single_input 256
91 #define file_input 257
92 #define eval_input 258
94 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
95 /* Python 2.3: can invoke ":python" recursively. */
96 # define PY_CAN_RECURSE
97 #endif
99 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
100 # ifndef DYNAMIC_PYTHON
101 # define HINSTANCE long_u /* for generating prototypes */
102 # endif
104 /* This makes if_python.c compile without warnings against Python 2.5
105 * on Win32 and Win64. */
106 #undef PyRun_SimpleString
107 #undef PyArg_Parse
108 #undef PyArg_ParseTuple
109 #undef Py_BuildValue
110 #undef Py_InitModule4
111 #undef Py_InitModule4_64
114 * Wrapper defines
116 # define PyArg_Parse dll_PyArg_Parse
117 # define PyArg_ParseTuple dll_PyArg_ParseTuple
118 # define PyDict_SetItemString dll_PyDict_SetItemString
119 # define PyErr_BadArgument dll_PyErr_BadArgument
120 # define PyErr_Clear dll_PyErr_Clear
121 # define PyErr_NoMemory dll_PyErr_NoMemory
122 # define PyErr_Occurred dll_PyErr_Occurred
123 # define PyErr_SetNone dll_PyErr_SetNone
124 # define PyErr_SetString dll_PyErr_SetString
125 # define PyEval_InitThreads dll_PyEval_InitThreads
126 # define PyEval_RestoreThread dll_PyEval_RestoreThread
127 # define PyEval_SaveThread dll_PyEval_SaveThread
128 # ifdef PY_CAN_RECURSE
129 # define PyGILState_Ensure dll_PyGILState_Ensure
130 # define PyGILState_Release dll_PyGILState_Release
131 # endif
132 # define PyInt_AsLong dll_PyInt_AsLong
133 # define PyInt_FromLong dll_PyInt_FromLong
134 # define PyInt_Type (*dll_PyInt_Type)
135 # define PyList_GetItem dll_PyList_GetItem
136 # define PyList_Append dll_PyList_Append
137 # define PyList_New dll_PyList_New
138 # define PyList_SetItem dll_PyList_SetItem
139 # define PyList_Size dll_PyList_Size
140 # define PyList_Type (*dll_PyList_Type)
141 # define PyImport_ImportModule dll_PyImport_ImportModule
142 # define PyDict_New dll_PyDict_New
143 # define PyDict_GetItemString dll_PyDict_GetItemString
144 # define PyModule_GetDict dll_PyModule_GetDict
145 # define PyRun_SimpleString dll_PyRun_SimpleString
146 # define PyString_AsString dll_PyString_AsString
147 # define PyString_FromString dll_PyString_FromString
148 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
149 # define PyString_Size dll_PyString_Size
150 # define PyString_Type (*dll_PyString_Type)
151 # define PySys_SetObject dll_PySys_SetObject
152 # define PySys_SetArgv dll_PySys_SetArgv
153 # define PyType_Type (*dll_PyType_Type)
154 # define Py_BuildValue dll_Py_BuildValue
155 # define Py_FindMethod dll_Py_FindMethod
156 # define Py_InitModule4 dll_Py_InitModule4
157 # define Py_Initialize dll_Py_Initialize
158 # define Py_Finalize dll_Py_Finalize
159 # define Py_IsInitialized dll_Py_IsInitialized
160 # define _PyObject_New dll__PyObject_New
161 # define _Py_NoneStruct (*dll__Py_NoneStruct)
162 # define PyObject_Init dll__PyObject_Init
163 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
164 # define PyType_IsSubtype dll_PyType_IsSubtype
165 # endif
166 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
167 # define PyObject_Malloc dll_PyObject_Malloc
168 # define PyObject_Free dll_PyObject_Free
169 # endif
172 * Pointers for dynamic link
174 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
175 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
176 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
177 static int(*dll_PyErr_BadArgument)(void);
178 static void(*dll_PyErr_Clear)(void);
179 static PyObject*(*dll_PyErr_NoMemory)(void);
180 static PyObject*(*dll_PyErr_Occurred)(void);
181 static void(*dll_PyErr_SetNone)(PyObject *);
182 static void(*dll_PyErr_SetString)(PyObject *, const char *);
183 static void(*dll_PyEval_InitThreads)(void);
184 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
185 static PyThreadState*(*dll_PyEval_SaveThread)(void);
186 # ifdef PY_CAN_RECURSE
187 static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
188 static void (*dll_PyGILState_Release)(PyGILState_STATE);
189 #endif
190 static long(*dll_PyInt_AsLong)(PyObject *);
191 static PyObject*(*dll_PyInt_FromLong)(long);
192 static PyTypeObject* dll_PyInt_Type;
193 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
194 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
195 static PyObject*(*dll_PyList_New)(PyInt size);
196 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
197 static PyInt(*dll_PyList_Size)(PyObject *);
198 static PyTypeObject* dll_PyList_Type;
199 static PyObject*(*dll_PyImport_ImportModule)(const char *);
200 static PyObject*(*dll_PyDict_New)(void);
201 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
202 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
203 static int(*dll_PyRun_SimpleString)(char *);
204 static char*(*dll_PyString_AsString)(PyObject *);
205 static PyObject*(*dll_PyString_FromString)(const char *);
206 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
207 static PyInt(*dll_PyString_Size)(PyObject *);
208 static PyTypeObject* dll_PyString_Type;
209 static int(*dll_PySys_SetObject)(char *, PyObject *);
210 static int(*dll_PySys_SetArgv)(int, char **);
211 static PyTypeObject* dll_PyType_Type;
212 static PyObject*(*dll_Py_BuildValue)(char *, ...);
213 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
214 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
215 static void(*dll_Py_Initialize)(void);
216 static void(*dll_Py_Finalize)(void);
217 static int(*dll_Py_IsInitialized)(void);
218 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
219 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
220 static PyObject* dll__Py_NoneStruct;
221 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
222 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
223 # endif
224 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
225 static void* (*dll_PyObject_Malloc)(size_t);
226 static void (*dll_PyObject_Free)(void*);
227 # endif
229 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
231 /* Imported exception objects */
232 static PyObject *imp_PyExc_AttributeError;
233 static PyObject *imp_PyExc_IndexError;
234 static PyObject *imp_PyExc_KeyboardInterrupt;
235 static PyObject *imp_PyExc_TypeError;
236 static PyObject *imp_PyExc_ValueError;
238 # define PyExc_AttributeError imp_PyExc_AttributeError
239 # define PyExc_IndexError imp_PyExc_IndexError
240 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
241 # define PyExc_TypeError imp_PyExc_TypeError
242 # define PyExc_ValueError imp_PyExc_ValueError
245 * Table of name to function pointer of python.
247 # define PYTHON_PROC FARPROC
248 static struct
250 char *name;
251 PYTHON_PROC *ptr;
252 } python_funcname_table[] =
254 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
255 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
256 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
257 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
258 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
259 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
260 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
261 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
262 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
263 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
264 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
265 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
266 # ifdef PY_CAN_RECURSE
267 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
268 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
269 # endif
270 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
271 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
272 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
273 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
274 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
275 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
276 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
277 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
278 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
279 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
280 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
281 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
282 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
283 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
284 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
285 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
286 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
287 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
288 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
289 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
290 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
291 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
292 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
293 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
294 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
295 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
296 # else
297 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
298 # endif
299 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
300 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
301 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
302 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
303 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
304 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
305 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
306 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
307 # endif
308 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
309 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
310 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
311 # endif
312 {"", NULL},
316 * Free python.dll
318 static void
319 end_dynamic_python(void)
321 if (hinstPython)
323 FreeLibrary(hinstPython);
324 hinstPython = 0;
329 * Load library and get all pointers.
330 * Parameter 'libname' provides name of DLL.
331 * Return OK or FAIL.
333 static int
334 python_runtime_link_init(char *libname, int verbose)
336 int i;
338 if (hinstPython)
339 return OK;
340 hinstPython = LoadLibrary(libname);
341 if (!hinstPython)
343 if (verbose)
344 EMSG2(_(e_loadlib), libname);
345 return FAIL;
348 for (i = 0; python_funcname_table[i].ptr; ++i)
350 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
351 python_funcname_table[i].name)) == NULL)
353 FreeLibrary(hinstPython);
354 hinstPython = 0;
355 if (verbose)
356 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
357 return FAIL;
360 return OK;
364 * If python is enabled (there is installed python on Windows system) return
365 * TRUE, else FALSE.
368 python_enabled(int verbose)
370 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
373 /* Load the standard Python exceptions - don't import the symbols from the
374 * DLL, as this can cause errors (importing data symbols is not reliable).
376 static void get_exceptions __ARGS((void));
378 static void
379 get_exceptions()
381 PyObject *exmod = PyImport_ImportModule("exceptions");
382 PyObject *exdict = PyModule_GetDict(exmod);
383 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
384 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
385 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
386 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
387 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
388 Py_XINCREF(imp_PyExc_AttributeError);
389 Py_XINCREF(imp_PyExc_IndexError);
390 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
391 Py_XINCREF(imp_PyExc_TypeError);
392 Py_XINCREF(imp_PyExc_ValueError);
393 Py_XDECREF(exmod);
395 #endif /* DYNAMIC_PYTHON */
397 /******************************************************
398 * Internal function prototypes.
401 static void DoPythonCommand(exarg_T *, const char *);
402 static PyInt RangeStart;
403 static PyInt RangeEnd;
405 static void PythonIO_Flush(void);
406 static int PythonIO_Init(void);
407 static int PythonMod_Init(void);
409 /* Utility functions for the vim/python interface
410 * ----------------------------------------------
412 static PyObject *GetBufferLine(buf_T *, PyInt);
413 static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
415 static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
416 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
417 static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
419 static PyObject *LineToString(const char *);
420 static char *StringToLine(PyObject *);
422 static int VimErrorCheck(void);
424 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
426 /******************************************************
427 * 1. Python interpreter main program.
430 static int initialised = 0;
432 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
433 typedef PyObject PyThreadState;
434 #endif
436 #ifdef PY_CAN_RECURSE
437 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
438 #else
439 static PyThreadState *saved_python_thread = NULL;
440 #endif
443 * Suspend a thread of the Python interpreter, other threads are allowed to
444 * run.
446 static void
447 Python_SaveThread(void)
449 #ifdef PY_CAN_RECURSE
450 PyGILState_Release(pygilstate);
451 #else
452 saved_python_thread = PyEval_SaveThread();
453 #endif
457 * Restore a thread of the Python interpreter, waits for other threads to
458 * block.
460 static void
461 Python_RestoreThread(void)
463 #ifdef PY_CAN_RECURSE
464 pygilstate = PyGILState_Ensure();
465 #else
466 PyEval_RestoreThread(saved_python_thread);
467 saved_python_thread = NULL;
468 #endif
472 * obtain a lock on the Vim data structures
474 static void Python_Lock_Vim(void)
479 * release a lock on the Vim data structures
481 static void Python_Release_Vim(void)
485 void
486 python_end()
488 static int recurse = 0;
490 /* If a crash occurs while doing this, don't try again. */
491 if (recurse != 0)
492 return;
494 ++recurse;
496 #ifdef DYNAMIC_PYTHON
497 if (hinstPython && Py_IsInitialized())
499 Python_RestoreThread(); /* enter python */
500 Py_Finalize();
502 end_dynamic_python();
503 #else
504 if (Py_IsInitialized())
506 Python_RestoreThread(); /* enter python */
507 Py_Finalize();
509 #endif
511 --recurse;
514 static int
515 Python_Init(void)
517 if (!initialised)
519 #ifdef DYNAMIC_PYTHON
520 if (!python_enabled(TRUE))
522 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
523 goto fail;
525 #endif
527 #if !defined(MACOS) || defined(MACOS_X_UNIX)
528 Py_Initialize();
529 #else
530 PyMac_Initialize();
531 #endif
532 /* initialise threads */
533 PyEval_InitThreads();
535 #ifdef DYNAMIC_PYTHON
536 get_exceptions();
537 #endif
539 if (PythonIO_Init())
540 goto fail;
542 if (PythonMod_Init())
543 goto fail;
545 /* Remove the element from sys.path that was added because of our
546 * argv[0] value in PythonMod_Init(). Previously we used an empty
547 * string, but dependinding on the OS we then get an empty entry or
548 * the current directory in sys.path. */
549 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
551 /* the first python thread is vim's, release the lock */
552 Python_SaveThread();
554 initialised = 1;
557 return 0;
559 fail:
560 /* We call PythonIO_Flush() here to print any Python errors.
561 * This is OK, as it is possible to call this function even
562 * if PythonIO_Init() has not completed successfully (it will
563 * not do anything in this case).
565 PythonIO_Flush();
566 return -1;
570 * External interface
572 static void
573 DoPythonCommand(exarg_T *eap, const char *cmd)
575 #ifndef PY_CAN_RECURSE
576 static int recursive = 0;
577 #endif
578 #if defined(MACOS) && !defined(MACOS_X_UNIX)
579 GrafPtr oldPort;
580 #endif
581 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
582 char *saved_locale;
583 #endif
585 #ifndef PY_CAN_RECURSE
586 if (recursive)
588 EMSG(_("E659: Cannot invoke Python recursively"));
589 return;
591 ++recursive;
592 #endif
594 #if defined(MACOS) && !defined(MACOS_X_UNIX)
595 GetPort(&oldPort);
596 /* Check if the Python library is available */
597 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
598 goto theend;
599 #endif
600 if (Python_Init())
601 goto theend;
603 RangeStart = eap->line1;
604 RangeEnd = eap->line2;
605 Python_Release_Vim(); /* leave vim */
607 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
608 /* Python only works properly when the LC_NUMERIC locale is "C". */
609 saved_locale = setlocale(LC_NUMERIC, NULL);
610 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
611 saved_locale = NULL;
612 else
614 /* Need to make a copy, value may change when setting new locale. */
615 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
616 (void)setlocale(LC_NUMERIC, "C");
618 #endif
620 Python_RestoreThread(); /* enter python */
622 PyRun_SimpleString((char *)(cmd));
624 Python_SaveThread(); /* leave python */
626 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
627 if (saved_locale != NULL)
629 (void)setlocale(LC_NUMERIC, saved_locale);
630 vim_free(saved_locale);
632 #endif
634 Python_Lock_Vim(); /* enter vim */
635 PythonIO_Flush();
636 #if defined(MACOS) && !defined(MACOS_X_UNIX)
637 SetPort(oldPort);
638 #endif
640 theend:
641 #ifndef PY_CAN_RECURSE
642 --recursive;
643 #endif
644 return; /* keeps lint happy */
648 * ":python"
650 void
651 ex_python(exarg_T *eap)
653 char_u *script;
655 script = script_get(eap, eap->arg);
656 if (!eap->skip)
658 if (script == NULL)
659 DoPythonCommand(eap, (char *)eap->arg);
660 else
661 DoPythonCommand(eap, (char *)script);
663 vim_free(script);
666 #define BUFFER_SIZE 1024
669 * ":pyfile"
671 void
672 ex_pyfile(exarg_T *eap)
674 static char buffer[BUFFER_SIZE];
675 const char *file = (char *)eap->arg;
676 char *p;
678 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
679 * stdio file pointer, but Vim and the Python DLL are compiled with
680 * different options under Windows, meaning that stdio pointers aren't
681 * compatible between the two. Yuk.
683 * Put the string "execfile('file')" into buffer. But, we need to
684 * escape any backslashes or single quotes in the file name, so that
685 * Python won't mangle the file name.
687 strcpy(buffer, "execfile('");
688 p = buffer + 10; /* size of "execfile('" */
690 while (*file && p < buffer + (BUFFER_SIZE - 3))
692 if (*file == '\\' || *file == '\'')
693 *p++ = '\\';
694 *p++ = *file++;
697 /* If we didn't finish the file name, we hit a buffer overflow */
698 if (*file != '\0')
699 return;
701 /* Put in the terminating "')" and a null */
702 *p++ = '\'';
703 *p++ = ')';
704 *p++ = '\0';
706 /* Execute the file */
707 DoPythonCommand(eap, buffer);
710 /******************************************************
711 * 2. Python output stream: writes output via [e]msg().
714 /* Implementation functions
717 static PyObject *OutputGetattr(PyObject *, char *);
718 static int OutputSetattr(PyObject *, char *, PyObject *);
720 static PyObject *OutputWrite(PyObject *, PyObject *);
721 static PyObject *OutputWritelines(PyObject *, PyObject *);
723 typedef void (*writefn)(char_u *);
724 static void writer(writefn fn, char_u *str, PyInt n);
726 /* Output object definition
729 typedef struct
731 PyObject_HEAD
732 long softspace;
733 long error;
734 } OutputObject;
736 static struct PyMethodDef OutputMethods[] = {
737 /* name, function, calling, documentation */
738 {"write", OutputWrite, 1, "" },
739 {"writelines", OutputWritelines, 1, "" },
740 { NULL, NULL, 0, NULL }
743 static PyTypeObject OutputType = {
744 PyObject_HEAD_INIT(0)
746 "message",
747 sizeof(OutputObject),
750 (destructor) 0,
751 (printfunc) 0,
752 (getattrfunc) OutputGetattr,
753 (setattrfunc) OutputSetattr,
754 (cmpfunc) 0,
755 (reprfunc) 0,
757 0, /* as number */
758 0, /* as sequence */
759 0, /* as mapping */
761 (hashfunc) 0,
762 (ternaryfunc) 0,
763 (reprfunc) 0
766 /*************/
768 static PyObject *
769 OutputGetattr(PyObject *self, char *name)
771 if (strcmp(name, "softspace") == 0)
772 return PyInt_FromLong(((OutputObject *)(self))->softspace);
774 return Py_FindMethod(OutputMethods, self, name);
777 static int
778 OutputSetattr(PyObject *self, char *name, PyObject *val)
780 if (val == NULL) {
781 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
782 return -1;
785 if (strcmp(name, "softspace") == 0)
787 if (!PyInt_Check(val)) {
788 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
789 return -1;
792 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
793 return 0;
796 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
797 return -1;
800 /*************/
802 static PyObject *
803 OutputWrite(PyObject *self, PyObject *args)
805 int len;
806 char *str;
807 int error = ((OutputObject *)(self))->error;
809 if (!PyArg_ParseTuple(args, "s#", &str, &len))
810 return NULL;
812 Py_BEGIN_ALLOW_THREADS
813 Python_Lock_Vim();
814 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
815 Python_Release_Vim();
816 Py_END_ALLOW_THREADS
818 Py_INCREF(Py_None);
819 return Py_None;
822 static PyObject *
823 OutputWritelines(PyObject *self, PyObject *args)
825 PyInt n;
826 PyInt i;
827 PyObject *list;
828 int error = ((OutputObject *)(self))->error;
830 if (!PyArg_ParseTuple(args, "O", &list))
831 return NULL;
832 Py_INCREF(list);
834 if (!PyList_Check(list)) {
835 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
836 Py_DECREF(list);
837 return NULL;
840 n = PyList_Size(list);
842 for (i = 0; i < n; ++i)
844 PyObject *line = PyList_GetItem(list, i);
845 char *str;
846 PyInt len;
848 if (!PyArg_Parse(line, "s#", &str, &len)) {
849 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
850 Py_DECREF(list);
851 return NULL;
854 Py_BEGIN_ALLOW_THREADS
855 Python_Lock_Vim();
856 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
857 Python_Release_Vim();
858 Py_END_ALLOW_THREADS
861 Py_DECREF(list);
862 Py_INCREF(Py_None);
863 return Py_None;
866 /* Output buffer management
869 static char_u *buffer = NULL;
870 static PyInt buffer_len = 0;
871 static PyInt buffer_size = 0;
873 static writefn old_fn = NULL;
875 static void
876 buffer_ensure(PyInt n)
878 PyInt new_size;
879 char_u *new_buffer;
881 if (n < buffer_size)
882 return;
884 new_size = buffer_size;
885 while (new_size < n)
886 new_size += 80;
888 if (new_size != buffer_size)
890 new_buffer = alloc((unsigned)new_size);
891 if (new_buffer == NULL)
892 return;
894 if (buffer)
896 memcpy(new_buffer, buffer, buffer_len);
897 vim_free(buffer);
900 buffer = new_buffer;
901 buffer_size = new_size;
905 static void
906 PythonIO_Flush(void)
908 if (old_fn && buffer_len)
910 buffer[buffer_len] = 0;
911 old_fn(buffer);
914 buffer_len = 0;
917 static void
918 writer(writefn fn, char_u *str, PyInt n)
920 char_u *ptr;
922 if (fn != old_fn && old_fn != NULL)
923 PythonIO_Flush();
925 old_fn = fn;
927 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
929 PyInt len = ptr - str;
931 buffer_ensure(buffer_len + len + 1);
933 memcpy(buffer + buffer_len, str, len);
934 buffer_len += len;
935 buffer[buffer_len] = 0;
936 fn(buffer);
937 str = ptr + 1;
938 n -= len + 1;
939 buffer_len = 0;
942 /* Put the remaining text into the buffer for later printing */
943 buffer_ensure(buffer_len + n + 1);
944 memcpy(buffer + buffer_len, str, n);
945 buffer_len += n;
948 /***************/
950 static OutputObject Output =
952 PyObject_HEAD_INIT(&OutputType)
957 static OutputObject Error =
959 PyObject_HEAD_INIT(&OutputType)
964 static int
965 PythonIO_Init(void)
967 /* Fixups... */
968 OutputType.ob_type = &PyType_Type;
970 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
971 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
973 if (PyErr_Occurred())
975 EMSG(_("E264: Python: Error initialising I/O objects"));
976 return -1;
979 return 0;
982 /******************************************************
983 * 3. Implementation of the Vim module for Python
986 /* Vim module - Implementation functions
987 * -------------------------------------
990 static PyObject *VimError;
992 static PyObject *VimCommand(PyObject *, PyObject *);
993 static PyObject *VimEval(PyObject *, PyObject *);
995 /* Window type - Implementation functions
996 * --------------------------------------
999 typedef struct
1001 PyObject_HEAD
1002 win_T *win;
1004 WindowObject;
1006 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1008 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1010 static PyObject *WindowNew(win_T *);
1012 static void WindowDestructor(PyObject *);
1013 static PyObject *WindowGetattr(PyObject *, char *);
1014 static int WindowSetattr(PyObject *, char *, PyObject *);
1015 static PyObject *WindowRepr(PyObject *);
1017 /* Buffer type - Implementation functions
1018 * --------------------------------------
1021 typedef struct
1023 PyObject_HEAD
1024 buf_T *buf;
1026 BufferObject;
1028 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1030 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1032 static PyObject *BufferNew (buf_T *);
1034 static void BufferDestructor(PyObject *);
1035 static PyObject *BufferGetattr(PyObject *, char *);
1036 static PyObject *BufferRepr(PyObject *);
1038 static PyInt BufferLength(PyObject *);
1039 static PyObject *BufferItem(PyObject *, PyInt);
1040 static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1041 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1042 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1044 static PyObject *BufferAppend(PyObject *, PyObject *);
1045 static PyObject *BufferMark(PyObject *, PyObject *);
1046 static PyObject *BufferRange(PyObject *, PyObject *);
1048 /* Line range type - Implementation functions
1049 * --------------------------------------
1052 typedef struct
1054 PyObject_HEAD
1055 BufferObject *buf;
1056 PyInt start;
1057 PyInt end;
1059 RangeObject;
1061 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1063 static PyObject *RangeNew(buf_T *, PyInt, PyInt);
1065 static void RangeDestructor(PyObject *);
1066 static PyObject *RangeGetattr(PyObject *, char *);
1067 static PyObject *RangeRepr(PyObject *);
1069 static PyInt RangeLength(PyObject *);
1070 static PyObject *RangeItem(PyObject *, PyInt);
1071 static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1072 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1073 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1075 static PyObject *RangeAppend(PyObject *, PyObject *);
1077 /* Window list type - Implementation functions
1078 * -------------------------------------------
1081 static PyInt WinListLength(PyObject *);
1082 static PyObject *WinListItem(PyObject *, PyInt);
1084 /* Buffer list type - Implementation functions
1085 * -------------------------------------------
1088 static PyInt BufListLength(PyObject *);
1089 static PyObject *BufListItem(PyObject *, PyInt);
1091 /* Current objects type - Implementation functions
1092 * -----------------------------------------------
1095 static PyObject *CurrentGetattr(PyObject *, char *);
1096 static int CurrentSetattr(PyObject *, char *, PyObject *);
1098 /* Vim module - Definitions
1101 static struct PyMethodDef VimMethods[] = {
1102 /* name, function, calling, documentation */
1103 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1104 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
1105 { NULL, NULL, 0, NULL }
1108 /* Vim module - Implementation
1110 static PyObject *
1111 VimCommand(PyObject *self UNUSED, PyObject *args)
1113 char *cmd;
1114 PyObject *result;
1116 if (!PyArg_ParseTuple(args, "s", &cmd))
1117 return NULL;
1119 PyErr_Clear();
1121 Py_BEGIN_ALLOW_THREADS
1122 Python_Lock_Vim();
1124 do_cmdline_cmd((char_u *)cmd);
1125 update_screen(VALID);
1127 Python_Release_Vim();
1128 Py_END_ALLOW_THREADS
1130 if (VimErrorCheck())
1131 result = NULL;
1132 else
1133 result = Py_None;
1135 Py_XINCREF(result);
1136 return result;
1139 #ifdef FEAT_EVAL
1141 * Function to translate a typval_T into a PyObject; this will recursively
1142 * translate lists/dictionaries into their Python equivalents.
1144 * The depth parameter is to avoid infinite recursion, set it to 1 when
1145 * you call VimToPython.
1147 static PyObject *
1148 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1150 PyObject *result;
1151 PyObject *newObj;
1152 char ptrBuf[NUMBUFLEN];
1154 /* Avoid infinite recursion */
1155 if (depth > 100)
1157 Py_INCREF(Py_None);
1158 result = Py_None;
1159 return result;
1162 /* Check if we run into a recursive loop. The item must be in lookupDict
1163 * then and we can use it again. */
1164 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1165 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1167 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
1168 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1169 : (long_u)our_tv->vval.v_dict);
1170 result = PyDict_GetItemString(lookupDict, ptrBuf);
1171 if (result != NULL)
1173 Py_INCREF(result);
1174 return result;
1178 if (our_tv->v_type == VAR_STRING)
1180 result = Py_BuildValue("s", our_tv->vval.v_string);
1182 else if (our_tv->v_type == VAR_NUMBER)
1184 char buf[NUMBUFLEN];
1186 /* For backwards compatibility numbers are stored as strings. */
1187 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1188 result = Py_BuildValue("s", buf);
1190 # ifdef FEAT_FLOAT
1191 else if (our_tv->v_type == VAR_FLOAT)
1193 char buf[NUMBUFLEN];
1195 sprintf(buf, "%f", our_tv->vval.v_float);
1196 result = Py_BuildValue("s", buf);
1198 # endif
1199 else if (our_tv->v_type == VAR_LIST)
1201 list_T *list = our_tv->vval.v_list;
1202 listitem_T *curr;
1204 result = PyList_New(0);
1206 if (list != NULL)
1208 PyDict_SetItemString(lookupDict, ptrBuf, result);
1210 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1212 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1213 PyList_Append(result, newObj);
1214 Py_DECREF(newObj);
1218 else if (our_tv->v_type == VAR_DICT)
1220 result = PyDict_New();
1222 if (our_tv->vval.v_dict != NULL)
1224 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1225 long_u todo = ht->ht_used;
1226 hashitem_T *hi;
1227 dictitem_T *di;
1229 PyDict_SetItemString(lookupDict, ptrBuf, result);
1231 for (hi = ht->ht_array; todo > 0; ++hi)
1233 if (!HASHITEM_EMPTY(hi))
1235 --todo;
1237 di = dict_lookup(hi);
1238 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1239 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1240 Py_DECREF(newObj);
1245 else
1247 Py_INCREF(Py_None);
1248 result = Py_None;
1251 return result;
1253 #endif
1255 static PyObject *
1256 VimEval(PyObject *self UNUSED, PyObject *args)
1258 #ifdef FEAT_EVAL
1259 char *expr;
1260 typval_T *our_tv;
1261 PyObject *result;
1262 PyObject *lookup_dict;
1264 if (!PyArg_ParseTuple(args, "s", &expr))
1265 return NULL;
1267 Py_BEGIN_ALLOW_THREADS
1268 Python_Lock_Vim();
1269 our_tv = eval_expr((char_u *)expr, NULL);
1271 Python_Release_Vim();
1272 Py_END_ALLOW_THREADS
1274 if (our_tv == NULL)
1276 PyErr_SetVim(_("invalid expression"));
1277 return NULL;
1280 /* Convert the Vim type into a Python type. Create a dictionary that's
1281 * used to check for recursive loops. */
1282 lookup_dict = PyDict_New();
1283 result = VimToPython(our_tv, 1, lookup_dict);
1284 Py_DECREF(lookup_dict);
1287 Py_BEGIN_ALLOW_THREADS
1288 Python_Lock_Vim();
1289 free_tv(our_tv);
1290 Python_Release_Vim();
1291 Py_END_ALLOW_THREADS
1293 return result;
1294 #else
1295 PyErr_SetVim(_("expressions disabled at compile time"));
1296 return NULL;
1297 #endif
1300 /* Common routines for buffers and line ranges
1301 * -------------------------------------------
1303 static int
1304 CheckBuffer(BufferObject *this)
1306 if (this->buf == INVALID_BUFFER_VALUE)
1308 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1309 return -1;
1312 return 0;
1315 static PyObject *
1316 RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
1318 if (CheckBuffer(self))
1319 return NULL;
1321 if (n < 0 || n > end - start)
1323 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1324 return NULL;
1327 return GetBufferLine(self->buf, n+start);
1330 static PyObject *
1331 RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
1333 PyInt size;
1335 if (CheckBuffer(self))
1336 return NULL;
1338 size = end - start + 1;
1340 if (lo < 0)
1341 lo = 0;
1342 else if (lo > size)
1343 lo = size;
1344 if (hi < 0)
1345 hi = 0;
1346 if (hi < lo)
1347 hi = lo;
1348 else if (hi > size)
1349 hi = size;
1351 return GetBufferLineList(self->buf, lo+start, hi+start);
1354 static PyInt
1355 RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1357 PyInt len_change;
1359 if (CheckBuffer(self))
1360 return -1;
1362 if (n < 0 || n > end - start)
1364 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1365 return -1;
1368 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1369 return -1;
1371 if (new_end)
1372 *new_end = end + len_change;
1374 return 0;
1377 static PyInt
1378 RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1380 PyInt size;
1381 PyInt len_change;
1383 /* Self must be a valid buffer */
1384 if (CheckBuffer(self))
1385 return -1;
1387 /* Sort out the slice range */
1388 size = end - start + 1;
1390 if (lo < 0)
1391 lo = 0;
1392 else if (lo > size)
1393 lo = size;
1394 if (hi < 0)
1395 hi = 0;
1396 if (hi < lo)
1397 hi = lo;
1398 else if (hi > size)
1399 hi = size;
1401 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1402 return -1;
1404 if (new_end)
1405 *new_end = end + len_change;
1407 return 0;
1410 static PyObject *
1411 RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
1413 PyObject *lines;
1414 PyInt len_change;
1415 PyInt max;
1416 PyInt n;
1418 if (CheckBuffer(self))
1419 return NULL;
1421 max = n = end - start + 1;
1423 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
1424 return NULL;
1426 if (n < 0 || n > max)
1428 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1429 return NULL;
1432 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1433 return NULL;
1435 if (new_end)
1436 *new_end = end + len_change;
1438 Py_INCREF(Py_None);
1439 return Py_None;
1443 /* Buffer object - Definitions
1446 static struct PyMethodDef BufferMethods[] = {
1447 /* name, function, calling, documentation */
1448 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1449 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1450 {"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1451 { NULL, NULL, 0, NULL }
1454 static PySequenceMethods BufferAsSeq = {
1455 (PyInquiry) BufferLength, /* sq_length, len(x) */
1456 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1457 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1458 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1459 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1460 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1461 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1464 static PyTypeObject BufferType = {
1465 PyObject_HEAD_INIT(0)
1467 "buffer",
1468 sizeof(BufferObject),
1471 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1472 (printfunc) 0, /* tp_print, print x */
1473 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1474 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1475 (cmpfunc) 0, /* tp_compare, x>y */
1476 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1478 0, /* as number */
1479 &BufferAsSeq, /* as sequence */
1480 0, /* as mapping */
1482 (hashfunc) 0, /* tp_hash, dict(x) */
1483 (ternaryfunc) 0, /* tp_call, x() */
1484 (reprfunc) 0, /* tp_str, str(x) */
1487 /* Buffer object - Implementation
1490 static PyObject *
1491 BufferNew(buf_T *buf)
1493 /* We need to handle deletion of buffers underneath us.
1494 * If we add a "b_python_ref" field to the buf_T structure,
1495 * then we can get at it in buf_freeall() in vim. We then
1496 * need to create only ONE Python object per buffer - if
1497 * we try to create a second, just INCREF the existing one
1498 * and return it. The (single) Python object referring to
1499 * the buffer is stored in "b_python_ref".
1500 * Question: what to do on a buf_freeall(). We'll probably
1501 * have to either delete the Python object (DECREF it to
1502 * zero - a bad idea, as it leaves dangling refs!) or
1503 * set the buf_T * value to an invalid value (-1?), which
1504 * means we need checks in all access functions... Bah.
1507 BufferObject *self;
1509 if (buf->b_python_ref != NULL)
1511 self = buf->b_python_ref;
1512 Py_INCREF(self);
1514 else
1516 self = PyObject_NEW(BufferObject, &BufferType);
1517 if (self == NULL)
1518 return NULL;
1519 self->buf = buf;
1520 buf->b_python_ref = self;
1523 return (PyObject *)(self);
1526 static void
1527 BufferDestructor(PyObject *self)
1529 BufferObject *this = (BufferObject *)(self);
1531 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1532 this->buf->b_python_ref = NULL;
1534 Py_DECREF(self);
1537 static PyObject *
1538 BufferGetattr(PyObject *self, char *name)
1540 BufferObject *this = (BufferObject *)(self);
1542 if (CheckBuffer(this))
1543 return NULL;
1545 if (strcmp(name, "name") == 0)
1546 return Py_BuildValue("s", this->buf->b_ffname);
1547 else if (strcmp(name, "number") == 0)
1548 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
1549 else if (strcmp(name,"__members__") == 0)
1550 return Py_BuildValue("[ss]", "name", "number");
1551 else
1552 return Py_FindMethod(BufferMethods, self, name);
1555 static PyObject *
1556 BufferRepr(PyObject *self)
1558 static char repr[100];
1559 BufferObject *this = (BufferObject *)(self);
1561 if (this->buf == INVALID_BUFFER_VALUE)
1563 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
1564 return PyString_FromString(repr);
1566 else
1568 char *name = (char *)this->buf->b_fname;
1569 PyInt len;
1571 if (name == NULL)
1572 name = "";
1573 len = strlen(name);
1575 if (len > 35)
1576 name = name + (35 - len);
1578 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1580 return PyString_FromString(repr);
1584 /******************/
1586 static PyInt
1587 BufferLength(PyObject *self)
1589 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1590 if (CheckBuffer((BufferObject *)(self)))
1591 return -1; /* ??? */
1593 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1596 static PyObject *
1597 BufferItem(PyObject *self, PyInt n)
1599 return RBItem((BufferObject *)(self), n, 1,
1600 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1603 static PyObject *
1604 BufferSlice(PyObject *self, PyInt lo, PyInt hi)
1606 return RBSlice((BufferObject *)(self), lo, hi, 1,
1607 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1610 static PyInt
1611 BufferAssItem(PyObject *self, PyInt n, PyObject *val)
1613 return RBAssItem((BufferObject *)(self), n, val, 1,
1614 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1615 NULL);
1618 static PyInt
1619 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1621 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1622 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1623 NULL);
1626 static PyObject *
1627 BufferAppend(PyObject *self, PyObject *args)
1629 return RBAppend((BufferObject *)(self), args, 1,
1630 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1631 NULL);
1634 static PyObject *
1635 BufferMark(PyObject *self, PyObject *args)
1637 pos_T *posp;
1638 char mark;
1639 buf_T *curbuf_save;
1641 if (CheckBuffer((BufferObject *)(self)))
1642 return NULL;
1644 if (!PyArg_ParseTuple(args, "c", &mark))
1645 return NULL;
1647 curbuf_save = curbuf;
1648 curbuf = ((BufferObject *)(self))->buf;
1649 posp = getmark(mark, FALSE);
1650 curbuf = curbuf_save;
1652 if (posp == NULL)
1654 PyErr_SetVim(_("invalid mark name"));
1655 return NULL;
1658 /* Ckeck for keyboard interrupt */
1659 if (VimErrorCheck())
1660 return NULL;
1662 if (posp->lnum <= 0)
1664 /* Or raise an error? */
1665 Py_INCREF(Py_None);
1666 return Py_None;
1669 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1672 static PyObject *
1673 BufferRange(PyObject *self, PyObject *args)
1675 PyInt start;
1676 PyInt end;
1678 if (CheckBuffer((BufferObject *)(self)))
1679 return NULL;
1681 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
1682 return NULL;
1684 return RangeNew(((BufferObject *)(self))->buf, start, end);
1687 /* Line range object - Definitions
1690 static struct PyMethodDef RangeMethods[] = {
1691 /* name, function, calling, documentation */
1692 {"append", RangeAppend, 1, "Append data to the Vim range" },
1693 { NULL, NULL, 0, NULL }
1696 static PySequenceMethods RangeAsSeq = {
1697 (PyInquiry) RangeLength, /* sq_length, len(x) */
1698 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1699 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1700 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1701 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1702 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1703 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1706 static PyTypeObject RangeType = {
1707 PyObject_HEAD_INIT(0)
1709 "range",
1710 sizeof(RangeObject),
1713 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1714 (printfunc) 0, /* tp_print, print x */
1715 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1716 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1717 (cmpfunc) 0, /* tp_compare, x>y */
1718 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1720 0, /* as number */
1721 &RangeAsSeq, /* as sequence */
1722 0, /* as mapping */
1724 (hashfunc) 0, /* tp_hash, dict(x) */
1725 (ternaryfunc) 0, /* tp_call, x() */
1726 (reprfunc) 0, /* tp_str, str(x) */
1729 /* Line range object - Implementation
1732 static PyObject *
1733 RangeNew(buf_T *buf, PyInt start, PyInt end)
1735 BufferObject *bufr;
1736 RangeObject *self;
1737 self = PyObject_NEW(RangeObject, &RangeType);
1738 if (self == NULL)
1739 return NULL;
1741 bufr = (BufferObject *)BufferNew(buf);
1742 if (bufr == NULL)
1744 Py_DECREF(self);
1745 return NULL;
1747 Py_INCREF(bufr);
1749 self->buf = bufr;
1750 self->start = start;
1751 self->end = end;
1753 return (PyObject *)(self);
1756 static void
1757 RangeDestructor(PyObject *self)
1759 Py_DECREF(((RangeObject *)(self))->buf);
1760 Py_DECREF(self);
1763 static PyObject *
1764 RangeGetattr(PyObject *self, char *name)
1766 if (strcmp(name, "start") == 0)
1767 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
1768 else if (strcmp(name, "end") == 0)
1769 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
1770 else
1771 return Py_FindMethod(RangeMethods, self, name);
1774 static PyObject *
1775 RangeRepr(PyObject *self)
1777 static char repr[100];
1778 RangeObject *this = (RangeObject *)(self);
1780 if (this->buf->buf == INVALID_BUFFER_VALUE)
1782 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1783 (self));
1784 return PyString_FromString(repr);
1786 else
1788 char *name = (char *)this->buf->buf->b_fname;
1789 int len;
1791 if (name == NULL)
1792 name = "";
1793 len = (int)strlen(name);
1795 if (len > 45)
1796 name = name + (45 - len);
1798 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1799 len > 45 ? "..." : "", name,
1800 this->start, this->end);
1802 return PyString_FromString(repr);
1806 /****************/
1808 static PyInt
1809 RangeLength(PyObject *self)
1811 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1812 if (CheckBuffer(((RangeObject *)(self))->buf))
1813 return -1; /* ??? */
1815 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1818 static PyObject *
1819 RangeItem(PyObject *self, PyInt n)
1821 return RBItem(((RangeObject *)(self))->buf, n,
1822 ((RangeObject *)(self))->start,
1823 ((RangeObject *)(self))->end);
1826 static PyObject *
1827 RangeSlice(PyObject *self, PyInt lo, PyInt hi)
1829 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1830 ((RangeObject *)(self))->start,
1831 ((RangeObject *)(self))->end);
1834 static PyInt
1835 RangeAssItem(PyObject *self, PyInt n, PyObject *val)
1837 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1838 ((RangeObject *)(self))->start,
1839 ((RangeObject *)(self))->end,
1840 &((RangeObject *)(self))->end);
1843 static PyInt
1844 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1846 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1847 ((RangeObject *)(self))->start,
1848 ((RangeObject *)(self))->end,
1849 &((RangeObject *)(self))->end);
1852 static PyObject *
1853 RangeAppend(PyObject *self, PyObject *args)
1855 return RBAppend(((RangeObject *)(self))->buf, args,
1856 ((RangeObject *)(self))->start,
1857 ((RangeObject *)(self))->end,
1858 &((RangeObject *)(self))->end);
1861 /* Buffer list object - Definitions
1864 typedef struct
1866 PyObject_HEAD
1868 BufListObject;
1870 static PySequenceMethods BufListAsSeq = {
1871 (PyInquiry) BufListLength, /* sq_length, len(x) */
1872 (binaryfunc) 0, /* sq_concat, x+y */
1873 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1874 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1875 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1876 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1877 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1880 static PyTypeObject BufListType = {
1881 PyObject_HEAD_INIT(0)
1883 "buffer list",
1884 sizeof(BufListObject),
1887 (destructor) 0, /* tp_dealloc, refcount==0 */
1888 (printfunc) 0, /* tp_print, print x */
1889 (getattrfunc) 0, /* tp_getattr, x.attr */
1890 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1891 (cmpfunc) 0, /* tp_compare, x>y */
1892 (reprfunc) 0, /* tp_repr, `x`, print x */
1894 0, /* as number */
1895 &BufListAsSeq, /* as sequence */
1896 0, /* as mapping */
1898 (hashfunc) 0, /* tp_hash, dict(x) */
1899 (ternaryfunc) 0, /* tp_call, x() */
1900 (reprfunc) 0, /* tp_str, str(x) */
1903 /* Buffer list object - Implementation
1906 static PyInt
1907 BufListLength(PyObject *self UNUSED)
1909 buf_T *b = firstbuf;
1910 PyInt n = 0;
1912 while (b)
1914 ++n;
1915 b = b->b_next;
1918 return n;
1921 static PyObject *
1922 BufListItem(PyObject *self UNUSED, PyInt n)
1924 buf_T *b;
1926 for (b = firstbuf; b; b = b->b_next, --n)
1928 if (n == 0)
1929 return BufferNew(b);
1932 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1933 return NULL;
1936 /* Window object - Definitions
1939 static struct PyMethodDef WindowMethods[] = {
1940 /* name, function, calling, documentation */
1941 { NULL, NULL, 0, NULL }
1944 static PyTypeObject WindowType = {
1945 PyObject_HEAD_INIT(0)
1947 "window",
1948 sizeof(WindowObject),
1951 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1952 (printfunc) 0, /* tp_print, print x */
1953 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1954 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1955 (cmpfunc) 0, /* tp_compare, x>y */
1956 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1958 0, /* as number */
1959 0, /* as sequence */
1960 0, /* as mapping */
1962 (hashfunc) 0, /* tp_hash, dict(x) */
1963 (ternaryfunc) 0, /* tp_call, x() */
1964 (reprfunc) 0, /* tp_str, str(x) */
1967 /* Window object - Implementation
1970 static PyObject *
1971 WindowNew(win_T *win)
1973 /* We need to handle deletion of windows underneath us.
1974 * If we add a "w_python_ref" field to the win_T structure,
1975 * then we can get at it in win_free() in vim. We then
1976 * need to create only ONE Python object per window - if
1977 * we try to create a second, just INCREF the existing one
1978 * and return it. The (single) Python object referring to
1979 * the window is stored in "w_python_ref".
1980 * On a win_free() we set the Python object's win_T* field
1981 * to an invalid value. We trap all uses of a window
1982 * object, and reject them if the win_T* field is invalid.
1985 WindowObject *self;
1987 if (win->w_python_ref)
1989 self = win->w_python_ref;
1990 Py_INCREF(self);
1992 else
1994 self = PyObject_NEW(WindowObject, &WindowType);
1995 if (self == NULL)
1996 return NULL;
1997 self->win = win;
1998 win->w_python_ref = self;
2001 return (PyObject *)(self);
2004 static void
2005 WindowDestructor(PyObject *self)
2007 WindowObject *this = (WindowObject *)(self);
2009 if (this->win && this->win != INVALID_WINDOW_VALUE)
2010 this->win->w_python_ref = NULL;
2012 Py_DECREF(self);
2015 static int
2016 CheckWindow(WindowObject *this)
2018 if (this->win == INVALID_WINDOW_VALUE)
2020 PyErr_SetVim(_("attempt to refer to deleted window"));
2021 return -1;
2024 return 0;
2027 static PyObject *
2028 WindowGetattr(PyObject *self, char *name)
2030 WindowObject *this = (WindowObject *)(self);
2032 if (CheckWindow(this))
2033 return NULL;
2035 if (strcmp(name, "buffer") == 0)
2036 return (PyObject *)BufferNew(this->win->w_buffer);
2037 else if (strcmp(name, "cursor") == 0)
2039 pos_T *pos = &this->win->w_cursor;
2041 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2043 else if (strcmp(name, "height") == 0)
2044 return Py_BuildValue("l", (long)(this->win->w_height));
2045 #ifdef FEAT_VERTSPLIT
2046 else if (strcmp(name, "width") == 0)
2047 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2048 #endif
2049 else if (strcmp(name,"__members__") == 0)
2050 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2051 else
2052 return Py_FindMethod(WindowMethods, self, name);
2055 static int
2056 WindowSetattr(PyObject *self, char *name, PyObject *val)
2058 WindowObject *this = (WindowObject *)(self);
2060 if (CheckWindow(this))
2061 return -1;
2063 if (strcmp(name, "buffer") == 0)
2065 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2066 return -1;
2068 else if (strcmp(name, "cursor") == 0)
2070 long lnum;
2071 long col;
2072 long len;
2074 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2075 return -1;
2077 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2079 PyErr_SetVim(_("cursor position outside buffer"));
2080 return -1;
2083 /* Check for keyboard interrupts */
2084 if (VimErrorCheck())
2085 return -1;
2087 /* When column is out of range silently correct it. */
2088 len = (long)STRLEN(ml_get_buf(this->win->w_buffer, lnum, FALSE));
2089 if (col > len)
2090 col = len;
2092 this->win->w_cursor.lnum = lnum;
2093 this->win->w_cursor.col = col;
2094 #ifdef FEAT_VIRTUALEDIT
2095 this->win->w_cursor.coladd = 0;
2096 #endif
2097 update_screen(VALID);
2099 return 0;
2101 else if (strcmp(name, "height") == 0)
2103 int height;
2104 win_T *savewin;
2106 if (!PyArg_Parse(val, "i", &height))
2107 return -1;
2109 #ifdef FEAT_GUI
2110 need_mouse_correct = TRUE;
2111 #endif
2112 savewin = curwin;
2113 curwin = this->win;
2114 win_setheight(height);
2115 curwin = savewin;
2117 /* Check for keyboard interrupts */
2118 if (VimErrorCheck())
2119 return -1;
2121 return 0;
2123 #ifdef FEAT_VERTSPLIT
2124 else if (strcmp(name, "width") == 0)
2126 int width;
2127 win_T *savewin;
2129 if (!PyArg_Parse(val, "i", &width))
2130 return -1;
2132 #ifdef FEAT_GUI
2133 need_mouse_correct = TRUE;
2134 #endif
2135 savewin = curwin;
2136 curwin = this->win;
2137 win_setwidth(width);
2138 curwin = savewin;
2140 /* Check for keyboard interrupts */
2141 if (VimErrorCheck())
2142 return -1;
2144 return 0;
2146 #endif
2147 else
2149 PyErr_SetString(PyExc_AttributeError, name);
2150 return -1;
2154 static PyObject *
2155 WindowRepr(PyObject *self)
2157 static char repr[100];
2158 WindowObject *this = (WindowObject *)(self);
2160 if (this->win == INVALID_WINDOW_VALUE)
2162 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
2163 return PyString_FromString(repr);
2165 else
2167 int i = 0;
2168 win_T *w;
2170 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2171 ++i;
2173 if (w == NULL)
2174 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2175 (self));
2176 else
2177 vim_snprintf(repr, 100, _("<window %d>"), i);
2179 return PyString_FromString(repr);
2183 /* Window list object - Definitions
2186 typedef struct
2188 PyObject_HEAD
2190 WinListObject;
2192 static PySequenceMethods WinListAsSeq = {
2193 (PyInquiry) WinListLength, /* sq_length, len(x) */
2194 (binaryfunc) 0, /* sq_concat, x+y */
2195 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2196 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2197 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2198 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2199 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
2202 static PyTypeObject WinListType = {
2203 PyObject_HEAD_INIT(0)
2205 "window list",
2206 sizeof(WinListObject),
2209 (destructor) 0, /* tp_dealloc, refcount==0 */
2210 (printfunc) 0, /* tp_print, print x */
2211 (getattrfunc) 0, /* tp_getattr, x.attr */
2212 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2213 (cmpfunc) 0, /* tp_compare, x>y */
2214 (reprfunc) 0, /* tp_repr, `x`, print x */
2216 0, /* as number */
2217 &WinListAsSeq, /* as sequence */
2218 0, /* as mapping */
2220 (hashfunc) 0, /* tp_hash, dict(x) */
2221 (ternaryfunc) 0, /* tp_call, x() */
2222 (reprfunc) 0, /* tp_str, str(x) */
2225 /* Window list object - Implementation
2227 static PyInt
2228 WinListLength(PyObject *self UNUSED)
2230 win_T *w = firstwin;
2231 PyInt n = 0;
2233 while (w != NULL)
2235 ++n;
2236 w = W_NEXT(w);
2239 return n;
2242 static PyObject *
2243 WinListItem(PyObject *self UNUSED, PyInt n)
2245 win_T *w;
2247 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2248 if (n == 0)
2249 return WindowNew(w);
2251 PyErr_SetString(PyExc_IndexError, _("no such window"));
2252 return NULL;
2255 /* Current items object - Definitions
2258 typedef struct
2260 PyObject_HEAD
2262 CurrentObject;
2264 static PyTypeObject CurrentType = {
2265 PyObject_HEAD_INIT(0)
2267 "current data",
2268 sizeof(CurrentObject),
2271 (destructor) 0, /* tp_dealloc, refcount==0 */
2272 (printfunc) 0, /* tp_print, print x */
2273 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2274 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2275 (cmpfunc) 0, /* tp_compare, x>y */
2276 (reprfunc) 0, /* tp_repr, `x`, print x */
2278 0, /* as number */
2279 0, /* as sequence */
2280 0, /* as mapping */
2282 (hashfunc) 0, /* tp_hash, dict(x) */
2283 (ternaryfunc) 0, /* tp_call, x() */
2284 (reprfunc) 0, /* tp_str, str(x) */
2287 /* Current items object - Implementation
2289 static PyObject *
2290 CurrentGetattr(PyObject *self UNUSED, char *name)
2292 if (strcmp(name, "buffer") == 0)
2293 return (PyObject *)BufferNew(curbuf);
2294 else if (strcmp(name, "window") == 0)
2295 return (PyObject *)WindowNew(curwin);
2296 else if (strcmp(name, "line") == 0)
2297 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2298 else if (strcmp(name, "range") == 0)
2299 return RangeNew(curbuf, RangeStart, RangeEnd);
2300 else if (strcmp(name,"__members__") == 0)
2301 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2302 else
2304 PyErr_SetString(PyExc_AttributeError, name);
2305 return NULL;
2309 static int
2310 CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2312 if (strcmp(name, "line") == 0)
2314 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2315 return -1;
2317 return 0;
2319 else
2321 PyErr_SetString(PyExc_AttributeError, name);
2322 return -1;
2326 /* External interface
2329 void
2330 python_buffer_free(buf_T *buf)
2332 if (buf->b_python_ref != NULL)
2334 BufferObject *bp = buf->b_python_ref;
2335 bp->buf = INVALID_BUFFER_VALUE;
2336 buf->b_python_ref = NULL;
2340 #if defined(FEAT_WINDOWS) || defined(PROTO)
2341 void
2342 python_window_free(win_T *win)
2344 if (win->w_python_ref != NULL)
2346 WindowObject *wp = win->w_python_ref;
2347 wp->win = INVALID_WINDOW_VALUE;
2348 win->w_python_ref = NULL;
2351 #endif
2353 static BufListObject TheBufferList =
2355 PyObject_HEAD_INIT(&BufListType)
2358 static WinListObject TheWindowList =
2360 PyObject_HEAD_INIT(&WinListType)
2363 static CurrentObject TheCurrent =
2365 PyObject_HEAD_INIT(&CurrentType)
2368 static int
2369 PythonMod_Init(void)
2371 PyObject *mod;
2372 PyObject *dict;
2373 /* The special value is removed from sys.path in Python_Init(). */
2374 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
2376 /* Fixups... */
2377 BufferType.ob_type = &PyType_Type;
2378 RangeType.ob_type = &PyType_Type;
2379 WindowType.ob_type = &PyType_Type;
2380 BufListType.ob_type = &PyType_Type;
2381 WinListType.ob_type = &PyType_Type;
2382 CurrentType.ob_type = &PyType_Type;
2384 /* Set sys.argv[] to avoid a crash in warn(). */
2385 PySys_SetArgv(1, argv);
2387 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
2388 dict = PyModule_GetDict(mod);
2390 VimError = Py_BuildValue("s", "vim.error");
2392 PyDict_SetItemString(dict, "error", VimError);
2393 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2394 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2395 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
2397 if (PyErr_Occurred())
2398 return -1;
2400 return 0;
2403 /*************************************************************************
2404 * 4. Utility functions for handling the interface between Vim and Python.
2407 /* Get a line from the specified buffer. The line number is
2408 * in Vim format (1-based). The line is returned as a Python
2409 * string object.
2411 static PyObject *
2412 GetBufferLine(buf_T *buf, PyInt n)
2414 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2417 /* Get a list of lines from the specified buffer. The line numbers
2418 * are in Vim format (1-based). The range is from lo up to, but not
2419 * including, hi. The list is returned as a Python list of string objects.
2421 static PyObject *
2422 GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2424 PyInt i;
2425 PyInt n = hi - lo;
2426 PyObject *list = PyList_New(n);
2428 if (list == NULL)
2429 return NULL;
2431 for (i = 0; i < n; ++i)
2433 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2435 /* Error check - was the Python string creation OK? */
2436 if (str == NULL)
2438 Py_DECREF(list);
2439 return NULL;
2442 /* Set the list item */
2443 if (PyList_SetItem(list, i, str))
2445 Py_DECREF(str);
2446 Py_DECREF(list);
2447 return NULL;
2451 /* The ownership of the Python list is passed to the caller (ie,
2452 * the caller should Py_DECREF() the object when it is finished
2453 * with it).
2456 return list;
2460 * Check if deleting lines made the cursor position invalid.
2461 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2462 * deleted).
2464 static void
2465 py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2467 if (curwin->w_cursor.lnum >= lo)
2469 /* Adjust the cursor position if it's in/after the changed
2470 * lines. */
2471 if (curwin->w_cursor.lnum >= hi)
2473 curwin->w_cursor.lnum += extra;
2474 check_cursor_col();
2476 else if (extra < 0)
2478 curwin->w_cursor.lnum = lo;
2479 check_cursor();
2481 else
2482 check_cursor_col();
2483 changed_cline_bef_curs();
2485 invalidate_botline();
2488 /* Replace a line in the specified buffer. The line number is
2489 * in Vim format (1-based). The replacement line is given as
2490 * a Python string object. The object is checked for validity
2491 * and correct format. Errors are returned as a value of FAIL.
2492 * The return value is OK on success.
2493 * If OK is returned and len_change is not NULL, *len_change
2494 * is set to the change in the buffer length.
2496 static int
2497 SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2499 /* First of all, we check the thpe of the supplied Python object.
2500 * There are three cases:
2501 * 1. NULL, or None - this is a deletion.
2502 * 2. A string - this is a replacement.
2503 * 3. Anything else - this is an error.
2505 if (line == Py_None || line == NULL)
2507 buf_T *savebuf = curbuf;
2509 PyErr_Clear();
2510 curbuf = buf;
2512 if (u_savedel((linenr_T)n, 1L) == FAIL)
2513 PyErr_SetVim(_("cannot save undo information"));
2514 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2515 PyErr_SetVim(_("cannot delete line"));
2516 else
2518 if (buf == curwin->w_buffer)
2519 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2520 deleted_lines_mark((linenr_T)n, 1L);
2523 curbuf = savebuf;
2525 if (PyErr_Occurred() || VimErrorCheck())
2526 return FAIL;
2528 if (len_change)
2529 *len_change = -1;
2531 return OK;
2533 else if (PyString_Check(line))
2535 char *save = StringToLine(line);
2536 buf_T *savebuf = curbuf;
2538 if (save == NULL)
2539 return FAIL;
2541 /* We do not need to free "save" if ml_replace() consumes it. */
2542 PyErr_Clear();
2543 curbuf = buf;
2545 if (u_savesub((linenr_T)n) == FAIL)
2547 PyErr_SetVim(_("cannot save undo information"));
2548 vim_free(save);
2550 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2552 PyErr_SetVim(_("cannot replace line"));
2553 vim_free(save);
2555 else
2556 changed_bytes((linenr_T)n, 0);
2558 curbuf = savebuf;
2560 /* Check that the cursor is not beyond the end of the line now. */
2561 if (buf == curwin->w_buffer)
2562 check_cursor_col();
2564 if (PyErr_Occurred() || VimErrorCheck())
2565 return FAIL;
2567 if (len_change)
2568 *len_change = 0;
2570 return OK;
2572 else
2574 PyErr_BadArgument();
2575 return FAIL;
2579 /* Replace a range of lines in the specified buffer. The line numbers are in
2580 * Vim format (1-based). The range is from lo up to, but not including, hi.
2581 * The replacement lines are given as a Python list of string objects. The
2582 * list is checked for validity and correct format. Errors are returned as a
2583 * value of FAIL. The return value is OK on success.
2584 * If OK is returned and len_change is not NULL, *len_change
2585 * is set to the change in the buffer length.
2587 static int
2588 SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2590 /* First of all, we check the thpe of the supplied Python object.
2591 * There are three cases:
2592 * 1. NULL, or None - this is a deletion.
2593 * 2. A list - this is a replacement.
2594 * 3. Anything else - this is an error.
2596 if (list == Py_None || list == NULL)
2598 PyInt i;
2599 PyInt n = (int)(hi - lo);
2600 buf_T *savebuf = curbuf;
2602 PyErr_Clear();
2603 curbuf = buf;
2605 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2606 PyErr_SetVim(_("cannot save undo information"));
2607 else
2609 for (i = 0; i < n; ++i)
2611 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2613 PyErr_SetVim(_("cannot delete line"));
2614 break;
2617 if (buf == curwin->w_buffer)
2618 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2619 deleted_lines_mark((linenr_T)lo, (long)i);
2622 curbuf = savebuf;
2624 if (PyErr_Occurred() || VimErrorCheck())
2625 return FAIL;
2627 if (len_change)
2628 *len_change = -n;
2630 return OK;
2632 else if (PyList_Check(list))
2634 PyInt i;
2635 PyInt new_len = PyList_Size(list);
2636 PyInt old_len = hi - lo;
2637 PyInt extra = 0; /* lines added to text, can be negative */
2638 char **array;
2639 buf_T *savebuf;
2641 if (new_len == 0) /* avoid allocating zero bytes */
2642 array = NULL;
2643 else
2645 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2646 if (array == NULL)
2648 PyErr_NoMemory();
2649 return FAIL;
2653 for (i = 0; i < new_len; ++i)
2655 PyObject *line = PyList_GetItem(list, i);
2657 array[i] = StringToLine(line);
2658 if (array[i] == NULL)
2660 while (i)
2661 vim_free(array[--i]);
2662 vim_free(array);
2663 return FAIL;
2667 savebuf = curbuf;
2669 PyErr_Clear();
2670 curbuf = buf;
2672 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2673 PyErr_SetVim(_("cannot save undo information"));
2675 /* If the size of the range is reducing (ie, new_len < old_len) we
2676 * need to delete some old_len. We do this at the start, by
2677 * repeatedly deleting line "lo".
2679 if (!PyErr_Occurred())
2681 for (i = 0; i < old_len - new_len; ++i)
2682 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2684 PyErr_SetVim(_("cannot delete line"));
2685 break;
2687 extra -= i;
2690 /* For as long as possible, replace the existing old_len with the
2691 * new old_len. This is a more efficient operation, as it requires
2692 * less memory allocation and freeing.
2694 if (!PyErr_Occurred())
2696 for (i = 0; i < old_len && i < new_len; ++i)
2697 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2698 == FAIL)
2700 PyErr_SetVim(_("cannot replace line"));
2701 break;
2704 else
2705 i = 0;
2707 /* Now we may need to insert the remaining new old_len. If we do, we
2708 * must free the strings as we finish with them (we can't pass the
2709 * responsibility to vim in this case).
2711 if (!PyErr_Occurred())
2713 while (i < new_len)
2715 if (ml_append((linenr_T)(lo + i - 1),
2716 (char_u *)array[i], 0, FALSE) == FAIL)
2718 PyErr_SetVim(_("cannot insert line"));
2719 break;
2721 vim_free(array[i]);
2722 ++i;
2723 ++extra;
2727 /* Free any left-over old_len, as a result of an error */
2728 while (i < new_len)
2730 vim_free(array[i]);
2731 ++i;
2734 /* Free the array of old_len. All of its contents have now
2735 * been dealt with (either freed, or the responsibility passed
2736 * to vim.
2738 vim_free(array);
2740 /* Adjust marks. Invalidate any which lie in the
2741 * changed range, and move any in the remainder of the buffer.
2743 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2744 (long)MAXLNUM, (long)extra);
2745 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2747 if (buf == curwin->w_buffer)
2748 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2750 curbuf = savebuf;
2752 if (PyErr_Occurred() || VimErrorCheck())
2753 return FAIL;
2755 if (len_change)
2756 *len_change = new_len - old_len;
2758 return OK;
2760 else
2762 PyErr_BadArgument();
2763 return FAIL;
2767 /* Insert a number of lines into the specified buffer after the specifed line.
2768 * The line number is in Vim format (1-based). The lines to be inserted are
2769 * given as a Python list of string objects or as a single string. The lines
2770 * to be added are checked for validity and correct format. Errors are
2771 * returned as a value of FAIL. The return value is OK on success.
2772 * If OK is returned and len_change is not NULL, *len_change
2773 * is set to the change in the buffer length.
2775 static int
2776 InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2778 /* First of all, we check the type of the supplied Python object.
2779 * It must be a string or a list, or the call is in error.
2781 if (PyString_Check(lines))
2783 char *str = StringToLine(lines);
2784 buf_T *savebuf;
2786 if (str == NULL)
2787 return FAIL;
2789 savebuf = curbuf;
2791 PyErr_Clear();
2792 curbuf = buf;
2794 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2795 PyErr_SetVim(_("cannot save undo information"));
2796 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2797 PyErr_SetVim(_("cannot insert line"));
2798 else
2799 appended_lines_mark((linenr_T)n, 1L);
2801 vim_free(str);
2802 curbuf = savebuf;
2803 update_screen(VALID);
2805 if (PyErr_Occurred() || VimErrorCheck())
2806 return FAIL;
2808 if (len_change)
2809 *len_change = 1;
2811 return OK;
2813 else if (PyList_Check(lines))
2815 PyInt i;
2816 PyInt size = PyList_Size(lines);
2817 char **array;
2818 buf_T *savebuf;
2820 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2821 if (array == NULL)
2823 PyErr_NoMemory();
2824 return FAIL;
2827 for (i = 0; i < size; ++i)
2829 PyObject *line = PyList_GetItem(lines, i);
2830 array[i] = StringToLine(line);
2832 if (array[i] == NULL)
2834 while (i)
2835 vim_free(array[--i]);
2836 vim_free(array);
2837 return FAIL;
2841 savebuf = curbuf;
2843 PyErr_Clear();
2844 curbuf = buf;
2846 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2847 PyErr_SetVim(_("cannot save undo information"));
2848 else
2850 for (i = 0; i < size; ++i)
2852 if (ml_append((linenr_T)(n + i),
2853 (char_u *)array[i], 0, FALSE) == FAIL)
2855 PyErr_SetVim(_("cannot insert line"));
2857 /* Free the rest of the lines */
2858 while (i < size)
2859 vim_free(array[i++]);
2861 break;
2863 vim_free(array[i]);
2865 if (i > 0)
2866 appended_lines_mark((linenr_T)n, (long)i);
2869 /* Free the array of lines. All of its contents have now
2870 * been freed.
2872 vim_free(array);
2874 curbuf = savebuf;
2875 update_screen(VALID);
2877 if (PyErr_Occurred() || VimErrorCheck())
2878 return FAIL;
2880 if (len_change)
2881 *len_change = size;
2883 return OK;
2885 else
2887 PyErr_BadArgument();
2888 return FAIL;
2892 /* Convert a Vim line into a Python string.
2893 * All internal newlines are replaced by null characters.
2895 * On errors, the Python exception data is set, and NULL is returned.
2897 static PyObject *
2898 LineToString(const char *str)
2900 PyObject *result;
2901 PyInt len = strlen(str);
2902 char *p;
2904 /* Allocate an Python string object, with uninitialised contents. We
2905 * must do it this way, so that we can modify the string in place
2906 * later. See the Python source, Objects/stringobject.c for details.
2908 result = PyString_FromStringAndSize(NULL, len);
2909 if (result == NULL)
2910 return NULL;
2912 p = PyString_AsString(result);
2914 while (*str)
2916 if (*str == '\n')
2917 *p = '\0';
2918 else
2919 *p = *str;
2921 ++p;
2922 ++str;
2925 return result;
2928 /* Convert a Python string into a Vim line.
2930 * The result is in allocated memory. All internal nulls are replaced by
2931 * newline characters. It is an error for the string to contain newline
2932 * characters.
2934 * On errors, the Python exception data is set, and NULL is returned.
2936 static char *
2937 StringToLine(PyObject *obj)
2939 const char *str;
2940 char *save;
2941 PyInt len;
2942 PyInt i;
2943 char *p;
2945 if (obj == NULL || !PyString_Check(obj))
2947 PyErr_BadArgument();
2948 return NULL;
2951 str = PyString_AsString(obj);
2952 len = PyString_Size(obj);
2955 * Error checking: String must not contain newlines, as we
2956 * are replacing a single line, and we must replace it with
2957 * a single line.
2958 * A trailing newline is removed, so that append(f.readlines()) works.
2960 p = memchr(str, '\n', len);
2961 if (p != NULL)
2963 if (p == str + len - 1)
2964 --len;
2965 else
2967 PyErr_SetVim(_("string cannot contain newlines"));
2968 return NULL;
2972 /* Create a copy of the string, with internal nulls replaced by
2973 * newline characters, as is the vim convention.
2975 save = (char *)alloc((unsigned)(len+1));
2976 if (save == NULL)
2978 PyErr_NoMemory();
2979 return NULL;
2982 for (i = 0; i < len; ++i)
2984 if (str[i] == '\0')
2985 save[i] = '\n';
2986 else
2987 save[i] = str[i];
2990 save[i] = '\0';
2992 return save;
2995 /* Check to see whether a Vim error has been reported, or a keyboard
2996 * interrupt has been detected.
2998 static int
2999 VimErrorCheck(void)
3001 if (got_int)
3003 PyErr_SetNone(PyExc_KeyboardInterrupt);
3004 return 1;
3006 else if (did_emsg && !PyErr_Occurred())
3008 PyErr_SetNone(VimError);
3009 return 1;
3012 return 0;
3016 /* Don't generate a prototype for the next function, it generates an error on
3017 * newer Python versions. */
3018 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3020 char *
3021 Py_GetProgramName(void)
3023 return "vim";
3025 #endif /* Python 1.4 */