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.
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.
24 /* Python.h defines _POSIX_THREADS itself (if needed) */
26 # undef _POSIX_THREADS
29 #if defined(_WIN32) && defined (HAVE_FCNTL_H)
38 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */
41 #define PY_SSIZE_T_CLEAN
43 #ifdef FEAT_GUI_MACVIM
44 # include <Python/Python.h>
49 #if defined(MACOS) && !defined(MACOS_X_UNIX)
51 # include <CodeFragments.h>
53 #undef main /* Defined in python.h - aargh */
54 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
56 #if !defined(FEAT_PYTHON) && defined(PROTO)
57 /* Use this to be able to generate prototypes without python being used. */
58 # define PyObject Py_ssize_t
59 # define PyThreadState Py_ssize_t
60 # define PyTypeObject Py_ssize_t
61 struct PyMethodDef
{ Py_ssize_t a
; };
62 # define PySequenceMethods Py_ssize_t
65 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
66 # define PyInt Py_ssize_t
67 # define PyInquiry lenfunc
68 # define PyIntArgFunc ssizeargfunc
69 # define PyIntIntArgFunc ssizessizeargfunc
70 # define PyIntObjArgProc ssizeobjargproc
71 # define PyIntIntObjArgProc ssizessizeobjargproc
72 # define Py_ssize_t_fmt "n"
75 # define PyInquiry inquiry
76 # define PyIntArgFunc intargfunc
77 # define PyIntIntArgFunc intintargfunc
78 # define PyIntObjArgProc intobjargproc
79 # define PyIntIntObjArgProc intintobjargproc
80 # define Py_ssize_t_fmt "i"
84 #define single_input 256
85 #define file_input 257
86 #define eval_input 258
88 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
89 /* Python 2.3: can invoke ":python" recursively. */
90 # define PY_CAN_RECURSE
93 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
94 # ifndef DYNAMIC_PYTHON
95 # define HINSTANCE long_u /* for generating prototypes */
98 /* This makes if_python.c compile without warnings against Python 2.5
99 * on Win32 and Win64. */
100 #undef PyRun_SimpleString
102 #undef PyArg_ParseTuple
104 #undef Py_InitModule4
105 #undef Py_InitModule4_64
110 # define PyArg_Parse dll_PyArg_Parse
111 # define PyArg_ParseTuple dll_PyArg_ParseTuple
112 # define PyDict_SetItemString dll_PyDict_SetItemString
113 # define PyErr_BadArgument dll_PyErr_BadArgument
114 # define PyErr_Clear dll_PyErr_Clear
115 # define PyErr_NoMemory dll_PyErr_NoMemory
116 # define PyErr_Occurred dll_PyErr_Occurred
117 # define PyErr_SetNone dll_PyErr_SetNone
118 # define PyErr_SetString dll_PyErr_SetString
119 # define PyEval_InitThreads dll_PyEval_InitThreads
120 # define PyEval_RestoreThread dll_PyEval_RestoreThread
121 # define PyEval_SaveThread dll_PyEval_SaveThread
122 # ifdef PY_CAN_RECURSE
123 # define PyGILState_Ensure dll_PyGILState_Ensure
124 # define PyGILState_Release dll_PyGILState_Release
126 # define PyInt_AsLong dll_PyInt_AsLong
127 # define PyInt_FromLong dll_PyInt_FromLong
128 # define PyInt_Type (*dll_PyInt_Type)
129 # define PyList_GetItem dll_PyList_GetItem
130 # define PyList_Append dll_PyList_Append
131 # define PyList_New dll_PyList_New
132 # define PyList_SetItem dll_PyList_SetItem
133 # define PyList_Size dll_PyList_Size
134 # define PyList_Type (*dll_PyList_Type)
135 # define PyImport_ImportModule dll_PyImport_ImportModule
136 # define PyDict_New dll_PyDict_New
137 # define PyDict_GetItemString dll_PyDict_GetItemString
138 # define PyModule_GetDict dll_PyModule_GetDict
139 # define PyRun_SimpleString dll_PyRun_SimpleString
140 # define PyString_AsString dll_PyString_AsString
141 # define PyString_FromString dll_PyString_FromString
142 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
143 # define PyString_Size dll_PyString_Size
144 # define PyString_Type (*dll_PyString_Type)
145 # define PySys_SetObject dll_PySys_SetObject
146 # define PySys_SetArgv dll_PySys_SetArgv
147 # define PyType_Type (*dll_PyType_Type)
148 # define Py_BuildValue dll_Py_BuildValue
149 # define Py_FindMethod dll_Py_FindMethod
150 # define Py_InitModule4 dll_Py_InitModule4
151 # define Py_Initialize dll_Py_Initialize
152 # define Py_Finalize dll_Py_Finalize
153 # define Py_IsInitialized dll_Py_IsInitialized
154 # define _PyObject_New dll__PyObject_New
155 # define _Py_NoneStruct (*dll__Py_NoneStruct)
156 # define PyObject_Init dll__PyObject_Init
157 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
158 # define PyType_IsSubtype dll_PyType_IsSubtype
160 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
161 # define PyObject_Malloc dll_PyObject_Malloc
162 # define PyObject_Free dll_PyObject_Free
166 * Pointers for dynamic link
168 static int(*dll_PyArg_Parse
)(PyObject
*, char *, ...);
169 static int(*dll_PyArg_ParseTuple
)(PyObject
*, char *, ...);
170 static int(*dll_PyDict_SetItemString
)(PyObject
*dp
, char *key
, PyObject
*item
);
171 static int(*dll_PyErr_BadArgument
)(void);
172 static void(*dll_PyErr_Clear
)(void);
173 static PyObject
*(*dll_PyErr_NoMemory
)(void);
174 static PyObject
*(*dll_PyErr_Occurred
)(void);
175 static void(*dll_PyErr_SetNone
)(PyObject
*);
176 static void(*dll_PyErr_SetString
)(PyObject
*, const char *);
177 static void(*dll_PyEval_InitThreads
)(void);
178 static void(*dll_PyEval_RestoreThread
)(PyThreadState
*);
179 static PyThreadState
*(*dll_PyEval_SaveThread
)(void);
180 # ifdef PY_CAN_RECURSE
181 static PyGILState_STATE (*dll_PyGILState_Ensure
)(void);
182 static void (*dll_PyGILState_Release
)(PyGILState_STATE
);
184 static long(*dll_PyInt_AsLong
)(PyObject
*);
185 static PyObject
*(*dll_PyInt_FromLong
)(long);
186 static PyTypeObject
* dll_PyInt_Type
;
187 static PyObject
*(*dll_PyList_GetItem
)(PyObject
*, PyInt
);
188 static PyObject
*(*dll_PyList_Append
)(PyObject
*, PyObject
*);
189 static PyObject
*(*dll_PyList_New
)(PyInt size
);
190 static int(*dll_PyList_SetItem
)(PyObject
*, PyInt
, PyObject
*);
191 static PyInt(*dll_PyList_Size
)(PyObject
*);
192 static PyTypeObject
* dll_PyList_Type
;
193 static PyObject
*(*dll_PyImport_ImportModule
)(const char *);
194 static PyObject
*(*dll_PyDict_New
)(void);
195 static PyObject
*(*dll_PyDict_GetItemString
)(PyObject
*, const char *);
196 static PyObject
*(*dll_PyModule_GetDict
)(PyObject
*);
197 static int(*dll_PyRun_SimpleString
)(char *);
198 static char*(*dll_PyString_AsString
)(PyObject
*);
199 static PyObject
*(*dll_PyString_FromString
)(const char *);
200 static PyObject
*(*dll_PyString_FromStringAndSize
)(const char *, PyInt
);
201 static PyInt(*dll_PyString_Size
)(PyObject
*);
202 static PyTypeObject
* dll_PyString_Type
;
203 static int(*dll_PySys_SetObject
)(char *, PyObject
*);
204 static int(*dll_PySys_SetArgv
)(int, char **);
205 static PyTypeObject
* dll_PyType_Type
;
206 static PyObject
*(*dll_Py_BuildValue
)(char *, ...);
207 static PyObject
*(*dll_Py_FindMethod
)(struct PyMethodDef
[], PyObject
*, char *);
208 static PyObject
*(*dll_Py_InitModule4
)(char *, struct PyMethodDef
*, char *, PyObject
*, int);
209 static void(*dll_Py_Initialize
)(void);
210 static void(*dll_Py_Finalize
)(void);
211 static int(*dll_Py_IsInitialized
)(void);
212 static PyObject
*(*dll__PyObject_New
)(PyTypeObject
*, PyObject
*);
213 static PyObject
*(*dll__PyObject_Init
)(PyObject
*, PyTypeObject
*);
214 static PyObject
* dll__Py_NoneStruct
;
215 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
216 static int (*dll_PyType_IsSubtype
)(PyTypeObject
*, PyTypeObject
*);
218 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
219 static void* (*dll_PyObject_Malloc
)(size_t);
220 static void (*dll_PyObject_Free
)(void*);
223 static HINSTANCE hinstPython
= 0; /* Instance of python.dll */
225 /* Imported exception objects */
226 static PyObject
*imp_PyExc_AttributeError
;
227 static PyObject
*imp_PyExc_IndexError
;
228 static PyObject
*imp_PyExc_KeyboardInterrupt
;
229 static PyObject
*imp_PyExc_TypeError
;
230 static PyObject
*imp_PyExc_ValueError
;
232 # define PyExc_AttributeError imp_PyExc_AttributeError
233 # define PyExc_IndexError imp_PyExc_IndexError
234 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
235 # define PyExc_TypeError imp_PyExc_TypeError
236 # define PyExc_ValueError imp_PyExc_ValueError
239 * Table of name to function pointer of python.
241 # define PYTHON_PROC FARPROC
246 } python_funcname_table
[] =
248 {"PyArg_Parse", (PYTHON_PROC
*)&dll_PyArg_Parse
},
249 {"PyArg_ParseTuple", (PYTHON_PROC
*)&dll_PyArg_ParseTuple
},
250 {"PyDict_SetItemString", (PYTHON_PROC
*)&dll_PyDict_SetItemString
},
251 {"PyErr_BadArgument", (PYTHON_PROC
*)&dll_PyErr_BadArgument
},
252 {"PyErr_Clear", (PYTHON_PROC
*)&dll_PyErr_Clear
},
253 {"PyErr_NoMemory", (PYTHON_PROC
*)&dll_PyErr_NoMemory
},
254 {"PyErr_Occurred", (PYTHON_PROC
*)&dll_PyErr_Occurred
},
255 {"PyErr_SetNone", (PYTHON_PROC
*)&dll_PyErr_SetNone
},
256 {"PyErr_SetString", (PYTHON_PROC
*)&dll_PyErr_SetString
},
257 {"PyEval_InitThreads", (PYTHON_PROC
*)&dll_PyEval_InitThreads
},
258 {"PyEval_RestoreThread", (PYTHON_PROC
*)&dll_PyEval_RestoreThread
},
259 {"PyEval_SaveThread", (PYTHON_PROC
*)&dll_PyEval_SaveThread
},
260 # ifdef PY_CAN_RECURSE
261 {"PyGILState_Ensure", (PYTHON_PROC
*)&dll_PyGILState_Ensure
},
262 {"PyGILState_Release", (PYTHON_PROC
*)&dll_PyGILState_Release
},
264 {"PyInt_AsLong", (PYTHON_PROC
*)&dll_PyInt_AsLong
},
265 {"PyInt_FromLong", (PYTHON_PROC
*)&dll_PyInt_FromLong
},
266 {"PyInt_Type", (PYTHON_PROC
*)&dll_PyInt_Type
},
267 {"PyList_GetItem", (PYTHON_PROC
*)&dll_PyList_GetItem
},
268 {"PyList_Append", (PYTHON_PROC
*)&dll_PyList_Append
},
269 {"PyList_New", (PYTHON_PROC
*)&dll_PyList_New
},
270 {"PyList_SetItem", (PYTHON_PROC
*)&dll_PyList_SetItem
},
271 {"PyList_Size", (PYTHON_PROC
*)&dll_PyList_Size
},
272 {"PyList_Type", (PYTHON_PROC
*)&dll_PyList_Type
},
273 {"PyImport_ImportModule", (PYTHON_PROC
*)&dll_PyImport_ImportModule
},
274 {"PyDict_GetItemString", (PYTHON_PROC
*)&dll_PyDict_GetItemString
},
275 {"PyDict_New", (PYTHON_PROC
*)&dll_PyDict_New
},
276 {"PyModule_GetDict", (PYTHON_PROC
*)&dll_PyModule_GetDict
},
277 {"PyRun_SimpleString", (PYTHON_PROC
*)&dll_PyRun_SimpleString
},
278 {"PyString_AsString", (PYTHON_PROC
*)&dll_PyString_AsString
},
279 {"PyString_FromString", (PYTHON_PROC
*)&dll_PyString_FromString
},
280 {"PyString_FromStringAndSize", (PYTHON_PROC
*)&dll_PyString_FromStringAndSize
},
281 {"PyString_Size", (PYTHON_PROC
*)&dll_PyString_Size
},
282 {"PyString_Type", (PYTHON_PROC
*)&dll_PyString_Type
},
283 {"PySys_SetObject", (PYTHON_PROC
*)&dll_PySys_SetObject
},
284 {"PySys_SetArgv", (PYTHON_PROC
*)&dll_PySys_SetArgv
},
285 {"PyType_Type", (PYTHON_PROC
*)&dll_PyType_Type
},
286 {"Py_BuildValue", (PYTHON_PROC
*)&dll_Py_BuildValue
},
287 {"Py_FindMethod", (PYTHON_PROC
*)&dll_Py_FindMethod
},
288 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
289 {"Py_InitModule4_64", (PYTHON_PROC
*)&dll_Py_InitModule4
},
291 {"Py_InitModule4", (PYTHON_PROC
*)&dll_Py_InitModule4
},
293 {"Py_Initialize", (PYTHON_PROC
*)&dll_Py_Initialize
},
294 {"Py_Finalize", (PYTHON_PROC
*)&dll_Py_Finalize
},
295 {"Py_IsInitialized", (PYTHON_PROC
*)&dll_Py_IsInitialized
},
296 {"_PyObject_New", (PYTHON_PROC
*)&dll__PyObject_New
},
297 {"PyObject_Init", (PYTHON_PROC
*)&dll__PyObject_Init
},
298 {"_Py_NoneStruct", (PYTHON_PROC
*)&dll__Py_NoneStruct
},
299 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
300 {"PyType_IsSubtype", (PYTHON_PROC
*)&dll_PyType_IsSubtype
},
302 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
303 {"PyObject_Malloc", (PYTHON_PROC
*)&dll_PyObject_Malloc
},
304 {"PyObject_Free", (PYTHON_PROC
*)&dll_PyObject_Free
},
313 end_dynamic_python(void)
317 FreeLibrary(hinstPython
);
323 * Load library and get all pointers.
324 * Parameter 'libname' provides name of DLL.
328 python_runtime_link_init(char *libname
, int verbose
)
334 hinstPython
= LoadLibrary(libname
);
338 EMSG2(_(e_loadlib
), libname
);
342 for (i
= 0; python_funcname_table
[i
].ptr
; ++i
)
344 if ((*python_funcname_table
[i
].ptr
= GetProcAddress(hinstPython
,
345 python_funcname_table
[i
].name
)) == NULL
)
347 FreeLibrary(hinstPython
);
350 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
358 * If python is enabled (there is installed python on Windows system) return
362 python_enabled(int verbose
)
364 return python_runtime_link_init(DYNAMIC_PYTHON_DLL
, verbose
) == OK
;
367 /* Load the standard Python exceptions - don't import the symbols from the
368 * DLL, as this can cause errors (importing data symbols is not reliable).
370 static void get_exceptions
__ARGS((void));
375 PyObject
*exmod
= PyImport_ImportModule("exceptions");
376 PyObject
*exdict
= PyModule_GetDict(exmod
);
377 imp_PyExc_AttributeError
= PyDict_GetItemString(exdict
, "AttributeError");
378 imp_PyExc_IndexError
= PyDict_GetItemString(exdict
, "IndexError");
379 imp_PyExc_KeyboardInterrupt
= PyDict_GetItemString(exdict
, "KeyboardInterrupt");
380 imp_PyExc_TypeError
= PyDict_GetItemString(exdict
, "TypeError");
381 imp_PyExc_ValueError
= PyDict_GetItemString(exdict
, "ValueError");
382 Py_XINCREF(imp_PyExc_AttributeError
);
383 Py_XINCREF(imp_PyExc_IndexError
);
384 Py_XINCREF(imp_PyExc_KeyboardInterrupt
);
385 Py_XINCREF(imp_PyExc_TypeError
);
386 Py_XINCREF(imp_PyExc_ValueError
);
389 #endif /* DYNAMIC_PYTHON */
391 /******************************************************
392 * Internal function prototypes.
395 static void DoPythonCommand(exarg_T
*, const char *);
396 static PyInt RangeStart
;
397 static PyInt RangeEnd
;
399 static void PythonIO_Flush(void);
400 static int PythonIO_Init(void);
401 static int PythonMod_Init(void);
403 /* Utility functions for the vim/python interface
404 * ----------------------------------------------
406 static PyObject
*GetBufferLine(buf_T
*, PyInt
);
407 static PyObject
*GetBufferLineList(buf_T
*, PyInt
, PyInt
);
409 static int SetBufferLine(buf_T
*, PyInt
, PyObject
*, PyInt
*);
410 static int SetBufferLineList(buf_T
*, PyInt
, PyInt
, PyObject
*, PyInt
*);
411 static int InsertBufferLines(buf_T
*, PyInt
, PyObject
*, PyInt
*);
413 static PyObject
*LineToString(const char *);
414 static char *StringToLine(PyObject
*);
416 static int VimErrorCheck(void);
418 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
420 /******************************************************
421 * 1. Python interpreter main program.
424 static int initialised
= 0;
426 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
427 typedef PyObject PyThreadState
;
430 #ifdef PY_CAN_RECURSE
431 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
433 static PyThreadState
*saved_python_thread
= NULL
;
437 * Suspend a thread of the Python interpreter, other threads are allowed to
441 Python_SaveThread(void)
443 #ifdef PY_CAN_RECURSE
444 PyGILState_Release(pygilstate
);
446 saved_python_thread
= PyEval_SaveThread();
451 * Restore a thread of the Python interpreter, waits for other threads to
455 Python_RestoreThread(void)
457 #ifdef PY_CAN_RECURSE
458 pygilstate
= PyGILState_Ensure();
460 PyEval_RestoreThread(saved_python_thread
);
461 saved_python_thread
= NULL
;
466 * obtain a lock on the Vim data structures
468 static void Python_Lock_Vim(void)
473 * release a lock on the Vim data structures
475 static void Python_Release_Vim(void)
482 static int recurse
= 0;
484 /* If a crash occurs while doing this, don't try again. */
490 #ifdef DYNAMIC_PYTHON
491 if (hinstPython
&& Py_IsInitialized())
493 Python_RestoreThread(); /* enter python */
496 end_dynamic_python();
498 if (Py_IsInitialized())
500 Python_RestoreThread(); /* enter python */
513 #ifdef DYNAMIC_PYTHON
514 if (!python_enabled(TRUE
))
516 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
521 #if !defined(MACOS) || defined(MACOS_X_UNIX)
526 /* initialise threads */
527 PyEval_InitThreads();
529 #ifdef DYNAMIC_PYTHON
536 if (PythonMod_Init())
539 /* Remove the element from sys.path that was added because of our
540 * argv[0] value in PythonMod_Init(). Previously we used an empty
541 * string, but dependinding on the OS we then get an empty entry or
542 * the current directory in sys.path. */
543 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
545 /* the first python thread is vim's, release the lock */
554 /* We call PythonIO_Flush() here to print any Python errors.
555 * This is OK, as it is possible to call this function even
556 * if PythonIO_Init() has not completed successfully (it will
557 * not do anything in this case).
567 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
569 #ifndef PY_CAN_RECURSE
570 static int recursive
= 0;
572 #if defined(MACOS) && !defined(MACOS_X_UNIX)
575 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
579 #ifndef PY_CAN_RECURSE
582 EMSG(_("E659: Cannot invoke Python recursively"));
588 #if defined(MACOS) && !defined(MACOS_X_UNIX)
590 /* Check if the Python library is available */
591 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
597 RangeStart
= eap
->line1
;
598 RangeEnd
= eap
->line2
;
599 Python_Release_Vim(); /* leave vim */
601 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
602 /* Python only works properly when the LC_NUMERIC locale is "C". */
603 saved_locale
= setlocale(LC_NUMERIC
, NULL
);
604 if (saved_locale
== NULL
|| STRCMP(saved_locale
, "C") == 0)
608 /* Need to make a copy, value may change when setting new locale. */
609 saved_locale
= (char *)vim_strsave((char_u
*)saved_locale
);
610 (void)setlocale(LC_NUMERIC
, "C");
614 Python_RestoreThread(); /* enter python */
616 PyRun_SimpleString((char *)(cmd
));
618 Python_SaveThread(); /* leave python */
620 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
621 if (saved_locale
!= NULL
)
623 (void)setlocale(LC_NUMERIC
, saved_locale
);
624 vim_free(saved_locale
);
628 Python_Lock_Vim(); /* enter vim */
630 #if defined(MACOS) && !defined(MACOS_X_UNIX)
635 #ifndef PY_CAN_RECURSE
638 return; /* keeps lint happy */
645 ex_python(exarg_T
*eap
)
649 script
= script_get(eap
, eap
->arg
);
653 DoPythonCommand(eap
, (char *)eap
->arg
);
655 DoPythonCommand(eap
, (char *)script
);
660 #define BUFFER_SIZE 1024
666 ex_pyfile(exarg_T
*eap
)
668 static char buffer
[BUFFER_SIZE
];
669 const char *file
= (char *)eap
->arg
;
672 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
673 * stdio file pointer, but Vim and the Python DLL are compiled with
674 * different options under Windows, meaning that stdio pointers aren't
675 * compatible between the two. Yuk.
677 * Put the string "execfile('file')" into buffer. But, we need to
678 * escape any backslashes or single quotes in the file name, so that
679 * Python won't mangle the file name.
681 strcpy(buffer
, "execfile('");
682 p
= buffer
+ 10; /* size of "execfile('" */
684 while (*file
&& p
< buffer
+ (BUFFER_SIZE
- 3))
686 if (*file
== '\\' || *file
== '\'')
691 /* If we didn't finish the file name, we hit a buffer overflow */
695 /* Put in the terminating "')" and a null */
700 /* Execute the file */
701 DoPythonCommand(eap
, buffer
);
704 /******************************************************
705 * 2. Python output stream: writes output via [e]msg().
708 /* Implementation functions
711 static PyObject
*OutputGetattr(PyObject
*, char *);
712 static int OutputSetattr(PyObject
*, char *, PyObject
*);
714 static PyObject
*OutputWrite(PyObject
*, PyObject
*);
715 static PyObject
*OutputWritelines(PyObject
*, PyObject
*);
717 typedef void (*writefn
)(char_u
*);
718 static void writer(writefn fn
, char_u
*str
, PyInt n
);
720 /* Output object definition
730 static struct PyMethodDef OutputMethods
[] = {
731 /* name, function, calling, documentation */
732 {"write", OutputWrite
, 1, "" },
733 {"writelines", OutputWritelines
, 1, "" },
734 { NULL
, NULL
, 0, NULL
}
737 static PyTypeObject OutputType
= {
738 PyObject_HEAD_INIT(0)
741 sizeof(OutputObject
),
746 (getattrfunc
) OutputGetattr
,
747 (setattrfunc
) OutputSetattr
,
763 OutputGetattr(PyObject
*self
, char *name
)
765 if (strcmp(name
, "softspace") == 0)
766 return PyInt_FromLong(((OutputObject
*)(self
))->softspace
);
768 return Py_FindMethod(OutputMethods
, self
, name
);
772 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
775 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
779 if (strcmp(name
, "softspace") == 0)
781 if (!PyInt_Check(val
)) {
782 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
786 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
790 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
797 OutputWrite(PyObject
*self
, PyObject
*args
)
801 int error
= ((OutputObject
*)(self
))->error
;
803 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
806 Py_BEGIN_ALLOW_THREADS
808 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
809 Python_Release_Vim();
817 OutputWritelines(PyObject
*self
, PyObject
*args
)
822 int error
= ((OutputObject
*)(self
))->error
;
824 if (!PyArg_ParseTuple(args
, "O", &list
))
828 if (!PyList_Check(list
)) {
829 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
834 n
= PyList_Size(list
);
836 for (i
= 0; i
< n
; ++i
)
838 PyObject
*line
= PyList_GetItem(list
, i
);
842 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
843 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
848 Py_BEGIN_ALLOW_THREADS
850 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
851 Python_Release_Vim();
860 /* Output buffer management
863 static char_u
*buffer
= NULL
;
864 static PyInt buffer_len
= 0;
865 static PyInt buffer_size
= 0;
867 static writefn old_fn
= NULL
;
870 buffer_ensure(PyInt n
)
878 new_size
= buffer_size
;
882 if (new_size
!= buffer_size
)
884 new_buffer
= alloc((unsigned)new_size
);
885 if (new_buffer
== NULL
)
890 memcpy(new_buffer
, buffer
, buffer_len
);
895 buffer_size
= new_size
;
902 if (old_fn
&& buffer_len
)
904 buffer
[buffer_len
] = 0;
912 writer(writefn fn
, char_u
*str
, PyInt n
)
916 if (fn
!= old_fn
&& old_fn
!= NULL
)
921 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
923 PyInt len
= ptr
- str
;
925 buffer_ensure(buffer_len
+ len
+ 1);
927 memcpy(buffer
+ buffer_len
, str
, len
);
929 buffer
[buffer_len
] = 0;
936 /* Put the remaining text into the buffer for later printing */
937 buffer_ensure(buffer_len
+ n
+ 1);
938 memcpy(buffer
+ buffer_len
, str
, n
);
944 static OutputObject Output
=
946 PyObject_HEAD_INIT(&OutputType
)
951 static OutputObject Error
=
953 PyObject_HEAD_INIT(&OutputType
)
962 OutputType
.ob_type
= &PyType_Type
;
964 PySys_SetObject("stdout", (PyObject
*)(void *)&Output
);
965 PySys_SetObject("stderr", (PyObject
*)(void *)&Error
);
967 if (PyErr_Occurred())
969 EMSG(_("E264: Python: Error initialising I/O objects"));
976 /******************************************************
977 * 3. Implementation of the Vim module for Python
980 /* Vim module - Implementation functions
981 * -------------------------------------
984 static PyObject
*VimError
;
986 static PyObject
*VimCommand(PyObject
*, PyObject
*);
987 static PyObject
*VimEval(PyObject
*, PyObject
*);
989 /* Window type - Implementation functions
990 * --------------------------------------
1000 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1002 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1004 static PyObject
*WindowNew(win_T
*);
1006 static void WindowDestructor(PyObject
*);
1007 static PyObject
*WindowGetattr(PyObject
*, char *);
1008 static int WindowSetattr(PyObject
*, char *, PyObject
*);
1009 static PyObject
*WindowRepr(PyObject
*);
1011 /* Buffer type - Implementation functions
1012 * --------------------------------------
1022 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1024 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1026 static PyObject
*BufferNew (buf_T
*);
1028 static void BufferDestructor(PyObject
*);
1029 static PyObject
*BufferGetattr(PyObject
*, char *);
1030 static PyObject
*BufferRepr(PyObject
*);
1032 static PyInt
BufferLength(PyObject
*);
1033 static PyObject
*BufferItem(PyObject
*, PyInt
);
1034 static PyObject
*BufferSlice(PyObject
*, PyInt
, PyInt
);
1035 static PyInt
BufferAssItem(PyObject
*, PyInt
, PyObject
*);
1036 static PyInt
BufferAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1038 static PyObject
*BufferAppend(PyObject
*, PyObject
*);
1039 static PyObject
*BufferMark(PyObject
*, PyObject
*);
1040 static PyObject
*BufferRange(PyObject
*, PyObject
*);
1042 /* Line range type - Implementation functions
1043 * --------------------------------------
1055 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1057 static PyObject
*RangeNew(buf_T
*, PyInt
, PyInt
);
1059 static void RangeDestructor(PyObject
*);
1060 static PyObject
*RangeGetattr(PyObject
*, char *);
1061 static PyObject
*RangeRepr(PyObject
*);
1063 static PyInt
RangeLength(PyObject
*);
1064 static PyObject
*RangeItem(PyObject
*, PyInt
);
1065 static PyObject
*RangeSlice(PyObject
*, PyInt
, PyInt
);
1066 static PyInt
RangeAssItem(PyObject
*, PyInt
, PyObject
*);
1067 static PyInt
RangeAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1069 static PyObject
*RangeAppend(PyObject
*, PyObject
*);
1071 /* Window list type - Implementation functions
1072 * -------------------------------------------
1075 static PyInt
WinListLength(PyObject
*);
1076 static PyObject
*WinListItem(PyObject
*, PyInt
);
1078 /* Buffer list type - Implementation functions
1079 * -------------------------------------------
1082 static PyInt
BufListLength(PyObject
*);
1083 static PyObject
*BufListItem(PyObject
*, PyInt
);
1085 /* Current objects type - Implementation functions
1086 * -----------------------------------------------
1089 static PyObject
*CurrentGetattr(PyObject
*, char *);
1090 static int CurrentSetattr(PyObject
*, char *, PyObject
*);
1092 /* Vim module - Definitions
1095 static struct PyMethodDef VimMethods
[] = {
1096 /* name, function, calling, documentation */
1097 {"command", VimCommand
, 1, "Execute a Vim ex-mode command" },
1098 {"eval", VimEval
, 1, "Evaluate an expression using Vim evaluator" },
1099 { NULL
, NULL
, 0, NULL
}
1102 /* Vim module - Implementation
1105 VimCommand(PyObject
*self UNUSED
, PyObject
*args
)
1110 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1115 Py_BEGIN_ALLOW_THREADS
1118 do_cmdline_cmd((char_u
*)cmd
);
1119 update_screen(VALID
);
1121 Python_Release_Vim();
1122 Py_END_ALLOW_THREADS
1124 if (VimErrorCheck())
1135 * Function to translate a typval_T into a PyObject; this will recursively
1136 * translate lists/dictionaries into their Python equivalents.
1138 * The depth parameter is to avoid infinite recursion, set it to 1 when
1139 * you call VimToPython.
1142 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1146 char ptrBuf
[NUMBUFLEN
];
1148 /* Avoid infinite recursion */
1156 /* Check if we run into a recursive loop. The item must be in lookupDict
1157 * then and we can use it again. */
1158 if ((our_tv
->v_type
== VAR_LIST
&& our_tv
->vval
.v_list
!= NULL
)
1159 || (our_tv
->v_type
== VAR_DICT
&& our_tv
->vval
.v_dict
!= NULL
))
1161 sprintf(ptrBuf
, PRINTF_DECIMAL_LONG_U
,
1162 our_tv
->v_type
== VAR_LIST
? (long_u
)our_tv
->vval
.v_list
1163 : (long_u
)our_tv
->vval
.v_dict
);
1164 result
= PyDict_GetItemString(lookupDict
, ptrBuf
);
1172 if (our_tv
->v_type
== VAR_STRING
)
1174 result
= Py_BuildValue("s", our_tv
->vval
.v_string
);
1176 else if (our_tv
->v_type
== VAR_NUMBER
)
1178 char buf
[NUMBUFLEN
];
1180 /* For backwards compatibility numbers are stored as strings. */
1181 sprintf(buf
, "%ld", (long)our_tv
->vval
.v_number
);
1182 result
= Py_BuildValue("s", buf
);
1185 else if (our_tv
->v_type
== VAR_FLOAT
)
1187 char buf
[NUMBUFLEN
];
1189 sprintf(buf
, "%f", our_tv
->vval
.v_float
);
1190 result
= Py_BuildValue("s", buf
);
1193 else if (our_tv
->v_type
== VAR_LIST
)
1195 list_T
*list
= our_tv
->vval
.v_list
;
1198 result
= PyList_New(0);
1202 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1204 for (curr
= list
->lv_first
; curr
!= NULL
; curr
= curr
->li_next
)
1206 newObj
= VimToPython(&curr
->li_tv
, depth
+ 1, lookupDict
);
1207 PyList_Append(result
, newObj
);
1212 else if (our_tv
->v_type
== VAR_DICT
)
1214 result
= PyDict_New();
1216 if (our_tv
->vval
.v_dict
!= NULL
)
1218 hashtab_T
*ht
= &our_tv
->vval
.v_dict
->dv_hashtab
;
1219 long_u todo
= ht
->ht_used
;
1223 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1225 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1227 if (!HASHITEM_EMPTY(hi
))
1231 di
= dict_lookup(hi
);
1232 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1233 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1250 VimEval(PyObject
*self UNUSED
, PyObject
*args
)
1256 PyObject
*lookup_dict
;
1258 if (!PyArg_ParseTuple(args
, "s", &expr
))
1261 Py_BEGIN_ALLOW_THREADS
1263 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1265 Python_Release_Vim();
1266 Py_END_ALLOW_THREADS
1270 PyErr_SetVim(_("invalid expression"));
1274 /* Convert the Vim type into a Python type. Create a dictionary that's
1275 * used to check for recursive loops. */
1276 lookup_dict
= PyDict_New();
1277 result
= VimToPython(our_tv
, 1, lookup_dict
);
1278 Py_DECREF(lookup_dict
);
1281 Py_BEGIN_ALLOW_THREADS
1284 Python_Release_Vim();
1285 Py_END_ALLOW_THREADS
1289 PyErr_SetVim(_("expressions disabled at compile time"));
1294 /* Common routines for buffers and line ranges
1295 * -------------------------------------------
1298 CheckBuffer(BufferObject
*this)
1300 if (this->buf
== INVALID_BUFFER_VALUE
)
1302 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1310 RBItem(BufferObject
*self
, PyInt n
, PyInt start
, PyInt end
)
1312 if (CheckBuffer(self
))
1315 if (n
< 0 || n
> end
- start
)
1317 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1321 return GetBufferLine(self
->buf
, n
+start
);
1325 RBSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyInt start
, PyInt end
)
1329 if (CheckBuffer(self
))
1332 size
= end
- start
+ 1;
1345 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1349 RBAssItem(BufferObject
*self
, PyInt n
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1353 if (CheckBuffer(self
))
1356 if (n
< 0 || n
> end
- start
)
1358 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1362 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1366 *new_end
= end
+ len_change
;
1372 RBAssSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1377 /* Self must be a valid buffer */
1378 if (CheckBuffer(self
))
1381 /* Sort out the slice range */
1382 size
= end
- start
+ 1;
1395 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1399 *new_end
= end
+ len_change
;
1405 RBAppend(BufferObject
*self
, PyObject
*args
, PyInt start
, PyInt end
, PyInt
*new_end
)
1412 if (CheckBuffer(self
))
1415 max
= n
= end
- start
+ 1;
1417 if (!PyArg_ParseTuple(args
, "O|" Py_ssize_t_fmt
, &lines
, &n
))
1420 if (n
< 0 || n
> max
)
1422 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1426 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1430 *new_end
= end
+ len_change
;
1437 /* Buffer object - Definitions
1440 static struct PyMethodDef BufferMethods
[] = {
1441 /* name, function, calling, documentation */
1442 {"append", BufferAppend
, 1, "Append data to Vim buffer" },
1443 {"mark", BufferMark
, 1, "Return (row,col) representing position of named mark" },
1444 {"range", BufferRange
, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1445 { NULL
, NULL
, 0, NULL
}
1448 static PySequenceMethods BufferAsSeq
= {
1449 (PyInquiry
) BufferLength
, /* sq_length, len(x) */
1450 (binaryfunc
) 0, /* BufferConcat, */ /* sq_concat, x+y */
1451 (PyIntArgFunc
) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1452 (PyIntArgFunc
) BufferItem
, /* sq_item, x[i] */
1453 (PyIntIntArgFunc
) BufferSlice
, /* sq_slice, x[i:j] */
1454 (PyIntObjArgProc
) BufferAssItem
, /* sq_ass_item, x[i]=v */
1455 (PyIntIntObjArgProc
) BufferAssSlice
, /* sq_ass_slice, x[i:j]=v */
1458 static PyTypeObject BufferType
= {
1459 PyObject_HEAD_INIT(0)
1462 sizeof(BufferObject
),
1465 (destructor
) BufferDestructor
, /* tp_dealloc, refcount==0 */
1466 (printfunc
) 0, /* tp_print, print x */
1467 (getattrfunc
) BufferGetattr
, /* tp_getattr, x.attr */
1468 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1469 (cmpfunc
) 0, /* tp_compare, x>y */
1470 (reprfunc
) BufferRepr
, /* tp_repr, `x`, print x */
1473 &BufferAsSeq
, /* as sequence */
1476 (hashfunc
) 0, /* tp_hash, dict(x) */
1477 (ternaryfunc
) 0, /* tp_call, x() */
1478 (reprfunc
) 0, /* tp_str, str(x) */
1481 /* Buffer object - Implementation
1485 BufferNew(buf_T
*buf
)
1487 /* We need to handle deletion of buffers underneath us.
1488 * If we add a "b_python_ref" field to the buf_T structure,
1489 * then we can get at it in buf_freeall() in vim. We then
1490 * need to create only ONE Python object per buffer - if
1491 * we try to create a second, just INCREF the existing one
1492 * and return it. The (single) Python object referring to
1493 * the buffer is stored in "b_python_ref".
1494 * Question: what to do on a buf_freeall(). We'll probably
1495 * have to either delete the Python object (DECREF it to
1496 * zero - a bad idea, as it leaves dangling refs!) or
1497 * set the buf_T * value to an invalid value (-1?), which
1498 * means we need checks in all access functions... Bah.
1503 if (buf
->b_python_ref
!= NULL
)
1505 self
= buf
->b_python_ref
;
1510 self
= PyObject_NEW(BufferObject
, &BufferType
);
1514 buf
->b_python_ref
= self
;
1517 return (PyObject
*)(self
);
1521 BufferDestructor(PyObject
*self
)
1523 BufferObject
*this = (BufferObject
*)(self
);
1525 if (this->buf
&& this->buf
!= INVALID_BUFFER_VALUE
)
1526 this->buf
->b_python_ref
= NULL
;
1532 BufferGetattr(PyObject
*self
, char *name
)
1534 BufferObject
*this = (BufferObject
*)(self
);
1536 if (CheckBuffer(this))
1539 if (strcmp(name
, "name") == 0)
1540 return Py_BuildValue("s", this->buf
->b_ffname
);
1541 else if (strcmp(name
, "number") == 0)
1542 return Py_BuildValue(Py_ssize_t_fmt
, this->buf
->b_fnum
);
1543 else if (strcmp(name
,"__members__") == 0)
1544 return Py_BuildValue("[ss]", "name", "number");
1546 return Py_FindMethod(BufferMethods
, self
, name
);
1550 BufferRepr(PyObject
*self
)
1552 static char repr
[100];
1553 BufferObject
*this = (BufferObject
*)(self
);
1555 if (this->buf
== INVALID_BUFFER_VALUE
)
1557 vim_snprintf(repr
, 100, _("<buffer object (deleted) at %p>"), (self
));
1558 return PyString_FromString(repr
);
1562 char *name
= (char *)this->buf
->b_fname
;
1570 name
= name
+ (35 - len
);
1572 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1574 return PyString_FromString(repr
);
1578 /******************/
1581 BufferLength(PyObject
*self
)
1583 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1584 if (CheckBuffer((BufferObject
*)(self
)))
1585 return -1; /* ??? */
1587 return (((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1591 BufferItem(PyObject
*self
, PyInt n
)
1593 return RBItem((BufferObject
*)(self
), n
, 1,
1594 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1598 BufferSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1600 return RBSlice((BufferObject
*)(self
), lo
, hi
, 1,
1601 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1605 BufferAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1607 return RBAssItem((BufferObject
*)(self
), n
, val
, 1,
1608 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1613 BufferAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1615 return RBAssSlice((BufferObject
*)(self
), lo
, hi
, val
, 1,
1616 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1621 BufferAppend(PyObject
*self
, PyObject
*args
)
1623 return RBAppend((BufferObject
*)(self
), args
, 1,
1624 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1629 BufferMark(PyObject
*self
, PyObject
*args
)
1635 if (CheckBuffer((BufferObject
*)(self
)))
1638 if (!PyArg_ParseTuple(args
, "c", &mark
))
1641 curbuf_save
= curbuf
;
1642 curbuf
= ((BufferObject
*)(self
))->buf
;
1643 posp
= getmark(mark
, FALSE
);
1644 curbuf
= curbuf_save
;
1648 PyErr_SetVim(_("invalid mark name"));
1652 /* Ckeck for keyboard interrupt */
1653 if (VimErrorCheck())
1656 if (posp
->lnum
<= 0)
1658 /* Or raise an error? */
1663 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1667 BufferRange(PyObject
*self
, PyObject
*args
)
1672 if (CheckBuffer((BufferObject
*)(self
)))
1675 if (!PyArg_ParseTuple(args
, Py_ssize_t_fmt Py_ssize_t_fmt
, &start
, &end
))
1678 return RangeNew(((BufferObject
*)(self
))->buf
, start
, end
);
1681 /* Line range object - Definitions
1684 static struct PyMethodDef RangeMethods
[] = {
1685 /* name, function, calling, documentation */
1686 {"append", RangeAppend
, 1, "Append data to the Vim range" },
1687 { NULL
, NULL
, 0, NULL
}
1690 static PySequenceMethods RangeAsSeq
= {
1691 (PyInquiry
) RangeLength
, /* sq_length, len(x) */
1692 (binaryfunc
) 0, /* RangeConcat, */ /* sq_concat, x+y */
1693 (PyIntArgFunc
) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1694 (PyIntArgFunc
) RangeItem
, /* sq_item, x[i] */
1695 (PyIntIntArgFunc
) RangeSlice
, /* sq_slice, x[i:j] */
1696 (PyIntObjArgProc
) RangeAssItem
, /* sq_ass_item, x[i]=v */
1697 (PyIntIntObjArgProc
) RangeAssSlice
, /* sq_ass_slice, x[i:j]=v */
1700 static PyTypeObject RangeType
= {
1701 PyObject_HEAD_INIT(0)
1704 sizeof(RangeObject
),
1707 (destructor
) RangeDestructor
, /* tp_dealloc, refcount==0 */
1708 (printfunc
) 0, /* tp_print, print x */
1709 (getattrfunc
) RangeGetattr
, /* tp_getattr, x.attr */
1710 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1711 (cmpfunc
) 0, /* tp_compare, x>y */
1712 (reprfunc
) RangeRepr
, /* tp_repr, `x`, print x */
1715 &RangeAsSeq
, /* as sequence */
1718 (hashfunc
) 0, /* tp_hash, dict(x) */
1719 (ternaryfunc
) 0, /* tp_call, x() */
1720 (reprfunc
) 0, /* tp_str, str(x) */
1723 /* Line range object - Implementation
1727 RangeNew(buf_T
*buf
, PyInt start
, PyInt end
)
1731 self
= PyObject_NEW(RangeObject
, &RangeType
);
1735 bufr
= (BufferObject
*)BufferNew(buf
);
1744 self
->start
= start
;
1747 return (PyObject
*)(self
);
1751 RangeDestructor(PyObject
*self
)
1753 Py_DECREF(((RangeObject
*)(self
))->buf
);
1758 RangeGetattr(PyObject
*self
, char *name
)
1760 if (strcmp(name
, "start") == 0)
1761 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->start
- 1);
1762 else if (strcmp(name
, "end") == 0)
1763 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->end
- 1);
1765 return Py_FindMethod(RangeMethods
, self
, name
);
1769 RangeRepr(PyObject
*self
)
1771 static char repr
[100];
1772 RangeObject
*this = (RangeObject
*)(self
);
1774 if (this->buf
->buf
== INVALID_BUFFER_VALUE
)
1776 vim_snprintf(repr
, 100, "<range object (for deleted buffer) at %p>",
1778 return PyString_FromString(repr
);
1782 char *name
= (char *)this->buf
->buf
->b_fname
;
1787 len
= (int)strlen(name
);
1790 name
= name
+ (45 - len
);
1792 vim_snprintf(repr
, 100, "<range %s%s (%d:%d)>",
1793 len
> 45 ? "..." : "", name
,
1794 this->start
, this->end
);
1796 return PyString_FromString(repr
);
1803 RangeLength(PyObject
*self
)
1805 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1806 if (CheckBuffer(((RangeObject
*)(self
))->buf
))
1807 return -1; /* ??? */
1809 return (((RangeObject
*)(self
))->end
- ((RangeObject
*)(self
))->start
+ 1);
1813 RangeItem(PyObject
*self
, PyInt n
)
1815 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1816 ((RangeObject
*)(self
))->start
,
1817 ((RangeObject
*)(self
))->end
);
1821 RangeSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1823 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1824 ((RangeObject
*)(self
))->start
,
1825 ((RangeObject
*)(self
))->end
);
1829 RangeAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1831 return RBAssItem(((RangeObject
*)(self
))->buf
, n
, val
,
1832 ((RangeObject
*)(self
))->start
,
1833 ((RangeObject
*)(self
))->end
,
1834 &((RangeObject
*)(self
))->end
);
1838 RangeAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1840 return RBAssSlice(((RangeObject
*)(self
))->buf
, lo
, hi
, val
,
1841 ((RangeObject
*)(self
))->start
,
1842 ((RangeObject
*)(self
))->end
,
1843 &((RangeObject
*)(self
))->end
);
1847 RangeAppend(PyObject
*self
, PyObject
*args
)
1849 return RBAppend(((RangeObject
*)(self
))->buf
, args
,
1850 ((RangeObject
*)(self
))->start
,
1851 ((RangeObject
*)(self
))->end
,
1852 &((RangeObject
*)(self
))->end
);
1855 /* Buffer list object - Definitions
1864 static PySequenceMethods BufListAsSeq
= {
1865 (PyInquiry
) BufListLength
, /* sq_length, len(x) */
1866 (binaryfunc
) 0, /* sq_concat, x+y */
1867 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
1868 (PyIntArgFunc
) BufListItem
, /* sq_item, x[i] */
1869 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
1870 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
1871 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
1874 static PyTypeObject BufListType
= {
1875 PyObject_HEAD_INIT(0)
1878 sizeof(BufListObject
),
1881 (destructor
) 0, /* tp_dealloc, refcount==0 */
1882 (printfunc
) 0, /* tp_print, print x */
1883 (getattrfunc
) 0, /* tp_getattr, x.attr */
1884 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1885 (cmpfunc
) 0, /* tp_compare, x>y */
1886 (reprfunc
) 0, /* tp_repr, `x`, print x */
1889 &BufListAsSeq
, /* as sequence */
1892 (hashfunc
) 0, /* tp_hash, dict(x) */
1893 (ternaryfunc
) 0, /* tp_call, x() */
1894 (reprfunc
) 0, /* tp_str, str(x) */
1897 /* Buffer list object - Implementation
1901 BufListLength(PyObject
*self UNUSED
)
1903 buf_T
*b
= firstbuf
;
1916 BufListItem(PyObject
*self UNUSED
, PyInt n
)
1920 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1923 return BufferNew(b
);
1926 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
1930 /* Window object - Definitions
1933 static struct PyMethodDef WindowMethods
[] = {
1934 /* name, function, calling, documentation */
1935 { NULL
, NULL
, 0, NULL
}
1938 static PyTypeObject WindowType
= {
1939 PyObject_HEAD_INIT(0)
1942 sizeof(WindowObject
),
1945 (destructor
) WindowDestructor
, /* tp_dealloc, refcount==0 */
1946 (printfunc
) 0, /* tp_print, print x */
1947 (getattrfunc
) WindowGetattr
, /* tp_getattr, x.attr */
1948 (setattrfunc
) WindowSetattr
, /* tp_setattr, x.attr=v */
1949 (cmpfunc
) 0, /* tp_compare, x>y */
1950 (reprfunc
) WindowRepr
, /* tp_repr, `x`, print x */
1953 0, /* as sequence */
1956 (hashfunc
) 0, /* tp_hash, dict(x) */
1957 (ternaryfunc
) 0, /* tp_call, x() */
1958 (reprfunc
) 0, /* tp_str, str(x) */
1961 /* Window object - Implementation
1965 WindowNew(win_T
*win
)
1967 /* We need to handle deletion of windows underneath us.
1968 * If we add a "w_python_ref" field to the win_T structure,
1969 * then we can get at it in win_free() in vim. We then
1970 * need to create only ONE Python object per window - if
1971 * we try to create a second, just INCREF the existing one
1972 * and return it. The (single) Python object referring to
1973 * the window is stored in "w_python_ref".
1974 * On a win_free() we set the Python object's win_T* field
1975 * to an invalid value. We trap all uses of a window
1976 * object, and reject them if the win_T* field is invalid.
1981 if (win
->w_python_ref
)
1983 self
= win
->w_python_ref
;
1988 self
= PyObject_NEW(WindowObject
, &WindowType
);
1992 win
->w_python_ref
= self
;
1995 return (PyObject
*)(self
);
1999 WindowDestructor(PyObject
*self
)
2001 WindowObject
*this = (WindowObject
*)(self
);
2003 if (this->win
&& this->win
!= INVALID_WINDOW_VALUE
)
2004 this->win
->w_python_ref
= NULL
;
2010 CheckWindow(WindowObject
*this)
2012 if (this->win
== INVALID_WINDOW_VALUE
)
2014 PyErr_SetVim(_("attempt to refer to deleted window"));
2022 WindowGetattr(PyObject
*self
, char *name
)
2024 WindowObject
*this = (WindowObject
*)(self
);
2026 if (CheckWindow(this))
2029 if (strcmp(name
, "buffer") == 0)
2030 return (PyObject
*)BufferNew(this->win
->w_buffer
);
2031 else if (strcmp(name
, "cursor") == 0)
2033 pos_T
*pos
= &this->win
->w_cursor
;
2035 return Py_BuildValue("(ll)", (long)(pos
->lnum
), (long)(pos
->col
));
2037 else if (strcmp(name
, "height") == 0)
2038 return Py_BuildValue("l", (long)(this->win
->w_height
));
2039 #ifdef FEAT_VERTSPLIT
2040 else if (strcmp(name
, "width") == 0)
2041 return Py_BuildValue("l", (long)(W_WIDTH(this->win
)));
2043 else if (strcmp(name
,"__members__") == 0)
2044 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2046 return Py_FindMethod(WindowMethods
, self
, name
);
2050 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
2052 WindowObject
*this = (WindowObject
*)(self
);
2054 if (CheckWindow(this))
2057 if (strcmp(name
, "buffer") == 0)
2059 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2062 else if (strcmp(name
, "cursor") == 0)
2067 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2070 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2072 PyErr_SetVim(_("cursor position outside buffer"));
2076 /* Check for keyboard interrupts */
2077 if (VimErrorCheck())
2080 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2082 this->win
->w_cursor
.lnum
= lnum
;
2083 this->win
->w_cursor
.col
= col
;
2084 update_screen(VALID
);
2088 else if (strcmp(name
, "height") == 0)
2093 if (!PyArg_Parse(val
, "i", &height
))
2097 need_mouse_correct
= TRUE
;
2101 win_setheight(height
);
2104 /* Check for keyboard interrupts */
2105 if (VimErrorCheck())
2110 #ifdef FEAT_VERTSPLIT
2111 else if (strcmp(name
, "width") == 0)
2116 if (!PyArg_Parse(val
, "i", &width
))
2120 need_mouse_correct
= TRUE
;
2124 win_setwidth(width
);
2127 /* Check for keyboard interrupts */
2128 if (VimErrorCheck())
2136 PyErr_SetString(PyExc_AttributeError
, name
);
2142 WindowRepr(PyObject
*self
)
2144 static char repr
[100];
2145 WindowObject
*this = (WindowObject
*)(self
);
2147 if (this->win
== INVALID_WINDOW_VALUE
)
2149 vim_snprintf(repr
, 100, _("<window object (deleted) at %p>"), (self
));
2150 return PyString_FromString(repr
);
2157 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2161 vim_snprintf(repr
, 100, _("<window object (unknown) at %p>"),
2164 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2166 return PyString_FromString(repr
);
2170 /* Window list object - Definitions
2179 static PySequenceMethods WinListAsSeq
= {
2180 (PyInquiry
) WinListLength
, /* sq_length, len(x) */
2181 (binaryfunc
) 0, /* sq_concat, x+y */
2182 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
2183 (PyIntArgFunc
) WinListItem
, /* sq_item, x[i] */
2184 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
2185 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
2186 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
2189 static PyTypeObject WinListType
= {
2190 PyObject_HEAD_INIT(0)
2193 sizeof(WinListObject
),
2196 (destructor
) 0, /* tp_dealloc, refcount==0 */
2197 (printfunc
) 0, /* tp_print, print x */
2198 (getattrfunc
) 0, /* tp_getattr, x.attr */
2199 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
2200 (cmpfunc
) 0, /* tp_compare, x>y */
2201 (reprfunc
) 0, /* tp_repr, `x`, print x */
2204 &WinListAsSeq
, /* as sequence */
2207 (hashfunc
) 0, /* tp_hash, dict(x) */
2208 (ternaryfunc
) 0, /* tp_call, x() */
2209 (reprfunc
) 0, /* tp_str, str(x) */
2212 /* Window list object - Implementation
2215 WinListLength(PyObject
*self UNUSED
)
2217 win_T
*w
= firstwin
;
2230 WinListItem(PyObject
*self UNUSED
, PyInt n
)
2234 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2236 return WindowNew(w
);
2238 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2242 /* Current items object - Definitions
2251 static PyTypeObject CurrentType
= {
2252 PyObject_HEAD_INIT(0)
2255 sizeof(CurrentObject
),
2258 (destructor
) 0, /* tp_dealloc, refcount==0 */
2259 (printfunc
) 0, /* tp_print, print x */
2260 (getattrfunc
) CurrentGetattr
, /* tp_getattr, x.attr */
2261 (setattrfunc
) CurrentSetattr
, /* tp_setattr, x.attr=v */
2262 (cmpfunc
) 0, /* tp_compare, x>y */
2263 (reprfunc
) 0, /* tp_repr, `x`, print x */
2266 0, /* as sequence */
2269 (hashfunc
) 0, /* tp_hash, dict(x) */
2270 (ternaryfunc
) 0, /* tp_call, x() */
2271 (reprfunc
) 0, /* tp_str, str(x) */
2274 /* Current items object - Implementation
2277 CurrentGetattr(PyObject
*self UNUSED
, char *name
)
2279 if (strcmp(name
, "buffer") == 0)
2280 return (PyObject
*)BufferNew(curbuf
);
2281 else if (strcmp(name
, "window") == 0)
2282 return (PyObject
*)WindowNew(curwin
);
2283 else if (strcmp(name
, "line") == 0)
2284 return GetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
);
2285 else if (strcmp(name
, "range") == 0)
2286 return RangeNew(curbuf
, RangeStart
, RangeEnd
);
2287 else if (strcmp(name
,"__members__") == 0)
2288 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2291 PyErr_SetString(PyExc_AttributeError
, name
);
2297 CurrentSetattr(PyObject
*self UNUSED
, char *name
, PyObject
*value
)
2299 if (strcmp(name
, "line") == 0)
2301 if (SetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
, value
, NULL
) == FAIL
)
2308 PyErr_SetString(PyExc_AttributeError
, name
);
2313 /* External interface
2317 python_buffer_free(buf_T
*buf
)
2319 if (buf
->b_python_ref
!= NULL
)
2321 BufferObject
*bp
= buf
->b_python_ref
;
2322 bp
->buf
= INVALID_BUFFER_VALUE
;
2323 buf
->b_python_ref
= NULL
;
2327 #if defined(FEAT_WINDOWS) || defined(PROTO)
2329 python_window_free(win_T
*win
)
2331 if (win
->w_python_ref
!= NULL
)
2333 WindowObject
*wp
= win
->w_python_ref
;
2334 wp
->win
= INVALID_WINDOW_VALUE
;
2335 win
->w_python_ref
= NULL
;
2340 static BufListObject TheBufferList
=
2342 PyObject_HEAD_INIT(&BufListType
)
2345 static WinListObject TheWindowList
=
2347 PyObject_HEAD_INIT(&WinListType
)
2350 static CurrentObject TheCurrent
=
2352 PyObject_HEAD_INIT(&CurrentType
)
2356 PythonMod_Init(void)
2360 /* The special value is removed from sys.path in Python_Init(). */
2361 static char *(argv
[2]) = {"/must>not&exist/foo", NULL
};
2364 BufferType
.ob_type
= &PyType_Type
;
2365 RangeType
.ob_type
= &PyType_Type
;
2366 WindowType
.ob_type
= &PyType_Type
;
2367 BufListType
.ob_type
= &PyType_Type
;
2368 WinListType
.ob_type
= &PyType_Type
;
2369 CurrentType
.ob_type
= &PyType_Type
;
2371 /* Set sys.argv[] to avoid a crash in warn(). */
2372 PySys_SetArgv(1, argv
);
2374 mod
= Py_InitModule4("vim", VimMethods
, (char *)NULL
, (PyObject
*)NULL
, PYTHON_API_VERSION
);
2375 dict
= PyModule_GetDict(mod
);
2377 VimError
= Py_BuildValue("s", "vim.error");
2379 PyDict_SetItemString(dict
, "error", VimError
);
2380 PyDict_SetItemString(dict
, "buffers", (PyObject
*)(void *)&TheBufferList
);
2381 PyDict_SetItemString(dict
, "current", (PyObject
*)(void *)&TheCurrent
);
2382 PyDict_SetItemString(dict
, "windows", (PyObject
*)(void *)&TheWindowList
);
2384 if (PyErr_Occurred())
2390 /*************************************************************************
2391 * 4. Utility functions for handling the interface between Vim and Python.
2394 /* Get a line from the specified buffer. The line number is
2395 * in Vim format (1-based). The line is returned as a Python
2399 GetBufferLine(buf_T
*buf
, PyInt n
)
2401 return LineToString((char *)ml_get_buf(buf
, (linenr_T
)n
, FALSE
));
2404 /* Get a list of lines from the specified buffer. The line numbers
2405 * are in Vim format (1-based). The range is from lo up to, but not
2406 * including, hi. The list is returned as a Python list of string objects.
2409 GetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
)
2413 PyObject
*list
= PyList_New(n
);
2418 for (i
= 0; i
< n
; ++i
)
2420 PyObject
*str
= LineToString((char *)ml_get_buf(buf
, (linenr_T
)(lo
+i
), FALSE
));
2422 /* Error check - was the Python string creation OK? */
2429 /* Set the list item */
2430 if (PyList_SetItem(list
, i
, str
))
2438 /* The ownership of the Python list is passed to the caller (ie,
2439 * the caller should Py_DECREF() the object when it is finished
2447 * Check if deleting lines made the cursor position invalid.
2448 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2452 py_fix_cursor(linenr_T lo
, linenr_T hi
, linenr_T extra
)
2454 if (curwin
->w_cursor
.lnum
>= lo
)
2456 /* Adjust the cursor position if it's in/after the changed
2458 if (curwin
->w_cursor
.lnum
>= hi
)
2460 curwin
->w_cursor
.lnum
+= extra
;
2465 curwin
->w_cursor
.lnum
= lo
;
2470 changed_cline_bef_curs();
2472 invalidate_botline();
2475 /* Replace a line in the specified buffer. The line number is
2476 * in Vim format (1-based). The replacement line is given as
2477 * a Python string object. The object is checked for validity
2478 * and correct format. Errors are returned as a value of FAIL.
2479 * The return value is OK on success.
2480 * If OK is returned and len_change is not NULL, *len_change
2481 * is set to the change in the buffer length.
2484 SetBufferLine(buf_T
*buf
, PyInt n
, PyObject
*line
, PyInt
*len_change
)
2486 /* First of all, we check the thpe of the supplied Python object.
2487 * There are three cases:
2488 * 1. NULL, or None - this is a deletion.
2489 * 2. A string - this is a replacement.
2490 * 3. Anything else - this is an error.
2492 if (line
== Py_None
|| line
== NULL
)
2494 buf_T
*savebuf
= curbuf
;
2499 if (u_savedel((linenr_T
)n
, 1L) == FAIL
)
2500 PyErr_SetVim(_("cannot save undo information"));
2501 else if (ml_delete((linenr_T
)n
, FALSE
) == FAIL
)
2502 PyErr_SetVim(_("cannot delete line"));
2505 if (buf
== curwin
->w_buffer
)
2506 py_fix_cursor((linenr_T
)n
, (linenr_T
)n
+ 1, (linenr_T
)-1);
2507 deleted_lines_mark((linenr_T
)n
, 1L);
2512 if (PyErr_Occurred() || VimErrorCheck())
2520 else if (PyString_Check(line
))
2522 char *save
= StringToLine(line
);
2523 buf_T
*savebuf
= curbuf
;
2528 /* We do not need to free "save" if ml_replace() consumes it. */
2532 if (u_savesub((linenr_T
)n
) == FAIL
)
2534 PyErr_SetVim(_("cannot save undo information"));
2537 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2539 PyErr_SetVim(_("cannot replace line"));
2543 changed_bytes((linenr_T
)n
, 0);
2547 /* Check that the cursor is not beyond the end of the line now. */
2548 if (buf
== curwin
->w_buffer
)
2551 if (PyErr_Occurred() || VimErrorCheck())
2561 PyErr_BadArgument();
2566 /* Replace a range of lines in the specified buffer. The line numbers are in
2567 * Vim format (1-based). The range is from lo up to, but not including, hi.
2568 * The replacement lines are given as a Python list of string objects. The
2569 * list is checked for validity and correct format. Errors are returned as a
2570 * value of FAIL. The return value is OK on success.
2571 * If OK is returned and len_change is not NULL, *len_change
2572 * is set to the change in the buffer length.
2575 SetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
, PyObject
*list
, PyInt
*len_change
)
2577 /* First of all, we check the thpe of the supplied Python object.
2578 * There are three cases:
2579 * 1. NULL, or None - this is a deletion.
2580 * 2. A list - this is a replacement.
2581 * 3. Anything else - this is an error.
2583 if (list
== Py_None
|| list
== NULL
)
2586 PyInt n
= (int)(hi
- lo
);
2587 buf_T
*savebuf
= curbuf
;
2592 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2593 PyErr_SetVim(_("cannot save undo information"));
2596 for (i
= 0; i
< n
; ++i
)
2598 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2600 PyErr_SetVim(_("cannot delete line"));
2604 if (buf
== curwin
->w_buffer
)
2605 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)-n
);
2606 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2611 if (PyErr_Occurred() || VimErrorCheck())
2619 else if (PyList_Check(list
))
2622 PyInt new_len
= PyList_Size(list
);
2623 PyInt old_len
= hi
- lo
;
2624 PyInt extra
= 0; /* lines added to text, can be negative */
2628 if (new_len
== 0) /* avoid allocating zero bytes */
2632 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
2640 for (i
= 0; i
< new_len
; ++i
)
2642 PyObject
*line
= PyList_GetItem(list
, i
);
2644 array
[i
] = StringToLine(line
);
2645 if (array
[i
] == NULL
)
2648 vim_free(array
[--i
]);
2659 if (u_save((linenr_T
)(lo
-1), (linenr_T
)hi
) == FAIL
)
2660 PyErr_SetVim(_("cannot save undo information"));
2662 /* If the size of the range is reducing (ie, new_len < old_len) we
2663 * need to delete some old_len. We do this at the start, by
2664 * repeatedly deleting line "lo".
2666 if (!PyErr_Occurred())
2668 for (i
= 0; i
< old_len
- new_len
; ++i
)
2669 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2671 PyErr_SetVim(_("cannot delete line"));
2677 /* For as long as possible, replace the existing old_len with the
2678 * new old_len. This is a more efficient operation, as it requires
2679 * less memory allocation and freeing.
2681 if (!PyErr_Occurred())
2683 for (i
= 0; i
< old_len
&& i
< new_len
; ++i
)
2684 if (ml_replace((linenr_T
)(lo
+i
), (char_u
*)array
[i
], FALSE
)
2687 PyErr_SetVim(_("cannot replace line"));
2694 /* Now we may need to insert the remaining new old_len. If we do, we
2695 * must free the strings as we finish with them (we can't pass the
2696 * responsibility to vim in this case).
2698 if (!PyErr_Occurred())
2702 if (ml_append((linenr_T
)(lo
+ i
- 1),
2703 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2705 PyErr_SetVim(_("cannot insert line"));
2714 /* Free any left-over old_len, as a result of an error */
2721 /* Free the array of old_len. All of its contents have now
2722 * been dealt with (either freed, or the responsibility passed
2727 /* Adjust marks. Invalidate any which lie in the
2728 * changed range, and move any in the remainder of the buffer.
2730 mark_adjust((linenr_T
)lo
, (linenr_T
)(hi
- 1),
2731 (long)MAXLNUM
, (long)extra
);
2732 changed_lines((linenr_T
)lo
, 0, (linenr_T
)hi
, (long)extra
);
2734 if (buf
== curwin
->w_buffer
)
2735 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)extra
);
2739 if (PyErr_Occurred() || VimErrorCheck())
2743 *len_change
= new_len
- old_len
;
2749 PyErr_BadArgument();
2754 /* Insert a number of lines into the specified buffer after the specifed line.
2755 * The line number is in Vim format (1-based). The lines to be inserted are
2756 * given as a Python list of string objects or as a single string. The lines
2757 * to be added are checked for validity and correct format. Errors are
2758 * returned as a value of FAIL. The return value is OK on success.
2759 * If OK is returned and len_change is not NULL, *len_change
2760 * is set to the change in the buffer length.
2763 InsertBufferLines(buf_T
*buf
, PyInt n
, PyObject
*lines
, PyInt
*len_change
)
2765 /* First of all, we check the type of the supplied Python object.
2766 * It must be a string or a list, or the call is in error.
2768 if (PyString_Check(lines
))
2770 char *str
= StringToLine(lines
);
2781 if (u_save((linenr_T
)n
, (linenr_T
)(n
+1)) == FAIL
)
2782 PyErr_SetVim(_("cannot save undo information"));
2783 else if (ml_append((linenr_T
)n
, (char_u
*)str
, 0, FALSE
) == FAIL
)
2784 PyErr_SetVim(_("cannot insert line"));
2786 appended_lines_mark((linenr_T
)n
, 1L);
2790 update_screen(VALID
);
2792 if (PyErr_Occurred() || VimErrorCheck())
2800 else if (PyList_Check(lines
))
2803 PyInt size
= PyList_Size(lines
);
2807 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2814 for (i
= 0; i
< size
; ++i
)
2816 PyObject
*line
= PyList_GetItem(lines
, i
);
2817 array
[i
] = StringToLine(line
);
2819 if (array
[i
] == NULL
)
2822 vim_free(array
[--i
]);
2833 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2834 PyErr_SetVim(_("cannot save undo information"));
2837 for (i
= 0; i
< size
; ++i
)
2839 if (ml_append((linenr_T
)(n
+ i
),
2840 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2842 PyErr_SetVim(_("cannot insert line"));
2844 /* Free the rest of the lines */
2846 vim_free(array
[i
++]);
2853 appended_lines_mark((linenr_T
)n
, (long)i
);
2856 /* Free the array of lines. All of its contents have now
2862 update_screen(VALID
);
2864 if (PyErr_Occurred() || VimErrorCheck())
2874 PyErr_BadArgument();
2879 /* Convert a Vim line into a Python string.
2880 * All internal newlines are replaced by null characters.
2882 * On errors, the Python exception data is set, and NULL is returned.
2885 LineToString(const char *str
)
2888 PyInt len
= strlen(str
);
2891 /* Allocate an Python string object, with uninitialised contents. We
2892 * must do it this way, so that we can modify the string in place
2893 * later. See the Python source, Objects/stringobject.c for details.
2895 result
= PyString_FromStringAndSize(NULL
, len
);
2899 p
= PyString_AsString(result
);
2915 /* Convert a Python string into a Vim line.
2917 * The result is in allocated memory. All internal nulls are replaced by
2918 * newline characters. It is an error for the string to contain newline
2921 * On errors, the Python exception data is set, and NULL is returned.
2924 StringToLine(PyObject
*obj
)
2932 if (obj
== NULL
|| !PyString_Check(obj
))
2934 PyErr_BadArgument();
2938 str
= PyString_AsString(obj
);
2939 len
= PyString_Size(obj
);
2942 * Error checking: String must not contain newlines, as we
2943 * are replacing a single line, and we must replace it with
2945 * A trailing newline is removed, so that append(f.readlines()) works.
2947 p
= memchr(str
, '\n', len
);
2950 if (p
== str
+ len
- 1)
2954 PyErr_SetVim(_("string cannot contain newlines"));
2959 /* Create a copy of the string, with internal nulls replaced by
2960 * newline characters, as is the vim convention.
2962 save
= (char *)alloc((unsigned)(len
+1));
2969 for (i
= 0; i
< len
; ++i
)
2982 /* Check to see whether a Vim error has been reported, or a keyboard
2983 * interrupt has been detected.
2990 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2993 else if (did_emsg
&& !PyErr_Occurred())
2995 PyErr_SetNone(VimError
);
3003 /* Don't generate a prototype for the next function, it generates an error on
3004 * newer Python versions. */
3005 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3008 Py_GetProgramName(void)
3012 #endif /* Python 1.4 */