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. */
40 #ifdef _POSIX_C_SOURCE
41 # undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
44 # undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
47 #define PY_SSIZE_T_CLEAN
50 #if defined(MACOS) && !defined(MACOS_X_UNIX)
52 # include <CodeFragments.h>
54 #undef main /* Defined in python.h - aargh */
55 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
57 #if !defined(FEAT_PYTHON) && defined(PROTO)
58 /* Use this to be able to generate prototypes without python being used. */
59 # define PyObject Py_ssize_t
60 # define PyThreadState Py_ssize_t
61 # define PyTypeObject Py_ssize_t
62 struct PyMethodDef
{ Py_ssize_t a
; };
63 # define PySequenceMethods Py_ssize_t
66 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
67 # define PyInt Py_ssize_t
68 # define PyInquiry lenfunc
69 # define PyIntArgFunc ssizeargfunc
70 # define PyIntIntArgFunc ssizessizeargfunc
71 # define PyIntObjArgProc ssizeobjargproc
72 # define PyIntIntObjArgProc ssizessizeobjargproc
73 # define Py_ssize_t_fmt "n"
76 # define PyInquiry inquiry
77 # define PyIntArgFunc intargfunc
78 # define PyIntIntArgFunc intintargfunc
79 # define PyIntObjArgProc intobjargproc
80 # define PyIntIntObjArgProc intintobjargproc
81 # define Py_ssize_t_fmt "i"
85 #define single_input 256
86 #define file_input 257
87 #define eval_input 258
89 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
90 /* Python 2.3: can invoke ":python" recursively. */
91 # define PY_CAN_RECURSE
94 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
95 # ifndef DYNAMIC_PYTHON
96 # define HINSTANCE long_u /* for generating prototypes */
99 /* This makes if_python.c compile without warnings against Python 2.5
100 * on Win32 and Win64. */
101 #undef PyRun_SimpleString
103 #undef PyArg_ParseTuple
105 #undef Py_InitModule4
106 #undef Py_InitModule4_64
111 # define PyArg_Parse dll_PyArg_Parse
112 # define PyArg_ParseTuple dll_PyArg_ParseTuple
113 # define PyDict_SetItemString dll_PyDict_SetItemString
114 # define PyErr_BadArgument dll_PyErr_BadArgument
115 # define PyErr_Clear dll_PyErr_Clear
116 # define PyErr_NoMemory dll_PyErr_NoMemory
117 # define PyErr_Occurred dll_PyErr_Occurred
118 # define PyErr_SetNone dll_PyErr_SetNone
119 # define PyErr_SetString dll_PyErr_SetString
120 # define PyEval_InitThreads dll_PyEval_InitThreads
121 # define PyEval_RestoreThread dll_PyEval_RestoreThread
122 # define PyEval_SaveThread dll_PyEval_SaveThread
123 # ifdef PY_CAN_RECURSE
124 # define PyGILState_Ensure dll_PyGILState_Ensure
125 # define PyGILState_Release dll_PyGILState_Release
127 # define PyInt_AsLong dll_PyInt_AsLong
128 # define PyInt_FromLong dll_PyInt_FromLong
129 # define PyInt_Type (*dll_PyInt_Type)
130 # define PyList_GetItem dll_PyList_GetItem
131 # define PyList_Append dll_PyList_Append
132 # define PyList_New dll_PyList_New
133 # define PyList_SetItem dll_PyList_SetItem
134 # define PyList_Size dll_PyList_Size
135 # define PyList_Type (*dll_PyList_Type)
136 # define PyImport_ImportModule dll_PyImport_ImportModule
137 # define PyDict_New dll_PyDict_New
138 # define PyDict_GetItemString dll_PyDict_GetItemString
139 # define PyModule_GetDict dll_PyModule_GetDict
140 # define PyRun_SimpleString dll_PyRun_SimpleString
141 # define PyString_AsString dll_PyString_AsString
142 # define PyString_FromString dll_PyString_FromString
143 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
144 # define PyString_Size dll_PyString_Size
145 # define PyString_Type (*dll_PyString_Type)
146 # define PySys_SetObject dll_PySys_SetObject
147 # define PySys_SetArgv dll_PySys_SetArgv
148 # define PyType_Type (*dll_PyType_Type)
149 # define Py_BuildValue dll_Py_BuildValue
150 # define Py_FindMethod dll_Py_FindMethod
151 # define Py_InitModule4 dll_Py_InitModule4
152 # define Py_Initialize dll_Py_Initialize
153 # define Py_Finalize dll_Py_Finalize
154 # define Py_IsInitialized dll_Py_IsInitialized
155 # define _PyObject_New dll__PyObject_New
156 # define _Py_NoneStruct (*dll__Py_NoneStruct)
157 # define PyObject_Init dll__PyObject_Init
158 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
159 # define PyType_IsSubtype dll_PyType_IsSubtype
161 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
162 # define PyObject_Malloc dll_PyObject_Malloc
163 # define PyObject_Free dll_PyObject_Free
167 * Pointers for dynamic link
169 static int(*dll_PyArg_Parse
)(PyObject
*, char *, ...);
170 static int(*dll_PyArg_ParseTuple
)(PyObject
*, char *, ...);
171 static int(*dll_PyDict_SetItemString
)(PyObject
*dp
, char *key
, PyObject
*item
);
172 static int(*dll_PyErr_BadArgument
)(void);
173 static void(*dll_PyErr_Clear
)(void);
174 static PyObject
*(*dll_PyErr_NoMemory
)(void);
175 static PyObject
*(*dll_PyErr_Occurred
)(void);
176 static void(*dll_PyErr_SetNone
)(PyObject
*);
177 static void(*dll_PyErr_SetString
)(PyObject
*, const char *);
178 static void(*dll_PyEval_InitThreads
)(void);
179 static void(*dll_PyEval_RestoreThread
)(PyThreadState
*);
180 static PyThreadState
*(*dll_PyEval_SaveThread
)(void);
181 # ifdef PY_CAN_RECURSE
182 static PyGILState_STATE (*dll_PyGILState_Ensure
)(void);
183 static void (*dll_PyGILState_Release
)(PyGILState_STATE
);
185 static long(*dll_PyInt_AsLong
)(PyObject
*);
186 static PyObject
*(*dll_PyInt_FromLong
)(long);
187 static PyTypeObject
* dll_PyInt_Type
;
188 static PyObject
*(*dll_PyList_GetItem
)(PyObject
*, PyInt
);
189 static PyObject
*(*dll_PyList_Append
)(PyObject
*, PyObject
*);
190 static PyObject
*(*dll_PyList_New
)(PyInt size
);
191 static int(*dll_PyList_SetItem
)(PyObject
*, PyInt
, PyObject
*);
192 static PyInt(*dll_PyList_Size
)(PyObject
*);
193 static PyTypeObject
* dll_PyList_Type
;
194 static PyObject
*(*dll_PyImport_ImportModule
)(const char *);
195 static PyObject
*(*dll_PyDict_New
)(void);
196 static PyObject
*(*dll_PyDict_GetItemString
)(PyObject
*, const char *);
197 static PyObject
*(*dll_PyModule_GetDict
)(PyObject
*);
198 static int(*dll_PyRun_SimpleString
)(char *);
199 static char*(*dll_PyString_AsString
)(PyObject
*);
200 static PyObject
*(*dll_PyString_FromString
)(const char *);
201 static PyObject
*(*dll_PyString_FromStringAndSize
)(const char *, PyInt
);
202 static PyInt(*dll_PyString_Size
)(PyObject
*);
203 static PyTypeObject
* dll_PyString_Type
;
204 static int(*dll_PySys_SetObject
)(char *, PyObject
*);
205 static int(*dll_PySys_SetArgv
)(int, char **);
206 static PyTypeObject
* dll_PyType_Type
;
207 static PyObject
*(*dll_Py_BuildValue
)(char *, ...);
208 static PyObject
*(*dll_Py_FindMethod
)(struct PyMethodDef
[], PyObject
*, char *);
209 static PyObject
*(*dll_Py_InitModule4
)(char *, struct PyMethodDef
*, char *, PyObject
*, int);
210 static void(*dll_Py_Initialize
)(void);
211 static void(*dll_Py_Finalize
)(void);
212 static int(*dll_Py_IsInitialized
)(void);
213 static PyObject
*(*dll__PyObject_New
)(PyTypeObject
*, PyObject
*);
214 static PyObject
*(*dll__PyObject_Init
)(PyObject
*, PyTypeObject
*);
215 static PyObject
* dll__Py_NoneStruct
;
216 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
217 static int (*dll_PyType_IsSubtype
)(PyTypeObject
*, PyTypeObject
*);
219 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
220 static void* (*dll_PyObject_Malloc
)(size_t);
221 static void (*dll_PyObject_Free
)(void*);
224 static HINSTANCE hinstPython
= 0; /* Instance of python.dll */
226 /* Imported exception objects */
227 static PyObject
*imp_PyExc_AttributeError
;
228 static PyObject
*imp_PyExc_IndexError
;
229 static PyObject
*imp_PyExc_KeyboardInterrupt
;
230 static PyObject
*imp_PyExc_TypeError
;
231 static PyObject
*imp_PyExc_ValueError
;
233 # define PyExc_AttributeError imp_PyExc_AttributeError
234 # define PyExc_IndexError imp_PyExc_IndexError
235 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
236 # define PyExc_TypeError imp_PyExc_TypeError
237 # define PyExc_ValueError imp_PyExc_ValueError
240 * Table of name to function pointer of python.
242 # define PYTHON_PROC FARPROC
247 } python_funcname_table
[] =
249 {"PyArg_Parse", (PYTHON_PROC
*)&dll_PyArg_Parse
},
250 {"PyArg_ParseTuple", (PYTHON_PROC
*)&dll_PyArg_ParseTuple
},
251 {"PyDict_SetItemString", (PYTHON_PROC
*)&dll_PyDict_SetItemString
},
252 {"PyErr_BadArgument", (PYTHON_PROC
*)&dll_PyErr_BadArgument
},
253 {"PyErr_Clear", (PYTHON_PROC
*)&dll_PyErr_Clear
},
254 {"PyErr_NoMemory", (PYTHON_PROC
*)&dll_PyErr_NoMemory
},
255 {"PyErr_Occurred", (PYTHON_PROC
*)&dll_PyErr_Occurred
},
256 {"PyErr_SetNone", (PYTHON_PROC
*)&dll_PyErr_SetNone
},
257 {"PyErr_SetString", (PYTHON_PROC
*)&dll_PyErr_SetString
},
258 {"PyEval_InitThreads", (PYTHON_PROC
*)&dll_PyEval_InitThreads
},
259 {"PyEval_RestoreThread", (PYTHON_PROC
*)&dll_PyEval_RestoreThread
},
260 {"PyEval_SaveThread", (PYTHON_PROC
*)&dll_PyEval_SaveThread
},
261 # ifdef PY_CAN_RECURSE
262 {"PyGILState_Ensure", (PYTHON_PROC
*)&dll_PyGILState_Ensure
},
263 {"PyGILState_Release", (PYTHON_PROC
*)&dll_PyGILState_Release
},
265 {"PyInt_AsLong", (PYTHON_PROC
*)&dll_PyInt_AsLong
},
266 {"PyInt_FromLong", (PYTHON_PROC
*)&dll_PyInt_FromLong
},
267 {"PyInt_Type", (PYTHON_PROC
*)&dll_PyInt_Type
},
268 {"PyList_GetItem", (PYTHON_PROC
*)&dll_PyList_GetItem
},
269 {"PyList_Append", (PYTHON_PROC
*)&dll_PyList_Append
},
270 {"PyList_New", (PYTHON_PROC
*)&dll_PyList_New
},
271 {"PyList_SetItem", (PYTHON_PROC
*)&dll_PyList_SetItem
},
272 {"PyList_Size", (PYTHON_PROC
*)&dll_PyList_Size
},
273 {"PyList_Type", (PYTHON_PROC
*)&dll_PyList_Type
},
274 {"PyImport_ImportModule", (PYTHON_PROC
*)&dll_PyImport_ImportModule
},
275 {"PyDict_GetItemString", (PYTHON_PROC
*)&dll_PyDict_GetItemString
},
276 {"PyDict_New", (PYTHON_PROC
*)&dll_PyDict_New
},
277 {"PyModule_GetDict", (PYTHON_PROC
*)&dll_PyModule_GetDict
},
278 {"PyRun_SimpleString", (PYTHON_PROC
*)&dll_PyRun_SimpleString
},
279 {"PyString_AsString", (PYTHON_PROC
*)&dll_PyString_AsString
},
280 {"PyString_FromString", (PYTHON_PROC
*)&dll_PyString_FromString
},
281 {"PyString_FromStringAndSize", (PYTHON_PROC
*)&dll_PyString_FromStringAndSize
},
282 {"PyString_Size", (PYTHON_PROC
*)&dll_PyString_Size
},
283 {"PyString_Type", (PYTHON_PROC
*)&dll_PyString_Type
},
284 {"PySys_SetObject", (PYTHON_PROC
*)&dll_PySys_SetObject
},
285 {"PySys_SetArgv", (PYTHON_PROC
*)&dll_PySys_SetArgv
},
286 {"PyType_Type", (PYTHON_PROC
*)&dll_PyType_Type
},
287 {"Py_BuildValue", (PYTHON_PROC
*)&dll_Py_BuildValue
},
288 {"Py_FindMethod", (PYTHON_PROC
*)&dll_Py_FindMethod
},
289 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
290 {"Py_InitModule4_64", (PYTHON_PROC
*)&dll_Py_InitModule4
},
292 {"Py_InitModule4", (PYTHON_PROC
*)&dll_Py_InitModule4
},
294 {"Py_Initialize", (PYTHON_PROC
*)&dll_Py_Initialize
},
295 {"Py_Finalize", (PYTHON_PROC
*)&dll_Py_Finalize
},
296 {"Py_IsInitialized", (PYTHON_PROC
*)&dll_Py_IsInitialized
},
297 {"_PyObject_New", (PYTHON_PROC
*)&dll__PyObject_New
},
298 {"PyObject_Init", (PYTHON_PROC
*)&dll__PyObject_Init
},
299 {"_Py_NoneStruct", (PYTHON_PROC
*)&dll__Py_NoneStruct
},
300 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
301 {"PyType_IsSubtype", (PYTHON_PROC
*)&dll_PyType_IsSubtype
},
303 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
304 {"PyObject_Malloc", (PYTHON_PROC
*)&dll_PyObject_Malloc
},
305 {"PyObject_Free", (PYTHON_PROC
*)&dll_PyObject_Free
},
314 end_dynamic_python(void)
318 FreeLibrary(hinstPython
);
324 * Load library and get all pointers.
325 * Parameter 'libname' provides name of DLL.
329 python_runtime_link_init(char *libname
, int verbose
)
335 hinstPython
= LoadLibrary(libname
);
339 EMSG2(_(e_loadlib
), libname
);
343 for (i
= 0; python_funcname_table
[i
].ptr
; ++i
)
345 if ((*python_funcname_table
[i
].ptr
= GetProcAddress(hinstPython
,
346 python_funcname_table
[i
].name
)) == NULL
)
348 FreeLibrary(hinstPython
);
351 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
359 * If python is enabled (there is installed python on Windows system) return
363 python_enabled(int verbose
)
365 return python_runtime_link_init(DYNAMIC_PYTHON_DLL
, verbose
) == OK
;
368 /* Load the standard Python exceptions - don't import the symbols from the
369 * DLL, as this can cause errors (importing data symbols is not reliable).
371 static void get_exceptions
__ARGS((void));
376 PyObject
*exmod
= PyImport_ImportModule("exceptions");
377 PyObject
*exdict
= PyModule_GetDict(exmod
);
378 imp_PyExc_AttributeError
= PyDict_GetItemString(exdict
, "AttributeError");
379 imp_PyExc_IndexError
= PyDict_GetItemString(exdict
, "IndexError");
380 imp_PyExc_KeyboardInterrupt
= PyDict_GetItemString(exdict
, "KeyboardInterrupt");
381 imp_PyExc_TypeError
= PyDict_GetItemString(exdict
, "TypeError");
382 imp_PyExc_ValueError
= PyDict_GetItemString(exdict
, "ValueError");
383 Py_XINCREF(imp_PyExc_AttributeError
);
384 Py_XINCREF(imp_PyExc_IndexError
);
385 Py_XINCREF(imp_PyExc_KeyboardInterrupt
);
386 Py_XINCREF(imp_PyExc_TypeError
);
387 Py_XINCREF(imp_PyExc_ValueError
);
390 #endif /* DYNAMIC_PYTHON */
392 /******************************************************
393 * Internal function prototypes.
396 static void DoPythonCommand(exarg_T
*, const char *);
397 static PyInt RangeStart
;
398 static PyInt RangeEnd
;
400 static void PythonIO_Flush(void);
401 static int PythonIO_Init(void);
402 static int PythonMod_Init(void);
404 /* Utility functions for the vim/python interface
405 * ----------------------------------------------
407 static PyObject
*GetBufferLine(buf_T
*, PyInt
);
408 static PyObject
*GetBufferLineList(buf_T
*, PyInt
, PyInt
);
410 static int SetBufferLine(buf_T
*, PyInt
, PyObject
*, PyInt
*);
411 static int SetBufferLineList(buf_T
*, PyInt
, PyInt
, PyObject
*, PyInt
*);
412 static int InsertBufferLines(buf_T
*, PyInt
, PyObject
*, PyInt
*);
414 static PyObject
*LineToString(const char *);
415 static char *StringToLine(PyObject
*);
417 static int VimErrorCheck(void);
419 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
421 /******************************************************
422 * 1. Python interpreter main program.
425 static int initialised
= 0;
427 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
428 typedef PyObject PyThreadState
;
431 #ifdef PY_CAN_RECURSE
432 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
434 static PyThreadState
*saved_python_thread
= NULL
;
438 * Suspend a thread of the Python interpreter, other threads are allowed to
442 Python_SaveThread(void)
444 #ifdef PY_CAN_RECURSE
445 PyGILState_Release(pygilstate
);
447 saved_python_thread
= PyEval_SaveThread();
452 * Restore a thread of the Python interpreter, waits for other threads to
456 Python_RestoreThread(void)
458 #ifdef PY_CAN_RECURSE
459 pygilstate
= PyGILState_Ensure();
461 PyEval_RestoreThread(saved_python_thread
);
462 saved_python_thread
= NULL
;
467 * obtain a lock on the Vim data structures
469 static void Python_Lock_Vim(void)
474 * release a lock on the Vim data structures
476 static void Python_Release_Vim(void)
483 static int recurse
= 0;
485 /* If a crash occurs while doing this, don't try again. */
491 #ifdef DYNAMIC_PYTHON
492 if (hinstPython
&& Py_IsInitialized())
494 Python_RestoreThread(); /* enter python */
497 end_dynamic_python();
499 if (Py_IsInitialized())
501 Python_RestoreThread(); /* enter python */
514 #ifdef DYNAMIC_PYTHON
515 if (!python_enabled(TRUE
))
517 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
522 #if !defined(MACOS) || defined(MACOS_X_UNIX)
527 /* initialise threads */
528 PyEval_InitThreads();
530 #ifdef DYNAMIC_PYTHON
537 if (PythonMod_Init())
540 /* Remove the element from sys.path that was added because of our
541 * argv[0] value in PythonMod_Init(). Previously we used an empty
542 * string, but dependinding on the OS we then get an empty entry or
543 * the current directory in sys.path. */
544 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
546 /* the first python thread is vim's, release the lock */
555 /* We call PythonIO_Flush() here to print any Python errors.
556 * This is OK, as it is possible to call this function even
557 * if PythonIO_Init() has not completed successfully (it will
558 * not do anything in this case).
568 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
570 #ifndef PY_CAN_RECURSE
571 static int recursive
= 0;
573 #if defined(MACOS) && !defined(MACOS_X_UNIX)
576 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
580 #ifndef PY_CAN_RECURSE
583 EMSG(_("E659: Cannot invoke Python recursively"));
589 #if defined(MACOS) && !defined(MACOS_X_UNIX)
591 /* Check if the Python library is available */
592 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
598 RangeStart
= eap
->line1
;
599 RangeEnd
= eap
->line2
;
600 Python_Release_Vim(); /* leave vim */
602 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
603 /* Python only works properly when the LC_NUMERIC locale is "C". */
604 saved_locale
= setlocale(LC_NUMERIC
, NULL
);
605 if (saved_locale
== NULL
|| STRCMP(saved_locale
, "C") == 0)
609 /* Need to make a copy, value may change when setting new locale. */
610 saved_locale
= (char *)vim_strsave((char_u
*)saved_locale
);
611 (void)setlocale(LC_NUMERIC
, "C");
615 Python_RestoreThread(); /* enter python */
617 PyRun_SimpleString((char *)(cmd
));
619 Python_SaveThread(); /* leave python */
621 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
622 if (saved_locale
!= NULL
)
624 (void)setlocale(LC_NUMERIC
, saved_locale
);
625 vim_free(saved_locale
);
629 Python_Lock_Vim(); /* enter vim */
631 #if defined(MACOS) && !defined(MACOS_X_UNIX)
636 #ifndef PY_CAN_RECURSE
639 return; /* keeps lint happy */
646 ex_python(exarg_T
*eap
)
650 script
= script_get(eap
, eap
->arg
);
654 DoPythonCommand(eap
, (char *)eap
->arg
);
656 DoPythonCommand(eap
, (char *)script
);
661 #define BUFFER_SIZE 1024
667 ex_pyfile(exarg_T
*eap
)
669 static char buffer
[BUFFER_SIZE
];
670 const char *file
= (char *)eap
->arg
;
673 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
674 * stdio file pointer, but Vim and the Python DLL are compiled with
675 * different options under Windows, meaning that stdio pointers aren't
676 * compatible between the two. Yuk.
678 * Put the string "execfile('file')" into buffer. But, we need to
679 * escape any backslashes or single quotes in the file name, so that
680 * Python won't mangle the file name.
682 strcpy(buffer
, "execfile('");
683 p
= buffer
+ 10; /* size of "execfile('" */
685 while (*file
&& p
< buffer
+ (BUFFER_SIZE
- 3))
687 if (*file
== '\\' || *file
== '\'')
692 /* If we didn't finish the file name, we hit a buffer overflow */
696 /* Put in the terminating "')" and a null */
701 /* Execute the file */
702 DoPythonCommand(eap
, buffer
);
705 /******************************************************
706 * 2. Python output stream: writes output via [e]msg().
709 /* Implementation functions
712 static PyObject
*OutputGetattr(PyObject
*, char *);
713 static int OutputSetattr(PyObject
*, char *, PyObject
*);
715 static PyObject
*OutputWrite(PyObject
*, PyObject
*);
716 static PyObject
*OutputWritelines(PyObject
*, PyObject
*);
718 typedef void (*writefn
)(char_u
*);
719 static void writer(writefn fn
, char_u
*str
, PyInt n
);
721 /* Output object definition
731 static struct PyMethodDef OutputMethods
[] = {
732 /* name, function, calling, documentation */
733 {"write", OutputWrite
, 1, "" },
734 {"writelines", OutputWritelines
, 1, "" },
735 { NULL
, NULL
, 0, NULL
}
738 static PyTypeObject OutputType
= {
739 PyObject_HEAD_INIT(0)
742 sizeof(OutputObject
),
747 (getattrfunc
) OutputGetattr
,
748 (setattrfunc
) OutputSetattr
,
764 OutputGetattr(PyObject
*self
, char *name
)
766 if (strcmp(name
, "softspace") == 0)
767 return PyInt_FromLong(((OutputObject
*)(self
))->softspace
);
769 return Py_FindMethod(OutputMethods
, self
, name
);
773 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
776 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
780 if (strcmp(name
, "softspace") == 0)
782 if (!PyInt_Check(val
)) {
783 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
787 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
791 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
798 OutputWrite(PyObject
*self
, PyObject
*args
)
802 int error
= ((OutputObject
*)(self
))->error
;
804 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
807 Py_BEGIN_ALLOW_THREADS
809 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
810 Python_Release_Vim();
818 OutputWritelines(PyObject
*self
, PyObject
*args
)
823 int error
= ((OutputObject
*)(self
))->error
;
825 if (!PyArg_ParseTuple(args
, "O", &list
))
829 if (!PyList_Check(list
)) {
830 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
835 n
= PyList_Size(list
);
837 for (i
= 0; i
< n
; ++i
)
839 PyObject
*line
= PyList_GetItem(list
, i
);
843 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
844 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
849 Py_BEGIN_ALLOW_THREADS
851 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
852 Python_Release_Vim();
861 /* Output buffer management
864 static char_u
*buffer
= NULL
;
865 static PyInt buffer_len
= 0;
866 static PyInt buffer_size
= 0;
868 static writefn old_fn
= NULL
;
871 buffer_ensure(PyInt n
)
879 new_size
= buffer_size
;
883 if (new_size
!= buffer_size
)
885 new_buffer
= alloc((unsigned)new_size
);
886 if (new_buffer
== NULL
)
891 memcpy(new_buffer
, buffer
, buffer_len
);
896 buffer_size
= new_size
;
903 if (old_fn
&& buffer_len
)
905 buffer
[buffer_len
] = 0;
913 writer(writefn fn
, char_u
*str
, PyInt n
)
917 if (fn
!= old_fn
&& old_fn
!= NULL
)
922 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
924 PyInt len
= ptr
- str
;
926 buffer_ensure(buffer_len
+ len
+ 1);
928 memcpy(buffer
+ buffer_len
, str
, len
);
930 buffer
[buffer_len
] = 0;
937 /* Put the remaining text into the buffer for later printing */
938 buffer_ensure(buffer_len
+ n
+ 1);
939 memcpy(buffer
+ buffer_len
, str
, n
);
945 static OutputObject Output
=
947 PyObject_HEAD_INIT(&OutputType
)
952 static OutputObject Error
=
954 PyObject_HEAD_INIT(&OutputType
)
963 OutputType
.ob_type
= &PyType_Type
;
965 PySys_SetObject("stdout", (PyObject
*)(void *)&Output
);
966 PySys_SetObject("stderr", (PyObject
*)(void *)&Error
);
968 if (PyErr_Occurred())
970 EMSG(_("E264: Python: Error initialising I/O objects"));
977 /******************************************************
978 * 3. Implementation of the Vim module for Python
981 /* Vim module - Implementation functions
982 * -------------------------------------
985 static PyObject
*VimError
;
987 static PyObject
*VimCommand(PyObject
*, PyObject
*);
988 static PyObject
*VimEval(PyObject
*, PyObject
*);
990 /* Window type - Implementation functions
991 * --------------------------------------
1001 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1003 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1005 static PyObject
*WindowNew(win_T
*);
1007 static void WindowDestructor(PyObject
*);
1008 static PyObject
*WindowGetattr(PyObject
*, char *);
1009 static int WindowSetattr(PyObject
*, char *, PyObject
*);
1010 static PyObject
*WindowRepr(PyObject
*);
1012 /* Buffer type - Implementation functions
1013 * --------------------------------------
1023 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1025 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1027 static PyObject
*BufferNew (buf_T
*);
1029 static void BufferDestructor(PyObject
*);
1030 static PyObject
*BufferGetattr(PyObject
*, char *);
1031 static PyObject
*BufferRepr(PyObject
*);
1033 static PyInt
BufferLength(PyObject
*);
1034 static PyObject
*BufferItem(PyObject
*, PyInt
);
1035 static PyObject
*BufferSlice(PyObject
*, PyInt
, PyInt
);
1036 static PyInt
BufferAssItem(PyObject
*, PyInt
, PyObject
*);
1037 static PyInt
BufferAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1039 static PyObject
*BufferAppend(PyObject
*, PyObject
*);
1040 static PyObject
*BufferMark(PyObject
*, PyObject
*);
1041 static PyObject
*BufferRange(PyObject
*, PyObject
*);
1043 /* Line range type - Implementation functions
1044 * --------------------------------------
1056 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1058 static PyObject
*RangeNew(buf_T
*, PyInt
, PyInt
);
1060 static void RangeDestructor(PyObject
*);
1061 static PyObject
*RangeGetattr(PyObject
*, char *);
1062 static PyObject
*RangeRepr(PyObject
*);
1064 static PyInt
RangeLength(PyObject
*);
1065 static PyObject
*RangeItem(PyObject
*, PyInt
);
1066 static PyObject
*RangeSlice(PyObject
*, PyInt
, PyInt
);
1067 static PyInt
RangeAssItem(PyObject
*, PyInt
, PyObject
*);
1068 static PyInt
RangeAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1070 static PyObject
*RangeAppend(PyObject
*, PyObject
*);
1072 /* Window list type - Implementation functions
1073 * -------------------------------------------
1076 static PyInt
WinListLength(PyObject
*);
1077 static PyObject
*WinListItem(PyObject
*, PyInt
);
1079 /* Buffer list type - Implementation functions
1080 * -------------------------------------------
1083 static PyInt
BufListLength(PyObject
*);
1084 static PyObject
*BufListItem(PyObject
*, PyInt
);
1086 /* Current objects type - Implementation functions
1087 * -----------------------------------------------
1090 static PyObject
*CurrentGetattr(PyObject
*, char *);
1091 static int CurrentSetattr(PyObject
*, char *, PyObject
*);
1093 /* Vim module - Definitions
1096 static struct PyMethodDef VimMethods
[] = {
1097 /* name, function, calling, documentation */
1098 {"command", VimCommand
, 1, "Execute a Vim ex-mode command" },
1099 {"eval", VimEval
, 1, "Evaluate an expression using Vim evaluator" },
1100 { NULL
, NULL
, 0, NULL
}
1103 /* Vim module - Implementation
1106 VimCommand(PyObject
*self UNUSED
, PyObject
*args
)
1111 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1116 Py_BEGIN_ALLOW_THREADS
1119 do_cmdline_cmd((char_u
*)cmd
);
1120 update_screen(VALID
);
1122 Python_Release_Vim();
1123 Py_END_ALLOW_THREADS
1125 if (VimErrorCheck())
1136 * Function to translate a typval_T into a PyObject; this will recursively
1137 * translate lists/dictionaries into their Python equivalents.
1139 * The depth parameter is to avoid infinite recursion, set it to 1 when
1140 * you call VimToPython.
1143 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1147 char ptrBuf
[NUMBUFLEN
];
1149 /* Avoid infinite recursion */
1157 /* Check if we run into a recursive loop. The item must be in lookupDict
1158 * then and we can use it again. */
1159 if ((our_tv
->v_type
== VAR_LIST
&& our_tv
->vval
.v_list
!= NULL
)
1160 || (our_tv
->v_type
== VAR_DICT
&& our_tv
->vval
.v_dict
!= NULL
))
1162 sprintf(ptrBuf
, PRINTF_DECIMAL_LONG_U
,
1163 our_tv
->v_type
== VAR_LIST
? (long_u
)our_tv
->vval
.v_list
1164 : (long_u
)our_tv
->vval
.v_dict
);
1165 result
= PyDict_GetItemString(lookupDict
, ptrBuf
);
1173 if (our_tv
->v_type
== VAR_STRING
)
1175 result
= Py_BuildValue("s", our_tv
->vval
.v_string
);
1177 else if (our_tv
->v_type
== VAR_NUMBER
)
1179 char buf
[NUMBUFLEN
];
1181 /* For backwards compatibility numbers are stored as strings. */
1182 sprintf(buf
, "%ld", (long)our_tv
->vval
.v_number
);
1183 result
= Py_BuildValue("s", buf
);
1186 else if (our_tv
->v_type
== VAR_FLOAT
)
1188 char buf
[NUMBUFLEN
];
1190 sprintf(buf
, "%f", our_tv
->vval
.v_float
);
1191 result
= Py_BuildValue("s", buf
);
1194 else if (our_tv
->v_type
== VAR_LIST
)
1196 list_T
*list
= our_tv
->vval
.v_list
;
1199 result
= PyList_New(0);
1203 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1205 for (curr
= list
->lv_first
; curr
!= NULL
; curr
= curr
->li_next
)
1207 newObj
= VimToPython(&curr
->li_tv
, depth
+ 1, lookupDict
);
1208 PyList_Append(result
, newObj
);
1213 else if (our_tv
->v_type
== VAR_DICT
)
1215 result
= PyDict_New();
1217 if (our_tv
->vval
.v_dict
!= NULL
)
1219 hashtab_T
*ht
= &our_tv
->vval
.v_dict
->dv_hashtab
;
1220 long_u todo
= ht
->ht_used
;
1224 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1226 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1228 if (!HASHITEM_EMPTY(hi
))
1232 di
= dict_lookup(hi
);
1233 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1234 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1251 VimEval(PyObject
*self UNUSED
, PyObject
*args
)
1257 PyObject
*lookup_dict
;
1259 if (!PyArg_ParseTuple(args
, "s", &expr
))
1262 Py_BEGIN_ALLOW_THREADS
1264 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1266 Python_Release_Vim();
1267 Py_END_ALLOW_THREADS
1271 PyErr_SetVim(_("invalid expression"));
1275 /* Convert the Vim type into a Python type. Create a dictionary that's
1276 * used to check for recursive loops. */
1277 lookup_dict
= PyDict_New();
1278 result
= VimToPython(our_tv
, 1, lookup_dict
);
1279 Py_DECREF(lookup_dict
);
1282 Py_BEGIN_ALLOW_THREADS
1285 Python_Release_Vim();
1286 Py_END_ALLOW_THREADS
1290 PyErr_SetVim(_("expressions disabled at compile time"));
1295 /* Common routines for buffers and line ranges
1296 * -------------------------------------------
1299 CheckBuffer(BufferObject
*this)
1301 if (this->buf
== INVALID_BUFFER_VALUE
)
1303 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1311 RBItem(BufferObject
*self
, PyInt n
, PyInt start
, PyInt end
)
1313 if (CheckBuffer(self
))
1316 if (n
< 0 || n
> end
- start
)
1318 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1322 return GetBufferLine(self
->buf
, n
+start
);
1326 RBSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyInt start
, PyInt end
)
1330 if (CheckBuffer(self
))
1333 size
= end
- start
+ 1;
1346 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1350 RBAssItem(BufferObject
*self
, PyInt n
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1354 if (CheckBuffer(self
))
1357 if (n
< 0 || n
> end
- start
)
1359 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1363 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1367 *new_end
= end
+ len_change
;
1373 RBAssSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1378 /* Self must be a valid buffer */
1379 if (CheckBuffer(self
))
1382 /* Sort out the slice range */
1383 size
= end
- start
+ 1;
1396 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1400 *new_end
= end
+ len_change
;
1406 RBAppend(BufferObject
*self
, PyObject
*args
, PyInt start
, PyInt end
, PyInt
*new_end
)
1413 if (CheckBuffer(self
))
1416 max
= n
= end
- start
+ 1;
1418 if (!PyArg_ParseTuple(args
, "O|" Py_ssize_t_fmt
, &lines
, &n
))
1421 if (n
< 0 || n
> max
)
1423 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1427 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1431 *new_end
= end
+ len_change
;
1438 /* Buffer object - Definitions
1441 static struct PyMethodDef BufferMethods
[] = {
1442 /* name, function, calling, documentation */
1443 {"append", BufferAppend
, 1, "Append data to Vim buffer" },
1444 {"mark", BufferMark
, 1, "Return (row,col) representing position of named mark" },
1445 {"range", BufferRange
, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1446 { NULL
, NULL
, 0, NULL
}
1449 static PySequenceMethods BufferAsSeq
= {
1450 (PyInquiry
) BufferLength
, /* sq_length, len(x) */
1451 (binaryfunc
) 0, /* BufferConcat, */ /* sq_concat, x+y */
1452 (PyIntArgFunc
) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1453 (PyIntArgFunc
) BufferItem
, /* sq_item, x[i] */
1454 (PyIntIntArgFunc
) BufferSlice
, /* sq_slice, x[i:j] */
1455 (PyIntObjArgProc
) BufferAssItem
, /* sq_ass_item, x[i]=v */
1456 (PyIntIntObjArgProc
) BufferAssSlice
, /* sq_ass_slice, x[i:j]=v */
1459 static PyTypeObject BufferType
= {
1460 PyObject_HEAD_INIT(0)
1463 sizeof(BufferObject
),
1466 (destructor
) BufferDestructor
, /* tp_dealloc, refcount==0 */
1467 (printfunc
) 0, /* tp_print, print x */
1468 (getattrfunc
) BufferGetattr
, /* tp_getattr, x.attr */
1469 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1470 (cmpfunc
) 0, /* tp_compare, x>y */
1471 (reprfunc
) BufferRepr
, /* tp_repr, `x`, print x */
1474 &BufferAsSeq
, /* as sequence */
1477 (hashfunc
) 0, /* tp_hash, dict(x) */
1478 (ternaryfunc
) 0, /* tp_call, x() */
1479 (reprfunc
) 0, /* tp_str, str(x) */
1482 /* Buffer object - Implementation
1486 BufferNew(buf_T
*buf
)
1488 /* We need to handle deletion of buffers underneath us.
1489 * If we add a "b_python_ref" field to the buf_T structure,
1490 * then we can get at it in buf_freeall() in vim. We then
1491 * need to create only ONE Python object per buffer - if
1492 * we try to create a second, just INCREF the existing one
1493 * and return it. The (single) Python object referring to
1494 * the buffer is stored in "b_python_ref".
1495 * Question: what to do on a buf_freeall(). We'll probably
1496 * have to either delete the Python object (DECREF it to
1497 * zero - a bad idea, as it leaves dangling refs!) or
1498 * set the buf_T * value to an invalid value (-1?), which
1499 * means we need checks in all access functions... Bah.
1504 if (buf
->b_python_ref
!= NULL
)
1506 self
= buf
->b_python_ref
;
1511 self
= PyObject_NEW(BufferObject
, &BufferType
);
1515 buf
->b_python_ref
= self
;
1518 return (PyObject
*)(self
);
1522 BufferDestructor(PyObject
*self
)
1524 BufferObject
*this = (BufferObject
*)(self
);
1526 if (this->buf
&& this->buf
!= INVALID_BUFFER_VALUE
)
1527 this->buf
->b_python_ref
= NULL
;
1533 BufferGetattr(PyObject
*self
, char *name
)
1535 BufferObject
*this = (BufferObject
*)(self
);
1537 if (CheckBuffer(this))
1540 if (strcmp(name
, "name") == 0)
1541 return Py_BuildValue("s", this->buf
->b_ffname
);
1542 else if (strcmp(name
, "number") == 0)
1543 return Py_BuildValue(Py_ssize_t_fmt
, this->buf
->b_fnum
);
1544 else if (strcmp(name
,"__members__") == 0)
1545 return Py_BuildValue("[ss]", "name", "number");
1547 return Py_FindMethod(BufferMethods
, self
, name
);
1551 BufferRepr(PyObject
*self
)
1553 static char repr
[100];
1554 BufferObject
*this = (BufferObject
*)(self
);
1556 if (this->buf
== INVALID_BUFFER_VALUE
)
1558 vim_snprintf(repr
, 100, _("<buffer object (deleted) at %p>"), (self
));
1559 return PyString_FromString(repr
);
1563 char *name
= (char *)this->buf
->b_fname
;
1571 name
= name
+ (35 - len
);
1573 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1575 return PyString_FromString(repr
);
1579 /******************/
1582 BufferLength(PyObject
*self
)
1584 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1585 if (CheckBuffer((BufferObject
*)(self
)))
1586 return -1; /* ??? */
1588 return (((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1592 BufferItem(PyObject
*self
, PyInt n
)
1594 return RBItem((BufferObject
*)(self
), n
, 1,
1595 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1599 BufferSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1601 return RBSlice((BufferObject
*)(self
), lo
, hi
, 1,
1602 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1606 BufferAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1608 return RBAssItem((BufferObject
*)(self
), n
, val
, 1,
1609 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1614 BufferAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1616 return RBAssSlice((BufferObject
*)(self
), lo
, hi
, val
, 1,
1617 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1622 BufferAppend(PyObject
*self
, PyObject
*args
)
1624 return RBAppend((BufferObject
*)(self
), args
, 1,
1625 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1630 BufferMark(PyObject
*self
, PyObject
*args
)
1636 if (CheckBuffer((BufferObject
*)(self
)))
1639 if (!PyArg_ParseTuple(args
, "c", &mark
))
1642 curbuf_save
= curbuf
;
1643 curbuf
= ((BufferObject
*)(self
))->buf
;
1644 posp
= getmark(mark
, FALSE
);
1645 curbuf
= curbuf_save
;
1649 PyErr_SetVim(_("invalid mark name"));
1653 /* Ckeck for keyboard interrupt */
1654 if (VimErrorCheck())
1657 if (posp
->lnum
<= 0)
1659 /* Or raise an error? */
1664 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1668 BufferRange(PyObject
*self
, PyObject
*args
)
1673 if (CheckBuffer((BufferObject
*)(self
)))
1676 if (!PyArg_ParseTuple(args
, Py_ssize_t_fmt Py_ssize_t_fmt
, &start
, &end
))
1679 return RangeNew(((BufferObject
*)(self
))->buf
, start
, end
);
1682 /* Line range object - Definitions
1685 static struct PyMethodDef RangeMethods
[] = {
1686 /* name, function, calling, documentation */
1687 {"append", RangeAppend
, 1, "Append data to the Vim range" },
1688 { NULL
, NULL
, 0, NULL
}
1691 static PySequenceMethods RangeAsSeq
= {
1692 (PyInquiry
) RangeLength
, /* sq_length, len(x) */
1693 (binaryfunc
) 0, /* RangeConcat, */ /* sq_concat, x+y */
1694 (PyIntArgFunc
) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1695 (PyIntArgFunc
) RangeItem
, /* sq_item, x[i] */
1696 (PyIntIntArgFunc
) RangeSlice
, /* sq_slice, x[i:j] */
1697 (PyIntObjArgProc
) RangeAssItem
, /* sq_ass_item, x[i]=v */
1698 (PyIntIntObjArgProc
) RangeAssSlice
, /* sq_ass_slice, x[i:j]=v */
1701 static PyTypeObject RangeType
= {
1702 PyObject_HEAD_INIT(0)
1705 sizeof(RangeObject
),
1708 (destructor
) RangeDestructor
, /* tp_dealloc, refcount==0 */
1709 (printfunc
) 0, /* tp_print, print x */
1710 (getattrfunc
) RangeGetattr
, /* tp_getattr, x.attr */
1711 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1712 (cmpfunc
) 0, /* tp_compare, x>y */
1713 (reprfunc
) RangeRepr
, /* tp_repr, `x`, print x */
1716 &RangeAsSeq
, /* as sequence */
1719 (hashfunc
) 0, /* tp_hash, dict(x) */
1720 (ternaryfunc
) 0, /* tp_call, x() */
1721 (reprfunc
) 0, /* tp_str, str(x) */
1724 /* Line range object - Implementation
1728 RangeNew(buf_T
*buf
, PyInt start
, PyInt end
)
1732 self
= PyObject_NEW(RangeObject
, &RangeType
);
1736 bufr
= (BufferObject
*)BufferNew(buf
);
1745 self
->start
= start
;
1748 return (PyObject
*)(self
);
1752 RangeDestructor(PyObject
*self
)
1754 Py_DECREF(((RangeObject
*)(self
))->buf
);
1759 RangeGetattr(PyObject
*self
, char *name
)
1761 if (strcmp(name
, "start") == 0)
1762 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->start
- 1);
1763 else if (strcmp(name
, "end") == 0)
1764 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->end
- 1);
1766 return Py_FindMethod(RangeMethods
, self
, name
);
1770 RangeRepr(PyObject
*self
)
1772 static char repr
[100];
1773 RangeObject
*this = (RangeObject
*)(self
);
1775 if (this->buf
->buf
== INVALID_BUFFER_VALUE
)
1777 vim_snprintf(repr
, 100, "<range object (for deleted buffer) at %p>",
1779 return PyString_FromString(repr
);
1783 char *name
= (char *)this->buf
->buf
->b_fname
;
1788 len
= (int)strlen(name
);
1791 name
= name
+ (45 - len
);
1793 vim_snprintf(repr
, 100, "<range %s%s (%d:%d)>",
1794 len
> 45 ? "..." : "", name
,
1795 this->start
, this->end
);
1797 return PyString_FromString(repr
);
1804 RangeLength(PyObject
*self
)
1806 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1807 if (CheckBuffer(((RangeObject
*)(self
))->buf
))
1808 return -1; /* ??? */
1810 return (((RangeObject
*)(self
))->end
- ((RangeObject
*)(self
))->start
+ 1);
1814 RangeItem(PyObject
*self
, PyInt n
)
1816 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1817 ((RangeObject
*)(self
))->start
,
1818 ((RangeObject
*)(self
))->end
);
1822 RangeSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1824 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1825 ((RangeObject
*)(self
))->start
,
1826 ((RangeObject
*)(self
))->end
);
1830 RangeAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1832 return RBAssItem(((RangeObject
*)(self
))->buf
, n
, val
,
1833 ((RangeObject
*)(self
))->start
,
1834 ((RangeObject
*)(self
))->end
,
1835 &((RangeObject
*)(self
))->end
);
1839 RangeAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1841 return RBAssSlice(((RangeObject
*)(self
))->buf
, lo
, hi
, val
,
1842 ((RangeObject
*)(self
))->start
,
1843 ((RangeObject
*)(self
))->end
,
1844 &((RangeObject
*)(self
))->end
);
1848 RangeAppend(PyObject
*self
, PyObject
*args
)
1850 return RBAppend(((RangeObject
*)(self
))->buf
, args
,
1851 ((RangeObject
*)(self
))->start
,
1852 ((RangeObject
*)(self
))->end
,
1853 &((RangeObject
*)(self
))->end
);
1856 /* Buffer list object - Definitions
1865 static PySequenceMethods BufListAsSeq
= {
1866 (PyInquiry
) BufListLength
, /* sq_length, len(x) */
1867 (binaryfunc
) 0, /* sq_concat, x+y */
1868 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
1869 (PyIntArgFunc
) BufListItem
, /* sq_item, x[i] */
1870 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
1871 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
1872 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
1875 static PyTypeObject BufListType
= {
1876 PyObject_HEAD_INIT(0)
1879 sizeof(BufListObject
),
1882 (destructor
) 0, /* tp_dealloc, refcount==0 */
1883 (printfunc
) 0, /* tp_print, print x */
1884 (getattrfunc
) 0, /* tp_getattr, x.attr */
1885 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1886 (cmpfunc
) 0, /* tp_compare, x>y */
1887 (reprfunc
) 0, /* tp_repr, `x`, print x */
1890 &BufListAsSeq
, /* as sequence */
1893 (hashfunc
) 0, /* tp_hash, dict(x) */
1894 (ternaryfunc
) 0, /* tp_call, x() */
1895 (reprfunc
) 0, /* tp_str, str(x) */
1898 /* Buffer list object - Implementation
1902 BufListLength(PyObject
*self UNUSED
)
1904 buf_T
*b
= firstbuf
;
1917 BufListItem(PyObject
*self UNUSED
, PyInt n
)
1921 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1924 return BufferNew(b
);
1927 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
1931 /* Window object - Definitions
1934 static struct PyMethodDef WindowMethods
[] = {
1935 /* name, function, calling, documentation */
1936 { NULL
, NULL
, 0, NULL
}
1939 static PyTypeObject WindowType
= {
1940 PyObject_HEAD_INIT(0)
1943 sizeof(WindowObject
),
1946 (destructor
) WindowDestructor
, /* tp_dealloc, refcount==0 */
1947 (printfunc
) 0, /* tp_print, print x */
1948 (getattrfunc
) WindowGetattr
, /* tp_getattr, x.attr */
1949 (setattrfunc
) WindowSetattr
, /* tp_setattr, x.attr=v */
1950 (cmpfunc
) 0, /* tp_compare, x>y */
1951 (reprfunc
) WindowRepr
, /* tp_repr, `x`, print x */
1954 0, /* as sequence */
1957 (hashfunc
) 0, /* tp_hash, dict(x) */
1958 (ternaryfunc
) 0, /* tp_call, x() */
1959 (reprfunc
) 0, /* tp_str, str(x) */
1962 /* Window object - Implementation
1966 WindowNew(win_T
*win
)
1968 /* We need to handle deletion of windows underneath us.
1969 * If we add a "w_python_ref" field to the win_T structure,
1970 * then we can get at it in win_free() in vim. We then
1971 * need to create only ONE Python object per window - if
1972 * we try to create a second, just INCREF the existing one
1973 * and return it. The (single) Python object referring to
1974 * the window is stored in "w_python_ref".
1975 * On a win_free() we set the Python object's win_T* field
1976 * to an invalid value. We trap all uses of a window
1977 * object, and reject them if the win_T* field is invalid.
1982 if (win
->w_python_ref
)
1984 self
= win
->w_python_ref
;
1989 self
= PyObject_NEW(WindowObject
, &WindowType
);
1993 win
->w_python_ref
= self
;
1996 return (PyObject
*)(self
);
2000 WindowDestructor(PyObject
*self
)
2002 WindowObject
*this = (WindowObject
*)(self
);
2004 if (this->win
&& this->win
!= INVALID_WINDOW_VALUE
)
2005 this->win
->w_python_ref
= NULL
;
2011 CheckWindow(WindowObject
*this)
2013 if (this->win
== INVALID_WINDOW_VALUE
)
2015 PyErr_SetVim(_("attempt to refer to deleted window"));
2023 WindowGetattr(PyObject
*self
, char *name
)
2025 WindowObject
*this = (WindowObject
*)(self
);
2027 if (CheckWindow(this))
2030 if (strcmp(name
, "buffer") == 0)
2031 return (PyObject
*)BufferNew(this->win
->w_buffer
);
2032 else if (strcmp(name
, "cursor") == 0)
2034 pos_T
*pos
= &this->win
->w_cursor
;
2036 return Py_BuildValue("(ll)", (long)(pos
->lnum
), (long)(pos
->col
));
2038 else if (strcmp(name
, "height") == 0)
2039 return Py_BuildValue("l", (long)(this->win
->w_height
));
2040 #ifdef FEAT_VERTSPLIT
2041 else if (strcmp(name
, "width") == 0)
2042 return Py_BuildValue("l", (long)(W_WIDTH(this->win
)));
2044 else if (strcmp(name
,"__members__") == 0)
2045 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2047 return Py_FindMethod(WindowMethods
, self
, name
);
2051 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
2053 WindowObject
*this = (WindowObject
*)(self
);
2055 if (CheckWindow(this))
2058 if (strcmp(name
, "buffer") == 0)
2060 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2063 else if (strcmp(name
, "cursor") == 0)
2069 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2072 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2074 PyErr_SetVim(_("cursor position outside buffer"));
2078 /* Check for keyboard interrupts */
2079 if (VimErrorCheck())
2082 /* When column is out of range silently correct it. */
2083 len
= (long)STRLEN(ml_get_buf(this->win
->w_buffer
, lnum
, FALSE
));
2087 this->win
->w_cursor
.lnum
= lnum
;
2088 this->win
->w_cursor
.col
= col
;
2089 #ifdef FEAT_VIRTUALEDIT
2090 this->win
->w_cursor
.coladd
= 0;
2092 update_screen(VALID
);
2096 else if (strcmp(name
, "height") == 0)
2101 if (!PyArg_Parse(val
, "i", &height
))
2105 need_mouse_correct
= TRUE
;
2109 win_setheight(height
);
2112 /* Check for keyboard interrupts */
2113 if (VimErrorCheck())
2118 #ifdef FEAT_VERTSPLIT
2119 else if (strcmp(name
, "width") == 0)
2124 if (!PyArg_Parse(val
, "i", &width
))
2128 need_mouse_correct
= TRUE
;
2132 win_setwidth(width
);
2135 /* Check for keyboard interrupts */
2136 if (VimErrorCheck())
2144 PyErr_SetString(PyExc_AttributeError
, name
);
2150 WindowRepr(PyObject
*self
)
2152 static char repr
[100];
2153 WindowObject
*this = (WindowObject
*)(self
);
2155 if (this->win
== INVALID_WINDOW_VALUE
)
2157 vim_snprintf(repr
, 100, _("<window object (deleted) at %p>"), (self
));
2158 return PyString_FromString(repr
);
2165 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2169 vim_snprintf(repr
, 100, _("<window object (unknown) at %p>"),
2172 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2174 return PyString_FromString(repr
);
2178 /* Window list object - Definitions
2187 static PySequenceMethods WinListAsSeq
= {
2188 (PyInquiry
) WinListLength
, /* sq_length, len(x) */
2189 (binaryfunc
) 0, /* sq_concat, x+y */
2190 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
2191 (PyIntArgFunc
) WinListItem
, /* sq_item, x[i] */
2192 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
2193 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
2194 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
2197 static PyTypeObject WinListType
= {
2198 PyObject_HEAD_INIT(0)
2201 sizeof(WinListObject
),
2204 (destructor
) 0, /* tp_dealloc, refcount==0 */
2205 (printfunc
) 0, /* tp_print, print x */
2206 (getattrfunc
) 0, /* tp_getattr, x.attr */
2207 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
2208 (cmpfunc
) 0, /* tp_compare, x>y */
2209 (reprfunc
) 0, /* tp_repr, `x`, print x */
2212 &WinListAsSeq
, /* as sequence */
2215 (hashfunc
) 0, /* tp_hash, dict(x) */
2216 (ternaryfunc
) 0, /* tp_call, x() */
2217 (reprfunc
) 0, /* tp_str, str(x) */
2220 /* Window list object - Implementation
2223 WinListLength(PyObject
*self UNUSED
)
2225 win_T
*w
= firstwin
;
2238 WinListItem(PyObject
*self UNUSED
, PyInt n
)
2242 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2244 return WindowNew(w
);
2246 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2250 /* Current items object - Definitions
2259 static PyTypeObject CurrentType
= {
2260 PyObject_HEAD_INIT(0)
2263 sizeof(CurrentObject
),
2266 (destructor
) 0, /* tp_dealloc, refcount==0 */
2267 (printfunc
) 0, /* tp_print, print x */
2268 (getattrfunc
) CurrentGetattr
, /* tp_getattr, x.attr */
2269 (setattrfunc
) CurrentSetattr
, /* tp_setattr, x.attr=v */
2270 (cmpfunc
) 0, /* tp_compare, x>y */
2271 (reprfunc
) 0, /* tp_repr, `x`, print x */
2274 0, /* as sequence */
2277 (hashfunc
) 0, /* tp_hash, dict(x) */
2278 (ternaryfunc
) 0, /* tp_call, x() */
2279 (reprfunc
) 0, /* tp_str, str(x) */
2282 /* Current items object - Implementation
2285 CurrentGetattr(PyObject
*self UNUSED
, char *name
)
2287 if (strcmp(name
, "buffer") == 0)
2288 return (PyObject
*)BufferNew(curbuf
);
2289 else if (strcmp(name
, "window") == 0)
2290 return (PyObject
*)WindowNew(curwin
);
2291 else if (strcmp(name
, "line") == 0)
2292 return GetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
);
2293 else if (strcmp(name
, "range") == 0)
2294 return RangeNew(curbuf
, RangeStart
, RangeEnd
);
2295 else if (strcmp(name
,"__members__") == 0)
2296 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2299 PyErr_SetString(PyExc_AttributeError
, name
);
2305 CurrentSetattr(PyObject
*self UNUSED
, char *name
, PyObject
*value
)
2307 if (strcmp(name
, "line") == 0)
2309 if (SetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
, value
, NULL
) == FAIL
)
2316 PyErr_SetString(PyExc_AttributeError
, name
);
2321 /* External interface
2325 python_buffer_free(buf_T
*buf
)
2327 if (buf
->b_python_ref
!= NULL
)
2329 BufferObject
*bp
= buf
->b_python_ref
;
2330 bp
->buf
= INVALID_BUFFER_VALUE
;
2331 buf
->b_python_ref
= NULL
;
2335 #if defined(FEAT_WINDOWS) || defined(PROTO)
2337 python_window_free(win_T
*win
)
2339 if (win
->w_python_ref
!= NULL
)
2341 WindowObject
*wp
= win
->w_python_ref
;
2342 wp
->win
= INVALID_WINDOW_VALUE
;
2343 win
->w_python_ref
= NULL
;
2348 static BufListObject TheBufferList
=
2350 PyObject_HEAD_INIT(&BufListType
)
2353 static WinListObject TheWindowList
=
2355 PyObject_HEAD_INIT(&WinListType
)
2358 static CurrentObject TheCurrent
=
2360 PyObject_HEAD_INIT(&CurrentType
)
2364 PythonMod_Init(void)
2368 /* The special value is removed from sys.path in Python_Init(). */
2369 static char *(argv
[2]) = {"/must>not&exist/foo", NULL
};
2372 BufferType
.ob_type
= &PyType_Type
;
2373 RangeType
.ob_type
= &PyType_Type
;
2374 WindowType
.ob_type
= &PyType_Type
;
2375 BufListType
.ob_type
= &PyType_Type
;
2376 WinListType
.ob_type
= &PyType_Type
;
2377 CurrentType
.ob_type
= &PyType_Type
;
2379 /* Set sys.argv[] to avoid a crash in warn(). */
2380 PySys_SetArgv(1, argv
);
2382 mod
= Py_InitModule4("vim", VimMethods
, (char *)NULL
, (PyObject
*)NULL
, PYTHON_API_VERSION
);
2383 dict
= PyModule_GetDict(mod
);
2385 VimError
= Py_BuildValue("s", "vim.error");
2387 PyDict_SetItemString(dict
, "error", VimError
);
2388 PyDict_SetItemString(dict
, "buffers", (PyObject
*)(void *)&TheBufferList
);
2389 PyDict_SetItemString(dict
, "current", (PyObject
*)(void *)&TheCurrent
);
2390 PyDict_SetItemString(dict
, "windows", (PyObject
*)(void *)&TheWindowList
);
2392 if (PyErr_Occurred())
2398 /*************************************************************************
2399 * 4. Utility functions for handling the interface between Vim and Python.
2402 /* Get a line from the specified buffer. The line number is
2403 * in Vim format (1-based). The line is returned as a Python
2407 GetBufferLine(buf_T
*buf
, PyInt n
)
2409 return LineToString((char *)ml_get_buf(buf
, (linenr_T
)n
, FALSE
));
2412 /* Get a list of lines from the specified buffer. The line numbers
2413 * are in Vim format (1-based). The range is from lo up to, but not
2414 * including, hi. The list is returned as a Python list of string objects.
2417 GetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
)
2421 PyObject
*list
= PyList_New(n
);
2426 for (i
= 0; i
< n
; ++i
)
2428 PyObject
*str
= LineToString((char *)ml_get_buf(buf
, (linenr_T
)(lo
+i
), FALSE
));
2430 /* Error check - was the Python string creation OK? */
2437 /* Set the list item */
2438 if (PyList_SetItem(list
, i
, str
))
2446 /* The ownership of the Python list is passed to the caller (ie,
2447 * the caller should Py_DECREF() the object when it is finished
2455 * Check if deleting lines made the cursor position invalid.
2456 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2460 py_fix_cursor(linenr_T lo
, linenr_T hi
, linenr_T extra
)
2462 if (curwin
->w_cursor
.lnum
>= lo
)
2464 /* Adjust the cursor position if it's in/after the changed
2466 if (curwin
->w_cursor
.lnum
>= hi
)
2468 curwin
->w_cursor
.lnum
+= extra
;
2473 curwin
->w_cursor
.lnum
= lo
;
2478 changed_cline_bef_curs();
2480 invalidate_botline();
2483 /* Replace a line in the specified buffer. The line number is
2484 * in Vim format (1-based). The replacement line is given as
2485 * a Python string object. The object is checked for validity
2486 * and correct format. Errors are returned as a value of FAIL.
2487 * The return value is OK on success.
2488 * If OK is returned and len_change is not NULL, *len_change
2489 * is set to the change in the buffer length.
2492 SetBufferLine(buf_T
*buf
, PyInt n
, PyObject
*line
, PyInt
*len_change
)
2494 /* First of all, we check the thpe of the supplied Python object.
2495 * There are three cases:
2496 * 1. NULL, or None - this is a deletion.
2497 * 2. A string - this is a replacement.
2498 * 3. Anything else - this is an error.
2500 if (line
== Py_None
|| line
== NULL
)
2502 buf_T
*savebuf
= curbuf
;
2507 if (u_savedel((linenr_T
)n
, 1L) == FAIL
)
2508 PyErr_SetVim(_("cannot save undo information"));
2509 else if (ml_delete((linenr_T
)n
, FALSE
) == FAIL
)
2510 PyErr_SetVim(_("cannot delete line"));
2513 if (buf
== curwin
->w_buffer
)
2514 py_fix_cursor((linenr_T
)n
, (linenr_T
)n
+ 1, (linenr_T
)-1);
2515 deleted_lines_mark((linenr_T
)n
, 1L);
2520 if (PyErr_Occurred() || VimErrorCheck())
2528 else if (PyString_Check(line
))
2530 char *save
= StringToLine(line
);
2531 buf_T
*savebuf
= curbuf
;
2536 /* We do not need to free "save" if ml_replace() consumes it. */
2540 if (u_savesub((linenr_T
)n
) == FAIL
)
2542 PyErr_SetVim(_("cannot save undo information"));
2545 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2547 PyErr_SetVim(_("cannot replace line"));
2551 changed_bytes((linenr_T
)n
, 0);
2555 /* Check that the cursor is not beyond the end of the line now. */
2556 if (buf
== curwin
->w_buffer
)
2559 if (PyErr_Occurred() || VimErrorCheck())
2569 PyErr_BadArgument();
2574 /* Replace a range of lines in the specified buffer. The line numbers are in
2575 * Vim format (1-based). The range is from lo up to, but not including, hi.
2576 * The replacement lines are given as a Python list of string objects. The
2577 * list is checked for validity and correct format. Errors are returned as a
2578 * value of FAIL. The return value is OK on success.
2579 * If OK is returned and len_change is not NULL, *len_change
2580 * is set to the change in the buffer length.
2583 SetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
, PyObject
*list
, PyInt
*len_change
)
2585 /* First of all, we check the thpe of the supplied Python object.
2586 * There are three cases:
2587 * 1. NULL, or None - this is a deletion.
2588 * 2. A list - this is a replacement.
2589 * 3. Anything else - this is an error.
2591 if (list
== Py_None
|| list
== NULL
)
2594 PyInt n
= (int)(hi
- lo
);
2595 buf_T
*savebuf
= curbuf
;
2600 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2601 PyErr_SetVim(_("cannot save undo information"));
2604 for (i
= 0; i
< n
; ++i
)
2606 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2608 PyErr_SetVim(_("cannot delete line"));
2612 if (buf
== curwin
->w_buffer
)
2613 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)-n
);
2614 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2619 if (PyErr_Occurred() || VimErrorCheck())
2627 else if (PyList_Check(list
))
2630 PyInt new_len
= PyList_Size(list
);
2631 PyInt old_len
= hi
- lo
;
2632 PyInt extra
= 0; /* lines added to text, can be negative */
2636 if (new_len
== 0) /* avoid allocating zero bytes */
2640 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
2648 for (i
= 0; i
< new_len
; ++i
)
2650 PyObject
*line
= PyList_GetItem(list
, i
);
2652 array
[i
] = StringToLine(line
);
2653 if (array
[i
] == NULL
)
2656 vim_free(array
[--i
]);
2667 if (u_save((linenr_T
)(lo
-1), (linenr_T
)hi
) == FAIL
)
2668 PyErr_SetVim(_("cannot save undo information"));
2670 /* If the size of the range is reducing (ie, new_len < old_len) we
2671 * need to delete some old_len. We do this at the start, by
2672 * repeatedly deleting line "lo".
2674 if (!PyErr_Occurred())
2676 for (i
= 0; i
< old_len
- new_len
; ++i
)
2677 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2679 PyErr_SetVim(_("cannot delete line"));
2685 /* For as long as possible, replace the existing old_len with the
2686 * new old_len. This is a more efficient operation, as it requires
2687 * less memory allocation and freeing.
2689 if (!PyErr_Occurred())
2691 for (i
= 0; i
< old_len
&& i
< new_len
; ++i
)
2692 if (ml_replace((linenr_T
)(lo
+i
), (char_u
*)array
[i
], FALSE
)
2695 PyErr_SetVim(_("cannot replace line"));
2702 /* Now we may need to insert the remaining new old_len. If we do, we
2703 * must free the strings as we finish with them (we can't pass the
2704 * responsibility to vim in this case).
2706 if (!PyErr_Occurred())
2710 if (ml_append((linenr_T
)(lo
+ i
- 1),
2711 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2713 PyErr_SetVim(_("cannot insert line"));
2722 /* Free any left-over old_len, as a result of an error */
2729 /* Free the array of old_len. All of its contents have now
2730 * been dealt with (either freed, or the responsibility passed
2735 /* Adjust marks. Invalidate any which lie in the
2736 * changed range, and move any in the remainder of the buffer.
2738 mark_adjust((linenr_T
)lo
, (linenr_T
)(hi
- 1),
2739 (long)MAXLNUM
, (long)extra
);
2740 changed_lines((linenr_T
)lo
, 0, (linenr_T
)hi
, (long)extra
);
2742 if (buf
== curwin
->w_buffer
)
2743 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)extra
);
2747 if (PyErr_Occurred() || VimErrorCheck())
2751 *len_change
= new_len
- old_len
;
2757 PyErr_BadArgument();
2762 /* Insert a number of lines into the specified buffer after the specifed line.
2763 * The line number is in Vim format (1-based). The lines to be inserted are
2764 * given as a Python list of string objects or as a single string. The lines
2765 * to be added are checked for validity and correct format. Errors are
2766 * returned as a value of FAIL. The return value is OK on success.
2767 * If OK is returned and len_change is not NULL, *len_change
2768 * is set to the change in the buffer length.
2771 InsertBufferLines(buf_T
*buf
, PyInt n
, PyObject
*lines
, PyInt
*len_change
)
2773 /* First of all, we check the type of the supplied Python object.
2774 * It must be a string or a list, or the call is in error.
2776 if (PyString_Check(lines
))
2778 char *str
= StringToLine(lines
);
2789 if (u_save((linenr_T
)n
, (linenr_T
)(n
+1)) == FAIL
)
2790 PyErr_SetVim(_("cannot save undo information"));
2791 else if (ml_append((linenr_T
)n
, (char_u
*)str
, 0, FALSE
) == FAIL
)
2792 PyErr_SetVim(_("cannot insert line"));
2794 appended_lines_mark((linenr_T
)n
, 1L);
2798 update_screen(VALID
);
2800 if (PyErr_Occurred() || VimErrorCheck())
2808 else if (PyList_Check(lines
))
2811 PyInt size
= PyList_Size(lines
);
2815 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2822 for (i
= 0; i
< size
; ++i
)
2824 PyObject
*line
= PyList_GetItem(lines
, i
);
2825 array
[i
] = StringToLine(line
);
2827 if (array
[i
] == NULL
)
2830 vim_free(array
[--i
]);
2841 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2842 PyErr_SetVim(_("cannot save undo information"));
2845 for (i
= 0; i
< size
; ++i
)
2847 if (ml_append((linenr_T
)(n
+ i
),
2848 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2850 PyErr_SetVim(_("cannot insert line"));
2852 /* Free the rest of the lines */
2854 vim_free(array
[i
++]);
2861 appended_lines_mark((linenr_T
)n
, (long)i
);
2864 /* Free the array of lines. All of its contents have now
2870 update_screen(VALID
);
2872 if (PyErr_Occurred() || VimErrorCheck())
2882 PyErr_BadArgument();
2887 /* Convert a Vim line into a Python string.
2888 * All internal newlines are replaced by null characters.
2890 * On errors, the Python exception data is set, and NULL is returned.
2893 LineToString(const char *str
)
2896 PyInt len
= strlen(str
);
2899 /* Allocate an Python string object, with uninitialised contents. We
2900 * must do it this way, so that we can modify the string in place
2901 * later. See the Python source, Objects/stringobject.c for details.
2903 result
= PyString_FromStringAndSize(NULL
, len
);
2907 p
= PyString_AsString(result
);
2923 /* Convert a Python string into a Vim line.
2925 * The result is in allocated memory. All internal nulls are replaced by
2926 * newline characters. It is an error for the string to contain newline
2929 * On errors, the Python exception data is set, and NULL is returned.
2932 StringToLine(PyObject
*obj
)
2940 if (obj
== NULL
|| !PyString_Check(obj
))
2942 PyErr_BadArgument();
2946 str
= PyString_AsString(obj
);
2947 len
= PyString_Size(obj
);
2950 * Error checking: String must not contain newlines, as we
2951 * are replacing a single line, and we must replace it with
2953 * A trailing newline is removed, so that append(f.readlines()) works.
2955 p
= memchr(str
, '\n', len
);
2958 if (p
== str
+ len
- 1)
2962 PyErr_SetVim(_("string cannot contain newlines"));
2967 /* Create a copy of the string, with internal nulls replaced by
2968 * newline characters, as is the vim convention.
2970 save
= (char *)alloc((unsigned)(len
+1));
2977 for (i
= 0; i
< len
; ++i
)
2990 /* Check to see whether a Vim error has been reported, or a keyboard
2991 * interrupt has been detected.
2998 PyErr_SetNone(PyExc_KeyboardInterrupt
);
3001 else if (did_emsg
&& !PyErr_Occurred())
3003 PyErr_SetNone(VimError
);
3011 /* Don't generate a prototype for the next function, it generates an error on
3012 * newer Python versions. */
3013 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3016 Py_GetProgramName(void)
3020 #endif /* Python 1.4 */