Merged from the latest developing branch.
[MacVim/KaoriYa.git] / src / if_python.c
blob09510d538f80005ef726b65a13151c18ffbc1778
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 int
54 # define PyThreadState int
55 # define PyTypeObject int
56 struct PyMethodDef { int a; };
57 # define PySequenceMethods int
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 #else
68 # define PyInt int
69 # define PyInquiry inquiry
70 # define PyIntArgFunc intargfunc
71 # define PyIntIntArgFunc intintargfunc
72 # define PyIntObjArgProc intobjargproc
73 # define PyIntIntObjArgProc intintobjargproc
74 #endif
76 /* Parser flags */
77 #define single_input 256
78 #define file_input 257
79 #define eval_input 258
81 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
82 /* Python 2.3: can invoke ":python" recursively. */
83 # define PY_CAN_RECURSE
84 #endif
86 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
87 # ifndef DYNAMIC_PYTHON
88 # define HINSTANCE int /* for generating prototypes */
89 # endif
92 * Wrapper defines
94 # define PyArg_Parse dll_PyArg_Parse
95 # define PyArg_ParseTuple dll_PyArg_ParseTuple
96 # define PyDict_SetItemString dll_PyDict_SetItemString
97 # define PyErr_BadArgument dll_PyErr_BadArgument
98 # define PyErr_Clear dll_PyErr_Clear
99 # define PyErr_NoMemory dll_PyErr_NoMemory
100 # define PyErr_Occurred dll_PyErr_Occurred
101 # define PyErr_SetNone dll_PyErr_SetNone
102 # define PyErr_SetString dll_PyErr_SetString
103 # define PyEval_InitThreads dll_PyEval_InitThreads
104 # define PyEval_RestoreThread dll_PyEval_RestoreThread
105 # define PyEval_SaveThread dll_PyEval_SaveThread
106 # ifdef PY_CAN_RECURSE
107 # define PyGILState_Ensure dll_PyGILState_Ensure
108 # define PyGILState_Release dll_PyGILState_Release
109 # endif
110 # define PyInt_AsLong dll_PyInt_AsLong
111 # define PyInt_FromLong dll_PyInt_FromLong
112 # define PyInt_Type (*dll_PyInt_Type)
113 # define PyList_GetItem dll_PyList_GetItem
114 # define PyList_Append dll_PyList_Append
115 # define PyList_New dll_PyList_New
116 # define PyList_SetItem dll_PyList_SetItem
117 # define PyList_Size dll_PyList_Size
118 # define PyList_Type (*dll_PyList_Type)
119 # define PyImport_ImportModule dll_PyImport_ImportModule
120 # define PyDict_New dll_PyDict_New
121 # define PyDict_GetItemString dll_PyDict_GetItemString
122 # define PyModule_GetDict dll_PyModule_GetDict
123 # define PyRun_SimpleString dll_PyRun_SimpleString
124 # define PyString_AsString dll_PyString_AsString
125 # define PyString_FromString dll_PyString_FromString
126 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
127 # define PyString_Size dll_PyString_Size
128 # define PyString_Type (*dll_PyString_Type)
129 # define PySys_SetObject dll_PySys_SetObject
130 # define PySys_SetArgv dll_PySys_SetArgv
131 # define PyType_Type (*dll_PyType_Type)
132 # define Py_BuildValue dll_Py_BuildValue
133 # define Py_FindMethod dll_Py_FindMethod
134 # define Py_InitModule4 dll_Py_InitModule4
135 # define Py_Initialize dll_Py_Initialize
136 # define Py_Finalize dll_Py_Finalize
137 # define Py_IsInitialized dll_Py_IsInitialized
138 # define _PyObject_New dll__PyObject_New
139 # define _Py_NoneStruct (*dll__Py_NoneStruct)
140 # define PyObject_Init dll__PyObject_Init
141 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
142 # define PyType_IsSubtype dll_PyType_IsSubtype
143 # endif
144 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
145 # define PyObject_Malloc dll_PyObject_Malloc
146 # define PyObject_Free dll_PyObject_Free
147 # endif
150 * Pointers for dynamic link
152 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
153 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
154 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
155 static int(*dll_PyErr_BadArgument)(void);
156 static void(*dll_PyErr_Clear)(void);
157 static PyObject*(*dll_PyErr_NoMemory)(void);
158 static PyObject*(*dll_PyErr_Occurred)(void);
159 static void(*dll_PyErr_SetNone)(PyObject *);
160 static void(*dll_PyErr_SetString)(PyObject *, const char *);
161 static void(*dll_PyEval_InitThreads)(void);
162 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
163 static PyThreadState*(*dll_PyEval_SaveThread)(void);
164 # ifdef PY_CAN_RECURSE
165 static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
166 static void (*dll_PyGILState_Release)(PyGILState_STATE);
167 #endif
168 static long(*dll_PyInt_AsLong)(PyObject *);
169 static PyObject*(*dll_PyInt_FromLong)(long);
170 static PyTypeObject* dll_PyInt_Type;
171 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
172 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
173 static PyObject*(*dll_PyList_New)(PyInt size);
174 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
175 static PyInt(*dll_PyList_Size)(PyObject *);
176 static PyTypeObject* dll_PyList_Type;
177 static PyObject*(*dll_PyImport_ImportModule)(const char *);
178 static PyObject*(*dll_PyDict_New)(void);
179 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
180 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
181 static int(*dll_PyRun_SimpleString)(char *);
182 static char*(*dll_PyString_AsString)(PyObject *);
183 static PyObject*(*dll_PyString_FromString)(const char *);
184 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
185 static PyInt(*dll_PyString_Size)(PyObject *);
186 static PyTypeObject* dll_PyString_Type;
187 static int(*dll_PySys_SetObject)(char *, PyObject *);
188 static int(*dll_PySys_SetArgv)(int, char **);
189 static PyTypeObject* dll_PyType_Type;
190 static PyObject*(*dll_Py_BuildValue)(char *, ...);
191 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
192 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
193 static void(*dll_Py_Initialize)(void);
194 static void(*dll_Py_Finalize)(void);
195 static int(*dll_Py_IsInitialized)(void);
196 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
197 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
198 static PyObject* dll__Py_NoneStruct;
199 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
200 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
201 # endif
202 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
203 static void* (*dll_PyObject_Malloc)(size_t);
204 static void (*dll_PyObject_Free)(void*);
205 # endif
207 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
209 /* Imported exception objects */
210 static PyObject *imp_PyExc_AttributeError;
211 static PyObject *imp_PyExc_IndexError;
212 static PyObject *imp_PyExc_KeyboardInterrupt;
213 static PyObject *imp_PyExc_TypeError;
214 static PyObject *imp_PyExc_ValueError;
216 # define PyExc_AttributeError imp_PyExc_AttributeError
217 # define PyExc_IndexError imp_PyExc_IndexError
218 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
219 # define PyExc_TypeError imp_PyExc_TypeError
220 # define PyExc_ValueError imp_PyExc_ValueError
223 * Table of name to function pointer of python.
225 # define PYTHON_PROC FARPROC
226 static struct
228 char *name;
229 PYTHON_PROC *ptr;
230 } python_funcname_table[] =
232 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
233 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
234 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
235 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
236 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
237 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
238 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
239 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
240 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
241 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
242 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
243 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
244 # ifdef PY_CAN_RECURSE
245 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
246 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
247 # endif
248 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
249 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
250 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
251 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
252 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
253 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
254 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
255 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
256 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
257 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
258 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
259 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
260 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
261 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
262 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
263 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
264 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
265 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
266 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
267 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
268 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
269 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
270 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
271 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
272 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
273 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
274 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
275 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
276 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
277 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
278 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
279 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
280 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
281 # endif
282 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
283 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
284 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
285 # endif
286 {"", NULL},
290 * Free python.dll
292 static void
293 end_dynamic_python(void)
295 if (hinstPython)
297 FreeLibrary(hinstPython);
298 hinstPython = 0;
303 * Load library and get all pointers.
304 * Parameter 'libname' provides name of DLL.
305 * Return OK or FAIL.
307 static int
308 python_runtime_link_init(char *libname, int verbose)
310 int i;
312 if (hinstPython)
313 return OK;
314 hinstPython = LoadLibrary(libname);
315 if (!hinstPython)
317 if (verbose)
318 EMSG2(_(e_loadlib), libname);
319 return FAIL;
322 for (i = 0; python_funcname_table[i].ptr; ++i)
324 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
325 python_funcname_table[i].name)) == NULL)
327 FreeLibrary(hinstPython);
328 hinstPython = 0;
329 if (verbose)
330 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
331 return FAIL;
334 return OK;
338 * If python is enabled (there is installed python on Windows system) return
339 * TRUE, else FALSE.
342 python_enabled(verbose)
343 int verbose;
345 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
348 /* Load the standard Python exceptions - don't import the symbols from the
349 * DLL, as this can cause errors (importing data symbols is not reliable).
351 static void get_exceptions __ARGS((void));
353 static void
354 get_exceptions()
356 PyObject *exmod = PyImport_ImportModule("exceptions");
357 PyObject *exdict = PyModule_GetDict(exmod);
358 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
359 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
360 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
361 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
362 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
363 Py_XINCREF(imp_PyExc_AttributeError);
364 Py_XINCREF(imp_PyExc_IndexError);
365 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
366 Py_XINCREF(imp_PyExc_TypeError);
367 Py_XINCREF(imp_PyExc_ValueError);
368 Py_XDECREF(exmod);
370 #endif /* DYNAMIC_PYTHON */
372 /******************************************************
373 * Internal function prototypes.
376 static void DoPythonCommand(exarg_T *, const char *);
377 static int RangeStart;
378 static int RangeEnd;
380 static void PythonIO_Flush(void);
381 static int PythonIO_Init(void);
382 static int PythonMod_Init(void);
384 /* Utility functions for the vim/python interface
385 * ----------------------------------------------
387 static PyObject *GetBufferLine(buf_T *, int);
388 static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
390 static int SetBufferLine(buf_T *, int, PyObject *, int *);
391 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, int *);
392 static int InsertBufferLines(buf_T *, int, PyObject *, int *);
394 static PyObject *LineToString(const char *);
395 static char *StringToLine(PyObject *);
397 static int VimErrorCheck(void);
399 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
401 /******************************************************
402 * 1. Python interpreter main program.
405 static int initialised = 0;
407 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
408 typedef PyObject PyThreadState;
409 #endif
411 #ifdef PY_CAN_RECURSE
412 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
413 #else
414 static PyThreadState *saved_python_thread = NULL;
415 #endif
418 * Suspend a thread of the Python interpreter, other threads are allowed to
419 * run.
421 static void
422 Python_SaveThread(void)
424 #ifdef PY_CAN_RECURSE
425 PyGILState_Release(pygilstate);
426 #else
427 saved_python_thread = PyEval_SaveThread();
428 #endif
432 * Restore a thread of the Python interpreter, waits for other threads to
433 * block.
435 static void
436 Python_RestoreThread(void)
438 #ifdef PY_CAN_RECURSE
439 pygilstate = PyGILState_Ensure();
440 #else
441 PyEval_RestoreThread(saved_python_thread);
442 saved_python_thread = NULL;
443 #endif
447 * obtain a lock on the Vim data structures
449 static void Python_Lock_Vim(void)
454 * release a lock on the Vim data structures
456 static void Python_Release_Vim(void)
460 void
461 python_end()
463 static int recurse = 0;
465 /* If a crash occurs while doing this, don't try again. */
466 if (recurse != 0)
467 return;
469 ++recurse;
471 #ifdef DYNAMIC_PYTHON
472 if (hinstPython && Py_IsInitialized())
474 Python_RestoreThread(); /* enter python */
475 Py_Finalize();
477 end_dynamic_python();
478 #else
479 if (Py_IsInitialized())
481 Python_RestoreThread(); /* enter python */
482 Py_Finalize();
484 #endif
486 --recurse;
489 static int
490 Python_Init(void)
492 if (!initialised)
494 #ifdef DYNAMIC_PYTHON
495 if (!python_enabled(TRUE))
497 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
498 goto fail;
500 #endif
502 #if !defined(MACOS) || defined(MACOS_X_UNIX)
503 Py_Initialize();
504 #else
505 PyMac_Initialize();
506 #endif
507 /* initialise threads */
508 PyEval_InitThreads();
510 #ifdef DYNAMIC_PYTHON
511 get_exceptions();
512 #endif
514 if (PythonIO_Init())
515 goto fail;
517 if (PythonMod_Init())
518 goto fail;
520 /* the first python thread is vim's, release the lock */
521 Python_SaveThread();
523 initialised = 1;
526 return 0;
528 fail:
529 /* We call PythonIO_Flush() here to print any Python errors.
530 * This is OK, as it is possible to call this function even
531 * if PythonIO_Init() has not completed successfully (it will
532 * not do anything in this case).
534 PythonIO_Flush();
535 return -1;
539 * External interface
541 static void
542 DoPythonCommand(exarg_T *eap, const char *cmd)
544 #ifndef PY_CAN_RECURSE
545 static int recursive = 0;
546 #endif
547 #if defined(MACOS) && !defined(MACOS_X_UNIX)
548 GrafPtr oldPort;
549 #endif
550 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
551 char *saved_locale;
552 #endif
554 #ifndef PY_CAN_RECURSE
555 if (recursive)
557 EMSG(_("E659: Cannot invoke Python recursively"));
558 return;
560 ++recursive;
561 #endif
563 #if defined(MACOS) && !defined(MACOS_X_UNIX)
564 GetPort(&oldPort);
565 /* Check if the Python library is available */
566 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
567 goto theend;
568 #endif
569 if (Python_Init())
570 goto theend;
572 RangeStart = eap->line1;
573 RangeEnd = eap->line2;
574 Python_Release_Vim(); /* leave vim */
576 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
577 /* Python only works properly when the LC_NUMERIC locale is "C". */
578 saved_locale = setlocale(LC_NUMERIC, NULL);
579 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
580 saved_locale = NULL;
581 else
583 /* Need to make a copy, value may change when setting new locale. */
584 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
585 (void)setlocale(LC_NUMERIC, "C");
587 #endif
589 Python_RestoreThread(); /* enter python */
591 PyRun_SimpleString((char *)(cmd));
593 Python_SaveThread(); /* leave python */
595 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
596 if (saved_locale != NULL)
598 (void)setlocale(LC_NUMERIC, saved_locale);
599 vim_free(saved_locale);
601 #endif
603 Python_Lock_Vim(); /* enter vim */
604 PythonIO_Flush();
605 #if defined(MACOS) && !defined(MACOS_X_UNIX)
606 SetPort(oldPort);
607 #endif
609 theend:
610 #ifndef PY_CAN_RECURSE
611 --recursive;
612 #endif
613 return; /* keeps lint happy */
617 * ":python"
619 void
620 ex_python(exarg_T *eap)
622 char_u *script;
624 script = script_get(eap, eap->arg);
625 if (!eap->skip)
627 if (script == NULL)
628 DoPythonCommand(eap, (char *)eap->arg);
629 else
630 DoPythonCommand(eap, (char *)script);
632 vim_free(script);
635 #define BUFFER_SIZE 1024
638 * ":pyfile"
640 void
641 ex_pyfile(exarg_T *eap)
643 static char buffer[BUFFER_SIZE];
644 const char *file = (char *)eap->arg;
645 char *p;
647 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
648 * stdio file pointer, but Vim and the Python DLL are compiled with
649 * different options under Windows, meaning that stdio pointers aren't
650 * compatible between the two. Yuk.
652 * Put the string "execfile('file')" into buffer. But, we need to
653 * escape any backslashes or single quotes in the file name, so that
654 * Python won't mangle the file name.
656 strcpy(buffer, "execfile('");
657 p = buffer + 10; /* size of "execfile('" */
659 while (*file && p < buffer + (BUFFER_SIZE - 3))
661 if (*file == '\\' || *file == '\'')
662 *p++ = '\\';
663 *p++ = *file++;
666 /* If we didn't finish the file name, we hit a buffer overflow */
667 if (*file != '\0')
668 return;
670 /* Put in the terminating "')" and a null */
671 *p++ = '\'';
672 *p++ = ')';
673 *p++ = '\0';
675 /* Execute the file */
676 DoPythonCommand(eap, buffer);
679 /******************************************************
680 * 2. Python output stream: writes output via [e]msg().
683 /* Implementation functions
686 static PyObject *OutputGetattr(PyObject *, char *);
687 static int OutputSetattr(PyObject *, char *, PyObject *);
689 static PyObject *OutputWrite(PyObject *, PyObject *);
690 static PyObject *OutputWritelines(PyObject *, PyObject *);
692 typedef void (*writefn)(char_u *);
693 static void writer(writefn fn, char_u *str, int n);
695 /* Output object definition
698 typedef struct
700 PyObject_HEAD
701 long softspace;
702 long error;
703 } OutputObject;
705 static struct PyMethodDef OutputMethods[] = {
706 /* name, function, calling, documentation */
707 {"write", OutputWrite, 1, "" },
708 {"writelines", OutputWritelines, 1, "" },
709 { NULL, NULL, 0, NULL }
712 static PyTypeObject OutputType = {
713 PyObject_HEAD_INIT(0)
715 "message",
716 sizeof(OutputObject),
719 (destructor) 0,
720 (printfunc) 0,
721 (getattrfunc) OutputGetattr,
722 (setattrfunc) OutputSetattr,
723 (cmpfunc) 0,
724 (reprfunc) 0,
726 0, /* as number */
727 0, /* as sequence */
728 0, /* as mapping */
730 (hashfunc) 0,
731 (ternaryfunc) 0,
732 (reprfunc) 0
735 /*************/
737 static PyObject *
738 OutputGetattr(PyObject *self, char *name)
740 if (strcmp(name, "softspace") == 0)
741 return PyInt_FromLong(((OutputObject *)(self))->softspace);
743 return Py_FindMethod(OutputMethods, self, name);
746 static int
747 OutputSetattr(PyObject *self, char *name, PyObject *val)
749 if (val == NULL) {
750 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
751 return -1;
754 if (strcmp(name, "softspace") == 0)
756 if (!PyInt_Check(val)) {
757 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
758 return -1;
761 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
762 return 0;
765 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
766 return -1;
769 /*************/
771 static PyObject *
772 OutputWrite(PyObject *self, PyObject *args)
774 int len;
775 char *str;
776 int error = ((OutputObject *)(self))->error;
778 if (!PyArg_ParseTuple(args, "s#", &str, &len))
779 return NULL;
781 Py_BEGIN_ALLOW_THREADS
782 Python_Lock_Vim();
783 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
784 Python_Release_Vim();
785 Py_END_ALLOW_THREADS
787 Py_INCREF(Py_None);
788 return Py_None;
791 static PyObject *
792 OutputWritelines(PyObject *self, PyObject *args)
794 PyInt n;
795 PyInt i;
796 PyObject *list;
797 int error = ((OutputObject *)(self))->error;
799 if (!PyArg_ParseTuple(args, "O", &list))
800 return NULL;
801 Py_INCREF(list);
803 if (!PyList_Check(list)) {
804 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
805 Py_DECREF(list);
806 return NULL;
809 n = PyList_Size(list);
811 for (i = 0; i < n; ++i)
813 PyObject *line = PyList_GetItem(list, i);
814 char *str;
815 int len;
817 if (!PyArg_Parse(line, "s#", &str, &len)) {
818 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
819 Py_DECREF(list);
820 return NULL;
823 Py_BEGIN_ALLOW_THREADS
824 Python_Lock_Vim();
825 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
826 Python_Release_Vim();
827 Py_END_ALLOW_THREADS
830 Py_DECREF(list);
831 Py_INCREF(Py_None);
832 return Py_None;
835 /* Output buffer management
838 static char_u *buffer = NULL;
839 static int buffer_len = 0;
840 static int buffer_size = 0;
842 static writefn old_fn = NULL;
844 static void
845 buffer_ensure(int n)
847 int new_size;
848 char_u *new_buffer;
850 if (n < buffer_size)
851 return;
853 new_size = buffer_size;
854 while (new_size < n)
855 new_size += 80;
857 if (new_size != buffer_size)
859 new_buffer = alloc((unsigned)new_size);
860 if (new_buffer == NULL)
861 return;
863 if (buffer)
865 memcpy(new_buffer, buffer, buffer_len);
866 vim_free(buffer);
869 buffer = new_buffer;
870 buffer_size = new_size;
874 static void
875 PythonIO_Flush(void)
877 if (old_fn && buffer_len)
879 buffer[buffer_len] = 0;
880 old_fn(buffer);
883 buffer_len = 0;
886 static void
887 writer(writefn fn, char_u *str, int n)
889 char_u *ptr;
891 if (fn != old_fn && old_fn != NULL)
892 PythonIO_Flush();
894 old_fn = fn;
896 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
898 int len = ptr - str;
900 buffer_ensure(buffer_len + len + 1);
902 memcpy(buffer + buffer_len, str, len);
903 buffer_len += len;
904 buffer[buffer_len] = 0;
905 fn(buffer);
906 str = ptr + 1;
907 n -= len + 1;
908 buffer_len = 0;
911 /* Put the remaining text into the buffer for later printing */
912 buffer_ensure(buffer_len + n + 1);
913 memcpy(buffer + buffer_len, str, n);
914 buffer_len += n;
917 /***************/
919 static OutputObject Output =
921 PyObject_HEAD_INIT(&OutputType)
926 static OutputObject Error =
928 PyObject_HEAD_INIT(&OutputType)
933 static int
934 PythonIO_Init(void)
936 /* Fixups... */
937 OutputType.ob_type = &PyType_Type;
939 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
940 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
942 if (PyErr_Occurred())
944 EMSG(_("E264: Python: Error initialising I/O objects"));
945 return -1;
948 return 0;
951 /******************************************************
952 * 3. Implementation of the Vim module for Python
955 /* Vim module - Implementation functions
956 * -------------------------------------
959 static PyObject *VimError;
961 static PyObject *VimCommand(PyObject *, PyObject *);
962 static PyObject *VimEval(PyObject *, PyObject *);
964 /* Window type - Implementation functions
965 * --------------------------------------
968 typedef struct
970 PyObject_HEAD
971 win_T *win;
973 WindowObject;
975 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
977 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
979 static PyObject *WindowNew(win_T *);
981 static void WindowDestructor(PyObject *);
982 static PyObject *WindowGetattr(PyObject *, char *);
983 static int WindowSetattr(PyObject *, char *, PyObject *);
984 static PyObject *WindowRepr(PyObject *);
986 /* Buffer type - Implementation functions
987 * --------------------------------------
990 typedef struct
992 PyObject_HEAD
993 buf_T *buf;
995 BufferObject;
997 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
999 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1001 static PyObject *BufferNew (buf_T *);
1003 static void BufferDestructor(PyObject *);
1004 static PyObject *BufferGetattr(PyObject *, char *);
1005 static PyObject *BufferRepr(PyObject *);
1007 static PyInt BufferLength(PyObject *);
1008 static PyObject *BufferItem(PyObject *, PyInt);
1009 static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1010 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1011 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1013 static PyObject *BufferAppend(PyObject *, PyObject *);
1014 static PyObject *BufferMark(PyObject *, PyObject *);
1015 static PyObject *BufferRange(PyObject *, PyObject *);
1017 /* Line range type - Implementation functions
1018 * --------------------------------------
1021 typedef struct
1023 PyObject_HEAD
1024 BufferObject *buf;
1025 int start;
1026 int end;
1028 RangeObject;
1030 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1032 static PyObject *RangeNew(buf_T *, int, int);
1034 static void RangeDestructor(PyObject *);
1035 static PyObject *RangeGetattr(PyObject *, char *);
1036 static PyObject *RangeRepr(PyObject *);
1038 static PyInt RangeLength(PyObject *);
1039 static PyObject *RangeItem(PyObject *, PyInt);
1040 static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1041 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1042 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
1044 static PyObject *RangeAppend(PyObject *, PyObject *);
1046 /* Window list type - Implementation functions
1047 * -------------------------------------------
1050 static PyInt WinListLength(PyObject *);
1051 static PyObject *WinListItem(PyObject *, PyInt);
1053 /* Buffer list type - Implementation functions
1054 * -------------------------------------------
1057 static PyInt BufListLength(PyObject *);
1058 static PyObject *BufListItem(PyObject *, PyInt);
1060 /* Current objects type - Implementation functions
1061 * -----------------------------------------------
1064 static PyObject *CurrentGetattr(PyObject *, char *);
1065 static int CurrentSetattr(PyObject *, char *, PyObject *);
1067 /* Vim module - Definitions
1070 static struct PyMethodDef VimMethods[] = {
1071 /* name, function, calling, documentation */
1072 {"command", VimCommand, 1, "" },
1073 {"eval", VimEval, 1, "" },
1074 { NULL, NULL, 0, NULL }
1077 /* Vim module - Implementation
1079 /*ARGSUSED*/
1080 static PyObject *
1081 VimCommand(PyObject *self, PyObject *args)
1083 char *cmd;
1084 PyObject *result;
1086 if (!PyArg_ParseTuple(args, "s", &cmd))
1087 return NULL;
1089 PyErr_Clear();
1091 Py_BEGIN_ALLOW_THREADS
1092 Python_Lock_Vim();
1094 do_cmdline_cmd((char_u *)cmd);
1095 update_screen(VALID);
1097 Python_Release_Vim();
1098 Py_END_ALLOW_THREADS
1100 if (VimErrorCheck())
1101 result = NULL;
1102 else
1103 result = Py_None;
1105 Py_XINCREF(result);
1106 return result;
1110 * Function to translate a typval_T into a PyObject; this will recursively
1111 * translate lists/dictionaries into their Python equivalents.
1113 * The depth parameter is too avoid infinite recursion, set it to 1 when
1114 * you call VimToPython.
1116 static PyObject *
1117 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1119 PyObject *result;
1120 PyObject *newObj;
1121 char ptrBuf[NUMBUFLEN];
1123 /* Avoid infinite recursion */
1124 if (depth > 100)
1126 Py_INCREF(Py_None);
1127 result = Py_None;
1128 return result;
1131 /* Check if we run into a recursive loop. The item must be in lookupDict
1132 * then and we can use it again. */
1133 sprintf(ptrBuf, "%ld", (long)our_tv);
1134 result = PyDict_GetItemString(lookupDict, ptrBuf);
1135 if (result != NULL)
1136 Py_INCREF(result);
1137 else if (our_tv->v_type == VAR_STRING)
1139 result = Py_BuildValue("s", our_tv->vval.v_string);
1140 PyDict_SetItemString(lookupDict, ptrBuf, result);
1142 else if (our_tv->v_type == VAR_NUMBER)
1144 char buf[NUMBUFLEN];
1146 /* For backwards compatibility numbers are stored as strings. */
1147 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1148 result = Py_BuildValue("s", buf);
1149 PyDict_SetItemString(lookupDict, ptrBuf, result);
1151 #ifdef FEAT_FLOAT
1152 else if (our_tv->v_type == VAR_FLOAT)
1154 char buf[NUMBUFLEN];
1156 sprintf(buf, "%f", our_tv->vval.v_float);
1157 result = Py_BuildValue("s", buf);
1158 PyDict_SetItemString(lookupDict, ptrBuf, result);
1160 #endif
1161 else if (our_tv->v_type == VAR_LIST)
1163 list_T *list = our_tv->vval.v_list;
1164 listitem_T *curr;
1166 result = PyList_New(0);
1167 PyDict_SetItemString(lookupDict, ptrBuf, result);
1169 if (list != NULL)
1171 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1173 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1174 PyList_Append(result, newObj);
1175 Py_DECREF(newObj);
1179 else if (our_tv->v_type == VAR_DICT)
1181 result = PyDict_New();
1182 PyDict_SetItemString(lookupDict, ptrBuf, result);
1184 if (our_tv->vval.v_dict != NULL)
1186 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1187 int todo = ht->ht_used;
1188 hashitem_T *hi;
1189 dictitem_T *di;
1191 for (hi = ht->ht_array; todo > 0; ++hi)
1193 if (!HASHITEM_EMPTY(hi))
1195 --todo;
1197 di = dict_lookup(hi);
1198 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1199 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1200 Py_DECREF(newObj);
1205 else
1207 Py_INCREF(Py_None);
1208 result = Py_None;
1211 return result;
1214 /*ARGSUSED*/
1215 static PyObject *
1216 VimEval(PyObject *self, PyObject *args)
1218 #ifdef FEAT_EVAL
1219 char *expr;
1220 typval_T *our_tv;
1221 PyObject *result;
1222 PyObject *lookup_dict;
1224 if (!PyArg_ParseTuple(args, "s", &expr))
1225 return NULL;
1227 Py_BEGIN_ALLOW_THREADS
1228 Python_Lock_Vim();
1229 our_tv = eval_expr((char_u *)expr, NULL);
1231 Python_Release_Vim();
1232 Py_END_ALLOW_THREADS
1234 if (our_tv == NULL)
1236 PyErr_SetVim(_("invalid expression"));
1237 return NULL;
1240 /* Convert the Vim type into a Python type. Create a dictionary that's
1241 * used to check for recursive loops. */
1242 lookup_dict = PyDict_New();
1243 result = VimToPython(our_tv, 1, lookup_dict);
1244 Py_DECREF(lookup_dict);
1247 Py_BEGIN_ALLOW_THREADS
1248 Python_Lock_Vim();
1249 free_tv(our_tv);
1250 Python_Release_Vim();
1251 Py_END_ALLOW_THREADS
1253 return result;
1254 #else
1255 PyErr_SetVim(_("expressions disabled at compile time"));
1256 return NULL;
1257 #endif
1260 /* Common routines for buffers and line ranges
1261 * -------------------------------------------
1263 static int
1264 CheckBuffer(BufferObject *this)
1266 if (this->buf == INVALID_BUFFER_VALUE)
1268 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1269 return -1;
1272 return 0;
1275 static PyObject *
1276 RBItem(BufferObject *self, PyInt n, int start, int end)
1278 if (CheckBuffer(self))
1279 return NULL;
1281 if (n < 0 || n > end - start)
1283 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1284 return NULL;
1287 return GetBufferLine(self->buf, n+start);
1290 static PyObject *
1291 RBSlice(BufferObject *self, PyInt lo, PyInt hi, int start, int end)
1293 PyInt size;
1295 if (CheckBuffer(self))
1296 return NULL;
1298 size = end - start + 1;
1300 if (lo < 0)
1301 lo = 0;
1302 else if (lo > size)
1303 lo = size;
1304 if (hi < 0)
1305 hi = 0;
1306 if (hi < lo)
1307 hi = lo;
1308 else if (hi > size)
1309 hi = size;
1311 return GetBufferLineList(self->buf, lo+start, hi+start);
1314 static PyInt
1315 RBAssItem(BufferObject *self, PyInt n, PyObject *val, int start, int end, int *new_end)
1317 int len_change;
1319 if (CheckBuffer(self))
1320 return -1;
1322 if (n < 0 || n > end - start)
1324 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1325 return -1;
1328 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1329 return -1;
1331 if (new_end)
1332 *new_end = end + len_change;
1334 return 0;
1337 static PyInt
1338 RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, int start, int end, int *new_end)
1340 int size;
1341 int len_change;
1343 /* Self must be a valid buffer */
1344 if (CheckBuffer(self))
1345 return -1;
1347 /* Sort out the slice range */
1348 size = end - start + 1;
1350 if (lo < 0)
1351 lo = 0;
1352 else if (lo > size)
1353 lo = size;
1354 if (hi < 0)
1355 hi = 0;
1356 if (hi < lo)
1357 hi = lo;
1358 else if (hi > size)
1359 hi = size;
1361 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1362 return -1;
1364 if (new_end)
1365 *new_end = end + len_change;
1367 return 0;
1370 static PyObject *
1371 RBAppend(BufferObject *self, PyObject *args, int start, int end, int *new_end)
1373 PyObject *lines;
1374 int len_change;
1375 int max;
1376 int n;
1378 if (CheckBuffer(self))
1379 return NULL;
1381 max = n = end - start + 1;
1383 if (!PyArg_ParseTuple(args, "O|i", &lines, &n))
1384 return NULL;
1386 if (n < 0 || n > max)
1388 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1389 return NULL;
1392 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1393 return NULL;
1395 if (new_end)
1396 *new_end = end + len_change;
1398 Py_INCREF(Py_None);
1399 return Py_None;
1403 /* Buffer object - Definitions
1406 static struct PyMethodDef BufferMethods[] = {
1407 /* name, function, calling, documentation */
1408 {"append", BufferAppend, 1, "" },
1409 {"mark", BufferMark, 1, "" },
1410 {"range", BufferRange, 1, "" },
1411 { NULL, NULL, 0, NULL }
1414 static PySequenceMethods BufferAsSeq = {
1415 (PyInquiry) BufferLength, /* sq_length, len(x) */
1416 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1417 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1418 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1419 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1420 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1421 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1424 static PyTypeObject BufferType = {
1425 PyObject_HEAD_INIT(0)
1427 "buffer",
1428 sizeof(BufferObject),
1431 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1432 (printfunc) 0, /* tp_print, print x */
1433 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1434 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1435 (cmpfunc) 0, /* tp_compare, x>y */
1436 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1438 0, /* as number */
1439 &BufferAsSeq, /* as sequence */
1440 0, /* as mapping */
1442 (hashfunc) 0, /* tp_hash, dict(x) */
1443 (ternaryfunc) 0, /* tp_call, x() */
1444 (reprfunc) 0, /* tp_str, str(x) */
1447 /* Buffer object - Implementation
1450 static PyObject *
1451 BufferNew(buf_T *buf)
1453 /* We need to handle deletion of buffers underneath us.
1454 * If we add a "b_python_ref" field to the buf_T structure,
1455 * then we can get at it in buf_freeall() in vim. We then
1456 * need to create only ONE Python object per buffer - if
1457 * we try to create a second, just INCREF the existing one
1458 * and return it. The (single) Python object referring to
1459 * the buffer is stored in "b_python_ref".
1460 * Question: what to do on a buf_freeall(). We'll probably
1461 * have to either delete the Python object (DECREF it to
1462 * zero - a bad idea, as it leaves dangling refs!) or
1463 * set the buf_T * value to an invalid value (-1?), which
1464 * means we need checks in all access functions... Bah.
1467 BufferObject *self;
1469 if (buf->b_python_ref != NULL)
1471 self = buf->b_python_ref;
1472 Py_INCREF(self);
1474 else
1476 self = PyObject_NEW(BufferObject, &BufferType);
1477 if (self == NULL)
1478 return NULL;
1479 self->buf = buf;
1480 buf->b_python_ref = self;
1483 return (PyObject *)(self);
1486 static void
1487 BufferDestructor(PyObject *self)
1489 BufferObject *this = (BufferObject *)(self);
1491 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1492 this->buf->b_python_ref = NULL;
1494 Py_DECREF(self);
1497 static PyObject *
1498 BufferGetattr(PyObject *self, char *name)
1500 BufferObject *this = (BufferObject *)(self);
1502 if (CheckBuffer(this))
1503 return NULL;
1505 if (strcmp(name, "name") == 0)
1506 return Py_BuildValue("s",this->buf->b_ffname);
1507 else if (strcmp(name, "number") == 0)
1508 return Py_BuildValue("i",this->buf->b_fnum);
1509 else if (strcmp(name,"__members__") == 0)
1510 return Py_BuildValue("[ss]", "name", "number");
1511 else
1512 return Py_FindMethod(BufferMethods, self, name);
1515 static PyObject *
1516 BufferRepr(PyObject *self)
1518 static char repr[100];
1519 BufferObject *this = (BufferObject *)(self);
1521 if (this->buf == INVALID_BUFFER_VALUE)
1523 vim_snprintf(repr, 100, _("<buffer object (deleted) at %8lX>"),
1524 (long)(self));
1525 return PyString_FromString(repr);
1527 else
1529 char *name = (char *)this->buf->b_fname;
1530 int len;
1532 if (name == NULL)
1533 name = "";
1534 len = strlen(name);
1536 if (len > 35)
1537 name = name + (35 - len);
1539 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1541 return PyString_FromString(repr);
1545 /******************/
1547 static PyInt
1548 BufferLength(PyObject *self)
1550 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1551 if (CheckBuffer((BufferObject *)(self)))
1552 return -1; /* ??? */
1554 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1557 static PyObject *
1558 BufferItem(PyObject *self, PyInt n)
1560 return RBItem((BufferObject *)(self), n, 1,
1561 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1564 static PyObject *
1565 BufferSlice(PyObject *self, PyInt lo, PyInt hi)
1567 return RBSlice((BufferObject *)(self), lo, hi, 1,
1568 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1571 static PyInt
1572 BufferAssItem(PyObject *self, PyInt n, PyObject *val)
1574 return RBAssItem((BufferObject *)(self), n, val, 1,
1575 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1576 NULL);
1579 static PyInt
1580 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1582 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1583 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1584 NULL);
1587 static PyObject *
1588 BufferAppend(PyObject *self, PyObject *args)
1590 return RBAppend((BufferObject *)(self), args, 1,
1591 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1592 NULL);
1595 static PyObject *
1596 BufferMark(PyObject *self, PyObject *args)
1598 pos_T *posp;
1599 char mark;
1600 buf_T *curbuf_save;
1602 if (CheckBuffer((BufferObject *)(self)))
1603 return NULL;
1605 if (!PyArg_ParseTuple(args, "c", &mark))
1606 return NULL;
1608 curbuf_save = curbuf;
1609 curbuf = ((BufferObject *)(self))->buf;
1610 posp = getmark(mark, FALSE);
1611 curbuf = curbuf_save;
1613 if (posp == NULL)
1615 PyErr_SetVim(_("invalid mark name"));
1616 return NULL;
1619 /* Ckeck for keyboard interrupt */
1620 if (VimErrorCheck())
1621 return NULL;
1623 if (posp->lnum <= 0)
1625 /* Or raise an error? */
1626 Py_INCREF(Py_None);
1627 return Py_None;
1630 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1633 static PyObject *
1634 BufferRange(PyObject *self, PyObject *args)
1636 int start;
1637 int end;
1639 if (CheckBuffer((BufferObject *)(self)))
1640 return NULL;
1642 if (!PyArg_ParseTuple(args, "ii", &start, &end))
1643 return NULL;
1645 return RangeNew(((BufferObject *)(self))->buf, start, end);
1648 /* Line range object - Definitions
1651 static struct PyMethodDef RangeMethods[] = {
1652 /* name, function, calling, documentation */
1653 {"append", RangeAppend, 1, "" },
1654 { NULL, NULL, 0, NULL }
1657 static PySequenceMethods RangeAsSeq = {
1658 (PyInquiry) RangeLength, /* sq_length, len(x) */
1659 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1660 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1661 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1662 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1663 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1664 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1667 static PyTypeObject RangeType = {
1668 PyObject_HEAD_INIT(0)
1670 "range",
1671 sizeof(RangeObject),
1674 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1675 (printfunc) 0, /* tp_print, print x */
1676 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1677 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1678 (cmpfunc) 0, /* tp_compare, x>y */
1679 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1681 0, /* as number */
1682 &RangeAsSeq, /* as sequence */
1683 0, /* as mapping */
1685 (hashfunc) 0, /* tp_hash, dict(x) */
1686 (ternaryfunc) 0, /* tp_call, x() */
1687 (reprfunc) 0, /* tp_str, str(x) */
1690 /* Line range object - Implementation
1693 static PyObject *
1694 RangeNew(buf_T *buf, int start, int end)
1696 BufferObject *bufr;
1697 RangeObject *self;
1698 self = PyObject_NEW(RangeObject, &RangeType);
1699 if (self == NULL)
1700 return NULL;
1702 bufr = (BufferObject *)BufferNew(buf);
1703 if (bufr == NULL)
1705 Py_DECREF(self);
1706 return NULL;
1708 Py_INCREF(bufr);
1710 self->buf = bufr;
1711 self->start = start;
1712 self->end = end;
1714 return (PyObject *)(self);
1717 static void
1718 RangeDestructor(PyObject *self)
1720 Py_DECREF(((RangeObject *)(self))->buf);
1721 Py_DECREF(self);
1724 static PyObject *
1725 RangeGetattr(PyObject *self, char *name)
1727 if (strcmp(name, "start") == 0)
1728 return Py_BuildValue("i",((RangeObject *)(self))->start - 1);
1729 else if (strcmp(name, "end") == 0)
1730 return Py_BuildValue("i",((RangeObject *)(self))->end - 1);
1731 else
1732 return Py_FindMethod(RangeMethods, self, name);
1735 static PyObject *
1736 RangeRepr(PyObject *self)
1738 static char repr[100];
1739 RangeObject *this = (RangeObject *)(self);
1741 if (this->buf->buf == INVALID_BUFFER_VALUE)
1743 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %8lX>",
1744 (long)(self));
1745 return PyString_FromString(repr);
1747 else
1749 char *name = (char *)this->buf->buf->b_fname;
1750 int len;
1752 if (name == NULL)
1753 name = "";
1754 len = strlen(name);
1756 if (len > 45)
1757 name = name + (45 - len);
1759 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1760 len > 45 ? "..." : "", name,
1761 this->start, this->end);
1763 return PyString_FromString(repr);
1767 /****************/
1769 static PyInt
1770 RangeLength(PyObject *self)
1772 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1773 if (CheckBuffer(((RangeObject *)(self))->buf))
1774 return -1; /* ??? */
1776 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1779 static PyObject *
1780 RangeItem(PyObject *self, PyInt n)
1782 return RBItem(((RangeObject *)(self))->buf, n,
1783 ((RangeObject *)(self))->start,
1784 ((RangeObject *)(self))->end);
1787 static PyObject *
1788 RangeSlice(PyObject *self, PyInt lo, PyInt hi)
1790 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1791 ((RangeObject *)(self))->start,
1792 ((RangeObject *)(self))->end);
1795 static PyInt
1796 RangeAssItem(PyObject *self, PyInt n, PyObject *val)
1798 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1799 ((RangeObject *)(self))->start,
1800 ((RangeObject *)(self))->end,
1801 &((RangeObject *)(self))->end);
1804 static PyInt
1805 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
1807 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1808 ((RangeObject *)(self))->start,
1809 ((RangeObject *)(self))->end,
1810 &((RangeObject *)(self))->end);
1813 static PyObject *
1814 RangeAppend(PyObject *self, PyObject *args)
1816 return RBAppend(((RangeObject *)(self))->buf, args,
1817 ((RangeObject *)(self))->start,
1818 ((RangeObject *)(self))->end,
1819 &((RangeObject *)(self))->end);
1822 /* Buffer list object - Definitions
1825 typedef struct
1827 PyObject_HEAD
1829 BufListObject;
1831 static PySequenceMethods BufListAsSeq = {
1832 (PyInquiry) BufListLength, /* sq_length, len(x) */
1833 (binaryfunc) 0, /* sq_concat, x+y */
1834 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1835 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1836 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1837 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1838 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1841 static PyTypeObject BufListType = {
1842 PyObject_HEAD_INIT(0)
1844 "buffer list",
1845 sizeof(BufListObject),
1848 (destructor) 0, /* tp_dealloc, refcount==0 */
1849 (printfunc) 0, /* tp_print, print x */
1850 (getattrfunc) 0, /* tp_getattr, x.attr */
1851 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1852 (cmpfunc) 0, /* tp_compare, x>y */
1853 (reprfunc) 0, /* tp_repr, `x`, print x */
1855 0, /* as number */
1856 &BufListAsSeq, /* as sequence */
1857 0, /* as mapping */
1859 (hashfunc) 0, /* tp_hash, dict(x) */
1860 (ternaryfunc) 0, /* tp_call, x() */
1861 (reprfunc) 0, /* tp_str, str(x) */
1864 /* Buffer list object - Implementation
1867 /*ARGSUSED*/
1868 static PyInt
1869 BufListLength(PyObject *self)
1871 buf_T *b = firstbuf;
1872 int n = 0;
1874 while (b)
1876 ++n;
1877 b = b->b_next;
1880 return n;
1883 /*ARGSUSED*/
1884 static PyObject *
1885 BufListItem(PyObject *self, PyInt n)
1887 buf_T *b;
1889 for (b = firstbuf; b; b = b->b_next, --n)
1891 if (n == 0)
1892 return BufferNew(b);
1895 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1896 return NULL;
1899 /* Window object - Definitions
1902 static struct PyMethodDef WindowMethods[] = {
1903 /* name, function, calling, documentation */
1904 { NULL, NULL, 0, NULL }
1907 static PyTypeObject WindowType = {
1908 PyObject_HEAD_INIT(0)
1910 "window",
1911 sizeof(WindowObject),
1914 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1915 (printfunc) 0, /* tp_print, print x */
1916 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1917 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1918 (cmpfunc) 0, /* tp_compare, x>y */
1919 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1921 0, /* as number */
1922 0, /* as sequence */
1923 0, /* as mapping */
1925 (hashfunc) 0, /* tp_hash, dict(x) */
1926 (ternaryfunc) 0, /* tp_call, x() */
1927 (reprfunc) 0, /* tp_str, str(x) */
1930 /* Window object - Implementation
1933 static PyObject *
1934 WindowNew(win_T *win)
1936 /* We need to handle deletion of windows underneath us.
1937 * If we add a "w_python_ref" field to the win_T structure,
1938 * then we can get at it in win_free() in vim. We then
1939 * need to create only ONE Python object per window - if
1940 * we try to create a second, just INCREF the existing one
1941 * and return it. The (single) Python object referring to
1942 * the window is stored in "w_python_ref".
1943 * On a win_free() we set the Python object's win_T* field
1944 * to an invalid value. We trap all uses of a window
1945 * object, and reject them if the win_T* field is invalid.
1948 WindowObject *self;
1950 if (win->w_python_ref)
1952 self = win->w_python_ref;
1953 Py_INCREF(self);
1955 else
1957 self = PyObject_NEW(WindowObject, &WindowType);
1958 if (self == NULL)
1959 return NULL;
1960 self->win = win;
1961 win->w_python_ref = self;
1964 return (PyObject *)(self);
1967 static void
1968 WindowDestructor(PyObject *self)
1970 WindowObject *this = (WindowObject *)(self);
1972 if (this->win && this->win != INVALID_WINDOW_VALUE)
1973 this->win->w_python_ref = NULL;
1975 Py_DECREF(self);
1978 static int
1979 CheckWindow(WindowObject *this)
1981 if (this->win == INVALID_WINDOW_VALUE)
1983 PyErr_SetVim(_("attempt to refer to deleted window"));
1984 return -1;
1987 return 0;
1990 static PyObject *
1991 WindowGetattr(PyObject *self, char *name)
1993 WindowObject *this = (WindowObject *)(self);
1995 if (CheckWindow(this))
1996 return NULL;
1998 if (strcmp(name, "buffer") == 0)
1999 return (PyObject *)BufferNew(this->win->w_buffer);
2000 else if (strcmp(name, "cursor") == 0)
2002 pos_T *pos = &this->win->w_cursor;
2004 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2006 else if (strcmp(name, "height") == 0)
2007 return Py_BuildValue("l", (long)(this->win->w_height));
2008 #ifdef FEAT_VERTSPLIT
2009 else if (strcmp(name, "width") == 0)
2010 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2011 #endif
2012 else if (strcmp(name,"__members__") == 0)
2013 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2014 else
2015 return Py_FindMethod(WindowMethods, self, name);
2018 static int
2019 WindowSetattr(PyObject *self, char *name, PyObject *val)
2021 WindowObject *this = (WindowObject *)(self);
2023 if (CheckWindow(this))
2024 return -1;
2026 if (strcmp(name, "buffer") == 0)
2028 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2029 return -1;
2031 else if (strcmp(name, "cursor") == 0)
2033 long lnum;
2034 long col;
2036 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2037 return -1;
2039 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2041 PyErr_SetVim(_("cursor position outside buffer"));
2042 return -1;
2045 /* Check for keyboard interrupts */
2046 if (VimErrorCheck())
2047 return -1;
2049 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2051 this->win->w_cursor.lnum = lnum;
2052 this->win->w_cursor.col = col;
2053 update_screen(VALID);
2055 return 0;
2057 else if (strcmp(name, "height") == 0)
2059 int height;
2060 win_T *savewin;
2062 if (!PyArg_Parse(val, "i", &height))
2063 return -1;
2065 #ifdef FEAT_GUI
2066 need_mouse_correct = TRUE;
2067 #endif
2068 savewin = curwin;
2069 curwin = this->win;
2070 win_setheight(height);
2071 curwin = savewin;
2073 /* Check for keyboard interrupts */
2074 if (VimErrorCheck())
2075 return -1;
2077 return 0;
2079 #ifdef FEAT_VERTSPLIT
2080 else if (strcmp(name, "width") == 0)
2082 int width;
2083 win_T *savewin;
2085 if (!PyArg_Parse(val, "i", &width))
2086 return -1;
2088 #ifdef FEAT_GUI
2089 need_mouse_correct = TRUE;
2090 #endif
2091 savewin = curwin;
2092 curwin = this->win;
2093 win_setwidth(width);
2094 curwin = savewin;
2096 /* Check for keyboard interrupts */
2097 if (VimErrorCheck())
2098 return -1;
2100 return 0;
2102 #endif
2103 else
2105 PyErr_SetString(PyExc_AttributeError, name);
2106 return -1;
2110 static PyObject *
2111 WindowRepr(PyObject *self)
2113 static char repr[100];
2114 WindowObject *this = (WindowObject *)(self);
2116 if (this->win == INVALID_WINDOW_VALUE)
2118 vim_snprintf(repr, 100, _("<window object (deleted) at %.8lX>"),
2119 (long)(self));
2120 return PyString_FromString(repr);
2122 else
2124 int i = 0;
2125 win_T *w;
2127 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2128 ++i;
2130 if (w == NULL)
2131 vim_snprintf(repr, 100, _("<window object (unknown) at %.8lX>"),
2132 (long)(self));
2133 else
2134 vim_snprintf(repr, 100, _("<window %d>"), i);
2136 return PyString_FromString(repr);
2140 /* Window list object - Definitions
2143 typedef struct
2145 PyObject_HEAD
2147 WinListObject;
2149 static PySequenceMethods WinListAsSeq = {
2150 (PyInquiry) WinListLength, /* sq_length, len(x) */
2151 (binaryfunc) 0, /* sq_concat, x+y */
2152 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2153 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2154 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2155 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2156 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
2159 static PyTypeObject WinListType = {
2160 PyObject_HEAD_INIT(0)
2162 "window list",
2163 sizeof(WinListObject),
2166 (destructor) 0, /* tp_dealloc, refcount==0 */
2167 (printfunc) 0, /* tp_print, print x */
2168 (getattrfunc) 0, /* tp_getattr, x.attr */
2169 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2170 (cmpfunc) 0, /* tp_compare, x>y */
2171 (reprfunc) 0, /* tp_repr, `x`, print x */
2173 0, /* as number */
2174 &WinListAsSeq, /* as sequence */
2175 0, /* as mapping */
2177 (hashfunc) 0, /* tp_hash, dict(x) */
2178 (ternaryfunc) 0, /* tp_call, x() */
2179 (reprfunc) 0, /* tp_str, str(x) */
2182 /* Window list object - Implementation
2184 /*ARGSUSED*/
2185 static PyInt
2186 WinListLength(PyObject *self)
2188 win_T *w = firstwin;
2189 int n = 0;
2191 while (w != NULL)
2193 ++n;
2194 w = W_NEXT(w);
2197 return n;
2200 /*ARGSUSED*/
2201 static PyObject *
2202 WinListItem(PyObject *self, PyInt n)
2204 win_T *w;
2206 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2207 if (n == 0)
2208 return WindowNew(w);
2210 PyErr_SetString(PyExc_IndexError, _("no such window"));
2211 return NULL;
2214 /* Current items object - Definitions
2217 typedef struct
2219 PyObject_HEAD
2221 CurrentObject;
2223 static PyTypeObject CurrentType = {
2224 PyObject_HEAD_INIT(0)
2226 "current data",
2227 sizeof(CurrentObject),
2230 (destructor) 0, /* tp_dealloc, refcount==0 */
2231 (printfunc) 0, /* tp_print, print x */
2232 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2233 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2234 (cmpfunc) 0, /* tp_compare, x>y */
2235 (reprfunc) 0, /* tp_repr, `x`, print x */
2237 0, /* as number */
2238 0, /* as sequence */
2239 0, /* as mapping */
2241 (hashfunc) 0, /* tp_hash, dict(x) */
2242 (ternaryfunc) 0, /* tp_call, x() */
2243 (reprfunc) 0, /* tp_str, str(x) */
2246 /* Current items object - Implementation
2248 /*ARGSUSED*/
2249 static PyObject *
2250 CurrentGetattr(PyObject *self, char *name)
2252 if (strcmp(name, "buffer") == 0)
2253 return (PyObject *)BufferNew(curbuf);
2254 else if (strcmp(name, "window") == 0)
2255 return (PyObject *)WindowNew(curwin);
2256 else if (strcmp(name, "line") == 0)
2257 return GetBufferLine(curbuf, (int)curwin->w_cursor.lnum);
2258 else if (strcmp(name, "range") == 0)
2259 return RangeNew(curbuf, RangeStart, RangeEnd);
2260 else if (strcmp(name,"__members__") == 0)
2261 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2262 else
2264 PyErr_SetString(PyExc_AttributeError, name);
2265 return NULL;
2269 /*ARGSUSED*/
2270 static int
2271 CurrentSetattr(PyObject *self, char *name, PyObject *value)
2273 if (strcmp(name, "line") == 0)
2275 if (SetBufferLine(curbuf, (int)curwin->w_cursor.lnum, value, NULL) == FAIL)
2276 return -1;
2278 return 0;
2280 else
2282 PyErr_SetString(PyExc_AttributeError, name);
2283 return -1;
2287 /* External interface
2290 void
2291 python_buffer_free(buf_T *buf)
2293 if (buf->b_python_ref != NULL)
2295 BufferObject *bp = buf->b_python_ref;
2296 bp->buf = INVALID_BUFFER_VALUE;
2297 buf->b_python_ref = NULL;
2301 #if defined(FEAT_WINDOWS) || defined(PROTO)
2302 void
2303 python_window_free(win_T *win)
2305 if (win->w_python_ref != NULL)
2307 WindowObject *wp = win->w_python_ref;
2308 wp->win = INVALID_WINDOW_VALUE;
2309 win->w_python_ref = NULL;
2312 #endif
2314 static BufListObject TheBufferList =
2316 PyObject_HEAD_INIT(&BufListType)
2319 static WinListObject TheWindowList =
2321 PyObject_HEAD_INIT(&WinListType)
2324 static CurrentObject TheCurrent =
2326 PyObject_HEAD_INIT(&CurrentType)
2329 static int
2330 PythonMod_Init(void)
2332 PyObject *mod;
2333 PyObject *dict;
2334 static char *(argv[2]) = {"", NULL};
2336 /* Fixups... */
2337 BufferType.ob_type = &PyType_Type;
2338 RangeType.ob_type = &PyType_Type;
2339 WindowType.ob_type = &PyType_Type;
2340 BufListType.ob_type = &PyType_Type;
2341 WinListType.ob_type = &PyType_Type;
2342 CurrentType.ob_type = &PyType_Type;
2344 /* Set sys.argv[] to avoid a crash in warn(). */
2345 PySys_SetArgv(1, argv);
2347 mod = Py_InitModule("vim", VimMethods);
2348 dict = PyModule_GetDict(mod);
2350 VimError = Py_BuildValue("s", "vim.error");
2352 PyDict_SetItemString(dict, "error", VimError);
2353 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2354 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2355 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
2357 if (PyErr_Occurred())
2358 return -1;
2360 return 0;
2363 /*************************************************************************
2364 * 4. Utility functions for handling the interface between Vim and Python.
2367 /* Get a line from the specified buffer. The line number is
2368 * in Vim format (1-based). The line is returned as a Python
2369 * string object.
2371 static PyObject *
2372 GetBufferLine(buf_T *buf, int n)
2374 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2377 /* Get a list of lines from the specified buffer. The line numbers
2378 * are in Vim format (1-based). The range is from lo up to, but not
2379 * including, hi. The list is returned as a Python list of string objects.
2381 static PyObject *
2382 GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2384 PyInt i;
2385 PyInt n = hi - lo;
2386 PyObject *list = PyList_New(n);
2388 if (list == NULL)
2389 return NULL;
2391 for (i = 0; i < n; ++i)
2393 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2395 /* Error check - was the Python string creation OK? */
2396 if (str == NULL)
2398 Py_DECREF(list);
2399 return NULL;
2402 /* Set the list item */
2403 if (PyList_SetItem(list, i, str))
2405 Py_DECREF(str);
2406 Py_DECREF(list);
2407 return NULL;
2411 /* The ownership of the Python list is passed to the caller (ie,
2412 * the caller should Py_DECREF() the object when it is finished
2413 * with it).
2416 return list;
2420 * Check if deleting lines made the cursor position invalid.
2421 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2422 * deleted).
2424 static void
2425 py_fix_cursor(int lo, int hi, int extra)
2427 if (curwin->w_cursor.lnum >= lo)
2429 /* Adjust the cursor position if it's in/after the changed
2430 * lines. */
2431 if (curwin->w_cursor.lnum >= hi)
2433 curwin->w_cursor.lnum += extra;
2434 check_cursor_col();
2436 else if (extra < 0)
2438 curwin->w_cursor.lnum = lo;
2439 check_cursor();
2441 else
2442 check_cursor_col();
2443 changed_cline_bef_curs();
2445 invalidate_botline();
2448 /* Replace a line in the specified buffer. The line number is
2449 * in Vim format (1-based). The replacement line is given as
2450 * a Python string object. The object is checked for validity
2451 * and correct format. Errors are returned as a value of FAIL.
2452 * The return value is OK on success.
2453 * If OK is returned and len_change is not NULL, *len_change
2454 * is set to the change in the buffer length.
2456 static int
2457 SetBufferLine(buf_T *buf, int n, PyObject *line, int *len_change)
2459 /* First of all, we check the thpe of the supplied Python object.
2460 * There are three cases:
2461 * 1. NULL, or None - this is a deletion.
2462 * 2. A string - this is a replacement.
2463 * 3. Anything else - this is an error.
2465 if (line == Py_None || line == NULL)
2467 buf_T *savebuf = curbuf;
2469 PyErr_Clear();
2470 curbuf = buf;
2472 if (u_savedel((linenr_T)n, 1L) == FAIL)
2473 PyErr_SetVim(_("cannot save undo information"));
2474 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2475 PyErr_SetVim(_("cannot delete line"));
2476 else
2478 deleted_lines_mark((linenr_T)n, 1L);
2479 if (buf == curwin->w_buffer)
2480 py_fix_cursor(n, n + 1, -1);
2483 curbuf = savebuf;
2485 if (PyErr_Occurred() || VimErrorCheck())
2486 return FAIL;
2488 if (len_change)
2489 *len_change = -1;
2491 return OK;
2493 else if (PyString_Check(line))
2495 char *save = StringToLine(line);
2496 buf_T *savebuf = curbuf;
2498 if (save == NULL)
2499 return FAIL;
2501 /* We do not need to free "save" if ml_replace() consumes it. */
2502 PyErr_Clear();
2503 curbuf = buf;
2505 if (u_savesub((linenr_T)n) == FAIL)
2507 PyErr_SetVim(_("cannot save undo information"));
2508 vim_free(save);
2510 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2512 PyErr_SetVim(_("cannot replace line"));
2513 vim_free(save);
2515 else
2516 changed_bytes((linenr_T)n, 0);
2518 curbuf = savebuf;
2520 /* Check that the cursor is not beyond the end of the line now. */
2521 if (buf == curwin->w_buffer)
2522 check_cursor_col();
2524 if (PyErr_Occurred() || VimErrorCheck())
2525 return FAIL;
2527 if (len_change)
2528 *len_change = 0;
2530 return OK;
2532 else
2534 PyErr_BadArgument();
2535 return FAIL;
2539 /* Replace a range of lines in the specified buffer. The line numbers are in
2540 * Vim format (1-based). The range is from lo up to, but not including, hi.
2541 * The replacement lines are given as a Python list of string objects. The
2542 * list is checked for validity and correct format. Errors are returned as a
2543 * value of FAIL. The return value is OK on success.
2544 * If OK is returned and len_change is not NULL, *len_change
2545 * is set to the change in the buffer length.
2547 static int
2548 SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, int *len_change)
2550 /* First of all, we check the thpe of the supplied Python object.
2551 * There are three cases:
2552 * 1. NULL, or None - this is a deletion.
2553 * 2. A list - this is a replacement.
2554 * 3. Anything else - this is an error.
2556 if (list == Py_None || list == NULL)
2558 PyInt i;
2559 PyInt n = hi - lo;
2560 buf_T *savebuf = curbuf;
2562 PyErr_Clear();
2563 curbuf = buf;
2565 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2566 PyErr_SetVim(_("cannot save undo information"));
2567 else
2569 for (i = 0; i < n; ++i)
2571 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2573 PyErr_SetVim(_("cannot delete line"));
2574 break;
2577 deleted_lines_mark((linenr_T)lo, (long)i);
2579 if (buf == curwin->w_buffer)
2580 py_fix_cursor(lo, hi, -n);
2583 curbuf = savebuf;
2585 if (PyErr_Occurred() || VimErrorCheck())
2586 return FAIL;
2588 if (len_change)
2589 *len_change = -n;
2591 return OK;
2593 else if (PyList_Check(list))
2595 PyInt i;
2596 PyInt new_len = PyList_Size(list);
2597 PyInt old_len = hi - lo;
2598 int extra = 0; /* lines added to text, can be negative */
2599 char **array;
2600 buf_T *savebuf;
2602 if (new_len == 0) /* avoid allocating zero bytes */
2603 array = NULL;
2604 else
2606 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2607 if (array == NULL)
2609 PyErr_NoMemory();
2610 return FAIL;
2614 for (i = 0; i < new_len; ++i)
2616 PyObject *line = PyList_GetItem(list, i);
2618 array[i] = StringToLine(line);
2619 if (array[i] == NULL)
2621 while (i)
2622 vim_free(array[--i]);
2623 vim_free(array);
2624 return FAIL;
2628 savebuf = curbuf;
2630 PyErr_Clear();
2631 curbuf = buf;
2633 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2634 PyErr_SetVim(_("cannot save undo information"));
2636 /* If the size of the range is reducing (ie, new_len < old_len) we
2637 * need to delete some old_len. We do this at the start, by
2638 * repeatedly deleting line "lo".
2640 if (!PyErr_Occurred())
2642 for (i = 0; i < old_len - new_len; ++i)
2643 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2645 PyErr_SetVim(_("cannot delete line"));
2646 break;
2648 extra -= i;
2651 /* For as long as possible, replace the existing old_len with the
2652 * new old_len. This is a more efficient operation, as it requires
2653 * less memory allocation and freeing.
2655 if (!PyErr_Occurred())
2657 for (i = 0; i < old_len && i < new_len; ++i)
2658 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2659 == FAIL)
2661 PyErr_SetVim(_("cannot replace line"));
2662 break;
2665 else
2666 i = 0;
2668 /* Now we may need to insert the remaining new old_len. If we do, we
2669 * must free the strings as we finish with them (we can't pass the
2670 * responsibility to vim in this case).
2672 if (!PyErr_Occurred())
2674 while (i < new_len)
2676 if (ml_append((linenr_T)(lo + i - 1),
2677 (char_u *)array[i], 0, FALSE) == FAIL)
2679 PyErr_SetVim(_("cannot insert line"));
2680 break;
2682 vim_free(array[i]);
2683 ++i;
2684 ++extra;
2688 /* Free any left-over old_len, as a result of an error */
2689 while (i < new_len)
2691 vim_free(array[i]);
2692 ++i;
2695 /* Free the array of old_len. All of its contents have now
2696 * been dealt with (either freed, or the responsibility passed
2697 * to vim.
2699 vim_free(array);
2701 /* Adjust marks. Invalidate any which lie in the
2702 * changed range, and move any in the remainder of the buffer.
2704 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2705 (long)MAXLNUM, (long)extra);
2706 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2708 if (buf == curwin->w_buffer)
2709 py_fix_cursor(lo, hi, extra);
2711 curbuf = savebuf;
2713 if (PyErr_Occurred() || VimErrorCheck())
2714 return FAIL;
2716 if (len_change)
2717 *len_change = new_len - old_len;
2719 return OK;
2721 else
2723 PyErr_BadArgument();
2724 return FAIL;
2728 /* Insert a number of lines into the specified buffer after the specifed line.
2729 * The line number is in Vim format (1-based). The lines to be inserted are
2730 * given as a Python list of string objects or as a single string. The lines
2731 * to be added are checked for validity and correct format. Errors are
2732 * returned as a value of FAIL. The return value is OK on success.
2733 * If OK is returned and len_change is not NULL, *len_change
2734 * is set to the change in the buffer length.
2736 static int
2737 InsertBufferLines(buf_T *buf, int n, PyObject *lines, int *len_change)
2739 /* First of all, we check the type of the supplied Python object.
2740 * It must be a string or a list, or the call is in error.
2742 if (PyString_Check(lines))
2744 char *str = StringToLine(lines);
2745 buf_T *savebuf;
2747 if (str == NULL)
2748 return FAIL;
2750 savebuf = curbuf;
2752 PyErr_Clear();
2753 curbuf = buf;
2755 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2756 PyErr_SetVim(_("cannot save undo information"));
2757 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2758 PyErr_SetVim(_("cannot insert line"));
2759 else
2760 appended_lines_mark((linenr_T)n, 1L);
2762 vim_free(str);
2763 curbuf = savebuf;
2764 update_screen(VALID);
2766 if (PyErr_Occurred() || VimErrorCheck())
2767 return FAIL;
2769 if (len_change)
2770 *len_change = 1;
2772 return OK;
2774 else if (PyList_Check(lines))
2776 PyInt i;
2777 PyInt size = PyList_Size(lines);
2778 char **array;
2779 buf_T *savebuf;
2781 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2782 if (array == NULL)
2784 PyErr_NoMemory();
2785 return FAIL;
2788 for (i = 0; i < size; ++i)
2790 PyObject *line = PyList_GetItem(lines, i);
2791 array[i] = StringToLine(line);
2793 if (array[i] == NULL)
2795 while (i)
2796 vim_free(array[--i]);
2797 vim_free(array);
2798 return FAIL;
2802 savebuf = curbuf;
2804 PyErr_Clear();
2805 curbuf = buf;
2807 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2808 PyErr_SetVim(_("cannot save undo information"));
2809 else
2811 for (i = 0; i < size; ++i)
2813 if (ml_append((linenr_T)(n + i),
2814 (char_u *)array[i], 0, FALSE) == FAIL)
2816 PyErr_SetVim(_("cannot insert line"));
2818 /* Free the rest of the lines */
2819 while (i < size)
2820 vim_free(array[i++]);
2822 break;
2824 vim_free(array[i]);
2826 if (i > 0)
2827 appended_lines_mark((linenr_T)n, (long)i);
2830 /* Free the array of lines. All of its contents have now
2831 * been freed.
2833 vim_free(array);
2835 curbuf = savebuf;
2836 update_screen(VALID);
2838 if (PyErr_Occurred() || VimErrorCheck())
2839 return FAIL;
2841 if (len_change)
2842 *len_change = size;
2844 return OK;
2846 else
2848 PyErr_BadArgument();
2849 return FAIL;
2853 /* Convert a Vim line into a Python string.
2854 * All internal newlines are replaced by null characters.
2856 * On errors, the Python exception data is set, and NULL is returned.
2858 static PyObject *
2859 LineToString(const char *str)
2861 PyObject *result;
2862 PyInt len = strlen(str);
2863 char *p;
2865 /* Allocate an Python string object, with uninitialised contents. We
2866 * must do it this way, so that we can modify the string in place
2867 * later. See the Python source, Objects/stringobject.c for details.
2869 result = PyString_FromStringAndSize(NULL, len);
2870 if (result == NULL)
2871 return NULL;
2873 p = PyString_AsString(result);
2875 while (*str)
2877 if (*str == '\n')
2878 *p = '\0';
2879 else
2880 *p = *str;
2882 ++p;
2883 ++str;
2886 return result;
2889 /* Convert a Python string into a Vim line.
2891 * The result is in allocated memory. All internal nulls are replaced by
2892 * newline characters. It is an error for the string to contain newline
2893 * characters.
2895 * On errors, the Python exception data is set, and NULL is returned.
2897 static char *
2898 StringToLine(PyObject *obj)
2900 const char *str;
2901 char *save;
2902 PyInt len;
2903 PyInt i;
2904 char *p;
2906 if (obj == NULL || !PyString_Check(obj))
2908 PyErr_BadArgument();
2909 return NULL;
2912 str = PyString_AsString(obj);
2913 len = PyString_Size(obj);
2916 * Error checking: String must not contain newlines, as we
2917 * are replacing a single line, and we must replace it with
2918 * a single line.
2919 * A trailing newline is removed, so that append(f.readlines()) works.
2921 p = memchr(str, '\n', len);
2922 if (p != NULL)
2924 if (p == str + len - 1)
2925 --len;
2926 else
2928 PyErr_SetVim(_("string cannot contain newlines"));
2929 return NULL;
2933 /* Create a copy of the string, with internal nulls replaced by
2934 * newline characters, as is the vim convention.
2936 save = (char *)alloc((unsigned)(len+1));
2937 if (save == NULL)
2939 PyErr_NoMemory();
2940 return NULL;
2943 for (i = 0; i < len; ++i)
2945 if (str[i] == '\0')
2946 save[i] = '\n';
2947 else
2948 save[i] = str[i];
2951 save[i] = '\0';
2953 return save;
2956 /* Check to see whether a Vim error has been reported, or a keyboard
2957 * interrupt has been detected.
2959 static int
2960 VimErrorCheck(void)
2962 if (got_int)
2964 PyErr_SetNone(PyExc_KeyboardInterrupt);
2965 return 1;
2967 else if (did_emsg && !PyErr_Occurred())
2969 PyErr_SetNone(VimError);
2970 return 1;
2973 return 0;
2977 /* Don't generate a prototype for the next function, it generates an error on
2978 * newer Python versions. */
2979 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
2981 char *
2982 Py_GetProgramName(void)
2984 return "vim";
2986 #endif /* Python 1.4 */