blob: 4f23ffa8b834ca7915171bea61feb1094a532574 [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
Bram Moolenaarbe2c9ae2009-11-11 14:06:59 +000040#ifdef _POSIX_C_SOURCE
41# undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
42#endif
43#ifdef _XOPEN_SOURCE
44# undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
45#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000046
Bram Moolenaar2c45e942008-06-04 11:35:26 +000047#define PY_SSIZE_T_CLEAN
48
Bram Moolenaar071d4272004-06-13 20:20:40 +000049#include <Python.h>
50#if defined(MACOS) && !defined(MACOS_X_UNIX)
51# include "macglue.h"
52# include <CodeFragments.h>
53#endif
54#undef main /* Defined in python.h - aargh */
55#undef HAVE_FCNTL_H /* Clash with os_win32.h */
56
57#if !defined(FEAT_PYTHON) && defined(PROTO)
58/* Use this to be able to generate prototypes without python being used. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000059# define PyObject Py_ssize_t
60# define PyThreadState Py_ssize_t
61# define PyTypeObject Py_ssize_t
62struct PyMethodDef { Py_ssize_t a; };
63# define PySequenceMethods Py_ssize_t
Bram Moolenaar071d4272004-06-13 20:20:40 +000064#endif
65
Bram Moolenaar2c45e942008-06-04 11:35:26 +000066#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
67# define PyInt Py_ssize_t
68# define PyInquiry lenfunc
69# define PyIntArgFunc ssizeargfunc
70# define PyIntIntArgFunc ssizessizeargfunc
71# define PyIntObjArgProc ssizeobjargproc
72# define PyIntIntObjArgProc ssizessizeobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000073# define Py_ssize_t_fmt "n"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000074#else
75# define PyInt int
76# define PyInquiry inquiry
77# define PyIntArgFunc intargfunc
78# define PyIntIntArgFunc intintargfunc
79# define PyIntObjArgProc intobjargproc
80# define PyIntIntObjArgProc intintobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000081# define Py_ssize_t_fmt "i"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000082#endif
83
Bram Moolenaar071d4272004-06-13 20:20:40 +000084/* Parser flags */
85#define single_input 256
86#define file_input 257
87#define eval_input 258
88
89#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
90 /* Python 2.3: can invoke ":python" recursively. */
91# define PY_CAN_RECURSE
92#endif
93
94#if defined(DYNAMIC_PYTHON) || defined(PROTO)
95# ifndef DYNAMIC_PYTHON
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000096# define HINSTANCE long_u /* for generating prototypes */
Bram Moolenaar071d4272004-06-13 20:20:40 +000097# endif
98
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000099/* This makes if_python.c compile without warnings against Python 2.5
100 * on Win32 and Win64. */
101#undef PyRun_SimpleString
102#undef PyArg_Parse
103#undef PyArg_ParseTuple
104#undef Py_BuildValue
105#undef Py_InitModule4
106#undef Py_InitModule4_64
107
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108/*
109 * Wrapper defines
110 */
111# define PyArg_Parse dll_PyArg_Parse
112# define PyArg_ParseTuple dll_PyArg_ParseTuple
113# define PyDict_SetItemString dll_PyDict_SetItemString
114# define PyErr_BadArgument dll_PyErr_BadArgument
115# define PyErr_Clear dll_PyErr_Clear
116# define PyErr_NoMemory dll_PyErr_NoMemory
117# define PyErr_Occurred dll_PyErr_Occurred
118# define PyErr_SetNone dll_PyErr_SetNone
119# define PyErr_SetString dll_PyErr_SetString
120# define PyEval_InitThreads dll_PyEval_InitThreads
121# define PyEval_RestoreThread dll_PyEval_RestoreThread
122# define PyEval_SaveThread dll_PyEval_SaveThread
123# ifdef PY_CAN_RECURSE
124# define PyGILState_Ensure dll_PyGILState_Ensure
125# define PyGILState_Release dll_PyGILState_Release
126# endif
127# define PyInt_AsLong dll_PyInt_AsLong
128# define PyInt_FromLong dll_PyInt_FromLong
129# define PyInt_Type (*dll_PyInt_Type)
130# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000131# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132# define PyList_New dll_PyList_New
133# define PyList_SetItem dll_PyList_SetItem
134# define PyList_Size dll_PyList_Size
135# define PyList_Type (*dll_PyList_Type)
136# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000137# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138# define PyDict_GetItemString dll_PyDict_GetItemString
139# define PyModule_GetDict dll_PyModule_GetDict
140# define PyRun_SimpleString dll_PyRun_SimpleString
141# define PyString_AsString dll_PyString_AsString
142# define PyString_FromString dll_PyString_FromString
143# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
144# define PyString_Size dll_PyString_Size
145# define PyString_Type (*dll_PyString_Type)
146# define PySys_SetObject dll_PySys_SetObject
147# define PySys_SetArgv dll_PySys_SetArgv
148# define PyType_Type (*dll_PyType_Type)
149# define Py_BuildValue dll_Py_BuildValue
150# define Py_FindMethod dll_Py_FindMethod
151# define Py_InitModule4 dll_Py_InitModule4
152# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000153# define Py_Finalize dll_Py_Finalize
154# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155# define _PyObject_New dll__PyObject_New
156# define _Py_NoneStruct (*dll__Py_NoneStruct)
157# define PyObject_Init dll__PyObject_Init
158# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
159# define PyType_IsSubtype dll_PyType_IsSubtype
160# endif
161# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
162# define PyObject_Malloc dll_PyObject_Malloc
163# define PyObject_Free dll_PyObject_Free
164# endif
165
166/*
167 * Pointers for dynamic link
168 */
169static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
170static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
171static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
172static int(*dll_PyErr_BadArgument)(void);
173static void(*dll_PyErr_Clear)(void);
174static PyObject*(*dll_PyErr_NoMemory)(void);
175static PyObject*(*dll_PyErr_Occurred)(void);
176static void(*dll_PyErr_SetNone)(PyObject *);
177static void(*dll_PyErr_SetString)(PyObject *, const char *);
178static void(*dll_PyEval_InitThreads)(void);
179static void(*dll_PyEval_RestoreThread)(PyThreadState *);
180static PyThreadState*(*dll_PyEval_SaveThread)(void);
181# ifdef PY_CAN_RECURSE
182static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
183static void (*dll_PyGILState_Release)(PyGILState_STATE);
184#endif
185static long(*dll_PyInt_AsLong)(PyObject *);
186static PyObject*(*dll_PyInt_FromLong)(long);
187static PyTypeObject* dll_PyInt_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000188static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000189static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000190static PyObject*(*dll_PyList_New)(PyInt size);
191static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
192static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193static PyTypeObject* dll_PyList_Type;
194static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000195static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000196static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
197static PyObject*(*dll_PyModule_GetDict)(PyObject *);
198static int(*dll_PyRun_SimpleString)(char *);
199static char*(*dll_PyString_AsString)(PyObject *);
200static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000201static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
202static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203static PyTypeObject* dll_PyString_Type;
204static int(*dll_PySys_SetObject)(char *, PyObject *);
205static int(*dll_PySys_SetArgv)(int, char **);
206static PyTypeObject* dll_PyType_Type;
207static PyObject*(*dll_Py_BuildValue)(char *, ...);
208static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
209static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
210static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000211static void(*dll_Py_Finalize)(void);
212static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000213static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
214static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
215static PyObject* dll__Py_NoneStruct;
216# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
217static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
218# endif
219# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
220static void* (*dll_PyObject_Malloc)(size_t);
221static void (*dll_PyObject_Free)(void*);
222# endif
223
224static HINSTANCE hinstPython = 0; /* Instance of python.dll */
225
226/* Imported exception objects */
227static PyObject *imp_PyExc_AttributeError;
228static PyObject *imp_PyExc_IndexError;
229static PyObject *imp_PyExc_KeyboardInterrupt;
230static PyObject *imp_PyExc_TypeError;
231static PyObject *imp_PyExc_ValueError;
232
233# define PyExc_AttributeError imp_PyExc_AttributeError
234# define PyExc_IndexError imp_PyExc_IndexError
235# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
236# define PyExc_TypeError imp_PyExc_TypeError
237# define PyExc_ValueError imp_PyExc_ValueError
238
239/*
240 * Table of name to function pointer of python.
241 */
242# define PYTHON_PROC FARPROC
243static struct
244{
245 char *name;
246 PYTHON_PROC *ptr;
247} python_funcname_table[] =
248{
249 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
250 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
251 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
252 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
253 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
254 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
255 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
256 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
257 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
258 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
259 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
260 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
261# ifdef PY_CAN_RECURSE
262 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
263 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
264# endif
265 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
266 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
267 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
268 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000269 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000270 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
271 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
272 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
273 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
274 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
275 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000276 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
278 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
279 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
280 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
281 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
282 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
283 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
284 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
285 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
286 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
287 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
288 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000289# if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
290 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
291# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000293# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000295 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
296 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
298 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
299 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
300# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
301 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
302# endif
303# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
304 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
305 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
306# endif
307 {"", NULL},
308};
309
310/*
311 * Free python.dll
312 */
313 static void
314end_dynamic_python(void)
315{
316 if (hinstPython)
317 {
318 FreeLibrary(hinstPython);
319 hinstPython = 0;
320 }
321}
322
323/*
324 * Load library and get all pointers.
325 * Parameter 'libname' provides name of DLL.
326 * Return OK or FAIL.
327 */
328 static int
329python_runtime_link_init(char *libname, int verbose)
330{
331 int i;
332
333 if (hinstPython)
334 return OK;
335 hinstPython = LoadLibrary(libname);
336 if (!hinstPython)
337 {
338 if (verbose)
339 EMSG2(_(e_loadlib), libname);
340 return FAIL;
341 }
342
343 for (i = 0; python_funcname_table[i].ptr; ++i)
344 {
345 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
346 python_funcname_table[i].name)) == NULL)
347 {
348 FreeLibrary(hinstPython);
349 hinstPython = 0;
350 if (verbose)
351 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
352 return FAIL;
353 }
354 }
355 return OK;
356}
357
358/*
359 * If python is enabled (there is installed python on Windows system) return
360 * TRUE, else FALSE.
361 */
362 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000363python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364{
365 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
366}
367
368/* Load the standard Python exceptions - don't import the symbols from the
369 * DLL, as this can cause errors (importing data symbols is not reliable).
370 */
371static void get_exceptions __ARGS((void));
372
373 static void
374get_exceptions()
375{
376 PyObject *exmod = PyImport_ImportModule("exceptions");
377 PyObject *exdict = PyModule_GetDict(exmod);
378 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
379 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
380 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
381 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
382 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
383 Py_XINCREF(imp_PyExc_AttributeError);
384 Py_XINCREF(imp_PyExc_IndexError);
385 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
386 Py_XINCREF(imp_PyExc_TypeError);
387 Py_XINCREF(imp_PyExc_ValueError);
388 Py_XDECREF(exmod);
389}
390#endif /* DYNAMIC_PYTHON */
391
392/******************************************************
393 * Internal function prototypes.
394 */
395
396static void DoPythonCommand(exarg_T *, const char *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000397static PyInt RangeStart;
398static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399
400static void PythonIO_Flush(void);
401static int PythonIO_Init(void);
402static int PythonMod_Init(void);
403
404/* Utility functions for the vim/python interface
405 * ----------------------------------------------
406 */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000407static PyObject *GetBufferLine(buf_T *, PyInt);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000408static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000410static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
411static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
412static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000413
414static PyObject *LineToString(const char *);
415static char *StringToLine(PyObject *);
416
417static int VimErrorCheck(void);
418
419#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
420
421/******************************************************
422 * 1. Python interpreter main program.
423 */
424
425static int initialised = 0;
426
427#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
428typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000429#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000431#ifdef PY_CAN_RECURSE
432static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
433#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000434static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000435#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436
437/*
438 * Suspend a thread of the Python interpreter, other threads are allowed to
439 * run.
440 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441 static void
442Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000444#ifdef PY_CAN_RECURSE
445 PyGILState_Release(pygilstate);
446#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000448#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449}
450
451/*
452 * Restore a thread of the Python interpreter, waits for other threads to
453 * block.
454 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000455 static void
456Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000458#ifdef PY_CAN_RECURSE
459 pygilstate = PyGILState_Ensure();
460#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 PyEval_RestoreThread(saved_python_thread);
462 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000464}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465
466/*
467 * obtain a lock on the Vim data structures
468 */
469static void Python_Lock_Vim(void)
470{
471}
472
473/*
474 * release a lock on the Vim data structures
475 */
476static void Python_Release_Vim(void)
477{
478}
479
480 void
481python_end()
482{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000483 static int recurse = 0;
484
485 /* If a crash occurs while doing this, don't try again. */
486 if (recurse != 0)
487 return;
488
489 ++recurse;
490
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000492 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000493 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000494 Python_RestoreThread(); /* enter python */
495 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000496 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000498#else
499 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000500 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000501 Python_RestoreThread(); /* enter python */
502 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000505
506 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507}
508
509 static int
510Python_Init(void)
511{
512 if (!initialised)
513 {
514#ifdef DYNAMIC_PYTHON
515 if (!python_enabled(TRUE))
516 {
517 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
518 goto fail;
519 }
520#endif
521
522#if !defined(MACOS) || defined(MACOS_X_UNIX)
523 Py_Initialize();
524#else
525 PyMac_Initialize();
526#endif
527 /* initialise threads */
528 PyEval_InitThreads();
529
530#ifdef DYNAMIC_PYTHON
531 get_exceptions();
532#endif
533
534 if (PythonIO_Init())
535 goto fail;
536
537 if (PythonMod_Init())
538 goto fail;
539
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000540 /* Remove the element from sys.path that was added because of our
541 * argv[0] value in PythonMod_Init(). Previously we used an empty
542 * string, but dependinding on the OS we then get an empty entry or
543 * the current directory in sys.path. */
544 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
545
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000546 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000548
549 initialised = 1;
550 }
551
552 return 0;
553
554fail:
555 /* We call PythonIO_Flush() here to print any Python errors.
556 * This is OK, as it is possible to call this function even
557 * if PythonIO_Init() has not completed successfully (it will
558 * not do anything in this case).
559 */
560 PythonIO_Flush();
561 return -1;
562}
563
564/*
565 * External interface
566 */
567 static void
568DoPythonCommand(exarg_T *eap, const char *cmd)
569{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000570#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571 static int recursive = 0;
572#endif
573#if defined(MACOS) && !defined(MACOS_X_UNIX)
574 GrafPtr oldPort;
575#endif
576#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
577 char *saved_locale;
578#endif
579
580#ifndef PY_CAN_RECURSE
581 if (recursive)
582 {
583 EMSG(_("E659: Cannot invoke Python recursively"));
584 return;
585 }
586 ++recursive;
587#endif
588
589#if defined(MACOS) && !defined(MACOS_X_UNIX)
590 GetPort(&oldPort);
591 /* Check if the Python library is available */
592 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
593 goto theend;
594#endif
595 if (Python_Init())
596 goto theend;
597
598 RangeStart = eap->line1;
599 RangeEnd = eap->line2;
600 Python_Release_Vim(); /* leave vim */
601
602#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
603 /* Python only works properly when the LC_NUMERIC locale is "C". */
604 saved_locale = setlocale(LC_NUMERIC, NULL);
605 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
606 saved_locale = NULL;
607 else
608 {
609 /* Need to make a copy, value may change when setting new locale. */
610 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
611 (void)setlocale(LC_NUMERIC, "C");
612 }
613#endif
614
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616
617 PyRun_SimpleString((char *)(cmd));
618
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620
621#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
622 if (saved_locale != NULL)
623 {
624 (void)setlocale(LC_NUMERIC, saved_locale);
625 vim_free(saved_locale);
626 }
627#endif
628
629 Python_Lock_Vim(); /* enter vim */
630 PythonIO_Flush();
631#if defined(MACOS) && !defined(MACOS_X_UNIX)
632 SetPort(oldPort);
633#endif
634
635theend:
636#ifndef PY_CAN_RECURSE
637 --recursive;
638#endif
639 return; /* keeps lint happy */
640}
641
642/*
643 * ":python"
644 */
645 void
646ex_python(exarg_T *eap)
647{
648 char_u *script;
649
650 script = script_get(eap, eap->arg);
651 if (!eap->skip)
652 {
653 if (script == NULL)
654 DoPythonCommand(eap, (char *)eap->arg);
655 else
656 DoPythonCommand(eap, (char *)script);
657 }
658 vim_free(script);
659}
660
661#define BUFFER_SIZE 1024
662
663/*
664 * ":pyfile"
665 */
666 void
667ex_pyfile(exarg_T *eap)
668{
669 static char buffer[BUFFER_SIZE];
670 const char *file = (char *)eap->arg;
671 char *p;
672
673 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
674 * stdio file pointer, but Vim and the Python DLL are compiled with
675 * different options under Windows, meaning that stdio pointers aren't
676 * compatible between the two. Yuk.
677 *
678 * Put the string "execfile('file')" into buffer. But, we need to
679 * escape any backslashes or single quotes in the file name, so that
680 * Python won't mangle the file name.
681 */
682 strcpy(buffer, "execfile('");
683 p = buffer + 10; /* size of "execfile('" */
684
685 while (*file && p < buffer + (BUFFER_SIZE - 3))
686 {
687 if (*file == '\\' || *file == '\'')
688 *p++ = '\\';
689 *p++ = *file++;
690 }
691
692 /* If we didn't finish the file name, we hit a buffer overflow */
693 if (*file != '\0')
694 return;
695
696 /* Put in the terminating "')" and a null */
697 *p++ = '\'';
698 *p++ = ')';
699 *p++ = '\0';
700
701 /* Execute the file */
702 DoPythonCommand(eap, buffer);
703}
704
705/******************************************************
706 * 2. Python output stream: writes output via [e]msg().
707 */
708
709/* Implementation functions
710 */
711
712static PyObject *OutputGetattr(PyObject *, char *);
713static int OutputSetattr(PyObject *, char *, PyObject *);
714
715static PyObject *OutputWrite(PyObject *, PyObject *);
716static PyObject *OutputWritelines(PyObject *, PyObject *);
717
718typedef void (*writefn)(char_u *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000719static void writer(writefn fn, char_u *str, PyInt n);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720
721/* Output object definition
722 */
723
724typedef struct
725{
726 PyObject_HEAD
727 long softspace;
728 long error;
729} OutputObject;
730
731static struct PyMethodDef OutputMethods[] = {
732 /* name, function, calling, documentation */
733 {"write", OutputWrite, 1, "" },
734 {"writelines", OutputWritelines, 1, "" },
735 { NULL, NULL, 0, NULL }
736};
737
738static PyTypeObject OutputType = {
739 PyObject_HEAD_INIT(0)
740 0,
741 "message",
742 sizeof(OutputObject),
743 0,
744
745 (destructor) 0,
746 (printfunc) 0,
747 (getattrfunc) OutputGetattr,
748 (setattrfunc) OutputSetattr,
749 (cmpfunc) 0,
750 (reprfunc) 0,
751
752 0, /* as number */
753 0, /* as sequence */
754 0, /* as mapping */
755
756 (hashfunc) 0,
757 (ternaryfunc) 0,
758 (reprfunc) 0
759};
760
761/*************/
762
763 static PyObject *
764OutputGetattr(PyObject *self, char *name)
765{
766 if (strcmp(name, "softspace") == 0)
767 return PyInt_FromLong(((OutputObject *)(self))->softspace);
768
769 return Py_FindMethod(OutputMethods, self, name);
770}
771
772 static int
773OutputSetattr(PyObject *self, char *name, PyObject *val)
774{
775 if (val == NULL) {
776 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
777 return -1;
778 }
779
780 if (strcmp(name, "softspace") == 0)
781 {
782 if (!PyInt_Check(val)) {
783 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
784 return -1;
785 }
786
787 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
788 return 0;
789 }
790
791 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
792 return -1;
793}
794
795/*************/
796
797 static PyObject *
798OutputWrite(PyObject *self, PyObject *args)
799{
800 int len;
801 char *str;
802 int error = ((OutputObject *)(self))->error;
803
804 if (!PyArg_ParseTuple(args, "s#", &str, &len))
805 return NULL;
806
807 Py_BEGIN_ALLOW_THREADS
808 Python_Lock_Vim();
809 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
810 Python_Release_Vim();
811 Py_END_ALLOW_THREADS
812
813 Py_INCREF(Py_None);
814 return Py_None;
815}
816
817 static PyObject *
818OutputWritelines(PyObject *self, PyObject *args)
819{
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000820 PyInt n;
821 PyInt i;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000822 PyObject *list;
823 int error = ((OutputObject *)(self))->error;
824
825 if (!PyArg_ParseTuple(args, "O", &list))
826 return NULL;
827 Py_INCREF(list);
828
829 if (!PyList_Check(list)) {
830 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
831 Py_DECREF(list);
832 return NULL;
833 }
834
835 n = PyList_Size(list);
836
837 for (i = 0; i < n; ++i)
838 {
839 PyObject *line = PyList_GetItem(list, i);
840 char *str;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000841 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842
843 if (!PyArg_Parse(line, "s#", &str, &len)) {
844 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
845 Py_DECREF(list);
846 return NULL;
847 }
848
849 Py_BEGIN_ALLOW_THREADS
850 Python_Lock_Vim();
851 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
852 Python_Release_Vim();
853 Py_END_ALLOW_THREADS
854 }
855
856 Py_DECREF(list);
857 Py_INCREF(Py_None);
858 return Py_None;
859}
860
861/* Output buffer management
862 */
863
864static char_u *buffer = NULL;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000865static PyInt buffer_len = 0;
866static PyInt buffer_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867
868static writefn old_fn = NULL;
869
870 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000871buffer_ensure(PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000873 PyInt new_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874 char_u *new_buffer;
875
876 if (n < buffer_size)
877 return;
878
879 new_size = buffer_size;
880 while (new_size < n)
881 new_size += 80;
882
883 if (new_size != buffer_size)
884 {
885 new_buffer = alloc((unsigned)new_size);
886 if (new_buffer == NULL)
887 return;
888
889 if (buffer)
890 {
891 memcpy(new_buffer, buffer, buffer_len);
892 vim_free(buffer);
893 }
894
895 buffer = new_buffer;
896 buffer_size = new_size;
897 }
898}
899
900 static void
901PythonIO_Flush(void)
902{
903 if (old_fn && buffer_len)
904 {
905 buffer[buffer_len] = 0;
906 old_fn(buffer);
907 }
908
909 buffer_len = 0;
910}
911
912 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000913writer(writefn fn, char_u *str, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914{
915 char_u *ptr;
916
917 if (fn != old_fn && old_fn != NULL)
918 PythonIO_Flush();
919
920 old_fn = fn;
921
922 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
923 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000924 PyInt len = ptr - str;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925
926 buffer_ensure(buffer_len + len + 1);
927
928 memcpy(buffer + buffer_len, str, len);
929 buffer_len += len;
930 buffer[buffer_len] = 0;
931 fn(buffer);
932 str = ptr + 1;
933 n -= len + 1;
934 buffer_len = 0;
935 }
936
937 /* Put the remaining text into the buffer for later printing */
938 buffer_ensure(buffer_len + n + 1);
939 memcpy(buffer + buffer_len, str, n);
940 buffer_len += n;
941}
942
943/***************/
944
945static OutputObject Output =
946{
947 PyObject_HEAD_INIT(&OutputType)
948 0,
949 0
950};
951
952static OutputObject Error =
953{
954 PyObject_HEAD_INIT(&OutputType)
955 0,
956 1
957};
958
959 static int
960PythonIO_Init(void)
961{
962 /* Fixups... */
963 OutputType.ob_type = &PyType_Type;
964
Bram Moolenaar7df2d662005-01-25 22:18:08 +0000965 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
966 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967
968 if (PyErr_Occurred())
969 {
970 EMSG(_("E264: Python: Error initialising I/O objects"));
971 return -1;
972 }
973
974 return 0;
975}
976
977/******************************************************
978 * 3. Implementation of the Vim module for Python
979 */
980
981/* Vim module - Implementation functions
982 * -------------------------------------
983 */
984
985static PyObject *VimError;
986
987static PyObject *VimCommand(PyObject *, PyObject *);
988static PyObject *VimEval(PyObject *, PyObject *);
989
990/* Window type - Implementation functions
991 * --------------------------------------
992 */
993
994typedef struct
995{
996 PyObject_HEAD
997 win_T *win;
998}
999WindowObject;
1000
1001#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1002
1003#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1004
1005static PyObject *WindowNew(win_T *);
1006
1007static void WindowDestructor(PyObject *);
1008static PyObject *WindowGetattr(PyObject *, char *);
1009static int WindowSetattr(PyObject *, char *, PyObject *);
1010static PyObject *WindowRepr(PyObject *);
1011
1012/* Buffer type - Implementation functions
1013 * --------------------------------------
1014 */
1015
1016typedef struct
1017{
1018 PyObject_HEAD
1019 buf_T *buf;
1020}
1021BufferObject;
1022
1023#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1024
1025#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1026
1027static PyObject *BufferNew (buf_T *);
1028
1029static void BufferDestructor(PyObject *);
1030static PyObject *BufferGetattr(PyObject *, char *);
1031static PyObject *BufferRepr(PyObject *);
1032
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001033static PyInt BufferLength(PyObject *);
1034static PyObject *BufferItem(PyObject *, PyInt);
1035static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1036static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1037static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
1039static PyObject *BufferAppend(PyObject *, PyObject *);
1040static PyObject *BufferMark(PyObject *, PyObject *);
1041static PyObject *BufferRange(PyObject *, PyObject *);
1042
1043/* Line range type - Implementation functions
1044 * --------------------------------------
1045 */
1046
1047typedef struct
1048{
1049 PyObject_HEAD
1050 BufferObject *buf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001051 PyInt start;
1052 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053}
1054RangeObject;
1055
1056#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1057
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001058static PyObject *RangeNew(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059
1060static void RangeDestructor(PyObject *);
1061static PyObject *RangeGetattr(PyObject *, char *);
1062static PyObject *RangeRepr(PyObject *);
1063
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001064static PyInt RangeLength(PyObject *);
1065static PyObject *RangeItem(PyObject *, PyInt);
1066static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1067static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1068static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069
1070static PyObject *RangeAppend(PyObject *, PyObject *);
1071
1072/* Window list type - Implementation functions
1073 * -------------------------------------------
1074 */
1075
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001076static PyInt WinListLength(PyObject *);
1077static PyObject *WinListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078
1079/* Buffer list type - Implementation functions
1080 * -------------------------------------------
1081 */
1082
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001083static PyInt BufListLength(PyObject *);
1084static PyObject *BufListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085
1086/* Current objects type - Implementation functions
1087 * -----------------------------------------------
1088 */
1089
1090static PyObject *CurrentGetattr(PyObject *, char *);
1091static int CurrentSetattr(PyObject *, char *, PyObject *);
1092
1093/* Vim module - Definitions
1094 */
1095
1096static struct PyMethodDef VimMethods[] = {
1097 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001098 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1099 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 { NULL, NULL, 0, NULL }
1101};
1102
1103/* Vim module - Implementation
1104 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001106VimCommand(PyObject *self UNUSED, PyObject *args)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107{
1108 char *cmd;
1109 PyObject *result;
1110
1111 if (!PyArg_ParseTuple(args, "s", &cmd))
1112 return NULL;
1113
1114 PyErr_Clear();
1115
1116 Py_BEGIN_ALLOW_THREADS
1117 Python_Lock_Vim();
1118
1119 do_cmdline_cmd((char_u *)cmd);
1120 update_screen(VALID);
1121
1122 Python_Release_Vim();
1123 Py_END_ALLOW_THREADS
1124
1125 if (VimErrorCheck())
1126 result = NULL;
1127 else
1128 result = Py_None;
1129
1130 Py_XINCREF(result);
1131 return result;
1132}
1133
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001134#ifdef FEAT_EVAL
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001135/*
1136 * Function to translate a typval_T into a PyObject; this will recursively
1137 * translate lists/dictionaries into their Python equivalents.
1138 *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001139 * The depth parameter is to avoid infinite recursion, set it to 1 when
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001140 * you call VimToPython.
1141 */
1142 static PyObject *
1143VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1144{
1145 PyObject *result;
1146 PyObject *newObj;
1147 char ptrBuf[NUMBUFLEN];
1148
1149 /* Avoid infinite recursion */
1150 if (depth > 100)
1151 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001152 Py_INCREF(Py_None);
1153 result = Py_None;
1154 return result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001155 }
1156
1157 /* Check if we run into a recursive loop. The item must be in lookupDict
1158 * then and we can use it again. */
Bram Moolenaard72b3862009-01-13 17:11:05 +00001159 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1160 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1161 {
1162 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
1163 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1164 : (long_u)our_tv->vval.v_dict);
1165 result = PyDict_GetItemString(lookupDict, ptrBuf);
1166 if (result != NULL)
1167 {
1168 Py_INCREF(result);
1169 return result;
1170 }
1171 }
1172
1173 if (our_tv->v_type == VAR_STRING)
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001174 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001175 result = Py_BuildValue("s", our_tv->vval.v_string);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001176 }
1177 else if (our_tv->v_type == VAR_NUMBER)
1178 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001179 char buf[NUMBUFLEN];
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001180
1181 /* For backwards compatibility numbers are stored as strings. */
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001182 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1183 result = Py_BuildValue("s", buf);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001184 }
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001185# ifdef FEAT_FLOAT
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001186 else if (our_tv->v_type == VAR_FLOAT)
1187 {
1188 char buf[NUMBUFLEN];
1189
1190 sprintf(buf, "%f", our_tv->vval.v_float);
1191 result = Py_BuildValue("s", buf);
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001192 }
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001193# endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001194 else if (our_tv->v_type == VAR_LIST)
1195 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001196 list_T *list = our_tv->vval.v_list;
1197 listitem_T *curr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001198
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001199 result = PyList_New(0);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001200
1201 if (list != NULL)
1202 {
Bram Moolenaard72b3862009-01-13 17:11:05 +00001203 PyDict_SetItemString(lookupDict, ptrBuf, result);
1204
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001205 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1206 {
1207 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1208 PyList_Append(result, newObj);
1209 Py_DECREF(newObj);
1210 }
1211 }
1212 }
1213 else if (our_tv->v_type == VAR_DICT)
1214 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001215 result = PyDict_New();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001216
1217 if (our_tv->vval.v_dict != NULL)
1218 {
1219 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001220 long_u todo = ht->ht_used;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001221 hashitem_T *hi;
1222 dictitem_T *di;
1223
Bram Moolenaard72b3862009-01-13 17:11:05 +00001224 PyDict_SetItemString(lookupDict, ptrBuf, result);
1225
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001226 for (hi = ht->ht_array; todo > 0; ++hi)
1227 {
1228 if (!HASHITEM_EMPTY(hi))
1229 {
1230 --todo;
1231
1232 di = dict_lookup(hi);
1233 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1234 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1235 Py_DECREF(newObj);
1236 }
1237 }
1238 }
1239 }
1240 else
1241 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001242 Py_INCREF(Py_None);
1243 result = Py_None;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001244 }
1245
1246 return result;
1247}
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001248#endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001249
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001251VimEval(PyObject *self UNUSED, PyObject *args)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252{
1253#ifdef FEAT_EVAL
1254 char *expr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001255 typval_T *our_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001256 PyObject *result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001257 PyObject *lookup_dict;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001258
1259 if (!PyArg_ParseTuple(args, "s", &expr))
1260 return NULL;
1261
1262 Py_BEGIN_ALLOW_THREADS
1263 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001264 our_tv = eval_expr((char_u *)expr, NULL);
1265
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266 Python_Release_Vim();
1267 Py_END_ALLOW_THREADS
1268
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001269 if (our_tv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001270 {
1271 PyErr_SetVim(_("invalid expression"));
1272 return NULL;
1273 }
1274
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001275 /* Convert the Vim type into a Python type. Create a dictionary that's
1276 * used to check for recursive loops. */
1277 lookup_dict = PyDict_New();
1278 result = VimToPython(our_tv, 1, lookup_dict);
1279 Py_DECREF(lookup_dict);
1280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281
1282 Py_BEGIN_ALLOW_THREADS
1283 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001284 free_tv(our_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 Python_Release_Vim();
1286 Py_END_ALLOW_THREADS
1287
1288 return result;
1289#else
1290 PyErr_SetVim(_("expressions disabled at compile time"));
1291 return NULL;
1292#endif
1293}
1294
1295/* Common routines for buffers and line ranges
1296 * -------------------------------------------
1297 */
1298 static int
1299CheckBuffer(BufferObject *this)
1300{
1301 if (this->buf == INVALID_BUFFER_VALUE)
1302 {
1303 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1304 return -1;
1305 }
1306
1307 return 0;
1308}
1309
1310 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001311RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312{
1313 if (CheckBuffer(self))
1314 return NULL;
1315
1316 if (n < 0 || n > end - start)
1317 {
1318 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1319 return NULL;
1320 }
1321
1322 return GetBufferLine(self->buf, n+start);
1323}
1324
1325 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001326RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001328 PyInt size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329
1330 if (CheckBuffer(self))
1331 return NULL;
1332
1333 size = end - start + 1;
1334
1335 if (lo < 0)
1336 lo = 0;
1337 else if (lo > size)
1338 lo = size;
1339 if (hi < 0)
1340 hi = 0;
1341 if (hi < lo)
1342 hi = lo;
1343 else if (hi > size)
1344 hi = size;
1345
1346 return GetBufferLineList(self->buf, lo+start, hi+start);
1347}
1348
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001349 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001350RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001352 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353
1354 if (CheckBuffer(self))
1355 return -1;
1356
1357 if (n < 0 || n > end - start)
1358 {
1359 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1360 return -1;
1361 }
1362
1363 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1364 return -1;
1365
1366 if (new_end)
1367 *new_end = end + len_change;
1368
1369 return 0;
1370}
1371
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001372 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001373RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001375 PyInt size;
1376 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001377
1378 /* Self must be a valid buffer */
1379 if (CheckBuffer(self))
1380 return -1;
1381
1382 /* Sort out the slice range */
1383 size = end - start + 1;
1384
1385 if (lo < 0)
1386 lo = 0;
1387 else if (lo > size)
1388 lo = size;
1389 if (hi < 0)
1390 hi = 0;
1391 if (hi < lo)
1392 hi = lo;
1393 else if (hi > size)
1394 hi = size;
1395
1396 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1397 return -1;
1398
1399 if (new_end)
1400 *new_end = end + len_change;
1401
1402 return 0;
1403}
1404
1405 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001406RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407{
1408 PyObject *lines;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001409 PyInt len_change;
1410 PyInt max;
1411 PyInt n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412
1413 if (CheckBuffer(self))
1414 return NULL;
1415
1416 max = n = end - start + 1;
1417
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001418 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419 return NULL;
1420
1421 if (n < 0 || n > max)
1422 {
1423 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1424 return NULL;
1425 }
1426
1427 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1428 return NULL;
1429
1430 if (new_end)
1431 *new_end = end + len_change;
1432
1433 Py_INCREF(Py_None);
1434 return Py_None;
1435}
1436
1437
1438/* Buffer object - Definitions
1439 */
1440
1441static struct PyMethodDef BufferMethods[] = {
1442 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001443 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1444 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1445 {"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 +00001446 { NULL, NULL, 0, NULL }
1447};
1448
1449static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001450 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001452 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1453 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1454 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1455 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1456 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457};
1458
1459static PyTypeObject BufferType = {
1460 PyObject_HEAD_INIT(0)
1461 0,
1462 "buffer",
1463 sizeof(BufferObject),
1464 0,
1465
1466 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1467 (printfunc) 0, /* tp_print, print x */
1468 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1469 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1470 (cmpfunc) 0, /* tp_compare, x>y */
1471 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1472
1473 0, /* as number */
1474 &BufferAsSeq, /* as sequence */
1475 0, /* as mapping */
1476
1477 (hashfunc) 0, /* tp_hash, dict(x) */
1478 (ternaryfunc) 0, /* tp_call, x() */
1479 (reprfunc) 0, /* tp_str, str(x) */
1480};
1481
1482/* Buffer object - Implementation
1483 */
1484
1485 static PyObject *
1486BufferNew(buf_T *buf)
1487{
1488 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001489 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 * then we can get at it in buf_freeall() in vim. We then
1491 * need to create only ONE Python object per buffer - if
1492 * we try to create a second, just INCREF the existing one
1493 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001494 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 * Question: what to do on a buf_freeall(). We'll probably
1496 * have to either delete the Python object (DECREF it to
1497 * zero - a bad idea, as it leaves dangling refs!) or
1498 * set the buf_T * value to an invalid value (-1?), which
1499 * means we need checks in all access functions... Bah.
1500 */
1501
1502 BufferObject *self;
1503
Bram Moolenaare344bea2005-09-01 20:46:49 +00001504 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001506 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507 Py_INCREF(self);
1508 }
1509 else
1510 {
1511 self = PyObject_NEW(BufferObject, &BufferType);
1512 if (self == NULL)
1513 return NULL;
1514 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001515 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516 }
1517
1518 return (PyObject *)(self);
1519}
1520
1521 static void
1522BufferDestructor(PyObject *self)
1523{
1524 BufferObject *this = (BufferObject *)(self);
1525
1526 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001527 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528
Bram Moolenaar658ada62006-10-03 13:02:36 +00001529 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530}
1531
1532 static PyObject *
1533BufferGetattr(PyObject *self, char *name)
1534{
1535 BufferObject *this = (BufferObject *)(self);
1536
1537 if (CheckBuffer(this))
1538 return NULL;
1539
1540 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001541 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001543 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 else if (strcmp(name,"__members__") == 0)
1545 return Py_BuildValue("[ss]", "name", "number");
1546 else
1547 return Py_FindMethod(BufferMethods, self, name);
1548}
1549
1550 static PyObject *
1551BufferRepr(PyObject *self)
1552{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001553 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 BufferObject *this = (BufferObject *)(self);
1555
1556 if (this->buf == INVALID_BUFFER_VALUE)
1557 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001558 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559 return PyString_FromString(repr);
1560 }
1561 else
1562 {
1563 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001564 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565
1566 if (name == NULL)
1567 name = "";
1568 len = strlen(name);
1569
1570 if (len > 35)
1571 name = name + (35 - len);
1572
Bram Moolenaar555b2802005-05-19 21:08:39 +00001573 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574
1575 return PyString_FromString(repr);
1576 }
1577}
1578
1579/******************/
1580
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001581 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582BufferLength(PyObject *self)
1583{
1584 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1585 if (CheckBuffer((BufferObject *)(self)))
1586 return -1; /* ??? */
1587
1588 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1589}
1590
1591 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001592BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593{
1594 return RBItem((BufferObject *)(self), n, 1,
1595 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1596}
1597
1598 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001599BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600{
1601 return RBSlice((BufferObject *)(self), lo, hi, 1,
1602 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1603}
1604
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001605 static PyInt
1606BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607{
1608 return RBAssItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001609 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 NULL);
1611}
1612
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001613 static PyInt
1614BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615{
1616 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001617 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 NULL);
1619}
1620
1621 static PyObject *
1622BufferAppend(PyObject *self, PyObject *args)
1623{
1624 return RBAppend((BufferObject *)(self), args, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001625 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 NULL);
1627}
1628
1629 static PyObject *
1630BufferMark(PyObject *self, PyObject *args)
1631{
1632 pos_T *posp;
1633 char mark;
1634 buf_T *curbuf_save;
1635
1636 if (CheckBuffer((BufferObject *)(self)))
1637 return NULL;
1638
1639 if (!PyArg_ParseTuple(args, "c", &mark))
1640 return NULL;
1641
1642 curbuf_save = curbuf;
1643 curbuf = ((BufferObject *)(self))->buf;
1644 posp = getmark(mark, FALSE);
1645 curbuf = curbuf_save;
1646
1647 if (posp == NULL)
1648 {
1649 PyErr_SetVim(_("invalid mark name"));
1650 return NULL;
1651 }
1652
1653 /* Ckeck for keyboard interrupt */
1654 if (VimErrorCheck())
1655 return NULL;
1656
1657 if (posp->lnum <= 0)
1658 {
1659 /* Or raise an error? */
1660 Py_INCREF(Py_None);
1661 return Py_None;
1662 }
1663
1664 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1665}
1666
1667 static PyObject *
1668BufferRange(PyObject *self, PyObject *args)
1669{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001670 PyInt start;
1671 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672
1673 if (CheckBuffer((BufferObject *)(self)))
1674 return NULL;
1675
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001676 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 return NULL;
1678
1679 return RangeNew(((BufferObject *)(self))->buf, start, end);
1680}
1681
1682/* Line range object - Definitions
1683 */
1684
1685static struct PyMethodDef RangeMethods[] = {
1686 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001687 {"append", RangeAppend, 1, "Append data to the Vim range" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 { NULL, NULL, 0, NULL }
1689};
1690
1691static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001692 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001694 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1695 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1696 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1697 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1698 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699};
1700
1701static PyTypeObject RangeType = {
1702 PyObject_HEAD_INIT(0)
1703 0,
1704 "range",
1705 sizeof(RangeObject),
1706 0,
1707
1708 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1709 (printfunc) 0, /* tp_print, print x */
1710 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1711 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1712 (cmpfunc) 0, /* tp_compare, x>y */
1713 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1714
1715 0, /* as number */
1716 &RangeAsSeq, /* as sequence */
1717 0, /* as mapping */
1718
1719 (hashfunc) 0, /* tp_hash, dict(x) */
1720 (ternaryfunc) 0, /* tp_call, x() */
1721 (reprfunc) 0, /* tp_str, str(x) */
1722};
1723
1724/* Line range object - Implementation
1725 */
1726
1727 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001728RangeNew(buf_T *buf, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729{
1730 BufferObject *bufr;
1731 RangeObject *self;
1732 self = PyObject_NEW(RangeObject, &RangeType);
1733 if (self == NULL)
1734 return NULL;
1735
1736 bufr = (BufferObject *)BufferNew(buf);
1737 if (bufr == NULL)
1738 {
Bram Moolenaar658ada62006-10-03 13:02:36 +00001739 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 return NULL;
1741 }
1742 Py_INCREF(bufr);
1743
1744 self->buf = bufr;
1745 self->start = start;
1746 self->end = end;
1747
1748 return (PyObject *)(self);
1749}
1750
1751 static void
1752RangeDestructor(PyObject *self)
1753{
1754 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001755 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756}
1757
1758 static PyObject *
1759RangeGetattr(PyObject *self, char *name)
1760{
1761 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001762 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001764 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765 else
1766 return Py_FindMethod(RangeMethods, self, name);
1767}
1768
1769 static PyObject *
1770RangeRepr(PyObject *self)
1771{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001772 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 RangeObject *this = (RangeObject *)(self);
1774
1775 if (this->buf->buf == INVALID_BUFFER_VALUE)
1776 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001777 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1778 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 return PyString_FromString(repr);
1780 }
1781 else
1782 {
1783 char *name = (char *)this->buf->buf->b_fname;
1784 int len;
1785
1786 if (name == NULL)
1787 name = "";
Bram Moolenaarc236c162008-07-13 17:41:49 +00001788 len = (int)strlen(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789
1790 if (len > 45)
1791 name = name + (45 - len);
1792
Bram Moolenaar555b2802005-05-19 21:08:39 +00001793 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 len > 45 ? "..." : "", name,
1795 this->start, this->end);
1796
1797 return PyString_FromString(repr);
1798 }
1799}
1800
1801/****************/
1802
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001803 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804RangeLength(PyObject *self)
1805{
1806 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1807 if (CheckBuffer(((RangeObject *)(self))->buf))
1808 return -1; /* ??? */
1809
1810 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1811}
1812
1813 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001814RangeItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815{
1816 return RBItem(((RangeObject *)(self))->buf, n,
1817 ((RangeObject *)(self))->start,
1818 ((RangeObject *)(self))->end);
1819}
1820
1821 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001822RangeSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823{
1824 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1825 ((RangeObject *)(self))->start,
1826 ((RangeObject *)(self))->end);
1827}
1828
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001829 static PyInt
1830RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831{
1832 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1833 ((RangeObject *)(self))->start,
1834 ((RangeObject *)(self))->end,
1835 &((RangeObject *)(self))->end);
1836}
1837
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001838 static PyInt
1839RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840{
1841 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1842 ((RangeObject *)(self))->start,
1843 ((RangeObject *)(self))->end,
1844 &((RangeObject *)(self))->end);
1845}
1846
1847 static PyObject *
1848RangeAppend(PyObject *self, PyObject *args)
1849{
1850 return RBAppend(((RangeObject *)(self))->buf, args,
1851 ((RangeObject *)(self))->start,
1852 ((RangeObject *)(self))->end,
1853 &((RangeObject *)(self))->end);
1854}
1855
1856/* Buffer list object - Definitions
1857 */
1858
1859typedef struct
1860{
1861 PyObject_HEAD
1862}
1863BufListObject;
1864
1865static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001866 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001868 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1869 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1870 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1871 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1872 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873};
1874
1875static PyTypeObject BufListType = {
1876 PyObject_HEAD_INIT(0)
1877 0,
1878 "buffer list",
1879 sizeof(BufListObject),
1880 0,
1881
1882 (destructor) 0, /* tp_dealloc, refcount==0 */
1883 (printfunc) 0, /* tp_print, print x */
1884 (getattrfunc) 0, /* tp_getattr, x.attr */
1885 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1886 (cmpfunc) 0, /* tp_compare, x>y */
1887 (reprfunc) 0, /* tp_repr, `x`, print x */
1888
1889 0, /* as number */
1890 &BufListAsSeq, /* as sequence */
1891 0, /* as mapping */
1892
1893 (hashfunc) 0, /* tp_hash, dict(x) */
1894 (ternaryfunc) 0, /* tp_call, x() */
1895 (reprfunc) 0, /* tp_str, str(x) */
1896};
1897
1898/* Buffer list object - Implementation
1899 */
1900
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001901 static PyInt
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001902BufListLength(PyObject *self UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001903{
1904 buf_T *b = firstbuf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001905 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906
1907 while (b)
1908 {
1909 ++n;
1910 b = b->b_next;
1911 }
1912
1913 return n;
1914}
1915
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001917BufListItem(PyObject *self UNUSED, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918{
1919 buf_T *b;
1920
1921 for (b = firstbuf; b; b = b->b_next, --n)
1922 {
1923 if (n == 0)
1924 return BufferNew(b);
1925 }
1926
1927 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1928 return NULL;
1929}
1930
1931/* Window object - Definitions
1932 */
1933
1934static struct PyMethodDef WindowMethods[] = {
1935 /* name, function, calling, documentation */
1936 { NULL, NULL, 0, NULL }
1937};
1938
1939static PyTypeObject WindowType = {
1940 PyObject_HEAD_INIT(0)
1941 0,
1942 "window",
1943 sizeof(WindowObject),
1944 0,
1945
1946 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1947 (printfunc) 0, /* tp_print, print x */
1948 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1949 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1950 (cmpfunc) 0, /* tp_compare, x>y */
1951 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1952
1953 0, /* as number */
1954 0, /* as sequence */
1955 0, /* as mapping */
1956
1957 (hashfunc) 0, /* tp_hash, dict(x) */
1958 (ternaryfunc) 0, /* tp_call, x() */
1959 (reprfunc) 0, /* tp_str, str(x) */
1960};
1961
1962/* Window object - Implementation
1963 */
1964
1965 static PyObject *
1966WindowNew(win_T *win)
1967{
1968 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001969 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001970 * then we can get at it in win_free() in vim. We then
1971 * need to create only ONE Python object per window - if
1972 * we try to create a second, just INCREF the existing one
1973 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001974 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 * On a win_free() we set the Python object's win_T* field
1976 * to an invalid value. We trap all uses of a window
1977 * object, and reject them if the win_T* field is invalid.
1978 */
1979
1980 WindowObject *self;
1981
Bram Moolenaare344bea2005-09-01 20:46:49 +00001982 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001983 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001984 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 Py_INCREF(self);
1986 }
1987 else
1988 {
1989 self = PyObject_NEW(WindowObject, &WindowType);
1990 if (self == NULL)
1991 return NULL;
1992 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001993 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 }
1995
1996 return (PyObject *)(self);
1997}
1998
1999 static void
2000WindowDestructor(PyObject *self)
2001{
2002 WindowObject *this = (WindowObject *)(self);
2003
2004 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00002005 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006
Bram Moolenaar658ada62006-10-03 13:02:36 +00002007 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008}
2009
2010 static int
2011CheckWindow(WindowObject *this)
2012{
2013 if (this->win == INVALID_WINDOW_VALUE)
2014 {
2015 PyErr_SetVim(_("attempt to refer to deleted window"));
2016 return -1;
2017 }
2018
2019 return 0;
2020}
2021
2022 static PyObject *
2023WindowGetattr(PyObject *self, char *name)
2024{
2025 WindowObject *this = (WindowObject *)(self);
2026
2027 if (CheckWindow(this))
2028 return NULL;
2029
2030 if (strcmp(name, "buffer") == 0)
2031 return (PyObject *)BufferNew(this->win->w_buffer);
2032 else if (strcmp(name, "cursor") == 0)
2033 {
2034 pos_T *pos = &this->win->w_cursor;
2035
2036 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2037 }
2038 else if (strcmp(name, "height") == 0)
2039 return Py_BuildValue("l", (long)(this->win->w_height));
2040#ifdef FEAT_VERTSPLIT
2041 else if (strcmp(name, "width") == 0)
2042 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2043#endif
2044 else if (strcmp(name,"__members__") == 0)
2045 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2046 else
2047 return Py_FindMethod(WindowMethods, self, name);
2048}
2049
2050 static int
2051WindowSetattr(PyObject *self, char *name, PyObject *val)
2052{
2053 WindowObject *this = (WindowObject *)(self);
2054
2055 if (CheckWindow(this))
2056 return -1;
2057
2058 if (strcmp(name, "buffer") == 0)
2059 {
2060 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2061 return -1;
2062 }
2063 else if (strcmp(name, "cursor") == 0)
2064 {
2065 long lnum;
2066 long col;
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002067 long len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068
2069 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2070 return -1;
2071
2072 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2073 {
2074 PyErr_SetVim(_("cursor position outside buffer"));
2075 return -1;
2076 }
2077
2078 /* Check for keyboard interrupts */
2079 if (VimErrorCheck())
2080 return -1;
2081
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002082 /* When column is out of range silently correct it. */
Bram Moolenaar8b9c05f2010-03-02 17:54:33 +01002083 len = (long)STRLEN(ml_get_buf(this->win->w_buffer, lnum, FALSE));
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002084 if (col > len)
2085 col = len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086
2087 this->win->w_cursor.lnum = lnum;
2088 this->win->w_cursor.col = col;
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002089#ifdef FEAT_VIRTUALEDIT
2090 this->win->w_cursor.coladd = 0;
2091#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 update_screen(VALID);
2093
2094 return 0;
2095 }
2096 else if (strcmp(name, "height") == 0)
2097 {
2098 int height;
2099 win_T *savewin;
2100
2101 if (!PyArg_Parse(val, "i", &height))
2102 return -1;
2103
2104#ifdef FEAT_GUI
2105 need_mouse_correct = TRUE;
2106#endif
2107 savewin = curwin;
2108 curwin = this->win;
2109 win_setheight(height);
2110 curwin = savewin;
2111
2112 /* Check for keyboard interrupts */
2113 if (VimErrorCheck())
2114 return -1;
2115
2116 return 0;
2117 }
2118#ifdef FEAT_VERTSPLIT
2119 else if (strcmp(name, "width") == 0)
2120 {
2121 int width;
2122 win_T *savewin;
2123
2124 if (!PyArg_Parse(val, "i", &width))
2125 return -1;
2126
2127#ifdef FEAT_GUI
2128 need_mouse_correct = TRUE;
2129#endif
2130 savewin = curwin;
2131 curwin = this->win;
2132 win_setwidth(width);
2133 curwin = savewin;
2134
2135 /* Check for keyboard interrupts */
2136 if (VimErrorCheck())
2137 return -1;
2138
2139 return 0;
2140 }
2141#endif
2142 else
2143 {
2144 PyErr_SetString(PyExc_AttributeError, name);
2145 return -1;
2146 }
2147}
2148
2149 static PyObject *
2150WindowRepr(PyObject *self)
2151{
Bram Moolenaar555b2802005-05-19 21:08:39 +00002152 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002153 WindowObject *this = (WindowObject *)(self);
2154
2155 if (this->win == INVALID_WINDOW_VALUE)
2156 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002157 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002158 return PyString_FromString(repr);
2159 }
2160 else
2161 {
2162 int i = 0;
2163 win_T *w;
2164
2165 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2166 ++i;
2167
2168 if (w == NULL)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002169 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2170 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00002172 vim_snprintf(repr, 100, _("<window %d>"), i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173
2174 return PyString_FromString(repr);
2175 }
2176}
2177
2178/* Window list object - Definitions
2179 */
2180
2181typedef struct
2182{
2183 PyObject_HEAD
2184}
2185WinListObject;
2186
2187static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002188 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002190 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2191 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2192 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2193 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2194 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195};
2196
2197static PyTypeObject WinListType = {
2198 PyObject_HEAD_INIT(0)
2199 0,
2200 "window list",
2201 sizeof(WinListObject),
2202 0,
2203
2204 (destructor) 0, /* tp_dealloc, refcount==0 */
2205 (printfunc) 0, /* tp_print, print x */
2206 (getattrfunc) 0, /* tp_getattr, x.attr */
2207 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2208 (cmpfunc) 0, /* tp_compare, x>y */
2209 (reprfunc) 0, /* tp_repr, `x`, print x */
2210
2211 0, /* as number */
2212 &WinListAsSeq, /* as sequence */
2213 0, /* as mapping */
2214
2215 (hashfunc) 0, /* tp_hash, dict(x) */
2216 (ternaryfunc) 0, /* tp_call, x() */
2217 (reprfunc) 0, /* tp_str, str(x) */
2218};
2219
2220/* Window list object - Implementation
2221 */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002222 static PyInt
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002223WinListLength(PyObject *self UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224{
2225 win_T *w = firstwin;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002226 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227
Bram Moolenaarf740b292006-02-16 22:11:02 +00002228 while (w != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 {
2230 ++n;
2231 w = W_NEXT(w);
2232 }
2233
2234 return n;
2235}
2236
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002238WinListItem(PyObject *self UNUSED, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002239{
2240 win_T *w;
2241
Bram Moolenaarf740b292006-02-16 22:11:02 +00002242 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 if (n == 0)
2244 return WindowNew(w);
2245
2246 PyErr_SetString(PyExc_IndexError, _("no such window"));
2247 return NULL;
2248}
2249
2250/* Current items object - Definitions
2251 */
2252
2253typedef struct
2254{
2255 PyObject_HEAD
2256}
2257CurrentObject;
2258
2259static PyTypeObject CurrentType = {
2260 PyObject_HEAD_INIT(0)
2261 0,
2262 "current data",
2263 sizeof(CurrentObject),
2264 0,
2265
2266 (destructor) 0, /* tp_dealloc, refcount==0 */
2267 (printfunc) 0, /* tp_print, print x */
2268 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2269 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2270 (cmpfunc) 0, /* tp_compare, x>y */
2271 (reprfunc) 0, /* tp_repr, `x`, print x */
2272
2273 0, /* as number */
2274 0, /* as sequence */
2275 0, /* as mapping */
2276
2277 (hashfunc) 0, /* tp_hash, dict(x) */
2278 (ternaryfunc) 0, /* tp_call, x() */
2279 (reprfunc) 0, /* tp_str, str(x) */
2280};
2281
2282/* Current items object - Implementation
2283 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002285CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286{
2287 if (strcmp(name, "buffer") == 0)
2288 return (PyObject *)BufferNew(curbuf);
2289 else if (strcmp(name, "window") == 0)
2290 return (PyObject *)WindowNew(curwin);
2291 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002292 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293 else if (strcmp(name, "range") == 0)
2294 return RangeNew(curbuf, RangeStart, RangeEnd);
2295 else if (strcmp(name,"__members__") == 0)
2296 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2297 else
2298 {
2299 PyErr_SetString(PyExc_AttributeError, name);
2300 return NULL;
2301 }
2302}
2303
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002305CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306{
2307 if (strcmp(name, "line") == 0)
2308 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002309 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 return -1;
2311
2312 return 0;
2313 }
2314 else
2315 {
2316 PyErr_SetString(PyExc_AttributeError, name);
2317 return -1;
2318 }
2319}
2320
2321/* External interface
2322 */
2323
2324 void
2325python_buffer_free(buf_T *buf)
2326{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002327 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002329 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002330 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002331 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 }
2333}
2334
2335#if defined(FEAT_WINDOWS) || defined(PROTO)
2336 void
2337python_window_free(win_T *win)
2338{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002339 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002341 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002343 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 }
2345}
2346#endif
2347
2348static BufListObject TheBufferList =
2349{
2350 PyObject_HEAD_INIT(&BufListType)
2351};
2352
2353static WinListObject TheWindowList =
2354{
2355 PyObject_HEAD_INIT(&WinListType)
2356};
2357
2358static CurrentObject TheCurrent =
2359{
2360 PyObject_HEAD_INIT(&CurrentType)
2361};
2362
2363 static int
2364PythonMod_Init(void)
2365{
2366 PyObject *mod;
2367 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00002368 /* The special value is removed from sys.path in Python_Init(). */
2369 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370
2371 /* Fixups... */
2372 BufferType.ob_type = &PyType_Type;
2373 RangeType.ob_type = &PyType_Type;
2374 WindowType.ob_type = &PyType_Type;
2375 BufListType.ob_type = &PyType_Type;
2376 WinListType.ob_type = &PyType_Type;
2377 CurrentType.ob_type = &PyType_Type;
2378
2379 /* Set sys.argv[] to avoid a crash in warn(). */
2380 PySys_SetArgv(1, argv);
2381
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002382 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 dict = PyModule_GetDict(mod);
2384
2385 VimError = Py_BuildValue("s", "vim.error");
2386
2387 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00002388 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2389 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2390 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391
2392 if (PyErr_Occurred())
2393 return -1;
2394
2395 return 0;
2396}
2397
2398/*************************************************************************
2399 * 4. Utility functions for handling the interface between Vim and Python.
2400 */
2401
2402/* Get a line from the specified buffer. The line number is
2403 * in Vim format (1-based). The line is returned as a Python
2404 * string object.
2405 */
2406 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002407GetBufferLine(buf_T *buf, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408{
2409 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2410}
2411
2412/* Get a list of lines from the specified buffer. The line numbers
2413 * are in Vim format (1-based). The range is from lo up to, but not
2414 * including, hi. The list is returned as a Python list of string objects.
2415 */
2416 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002417GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002419 PyInt i;
2420 PyInt n = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 PyObject *list = PyList_New(n);
2422
2423 if (list == NULL)
2424 return NULL;
2425
2426 for (i = 0; i < n; ++i)
2427 {
2428 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2429
2430 /* Error check - was the Python string creation OK? */
2431 if (str == NULL)
2432 {
2433 Py_DECREF(list);
2434 return NULL;
2435 }
2436
2437 /* Set the list item */
2438 if (PyList_SetItem(list, i, str))
2439 {
2440 Py_DECREF(str);
2441 Py_DECREF(list);
2442 return NULL;
2443 }
2444 }
2445
2446 /* The ownership of the Python list is passed to the caller (ie,
2447 * the caller should Py_DECREF() the object when it is finished
2448 * with it).
2449 */
2450
2451 return list;
2452}
2453
2454/*
2455 * Check if deleting lines made the cursor position invalid.
2456 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2457 * deleted).
2458 */
2459 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002460py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461{
2462 if (curwin->w_cursor.lnum >= lo)
2463 {
2464 /* Adjust the cursor position if it's in/after the changed
2465 * lines. */
2466 if (curwin->w_cursor.lnum >= hi)
2467 {
2468 curwin->w_cursor.lnum += extra;
2469 check_cursor_col();
2470 }
2471 else if (extra < 0)
2472 {
2473 curwin->w_cursor.lnum = lo;
2474 check_cursor();
2475 }
Bram Moolenaar454ec052007-03-08 09:20:28 +00002476 else
2477 check_cursor_col();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 changed_cline_bef_curs();
2479 }
2480 invalidate_botline();
2481}
2482
2483/* Replace a line in the specified buffer. The line number is
2484 * in Vim format (1-based). The replacement line is given as
2485 * a Python string object. The object is checked for validity
2486 * and correct format. Errors are returned as a value of FAIL.
2487 * The return value is OK on success.
2488 * If OK is returned and len_change is not NULL, *len_change
2489 * is set to the change in the buffer length.
2490 */
2491 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002492SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
2494 /* First of all, we check the thpe of the supplied Python object.
2495 * There are three cases:
2496 * 1. NULL, or None - this is a deletion.
2497 * 2. A string - this is a replacement.
2498 * 3. Anything else - this is an error.
2499 */
2500 if (line == Py_None || line == NULL)
2501 {
2502 buf_T *savebuf = curbuf;
2503
2504 PyErr_Clear();
2505 curbuf = buf;
2506
2507 if (u_savedel((linenr_T)n, 1L) == FAIL)
2508 PyErr_SetVim(_("cannot save undo information"));
2509 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2510 PyErr_SetVim(_("cannot delete line"));
2511 else
2512 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002514 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002515 deleted_lines_mark((linenr_T)n, 1L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 }
2517
2518 curbuf = savebuf;
2519
2520 if (PyErr_Occurred() || VimErrorCheck())
2521 return FAIL;
2522
2523 if (len_change)
2524 *len_change = -1;
2525
2526 return OK;
2527 }
2528 else if (PyString_Check(line))
2529 {
2530 char *save = StringToLine(line);
2531 buf_T *savebuf = curbuf;
2532
2533 if (save == NULL)
2534 return FAIL;
2535
2536 /* We do not need to free "save" if ml_replace() consumes it. */
2537 PyErr_Clear();
2538 curbuf = buf;
2539
2540 if (u_savesub((linenr_T)n) == FAIL)
2541 {
2542 PyErr_SetVim(_("cannot save undo information"));
2543 vim_free(save);
2544 }
2545 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2546 {
2547 PyErr_SetVim(_("cannot replace line"));
2548 vim_free(save);
2549 }
2550 else
2551 changed_bytes((linenr_T)n, 0);
2552
2553 curbuf = savebuf;
2554
Bram Moolenaar454ec052007-03-08 09:20:28 +00002555 /* Check that the cursor is not beyond the end of the line now. */
2556 if (buf == curwin->w_buffer)
2557 check_cursor_col();
2558
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 if (PyErr_Occurred() || VimErrorCheck())
2560 return FAIL;
2561
2562 if (len_change)
2563 *len_change = 0;
2564
2565 return OK;
2566 }
2567 else
2568 {
2569 PyErr_BadArgument();
2570 return FAIL;
2571 }
2572}
2573
2574/* Replace a range of lines in the specified buffer. The line numbers are in
2575 * Vim format (1-based). The range is from lo up to, but not including, hi.
2576 * The replacement lines are given as a Python list of string objects. The
2577 * list is checked for validity and correct format. Errors are returned as a
2578 * value of FAIL. The return value is OK on success.
2579 * If OK is returned and len_change is not NULL, *len_change
2580 * is set to the change in the buffer length.
2581 */
2582 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002583SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584{
2585 /* First of all, we check the thpe of the supplied Python object.
2586 * There are three cases:
2587 * 1. NULL, or None - this is a deletion.
2588 * 2. A list - this is a replacement.
2589 * 3. Anything else - this is an error.
2590 */
2591 if (list == Py_None || list == NULL)
2592 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002593 PyInt i;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002594 PyInt n = (int)(hi - lo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 buf_T *savebuf = curbuf;
2596
2597 PyErr_Clear();
2598 curbuf = buf;
2599
2600 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2601 PyErr_SetVim(_("cannot save undo information"));
2602 else
2603 {
2604 for (i = 0; i < n; ++i)
2605 {
2606 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2607 {
2608 PyErr_SetVim(_("cannot delete line"));
2609 break;
2610 }
2611 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002613 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002614 deleted_lines_mark((linenr_T)lo, (long)i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 }
2616
2617 curbuf = savebuf;
2618
2619 if (PyErr_Occurred() || VimErrorCheck())
2620 return FAIL;
2621
2622 if (len_change)
2623 *len_change = -n;
2624
2625 return OK;
2626 }
2627 else if (PyList_Check(list))
2628 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002629 PyInt i;
2630 PyInt new_len = PyList_Size(list);
2631 PyInt old_len = hi - lo;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002632 PyInt extra = 0; /* lines added to text, can be negative */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633 char **array;
2634 buf_T *savebuf;
2635
2636 if (new_len == 0) /* avoid allocating zero bytes */
2637 array = NULL;
2638 else
2639 {
2640 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2641 if (array == NULL)
2642 {
2643 PyErr_NoMemory();
2644 return FAIL;
2645 }
2646 }
2647
2648 for (i = 0; i < new_len; ++i)
2649 {
2650 PyObject *line = PyList_GetItem(list, i);
2651
2652 array[i] = StringToLine(line);
2653 if (array[i] == NULL)
2654 {
2655 while (i)
2656 vim_free(array[--i]);
2657 vim_free(array);
2658 return FAIL;
2659 }
2660 }
2661
2662 savebuf = curbuf;
2663
2664 PyErr_Clear();
2665 curbuf = buf;
2666
2667 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2668 PyErr_SetVim(_("cannot save undo information"));
2669
2670 /* If the size of the range is reducing (ie, new_len < old_len) we
2671 * need to delete some old_len. We do this at the start, by
2672 * repeatedly deleting line "lo".
2673 */
2674 if (!PyErr_Occurred())
2675 {
2676 for (i = 0; i < old_len - new_len; ++i)
2677 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2678 {
2679 PyErr_SetVim(_("cannot delete line"));
2680 break;
2681 }
2682 extra -= i;
2683 }
2684
2685 /* For as long as possible, replace the existing old_len with the
2686 * new old_len. This is a more efficient operation, as it requires
2687 * less memory allocation and freeing.
2688 */
2689 if (!PyErr_Occurred())
2690 {
2691 for (i = 0; i < old_len && i < new_len; ++i)
2692 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2693 == FAIL)
2694 {
2695 PyErr_SetVim(_("cannot replace line"));
2696 break;
2697 }
2698 }
2699 else
2700 i = 0;
2701
2702 /* Now we may need to insert the remaining new old_len. If we do, we
2703 * must free the strings as we finish with them (we can't pass the
2704 * responsibility to vim in this case).
2705 */
2706 if (!PyErr_Occurred())
2707 {
2708 while (i < new_len)
2709 {
2710 if (ml_append((linenr_T)(lo + i - 1),
2711 (char_u *)array[i], 0, FALSE) == FAIL)
2712 {
2713 PyErr_SetVim(_("cannot insert line"));
2714 break;
2715 }
2716 vim_free(array[i]);
2717 ++i;
2718 ++extra;
2719 }
2720 }
2721
2722 /* Free any left-over old_len, as a result of an error */
2723 while (i < new_len)
2724 {
2725 vim_free(array[i]);
2726 ++i;
2727 }
2728
2729 /* Free the array of old_len. All of its contents have now
2730 * been dealt with (either freed, or the responsibility passed
2731 * to vim.
2732 */
2733 vim_free(array);
2734
2735 /* Adjust marks. Invalidate any which lie in the
2736 * changed range, and move any in the remainder of the buffer.
2737 */
2738 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2739 (long)MAXLNUM, (long)extra);
2740 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2741
2742 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002743 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744
2745 curbuf = savebuf;
2746
2747 if (PyErr_Occurred() || VimErrorCheck())
2748 return FAIL;
2749
2750 if (len_change)
2751 *len_change = new_len - old_len;
2752
2753 return OK;
2754 }
2755 else
2756 {
2757 PyErr_BadArgument();
2758 return FAIL;
2759 }
2760}
2761
2762/* Insert a number of lines into the specified buffer after the specifed line.
2763 * The line number is in Vim format (1-based). The lines to be inserted are
2764 * given as a Python list of string objects or as a single string. The lines
2765 * to be added are checked for validity and correct format. Errors are
2766 * returned as a value of FAIL. The return value is OK on success.
2767 * If OK is returned and len_change is not NULL, *len_change
2768 * is set to the change in the buffer length.
2769 */
2770 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002771InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772{
2773 /* First of all, we check the type of the supplied Python object.
2774 * It must be a string or a list, or the call is in error.
2775 */
2776 if (PyString_Check(lines))
2777 {
2778 char *str = StringToLine(lines);
2779 buf_T *savebuf;
2780
2781 if (str == NULL)
2782 return FAIL;
2783
2784 savebuf = curbuf;
2785
2786 PyErr_Clear();
2787 curbuf = buf;
2788
2789 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2790 PyErr_SetVim(_("cannot save undo information"));
2791 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2792 PyErr_SetVim(_("cannot insert line"));
2793 else
2794 appended_lines_mark((linenr_T)n, 1L);
2795
2796 vim_free(str);
2797 curbuf = savebuf;
2798 update_screen(VALID);
2799
2800 if (PyErr_Occurred() || VimErrorCheck())
2801 return FAIL;
2802
2803 if (len_change)
2804 *len_change = 1;
2805
2806 return OK;
2807 }
2808 else if (PyList_Check(lines))
2809 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002810 PyInt i;
2811 PyInt size = PyList_Size(lines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812 char **array;
2813 buf_T *savebuf;
2814
2815 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2816 if (array == NULL)
2817 {
2818 PyErr_NoMemory();
2819 return FAIL;
2820 }
2821
2822 for (i = 0; i < size; ++i)
2823 {
2824 PyObject *line = PyList_GetItem(lines, i);
2825 array[i] = StringToLine(line);
2826
2827 if (array[i] == NULL)
2828 {
2829 while (i)
2830 vim_free(array[--i]);
2831 vim_free(array);
2832 return FAIL;
2833 }
2834 }
2835
2836 savebuf = curbuf;
2837
2838 PyErr_Clear();
2839 curbuf = buf;
2840
2841 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2842 PyErr_SetVim(_("cannot save undo information"));
2843 else
2844 {
2845 for (i = 0; i < size; ++i)
2846 {
2847 if (ml_append((linenr_T)(n + i),
2848 (char_u *)array[i], 0, FALSE) == FAIL)
2849 {
2850 PyErr_SetVim(_("cannot insert line"));
2851
2852 /* Free the rest of the lines */
2853 while (i < size)
2854 vim_free(array[i++]);
2855
2856 break;
2857 }
2858 vim_free(array[i]);
2859 }
2860 if (i > 0)
2861 appended_lines_mark((linenr_T)n, (long)i);
2862 }
2863
2864 /* Free the array of lines. All of its contents have now
2865 * been freed.
2866 */
2867 vim_free(array);
2868
2869 curbuf = savebuf;
2870 update_screen(VALID);
2871
2872 if (PyErr_Occurred() || VimErrorCheck())
2873 return FAIL;
2874
2875 if (len_change)
2876 *len_change = size;
2877
2878 return OK;
2879 }
2880 else
2881 {
2882 PyErr_BadArgument();
2883 return FAIL;
2884 }
2885}
2886
2887/* Convert a Vim line into a Python string.
2888 * All internal newlines are replaced by null characters.
2889 *
2890 * On errors, the Python exception data is set, and NULL is returned.
2891 */
2892 static PyObject *
2893LineToString(const char *str)
2894{
2895 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002896 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 char *p;
2898
2899 /* Allocate an Python string object, with uninitialised contents. We
2900 * must do it this way, so that we can modify the string in place
2901 * later. See the Python source, Objects/stringobject.c for details.
2902 */
2903 result = PyString_FromStringAndSize(NULL, len);
2904 if (result == NULL)
2905 return NULL;
2906
2907 p = PyString_AsString(result);
2908
2909 while (*str)
2910 {
2911 if (*str == '\n')
2912 *p = '\0';
2913 else
2914 *p = *str;
2915
2916 ++p;
2917 ++str;
2918 }
2919
2920 return result;
2921}
2922
2923/* Convert a Python string into a Vim line.
2924 *
2925 * The result is in allocated memory. All internal nulls are replaced by
2926 * newline characters. It is an error for the string to contain newline
2927 * characters.
2928 *
2929 * On errors, the Python exception data is set, and NULL is returned.
2930 */
2931 static char *
2932StringToLine(PyObject *obj)
2933{
2934 const char *str;
2935 char *save;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002936 PyInt len;
2937 PyInt i;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002938 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939
2940 if (obj == NULL || !PyString_Check(obj))
2941 {
2942 PyErr_BadArgument();
2943 return NULL;
2944 }
2945
2946 str = PyString_AsString(obj);
2947 len = PyString_Size(obj);
2948
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002949 /*
2950 * Error checking: String must not contain newlines, as we
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 * are replacing a single line, and we must replace it with
2952 * a single line.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002953 * A trailing newline is removed, so that append(f.readlines()) works.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002954 */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002955 p = memchr(str, '\n', len);
2956 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002958 if (p == str + len - 1)
2959 --len;
2960 else
2961 {
2962 PyErr_SetVim(_("string cannot contain newlines"));
2963 return NULL;
2964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 }
2966
2967 /* Create a copy of the string, with internal nulls replaced by
2968 * newline characters, as is the vim convention.
2969 */
2970 save = (char *)alloc((unsigned)(len+1));
2971 if (save == NULL)
2972 {
2973 PyErr_NoMemory();
2974 return NULL;
2975 }
2976
2977 for (i = 0; i < len; ++i)
2978 {
2979 if (str[i] == '\0')
2980 save[i] = '\n';
2981 else
2982 save[i] = str[i];
2983 }
2984
2985 save[i] = '\0';
2986
2987 return save;
2988}
2989
2990/* Check to see whether a Vim error has been reported, or a keyboard
2991 * interrupt has been detected.
2992 */
2993 static int
2994VimErrorCheck(void)
2995{
2996 if (got_int)
2997 {
2998 PyErr_SetNone(PyExc_KeyboardInterrupt);
2999 return 1;
3000 }
3001 else if (did_emsg && !PyErr_Occurred())
3002 {
3003 PyErr_SetNone(VimError);
3004 return 1;
3005 }
3006
3007 return 0;
3008}
3009
3010
3011/* Don't generate a prototype for the next function, it generates an error on
3012 * newer Python versions. */
3013#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3014
3015 char *
3016Py_GetProgramName(void)
3017{
3018 return "vim";
3019}
3020#endif /* Python 1.4 */