blob: 09510d538f80005ef726b65a13151c18ffbc1778 [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. */
53# define PyObject int
54# define PyThreadState int
55# define PyTypeObject int
56struct PyMethodDef { int a; };
57# define PySequenceMethods int
58#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
67#else
68# define PyInt int
69# define PyInquiry inquiry
70# define PyIntArgFunc intargfunc
71# define PyIntIntArgFunc intintargfunc
72# define PyIntObjArgProc intobjargproc
73# define PyIntIntObjArgProc intintobjargproc
74#endif
75
Bram Moolenaar071d4272004-06-13 20:20:40 +000076/* Parser flags */
77#define single_input 256
78#define file_input 257
79#define eval_input 258
80
81#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
82 /* Python 2.3: can invoke ":python" recursively. */
83# define PY_CAN_RECURSE
84#endif
85
86#if defined(DYNAMIC_PYTHON) || defined(PROTO)
87# ifndef DYNAMIC_PYTHON
88# define HINSTANCE int /* for generating prototypes */
89# endif
90
91/*
92 * Wrapper defines
93 */
94# define PyArg_Parse dll_PyArg_Parse
95# define PyArg_ParseTuple dll_PyArg_ParseTuple
96# define PyDict_SetItemString dll_PyDict_SetItemString
97# define PyErr_BadArgument dll_PyErr_BadArgument
98# define PyErr_Clear dll_PyErr_Clear
99# define PyErr_NoMemory dll_PyErr_NoMemory
100# define PyErr_Occurred dll_PyErr_Occurred
101# define PyErr_SetNone dll_PyErr_SetNone
102# define PyErr_SetString dll_PyErr_SetString
103# define PyEval_InitThreads dll_PyEval_InitThreads
104# define PyEval_RestoreThread dll_PyEval_RestoreThread
105# define PyEval_SaveThread dll_PyEval_SaveThread
106# ifdef PY_CAN_RECURSE
107# define PyGILState_Ensure dll_PyGILState_Ensure
108# define PyGILState_Release dll_PyGILState_Release
109# endif
110# define PyInt_AsLong dll_PyInt_AsLong
111# define PyInt_FromLong dll_PyInt_FromLong
112# define PyInt_Type (*dll_PyInt_Type)
113# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000114# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115# define PyList_New dll_PyList_New
116# define PyList_SetItem dll_PyList_SetItem
117# define PyList_Size dll_PyList_Size
118# define PyList_Type (*dll_PyList_Type)
119# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000120# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121# define PyDict_GetItemString dll_PyDict_GetItemString
122# define PyModule_GetDict dll_PyModule_GetDict
123# define PyRun_SimpleString dll_PyRun_SimpleString
124# define PyString_AsString dll_PyString_AsString
125# define PyString_FromString dll_PyString_FromString
126# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
127# define PyString_Size dll_PyString_Size
128# define PyString_Type (*dll_PyString_Type)
129# define PySys_SetObject dll_PySys_SetObject
130# define PySys_SetArgv dll_PySys_SetArgv
131# define PyType_Type (*dll_PyType_Type)
132# define Py_BuildValue dll_Py_BuildValue
133# define Py_FindMethod dll_Py_FindMethod
134# define Py_InitModule4 dll_Py_InitModule4
135# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000136# define Py_Finalize dll_Py_Finalize
137# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138# define _PyObject_New dll__PyObject_New
139# define _Py_NoneStruct (*dll__Py_NoneStruct)
140# define PyObject_Init dll__PyObject_Init
141# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
142# define PyType_IsSubtype dll_PyType_IsSubtype
143# endif
144# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
145# define PyObject_Malloc dll_PyObject_Malloc
146# define PyObject_Free dll_PyObject_Free
147# endif
148
149/*
150 * Pointers for dynamic link
151 */
152static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
153static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
154static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
155static int(*dll_PyErr_BadArgument)(void);
156static void(*dll_PyErr_Clear)(void);
157static PyObject*(*dll_PyErr_NoMemory)(void);
158static PyObject*(*dll_PyErr_Occurred)(void);
159static void(*dll_PyErr_SetNone)(PyObject *);
160static void(*dll_PyErr_SetString)(PyObject *, const char *);
161static void(*dll_PyEval_InitThreads)(void);
162static void(*dll_PyEval_RestoreThread)(PyThreadState *);
163static PyThreadState*(*dll_PyEval_SaveThread)(void);
164# ifdef PY_CAN_RECURSE
165static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
166static void (*dll_PyGILState_Release)(PyGILState_STATE);
167#endif
168static long(*dll_PyInt_AsLong)(PyObject *);
169static PyObject*(*dll_PyInt_FromLong)(long);
170static PyTypeObject* dll_PyInt_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000171static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000172static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000173static PyObject*(*dll_PyList_New)(PyInt size);
174static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
175static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static PyTypeObject* dll_PyList_Type;
177static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000178static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
180static PyObject*(*dll_PyModule_GetDict)(PyObject *);
181static int(*dll_PyRun_SimpleString)(char *);
182static char*(*dll_PyString_AsString)(PyObject *);
183static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000184static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
185static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000186static PyTypeObject* dll_PyString_Type;
187static int(*dll_PySys_SetObject)(char *, PyObject *);
188static int(*dll_PySys_SetArgv)(int, char **);
189static PyTypeObject* dll_PyType_Type;
190static PyObject*(*dll_Py_BuildValue)(char *, ...);
191static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
192static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
193static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000194static void(*dll_Py_Finalize)(void);
195static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000196static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
197static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
198static PyObject* dll__Py_NoneStruct;
199# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
200static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
201# endif
202# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
203static void* (*dll_PyObject_Malloc)(size_t);
204static void (*dll_PyObject_Free)(void*);
205# endif
206
207static HINSTANCE hinstPython = 0; /* Instance of python.dll */
208
209/* Imported exception objects */
210static PyObject *imp_PyExc_AttributeError;
211static PyObject *imp_PyExc_IndexError;
212static PyObject *imp_PyExc_KeyboardInterrupt;
213static PyObject *imp_PyExc_TypeError;
214static PyObject *imp_PyExc_ValueError;
215
216# define PyExc_AttributeError imp_PyExc_AttributeError
217# define PyExc_IndexError imp_PyExc_IndexError
218# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
219# define PyExc_TypeError imp_PyExc_TypeError
220# define PyExc_ValueError imp_PyExc_ValueError
221
222/*
223 * Table of name to function pointer of python.
224 */
225# define PYTHON_PROC FARPROC
226static struct
227{
228 char *name;
229 PYTHON_PROC *ptr;
230} python_funcname_table[] =
231{
232 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
233 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
234 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
235 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
236 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
237 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
238 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
239 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
240 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
241 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
242 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
243 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
244# ifdef PY_CAN_RECURSE
245 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
246 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
247# endif
248 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
249 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
250 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
251 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000252 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
254 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
255 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
256 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
257 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
258 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000259 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
261 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
262 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
263 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
264 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
265 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
266 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
267 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
268 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
269 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
270 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
271 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
272 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
273 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000274 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
275 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
277 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
278 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
279# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
280 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
281# endif
282# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
283 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
284 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
285# endif
286 {"", NULL},
287};
288
289/*
290 * Free python.dll
291 */
292 static void
293end_dynamic_python(void)
294{
295 if (hinstPython)
296 {
297 FreeLibrary(hinstPython);
298 hinstPython = 0;
299 }
300}
301
302/*
303 * Load library and get all pointers.
304 * Parameter 'libname' provides name of DLL.
305 * Return OK or FAIL.
306 */
307 static int
308python_runtime_link_init(char *libname, int verbose)
309{
310 int i;
311
312 if (hinstPython)
313 return OK;
314 hinstPython = LoadLibrary(libname);
315 if (!hinstPython)
316 {
317 if (verbose)
318 EMSG2(_(e_loadlib), libname);
319 return FAIL;
320 }
321
322 for (i = 0; python_funcname_table[i].ptr; ++i)
323 {
324 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
325 python_funcname_table[i].name)) == NULL)
326 {
327 FreeLibrary(hinstPython);
328 hinstPython = 0;
329 if (verbose)
330 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
331 return FAIL;
332 }
333 }
334 return OK;
335}
336
337/*
338 * If python is enabled (there is installed python on Windows system) return
339 * TRUE, else FALSE.
340 */
341 int
342python_enabled(verbose)
343 int verbose;
344{
345 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
346}
347
348/* Load the standard Python exceptions - don't import the symbols from the
349 * DLL, as this can cause errors (importing data symbols is not reliable).
350 */
351static void get_exceptions __ARGS((void));
352
353 static void
354get_exceptions()
355{
356 PyObject *exmod = PyImport_ImportModule("exceptions");
357 PyObject *exdict = PyModule_GetDict(exmod);
358 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
359 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
360 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
361 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
362 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
363 Py_XINCREF(imp_PyExc_AttributeError);
364 Py_XINCREF(imp_PyExc_IndexError);
365 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
366 Py_XINCREF(imp_PyExc_TypeError);
367 Py_XINCREF(imp_PyExc_ValueError);
368 Py_XDECREF(exmod);
369}
370#endif /* DYNAMIC_PYTHON */
371
372/******************************************************
373 * Internal function prototypes.
374 */
375
376static void DoPythonCommand(exarg_T *, const char *);
377static int RangeStart;
378static int RangeEnd;
379
380static void PythonIO_Flush(void);
381static int PythonIO_Init(void);
382static int PythonMod_Init(void);
383
384/* Utility functions for the vim/python interface
385 * ----------------------------------------------
386 */
387static PyObject *GetBufferLine(buf_T *, int);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000388static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389
390static int SetBufferLine(buf_T *, int, PyObject *, int *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000391static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, int *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392static int InsertBufferLines(buf_T *, int, PyObject *, int *);
393
394static PyObject *LineToString(const char *);
395static char *StringToLine(PyObject *);
396
397static int VimErrorCheck(void);
398
399#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
400
401/******************************************************
402 * 1. Python interpreter main program.
403 */
404
405static int initialised = 0;
406
407#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
408typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000409#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000411#ifdef PY_CAN_RECURSE
412static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
413#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000414static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000415#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416
417/*
418 * Suspend a thread of the Python interpreter, other threads are allowed to
419 * run.
420 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000421 static void
422Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000423{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000424#ifdef PY_CAN_RECURSE
425 PyGILState_Release(pygilstate);
426#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000428#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429}
430
431/*
432 * Restore a thread of the Python interpreter, waits for other threads to
433 * block.
434 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000435 static void
436Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000438#ifdef PY_CAN_RECURSE
439 pygilstate = PyGILState_Ensure();
440#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 PyEval_RestoreThread(saved_python_thread);
442 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000444}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445
446/*
447 * obtain a lock on the Vim data structures
448 */
449static void Python_Lock_Vim(void)
450{
451}
452
453/*
454 * release a lock on the Vim data structures
455 */
456static void Python_Release_Vim(void)
457{
458}
459
460 void
461python_end()
462{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000463 static int recurse = 0;
464
465 /* If a crash occurs while doing this, don't try again. */
466 if (recurse != 0)
467 return;
468
469 ++recurse;
470
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000472 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000473 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000474 Python_RestoreThread(); /* enter python */
475 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000478#else
479 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000480 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000481 Python_RestoreThread(); /* enter python */
482 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000483 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000485
486 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487}
488
489 static int
490Python_Init(void)
491{
492 if (!initialised)
493 {
494#ifdef DYNAMIC_PYTHON
495 if (!python_enabled(TRUE))
496 {
497 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
498 goto fail;
499 }
500#endif
501
502#if !defined(MACOS) || defined(MACOS_X_UNIX)
503 Py_Initialize();
504#else
505 PyMac_Initialize();
506#endif
507 /* initialise threads */
508 PyEval_InitThreads();
509
510#ifdef DYNAMIC_PYTHON
511 get_exceptions();
512#endif
513
514 if (PythonIO_Init())
515 goto fail;
516
517 if (PythonMod_Init())
518 goto fail;
519
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000520 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522
523 initialised = 1;
524 }
525
526 return 0;
527
528fail:
529 /* We call PythonIO_Flush() here to print any Python errors.
530 * This is OK, as it is possible to call this function even
531 * if PythonIO_Init() has not completed successfully (it will
532 * not do anything in this case).
533 */
534 PythonIO_Flush();
535 return -1;
536}
537
538/*
539 * External interface
540 */
541 static void
542DoPythonCommand(exarg_T *eap, const char *cmd)
543{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000544#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545 static int recursive = 0;
546#endif
547#if defined(MACOS) && !defined(MACOS_X_UNIX)
548 GrafPtr oldPort;
549#endif
550#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
551 char *saved_locale;
552#endif
553
554#ifndef PY_CAN_RECURSE
555 if (recursive)
556 {
557 EMSG(_("E659: Cannot invoke Python recursively"));
558 return;
559 }
560 ++recursive;
561#endif
562
563#if defined(MACOS) && !defined(MACOS_X_UNIX)
564 GetPort(&oldPort);
565 /* Check if the Python library is available */
566 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
567 goto theend;
568#endif
569 if (Python_Init())
570 goto theend;
571
572 RangeStart = eap->line1;
573 RangeEnd = eap->line2;
574 Python_Release_Vim(); /* leave vim */
575
576#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
577 /* Python only works properly when the LC_NUMERIC locale is "C". */
578 saved_locale = setlocale(LC_NUMERIC, NULL);
579 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
580 saved_locale = NULL;
581 else
582 {
583 /* Need to make a copy, value may change when setting new locale. */
584 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
585 (void)setlocale(LC_NUMERIC, "C");
586 }
587#endif
588
Bram Moolenaar071d4272004-06-13 20:20:40 +0000589 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590
591 PyRun_SimpleString((char *)(cmd));
592
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594
595#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
596 if (saved_locale != NULL)
597 {
598 (void)setlocale(LC_NUMERIC, saved_locale);
599 vim_free(saved_locale);
600 }
601#endif
602
603 Python_Lock_Vim(); /* enter vim */
604 PythonIO_Flush();
605#if defined(MACOS) && !defined(MACOS_X_UNIX)
606 SetPort(oldPort);
607#endif
608
609theend:
610#ifndef PY_CAN_RECURSE
611 --recursive;
612#endif
613 return; /* keeps lint happy */
614}
615
616/*
617 * ":python"
618 */
619 void
620ex_python(exarg_T *eap)
621{
622 char_u *script;
623
624 script = script_get(eap, eap->arg);
625 if (!eap->skip)
626 {
627 if (script == NULL)
628 DoPythonCommand(eap, (char *)eap->arg);
629 else
630 DoPythonCommand(eap, (char *)script);
631 }
632 vim_free(script);
633}
634
635#define BUFFER_SIZE 1024
636
637/*
638 * ":pyfile"
639 */
640 void
641ex_pyfile(exarg_T *eap)
642{
643 static char buffer[BUFFER_SIZE];
644 const char *file = (char *)eap->arg;
645 char *p;
646
647 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
648 * stdio file pointer, but Vim and the Python DLL are compiled with
649 * different options under Windows, meaning that stdio pointers aren't
650 * compatible between the two. Yuk.
651 *
652 * Put the string "execfile('file')" into buffer. But, we need to
653 * escape any backslashes or single quotes in the file name, so that
654 * Python won't mangle the file name.
655 */
656 strcpy(buffer, "execfile('");
657 p = buffer + 10; /* size of "execfile('" */
658
659 while (*file && p < buffer + (BUFFER_SIZE - 3))
660 {
661 if (*file == '\\' || *file == '\'')
662 *p++ = '\\';
663 *p++ = *file++;
664 }
665
666 /* If we didn't finish the file name, we hit a buffer overflow */
667 if (*file != '\0')
668 return;
669
670 /* Put in the terminating "')" and a null */
671 *p++ = '\'';
672 *p++ = ')';
673 *p++ = '\0';
674
675 /* Execute the file */
676 DoPythonCommand(eap, buffer);
677}
678
679/******************************************************
680 * 2. Python output stream: writes output via [e]msg().
681 */
682
683/* Implementation functions
684 */
685
686static PyObject *OutputGetattr(PyObject *, char *);
687static int OutputSetattr(PyObject *, char *, PyObject *);
688
689static PyObject *OutputWrite(PyObject *, PyObject *);
690static PyObject *OutputWritelines(PyObject *, PyObject *);
691
692typedef void (*writefn)(char_u *);
693static void writer(writefn fn, char_u *str, int n);
694
695/* Output object definition
696 */
697
698typedef struct
699{
700 PyObject_HEAD
701 long softspace;
702 long error;
703} OutputObject;
704
705static struct PyMethodDef OutputMethods[] = {
706 /* name, function, calling, documentation */
707 {"write", OutputWrite, 1, "" },
708 {"writelines", OutputWritelines, 1, "" },
709 { NULL, NULL, 0, NULL }
710};
711
712static PyTypeObject OutputType = {
713 PyObject_HEAD_INIT(0)
714 0,
715 "message",
716 sizeof(OutputObject),
717 0,
718
719 (destructor) 0,
720 (printfunc) 0,
721 (getattrfunc) OutputGetattr,
722 (setattrfunc) OutputSetattr,
723 (cmpfunc) 0,
724 (reprfunc) 0,
725
726 0, /* as number */
727 0, /* as sequence */
728 0, /* as mapping */
729
730 (hashfunc) 0,
731 (ternaryfunc) 0,
732 (reprfunc) 0
733};
734
735/*************/
736
737 static PyObject *
738OutputGetattr(PyObject *self, char *name)
739{
740 if (strcmp(name, "softspace") == 0)
741 return PyInt_FromLong(((OutputObject *)(self))->softspace);
742
743 return Py_FindMethod(OutputMethods, self, name);
744}
745
746 static int
747OutputSetattr(PyObject *self, char *name, PyObject *val)
748{
749 if (val == NULL) {
750 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
751 return -1;
752 }
753
754 if (strcmp(name, "softspace") == 0)
755 {
756 if (!PyInt_Check(val)) {
757 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
758 return -1;
759 }
760
761 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
762 return 0;
763 }
764
765 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
766 return -1;
767}
768
769/*************/
770
771 static PyObject *
772OutputWrite(PyObject *self, PyObject *args)
773{
774 int len;
775 char *str;
776 int error = ((OutputObject *)(self))->error;
777
778 if (!PyArg_ParseTuple(args, "s#", &str, &len))
779 return NULL;
780
781 Py_BEGIN_ALLOW_THREADS
782 Python_Lock_Vim();
783 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
784 Python_Release_Vim();
785 Py_END_ALLOW_THREADS
786
787 Py_INCREF(Py_None);
788 return Py_None;
789}
790
791 static PyObject *
792OutputWritelines(PyObject *self, PyObject *args)
793{
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000794 PyInt n;
795 PyInt i;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796 PyObject *list;
797 int error = ((OutputObject *)(self))->error;
798
799 if (!PyArg_ParseTuple(args, "O", &list))
800 return NULL;
801 Py_INCREF(list);
802
803 if (!PyList_Check(list)) {
804 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
805 Py_DECREF(list);
806 return NULL;
807 }
808
809 n = PyList_Size(list);
810
811 for (i = 0; i < n; ++i)
812 {
813 PyObject *line = PyList_GetItem(list, i);
814 char *str;
815 int len;
816
817 if (!PyArg_Parse(line, "s#", &str, &len)) {
818 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
819 Py_DECREF(list);
820 return NULL;
821 }
822
823 Py_BEGIN_ALLOW_THREADS
824 Python_Lock_Vim();
825 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
826 Python_Release_Vim();
827 Py_END_ALLOW_THREADS
828 }
829
830 Py_DECREF(list);
831 Py_INCREF(Py_None);
832 return Py_None;
833}
834
835/* Output buffer management
836 */
837
838static char_u *buffer = NULL;
839static int buffer_len = 0;
840static int buffer_size = 0;
841
842static writefn old_fn = NULL;
843
844 static void
845buffer_ensure(int n)
846{
847 int new_size;
848 char_u *new_buffer;
849
850 if (n < buffer_size)
851 return;
852
853 new_size = buffer_size;
854 while (new_size < n)
855 new_size += 80;
856
857 if (new_size != buffer_size)
858 {
859 new_buffer = alloc((unsigned)new_size);
860 if (new_buffer == NULL)
861 return;
862
863 if (buffer)
864 {
865 memcpy(new_buffer, buffer, buffer_len);
866 vim_free(buffer);
867 }
868
869 buffer = new_buffer;
870 buffer_size = new_size;
871 }
872}
873
874 static void
875PythonIO_Flush(void)
876{
877 if (old_fn && buffer_len)
878 {
879 buffer[buffer_len] = 0;
880 old_fn(buffer);
881 }
882
883 buffer_len = 0;
884}
885
886 static void
887writer(writefn fn, char_u *str, int n)
888{
889 char_u *ptr;
890
891 if (fn != old_fn && old_fn != NULL)
892 PythonIO_Flush();
893
894 old_fn = fn;
895
896 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
897 {
898 int len = ptr - str;
899
900 buffer_ensure(buffer_len + len + 1);
901
902 memcpy(buffer + buffer_len, str, len);
903 buffer_len += len;
904 buffer[buffer_len] = 0;
905 fn(buffer);
906 str = ptr + 1;
907 n -= len + 1;
908 buffer_len = 0;
909 }
910
911 /* Put the remaining text into the buffer for later printing */
912 buffer_ensure(buffer_len + n + 1);
913 memcpy(buffer + buffer_len, str, n);
914 buffer_len += n;
915}
916
917/***************/
918
919static OutputObject Output =
920{
921 PyObject_HEAD_INIT(&OutputType)
922 0,
923 0
924};
925
926static OutputObject Error =
927{
928 PyObject_HEAD_INIT(&OutputType)
929 0,
930 1
931};
932
933 static int
934PythonIO_Init(void)
935{
936 /* Fixups... */
937 OutputType.ob_type = &PyType_Type;
938
Bram Moolenaar7df2d662005-01-25 22:18:08 +0000939 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
940 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941
942 if (PyErr_Occurred())
943 {
944 EMSG(_("E264: Python: Error initialising I/O objects"));
945 return -1;
946 }
947
948 return 0;
949}
950
951/******************************************************
952 * 3. Implementation of the Vim module for Python
953 */
954
955/* Vim module - Implementation functions
956 * -------------------------------------
957 */
958
959static PyObject *VimError;
960
961static PyObject *VimCommand(PyObject *, PyObject *);
962static PyObject *VimEval(PyObject *, PyObject *);
963
964/* Window type - Implementation functions
965 * --------------------------------------
966 */
967
968typedef struct
969{
970 PyObject_HEAD
971 win_T *win;
972}
973WindowObject;
974
975#define INVALID_WINDOW_VALUE ((win_T *)(-1))
976
977#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
978
979static PyObject *WindowNew(win_T *);
980
981static void WindowDestructor(PyObject *);
982static PyObject *WindowGetattr(PyObject *, char *);
983static int WindowSetattr(PyObject *, char *, PyObject *);
984static PyObject *WindowRepr(PyObject *);
985
986/* Buffer type - Implementation functions
987 * --------------------------------------
988 */
989
990typedef struct
991{
992 PyObject_HEAD
993 buf_T *buf;
994}
995BufferObject;
996
997#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
998
999#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1000
1001static PyObject *BufferNew (buf_T *);
1002
1003static void BufferDestructor(PyObject *);
1004static PyObject *BufferGetattr(PyObject *, char *);
1005static PyObject *BufferRepr(PyObject *);
1006
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001007static PyInt BufferLength(PyObject *);
1008static PyObject *BufferItem(PyObject *, PyInt);
1009static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1010static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1011static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012
1013static PyObject *BufferAppend(PyObject *, PyObject *);
1014static PyObject *BufferMark(PyObject *, PyObject *);
1015static PyObject *BufferRange(PyObject *, PyObject *);
1016
1017/* Line range type - Implementation functions
1018 * --------------------------------------
1019 */
1020
1021typedef struct
1022{
1023 PyObject_HEAD
1024 BufferObject *buf;
1025 int start;
1026 int end;
1027}
1028RangeObject;
1029
1030#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1031
1032static PyObject *RangeNew(buf_T *, int, int);
1033
1034static void RangeDestructor(PyObject *);
1035static PyObject *RangeGetattr(PyObject *, char *);
1036static PyObject *RangeRepr(PyObject *);
1037
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001038static PyInt RangeLength(PyObject *);
1039static PyObject *RangeItem(PyObject *, PyInt);
1040static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1041static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1042static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043
1044static PyObject *RangeAppend(PyObject *, PyObject *);
1045
1046/* Window list type - Implementation functions
1047 * -------------------------------------------
1048 */
1049
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001050static PyInt WinListLength(PyObject *);
1051static PyObject *WinListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052
1053/* Buffer list type - Implementation functions
1054 * -------------------------------------------
1055 */
1056
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001057static PyInt BufListLength(PyObject *);
1058static PyObject *BufListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059
1060/* Current objects type - Implementation functions
1061 * -----------------------------------------------
1062 */
1063
1064static PyObject *CurrentGetattr(PyObject *, char *);
1065static int CurrentSetattr(PyObject *, char *, PyObject *);
1066
1067/* Vim module - Definitions
1068 */
1069
1070static struct PyMethodDef VimMethods[] = {
1071 /* name, function, calling, documentation */
1072 {"command", VimCommand, 1, "" },
1073 {"eval", VimEval, 1, "" },
1074 { NULL, NULL, 0, NULL }
1075};
1076
1077/* Vim module - Implementation
1078 */
1079/*ARGSUSED*/
1080 static PyObject *
1081VimCommand(PyObject *self, PyObject *args)
1082{
1083 char *cmd;
1084 PyObject *result;
1085
1086 if (!PyArg_ParseTuple(args, "s", &cmd))
1087 return NULL;
1088
1089 PyErr_Clear();
1090
1091 Py_BEGIN_ALLOW_THREADS
1092 Python_Lock_Vim();
1093
1094 do_cmdline_cmd((char_u *)cmd);
1095 update_screen(VALID);
1096
1097 Python_Release_Vim();
1098 Py_END_ALLOW_THREADS
1099
1100 if (VimErrorCheck())
1101 result = NULL;
1102 else
1103 result = Py_None;
1104
1105 Py_XINCREF(result);
1106 return result;
1107}
1108
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001109/*
1110 * Function to translate a typval_T into a PyObject; this will recursively
1111 * translate lists/dictionaries into their Python equivalents.
1112 *
1113 * The depth parameter is too avoid infinite recursion, set it to 1 when
1114 * you call VimToPython.
1115 */
1116 static PyObject *
1117VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1118{
1119 PyObject *result;
1120 PyObject *newObj;
1121 char ptrBuf[NUMBUFLEN];
1122
1123 /* Avoid infinite recursion */
1124 if (depth > 100)
1125 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001126 Py_INCREF(Py_None);
1127 result = Py_None;
1128 return result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001129 }
1130
1131 /* Check if we run into a recursive loop. The item must be in lookupDict
1132 * then and we can use it again. */
1133 sprintf(ptrBuf, "%ld", (long)our_tv);
1134 result = PyDict_GetItemString(lookupDict, ptrBuf);
1135 if (result != NULL)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001136 Py_INCREF(result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001137 else if (our_tv->v_type == VAR_STRING)
1138 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001139 result = Py_BuildValue("s", our_tv->vval.v_string);
1140 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001141 }
1142 else if (our_tv->v_type == VAR_NUMBER)
1143 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001144 char buf[NUMBUFLEN];
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001145
1146 /* For backwards compatibility numbers are stored as strings. */
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001147 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1148 result = Py_BuildValue("s", buf);
1149 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001150 }
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001151#ifdef FEAT_FLOAT
1152 else if (our_tv->v_type == VAR_FLOAT)
1153 {
1154 char buf[NUMBUFLEN];
1155
1156 sprintf(buf, "%f", our_tv->vval.v_float);
1157 result = Py_BuildValue("s", buf);
1158 PyDict_SetItemString(lookupDict, ptrBuf, result);
1159 }
1160#endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001161 else if (our_tv->v_type == VAR_LIST)
1162 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001163 list_T *list = our_tv->vval.v_list;
1164 listitem_T *curr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001165
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001166 result = PyList_New(0);
1167 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001168
1169 if (list != NULL)
1170 {
1171 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1172 {
1173 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1174 PyList_Append(result, newObj);
1175 Py_DECREF(newObj);
1176 }
1177 }
1178 }
1179 else if (our_tv->v_type == VAR_DICT)
1180 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001181 result = PyDict_New();
1182 PyDict_SetItemString(lookupDict, ptrBuf, result);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001183
1184 if (our_tv->vval.v_dict != NULL)
1185 {
1186 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1187 int todo = ht->ht_used;
1188 hashitem_T *hi;
1189 dictitem_T *di;
1190
1191 for (hi = ht->ht_array; todo > 0; ++hi)
1192 {
1193 if (!HASHITEM_EMPTY(hi))
1194 {
1195 --todo;
1196
1197 di = dict_lookup(hi);
1198 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1199 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1200 Py_DECREF(newObj);
1201 }
1202 }
1203 }
1204 }
1205 else
1206 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001207 Py_INCREF(Py_None);
1208 result = Py_None;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001209 }
1210
1211 return result;
1212}
1213
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214/*ARGSUSED*/
1215 static PyObject *
1216VimEval(PyObject *self, PyObject *args)
1217{
1218#ifdef FEAT_EVAL
1219 char *expr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001220 typval_T *our_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221 PyObject *result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001222 PyObject *lookup_dict;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223
1224 if (!PyArg_ParseTuple(args, "s", &expr))
1225 return NULL;
1226
1227 Py_BEGIN_ALLOW_THREADS
1228 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001229 our_tv = eval_expr((char_u *)expr, NULL);
1230
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 Python_Release_Vim();
1232 Py_END_ALLOW_THREADS
1233
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001234 if (our_tv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001235 {
1236 PyErr_SetVim(_("invalid expression"));
1237 return NULL;
1238 }
1239
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001240 /* Convert the Vim type into a Python type. Create a dictionary that's
1241 * used to check for recursive loops. */
1242 lookup_dict = PyDict_New();
1243 result = VimToPython(our_tv, 1, lookup_dict);
1244 Py_DECREF(lookup_dict);
1245
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246
1247 Py_BEGIN_ALLOW_THREADS
1248 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001249 free_tv(our_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250 Python_Release_Vim();
1251 Py_END_ALLOW_THREADS
1252
1253 return result;
1254#else
1255 PyErr_SetVim(_("expressions disabled at compile time"));
1256 return NULL;
1257#endif
1258}
1259
1260/* Common routines for buffers and line ranges
1261 * -------------------------------------------
1262 */
1263 static int
1264CheckBuffer(BufferObject *this)
1265{
1266 if (this->buf == INVALID_BUFFER_VALUE)
1267 {
1268 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1269 return -1;
1270 }
1271
1272 return 0;
1273}
1274
1275 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001276RBItem(BufferObject *self, PyInt n, int start, int end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277{
1278 if (CheckBuffer(self))
1279 return NULL;
1280
1281 if (n < 0 || n > end - start)
1282 {
1283 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1284 return NULL;
1285 }
1286
1287 return GetBufferLine(self->buf, n+start);
1288}
1289
1290 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001291RBSlice(BufferObject *self, PyInt lo, PyInt hi, int start, int end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001293 PyInt size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294
1295 if (CheckBuffer(self))
1296 return NULL;
1297
1298 size = end - start + 1;
1299
1300 if (lo < 0)
1301 lo = 0;
1302 else if (lo > size)
1303 lo = size;
1304 if (hi < 0)
1305 hi = 0;
1306 if (hi < lo)
1307 hi = lo;
1308 else if (hi > size)
1309 hi = size;
1310
1311 return GetBufferLineList(self->buf, lo+start, hi+start);
1312}
1313
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001314 static PyInt
1315RBAssItem(BufferObject *self, PyInt n, PyObject *val, int start, int end, int *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316{
1317 int len_change;
1318
1319 if (CheckBuffer(self))
1320 return -1;
1321
1322 if (n < 0 || n > end - start)
1323 {
1324 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1325 return -1;
1326 }
1327
1328 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1329 return -1;
1330
1331 if (new_end)
1332 *new_end = end + len_change;
1333
1334 return 0;
1335}
1336
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001337 static PyInt
1338RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, int start, int end, int *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001339{
1340 int size;
1341 int len_change;
1342
1343 /* Self must be a valid buffer */
1344 if (CheckBuffer(self))
1345 return -1;
1346
1347 /* Sort out the slice range */
1348 size = end - start + 1;
1349
1350 if (lo < 0)
1351 lo = 0;
1352 else if (lo > size)
1353 lo = size;
1354 if (hi < 0)
1355 hi = 0;
1356 if (hi < lo)
1357 hi = lo;
1358 else if (hi > size)
1359 hi = size;
1360
1361 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1362 return -1;
1363
1364 if (new_end)
1365 *new_end = end + len_change;
1366
1367 return 0;
1368}
1369
1370 static PyObject *
1371RBAppend(BufferObject *self, PyObject *args, int start, int end, int *new_end)
1372{
1373 PyObject *lines;
1374 int len_change;
1375 int max;
1376 int n;
1377
1378 if (CheckBuffer(self))
1379 return NULL;
1380
1381 max = n = end - start + 1;
1382
1383 if (!PyArg_ParseTuple(args, "O|i", &lines, &n))
1384 return NULL;
1385
1386 if (n < 0 || n > max)
1387 {
1388 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1389 return NULL;
1390 }
1391
1392 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1393 return NULL;
1394
1395 if (new_end)
1396 *new_end = end + len_change;
1397
1398 Py_INCREF(Py_None);
1399 return Py_None;
1400}
1401
1402
1403/* Buffer object - Definitions
1404 */
1405
1406static struct PyMethodDef BufferMethods[] = {
1407 /* name, function, calling, documentation */
1408 {"append", BufferAppend, 1, "" },
1409 {"mark", BufferMark, 1, "" },
1410 {"range", BufferRange, 1, "" },
1411 { NULL, NULL, 0, NULL }
1412};
1413
1414static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001415 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001417 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1418 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1419 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1420 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1421 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001422};
1423
1424static PyTypeObject BufferType = {
1425 PyObject_HEAD_INIT(0)
1426 0,
1427 "buffer",
1428 sizeof(BufferObject),
1429 0,
1430
1431 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1432 (printfunc) 0, /* tp_print, print x */
1433 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1434 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1435 (cmpfunc) 0, /* tp_compare, x>y */
1436 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1437
1438 0, /* as number */
1439 &BufferAsSeq, /* as sequence */
1440 0, /* as mapping */
1441
1442 (hashfunc) 0, /* tp_hash, dict(x) */
1443 (ternaryfunc) 0, /* tp_call, x() */
1444 (reprfunc) 0, /* tp_str, str(x) */
1445};
1446
1447/* Buffer object - Implementation
1448 */
1449
1450 static PyObject *
1451BufferNew(buf_T *buf)
1452{
1453 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001454 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 * then we can get at it in buf_freeall() in vim. We then
1456 * need to create only ONE Python object per buffer - if
1457 * we try to create a second, just INCREF the existing one
1458 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001459 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001460 * Question: what to do on a buf_freeall(). We'll probably
1461 * have to either delete the Python object (DECREF it to
1462 * zero - a bad idea, as it leaves dangling refs!) or
1463 * set the buf_T * value to an invalid value (-1?), which
1464 * means we need checks in all access functions... Bah.
1465 */
1466
1467 BufferObject *self;
1468
Bram Moolenaare344bea2005-09-01 20:46:49 +00001469 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001471 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 Py_INCREF(self);
1473 }
1474 else
1475 {
1476 self = PyObject_NEW(BufferObject, &BufferType);
1477 if (self == NULL)
1478 return NULL;
1479 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001480 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 }
1482
1483 return (PyObject *)(self);
1484}
1485
1486 static void
1487BufferDestructor(PyObject *self)
1488{
1489 BufferObject *this = (BufferObject *)(self);
1490
1491 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001492 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493
Bram Moolenaar658ada62006-10-03 13:02:36 +00001494 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495}
1496
1497 static PyObject *
1498BufferGetattr(PyObject *self, char *name)
1499{
1500 BufferObject *this = (BufferObject *)(self);
1501
1502 if (CheckBuffer(this))
1503 return NULL;
1504
1505 if (strcmp(name, "name") == 0)
1506 return Py_BuildValue("s",this->buf->b_ffname);
1507 else if (strcmp(name, "number") == 0)
1508 return Py_BuildValue("i",this->buf->b_fnum);
1509 else if (strcmp(name,"__members__") == 0)
1510 return Py_BuildValue("[ss]", "name", "number");
1511 else
1512 return Py_FindMethod(BufferMethods, self, name);
1513}
1514
1515 static PyObject *
1516BufferRepr(PyObject *self)
1517{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001518 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519 BufferObject *this = (BufferObject *)(self);
1520
1521 if (this->buf == INVALID_BUFFER_VALUE)
1522 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00001523 vim_snprintf(repr, 100, _("<buffer object (deleted) at %8lX>"),
1524 (long)(self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 return PyString_FromString(repr);
1526 }
1527 else
1528 {
1529 char *name = (char *)this->buf->b_fname;
1530 int len;
1531
1532 if (name == NULL)
1533 name = "";
1534 len = strlen(name);
1535
1536 if (len > 35)
1537 name = name + (35 - len);
1538
Bram Moolenaar555b2802005-05-19 21:08:39 +00001539 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540
1541 return PyString_FromString(repr);
1542 }
1543}
1544
1545/******************/
1546
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001547 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548BufferLength(PyObject *self)
1549{
1550 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1551 if (CheckBuffer((BufferObject *)(self)))
1552 return -1; /* ??? */
1553
1554 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1555}
1556
1557 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001558BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559{
1560 return RBItem((BufferObject *)(self), n, 1,
1561 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1562}
1563
1564 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001565BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566{
1567 return RBSlice((BufferObject *)(self), lo, hi, 1,
1568 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1569}
1570
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001571 static PyInt
1572BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573{
1574 return RBAssItem((BufferObject *)(self), n, val, 1,
1575 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1576 NULL);
1577}
1578
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001579 static PyInt
1580BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581{
1582 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1583 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1584 NULL);
1585}
1586
1587 static PyObject *
1588BufferAppend(PyObject *self, PyObject *args)
1589{
1590 return RBAppend((BufferObject *)(self), args, 1,
1591 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1592 NULL);
1593}
1594
1595 static PyObject *
1596BufferMark(PyObject *self, PyObject *args)
1597{
1598 pos_T *posp;
1599 char mark;
1600 buf_T *curbuf_save;
1601
1602 if (CheckBuffer((BufferObject *)(self)))
1603 return NULL;
1604
1605 if (!PyArg_ParseTuple(args, "c", &mark))
1606 return NULL;
1607
1608 curbuf_save = curbuf;
1609 curbuf = ((BufferObject *)(self))->buf;
1610 posp = getmark(mark, FALSE);
1611 curbuf = curbuf_save;
1612
1613 if (posp == NULL)
1614 {
1615 PyErr_SetVim(_("invalid mark name"));
1616 return NULL;
1617 }
1618
1619 /* Ckeck for keyboard interrupt */
1620 if (VimErrorCheck())
1621 return NULL;
1622
1623 if (posp->lnum <= 0)
1624 {
1625 /* Or raise an error? */
1626 Py_INCREF(Py_None);
1627 return Py_None;
1628 }
1629
1630 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1631}
1632
1633 static PyObject *
1634BufferRange(PyObject *self, PyObject *args)
1635{
1636 int start;
1637 int end;
1638
1639 if (CheckBuffer((BufferObject *)(self)))
1640 return NULL;
1641
1642 if (!PyArg_ParseTuple(args, "ii", &start, &end))
1643 return NULL;
1644
1645 return RangeNew(((BufferObject *)(self))->buf, start, end);
1646}
1647
1648/* Line range object - Definitions
1649 */
1650
1651static struct PyMethodDef RangeMethods[] = {
1652 /* name, function, calling, documentation */
1653 {"append", RangeAppend, 1, "" },
1654 { NULL, NULL, 0, NULL }
1655};
1656
1657static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001658 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001660 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1661 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1662 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1663 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1664 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665};
1666
1667static PyTypeObject RangeType = {
1668 PyObject_HEAD_INIT(0)
1669 0,
1670 "range",
1671 sizeof(RangeObject),
1672 0,
1673
1674 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1675 (printfunc) 0, /* tp_print, print x */
1676 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1677 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1678 (cmpfunc) 0, /* tp_compare, x>y */
1679 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1680
1681 0, /* as number */
1682 &RangeAsSeq, /* as sequence */
1683 0, /* as mapping */
1684
1685 (hashfunc) 0, /* tp_hash, dict(x) */
1686 (ternaryfunc) 0, /* tp_call, x() */
1687 (reprfunc) 0, /* tp_str, str(x) */
1688};
1689
1690/* Line range object - Implementation
1691 */
1692
1693 static PyObject *
1694RangeNew(buf_T *buf, int start, int end)
1695{
1696 BufferObject *bufr;
1697 RangeObject *self;
1698 self = PyObject_NEW(RangeObject, &RangeType);
1699 if (self == NULL)
1700 return NULL;
1701
1702 bufr = (BufferObject *)BufferNew(buf);
1703 if (bufr == NULL)
1704 {
Bram Moolenaar658ada62006-10-03 13:02:36 +00001705 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 return NULL;
1707 }
1708 Py_INCREF(bufr);
1709
1710 self->buf = bufr;
1711 self->start = start;
1712 self->end = end;
1713
1714 return (PyObject *)(self);
1715}
1716
1717 static void
1718RangeDestructor(PyObject *self)
1719{
1720 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001721 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722}
1723
1724 static PyObject *
1725RangeGetattr(PyObject *self, char *name)
1726{
1727 if (strcmp(name, "start") == 0)
1728 return Py_BuildValue("i",((RangeObject *)(self))->start - 1);
1729 else if (strcmp(name, "end") == 0)
1730 return Py_BuildValue("i",((RangeObject *)(self))->end - 1);
1731 else
1732 return Py_FindMethod(RangeMethods, self, name);
1733}
1734
1735 static PyObject *
1736RangeRepr(PyObject *self)
1737{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001738 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 RangeObject *this = (RangeObject *)(self);
1740
1741 if (this->buf->buf == INVALID_BUFFER_VALUE)
1742 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00001743 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %8lX>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 (long)(self));
1745 return PyString_FromString(repr);
1746 }
1747 else
1748 {
1749 char *name = (char *)this->buf->buf->b_fname;
1750 int len;
1751
1752 if (name == NULL)
1753 name = "";
1754 len = strlen(name);
1755
1756 if (len > 45)
1757 name = name + (45 - len);
1758
Bram Moolenaar555b2802005-05-19 21:08:39 +00001759 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 len > 45 ? "..." : "", name,
1761 this->start, this->end);
1762
1763 return PyString_FromString(repr);
1764 }
1765}
1766
1767/****************/
1768
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001769 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770RangeLength(PyObject *self)
1771{
1772 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1773 if (CheckBuffer(((RangeObject *)(self))->buf))
1774 return -1; /* ??? */
1775
1776 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1777}
1778
1779 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001780RangeItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781{
1782 return RBItem(((RangeObject *)(self))->buf, n,
1783 ((RangeObject *)(self))->start,
1784 ((RangeObject *)(self))->end);
1785}
1786
1787 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001788RangeSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789{
1790 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1791 ((RangeObject *)(self))->start,
1792 ((RangeObject *)(self))->end);
1793}
1794
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001795 static PyInt
1796RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797{
1798 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1799 ((RangeObject *)(self))->start,
1800 ((RangeObject *)(self))->end,
1801 &((RangeObject *)(self))->end);
1802}
1803
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001804 static PyInt
1805RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806{
1807 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1808 ((RangeObject *)(self))->start,
1809 ((RangeObject *)(self))->end,
1810 &((RangeObject *)(self))->end);
1811}
1812
1813 static PyObject *
1814RangeAppend(PyObject *self, PyObject *args)
1815{
1816 return RBAppend(((RangeObject *)(self))->buf, args,
1817 ((RangeObject *)(self))->start,
1818 ((RangeObject *)(self))->end,
1819 &((RangeObject *)(self))->end);
1820}
1821
1822/* Buffer list object - Definitions
1823 */
1824
1825typedef struct
1826{
1827 PyObject_HEAD
1828}
1829BufListObject;
1830
1831static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001832 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001834 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1835 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1836 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1837 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1838 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839};
1840
1841static PyTypeObject BufListType = {
1842 PyObject_HEAD_INIT(0)
1843 0,
1844 "buffer list",
1845 sizeof(BufListObject),
1846 0,
1847
1848 (destructor) 0, /* tp_dealloc, refcount==0 */
1849 (printfunc) 0, /* tp_print, print x */
1850 (getattrfunc) 0, /* tp_getattr, x.attr */
1851 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1852 (cmpfunc) 0, /* tp_compare, x>y */
1853 (reprfunc) 0, /* tp_repr, `x`, print x */
1854
1855 0, /* as number */
1856 &BufListAsSeq, /* as sequence */
1857 0, /* as mapping */
1858
1859 (hashfunc) 0, /* tp_hash, dict(x) */
1860 (ternaryfunc) 0, /* tp_call, x() */
1861 (reprfunc) 0, /* tp_str, str(x) */
1862};
1863
1864/* Buffer list object - Implementation
1865 */
1866
1867/*ARGSUSED*/
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001868 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869BufListLength(PyObject *self)
1870{
1871 buf_T *b = firstbuf;
1872 int n = 0;
1873
1874 while (b)
1875 {
1876 ++n;
1877 b = b->b_next;
1878 }
1879
1880 return n;
1881}
1882
1883/*ARGSUSED*/
1884 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001885BufListItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886{
1887 buf_T *b;
1888
1889 for (b = firstbuf; b; b = b->b_next, --n)
1890 {
1891 if (n == 0)
1892 return BufferNew(b);
1893 }
1894
1895 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1896 return NULL;
1897}
1898
1899/* Window object - Definitions
1900 */
1901
1902static struct PyMethodDef WindowMethods[] = {
1903 /* name, function, calling, documentation */
1904 { NULL, NULL, 0, NULL }
1905};
1906
1907static PyTypeObject WindowType = {
1908 PyObject_HEAD_INIT(0)
1909 0,
1910 "window",
1911 sizeof(WindowObject),
1912 0,
1913
1914 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1915 (printfunc) 0, /* tp_print, print x */
1916 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1917 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1918 (cmpfunc) 0, /* tp_compare, x>y */
1919 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1920
1921 0, /* as number */
1922 0, /* as sequence */
1923 0, /* as mapping */
1924
1925 (hashfunc) 0, /* tp_hash, dict(x) */
1926 (ternaryfunc) 0, /* tp_call, x() */
1927 (reprfunc) 0, /* tp_str, str(x) */
1928};
1929
1930/* Window object - Implementation
1931 */
1932
1933 static PyObject *
1934WindowNew(win_T *win)
1935{
1936 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001937 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 * then we can get at it in win_free() in vim. We then
1939 * need to create only ONE Python object per window - if
1940 * we try to create a second, just INCREF the existing one
1941 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001942 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943 * On a win_free() we set the Python object's win_T* field
1944 * to an invalid value. We trap all uses of a window
1945 * object, and reject them if the win_T* field is invalid.
1946 */
1947
1948 WindowObject *self;
1949
Bram Moolenaare344bea2005-09-01 20:46:49 +00001950 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001952 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 Py_INCREF(self);
1954 }
1955 else
1956 {
1957 self = PyObject_NEW(WindowObject, &WindowType);
1958 if (self == NULL)
1959 return NULL;
1960 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001961 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 }
1963
1964 return (PyObject *)(self);
1965}
1966
1967 static void
1968WindowDestructor(PyObject *self)
1969{
1970 WindowObject *this = (WindowObject *)(self);
1971
1972 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001973 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974
Bram Moolenaar658ada62006-10-03 13:02:36 +00001975 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976}
1977
1978 static int
1979CheckWindow(WindowObject *this)
1980{
1981 if (this->win == INVALID_WINDOW_VALUE)
1982 {
1983 PyErr_SetVim(_("attempt to refer to deleted window"));
1984 return -1;
1985 }
1986
1987 return 0;
1988}
1989
1990 static PyObject *
1991WindowGetattr(PyObject *self, char *name)
1992{
1993 WindowObject *this = (WindowObject *)(self);
1994
1995 if (CheckWindow(this))
1996 return NULL;
1997
1998 if (strcmp(name, "buffer") == 0)
1999 return (PyObject *)BufferNew(this->win->w_buffer);
2000 else if (strcmp(name, "cursor") == 0)
2001 {
2002 pos_T *pos = &this->win->w_cursor;
2003
2004 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2005 }
2006 else if (strcmp(name, "height") == 0)
2007 return Py_BuildValue("l", (long)(this->win->w_height));
2008#ifdef FEAT_VERTSPLIT
2009 else if (strcmp(name, "width") == 0)
2010 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2011#endif
2012 else if (strcmp(name,"__members__") == 0)
2013 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2014 else
2015 return Py_FindMethod(WindowMethods, self, name);
2016}
2017
2018 static int
2019WindowSetattr(PyObject *self, char *name, PyObject *val)
2020{
2021 WindowObject *this = (WindowObject *)(self);
2022
2023 if (CheckWindow(this))
2024 return -1;
2025
2026 if (strcmp(name, "buffer") == 0)
2027 {
2028 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2029 return -1;
2030 }
2031 else if (strcmp(name, "cursor") == 0)
2032 {
2033 long lnum;
2034 long col;
2035
2036 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2037 return -1;
2038
2039 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2040 {
2041 PyErr_SetVim(_("cursor position outside buffer"));
2042 return -1;
2043 }
2044
2045 /* Check for keyboard interrupts */
2046 if (VimErrorCheck())
2047 return -1;
2048
2049 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2050
2051 this->win->w_cursor.lnum = lnum;
2052 this->win->w_cursor.col = col;
2053 update_screen(VALID);
2054
2055 return 0;
2056 }
2057 else if (strcmp(name, "height") == 0)
2058 {
2059 int height;
2060 win_T *savewin;
2061
2062 if (!PyArg_Parse(val, "i", &height))
2063 return -1;
2064
2065#ifdef FEAT_GUI
2066 need_mouse_correct = TRUE;
2067#endif
2068 savewin = curwin;
2069 curwin = this->win;
2070 win_setheight(height);
2071 curwin = savewin;
2072
2073 /* Check for keyboard interrupts */
2074 if (VimErrorCheck())
2075 return -1;
2076
2077 return 0;
2078 }
2079#ifdef FEAT_VERTSPLIT
2080 else if (strcmp(name, "width") == 0)
2081 {
2082 int width;
2083 win_T *savewin;
2084
2085 if (!PyArg_Parse(val, "i", &width))
2086 return -1;
2087
2088#ifdef FEAT_GUI
2089 need_mouse_correct = TRUE;
2090#endif
2091 savewin = curwin;
2092 curwin = this->win;
2093 win_setwidth(width);
2094 curwin = savewin;
2095
2096 /* Check for keyboard interrupts */
2097 if (VimErrorCheck())
2098 return -1;
2099
2100 return 0;
2101 }
2102#endif
2103 else
2104 {
2105 PyErr_SetString(PyExc_AttributeError, name);
2106 return -1;
2107 }
2108}
2109
2110 static PyObject *
2111WindowRepr(PyObject *self)
2112{
Bram Moolenaar555b2802005-05-19 21:08:39 +00002113 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 WindowObject *this = (WindowObject *)(self);
2115
2116 if (this->win == INVALID_WINDOW_VALUE)
2117 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00002118 vim_snprintf(repr, 100, _("<window object (deleted) at %.8lX>"),
2119 (long)(self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002120 return PyString_FromString(repr);
2121 }
2122 else
2123 {
2124 int i = 0;
2125 win_T *w;
2126
2127 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2128 ++i;
2129
2130 if (w == NULL)
Bram Moolenaar555b2802005-05-19 21:08:39 +00002131 vim_snprintf(repr, 100, _("<window object (unknown) at %.8lX>"),
2132 (long)(self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00002134 vim_snprintf(repr, 100, _("<window %d>"), i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135
2136 return PyString_FromString(repr);
2137 }
2138}
2139
2140/* Window list object - Definitions
2141 */
2142
2143typedef struct
2144{
2145 PyObject_HEAD
2146}
2147WinListObject;
2148
2149static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002150 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002152 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2153 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2154 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2155 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2156 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002157};
2158
2159static PyTypeObject WinListType = {
2160 PyObject_HEAD_INIT(0)
2161 0,
2162 "window list",
2163 sizeof(WinListObject),
2164 0,
2165
2166 (destructor) 0, /* tp_dealloc, refcount==0 */
2167 (printfunc) 0, /* tp_print, print x */
2168 (getattrfunc) 0, /* tp_getattr, x.attr */
2169 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2170 (cmpfunc) 0, /* tp_compare, x>y */
2171 (reprfunc) 0, /* tp_repr, `x`, print x */
2172
2173 0, /* as number */
2174 &WinListAsSeq, /* as sequence */
2175 0, /* as mapping */
2176
2177 (hashfunc) 0, /* tp_hash, dict(x) */
2178 (ternaryfunc) 0, /* tp_call, x() */
2179 (reprfunc) 0, /* tp_str, str(x) */
2180};
2181
2182/* Window list object - Implementation
2183 */
2184/*ARGSUSED*/
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002185 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186WinListLength(PyObject *self)
2187{
2188 win_T *w = firstwin;
2189 int n = 0;
2190
Bram Moolenaarf740b292006-02-16 22:11:02 +00002191 while (w != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 {
2193 ++n;
2194 w = W_NEXT(w);
2195 }
2196
2197 return n;
2198}
2199
2200/*ARGSUSED*/
2201 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002202WinListItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002203{
2204 win_T *w;
2205
Bram Moolenaarf740b292006-02-16 22:11:02 +00002206 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 if (n == 0)
2208 return WindowNew(w);
2209
2210 PyErr_SetString(PyExc_IndexError, _("no such window"));
2211 return NULL;
2212}
2213
2214/* Current items object - Definitions
2215 */
2216
2217typedef struct
2218{
2219 PyObject_HEAD
2220}
2221CurrentObject;
2222
2223static PyTypeObject CurrentType = {
2224 PyObject_HEAD_INIT(0)
2225 0,
2226 "current data",
2227 sizeof(CurrentObject),
2228 0,
2229
2230 (destructor) 0, /* tp_dealloc, refcount==0 */
2231 (printfunc) 0, /* tp_print, print x */
2232 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2233 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2234 (cmpfunc) 0, /* tp_compare, x>y */
2235 (reprfunc) 0, /* tp_repr, `x`, print x */
2236
2237 0, /* as number */
2238 0, /* as sequence */
2239 0, /* as mapping */
2240
2241 (hashfunc) 0, /* tp_hash, dict(x) */
2242 (ternaryfunc) 0, /* tp_call, x() */
2243 (reprfunc) 0, /* tp_str, str(x) */
2244};
2245
2246/* Current items object - Implementation
2247 */
2248/*ARGSUSED*/
2249 static PyObject *
2250CurrentGetattr(PyObject *self, char *name)
2251{
2252 if (strcmp(name, "buffer") == 0)
2253 return (PyObject *)BufferNew(curbuf);
2254 else if (strcmp(name, "window") == 0)
2255 return (PyObject *)WindowNew(curwin);
2256 else if (strcmp(name, "line") == 0)
2257 return GetBufferLine(curbuf, (int)curwin->w_cursor.lnum);
2258 else if (strcmp(name, "range") == 0)
2259 return RangeNew(curbuf, RangeStart, RangeEnd);
2260 else if (strcmp(name,"__members__") == 0)
2261 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2262 else
2263 {
2264 PyErr_SetString(PyExc_AttributeError, name);
2265 return NULL;
2266 }
2267}
2268
2269/*ARGSUSED*/
2270 static int
2271CurrentSetattr(PyObject *self, char *name, PyObject *value)
2272{
2273 if (strcmp(name, "line") == 0)
2274 {
2275 if (SetBufferLine(curbuf, (int)curwin->w_cursor.lnum, value, NULL) == FAIL)
2276 return -1;
2277
2278 return 0;
2279 }
2280 else
2281 {
2282 PyErr_SetString(PyExc_AttributeError, name);
2283 return -1;
2284 }
2285}
2286
2287/* External interface
2288 */
2289
2290 void
2291python_buffer_free(buf_T *buf)
2292{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002293 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002295 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002297 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 }
2299}
2300
2301#if defined(FEAT_WINDOWS) || defined(PROTO)
2302 void
2303python_window_free(win_T *win)
2304{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002305 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002307 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002309 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 }
2311}
2312#endif
2313
2314static BufListObject TheBufferList =
2315{
2316 PyObject_HEAD_INIT(&BufListType)
2317};
2318
2319static WinListObject TheWindowList =
2320{
2321 PyObject_HEAD_INIT(&WinListType)
2322};
2323
2324static CurrentObject TheCurrent =
2325{
2326 PyObject_HEAD_INIT(&CurrentType)
2327};
2328
2329 static int
2330PythonMod_Init(void)
2331{
2332 PyObject *mod;
2333 PyObject *dict;
2334 static char *(argv[2]) = {"", NULL};
2335
2336 /* Fixups... */
2337 BufferType.ob_type = &PyType_Type;
2338 RangeType.ob_type = &PyType_Type;
2339 WindowType.ob_type = &PyType_Type;
2340 BufListType.ob_type = &PyType_Type;
2341 WinListType.ob_type = &PyType_Type;
2342 CurrentType.ob_type = &PyType_Type;
2343
2344 /* Set sys.argv[] to avoid a crash in warn(). */
2345 PySys_SetArgv(1, argv);
2346
2347 mod = Py_InitModule("vim", VimMethods);
2348 dict = PyModule_GetDict(mod);
2349
2350 VimError = Py_BuildValue("s", "vim.error");
2351
2352 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00002353 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2354 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2355 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356
2357 if (PyErr_Occurred())
2358 return -1;
2359
2360 return 0;
2361}
2362
2363/*************************************************************************
2364 * 4. Utility functions for handling the interface between Vim and Python.
2365 */
2366
2367/* Get a line from the specified buffer. The line number is
2368 * in Vim format (1-based). The line is returned as a Python
2369 * string object.
2370 */
2371 static PyObject *
2372GetBufferLine(buf_T *buf, int n)
2373{
2374 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2375}
2376
2377/* Get a list of lines from the specified buffer. The line numbers
2378 * are in Vim format (1-based). The range is from lo up to, but not
2379 * including, hi. The list is returned as a Python list of string objects.
2380 */
2381 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002382GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002384 PyInt i;
2385 PyInt n = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 PyObject *list = PyList_New(n);
2387
2388 if (list == NULL)
2389 return NULL;
2390
2391 for (i = 0; i < n; ++i)
2392 {
2393 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2394
2395 /* Error check - was the Python string creation OK? */
2396 if (str == NULL)
2397 {
2398 Py_DECREF(list);
2399 return NULL;
2400 }
2401
2402 /* Set the list item */
2403 if (PyList_SetItem(list, i, str))
2404 {
2405 Py_DECREF(str);
2406 Py_DECREF(list);
2407 return NULL;
2408 }
2409 }
2410
2411 /* The ownership of the Python list is passed to the caller (ie,
2412 * the caller should Py_DECREF() the object when it is finished
2413 * with it).
2414 */
2415
2416 return list;
2417}
2418
2419/*
2420 * Check if deleting lines made the cursor position invalid.
2421 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2422 * deleted).
2423 */
2424 static void
2425py_fix_cursor(int lo, int hi, int extra)
2426{
2427 if (curwin->w_cursor.lnum >= lo)
2428 {
2429 /* Adjust the cursor position if it's in/after the changed
2430 * lines. */
2431 if (curwin->w_cursor.lnum >= hi)
2432 {
2433 curwin->w_cursor.lnum += extra;
2434 check_cursor_col();
2435 }
2436 else if (extra < 0)
2437 {
2438 curwin->w_cursor.lnum = lo;
2439 check_cursor();
2440 }
Bram Moolenaar454ec052007-03-08 09:20:28 +00002441 else
2442 check_cursor_col();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 changed_cline_bef_curs();
2444 }
2445 invalidate_botline();
2446}
2447
2448/* Replace a line in the specified buffer. The line number is
2449 * in Vim format (1-based). The replacement line is given as
2450 * a Python string object. The object is checked for validity
2451 * and correct format. Errors are returned as a value of FAIL.
2452 * The return value is OK on success.
2453 * If OK is returned and len_change is not NULL, *len_change
2454 * is set to the change in the buffer length.
2455 */
2456 static int
2457SetBufferLine(buf_T *buf, int n, PyObject *line, int *len_change)
2458{
2459 /* First of all, we check the thpe of the supplied Python object.
2460 * There are three cases:
2461 * 1. NULL, or None - this is a deletion.
2462 * 2. A string - this is a replacement.
2463 * 3. Anything else - this is an error.
2464 */
2465 if (line == Py_None || line == NULL)
2466 {
2467 buf_T *savebuf = curbuf;
2468
2469 PyErr_Clear();
2470 curbuf = buf;
2471
2472 if (u_savedel((linenr_T)n, 1L) == FAIL)
2473 PyErr_SetVim(_("cannot save undo information"));
2474 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2475 PyErr_SetVim(_("cannot delete line"));
2476 else
2477 {
2478 deleted_lines_mark((linenr_T)n, 1L);
2479 if (buf == curwin->w_buffer)
2480 py_fix_cursor(n, n + 1, -1);
2481 }
2482
2483 curbuf = savebuf;
2484
2485 if (PyErr_Occurred() || VimErrorCheck())
2486 return FAIL;
2487
2488 if (len_change)
2489 *len_change = -1;
2490
2491 return OK;
2492 }
2493 else if (PyString_Check(line))
2494 {
2495 char *save = StringToLine(line);
2496 buf_T *savebuf = curbuf;
2497
2498 if (save == NULL)
2499 return FAIL;
2500
2501 /* We do not need to free "save" if ml_replace() consumes it. */
2502 PyErr_Clear();
2503 curbuf = buf;
2504
2505 if (u_savesub((linenr_T)n) == FAIL)
2506 {
2507 PyErr_SetVim(_("cannot save undo information"));
2508 vim_free(save);
2509 }
2510 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2511 {
2512 PyErr_SetVim(_("cannot replace line"));
2513 vim_free(save);
2514 }
2515 else
2516 changed_bytes((linenr_T)n, 0);
2517
2518 curbuf = savebuf;
2519
Bram Moolenaar454ec052007-03-08 09:20:28 +00002520 /* Check that the cursor is not beyond the end of the line now. */
2521 if (buf == curwin->w_buffer)
2522 check_cursor_col();
2523
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 if (PyErr_Occurred() || VimErrorCheck())
2525 return FAIL;
2526
2527 if (len_change)
2528 *len_change = 0;
2529
2530 return OK;
2531 }
2532 else
2533 {
2534 PyErr_BadArgument();
2535 return FAIL;
2536 }
2537}
2538
2539/* Replace a range of lines in the specified buffer. The line numbers are in
2540 * Vim format (1-based). The range is from lo up to, but not including, hi.
2541 * The replacement lines are given as a Python list of string objects. The
2542 * list is checked for validity and correct format. Errors are returned as a
2543 * value of FAIL. The return value is OK on success.
2544 * If OK is returned and len_change is not NULL, *len_change
2545 * is set to the change in the buffer length.
2546 */
2547 static int
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002548SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, int *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549{
2550 /* First of all, we check the thpe of the supplied Python object.
2551 * There are three cases:
2552 * 1. NULL, or None - this is a deletion.
2553 * 2. A list - this is a replacement.
2554 * 3. Anything else - this is an error.
2555 */
2556 if (list == Py_None || list == NULL)
2557 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002558 PyInt i;
2559 PyInt n = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002560 buf_T *savebuf = curbuf;
2561
2562 PyErr_Clear();
2563 curbuf = buf;
2564
2565 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2566 PyErr_SetVim(_("cannot save undo information"));
2567 else
2568 {
2569 for (i = 0; i < n; ++i)
2570 {
2571 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2572 {
2573 PyErr_SetVim(_("cannot delete line"));
2574 break;
2575 }
2576 }
2577 deleted_lines_mark((linenr_T)lo, (long)i);
2578
2579 if (buf == curwin->w_buffer)
2580 py_fix_cursor(lo, hi, -n);
2581 }
2582
2583 curbuf = savebuf;
2584
2585 if (PyErr_Occurred() || VimErrorCheck())
2586 return FAIL;
2587
2588 if (len_change)
2589 *len_change = -n;
2590
2591 return OK;
2592 }
2593 else if (PyList_Check(list))
2594 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002595 PyInt i;
2596 PyInt new_len = PyList_Size(list);
2597 PyInt old_len = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 int extra = 0; /* lines added to text, can be negative */
2599 char **array;
2600 buf_T *savebuf;
2601
2602 if (new_len == 0) /* avoid allocating zero bytes */
2603 array = NULL;
2604 else
2605 {
2606 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2607 if (array == NULL)
2608 {
2609 PyErr_NoMemory();
2610 return FAIL;
2611 }
2612 }
2613
2614 for (i = 0; i < new_len; ++i)
2615 {
2616 PyObject *line = PyList_GetItem(list, i);
2617
2618 array[i] = StringToLine(line);
2619 if (array[i] == NULL)
2620 {
2621 while (i)
2622 vim_free(array[--i]);
2623 vim_free(array);
2624 return FAIL;
2625 }
2626 }
2627
2628 savebuf = curbuf;
2629
2630 PyErr_Clear();
2631 curbuf = buf;
2632
2633 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2634 PyErr_SetVim(_("cannot save undo information"));
2635
2636 /* If the size of the range is reducing (ie, new_len < old_len) we
2637 * need to delete some old_len. We do this at the start, by
2638 * repeatedly deleting line "lo".
2639 */
2640 if (!PyErr_Occurred())
2641 {
2642 for (i = 0; i < old_len - new_len; ++i)
2643 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2644 {
2645 PyErr_SetVim(_("cannot delete line"));
2646 break;
2647 }
2648 extra -= i;
2649 }
2650
2651 /* For as long as possible, replace the existing old_len with the
2652 * new old_len. This is a more efficient operation, as it requires
2653 * less memory allocation and freeing.
2654 */
2655 if (!PyErr_Occurred())
2656 {
2657 for (i = 0; i < old_len && i < new_len; ++i)
2658 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2659 == FAIL)
2660 {
2661 PyErr_SetVim(_("cannot replace line"));
2662 break;
2663 }
2664 }
2665 else
2666 i = 0;
2667
2668 /* Now we may need to insert the remaining new old_len. If we do, we
2669 * must free the strings as we finish with them (we can't pass the
2670 * responsibility to vim in this case).
2671 */
2672 if (!PyErr_Occurred())
2673 {
2674 while (i < new_len)
2675 {
2676 if (ml_append((linenr_T)(lo + i - 1),
2677 (char_u *)array[i], 0, FALSE) == FAIL)
2678 {
2679 PyErr_SetVim(_("cannot insert line"));
2680 break;
2681 }
2682 vim_free(array[i]);
2683 ++i;
2684 ++extra;
2685 }
2686 }
2687
2688 /* Free any left-over old_len, as a result of an error */
2689 while (i < new_len)
2690 {
2691 vim_free(array[i]);
2692 ++i;
2693 }
2694
2695 /* Free the array of old_len. All of its contents have now
2696 * been dealt with (either freed, or the responsibility passed
2697 * to vim.
2698 */
2699 vim_free(array);
2700
2701 /* Adjust marks. Invalidate any which lie in the
2702 * changed range, and move any in the remainder of the buffer.
2703 */
2704 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2705 (long)MAXLNUM, (long)extra);
2706 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2707
2708 if (buf == curwin->w_buffer)
2709 py_fix_cursor(lo, hi, extra);
2710
2711 curbuf = savebuf;
2712
2713 if (PyErr_Occurred() || VimErrorCheck())
2714 return FAIL;
2715
2716 if (len_change)
2717 *len_change = new_len - old_len;
2718
2719 return OK;
2720 }
2721 else
2722 {
2723 PyErr_BadArgument();
2724 return FAIL;
2725 }
2726}
2727
2728/* Insert a number of lines into the specified buffer after the specifed line.
2729 * The line number is in Vim format (1-based). The lines to be inserted are
2730 * given as a Python list of string objects or as a single string. The lines
2731 * to be added are checked for validity and correct format. Errors are
2732 * returned as a value of FAIL. The return value is OK on success.
2733 * If OK is returned and len_change is not NULL, *len_change
2734 * is set to the change in the buffer length.
2735 */
2736 static int
2737InsertBufferLines(buf_T *buf, int n, PyObject *lines, int *len_change)
2738{
2739 /* First of all, we check the type of the supplied Python object.
2740 * It must be a string or a list, or the call is in error.
2741 */
2742 if (PyString_Check(lines))
2743 {
2744 char *str = StringToLine(lines);
2745 buf_T *savebuf;
2746
2747 if (str == NULL)
2748 return FAIL;
2749
2750 savebuf = curbuf;
2751
2752 PyErr_Clear();
2753 curbuf = buf;
2754
2755 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2756 PyErr_SetVim(_("cannot save undo information"));
2757 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2758 PyErr_SetVim(_("cannot insert line"));
2759 else
2760 appended_lines_mark((linenr_T)n, 1L);
2761
2762 vim_free(str);
2763 curbuf = savebuf;
2764 update_screen(VALID);
2765
2766 if (PyErr_Occurred() || VimErrorCheck())
2767 return FAIL;
2768
2769 if (len_change)
2770 *len_change = 1;
2771
2772 return OK;
2773 }
2774 else if (PyList_Check(lines))
2775 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002776 PyInt i;
2777 PyInt size = PyList_Size(lines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 char **array;
2779 buf_T *savebuf;
2780
2781 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2782 if (array == NULL)
2783 {
2784 PyErr_NoMemory();
2785 return FAIL;
2786 }
2787
2788 for (i = 0; i < size; ++i)
2789 {
2790 PyObject *line = PyList_GetItem(lines, i);
2791 array[i] = StringToLine(line);
2792
2793 if (array[i] == NULL)
2794 {
2795 while (i)
2796 vim_free(array[--i]);
2797 vim_free(array);
2798 return FAIL;
2799 }
2800 }
2801
2802 savebuf = curbuf;
2803
2804 PyErr_Clear();
2805 curbuf = buf;
2806
2807 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2808 PyErr_SetVim(_("cannot save undo information"));
2809 else
2810 {
2811 for (i = 0; i < size; ++i)
2812 {
2813 if (ml_append((linenr_T)(n + i),
2814 (char_u *)array[i], 0, FALSE) == FAIL)
2815 {
2816 PyErr_SetVim(_("cannot insert line"));
2817
2818 /* Free the rest of the lines */
2819 while (i < size)
2820 vim_free(array[i++]);
2821
2822 break;
2823 }
2824 vim_free(array[i]);
2825 }
2826 if (i > 0)
2827 appended_lines_mark((linenr_T)n, (long)i);
2828 }
2829
2830 /* Free the array of lines. All of its contents have now
2831 * been freed.
2832 */
2833 vim_free(array);
2834
2835 curbuf = savebuf;
2836 update_screen(VALID);
2837
2838 if (PyErr_Occurred() || VimErrorCheck())
2839 return FAIL;
2840
2841 if (len_change)
2842 *len_change = size;
2843
2844 return OK;
2845 }
2846 else
2847 {
2848 PyErr_BadArgument();
2849 return FAIL;
2850 }
2851}
2852
2853/* Convert a Vim line into a Python string.
2854 * All internal newlines are replaced by null characters.
2855 *
2856 * On errors, the Python exception data is set, and NULL is returned.
2857 */
2858 static PyObject *
2859LineToString(const char *str)
2860{
2861 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002862 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 char *p;
2864
2865 /* Allocate an Python string object, with uninitialised contents. We
2866 * must do it this way, so that we can modify the string in place
2867 * later. See the Python source, Objects/stringobject.c for details.
2868 */
2869 result = PyString_FromStringAndSize(NULL, len);
2870 if (result == NULL)
2871 return NULL;
2872
2873 p = PyString_AsString(result);
2874
2875 while (*str)
2876 {
2877 if (*str == '\n')
2878 *p = '\0';
2879 else
2880 *p = *str;
2881
2882 ++p;
2883 ++str;
2884 }
2885
2886 return result;
2887}
2888
2889/* Convert a Python string into a Vim line.
2890 *
2891 * The result is in allocated memory. All internal nulls are replaced by
2892 * newline characters. It is an error for the string to contain newline
2893 * characters.
2894 *
2895 * On errors, the Python exception data is set, and NULL is returned.
2896 */
2897 static char *
2898StringToLine(PyObject *obj)
2899{
2900 const char *str;
2901 char *save;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002902 PyInt len;
2903 PyInt i;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002904 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905
2906 if (obj == NULL || !PyString_Check(obj))
2907 {
2908 PyErr_BadArgument();
2909 return NULL;
2910 }
2911
2912 str = PyString_AsString(obj);
2913 len = PyString_Size(obj);
2914
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002915 /*
2916 * Error checking: String must not contain newlines, as we
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917 * are replacing a single line, and we must replace it with
2918 * a single line.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002919 * A trailing newline is removed, so that append(f.readlines()) works.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002921 p = memchr(str, '\n', len);
2922 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002924 if (p == str + len - 1)
2925 --len;
2926 else
2927 {
2928 PyErr_SetVim(_("string cannot contain newlines"));
2929 return NULL;
2930 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 }
2932
2933 /* Create a copy of the string, with internal nulls replaced by
2934 * newline characters, as is the vim convention.
2935 */
2936 save = (char *)alloc((unsigned)(len+1));
2937 if (save == NULL)
2938 {
2939 PyErr_NoMemory();
2940 return NULL;
2941 }
2942
2943 for (i = 0; i < len; ++i)
2944 {
2945 if (str[i] == '\0')
2946 save[i] = '\n';
2947 else
2948 save[i] = str[i];
2949 }
2950
2951 save[i] = '\0';
2952
2953 return save;
2954}
2955
2956/* Check to see whether a Vim error has been reported, or a keyboard
2957 * interrupt has been detected.
2958 */
2959 static int
2960VimErrorCheck(void)
2961{
2962 if (got_int)
2963 {
2964 PyErr_SetNone(PyExc_KeyboardInterrupt);
2965 return 1;
2966 }
2967 else if (did_emsg && !PyErr_Occurred())
2968 {
2969 PyErr_SetNone(VimError);
2970 return 1;
2971 }
2972
2973 return 0;
2974}
2975
2976
2977/* Don't generate a prototype for the next function, it generates an error on
2978 * newer Python versions. */
2979#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
2980
2981 char *
2982Py_GetProgramName(void)
2983{
2984 return "vim";
2985}
2986#endif /* Python 1.4 */