1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
10 * Python extensions by Paul Moore.
11 * Changes for Unix by David Leonard.
13 * This consists of four parts:
14 * 1. Python interpreter main program
15 * 2. Python output stream: writes output via [e]msg().
16 * 3. Implementation of the Vim module for Python
17 * 4. Utility functions for handling the interface between Vim and Python.
24 /* Python.h defines _POSIX_THREADS itself (if needed) */
26 # undef _POSIX_THREADS
29 #if defined(_WIN32) && defined (HAVE_FCNTL_H)
38 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */
40 #ifdef _POSIX_C_SOURCE
41 # undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
44 # undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
47 #define PY_SSIZE_T_CLEAN
49 #ifdef FEAT_GUI_MACVIM
50 # include <Python/Python.h>
55 #if defined(MACOS) && !defined(MACOS_X_UNIX)
57 # include <CodeFragments.h>
59 #undef main /* Defined in python.h - aargh */
60 #undef HAVE_FCNTL_H /* Clash with os_win32.h */
62 #if !defined(FEAT_PYTHON) && defined(PROTO)
63 /* Use this to be able to generate prototypes without python being used. */
64 # define PyObject Py_ssize_t
65 # define PyThreadState Py_ssize_t
66 # define PyTypeObject Py_ssize_t
67 struct PyMethodDef
{ Py_ssize_t a
; };
68 # define PySequenceMethods Py_ssize_t
71 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
72 # define PyInt Py_ssize_t
73 # define PyInquiry lenfunc
74 # define PyIntArgFunc ssizeargfunc
75 # define PyIntIntArgFunc ssizessizeargfunc
76 # define PyIntObjArgProc ssizeobjargproc
77 # define PyIntIntObjArgProc ssizessizeobjargproc
78 # define Py_ssize_t_fmt "n"
81 # define PyInquiry inquiry
82 # define PyIntArgFunc intargfunc
83 # define PyIntIntArgFunc intintargfunc
84 # define PyIntObjArgProc intobjargproc
85 # define PyIntIntObjArgProc intintobjargproc
86 # define Py_ssize_t_fmt "i"
90 #define single_input 256
91 #define file_input 257
92 #define eval_input 258
94 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
95 /* Python 2.3: can invoke ":python" recursively. */
96 # define PY_CAN_RECURSE
99 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
100 # ifndef DYNAMIC_PYTHON
101 # define HINSTANCE long_u /* for generating prototypes */
104 /* This makes if_python.c compile without warnings against Python 2.5
105 * on Win32 and Win64. */
106 #undef PyRun_SimpleString
108 #undef PyArg_ParseTuple
110 #undef Py_InitModule4
111 #undef Py_InitModule4_64
116 # define PyArg_Parse dll_PyArg_Parse
117 # define PyArg_ParseTuple dll_PyArg_ParseTuple
118 # define PyDict_SetItemString dll_PyDict_SetItemString
119 # define PyErr_BadArgument dll_PyErr_BadArgument
120 # define PyErr_Clear dll_PyErr_Clear
121 # define PyErr_NoMemory dll_PyErr_NoMemory
122 # define PyErr_Occurred dll_PyErr_Occurred
123 # define PyErr_SetNone dll_PyErr_SetNone
124 # define PyErr_SetString dll_PyErr_SetString
125 # define PyEval_InitThreads dll_PyEval_InitThreads
126 # define PyEval_RestoreThread dll_PyEval_RestoreThread
127 # define PyEval_SaveThread dll_PyEval_SaveThread
128 # ifdef PY_CAN_RECURSE
129 # define PyGILState_Ensure dll_PyGILState_Ensure
130 # define PyGILState_Release dll_PyGILState_Release
132 # define PyInt_AsLong dll_PyInt_AsLong
133 # define PyInt_FromLong dll_PyInt_FromLong
134 # define PyInt_Type (*dll_PyInt_Type)
135 # define PyList_GetItem dll_PyList_GetItem
136 # define PyList_Append dll_PyList_Append
137 # define PyList_New dll_PyList_New
138 # define PyList_SetItem dll_PyList_SetItem
139 # define PyList_Size dll_PyList_Size
140 # define PyList_Type (*dll_PyList_Type)
141 # define PyImport_ImportModule dll_PyImport_ImportModule
142 # define PyDict_New dll_PyDict_New
143 # define PyDict_GetItemString dll_PyDict_GetItemString
144 # define PyModule_GetDict dll_PyModule_GetDict
145 # define PyRun_SimpleString dll_PyRun_SimpleString
146 # define PyString_AsString dll_PyString_AsString
147 # define PyString_FromString dll_PyString_FromString
148 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize
149 # define PyString_Size dll_PyString_Size
150 # define PyString_Type (*dll_PyString_Type)
151 # define PySys_SetObject dll_PySys_SetObject
152 # define PySys_SetArgv dll_PySys_SetArgv
153 # define PyType_Type (*dll_PyType_Type)
154 # define Py_BuildValue dll_Py_BuildValue
155 # define Py_FindMethod dll_Py_FindMethod
156 # define Py_InitModule4 dll_Py_InitModule4
157 # define Py_Initialize dll_Py_Initialize
158 # define Py_Finalize dll_Py_Finalize
159 # define Py_IsInitialized dll_Py_IsInitialized
160 # define _PyObject_New dll__PyObject_New
161 # define _Py_NoneStruct (*dll__Py_NoneStruct)
162 # define PyObject_Init dll__PyObject_Init
163 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
164 # define PyType_IsSubtype dll_PyType_IsSubtype
166 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
167 # define PyObject_Malloc dll_PyObject_Malloc
168 # define PyObject_Free dll_PyObject_Free
172 * Pointers for dynamic link
174 static int(*dll_PyArg_Parse
)(PyObject
*, char *, ...);
175 static int(*dll_PyArg_ParseTuple
)(PyObject
*, char *, ...);
176 static int(*dll_PyDict_SetItemString
)(PyObject
*dp
, char *key
, PyObject
*item
);
177 static int(*dll_PyErr_BadArgument
)(void);
178 static void(*dll_PyErr_Clear
)(void);
179 static PyObject
*(*dll_PyErr_NoMemory
)(void);
180 static PyObject
*(*dll_PyErr_Occurred
)(void);
181 static void(*dll_PyErr_SetNone
)(PyObject
*);
182 static void(*dll_PyErr_SetString
)(PyObject
*, const char *);
183 static void(*dll_PyEval_InitThreads
)(void);
184 static void(*dll_PyEval_RestoreThread
)(PyThreadState
*);
185 static PyThreadState
*(*dll_PyEval_SaveThread
)(void);
186 # ifdef PY_CAN_RECURSE
187 static PyGILState_STATE (*dll_PyGILState_Ensure
)(void);
188 static void (*dll_PyGILState_Release
)(PyGILState_STATE
);
190 static long(*dll_PyInt_AsLong
)(PyObject
*);
191 static PyObject
*(*dll_PyInt_FromLong
)(long);
192 static PyTypeObject
* dll_PyInt_Type
;
193 static PyObject
*(*dll_PyList_GetItem
)(PyObject
*, PyInt
);
194 static PyObject
*(*dll_PyList_Append
)(PyObject
*, PyObject
*);
195 static PyObject
*(*dll_PyList_New
)(PyInt size
);
196 static int(*dll_PyList_SetItem
)(PyObject
*, PyInt
, PyObject
*);
197 static PyInt(*dll_PyList_Size
)(PyObject
*);
198 static PyTypeObject
* dll_PyList_Type
;
199 static PyObject
*(*dll_PyImport_ImportModule
)(const char *);
200 static PyObject
*(*dll_PyDict_New
)(void);
201 static PyObject
*(*dll_PyDict_GetItemString
)(PyObject
*, const char *);
202 static PyObject
*(*dll_PyModule_GetDict
)(PyObject
*);
203 static int(*dll_PyRun_SimpleString
)(char *);
204 static char*(*dll_PyString_AsString
)(PyObject
*);
205 static PyObject
*(*dll_PyString_FromString
)(const char *);
206 static PyObject
*(*dll_PyString_FromStringAndSize
)(const char *, PyInt
);
207 static PyInt(*dll_PyString_Size
)(PyObject
*);
208 static PyTypeObject
* dll_PyString_Type
;
209 static int(*dll_PySys_SetObject
)(char *, PyObject
*);
210 static int(*dll_PySys_SetArgv
)(int, char **);
211 static PyTypeObject
* dll_PyType_Type
;
212 static PyObject
*(*dll_Py_BuildValue
)(char *, ...);
213 static PyObject
*(*dll_Py_FindMethod
)(struct PyMethodDef
[], PyObject
*, char *);
214 static PyObject
*(*dll_Py_InitModule4
)(char *, struct PyMethodDef
*, char *, PyObject
*, int);
215 static void(*dll_Py_Initialize
)(void);
216 static void(*dll_Py_Finalize
)(void);
217 static int(*dll_Py_IsInitialized
)(void);
218 static PyObject
*(*dll__PyObject_New
)(PyTypeObject
*, PyObject
*);
219 static PyObject
*(*dll__PyObject_Init
)(PyObject
*, PyTypeObject
*);
220 static PyObject
* dll__Py_NoneStruct
;
221 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
222 static int (*dll_PyType_IsSubtype
)(PyTypeObject
*, PyTypeObject
*);
224 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
225 static void* (*dll_PyObject_Malloc
)(size_t);
226 static void (*dll_PyObject_Free
)(void*);
229 static HINSTANCE hinstPython
= 0; /* Instance of python.dll */
231 /* Imported exception objects */
232 static PyObject
*imp_PyExc_AttributeError
;
233 static PyObject
*imp_PyExc_IndexError
;
234 static PyObject
*imp_PyExc_KeyboardInterrupt
;
235 static PyObject
*imp_PyExc_TypeError
;
236 static PyObject
*imp_PyExc_ValueError
;
238 # define PyExc_AttributeError imp_PyExc_AttributeError
239 # define PyExc_IndexError imp_PyExc_IndexError
240 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
241 # define PyExc_TypeError imp_PyExc_TypeError
242 # define PyExc_ValueError imp_PyExc_ValueError
245 * Table of name to function pointer of python.
247 # define PYTHON_PROC FARPROC
252 } python_funcname_table
[] =
254 {"PyArg_Parse", (PYTHON_PROC
*)&dll_PyArg_Parse
},
255 {"PyArg_ParseTuple", (PYTHON_PROC
*)&dll_PyArg_ParseTuple
},
256 {"PyDict_SetItemString", (PYTHON_PROC
*)&dll_PyDict_SetItemString
},
257 {"PyErr_BadArgument", (PYTHON_PROC
*)&dll_PyErr_BadArgument
},
258 {"PyErr_Clear", (PYTHON_PROC
*)&dll_PyErr_Clear
},
259 {"PyErr_NoMemory", (PYTHON_PROC
*)&dll_PyErr_NoMemory
},
260 {"PyErr_Occurred", (PYTHON_PROC
*)&dll_PyErr_Occurred
},
261 {"PyErr_SetNone", (PYTHON_PROC
*)&dll_PyErr_SetNone
},
262 {"PyErr_SetString", (PYTHON_PROC
*)&dll_PyErr_SetString
},
263 {"PyEval_InitThreads", (PYTHON_PROC
*)&dll_PyEval_InitThreads
},
264 {"PyEval_RestoreThread", (PYTHON_PROC
*)&dll_PyEval_RestoreThread
},
265 {"PyEval_SaveThread", (PYTHON_PROC
*)&dll_PyEval_SaveThread
},
266 # ifdef PY_CAN_RECURSE
267 {"PyGILState_Ensure", (PYTHON_PROC
*)&dll_PyGILState_Ensure
},
268 {"PyGILState_Release", (PYTHON_PROC
*)&dll_PyGILState_Release
},
270 {"PyInt_AsLong", (PYTHON_PROC
*)&dll_PyInt_AsLong
},
271 {"PyInt_FromLong", (PYTHON_PROC
*)&dll_PyInt_FromLong
},
272 {"PyInt_Type", (PYTHON_PROC
*)&dll_PyInt_Type
},
273 {"PyList_GetItem", (PYTHON_PROC
*)&dll_PyList_GetItem
},
274 {"PyList_Append", (PYTHON_PROC
*)&dll_PyList_Append
},
275 {"PyList_New", (PYTHON_PROC
*)&dll_PyList_New
},
276 {"PyList_SetItem", (PYTHON_PROC
*)&dll_PyList_SetItem
},
277 {"PyList_Size", (PYTHON_PROC
*)&dll_PyList_Size
},
278 {"PyList_Type", (PYTHON_PROC
*)&dll_PyList_Type
},
279 {"PyImport_ImportModule", (PYTHON_PROC
*)&dll_PyImport_ImportModule
},
280 {"PyDict_GetItemString", (PYTHON_PROC
*)&dll_PyDict_GetItemString
},
281 {"PyDict_New", (PYTHON_PROC
*)&dll_PyDict_New
},
282 {"PyModule_GetDict", (PYTHON_PROC
*)&dll_PyModule_GetDict
},
283 {"PyRun_SimpleString", (PYTHON_PROC
*)&dll_PyRun_SimpleString
},
284 {"PyString_AsString", (PYTHON_PROC
*)&dll_PyString_AsString
},
285 {"PyString_FromString", (PYTHON_PROC
*)&dll_PyString_FromString
},
286 {"PyString_FromStringAndSize", (PYTHON_PROC
*)&dll_PyString_FromStringAndSize
},
287 {"PyString_Size", (PYTHON_PROC
*)&dll_PyString_Size
},
288 {"PyString_Type", (PYTHON_PROC
*)&dll_PyString_Type
},
289 {"PySys_SetObject", (PYTHON_PROC
*)&dll_PySys_SetObject
},
290 {"PySys_SetArgv", (PYTHON_PROC
*)&dll_PySys_SetArgv
},
291 {"PyType_Type", (PYTHON_PROC
*)&dll_PyType_Type
},
292 {"Py_BuildValue", (PYTHON_PROC
*)&dll_Py_BuildValue
},
293 {"Py_FindMethod", (PYTHON_PROC
*)&dll_Py_FindMethod
},
294 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
295 {"Py_InitModule4_64", (PYTHON_PROC
*)&dll_Py_InitModule4
},
297 {"Py_InitModule4", (PYTHON_PROC
*)&dll_Py_InitModule4
},
299 {"Py_Initialize", (PYTHON_PROC
*)&dll_Py_Initialize
},
300 {"Py_Finalize", (PYTHON_PROC
*)&dll_Py_Finalize
},
301 {"Py_IsInitialized", (PYTHON_PROC
*)&dll_Py_IsInitialized
},
302 {"_PyObject_New", (PYTHON_PROC
*)&dll__PyObject_New
},
303 {"PyObject_Init", (PYTHON_PROC
*)&dll__PyObject_Init
},
304 {"_Py_NoneStruct", (PYTHON_PROC
*)&dll__Py_NoneStruct
},
305 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
306 {"PyType_IsSubtype", (PYTHON_PROC
*)&dll_PyType_IsSubtype
},
308 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
309 {"PyObject_Malloc", (PYTHON_PROC
*)&dll_PyObject_Malloc
},
310 {"PyObject_Free", (PYTHON_PROC
*)&dll_PyObject_Free
},
319 end_dynamic_python(void)
323 FreeLibrary(hinstPython
);
329 * Load library and get all pointers.
330 * Parameter 'libname' provides name of DLL.
334 python_runtime_link_init(char *libname
, int verbose
)
340 hinstPython
= LoadLibrary(libname
);
344 EMSG2(_(e_loadlib
), libname
);
348 for (i
= 0; python_funcname_table
[i
].ptr
; ++i
)
350 if ((*python_funcname_table
[i
].ptr
= GetProcAddress(hinstPython
,
351 python_funcname_table
[i
].name
)) == NULL
)
353 FreeLibrary(hinstPython
);
356 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
364 * If python is enabled (there is installed python on Windows system) return
368 python_enabled(int verbose
)
370 return python_runtime_link_init(DYNAMIC_PYTHON_DLL
, verbose
) == OK
;
373 /* Load the standard Python exceptions - don't import the symbols from the
374 * DLL, as this can cause errors (importing data symbols is not reliable).
376 static void get_exceptions
__ARGS((void));
381 PyObject
*exmod
= PyImport_ImportModule("exceptions");
382 PyObject
*exdict
= PyModule_GetDict(exmod
);
383 imp_PyExc_AttributeError
= PyDict_GetItemString(exdict
, "AttributeError");
384 imp_PyExc_IndexError
= PyDict_GetItemString(exdict
, "IndexError");
385 imp_PyExc_KeyboardInterrupt
= PyDict_GetItemString(exdict
, "KeyboardInterrupt");
386 imp_PyExc_TypeError
= PyDict_GetItemString(exdict
, "TypeError");
387 imp_PyExc_ValueError
= PyDict_GetItemString(exdict
, "ValueError");
388 Py_XINCREF(imp_PyExc_AttributeError
);
389 Py_XINCREF(imp_PyExc_IndexError
);
390 Py_XINCREF(imp_PyExc_KeyboardInterrupt
);
391 Py_XINCREF(imp_PyExc_TypeError
);
392 Py_XINCREF(imp_PyExc_ValueError
);
395 #endif /* DYNAMIC_PYTHON */
397 /******************************************************
398 * Internal function prototypes.
401 static void DoPythonCommand(exarg_T
*, const char *);
402 static PyInt RangeStart
;
403 static PyInt RangeEnd
;
405 static void PythonIO_Flush(void);
406 static int PythonIO_Init(void);
407 static int PythonMod_Init(void);
409 /* Utility functions for the vim/python interface
410 * ----------------------------------------------
412 static PyObject
*GetBufferLine(buf_T
*, PyInt
);
413 static PyObject
*GetBufferLineList(buf_T
*, PyInt
, PyInt
);
415 static int SetBufferLine(buf_T
*, PyInt
, PyObject
*, PyInt
*);
416 static int SetBufferLineList(buf_T
*, PyInt
, PyInt
, PyObject
*, PyInt
*);
417 static int InsertBufferLines(buf_T
*, PyInt
, PyObject
*, PyInt
*);
419 static PyObject
*LineToString(const char *);
420 static char *StringToLine(PyObject
*);
422 static int VimErrorCheck(void);
424 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
426 /******************************************************
427 * 1. Python interpreter main program.
430 static int initialised
= 0;
432 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
433 typedef PyObject PyThreadState
;
436 #ifdef PY_CAN_RECURSE
437 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
439 static PyThreadState
*saved_python_thread
= NULL
;
443 * Suspend a thread of the Python interpreter, other threads are allowed to
447 Python_SaveThread(void)
449 #ifdef PY_CAN_RECURSE
450 PyGILState_Release(pygilstate
);
452 saved_python_thread
= PyEval_SaveThread();
457 * Restore a thread of the Python interpreter, waits for other threads to
461 Python_RestoreThread(void)
463 #ifdef PY_CAN_RECURSE
464 pygilstate
= PyGILState_Ensure();
466 PyEval_RestoreThread(saved_python_thread
);
467 saved_python_thread
= NULL
;
472 * obtain a lock on the Vim data structures
474 static void Python_Lock_Vim(void)
479 * release a lock on the Vim data structures
481 static void Python_Release_Vim(void)
488 static int recurse
= 0;
490 /* If a crash occurs while doing this, don't try again. */
496 #ifdef DYNAMIC_PYTHON
497 if (hinstPython
&& Py_IsInitialized())
499 Python_RestoreThread(); /* enter python */
502 end_dynamic_python();
504 if (Py_IsInitialized())
506 Python_RestoreThread(); /* enter python */
519 #ifdef DYNAMIC_PYTHON
520 if (!python_enabled(TRUE
))
522 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
527 #if !defined(MACOS) || defined(MACOS_X_UNIX)
532 /* initialise threads */
533 PyEval_InitThreads();
535 #ifdef DYNAMIC_PYTHON
542 if (PythonMod_Init())
545 /* Remove the element from sys.path that was added because of our
546 * argv[0] value in PythonMod_Init(). Previously we used an empty
547 * string, but dependinding on the OS we then get an empty entry or
548 * the current directory in sys.path. */
549 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
551 /* the first python thread is vim's, release the lock */
560 /* We call PythonIO_Flush() here to print any Python errors.
561 * This is OK, as it is possible to call this function even
562 * if PythonIO_Init() has not completed successfully (it will
563 * not do anything in this case).
573 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
575 #ifndef PY_CAN_RECURSE
576 static int recursive
= 0;
578 #if defined(MACOS) && !defined(MACOS_X_UNIX)
581 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
585 #ifndef PY_CAN_RECURSE
588 EMSG(_("E659: Cannot invoke Python recursively"));
594 #if defined(MACOS) && !defined(MACOS_X_UNIX)
596 /* Check if the Python library is available */
597 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
603 RangeStart
= eap
->line1
;
604 RangeEnd
= eap
->line2
;
605 Python_Release_Vim(); /* leave vim */
607 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
608 /* Python only works properly when the LC_NUMERIC locale is "C". */
609 saved_locale
= setlocale(LC_NUMERIC
, NULL
);
610 if (saved_locale
== NULL
|| STRCMP(saved_locale
, "C") == 0)
614 /* Need to make a copy, value may change when setting new locale. */
615 saved_locale
= (char *)vim_strsave((char_u
*)saved_locale
);
616 (void)setlocale(LC_NUMERIC
, "C");
620 Python_RestoreThread(); /* enter python */
622 PyRun_SimpleString((char *)(cmd
));
624 Python_SaveThread(); /* leave python */
626 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
627 if (saved_locale
!= NULL
)
629 (void)setlocale(LC_NUMERIC
, saved_locale
);
630 vim_free(saved_locale
);
634 Python_Lock_Vim(); /* enter vim */
636 #if defined(MACOS) && !defined(MACOS_X_UNIX)
641 #ifndef PY_CAN_RECURSE
644 return; /* keeps lint happy */
651 ex_python(exarg_T
*eap
)
655 script
= script_get(eap
, eap
->arg
);
659 DoPythonCommand(eap
, (char *)eap
->arg
);
661 DoPythonCommand(eap
, (char *)script
);
666 #define BUFFER_SIZE 1024
672 ex_pyfile(exarg_T
*eap
)
674 static char buffer
[BUFFER_SIZE
];
675 const char *file
= (char *)eap
->arg
;
678 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
679 * stdio file pointer, but Vim and the Python DLL are compiled with
680 * different options under Windows, meaning that stdio pointers aren't
681 * compatible between the two. Yuk.
683 * Put the string "execfile('file')" into buffer. But, we need to
684 * escape any backslashes or single quotes in the file name, so that
685 * Python won't mangle the file name.
687 strcpy(buffer
, "execfile('");
688 p
= buffer
+ 10; /* size of "execfile('" */
690 while (*file
&& p
< buffer
+ (BUFFER_SIZE
- 3))
692 if (*file
== '\\' || *file
== '\'')
697 /* If we didn't finish the file name, we hit a buffer overflow */
701 /* Put in the terminating "')" and a null */
706 /* Execute the file */
707 DoPythonCommand(eap
, buffer
);
710 /******************************************************
711 * 2. Python output stream: writes output via [e]msg().
714 /* Implementation functions
717 static PyObject
*OutputGetattr(PyObject
*, char *);
718 static int OutputSetattr(PyObject
*, char *, PyObject
*);
720 static PyObject
*OutputWrite(PyObject
*, PyObject
*);
721 static PyObject
*OutputWritelines(PyObject
*, PyObject
*);
723 typedef void (*writefn
)(char_u
*);
724 static void writer(writefn fn
, char_u
*str
, PyInt n
);
726 /* Output object definition
736 static struct PyMethodDef OutputMethods
[] = {
737 /* name, function, calling, documentation */
738 {"write", OutputWrite
, 1, "" },
739 {"writelines", OutputWritelines
, 1, "" },
740 { NULL
, NULL
, 0, NULL
}
743 static PyTypeObject OutputType
= {
744 PyObject_HEAD_INIT(0)
747 sizeof(OutputObject
),
752 (getattrfunc
) OutputGetattr
,
753 (setattrfunc
) OutputSetattr
,
769 OutputGetattr(PyObject
*self
, char *name
)
771 if (strcmp(name
, "softspace") == 0)
772 return PyInt_FromLong(((OutputObject
*)(self
))->softspace
);
774 return Py_FindMethod(OutputMethods
, self
, name
);
778 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
781 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
785 if (strcmp(name
, "softspace") == 0)
787 if (!PyInt_Check(val
)) {
788 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
792 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
796 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
803 OutputWrite(PyObject
*self
, PyObject
*args
)
807 int error
= ((OutputObject
*)(self
))->error
;
809 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
812 Py_BEGIN_ALLOW_THREADS
814 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
815 Python_Release_Vim();
823 OutputWritelines(PyObject
*self
, PyObject
*args
)
828 int error
= ((OutputObject
*)(self
))->error
;
830 if (!PyArg_ParseTuple(args
, "O", &list
))
834 if (!PyList_Check(list
)) {
835 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
840 n
= PyList_Size(list
);
842 for (i
= 0; i
< n
; ++i
)
844 PyObject
*line
= PyList_GetItem(list
, i
);
848 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
849 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
854 Py_BEGIN_ALLOW_THREADS
856 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
857 Python_Release_Vim();
866 /* Output buffer management
869 static char_u
*buffer
= NULL
;
870 static PyInt buffer_len
= 0;
871 static PyInt buffer_size
= 0;
873 static writefn old_fn
= NULL
;
876 buffer_ensure(PyInt n
)
884 new_size
= buffer_size
;
888 if (new_size
!= buffer_size
)
890 new_buffer
= alloc((unsigned)new_size
);
891 if (new_buffer
== NULL
)
896 memcpy(new_buffer
, buffer
, buffer_len
);
901 buffer_size
= new_size
;
908 if (old_fn
&& buffer_len
)
910 buffer
[buffer_len
] = 0;
918 writer(writefn fn
, char_u
*str
, PyInt n
)
922 if (fn
!= old_fn
&& old_fn
!= NULL
)
927 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
929 PyInt len
= ptr
- str
;
931 buffer_ensure(buffer_len
+ len
+ 1);
933 memcpy(buffer
+ buffer_len
, str
, len
);
935 buffer
[buffer_len
] = 0;
942 /* Put the remaining text into the buffer for later printing */
943 buffer_ensure(buffer_len
+ n
+ 1);
944 memcpy(buffer
+ buffer_len
, str
, n
);
950 static OutputObject Output
=
952 PyObject_HEAD_INIT(&OutputType
)
957 static OutputObject Error
=
959 PyObject_HEAD_INIT(&OutputType
)
968 OutputType
.ob_type
= &PyType_Type
;
970 PySys_SetObject("stdout", (PyObject
*)(void *)&Output
);
971 PySys_SetObject("stderr", (PyObject
*)(void *)&Error
);
973 if (PyErr_Occurred())
975 EMSG(_("E264: Python: Error initialising I/O objects"));
982 /******************************************************
983 * 3. Implementation of the Vim module for Python
986 /* Vim module - Implementation functions
987 * -------------------------------------
990 static PyObject
*VimError
;
992 static PyObject
*VimCommand(PyObject
*, PyObject
*);
993 static PyObject
*VimEval(PyObject
*, PyObject
*);
995 /* Window type - Implementation functions
996 * --------------------------------------
1006 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
1008 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1010 static PyObject
*WindowNew(win_T
*);
1012 static void WindowDestructor(PyObject
*);
1013 static PyObject
*WindowGetattr(PyObject
*, char *);
1014 static int WindowSetattr(PyObject
*, char *, PyObject
*);
1015 static PyObject
*WindowRepr(PyObject
*);
1017 /* Buffer type - Implementation functions
1018 * --------------------------------------
1028 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1030 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1032 static PyObject
*BufferNew (buf_T
*);
1034 static void BufferDestructor(PyObject
*);
1035 static PyObject
*BufferGetattr(PyObject
*, char *);
1036 static PyObject
*BufferRepr(PyObject
*);
1038 static PyInt
BufferLength(PyObject
*);
1039 static PyObject
*BufferItem(PyObject
*, PyInt
);
1040 static PyObject
*BufferSlice(PyObject
*, PyInt
, PyInt
);
1041 static PyInt
BufferAssItem(PyObject
*, PyInt
, PyObject
*);
1042 static PyInt
BufferAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1044 static PyObject
*BufferAppend(PyObject
*, PyObject
*);
1045 static PyObject
*BufferMark(PyObject
*, PyObject
*);
1046 static PyObject
*BufferRange(PyObject
*, PyObject
*);
1048 /* Line range type - Implementation functions
1049 * --------------------------------------
1061 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1063 static PyObject
*RangeNew(buf_T
*, PyInt
, PyInt
);
1065 static void RangeDestructor(PyObject
*);
1066 static PyObject
*RangeGetattr(PyObject
*, char *);
1067 static PyObject
*RangeRepr(PyObject
*);
1069 static PyInt
RangeLength(PyObject
*);
1070 static PyObject
*RangeItem(PyObject
*, PyInt
);
1071 static PyObject
*RangeSlice(PyObject
*, PyInt
, PyInt
);
1072 static PyInt
RangeAssItem(PyObject
*, PyInt
, PyObject
*);
1073 static PyInt
RangeAssSlice(PyObject
*, PyInt
, PyInt
, PyObject
*);
1075 static PyObject
*RangeAppend(PyObject
*, PyObject
*);
1077 /* Window list type - Implementation functions
1078 * -------------------------------------------
1081 static PyInt
WinListLength(PyObject
*);
1082 static PyObject
*WinListItem(PyObject
*, PyInt
);
1084 /* Buffer list type - Implementation functions
1085 * -------------------------------------------
1088 static PyInt
BufListLength(PyObject
*);
1089 static PyObject
*BufListItem(PyObject
*, PyInt
);
1091 /* Current objects type - Implementation functions
1092 * -----------------------------------------------
1095 static PyObject
*CurrentGetattr(PyObject
*, char *);
1096 static int CurrentSetattr(PyObject
*, char *, PyObject
*);
1098 /* Vim module - Definitions
1101 static struct PyMethodDef VimMethods
[] = {
1102 /* name, function, calling, documentation */
1103 {"command", VimCommand
, 1, "Execute a Vim ex-mode command" },
1104 {"eval", VimEval
, 1, "Evaluate an expression using Vim evaluator" },
1105 { NULL
, NULL
, 0, NULL
}
1108 /* Vim module - Implementation
1111 VimCommand(PyObject
*self UNUSED
, PyObject
*args
)
1116 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1121 Py_BEGIN_ALLOW_THREADS
1124 do_cmdline_cmd((char_u
*)cmd
);
1125 update_screen(VALID
);
1127 Python_Release_Vim();
1128 Py_END_ALLOW_THREADS
1130 if (VimErrorCheck())
1141 * Function to translate a typval_T into a PyObject; this will recursively
1142 * translate lists/dictionaries into their Python equivalents.
1144 * The depth parameter is to avoid infinite recursion, set it to 1 when
1145 * you call VimToPython.
1148 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1152 char ptrBuf
[NUMBUFLEN
];
1154 /* Avoid infinite recursion */
1162 /* Check if we run into a recursive loop. The item must be in lookupDict
1163 * then and we can use it again. */
1164 if ((our_tv
->v_type
== VAR_LIST
&& our_tv
->vval
.v_list
!= NULL
)
1165 || (our_tv
->v_type
== VAR_DICT
&& our_tv
->vval
.v_dict
!= NULL
))
1167 sprintf(ptrBuf
, PRINTF_DECIMAL_LONG_U
,
1168 our_tv
->v_type
== VAR_LIST
? (long_u
)our_tv
->vval
.v_list
1169 : (long_u
)our_tv
->vval
.v_dict
);
1170 result
= PyDict_GetItemString(lookupDict
, ptrBuf
);
1178 if (our_tv
->v_type
== VAR_STRING
)
1180 result
= Py_BuildValue("s", our_tv
->vval
.v_string
);
1182 else if (our_tv
->v_type
== VAR_NUMBER
)
1184 char buf
[NUMBUFLEN
];
1186 /* For backwards compatibility numbers are stored as strings. */
1187 sprintf(buf
, "%ld", (long)our_tv
->vval
.v_number
);
1188 result
= Py_BuildValue("s", buf
);
1191 else if (our_tv
->v_type
== VAR_FLOAT
)
1193 char buf
[NUMBUFLEN
];
1195 sprintf(buf
, "%f", our_tv
->vval
.v_float
);
1196 result
= Py_BuildValue("s", buf
);
1199 else if (our_tv
->v_type
== VAR_LIST
)
1201 list_T
*list
= our_tv
->vval
.v_list
;
1204 result
= PyList_New(0);
1208 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1210 for (curr
= list
->lv_first
; curr
!= NULL
; curr
= curr
->li_next
)
1212 newObj
= VimToPython(&curr
->li_tv
, depth
+ 1, lookupDict
);
1213 PyList_Append(result
, newObj
);
1218 else if (our_tv
->v_type
== VAR_DICT
)
1220 result
= PyDict_New();
1222 if (our_tv
->vval
.v_dict
!= NULL
)
1224 hashtab_T
*ht
= &our_tv
->vval
.v_dict
->dv_hashtab
;
1225 long_u todo
= ht
->ht_used
;
1229 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
1231 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1233 if (!HASHITEM_EMPTY(hi
))
1237 di
= dict_lookup(hi
);
1238 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1239 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1256 VimEval(PyObject
*self UNUSED
, PyObject
*args
)
1262 PyObject
*lookup_dict
;
1264 if (!PyArg_ParseTuple(args
, "s", &expr
))
1267 Py_BEGIN_ALLOW_THREADS
1269 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1271 Python_Release_Vim();
1272 Py_END_ALLOW_THREADS
1276 PyErr_SetVim(_("invalid expression"));
1280 /* Convert the Vim type into a Python type. Create a dictionary that's
1281 * used to check for recursive loops. */
1282 lookup_dict
= PyDict_New();
1283 result
= VimToPython(our_tv
, 1, lookup_dict
);
1284 Py_DECREF(lookup_dict
);
1287 Py_BEGIN_ALLOW_THREADS
1290 Python_Release_Vim();
1291 Py_END_ALLOW_THREADS
1295 PyErr_SetVim(_("expressions disabled at compile time"));
1300 /* Common routines for buffers and line ranges
1301 * -------------------------------------------
1304 CheckBuffer(BufferObject
*this)
1306 if (this->buf
== INVALID_BUFFER_VALUE
)
1308 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1316 RBItem(BufferObject
*self
, PyInt n
, PyInt start
, PyInt end
)
1318 if (CheckBuffer(self
))
1321 if (n
< 0 || n
> end
- start
)
1323 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1327 return GetBufferLine(self
->buf
, n
+start
);
1331 RBSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyInt start
, PyInt end
)
1335 if (CheckBuffer(self
))
1338 size
= end
- start
+ 1;
1351 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1355 RBAssItem(BufferObject
*self
, PyInt n
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1359 if (CheckBuffer(self
))
1362 if (n
< 0 || n
> end
- start
)
1364 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1368 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1372 *new_end
= end
+ len_change
;
1378 RBAssSlice(BufferObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
, PyInt start
, PyInt end
, PyInt
*new_end
)
1383 /* Self must be a valid buffer */
1384 if (CheckBuffer(self
))
1387 /* Sort out the slice range */
1388 size
= end
- start
+ 1;
1401 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1405 *new_end
= end
+ len_change
;
1411 RBAppend(BufferObject
*self
, PyObject
*args
, PyInt start
, PyInt end
, PyInt
*new_end
)
1418 if (CheckBuffer(self
))
1421 max
= n
= end
- start
+ 1;
1423 if (!PyArg_ParseTuple(args
, "O|" Py_ssize_t_fmt
, &lines
, &n
))
1426 if (n
< 0 || n
> max
)
1428 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1432 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1436 *new_end
= end
+ len_change
;
1443 /* Buffer object - Definitions
1446 static struct PyMethodDef BufferMethods
[] = {
1447 /* name, function, calling, documentation */
1448 {"append", BufferAppend
, 1, "Append data to Vim buffer" },
1449 {"mark", BufferMark
, 1, "Return (row,col) representing position of named mark" },
1450 {"range", BufferRange
, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
1451 { NULL
, NULL
, 0, NULL
}
1454 static PySequenceMethods BufferAsSeq
= {
1455 (PyInquiry
) BufferLength
, /* sq_length, len(x) */
1456 (binaryfunc
) 0, /* BufferConcat, */ /* sq_concat, x+y */
1457 (PyIntArgFunc
) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1458 (PyIntArgFunc
) BufferItem
, /* sq_item, x[i] */
1459 (PyIntIntArgFunc
) BufferSlice
, /* sq_slice, x[i:j] */
1460 (PyIntObjArgProc
) BufferAssItem
, /* sq_ass_item, x[i]=v */
1461 (PyIntIntObjArgProc
) BufferAssSlice
, /* sq_ass_slice, x[i:j]=v */
1464 static PyTypeObject BufferType
= {
1465 PyObject_HEAD_INIT(0)
1468 sizeof(BufferObject
),
1471 (destructor
) BufferDestructor
, /* tp_dealloc, refcount==0 */
1472 (printfunc
) 0, /* tp_print, print x */
1473 (getattrfunc
) BufferGetattr
, /* tp_getattr, x.attr */
1474 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1475 (cmpfunc
) 0, /* tp_compare, x>y */
1476 (reprfunc
) BufferRepr
, /* tp_repr, `x`, print x */
1479 &BufferAsSeq
, /* as sequence */
1482 (hashfunc
) 0, /* tp_hash, dict(x) */
1483 (ternaryfunc
) 0, /* tp_call, x() */
1484 (reprfunc
) 0, /* tp_str, str(x) */
1487 /* Buffer object - Implementation
1491 BufferNew(buf_T
*buf
)
1493 /* We need to handle deletion of buffers underneath us.
1494 * If we add a "b_python_ref" field to the buf_T structure,
1495 * then we can get at it in buf_freeall() in vim. We then
1496 * need to create only ONE Python object per buffer - if
1497 * we try to create a second, just INCREF the existing one
1498 * and return it. The (single) Python object referring to
1499 * the buffer is stored in "b_python_ref".
1500 * Question: what to do on a buf_freeall(). We'll probably
1501 * have to either delete the Python object (DECREF it to
1502 * zero - a bad idea, as it leaves dangling refs!) or
1503 * set the buf_T * value to an invalid value (-1?), which
1504 * means we need checks in all access functions... Bah.
1509 if (buf
->b_python_ref
!= NULL
)
1511 self
= buf
->b_python_ref
;
1516 self
= PyObject_NEW(BufferObject
, &BufferType
);
1520 buf
->b_python_ref
= self
;
1523 return (PyObject
*)(self
);
1527 BufferDestructor(PyObject
*self
)
1529 BufferObject
*this = (BufferObject
*)(self
);
1531 if (this->buf
&& this->buf
!= INVALID_BUFFER_VALUE
)
1532 this->buf
->b_python_ref
= NULL
;
1538 BufferGetattr(PyObject
*self
, char *name
)
1540 BufferObject
*this = (BufferObject
*)(self
);
1542 if (CheckBuffer(this))
1545 if (strcmp(name
, "name") == 0)
1546 return Py_BuildValue("s", this->buf
->b_ffname
);
1547 else if (strcmp(name
, "number") == 0)
1548 return Py_BuildValue(Py_ssize_t_fmt
, this->buf
->b_fnum
);
1549 else if (strcmp(name
,"__members__") == 0)
1550 return Py_BuildValue("[ss]", "name", "number");
1552 return Py_FindMethod(BufferMethods
, self
, name
);
1556 BufferRepr(PyObject
*self
)
1558 static char repr
[100];
1559 BufferObject
*this = (BufferObject
*)(self
);
1561 if (this->buf
== INVALID_BUFFER_VALUE
)
1563 vim_snprintf(repr
, 100, _("<buffer object (deleted) at %p>"), (self
));
1564 return PyString_FromString(repr
);
1568 char *name
= (char *)this->buf
->b_fname
;
1576 name
= name
+ (35 - len
);
1578 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1580 return PyString_FromString(repr
);
1584 /******************/
1587 BufferLength(PyObject
*self
)
1589 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1590 if (CheckBuffer((BufferObject
*)(self
)))
1591 return -1; /* ??? */
1593 return (((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1597 BufferItem(PyObject
*self
, PyInt n
)
1599 return RBItem((BufferObject
*)(self
), n
, 1,
1600 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1604 BufferSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1606 return RBSlice((BufferObject
*)(self
), lo
, hi
, 1,
1607 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
1611 BufferAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1613 return RBAssItem((BufferObject
*)(self
), n
, val
, 1,
1614 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1619 BufferAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1621 return RBAssSlice((BufferObject
*)(self
), lo
, hi
, val
, 1,
1622 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1627 BufferAppend(PyObject
*self
, PyObject
*args
)
1629 return RBAppend((BufferObject
*)(self
), args
, 1,
1630 (PyInt
)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1635 BufferMark(PyObject
*self
, PyObject
*args
)
1641 if (CheckBuffer((BufferObject
*)(self
)))
1644 if (!PyArg_ParseTuple(args
, "c", &mark
))
1647 curbuf_save
= curbuf
;
1648 curbuf
= ((BufferObject
*)(self
))->buf
;
1649 posp
= getmark(mark
, FALSE
);
1650 curbuf
= curbuf_save
;
1654 PyErr_SetVim(_("invalid mark name"));
1658 /* Ckeck for keyboard interrupt */
1659 if (VimErrorCheck())
1662 if (posp
->lnum
<= 0)
1664 /* Or raise an error? */
1669 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1673 BufferRange(PyObject
*self
, PyObject
*args
)
1678 if (CheckBuffer((BufferObject
*)(self
)))
1681 if (!PyArg_ParseTuple(args
, Py_ssize_t_fmt Py_ssize_t_fmt
, &start
, &end
))
1684 return RangeNew(((BufferObject
*)(self
))->buf
, start
, end
);
1687 /* Line range object - Definitions
1690 static struct PyMethodDef RangeMethods
[] = {
1691 /* name, function, calling, documentation */
1692 {"append", RangeAppend
, 1, "Append data to the Vim range" },
1693 { NULL
, NULL
, 0, NULL
}
1696 static PySequenceMethods RangeAsSeq
= {
1697 (PyInquiry
) RangeLength
, /* sq_length, len(x) */
1698 (binaryfunc
) 0, /* RangeConcat, */ /* sq_concat, x+y */
1699 (PyIntArgFunc
) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1700 (PyIntArgFunc
) RangeItem
, /* sq_item, x[i] */
1701 (PyIntIntArgFunc
) RangeSlice
, /* sq_slice, x[i:j] */
1702 (PyIntObjArgProc
) RangeAssItem
, /* sq_ass_item, x[i]=v */
1703 (PyIntIntObjArgProc
) RangeAssSlice
, /* sq_ass_slice, x[i:j]=v */
1706 static PyTypeObject RangeType
= {
1707 PyObject_HEAD_INIT(0)
1710 sizeof(RangeObject
),
1713 (destructor
) RangeDestructor
, /* tp_dealloc, refcount==0 */
1714 (printfunc
) 0, /* tp_print, print x */
1715 (getattrfunc
) RangeGetattr
, /* tp_getattr, x.attr */
1716 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1717 (cmpfunc
) 0, /* tp_compare, x>y */
1718 (reprfunc
) RangeRepr
, /* tp_repr, `x`, print x */
1721 &RangeAsSeq
, /* as sequence */
1724 (hashfunc
) 0, /* tp_hash, dict(x) */
1725 (ternaryfunc
) 0, /* tp_call, x() */
1726 (reprfunc
) 0, /* tp_str, str(x) */
1729 /* Line range object - Implementation
1733 RangeNew(buf_T
*buf
, PyInt start
, PyInt end
)
1737 self
= PyObject_NEW(RangeObject
, &RangeType
);
1741 bufr
= (BufferObject
*)BufferNew(buf
);
1750 self
->start
= start
;
1753 return (PyObject
*)(self
);
1757 RangeDestructor(PyObject
*self
)
1759 Py_DECREF(((RangeObject
*)(self
))->buf
);
1764 RangeGetattr(PyObject
*self
, char *name
)
1766 if (strcmp(name
, "start") == 0)
1767 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->start
- 1);
1768 else if (strcmp(name
, "end") == 0)
1769 return Py_BuildValue(Py_ssize_t_fmt
, ((RangeObject
*)(self
))->end
- 1);
1771 return Py_FindMethod(RangeMethods
, self
, name
);
1775 RangeRepr(PyObject
*self
)
1777 static char repr
[100];
1778 RangeObject
*this = (RangeObject
*)(self
);
1780 if (this->buf
->buf
== INVALID_BUFFER_VALUE
)
1782 vim_snprintf(repr
, 100, "<range object (for deleted buffer) at %p>",
1784 return PyString_FromString(repr
);
1788 char *name
= (char *)this->buf
->buf
->b_fname
;
1793 len
= (int)strlen(name
);
1796 name
= name
+ (45 - len
);
1798 vim_snprintf(repr
, 100, "<range %s%s (%d:%d)>",
1799 len
> 45 ? "..." : "", name
,
1800 this->start
, this->end
);
1802 return PyString_FromString(repr
);
1809 RangeLength(PyObject
*self
)
1811 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1812 if (CheckBuffer(((RangeObject
*)(self
))->buf
))
1813 return -1; /* ??? */
1815 return (((RangeObject
*)(self
))->end
- ((RangeObject
*)(self
))->start
+ 1);
1819 RangeItem(PyObject
*self
, PyInt n
)
1821 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1822 ((RangeObject
*)(self
))->start
,
1823 ((RangeObject
*)(self
))->end
);
1827 RangeSlice(PyObject
*self
, PyInt lo
, PyInt hi
)
1829 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1830 ((RangeObject
*)(self
))->start
,
1831 ((RangeObject
*)(self
))->end
);
1835 RangeAssItem(PyObject
*self
, PyInt n
, PyObject
*val
)
1837 return RBAssItem(((RangeObject
*)(self
))->buf
, n
, val
,
1838 ((RangeObject
*)(self
))->start
,
1839 ((RangeObject
*)(self
))->end
,
1840 &((RangeObject
*)(self
))->end
);
1844 RangeAssSlice(PyObject
*self
, PyInt lo
, PyInt hi
, PyObject
*val
)
1846 return RBAssSlice(((RangeObject
*)(self
))->buf
, lo
, hi
, val
,
1847 ((RangeObject
*)(self
))->start
,
1848 ((RangeObject
*)(self
))->end
,
1849 &((RangeObject
*)(self
))->end
);
1853 RangeAppend(PyObject
*self
, PyObject
*args
)
1855 return RBAppend(((RangeObject
*)(self
))->buf
, args
,
1856 ((RangeObject
*)(self
))->start
,
1857 ((RangeObject
*)(self
))->end
,
1858 &((RangeObject
*)(self
))->end
);
1861 /* Buffer list object - Definitions
1870 static PySequenceMethods BufListAsSeq
= {
1871 (PyInquiry
) BufListLength
, /* sq_length, len(x) */
1872 (binaryfunc
) 0, /* sq_concat, x+y */
1873 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
1874 (PyIntArgFunc
) BufListItem
, /* sq_item, x[i] */
1875 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
1876 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
1877 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
1880 static PyTypeObject BufListType
= {
1881 PyObject_HEAD_INIT(0)
1884 sizeof(BufListObject
),
1887 (destructor
) 0, /* tp_dealloc, refcount==0 */
1888 (printfunc
) 0, /* tp_print, print x */
1889 (getattrfunc
) 0, /* tp_getattr, x.attr */
1890 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
1891 (cmpfunc
) 0, /* tp_compare, x>y */
1892 (reprfunc
) 0, /* tp_repr, `x`, print x */
1895 &BufListAsSeq
, /* as sequence */
1898 (hashfunc
) 0, /* tp_hash, dict(x) */
1899 (ternaryfunc
) 0, /* tp_call, x() */
1900 (reprfunc
) 0, /* tp_str, str(x) */
1903 /* Buffer list object - Implementation
1907 BufListLength(PyObject
*self UNUSED
)
1909 buf_T
*b
= firstbuf
;
1922 BufListItem(PyObject
*self UNUSED
, PyInt n
)
1926 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1929 return BufferNew(b
);
1932 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
1936 /* Window object - Definitions
1939 static struct PyMethodDef WindowMethods
[] = {
1940 /* name, function, calling, documentation */
1941 { NULL
, NULL
, 0, NULL
}
1944 static PyTypeObject WindowType
= {
1945 PyObject_HEAD_INIT(0)
1948 sizeof(WindowObject
),
1951 (destructor
) WindowDestructor
, /* tp_dealloc, refcount==0 */
1952 (printfunc
) 0, /* tp_print, print x */
1953 (getattrfunc
) WindowGetattr
, /* tp_getattr, x.attr */
1954 (setattrfunc
) WindowSetattr
, /* tp_setattr, x.attr=v */
1955 (cmpfunc
) 0, /* tp_compare, x>y */
1956 (reprfunc
) WindowRepr
, /* tp_repr, `x`, print x */
1959 0, /* as sequence */
1962 (hashfunc
) 0, /* tp_hash, dict(x) */
1963 (ternaryfunc
) 0, /* tp_call, x() */
1964 (reprfunc
) 0, /* tp_str, str(x) */
1967 /* Window object - Implementation
1971 WindowNew(win_T
*win
)
1973 /* We need to handle deletion of windows underneath us.
1974 * If we add a "w_python_ref" field to the win_T structure,
1975 * then we can get at it in win_free() in vim. We then
1976 * need to create only ONE Python object per window - if
1977 * we try to create a second, just INCREF the existing one
1978 * and return it. The (single) Python object referring to
1979 * the window is stored in "w_python_ref".
1980 * On a win_free() we set the Python object's win_T* field
1981 * to an invalid value. We trap all uses of a window
1982 * object, and reject them if the win_T* field is invalid.
1987 if (win
->w_python_ref
)
1989 self
= win
->w_python_ref
;
1994 self
= PyObject_NEW(WindowObject
, &WindowType
);
1998 win
->w_python_ref
= self
;
2001 return (PyObject
*)(self
);
2005 WindowDestructor(PyObject
*self
)
2007 WindowObject
*this = (WindowObject
*)(self
);
2009 if (this->win
&& this->win
!= INVALID_WINDOW_VALUE
)
2010 this->win
->w_python_ref
= NULL
;
2016 CheckWindow(WindowObject
*this)
2018 if (this->win
== INVALID_WINDOW_VALUE
)
2020 PyErr_SetVim(_("attempt to refer to deleted window"));
2028 WindowGetattr(PyObject
*self
, char *name
)
2030 WindowObject
*this = (WindowObject
*)(self
);
2032 if (CheckWindow(this))
2035 if (strcmp(name
, "buffer") == 0)
2036 return (PyObject
*)BufferNew(this->win
->w_buffer
);
2037 else if (strcmp(name
, "cursor") == 0)
2039 pos_T
*pos
= &this->win
->w_cursor
;
2041 return Py_BuildValue("(ll)", (long)(pos
->lnum
), (long)(pos
->col
));
2043 else if (strcmp(name
, "height") == 0)
2044 return Py_BuildValue("l", (long)(this->win
->w_height
));
2045 #ifdef FEAT_VERTSPLIT
2046 else if (strcmp(name
, "width") == 0)
2047 return Py_BuildValue("l", (long)(W_WIDTH(this->win
)));
2049 else if (strcmp(name
,"__members__") == 0)
2050 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2052 return Py_FindMethod(WindowMethods
, self
, name
);
2056 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
2058 WindowObject
*this = (WindowObject
*)(self
);
2060 if (CheckWindow(this))
2063 if (strcmp(name
, "buffer") == 0)
2065 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2068 else if (strcmp(name
, "cursor") == 0)
2074 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2077 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2079 PyErr_SetVim(_("cursor position outside buffer"));
2083 /* Check for keyboard interrupts */
2084 if (VimErrorCheck())
2087 /* When column is out of range silently correct it. */
2088 len
= (long)STRLEN(ml_get_buf(this->win
->w_buffer
, lnum
, FALSE
));
2092 this->win
->w_cursor
.lnum
= lnum
;
2093 this->win
->w_cursor
.col
= col
;
2094 #ifdef FEAT_VIRTUALEDIT
2095 this->win
->w_cursor
.coladd
= 0;
2097 update_screen(VALID
);
2101 else if (strcmp(name
, "height") == 0)
2106 if (!PyArg_Parse(val
, "i", &height
))
2110 need_mouse_correct
= TRUE
;
2114 win_setheight(height
);
2117 /* Check for keyboard interrupts */
2118 if (VimErrorCheck())
2123 #ifdef FEAT_VERTSPLIT
2124 else if (strcmp(name
, "width") == 0)
2129 if (!PyArg_Parse(val
, "i", &width
))
2133 need_mouse_correct
= TRUE
;
2137 win_setwidth(width
);
2140 /* Check for keyboard interrupts */
2141 if (VimErrorCheck())
2149 PyErr_SetString(PyExc_AttributeError
, name
);
2155 WindowRepr(PyObject
*self
)
2157 static char repr
[100];
2158 WindowObject
*this = (WindowObject
*)(self
);
2160 if (this->win
== INVALID_WINDOW_VALUE
)
2162 vim_snprintf(repr
, 100, _("<window object (deleted) at %p>"), (self
));
2163 return PyString_FromString(repr
);
2170 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2174 vim_snprintf(repr
, 100, _("<window object (unknown) at %p>"),
2177 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2179 return PyString_FromString(repr
);
2183 /* Window list object - Definitions
2192 static PySequenceMethods WinListAsSeq
= {
2193 (PyInquiry
) WinListLength
, /* sq_length, len(x) */
2194 (binaryfunc
) 0, /* sq_concat, x+y */
2195 (PyIntArgFunc
) 0, /* sq_repeat, x*n */
2196 (PyIntArgFunc
) WinListItem
, /* sq_item, x[i] */
2197 (PyIntIntArgFunc
) 0, /* sq_slice, x[i:j] */
2198 (PyIntObjArgProc
) 0, /* sq_ass_item, x[i]=v */
2199 (PyIntIntObjArgProc
) 0, /* sq_ass_slice, x[i:j]=v */
2202 static PyTypeObject WinListType
= {
2203 PyObject_HEAD_INIT(0)
2206 sizeof(WinListObject
),
2209 (destructor
) 0, /* tp_dealloc, refcount==0 */
2210 (printfunc
) 0, /* tp_print, print x */
2211 (getattrfunc
) 0, /* tp_getattr, x.attr */
2212 (setattrfunc
) 0, /* tp_setattr, x.attr=v */
2213 (cmpfunc
) 0, /* tp_compare, x>y */
2214 (reprfunc
) 0, /* tp_repr, `x`, print x */
2217 &WinListAsSeq
, /* as sequence */
2220 (hashfunc
) 0, /* tp_hash, dict(x) */
2221 (ternaryfunc
) 0, /* tp_call, x() */
2222 (reprfunc
) 0, /* tp_str, str(x) */
2225 /* Window list object - Implementation
2228 WinListLength(PyObject
*self UNUSED
)
2230 win_T
*w
= firstwin
;
2243 WinListItem(PyObject
*self UNUSED
, PyInt n
)
2247 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2249 return WindowNew(w
);
2251 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2255 /* Current items object - Definitions
2264 static PyTypeObject CurrentType
= {
2265 PyObject_HEAD_INIT(0)
2268 sizeof(CurrentObject
),
2271 (destructor
) 0, /* tp_dealloc, refcount==0 */
2272 (printfunc
) 0, /* tp_print, print x */
2273 (getattrfunc
) CurrentGetattr
, /* tp_getattr, x.attr */
2274 (setattrfunc
) CurrentSetattr
, /* tp_setattr, x.attr=v */
2275 (cmpfunc
) 0, /* tp_compare, x>y */
2276 (reprfunc
) 0, /* tp_repr, `x`, print x */
2279 0, /* as sequence */
2282 (hashfunc
) 0, /* tp_hash, dict(x) */
2283 (ternaryfunc
) 0, /* tp_call, x() */
2284 (reprfunc
) 0, /* tp_str, str(x) */
2287 /* Current items object - Implementation
2290 CurrentGetattr(PyObject
*self UNUSED
, char *name
)
2292 if (strcmp(name
, "buffer") == 0)
2293 return (PyObject
*)BufferNew(curbuf
);
2294 else if (strcmp(name
, "window") == 0)
2295 return (PyObject
*)WindowNew(curwin
);
2296 else if (strcmp(name
, "line") == 0)
2297 return GetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
);
2298 else if (strcmp(name
, "range") == 0)
2299 return RangeNew(curbuf
, RangeStart
, RangeEnd
);
2300 else if (strcmp(name
,"__members__") == 0)
2301 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2304 PyErr_SetString(PyExc_AttributeError
, name
);
2310 CurrentSetattr(PyObject
*self UNUSED
, char *name
, PyObject
*value
)
2312 if (strcmp(name
, "line") == 0)
2314 if (SetBufferLine(curbuf
, (PyInt
)curwin
->w_cursor
.lnum
, value
, NULL
) == FAIL
)
2321 PyErr_SetString(PyExc_AttributeError
, name
);
2326 /* External interface
2330 python_buffer_free(buf_T
*buf
)
2332 if (buf
->b_python_ref
!= NULL
)
2334 BufferObject
*bp
= buf
->b_python_ref
;
2335 bp
->buf
= INVALID_BUFFER_VALUE
;
2336 buf
->b_python_ref
= NULL
;
2340 #if defined(FEAT_WINDOWS) || defined(PROTO)
2342 python_window_free(win_T
*win
)
2344 if (win
->w_python_ref
!= NULL
)
2346 WindowObject
*wp
= win
->w_python_ref
;
2347 wp
->win
= INVALID_WINDOW_VALUE
;
2348 win
->w_python_ref
= NULL
;
2353 static BufListObject TheBufferList
=
2355 PyObject_HEAD_INIT(&BufListType
)
2358 static WinListObject TheWindowList
=
2360 PyObject_HEAD_INIT(&WinListType
)
2363 static CurrentObject TheCurrent
=
2365 PyObject_HEAD_INIT(&CurrentType
)
2369 PythonMod_Init(void)
2373 /* The special value is removed from sys.path in Python_Init(). */
2374 static char *(argv
[2]) = {"/must>not&exist/foo", NULL
};
2377 BufferType
.ob_type
= &PyType_Type
;
2378 RangeType
.ob_type
= &PyType_Type
;
2379 WindowType
.ob_type
= &PyType_Type
;
2380 BufListType
.ob_type
= &PyType_Type
;
2381 WinListType
.ob_type
= &PyType_Type
;
2382 CurrentType
.ob_type
= &PyType_Type
;
2384 /* Set sys.argv[] to avoid a crash in warn(). */
2385 PySys_SetArgv(1, argv
);
2387 mod
= Py_InitModule4("vim", VimMethods
, (char *)NULL
, (PyObject
*)NULL
, PYTHON_API_VERSION
);
2388 dict
= PyModule_GetDict(mod
);
2390 VimError
= Py_BuildValue("s", "vim.error");
2392 PyDict_SetItemString(dict
, "error", VimError
);
2393 PyDict_SetItemString(dict
, "buffers", (PyObject
*)(void *)&TheBufferList
);
2394 PyDict_SetItemString(dict
, "current", (PyObject
*)(void *)&TheCurrent
);
2395 PyDict_SetItemString(dict
, "windows", (PyObject
*)(void *)&TheWindowList
);
2397 if (PyErr_Occurred())
2403 /*************************************************************************
2404 * 4. Utility functions for handling the interface between Vim and Python.
2407 /* Get a line from the specified buffer. The line number is
2408 * in Vim format (1-based). The line is returned as a Python
2412 GetBufferLine(buf_T
*buf
, PyInt n
)
2414 return LineToString((char *)ml_get_buf(buf
, (linenr_T
)n
, FALSE
));
2417 /* Get a list of lines from the specified buffer. The line numbers
2418 * are in Vim format (1-based). The range is from lo up to, but not
2419 * including, hi. The list is returned as a Python list of string objects.
2422 GetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
)
2426 PyObject
*list
= PyList_New(n
);
2431 for (i
= 0; i
< n
; ++i
)
2433 PyObject
*str
= LineToString((char *)ml_get_buf(buf
, (linenr_T
)(lo
+i
), FALSE
));
2435 /* Error check - was the Python string creation OK? */
2442 /* Set the list item */
2443 if (PyList_SetItem(list
, i
, str
))
2451 /* The ownership of the Python list is passed to the caller (ie,
2452 * the caller should Py_DECREF() the object when it is finished
2460 * Check if deleting lines made the cursor position invalid.
2461 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2465 py_fix_cursor(linenr_T lo
, linenr_T hi
, linenr_T extra
)
2467 if (curwin
->w_cursor
.lnum
>= lo
)
2469 /* Adjust the cursor position if it's in/after the changed
2471 if (curwin
->w_cursor
.lnum
>= hi
)
2473 curwin
->w_cursor
.lnum
+= extra
;
2478 curwin
->w_cursor
.lnum
= lo
;
2483 changed_cline_bef_curs();
2485 invalidate_botline();
2488 /* Replace a line in the specified buffer. The line number is
2489 * in Vim format (1-based). The replacement line is given as
2490 * a Python string object. The object is checked for validity
2491 * and correct format. Errors are returned as a value of FAIL.
2492 * The return value is OK on success.
2493 * If OK is returned and len_change is not NULL, *len_change
2494 * is set to the change in the buffer length.
2497 SetBufferLine(buf_T
*buf
, PyInt n
, PyObject
*line
, PyInt
*len_change
)
2499 /* First of all, we check the thpe of the supplied Python object.
2500 * There are three cases:
2501 * 1. NULL, or None - this is a deletion.
2502 * 2. A string - this is a replacement.
2503 * 3. Anything else - this is an error.
2505 if (line
== Py_None
|| line
== NULL
)
2507 buf_T
*savebuf
= curbuf
;
2512 if (u_savedel((linenr_T
)n
, 1L) == FAIL
)
2513 PyErr_SetVim(_("cannot save undo information"));
2514 else if (ml_delete((linenr_T
)n
, FALSE
) == FAIL
)
2515 PyErr_SetVim(_("cannot delete line"));
2518 if (buf
== curwin
->w_buffer
)
2519 py_fix_cursor((linenr_T
)n
, (linenr_T
)n
+ 1, (linenr_T
)-1);
2520 deleted_lines_mark((linenr_T
)n
, 1L);
2525 if (PyErr_Occurred() || VimErrorCheck())
2533 else if (PyString_Check(line
))
2535 char *save
= StringToLine(line
);
2536 buf_T
*savebuf
= curbuf
;
2541 /* We do not need to free "save" if ml_replace() consumes it. */
2545 if (u_savesub((linenr_T
)n
) == FAIL
)
2547 PyErr_SetVim(_("cannot save undo information"));
2550 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2552 PyErr_SetVim(_("cannot replace line"));
2556 changed_bytes((linenr_T
)n
, 0);
2560 /* Check that the cursor is not beyond the end of the line now. */
2561 if (buf
== curwin
->w_buffer
)
2564 if (PyErr_Occurred() || VimErrorCheck())
2574 PyErr_BadArgument();
2579 /* Replace a range of lines in the specified buffer. The line numbers are in
2580 * Vim format (1-based). The range is from lo up to, but not including, hi.
2581 * The replacement lines are given as a Python list of string objects. The
2582 * list is checked for validity and correct format. Errors are returned as a
2583 * value of FAIL. The return value is OK on success.
2584 * If OK is returned and len_change is not NULL, *len_change
2585 * is set to the change in the buffer length.
2588 SetBufferLineList(buf_T
*buf
, PyInt lo
, PyInt hi
, PyObject
*list
, PyInt
*len_change
)
2590 /* First of all, we check the thpe of the supplied Python object.
2591 * There are three cases:
2592 * 1. NULL, or None - this is a deletion.
2593 * 2. A list - this is a replacement.
2594 * 3. Anything else - this is an error.
2596 if (list
== Py_None
|| list
== NULL
)
2599 PyInt n
= (int)(hi
- lo
);
2600 buf_T
*savebuf
= curbuf
;
2605 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2606 PyErr_SetVim(_("cannot save undo information"));
2609 for (i
= 0; i
< n
; ++i
)
2611 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2613 PyErr_SetVim(_("cannot delete line"));
2617 if (buf
== curwin
->w_buffer
)
2618 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)-n
);
2619 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2624 if (PyErr_Occurred() || VimErrorCheck())
2632 else if (PyList_Check(list
))
2635 PyInt new_len
= PyList_Size(list
);
2636 PyInt old_len
= hi
- lo
;
2637 PyInt extra
= 0; /* lines added to text, can be negative */
2641 if (new_len
== 0) /* avoid allocating zero bytes */
2645 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
2653 for (i
= 0; i
< new_len
; ++i
)
2655 PyObject
*line
= PyList_GetItem(list
, i
);
2657 array
[i
] = StringToLine(line
);
2658 if (array
[i
] == NULL
)
2661 vim_free(array
[--i
]);
2672 if (u_save((linenr_T
)(lo
-1), (linenr_T
)hi
) == FAIL
)
2673 PyErr_SetVim(_("cannot save undo information"));
2675 /* If the size of the range is reducing (ie, new_len < old_len) we
2676 * need to delete some old_len. We do this at the start, by
2677 * repeatedly deleting line "lo".
2679 if (!PyErr_Occurred())
2681 for (i
= 0; i
< old_len
- new_len
; ++i
)
2682 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2684 PyErr_SetVim(_("cannot delete line"));
2690 /* For as long as possible, replace the existing old_len with the
2691 * new old_len. This is a more efficient operation, as it requires
2692 * less memory allocation and freeing.
2694 if (!PyErr_Occurred())
2696 for (i
= 0; i
< old_len
&& i
< new_len
; ++i
)
2697 if (ml_replace((linenr_T
)(lo
+i
), (char_u
*)array
[i
], FALSE
)
2700 PyErr_SetVim(_("cannot replace line"));
2707 /* Now we may need to insert the remaining new old_len. If we do, we
2708 * must free the strings as we finish with them (we can't pass the
2709 * responsibility to vim in this case).
2711 if (!PyErr_Occurred())
2715 if (ml_append((linenr_T
)(lo
+ i
- 1),
2716 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2718 PyErr_SetVim(_("cannot insert line"));
2727 /* Free any left-over old_len, as a result of an error */
2734 /* Free the array of old_len. All of its contents have now
2735 * been dealt with (either freed, or the responsibility passed
2740 /* Adjust marks. Invalidate any which lie in the
2741 * changed range, and move any in the remainder of the buffer.
2743 mark_adjust((linenr_T
)lo
, (linenr_T
)(hi
- 1),
2744 (long)MAXLNUM
, (long)extra
);
2745 changed_lines((linenr_T
)lo
, 0, (linenr_T
)hi
, (long)extra
);
2747 if (buf
== curwin
->w_buffer
)
2748 py_fix_cursor((linenr_T
)lo
, (linenr_T
)hi
, (linenr_T
)extra
);
2752 if (PyErr_Occurred() || VimErrorCheck())
2756 *len_change
= new_len
- old_len
;
2762 PyErr_BadArgument();
2767 /* Insert a number of lines into the specified buffer after the specifed line.
2768 * The line number is in Vim format (1-based). The lines to be inserted are
2769 * given as a Python list of string objects or as a single string. The lines
2770 * to be added are checked for validity and correct format. Errors are
2771 * returned as a value of FAIL. The return value is OK on success.
2772 * If OK is returned and len_change is not NULL, *len_change
2773 * is set to the change in the buffer length.
2776 InsertBufferLines(buf_T
*buf
, PyInt n
, PyObject
*lines
, PyInt
*len_change
)
2778 /* First of all, we check the type of the supplied Python object.
2779 * It must be a string or a list, or the call is in error.
2781 if (PyString_Check(lines
))
2783 char *str
= StringToLine(lines
);
2794 if (u_save((linenr_T
)n
, (linenr_T
)(n
+1)) == FAIL
)
2795 PyErr_SetVim(_("cannot save undo information"));
2796 else if (ml_append((linenr_T
)n
, (char_u
*)str
, 0, FALSE
) == FAIL
)
2797 PyErr_SetVim(_("cannot insert line"));
2799 appended_lines_mark((linenr_T
)n
, 1L);
2803 update_screen(VALID
);
2805 if (PyErr_Occurred() || VimErrorCheck())
2813 else if (PyList_Check(lines
))
2816 PyInt size
= PyList_Size(lines
);
2820 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2827 for (i
= 0; i
< size
; ++i
)
2829 PyObject
*line
= PyList_GetItem(lines
, i
);
2830 array
[i
] = StringToLine(line
);
2832 if (array
[i
] == NULL
)
2835 vim_free(array
[--i
]);
2846 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2847 PyErr_SetVim(_("cannot save undo information"));
2850 for (i
= 0; i
< size
; ++i
)
2852 if (ml_append((linenr_T
)(n
+ i
),
2853 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2855 PyErr_SetVim(_("cannot insert line"));
2857 /* Free the rest of the lines */
2859 vim_free(array
[i
++]);
2866 appended_lines_mark((linenr_T
)n
, (long)i
);
2869 /* Free the array of lines. All of its contents have now
2875 update_screen(VALID
);
2877 if (PyErr_Occurred() || VimErrorCheck())
2887 PyErr_BadArgument();
2892 /* Convert a Vim line into a Python string.
2893 * All internal newlines are replaced by null characters.
2895 * On errors, the Python exception data is set, and NULL is returned.
2898 LineToString(const char *str
)
2901 PyInt len
= strlen(str
);
2904 /* Allocate an Python string object, with uninitialised contents. We
2905 * must do it this way, so that we can modify the string in place
2906 * later. See the Python source, Objects/stringobject.c for details.
2908 result
= PyString_FromStringAndSize(NULL
, len
);
2912 p
= PyString_AsString(result
);
2928 /* Convert a Python string into a Vim line.
2930 * The result is in allocated memory. All internal nulls are replaced by
2931 * newline characters. It is an error for the string to contain newline
2934 * On errors, the Python exception data is set, and NULL is returned.
2937 StringToLine(PyObject
*obj
)
2945 if (obj
== NULL
|| !PyString_Check(obj
))
2947 PyErr_BadArgument();
2951 str
= PyString_AsString(obj
);
2952 len
= PyString_Size(obj
);
2955 * Error checking: String must not contain newlines, as we
2956 * are replacing a single line, and we must replace it with
2958 * A trailing newline is removed, so that append(f.readlines()) works.
2960 p
= memchr(str
, '\n', len
);
2963 if (p
== str
+ len
- 1)
2967 PyErr_SetVim(_("string cannot contain newlines"));
2972 /* Create a copy of the string, with internal nulls replaced by
2973 * newline characters, as is the vim convention.
2975 save
= (char *)alloc((unsigned)(len
+1));
2982 for (i
= 0; i
< len
; ++i
)
2995 /* Check to see whether a Vim error has been reported, or a keyboard
2996 * interrupt has been detected.
3003 PyErr_SetNone(PyExc_KeyboardInterrupt
);
3006 else if (did_emsg
&& !PyErr_Occurred())
3008 PyErr_SetNone(VimError
);
3016 /* Don't generate a prototype for the next function, it generates an error on
3017 * newer Python versions. */
3018 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3021 Py_GetProgramName(void)
3025 #endif /* Python 1.4 */