blob: 8fcb10930274f15e6bcfb0c0ec0a4f13b976b77a [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
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.
8 */
9/*
10 * Python extensions by Paul Moore.
11 * Changes for Unix by David Leonard.
12 *
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.
18 */
19
20#include "vim.h"
21
Bram Moolenaar071d4272004-06-13 20:20:40 +000022#include <limits.h>
23
24/* Python.h defines _POSIX_THREADS itself (if needed) */
25#ifdef _POSIX_THREADS
26# undef _POSIX_THREADS
27#endif
28
29#if defined(_WIN32) && defined (HAVE_FCNTL_H)
30# undef HAVE_FCNTL_H
31#endif
32
33#ifdef _DEBUG
34# undef _DEBUG
35#endif
36
37#ifdef HAVE_STDARG_H
38# undef HAVE_STDARG_H /* Python's config.h defines it as well. */
39#endif
40
Bram Moolenaar2c45e942008-06-04 11:35:26 +000041#define PY_SSIZE_T_CLEAN
42
Bram Moolenaar071d4272004-06-13 20:20:40 +000043#include <Python.h>
44#if defined(MACOS) && !defined(MACOS_X_UNIX)
45# include "macglue.h"
46# include <CodeFragments.h>
47#endif
48#undef main /* Defined in python.h - aargh */
49#undef HAVE_FCNTL_H /* Clash with os_win32.h */
50
51#if !defined(FEAT_PYTHON) && defined(PROTO)
52/* Use this to be able to generate prototypes without python being used. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000053# define PyObject Py_ssize_t
54# define PyThreadState Py_ssize_t
55# define PyTypeObject Py_ssize_t
56struct PyMethodDef { Py_ssize_t a; };
57# define PySequenceMethods Py_ssize_t
Bram Moolenaar071d4272004-06-13 20:20:40 +000058#endif
59
Bram Moolenaar2c45e942008-06-04 11:35:26 +000060#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
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000067# define Py_ssize_t_fmt "n"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000068#else
69# define PyInt int
70# define PyInquiry inquiry
71# define PyIntArgFunc intargfunc
72# define PyIntIntArgFunc intintargfunc
73# define PyIntObjArgProc intobjargproc
74# define PyIntIntObjArgProc intintobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000075# define Py_ssize_t_fmt "i"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000076#endif
77
Bram Moolenaar071d4272004-06-13 20:20:40 +000078/* Parser flags */
79#define single_input 256
80#define file_input 257
81#define eval_input 258
82
83#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
84 /* Python 2.3: can invoke ":python" recursively. */
85# define PY_CAN_RECURSE
86#endif
87
88#if defined(DYNAMIC_PYTHON) || defined(PROTO)
89# ifndef DYNAMIC_PYTHON
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000090# define HINSTANCE long_u /* for generating prototypes */
Bram Moolenaar071d4272004-06-13 20:20:40 +000091# endif
92
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000093/* This makes if_python.c compile without warnings against Python 2.5
94 * on Win32 and Win64. */
95#undef PyRun_SimpleString
96#undef PyArg_Parse
97#undef PyArg_ParseTuple
98#undef Py_BuildValue
99#undef Py_InitModule4
100#undef Py_InitModule4_64
101
Bram Moolenaar071d4272004-06-13 20:20:40 +0000102/*
103 * Wrapper defines
104 */
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
120# endif
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
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000125# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000126# 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
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000131# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132# 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
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000147# define Py_Finalize dll_Py_Finalize
148# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149# 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
154# endif
155# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
156# define PyObject_Malloc dll_PyObject_Malloc
157# define PyObject_Free dll_PyObject_Free
158# endif
159
160/*
161 * Pointers for dynamic link
162 */
163static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
164static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
165static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
166static int(*dll_PyErr_BadArgument)(void);
167static void(*dll_PyErr_Clear)(void);
168static PyObject*(*dll_PyErr_NoMemory)(void);
169static PyObject*(*dll_PyErr_Occurred)(void);
170static void(*dll_PyErr_SetNone)(PyObject *);
171static void(*dll_PyErr_SetString)(PyObject *, const char *);
172static void(*dll_PyEval_InitThreads)(void);
173static void(*dll_PyEval_RestoreThread)(PyThreadState *);
174static PyThreadState*(*dll_PyEval_SaveThread)(void);
175# ifdef PY_CAN_RECURSE
176static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
177static void (*dll_PyGILState_Release)(PyGILState_STATE);
178#endif
179static long(*dll_PyInt_AsLong)(PyObject *);
180static PyObject*(*dll_PyInt_FromLong)(long);
181static PyTypeObject* dll_PyInt_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000182static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000183static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000184static PyObject*(*dll_PyList_New)(PyInt size);
185static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
186static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000187static PyTypeObject* dll_PyList_Type;
188static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000189static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000190static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
191static PyObject*(*dll_PyModule_GetDict)(PyObject *);
192static int(*dll_PyRun_SimpleString)(char *);
193static char*(*dll_PyString_AsString)(PyObject *);
194static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000195static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
196static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197static PyTypeObject* dll_PyString_Type;
198static int(*dll_PySys_SetObject)(char *, PyObject *);
199static int(*dll_PySys_SetArgv)(int, char **);
200static PyTypeObject* dll_PyType_Type;
201static PyObject*(*dll_Py_BuildValue)(char *, ...);
202static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
203static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
204static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000205static void(*dll_Py_Finalize)(void);
206static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000207static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
208static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
209static PyObject* dll__Py_NoneStruct;
210# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
211static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
212# endif
213# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
214static void* (*dll_PyObject_Malloc)(size_t);
215static void (*dll_PyObject_Free)(void*);
216# endif
217
218static HINSTANCE hinstPython = 0; /* Instance of python.dll */
219
220/* Imported exception objects */
221static PyObject *imp_PyExc_AttributeError;
222static PyObject *imp_PyExc_IndexError;
223static PyObject *imp_PyExc_KeyboardInterrupt;
224static PyObject *imp_PyExc_TypeError;
225static PyObject *imp_PyExc_ValueError;
226
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
232
233/*
234 * Table of name to function pointer of python.
235 */
236# define PYTHON_PROC FARPROC
237static struct
238{
239 char *name;
240 PYTHON_PROC *ptr;
241} python_funcname_table[] =
242{
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},
258# endif
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},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000263 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000264 {"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},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000270 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000271 {"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},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000283# if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
284 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
285# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000286 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000287# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000289 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
290 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000291 {"_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},
296# endif
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},
300# endif
301 {"", NULL},
302};
303
304/*
305 * Free python.dll
306 */
307 static void
308end_dynamic_python(void)
309{
310 if (hinstPython)
311 {
312 FreeLibrary(hinstPython);
313 hinstPython = 0;
314 }
315}
316
317/*
318 * Load library and get all pointers.
319 * Parameter 'libname' provides name of DLL.
320 * Return OK or FAIL.
321 */
322 static int
323python_runtime_link_init(char *libname, int verbose)
324{
325 int i;
326
327 if (hinstPython)
328 return OK;
329 hinstPython = LoadLibrary(libname);
330 if (!hinstPython)
331 {
332 if (verbose)
333 EMSG2(_(e_loadlib), libname);
334 return FAIL;
335 }
336
337 for (i = 0; python_funcname_table[i].ptr; ++i)
338 {
339 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
340 python_funcname_table[i].name)) == NULL)
341 {
342 FreeLibrary(hinstPython);
343 hinstPython = 0;
344 if (verbose)
345 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
346 return FAIL;
347 }
348 }
349 return OK;
350}
351
352/*
353 * If python is enabled (there is installed python on Windows system) return
354 * TRUE, else FALSE.
355 */
356 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000357python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358{
359 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
360}
361
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).
364 */
365static void get_exceptions __ARGS((void));
366
367 static void
368get_exceptions()
369{
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);
382 Py_XDECREF(exmod);
383}
384#endif /* DYNAMIC_PYTHON */
385
386/******************************************************
387 * Internal function prototypes.
388 */
389
390static void DoPythonCommand(exarg_T *, const char *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000391static PyInt RangeStart;
392static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393
394static void PythonIO_Flush(void);
395static int PythonIO_Init(void);
396static int PythonMod_Init(void);
397
398/* Utility functions for the vim/python interface
399 * ----------------------------------------------
400 */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000401static PyObject *GetBufferLine(buf_T *, PyInt);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000402static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000404static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
405static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
406static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407
408static PyObject *LineToString(const char *);
409static char *StringToLine(PyObject *);
410
411static int VimErrorCheck(void);
412
413#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
414
415/******************************************************
416 * 1. Python interpreter main program.
417 */
418
419static int initialised = 0;
420
421#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
422typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000423#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000425#ifdef PY_CAN_RECURSE
426static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
427#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000428static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000429#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430
431/*
432 * Suspend a thread of the Python interpreter, other threads are allowed to
433 * run.
434 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000435 static void
436Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000438#ifdef PY_CAN_RECURSE
439 PyGILState_Release(pygilstate);
440#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000442#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443}
444
445/*
446 * Restore a thread of the Python interpreter, waits for other threads to
447 * block.
448 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000449 static void
450Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000452#ifdef PY_CAN_RECURSE
453 pygilstate = PyGILState_Ensure();
454#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 PyEval_RestoreThread(saved_python_thread);
456 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000458}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
460/*
461 * obtain a lock on the Vim data structures
462 */
463static void Python_Lock_Vim(void)
464{
465}
466
467/*
468 * release a lock on the Vim data structures
469 */
470static void Python_Release_Vim(void)
471{
472}
473
474 void
475python_end()
476{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000477 static int recurse = 0;
478
479 /* If a crash occurs while doing this, don't try again. */
480 if (recurse != 0)
481 return;
482
483 ++recurse;
484
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000486 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000487 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000488 Python_RestoreThread(); /* enter python */
489 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000492#else
493 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000494 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000495 Python_RestoreThread(); /* enter python */
496 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000499
500 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501}
502
503 static int
504Python_Init(void)
505{
506 if (!initialised)
507 {
508#ifdef DYNAMIC_PYTHON
509 if (!python_enabled(TRUE))
510 {
511 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
512 goto fail;
513 }
514#endif
515
516#if !defined(MACOS) || defined(MACOS_X_UNIX)
517 Py_Initialize();
518#else
519 PyMac_Initialize();
520#endif
521 /* initialise threads */
522 PyEval_InitThreads();
523
524#ifdef DYNAMIC_PYTHON
525 get_exceptions();
526#endif
527
528 if (PythonIO_Init())
529 goto fail;
530
531 if (PythonMod_Init())
532 goto fail;
533
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000534 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536
537 initialised = 1;
538 }
539
540 return 0;
541
542fail:
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).
547 */
548 PythonIO_Flush();
549 return -1;
550}
551
552/*
553 * External interface
554 */
555 static void
556DoPythonCommand(exarg_T *eap, const char *cmd)
557{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000558#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 static int recursive = 0;
560#endif
561#if defined(MACOS) && !defined(MACOS_X_UNIX)
562 GrafPtr oldPort;
563#endif
564#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
565 char *saved_locale;
566#endif
567
568#ifndef PY_CAN_RECURSE
569 if (recursive)
570 {
571 EMSG(_("E659: Cannot invoke Python recursively"));
572 return;
573 }
574 ++recursive;
575#endif
576
577#if defined(MACOS) && !defined(MACOS_X_UNIX)
578 GetPort(&oldPort);
579 /* Check if the Python library is available */
580 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
581 goto theend;
582#endif
583 if (Python_Init())
584 goto theend;
585
586 RangeStart = eap->line1;
587 RangeEnd = eap->line2;
588 Python_Release_Vim(); /* leave vim */
589
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)
594 saved_locale = NULL;
595 else
596 {
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");
600 }
601#endif
602
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604
605 PyRun_SimpleString((char *)(cmd));
606
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608
609#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
610 if (saved_locale != NULL)
611 {
612 (void)setlocale(LC_NUMERIC, saved_locale);
613 vim_free(saved_locale);
614 }
615#endif
616
617 Python_Lock_Vim(); /* enter vim */
618 PythonIO_Flush();
619#if defined(MACOS) && !defined(MACOS_X_UNIX)
620 SetPort(oldPort);
621#endif
622
623theend:
624#ifndef PY_CAN_RECURSE
625 --recursive;
626#endif
627 return; /* keeps lint happy */
628}
629
630/*
631 * ":python"
632 */
633 void
634ex_python(exarg_T *eap)
635{
636 char_u *script;
637
638 script = script_get(eap, eap->arg);
639 if (!eap->skip)
640 {
641 if (script == NULL)
642 DoPythonCommand(eap, (char *)eap->arg);
643 else
644 DoPythonCommand(eap, (char *)script);
645 }
646 vim_free(script);
647}
648
649#define BUFFER_SIZE 1024
650
651/*
652 * ":pyfile"
653 */
654 void
655ex_pyfile(exarg_T *eap)
656{
657 static char buffer[BUFFER_SIZE];
658 const char *file = (char *)eap->arg;
659 char *p;
660
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.
665 *
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.
669 */
670 strcpy(buffer, "execfile('");
671 p = buffer + 10; /* size of "execfile('" */
672
673 while (*file && p < buffer + (BUFFER_SIZE - 3))
674 {
675 if (*file == '\\' || *file == '\'')
676 *p++ = '\\';
677 *p++ = *file++;
678 }
679
680 /* If we didn't finish the file name, we hit a buffer overflow */
681 if (*file != '\0')
682 return;
683
684 /* Put in the terminating "')" and a null */
685 *p++ = '\'';
686 *p++ = ')';
687 *p++ = '\0';
688
689 /* Execute the file */
690 DoPythonCommand(eap, buffer);
691}
692
693/******************************************************
694 * 2. Python output stream: writes output via [e]msg().
695 */
696
697/* Implementation functions
698 */
699
700static PyObject *OutputGetattr(PyObject *, char *);
701static int OutputSetattr(PyObject *, char *, PyObject *);
702
703static PyObject *OutputWrite(PyObject *, PyObject *);
704static PyObject *OutputWritelines(PyObject *, PyObject *);
705
706typedef void (*writefn)(char_u *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000707static void writer(writefn fn, char_u *str, PyInt n);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708
709/* Output object definition
710 */
711
712typedef struct
713{
714 PyObject_HEAD
715 long softspace;
716 long error;
717} OutputObject;
718
719static struct PyMethodDef OutputMethods[] = {
720 /* name, function, calling, documentation */
721 {"write", OutputWrite, 1, "" },
722 {"writelines", OutputWritelines, 1, "" },
723 { NULL, NULL, 0, NULL }
724};
725
726static PyTypeObject OutputType = {
727 PyObject_HEAD_INIT(0)
728 0,
729 "message",
730 sizeof(OutputObject),
731 0,
732
733 (destructor) 0,
734 (printfunc) 0,
735 (getattrfunc) OutputGetattr,
736 (setattrfunc) OutputSetattr,
737 (cmpfunc) 0,
738 (reprfunc) 0,
739
740 0, /* as number */
741 0, /* as sequence */
742 0, /* as mapping */
743
744 (hashfunc) 0,
745 (ternaryfunc) 0,
746 (reprfunc) 0
747};
748
749/*************/
750
751 static PyObject *
752OutputGetattr(PyObject *self, char *name)
753{
754 if (strcmp(name, "softspace") == 0)
755 return PyInt_FromLong(((OutputObject *)(self))->softspace);
756
757 return Py_FindMethod(OutputMethods, self, name);
758}
759
760 static int
761OutputSetattr(PyObject *self, char *name, PyObject *val)
762{
763 if (val == NULL) {
764 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
765 return -1;
766 }
767
768 if (strcmp(name, "softspace") == 0)
769 {
770 if (!PyInt_Check(val)) {
771 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
772 return -1;
773 }
774
775 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
776 return 0;
777 }
778
779 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
780 return -1;
781}
782
783/*************/
784
785 static PyObject *
786OutputWrite(PyObject *self, PyObject *args)
787{
788 int len;
789 char *str;
790 int error = ((OutputObject *)(self))->error;
791
792 if (!PyArg_ParseTuple(args, "s#", &str, &len))
793 return NULL;
794
795 Py_BEGIN_ALLOW_THREADS
796 Python_Lock_Vim();
797 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
798 Python_Release_Vim();
799 Py_END_ALLOW_THREADS
800
801 Py_INCREF(Py_None);
802 return Py_None;
803}
804
805 static PyObject *
806OutputWritelines(PyObject *self, PyObject *args)
807{
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000808 PyInt n;
809 PyInt i;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810 PyObject *list;
811 int error = ((OutputObject *)(self))->error;
812
813 if (!PyArg_ParseTuple(args, "O", &list))
814 return NULL;
815 Py_INCREF(list);
816
817 if (!PyList_Check(list)) {
818 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
819 Py_DECREF(list);
820 return NULL;
821 }
822
823 n = PyList_Size(list);
824
825 for (i = 0; i < n; ++i)
826 {
827 PyObject *line = PyList_GetItem(list, i);
828 char *str;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000829 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830
831 if (!PyArg_Parse(line, "s#", &str, &len)) {
832 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
833 Py_DECREF(list);
834 return NULL;
835 }
836
837 Py_BEGIN_ALLOW_THREADS
838 Python_Lock_Vim();
839 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
840 Python_Release_Vim();
841 Py_END_ALLOW_THREADS
842 }
843
844 Py_DECREF(list);
845 Py_INCREF(Py_None);
846 return Py_None;
847}
848
849/* Output buffer management
850 */
851
852static char_u *buffer = NULL;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000853static PyInt buffer_len = 0;
854static PyInt buffer_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855
856static writefn old_fn = NULL;
857
858 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000859buffer_ensure(PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000861 PyInt new_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 char_u *new_buffer;
863
864 if (n < buffer_size)
865 return;
866
867 new_size = buffer_size;
868 while (new_size < n)
869 new_size += 80;
870
871 if (new_size != buffer_size)
872 {
873 new_buffer = alloc((unsigned)new_size);
874 if (new_buffer == NULL)
875 return;
876
877 if (buffer)
878 {
879 memcpy(new_buffer, buffer, buffer_len);
880 vim_free(buffer);
881 }
882
883 buffer = new_buffer;
884 buffer_size = new_size;
885 }
886}
887
888 static void
889PythonIO_Flush(void)
890{
891 if (old_fn && buffer_len)
892 {
893 buffer[buffer_len] = 0;
894 old_fn(buffer);
895 }
896
897 buffer_len = 0;
898}
899
900 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000901writer(writefn fn, char_u *str, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902{
903 char_u *ptr;
904
905 if (fn != old_fn && old_fn != NULL)
906 PythonIO_Flush();
907
908 old_fn = fn;
909
910 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
911 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000912 PyInt len = ptr - str;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
914 buffer_ensure(buffer_len + len + 1);
915
916 memcpy(buffer + buffer_len, str, len);
917 buffer_len += len;
918 buffer[buffer_len] = 0;
919 fn(buffer);
920 str = ptr + 1;
921 n -= len + 1;
922 buffer_len = 0;
923 }
924
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);
928 buffer_len += n;
929}
930
931/***************/
932
933static OutputObject Output =
934{
935 PyObject_HEAD_INIT(&OutputType)
936 0,
937 0
938};
939
940static OutputObject Error =
941{
942 PyObject_HEAD_INIT(&OutputType)
943 0,
944 1
945};
946
947 static int
948PythonIO_Init(void)
949{
950 /* Fixups... */
951 OutputType.ob_type = &PyType_Type;
952
Bram Moolenaar7df2d662005-01-25 22:18:08 +0000953 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
954 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955
956 if (PyErr_Occurred())
957 {
958 EMSG(_("E264: Python: Error initialising I/O objects"));
959 return -1;
960 }
961
962 return 0;
963}
964
965/******************************************************
966 * 3. Implementation of the Vim module for Python
967 */
968
969/* Vim module - Implementation functions
970 * -------------------------------------
971 */
972
973static PyObject *VimError;
974
975static PyObject *VimCommand(PyObject *, PyObject *);
976static PyObject *VimEval(PyObject *, PyObject *);
977
978/* Window type - Implementation functions
979 * --------------------------------------
980 */
981
982typedef struct
983{
984 PyObject_HEAD
985 win_T *win;
986}
987WindowObject;
988
989#define INVALID_WINDOW_VALUE ((win_T *)(-1))
990
991#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
992
993static PyObject *WindowNew(win_T *);
994
995static void WindowDestructor(PyObject *);
996static PyObject *WindowGetattr(PyObject *, char *);
997static int WindowSetattr(PyObject *, char *, PyObject *);
998static PyObject *WindowRepr(PyObject *);
999
1000/* Buffer type - Implementation functions
1001 * --------------------------------------
1002 */
1003
1004typedef struct
1005{
1006 PyObject_HEAD
1007 buf_T *buf;
1008}
1009BufferObject;
1010
1011#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1012
1013#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1014
1015static PyObject *BufferNew (buf_T *);
1016
1017static void BufferDestructor(PyObject *);
1018static PyObject *BufferGetattr(PyObject *, char *);
1019static PyObject *BufferRepr(PyObject *);
1020
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001021static PyInt BufferLength(PyObject *);
1022static PyObject *BufferItem(PyObject *, PyInt);
1023static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1024static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1025static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026
1027static PyObject *BufferAppend(PyObject *, PyObject *);
1028static PyObject *BufferMark(PyObject *, PyObject *);
1029static PyObject *BufferRange(PyObject *, PyObject *);
1030
1031/* Line range type - Implementation functions
1032 * --------------------------------------
1033 */
1034
1035typedef struct
1036{
1037 PyObject_HEAD
1038 BufferObject *buf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001039 PyInt start;
1040 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041}
1042RangeObject;
1043
1044#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1045
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001046static PyObject *RangeNew(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047
1048static void RangeDestructor(PyObject *);
1049static PyObject *RangeGetattr(PyObject *, char *);
1050static PyObject *RangeRepr(PyObject *);
1051
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001052static PyInt RangeLength(PyObject *);
1053static PyObject *RangeItem(PyObject *, PyInt);
1054static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1055static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1056static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057
1058static PyObject *RangeAppend(PyObject *, PyObject *);
1059
1060/* Window list type - Implementation functions
1061 * -------------------------------------------
1062 */
1063
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001064static PyInt WinListLength(PyObject *);
1065static PyObject *WinListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066
1067/* Buffer list type - Implementation functions
1068 * -------------------------------------------
1069 */
1070
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001071static PyInt BufListLength(PyObject *);
1072static PyObject *BufListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073
1074/* Current objects type - Implementation functions
1075 * -----------------------------------------------
1076 */
1077
1078static PyObject *CurrentGetattr(PyObject *, char *);
1079static int CurrentSetattr(PyObject *, char *, PyObject *);
1080
1081/* Vim module - Definitions
1082 */
1083
1084static struct PyMethodDef VimMethods[] = {
1085 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001086 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1087 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 { NULL, NULL, 0, NULL }
1089};
1090
1091/* Vim module - Implementation
1092 */
1093/*ARGSUSED*/
1094 static PyObject *
1095VimCommand(PyObject *self, PyObject *args)
1096{
1097 char *cmd;
1098 PyObject *result;
1099
1100 if (!PyArg_ParseTuple(args, "s", &cmd))
1101 return NULL;
1102
1103 PyErr_Clear();
1104
1105 Py_BEGIN_ALLOW_THREADS
1106 Python_Lock_Vim();
1107
1108 do_cmdline_cmd((char_u *)cmd);
1109 update_screen(VALID);
1110
1111 Python_Release_Vim();
1112 Py_END_ALLOW_THREADS
1113
1114 if (VimErrorCheck())
1115 result = NULL;
1116 else
1117 result = Py_None;
1118
1119 Py_XINCREF(result);
1120 return result;
1121}
1122
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001123/*
1124 * Function to translate a typval_T into a PyObject; this will recursively
1125 * translate lists/dictionaries into their Python equivalents.
1126 *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001127 * The depth parameter is to avoid infinite recursion, set it to 1 when
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001128 * you call VimToPython.
1129 */
1130 static PyObject *
1131VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1132{
1133 PyObject *result;
1134 PyObject *newObj;
1135 char ptrBuf[NUMBUFLEN];
1136
1137 /* Avoid infinite recursion */
1138 if (depth > 100)
1139 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001140 Py_INCREF(Py_None);
1141 result = Py_None;
1142 return result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001143 }
1144
1145 /* Check if we run into a recursive loop. The item must be in lookupDict
1146 * then and we can use it again. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001147 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U, (long_u)our_tv);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001148 result = PyDict_GetItemString(lookupDict, ptrBuf);
1149 if (result != NULL)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001150 Py_INCREF(result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001151 else if (our_tv->v_type == VAR_STRING)
1152 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001153 result = Py_BuildValue("s", our_tv->vval.v_string);
1154 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001155 }
1156 else if (our_tv->v_type == VAR_NUMBER)
1157 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001158 char buf[NUMBUFLEN];
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001159
1160 /* For backwards compatibility numbers are stored as strings. */
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001161 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1162 result = Py_BuildValue("s", buf);
1163 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001164 }
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001165#ifdef FEAT_FLOAT
1166 else if (our_tv->v_type == VAR_FLOAT)
1167 {
1168 char buf[NUMBUFLEN];
1169
1170 sprintf(buf, "%f", our_tv->vval.v_float);
1171 result = Py_BuildValue("s", buf);
1172 PyDict_SetItemString(lookupDict, ptrBuf, result);
1173 }
1174#endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001175 else if (our_tv->v_type == VAR_LIST)
1176 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001177 list_T *list = our_tv->vval.v_list;
1178 listitem_T *curr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001179
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001180 result = PyList_New(0);
1181 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001182
1183 if (list != NULL)
1184 {
1185 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1186 {
1187 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1188 PyList_Append(result, newObj);
1189 Py_DECREF(newObj);
1190 }
1191 }
1192 }
1193 else if (our_tv->v_type == VAR_DICT)
1194 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001195 result = PyDict_New();
1196 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001197
1198 if (our_tv->vval.v_dict != NULL)
1199 {
1200 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001201 long_u todo = ht->ht_used;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001202 hashitem_T *hi;
1203 dictitem_T *di;
1204
1205 for (hi = ht->ht_array; todo > 0; ++hi)
1206 {
1207 if (!HASHITEM_EMPTY(hi))
1208 {
1209 --todo;
1210
1211 di = dict_lookup(hi);
1212 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1213 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1214 Py_DECREF(newObj);
1215 }
1216 }
1217 }
1218 }
1219 else
1220 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001221 Py_INCREF(Py_None);
1222 result = Py_None;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001223 }
1224
1225 return result;
1226}
1227
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228/*ARGSUSED*/
1229 static PyObject *
1230VimEval(PyObject *self, PyObject *args)
1231{
1232#ifdef FEAT_EVAL
1233 char *expr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001234 typval_T *our_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235 PyObject *result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001236 PyObject *lookup_dict;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001237
1238 if (!PyArg_ParseTuple(args, "s", &expr))
1239 return NULL;
1240
1241 Py_BEGIN_ALLOW_THREADS
1242 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001243 our_tv = eval_expr((char_u *)expr, NULL);
1244
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 Python_Release_Vim();
1246 Py_END_ALLOW_THREADS
1247
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001248 if (our_tv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249 {
1250 PyErr_SetVim(_("invalid expression"));
1251 return NULL;
1252 }
1253
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001254 /* 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);
1259
Bram Moolenaar071d4272004-06-13 20:20:40 +00001260
1261 Py_BEGIN_ALLOW_THREADS
1262 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001263 free_tv(our_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 Python_Release_Vim();
1265 Py_END_ALLOW_THREADS
1266
1267 return result;
1268#else
1269 PyErr_SetVim(_("expressions disabled at compile time"));
1270 return NULL;
1271#endif
1272}
1273
1274/* Common routines for buffers and line ranges
1275 * -------------------------------------------
1276 */
1277 static int
1278CheckBuffer(BufferObject *this)
1279{
1280 if (this->buf == INVALID_BUFFER_VALUE)
1281 {
1282 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1283 return -1;
1284 }
1285
1286 return 0;
1287}
1288
1289 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001290RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291{
1292 if (CheckBuffer(self))
1293 return NULL;
1294
1295 if (n < 0 || n > end - start)
1296 {
1297 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1298 return NULL;
1299 }
1300
1301 return GetBufferLine(self->buf, n+start);
1302}
1303
1304 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001305RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001307 PyInt size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308
1309 if (CheckBuffer(self))
1310 return NULL;
1311
1312 size = end - start + 1;
1313
1314 if (lo < 0)
1315 lo = 0;
1316 else if (lo > size)
1317 lo = size;
1318 if (hi < 0)
1319 hi = 0;
1320 if (hi < lo)
1321 hi = lo;
1322 else if (hi > size)
1323 hi = size;
1324
1325 return GetBufferLineList(self->buf, lo+start, hi+start);
1326}
1327
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001328 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001329RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001331 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001332
1333 if (CheckBuffer(self))
1334 return -1;
1335
1336 if (n < 0 || n > end - start)
1337 {
1338 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1339 return -1;
1340 }
1341
1342 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1343 return -1;
1344
1345 if (new_end)
1346 *new_end = end + len_change;
1347
1348 return 0;
1349}
1350
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001351 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001352RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001354 PyInt size;
1355 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356
1357 /* Self must be a valid buffer */
1358 if (CheckBuffer(self))
1359 return -1;
1360
1361 /* Sort out the slice range */
1362 size = end - start + 1;
1363
1364 if (lo < 0)
1365 lo = 0;
1366 else if (lo > size)
1367 lo = size;
1368 if (hi < 0)
1369 hi = 0;
1370 if (hi < lo)
1371 hi = lo;
1372 else if (hi > size)
1373 hi = size;
1374
1375 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1376 return -1;
1377
1378 if (new_end)
1379 *new_end = end + len_change;
1380
1381 return 0;
1382}
1383
1384 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001385RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001386{
1387 PyObject *lines;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001388 PyInt len_change;
1389 PyInt max;
1390 PyInt n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391
1392 if (CheckBuffer(self))
1393 return NULL;
1394
1395 max = n = end - start + 1;
1396
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001397 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 return NULL;
1399
1400 if (n < 0 || n > max)
1401 {
1402 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1403 return NULL;
1404 }
1405
1406 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1407 return NULL;
1408
1409 if (new_end)
1410 *new_end = end + len_change;
1411
1412 Py_INCREF(Py_None);
1413 return Py_None;
1414}
1415
1416
1417/* Buffer object - Definitions
1418 */
1419
1420static struct PyMethodDef BufferMethods[] = {
1421 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001422 {"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" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001425 { NULL, NULL, 0, NULL }
1426};
1427
1428static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001429 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001431 (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 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001436};
1437
1438static PyTypeObject BufferType = {
1439 PyObject_HEAD_INIT(0)
1440 0,
1441 "buffer",
1442 sizeof(BufferObject),
1443 0,
1444
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 */
1451
1452 0, /* as number */
1453 &BufferAsSeq, /* as sequence */
1454 0, /* as mapping */
1455
1456 (hashfunc) 0, /* tp_hash, dict(x) */
1457 (ternaryfunc) 0, /* tp_call, x() */
1458 (reprfunc) 0, /* tp_str, str(x) */
1459};
1460
1461/* Buffer object - Implementation
1462 */
1463
1464 static PyObject *
1465BufferNew(buf_T *buf)
1466{
1467 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001468 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469 * 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
Bram Moolenaare344bea2005-09-01 20:46:49 +00001473 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474 * 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.
1479 */
1480
1481 BufferObject *self;
1482
Bram Moolenaare344bea2005-09-01 20:46:49 +00001483 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001484 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001485 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 Py_INCREF(self);
1487 }
1488 else
1489 {
1490 self = PyObject_NEW(BufferObject, &BufferType);
1491 if (self == NULL)
1492 return NULL;
1493 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001494 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 }
1496
1497 return (PyObject *)(self);
1498}
1499
1500 static void
1501BufferDestructor(PyObject *self)
1502{
1503 BufferObject *this = (BufferObject *)(self);
1504
1505 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001506 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507
Bram Moolenaar658ada62006-10-03 13:02:36 +00001508 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001509}
1510
1511 static PyObject *
1512BufferGetattr(PyObject *self, char *name)
1513{
1514 BufferObject *this = (BufferObject *)(self);
1515
1516 if (CheckBuffer(this))
1517 return NULL;
1518
1519 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001520 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001522 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 else if (strcmp(name,"__members__") == 0)
1524 return Py_BuildValue("[ss]", "name", "number");
1525 else
1526 return Py_FindMethod(BufferMethods, self, name);
1527}
1528
1529 static PyObject *
1530BufferRepr(PyObject *self)
1531{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001532 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 BufferObject *this = (BufferObject *)(self);
1534
1535 if (this->buf == INVALID_BUFFER_VALUE)
1536 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001537 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 return PyString_FromString(repr);
1539 }
1540 else
1541 {
1542 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001543 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544
1545 if (name == NULL)
1546 name = "";
1547 len = strlen(name);
1548
1549 if (len > 35)
1550 name = name + (35 - len);
1551
Bram Moolenaar555b2802005-05-19 21:08:39 +00001552 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553
1554 return PyString_FromString(repr);
1555 }
1556}
1557
1558/******************/
1559
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001560 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561BufferLength(PyObject *self)
1562{
1563 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1564 if (CheckBuffer((BufferObject *)(self)))
1565 return -1; /* ??? */
1566
1567 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1568}
1569
1570 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001571BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572{
1573 return RBItem((BufferObject *)(self), n, 1,
1574 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1575}
1576
1577 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001578BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579{
1580 return RBSlice((BufferObject *)(self), lo, hi, 1,
1581 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1582}
1583
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001584 static PyInt
1585BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586{
1587 return RBAssItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001588 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 NULL);
1590}
1591
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001592 static PyInt
1593BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594{
1595 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001596 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597 NULL);
1598}
1599
1600 static PyObject *
1601BufferAppend(PyObject *self, PyObject *args)
1602{
1603 return RBAppend((BufferObject *)(self), args, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001604 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 NULL);
1606}
1607
1608 static PyObject *
1609BufferMark(PyObject *self, PyObject *args)
1610{
1611 pos_T *posp;
1612 char mark;
1613 buf_T *curbuf_save;
1614
1615 if (CheckBuffer((BufferObject *)(self)))
1616 return NULL;
1617
1618 if (!PyArg_ParseTuple(args, "c", &mark))
1619 return NULL;
1620
1621 curbuf_save = curbuf;
1622 curbuf = ((BufferObject *)(self))->buf;
1623 posp = getmark(mark, FALSE);
1624 curbuf = curbuf_save;
1625
1626 if (posp == NULL)
1627 {
1628 PyErr_SetVim(_("invalid mark name"));
1629 return NULL;
1630 }
1631
1632 /* Ckeck for keyboard interrupt */
1633 if (VimErrorCheck())
1634 return NULL;
1635
1636 if (posp->lnum <= 0)
1637 {
1638 /* Or raise an error? */
1639 Py_INCREF(Py_None);
1640 return Py_None;
1641 }
1642
1643 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1644}
1645
1646 static PyObject *
1647BufferRange(PyObject *self, PyObject *args)
1648{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001649 PyInt start;
1650 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651
1652 if (CheckBuffer((BufferObject *)(self)))
1653 return NULL;
1654
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001655 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656 return NULL;
1657
1658 return RangeNew(((BufferObject *)(self))->buf, start, end);
1659}
1660
1661/* Line range object - Definitions
1662 */
1663
1664static struct PyMethodDef RangeMethods[] = {
1665 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001666 {"append", RangeAppend, 1, "Append data to the Vim range" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 { NULL, NULL, 0, NULL }
1668};
1669
1670static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001671 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001673 (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 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678};
1679
1680static PyTypeObject RangeType = {
1681 PyObject_HEAD_INIT(0)
1682 0,
1683 "range",
1684 sizeof(RangeObject),
1685 0,
1686
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 */
1693
1694 0, /* as number */
1695 &RangeAsSeq, /* as sequence */
1696 0, /* as mapping */
1697
1698 (hashfunc) 0, /* tp_hash, dict(x) */
1699 (ternaryfunc) 0, /* tp_call, x() */
1700 (reprfunc) 0, /* tp_str, str(x) */
1701};
1702
1703/* Line range object - Implementation
1704 */
1705
1706 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001707RangeNew(buf_T *buf, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708{
1709 BufferObject *bufr;
1710 RangeObject *self;
1711 self = PyObject_NEW(RangeObject, &RangeType);
1712 if (self == NULL)
1713 return NULL;
1714
1715 bufr = (BufferObject *)BufferNew(buf);
1716 if (bufr == NULL)
1717 {
Bram Moolenaar658ada62006-10-03 13:02:36 +00001718 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 return NULL;
1720 }
1721 Py_INCREF(bufr);
1722
1723 self->buf = bufr;
1724 self->start = start;
1725 self->end = end;
1726
1727 return (PyObject *)(self);
1728}
1729
1730 static void
1731RangeDestructor(PyObject *self)
1732{
1733 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001734 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735}
1736
1737 static PyObject *
1738RangeGetattr(PyObject *self, char *name)
1739{
1740 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001741 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001743 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 else
1745 return Py_FindMethod(RangeMethods, self, name);
1746}
1747
1748 static PyObject *
1749RangeRepr(PyObject *self)
1750{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001751 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 RangeObject *this = (RangeObject *)(self);
1753
1754 if (this->buf->buf == INVALID_BUFFER_VALUE)
1755 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001756 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1757 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001758 return PyString_FromString(repr);
1759 }
1760 else
1761 {
1762 char *name = (char *)this->buf->buf->b_fname;
1763 int len;
1764
1765 if (name == NULL)
1766 name = "";
1767 len = strlen(name);
1768
1769 if (len > 45)
1770 name = name + (45 - len);
1771
Bram Moolenaar555b2802005-05-19 21:08:39 +00001772 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 len > 45 ? "..." : "", name,
1774 this->start, this->end);
1775
1776 return PyString_FromString(repr);
1777 }
1778}
1779
1780/****************/
1781
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001782 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783RangeLength(PyObject *self)
1784{
1785 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1786 if (CheckBuffer(((RangeObject *)(self))->buf))
1787 return -1; /* ??? */
1788
1789 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1790}
1791
1792 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001793RangeItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794{
1795 return RBItem(((RangeObject *)(self))->buf, n,
1796 ((RangeObject *)(self))->start,
1797 ((RangeObject *)(self))->end);
1798}
1799
1800 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001801RangeSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802{
1803 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1804 ((RangeObject *)(self))->start,
1805 ((RangeObject *)(self))->end);
1806}
1807
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001808 static PyInt
1809RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810{
1811 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1812 ((RangeObject *)(self))->start,
1813 ((RangeObject *)(self))->end,
1814 &((RangeObject *)(self))->end);
1815}
1816
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001817 static PyInt
1818RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819{
1820 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1821 ((RangeObject *)(self))->start,
1822 ((RangeObject *)(self))->end,
1823 &((RangeObject *)(self))->end);
1824}
1825
1826 static PyObject *
1827RangeAppend(PyObject *self, PyObject *args)
1828{
1829 return RBAppend(((RangeObject *)(self))->buf, args,
1830 ((RangeObject *)(self))->start,
1831 ((RangeObject *)(self))->end,
1832 &((RangeObject *)(self))->end);
1833}
1834
1835/* Buffer list object - Definitions
1836 */
1837
1838typedef struct
1839{
1840 PyObject_HEAD
1841}
1842BufListObject;
1843
1844static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001845 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001847 (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 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852};
1853
1854static PyTypeObject BufListType = {
1855 PyObject_HEAD_INIT(0)
1856 0,
1857 "buffer list",
1858 sizeof(BufListObject),
1859 0,
1860
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 */
1867
1868 0, /* as number */
1869 &BufListAsSeq, /* as sequence */
1870 0, /* as mapping */
1871
1872 (hashfunc) 0, /* tp_hash, dict(x) */
1873 (ternaryfunc) 0, /* tp_call, x() */
1874 (reprfunc) 0, /* tp_str, str(x) */
1875};
1876
1877/* Buffer list object - Implementation
1878 */
1879
1880/*ARGSUSED*/
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001881 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882BufListLength(PyObject *self)
1883{
1884 buf_T *b = firstbuf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001885 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886
1887 while (b)
1888 {
1889 ++n;
1890 b = b->b_next;
1891 }
1892
1893 return n;
1894}
1895
1896/*ARGSUSED*/
1897 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001898BufListItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899{
1900 buf_T *b;
1901
1902 for (b = firstbuf; b; b = b->b_next, --n)
1903 {
1904 if (n == 0)
1905 return BufferNew(b);
1906 }
1907
1908 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1909 return NULL;
1910}
1911
1912/* Window object - Definitions
1913 */
1914
1915static struct PyMethodDef WindowMethods[] = {
1916 /* name, function, calling, documentation */
1917 { NULL, NULL, 0, NULL }
1918};
1919
1920static PyTypeObject WindowType = {
1921 PyObject_HEAD_INIT(0)
1922 0,
1923 "window",
1924 sizeof(WindowObject),
1925 0,
1926
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 */
1933
1934 0, /* as number */
1935 0, /* as sequence */
1936 0, /* as mapping */
1937
1938 (hashfunc) 0, /* tp_hash, dict(x) */
1939 (ternaryfunc) 0, /* tp_call, x() */
1940 (reprfunc) 0, /* tp_str, str(x) */
1941};
1942
1943/* Window object - Implementation
1944 */
1945
1946 static PyObject *
1947WindowNew(win_T *win)
1948{
1949 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001950 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 * 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
Bram Moolenaare344bea2005-09-01 20:46:49 +00001955 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 * 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.
1959 */
1960
1961 WindowObject *self;
1962
Bram Moolenaare344bea2005-09-01 20:46:49 +00001963 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001965 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 Py_INCREF(self);
1967 }
1968 else
1969 {
1970 self = PyObject_NEW(WindowObject, &WindowType);
1971 if (self == NULL)
1972 return NULL;
1973 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001974 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 }
1976
1977 return (PyObject *)(self);
1978}
1979
1980 static void
1981WindowDestructor(PyObject *self)
1982{
1983 WindowObject *this = (WindowObject *)(self);
1984
1985 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001986 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987
Bram Moolenaar658ada62006-10-03 13:02:36 +00001988 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989}
1990
1991 static int
1992CheckWindow(WindowObject *this)
1993{
1994 if (this->win == INVALID_WINDOW_VALUE)
1995 {
1996 PyErr_SetVim(_("attempt to refer to deleted window"));
1997 return -1;
1998 }
1999
2000 return 0;
2001}
2002
2003 static PyObject *
2004WindowGetattr(PyObject *self, char *name)
2005{
2006 WindowObject *this = (WindowObject *)(self);
2007
2008 if (CheckWindow(this))
2009 return NULL;
2010
2011 if (strcmp(name, "buffer") == 0)
2012 return (PyObject *)BufferNew(this->win->w_buffer);
2013 else if (strcmp(name, "cursor") == 0)
2014 {
2015 pos_T *pos = &this->win->w_cursor;
2016
2017 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2018 }
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)));
2024#endif
2025 else if (strcmp(name,"__members__") == 0)
2026 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2027 else
2028 return Py_FindMethod(WindowMethods, self, name);
2029}
2030
2031 static int
2032WindowSetattr(PyObject *self, char *name, PyObject *val)
2033{
2034 WindowObject *this = (WindowObject *)(self);
2035
2036 if (CheckWindow(this))
2037 return -1;
2038
2039 if (strcmp(name, "buffer") == 0)
2040 {
2041 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2042 return -1;
2043 }
2044 else if (strcmp(name, "cursor") == 0)
2045 {
2046 long lnum;
2047 long col;
2048
2049 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2050 return -1;
2051
2052 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2053 {
2054 PyErr_SetVim(_("cursor position outside buffer"));
2055 return -1;
2056 }
2057
2058 /* Check for keyboard interrupts */
2059 if (VimErrorCheck())
2060 return -1;
2061
2062 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2063
2064 this->win->w_cursor.lnum = lnum;
2065 this->win->w_cursor.col = col;
2066 update_screen(VALID);
2067
2068 return 0;
2069 }
2070 else if (strcmp(name, "height") == 0)
2071 {
2072 int height;
2073 win_T *savewin;
2074
2075 if (!PyArg_Parse(val, "i", &height))
2076 return -1;
2077
2078#ifdef FEAT_GUI
2079 need_mouse_correct = TRUE;
2080#endif
2081 savewin = curwin;
2082 curwin = this->win;
2083 win_setheight(height);
2084 curwin = savewin;
2085
2086 /* Check for keyboard interrupts */
2087 if (VimErrorCheck())
2088 return -1;
2089
2090 return 0;
2091 }
2092#ifdef FEAT_VERTSPLIT
2093 else if (strcmp(name, "width") == 0)
2094 {
2095 int width;
2096 win_T *savewin;
2097
2098 if (!PyArg_Parse(val, "i", &width))
2099 return -1;
2100
2101#ifdef FEAT_GUI
2102 need_mouse_correct = TRUE;
2103#endif
2104 savewin = curwin;
2105 curwin = this->win;
2106 win_setwidth(width);
2107 curwin = savewin;
2108
2109 /* Check for keyboard interrupts */
2110 if (VimErrorCheck())
2111 return -1;
2112
2113 return 0;
2114 }
2115#endif
2116 else
2117 {
2118 PyErr_SetString(PyExc_AttributeError, name);
2119 return -1;
2120 }
2121}
2122
2123 static PyObject *
2124WindowRepr(PyObject *self)
2125{
Bram Moolenaar555b2802005-05-19 21:08:39 +00002126 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002127 WindowObject *this = (WindowObject *)(self);
2128
2129 if (this->win == INVALID_WINDOW_VALUE)
2130 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002131 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 return PyString_FromString(repr);
2133 }
2134 else
2135 {
2136 int i = 0;
2137 win_T *w;
2138
2139 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2140 ++i;
2141
2142 if (w == NULL)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002143 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2144 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00002146 vim_snprintf(repr, 100, _("<window %d>"), i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147
2148 return PyString_FromString(repr);
2149 }
2150}
2151
2152/* Window list object - Definitions
2153 */
2154
2155typedef struct
2156{
2157 PyObject_HEAD
2158}
2159WinListObject;
2160
2161static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002162 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002163 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002164 (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 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169};
2170
2171static PyTypeObject WinListType = {
2172 PyObject_HEAD_INIT(0)
2173 0,
2174 "window list",
2175 sizeof(WinListObject),
2176 0,
2177
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 */
2184
2185 0, /* as number */
2186 &WinListAsSeq, /* as sequence */
2187 0, /* as mapping */
2188
2189 (hashfunc) 0, /* tp_hash, dict(x) */
2190 (ternaryfunc) 0, /* tp_call, x() */
2191 (reprfunc) 0, /* tp_str, str(x) */
2192};
2193
2194/* Window list object - Implementation
2195 */
2196/*ARGSUSED*/
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002197 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198WinListLength(PyObject *self)
2199{
2200 win_T *w = firstwin;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002201 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202
Bram Moolenaarf740b292006-02-16 22:11:02 +00002203 while (w != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 {
2205 ++n;
2206 w = W_NEXT(w);
2207 }
2208
2209 return n;
2210}
2211
2212/*ARGSUSED*/
2213 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002214WinListItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215{
2216 win_T *w;
2217
Bram Moolenaarf740b292006-02-16 22:11:02 +00002218 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 if (n == 0)
2220 return WindowNew(w);
2221
2222 PyErr_SetString(PyExc_IndexError, _("no such window"));
2223 return NULL;
2224}
2225
2226/* Current items object - Definitions
2227 */
2228
2229typedef struct
2230{
2231 PyObject_HEAD
2232}
2233CurrentObject;
2234
2235static PyTypeObject CurrentType = {
2236 PyObject_HEAD_INIT(0)
2237 0,
2238 "current data",
2239 sizeof(CurrentObject),
2240 0,
2241
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 */
2248
2249 0, /* as number */
2250 0, /* as sequence */
2251 0, /* as mapping */
2252
2253 (hashfunc) 0, /* tp_hash, dict(x) */
2254 (ternaryfunc) 0, /* tp_call, x() */
2255 (reprfunc) 0, /* tp_str, str(x) */
2256};
2257
2258/* Current items object - Implementation
2259 */
2260/*ARGSUSED*/
2261 static PyObject *
2262CurrentGetattr(PyObject *self, char *name)
2263{
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)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002269 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270 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");
2274 else
2275 {
2276 PyErr_SetString(PyExc_AttributeError, name);
2277 return NULL;
2278 }
2279}
2280
2281/*ARGSUSED*/
2282 static int
2283CurrentSetattr(PyObject *self, char *name, PyObject *value)
2284{
2285 if (strcmp(name, "line") == 0)
2286 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002287 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 return -1;
2289
2290 return 0;
2291 }
2292 else
2293 {
2294 PyErr_SetString(PyExc_AttributeError, name);
2295 return -1;
2296 }
2297}
2298
2299/* External interface
2300 */
2301
2302 void
2303python_buffer_free(buf_T *buf)
2304{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002305 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002307 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002309 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 }
2311}
2312
2313#if defined(FEAT_WINDOWS) || defined(PROTO)
2314 void
2315python_window_free(win_T *win)
2316{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002317 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002319 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002321 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 }
2323}
2324#endif
2325
2326static BufListObject TheBufferList =
2327{
2328 PyObject_HEAD_INIT(&BufListType)
2329};
2330
2331static WinListObject TheWindowList =
2332{
2333 PyObject_HEAD_INIT(&WinListType)
2334};
2335
2336static CurrentObject TheCurrent =
2337{
2338 PyObject_HEAD_INIT(&CurrentType)
2339};
2340
2341 static int
2342PythonMod_Init(void)
2343{
2344 PyObject *mod;
2345 PyObject *dict;
2346 static char *(argv[2]) = {"", NULL};
2347
2348 /* Fixups... */
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;
2355
2356 /* Set sys.argv[] to avoid a crash in warn(). */
2357 PySys_SetArgv(1, argv);
2358
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002359 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 dict = PyModule_GetDict(mod);
2361
2362 VimError = Py_BuildValue("s", "vim.error");
2363
2364 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00002365 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2366 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2367 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368
2369 if (PyErr_Occurred())
2370 return -1;
2371
2372 return 0;
2373}
2374
2375/*************************************************************************
2376 * 4. Utility functions for handling the interface between Vim and Python.
2377 */
2378
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
2381 * string object.
2382 */
2383 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002384GetBufferLine(buf_T *buf, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385{
2386 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2387}
2388
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.
2392 */
2393 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002394GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002396 PyInt i;
2397 PyInt n = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 PyObject *list = PyList_New(n);
2399
2400 if (list == NULL)
2401 return NULL;
2402
2403 for (i = 0; i < n; ++i)
2404 {
2405 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2406
2407 /* Error check - was the Python string creation OK? */
2408 if (str == NULL)
2409 {
2410 Py_DECREF(list);
2411 return NULL;
2412 }
2413
2414 /* Set the list item */
2415 if (PyList_SetItem(list, i, str))
2416 {
2417 Py_DECREF(str);
2418 Py_DECREF(list);
2419 return NULL;
2420 }
2421 }
2422
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
2425 * with it).
2426 */
2427
2428 return list;
2429}
2430
2431/*
2432 * Check if deleting lines made the cursor position invalid.
2433 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2434 * deleted).
2435 */
2436 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002437py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438{
2439 if (curwin->w_cursor.lnum >= lo)
2440 {
2441 /* Adjust the cursor position if it's in/after the changed
2442 * lines. */
2443 if (curwin->w_cursor.lnum >= hi)
2444 {
2445 curwin->w_cursor.lnum += extra;
2446 check_cursor_col();
2447 }
2448 else if (extra < 0)
2449 {
2450 curwin->w_cursor.lnum = lo;
2451 check_cursor();
2452 }
Bram Moolenaar454ec052007-03-08 09:20:28 +00002453 else
2454 check_cursor_col();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 changed_cline_bef_curs();
2456 }
2457 invalidate_botline();
2458}
2459
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.
2467 */
2468 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002469SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470{
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.
2476 */
2477 if (line == Py_None || line == NULL)
2478 {
2479 buf_T *savebuf = curbuf;
2480
2481 PyErr_Clear();
2482 curbuf = buf;
2483
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"));
2488 else
2489 {
2490 deleted_lines_mark((linenr_T)n, 1L);
2491 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002492 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 }
2494
2495 curbuf = savebuf;
2496
2497 if (PyErr_Occurred() || VimErrorCheck())
2498 return FAIL;
2499
2500 if (len_change)
2501 *len_change = -1;
2502
2503 return OK;
2504 }
2505 else if (PyString_Check(line))
2506 {
2507 char *save = StringToLine(line);
2508 buf_T *savebuf = curbuf;
2509
2510 if (save == NULL)
2511 return FAIL;
2512
2513 /* We do not need to free "save" if ml_replace() consumes it. */
2514 PyErr_Clear();
2515 curbuf = buf;
2516
2517 if (u_savesub((linenr_T)n) == FAIL)
2518 {
2519 PyErr_SetVim(_("cannot save undo information"));
2520 vim_free(save);
2521 }
2522 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2523 {
2524 PyErr_SetVim(_("cannot replace line"));
2525 vim_free(save);
2526 }
2527 else
2528 changed_bytes((linenr_T)n, 0);
2529
2530 curbuf = savebuf;
2531
Bram Moolenaar454ec052007-03-08 09:20:28 +00002532 /* Check that the cursor is not beyond the end of the line now. */
2533 if (buf == curwin->w_buffer)
2534 check_cursor_col();
2535
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (PyErr_Occurred() || VimErrorCheck())
2537 return FAIL;
2538
2539 if (len_change)
2540 *len_change = 0;
2541
2542 return OK;
2543 }
2544 else
2545 {
2546 PyErr_BadArgument();
2547 return FAIL;
2548 }
2549}
2550
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.
2558 */
2559 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002560SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561{
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.
2567 */
2568 if (list == Py_None || list == NULL)
2569 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002570 PyInt i;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002571 PyInt n = (int)(hi - lo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 buf_T *savebuf = curbuf;
2573
2574 PyErr_Clear();
2575 curbuf = buf;
2576
2577 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2578 PyErr_SetVim(_("cannot save undo information"));
2579 else
2580 {
2581 for (i = 0; i < n; ++i)
2582 {
2583 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2584 {
2585 PyErr_SetVim(_("cannot delete line"));
2586 break;
2587 }
2588 }
2589 deleted_lines_mark((linenr_T)lo, (long)i);
2590
2591 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002592 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002593 }
2594
2595 curbuf = savebuf;
2596
2597 if (PyErr_Occurred() || VimErrorCheck())
2598 return FAIL;
2599
2600 if (len_change)
2601 *len_change = -n;
2602
2603 return OK;
2604 }
2605 else if (PyList_Check(list))
2606 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002607 PyInt i;
2608 PyInt new_len = PyList_Size(list);
2609 PyInt old_len = hi - lo;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002610 PyInt extra = 0; /* lines added to text, can be negative */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 char **array;
2612 buf_T *savebuf;
2613
2614 if (new_len == 0) /* avoid allocating zero bytes */
2615 array = NULL;
2616 else
2617 {
2618 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2619 if (array == NULL)
2620 {
2621 PyErr_NoMemory();
2622 return FAIL;
2623 }
2624 }
2625
2626 for (i = 0; i < new_len; ++i)
2627 {
2628 PyObject *line = PyList_GetItem(list, i);
2629
2630 array[i] = StringToLine(line);
2631 if (array[i] == NULL)
2632 {
2633 while (i)
2634 vim_free(array[--i]);
2635 vim_free(array);
2636 return FAIL;
2637 }
2638 }
2639
2640 savebuf = curbuf;
2641
2642 PyErr_Clear();
2643 curbuf = buf;
2644
2645 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2646 PyErr_SetVim(_("cannot save undo information"));
2647
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".
2651 */
2652 if (!PyErr_Occurred())
2653 {
2654 for (i = 0; i < old_len - new_len; ++i)
2655 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2656 {
2657 PyErr_SetVim(_("cannot delete line"));
2658 break;
2659 }
2660 extra -= i;
2661 }
2662
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.
2666 */
2667 if (!PyErr_Occurred())
2668 {
2669 for (i = 0; i < old_len && i < new_len; ++i)
2670 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2671 == FAIL)
2672 {
2673 PyErr_SetVim(_("cannot replace line"));
2674 break;
2675 }
2676 }
2677 else
2678 i = 0;
2679
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).
2683 */
2684 if (!PyErr_Occurred())
2685 {
2686 while (i < new_len)
2687 {
2688 if (ml_append((linenr_T)(lo + i - 1),
2689 (char_u *)array[i], 0, FALSE) == FAIL)
2690 {
2691 PyErr_SetVim(_("cannot insert line"));
2692 break;
2693 }
2694 vim_free(array[i]);
2695 ++i;
2696 ++extra;
2697 }
2698 }
2699
2700 /* Free any left-over old_len, as a result of an error */
2701 while (i < new_len)
2702 {
2703 vim_free(array[i]);
2704 ++i;
2705 }
2706
2707 /* Free the array of old_len. All of its contents have now
2708 * been dealt with (either freed, or the responsibility passed
2709 * to vim.
2710 */
2711 vim_free(array);
2712
2713 /* Adjust marks. Invalidate any which lie in the
2714 * changed range, and move any in the remainder of the buffer.
2715 */
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);
2719
2720 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002721 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002722
2723 curbuf = savebuf;
2724
2725 if (PyErr_Occurred() || VimErrorCheck())
2726 return FAIL;
2727
2728 if (len_change)
2729 *len_change = new_len - old_len;
2730
2731 return OK;
2732 }
2733 else
2734 {
2735 PyErr_BadArgument();
2736 return FAIL;
2737 }
2738}
2739
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.
2747 */
2748 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002749InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750{
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.
2753 */
2754 if (PyString_Check(lines))
2755 {
2756 char *str = StringToLine(lines);
2757 buf_T *savebuf;
2758
2759 if (str == NULL)
2760 return FAIL;
2761
2762 savebuf = curbuf;
2763
2764 PyErr_Clear();
2765 curbuf = buf;
2766
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"));
2771 else
2772 appended_lines_mark((linenr_T)n, 1L);
2773
2774 vim_free(str);
2775 curbuf = savebuf;
2776 update_screen(VALID);
2777
2778 if (PyErr_Occurred() || VimErrorCheck())
2779 return FAIL;
2780
2781 if (len_change)
2782 *len_change = 1;
2783
2784 return OK;
2785 }
2786 else if (PyList_Check(lines))
2787 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002788 PyInt i;
2789 PyInt size = PyList_Size(lines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790 char **array;
2791 buf_T *savebuf;
2792
2793 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2794 if (array == NULL)
2795 {
2796 PyErr_NoMemory();
2797 return FAIL;
2798 }
2799
2800 for (i = 0; i < size; ++i)
2801 {
2802 PyObject *line = PyList_GetItem(lines, i);
2803 array[i] = StringToLine(line);
2804
2805 if (array[i] == NULL)
2806 {
2807 while (i)
2808 vim_free(array[--i]);
2809 vim_free(array);
2810 return FAIL;
2811 }
2812 }
2813
2814 savebuf = curbuf;
2815
2816 PyErr_Clear();
2817 curbuf = buf;
2818
2819 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2820 PyErr_SetVim(_("cannot save undo information"));
2821 else
2822 {
2823 for (i = 0; i < size; ++i)
2824 {
2825 if (ml_append((linenr_T)(n + i),
2826 (char_u *)array[i], 0, FALSE) == FAIL)
2827 {
2828 PyErr_SetVim(_("cannot insert line"));
2829
2830 /* Free the rest of the lines */
2831 while (i < size)
2832 vim_free(array[i++]);
2833
2834 break;
2835 }
2836 vim_free(array[i]);
2837 }
2838 if (i > 0)
2839 appended_lines_mark((linenr_T)n, (long)i);
2840 }
2841
2842 /* Free the array of lines. All of its contents have now
2843 * been freed.
2844 */
2845 vim_free(array);
2846
2847 curbuf = savebuf;
2848 update_screen(VALID);
2849
2850 if (PyErr_Occurred() || VimErrorCheck())
2851 return FAIL;
2852
2853 if (len_change)
2854 *len_change = size;
2855
2856 return OK;
2857 }
2858 else
2859 {
2860 PyErr_BadArgument();
2861 return FAIL;
2862 }
2863}
2864
2865/* Convert a Vim line into a Python string.
2866 * All internal newlines are replaced by null characters.
2867 *
2868 * On errors, the Python exception data is set, and NULL is returned.
2869 */
2870 static PyObject *
2871LineToString(const char *str)
2872{
2873 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002874 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875 char *p;
2876
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.
2880 */
2881 result = PyString_FromStringAndSize(NULL, len);
2882 if (result == NULL)
2883 return NULL;
2884
2885 p = PyString_AsString(result);
2886
2887 while (*str)
2888 {
2889 if (*str == '\n')
2890 *p = '\0';
2891 else
2892 *p = *str;
2893
2894 ++p;
2895 ++str;
2896 }
2897
2898 return result;
2899}
2900
2901/* Convert a Python string into a Vim line.
2902 *
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
2905 * characters.
2906 *
2907 * On errors, the Python exception data is set, and NULL is returned.
2908 */
2909 static char *
2910StringToLine(PyObject *obj)
2911{
2912 const char *str;
2913 char *save;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002914 PyInt len;
2915 PyInt i;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002916 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917
2918 if (obj == NULL || !PyString_Check(obj))
2919 {
2920 PyErr_BadArgument();
2921 return NULL;
2922 }
2923
2924 str = PyString_AsString(obj);
2925 len = PyString_Size(obj);
2926
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002927 /*
2928 * Error checking: String must not contain newlines, as we
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 * are replacing a single line, and we must replace it with
2930 * a single line.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002931 * A trailing newline is removed, so that append(f.readlines()) works.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002933 p = memchr(str, '\n', len);
2934 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002936 if (p == str + len - 1)
2937 --len;
2938 else
2939 {
2940 PyErr_SetVim(_("string cannot contain newlines"));
2941 return NULL;
2942 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 }
2944
2945 /* Create a copy of the string, with internal nulls replaced by
2946 * newline characters, as is the vim convention.
2947 */
2948 save = (char *)alloc((unsigned)(len+1));
2949 if (save == NULL)
2950 {
2951 PyErr_NoMemory();
2952 return NULL;
2953 }
2954
2955 for (i = 0; i < len; ++i)
2956 {
2957 if (str[i] == '\0')
2958 save[i] = '\n';
2959 else
2960 save[i] = str[i];
2961 }
2962
2963 save[i] = '\0';
2964
2965 return save;
2966}
2967
2968/* Check to see whether a Vim error has been reported, or a keyboard
2969 * interrupt has been detected.
2970 */
2971 static int
2972VimErrorCheck(void)
2973{
2974 if (got_int)
2975 {
2976 PyErr_SetNone(PyExc_KeyboardInterrupt);
2977 return 1;
2978 }
2979 else if (did_emsg && !PyErr_Occurred())
2980 {
2981 PyErr_SetNone(VimError);
2982 return 1;
2983 }
2984
2985 return 0;
2986}
2987
2988
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)
2992
2993 char *
2994Py_GetProgramName(void)
2995{
2996 return "vim";
2997}
2998#endif /* Python 1.4 */