blob: ce9bb3eebe93de9c708136858ac8de06f04944d4 [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 Moolenaar9774ecc2008-11-20 10:04:53 +0000534 /* Remove the element from sys.path that was added because of our
535 * argv[0] value in PythonMod_Init(). Previously we used an empty
536 * string, but dependinding on the OS we then get an empty entry or
537 * the current directory in sys.path. */
538 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
539
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000540 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542
543 initialised = 1;
544 }
545
546 return 0;
547
548fail:
549 /* We call PythonIO_Flush() here to print any Python errors.
550 * This is OK, as it is possible to call this function even
551 * if PythonIO_Init() has not completed successfully (it will
552 * not do anything in this case).
553 */
554 PythonIO_Flush();
555 return -1;
556}
557
558/*
559 * External interface
560 */
561 static void
562DoPythonCommand(exarg_T *eap, const char *cmd)
563{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000564#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565 static int recursive = 0;
566#endif
567#if defined(MACOS) && !defined(MACOS_X_UNIX)
568 GrafPtr oldPort;
569#endif
570#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
571 char *saved_locale;
572#endif
573
574#ifndef PY_CAN_RECURSE
575 if (recursive)
576 {
577 EMSG(_("E659: Cannot invoke Python recursively"));
578 return;
579 }
580 ++recursive;
581#endif
582
583#if defined(MACOS) && !defined(MACOS_X_UNIX)
584 GetPort(&oldPort);
585 /* Check if the Python library is available */
586 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
587 goto theend;
588#endif
589 if (Python_Init())
590 goto theend;
591
592 RangeStart = eap->line1;
593 RangeEnd = eap->line2;
594 Python_Release_Vim(); /* leave vim */
595
596#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
597 /* Python only works properly when the LC_NUMERIC locale is "C". */
598 saved_locale = setlocale(LC_NUMERIC, NULL);
599 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
600 saved_locale = NULL;
601 else
602 {
603 /* Need to make a copy, value may change when setting new locale. */
604 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
605 (void)setlocale(LC_NUMERIC, "C");
606 }
607#endif
608
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610
611 PyRun_SimpleString((char *)(cmd));
612
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
615#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
616 if (saved_locale != NULL)
617 {
618 (void)setlocale(LC_NUMERIC, saved_locale);
619 vim_free(saved_locale);
620 }
621#endif
622
623 Python_Lock_Vim(); /* enter vim */
624 PythonIO_Flush();
625#if defined(MACOS) && !defined(MACOS_X_UNIX)
626 SetPort(oldPort);
627#endif
628
629theend:
630#ifndef PY_CAN_RECURSE
631 --recursive;
632#endif
633 return; /* keeps lint happy */
634}
635
636/*
637 * ":python"
638 */
639 void
640ex_python(exarg_T *eap)
641{
642 char_u *script;
643
644 script = script_get(eap, eap->arg);
645 if (!eap->skip)
646 {
647 if (script == NULL)
648 DoPythonCommand(eap, (char *)eap->arg);
649 else
650 DoPythonCommand(eap, (char *)script);
651 }
652 vim_free(script);
653}
654
655#define BUFFER_SIZE 1024
656
657/*
658 * ":pyfile"
659 */
660 void
661ex_pyfile(exarg_T *eap)
662{
663 static char buffer[BUFFER_SIZE];
664 const char *file = (char *)eap->arg;
665 char *p;
666
667 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
668 * stdio file pointer, but Vim and the Python DLL are compiled with
669 * different options under Windows, meaning that stdio pointers aren't
670 * compatible between the two. Yuk.
671 *
672 * Put the string "execfile('file')" into buffer. But, we need to
673 * escape any backslashes or single quotes in the file name, so that
674 * Python won't mangle the file name.
675 */
676 strcpy(buffer, "execfile('");
677 p = buffer + 10; /* size of "execfile('" */
678
679 while (*file && p < buffer + (BUFFER_SIZE - 3))
680 {
681 if (*file == '\\' || *file == '\'')
682 *p++ = '\\';
683 *p++ = *file++;
684 }
685
686 /* If we didn't finish the file name, we hit a buffer overflow */
687 if (*file != '\0')
688 return;
689
690 /* Put in the terminating "')" and a null */
691 *p++ = '\'';
692 *p++ = ')';
693 *p++ = '\0';
694
695 /* Execute the file */
696 DoPythonCommand(eap, buffer);
697}
698
699/******************************************************
700 * 2. Python output stream: writes output via [e]msg().
701 */
702
703/* Implementation functions
704 */
705
706static PyObject *OutputGetattr(PyObject *, char *);
707static int OutputSetattr(PyObject *, char *, PyObject *);
708
709static PyObject *OutputWrite(PyObject *, PyObject *);
710static PyObject *OutputWritelines(PyObject *, PyObject *);
711
712typedef void (*writefn)(char_u *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000713static void writer(writefn fn, char_u *str, PyInt n);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714
715/* Output object definition
716 */
717
718typedef struct
719{
720 PyObject_HEAD
721 long softspace;
722 long error;
723} OutputObject;
724
725static struct PyMethodDef OutputMethods[] = {
726 /* name, function, calling, documentation */
727 {"write", OutputWrite, 1, "" },
728 {"writelines", OutputWritelines, 1, "" },
729 { NULL, NULL, 0, NULL }
730};
731
732static PyTypeObject OutputType = {
733 PyObject_HEAD_INIT(0)
734 0,
735 "message",
736 sizeof(OutputObject),
737 0,
738
739 (destructor) 0,
740 (printfunc) 0,
741 (getattrfunc) OutputGetattr,
742 (setattrfunc) OutputSetattr,
743 (cmpfunc) 0,
744 (reprfunc) 0,
745
746 0, /* as number */
747 0, /* as sequence */
748 0, /* as mapping */
749
750 (hashfunc) 0,
751 (ternaryfunc) 0,
752 (reprfunc) 0
753};
754
755/*************/
756
757 static PyObject *
758OutputGetattr(PyObject *self, char *name)
759{
760 if (strcmp(name, "softspace") == 0)
761 return PyInt_FromLong(((OutputObject *)(self))->softspace);
762
763 return Py_FindMethod(OutputMethods, self, name);
764}
765
766 static int
767OutputSetattr(PyObject *self, char *name, PyObject *val)
768{
769 if (val == NULL) {
770 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
771 return -1;
772 }
773
774 if (strcmp(name, "softspace") == 0)
775 {
776 if (!PyInt_Check(val)) {
777 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
778 return -1;
779 }
780
781 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
782 return 0;
783 }
784
785 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
786 return -1;
787}
788
789/*************/
790
791 static PyObject *
792OutputWrite(PyObject *self, PyObject *args)
793{
794 int len;
795 char *str;
796 int error = ((OutputObject *)(self))->error;
797
798 if (!PyArg_ParseTuple(args, "s#", &str, &len))
799 return NULL;
800
801 Py_BEGIN_ALLOW_THREADS
802 Python_Lock_Vim();
803 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
804 Python_Release_Vim();
805 Py_END_ALLOW_THREADS
806
807 Py_INCREF(Py_None);
808 return Py_None;
809}
810
811 static PyObject *
812OutputWritelines(PyObject *self, PyObject *args)
813{
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000814 PyInt n;
815 PyInt i;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816 PyObject *list;
817 int error = ((OutputObject *)(self))->error;
818
819 if (!PyArg_ParseTuple(args, "O", &list))
820 return NULL;
821 Py_INCREF(list);
822
823 if (!PyList_Check(list)) {
824 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
825 Py_DECREF(list);
826 return NULL;
827 }
828
829 n = PyList_Size(list);
830
831 for (i = 0; i < n; ++i)
832 {
833 PyObject *line = PyList_GetItem(list, i);
834 char *str;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000835 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836
837 if (!PyArg_Parse(line, "s#", &str, &len)) {
838 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
839 Py_DECREF(list);
840 return NULL;
841 }
842
843 Py_BEGIN_ALLOW_THREADS
844 Python_Lock_Vim();
845 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
846 Python_Release_Vim();
847 Py_END_ALLOW_THREADS
848 }
849
850 Py_DECREF(list);
851 Py_INCREF(Py_None);
852 return Py_None;
853}
854
855/* Output buffer management
856 */
857
858static char_u *buffer = NULL;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000859static PyInt buffer_len = 0;
860static PyInt buffer_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000861
862static writefn old_fn = NULL;
863
864 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000865buffer_ensure(PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000867 PyInt new_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868 char_u *new_buffer;
869
870 if (n < buffer_size)
871 return;
872
873 new_size = buffer_size;
874 while (new_size < n)
875 new_size += 80;
876
877 if (new_size != buffer_size)
878 {
879 new_buffer = alloc((unsigned)new_size);
880 if (new_buffer == NULL)
881 return;
882
883 if (buffer)
884 {
885 memcpy(new_buffer, buffer, buffer_len);
886 vim_free(buffer);
887 }
888
889 buffer = new_buffer;
890 buffer_size = new_size;
891 }
892}
893
894 static void
895PythonIO_Flush(void)
896{
897 if (old_fn && buffer_len)
898 {
899 buffer[buffer_len] = 0;
900 old_fn(buffer);
901 }
902
903 buffer_len = 0;
904}
905
906 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000907writer(writefn fn, char_u *str, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908{
909 char_u *ptr;
910
911 if (fn != old_fn && old_fn != NULL)
912 PythonIO_Flush();
913
914 old_fn = fn;
915
916 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
917 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000918 PyInt len = ptr - str;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919
920 buffer_ensure(buffer_len + len + 1);
921
922 memcpy(buffer + buffer_len, str, len);
923 buffer_len += len;
924 buffer[buffer_len] = 0;
925 fn(buffer);
926 str = ptr + 1;
927 n -= len + 1;
928 buffer_len = 0;
929 }
930
931 /* Put the remaining text into the buffer for later printing */
932 buffer_ensure(buffer_len + n + 1);
933 memcpy(buffer + buffer_len, str, n);
934 buffer_len += n;
935}
936
937/***************/
938
939static OutputObject Output =
940{
941 PyObject_HEAD_INIT(&OutputType)
942 0,
943 0
944};
945
946static OutputObject Error =
947{
948 PyObject_HEAD_INIT(&OutputType)
949 0,
950 1
951};
952
953 static int
954PythonIO_Init(void)
955{
956 /* Fixups... */
957 OutputType.ob_type = &PyType_Type;
958
Bram Moolenaar7df2d662005-01-25 22:18:08 +0000959 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
960 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961
962 if (PyErr_Occurred())
963 {
964 EMSG(_("E264: Python: Error initialising I/O objects"));
965 return -1;
966 }
967
968 return 0;
969}
970
971/******************************************************
972 * 3. Implementation of the Vim module for Python
973 */
974
975/* Vim module - Implementation functions
976 * -------------------------------------
977 */
978
979static PyObject *VimError;
980
981static PyObject *VimCommand(PyObject *, PyObject *);
982static PyObject *VimEval(PyObject *, PyObject *);
983
984/* Window type - Implementation functions
985 * --------------------------------------
986 */
987
988typedef struct
989{
990 PyObject_HEAD
991 win_T *win;
992}
993WindowObject;
994
995#define INVALID_WINDOW_VALUE ((win_T *)(-1))
996
997#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
998
999static PyObject *WindowNew(win_T *);
1000
1001static void WindowDestructor(PyObject *);
1002static PyObject *WindowGetattr(PyObject *, char *);
1003static int WindowSetattr(PyObject *, char *, PyObject *);
1004static PyObject *WindowRepr(PyObject *);
1005
1006/* Buffer type - Implementation functions
1007 * --------------------------------------
1008 */
1009
1010typedef struct
1011{
1012 PyObject_HEAD
1013 buf_T *buf;
1014}
1015BufferObject;
1016
1017#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1018
1019#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1020
1021static PyObject *BufferNew (buf_T *);
1022
1023static void BufferDestructor(PyObject *);
1024static PyObject *BufferGetattr(PyObject *, char *);
1025static PyObject *BufferRepr(PyObject *);
1026
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001027static PyInt BufferLength(PyObject *);
1028static PyObject *BufferItem(PyObject *, PyInt);
1029static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1030static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1031static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032
1033static PyObject *BufferAppend(PyObject *, PyObject *);
1034static PyObject *BufferMark(PyObject *, PyObject *);
1035static PyObject *BufferRange(PyObject *, PyObject *);
1036
1037/* Line range type - Implementation functions
1038 * --------------------------------------
1039 */
1040
1041typedef struct
1042{
1043 PyObject_HEAD
1044 BufferObject *buf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001045 PyInt start;
1046 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047}
1048RangeObject;
1049
1050#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1051
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001052static PyObject *RangeNew(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053
1054static void RangeDestructor(PyObject *);
1055static PyObject *RangeGetattr(PyObject *, char *);
1056static PyObject *RangeRepr(PyObject *);
1057
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001058static PyInt RangeLength(PyObject *);
1059static PyObject *RangeItem(PyObject *, PyInt);
1060static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1061static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1062static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063
1064static PyObject *RangeAppend(PyObject *, PyObject *);
1065
1066/* Window list type - Implementation functions
1067 * -------------------------------------------
1068 */
1069
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001070static PyInt WinListLength(PyObject *);
1071static PyObject *WinListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072
1073/* Buffer list type - Implementation functions
1074 * -------------------------------------------
1075 */
1076
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001077static PyInt BufListLength(PyObject *);
1078static PyObject *BufListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079
1080/* Current objects type - Implementation functions
1081 * -----------------------------------------------
1082 */
1083
1084static PyObject *CurrentGetattr(PyObject *, char *);
1085static int CurrentSetattr(PyObject *, char *, PyObject *);
1086
1087/* Vim module - Definitions
1088 */
1089
1090static struct PyMethodDef VimMethods[] = {
1091 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001092 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1093 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 { NULL, NULL, 0, NULL }
1095};
1096
1097/* Vim module - Implementation
1098 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001100VimCommand(PyObject *self UNUSED, PyObject *args)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101{
1102 char *cmd;
1103 PyObject *result;
1104
1105 if (!PyArg_ParseTuple(args, "s", &cmd))
1106 return NULL;
1107
1108 PyErr_Clear();
1109
1110 Py_BEGIN_ALLOW_THREADS
1111 Python_Lock_Vim();
1112
1113 do_cmdline_cmd((char_u *)cmd);
1114 update_screen(VALID);
1115
1116 Python_Release_Vim();
1117 Py_END_ALLOW_THREADS
1118
1119 if (VimErrorCheck())
1120 result = NULL;
1121 else
1122 result = Py_None;
1123
1124 Py_XINCREF(result);
1125 return result;
1126}
1127
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001128#ifdef FEAT_EVAL
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001129/*
1130 * Function to translate a typval_T into a PyObject; this will recursively
1131 * translate lists/dictionaries into their Python equivalents.
1132 *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001133 * The depth parameter is to avoid infinite recursion, set it to 1 when
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001134 * you call VimToPython.
1135 */
1136 static PyObject *
1137VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1138{
1139 PyObject *result;
1140 PyObject *newObj;
1141 char ptrBuf[NUMBUFLEN];
1142
1143 /* Avoid infinite recursion */
1144 if (depth > 100)
1145 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001146 Py_INCREF(Py_None);
1147 result = Py_None;
1148 return result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001149 }
1150
1151 /* Check if we run into a recursive loop. The item must be in lookupDict
1152 * then and we can use it again. */
Bram Moolenaard72b3862009-01-13 17:11:05 +00001153 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1154 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1155 {
1156 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
1157 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1158 : (long_u)our_tv->vval.v_dict);
1159 result = PyDict_GetItemString(lookupDict, ptrBuf);
1160 if (result != NULL)
1161 {
1162 Py_INCREF(result);
1163 return result;
1164 }
1165 }
1166
1167 if (our_tv->v_type == VAR_STRING)
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001168 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001169 result = Py_BuildValue("s", our_tv->vval.v_string);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001170 }
1171 else if (our_tv->v_type == VAR_NUMBER)
1172 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001173 char buf[NUMBUFLEN];
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001174
1175 /* For backwards compatibility numbers are stored as strings. */
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001176 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1177 result = Py_BuildValue("s", buf);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001178 }
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001179# ifdef FEAT_FLOAT
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001180 else if (our_tv->v_type == VAR_FLOAT)
1181 {
1182 char buf[NUMBUFLEN];
1183
1184 sprintf(buf, "%f", our_tv->vval.v_float);
1185 result = Py_BuildValue("s", buf);
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001186 }
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001187# endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001188 else if (our_tv->v_type == VAR_LIST)
1189 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001190 list_T *list = our_tv->vval.v_list;
1191 listitem_T *curr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001192
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001193 result = PyList_New(0);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001194
1195 if (list != NULL)
1196 {
Bram Moolenaard72b3862009-01-13 17:11:05 +00001197 PyDict_SetItemString(lookupDict, ptrBuf, result);
1198
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001199 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1200 {
1201 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1202 PyList_Append(result, newObj);
1203 Py_DECREF(newObj);
1204 }
1205 }
1206 }
1207 else if (our_tv->v_type == VAR_DICT)
1208 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001209 result = PyDict_New();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001210
1211 if (our_tv->vval.v_dict != NULL)
1212 {
1213 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001214 long_u todo = ht->ht_used;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001215 hashitem_T *hi;
1216 dictitem_T *di;
1217
Bram Moolenaard72b3862009-01-13 17:11:05 +00001218 PyDict_SetItemString(lookupDict, ptrBuf, result);
1219
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001220 for (hi = ht->ht_array; todo > 0; ++hi)
1221 {
1222 if (!HASHITEM_EMPTY(hi))
1223 {
1224 --todo;
1225
1226 di = dict_lookup(hi);
1227 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1228 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1229 Py_DECREF(newObj);
1230 }
1231 }
1232 }
1233 }
1234 else
1235 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001236 Py_INCREF(Py_None);
1237 result = Py_None;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001238 }
1239
1240 return result;
1241}
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001242#endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001243
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001245VimEval(PyObject *self UNUSED, PyObject *args)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246{
1247#ifdef FEAT_EVAL
1248 char *expr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001249 typval_T *our_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250 PyObject *result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001251 PyObject *lookup_dict;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252
1253 if (!PyArg_ParseTuple(args, "s", &expr))
1254 return NULL;
1255
1256 Py_BEGIN_ALLOW_THREADS
1257 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001258 our_tv = eval_expr((char_u *)expr, NULL);
1259
Bram Moolenaar071d4272004-06-13 20:20:40 +00001260 Python_Release_Vim();
1261 Py_END_ALLOW_THREADS
1262
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001263 if (our_tv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 {
1265 PyErr_SetVim(_("invalid expression"));
1266 return NULL;
1267 }
1268
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001269 /* Convert the Vim type into a Python type. Create a dictionary that's
1270 * used to check for recursive loops. */
1271 lookup_dict = PyDict_New();
1272 result = VimToPython(our_tv, 1, lookup_dict);
1273 Py_DECREF(lookup_dict);
1274
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275
1276 Py_BEGIN_ALLOW_THREADS
1277 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001278 free_tv(our_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279 Python_Release_Vim();
1280 Py_END_ALLOW_THREADS
1281
1282 return result;
1283#else
1284 PyErr_SetVim(_("expressions disabled at compile time"));
1285 return NULL;
1286#endif
1287}
1288
1289/* Common routines for buffers and line ranges
1290 * -------------------------------------------
1291 */
1292 static int
1293CheckBuffer(BufferObject *this)
1294{
1295 if (this->buf == INVALID_BUFFER_VALUE)
1296 {
1297 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1298 return -1;
1299 }
1300
1301 return 0;
1302}
1303
1304 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001305RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306{
1307 if (CheckBuffer(self))
1308 return NULL;
1309
1310 if (n < 0 || n > end - start)
1311 {
1312 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1313 return NULL;
1314 }
1315
1316 return GetBufferLine(self->buf, n+start);
1317}
1318
1319 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001320RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001322 PyInt size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323
1324 if (CheckBuffer(self))
1325 return NULL;
1326
1327 size = end - start + 1;
1328
1329 if (lo < 0)
1330 lo = 0;
1331 else if (lo > size)
1332 lo = size;
1333 if (hi < 0)
1334 hi = 0;
1335 if (hi < lo)
1336 hi = lo;
1337 else if (hi > size)
1338 hi = size;
1339
1340 return GetBufferLineList(self->buf, lo+start, hi+start);
1341}
1342
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001343 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001344RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001346 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001347
1348 if (CheckBuffer(self))
1349 return -1;
1350
1351 if (n < 0 || n > end - start)
1352 {
1353 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1354 return -1;
1355 }
1356
1357 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1358 return -1;
1359
1360 if (new_end)
1361 *new_end = end + len_change;
1362
1363 return 0;
1364}
1365
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001366 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001367RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001369 PyInt size;
1370 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371
1372 /* Self must be a valid buffer */
1373 if (CheckBuffer(self))
1374 return -1;
1375
1376 /* Sort out the slice range */
1377 size = end - start + 1;
1378
1379 if (lo < 0)
1380 lo = 0;
1381 else if (lo > size)
1382 lo = size;
1383 if (hi < 0)
1384 hi = 0;
1385 if (hi < lo)
1386 hi = lo;
1387 else if (hi > size)
1388 hi = size;
1389
1390 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1391 return -1;
1392
1393 if (new_end)
1394 *new_end = end + len_change;
1395
1396 return 0;
1397}
1398
1399 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001400RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401{
1402 PyObject *lines;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001403 PyInt len_change;
1404 PyInt max;
1405 PyInt n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406
1407 if (CheckBuffer(self))
1408 return NULL;
1409
1410 max = n = end - start + 1;
1411
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001412 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 return NULL;
1414
1415 if (n < 0 || n > max)
1416 {
1417 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1418 return NULL;
1419 }
1420
1421 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1422 return NULL;
1423
1424 if (new_end)
1425 *new_end = end + len_change;
1426
1427 Py_INCREF(Py_None);
1428 return Py_None;
1429}
1430
1431
1432/* Buffer object - Definitions
1433 */
1434
1435static struct PyMethodDef BufferMethods[] = {
1436 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001437 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1438 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1439 {"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 +00001440 { NULL, NULL, 0, NULL }
1441};
1442
1443static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001444 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001446 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1447 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1448 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1449 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1450 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451};
1452
1453static PyTypeObject BufferType = {
1454 PyObject_HEAD_INIT(0)
1455 0,
1456 "buffer",
1457 sizeof(BufferObject),
1458 0,
1459
1460 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1461 (printfunc) 0, /* tp_print, print x */
1462 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1463 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1464 (cmpfunc) 0, /* tp_compare, x>y */
1465 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1466
1467 0, /* as number */
1468 &BufferAsSeq, /* as sequence */
1469 0, /* as mapping */
1470
1471 (hashfunc) 0, /* tp_hash, dict(x) */
1472 (ternaryfunc) 0, /* tp_call, x() */
1473 (reprfunc) 0, /* tp_str, str(x) */
1474};
1475
1476/* Buffer object - Implementation
1477 */
1478
1479 static PyObject *
1480BufferNew(buf_T *buf)
1481{
1482 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001483 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001484 * then we can get at it in buf_freeall() in vim. We then
1485 * need to create only ONE Python object per buffer - if
1486 * we try to create a second, just INCREF the existing one
1487 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001488 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 * Question: what to do on a buf_freeall(). We'll probably
1490 * have to either delete the Python object (DECREF it to
1491 * zero - a bad idea, as it leaves dangling refs!) or
1492 * set the buf_T * value to an invalid value (-1?), which
1493 * means we need checks in all access functions... Bah.
1494 */
1495
1496 BufferObject *self;
1497
Bram Moolenaare344bea2005-09-01 20:46:49 +00001498 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001500 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 Py_INCREF(self);
1502 }
1503 else
1504 {
1505 self = PyObject_NEW(BufferObject, &BufferType);
1506 if (self == NULL)
1507 return NULL;
1508 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001509 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510 }
1511
1512 return (PyObject *)(self);
1513}
1514
1515 static void
1516BufferDestructor(PyObject *self)
1517{
1518 BufferObject *this = (BufferObject *)(self);
1519
1520 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001521 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522
Bram Moolenaar658ada62006-10-03 13:02:36 +00001523 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001524}
1525
1526 static PyObject *
1527BufferGetattr(PyObject *self, char *name)
1528{
1529 BufferObject *this = (BufferObject *)(self);
1530
1531 if (CheckBuffer(this))
1532 return NULL;
1533
1534 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001535 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001537 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 else if (strcmp(name,"__members__") == 0)
1539 return Py_BuildValue("[ss]", "name", "number");
1540 else
1541 return Py_FindMethod(BufferMethods, self, name);
1542}
1543
1544 static PyObject *
1545BufferRepr(PyObject *self)
1546{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001547 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 BufferObject *this = (BufferObject *)(self);
1549
1550 if (this->buf == INVALID_BUFFER_VALUE)
1551 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001552 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 return PyString_FromString(repr);
1554 }
1555 else
1556 {
1557 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001558 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559
1560 if (name == NULL)
1561 name = "";
1562 len = strlen(name);
1563
1564 if (len > 35)
1565 name = name + (35 - len);
1566
Bram Moolenaar555b2802005-05-19 21:08:39 +00001567 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568
1569 return PyString_FromString(repr);
1570 }
1571}
1572
1573/******************/
1574
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001575 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576BufferLength(PyObject *self)
1577{
1578 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1579 if (CheckBuffer((BufferObject *)(self)))
1580 return -1; /* ??? */
1581
1582 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1583}
1584
1585 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001586BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587{
1588 return RBItem((BufferObject *)(self), n, 1,
1589 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1590}
1591
1592 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001593BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594{
1595 return RBSlice((BufferObject *)(self), lo, hi, 1,
1596 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1597}
1598
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001599 static PyInt
1600BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601{
1602 return RBAssItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001603 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 NULL);
1605}
1606
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001607 static PyInt
1608BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609{
1610 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001611 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 NULL);
1613}
1614
1615 static PyObject *
1616BufferAppend(PyObject *self, PyObject *args)
1617{
1618 return RBAppend((BufferObject *)(self), args, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001619 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 NULL);
1621}
1622
1623 static PyObject *
1624BufferMark(PyObject *self, PyObject *args)
1625{
1626 pos_T *posp;
1627 char mark;
1628 buf_T *curbuf_save;
1629
1630 if (CheckBuffer((BufferObject *)(self)))
1631 return NULL;
1632
1633 if (!PyArg_ParseTuple(args, "c", &mark))
1634 return NULL;
1635
1636 curbuf_save = curbuf;
1637 curbuf = ((BufferObject *)(self))->buf;
1638 posp = getmark(mark, FALSE);
1639 curbuf = curbuf_save;
1640
1641 if (posp == NULL)
1642 {
1643 PyErr_SetVim(_("invalid mark name"));
1644 return NULL;
1645 }
1646
1647 /* Ckeck for keyboard interrupt */
1648 if (VimErrorCheck())
1649 return NULL;
1650
1651 if (posp->lnum <= 0)
1652 {
1653 /* Or raise an error? */
1654 Py_INCREF(Py_None);
1655 return Py_None;
1656 }
1657
1658 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1659}
1660
1661 static PyObject *
1662BufferRange(PyObject *self, PyObject *args)
1663{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001664 PyInt start;
1665 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666
1667 if (CheckBuffer((BufferObject *)(self)))
1668 return NULL;
1669
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001670 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 return NULL;
1672
1673 return RangeNew(((BufferObject *)(self))->buf, start, end);
1674}
1675
1676/* Line range object - Definitions
1677 */
1678
1679static struct PyMethodDef RangeMethods[] = {
1680 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001681 {"append", RangeAppend, 1, "Append data to the Vim range" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 { NULL, NULL, 0, NULL }
1683};
1684
1685static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001686 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001688 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1689 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1690 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1691 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1692 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693};
1694
1695static PyTypeObject RangeType = {
1696 PyObject_HEAD_INIT(0)
1697 0,
1698 "range",
1699 sizeof(RangeObject),
1700 0,
1701
1702 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1703 (printfunc) 0, /* tp_print, print x */
1704 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1705 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1706 (cmpfunc) 0, /* tp_compare, x>y */
1707 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1708
1709 0, /* as number */
1710 &RangeAsSeq, /* as sequence */
1711 0, /* as mapping */
1712
1713 (hashfunc) 0, /* tp_hash, dict(x) */
1714 (ternaryfunc) 0, /* tp_call, x() */
1715 (reprfunc) 0, /* tp_str, str(x) */
1716};
1717
1718/* Line range object - Implementation
1719 */
1720
1721 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001722RangeNew(buf_T *buf, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723{
1724 BufferObject *bufr;
1725 RangeObject *self;
1726 self = PyObject_NEW(RangeObject, &RangeType);
1727 if (self == NULL)
1728 return NULL;
1729
1730 bufr = (BufferObject *)BufferNew(buf);
1731 if (bufr == NULL)
1732 {
Bram Moolenaar658ada62006-10-03 13:02:36 +00001733 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734 return NULL;
1735 }
1736 Py_INCREF(bufr);
1737
1738 self->buf = bufr;
1739 self->start = start;
1740 self->end = end;
1741
1742 return (PyObject *)(self);
1743}
1744
1745 static void
1746RangeDestructor(PyObject *self)
1747{
1748 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001749 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750}
1751
1752 static PyObject *
1753RangeGetattr(PyObject *self, char *name)
1754{
1755 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001756 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001758 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759 else
1760 return Py_FindMethod(RangeMethods, self, name);
1761}
1762
1763 static PyObject *
1764RangeRepr(PyObject *self)
1765{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001766 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 RangeObject *this = (RangeObject *)(self);
1768
1769 if (this->buf->buf == INVALID_BUFFER_VALUE)
1770 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001771 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1772 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 return PyString_FromString(repr);
1774 }
1775 else
1776 {
1777 char *name = (char *)this->buf->buf->b_fname;
1778 int len;
1779
1780 if (name == NULL)
1781 name = "";
Bram Moolenaarc236c162008-07-13 17:41:49 +00001782 len = (int)strlen(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783
1784 if (len > 45)
1785 name = name + (45 - len);
1786
Bram Moolenaar555b2802005-05-19 21:08:39 +00001787 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 len > 45 ? "..." : "", name,
1789 this->start, this->end);
1790
1791 return PyString_FromString(repr);
1792 }
1793}
1794
1795/****************/
1796
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001797 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798RangeLength(PyObject *self)
1799{
1800 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1801 if (CheckBuffer(((RangeObject *)(self))->buf))
1802 return -1; /* ??? */
1803
1804 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1805}
1806
1807 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001808RangeItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809{
1810 return RBItem(((RangeObject *)(self))->buf, n,
1811 ((RangeObject *)(self))->start,
1812 ((RangeObject *)(self))->end);
1813}
1814
1815 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001816RangeSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817{
1818 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1819 ((RangeObject *)(self))->start,
1820 ((RangeObject *)(self))->end);
1821}
1822
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001823 static PyInt
1824RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825{
1826 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1827 ((RangeObject *)(self))->start,
1828 ((RangeObject *)(self))->end,
1829 &((RangeObject *)(self))->end);
1830}
1831
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001832 static PyInt
1833RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834{
1835 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1836 ((RangeObject *)(self))->start,
1837 ((RangeObject *)(self))->end,
1838 &((RangeObject *)(self))->end);
1839}
1840
1841 static PyObject *
1842RangeAppend(PyObject *self, PyObject *args)
1843{
1844 return RBAppend(((RangeObject *)(self))->buf, args,
1845 ((RangeObject *)(self))->start,
1846 ((RangeObject *)(self))->end,
1847 &((RangeObject *)(self))->end);
1848}
1849
1850/* Buffer list object - Definitions
1851 */
1852
1853typedef struct
1854{
1855 PyObject_HEAD
1856}
1857BufListObject;
1858
1859static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001860 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001862 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1863 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1864 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1865 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1866 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867};
1868
1869static PyTypeObject BufListType = {
1870 PyObject_HEAD_INIT(0)
1871 0,
1872 "buffer list",
1873 sizeof(BufListObject),
1874 0,
1875
1876 (destructor) 0, /* tp_dealloc, refcount==0 */
1877 (printfunc) 0, /* tp_print, print x */
1878 (getattrfunc) 0, /* tp_getattr, x.attr */
1879 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1880 (cmpfunc) 0, /* tp_compare, x>y */
1881 (reprfunc) 0, /* tp_repr, `x`, print x */
1882
1883 0, /* as number */
1884 &BufListAsSeq, /* as sequence */
1885 0, /* as mapping */
1886
1887 (hashfunc) 0, /* tp_hash, dict(x) */
1888 (ternaryfunc) 0, /* tp_call, x() */
1889 (reprfunc) 0, /* tp_str, str(x) */
1890};
1891
1892/* Buffer list object - Implementation
1893 */
1894
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001895 static PyInt
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001896BufListLength(PyObject *self UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897{
1898 buf_T *b = firstbuf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001899 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900
1901 while (b)
1902 {
1903 ++n;
1904 b = b->b_next;
1905 }
1906
1907 return n;
1908}
1909
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001911BufListItem(PyObject *self UNUSED, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912{
1913 buf_T *b;
1914
1915 for (b = firstbuf; b; b = b->b_next, --n)
1916 {
1917 if (n == 0)
1918 return BufferNew(b);
1919 }
1920
1921 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1922 return NULL;
1923}
1924
1925/* Window object - Definitions
1926 */
1927
1928static struct PyMethodDef WindowMethods[] = {
1929 /* name, function, calling, documentation */
1930 { NULL, NULL, 0, NULL }
1931};
1932
1933static PyTypeObject WindowType = {
1934 PyObject_HEAD_INIT(0)
1935 0,
1936 "window",
1937 sizeof(WindowObject),
1938 0,
1939
1940 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1941 (printfunc) 0, /* tp_print, print x */
1942 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1943 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1944 (cmpfunc) 0, /* tp_compare, x>y */
1945 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1946
1947 0, /* as number */
1948 0, /* as sequence */
1949 0, /* as mapping */
1950
1951 (hashfunc) 0, /* tp_hash, dict(x) */
1952 (ternaryfunc) 0, /* tp_call, x() */
1953 (reprfunc) 0, /* tp_str, str(x) */
1954};
1955
1956/* Window object - Implementation
1957 */
1958
1959 static PyObject *
1960WindowNew(win_T *win)
1961{
1962 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001963 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 * then we can get at it in win_free() in vim. We then
1965 * need to create only ONE Python object per window - if
1966 * we try to create a second, just INCREF the existing one
1967 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001968 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 * On a win_free() we set the Python object's win_T* field
1970 * to an invalid value. We trap all uses of a window
1971 * object, and reject them if the win_T* field is invalid.
1972 */
1973
1974 WindowObject *self;
1975
Bram Moolenaare344bea2005-09-01 20:46:49 +00001976 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001978 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 Py_INCREF(self);
1980 }
1981 else
1982 {
1983 self = PyObject_NEW(WindowObject, &WindowType);
1984 if (self == NULL)
1985 return NULL;
1986 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001987 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001988 }
1989
1990 return (PyObject *)(self);
1991}
1992
1993 static void
1994WindowDestructor(PyObject *self)
1995{
1996 WindowObject *this = (WindowObject *)(self);
1997
1998 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001999 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000
Bram Moolenaar658ada62006-10-03 13:02:36 +00002001 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002}
2003
2004 static int
2005CheckWindow(WindowObject *this)
2006{
2007 if (this->win == INVALID_WINDOW_VALUE)
2008 {
2009 PyErr_SetVim(_("attempt to refer to deleted window"));
2010 return -1;
2011 }
2012
2013 return 0;
2014}
2015
2016 static PyObject *
2017WindowGetattr(PyObject *self, char *name)
2018{
2019 WindowObject *this = (WindowObject *)(self);
2020
2021 if (CheckWindow(this))
2022 return NULL;
2023
2024 if (strcmp(name, "buffer") == 0)
2025 return (PyObject *)BufferNew(this->win->w_buffer);
2026 else if (strcmp(name, "cursor") == 0)
2027 {
2028 pos_T *pos = &this->win->w_cursor;
2029
2030 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2031 }
2032 else if (strcmp(name, "height") == 0)
2033 return Py_BuildValue("l", (long)(this->win->w_height));
2034#ifdef FEAT_VERTSPLIT
2035 else if (strcmp(name, "width") == 0)
2036 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2037#endif
2038 else if (strcmp(name,"__members__") == 0)
2039 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2040 else
2041 return Py_FindMethod(WindowMethods, self, name);
2042}
2043
2044 static int
2045WindowSetattr(PyObject *self, char *name, PyObject *val)
2046{
2047 WindowObject *this = (WindowObject *)(self);
2048
2049 if (CheckWindow(this))
2050 return -1;
2051
2052 if (strcmp(name, "buffer") == 0)
2053 {
2054 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2055 return -1;
2056 }
2057 else if (strcmp(name, "cursor") == 0)
2058 {
2059 long lnum;
2060 long col;
2061
2062 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2063 return -1;
2064
2065 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2066 {
2067 PyErr_SetVim(_("cursor position outside buffer"));
2068 return -1;
2069 }
2070
2071 /* Check for keyboard interrupts */
2072 if (VimErrorCheck())
2073 return -1;
2074
2075 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2076
2077 this->win->w_cursor.lnum = lnum;
2078 this->win->w_cursor.col = col;
2079 update_screen(VALID);
2080
2081 return 0;
2082 }
2083 else if (strcmp(name, "height") == 0)
2084 {
2085 int height;
2086 win_T *savewin;
2087
2088 if (!PyArg_Parse(val, "i", &height))
2089 return -1;
2090
2091#ifdef FEAT_GUI
2092 need_mouse_correct = TRUE;
2093#endif
2094 savewin = curwin;
2095 curwin = this->win;
2096 win_setheight(height);
2097 curwin = savewin;
2098
2099 /* Check for keyboard interrupts */
2100 if (VimErrorCheck())
2101 return -1;
2102
2103 return 0;
2104 }
2105#ifdef FEAT_VERTSPLIT
2106 else if (strcmp(name, "width") == 0)
2107 {
2108 int width;
2109 win_T *savewin;
2110
2111 if (!PyArg_Parse(val, "i", &width))
2112 return -1;
2113
2114#ifdef FEAT_GUI
2115 need_mouse_correct = TRUE;
2116#endif
2117 savewin = curwin;
2118 curwin = this->win;
2119 win_setwidth(width);
2120 curwin = savewin;
2121
2122 /* Check for keyboard interrupts */
2123 if (VimErrorCheck())
2124 return -1;
2125
2126 return 0;
2127 }
2128#endif
2129 else
2130 {
2131 PyErr_SetString(PyExc_AttributeError, name);
2132 return -1;
2133 }
2134}
2135
2136 static PyObject *
2137WindowRepr(PyObject *self)
2138{
Bram Moolenaar555b2802005-05-19 21:08:39 +00002139 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 WindowObject *this = (WindowObject *)(self);
2141
2142 if (this->win == INVALID_WINDOW_VALUE)
2143 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002144 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 return PyString_FromString(repr);
2146 }
2147 else
2148 {
2149 int i = 0;
2150 win_T *w;
2151
2152 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2153 ++i;
2154
2155 if (w == NULL)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002156 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2157 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00002159 vim_snprintf(repr, 100, _("<window %d>"), i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002160
2161 return PyString_FromString(repr);
2162 }
2163}
2164
2165/* Window list object - Definitions
2166 */
2167
2168typedef struct
2169{
2170 PyObject_HEAD
2171}
2172WinListObject;
2173
2174static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002175 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002177 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2178 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2179 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2180 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2181 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182};
2183
2184static PyTypeObject WinListType = {
2185 PyObject_HEAD_INIT(0)
2186 0,
2187 "window list",
2188 sizeof(WinListObject),
2189 0,
2190
2191 (destructor) 0, /* tp_dealloc, refcount==0 */
2192 (printfunc) 0, /* tp_print, print x */
2193 (getattrfunc) 0, /* tp_getattr, x.attr */
2194 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2195 (cmpfunc) 0, /* tp_compare, x>y */
2196 (reprfunc) 0, /* tp_repr, `x`, print x */
2197
2198 0, /* as number */
2199 &WinListAsSeq, /* as sequence */
2200 0, /* as mapping */
2201
2202 (hashfunc) 0, /* tp_hash, dict(x) */
2203 (ternaryfunc) 0, /* tp_call, x() */
2204 (reprfunc) 0, /* tp_str, str(x) */
2205};
2206
2207/* Window list object - Implementation
2208 */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002209 static PyInt
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002210WinListLength(PyObject *self UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211{
2212 win_T *w = firstwin;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002213 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214
Bram Moolenaarf740b292006-02-16 22:11:02 +00002215 while (w != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216 {
2217 ++n;
2218 w = W_NEXT(w);
2219 }
2220
2221 return n;
2222}
2223
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002225WinListItem(PyObject *self UNUSED, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226{
2227 win_T *w;
2228
Bram Moolenaarf740b292006-02-16 22:11:02 +00002229 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002230 if (n == 0)
2231 return WindowNew(w);
2232
2233 PyErr_SetString(PyExc_IndexError, _("no such window"));
2234 return NULL;
2235}
2236
2237/* Current items object - Definitions
2238 */
2239
2240typedef struct
2241{
2242 PyObject_HEAD
2243}
2244CurrentObject;
2245
2246static PyTypeObject CurrentType = {
2247 PyObject_HEAD_INIT(0)
2248 0,
2249 "current data",
2250 sizeof(CurrentObject),
2251 0,
2252
2253 (destructor) 0, /* tp_dealloc, refcount==0 */
2254 (printfunc) 0, /* tp_print, print x */
2255 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2256 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2257 (cmpfunc) 0, /* tp_compare, x>y */
2258 (reprfunc) 0, /* tp_repr, `x`, print x */
2259
2260 0, /* as number */
2261 0, /* as sequence */
2262 0, /* as mapping */
2263
2264 (hashfunc) 0, /* tp_hash, dict(x) */
2265 (ternaryfunc) 0, /* tp_call, x() */
2266 (reprfunc) 0, /* tp_str, str(x) */
2267};
2268
2269/* Current items object - Implementation
2270 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002272CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273{
2274 if (strcmp(name, "buffer") == 0)
2275 return (PyObject *)BufferNew(curbuf);
2276 else if (strcmp(name, "window") == 0)
2277 return (PyObject *)WindowNew(curwin);
2278 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002279 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 else if (strcmp(name, "range") == 0)
2281 return RangeNew(curbuf, RangeStart, RangeEnd);
2282 else if (strcmp(name,"__members__") == 0)
2283 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2284 else
2285 {
2286 PyErr_SetString(PyExc_AttributeError, name);
2287 return NULL;
2288 }
2289}
2290
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002292CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293{
2294 if (strcmp(name, "line") == 0)
2295 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002296 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297 return -1;
2298
2299 return 0;
2300 }
2301 else
2302 {
2303 PyErr_SetString(PyExc_AttributeError, name);
2304 return -1;
2305 }
2306}
2307
2308/* External interface
2309 */
2310
2311 void
2312python_buffer_free(buf_T *buf)
2313{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002314 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002316 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002318 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 }
2320}
2321
2322#if defined(FEAT_WINDOWS) || defined(PROTO)
2323 void
2324python_window_free(win_T *win)
2325{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002326 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002328 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002330 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 }
2332}
2333#endif
2334
2335static BufListObject TheBufferList =
2336{
2337 PyObject_HEAD_INIT(&BufListType)
2338};
2339
2340static WinListObject TheWindowList =
2341{
2342 PyObject_HEAD_INIT(&WinListType)
2343};
2344
2345static CurrentObject TheCurrent =
2346{
2347 PyObject_HEAD_INIT(&CurrentType)
2348};
2349
2350 static int
2351PythonMod_Init(void)
2352{
2353 PyObject *mod;
2354 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00002355 /* The special value is removed from sys.path in Python_Init(). */
2356 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357
2358 /* Fixups... */
2359 BufferType.ob_type = &PyType_Type;
2360 RangeType.ob_type = &PyType_Type;
2361 WindowType.ob_type = &PyType_Type;
2362 BufListType.ob_type = &PyType_Type;
2363 WinListType.ob_type = &PyType_Type;
2364 CurrentType.ob_type = &PyType_Type;
2365
2366 /* Set sys.argv[] to avoid a crash in warn(). */
2367 PySys_SetArgv(1, argv);
2368
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002369 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 dict = PyModule_GetDict(mod);
2371
2372 VimError = Py_BuildValue("s", "vim.error");
2373
2374 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00002375 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2376 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2377 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378
2379 if (PyErr_Occurred())
2380 return -1;
2381
2382 return 0;
2383}
2384
2385/*************************************************************************
2386 * 4. Utility functions for handling the interface between Vim and Python.
2387 */
2388
2389/* Get a line from the specified buffer. The line number is
2390 * in Vim format (1-based). The line is returned as a Python
2391 * string object.
2392 */
2393 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002394GetBufferLine(buf_T *buf, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395{
2396 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2397}
2398
2399/* Get a list of lines from the specified buffer. The line numbers
2400 * are in Vim format (1-based). The range is from lo up to, but not
2401 * including, hi. The list is returned as a Python list of string objects.
2402 */
2403 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002404GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002406 PyInt i;
2407 PyInt n = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 PyObject *list = PyList_New(n);
2409
2410 if (list == NULL)
2411 return NULL;
2412
2413 for (i = 0; i < n; ++i)
2414 {
2415 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2416
2417 /* Error check - was the Python string creation OK? */
2418 if (str == NULL)
2419 {
2420 Py_DECREF(list);
2421 return NULL;
2422 }
2423
2424 /* Set the list item */
2425 if (PyList_SetItem(list, i, str))
2426 {
2427 Py_DECREF(str);
2428 Py_DECREF(list);
2429 return NULL;
2430 }
2431 }
2432
2433 /* The ownership of the Python list is passed to the caller (ie,
2434 * the caller should Py_DECREF() the object when it is finished
2435 * with it).
2436 */
2437
2438 return list;
2439}
2440
2441/*
2442 * Check if deleting lines made the cursor position invalid.
2443 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2444 * deleted).
2445 */
2446 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002447py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002448{
2449 if (curwin->w_cursor.lnum >= lo)
2450 {
2451 /* Adjust the cursor position if it's in/after the changed
2452 * lines. */
2453 if (curwin->w_cursor.lnum >= hi)
2454 {
2455 curwin->w_cursor.lnum += extra;
2456 check_cursor_col();
2457 }
2458 else if (extra < 0)
2459 {
2460 curwin->w_cursor.lnum = lo;
2461 check_cursor();
2462 }
Bram Moolenaar454ec052007-03-08 09:20:28 +00002463 else
2464 check_cursor_col();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 changed_cline_bef_curs();
2466 }
2467 invalidate_botline();
2468}
2469
2470/* Replace a line in the specified buffer. The line number is
2471 * in Vim format (1-based). The replacement line is given as
2472 * a Python string object. The object is checked for validity
2473 * and correct format. Errors are returned as a value of FAIL.
2474 * The return value is OK on success.
2475 * If OK is returned and len_change is not NULL, *len_change
2476 * is set to the change in the buffer length.
2477 */
2478 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002479SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480{
2481 /* First of all, we check the thpe of the supplied Python object.
2482 * There are three cases:
2483 * 1. NULL, or None - this is a deletion.
2484 * 2. A string - this is a replacement.
2485 * 3. Anything else - this is an error.
2486 */
2487 if (line == Py_None || line == NULL)
2488 {
2489 buf_T *savebuf = curbuf;
2490
2491 PyErr_Clear();
2492 curbuf = buf;
2493
2494 if (u_savedel((linenr_T)n, 1L) == FAIL)
2495 PyErr_SetVim(_("cannot save undo information"));
2496 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2497 PyErr_SetVim(_("cannot delete line"));
2498 else
2499 {
2500 deleted_lines_mark((linenr_T)n, 1L);
2501 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002502 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 }
2504
2505 curbuf = savebuf;
2506
2507 if (PyErr_Occurred() || VimErrorCheck())
2508 return FAIL;
2509
2510 if (len_change)
2511 *len_change = -1;
2512
2513 return OK;
2514 }
2515 else if (PyString_Check(line))
2516 {
2517 char *save = StringToLine(line);
2518 buf_T *savebuf = curbuf;
2519
2520 if (save == NULL)
2521 return FAIL;
2522
2523 /* We do not need to free "save" if ml_replace() consumes it. */
2524 PyErr_Clear();
2525 curbuf = buf;
2526
2527 if (u_savesub((linenr_T)n) == FAIL)
2528 {
2529 PyErr_SetVim(_("cannot save undo information"));
2530 vim_free(save);
2531 }
2532 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2533 {
2534 PyErr_SetVim(_("cannot replace line"));
2535 vim_free(save);
2536 }
2537 else
2538 changed_bytes((linenr_T)n, 0);
2539
2540 curbuf = savebuf;
2541
Bram Moolenaar454ec052007-03-08 09:20:28 +00002542 /* Check that the cursor is not beyond the end of the line now. */
2543 if (buf == curwin->w_buffer)
2544 check_cursor_col();
2545
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (PyErr_Occurred() || VimErrorCheck())
2547 return FAIL;
2548
2549 if (len_change)
2550 *len_change = 0;
2551
2552 return OK;
2553 }
2554 else
2555 {
2556 PyErr_BadArgument();
2557 return FAIL;
2558 }
2559}
2560
2561/* Replace a range of lines in the specified buffer. The line numbers are in
2562 * Vim format (1-based). The range is from lo up to, but not including, hi.
2563 * The replacement lines are given as a Python list of string objects. The
2564 * list is checked for validity and correct format. Errors are returned as a
2565 * value of FAIL. The return value is OK on success.
2566 * If OK is returned and len_change is not NULL, *len_change
2567 * is set to the change in the buffer length.
2568 */
2569 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002570SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571{
2572 /* First of all, we check the thpe of the supplied Python object.
2573 * There are three cases:
2574 * 1. NULL, or None - this is a deletion.
2575 * 2. A list - this is a replacement.
2576 * 3. Anything else - this is an error.
2577 */
2578 if (list == Py_None || list == NULL)
2579 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002580 PyInt i;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002581 PyInt n = (int)(hi - lo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 buf_T *savebuf = curbuf;
2583
2584 PyErr_Clear();
2585 curbuf = buf;
2586
2587 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2588 PyErr_SetVim(_("cannot save undo information"));
2589 else
2590 {
2591 for (i = 0; i < n; ++i)
2592 {
2593 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2594 {
2595 PyErr_SetVim(_("cannot delete line"));
2596 break;
2597 }
2598 }
2599 deleted_lines_mark((linenr_T)lo, (long)i);
2600
2601 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002602 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 }
2604
2605 curbuf = savebuf;
2606
2607 if (PyErr_Occurred() || VimErrorCheck())
2608 return FAIL;
2609
2610 if (len_change)
2611 *len_change = -n;
2612
2613 return OK;
2614 }
2615 else if (PyList_Check(list))
2616 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002617 PyInt i;
2618 PyInt new_len = PyList_Size(list);
2619 PyInt old_len = hi - lo;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002620 PyInt extra = 0; /* lines added to text, can be negative */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621 char **array;
2622 buf_T *savebuf;
2623
2624 if (new_len == 0) /* avoid allocating zero bytes */
2625 array = NULL;
2626 else
2627 {
2628 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2629 if (array == NULL)
2630 {
2631 PyErr_NoMemory();
2632 return FAIL;
2633 }
2634 }
2635
2636 for (i = 0; i < new_len; ++i)
2637 {
2638 PyObject *line = PyList_GetItem(list, i);
2639
2640 array[i] = StringToLine(line);
2641 if (array[i] == NULL)
2642 {
2643 while (i)
2644 vim_free(array[--i]);
2645 vim_free(array);
2646 return FAIL;
2647 }
2648 }
2649
2650 savebuf = curbuf;
2651
2652 PyErr_Clear();
2653 curbuf = buf;
2654
2655 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2656 PyErr_SetVim(_("cannot save undo information"));
2657
2658 /* If the size of the range is reducing (ie, new_len < old_len) we
2659 * need to delete some old_len. We do this at the start, by
2660 * repeatedly deleting line "lo".
2661 */
2662 if (!PyErr_Occurred())
2663 {
2664 for (i = 0; i < old_len - new_len; ++i)
2665 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2666 {
2667 PyErr_SetVim(_("cannot delete line"));
2668 break;
2669 }
2670 extra -= i;
2671 }
2672
2673 /* For as long as possible, replace the existing old_len with the
2674 * new old_len. This is a more efficient operation, as it requires
2675 * less memory allocation and freeing.
2676 */
2677 if (!PyErr_Occurred())
2678 {
2679 for (i = 0; i < old_len && i < new_len; ++i)
2680 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2681 == FAIL)
2682 {
2683 PyErr_SetVim(_("cannot replace line"));
2684 break;
2685 }
2686 }
2687 else
2688 i = 0;
2689
2690 /* Now we may need to insert the remaining new old_len. If we do, we
2691 * must free the strings as we finish with them (we can't pass the
2692 * responsibility to vim in this case).
2693 */
2694 if (!PyErr_Occurred())
2695 {
2696 while (i < new_len)
2697 {
2698 if (ml_append((linenr_T)(lo + i - 1),
2699 (char_u *)array[i], 0, FALSE) == FAIL)
2700 {
2701 PyErr_SetVim(_("cannot insert line"));
2702 break;
2703 }
2704 vim_free(array[i]);
2705 ++i;
2706 ++extra;
2707 }
2708 }
2709
2710 /* Free any left-over old_len, as a result of an error */
2711 while (i < new_len)
2712 {
2713 vim_free(array[i]);
2714 ++i;
2715 }
2716
2717 /* Free the array of old_len. All of its contents have now
2718 * been dealt with (either freed, or the responsibility passed
2719 * to vim.
2720 */
2721 vim_free(array);
2722
2723 /* Adjust marks. Invalidate any which lie in the
2724 * changed range, and move any in the remainder of the buffer.
2725 */
2726 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2727 (long)MAXLNUM, (long)extra);
2728 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2729
2730 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002731 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732
2733 curbuf = savebuf;
2734
2735 if (PyErr_Occurred() || VimErrorCheck())
2736 return FAIL;
2737
2738 if (len_change)
2739 *len_change = new_len - old_len;
2740
2741 return OK;
2742 }
2743 else
2744 {
2745 PyErr_BadArgument();
2746 return FAIL;
2747 }
2748}
2749
2750/* Insert a number of lines into the specified buffer after the specifed line.
2751 * The line number is in Vim format (1-based). The lines to be inserted are
2752 * given as a Python list of string objects or as a single string. The lines
2753 * to be added are checked for validity and correct format. Errors are
2754 * returned as a value of FAIL. The return value is OK on success.
2755 * If OK is returned and len_change is not NULL, *len_change
2756 * is set to the change in the buffer length.
2757 */
2758 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002759InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760{
2761 /* First of all, we check the type of the supplied Python object.
2762 * It must be a string or a list, or the call is in error.
2763 */
2764 if (PyString_Check(lines))
2765 {
2766 char *str = StringToLine(lines);
2767 buf_T *savebuf;
2768
2769 if (str == NULL)
2770 return FAIL;
2771
2772 savebuf = curbuf;
2773
2774 PyErr_Clear();
2775 curbuf = buf;
2776
2777 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2778 PyErr_SetVim(_("cannot save undo information"));
2779 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2780 PyErr_SetVim(_("cannot insert line"));
2781 else
2782 appended_lines_mark((linenr_T)n, 1L);
2783
2784 vim_free(str);
2785 curbuf = savebuf;
2786 update_screen(VALID);
2787
2788 if (PyErr_Occurred() || VimErrorCheck())
2789 return FAIL;
2790
2791 if (len_change)
2792 *len_change = 1;
2793
2794 return OK;
2795 }
2796 else if (PyList_Check(lines))
2797 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002798 PyInt i;
2799 PyInt size = PyList_Size(lines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 char **array;
2801 buf_T *savebuf;
2802
2803 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2804 if (array == NULL)
2805 {
2806 PyErr_NoMemory();
2807 return FAIL;
2808 }
2809
2810 for (i = 0; i < size; ++i)
2811 {
2812 PyObject *line = PyList_GetItem(lines, i);
2813 array[i] = StringToLine(line);
2814
2815 if (array[i] == NULL)
2816 {
2817 while (i)
2818 vim_free(array[--i]);
2819 vim_free(array);
2820 return FAIL;
2821 }
2822 }
2823
2824 savebuf = curbuf;
2825
2826 PyErr_Clear();
2827 curbuf = buf;
2828
2829 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2830 PyErr_SetVim(_("cannot save undo information"));
2831 else
2832 {
2833 for (i = 0; i < size; ++i)
2834 {
2835 if (ml_append((linenr_T)(n + i),
2836 (char_u *)array[i], 0, FALSE) == FAIL)
2837 {
2838 PyErr_SetVim(_("cannot insert line"));
2839
2840 /* Free the rest of the lines */
2841 while (i < size)
2842 vim_free(array[i++]);
2843
2844 break;
2845 }
2846 vim_free(array[i]);
2847 }
2848 if (i > 0)
2849 appended_lines_mark((linenr_T)n, (long)i);
2850 }
2851
2852 /* Free the array of lines. All of its contents have now
2853 * been freed.
2854 */
2855 vim_free(array);
2856
2857 curbuf = savebuf;
2858 update_screen(VALID);
2859
2860 if (PyErr_Occurred() || VimErrorCheck())
2861 return FAIL;
2862
2863 if (len_change)
2864 *len_change = size;
2865
2866 return OK;
2867 }
2868 else
2869 {
2870 PyErr_BadArgument();
2871 return FAIL;
2872 }
2873}
2874
2875/* Convert a Vim line into a Python string.
2876 * All internal newlines are replaced by null characters.
2877 *
2878 * On errors, the Python exception data is set, and NULL is returned.
2879 */
2880 static PyObject *
2881LineToString(const char *str)
2882{
2883 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002884 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 char *p;
2886
2887 /* Allocate an Python string object, with uninitialised contents. We
2888 * must do it this way, so that we can modify the string in place
2889 * later. See the Python source, Objects/stringobject.c for details.
2890 */
2891 result = PyString_FromStringAndSize(NULL, len);
2892 if (result == NULL)
2893 return NULL;
2894
2895 p = PyString_AsString(result);
2896
2897 while (*str)
2898 {
2899 if (*str == '\n')
2900 *p = '\0';
2901 else
2902 *p = *str;
2903
2904 ++p;
2905 ++str;
2906 }
2907
2908 return result;
2909}
2910
2911/* Convert a Python string into a Vim line.
2912 *
2913 * The result is in allocated memory. All internal nulls are replaced by
2914 * newline characters. It is an error for the string to contain newline
2915 * characters.
2916 *
2917 * On errors, the Python exception data is set, and NULL is returned.
2918 */
2919 static char *
2920StringToLine(PyObject *obj)
2921{
2922 const char *str;
2923 char *save;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002924 PyInt len;
2925 PyInt i;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002926 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927
2928 if (obj == NULL || !PyString_Check(obj))
2929 {
2930 PyErr_BadArgument();
2931 return NULL;
2932 }
2933
2934 str = PyString_AsString(obj);
2935 len = PyString_Size(obj);
2936
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002937 /*
2938 * Error checking: String must not contain newlines, as we
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 * are replacing a single line, and we must replace it with
2940 * a single line.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002941 * A trailing newline is removed, so that append(f.readlines()) works.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002943 p = memchr(str, '\n', len);
2944 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002946 if (p == str + len - 1)
2947 --len;
2948 else
2949 {
2950 PyErr_SetVim(_("string cannot contain newlines"));
2951 return NULL;
2952 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 }
2954
2955 /* Create a copy of the string, with internal nulls replaced by
2956 * newline characters, as is the vim convention.
2957 */
2958 save = (char *)alloc((unsigned)(len+1));
2959 if (save == NULL)
2960 {
2961 PyErr_NoMemory();
2962 return NULL;
2963 }
2964
2965 for (i = 0; i < len; ++i)
2966 {
2967 if (str[i] == '\0')
2968 save[i] = '\n';
2969 else
2970 save[i] = str[i];
2971 }
2972
2973 save[i] = '\0';
2974
2975 return save;
2976}
2977
2978/* Check to see whether a Vim error has been reported, or a keyboard
2979 * interrupt has been detected.
2980 */
2981 static int
2982VimErrorCheck(void)
2983{
2984 if (got_int)
2985 {
2986 PyErr_SetNone(PyExc_KeyboardInterrupt);
2987 return 1;
2988 }
2989 else if (did_emsg && !PyErr_Occurred())
2990 {
2991 PyErr_SetNone(VimError);
2992 return 1;
2993 }
2994
2995 return 0;
2996}
2997
2998
2999/* Don't generate a prototype for the next function, it generates an error on
3000 * newer Python versions. */
3001#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3002
3003 char *
3004Py_GetProgramName(void)
3005{
3006 return "vim";
3007}
3008#endif /* Python 1.4 */