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 /* This makes if_python.c compile without warnings against Python 2.5
94 * on Win32 and Win64. */
95 #undef PyRun_SimpleString
97 #undef PyArg_ParseTuple
100 #undef Py_InitModule4_64
105 # define PyArg_Parse dll_PyArg_Parse
106 # define PyArg_ParseTuple dll_PyArg_ParseTuple
107 # define PyDict_SetItemString dll_PyDict_SetItemString
108 # define PyErr_BadArgument dll_PyErr_BadArgument
109 # define PyErr_Clear dll_PyErr_Clear
110 # define PyErr_NoMemory dll_PyErr_NoMemory
111 # define PyErr_Occurred dll_PyErr_Occurred
112 # define PyErr_SetNone dll_PyErr_SetNone
113 # define PyErr_SetString dll_PyErr_SetString
114 # define PyEval_InitThreads dll_PyEval_InitThreads
115 # define PyEval_RestoreThread dll_PyEval_RestoreThread
116 # define PyEval_SaveThread dll_PyEval_SaveThread
117 # ifdef PY_CAN_RECURSE
118 # define PyGILState_Ensure dll_PyGILState_Ensure
119 # define PyGILState_Release dll_PyGILState_Release
121 # define PyInt_AsLong dll_PyInt_AsLong
122 # define PyInt_FromLong dll_PyInt_FromLong
123 # define PyInt_Type (*dll_PyInt_Type)
124 # define PyList_GetItem dll_PyList_GetItem
125 # define PyList_Append dll_PyList_Append
126 # define PyList_New dll_PyList_New
127 # define PyList_SetItem dll_PyList_SetItem
128 # define PyList_Size dll_PyList_Size
129 # define PyList_Type (*dll_PyList_Type)
130 # define PyImport_ImportModule dll_PyImport_ImportModule
131 # define PyDict_New dll_PyDict_New
132 # define PyDict_GetItemString dll_PyDict_GetItemString
133 # define PyModule_GetDict dll_PyModule_GetDict
134 # define PyRun_SimpleString dll_PyRun_SimpleString
135 # define PyString_AsString dll_PyString_AsString
136 # define PyString_FromString dll_PyString_FromString
137 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
138 # define PyString_Size dll_PyString_Size
139 # define PyString_Type (*dll_PyString_Type)
140 # define PySys_SetObject dll_PySys_SetObject
141 # define PySys_SetArgv dll_PySys_SetArgv
142 # define PyType_Type (*dll_PyType_Type)
143 # define Py_BuildValue dll_Py_BuildValue
144 # define Py_FindMethod dll_Py_FindMethod
145 # define Py_InitModule4 dll_Py_InitModule4
146 # define Py_Initialize dll_Py_Initialize
147 # define Py_Finalize dll_Py_Finalize
148 # define Py_IsInitialized dll_Py_IsInitialized
149 # define _PyObject_New dll__PyObject_New
150 # define _Py_NoneStruct (*dll__Py_NoneStruct)
151 # define PyObject_Init dll__PyObject_Init
152 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
153 # define PyType_IsSubtype dll_PyType_IsSubtype
155 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
156 # define PyObject_Malloc dll_PyObject_Malloc
157 # define PyObject_Free dll_PyObject_Free
161 * Pointers for dynamic link
163 static int(*dll_PyArg_Parse
)(PyObject
*, char *, ...);
164 static int(*dll_PyArg_ParseTuple
)(PyObject
*, char *, ...);
165 static int(*dll_PyDict_SetItemString
)(PyObject
*dp
, char *key
, PyObject
*item
);
166 static int(*dll_PyErr_BadArgument
)(void);
167 static void(*dll_PyErr_Clear
)(void);
168 static PyObject
*(*dll_PyErr_NoMemory
)(void);
169 static PyObject
*(*dll_PyErr_Occurred
)(void);
170 static void(*dll_PyErr_SetNone
)(PyObject
*);
171 static void(*dll_PyErr_SetString
)(PyObject
*, const char *);
172 static void(*dll_PyEval_InitThreads
)(void);
173 static void(*dll_PyEval_RestoreThread
)(PyThreadState
*);
174 static PyThreadState
*(*dll_PyEval_SaveThread
)(void);
175 # ifdef PY_CAN_RECURSE
176 static PyGILState_STATE (*dll_PyGILState_Ensure
)(void);
177 static void (*dll_PyGILState_Release
)(PyGILState_STATE
);
179 static long(*dll_PyInt_AsLong
)(PyObject
*);
180 static PyObject
*(*dll_PyInt_FromLong
)(long);
181 static PyTypeObject
* dll_PyInt_Type
;
182 static PyObject
*(*dll_PyList_GetItem
)(PyObject
*, PyInt
);
183 static PyObject
*(*dll_PyList_Append
)(PyObject
*, PyObject
*);
184 static PyObject
*(*dll_PyList_New
)(PyInt size
);
185 static int(*dll_PyList_SetItem
)(PyObject
*, PyInt
, PyObject
*);
186 static PyInt(*dll_PyList_Size
)(PyObject
*);
187 static PyTypeObject
* dll_PyList_Type
;
188 static PyObject
*(*dll_PyImport_ImportModule
)(const char *);
189 static PyObject
*(*dll_PyDict_New
)(void);
190 static PyObject
*(*dll_PyDict_GetItemString
)(PyObject
*, const char *);
191 static PyObject
*(*dll_PyModule_GetDict
)(PyObject
*);
192 static int(*dll_PyRun_SimpleString
)(char *);
193 static char*(*dll_PyString_AsString
)(PyObject
*);
194 static PyObject
*(*dll_PyString_FromString
)(const char *);
195 static PyObject
*(*dll_PyString_FromStringAndSize
)(const char *, PyInt
);
196 static PyInt(*dll_PyString_Size
)(PyObject
*);
197 static PyTypeObject
* dll_PyString_Type
;
198 static int(*dll_PySys_SetObject
)(char *, PyObject
*);
199 static int(*dll_PySys_SetArgv
)(int, char **);
200 static PyTypeObject
* dll_PyType_Type
;
201 static PyObject
*(*dll_Py_BuildValue
)(char *, ...);
202 static PyObject
*(*dll_Py_FindMethod
)(struct PyMethodDef
[], PyObject
*, char *);
203 static PyObject
*(*dll_Py_InitModule4
)(char *, struct PyMethodDef
*, char *, PyObject
*, int);
204 static void(*dll_Py_Initialize
)(void);
205 static void(*dll_Py_Finalize
)(void);
206 static int(*dll_Py_IsInitialized
)(void);
207 static PyObject
*(*dll__PyObject_New
)(PyTypeObject
*, PyObject
*);
208 static PyObject
*(*dll__PyObject_Init
)(PyObject
*, PyTypeObject
*);
209 static PyObject
* dll__Py_NoneStruct
;
210 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
211 static int (*dll_PyType_IsSubtype
)(PyTypeObject
*, PyTypeObject
*);
213 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
214 static void* (*dll_PyObject_Malloc
)(size_t);
215 static void (*dll_PyObject_Free
)(void*);
218 static HINSTANCE hinstPython
= 0; /* Instance of python.dll */
220 /* Imported exception objects */
221 static PyObject
*imp_PyExc_AttributeError
;
222 static PyObject
*imp_PyExc_IndexError
;
223 static PyObject
*imp_PyExc_KeyboardInterrupt
;
224 static PyObject
*imp_PyExc_TypeError
;
225 static PyObject
*imp_PyExc_ValueError
;
227 # define PyExc_AttributeError imp_PyExc_AttributeError
228 # define PyExc_IndexError imp_PyExc_IndexError
229 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
230 # define PyExc_TypeError imp_PyExc_TypeError
231 # define PyExc_ValueError imp_PyExc_ValueError
234 * Table of name to function pointer of python.
236 # define PYTHON_PROC FARPROC
241 } python_funcname_table
[] =
243 {"PyArg_Parse", (PYTHON_PROC
*)&dll_PyArg_Parse
},
244 {"PyArg_ParseTuple", (PYTHON_PROC
*)&dll_PyArg_ParseTuple
},
245 {"PyDict_SetItemString", (PYTHON_PROC
*)&dll_PyDict_SetItemString
},
246 {"PyErr_BadArgument", (PYTHON_PROC
*)&dll_PyErr_BadArgument
},
247 {"PyErr_Clear", (PYTHON_PROC
*)&dll_PyErr_Clear
},
248 {"PyErr_NoMemory", (PYTHON_PROC
*)&dll_PyErr_NoMemory
},
249 {"PyErr_Occurred", (PYTHON_PROC
*)&dll_PyErr_Occurred
},
250 {"PyErr_SetNone", (PYTHON_PROC
*)&dll_PyErr_SetNone
},
251 {"PyErr_SetString", (PYTHON_PROC
*)&dll_PyErr_SetString
},
252 {"PyEval_InitThreads", (PYTHON_PROC
*)&dll_PyEval_InitThreads
},
253 {"PyEval_RestoreThread", (PYTHON_PROC
*)&dll_PyEval_RestoreThread
},
254 {"PyEval_SaveThread", (PYTHON_PROC
*)&dll_PyEval_SaveThread
},
255 # ifdef PY_CAN_RECURSE
256 {"PyGILState_Ensure", (PYTHON_PROC
*)&dll_PyGILState_Ensure
},
257 {"PyGILState_Release", (PYTHON_PROC
*)&dll_PyGILState_Release
},
259 {"PyInt_AsLong", (PYTHON_PROC
*)&dll_PyInt_AsLong
},
260 {"PyInt_FromLong", (PYTHON_PROC
*)&dll_PyInt_FromLong
},
261 {"PyInt_Type", (PYTHON_PROC
*)&dll_PyInt_Type
},
262 {"PyList_GetItem", (PYTHON_PROC
*)&dll_PyList_GetItem
},
263 {"PyList_Append", (PYTHON_PROC
*)&dll_PyList_Append
},
264 {"PyList_New", (PYTHON_PROC
*)&dll_PyList_New
},
265 {"PyList_SetItem", (PYTHON_PROC
*)&dll_PyList_SetItem
},
266 {"PyList_Size", (PYTHON_PROC
*)&dll_PyList_Size
},
267 {"PyList_Type", (PYTHON_PROC
*)&dll_PyList_Type
},
268 {"PyImport_ImportModule", (PYTHON_PROC
*)&dll_PyImport_ImportModule
},
269 {"PyDict_GetItemString", (PYTHON_PROC
*)&dll_PyDict_GetItemString
},
270 {"PyDict_New", (PYTHON_PROC
*)&dll_PyDict_New
},
271 {"PyModule_GetDict", (PYTHON_PROC
*)&dll_PyModule_GetDict
},
272 {"PyRun_SimpleString", (PYTHON_PROC
*)&dll_PyRun_SimpleString
},
273 {"PyString_AsString", (PYTHON_PROC
*)&dll_PyString_AsString
},
274 {"PyString_FromString", (PYTHON_PROC
*)&dll_PyString_FromString
},
275 {"PyString_FromStringAndSize", (PYTHON_PROC
*)&dll_PyString_FromStringAndSize
},
276 {"PyString_Size", (PYTHON_PROC
*)&dll_PyString_Size
},
277 {"PyString_Type", (PYTHON_PROC
*)&dll_PyString_Type
},
278 {"PySys_SetObject", (PYTHON_PROC
*)&dll_PySys_SetObject
},
279 {"PySys_SetArgv", (PYTHON_PROC
*)&dll_PySys_SetArgv
},
280 {"PyType_Type", (PYTHON_PROC
*)&dll_PyType_Type
},
281 {"Py_BuildValue", (PYTHON_PROC
*)&dll_Py_BuildValue
},
282 {"Py_FindMethod", (PYTHON_PROC
*)&dll_Py_FindMethod
},
283 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
284 {"Py_InitModule4_64", (PYTHON_PROC
*)&dll_Py_InitModule4
},
286 {"Py_InitModule4", (PYTHON_PROC
*)&dll_Py_InitModule4
},
288 {"Py_Initialize", (PYTHON_PROC
*)&dll_Py_Initialize
},
289 {"Py_Finalize", (PYTHON_PROC
*)&dll_Py_Finalize
},
290 {"Py_IsInitialized", (PYTHON_PROC
*)&dll_Py_IsInitialized
},
291 {"_PyObject_New", (PYTHON_PROC
*)&dll__PyObject_New
},
292 {"PyObject_Init", (PYTHON_PROC
*)&dll__PyObject_Init
},
293 {"_Py_NoneStruct", (PYTHON_PROC
*)&dll__Py_NoneStruct
},
294 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
295 {"PyType_IsSubtype", (PYTHON_PROC
*)&dll_PyType_IsSubtype
},
297 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
298 {"PyObject_Malloc", (PYTHON_PROC
*)&dll_PyObject_Malloc
},
299 {"PyObject_Free", (PYTHON_PROC
*)&dll_PyObject_Free
},
308 end_dynamic_python(void)
312 FreeLibrary(hinstPython
);
318 * Load library and get all pointers.
319 * Parameter 'libname' provides name of DLL.
323 python_runtime_link_init(char *libname
, int verbose
)
329 hinstPython
= LoadLibrary(libname
);
333 EMSG2(_(e_loadlib
), libname
);
337 for (i
= 0; python_funcname_table
[i
].ptr
; ++i
)
339 if ((*python_funcname_table
[i
].ptr
= GetProcAddress(hinstPython
,
340 python_funcname_table
[i
].name
)) == NULL
)
342 FreeLibrary(hinstPython
);
345 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
353 * If python is enabled (there is installed python on Windows system) return
357 python_enabled(int verbose
)
359 return python_runtime_link_init(DYNAMIC_PYTHON_DLL
, verbose
) == OK
;
362 /* Load the standard Python exceptions - don't import the symbols from the
363 * DLL, as this can cause errors (importing data symbols is not reliable).
365 static void get_exceptions
__ARGS((void));
370 PyObject
*exmod
= PyImport_ImportModule("exceptions");
371 PyObject
*exdict
= PyModule_GetDict(exmod
);
372 imp_PyExc_AttributeError
= PyDict_GetItemString(exdict
, "AttributeError");
373 imp_PyExc_IndexError
= PyDict_GetItemString(exdict
, "IndexError");
374 imp_PyExc_KeyboardInterrupt
= PyDict_GetItemString(exdict
, "KeyboardInterrupt");
375 imp_PyExc_TypeError
= PyDict_GetItemString(exdict
, "TypeError");
376 imp_PyExc_ValueError
= PyDict_GetItemString(exdict
, "ValueError");
377 Py_XINCREF(imp_PyExc_AttributeError
);
378 Py_XINCREF(imp_PyExc_IndexError
);
379 Py_XINCREF(imp_PyExc_KeyboardInterrupt
);
380 Py_XINCREF(imp_PyExc_TypeError
);
381 Py_XINCREF(imp_PyExc_ValueError
);
384 #endif /* DYNAMIC_PYTHON */
386 /******************************************************
387 * Internal function prototypes.
390 static void DoPythonCommand(exarg_T
*, const char *);
391 static PyInt RangeStart
;
392 static PyInt RangeEnd
;
394 static void PythonIO_Flush(void);
395 static int PythonIO_Init(void);
396 static int PythonMod_Init(void);
398 /* Utility functions for the vim/python interface
399 * ----------------------------------------------
401 static PyObject
*GetBufferLine(buf_T
*, PyInt
);
402 static PyObject
*GetBufferLineList(buf_T
*, PyInt
, PyInt
);
404 static int SetBufferLine(buf_T
*, PyInt
, PyObject
*, PyInt
*);
405 static int SetBufferLineList(buf_T
*, PyInt
, PyInt
, PyObject
*, PyInt
*);
406 static int InsertBufferLines(buf_T
*, PyInt
, PyObject
*, PyInt
*);
408 static PyObject
*LineToString(const char *);
409 static char *StringToLine(PyObject
*);
411 static int VimErrorCheck(void);
413 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
415 /******************************************************
416 * 1. Python interpreter main program.
419 static int initialised
= 0;
421 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
422 typedef PyObject PyThreadState
;
425 #ifdef PY_CAN_RECURSE
426 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
428 static PyThreadState
*saved_python_thread
= NULL
;
432 * Suspend a thread of the Python interpreter, other threads are allowed to
436 Python_SaveThread(void)
438 #ifdef PY_CAN_RECURSE
439 PyGILState_Release(pygilstate
);
441 saved_python_thread
= PyEval_SaveThread();
446 * Restore a thread of the Python interpreter, waits for other threads to
450 Python_RestoreThread(void)
452 #ifdef PY_CAN_RECURSE
453 pygilstate
= PyGILState_Ensure();
455 PyEval_RestoreThread(saved_python_thread
);
456 saved_python_thread
= NULL
;
461 * obtain a lock on the Vim data structures
463 static void Python_Lock_Vim(void)
468 * release a lock on the Vim data structures
470 static void Python_Release_Vim(void)
477 static int recurse
= 0;
479 /* If a crash occurs while doing this, don't try again. */
485 #ifdef DYNAMIC_PYTHON
486 if (hinstPython
&& Py_IsInitialized())
488 Python_RestoreThread(); /* enter python */
491 end_dynamic_python();
493 if (Py_IsInitialized())
495 Python_RestoreThread(); /* enter python */
508 #ifdef DYNAMIC_PYTHON
509 if (!python_enabled(TRUE
))
511 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
516 #if !defined(MACOS) || defined(MACOS_X_UNIX)
521 /* initialise threads */
522 PyEval_InitThreads();
524 #ifdef DYNAMIC_PYTHON
531 if (PythonMod_Init())
534 /* the first python thread is vim's, release the lock */
543 /* We call PythonIO_Flush() here to print any Python errors.
544 * This is OK, as it is possible to call this function even
545 * if PythonIO_Init() has not completed successfully (it will
546 * not do anything in this case).
556 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
558 #ifndef PY_CAN_RECURSE
559 static int recursive
= 0;
561 #if defined(MACOS) && !defined(MACOS_X_UNIX)
564 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
568 #ifndef PY_CAN_RECURSE
571 EMSG(_("E659: Cannot invoke Python recursively"));
577 #if defined(MACOS) && !defined(MACOS_X_UNIX)
579 /* Check if the Python library is available */
580 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
586 RangeStart
= eap
->line1
;
587 RangeEnd
= eap
->line2
;
588 Python_Release_Vim(); /* leave vim */
590 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
591 /* Python only works properly when the LC_NUMERIC locale is "C". */
592 saved_locale
= setlocale(LC_NUMERIC
, NULL
);
593 if (saved_locale
== NULL
|| STRCMP(saved_locale
, "C") == 0)
597 /* Need to make a copy, value may change when setting new locale. */
598 saved_locale
= (char *)vim_strsave((char_u
*)saved_locale
);
599 (void)setlocale(LC_NUMERIC
, "C");
603 Python_RestoreThread(); /* enter python */
605 PyRun_SimpleString((char *)(cmd
));
607 Python_SaveThread(); /* leave python */
609 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
610 if (saved_locale
!= NULL
)
612 (void)setlocale(LC_NUMERIC
, saved_locale
);
613 vim_free(saved_locale
);
617 Python_Lock_Vim(); /* enter vim */
619 #if defined(MACOS) && !defined(MACOS_X_UNIX)
624 #ifndef PY_CAN_RECURSE
627 return; /* keeps lint happy */
634 ex_python(exarg_T
*eap
)
638 script
= script_get(eap
, eap
->arg
);
642 DoPythonCommand(eap
, (char *)eap
->arg
);
644 DoPythonCommand(eap
, (char *)script
);
649 #define BUFFER_SIZE 1024
655 ex_pyfile(exarg_T
*eap
)
657 static char buffer
[BUFFER_SIZE
];
658 const char *file
= (char *)eap
->arg
;
661 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
662 * stdio file pointer, but Vim and the Python DLL are compiled with
663 * different options under Windows, meaning that stdio pointers aren't
664 * compatible between the two. Yuk.
666 * Put the string "execfile('file')" into buffer. But, we need to
667 * escape any backslashes or single quotes in the file name, so that
668 * Python won't mangle the file name.
670 strcpy(buffer
, "execfile('");
671 p
= buffer
+ 10; /* size of "execfile('" */
673 while (*file
&& p
< buffer
+ (BUFFER_SIZE
- 3))
675 if (*file
== '\\' || *file
== '\'')
680 /* If we didn't finish the file name, we hit a buffer overflow */
684 /* Put in the terminating "')" and a null */
689 /* Execute the file */
690 DoPythonCommand(eap
, buffer
);
693 /******************************************************
694 * 2. Python output stream: writes output via [e]msg().
697 /* Implementation functions
700 static PyObject
*OutputGetattr(PyObject
*, char *);
701 static int OutputSetattr(PyObject
*, char *, PyObject
*);
703 static PyObject
*OutputWrite(PyObject
*, PyObject
*);
704 static PyObject
*OutputWritelines(PyObject
*, PyObject
*);
706 typedef void (*writefn
)(char_u
*);
707 static void writer(writefn fn
, char_u
*str
, PyInt n
);
709 /* Output object definition
719 static struct PyMethodDef OutputMethods
[] = {
720 /* name, function, calling, documentation */
721 {"write", OutputWrite
, 1, "" },
722 {"writelines", OutputWritelines
, 1, "" },
723 { NULL
, NULL
, 0, NULL
}
726 static PyTypeObject OutputType
= {
727 PyObject_HEAD_INIT(0)
730 sizeof(OutputObject
),
735 (getattrfunc
) OutputGetattr
,
736 (setattrfunc
) OutputSetattr
,
752 OutputGetattr(PyObject
*self
, char *name
)
754 if (strcmp(name
, "softspace") == 0)
755 return PyInt_FromLong(((OutputObject
*)(self
))->softspace
);
757 return Py_FindMethod(OutputMethods
, self
, name
);
761 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
764 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
768 if (strcmp(name
, "softspace") == 0)
770 if (!PyInt_Check(val
)) {
771 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
775 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
779 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
786 OutputWrite(PyObject
*self
, PyObject
*args
)
790 int error
= ((OutputObject
*)(self
))->error
;
792 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
795 Py_BEGIN_ALLOW_THREADS
797 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
798 Python_Release_Vim();
806 OutputWritelines(PyObject
*self
, PyObject
*args
)
811 int error
= ((OutputObject
*)(self
))->error
;
813 if (!PyArg_ParseTuple(args
, "O", &list
))
817 if (!PyList_Check(list
)) {
818 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
823 n
= PyList_Size(list
);
825 for (i
= 0; i
< n
; ++i
)
827 PyObject
*line
= PyList_GetItem(list
, i
);
831 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
832 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
837 Py_BEGIN_ALLOW_THREADS
839 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
840 Python_Release_Vim();
849 /* Output buffer management
852 static char_u
*buffer
= NULL
;
853 static PyInt buffer_len
= 0;
854 static PyInt buffer_size
= 0;
856 static writefn old_fn
= NULL
;
859 buffer_ensure(PyInt n
)
867 new_size
= buffer_size
;
871 if (new_size
!= buffer_size
)
873 new_buffer
= alloc((unsigned)new_size
);
874 if (new_buffer
== NULL
)
879 memcpy(new_buffer
, buffer
, buffer_len
);
884 buffer_size
= new_size
;
891 if (old_fn
&& buffer_len
)
893 buffer
[buffer_len
] = 0;
901 writer(writefn fn
, char_u
*str
, PyInt n
)
905 if (fn
!= old_fn
&& old_fn
!= NULL
)
910 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
912 PyInt len
= ptr
- str
;
914 buffer_ensure(buffer_len
+ len
+ 1);
916 memcpy(buffer
+ buffer_len
, str
, len
);
918 buffer
[buffer_len
] = 0;
925 /* Put the remaining text into the buffer for later printing */
926 buffer_ensure(buffer_len
+ n
+ 1);
927 memcpy(buffer
+ buffer_len
, str
, n
);
933 static OutputObject Output
=
935 PyObject_HEAD_INIT(&OutputType
)
940 static OutputObject Error
=
942 PyObject_HEAD_INIT(&OutputType
)
951 OutputType
.ob_type
= &PyType_Type
;
953 PySys_SetObject("stdout", (PyObject
*)(void *)&Output
);
954 PySys_SetObject("stderr", (PyObject
*)(void *)&Error
);
956 if (PyErr_Occurred())
958 EMSG(_("E264: Python: Error initialising I/O objects"));
965 /******************************************************
966 * 3. Implementation of the Vim module for Python
969 /* Vim module - Implementation functions
970 * -------------------------------------
973 static PyObject
*VimError
;
975 static PyObject
*VimCommand(PyObject
*, PyObject
*);
976 static PyObject
*VimEval(PyObject
*, PyObject
*);
978 /* Window type - Implementation functions
979 * --------------------------------------
989 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
991 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
993 static PyObject
*WindowNew(win_T
*);
995 static void WindowDestructor(PyObject
*);
996 static PyObject
*WindowGetattr(PyObject
*, char *);
997 static int WindowSetattr(PyObject
*, char *, PyObject
*);
998 static PyObject
*WindowRepr(PyObject
*);
1000 /* Buffer type - Implementation functions
1001 * --------------------------------------
1011 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1013 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1015 static PyObject
*BufferNew (buf_T
*);
1017 static void BufferDestructor(PyObject
*);
1018 static PyObject
*BufferGetattr(PyObject
*, char *);
1019 static PyObject
*BufferRepr(PyObject
*);
1021 static PyInt
BufferLength(PyObject
*);
1022 static PyObject
*BufferItem(PyObject
*, PyInt
);
1023 static PyObject
*BufferSlice(PyObject
*, PyInt
, PyInt
);
1024 static PyInt
BufferAssItem(PyObject
*, PyInt
, PyObject
*);
1025 static PyInt
BufferAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1027 static PyObject
*BufferAppend(PyObject
*, PyObject
*);
1028 static PyObject
*BufferMark(PyObject
*, PyObject
*);
1029 static PyObject
*BufferRange(PyObject
*, PyObject
*);
1031 /* Line range type - Implementation functions
1032 * --------------------------------------
1044 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1046 static PyObject
*RangeNew(buf_T
*, PyInt
, PyInt
);
1048 static void RangeDestructor(PyObject
*);
1049 static PyObject
*RangeGetattr(PyObject
*, char *);
1050 static PyObject
*RangeRepr(PyObject
*);
1052 static PyInt
RangeLength(PyObject
*);
1053 static PyObject
*RangeItem(PyObject
*, PyInt
);
1054 static PyObject
*RangeSlice(PyObject
*, PyInt
, PyInt
);
1055 static PyInt
RangeAssItem(PyObject
*, PyInt
, PyObject
*);
1056 static PyInt
RangeAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1058 static PyObject
*RangeAppend(PyObject
*, PyObject
*);
1060 /* Window list type - Implementation functions
1061 * -------------------------------------------
1064 static PyInt
WinListLength(PyObject
*);
1065 static PyObject
*WinListItem(PyObject
*, PyInt
);
1067 /* Buffer list type - Implementation functions
1068 * -------------------------------------------
1071 static PyInt
BufListLength(PyObject
*);
1072 static PyObject
*BufListItem(PyObject
*, PyInt
);
1074 /* Current objects type - Implementation functions
1075 * -----------------------------------------------
1078 static PyObject
*CurrentGetattr(PyObject
*, char *);
1079 static int CurrentSetattr(PyObject
*, char *, PyObject
*);
1081 /* Vim module - Definitions
1084 static struct PyMethodDef VimMethods
[] = {
1085 /* name, function, calling, documentation */
1086 {"command", VimCommand
, 1, "Execute a Vim ex-mode command" },
1087 {"eval", VimEval
, 1, "Evaluate an expression using Vim evaluator" },
1088 { NULL
, NULL
, 0, NULL
}
1091 /* Vim module - Implementation
1095 VimCommand(PyObject
*self
, PyObject
*args
)
1100 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1105 Py_BEGIN_ALLOW_THREADS
1108 do_cmdline_cmd((char_u
*)cmd
);
1109 update_screen(VALID
);
1111 Python_Release_Vim();
1112 Py_END_ALLOW_THREADS
1114 if (VimErrorCheck())
1124 * Function to translate a typval_T into a PyObject; this will recursively
1125 * translate lists/dictionaries into their Python equivalents.
1127 * The depth parameter is to avoid infinite recursion, set it to 1 when
1128 * you call VimToPython.
1131 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1135 char ptrBuf
[NUMBUFLEN
];
1137 /* Avoid infinite recursion */
1145 /* Check if we run into a recursive loop. The item must be in lookupDict
1146 * then and we can use it again. */
1147 sprintf(ptrBuf
, PRINTF_DECIMAL_LONG_U
, (long_u
)our_tv
);
1148 result
= PyDict_GetItemString(lookupDict
, ptrBuf
);
1151 else if (our_tv
->v_type
== VAR_STRING
)
1153 result
= Py_BuildValue("s", our_tv
->vval
.v_string
);
1154 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1156 else if (our_tv
->v_type
== VAR_NUMBER
)
1158 char buf
[NUMBUFLEN
];
1160 /* For backwards compatibility numbers are stored as strings. */
1161 sprintf(buf
, "%ld", (long)our_tv
->vval
.v_number
);
1162 result
= Py_BuildValue("s", buf
);
1163 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1166 else if (our_tv
->v_type
== VAR_FLOAT
)
1168 char buf
[NUMBUFLEN
];
1170 sprintf(buf
, "%f", our_tv
->vval
.v_float
);
1171 result
= Py_BuildValue("s", buf
);
1172 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1175 else if (our_tv
->v_type
== VAR_LIST
)
1177 list_T
*list
= our_tv
->vval
.v_list
;
1180 result
= PyList_New(0);
1181 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1185 for (curr
= list
->lv_first
; curr
!= NULL
; curr
= curr
->li_next
)
1187 newObj
= VimToPython(&curr
->li_tv
, depth
+ 1, lookupDict
);
1188 PyList_Append(result
, newObj
);
1193 else if (our_tv
->v_type
== VAR_DICT
)
1195 result
= PyDict_New();
1196 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1198 if (our_tv
->vval
.v_dict
!= NULL
)
1200 hashtab_T
*ht
= &our_tv
->vval
.v_dict
->dv_hashtab
;
1201 long_u todo
= ht
->ht_used
;
1205 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1207 if (!HASHITEM_EMPTY(hi
))
1211 di
= dict_lookup(hi
);
1212 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1213 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1230 VimEval(PyObject
*self
, PyObject
*args
)
1236 PyObject
*lookup_dict
;
1238 if (!PyArg_ParseTuple(args
, "s", &expr
))
1241 Py_BEGIN_ALLOW_THREADS
1243 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1245 Python_Release_Vim();
1246 Py_END_ALLOW_THREADS
1250 PyErr_SetVim(_("invalid expression"));
1254 /* Convert the Vim type into a Python type. Create a dictionary that's
1255 * used to check for recursive loops. */
1256 lookup_dict
= PyDict_New();
1257 result
= VimToPython(our_tv
, 1, lookup_dict
);
1258 Py_DECREF(lookup_dict
);
1261 Py_BEGIN_ALLOW_THREADS
1264 Python_Release_Vim();
1265 Py_END_ALLOW_THREADS
1269 PyErr_SetVim(_("expressions disabled at compile time"));
1274 /* Common routines for buffers and line ranges
1275 * -------------------------------------------
1278 CheckBuffer(BufferObject
*this)
1280 if (this->buf
== INVALID_BUFFER_VALUE
)
1282 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1290 RBItem(BufferObject
*self
, PyInt n
, PyInt start
, PyInt end
)
1292 if (CheckBuffer(self
))
1295 if (n
< 0 || n
> end
- start
)
1297 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1301 return GetBufferLine(self
->buf
, n
+start
);
1305 RBSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyInt start
, PyInt end
)
1309 if (CheckBuffer(self
))
1312 size
= end
- start
+ 1;
1325 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1329 RBAssItem(BufferObject
*self
, PyInt n
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1333 if (CheckBuffer(self
))
1336 if (n
< 0 || n
> end
- start
)
1338 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1342 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1346 *new_end
= end
+ len_change
;
1352 RBAssSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1357 /* Self must be a valid buffer */
1358 if (CheckBuffer(self
))
1361 /* Sort out the slice range */
1362 size
= end
- start
+ 1;
1375 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1379 *new_end
= end
+ len_change
;
1385 RBAppend(BufferObject
*self
, PyObject
*args
, PyInt start
, PyInt end
, PyInt
*new_end
)
1392 if (CheckBuffer(self
))
1395 max
= n
= end
- start
+ 1;
1397 if (!PyArg_ParseTuple(args
, "O|" Py_ssize_t_fmt
, &lines
, &n
))
1400 if (n
< 0 || n
> max
)
1402 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1406 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1410 *new_end
= end
+ len_change
;
1417 /* Buffer object - Definitions
1420 static struct PyMethodDef BufferMethods
[] = {
1421 /* name, function, calling, documentation */
1422 {"append", BufferAppend
, 1, "Append data to Vim buffer" },
1423 {"mark", BufferMark
, 1, "Return (row,col) representing position of named mark" },
1424 {"range", BufferRange
, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1425 { NULL
, NULL
, 0, NULL
}
1428 static PySequenceMethods BufferAsSeq
= {
1429 (PyInquiry
) BufferLength
, /* sq_length, len(x) */
1430 (binaryfunc
) 0, /* BufferConcat, */ /* sq_concat, x+y */
1431 (PyIntArgFunc
) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1432 (PyIntArgFunc
) BufferItem
, /* sq_item, x[i] */
1433 (PyIntIntArgFunc
) BufferSlice
, /* sq_slice, x[i:j] */
1434 (PyIntObjArgProc
) BufferAssItem
, /* sq_ass_item, x[i]=v */
1435 (PyIntIntObjArgProc
) BufferAssSlice
, /* sq_ass_slice, x[i:j]=v */
1438 static PyTypeObject BufferType
= {
1439 PyObject_HEAD_INIT(0)
1442 sizeof(BufferObject
),
1445 (destructor
) BufferDestructor
, /* tp_dealloc, refcount==0 */
1446 (printfunc
) 0, /* tp_print, print x */
1447 (getattrfunc
) BufferGetattr
, /* tp_getattr, x.attr */
1448 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1449 (cmpfunc
) 0, /* tp_compare, x>y */
1450 (reprfunc
) BufferRepr
, /* tp_repr, `x`, print x */
1453 &BufferAsSeq
, /* as sequence */
1456 (hashfunc
) 0, /* tp_hash, dict(x) */
1457 (ternaryfunc
) 0, /* tp_call, x() */
1458 (reprfunc
) 0, /* tp_str, str(x) */
1461 /* Buffer object - Implementation
1465 BufferNew(buf_T
*buf
)
1467 /* We need to handle deletion of buffers underneath us.
1468 * If we add a "b_python_ref" field to the buf_T structure,
1469 * then we can get at it in buf_freeall() in vim. We then
1470 * need to create only ONE Python object per buffer - if
1471 * we try to create a second, just INCREF the existing one
1472 * and return it. The (single) Python object referring to
1473 * the buffer is stored in "b_python_ref".
1474 * Question: what to do on a buf_freeall(). We'll probably
1475 * have to either delete the Python object (DECREF it to
1476 * zero - a bad idea, as it leaves dangling refs!) or
1477 * set the buf_T * value to an invalid value (-1?), which
1478 * means we need checks in all access functions... Bah.
1483 if (buf
->b_python_ref
!= NULL
)
1485 self
= buf
->b_python_ref
;
1490 self
= PyObject_NEW(BufferObject
, &BufferType
);
1494 buf
->b_python_ref
= self
;
1497 return (PyObject
*)(self
);
1501 BufferDestructor(PyObject
*self
)
1503 BufferObject
*this = (BufferObject
*)(self
);
1505 if (this->buf
&& this->buf
!= INVALID_BUFFER_VALUE
)
1506 this->buf
->b_python_ref
= NULL
;
1512 BufferGetattr(PyObject
*self
, char *name
)
1514 BufferObject
*this = (BufferObject
*)(self
);
1516 if (CheckBuffer(this))
1519 if (strcmp(name
, "name") == 0)
1520 return Py_BuildValue("s", this->buf
->b_ffname
);
1521 else if (strcmp(name
, "number") == 0)
1522 return Py_BuildValue(Py_ssize_t_fmt
, this->buf
->b_fnum
);
1523 else if (strcmp(name
,"__members__") == 0)
1524 return Py_BuildValue("[ss]", "name", "number");
1526 return Py_FindMethod(BufferMethods
, self
, name
);
1530 BufferRepr(PyObject
*self
)
1532 static char repr
[100];
1533 BufferObject
*this = (BufferObject
*)(self
);
1535 if (this->buf
== INVALID_BUFFER_VALUE
)
1537 vim_snprintf(repr
, 100, _("<buffer object (deleted) at %p>"), (self
));
1538 return PyString_FromString(repr
);
1542 char *name
= (char *)this->buf
->b_fname
;
1550 name
= name
+ (35 - len
);
1552 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1554 return PyString_FromString(repr
);
1558 /******************/
1561 BufferLength(PyObject
*self
)
1563 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1564 if (CheckBuffer((BufferObject
*)(self
)))
1565 return -1; /* ??? */
1567 return (((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1571 BufferItem(PyObject
*self
, PyInt n
)
1573 return RBItem((BufferObject
*)(self
), n
, 1,
1574 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1578 BufferSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1580 return RBSlice((BufferObject
*)(self
), lo
, hi
, 1,
1581 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1585 BufferAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1587 return RBAssItem((BufferObject
*)(self
), n
, val
, 1,
1588 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1593 BufferAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1595 return RBAssSlice((BufferObject
*)(self
), lo
, hi
, val
, 1,
1596 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1601 BufferAppend(PyObject
*self
, PyObject
*args
)
1603 return RBAppend((BufferObject
*)(self
), args
, 1,
1604 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1609 BufferMark(PyObject
*self
, PyObject
*args
)
1615 if (CheckBuffer((BufferObject
*)(self
)))
1618 if (!PyArg_ParseTuple(args
, "c", &mark
))
1621 curbuf_save
= curbuf
;
1622 curbuf
= ((BufferObject
*)(self
))->buf
;
1623 posp
= getmark(mark
, FALSE
);
1624 curbuf
= curbuf_save
;
1628 PyErr_SetVim(_("invalid mark name"));
1632 /* Ckeck for keyboard interrupt */
1633 if (VimErrorCheck())
1636 if (posp
->lnum
<= 0)
1638 /* Or raise an error? */
1643 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1647 BufferRange(PyObject
*self
, PyObject
*args
)
1652 if (CheckBuffer((BufferObject
*)(self
)))
1655 if (!PyArg_ParseTuple(args
, Py_ssize_t_fmt Py_ssize_t_fmt
, &start
, &end
))
1658 return RangeNew(((BufferObject
*)(self
))->buf
, start
, end
);
1661 /* Line range object - Definitions
1664 static struct PyMethodDef RangeMethods
[] = {
1665 /* name, function, calling, documentation */
1666 {"append", RangeAppend
, 1, "Append data to the Vim range" },
1667 { NULL
, NULL
, 0, NULL
}
1670 static PySequenceMethods RangeAsSeq
= {
1671 (PyInquiry
) RangeLength
, /* sq_length, len(x) */
1672 (binaryfunc
) 0, /* RangeConcat, */ /* sq_concat, x+y */
1673 (PyIntArgFunc
) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1674 (PyIntArgFunc
) RangeItem
, /* sq_item, x[i] */
1675 (PyIntIntArgFunc
) RangeSlice
, /* sq_slice, x[i:j] */
1676 (PyIntObjArgProc
) RangeAssItem
, /* sq_ass_item, x[i]=v */
1677 (PyIntIntObjArgProc
) RangeAssSlice
, /* sq_ass_slice, x[i:j]=v */
1680 static PyTypeObject RangeType
= {
1681 PyObject_HEAD_INIT(0)
1684 sizeof(RangeObject
),
1687 (destructor
) RangeDestructor
, /* tp_dealloc, refcount==0 */
1688 (printfunc
) 0, /* tp_print, print x */
1689 (getattrfunc
) RangeGetattr
, /* tp_getattr, x.attr */
1690 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1691 (cmpfunc
) 0, /* tp_compare, x>y */
1692 (reprfunc
) RangeRepr
, /* tp_repr, `x`, print x */
1695 &RangeAsSeq
, /* as sequence */
1698 (hashfunc
) 0, /* tp_hash, dict(x) */
1699 (ternaryfunc
) 0, /* tp_call, x() */
1700 (reprfunc
) 0, /* tp_str, str(x) */
1703 /* Line range object - Implementation
1707 RangeNew(buf_T
*buf
, PyInt start
, PyInt end
)
1711 self
= PyObject_NEW(RangeObject
, &RangeType
);
1715 bufr
= (BufferObject
*)BufferNew(buf
);
1724 self
->start
= start
;
1727 return (PyObject
*)(self
);
1731 RangeDestructor(PyObject
*self
)
1733 Py_DECREF(((RangeObject
*)(self
))->buf
);
1738 RangeGetattr(PyObject
*self
, char *name
)
1740 if (strcmp(name
, "start") == 0)
1741 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->start
- 1);
1742 else if (strcmp(name
, "end") == 0)
1743 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->end
- 1);
1745 return Py_FindMethod(RangeMethods
, self
, name
);
1749 RangeRepr(PyObject
*self
)
1751 static char repr
[100];
1752 RangeObject
*this = (RangeObject
*)(self
);
1754 if (this->buf
->buf
== INVALID_BUFFER_VALUE
)
1756 vim_snprintf(repr
, 100, "<range object (for deleted buffer) at %p>",
1758 return PyString_FromString(repr
);
1762 char *name
= (char *)this->buf
->buf
->b_fname
;
1767 len
= (int)strlen(name
);
1770 name
= name
+ (45 - len
);
1772 vim_snprintf(repr
, 100, "<range %s%s (%d:%d)>",
1773 len
> 45 ? "..." : "", name
,
1774 this->start
, this->end
);
1776 return PyString_FromString(repr
);
1783 RangeLength(PyObject
*self
)
1785 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1786 if (CheckBuffer(((RangeObject
*)(self
))->buf
))
1787 return -1; /* ??? */
1789 return (((RangeObject
*)(self
))->end
- ((RangeObject
*)(self
))->start
+ 1);
1793 RangeItem(PyObject
*self
, PyInt n
)
1795 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1796 ((RangeObject
*)(self
))->start
,
1797 ((RangeObject
*)(self
))->end
);
1801 RangeSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1803 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1804 ((RangeObject
*)(self
))->start
,
1805 ((RangeObject
*)(self
))->end
);
1809 RangeAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1811 return RBAssItem(((RangeObject
*)(self
))->buf
, n
, val
,
1812 ((RangeObject
*)(self
))->start
,
1813 ((RangeObject
*)(self
))->end
,
1814 &((RangeObject
*)(self
))->end
);
1818 RangeAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1820 return RBAssSlice(((RangeObject
*)(self
))->buf
, lo
, hi
, val
,
1821 ((RangeObject
*)(self
))->start
,
1822 ((RangeObject
*)(self
))->end
,
1823 &((RangeObject
*)(self
))->end
);
1827 RangeAppend(PyObject
*self
, PyObject
*args
)
1829 return RBAppend(((RangeObject
*)(self
))->buf
, args
,
1830 ((RangeObject
*)(self
))->start
,
1831 ((RangeObject
*)(self
))->end
,
1832 &((RangeObject
*)(self
))->end
);
1835 /* Buffer list object - Definitions
1844 static PySequenceMethods BufListAsSeq
= {
1845 (PyInquiry
) BufListLength
, /* sq_length, len(x) */
1846 (binaryfunc
) 0, /* sq_concat, x+y */
1847 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
1848 (PyIntArgFunc
) BufListItem
, /* sq_item, x[i] */
1849 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
1850 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
1851 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
1854 static PyTypeObject BufListType
= {
1855 PyObject_HEAD_INIT(0)
1858 sizeof(BufListObject
),
1861 (destructor
) 0, /* tp_dealloc, refcount==0 */
1862 (printfunc
) 0, /* tp_print, print x */
1863 (getattrfunc
) 0, /* tp_getattr, x.attr */
1864 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1865 (cmpfunc
) 0, /* tp_compare, x>y */
1866 (reprfunc
) 0, /* tp_repr, `x`, print x */
1869 &BufListAsSeq
, /* as sequence */
1872 (hashfunc
) 0, /* tp_hash, dict(x) */
1873 (ternaryfunc
) 0, /* tp_call, x() */
1874 (reprfunc
) 0, /* tp_str, str(x) */
1877 /* Buffer list object - Implementation
1882 BufListLength(PyObject
*self
)
1884 buf_T
*b
= firstbuf
;
1898 BufListItem(PyObject
*self
, PyInt n
)
1902 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1905 return BufferNew(b
);
1908 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
1912 /* Window object - Definitions
1915 static struct PyMethodDef WindowMethods
[] = {
1916 /* name, function, calling, documentation */
1917 { NULL
, NULL
, 0, NULL
}
1920 static PyTypeObject WindowType
= {
1921 PyObject_HEAD_INIT(0)
1924 sizeof(WindowObject
),
1927 (destructor
) WindowDestructor
, /* tp_dealloc, refcount==0 */
1928 (printfunc
) 0, /* tp_print, print x */
1929 (getattrfunc
) WindowGetattr
, /* tp_getattr, x.attr */
1930 (setattrfunc
) WindowSetattr
, /* tp_setattr, x.attr=v */
1931 (cmpfunc
) 0, /* tp_compare, x>y */
1932 (reprfunc
) WindowRepr
, /* tp_repr, `x`, print x */
1935 0, /* as sequence */
1938 (hashfunc
) 0, /* tp_hash, dict(x) */
1939 (ternaryfunc
) 0, /* tp_call, x() */
1940 (reprfunc
) 0, /* tp_str, str(x) */
1943 /* Window object - Implementation
1947 WindowNew(win_T
*win
)
1949 /* We need to handle deletion of windows underneath us.
1950 * If we add a "w_python_ref" field to the win_T structure,
1951 * then we can get at it in win_free() in vim. We then
1952 * need to create only ONE Python object per window - if
1953 * we try to create a second, just INCREF the existing one
1954 * and return it. The (single) Python object referring to
1955 * the window is stored in "w_python_ref".
1956 * On a win_free() we set the Python object's win_T* field
1957 * to an invalid value. We trap all uses of a window
1958 * object, and reject them if the win_T* field is invalid.
1963 if (win
->w_python_ref
)
1965 self
= win
->w_python_ref
;
1970 self
= PyObject_NEW(WindowObject
, &WindowType
);
1974 win
->w_python_ref
= self
;
1977 return (PyObject
*)(self
);
1981 WindowDestructor(PyObject
*self
)
1983 WindowObject
*this = (WindowObject
*)(self
);
1985 if (this->win
&& this->win
!= INVALID_WINDOW_VALUE
)
1986 this->win
->w_python_ref
= NULL
;
1992 CheckWindow(WindowObject
*this)
1994 if (this->win
== INVALID_WINDOW_VALUE
)
1996 PyErr_SetVim(_("attempt to refer to deleted window"));
2004 WindowGetattr(PyObject
*self
, char *name
)
2006 WindowObject
*this = (WindowObject
*)(self
);
2008 if (CheckWindow(this))
2011 if (strcmp(name
, "buffer") == 0)
2012 return (PyObject
*)BufferNew(this->win
->w_buffer
);
2013 else if (strcmp(name
, "cursor") == 0)
2015 pos_T
*pos
= &this->win
->w_cursor
;
2017 return Py_BuildValue("(ll)", (long)(pos
->lnum
), (long)(pos
->col
));
2019 else if (strcmp(name
, "height") == 0)
2020 return Py_BuildValue("l", (long)(this->win
->w_height
));
2021 #ifdef FEAT_VERTSPLIT
2022 else if (strcmp(name
, "width") == 0)
2023 return Py_BuildValue("l", (long)(W_WIDTH(this->win
)));
2025 else if (strcmp(name
,"__members__") == 0)
2026 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2028 return Py_FindMethod(WindowMethods
, self
, name
);
2032 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
2034 WindowObject
*this = (WindowObject
*)(self
);
2036 if (CheckWindow(this))
2039 if (strcmp(name
, "buffer") == 0)
2041 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2044 else if (strcmp(name
, "cursor") == 0)
2049 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2052 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2054 PyErr_SetVim(_("cursor position outside buffer"));
2058 /* Check for keyboard interrupts */
2059 if (VimErrorCheck())
2062 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2064 this->win
->w_cursor
.lnum
= lnum
;
2065 this->win
->w_cursor
.col
= col
;
2066 update_screen(VALID
);
2070 else if (strcmp(name
, "height") == 0)
2075 if (!PyArg_Parse(val
, "i", &height
))
2079 need_mouse_correct
= TRUE
;
2083 win_setheight(height
);
2086 /* Check for keyboard interrupts */
2087 if (VimErrorCheck())
2092 #ifdef FEAT_VERTSPLIT
2093 else if (strcmp(name
, "width") == 0)
2098 if (!PyArg_Parse(val
, "i", &width
))
2102 need_mouse_correct
= TRUE
;
2106 win_setwidth(width
);
2109 /* Check for keyboard interrupts */
2110 if (VimErrorCheck())
2118 PyErr_SetString(PyExc_AttributeError
, name
);
2124 WindowRepr(PyObject
*self
)
2126 static char repr
[100];
2127 WindowObject
*this = (WindowObject
*)(self
);
2129 if (this->win
== INVALID_WINDOW_VALUE
)
2131 vim_snprintf(repr
, 100, _("<window object (deleted) at %p>"), (self
));
2132 return PyString_FromString(repr
);
2139 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2143 vim_snprintf(repr
, 100, _("<window object (unknown) at %p>"),
2146 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2148 return PyString_FromString(repr
);
2152 /* Window list object - Definitions
2161 static PySequenceMethods WinListAsSeq
= {
2162 (PyInquiry
) WinListLength
, /* sq_length, len(x) */
2163 (binaryfunc
) 0, /* sq_concat, x+y */
2164 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
2165 (PyIntArgFunc
) WinListItem
, /* sq_item, x[i] */
2166 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
2167 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
2168 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
2171 static PyTypeObject WinListType
= {
2172 PyObject_HEAD_INIT(0)
2175 sizeof(WinListObject
),
2178 (destructor
) 0, /* tp_dealloc, refcount==0 */
2179 (printfunc
) 0, /* tp_print, print x */
2180 (getattrfunc
) 0, /* tp_getattr, x.attr */
2181 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
2182 (cmpfunc
) 0, /* tp_compare, x>y */
2183 (reprfunc
) 0, /* tp_repr, `x`, print x */
2186 &WinListAsSeq
, /* as sequence */
2189 (hashfunc
) 0, /* tp_hash, dict(x) */
2190 (ternaryfunc
) 0, /* tp_call, x() */
2191 (reprfunc
) 0, /* tp_str, str(x) */
2194 /* Window list object - Implementation
2198 WinListLength(PyObject
*self
)
2200 win_T
*w
= firstwin
;
2214 WinListItem(PyObject
*self
, PyInt n
)
2218 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2220 return WindowNew(w
);
2222 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2226 /* Current items object - Definitions
2235 static PyTypeObject CurrentType
= {
2236 PyObject_HEAD_INIT(0)
2239 sizeof(CurrentObject
),
2242 (destructor
) 0, /* tp_dealloc, refcount==0 */
2243 (printfunc
) 0, /* tp_print, print x */
2244 (getattrfunc
) CurrentGetattr
, /* tp_getattr, x.attr */
2245 (setattrfunc
) CurrentSetattr
, /* tp_setattr, x.attr=v */
2246 (cmpfunc
) 0, /* tp_compare, x>y */
2247 (reprfunc
) 0, /* tp_repr, `x`, print x */
2250 0, /* as sequence */
2253 (hashfunc
) 0, /* tp_hash, dict(x) */
2254 (ternaryfunc
) 0, /* tp_call, x() */
2255 (reprfunc
) 0, /* tp_str, str(x) */
2258 /* Current items object - Implementation
2262 CurrentGetattr(PyObject
*self
, char *name
)
2264 if (strcmp(name
, "buffer") == 0)
2265 return (PyObject
*)BufferNew(curbuf
);
2266 else if (strcmp(name
, "window") == 0)
2267 return (PyObject
*)WindowNew(curwin
);
2268 else if (strcmp(name
, "line") == 0)
2269 return GetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
);
2270 else if (strcmp(name
, "range") == 0)
2271 return RangeNew(curbuf
, RangeStart
, RangeEnd
);
2272 else if (strcmp(name
,"__members__") == 0)
2273 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2276 PyErr_SetString(PyExc_AttributeError
, name
);
2283 CurrentSetattr(PyObject
*self
, char *name
, PyObject
*value
)
2285 if (strcmp(name
, "line") == 0)
2287 if (SetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
, value
, NULL
) == FAIL
)
2294 PyErr_SetString(PyExc_AttributeError
, name
);
2299 /* External interface
2303 python_buffer_free(buf_T
*buf
)
2305 if (buf
->b_python_ref
!= NULL
)
2307 BufferObject
*bp
= buf
->b_python_ref
;
2308 bp
->buf
= INVALID_BUFFER_VALUE
;
2309 buf
->b_python_ref
= NULL
;
2313 #if defined(FEAT_WINDOWS) || defined(PROTO)
2315 python_window_free(win_T
*win
)
2317 if (win
->w_python_ref
!= NULL
)
2319 WindowObject
*wp
= win
->w_python_ref
;
2320 wp
->win
= INVALID_WINDOW_VALUE
;
2321 win
->w_python_ref
= NULL
;
2326 static BufListObject TheBufferList
=
2328 PyObject_HEAD_INIT(&BufListType
)
2331 static WinListObject TheWindowList
=
2333 PyObject_HEAD_INIT(&WinListType
)
2336 static CurrentObject TheCurrent
=
2338 PyObject_HEAD_INIT(&CurrentType
)
2342 PythonMod_Init(void)
2346 static char *(argv
[2]) = {"", NULL
};
2349 BufferType
.ob_type
= &PyType_Type
;
2350 RangeType
.ob_type
= &PyType_Type
;
2351 WindowType
.ob_type
= &PyType_Type
;
2352 BufListType
.ob_type
= &PyType_Type
;
2353 WinListType
.ob_type
= &PyType_Type
;
2354 CurrentType
.ob_type
= &PyType_Type
;
2356 /* Set sys.argv[] to avoid a crash in warn(). */
2357 PySys_SetArgv(1, argv
);
2359 mod
= Py_InitModule4("vim", VimMethods
, (char *)NULL
, (PyObject
*)NULL
, PYTHON_API_VERSION
);
2360 dict
= PyModule_GetDict(mod
);
2362 VimError
= Py_BuildValue("s", "vim.error");
2364 PyDict_SetItemString(dict
, "error", VimError
);
2365 PyDict_SetItemString(dict
, "buffers", (PyObject
*)(void *)&TheBufferList
);
2366 PyDict_SetItemString(dict
, "current", (PyObject
*)(void *)&TheCurrent
);
2367 PyDict_SetItemString(dict
, "windows", (PyObject
*)(void *)&TheWindowList
);
2369 if (PyErr_Occurred())
2375 /*************************************************************************
2376 * 4. Utility functions for handling the interface between Vim and Python.
2379 /* Get a line from the specified buffer. The line number is
2380 * in Vim format (1-based). The line is returned as a Python
2384 GetBufferLine(buf_T
*buf
, PyInt n
)
2386 return LineToString((char *)ml_get_buf(buf
, (linenr_T
)n
, FALSE
));
2389 /* Get a list of lines from the specified buffer. The line numbers
2390 * are in Vim format (1-based). The range is from lo up to, but not
2391 * including, hi. The list is returned as a Python list of string objects.
2394 GetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
)
2398 PyObject
*list
= PyList_New(n
);
2403 for (i
= 0; i
< n
; ++i
)
2405 PyObject
*str
= LineToString((char *)ml_get_buf(buf
, (linenr_T
)(lo
+i
), FALSE
));
2407 /* Error check - was the Python string creation OK? */
2414 /* Set the list item */
2415 if (PyList_SetItem(list
, i
, str
))
2423 /* The ownership of the Python list is passed to the caller (ie,
2424 * the caller should Py_DECREF() the object when it is finished
2432 * Check if deleting lines made the cursor position invalid.
2433 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2437 py_fix_cursor(linenr_T lo
, linenr_T hi
, linenr_T extra
)
2439 if (curwin
->w_cursor
.lnum
>= lo
)
2441 /* Adjust the cursor position if it's in/after the changed
2443 if (curwin
->w_cursor
.lnum
>= hi
)
2445 curwin
->w_cursor
.lnum
+= extra
;
2450 curwin
->w_cursor
.lnum
= lo
;
2455 changed_cline_bef_curs();
2457 invalidate_botline();
2460 /* Replace a line in the specified buffer. The line number is
2461 * in Vim format (1-based). The replacement line is given as
2462 * a Python string object. The object is checked for validity
2463 * and correct format. Errors are returned as a value of FAIL.
2464 * The return value is OK on success.
2465 * If OK is returned and len_change is not NULL, *len_change
2466 * is set to the change in the buffer length.
2469 SetBufferLine(buf_T
*buf
, PyInt n
, PyObject
*line
, PyInt
*len_change
)
2471 /* First of all, we check the thpe of the supplied Python object.
2472 * There are three cases:
2473 * 1. NULL, or None - this is a deletion.
2474 * 2. A string - this is a replacement.
2475 * 3. Anything else - this is an error.
2477 if (line
== Py_None
|| line
== NULL
)
2479 buf_T
*savebuf
= curbuf
;
2484 if (u_savedel((linenr_T
)n
, 1L) == FAIL
)
2485 PyErr_SetVim(_("cannot save undo information"));
2486 else if (ml_delete((linenr_T
)n
, FALSE
) == FAIL
)
2487 PyErr_SetVim(_("cannot delete line"));
2490 deleted_lines_mark((linenr_T
)n
, 1L);
2491 if (buf
== curwin
->w_buffer
)
2492 py_fix_cursor((linenr_T
)n
, (linenr_T
)n
+ 1, (linenr_T
)-1);
2497 if (PyErr_Occurred() || VimErrorCheck())
2505 else if (PyString_Check(line
))
2507 char *save
= StringToLine(line
);
2508 buf_T
*savebuf
= curbuf
;
2513 /* We do not need to free "save" if ml_replace() consumes it. */
2517 if (u_savesub((linenr_T
)n
) == FAIL
)
2519 PyErr_SetVim(_("cannot save undo information"));
2522 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2524 PyErr_SetVim(_("cannot replace line"));
2528 changed_bytes((linenr_T
)n
, 0);
2532 /* Check that the cursor is not beyond the end of the line now. */
2533 if (buf
== curwin
->w_buffer
)
2536 if (PyErr_Occurred() || VimErrorCheck())
2546 PyErr_BadArgument();
2551 /* Replace a range of lines in the specified buffer. The line numbers are in
2552 * Vim format (1-based). The range is from lo up to, but not including, hi.
2553 * The replacement lines are given as a Python list of string objects. The
2554 * list is checked for validity and correct format. Errors are returned as a
2555 * value of FAIL. The return value is OK on success.
2556 * If OK is returned and len_change is not NULL, *len_change
2557 * is set to the change in the buffer length.
2560 SetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
, PyObject
*list
, PyInt
*len_change
)
2562 /* First of all, we check the thpe of the supplied Python object.
2563 * There are three cases:
2564 * 1. NULL, or None - this is a deletion.
2565 * 2. A list - this is a replacement.
2566 * 3. Anything else - this is an error.
2568 if (list
== Py_None
|| list
== NULL
)
2571 PyInt n
= (int)(hi
- lo
);
2572 buf_T
*savebuf
= curbuf
;
2577 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2578 PyErr_SetVim(_("cannot save undo information"));
2581 for (i
= 0; i
< n
; ++i
)
2583 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2585 PyErr_SetVim(_("cannot delete line"));
2589 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2591 if (buf
== curwin
->w_buffer
)
2592 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)-n
);
2597 if (PyErr_Occurred() || VimErrorCheck())
2605 else if (PyList_Check(list
))
2608 PyInt new_len
= PyList_Size(list
);
2609 PyInt old_len
= hi
- lo
;
2610 PyInt extra
= 0; /* lines added to text, can be negative */
2614 if (new_len
== 0) /* avoid allocating zero bytes */
2618 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
2626 for (i
= 0; i
< new_len
; ++i
)
2628 PyObject
*line
= PyList_GetItem(list
, i
);
2630 array
[i
] = StringToLine(line
);
2631 if (array
[i
] == NULL
)
2634 vim_free(array
[--i
]);
2645 if (u_save((linenr_T
)(lo
-1), (linenr_T
)hi
) == FAIL
)
2646 PyErr_SetVim(_("cannot save undo information"));
2648 /* If the size of the range is reducing (ie, new_len < old_len) we
2649 * need to delete some old_len. We do this at the start, by
2650 * repeatedly deleting line "lo".
2652 if (!PyErr_Occurred())
2654 for (i
= 0; i
< old_len
- new_len
; ++i
)
2655 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2657 PyErr_SetVim(_("cannot delete line"));
2663 /* For as long as possible, replace the existing old_len with the
2664 * new old_len. This is a more efficient operation, as it requires
2665 * less memory allocation and freeing.
2667 if (!PyErr_Occurred())
2669 for (i
= 0; i
< old_len
&& i
< new_len
; ++i
)
2670 if (ml_replace((linenr_T
)(lo
+i
), (char_u
*)array
[i
], FALSE
)
2673 PyErr_SetVim(_("cannot replace line"));
2680 /* Now we may need to insert the remaining new old_len. If we do, we
2681 * must free the strings as we finish with them (we can't pass the
2682 * responsibility to vim in this case).
2684 if (!PyErr_Occurred())
2688 if (ml_append((linenr_T
)(lo
+ i
- 1),
2689 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2691 PyErr_SetVim(_("cannot insert line"));
2700 /* Free any left-over old_len, as a result of an error */
2707 /* Free the array of old_len. All of its contents have now
2708 * been dealt with (either freed, or the responsibility passed
2713 /* Adjust marks. Invalidate any which lie in the
2714 * changed range, and move any in the remainder of the buffer.
2716 mark_adjust((linenr_T
)lo
, (linenr_T
)(hi
- 1),
2717 (long)MAXLNUM
, (long)extra
);
2718 changed_lines((linenr_T
)lo
, 0, (linenr_T
)hi
, (long)extra
);
2720 if (buf
== curwin
->w_buffer
)
2721 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)extra
);
2725 if (PyErr_Occurred() || VimErrorCheck())
2729 *len_change
= new_len
- old_len
;
2735 PyErr_BadArgument();
2740 /* Insert a number of lines into the specified buffer after the specifed line.
2741 * The line number is in Vim format (1-based). The lines to be inserted are
2742 * given as a Python list of string objects or as a single string. The lines
2743 * to be added are checked for validity and correct format. Errors are
2744 * returned as a value of FAIL. The return value is OK on success.
2745 * If OK is returned and len_change is not NULL, *len_change
2746 * is set to the change in the buffer length.
2749 InsertBufferLines(buf_T
*buf
, PyInt n
, PyObject
*lines
, PyInt
*len_change
)
2751 /* First of all, we check the type of the supplied Python object.
2752 * It must be a string or a list, or the call is in error.
2754 if (PyString_Check(lines
))
2756 char *str
= StringToLine(lines
);
2767 if (u_save((linenr_T
)n
, (linenr_T
)(n
+1)) == FAIL
)
2768 PyErr_SetVim(_("cannot save undo information"));
2769 else if (ml_append((linenr_T
)n
, (char_u
*)str
, 0, FALSE
) == FAIL
)
2770 PyErr_SetVim(_("cannot insert line"));
2772 appended_lines_mark((linenr_T
)n
, 1L);
2776 update_screen(VALID
);
2778 if (PyErr_Occurred() || VimErrorCheck())
2786 else if (PyList_Check(lines
))
2789 PyInt size
= PyList_Size(lines
);
2793 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2800 for (i
= 0; i
< size
; ++i
)
2802 PyObject
*line
= PyList_GetItem(lines
, i
);
2803 array
[i
] = StringToLine(line
);
2805 if (array
[i
] == NULL
)
2808 vim_free(array
[--i
]);
2819 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2820 PyErr_SetVim(_("cannot save undo information"));
2823 for (i
= 0; i
< size
; ++i
)
2825 if (ml_append((linenr_T
)(n
+ i
),
2826 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2828 PyErr_SetVim(_("cannot insert line"));
2830 /* Free the rest of the lines */
2832 vim_free(array
[i
++]);
2839 appended_lines_mark((linenr_T
)n
, (long)i
);
2842 /* Free the array of lines. All of its contents have now
2848 update_screen(VALID
);
2850 if (PyErr_Occurred() || VimErrorCheck())
2860 PyErr_BadArgument();
2865 /* Convert a Vim line into a Python string.
2866 * All internal newlines are replaced by null characters.
2868 * On errors, the Python exception data is set, and NULL is returned.
2871 LineToString(const char *str
)
2874 PyInt len
= strlen(str
);
2877 /* Allocate an Python string object, with uninitialised contents. We
2878 * must do it this way, so that we can modify the string in place
2879 * later. See the Python source, Objects/stringobject.c for details.
2881 result
= PyString_FromStringAndSize(NULL
, len
);
2885 p
= PyString_AsString(result
);
2901 /* Convert a Python string into a Vim line.
2903 * The result is in allocated memory. All internal nulls are replaced by
2904 * newline characters. It is an error for the string to contain newline
2907 * On errors, the Python exception data is set, and NULL is returned.
2910 StringToLine(PyObject
*obj
)
2918 if (obj
== NULL
|| !PyString_Check(obj
))
2920 PyErr_BadArgument();
2924 str
= PyString_AsString(obj
);
2925 len
= PyString_Size(obj
);
2928 * Error checking: String must not contain newlines, as we
2929 * are replacing a single line, and we must replace it with
2931 * A trailing newline is removed, so that append(f.readlines()) works.
2933 p
= memchr(str
, '\n', len
);
2936 if (p
== str
+ len
- 1)
2940 PyErr_SetVim(_("string cannot contain newlines"));
2945 /* Create a copy of the string, with internal nulls replaced by
2946 * newline characters, as is the vim convention.
2948 save
= (char *)alloc((unsigned)(len
+1));
2955 for (i
= 0; i
< len
; ++i
)
2968 /* Check to see whether a Vim error has been reported, or a keyboard
2969 * interrupt has been detected.
2976 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2979 else if (did_emsg
&& !PyErr_Occurred())
2981 PyErr_SetNone(VimError
);
2989 /* Don't generate a prototype for the next function, it generates an error on
2990 * newer Python versions. */
2991 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
2994 Py_GetProgramName(void)
2998 #endif /* Python 1.4 */