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
44 #if defined(MACOS) && !defined(MACOS_X_UNIX)
46 # include <CodeFragments.h>
48 #undef main /* Defined in python.h - aargh */
49 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
51 #if !defined(FEAT_PYTHON) && defined(PROTO)
52 /* Use this to be able to generate prototypes without python being used. */
53 # define PyObject Py_ssize_t
54 # define PyThreadState Py_ssize_t
55 # define PyTypeObject Py_ssize_t
56 struct PyMethodDef
{ Py_ssize_t a
; };
57 # define PySequenceMethods Py_ssize_t
60 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
61 # define PyInt Py_ssize_t
62 # define PyInquiry lenfunc
63 # define PyIntArgFunc ssizeargfunc
64 # define PyIntIntArgFunc ssizessizeargfunc
65 # define PyIntObjArgProc ssizeobjargproc
66 # define PyIntIntObjArgProc ssizessizeobjargproc
67 # define Py_ssize_t_fmt "n"
70 # define PyInquiry inquiry
71 # define PyIntArgFunc intargfunc
72 # define PyIntIntArgFunc intintargfunc
73 # define PyIntObjArgProc intobjargproc
74 # define PyIntIntObjArgProc intintobjargproc
75 # define Py_ssize_t_fmt "i"
79 #define single_input 256
80 #define file_input 257
81 #define eval_input 258
83 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
84 /* Python 2.3: can invoke ":python" recursively. */
85 # define PY_CAN_RECURSE
88 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
89 # ifndef DYNAMIC_PYTHON
90 # define HINSTANCE long_u /* for generating prototypes */
93 # if defined(MACOS_X_UNIX)
94 typedef void * HINSTANCE
;
95 typedef void * FARPROC
;
97 # define LoadLibrary(a) dlopen(a,RTLD_NOW|RTLD_LOCAL)
98 # define FreeLibrary(a) dlclose(a)
99 # define GetProcAddress dlsym
102 /* This makes if_python.c compile without warnings against Python 2.5
103 * on Win32 and Win64. */
104 #undef PyRun_SimpleString
106 #undef PyArg_ParseTuple
108 #undef Py_InitModule4
109 #undef Py_InitModule4_64
114 # define PyArg_Parse dll_PyArg_Parse
115 # define PyArg_ParseTuple dll_PyArg_ParseTuple
116 # define PyDict_SetItemString dll_PyDict_SetItemString
117 # define PyErr_BadArgument dll_PyErr_BadArgument
118 # define PyErr_Clear dll_PyErr_Clear
119 # define PyErr_NoMemory dll_PyErr_NoMemory
120 # define PyErr_Occurred dll_PyErr_Occurred
121 # define PyErr_SetNone dll_PyErr_SetNone
122 # define PyErr_SetString dll_PyErr_SetString
123 # define PyEval_InitThreads dll_PyEval_InitThreads
124 # define PyEval_RestoreThread dll_PyEval_RestoreThread
125 # define PyEval_SaveThread dll_PyEval_SaveThread
126 # ifdef PY_CAN_RECURSE
127 # define PyGILState_Ensure dll_PyGILState_Ensure
128 # define PyGILState_Release dll_PyGILState_Release
130 # define PyInt_AsLong dll_PyInt_AsLong
131 # define PyInt_FromLong dll_PyInt_FromLong
132 # define PyInt_Type (*dll_PyInt_Type)
133 # define PyList_GetItem dll_PyList_GetItem
134 # define PyList_Append dll_PyList_Append
135 # define PyList_New dll_PyList_New
136 # define PyList_SetItem dll_PyList_SetItem
137 # define PyList_Size dll_PyList_Size
138 # define PyList_Type (*dll_PyList_Type)
139 # define PyImport_ImportModule dll_PyImport_ImportModule
140 # define PyDict_New dll_PyDict_New
141 # define PyDict_GetItemString dll_PyDict_GetItemString
142 # define PyModule_GetDict dll_PyModule_GetDict
143 # define PyRun_SimpleString dll_PyRun_SimpleString
144 # define PyString_AsString dll_PyString_AsString
145 # define PyString_FromString dll_PyString_FromString
146 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
147 # define PyString_Size dll_PyString_Size
148 # define PyString_Type (*dll_PyString_Type)
149 # define PySys_SetObject dll_PySys_SetObject
150 # define PySys_SetArgv dll_PySys_SetArgv
151 # define PyType_Type (*dll_PyType_Type)
152 # define Py_BuildValue dll_Py_BuildValue
153 # define Py_FindMethod dll_Py_FindMethod
154 # define Py_InitModule4 dll_Py_InitModule4
155 # define Py_Initialize dll_Py_Initialize
156 # define Py_Finalize dll_Py_Finalize
157 # define Py_IsInitialized dll_Py_IsInitialized
158 # define _PyObject_New dll__PyObject_New
159 # define _Py_NoneStruct (*dll__Py_NoneStruct)
160 # define PyObject_Init dll__PyObject_Init
161 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
162 # define PyType_IsSubtype dll_PyType_IsSubtype
164 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
165 # define PyObject_Malloc dll_PyObject_Malloc
166 # define PyObject_Free dll_PyObject_Free
170 * Pointers for dynamic link
172 static int(*dll_PyArg_Parse
)(PyObject
*, char *, ...);
173 static int(*dll_PyArg_ParseTuple
)(PyObject
*, char *, ...);
174 static int(*dll_PyDict_SetItemString
)(PyObject
*dp
, char *key
, PyObject
*item
);
175 static int(*dll_PyErr_BadArgument
)(void);
176 static void(*dll_PyErr_Clear
)(void);
177 static PyObject
*(*dll_PyErr_NoMemory
)(void);
178 static PyObject
*(*dll_PyErr_Occurred
)(void);
179 static void(*dll_PyErr_SetNone
)(PyObject
*);
180 static void(*dll_PyErr_SetString
)(PyObject
*, const char *);
181 static void(*dll_PyEval_InitThreads
)(void);
182 static void(*dll_PyEval_RestoreThread
)(PyThreadState
*);
183 static PyThreadState
*(*dll_PyEval_SaveThread
)(void);
184 # ifdef PY_CAN_RECURSE
185 static PyGILState_STATE (*dll_PyGILState_Ensure
)(void);
186 static void (*dll_PyGILState_Release
)(PyGILState_STATE
);
188 static long(*dll_PyInt_AsLong
)(PyObject
*);
189 static PyObject
*(*dll_PyInt_FromLong
)(long);
190 static PyTypeObject
* dll_PyInt_Type
;
191 static PyObject
*(*dll_PyList_GetItem
)(PyObject
*, PyInt
);
192 static PyObject
*(*dll_PyList_Append
)(PyObject
*, PyObject
*);
193 static PyObject
*(*dll_PyList_New
)(PyInt size
);
194 static int(*dll_PyList_SetItem
)(PyObject
*, PyInt
, PyObject
*);
195 static PyInt(*dll_PyList_Size
)(PyObject
*);
196 static PyTypeObject
* dll_PyList_Type
;
197 static PyObject
*(*dll_PyImport_ImportModule
)(const char *);
198 static PyObject
*(*dll_PyDict_New
)(void);
199 static PyObject
*(*dll_PyDict_GetItemString
)(PyObject
*, const char *);
200 static PyObject
*(*dll_PyModule_GetDict
)(PyObject
*);
201 static int(*dll_PyRun_SimpleString
)(char *);
202 static char*(*dll_PyString_AsString
)(PyObject
*);
203 static PyObject
*(*dll_PyString_FromString
)(const char *);
204 static PyObject
*(*dll_PyString_FromStringAndSize
)(const char *, PyInt
);
205 static PyInt(*dll_PyString_Size
)(PyObject
*);
206 static PyTypeObject
* dll_PyString_Type
;
207 static int(*dll_PySys_SetObject
)(char *, PyObject
*);
208 static int(*dll_PySys_SetArgv
)(int, char **);
209 static PyTypeObject
* dll_PyType_Type
;
210 static PyObject
*(*dll_Py_BuildValue
)(char *, ...);
211 static PyObject
*(*dll_Py_FindMethod
)(struct PyMethodDef
[], PyObject
*, char *);
212 static PyObject
*(*dll_Py_InitModule4
)(char *, struct PyMethodDef
*, char *, PyObject
*, int);
213 static void(*dll_Py_Initialize
)(void);
214 static void(*dll_Py_Finalize
)(void);
215 static int(*dll_Py_IsInitialized
)(void);
216 static PyObject
*(*dll__PyObject_New
)(PyTypeObject
*, PyObject
*);
217 static PyObject
*(*dll__PyObject_Init
)(PyObject
*, PyTypeObject
*);
218 static PyObject
* dll__Py_NoneStruct
;
219 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
220 static int (*dll_PyType_IsSubtype
)(PyTypeObject
*, PyTypeObject
*);
222 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
223 static void* (*dll_PyObject_Malloc
)(size_t);
224 static void (*dll_PyObject_Free
)(void*);
227 static HINSTANCE hinstPython
= 0; /* Instance of python.dll */
229 /* Imported exception objects */
230 static PyObject
*imp_PyExc_AttributeError
;
231 static PyObject
*imp_PyExc_IndexError
;
232 static PyObject
*imp_PyExc_KeyboardInterrupt
;
233 static PyObject
*imp_PyExc_TypeError
;
234 static PyObject
*imp_PyExc_ValueError
;
236 # define PyExc_AttributeError imp_PyExc_AttributeError
237 # define PyExc_IndexError imp_PyExc_IndexError
238 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
239 # define PyExc_TypeError imp_PyExc_TypeError
240 # define PyExc_ValueError imp_PyExc_ValueError
243 * Table of name to function pointer of python.
245 # define PYTHON_PROC FARPROC
250 } python_funcname_table
[] =
252 {"PyArg_Parse", (PYTHON_PROC
*)&dll_PyArg_Parse
},
253 {"PyArg_ParseTuple", (PYTHON_PROC
*)&dll_PyArg_ParseTuple
},
254 {"PyDict_SetItemString", (PYTHON_PROC
*)&dll_PyDict_SetItemString
},
255 {"PyErr_BadArgument", (PYTHON_PROC
*)&dll_PyErr_BadArgument
},
256 {"PyErr_Clear", (PYTHON_PROC
*)&dll_PyErr_Clear
},
257 {"PyErr_NoMemory", (PYTHON_PROC
*)&dll_PyErr_NoMemory
},
258 {"PyErr_Occurred", (PYTHON_PROC
*)&dll_PyErr_Occurred
},
259 {"PyErr_SetNone", (PYTHON_PROC
*)&dll_PyErr_SetNone
},
260 {"PyErr_SetString", (PYTHON_PROC
*)&dll_PyErr_SetString
},
261 {"PyEval_InitThreads", (PYTHON_PROC
*)&dll_PyEval_InitThreads
},
262 {"PyEval_RestoreThread", (PYTHON_PROC
*)&dll_PyEval_RestoreThread
},
263 {"PyEval_SaveThread", (PYTHON_PROC
*)&dll_PyEval_SaveThread
},
264 # ifdef PY_CAN_RECURSE
265 {"PyGILState_Ensure", (PYTHON_PROC
*)&dll_PyGILState_Ensure
},
266 {"PyGILState_Release", (PYTHON_PROC
*)&dll_PyGILState_Release
},
268 {"PyInt_AsLong", (PYTHON_PROC
*)&dll_PyInt_AsLong
},
269 {"PyInt_FromLong", (PYTHON_PROC
*)&dll_PyInt_FromLong
},
270 {"PyInt_Type", (PYTHON_PROC
*)&dll_PyInt_Type
},
271 {"PyList_GetItem", (PYTHON_PROC
*)&dll_PyList_GetItem
},
272 {"PyList_Append", (PYTHON_PROC
*)&dll_PyList_Append
},
273 {"PyList_New", (PYTHON_PROC
*)&dll_PyList_New
},
274 {"PyList_SetItem", (PYTHON_PROC
*)&dll_PyList_SetItem
},
275 {"PyList_Size", (PYTHON_PROC
*)&dll_PyList_Size
},
276 {"PyList_Type", (PYTHON_PROC
*)&dll_PyList_Type
},
277 {"PyImport_ImportModule", (PYTHON_PROC
*)&dll_PyImport_ImportModule
},
278 {"PyDict_GetItemString", (PYTHON_PROC
*)&dll_PyDict_GetItemString
},
279 {"PyDict_New", (PYTHON_PROC
*)&dll_PyDict_New
},
280 {"PyModule_GetDict", (PYTHON_PROC
*)&dll_PyModule_GetDict
},
281 {"PyRun_SimpleString", (PYTHON_PROC
*)&dll_PyRun_SimpleString
},
282 {"PyString_AsString", (PYTHON_PROC
*)&dll_PyString_AsString
},
283 {"PyString_FromString", (PYTHON_PROC
*)&dll_PyString_FromString
},
284 {"PyString_FromStringAndSize", (PYTHON_PROC
*)&dll_PyString_FromStringAndSize
},
285 {"PyString_Size", (PYTHON_PROC
*)&dll_PyString_Size
},
286 {"PyString_Type", (PYTHON_PROC
*)&dll_PyString_Type
},
287 {"PySys_SetObject", (PYTHON_PROC
*)&dll_PySys_SetObject
},
288 {"PySys_SetArgv", (PYTHON_PROC
*)&dll_PySys_SetArgv
},
289 {"PyType_Type", (PYTHON_PROC
*)&dll_PyType_Type
},
290 {"Py_BuildValue", (PYTHON_PROC
*)&dll_Py_BuildValue
},
291 {"Py_FindMethod", (PYTHON_PROC
*)&dll_Py_FindMethod
},
292 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
293 {"Py_InitModule4_64", (PYTHON_PROC
*)&dll_Py_InitModule4
},
295 {"Py_InitModule4", (PYTHON_PROC
*)&dll_Py_InitModule4
},
297 {"Py_Initialize", (PYTHON_PROC
*)&dll_Py_Initialize
},
298 {"Py_Finalize", (PYTHON_PROC
*)&dll_Py_Finalize
},
299 {"Py_IsInitialized", (PYTHON_PROC
*)&dll_Py_IsInitialized
},
300 {"_PyObject_New", (PYTHON_PROC
*)&dll__PyObject_New
},
301 {"PyObject_Init", (PYTHON_PROC
*)&dll__PyObject_Init
},
302 {"_Py_NoneStruct", (PYTHON_PROC
*)&dll__Py_NoneStruct
},
303 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
304 {"PyType_IsSubtype", (PYTHON_PROC
*)&dll_PyType_IsSubtype
},
306 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
307 {"PyObject_Malloc", (PYTHON_PROC
*)&dll_PyObject_Malloc
},
308 {"PyObject_Free", (PYTHON_PROC
*)&dll_PyObject_Free
},
317 end_dynamic_python(void)
321 FreeLibrary(hinstPython
);
327 * Load library and get all pointers.
328 * Parameter 'libname' provides name of DLL.
332 python_runtime_link_init(char *libname
, int verbose
)
338 hinstPython
= LoadLibrary(libname
);
342 EMSG2(_(e_loadlib
), libname
);
346 for (i
= 0; python_funcname_table
[i
].ptr
; ++i
)
348 if ((*python_funcname_table
[i
].ptr
= GetProcAddress(hinstPython
,
349 python_funcname_table
[i
].name
)) == NULL
)
351 FreeLibrary(hinstPython
);
354 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
362 * If python is enabled (there is installed python on Windows system) return
366 python_enabled(int verbose
)
368 #if defined(MACOS_X_UNIX)
370 int mustfree
= FALSE
;
371 char_u
*s
= vim_getenv("PYTHON_DLL", &mustfree
);
373 ret
= python_runtime_link_init(s
, verbose
) == OK
;
377 ret
= python_runtime_link_init(
378 "/System/Library/Frameworks/Python.framework/Versions/Current/Python",
383 return python_runtime_link_init(DYNAMIC_PYTHON_DLL
, verbose
) == OK
;
387 /* Load the standard Python exceptions - don't import the symbols from the
388 * DLL, as this can cause errors (importing data symbols is not reliable).
390 static void get_exceptions
__ARGS((void));
395 PyObject
*exmod
= PyImport_ImportModule("exceptions");
396 PyObject
*exdict
= PyModule_GetDict(exmod
);
397 imp_PyExc_AttributeError
= PyDict_GetItemString(exdict
, "AttributeError");
398 imp_PyExc_IndexError
= PyDict_GetItemString(exdict
, "IndexError");
399 imp_PyExc_KeyboardInterrupt
= PyDict_GetItemString(exdict
, "KeyboardInterrupt");
400 imp_PyExc_TypeError
= PyDict_GetItemString(exdict
, "TypeError");
401 imp_PyExc_ValueError
= PyDict_GetItemString(exdict
, "ValueError");
402 Py_XINCREF(imp_PyExc_AttributeError
);
403 Py_XINCREF(imp_PyExc_IndexError
);
404 Py_XINCREF(imp_PyExc_KeyboardInterrupt
);
405 Py_XINCREF(imp_PyExc_TypeError
);
406 Py_XINCREF(imp_PyExc_ValueError
);
409 #endif /* DYNAMIC_PYTHON */
411 /******************************************************
412 * Internal function prototypes.
415 static void DoPythonCommand(exarg_T
*, const char *);
416 static PyInt RangeStart
;
417 static PyInt RangeEnd
;
419 static void PythonIO_Flush(void);
420 static int PythonIO_Init(void);
421 static int PythonMod_Init(void);
423 /* Utility functions for the vim/python interface
424 * ----------------------------------------------
426 static PyObject
*GetBufferLine(buf_T
*, PyInt
);
427 static PyObject
*GetBufferLineList(buf_T
*, PyInt
, PyInt
);
429 static int SetBufferLine(buf_T
*, PyInt
, PyObject
*, PyInt
*);
430 static int SetBufferLineList(buf_T
*, PyInt
, PyInt
, PyObject
*, PyInt
*);
431 static int InsertBufferLines(buf_T
*, PyInt
, PyObject
*, PyInt
*);
433 static PyObject
*LineToString(const char *);
434 static char *StringToLine(PyObject
*);
436 static int VimErrorCheck(void);
438 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
440 /******************************************************
441 * 1. Python interpreter main program.
444 static int initialised
= 0;
446 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
447 typedef PyObject PyThreadState
;
450 #ifdef PY_CAN_RECURSE
451 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
453 static PyThreadState
*saved_python_thread
= NULL
;
457 * Suspend a thread of the Python interpreter, other threads are allowed to
461 Python_SaveThread(void)
463 #ifdef PY_CAN_RECURSE
464 PyGILState_Release(pygilstate
);
466 saved_python_thread
= PyEval_SaveThread();
471 * Restore a thread of the Python interpreter, waits for other threads to
475 Python_RestoreThread(void)
477 #ifdef PY_CAN_RECURSE
478 pygilstate
= PyGILState_Ensure();
480 PyEval_RestoreThread(saved_python_thread
);
481 saved_python_thread
= NULL
;
486 * obtain a lock on the Vim data structures
488 static void Python_Lock_Vim(void)
493 * release a lock on the Vim data structures
495 static void Python_Release_Vim(void)
502 static int recurse
= 0;
504 /* If a crash occurs while doing this, don't try again. */
510 #ifdef DYNAMIC_PYTHON
511 if (hinstPython
&& Py_IsInitialized())
513 Python_RestoreThread(); /* enter python */
516 end_dynamic_python();
518 if (Py_IsInitialized())
520 Python_RestoreThread(); /* enter python */
533 #ifdef DYNAMIC_PYTHON
534 if (!python_enabled(TRUE
))
536 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
541 #if !defined(MACOS) || defined(MACOS_X_UNIX)
546 /* initialise threads */
547 PyEval_InitThreads();
549 #ifdef DYNAMIC_PYTHON
556 if (PythonMod_Init())
559 /* Remove the element from sys.path that was added because of our
560 * argv[0] value in PythonMod_Init(). Previously we used an empty
561 * string, but dependinding on the OS we then get an empty entry or
562 * the current directory in sys.path. */
563 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
565 /* the first python thread is vim's, release the lock */
574 /* We call PythonIO_Flush() here to print any Python errors.
575 * This is OK, as it is possible to call this function even
576 * if PythonIO_Init() has not completed successfully (it will
577 * not do anything in this case).
587 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
589 #ifndef PY_CAN_RECURSE
590 static int recursive
= 0;
592 #if defined(MACOS) && !defined(MACOS_X_UNIX)
595 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
599 #ifndef PY_CAN_RECURSE
602 EMSG(_("E659: Cannot invoke Python recursively"));
608 #if defined(MACOS) && !defined(MACOS_X_UNIX)
610 /* Check if the Python library is available */
611 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
617 RangeStart
= eap
->line1
;
618 RangeEnd
= eap
->line2
;
619 Python_Release_Vim(); /* leave vim */
621 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
622 /* Python only works properly when the LC_NUMERIC locale is "C". */
623 saved_locale
= setlocale(LC_NUMERIC
, NULL
);
624 if (saved_locale
== NULL
|| STRCMP(saved_locale
, "C") == 0)
628 /* Need to make a copy, value may change when setting new locale. */
629 saved_locale
= (char *)vim_strsave((char_u
*)saved_locale
);
630 (void)setlocale(LC_NUMERIC
, "C");
634 Python_RestoreThread(); /* enter python */
636 PyRun_SimpleString((char *)(cmd
));
638 Python_SaveThread(); /* leave python */
640 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
641 if (saved_locale
!= NULL
)
643 (void)setlocale(LC_NUMERIC
, saved_locale
);
644 vim_free(saved_locale
);
648 Python_Lock_Vim(); /* enter vim */
650 #if defined(MACOS) && !defined(MACOS_X_UNIX)
655 #ifndef PY_CAN_RECURSE
658 return; /* keeps lint happy */
665 ex_python(exarg_T
*eap
)
669 script
= script_get(eap
, eap
->arg
);
673 DoPythonCommand(eap
, (char *)eap
->arg
);
675 DoPythonCommand(eap
, (char *)script
);
680 #define BUFFER_SIZE 1024
686 ex_pyfile(exarg_T
*eap
)
688 static char buffer
[BUFFER_SIZE
];
689 const char *file
= (char *)eap
->arg
;
692 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
693 * stdio file pointer, but Vim and the Python DLL are compiled with
694 * different options under Windows, meaning that stdio pointers aren't
695 * compatible between the two. Yuk.
697 * Put the string "execfile('file')" into buffer. But, we need to
698 * escape any backslashes or single quotes in the file name, so that
699 * Python won't mangle the file name.
701 strcpy(buffer
, "execfile('");
702 p
= buffer
+ 10; /* size of "execfile('" */
704 while (*file
&& p
< buffer
+ (BUFFER_SIZE
- 3))
706 if (*file
== '\\' || *file
== '\'')
711 /* If we didn't finish the file name, we hit a buffer overflow */
715 /* Put in the terminating "')" and a null */
720 /* Execute the file */
721 DoPythonCommand(eap
, buffer
);
724 /******************************************************
725 * 2. Python output stream: writes output via [e]msg().
728 /* Implementation functions
731 static PyObject
*OutputGetattr(PyObject
*, char *);
732 static int OutputSetattr(PyObject
*, char *, PyObject
*);
734 static PyObject
*OutputWrite(PyObject
*, PyObject
*);
735 static PyObject
*OutputWritelines(PyObject
*, PyObject
*);
737 typedef void (*writefn
)(char_u
*);
738 static void writer(writefn fn
, char_u
*str
, PyInt n
);
740 /* Output object definition
750 static struct PyMethodDef OutputMethods
[] = {
751 /* name, function, calling, documentation */
752 {"write", OutputWrite
, 1, "" },
753 {"writelines", OutputWritelines
, 1, "" },
754 { NULL
, NULL
, 0, NULL
}
757 static PyTypeObject OutputType
= {
758 PyObject_HEAD_INIT(0)
761 sizeof(OutputObject
),
766 (getattrfunc
) OutputGetattr
,
767 (setattrfunc
) OutputSetattr
,
783 OutputGetattr(PyObject
*self
, char *name
)
785 if (strcmp(name
, "softspace") == 0)
786 return PyInt_FromLong(((OutputObject
*)(self
))->softspace
);
788 return Py_FindMethod(OutputMethods
, self
, name
);
792 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
795 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
799 if (strcmp(name
, "softspace") == 0)
801 if (!PyInt_Check(val
)) {
802 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
806 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
810 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
817 OutputWrite(PyObject
*self
, PyObject
*args
)
821 int error
= ((OutputObject
*)(self
))->error
;
823 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
826 Py_BEGIN_ALLOW_THREADS
828 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
829 Python_Release_Vim();
837 OutputWritelines(PyObject
*self
, PyObject
*args
)
842 int error
= ((OutputObject
*)(self
))->error
;
844 if (!PyArg_ParseTuple(args
, "O", &list
))
848 if (!PyList_Check(list
)) {
849 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
854 n
= PyList_Size(list
);
856 for (i
= 0; i
< n
; ++i
)
858 PyObject
*line
= PyList_GetItem(list
, i
);
862 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
863 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
868 Py_BEGIN_ALLOW_THREADS
870 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
871 Python_Release_Vim();
880 /* Output buffer management
883 static char_u
*buffer
= NULL
;
884 static PyInt buffer_len
= 0;
885 static PyInt buffer_size
= 0;
887 static writefn old_fn
= NULL
;
890 buffer_ensure(PyInt n
)
898 new_size
= buffer_size
;
902 if (new_size
!= buffer_size
)
904 new_buffer
= alloc((unsigned)new_size
);
905 if (new_buffer
== NULL
)
910 memcpy(new_buffer
, buffer
, buffer_len
);
915 buffer_size
= new_size
;
922 if (old_fn
&& buffer_len
)
924 buffer
[buffer_len
] = 0;
932 writer(writefn fn
, char_u
*str
, PyInt n
)
936 if (fn
!= old_fn
&& old_fn
!= NULL
)
941 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
943 PyInt len
= ptr
- str
;
945 buffer_ensure(buffer_len
+ len
+ 1);
947 memcpy(buffer
+ buffer_len
, str
, len
);
949 buffer
[buffer_len
] = 0;
956 /* Put the remaining text into the buffer for later printing */
957 buffer_ensure(buffer_len
+ n
+ 1);
958 memcpy(buffer
+ buffer_len
, str
, n
);
964 static OutputObject Output
=
966 PyObject_HEAD_INIT(&OutputType
)
971 static OutputObject Error
=
973 PyObject_HEAD_INIT(&OutputType
)
982 OutputType
.ob_type
= &PyType_Type
;
984 PySys_SetObject("stdout", (PyObject
*)(void *)&Output
);
985 PySys_SetObject("stderr", (PyObject
*)(void *)&Error
);
987 if (PyErr_Occurred())
989 EMSG(_("E264: Python: Error initialising I/O objects"));
996 /******************************************************
997 * 3. Implementation of the Vim module for Python
1000 /* Vim module - Implementation functions
1001 * -------------------------------------
1004 static PyObject
*VimError
;
1006 static PyObject
*VimCommand(PyObject
*, PyObject
*);
1007 static PyObject
*VimEval(PyObject
*, PyObject
*);
1009 /* Window type - Implementation functions
1010 * --------------------------------------
1020 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1022 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1024 static PyObject
*WindowNew(win_T
*);
1026 static void WindowDestructor(PyObject
*);
1027 static PyObject
*WindowGetattr(PyObject
*, char *);
1028 static int WindowSetattr(PyObject
*, char *, PyObject
*);
1029 static PyObject
*WindowRepr(PyObject
*);
1031 /* Buffer type - Implementation functions
1032 * --------------------------------------
1042 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1044 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1046 static PyObject
*BufferNew (buf_T
*);
1048 static void BufferDestructor(PyObject
*);
1049 static PyObject
*BufferGetattr(PyObject
*, char *);
1050 static PyObject
*BufferRepr(PyObject
*);
1052 static PyInt
BufferLength(PyObject
*);
1053 static PyObject
*BufferItem(PyObject
*, PyInt
);
1054 static PyObject
*BufferSlice(PyObject
*, PyInt
, PyInt
);
1055 static PyInt
BufferAssItem(PyObject
*, PyInt
, PyObject
*);
1056 static PyInt
BufferAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1058 static PyObject
*BufferAppend(PyObject
*, PyObject
*);
1059 static PyObject
*BufferMark(PyObject
*, PyObject
*);
1060 static PyObject
*BufferRange(PyObject
*, PyObject
*);
1062 /* Line range type - Implementation functions
1063 * --------------------------------------
1075 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1077 static PyObject
*RangeNew(buf_T
*, PyInt
, PyInt
);
1079 static void RangeDestructor(PyObject
*);
1080 static PyObject
*RangeGetattr(PyObject
*, char *);
1081 static PyObject
*RangeRepr(PyObject
*);
1083 static PyInt
RangeLength(PyObject
*);
1084 static PyObject
*RangeItem(PyObject
*, PyInt
);
1085 static PyObject
*RangeSlice(PyObject
*, PyInt
, PyInt
);
1086 static PyInt
RangeAssItem(PyObject
*, PyInt
, PyObject
*);
1087 static PyInt
RangeAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1089 static PyObject
*RangeAppend(PyObject
*, PyObject
*);
1091 /* Window list type - Implementation functions
1092 * -------------------------------------------
1095 static PyInt
WinListLength(PyObject
*);
1096 static PyObject
*WinListItem(PyObject
*, PyInt
);
1098 /* Buffer list type - Implementation functions
1099 * -------------------------------------------
1102 static PyInt
BufListLength(PyObject
*);
1103 static PyObject
*BufListItem(PyObject
*, PyInt
);
1105 /* Current objects type - Implementation functions
1106 * -----------------------------------------------
1109 static PyObject
*CurrentGetattr(PyObject
*, char *);
1110 static int CurrentSetattr(PyObject
*, char *, PyObject
*);
1112 /* Vim module - Definitions
1115 static struct PyMethodDef VimMethods
[] = {
1116 /* name, function, calling, documentation */
1117 {"command", VimCommand
, 1, "Execute a Vim ex-mode command" },
1118 {"eval", VimEval
, 1, "Evaluate an expression using Vim evaluator" },
1119 { NULL
, NULL
, 0, NULL
}
1122 /* Vim module - Implementation
1126 VimCommand(PyObject
*self
, PyObject
*args
)
1131 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1136 Py_BEGIN_ALLOW_THREADS
1139 do_cmdline_cmd((char_u
*)cmd
);
1140 update_screen(VALID
);
1142 Python_Release_Vim();
1143 Py_END_ALLOW_THREADS
1145 if (VimErrorCheck())
1156 * Function to translate a typval_T into a PyObject; this will recursively
1157 * translate lists/dictionaries into their Python equivalents.
1159 * The depth parameter is to avoid infinite recursion, set it to 1 when
1160 * you call VimToPython.
1163 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1167 char ptrBuf
[NUMBUFLEN
];
1169 /* Avoid infinite recursion */
1177 /* Check if we run into a recursive loop. The item must be in lookupDict
1178 * then and we can use it again. */
1179 if ((our_tv
->v_type
== VAR_LIST
&& our_tv
->vval
.v_list
!= NULL
)
1180 || (our_tv
->v_type
== VAR_DICT
&& our_tv
->vval
.v_dict
!= NULL
))
1182 sprintf(ptrBuf
, PRINTF_DECIMAL_LONG_U
,
1183 our_tv
->v_type
== VAR_LIST
? (long_u
)our_tv
->vval
.v_list
1184 : (long_u
)our_tv
->vval
.v_dict
);
1185 result
= PyDict_GetItemString(lookupDict
, ptrBuf
);
1193 if (our_tv
->v_type
== VAR_STRING
)
1195 result
= Py_BuildValue("s", our_tv
->vval
.v_string
);
1197 else if (our_tv
->v_type
== VAR_NUMBER
)
1199 char buf
[NUMBUFLEN
];
1201 /* For backwards compatibility numbers are stored as strings. */
1202 sprintf(buf
, "%ld", (long)our_tv
->vval
.v_number
);
1203 result
= Py_BuildValue("s", buf
);
1206 else if (our_tv
->v_type
== VAR_FLOAT
)
1208 char buf
[NUMBUFLEN
];
1210 sprintf(buf
, "%f", our_tv
->vval
.v_float
);
1211 result
= Py_BuildValue("s", buf
);
1214 else if (our_tv
->v_type
== VAR_LIST
)
1216 list_T
*list
= our_tv
->vval
.v_list
;
1219 result
= PyList_New(0);
1223 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1225 for (curr
= list
->lv_first
; curr
!= NULL
; curr
= curr
->li_next
)
1227 newObj
= VimToPython(&curr
->li_tv
, depth
+ 1, lookupDict
);
1228 PyList_Append(result
, newObj
);
1233 else if (our_tv
->v_type
== VAR_DICT
)
1235 result
= PyDict_New();
1237 if (our_tv
->vval
.v_dict
!= NULL
)
1239 hashtab_T
*ht
= &our_tv
->vval
.v_dict
->dv_hashtab
;
1240 long_u todo
= ht
->ht_used
;
1244 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1246 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1248 if (!HASHITEM_EMPTY(hi
))
1252 di
= dict_lookup(hi
);
1253 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1254 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1272 VimEval(PyObject
*self
, PyObject
*args
)
1278 PyObject
*lookup_dict
;
1280 if (!PyArg_ParseTuple(args
, "s", &expr
))
1283 Py_BEGIN_ALLOW_THREADS
1285 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1287 Python_Release_Vim();
1288 Py_END_ALLOW_THREADS
1292 PyErr_SetVim(_("invalid expression"));
1296 /* Convert the Vim type into a Python type. Create a dictionary that's
1297 * used to check for recursive loops. */
1298 lookup_dict
= PyDict_New();
1299 result
= VimToPython(our_tv
, 1, lookup_dict
);
1300 Py_DECREF(lookup_dict
);
1303 Py_BEGIN_ALLOW_THREADS
1306 Python_Release_Vim();
1307 Py_END_ALLOW_THREADS
1311 PyErr_SetVim(_("expressions disabled at compile time"));
1316 /* Common routines for buffers and line ranges
1317 * -------------------------------------------
1320 CheckBuffer(BufferObject
*this)
1322 if (this->buf
== INVALID_BUFFER_VALUE
)
1324 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1332 RBItem(BufferObject
*self
, PyInt n
, PyInt start
, PyInt end
)
1334 if (CheckBuffer(self
))
1337 if (n
< 0 || n
> end
- start
)
1339 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1343 return GetBufferLine(self
->buf
, n
+start
);
1347 RBSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyInt start
, PyInt end
)
1351 if (CheckBuffer(self
))
1354 size
= end
- start
+ 1;
1367 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1371 RBAssItem(BufferObject
*self
, PyInt n
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1375 if (CheckBuffer(self
))
1378 if (n
< 0 || n
> end
- start
)
1380 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1384 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1388 *new_end
= end
+ len_change
;
1394 RBAssSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1399 /* Self must be a valid buffer */
1400 if (CheckBuffer(self
))
1403 /* Sort out the slice range */
1404 size
= end
- start
+ 1;
1417 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1421 *new_end
= end
+ len_change
;
1427 RBAppend(BufferObject
*self
, PyObject
*args
, PyInt start
, PyInt end
, PyInt
*new_end
)
1434 if (CheckBuffer(self
))
1437 max
= n
= end
- start
+ 1;
1439 if (!PyArg_ParseTuple(args
, "O|" Py_ssize_t_fmt
, &lines
, &n
))
1442 if (n
< 0 || n
> max
)
1444 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1448 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1452 *new_end
= end
+ len_change
;
1459 /* Buffer object - Definitions
1462 static struct PyMethodDef BufferMethods
[] = {
1463 /* name, function, calling, documentation */
1464 {"append", BufferAppend
, 1, "Append data to Vim buffer" },
1465 {"mark", BufferMark
, 1, "Return (row,col) representing position of named mark" },
1466 {"range", BufferRange
, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1467 { NULL
, NULL
, 0, NULL
}
1470 static PySequenceMethods BufferAsSeq
= {
1471 (PyInquiry
) BufferLength
, /* sq_length, len(x) */
1472 (binaryfunc
) 0, /* BufferConcat, */ /* sq_concat, x+y */
1473 (PyIntArgFunc
) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1474 (PyIntArgFunc
) BufferItem
, /* sq_item, x[i] */
1475 (PyIntIntArgFunc
) BufferSlice
, /* sq_slice, x[i:j] */
1476 (PyIntObjArgProc
) BufferAssItem
, /* sq_ass_item, x[i]=v */
1477 (PyIntIntObjArgProc
) BufferAssSlice
, /* sq_ass_slice, x[i:j]=v */
1480 static PyTypeObject BufferType
= {
1481 PyObject_HEAD_INIT(0)
1484 sizeof(BufferObject
),
1487 (destructor
) BufferDestructor
, /* tp_dealloc, refcount==0 */
1488 (printfunc
) 0, /* tp_print, print x */
1489 (getattrfunc
) BufferGetattr
, /* tp_getattr, x.attr */
1490 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1491 (cmpfunc
) 0, /* tp_compare, x>y */
1492 (reprfunc
) BufferRepr
, /* tp_repr, `x`, print x */
1495 &BufferAsSeq
, /* as sequence */
1498 (hashfunc
) 0, /* tp_hash, dict(x) */
1499 (ternaryfunc
) 0, /* tp_call, x() */
1500 (reprfunc
) 0, /* tp_str, str(x) */
1503 /* Buffer object - Implementation
1507 BufferNew(buf_T
*buf
)
1509 /* We need to handle deletion of buffers underneath us.
1510 * If we add a "b_python_ref" field to the buf_T structure,
1511 * then we can get at it in buf_freeall() in vim. We then
1512 * need to create only ONE Python object per buffer - if
1513 * we try to create a second, just INCREF the existing one
1514 * and return it. The (single) Python object referring to
1515 * the buffer is stored in "b_python_ref".
1516 * Question: what to do on a buf_freeall(). We'll probably
1517 * have to either delete the Python object (DECREF it to
1518 * zero - a bad idea, as it leaves dangling refs!) or
1519 * set the buf_T * value to an invalid value (-1?), which
1520 * means we need checks in all access functions... Bah.
1525 if (buf
->b_python_ref
!= NULL
)
1527 self
= buf
->b_python_ref
;
1532 self
= PyObject_NEW(BufferObject
, &BufferType
);
1536 buf
->b_python_ref
= self
;
1539 return (PyObject
*)(self
);
1543 BufferDestructor(PyObject
*self
)
1545 BufferObject
*this = (BufferObject
*)(self
);
1547 if (this->buf
&& this->buf
!= INVALID_BUFFER_VALUE
)
1548 this->buf
->b_python_ref
= NULL
;
1554 BufferGetattr(PyObject
*self
, char *name
)
1556 BufferObject
*this = (BufferObject
*)(self
);
1558 if (CheckBuffer(this))
1561 if (strcmp(name
, "name") == 0)
1562 return Py_BuildValue("s", this->buf
->b_ffname
);
1563 else if (strcmp(name
, "number") == 0)
1564 return Py_BuildValue(Py_ssize_t_fmt
, this->buf
->b_fnum
);
1565 else if (strcmp(name
,"__members__") == 0)
1566 return Py_BuildValue("[ss]", "name", "number");
1568 return Py_FindMethod(BufferMethods
, self
, name
);
1572 BufferRepr(PyObject
*self
)
1574 static char repr
[100];
1575 BufferObject
*this = (BufferObject
*)(self
);
1577 if (this->buf
== INVALID_BUFFER_VALUE
)
1579 vim_snprintf(repr
, 100, _("<buffer object (deleted) at %p>"), (self
));
1580 return PyString_FromString(repr
);
1584 char *name
= (char *)this->buf
->b_fname
;
1592 name
= name
+ (35 - len
);
1594 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1596 return PyString_FromString(repr
);
1600 /******************/
1603 BufferLength(PyObject
*self
)
1605 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1606 if (CheckBuffer((BufferObject
*)(self
)))
1607 return -1; /* ??? */
1609 return (((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1613 BufferItem(PyObject
*self
, PyInt n
)
1615 return RBItem((BufferObject
*)(self
), n
, 1,
1616 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1620 BufferSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1622 return RBSlice((BufferObject
*)(self
), lo
, hi
, 1,
1623 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1627 BufferAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1629 return RBAssItem((BufferObject
*)(self
), n
, val
, 1,
1630 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1635 BufferAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1637 return RBAssSlice((BufferObject
*)(self
), lo
, hi
, val
, 1,
1638 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1643 BufferAppend(PyObject
*self
, PyObject
*args
)
1645 return RBAppend((BufferObject
*)(self
), args
, 1,
1646 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1651 BufferMark(PyObject
*self
, PyObject
*args
)
1657 if (CheckBuffer((BufferObject
*)(self
)))
1660 if (!PyArg_ParseTuple(args
, "c", &mark
))
1663 curbuf_save
= curbuf
;
1664 curbuf
= ((BufferObject
*)(self
))->buf
;
1665 posp
= getmark(mark
, FALSE
);
1666 curbuf
= curbuf_save
;
1670 PyErr_SetVim(_("invalid mark name"));
1674 /* Ckeck for keyboard interrupt */
1675 if (VimErrorCheck())
1678 if (posp
->lnum
<= 0)
1680 /* Or raise an error? */
1685 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1689 BufferRange(PyObject
*self
, PyObject
*args
)
1694 if (CheckBuffer((BufferObject
*)(self
)))
1697 if (!PyArg_ParseTuple(args
, Py_ssize_t_fmt Py_ssize_t_fmt
, &start
, &end
))
1700 return RangeNew(((BufferObject
*)(self
))->buf
, start
, end
);
1703 /* Line range object - Definitions
1706 static struct PyMethodDef RangeMethods
[] = {
1707 /* name, function, calling, documentation */
1708 {"append", RangeAppend
, 1, "Append data to the Vim range" },
1709 { NULL
, NULL
, 0, NULL
}
1712 static PySequenceMethods RangeAsSeq
= {
1713 (PyInquiry
) RangeLength
, /* sq_length, len(x) */
1714 (binaryfunc
) 0, /* RangeConcat, */ /* sq_concat, x+y */
1715 (PyIntArgFunc
) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1716 (PyIntArgFunc
) RangeItem
, /* sq_item, x[i] */
1717 (PyIntIntArgFunc
) RangeSlice
, /* sq_slice, x[i:j] */
1718 (PyIntObjArgProc
) RangeAssItem
, /* sq_ass_item, x[i]=v */
1719 (PyIntIntObjArgProc
) RangeAssSlice
, /* sq_ass_slice, x[i:j]=v */
1722 static PyTypeObject RangeType
= {
1723 PyObject_HEAD_INIT(0)
1726 sizeof(RangeObject
),
1729 (destructor
) RangeDestructor
, /* tp_dealloc, refcount==0 */
1730 (printfunc
) 0, /* tp_print, print x */
1731 (getattrfunc
) RangeGetattr
, /* tp_getattr, x.attr */
1732 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1733 (cmpfunc
) 0, /* tp_compare, x>y */
1734 (reprfunc
) RangeRepr
, /* tp_repr, `x`, print x */
1737 &RangeAsSeq
, /* as sequence */
1740 (hashfunc
) 0, /* tp_hash, dict(x) */
1741 (ternaryfunc
) 0, /* tp_call, x() */
1742 (reprfunc
) 0, /* tp_str, str(x) */
1745 /* Line range object - Implementation
1749 RangeNew(buf_T
*buf
, PyInt start
, PyInt end
)
1753 self
= PyObject_NEW(RangeObject
, &RangeType
);
1757 bufr
= (BufferObject
*)BufferNew(buf
);
1766 self
->start
= start
;
1769 return (PyObject
*)(self
);
1773 RangeDestructor(PyObject
*self
)
1775 Py_DECREF(((RangeObject
*)(self
))->buf
);
1780 RangeGetattr(PyObject
*self
, char *name
)
1782 if (strcmp(name
, "start") == 0)
1783 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->start
- 1);
1784 else if (strcmp(name
, "end") == 0)
1785 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->end
- 1);
1787 return Py_FindMethod(RangeMethods
, self
, name
);
1791 RangeRepr(PyObject
*self
)
1793 static char repr
[100];
1794 RangeObject
*this = (RangeObject
*)(self
);
1796 if (this->buf
->buf
== INVALID_BUFFER_VALUE
)
1798 vim_snprintf(repr
, 100, "<range object (for deleted buffer) at %p>",
1800 return PyString_FromString(repr
);
1804 char *name
= (char *)this->buf
->buf
->b_fname
;
1809 len
= (int)strlen(name
);
1812 name
= name
+ (45 - len
);
1814 vim_snprintf(repr
, 100, "<range %s%s (%d:%d)>",
1815 len
> 45 ? "..." : "", name
,
1816 this->start
, this->end
);
1818 return PyString_FromString(repr
);
1825 RangeLength(PyObject
*self
)
1827 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1828 if (CheckBuffer(((RangeObject
*)(self
))->buf
))
1829 return -1; /* ??? */
1831 return (((RangeObject
*)(self
))->end
- ((RangeObject
*)(self
))->start
+ 1);
1835 RangeItem(PyObject
*self
, PyInt n
)
1837 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1838 ((RangeObject
*)(self
))->start
,
1839 ((RangeObject
*)(self
))->end
);
1843 RangeSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1845 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1846 ((RangeObject
*)(self
))->start
,
1847 ((RangeObject
*)(self
))->end
);
1851 RangeAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1853 return RBAssItem(((RangeObject
*)(self
))->buf
, n
, val
,
1854 ((RangeObject
*)(self
))->start
,
1855 ((RangeObject
*)(self
))->end
,
1856 &((RangeObject
*)(self
))->end
);
1860 RangeAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1862 return RBAssSlice(((RangeObject
*)(self
))->buf
, lo
, hi
, val
,
1863 ((RangeObject
*)(self
))->start
,
1864 ((RangeObject
*)(self
))->end
,
1865 &((RangeObject
*)(self
))->end
);
1869 RangeAppend(PyObject
*self
, PyObject
*args
)
1871 return RBAppend(((RangeObject
*)(self
))->buf
, args
,
1872 ((RangeObject
*)(self
))->start
,
1873 ((RangeObject
*)(self
))->end
,
1874 &((RangeObject
*)(self
))->end
);
1877 /* Buffer list object - Definitions
1886 static PySequenceMethods BufListAsSeq
= {
1887 (PyInquiry
) BufListLength
, /* sq_length, len(x) */
1888 (binaryfunc
) 0, /* sq_concat, x+y */
1889 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
1890 (PyIntArgFunc
) BufListItem
, /* sq_item, x[i] */
1891 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
1892 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
1893 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
1896 static PyTypeObject BufListType
= {
1897 PyObject_HEAD_INIT(0)
1900 sizeof(BufListObject
),
1903 (destructor
) 0, /* tp_dealloc, refcount==0 */
1904 (printfunc
) 0, /* tp_print, print x */
1905 (getattrfunc
) 0, /* tp_getattr, x.attr */
1906 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1907 (cmpfunc
) 0, /* tp_compare, x>y */
1908 (reprfunc
) 0, /* tp_repr, `x`, print x */
1911 &BufListAsSeq
, /* as sequence */
1914 (hashfunc
) 0, /* tp_hash, dict(x) */
1915 (ternaryfunc
) 0, /* tp_call, x() */
1916 (reprfunc
) 0, /* tp_str, str(x) */
1919 /* Buffer list object - Implementation
1924 BufListLength(PyObject
*self
)
1926 buf_T
*b
= firstbuf
;
1940 BufListItem(PyObject
*self
, PyInt n
)
1944 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1947 return BufferNew(b
);
1950 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
1954 /* Window object - Definitions
1957 static struct PyMethodDef WindowMethods
[] = {
1958 /* name, function, calling, documentation */
1959 { NULL
, NULL
, 0, NULL
}
1962 static PyTypeObject WindowType
= {
1963 PyObject_HEAD_INIT(0)
1966 sizeof(WindowObject
),
1969 (destructor
) WindowDestructor
, /* tp_dealloc, refcount==0 */
1970 (printfunc
) 0, /* tp_print, print x */
1971 (getattrfunc
) WindowGetattr
, /* tp_getattr, x.attr */
1972 (setattrfunc
) WindowSetattr
, /* tp_setattr, x.attr=v */
1973 (cmpfunc
) 0, /* tp_compare, x>y */
1974 (reprfunc
) WindowRepr
, /* tp_repr, `x`, print x */
1977 0, /* as sequence */
1980 (hashfunc
) 0, /* tp_hash, dict(x) */
1981 (ternaryfunc
) 0, /* tp_call, x() */
1982 (reprfunc
) 0, /* tp_str, str(x) */
1985 /* Window object - Implementation
1989 WindowNew(win_T
*win
)
1991 /* We need to handle deletion of windows underneath us.
1992 * If we add a "w_python_ref" field to the win_T structure,
1993 * then we can get at it in win_free() in vim. We then
1994 * need to create only ONE Python object per window - if
1995 * we try to create a second, just INCREF the existing one
1996 * and return it. The (single) Python object referring to
1997 * the window is stored in "w_python_ref".
1998 * On a win_free() we set the Python object's win_T* field
1999 * to an invalid value. We trap all uses of a window
2000 * object, and reject them if the win_T* field is invalid.
2005 if (win
->w_python_ref
)
2007 self
= win
->w_python_ref
;
2012 self
= PyObject_NEW(WindowObject
, &WindowType
);
2016 win
->w_python_ref
= self
;
2019 return (PyObject
*)(self
);
2023 WindowDestructor(PyObject
*self
)
2025 WindowObject
*this = (WindowObject
*)(self
);
2027 if (this->win
&& this->win
!= INVALID_WINDOW_VALUE
)
2028 this->win
->w_python_ref
= NULL
;
2034 CheckWindow(WindowObject
*this)
2036 if (this->win
== INVALID_WINDOW_VALUE
)
2038 PyErr_SetVim(_("attempt to refer to deleted window"));
2046 WindowGetattr(PyObject
*self
, char *name
)
2048 WindowObject
*this = (WindowObject
*)(self
);
2050 if (CheckWindow(this))
2053 if (strcmp(name
, "buffer") == 0)
2054 return (PyObject
*)BufferNew(this->win
->w_buffer
);
2055 else if (strcmp(name
, "cursor") == 0)
2057 pos_T
*pos
= &this->win
->w_cursor
;
2059 return Py_BuildValue("(ll)", (long)(pos
->lnum
), (long)(pos
->col
));
2061 else if (strcmp(name
, "height") == 0)
2062 return Py_BuildValue("l", (long)(this->win
->w_height
));
2063 #ifdef FEAT_VERTSPLIT
2064 else if (strcmp(name
, "width") == 0)
2065 return Py_BuildValue("l", (long)(W_WIDTH(this->win
)));
2067 else if (strcmp(name
,"__members__") == 0)
2068 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2070 return Py_FindMethod(WindowMethods
, self
, name
);
2074 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
2076 WindowObject
*this = (WindowObject
*)(self
);
2078 if (CheckWindow(this))
2081 if (strcmp(name
, "buffer") == 0)
2083 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2086 else if (strcmp(name
, "cursor") == 0)
2091 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2094 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2096 PyErr_SetVim(_("cursor position outside buffer"));
2100 /* Check for keyboard interrupts */
2101 if (VimErrorCheck())
2104 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2106 this->win
->w_cursor
.lnum
= lnum
;
2107 this->win
->w_cursor
.col
= col
;
2108 update_screen(VALID
);
2112 else if (strcmp(name
, "height") == 0)
2117 if (!PyArg_Parse(val
, "i", &height
))
2121 need_mouse_correct
= TRUE
;
2125 win_setheight(height
);
2128 /* Check for keyboard interrupts */
2129 if (VimErrorCheck())
2134 #ifdef FEAT_VERTSPLIT
2135 else if (strcmp(name
, "width") == 0)
2140 if (!PyArg_Parse(val
, "i", &width
))
2144 need_mouse_correct
= TRUE
;
2148 win_setwidth(width
);
2151 /* Check for keyboard interrupts */
2152 if (VimErrorCheck())
2160 PyErr_SetString(PyExc_AttributeError
, name
);
2166 WindowRepr(PyObject
*self
)
2168 static char repr
[100];
2169 WindowObject
*this = (WindowObject
*)(self
);
2171 if (this->win
== INVALID_WINDOW_VALUE
)
2173 vim_snprintf(repr
, 100, _("<window object (deleted) at %p>"), (self
));
2174 return PyString_FromString(repr
);
2181 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2185 vim_snprintf(repr
, 100, _("<window object (unknown) at %p>"),
2188 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2190 return PyString_FromString(repr
);
2194 /* Window list object - Definitions
2203 static PySequenceMethods WinListAsSeq
= {
2204 (PyInquiry
) WinListLength
, /* sq_length, len(x) */
2205 (binaryfunc
) 0, /* sq_concat, x+y */
2206 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
2207 (PyIntArgFunc
) WinListItem
, /* sq_item, x[i] */
2208 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
2209 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
2210 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
2213 static PyTypeObject WinListType
= {
2214 PyObject_HEAD_INIT(0)
2217 sizeof(WinListObject
),
2220 (destructor
) 0, /* tp_dealloc, refcount==0 */
2221 (printfunc
) 0, /* tp_print, print x */
2222 (getattrfunc
) 0, /* tp_getattr, x.attr */
2223 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
2224 (cmpfunc
) 0, /* tp_compare, x>y */
2225 (reprfunc
) 0, /* tp_repr, `x`, print x */
2228 &WinListAsSeq
, /* as sequence */
2231 (hashfunc
) 0, /* tp_hash, dict(x) */
2232 (ternaryfunc
) 0, /* tp_call, x() */
2233 (reprfunc
) 0, /* tp_str, str(x) */
2236 /* Window list object - Implementation
2240 WinListLength(PyObject
*self
)
2242 win_T
*w
= firstwin
;
2256 WinListItem(PyObject
*self
, PyInt n
)
2260 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2262 return WindowNew(w
);
2264 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2268 /* Current items object - Definitions
2277 static PyTypeObject CurrentType
= {
2278 PyObject_HEAD_INIT(0)
2281 sizeof(CurrentObject
),
2284 (destructor
) 0, /* tp_dealloc, refcount==0 */
2285 (printfunc
) 0, /* tp_print, print x */
2286 (getattrfunc
) CurrentGetattr
, /* tp_getattr, x.attr */
2287 (setattrfunc
) CurrentSetattr
, /* tp_setattr, x.attr=v */
2288 (cmpfunc
) 0, /* tp_compare, x>y */
2289 (reprfunc
) 0, /* tp_repr, `x`, print x */
2292 0, /* as sequence */
2295 (hashfunc
) 0, /* tp_hash, dict(x) */
2296 (ternaryfunc
) 0, /* tp_call, x() */
2297 (reprfunc
) 0, /* tp_str, str(x) */
2300 /* Current items object - Implementation
2304 CurrentGetattr(PyObject
*self
, char *name
)
2306 if (strcmp(name
, "buffer") == 0)
2307 return (PyObject
*)BufferNew(curbuf
);
2308 else if (strcmp(name
, "window") == 0)
2309 return (PyObject
*)WindowNew(curwin
);
2310 else if (strcmp(name
, "line") == 0)
2311 return GetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
);
2312 else if (strcmp(name
, "range") == 0)
2313 return RangeNew(curbuf
, RangeStart
, RangeEnd
);
2314 else if (strcmp(name
,"__members__") == 0)
2315 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2318 PyErr_SetString(PyExc_AttributeError
, name
);
2325 CurrentSetattr(PyObject
*self
, char *name
, PyObject
*value
)
2327 if (strcmp(name
, "line") == 0)
2329 if (SetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
, value
, NULL
) == FAIL
)
2336 PyErr_SetString(PyExc_AttributeError
, name
);
2341 /* External interface
2345 python_buffer_free(buf_T
*buf
)
2347 if (buf
->b_python_ref
!= NULL
)
2349 BufferObject
*bp
= buf
->b_python_ref
;
2350 bp
->buf
= INVALID_BUFFER_VALUE
;
2351 buf
->b_python_ref
= NULL
;
2355 #if defined(FEAT_WINDOWS) || defined(PROTO)
2357 python_window_free(win_T
*win
)
2359 if (win
->w_python_ref
!= NULL
)
2361 WindowObject
*wp
= win
->w_python_ref
;
2362 wp
->win
= INVALID_WINDOW_VALUE
;
2363 win
->w_python_ref
= NULL
;
2368 static BufListObject TheBufferList
=
2370 PyObject_HEAD_INIT(&BufListType
)
2373 static WinListObject TheWindowList
=
2375 PyObject_HEAD_INIT(&WinListType
)
2378 static CurrentObject TheCurrent
=
2380 PyObject_HEAD_INIT(&CurrentType
)
2384 PythonMod_Init(void)
2388 /* The special value is removed from sys.path in Python_Init(). */
2389 static char *(argv
[2]) = {"/must>not&exist/foo", NULL
};
2392 BufferType
.ob_type
= &PyType_Type
;
2393 RangeType
.ob_type
= &PyType_Type
;
2394 WindowType
.ob_type
= &PyType_Type
;
2395 BufListType
.ob_type
= &PyType_Type
;
2396 WinListType
.ob_type
= &PyType_Type
;
2397 CurrentType
.ob_type
= &PyType_Type
;
2399 /* Set sys.argv[] to avoid a crash in warn(). */
2400 PySys_SetArgv(1, argv
);
2402 mod
= Py_InitModule4("vim", VimMethods
, (char *)NULL
, (PyObject
*)NULL
, PYTHON_API_VERSION
);
2403 dict
= PyModule_GetDict(mod
);
2405 VimError
= Py_BuildValue("s", "vim.error");
2407 PyDict_SetItemString(dict
, "error", VimError
);
2408 PyDict_SetItemString(dict
, "buffers", (PyObject
*)(void *)&TheBufferList
);
2409 PyDict_SetItemString(dict
, "current", (PyObject
*)(void *)&TheCurrent
);
2410 PyDict_SetItemString(dict
, "windows", (PyObject
*)(void *)&TheWindowList
);
2412 if (PyErr_Occurred())
2418 /*************************************************************************
2419 * 4. Utility functions for handling the interface between Vim and Python.
2422 /* Get a line from the specified buffer. The line number is
2423 * in Vim format (1-based). The line is returned as a Python
2427 GetBufferLine(buf_T
*buf
, PyInt n
)
2429 return LineToString((char *)ml_get_buf(buf
, (linenr_T
)n
, FALSE
));
2432 /* Get a list of lines from the specified buffer. The line numbers
2433 * are in Vim format (1-based). The range is from lo up to, but not
2434 * including, hi. The list is returned as a Python list of string objects.
2437 GetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
)
2441 PyObject
*list
= PyList_New(n
);
2446 for (i
= 0; i
< n
; ++i
)
2448 PyObject
*str
= LineToString((char *)ml_get_buf(buf
, (linenr_T
)(lo
+i
), FALSE
));
2450 /* Error check - was the Python string creation OK? */
2457 /* Set the list item */
2458 if (PyList_SetItem(list
, i
, str
))
2466 /* The ownership of the Python list is passed to the caller (ie,
2467 * the caller should Py_DECREF() the object when it is finished
2475 * Check if deleting lines made the cursor position invalid.
2476 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2480 py_fix_cursor(linenr_T lo
, linenr_T hi
, linenr_T extra
)
2482 if (curwin
->w_cursor
.lnum
>= lo
)
2484 /* Adjust the cursor position if it's in/after the changed
2486 if (curwin
->w_cursor
.lnum
>= hi
)
2488 curwin
->w_cursor
.lnum
+= extra
;
2493 curwin
->w_cursor
.lnum
= lo
;
2498 changed_cline_bef_curs();
2500 invalidate_botline();
2503 /* Replace a line in the specified buffer. The line number is
2504 * in Vim format (1-based). The replacement line is given as
2505 * a Python string object. The object is checked for validity
2506 * and correct format. Errors are returned as a value of FAIL.
2507 * The return value is OK on success.
2508 * If OK is returned and len_change is not NULL, *len_change
2509 * is set to the change in the buffer length.
2512 SetBufferLine(buf_T
*buf
, PyInt n
, PyObject
*line
, PyInt
*len_change
)
2514 /* First of all, we check the thpe of the supplied Python object.
2515 * There are three cases:
2516 * 1. NULL, or None - this is a deletion.
2517 * 2. A string - this is a replacement.
2518 * 3. Anything else - this is an error.
2520 if (line
== Py_None
|| line
== NULL
)
2522 buf_T
*savebuf
= curbuf
;
2527 if (u_savedel((linenr_T
)n
, 1L) == FAIL
)
2528 PyErr_SetVim(_("cannot save undo information"));
2529 else if (ml_delete((linenr_T
)n
, FALSE
) == FAIL
)
2530 PyErr_SetVim(_("cannot delete line"));
2533 deleted_lines_mark((linenr_T
)n
, 1L);
2534 if (buf
== curwin
->w_buffer
)
2535 py_fix_cursor((linenr_T
)n
, (linenr_T
)n
+ 1, (linenr_T
)-1);
2540 if (PyErr_Occurred() || VimErrorCheck())
2548 else if (PyString_Check(line
))
2550 char *save
= StringToLine(line
);
2551 buf_T
*savebuf
= curbuf
;
2556 /* We do not need to free "save" if ml_replace() consumes it. */
2560 if (u_savesub((linenr_T
)n
) == FAIL
)
2562 PyErr_SetVim(_("cannot save undo information"));
2565 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2567 PyErr_SetVim(_("cannot replace line"));
2571 changed_bytes((linenr_T
)n
, 0);
2575 /* Check that the cursor is not beyond the end of the line now. */
2576 if (buf
== curwin
->w_buffer
)
2579 if (PyErr_Occurred() || VimErrorCheck())
2589 PyErr_BadArgument();
2594 /* Replace a range of lines in the specified buffer. The line numbers are in
2595 * Vim format (1-based). The range is from lo up to, but not including, hi.
2596 * The replacement lines are given as a Python list of string objects. The
2597 * list is checked for validity and correct format. Errors are returned as a
2598 * value of FAIL. The return value is OK on success.
2599 * If OK is returned and len_change is not NULL, *len_change
2600 * is set to the change in the buffer length.
2603 SetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
, PyObject
*list
, PyInt
*len_change
)
2605 /* First of all, we check the thpe of the supplied Python object.
2606 * There are three cases:
2607 * 1. NULL, or None - this is a deletion.
2608 * 2. A list - this is a replacement.
2609 * 3. Anything else - this is an error.
2611 if (list
== Py_None
|| list
== NULL
)
2614 PyInt n
= (int)(hi
- lo
);
2615 buf_T
*savebuf
= curbuf
;
2620 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2621 PyErr_SetVim(_("cannot save undo information"));
2624 for (i
= 0; i
< n
; ++i
)
2626 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2628 PyErr_SetVim(_("cannot delete line"));
2632 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2634 if (buf
== curwin
->w_buffer
)
2635 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)-n
);
2640 if (PyErr_Occurred() || VimErrorCheck())
2648 else if (PyList_Check(list
))
2651 PyInt new_len
= PyList_Size(list
);
2652 PyInt old_len
= hi
- lo
;
2653 PyInt extra
= 0; /* lines added to text, can be negative */
2657 if (new_len
== 0) /* avoid allocating zero bytes */
2661 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
2669 for (i
= 0; i
< new_len
; ++i
)
2671 PyObject
*line
= PyList_GetItem(list
, i
);
2673 array
[i
] = StringToLine(line
);
2674 if (array
[i
] == NULL
)
2677 vim_free(array
[--i
]);
2688 if (u_save((linenr_T
)(lo
-1), (linenr_T
)hi
) == FAIL
)
2689 PyErr_SetVim(_("cannot save undo information"));
2691 /* If the size of the range is reducing (ie, new_len < old_len) we
2692 * need to delete some old_len. We do this at the start, by
2693 * repeatedly deleting line "lo".
2695 if (!PyErr_Occurred())
2697 for (i
= 0; i
< old_len
- new_len
; ++i
)
2698 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2700 PyErr_SetVim(_("cannot delete line"));
2706 /* For as long as possible, replace the existing old_len with the
2707 * new old_len. This is a more efficient operation, as it requires
2708 * less memory allocation and freeing.
2710 if (!PyErr_Occurred())
2712 for (i
= 0; i
< old_len
&& i
< new_len
; ++i
)
2713 if (ml_replace((linenr_T
)(lo
+i
), (char_u
*)array
[i
], FALSE
)
2716 PyErr_SetVim(_("cannot replace line"));
2723 /* Now we may need to insert the remaining new old_len. If we do, we
2724 * must free the strings as we finish with them (we can't pass the
2725 * responsibility to vim in this case).
2727 if (!PyErr_Occurred())
2731 if (ml_append((linenr_T
)(lo
+ i
- 1),
2732 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2734 PyErr_SetVim(_("cannot insert line"));
2743 /* Free any left-over old_len, as a result of an error */
2750 /* Free the array of old_len. All of its contents have now
2751 * been dealt with (either freed, or the responsibility passed
2756 /* Adjust marks. Invalidate any which lie in the
2757 * changed range, and move any in the remainder of the buffer.
2759 mark_adjust((linenr_T
)lo
, (linenr_T
)(hi
- 1),
2760 (long)MAXLNUM
, (long)extra
);
2761 changed_lines((linenr_T
)lo
, 0, (linenr_T
)hi
, (long)extra
);
2763 if (buf
== curwin
->w_buffer
)
2764 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)extra
);
2768 if (PyErr_Occurred() || VimErrorCheck())
2772 *len_change
= new_len
- old_len
;
2778 PyErr_BadArgument();
2783 /* Insert a number of lines into the specified buffer after the specifed line.
2784 * The line number is in Vim format (1-based). The lines to be inserted are
2785 * given as a Python list of string objects or as a single string. The lines
2786 * to be added are checked for validity and correct format. Errors are
2787 * returned as a value of FAIL. The return value is OK on success.
2788 * If OK is returned and len_change is not NULL, *len_change
2789 * is set to the change in the buffer length.
2792 InsertBufferLines(buf_T
*buf
, PyInt n
, PyObject
*lines
, PyInt
*len_change
)
2794 /* First of all, we check the type of the supplied Python object.
2795 * It must be a string or a list, or the call is in error.
2797 if (PyString_Check(lines
))
2799 char *str
= StringToLine(lines
);
2810 if (u_save((linenr_T
)n
, (linenr_T
)(n
+1)) == FAIL
)
2811 PyErr_SetVim(_("cannot save undo information"));
2812 else if (ml_append((linenr_T
)n
, (char_u
*)str
, 0, FALSE
) == FAIL
)
2813 PyErr_SetVim(_("cannot insert line"));
2815 appended_lines_mark((linenr_T
)n
, 1L);
2819 update_screen(VALID
);
2821 if (PyErr_Occurred() || VimErrorCheck())
2829 else if (PyList_Check(lines
))
2832 PyInt size
= PyList_Size(lines
);
2836 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2843 for (i
= 0; i
< size
; ++i
)
2845 PyObject
*line
= PyList_GetItem(lines
, i
);
2846 array
[i
] = StringToLine(line
);
2848 if (array
[i
] == NULL
)
2851 vim_free(array
[--i
]);
2862 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2863 PyErr_SetVim(_("cannot save undo information"));
2866 for (i
= 0; i
< size
; ++i
)
2868 if (ml_append((linenr_T
)(n
+ i
),
2869 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2871 PyErr_SetVim(_("cannot insert line"));
2873 /* Free the rest of the lines */
2875 vim_free(array
[i
++]);
2882 appended_lines_mark((linenr_T
)n
, (long)i
);
2885 /* Free the array of lines. All of its contents have now
2891 update_screen(VALID
);
2893 if (PyErr_Occurred() || VimErrorCheck())
2903 PyErr_BadArgument();
2908 /* Convert a Vim line into a Python string.
2909 * All internal newlines are replaced by null characters.
2911 * On errors, the Python exception data is set, and NULL is returned.
2914 LineToString(const char *str
)
2917 PyInt len
= strlen(str
);
2920 /* Allocate an Python string object, with uninitialised contents. We
2921 * must do it this way, so that we can modify the string in place
2922 * later. See the Python source, Objects/stringobject.c for details.
2924 result
= PyString_FromStringAndSize(NULL
, len
);
2928 p
= PyString_AsString(result
);
2944 /* Convert a Python string into a Vim line.
2946 * The result is in allocated memory. All internal nulls are replaced by
2947 * newline characters. It is an error for the string to contain newline
2950 * On errors, the Python exception data is set, and NULL is returned.
2953 StringToLine(PyObject
*obj
)
2961 if (obj
== NULL
|| !PyString_Check(obj
))
2963 PyErr_BadArgument();
2967 str
= PyString_AsString(obj
);
2968 len
= PyString_Size(obj
);
2971 * Error checking: String must not contain newlines, as we
2972 * are replacing a single line, and we must replace it with
2974 * A trailing newline is removed, so that append(f.readlines()) works.
2976 p
= memchr(str
, '\n', len
);
2979 if (p
== str
+ len
- 1)
2983 PyErr_SetVim(_("string cannot contain newlines"));
2988 /* Create a copy of the string, with internal nulls replaced by
2989 * newline characters, as is the vim convention.
2991 save
= (char *)alloc((unsigned)(len
+1));
2998 for (i
= 0; i
< len
; ++i
)
3011 /* Check to see whether a Vim error has been reported, or a keyboard
3012 * interrupt has been detected.
3019 PyErr_SetNone(PyExc_KeyboardInterrupt
);
3022 else if (did_emsg
&& !PyErr_Occurred())
3024 PyErr_SetNone(VimError
);
3032 /* Don't generate a prototype for the next function, it generates an error on
3033 * newer Python versions. */
3034 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3037 Py_GetProgramName(void)
3041 #endif /* Python 1.4 */