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. */
54 # define PyThreadState int
55 # define PyTypeObject int
56 struct PyMethodDef
{ int a
; };
57 # define PySequenceMethods int
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
69 # define PyInquiry inquiry
70 # define PyIntArgFunc intargfunc
71 # define PyIntIntArgFunc intintargfunc
72 # define PyIntObjArgProc intobjargproc
73 # define PyIntIntObjArgProc intintobjargproc
77 #define single_input 256
78 #define file_input 257
79 #define eval_input 258
81 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
82 /* Python 2.3: can invoke ":python" recursively. */
83 # define PY_CAN_RECURSE
86 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
87 # ifndef DYNAMIC_PYTHON
88 # define HINSTANCE int /* for generating prototypes */
94 # define PyArg_Parse dll_PyArg_Parse
95 # define PyArg_ParseTuple dll_PyArg_ParseTuple
96 # define PyDict_SetItemString dll_PyDict_SetItemString
97 # define PyErr_BadArgument dll_PyErr_BadArgument
98 # define PyErr_Clear dll_PyErr_Clear
99 # define PyErr_NoMemory dll_PyErr_NoMemory
100 # define PyErr_Occurred dll_PyErr_Occurred
101 # define PyErr_SetNone dll_PyErr_SetNone
102 # define PyErr_SetString dll_PyErr_SetString
103 # define PyEval_InitThreads dll_PyEval_InitThreads
104 # define PyEval_RestoreThread dll_PyEval_RestoreThread
105 # define PyEval_SaveThread dll_PyEval_SaveThread
106 # ifdef PY_CAN_RECURSE
107 # define PyGILState_Ensure dll_PyGILState_Ensure
108 # define PyGILState_Release dll_PyGILState_Release
110 # define PyInt_AsLong dll_PyInt_AsLong
111 # define PyInt_FromLong dll_PyInt_FromLong
112 # define PyInt_Type (*dll_PyInt_Type)
113 # define PyList_GetItem dll_PyList_GetItem
114 # define PyList_Append dll_PyList_Append
115 # define PyList_New dll_PyList_New
116 # define PyList_SetItem dll_PyList_SetItem
117 # define PyList_Size dll_PyList_Size
118 # define PyList_Type (*dll_PyList_Type)
119 # define PyImport_ImportModule dll_PyImport_ImportModule
120 # define PyDict_New dll_PyDict_New
121 # define PyDict_GetItemString dll_PyDict_GetItemString
122 # define PyModule_GetDict dll_PyModule_GetDict
123 # define PyRun_SimpleString dll_PyRun_SimpleString
124 # define PyString_AsString dll_PyString_AsString
125 # define PyString_FromString dll_PyString_FromString
126 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
127 # define PyString_Size dll_PyString_Size
128 # define PyString_Type (*dll_PyString_Type)
129 # define PySys_SetObject dll_PySys_SetObject
130 # define PySys_SetArgv dll_PySys_SetArgv
131 # define PyType_Type (*dll_PyType_Type)
132 # define Py_BuildValue dll_Py_BuildValue
133 # define Py_FindMethod dll_Py_FindMethod
134 # define Py_InitModule4 dll_Py_InitModule4
135 # define Py_Initialize dll_Py_Initialize
136 # define Py_Finalize dll_Py_Finalize
137 # define Py_IsInitialized dll_Py_IsInitialized
138 # define _PyObject_New dll__PyObject_New
139 # define _Py_NoneStruct (*dll__Py_NoneStruct)
140 # define PyObject_Init dll__PyObject_Init
141 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
142 # define PyType_IsSubtype dll_PyType_IsSubtype
144 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
145 # define PyObject_Malloc dll_PyObject_Malloc
146 # define PyObject_Free dll_PyObject_Free
150 * Pointers for dynamic link
152 static int(*dll_PyArg_Parse
)(PyObject
*, char *, ...);
153 static int(*dll_PyArg_ParseTuple
)(PyObject
*, char *, ...);
154 static int(*dll_PyDict_SetItemString
)(PyObject
*dp
, char *key
, PyObject
*item
);
155 static int(*dll_PyErr_BadArgument
)(void);
156 static void(*dll_PyErr_Clear
)(void);
157 static PyObject
*(*dll_PyErr_NoMemory
)(void);
158 static PyObject
*(*dll_PyErr_Occurred
)(void);
159 static void(*dll_PyErr_SetNone
)(PyObject
*);
160 static void(*dll_PyErr_SetString
)(PyObject
*, const char *);
161 static void(*dll_PyEval_InitThreads
)(void);
162 static void(*dll_PyEval_RestoreThread
)(PyThreadState
*);
163 static PyThreadState
*(*dll_PyEval_SaveThread
)(void);
164 # ifdef PY_CAN_RECURSE
165 static PyGILState_STATE (*dll_PyGILState_Ensure
)(void);
166 static void (*dll_PyGILState_Release
)(PyGILState_STATE
);
168 static long(*dll_PyInt_AsLong
)(PyObject
*);
169 static PyObject
*(*dll_PyInt_FromLong
)(long);
170 static PyTypeObject
* dll_PyInt_Type
;
171 static PyObject
*(*dll_PyList_GetItem
)(PyObject
*, PyInt
);
172 static PyObject
*(*dll_PyList_Append
)(PyObject
*, PyObject
*);
173 static PyObject
*(*dll_PyList_New
)(PyInt size
);
174 static int(*dll_PyList_SetItem
)(PyObject
*, PyInt
, PyObject
*);
175 static PyInt(*dll_PyList_Size
)(PyObject
*);
176 static PyTypeObject
* dll_PyList_Type
;
177 static PyObject
*(*dll_PyImport_ImportModule
)(const char *);
178 static PyObject
*(*dll_PyDict_New
)(void);
179 static PyObject
*(*dll_PyDict_GetItemString
)(PyObject
*, const char *);
180 static PyObject
*(*dll_PyModule_GetDict
)(PyObject
*);
181 static int(*dll_PyRun_SimpleString
)(char *);
182 static char*(*dll_PyString_AsString
)(PyObject
*);
183 static PyObject
*(*dll_PyString_FromString
)(const char *);
184 static PyObject
*(*dll_PyString_FromStringAndSize
)(const char *, PyInt
);
185 static PyInt(*dll_PyString_Size
)(PyObject
*);
186 static PyTypeObject
* dll_PyString_Type
;
187 static int(*dll_PySys_SetObject
)(char *, PyObject
*);
188 static int(*dll_PySys_SetArgv
)(int, char **);
189 static PyTypeObject
* dll_PyType_Type
;
190 static PyObject
*(*dll_Py_BuildValue
)(char *, ...);
191 static PyObject
*(*dll_Py_FindMethod
)(struct PyMethodDef
[], PyObject
*, char *);
192 static PyObject
*(*dll_Py_InitModule4
)(char *, struct PyMethodDef
*, char *, PyObject
*, int);
193 static void(*dll_Py_Initialize
)(void);
194 static void(*dll_Py_Finalize
)(void);
195 static int(*dll_Py_IsInitialized
)(void);
196 static PyObject
*(*dll__PyObject_New
)(PyTypeObject
*, PyObject
*);
197 static PyObject
*(*dll__PyObject_Init
)(PyObject
*, PyTypeObject
*);
198 static PyObject
* dll__Py_NoneStruct
;
199 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
200 static int (*dll_PyType_IsSubtype
)(PyTypeObject
*, PyTypeObject
*);
202 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
203 static void* (*dll_PyObject_Malloc
)(size_t);
204 static void (*dll_PyObject_Free
)(void*);
207 static HINSTANCE hinstPython
= 0; /* Instance of python.dll */
209 /* Imported exception objects */
210 static PyObject
*imp_PyExc_AttributeError
;
211 static PyObject
*imp_PyExc_IndexError
;
212 static PyObject
*imp_PyExc_KeyboardInterrupt
;
213 static PyObject
*imp_PyExc_TypeError
;
214 static PyObject
*imp_PyExc_ValueError
;
216 # define PyExc_AttributeError imp_PyExc_AttributeError
217 # define PyExc_IndexError imp_PyExc_IndexError
218 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
219 # define PyExc_TypeError imp_PyExc_TypeError
220 # define PyExc_ValueError imp_PyExc_ValueError
223 * Table of name to function pointer of python.
225 # define PYTHON_PROC FARPROC
230 } python_funcname_table
[] =
232 {"PyArg_Parse", (PYTHON_PROC
*)&dll_PyArg_Parse
},
233 {"PyArg_ParseTuple", (PYTHON_PROC
*)&dll_PyArg_ParseTuple
},
234 {"PyDict_SetItemString", (PYTHON_PROC
*)&dll_PyDict_SetItemString
},
235 {"PyErr_BadArgument", (PYTHON_PROC
*)&dll_PyErr_BadArgument
},
236 {"PyErr_Clear", (PYTHON_PROC
*)&dll_PyErr_Clear
},
237 {"PyErr_NoMemory", (PYTHON_PROC
*)&dll_PyErr_NoMemory
},
238 {"PyErr_Occurred", (PYTHON_PROC
*)&dll_PyErr_Occurred
},
239 {"PyErr_SetNone", (PYTHON_PROC
*)&dll_PyErr_SetNone
},
240 {"PyErr_SetString", (PYTHON_PROC
*)&dll_PyErr_SetString
},
241 {"PyEval_InitThreads", (PYTHON_PROC
*)&dll_PyEval_InitThreads
},
242 {"PyEval_RestoreThread", (PYTHON_PROC
*)&dll_PyEval_RestoreThread
},
243 {"PyEval_SaveThread", (PYTHON_PROC
*)&dll_PyEval_SaveThread
},
244 # ifdef PY_CAN_RECURSE
245 {"PyGILState_Ensure", (PYTHON_PROC
*)&dll_PyGILState_Ensure
},
246 {"PyGILState_Release", (PYTHON_PROC
*)&dll_PyGILState_Release
},
248 {"PyInt_AsLong", (PYTHON_PROC
*)&dll_PyInt_AsLong
},
249 {"PyInt_FromLong", (PYTHON_PROC
*)&dll_PyInt_FromLong
},
250 {"PyInt_Type", (PYTHON_PROC
*)&dll_PyInt_Type
},
251 {"PyList_GetItem", (PYTHON_PROC
*)&dll_PyList_GetItem
},
252 {"PyList_Append", (PYTHON_PROC
*)&dll_PyList_Append
},
253 {"PyList_New", (PYTHON_PROC
*)&dll_PyList_New
},
254 {"PyList_SetItem", (PYTHON_PROC
*)&dll_PyList_SetItem
},
255 {"PyList_Size", (PYTHON_PROC
*)&dll_PyList_Size
},
256 {"PyList_Type", (PYTHON_PROC
*)&dll_PyList_Type
},
257 {"PyImport_ImportModule", (PYTHON_PROC
*)&dll_PyImport_ImportModule
},
258 {"PyDict_GetItemString", (PYTHON_PROC
*)&dll_PyDict_GetItemString
},
259 {"PyDict_New", (PYTHON_PROC
*)&dll_PyDict_New
},
260 {"PyModule_GetDict", (PYTHON_PROC
*)&dll_PyModule_GetDict
},
261 {"PyRun_SimpleString", (PYTHON_PROC
*)&dll_PyRun_SimpleString
},
262 {"PyString_AsString", (PYTHON_PROC
*)&dll_PyString_AsString
},
263 {"PyString_FromString", (PYTHON_PROC
*)&dll_PyString_FromString
},
264 {"PyString_FromStringAndSize", (PYTHON_PROC
*)&dll_PyString_FromStringAndSize
},
265 {"PyString_Size", (PYTHON_PROC
*)&dll_PyString_Size
},
266 {"PyString_Type", (PYTHON_PROC
*)&dll_PyString_Type
},
267 {"PySys_SetObject", (PYTHON_PROC
*)&dll_PySys_SetObject
},
268 {"PySys_SetArgv", (PYTHON_PROC
*)&dll_PySys_SetArgv
},
269 {"PyType_Type", (PYTHON_PROC
*)&dll_PyType_Type
},
270 {"Py_BuildValue", (PYTHON_PROC
*)&dll_Py_BuildValue
},
271 {"Py_FindMethod", (PYTHON_PROC
*)&dll_Py_FindMethod
},
272 {"Py_InitModule4", (PYTHON_PROC
*)&dll_Py_InitModule4
},
273 {"Py_Initialize", (PYTHON_PROC
*)&dll_Py_Initialize
},
274 {"Py_Finalize", (PYTHON_PROC
*)&dll_Py_Finalize
},
275 {"Py_IsInitialized", (PYTHON_PROC
*)&dll_Py_IsInitialized
},
276 {"_PyObject_New", (PYTHON_PROC
*)&dll__PyObject_New
},
277 {"PyObject_Init", (PYTHON_PROC
*)&dll__PyObject_Init
},
278 {"_Py_NoneStruct", (PYTHON_PROC
*)&dll__Py_NoneStruct
},
279 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
280 {"PyType_IsSubtype", (PYTHON_PROC
*)&dll_PyType_IsSubtype
},
282 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
283 {"PyObject_Malloc", (PYTHON_PROC
*)&dll_PyObject_Malloc
},
284 {"PyObject_Free", (PYTHON_PROC
*)&dll_PyObject_Free
},
293 end_dynamic_python(void)
297 FreeLibrary(hinstPython
);
303 * Load library and get all pointers.
304 * Parameter 'libname' provides name of DLL.
308 python_runtime_link_init(char *libname
, int verbose
)
314 hinstPython
= LoadLibrary(libname
);
318 EMSG2(_(e_loadlib
), libname
);
322 for (i
= 0; python_funcname_table
[i
].ptr
; ++i
)
324 if ((*python_funcname_table
[i
].ptr
= GetProcAddress(hinstPython
,
325 python_funcname_table
[i
].name
)) == NULL
)
327 FreeLibrary(hinstPython
);
330 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
338 * If python is enabled (there is installed python on Windows system) return
342 python_enabled(verbose
)
345 return python_runtime_link_init(DYNAMIC_PYTHON_DLL
, verbose
) == OK
;
348 /* Load the standard Python exceptions - don't import the symbols from the
349 * DLL, as this can cause errors (importing data symbols is not reliable).
351 static void get_exceptions
__ARGS((void));
356 PyObject
*exmod
= PyImport_ImportModule("exceptions");
357 PyObject
*exdict
= PyModule_GetDict(exmod
);
358 imp_PyExc_AttributeError
= PyDict_GetItemString(exdict
, "AttributeError");
359 imp_PyExc_IndexError
= PyDict_GetItemString(exdict
, "IndexError");
360 imp_PyExc_KeyboardInterrupt
= PyDict_GetItemString(exdict
, "KeyboardInterrupt");
361 imp_PyExc_TypeError
= PyDict_GetItemString(exdict
, "TypeError");
362 imp_PyExc_ValueError
= PyDict_GetItemString(exdict
, "ValueError");
363 Py_XINCREF(imp_PyExc_AttributeError
);
364 Py_XINCREF(imp_PyExc_IndexError
);
365 Py_XINCREF(imp_PyExc_KeyboardInterrupt
);
366 Py_XINCREF(imp_PyExc_TypeError
);
367 Py_XINCREF(imp_PyExc_ValueError
);
370 #endif /* DYNAMIC_PYTHON */
372 /******************************************************
373 * Internal function prototypes.
376 static void DoPythonCommand(exarg_T
*, const char *);
377 static int RangeStart
;
380 static void PythonIO_Flush(void);
381 static int PythonIO_Init(void);
382 static int PythonMod_Init(void);
384 /* Utility functions for the vim/python interface
385 * ----------------------------------------------
387 static PyObject
*GetBufferLine(buf_T
*, int);
388 static PyObject
*GetBufferLineList(buf_T
*, PyInt
, PyInt
);
390 static int SetBufferLine(buf_T
*, int, PyObject
*, int *);
391 static int SetBufferLineList(buf_T
*, PyInt
, PyInt
, PyObject
*, int *);
392 static int InsertBufferLines(buf_T
*, int, PyObject
*, int *);
394 static PyObject
*LineToString(const char *);
395 static char *StringToLine(PyObject
*);
397 static int VimErrorCheck(void);
399 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
401 /******************************************************
402 * 1. Python interpreter main program.
405 static int initialised
= 0;
407 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
408 typedef PyObject PyThreadState
;
411 #ifdef PY_CAN_RECURSE
412 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
414 static PyThreadState
*saved_python_thread
= NULL
;
418 * Suspend a thread of the Python interpreter, other threads are allowed to
422 Python_SaveThread(void)
424 #ifdef PY_CAN_RECURSE
425 PyGILState_Release(pygilstate
);
427 saved_python_thread
= PyEval_SaveThread();
432 * Restore a thread of the Python interpreter, waits for other threads to
436 Python_RestoreThread(void)
438 #ifdef PY_CAN_RECURSE
439 pygilstate
= PyGILState_Ensure();
441 PyEval_RestoreThread(saved_python_thread
);
442 saved_python_thread
= NULL
;
447 * obtain a lock on the Vim data structures
449 static void Python_Lock_Vim(void)
454 * release a lock on the Vim data structures
456 static void Python_Release_Vim(void)
463 static int recurse
= 0;
465 /* If a crash occurs while doing this, don't try again. */
471 #ifdef DYNAMIC_PYTHON
472 if (hinstPython
&& Py_IsInitialized())
474 Python_RestoreThread(); /* enter python */
477 end_dynamic_python();
479 if (Py_IsInitialized())
481 Python_RestoreThread(); /* enter python */
494 #ifdef DYNAMIC_PYTHON
495 if (!python_enabled(TRUE
))
497 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
502 #if !defined(MACOS) || defined(MACOS_X_UNIX)
507 /* initialise threads */
508 PyEval_InitThreads();
510 #ifdef DYNAMIC_PYTHON
517 if (PythonMod_Init())
520 /* the first python thread is vim's, release the lock */
529 /* We call PythonIO_Flush() here to print any Python errors.
530 * This is OK, as it is possible to call this function even
531 * if PythonIO_Init() has not completed successfully (it will
532 * not do anything in this case).
542 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
544 #ifndef PY_CAN_RECURSE
545 static int recursive
= 0;
547 #if defined(MACOS) && !defined(MACOS_X_UNIX)
550 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
554 #ifndef PY_CAN_RECURSE
557 EMSG(_("E659: Cannot invoke Python recursively"));
563 #if defined(MACOS) && !defined(MACOS_X_UNIX)
565 /* Check if the Python library is available */
566 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
572 RangeStart
= eap
->line1
;
573 RangeEnd
= eap
->line2
;
574 Python_Release_Vim(); /* leave vim */
576 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
577 /* Python only works properly when the LC_NUMERIC locale is "C". */
578 saved_locale
= setlocale(LC_NUMERIC
, NULL
);
579 if (saved_locale
== NULL
|| STRCMP(saved_locale
, "C") == 0)
583 /* Need to make a copy, value may change when setting new locale. */
584 saved_locale
= (char *)vim_strsave((char_u
*)saved_locale
);
585 (void)setlocale(LC_NUMERIC
, "C");
589 Python_RestoreThread(); /* enter python */
591 PyRun_SimpleString((char *)(cmd
));
593 Python_SaveThread(); /* leave python */
595 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
596 if (saved_locale
!= NULL
)
598 (void)setlocale(LC_NUMERIC
, saved_locale
);
599 vim_free(saved_locale
);
603 Python_Lock_Vim(); /* enter vim */
605 #if defined(MACOS) && !defined(MACOS_X_UNIX)
610 #ifndef PY_CAN_RECURSE
613 return; /* keeps lint happy */
620 ex_python(exarg_T
*eap
)
624 script
= script_get(eap
, eap
->arg
);
628 DoPythonCommand(eap
, (char *)eap
->arg
);
630 DoPythonCommand(eap
, (char *)script
);
635 #define BUFFER_SIZE 1024
641 ex_pyfile(exarg_T
*eap
)
643 static char buffer
[BUFFER_SIZE
];
644 const char *file
= (char *)eap
->arg
;
647 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
648 * stdio file pointer, but Vim and the Python DLL are compiled with
649 * different options under Windows, meaning that stdio pointers aren't
650 * compatible between the two. Yuk.
652 * Put the string "execfile('file')" into buffer. But, we need to
653 * escape any backslashes or single quotes in the file name, so that
654 * Python won't mangle the file name.
656 strcpy(buffer
, "execfile('");
657 p
= buffer
+ 10; /* size of "execfile('" */
659 while (*file
&& p
< buffer
+ (BUFFER_SIZE
- 3))
661 if (*file
== '\\' || *file
== '\'')
666 /* If we didn't finish the file name, we hit a buffer overflow */
670 /* Put in the terminating "')" and a null */
675 /* Execute the file */
676 DoPythonCommand(eap
, buffer
);
679 /******************************************************
680 * 2. Python output stream: writes output via [e]msg().
683 /* Implementation functions
686 static PyObject
*OutputGetattr(PyObject
*, char *);
687 static int OutputSetattr(PyObject
*, char *, PyObject
*);
689 static PyObject
*OutputWrite(PyObject
*, PyObject
*);
690 static PyObject
*OutputWritelines(PyObject
*, PyObject
*);
692 typedef void (*writefn
)(char_u
*);
693 static void writer(writefn fn
, char_u
*str
, int n
);
695 /* Output object definition
705 static struct PyMethodDef OutputMethods
[] = {
706 /* name, function, calling, documentation */
707 {"write", OutputWrite
, 1, "" },
708 {"writelines", OutputWritelines
, 1, "" },
709 { NULL
, NULL
, 0, NULL
}
712 static PyTypeObject OutputType
= {
713 PyObject_HEAD_INIT(0)
716 sizeof(OutputObject
),
721 (getattrfunc
) OutputGetattr
,
722 (setattrfunc
) OutputSetattr
,
738 OutputGetattr(PyObject
*self
, char *name
)
740 if (strcmp(name
, "softspace") == 0)
741 return PyInt_FromLong(((OutputObject
*)(self
))->softspace
);
743 return Py_FindMethod(OutputMethods
, self
, name
);
747 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
750 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
754 if (strcmp(name
, "softspace") == 0)
756 if (!PyInt_Check(val
)) {
757 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
761 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
765 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
772 OutputWrite(PyObject
*self
, PyObject
*args
)
776 int error
= ((OutputObject
*)(self
))->error
;
778 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
781 Py_BEGIN_ALLOW_THREADS
783 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
784 Python_Release_Vim();
792 OutputWritelines(PyObject
*self
, PyObject
*args
)
797 int error
= ((OutputObject
*)(self
))->error
;
799 if (!PyArg_ParseTuple(args
, "O", &list
))
803 if (!PyList_Check(list
)) {
804 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
809 n
= PyList_Size(list
);
811 for (i
= 0; i
< n
; ++i
)
813 PyObject
*line
= PyList_GetItem(list
, i
);
817 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
818 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
823 Py_BEGIN_ALLOW_THREADS
825 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
826 Python_Release_Vim();
835 /* Output buffer management
838 static char_u
*buffer
= NULL
;
839 static int buffer_len
= 0;
840 static int buffer_size
= 0;
842 static writefn old_fn
= NULL
;
853 new_size
= buffer_size
;
857 if (new_size
!= buffer_size
)
859 new_buffer
= alloc((unsigned)new_size
);
860 if (new_buffer
== NULL
)
865 memcpy(new_buffer
, buffer
, buffer_len
);
870 buffer_size
= new_size
;
877 if (old_fn
&& buffer_len
)
879 buffer
[buffer_len
] = 0;
887 writer(writefn fn
, char_u
*str
, int n
)
891 if (fn
!= old_fn
&& old_fn
!= NULL
)
896 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
900 buffer_ensure(buffer_len
+ len
+ 1);
902 memcpy(buffer
+ buffer_len
, str
, len
);
904 buffer
[buffer_len
] = 0;
911 /* Put the remaining text into the buffer for later printing */
912 buffer_ensure(buffer_len
+ n
+ 1);
913 memcpy(buffer
+ buffer_len
, str
, n
);
919 static OutputObject Output
=
921 PyObject_HEAD_INIT(&OutputType
)
926 static OutputObject Error
=
928 PyObject_HEAD_INIT(&OutputType
)
937 OutputType
.ob_type
= &PyType_Type
;
939 PySys_SetObject("stdout", (PyObject
*)(void *)&Output
);
940 PySys_SetObject("stderr", (PyObject
*)(void *)&Error
);
942 if (PyErr_Occurred())
944 EMSG(_("E264: Python: Error initialising I/O objects"));
951 /******************************************************
952 * 3. Implementation of the Vim module for Python
955 /* Vim module - Implementation functions
956 * -------------------------------------
959 static PyObject
*VimError
;
961 static PyObject
*VimCommand(PyObject
*, PyObject
*);
962 static PyObject
*VimEval(PyObject
*, PyObject
*);
964 /* Window type - Implementation functions
965 * --------------------------------------
975 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
977 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
979 static PyObject
*WindowNew(win_T
*);
981 static void WindowDestructor(PyObject
*);
982 static PyObject
*WindowGetattr(PyObject
*, char *);
983 static int WindowSetattr(PyObject
*, char *, PyObject
*);
984 static PyObject
*WindowRepr(PyObject
*);
986 /* Buffer type - Implementation functions
987 * --------------------------------------
997 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
999 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1001 static PyObject
*BufferNew (buf_T
*);
1003 static void BufferDestructor(PyObject
*);
1004 static PyObject
*BufferGetattr(PyObject
*, char *);
1005 static PyObject
*BufferRepr(PyObject
*);
1007 static PyInt
BufferLength(PyObject
*);
1008 static PyObject
*BufferItem(PyObject
*, PyInt
);
1009 static PyObject
*BufferSlice(PyObject
*, PyInt
, PyInt
);
1010 static PyInt
BufferAssItem(PyObject
*, PyInt
, PyObject
*);
1011 static PyInt
BufferAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1013 static PyObject
*BufferAppend(PyObject
*, PyObject
*);
1014 static PyObject
*BufferMark(PyObject
*, PyObject
*);
1015 static PyObject
*BufferRange(PyObject
*, PyObject
*);
1017 /* Line range type - Implementation functions
1018 * --------------------------------------
1030 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1032 static PyObject
*RangeNew(buf_T
*, int, int);
1034 static void RangeDestructor(PyObject
*);
1035 static PyObject
*RangeGetattr(PyObject
*, char *);
1036 static PyObject
*RangeRepr(PyObject
*);
1038 static PyInt
RangeLength(PyObject
*);
1039 static PyObject
*RangeItem(PyObject
*, PyInt
);
1040 static PyObject
*RangeSlice(PyObject
*, PyInt
, PyInt
);
1041 static PyInt
RangeAssItem(PyObject
*, PyInt
, PyObject
*);
1042 static PyInt
RangeAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1044 static PyObject
*RangeAppend(PyObject
*, PyObject
*);
1046 /* Window list type - Implementation functions
1047 * -------------------------------------------
1050 static PyInt
WinListLength(PyObject
*);
1051 static PyObject
*WinListItem(PyObject
*, PyInt
);
1053 /* Buffer list type - Implementation functions
1054 * -------------------------------------------
1057 static PyInt
BufListLength(PyObject
*);
1058 static PyObject
*BufListItem(PyObject
*, PyInt
);
1060 /* Current objects type - Implementation functions
1061 * -----------------------------------------------
1064 static PyObject
*CurrentGetattr(PyObject
*, char *);
1065 static int CurrentSetattr(PyObject
*, char *, PyObject
*);
1067 /* Vim module - Definitions
1070 static struct PyMethodDef VimMethods
[] = {
1071 /* name, function, calling, documentation */
1072 {"command", VimCommand
, 1, "" },
1073 {"eval", VimEval
, 1, "" },
1074 { NULL
, NULL
, 0, NULL
}
1077 /* Vim module - Implementation
1081 VimCommand(PyObject
*self
, PyObject
*args
)
1086 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1091 Py_BEGIN_ALLOW_THREADS
1094 do_cmdline_cmd((char_u
*)cmd
);
1095 update_screen(VALID
);
1097 Python_Release_Vim();
1098 Py_END_ALLOW_THREADS
1100 if (VimErrorCheck())
1110 * Function to translate a typval_T into a PyObject; this will recursively
1111 * translate lists/dictionaries into their Python equivalents.
1113 * The depth parameter is too avoid infinite recursion, set it to 1 when
1114 * you call VimToPython.
1117 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1121 char ptrBuf
[NUMBUFLEN
];
1123 /* Avoid infinite recursion */
1131 /* Check if we run into a recursive loop. The item must be in lookupDict
1132 * then and we can use it again. */
1133 sprintf(ptrBuf
, "%ld", (long)our_tv
);
1134 result
= PyDict_GetItemString(lookupDict
, ptrBuf
);
1137 else if (our_tv
->v_type
== VAR_STRING
)
1139 result
= Py_BuildValue("s", our_tv
->vval
.v_string
);
1140 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1142 else if (our_tv
->v_type
== VAR_NUMBER
)
1144 char buf
[NUMBUFLEN
];
1146 /* For backwards compatibility numbers are stored as strings. */
1147 sprintf(buf
, "%ld", (long)our_tv
->vval
.v_number
);
1148 result
= Py_BuildValue("s", buf
);
1149 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1152 else if (our_tv
->v_type
== VAR_FLOAT
)
1154 char buf
[NUMBUFLEN
];
1156 sprintf(buf
, "%f", our_tv
->vval
.v_float
);
1157 result
= Py_BuildValue("s", buf
);
1158 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1161 else if (our_tv
->v_type
== VAR_LIST
)
1163 list_T
*list
= our_tv
->vval
.v_list
;
1166 result
= PyList_New(0);
1167 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1171 for (curr
= list
->lv_first
; curr
!= NULL
; curr
= curr
->li_next
)
1173 newObj
= VimToPython(&curr
->li_tv
, depth
+ 1, lookupDict
);
1174 PyList_Append(result
, newObj
);
1179 else if (our_tv
->v_type
== VAR_DICT
)
1181 result
= PyDict_New();
1182 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1184 if (our_tv
->vval
.v_dict
!= NULL
)
1186 hashtab_T
*ht
= &our_tv
->vval
.v_dict
->dv_hashtab
;
1187 int todo
= ht
->ht_used
;
1191 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1193 if (!HASHITEM_EMPTY(hi
))
1197 di
= dict_lookup(hi
);
1198 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1199 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1216 VimEval(PyObject
*self
, PyObject
*args
)
1222 PyObject
*lookup_dict
;
1224 if (!PyArg_ParseTuple(args
, "s", &expr
))
1227 Py_BEGIN_ALLOW_THREADS
1229 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1231 Python_Release_Vim();
1232 Py_END_ALLOW_THREADS
1236 PyErr_SetVim(_("invalid expression"));
1240 /* Convert the Vim type into a Python type. Create a dictionary that's
1241 * used to check for recursive loops. */
1242 lookup_dict
= PyDict_New();
1243 result
= VimToPython(our_tv
, 1, lookup_dict
);
1244 Py_DECREF(lookup_dict
);
1247 Py_BEGIN_ALLOW_THREADS
1250 Python_Release_Vim();
1251 Py_END_ALLOW_THREADS
1255 PyErr_SetVim(_("expressions disabled at compile time"));
1260 /* Common routines for buffers and line ranges
1261 * -------------------------------------------
1264 CheckBuffer(BufferObject
*this)
1266 if (this->buf
== INVALID_BUFFER_VALUE
)
1268 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1276 RBItem(BufferObject
*self
, PyInt n
, int start
, int end
)
1278 if (CheckBuffer(self
))
1281 if (n
< 0 || n
> end
- start
)
1283 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1287 return GetBufferLine(self
->buf
, n
+start
);
1291 RBSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, int start
, int end
)
1295 if (CheckBuffer(self
))
1298 size
= end
- start
+ 1;
1311 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1315 RBAssItem(BufferObject
*self
, PyInt n
, PyObject
*val
, int start
, int end
, int *new_end
)
1319 if (CheckBuffer(self
))
1322 if (n
< 0 || n
> end
- start
)
1324 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1328 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1332 *new_end
= end
+ len_change
;
1338 RBAssSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
, int start
, int end
, int *new_end
)
1343 /* Self must be a valid buffer */
1344 if (CheckBuffer(self
))
1347 /* Sort out the slice range */
1348 size
= end
- start
+ 1;
1361 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1365 *new_end
= end
+ len_change
;
1371 RBAppend(BufferObject
*self
, PyObject
*args
, int start
, int end
, int *new_end
)
1378 if (CheckBuffer(self
))
1381 max
= n
= end
- start
+ 1;
1383 if (!PyArg_ParseTuple(args
, "O|i", &lines
, &n
))
1386 if (n
< 0 || n
> max
)
1388 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1392 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1396 *new_end
= end
+ len_change
;
1403 /* Buffer object - Definitions
1406 static struct PyMethodDef BufferMethods
[] = {
1407 /* name, function, calling, documentation */
1408 {"append", BufferAppend
, 1, "" },
1409 {"mark", BufferMark
, 1, "" },
1410 {"range", BufferRange
, 1, "" },
1411 { NULL
, NULL
, 0, NULL
}
1414 static PySequenceMethods BufferAsSeq
= {
1415 (PyInquiry
) BufferLength
, /* sq_length, len(x) */
1416 (binaryfunc
) 0, /* BufferConcat, */ /* sq_concat, x+y */
1417 (PyIntArgFunc
) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1418 (PyIntArgFunc
) BufferItem
, /* sq_item, x[i] */
1419 (PyIntIntArgFunc
) BufferSlice
, /* sq_slice, x[i:j] */
1420 (PyIntObjArgProc
) BufferAssItem
, /* sq_ass_item, x[i]=v */
1421 (PyIntIntObjArgProc
) BufferAssSlice
, /* sq_ass_slice, x[i:j]=v */
1424 static PyTypeObject BufferType
= {
1425 PyObject_HEAD_INIT(0)
1428 sizeof(BufferObject
),
1431 (destructor
) BufferDestructor
, /* tp_dealloc, refcount==0 */
1432 (printfunc
) 0, /* tp_print, print x */
1433 (getattrfunc
) BufferGetattr
, /* tp_getattr, x.attr */
1434 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1435 (cmpfunc
) 0, /* tp_compare, x>y */
1436 (reprfunc
) BufferRepr
, /* tp_repr, `x`, print x */
1439 &BufferAsSeq
, /* as sequence */
1442 (hashfunc
) 0, /* tp_hash, dict(x) */
1443 (ternaryfunc
) 0, /* tp_call, x() */
1444 (reprfunc
) 0, /* tp_str, str(x) */
1447 /* Buffer object - Implementation
1451 BufferNew(buf_T
*buf
)
1453 /* We need to handle deletion of buffers underneath us.
1454 * If we add a "b_python_ref" field to the buf_T structure,
1455 * then we can get at it in buf_freeall() in vim. We then
1456 * need to create only ONE Python object per buffer - if
1457 * we try to create a second, just INCREF the existing one
1458 * and return it. The (single) Python object referring to
1459 * the buffer is stored in "b_python_ref".
1460 * Question: what to do on a buf_freeall(). We'll probably
1461 * have to either delete the Python object (DECREF it to
1462 * zero - a bad idea, as it leaves dangling refs!) or
1463 * set the buf_T * value to an invalid value (-1?), which
1464 * means we need checks in all access functions... Bah.
1469 if (buf
->b_python_ref
!= NULL
)
1471 self
= buf
->b_python_ref
;
1476 self
= PyObject_NEW(BufferObject
, &BufferType
);
1480 buf
->b_python_ref
= self
;
1483 return (PyObject
*)(self
);
1487 BufferDestructor(PyObject
*self
)
1489 BufferObject
*this = (BufferObject
*)(self
);
1491 if (this->buf
&& this->buf
!= INVALID_BUFFER_VALUE
)
1492 this->buf
->b_python_ref
= NULL
;
1498 BufferGetattr(PyObject
*self
, char *name
)
1500 BufferObject
*this = (BufferObject
*)(self
);
1502 if (CheckBuffer(this))
1505 if (strcmp(name
, "name") == 0)
1506 return Py_BuildValue("s",this->buf
->b_ffname
);
1507 else if (strcmp(name
, "number") == 0)
1508 return Py_BuildValue("i",this->buf
->b_fnum
);
1509 else if (strcmp(name
,"__members__") == 0)
1510 return Py_BuildValue("[ss]", "name", "number");
1512 return Py_FindMethod(BufferMethods
, self
, name
);
1516 BufferRepr(PyObject
*self
)
1518 static char repr
[100];
1519 BufferObject
*this = (BufferObject
*)(self
);
1521 if (this->buf
== INVALID_BUFFER_VALUE
)
1523 vim_snprintf(repr
, 100, _("<buffer object (deleted) at %8lX>"),
1525 return PyString_FromString(repr
);
1529 char *name
= (char *)this->buf
->b_fname
;
1537 name
= name
+ (35 - len
);
1539 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1541 return PyString_FromString(repr
);
1545 /******************/
1548 BufferLength(PyObject
*self
)
1550 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1551 if (CheckBuffer((BufferObject
*)(self
)))
1552 return -1; /* ??? */
1554 return (((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1558 BufferItem(PyObject
*self
, PyInt n
)
1560 return RBItem((BufferObject
*)(self
), n
, 1,
1561 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1565 BufferSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1567 return RBSlice((BufferObject
*)(self
), lo
, hi
, 1,
1568 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1572 BufferAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1574 return RBAssItem((BufferObject
*)(self
), n
, val
, 1,
1575 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1580 BufferAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1582 return RBAssSlice((BufferObject
*)(self
), lo
, hi
, val
, 1,
1583 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1588 BufferAppend(PyObject
*self
, PyObject
*args
)
1590 return RBAppend((BufferObject
*)(self
), args
, 1,
1591 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1596 BufferMark(PyObject
*self
, PyObject
*args
)
1602 if (CheckBuffer((BufferObject
*)(self
)))
1605 if (!PyArg_ParseTuple(args
, "c", &mark
))
1608 curbuf_save
= curbuf
;
1609 curbuf
= ((BufferObject
*)(self
))->buf
;
1610 posp
= getmark(mark
, FALSE
);
1611 curbuf
= curbuf_save
;
1615 PyErr_SetVim(_("invalid mark name"));
1619 /* Ckeck for keyboard interrupt */
1620 if (VimErrorCheck())
1623 if (posp
->lnum
<= 0)
1625 /* Or raise an error? */
1630 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1634 BufferRange(PyObject
*self
, PyObject
*args
)
1639 if (CheckBuffer((BufferObject
*)(self
)))
1642 if (!PyArg_ParseTuple(args
, "ii", &start
, &end
))
1645 return RangeNew(((BufferObject
*)(self
))->buf
, start
, end
);
1648 /* Line range object - Definitions
1651 static struct PyMethodDef RangeMethods
[] = {
1652 /* name, function, calling, documentation */
1653 {"append", RangeAppend
, 1, "" },
1654 { NULL
, NULL
, 0, NULL
}
1657 static PySequenceMethods RangeAsSeq
= {
1658 (PyInquiry
) RangeLength
, /* sq_length, len(x) */
1659 (binaryfunc
) 0, /* RangeConcat, */ /* sq_concat, x+y */
1660 (PyIntArgFunc
) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1661 (PyIntArgFunc
) RangeItem
, /* sq_item, x[i] */
1662 (PyIntIntArgFunc
) RangeSlice
, /* sq_slice, x[i:j] */
1663 (PyIntObjArgProc
) RangeAssItem
, /* sq_ass_item, x[i]=v */
1664 (PyIntIntObjArgProc
) RangeAssSlice
, /* sq_ass_slice, x[i:j]=v */
1667 static PyTypeObject RangeType
= {
1668 PyObject_HEAD_INIT(0)
1671 sizeof(RangeObject
),
1674 (destructor
) RangeDestructor
, /* tp_dealloc, refcount==0 */
1675 (printfunc
) 0, /* tp_print, print x */
1676 (getattrfunc
) RangeGetattr
, /* tp_getattr, x.attr */
1677 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1678 (cmpfunc
) 0, /* tp_compare, x>y */
1679 (reprfunc
) RangeRepr
, /* tp_repr, `x`, print x */
1682 &RangeAsSeq
, /* as sequence */
1685 (hashfunc
) 0, /* tp_hash, dict(x) */
1686 (ternaryfunc
) 0, /* tp_call, x() */
1687 (reprfunc
) 0, /* tp_str, str(x) */
1690 /* Line range object - Implementation
1694 RangeNew(buf_T
*buf
, int start
, int end
)
1698 self
= PyObject_NEW(RangeObject
, &RangeType
);
1702 bufr
= (BufferObject
*)BufferNew(buf
);
1711 self
->start
= start
;
1714 return (PyObject
*)(self
);
1718 RangeDestructor(PyObject
*self
)
1720 Py_DECREF(((RangeObject
*)(self
))->buf
);
1725 RangeGetattr(PyObject
*self
, char *name
)
1727 if (strcmp(name
, "start") == 0)
1728 return Py_BuildValue("i",((RangeObject
*)(self
))->start
- 1);
1729 else if (strcmp(name
, "end") == 0)
1730 return Py_BuildValue("i",((RangeObject
*)(self
))->end
- 1);
1732 return Py_FindMethod(RangeMethods
, self
, name
);
1736 RangeRepr(PyObject
*self
)
1738 static char repr
[100];
1739 RangeObject
*this = (RangeObject
*)(self
);
1741 if (this->buf
->buf
== INVALID_BUFFER_VALUE
)
1743 vim_snprintf(repr
, 100, "<range object (for deleted buffer) at %8lX>",
1745 return PyString_FromString(repr
);
1749 char *name
= (char *)this->buf
->buf
->b_fname
;
1757 name
= name
+ (45 - len
);
1759 vim_snprintf(repr
, 100, "<range %s%s (%d:%d)>",
1760 len
> 45 ? "..." : "", name
,
1761 this->start
, this->end
);
1763 return PyString_FromString(repr
);
1770 RangeLength(PyObject
*self
)
1772 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1773 if (CheckBuffer(((RangeObject
*)(self
))->buf
))
1774 return -1; /* ??? */
1776 return (((RangeObject
*)(self
))->end
- ((RangeObject
*)(self
))->start
+ 1);
1780 RangeItem(PyObject
*self
, PyInt n
)
1782 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1783 ((RangeObject
*)(self
))->start
,
1784 ((RangeObject
*)(self
))->end
);
1788 RangeSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1790 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1791 ((RangeObject
*)(self
))->start
,
1792 ((RangeObject
*)(self
))->end
);
1796 RangeAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1798 return RBAssItem(((RangeObject
*)(self
))->buf
, n
, val
,
1799 ((RangeObject
*)(self
))->start
,
1800 ((RangeObject
*)(self
))->end
,
1801 &((RangeObject
*)(self
))->end
);
1805 RangeAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1807 return RBAssSlice(((RangeObject
*)(self
))->buf
, lo
, hi
, val
,
1808 ((RangeObject
*)(self
))->start
,
1809 ((RangeObject
*)(self
))->end
,
1810 &((RangeObject
*)(self
))->end
);
1814 RangeAppend(PyObject
*self
, PyObject
*args
)
1816 return RBAppend(((RangeObject
*)(self
))->buf
, args
,
1817 ((RangeObject
*)(self
))->start
,
1818 ((RangeObject
*)(self
))->end
,
1819 &((RangeObject
*)(self
))->end
);
1822 /* Buffer list object - Definitions
1831 static PySequenceMethods BufListAsSeq
= {
1832 (PyInquiry
) BufListLength
, /* sq_length, len(x) */
1833 (binaryfunc
) 0, /* sq_concat, x+y */
1834 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
1835 (PyIntArgFunc
) BufListItem
, /* sq_item, x[i] */
1836 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
1837 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
1838 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
1841 static PyTypeObject BufListType
= {
1842 PyObject_HEAD_INIT(0)
1845 sizeof(BufListObject
),
1848 (destructor
) 0, /* tp_dealloc, refcount==0 */
1849 (printfunc
) 0, /* tp_print, print x */
1850 (getattrfunc
) 0, /* tp_getattr, x.attr */
1851 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1852 (cmpfunc
) 0, /* tp_compare, x>y */
1853 (reprfunc
) 0, /* tp_repr, `x`, print x */
1856 &BufListAsSeq
, /* as sequence */
1859 (hashfunc
) 0, /* tp_hash, dict(x) */
1860 (ternaryfunc
) 0, /* tp_call, x() */
1861 (reprfunc
) 0, /* tp_str, str(x) */
1864 /* Buffer list object - Implementation
1869 BufListLength(PyObject
*self
)
1871 buf_T
*b
= firstbuf
;
1885 BufListItem(PyObject
*self
, PyInt n
)
1889 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1892 return BufferNew(b
);
1895 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
1899 /* Window object - Definitions
1902 static struct PyMethodDef WindowMethods
[] = {
1903 /* name, function, calling, documentation */
1904 { NULL
, NULL
, 0, NULL
}
1907 static PyTypeObject WindowType
= {
1908 PyObject_HEAD_INIT(0)
1911 sizeof(WindowObject
),
1914 (destructor
) WindowDestructor
, /* tp_dealloc, refcount==0 */
1915 (printfunc
) 0, /* tp_print, print x */
1916 (getattrfunc
) WindowGetattr
, /* tp_getattr, x.attr */
1917 (setattrfunc
) WindowSetattr
, /* tp_setattr, x.attr=v */
1918 (cmpfunc
) 0, /* tp_compare, x>y */
1919 (reprfunc
) WindowRepr
, /* tp_repr, `x`, print x */
1922 0, /* as sequence */
1925 (hashfunc
) 0, /* tp_hash, dict(x) */
1926 (ternaryfunc
) 0, /* tp_call, x() */
1927 (reprfunc
) 0, /* tp_str, str(x) */
1930 /* Window object - Implementation
1934 WindowNew(win_T
*win
)
1936 /* We need to handle deletion of windows underneath us.
1937 * If we add a "w_python_ref" field to the win_T structure,
1938 * then we can get at it in win_free() in vim. We then
1939 * need to create only ONE Python object per window - if
1940 * we try to create a second, just INCREF the existing one
1941 * and return it. The (single) Python object referring to
1942 * the window is stored in "w_python_ref".
1943 * On a win_free() we set the Python object's win_T* field
1944 * to an invalid value. We trap all uses of a window
1945 * object, and reject them if the win_T* field is invalid.
1950 if (win
->w_python_ref
)
1952 self
= win
->w_python_ref
;
1957 self
= PyObject_NEW(WindowObject
, &WindowType
);
1961 win
->w_python_ref
= self
;
1964 return (PyObject
*)(self
);
1968 WindowDestructor(PyObject
*self
)
1970 WindowObject
*this = (WindowObject
*)(self
);
1972 if (this->win
&& this->win
!= INVALID_WINDOW_VALUE
)
1973 this->win
->w_python_ref
= NULL
;
1979 CheckWindow(WindowObject
*this)
1981 if (this->win
== INVALID_WINDOW_VALUE
)
1983 PyErr_SetVim(_("attempt to refer to deleted window"));
1991 WindowGetattr(PyObject
*self
, char *name
)
1993 WindowObject
*this = (WindowObject
*)(self
);
1995 if (CheckWindow(this))
1998 if (strcmp(name
, "buffer") == 0)
1999 return (PyObject
*)BufferNew(this->win
->w_buffer
);
2000 else if (strcmp(name
, "cursor") == 0)
2002 pos_T
*pos
= &this->win
->w_cursor
;
2004 return Py_BuildValue("(ll)", (long)(pos
->lnum
), (long)(pos
->col
));
2006 else if (strcmp(name
, "height") == 0)
2007 return Py_BuildValue("l", (long)(this->win
->w_height
));
2008 #ifdef FEAT_VERTSPLIT
2009 else if (strcmp(name
, "width") == 0)
2010 return Py_BuildValue("l", (long)(W_WIDTH(this->win
)));
2012 else if (strcmp(name
,"__members__") == 0)
2013 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2015 return Py_FindMethod(WindowMethods
, self
, name
);
2019 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
2021 WindowObject
*this = (WindowObject
*)(self
);
2023 if (CheckWindow(this))
2026 if (strcmp(name
, "buffer") == 0)
2028 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2031 else if (strcmp(name
, "cursor") == 0)
2036 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2039 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2041 PyErr_SetVim(_("cursor position outside buffer"));
2045 /* Check for keyboard interrupts */
2046 if (VimErrorCheck())
2049 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2051 this->win
->w_cursor
.lnum
= lnum
;
2052 this->win
->w_cursor
.col
= col
;
2053 update_screen(VALID
);
2057 else if (strcmp(name
, "height") == 0)
2062 if (!PyArg_Parse(val
, "i", &height
))
2066 need_mouse_correct
= TRUE
;
2070 win_setheight(height
);
2073 /* Check for keyboard interrupts */
2074 if (VimErrorCheck())
2079 #ifdef FEAT_VERTSPLIT
2080 else if (strcmp(name
, "width") == 0)
2085 if (!PyArg_Parse(val
, "i", &width
))
2089 need_mouse_correct
= TRUE
;
2093 win_setwidth(width
);
2096 /* Check for keyboard interrupts */
2097 if (VimErrorCheck())
2105 PyErr_SetString(PyExc_AttributeError
, name
);
2111 WindowRepr(PyObject
*self
)
2113 static char repr
[100];
2114 WindowObject
*this = (WindowObject
*)(self
);
2116 if (this->win
== INVALID_WINDOW_VALUE
)
2118 vim_snprintf(repr
, 100, _("<window object (deleted) at %.8lX>"),
2120 return PyString_FromString(repr
);
2127 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2131 vim_snprintf(repr
, 100, _("<window object (unknown) at %.8lX>"),
2134 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2136 return PyString_FromString(repr
);
2140 /* Window list object - Definitions
2149 static PySequenceMethods WinListAsSeq
= {
2150 (PyInquiry
) WinListLength
, /* sq_length, len(x) */
2151 (binaryfunc
) 0, /* sq_concat, x+y */
2152 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
2153 (PyIntArgFunc
) WinListItem
, /* sq_item, x[i] */
2154 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
2155 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
2156 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
2159 static PyTypeObject WinListType
= {
2160 PyObject_HEAD_INIT(0)
2163 sizeof(WinListObject
),
2166 (destructor
) 0, /* tp_dealloc, refcount==0 */
2167 (printfunc
) 0, /* tp_print, print x */
2168 (getattrfunc
) 0, /* tp_getattr, x.attr */
2169 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
2170 (cmpfunc
) 0, /* tp_compare, x>y */
2171 (reprfunc
) 0, /* tp_repr, `x`, print x */
2174 &WinListAsSeq
, /* as sequence */
2177 (hashfunc
) 0, /* tp_hash, dict(x) */
2178 (ternaryfunc
) 0, /* tp_call, x() */
2179 (reprfunc
) 0, /* tp_str, str(x) */
2182 /* Window list object - Implementation
2186 WinListLength(PyObject
*self
)
2188 win_T
*w
= firstwin
;
2202 WinListItem(PyObject
*self
, PyInt n
)
2206 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2208 return WindowNew(w
);
2210 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2214 /* Current items object - Definitions
2223 static PyTypeObject CurrentType
= {
2224 PyObject_HEAD_INIT(0)
2227 sizeof(CurrentObject
),
2230 (destructor
) 0, /* tp_dealloc, refcount==0 */
2231 (printfunc
) 0, /* tp_print, print x */
2232 (getattrfunc
) CurrentGetattr
, /* tp_getattr, x.attr */
2233 (setattrfunc
) CurrentSetattr
, /* tp_setattr, x.attr=v */
2234 (cmpfunc
) 0, /* tp_compare, x>y */
2235 (reprfunc
) 0, /* tp_repr, `x`, print x */
2238 0, /* as sequence */
2241 (hashfunc
) 0, /* tp_hash, dict(x) */
2242 (ternaryfunc
) 0, /* tp_call, x() */
2243 (reprfunc
) 0, /* tp_str, str(x) */
2246 /* Current items object - Implementation
2250 CurrentGetattr(PyObject
*self
, char *name
)
2252 if (strcmp(name
, "buffer") == 0)
2253 return (PyObject
*)BufferNew(curbuf
);
2254 else if (strcmp(name
, "window") == 0)
2255 return (PyObject
*)WindowNew(curwin
);
2256 else if (strcmp(name
, "line") == 0)
2257 return GetBufferLine(curbuf
, (int)curwin
->w_cursor
.lnum
);
2258 else if (strcmp(name
, "range") == 0)
2259 return RangeNew(curbuf
, RangeStart
, RangeEnd
);
2260 else if (strcmp(name
,"__members__") == 0)
2261 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2264 PyErr_SetString(PyExc_AttributeError
, name
);
2271 CurrentSetattr(PyObject
*self
, char *name
, PyObject
*value
)
2273 if (strcmp(name
, "line") == 0)
2275 if (SetBufferLine(curbuf
, (int)curwin
->w_cursor
.lnum
, value
, NULL
) == FAIL
)
2282 PyErr_SetString(PyExc_AttributeError
, name
);
2287 /* External interface
2291 python_buffer_free(buf_T
*buf
)
2293 if (buf
->b_python_ref
!= NULL
)
2295 BufferObject
*bp
= buf
->b_python_ref
;
2296 bp
->buf
= INVALID_BUFFER_VALUE
;
2297 buf
->b_python_ref
= NULL
;
2301 #if defined(FEAT_WINDOWS) || defined(PROTO)
2303 python_window_free(win_T
*win
)
2305 if (win
->w_python_ref
!= NULL
)
2307 WindowObject
*wp
= win
->w_python_ref
;
2308 wp
->win
= INVALID_WINDOW_VALUE
;
2309 win
->w_python_ref
= NULL
;
2314 static BufListObject TheBufferList
=
2316 PyObject_HEAD_INIT(&BufListType
)
2319 static WinListObject TheWindowList
=
2321 PyObject_HEAD_INIT(&WinListType
)
2324 static CurrentObject TheCurrent
=
2326 PyObject_HEAD_INIT(&CurrentType
)
2330 PythonMod_Init(void)
2334 static char *(argv
[2]) = {"", NULL
};
2337 BufferType
.ob_type
= &PyType_Type
;
2338 RangeType
.ob_type
= &PyType_Type
;
2339 WindowType
.ob_type
= &PyType_Type
;
2340 BufListType
.ob_type
= &PyType_Type
;
2341 WinListType
.ob_type
= &PyType_Type
;
2342 CurrentType
.ob_type
= &PyType_Type
;
2344 /* Set sys.argv[] to avoid a crash in warn(). */
2345 PySys_SetArgv(1, argv
);
2347 mod
= Py_InitModule("vim", VimMethods
);
2348 dict
= PyModule_GetDict(mod
);
2350 VimError
= Py_BuildValue("s", "vim.error");
2352 PyDict_SetItemString(dict
, "error", VimError
);
2353 PyDict_SetItemString(dict
, "buffers", (PyObject
*)(void *)&TheBufferList
);
2354 PyDict_SetItemString(dict
, "current", (PyObject
*)(void *)&TheCurrent
);
2355 PyDict_SetItemString(dict
, "windows", (PyObject
*)(void *)&TheWindowList
);
2357 if (PyErr_Occurred())
2363 /*************************************************************************
2364 * 4. Utility functions for handling the interface between Vim and Python.
2367 /* Get a line from the specified buffer. The line number is
2368 * in Vim format (1-based). The line is returned as a Python
2372 GetBufferLine(buf_T
*buf
, int n
)
2374 return LineToString((char *)ml_get_buf(buf
, (linenr_T
)n
, FALSE
));
2377 /* Get a list of lines from the specified buffer. The line numbers
2378 * are in Vim format (1-based). The range is from lo up to, but not
2379 * including, hi. The list is returned as a Python list of string objects.
2382 GetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
)
2386 PyObject
*list
= PyList_New(n
);
2391 for (i
= 0; i
< n
; ++i
)
2393 PyObject
*str
= LineToString((char *)ml_get_buf(buf
, (linenr_T
)(lo
+i
), FALSE
));
2395 /* Error check - was the Python string creation OK? */
2402 /* Set the list item */
2403 if (PyList_SetItem(list
, i
, str
))
2411 /* The ownership of the Python list is passed to the caller (ie,
2412 * the caller should Py_DECREF() the object when it is finished
2420 * Check if deleting lines made the cursor position invalid.
2421 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2425 py_fix_cursor(int lo
, int hi
, int extra
)
2427 if (curwin
->w_cursor
.lnum
>= lo
)
2429 /* Adjust the cursor position if it's in/after the changed
2431 if (curwin
->w_cursor
.lnum
>= hi
)
2433 curwin
->w_cursor
.lnum
+= extra
;
2438 curwin
->w_cursor
.lnum
= lo
;
2443 changed_cline_bef_curs();
2445 invalidate_botline();
2448 /* Replace a line in the specified buffer. The line number is
2449 * in Vim format (1-based). The replacement line is given as
2450 * a Python string object. The object is checked for validity
2451 * and correct format. Errors are returned as a value of FAIL.
2452 * The return value is OK on success.
2453 * If OK is returned and len_change is not NULL, *len_change
2454 * is set to the change in the buffer length.
2457 SetBufferLine(buf_T
*buf
, int n
, PyObject
*line
, int *len_change
)
2459 /* First of all, we check the thpe of the supplied Python object.
2460 * There are three cases:
2461 * 1. NULL, or None - this is a deletion.
2462 * 2. A string - this is a replacement.
2463 * 3. Anything else - this is an error.
2465 if (line
== Py_None
|| line
== NULL
)
2467 buf_T
*savebuf
= curbuf
;
2472 if (u_savedel((linenr_T
)n
, 1L) == FAIL
)
2473 PyErr_SetVim(_("cannot save undo information"));
2474 else if (ml_delete((linenr_T
)n
, FALSE
) == FAIL
)
2475 PyErr_SetVim(_("cannot delete line"));
2478 deleted_lines_mark((linenr_T
)n
, 1L);
2479 if (buf
== curwin
->w_buffer
)
2480 py_fix_cursor(n
, n
+ 1, -1);
2485 if (PyErr_Occurred() || VimErrorCheck())
2493 else if (PyString_Check(line
))
2495 char *save
= StringToLine(line
);
2496 buf_T
*savebuf
= curbuf
;
2501 /* We do not need to free "save" if ml_replace() consumes it. */
2505 if (u_savesub((linenr_T
)n
) == FAIL
)
2507 PyErr_SetVim(_("cannot save undo information"));
2510 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2512 PyErr_SetVim(_("cannot replace line"));
2516 changed_bytes((linenr_T
)n
, 0);
2520 /* Check that the cursor is not beyond the end of the line now. */
2521 if (buf
== curwin
->w_buffer
)
2524 if (PyErr_Occurred() || VimErrorCheck())
2534 PyErr_BadArgument();
2539 /* Replace a range of lines in the specified buffer. The line numbers are in
2540 * Vim format (1-based). The range is from lo up to, but not including, hi.
2541 * The replacement lines are given as a Python list of string objects. The
2542 * list is checked for validity and correct format. Errors are returned as a
2543 * value of FAIL. The return value is OK on success.
2544 * If OK is returned and len_change is not NULL, *len_change
2545 * is set to the change in the buffer length.
2548 SetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
, PyObject
*list
, int *len_change
)
2550 /* First of all, we check the thpe of the supplied Python object.
2551 * There are three cases:
2552 * 1. NULL, or None - this is a deletion.
2553 * 2. A list - this is a replacement.
2554 * 3. Anything else - this is an error.
2556 if (list
== Py_None
|| list
== NULL
)
2560 buf_T
*savebuf
= curbuf
;
2565 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2566 PyErr_SetVim(_("cannot save undo information"));
2569 for (i
= 0; i
< n
; ++i
)
2571 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2573 PyErr_SetVim(_("cannot delete line"));
2577 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2579 if (buf
== curwin
->w_buffer
)
2580 py_fix_cursor(lo
, hi
, -n
);
2585 if (PyErr_Occurred() || VimErrorCheck())
2593 else if (PyList_Check(list
))
2596 PyInt new_len
= PyList_Size(list
);
2597 PyInt old_len
= hi
- lo
;
2598 int extra
= 0; /* lines added to text, can be negative */
2602 if (new_len
== 0) /* avoid allocating zero bytes */
2606 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
2614 for (i
= 0; i
< new_len
; ++i
)
2616 PyObject
*line
= PyList_GetItem(list
, i
);
2618 array
[i
] = StringToLine(line
);
2619 if (array
[i
] == NULL
)
2622 vim_free(array
[--i
]);
2633 if (u_save((linenr_T
)(lo
-1), (linenr_T
)hi
) == FAIL
)
2634 PyErr_SetVim(_("cannot save undo information"));
2636 /* If the size of the range is reducing (ie, new_len < old_len) we
2637 * need to delete some old_len. We do this at the start, by
2638 * repeatedly deleting line "lo".
2640 if (!PyErr_Occurred())
2642 for (i
= 0; i
< old_len
- new_len
; ++i
)
2643 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2645 PyErr_SetVim(_("cannot delete line"));
2651 /* For as long as possible, replace the existing old_len with the
2652 * new old_len. This is a more efficient operation, as it requires
2653 * less memory allocation and freeing.
2655 if (!PyErr_Occurred())
2657 for (i
= 0; i
< old_len
&& i
< new_len
; ++i
)
2658 if (ml_replace((linenr_T
)(lo
+i
), (char_u
*)array
[i
], FALSE
)
2661 PyErr_SetVim(_("cannot replace line"));
2668 /* Now we may need to insert the remaining new old_len. If we do, we
2669 * must free the strings as we finish with them (we can't pass the
2670 * responsibility to vim in this case).
2672 if (!PyErr_Occurred())
2676 if (ml_append((linenr_T
)(lo
+ i
- 1),
2677 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2679 PyErr_SetVim(_("cannot insert line"));
2688 /* Free any left-over old_len, as a result of an error */
2695 /* Free the array of old_len. All of its contents have now
2696 * been dealt with (either freed, or the responsibility passed
2701 /* Adjust marks. Invalidate any which lie in the
2702 * changed range, and move any in the remainder of the buffer.
2704 mark_adjust((linenr_T
)lo
, (linenr_T
)(hi
- 1),
2705 (long)MAXLNUM
, (long)extra
);
2706 changed_lines((linenr_T
)lo
, 0, (linenr_T
)hi
, (long)extra
);
2708 if (buf
== curwin
->w_buffer
)
2709 py_fix_cursor(lo
, hi
, extra
);
2713 if (PyErr_Occurred() || VimErrorCheck())
2717 *len_change
= new_len
- old_len
;
2723 PyErr_BadArgument();
2728 /* Insert a number of lines into the specified buffer after the specifed line.
2729 * The line number is in Vim format (1-based). The lines to be inserted are
2730 * given as a Python list of string objects or as a single string. The lines
2731 * to be added are checked for validity and correct format. Errors are
2732 * returned as a value of FAIL. The return value is OK on success.
2733 * If OK is returned and len_change is not NULL, *len_change
2734 * is set to the change in the buffer length.
2737 InsertBufferLines(buf_T
*buf
, int n
, PyObject
*lines
, int *len_change
)
2739 /* First of all, we check the type of the supplied Python object.
2740 * It must be a string or a list, or the call is in error.
2742 if (PyString_Check(lines
))
2744 char *str
= StringToLine(lines
);
2755 if (u_save((linenr_T
)n
, (linenr_T
)(n
+1)) == FAIL
)
2756 PyErr_SetVim(_("cannot save undo information"));
2757 else if (ml_append((linenr_T
)n
, (char_u
*)str
, 0, FALSE
) == FAIL
)
2758 PyErr_SetVim(_("cannot insert line"));
2760 appended_lines_mark((linenr_T
)n
, 1L);
2764 update_screen(VALID
);
2766 if (PyErr_Occurred() || VimErrorCheck())
2774 else if (PyList_Check(lines
))
2777 PyInt size
= PyList_Size(lines
);
2781 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2788 for (i
= 0; i
< size
; ++i
)
2790 PyObject
*line
= PyList_GetItem(lines
, i
);
2791 array
[i
] = StringToLine(line
);
2793 if (array
[i
] == NULL
)
2796 vim_free(array
[--i
]);
2807 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2808 PyErr_SetVim(_("cannot save undo information"));
2811 for (i
= 0; i
< size
; ++i
)
2813 if (ml_append((linenr_T
)(n
+ i
),
2814 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2816 PyErr_SetVim(_("cannot insert line"));
2818 /* Free the rest of the lines */
2820 vim_free(array
[i
++]);
2827 appended_lines_mark((linenr_T
)n
, (long)i
);
2830 /* Free the array of lines. All of its contents have now
2836 update_screen(VALID
);
2838 if (PyErr_Occurred() || VimErrorCheck())
2848 PyErr_BadArgument();
2853 /* Convert a Vim line into a Python string.
2854 * All internal newlines are replaced by null characters.
2856 * On errors, the Python exception data is set, and NULL is returned.
2859 LineToString(const char *str
)
2862 PyInt len
= strlen(str
);
2865 /* Allocate an Python string object, with uninitialised contents. We
2866 * must do it this way, so that we can modify the string in place
2867 * later. See the Python source, Objects/stringobject.c for details.
2869 result
= PyString_FromStringAndSize(NULL
, len
);
2873 p
= PyString_AsString(result
);
2889 /* Convert a Python string into a Vim line.
2891 * The result is in allocated memory. All internal nulls are replaced by
2892 * newline characters. It is an error for the string to contain newline
2895 * On errors, the Python exception data is set, and NULL is returned.
2898 StringToLine(PyObject
*obj
)
2906 if (obj
== NULL
|| !PyString_Check(obj
))
2908 PyErr_BadArgument();
2912 str
= PyString_AsString(obj
);
2913 len
= PyString_Size(obj
);
2916 * Error checking: String must not contain newlines, as we
2917 * are replacing a single line, and we must replace it with
2919 * A trailing newline is removed, so that append(f.readlines()) works.
2921 p
= memchr(str
, '\n', len
);
2924 if (p
== str
+ len
- 1)
2928 PyErr_SetVim(_("string cannot contain newlines"));
2933 /* Create a copy of the string, with internal nulls replaced by
2934 * newline characters, as is the vim convention.
2936 save
= (char *)alloc((unsigned)(len
+1));
2943 for (i
= 0; i
< len
; ++i
)
2956 /* Check to see whether a Vim error has been reported, or a keyboard
2957 * interrupt has been detected.
2964 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2967 else if (did_emsg
&& !PyErr_Occurred())
2969 PyErr_SetNone(VimError
);
2977 /* Don't generate a prototype for the next function, it generates an error on
2978 * newer Python versions. */
2979 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
2982 Py_GetProgramName(void)
2986 #endif /* Python 1.4 */