blob: 95be357245e363aa70aac2cba7a4f5d7e54f8370 [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
Bram Moolenaar860cae12010-06-05 23:22:07 +020029#if defined(_WIN32) && defined(HAVE_FCNTL_H)
Bram Moolenaar071d4272004-06-13 20:20:40 +000030# 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 Moolenaarfa5d1e62010-07-22 21:44:13 +020099#ifndef WIN3264
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200100# include <dlfcn.h>
101# define FARPROC void*
102# define HINSTANCE void*
Bram Moolenaarfa5d1e62010-07-22 21:44:13 +0200103# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200104# define close_dll dlclose
105# define symbol_from_dll dlsym
106#else
107# define load_dll LoadLibrary
108# define close_dll FreeLibrary
109# define symbol_from_dll GetProcAddress
110#endif
111
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000112/* This makes if_python.c compile without warnings against Python 2.5
113 * on Win32 and Win64. */
114#undef PyRun_SimpleString
115#undef PyArg_Parse
116#undef PyArg_ParseTuple
117#undef Py_BuildValue
118#undef Py_InitModule4
119#undef Py_InitModule4_64
120
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121/*
122 * Wrapper defines
123 */
124# define PyArg_Parse dll_PyArg_Parse
125# define PyArg_ParseTuple dll_PyArg_ParseTuple
126# define PyDict_SetItemString dll_PyDict_SetItemString
127# define PyErr_BadArgument dll_PyErr_BadArgument
128# define PyErr_Clear dll_PyErr_Clear
129# define PyErr_NoMemory dll_PyErr_NoMemory
130# define PyErr_Occurred dll_PyErr_Occurred
131# define PyErr_SetNone dll_PyErr_SetNone
132# define PyErr_SetString dll_PyErr_SetString
133# define PyEval_InitThreads dll_PyEval_InitThreads
134# define PyEval_RestoreThread dll_PyEval_RestoreThread
135# define PyEval_SaveThread dll_PyEval_SaveThread
136# ifdef PY_CAN_RECURSE
137# define PyGILState_Ensure dll_PyGILState_Ensure
138# define PyGILState_Release dll_PyGILState_Release
139# endif
140# define PyInt_AsLong dll_PyInt_AsLong
141# define PyInt_FromLong dll_PyInt_FromLong
142# define PyInt_Type (*dll_PyInt_Type)
143# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000144# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145# define PyList_New dll_PyList_New
146# define PyList_SetItem dll_PyList_SetItem
147# define PyList_Size dll_PyList_Size
148# define PyList_Type (*dll_PyList_Type)
149# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000150# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000151# define PyDict_GetItemString dll_PyDict_GetItemString
152# define PyModule_GetDict dll_PyModule_GetDict
153# define PyRun_SimpleString dll_PyRun_SimpleString
154# define PyString_AsString dll_PyString_AsString
155# define PyString_FromString dll_PyString_FromString
156# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
157# define PyString_Size dll_PyString_Size
158# define PyString_Type (*dll_PyString_Type)
159# define PySys_SetObject dll_PySys_SetObject
160# define PySys_SetArgv dll_PySys_SetArgv
161# define PyType_Type (*dll_PyType_Type)
162# define Py_BuildValue dll_Py_BuildValue
163# define Py_FindMethod dll_Py_FindMethod
164# define Py_InitModule4 dll_Py_InitModule4
165# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000166# define Py_Finalize dll_Py_Finalize
167# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168# define _PyObject_New dll__PyObject_New
169# define _Py_NoneStruct (*dll__Py_NoneStruct)
170# define PyObject_Init dll__PyObject_Init
171# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
172# define PyType_IsSubtype dll_PyType_IsSubtype
173# endif
174# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
175# define PyObject_Malloc dll_PyObject_Malloc
176# define PyObject_Free dll_PyObject_Free
177# endif
178
179/*
180 * Pointers for dynamic link
181 */
182static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
183static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
184static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
185static int(*dll_PyErr_BadArgument)(void);
186static void(*dll_PyErr_Clear)(void);
187static PyObject*(*dll_PyErr_NoMemory)(void);
188static PyObject*(*dll_PyErr_Occurred)(void);
189static void(*dll_PyErr_SetNone)(PyObject *);
190static void(*dll_PyErr_SetString)(PyObject *, const char *);
191static void(*dll_PyEval_InitThreads)(void);
192static void(*dll_PyEval_RestoreThread)(PyThreadState *);
193static PyThreadState*(*dll_PyEval_SaveThread)(void);
194# ifdef PY_CAN_RECURSE
195static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
196static void (*dll_PyGILState_Release)(PyGILState_STATE);
197#endif
198static long(*dll_PyInt_AsLong)(PyObject *);
199static PyObject*(*dll_PyInt_FromLong)(long);
200static PyTypeObject* dll_PyInt_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000201static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000202static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000203static PyObject*(*dll_PyList_New)(PyInt size);
204static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
205static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000206static PyTypeObject* dll_PyList_Type;
207static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000208static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
210static PyObject*(*dll_PyModule_GetDict)(PyObject *);
211static int(*dll_PyRun_SimpleString)(char *);
212static char*(*dll_PyString_AsString)(PyObject *);
213static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000214static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
215static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216static PyTypeObject* dll_PyString_Type;
217static int(*dll_PySys_SetObject)(char *, PyObject *);
218static int(*dll_PySys_SetArgv)(int, char **);
219static PyTypeObject* dll_PyType_Type;
220static PyObject*(*dll_Py_BuildValue)(char *, ...);
221static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
222static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
223static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000224static void(*dll_Py_Finalize)(void);
225static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000226static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
227static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
228static PyObject* dll__Py_NoneStruct;
229# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
230static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
231# endif
232# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
233static void* (*dll_PyObject_Malloc)(size_t);
234static void (*dll_PyObject_Free)(void*);
235# endif
236
237static HINSTANCE hinstPython = 0; /* Instance of python.dll */
238
239/* Imported exception objects */
240static PyObject *imp_PyExc_AttributeError;
241static PyObject *imp_PyExc_IndexError;
242static PyObject *imp_PyExc_KeyboardInterrupt;
243static PyObject *imp_PyExc_TypeError;
244static PyObject *imp_PyExc_ValueError;
245
246# define PyExc_AttributeError imp_PyExc_AttributeError
247# define PyExc_IndexError imp_PyExc_IndexError
248# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
249# define PyExc_TypeError imp_PyExc_TypeError
250# define PyExc_ValueError imp_PyExc_ValueError
251
252/*
253 * Table of name to function pointer of python.
254 */
255# define PYTHON_PROC FARPROC
256static struct
257{
258 char *name;
259 PYTHON_PROC *ptr;
260} python_funcname_table[] =
261{
262 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
263 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
264 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
265 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
266 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
267 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
268 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
269 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
270 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
271 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
272 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
273 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
274# ifdef PY_CAN_RECURSE
275 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
276 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
277# endif
278 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
279 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
280 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
281 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000282 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000283 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
284 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
285 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
286 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
287 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
288 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000289 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
291 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
292 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
293 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
294 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
295 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
296 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
297 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
298 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
299 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
300 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
301 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000302# if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
303 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
304# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000305 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000306# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000308 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
309 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000310 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
311 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
312 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
313# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
314 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
315# endif
316# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
317 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
318 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
319# endif
320 {"", NULL},
321};
322
323/*
324 * Free python.dll
325 */
326 static void
327end_dynamic_python(void)
328{
329 if (hinstPython)
330 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200331 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 hinstPython = 0;
333 }
334}
335
336/*
337 * Load library and get all pointers.
338 * Parameter 'libname' provides name of DLL.
339 * Return OK or FAIL.
340 */
341 static int
342python_runtime_link_init(char *libname, int verbose)
343{
344 int i;
345
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200346#if defined(UNIX) && defined(FEAT_PYTHON3)
347 /* Can't have Python and Python3 loaded at the same time, it may cause a
348 * crash. */
349 if (python3_loaded())
350 {
351 EMSG(_("E999: Python: Cannot use :py and :py3 in one session"));
352 return FAIL;
353 }
354#endif
355
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356 if (hinstPython)
357 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200358 hinstPython = load_dll(libname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359 if (!hinstPython)
360 {
361 if (verbose)
362 EMSG2(_(e_loadlib), libname);
363 return FAIL;
364 }
365
366 for (i = 0; python_funcname_table[i].ptr; ++i)
367 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200368 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 python_funcname_table[i].name)) == NULL)
370 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200371 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372 hinstPython = 0;
373 if (verbose)
374 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
375 return FAIL;
376 }
377 }
378 return OK;
379}
380
381/*
382 * If python is enabled (there is installed python on Windows system) return
383 * TRUE, else FALSE.
384 */
385 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000386python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387{
388 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
389}
390
391/* Load the standard Python exceptions - don't import the symbols from the
392 * DLL, as this can cause errors (importing data symbols is not reliable).
393 */
394static void get_exceptions __ARGS((void));
395
396 static void
397get_exceptions()
398{
399 PyObject *exmod = PyImport_ImportModule("exceptions");
400 PyObject *exdict = PyModule_GetDict(exmod);
401 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
402 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
403 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
404 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
405 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
406 Py_XINCREF(imp_PyExc_AttributeError);
407 Py_XINCREF(imp_PyExc_IndexError);
408 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
409 Py_XINCREF(imp_PyExc_TypeError);
410 Py_XINCREF(imp_PyExc_ValueError);
411 Py_XDECREF(exmod);
412}
413#endif /* DYNAMIC_PYTHON */
414
415/******************************************************
416 * Internal function prototypes.
417 */
418
419static void DoPythonCommand(exarg_T *, const char *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000420static PyInt RangeStart;
421static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000422
423static void PythonIO_Flush(void);
424static int PythonIO_Init(void);
425static int PythonMod_Init(void);
426
427/* Utility functions for the vim/python interface
428 * ----------------------------------------------
429 */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000430static PyObject *GetBufferLine(buf_T *, PyInt);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000431static PyObject *GetBufferLineList(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000433static int SetBufferLine(buf_T *, PyInt, PyObject *, PyInt *);
434static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
435static int InsertBufferLines(buf_T *, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436
437static PyObject *LineToString(const char *);
438static char *StringToLine(PyObject *);
439
440static int VimErrorCheck(void);
441
442#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
443
444/******************************************************
445 * 1. Python interpreter main program.
446 */
447
448static int initialised = 0;
449
450#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
451typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000452#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000454#ifdef PY_CAN_RECURSE
455static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
456#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000457static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000458#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
460/*
461 * Suspend a thread of the Python interpreter, other threads are allowed to
462 * run.
463 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000464 static void
465Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000466{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000467#ifdef PY_CAN_RECURSE
468 PyGILState_Release(pygilstate);
469#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000471#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472}
473
474/*
475 * Restore a thread of the Python interpreter, waits for other threads to
476 * block.
477 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000478 static void
479Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000481#ifdef PY_CAN_RECURSE
482 pygilstate = PyGILState_Ensure();
483#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 PyEval_RestoreThread(saved_python_thread);
485 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000487}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488
489/*
490 * obtain a lock on the Vim data structures
491 */
492static void Python_Lock_Vim(void)
493{
494}
495
496/*
497 * release a lock on the Vim data structures
498 */
499static void Python_Release_Vim(void)
500{
501}
502
503 void
504python_end()
505{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000506 static int recurse = 0;
507
508 /* If a crash occurs while doing this, don't try again. */
509 if (recurse != 0)
510 return;
511
512 ++recurse;
513
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000515 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000516 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000517 Python_RestoreThread(); /* enter python */
518 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000519 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000521#else
522 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000523 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000524 Python_RestoreThread(); /* enter python */
525 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000528
529 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530}
531
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200532#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
533 int
534python_loaded()
535{
536 return (hinstPython != 0);
537}
538#endif
539
Bram Moolenaar071d4272004-06-13 20:20:40 +0000540 static int
541Python_Init(void)
542{
543 if (!initialised)
544 {
545#ifdef DYNAMIC_PYTHON
546 if (!python_enabled(TRUE))
547 {
548 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
549 goto fail;
550 }
551#endif
552
553#if !defined(MACOS) || defined(MACOS_X_UNIX)
554 Py_Initialize();
555#else
556 PyMac_Initialize();
557#endif
558 /* initialise threads */
559 PyEval_InitThreads();
560
561#ifdef DYNAMIC_PYTHON
562 get_exceptions();
563#endif
564
565 if (PythonIO_Init())
566 goto fail;
567
568 if (PythonMod_Init())
569 goto fail;
570
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000571 /* Remove the element from sys.path that was added because of our
572 * argv[0] value in PythonMod_Init(). Previously we used an empty
573 * string, but dependinding on the OS we then get an empty entry or
574 * the current directory in sys.path. */
575 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
576
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000577 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579
580 initialised = 1;
581 }
582
583 return 0;
584
585fail:
586 /* We call PythonIO_Flush() here to print any Python errors.
587 * This is OK, as it is possible to call this function even
588 * if PythonIO_Init() has not completed successfully (it will
589 * not do anything in this case).
590 */
591 PythonIO_Flush();
592 return -1;
593}
594
595/*
596 * External interface
597 */
598 static void
599DoPythonCommand(exarg_T *eap, const char *cmd)
600{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000601#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602 static int recursive = 0;
603#endif
604#if defined(MACOS) && !defined(MACOS_X_UNIX)
605 GrafPtr oldPort;
606#endif
607#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
608 char *saved_locale;
609#endif
610
611#ifndef PY_CAN_RECURSE
612 if (recursive)
613 {
614 EMSG(_("E659: Cannot invoke Python recursively"));
615 return;
616 }
617 ++recursive;
618#endif
619
620#if defined(MACOS) && !defined(MACOS_X_UNIX)
621 GetPort(&oldPort);
622 /* Check if the Python library is available */
623 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
624 goto theend;
625#endif
626 if (Python_Init())
627 goto theend;
628
629 RangeStart = eap->line1;
630 RangeEnd = eap->line2;
631 Python_Release_Vim(); /* leave vim */
632
633#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
634 /* Python only works properly when the LC_NUMERIC locale is "C". */
635 saved_locale = setlocale(LC_NUMERIC, NULL);
636 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
637 saved_locale = NULL;
638 else
639 {
640 /* Need to make a copy, value may change when setting new locale. */
641 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
642 (void)setlocale(LC_NUMERIC, "C");
643 }
644#endif
645
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647
648 PyRun_SimpleString((char *)(cmd));
649
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651
652#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
653 if (saved_locale != NULL)
654 {
655 (void)setlocale(LC_NUMERIC, saved_locale);
656 vim_free(saved_locale);
657 }
658#endif
659
660 Python_Lock_Vim(); /* enter vim */
661 PythonIO_Flush();
662#if defined(MACOS) && !defined(MACOS_X_UNIX)
663 SetPort(oldPort);
664#endif
665
666theend:
667#ifndef PY_CAN_RECURSE
668 --recursive;
669#endif
670 return; /* keeps lint happy */
671}
672
673/*
674 * ":python"
675 */
676 void
677ex_python(exarg_T *eap)
678{
679 char_u *script;
680
681 script = script_get(eap, eap->arg);
682 if (!eap->skip)
683 {
684 if (script == NULL)
685 DoPythonCommand(eap, (char *)eap->arg);
686 else
687 DoPythonCommand(eap, (char *)script);
688 }
689 vim_free(script);
690}
691
692#define BUFFER_SIZE 1024
693
694/*
695 * ":pyfile"
696 */
697 void
698ex_pyfile(exarg_T *eap)
699{
700 static char buffer[BUFFER_SIZE];
701 const char *file = (char *)eap->arg;
702 char *p;
703
704 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
705 * stdio file pointer, but Vim and the Python DLL are compiled with
706 * different options under Windows, meaning that stdio pointers aren't
707 * compatible between the two. Yuk.
708 *
709 * Put the string "execfile('file')" into buffer. But, we need to
710 * escape any backslashes or single quotes in the file name, so that
711 * Python won't mangle the file name.
712 */
713 strcpy(buffer, "execfile('");
714 p = buffer + 10; /* size of "execfile('" */
715
716 while (*file && p < buffer + (BUFFER_SIZE - 3))
717 {
718 if (*file == '\\' || *file == '\'')
719 *p++ = '\\';
720 *p++ = *file++;
721 }
722
723 /* If we didn't finish the file name, we hit a buffer overflow */
724 if (*file != '\0')
725 return;
726
727 /* Put in the terminating "')" and a null */
728 *p++ = '\'';
729 *p++ = ')';
730 *p++ = '\0';
731
732 /* Execute the file */
733 DoPythonCommand(eap, buffer);
734}
735
736/******************************************************
737 * 2. Python output stream: writes output via [e]msg().
738 */
739
740/* Implementation functions
741 */
742
743static PyObject *OutputGetattr(PyObject *, char *);
744static int OutputSetattr(PyObject *, char *, PyObject *);
745
746static PyObject *OutputWrite(PyObject *, PyObject *);
747static PyObject *OutputWritelines(PyObject *, PyObject *);
748
749typedef void (*writefn)(char_u *);
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000750static void writer(writefn fn, char_u *str, PyInt n);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751
752/* Output object definition
753 */
754
755typedef struct
756{
757 PyObject_HEAD
758 long softspace;
759 long error;
760} OutputObject;
761
762static struct PyMethodDef OutputMethods[] = {
763 /* name, function, calling, documentation */
764 {"write", OutputWrite, 1, "" },
765 {"writelines", OutputWritelines, 1, "" },
766 { NULL, NULL, 0, NULL }
767};
768
769static PyTypeObject OutputType = {
770 PyObject_HEAD_INIT(0)
771 0,
772 "message",
773 sizeof(OutputObject),
774 0,
775
776 (destructor) 0,
777 (printfunc) 0,
778 (getattrfunc) OutputGetattr,
779 (setattrfunc) OutputSetattr,
780 (cmpfunc) 0,
781 (reprfunc) 0,
782
783 0, /* as number */
784 0, /* as sequence */
785 0, /* as mapping */
786
787 (hashfunc) 0,
788 (ternaryfunc) 0,
789 (reprfunc) 0
790};
791
792/*************/
793
794 static PyObject *
795OutputGetattr(PyObject *self, char *name)
796{
797 if (strcmp(name, "softspace") == 0)
798 return PyInt_FromLong(((OutputObject *)(self))->softspace);
799
800 return Py_FindMethod(OutputMethods, self, name);
801}
802
803 static int
804OutputSetattr(PyObject *self, char *name, PyObject *val)
805{
806 if (val == NULL) {
807 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
808 return -1;
809 }
810
811 if (strcmp(name, "softspace") == 0)
812 {
813 if (!PyInt_Check(val)) {
814 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
815 return -1;
816 }
817
818 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
819 return 0;
820 }
821
822 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
823 return -1;
824}
825
826/*************/
827
828 static PyObject *
829OutputWrite(PyObject *self, PyObject *args)
830{
831 int len;
832 char *str;
833 int error = ((OutputObject *)(self))->error;
834
835 if (!PyArg_ParseTuple(args, "s#", &str, &len))
836 return NULL;
837
838 Py_BEGIN_ALLOW_THREADS
839 Python_Lock_Vim();
840 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
841 Python_Release_Vim();
842 Py_END_ALLOW_THREADS
843
844 Py_INCREF(Py_None);
845 return Py_None;
846}
847
848 static PyObject *
849OutputWritelines(PyObject *self, PyObject *args)
850{
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000851 PyInt n;
852 PyInt i;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 PyObject *list;
854 int error = ((OutputObject *)(self))->error;
855
856 if (!PyArg_ParseTuple(args, "O", &list))
857 return NULL;
858 Py_INCREF(list);
859
860 if (!PyList_Check(list)) {
861 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
862 Py_DECREF(list);
863 return NULL;
864 }
865
866 n = PyList_Size(list);
867
868 for (i = 0; i < n; ++i)
869 {
870 PyObject *line = PyList_GetItem(list, i);
871 char *str;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000872 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873
874 if (!PyArg_Parse(line, "s#", &str, &len)) {
875 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
876 Py_DECREF(list);
877 return NULL;
878 }
879
880 Py_BEGIN_ALLOW_THREADS
881 Python_Lock_Vim();
882 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
883 Python_Release_Vim();
884 Py_END_ALLOW_THREADS
885 }
886
887 Py_DECREF(list);
888 Py_INCREF(Py_None);
889 return Py_None;
890}
891
892/* Output buffer management
893 */
894
895static char_u *buffer = NULL;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000896static PyInt buffer_len = 0;
897static PyInt buffer_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898
899static writefn old_fn = NULL;
900
901 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000902buffer_ensure(PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000904 PyInt new_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905 char_u *new_buffer;
906
907 if (n < buffer_size)
908 return;
909
910 new_size = buffer_size;
911 while (new_size < n)
912 new_size += 80;
913
914 if (new_size != buffer_size)
915 {
916 new_buffer = alloc((unsigned)new_size);
917 if (new_buffer == NULL)
918 return;
919
920 if (buffer)
921 {
922 memcpy(new_buffer, buffer, buffer_len);
923 vim_free(buffer);
924 }
925
926 buffer = new_buffer;
927 buffer_size = new_size;
928 }
929}
930
931 static void
932PythonIO_Flush(void)
933{
934 if (old_fn && buffer_len)
935 {
936 buffer[buffer_len] = 0;
937 old_fn(buffer);
938 }
939
940 buffer_len = 0;
941}
942
943 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000944writer(writefn fn, char_u *str, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945{
946 char_u *ptr;
947
948 if (fn != old_fn && old_fn != NULL)
949 PythonIO_Flush();
950
951 old_fn = fn;
952
953 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
954 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000955 PyInt len = ptr - str;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956
957 buffer_ensure(buffer_len + len + 1);
958
959 memcpy(buffer + buffer_len, str, len);
960 buffer_len += len;
961 buffer[buffer_len] = 0;
962 fn(buffer);
963 str = ptr + 1;
964 n -= len + 1;
965 buffer_len = 0;
966 }
967
968 /* Put the remaining text into the buffer for later printing */
969 buffer_ensure(buffer_len + n + 1);
970 memcpy(buffer + buffer_len, str, n);
971 buffer_len += n;
972}
973
974/***************/
975
976static OutputObject Output =
977{
978 PyObject_HEAD_INIT(&OutputType)
979 0,
980 0
981};
982
983static OutputObject Error =
984{
985 PyObject_HEAD_INIT(&OutputType)
986 0,
987 1
988};
989
990 static int
991PythonIO_Init(void)
992{
993 /* Fixups... */
994 OutputType.ob_type = &PyType_Type;
995
Bram Moolenaar7df2d662005-01-25 22:18:08 +0000996 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
997 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998
999 if (PyErr_Occurred())
1000 {
1001 EMSG(_("E264: Python: Error initialising I/O objects"));
1002 return -1;
1003 }
1004
1005 return 0;
1006}
1007
1008/******************************************************
1009 * 3. Implementation of the Vim module for Python
1010 */
1011
1012/* Vim module - Implementation functions
1013 * -------------------------------------
1014 */
1015
1016static PyObject *VimError;
1017
1018static PyObject *VimCommand(PyObject *, PyObject *);
1019static PyObject *VimEval(PyObject *, PyObject *);
1020
1021/* Window type - Implementation functions
1022 * --------------------------------------
1023 */
1024
1025typedef struct
1026{
1027 PyObject_HEAD
1028 win_T *win;
1029}
1030WindowObject;
1031
1032#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1033
1034#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1035
1036static PyObject *WindowNew(win_T *);
1037
1038static void WindowDestructor(PyObject *);
1039static PyObject *WindowGetattr(PyObject *, char *);
1040static int WindowSetattr(PyObject *, char *, PyObject *);
1041static PyObject *WindowRepr(PyObject *);
1042
1043/* Buffer type - Implementation functions
1044 * --------------------------------------
1045 */
1046
1047typedef struct
1048{
1049 PyObject_HEAD
1050 buf_T *buf;
1051}
1052BufferObject;
1053
1054#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
1055
1056#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1057
1058static PyObject *BufferNew (buf_T *);
1059
1060static void BufferDestructor(PyObject *);
1061static PyObject *BufferGetattr(PyObject *, char *);
1062static PyObject *BufferRepr(PyObject *);
1063
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001064static PyInt BufferLength(PyObject *);
1065static PyObject *BufferItem(PyObject *, PyInt);
1066static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1067static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1068static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069
1070static PyObject *BufferAppend(PyObject *, PyObject *);
1071static PyObject *BufferMark(PyObject *, PyObject *);
1072static PyObject *BufferRange(PyObject *, PyObject *);
1073
1074/* Line range type - Implementation functions
1075 * --------------------------------------
1076 */
1077
1078typedef struct
1079{
1080 PyObject_HEAD
1081 BufferObject *buf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001082 PyInt start;
1083 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084}
1085RangeObject;
1086
1087#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1088
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001089static PyObject *RangeNew(buf_T *, PyInt, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090
1091static void RangeDestructor(PyObject *);
1092static PyObject *RangeGetattr(PyObject *, char *);
1093static PyObject *RangeRepr(PyObject *);
1094
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001095static PyInt RangeLength(PyObject *);
1096static PyObject *RangeItem(PyObject *, PyInt);
1097static PyObject *RangeSlice(PyObject *, PyInt, PyInt);
1098static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1099static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100
1101static PyObject *RangeAppend(PyObject *, PyObject *);
1102
1103/* Window list type - Implementation functions
1104 * -------------------------------------------
1105 */
1106
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001107static PyInt WinListLength(PyObject *);
1108static PyObject *WinListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109
1110/* Buffer list type - Implementation functions
1111 * -------------------------------------------
1112 */
1113
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001114static PyInt BufListLength(PyObject *);
1115static PyObject *BufListItem(PyObject *, PyInt);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116
1117/* Current objects type - Implementation functions
1118 * -----------------------------------------------
1119 */
1120
1121static PyObject *CurrentGetattr(PyObject *, char *);
1122static int CurrentSetattr(PyObject *, char *, PyObject *);
1123
1124/* Vim module - Definitions
1125 */
1126
1127static struct PyMethodDef VimMethods[] = {
1128 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001129 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
1130 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131 { NULL, NULL, 0, NULL }
1132};
1133
1134/* Vim module - Implementation
1135 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001137VimCommand(PyObject *self UNUSED, PyObject *args)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138{
1139 char *cmd;
1140 PyObject *result;
1141
1142 if (!PyArg_ParseTuple(args, "s", &cmd))
1143 return NULL;
1144
1145 PyErr_Clear();
1146
1147 Py_BEGIN_ALLOW_THREADS
1148 Python_Lock_Vim();
1149
1150 do_cmdline_cmd((char_u *)cmd);
1151 update_screen(VALID);
1152
1153 Python_Release_Vim();
1154 Py_END_ALLOW_THREADS
1155
1156 if (VimErrorCheck())
1157 result = NULL;
1158 else
1159 result = Py_None;
1160
1161 Py_XINCREF(result);
1162 return result;
1163}
1164
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001165#ifdef FEAT_EVAL
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001166/*
1167 * Function to translate a typval_T into a PyObject; this will recursively
1168 * translate lists/dictionaries into their Python equivalents.
1169 *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001170 * The depth parameter is to avoid infinite recursion, set it to 1 when
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001171 * you call VimToPython.
1172 */
1173 static PyObject *
1174VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1175{
1176 PyObject *result;
1177 PyObject *newObj;
1178 char ptrBuf[NUMBUFLEN];
1179
1180 /* Avoid infinite recursion */
1181 if (depth > 100)
1182 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001183 Py_INCREF(Py_None);
1184 result = Py_None;
1185 return result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001186 }
1187
1188 /* Check if we run into a recursive loop. The item must be in lookupDict
1189 * then and we can use it again. */
Bram Moolenaard72b3862009-01-13 17:11:05 +00001190 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1191 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1192 {
1193 sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
Bram Moolenaarcc448b32010-07-14 16:52:17 +02001194 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
1195 : (long_u)our_tv->vval.v_dict);
Bram Moolenaard72b3862009-01-13 17:11:05 +00001196 result = PyDict_GetItemString(lookupDict, ptrBuf);
1197 if (result != NULL)
1198 {
1199 Py_INCREF(result);
1200 return result;
1201 }
1202 }
1203
1204 if (our_tv->v_type == VAR_STRING)
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001205 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001206 result = Py_BuildValue("s", our_tv->vval.v_string);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001207 }
1208 else if (our_tv->v_type == VAR_NUMBER)
1209 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001210 char buf[NUMBUFLEN];
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001211
1212 /* For backwards compatibility numbers are stored as strings. */
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001213 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1214 result = Py_BuildValue("s", buf);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001215 }
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001216# ifdef FEAT_FLOAT
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001217 else if (our_tv->v_type == VAR_FLOAT)
1218 {
1219 char buf[NUMBUFLEN];
1220
1221 sprintf(buf, "%f", our_tv->vval.v_float);
1222 result = Py_BuildValue("s", buf);
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001223 }
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001224# endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001225 else if (our_tv->v_type == VAR_LIST)
1226 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001227 list_T *list = our_tv->vval.v_list;
1228 listitem_T *curr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001229
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001230 result = PyList_New(0);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001231
1232 if (list != NULL)
1233 {
Bram Moolenaard72b3862009-01-13 17:11:05 +00001234 PyDict_SetItemString(lookupDict, ptrBuf, result);
1235
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001236 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1237 {
1238 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1239 PyList_Append(result, newObj);
1240 Py_DECREF(newObj);
1241 }
1242 }
1243 }
1244 else if (our_tv->v_type == VAR_DICT)
1245 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001246 result = PyDict_New();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001247
1248 if (our_tv->vval.v_dict != NULL)
1249 {
1250 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001251 long_u todo = ht->ht_used;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001252 hashitem_T *hi;
1253 dictitem_T *di;
1254
Bram Moolenaard72b3862009-01-13 17:11:05 +00001255 PyDict_SetItemString(lookupDict, ptrBuf, result);
1256
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001257 for (hi = ht->ht_array; todo > 0; ++hi)
1258 {
1259 if (!HASHITEM_EMPTY(hi))
1260 {
1261 --todo;
1262
1263 di = dict_lookup(hi);
1264 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1265 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1266 Py_DECREF(newObj);
1267 }
1268 }
1269 }
1270 }
1271 else
1272 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00001273 Py_INCREF(Py_None);
1274 result = Py_None;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001275 }
1276
1277 return result;
1278}
Bram Moolenaar01dd60c2008-07-24 14:24:48 +00001279#endif
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001280
Bram Moolenaar071d4272004-06-13 20:20:40 +00001281 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001282VimEval(PyObject *self UNUSED, PyObject *args)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283{
1284#ifdef FEAT_EVAL
1285 char *expr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001286 typval_T *our_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 PyObject *result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001288 PyObject *lookup_dict;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289
1290 if (!PyArg_ParseTuple(args, "s", &expr))
1291 return NULL;
1292
1293 Py_BEGIN_ALLOW_THREADS
1294 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001295 our_tv = eval_expr((char_u *)expr, NULL);
1296
Bram Moolenaar071d4272004-06-13 20:20:40 +00001297 Python_Release_Vim();
1298 Py_END_ALLOW_THREADS
1299
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001300 if (our_tv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301 {
1302 PyErr_SetVim(_("invalid expression"));
1303 return NULL;
1304 }
1305
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001306 /* Convert the Vim type into a Python type. Create a dictionary that's
1307 * used to check for recursive loops. */
1308 lookup_dict = PyDict_New();
1309 result = VimToPython(our_tv, 1, lookup_dict);
1310 Py_DECREF(lookup_dict);
1311
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312
1313 Py_BEGIN_ALLOW_THREADS
1314 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001315 free_tv(our_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 Python_Release_Vim();
1317 Py_END_ALLOW_THREADS
1318
1319 return result;
1320#else
1321 PyErr_SetVim(_("expressions disabled at compile time"));
1322 return NULL;
1323#endif
1324}
1325
1326/* Common routines for buffers and line ranges
1327 * -------------------------------------------
1328 */
1329 static int
1330CheckBuffer(BufferObject *this)
1331{
1332 if (this->buf == INVALID_BUFFER_VALUE)
1333 {
1334 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1335 return -1;
1336 }
1337
1338 return 0;
1339}
1340
1341 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001342RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343{
1344 if (CheckBuffer(self))
1345 return NULL;
1346
1347 if (n < 0 || n > end - start)
1348 {
1349 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1350 return NULL;
1351 }
1352
1353 return GetBufferLine(self->buf, n+start);
1354}
1355
1356 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001357RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001358{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001359 PyInt size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001360
1361 if (CheckBuffer(self))
1362 return NULL;
1363
1364 size = end - start + 1;
1365
1366 if (lo < 0)
1367 lo = 0;
1368 else if (lo > size)
1369 lo = size;
1370 if (hi < 0)
1371 hi = 0;
1372 if (hi < lo)
1373 hi = lo;
1374 else if (hi > size)
1375 hi = size;
1376
1377 return GetBufferLineList(self->buf, lo+start, hi+start);
1378}
1379
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001380 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001381RBAssItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001383 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384
1385 if (CheckBuffer(self))
1386 return -1;
1387
1388 if (n < 0 || n > end - start)
1389 {
1390 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1391 return -1;
1392 }
1393
1394 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1395 return -1;
1396
1397 if (new_end)
1398 *new_end = end + len_change;
1399
1400 return 0;
1401}
1402
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001403 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001404RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001406 PyInt size;
1407 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408
1409 /* Self must be a valid buffer */
1410 if (CheckBuffer(self))
1411 return -1;
1412
1413 /* Sort out the slice range */
1414 size = end - start + 1;
1415
1416 if (lo < 0)
1417 lo = 0;
1418 else if (lo > size)
1419 lo = size;
1420 if (hi < 0)
1421 hi = 0;
1422 if (hi < lo)
1423 hi = lo;
1424 else if (hi > size)
1425 hi = size;
1426
1427 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1428 return -1;
1429
1430 if (new_end)
1431 *new_end = end + len_change;
1432
1433 return 0;
1434}
1435
1436 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001437RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438{
1439 PyObject *lines;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001440 PyInt len_change;
1441 PyInt max;
1442 PyInt n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001443
1444 if (CheckBuffer(self))
1445 return NULL;
1446
1447 max = n = end - start + 1;
1448
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001449 if (!PyArg_ParseTuple(args, "O|" Py_ssize_t_fmt, &lines, &n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450 return NULL;
1451
1452 if (n < 0 || n > max)
1453 {
1454 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1455 return NULL;
1456 }
1457
1458 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1459 return NULL;
1460
1461 if (new_end)
1462 *new_end = end + len_change;
1463
1464 Py_INCREF(Py_None);
1465 return Py_None;
1466}
1467
1468
1469/* Buffer object - Definitions
1470 */
1471
1472static struct PyMethodDef BufferMethods[] = {
1473 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001474 {"append", BufferAppend, 1, "Append data to Vim buffer" },
1475 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
1476 {"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 +00001477 { NULL, NULL, 0, NULL }
1478};
1479
1480static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001481 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001483 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1484 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1485 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1486 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1487 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488};
1489
1490static PyTypeObject BufferType = {
1491 PyObject_HEAD_INIT(0)
1492 0,
1493 "buffer",
1494 sizeof(BufferObject),
1495 0,
1496
1497 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1498 (printfunc) 0, /* tp_print, print x */
1499 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1500 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1501 (cmpfunc) 0, /* tp_compare, x>y */
1502 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1503
1504 0, /* as number */
1505 &BufferAsSeq, /* as sequence */
1506 0, /* as mapping */
1507
1508 (hashfunc) 0, /* tp_hash, dict(x) */
1509 (ternaryfunc) 0, /* tp_call, x() */
1510 (reprfunc) 0, /* tp_str, str(x) */
1511};
1512
1513/* Buffer object - Implementation
1514 */
1515
1516 static PyObject *
1517BufferNew(buf_T *buf)
1518{
1519 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001520 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521 * then we can get at it in buf_freeall() in vim. We then
1522 * need to create only ONE Python object per buffer - if
1523 * we try to create a second, just INCREF the existing one
1524 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001525 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 * Question: what to do on a buf_freeall(). We'll probably
1527 * have to either delete the Python object (DECREF it to
1528 * zero - a bad idea, as it leaves dangling refs!) or
1529 * set the buf_T * value to an invalid value (-1?), which
1530 * means we need checks in all access functions... Bah.
1531 */
1532
1533 BufferObject *self;
1534
Bram Moolenaare344bea2005-09-01 20:46:49 +00001535 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001537 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 Py_INCREF(self);
1539 }
1540 else
1541 {
1542 self = PyObject_NEW(BufferObject, &BufferType);
1543 if (self == NULL)
1544 return NULL;
1545 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001546 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 }
1548
1549 return (PyObject *)(self);
1550}
1551
1552 static void
1553BufferDestructor(PyObject *self)
1554{
1555 BufferObject *this = (BufferObject *)(self);
1556
1557 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001558 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559
Bram Moolenaar658ada62006-10-03 13:02:36 +00001560 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001561}
1562
1563 static PyObject *
1564BufferGetattr(PyObject *self, char *name)
1565{
1566 BufferObject *this = (BufferObject *)(self);
1567
1568 if (CheckBuffer(this))
1569 return NULL;
1570
1571 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001572 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001574 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575 else if (strcmp(name,"__members__") == 0)
1576 return Py_BuildValue("[ss]", "name", "number");
1577 else
1578 return Py_FindMethod(BufferMethods, self, name);
1579}
1580
1581 static PyObject *
1582BufferRepr(PyObject *self)
1583{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001584 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 BufferObject *this = (BufferObject *)(self);
1586
1587 if (this->buf == INVALID_BUFFER_VALUE)
1588 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001589 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 return PyString_FromString(repr);
1591 }
1592 else
1593 {
1594 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001595 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596
1597 if (name == NULL)
1598 name = "";
1599 len = strlen(name);
1600
1601 if (len > 35)
1602 name = name + (35 - len);
1603
Bram Moolenaar555b2802005-05-19 21:08:39 +00001604 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605
1606 return PyString_FromString(repr);
1607 }
1608}
1609
1610/******************/
1611
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001612 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613BufferLength(PyObject *self)
1614{
1615 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1616 if (CheckBuffer((BufferObject *)(self)))
1617 return -1; /* ??? */
1618
1619 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1620}
1621
1622 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001623BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624{
1625 return RBItem((BufferObject *)(self), n, 1,
1626 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1627}
1628
1629 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001630BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001631{
1632 return RBSlice((BufferObject *)(self), lo, hi, 1,
1633 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1634}
1635
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001636 static PyInt
1637BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638{
1639 return RBAssItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001640 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 NULL);
1642}
1643
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001644 static PyInt
1645BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646{
1647 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001648 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 NULL);
1650}
1651
1652 static PyObject *
1653BufferAppend(PyObject *self, PyObject *args)
1654{
1655 return RBAppend((BufferObject *)(self), args, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001656 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 NULL);
1658}
1659
1660 static PyObject *
1661BufferMark(PyObject *self, PyObject *args)
1662{
1663 pos_T *posp;
1664 char mark;
1665 buf_T *curbuf_save;
1666
1667 if (CheckBuffer((BufferObject *)(self)))
1668 return NULL;
1669
1670 if (!PyArg_ParseTuple(args, "c", &mark))
1671 return NULL;
1672
1673 curbuf_save = curbuf;
1674 curbuf = ((BufferObject *)(self))->buf;
1675 posp = getmark(mark, FALSE);
1676 curbuf = curbuf_save;
1677
1678 if (posp == NULL)
1679 {
1680 PyErr_SetVim(_("invalid mark name"));
1681 return NULL;
1682 }
1683
1684 /* Ckeck for keyboard interrupt */
1685 if (VimErrorCheck())
1686 return NULL;
1687
1688 if (posp->lnum <= 0)
1689 {
1690 /* Or raise an error? */
1691 Py_INCREF(Py_None);
1692 return Py_None;
1693 }
1694
1695 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1696}
1697
1698 static PyObject *
1699BufferRange(PyObject *self, PyObject *args)
1700{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001701 PyInt start;
1702 PyInt end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703
1704 if (CheckBuffer((BufferObject *)(self)))
1705 return NULL;
1706
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001707 if (!PyArg_ParseTuple(args, Py_ssize_t_fmt Py_ssize_t_fmt, &start, &end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 return NULL;
1709
1710 return RangeNew(((BufferObject *)(self))->buf, start, end);
1711}
1712
1713/* Line range object - Definitions
1714 */
1715
1716static struct PyMethodDef RangeMethods[] = {
1717 /* name, function, calling, documentation */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001718 {"append", RangeAppend, 1, "Append data to the Vim range" },
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 { NULL, NULL, 0, NULL }
1720};
1721
1722static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001723 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001724 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001725 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1726 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1727 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1728 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1729 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730};
1731
1732static PyTypeObject RangeType = {
1733 PyObject_HEAD_INIT(0)
1734 0,
1735 "range",
1736 sizeof(RangeObject),
1737 0,
1738
1739 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1740 (printfunc) 0, /* tp_print, print x */
1741 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1742 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1743 (cmpfunc) 0, /* tp_compare, x>y */
1744 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1745
1746 0, /* as number */
1747 &RangeAsSeq, /* as sequence */
1748 0, /* as mapping */
1749
1750 (hashfunc) 0, /* tp_hash, dict(x) */
1751 (ternaryfunc) 0, /* tp_call, x() */
1752 (reprfunc) 0, /* tp_str, str(x) */
1753};
1754
1755/* Line range object - Implementation
1756 */
1757
1758 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001759RangeNew(buf_T *buf, PyInt start, PyInt end)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760{
1761 BufferObject *bufr;
1762 RangeObject *self;
1763 self = PyObject_NEW(RangeObject, &RangeType);
1764 if (self == NULL)
1765 return NULL;
1766
1767 bufr = (BufferObject *)BufferNew(buf);
1768 if (bufr == NULL)
1769 {
Bram Moolenaar658ada62006-10-03 13:02:36 +00001770 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 return NULL;
1772 }
1773 Py_INCREF(bufr);
1774
1775 self->buf = bufr;
1776 self->start = start;
1777 self->end = end;
1778
1779 return (PyObject *)(self);
1780}
1781
1782 static void
1783RangeDestructor(PyObject *self)
1784{
1785 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001786 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787}
1788
1789 static PyObject *
1790RangeGetattr(PyObject *self, char *name)
1791{
1792 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001793 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001795 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 else
1797 return Py_FindMethod(RangeMethods, self, name);
1798}
1799
1800 static PyObject *
1801RangeRepr(PyObject *self)
1802{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001803 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 RangeObject *this = (RangeObject *)(self);
1805
1806 if (this->buf->buf == INVALID_BUFFER_VALUE)
1807 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001808 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1809 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 return PyString_FromString(repr);
1811 }
1812 else
1813 {
1814 char *name = (char *)this->buf->buf->b_fname;
1815 int len;
1816
1817 if (name == NULL)
1818 name = "";
Bram Moolenaarc236c162008-07-13 17:41:49 +00001819 len = (int)strlen(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820
1821 if (len > 45)
1822 name = name + (45 - len);
1823
Bram Moolenaar555b2802005-05-19 21:08:39 +00001824 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 len > 45 ? "..." : "", name,
1826 this->start, this->end);
1827
1828 return PyString_FromString(repr);
1829 }
1830}
1831
1832/****************/
1833
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001834 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835RangeLength(PyObject *self)
1836{
1837 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1838 if (CheckBuffer(((RangeObject *)(self))->buf))
1839 return -1; /* ??? */
1840
1841 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1842}
1843
1844 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001845RangeItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846{
1847 return RBItem(((RangeObject *)(self))->buf, n,
1848 ((RangeObject *)(self))->start,
1849 ((RangeObject *)(self))->end);
1850}
1851
1852 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001853RangeSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854{
1855 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1856 ((RangeObject *)(self))->start,
1857 ((RangeObject *)(self))->end);
1858}
1859
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001860 static PyInt
1861RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862{
1863 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1864 ((RangeObject *)(self))->start,
1865 ((RangeObject *)(self))->end,
1866 &((RangeObject *)(self))->end);
1867}
1868
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001869 static PyInt
1870RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871{
1872 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1873 ((RangeObject *)(self))->start,
1874 ((RangeObject *)(self))->end,
1875 &((RangeObject *)(self))->end);
1876}
1877
1878 static PyObject *
1879RangeAppend(PyObject *self, PyObject *args)
1880{
1881 return RBAppend(((RangeObject *)(self))->buf, args,
1882 ((RangeObject *)(self))->start,
1883 ((RangeObject *)(self))->end,
1884 &((RangeObject *)(self))->end);
1885}
1886
1887/* Buffer list object - Definitions
1888 */
1889
1890typedef struct
1891{
1892 PyObject_HEAD
1893}
1894BufListObject;
1895
1896static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001897 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001899 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1900 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1901 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1902 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1903 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904};
1905
1906static PyTypeObject BufListType = {
1907 PyObject_HEAD_INIT(0)
1908 0,
1909 "buffer list",
1910 sizeof(BufListObject),
1911 0,
1912
1913 (destructor) 0, /* tp_dealloc, refcount==0 */
1914 (printfunc) 0, /* tp_print, print x */
1915 (getattrfunc) 0, /* tp_getattr, x.attr */
1916 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1917 (cmpfunc) 0, /* tp_compare, x>y */
1918 (reprfunc) 0, /* tp_repr, `x`, print x */
1919
1920 0, /* as number */
1921 &BufListAsSeq, /* as sequence */
1922 0, /* as mapping */
1923
1924 (hashfunc) 0, /* tp_hash, dict(x) */
1925 (ternaryfunc) 0, /* tp_call, x() */
1926 (reprfunc) 0, /* tp_str, str(x) */
1927};
1928
1929/* Buffer list object - Implementation
1930 */
1931
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001932 static PyInt
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001933BufListLength(PyObject *self UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934{
1935 buf_T *b = firstbuf;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001936 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937
1938 while (b)
1939 {
1940 ++n;
1941 b = b->b_next;
1942 }
1943
1944 return n;
1945}
1946
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001948BufListItem(PyObject *self UNUSED, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949{
1950 buf_T *b;
1951
1952 for (b = firstbuf; b; b = b->b_next, --n)
1953 {
1954 if (n == 0)
1955 return BufferNew(b);
1956 }
1957
1958 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1959 return NULL;
1960}
1961
1962/* Window object - Definitions
1963 */
1964
1965static struct PyMethodDef WindowMethods[] = {
1966 /* name, function, calling, documentation */
1967 { NULL, NULL, 0, NULL }
1968};
1969
1970static PyTypeObject WindowType = {
1971 PyObject_HEAD_INIT(0)
1972 0,
1973 "window",
1974 sizeof(WindowObject),
1975 0,
1976
1977 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1978 (printfunc) 0, /* tp_print, print x */
1979 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1980 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1981 (cmpfunc) 0, /* tp_compare, x>y */
1982 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1983
1984 0, /* as number */
1985 0, /* as sequence */
1986 0, /* as mapping */
1987
1988 (hashfunc) 0, /* tp_hash, dict(x) */
1989 (ternaryfunc) 0, /* tp_call, x() */
1990 (reprfunc) 0, /* tp_str, str(x) */
1991};
1992
1993/* Window object - Implementation
1994 */
1995
1996 static PyObject *
1997WindowNew(win_T *win)
1998{
1999 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00002000 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001 * then we can get at it in win_free() in vim. We then
2002 * need to create only ONE Python object per window - if
2003 * we try to create a second, just INCREF the existing one
2004 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00002005 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 * On a win_free() we set the Python object's win_T* field
2007 * to an invalid value. We trap all uses of a window
2008 * object, and reject them if the win_T* field is invalid.
2009 */
2010
2011 WindowObject *self;
2012
Bram Moolenaare344bea2005-09-01 20:46:49 +00002013 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002015 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 Py_INCREF(self);
2017 }
2018 else
2019 {
2020 self = PyObject_NEW(WindowObject, &WindowType);
2021 if (self == NULL)
2022 return NULL;
2023 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002024 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 }
2026
2027 return (PyObject *)(self);
2028}
2029
2030 static void
2031WindowDestructor(PyObject *self)
2032{
2033 WindowObject *this = (WindowObject *)(self);
2034
2035 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00002036 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037
Bram Moolenaar658ada62006-10-03 13:02:36 +00002038 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039}
2040
2041 static int
2042CheckWindow(WindowObject *this)
2043{
2044 if (this->win == INVALID_WINDOW_VALUE)
2045 {
2046 PyErr_SetVim(_("attempt to refer to deleted window"));
2047 return -1;
2048 }
2049
2050 return 0;
2051}
2052
2053 static PyObject *
2054WindowGetattr(PyObject *self, char *name)
2055{
2056 WindowObject *this = (WindowObject *)(self);
2057
2058 if (CheckWindow(this))
2059 return NULL;
2060
2061 if (strcmp(name, "buffer") == 0)
2062 return (PyObject *)BufferNew(this->win->w_buffer);
2063 else if (strcmp(name, "cursor") == 0)
2064 {
2065 pos_T *pos = &this->win->w_cursor;
2066
2067 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
2068 }
2069 else if (strcmp(name, "height") == 0)
2070 return Py_BuildValue("l", (long)(this->win->w_height));
2071#ifdef FEAT_VERTSPLIT
2072 else if (strcmp(name, "width") == 0)
2073 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
2074#endif
2075 else if (strcmp(name,"__members__") == 0)
2076 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
2077 else
2078 return Py_FindMethod(WindowMethods, self, name);
2079}
2080
2081 static int
2082WindowSetattr(PyObject *self, char *name, PyObject *val)
2083{
2084 WindowObject *this = (WindowObject *)(self);
2085
2086 if (CheckWindow(this))
2087 return -1;
2088
2089 if (strcmp(name, "buffer") == 0)
2090 {
2091 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2092 return -1;
2093 }
2094 else if (strcmp(name, "cursor") == 0)
2095 {
2096 long lnum;
2097 long col;
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002098 long len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099
2100 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2101 return -1;
2102
2103 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2104 {
2105 PyErr_SetVim(_("cursor position outside buffer"));
2106 return -1;
2107 }
2108
2109 /* Check for keyboard interrupts */
2110 if (VimErrorCheck())
2111 return -1;
2112
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002113 /* When column is out of range silently correct it. */
Bram Moolenaar8b9c05f2010-03-02 17:54:33 +01002114 len = (long)STRLEN(ml_get_buf(this->win->w_buffer, lnum, FALSE));
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002115 if (col > len)
2116 col = len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002117
2118 this->win->w_cursor.lnum = lnum;
2119 this->win->w_cursor.col = col;
Bram Moolenaarbadfde12009-11-03 10:43:27 +00002120#ifdef FEAT_VIRTUALEDIT
2121 this->win->w_cursor.coladd = 0;
2122#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002123 update_screen(VALID);
2124
2125 return 0;
2126 }
2127 else if (strcmp(name, "height") == 0)
2128 {
2129 int height;
2130 win_T *savewin;
2131
2132 if (!PyArg_Parse(val, "i", &height))
2133 return -1;
2134
2135#ifdef FEAT_GUI
2136 need_mouse_correct = TRUE;
2137#endif
2138 savewin = curwin;
2139 curwin = this->win;
2140 win_setheight(height);
2141 curwin = savewin;
2142
2143 /* Check for keyboard interrupts */
2144 if (VimErrorCheck())
2145 return -1;
2146
2147 return 0;
2148 }
2149#ifdef FEAT_VERTSPLIT
2150 else if (strcmp(name, "width") == 0)
2151 {
2152 int width;
2153 win_T *savewin;
2154
2155 if (!PyArg_Parse(val, "i", &width))
2156 return -1;
2157
2158#ifdef FEAT_GUI
2159 need_mouse_correct = TRUE;
2160#endif
2161 savewin = curwin;
2162 curwin = this->win;
2163 win_setwidth(width);
2164 curwin = savewin;
2165
2166 /* Check for keyboard interrupts */
2167 if (VimErrorCheck())
2168 return -1;
2169
2170 return 0;
2171 }
2172#endif
2173 else
2174 {
2175 PyErr_SetString(PyExc_AttributeError, name);
2176 return -1;
2177 }
2178}
2179
2180 static PyObject *
2181WindowRepr(PyObject *self)
2182{
Bram Moolenaar555b2802005-05-19 21:08:39 +00002183 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184 WindowObject *this = (WindowObject *)(self);
2185
2186 if (this->win == INVALID_WINDOW_VALUE)
2187 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002188 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 return PyString_FromString(repr);
2190 }
2191 else
2192 {
2193 int i = 0;
2194 win_T *w;
2195
2196 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2197 ++i;
2198
2199 if (w == NULL)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002200 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2201 (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00002203 vim_snprintf(repr, 100, _("<window %d>"), i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204
2205 return PyString_FromString(repr);
2206 }
2207}
2208
2209/* Window list object - Definitions
2210 */
2211
2212typedef struct
2213{
2214 PyObject_HEAD
2215}
2216WinListObject;
2217
2218static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002219 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002221 (PyIntArgFunc) 0, /* sq_repeat, x*n */
2222 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
2223 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
2224 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
2225 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226};
2227
2228static PyTypeObject WinListType = {
2229 PyObject_HEAD_INIT(0)
2230 0,
2231 "window list",
2232 sizeof(WinListObject),
2233 0,
2234
2235 (destructor) 0, /* tp_dealloc, refcount==0 */
2236 (printfunc) 0, /* tp_print, print x */
2237 (getattrfunc) 0, /* tp_getattr, x.attr */
2238 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2239 (cmpfunc) 0, /* tp_compare, x>y */
2240 (reprfunc) 0, /* tp_repr, `x`, print x */
2241
2242 0, /* as number */
2243 &WinListAsSeq, /* as sequence */
2244 0, /* as mapping */
2245
2246 (hashfunc) 0, /* tp_hash, dict(x) */
2247 (ternaryfunc) 0, /* tp_call, x() */
2248 (reprfunc) 0, /* tp_str, str(x) */
2249};
2250
2251/* Window list object - Implementation
2252 */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002253 static PyInt
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002254WinListLength(PyObject *self UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255{
2256 win_T *w = firstwin;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002257 PyInt n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258
Bram Moolenaarf740b292006-02-16 22:11:02 +00002259 while (w != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 {
2261 ++n;
2262 w = W_NEXT(w);
2263 }
2264
2265 return n;
2266}
2267
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002269WinListItem(PyObject *self UNUSED, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270{
2271 win_T *w;
2272
Bram Moolenaarf740b292006-02-16 22:11:02 +00002273 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 if (n == 0)
2275 return WindowNew(w);
2276
2277 PyErr_SetString(PyExc_IndexError, _("no such window"));
2278 return NULL;
2279}
2280
2281/* Current items object - Definitions
2282 */
2283
2284typedef struct
2285{
2286 PyObject_HEAD
2287}
2288CurrentObject;
2289
2290static PyTypeObject CurrentType = {
2291 PyObject_HEAD_INIT(0)
2292 0,
2293 "current data",
2294 sizeof(CurrentObject),
2295 0,
2296
2297 (destructor) 0, /* tp_dealloc, refcount==0 */
2298 (printfunc) 0, /* tp_print, print x */
2299 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2300 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2301 (cmpfunc) 0, /* tp_compare, x>y */
2302 (reprfunc) 0, /* tp_repr, `x`, print x */
2303
2304 0, /* as number */
2305 0, /* as sequence */
2306 0, /* as mapping */
2307
2308 (hashfunc) 0, /* tp_hash, dict(x) */
2309 (ternaryfunc) 0, /* tp_call, x() */
2310 (reprfunc) 0, /* tp_str, str(x) */
2311};
2312
2313/* Current items object - Implementation
2314 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002316CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317{
2318 if (strcmp(name, "buffer") == 0)
2319 return (PyObject *)BufferNew(curbuf);
2320 else if (strcmp(name, "window") == 0)
2321 return (PyObject *)WindowNew(curwin);
2322 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002323 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002324 else if (strcmp(name, "range") == 0)
2325 return RangeNew(curbuf, RangeStart, RangeEnd);
2326 else if (strcmp(name,"__members__") == 0)
2327 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2328 else
2329 {
2330 PyErr_SetString(PyExc_AttributeError, name);
2331 return NULL;
2332 }
2333}
2334
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00002336CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337{
2338 if (strcmp(name, "line") == 0)
2339 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002340 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 return -1;
2342
2343 return 0;
2344 }
2345 else
2346 {
2347 PyErr_SetString(PyExc_AttributeError, name);
2348 return -1;
2349 }
2350}
2351
2352/* External interface
2353 */
2354
2355 void
2356python_buffer_free(buf_T *buf)
2357{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002358 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002359 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002360 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002362 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 }
2364}
2365
2366#if defined(FEAT_WINDOWS) || defined(PROTO)
2367 void
2368python_window_free(win_T *win)
2369{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002370 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002372 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002374 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 }
2376}
2377#endif
2378
2379static BufListObject TheBufferList =
2380{
2381 PyObject_HEAD_INIT(&BufListType)
2382};
2383
2384static WinListObject TheWindowList =
2385{
2386 PyObject_HEAD_INIT(&WinListType)
2387};
2388
2389static CurrentObject TheCurrent =
2390{
2391 PyObject_HEAD_INIT(&CurrentType)
2392};
2393
2394 static int
2395PythonMod_Init(void)
2396{
2397 PyObject *mod;
2398 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00002399 /* The special value is removed from sys.path in Python_Init(). */
2400 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401
2402 /* Fixups... */
2403 BufferType.ob_type = &PyType_Type;
2404 RangeType.ob_type = &PyType_Type;
2405 WindowType.ob_type = &PyType_Type;
2406 BufListType.ob_type = &PyType_Type;
2407 WinListType.ob_type = &PyType_Type;
2408 CurrentType.ob_type = &PyType_Type;
2409
2410 /* Set sys.argv[] to avoid a crash in warn(). */
2411 PySys_SetArgv(1, argv);
2412
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002413 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 dict = PyModule_GetDict(mod);
2415
2416 VimError = Py_BuildValue("s", "vim.error");
2417
2418 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00002419 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2420 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2421 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422
2423 if (PyErr_Occurred())
2424 return -1;
2425
2426 return 0;
2427}
2428
2429/*************************************************************************
2430 * 4. Utility functions for handling the interface between Vim and Python.
2431 */
2432
2433/* Get a line from the specified buffer. The line number is
2434 * in Vim format (1-based). The line is returned as a Python
2435 * string object.
2436 */
2437 static PyObject *
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002438GetBufferLine(buf_T *buf, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439{
2440 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2441}
2442
2443/* Get a list of lines from the specified buffer. The line numbers
2444 * are in Vim format (1-based). The range is from lo up to, but not
2445 * including, hi. The list is returned as a Python list of string objects.
2446 */
2447 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002448GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449{
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002450 PyInt i;
2451 PyInt n = hi - lo;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 PyObject *list = PyList_New(n);
2453
2454 if (list == NULL)
2455 return NULL;
2456
2457 for (i = 0; i < n; ++i)
2458 {
2459 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2460
2461 /* Error check - was the Python string creation OK? */
2462 if (str == NULL)
2463 {
2464 Py_DECREF(list);
2465 return NULL;
2466 }
2467
2468 /* Set the list item */
2469 if (PyList_SetItem(list, i, str))
2470 {
2471 Py_DECREF(str);
2472 Py_DECREF(list);
2473 return NULL;
2474 }
2475 }
2476
2477 /* The ownership of the Python list is passed to the caller (ie,
2478 * the caller should Py_DECREF() the object when it is finished
2479 * with it).
2480 */
2481
2482 return list;
2483}
2484
2485/*
2486 * Check if deleting lines made the cursor position invalid.
2487 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2488 * deleted).
2489 */
2490 static void
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002491py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492{
2493 if (curwin->w_cursor.lnum >= lo)
2494 {
2495 /* Adjust the cursor position if it's in/after the changed
2496 * lines. */
2497 if (curwin->w_cursor.lnum >= hi)
2498 {
2499 curwin->w_cursor.lnum += extra;
2500 check_cursor_col();
2501 }
2502 else if (extra < 0)
2503 {
2504 curwin->w_cursor.lnum = lo;
2505 check_cursor();
2506 }
Bram Moolenaar454ec052007-03-08 09:20:28 +00002507 else
2508 check_cursor_col();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 changed_cline_bef_curs();
2510 }
2511 invalidate_botline();
2512}
2513
2514/* Replace a line in the specified buffer. The line number is
2515 * in Vim format (1-based). The replacement line is given as
2516 * a Python string object. The object is checked for validity
2517 * and correct format. Errors are returned as a value of FAIL.
2518 * The return value is OK on success.
2519 * If OK is returned and len_change is not NULL, *len_change
2520 * is set to the change in the buffer length.
2521 */
2522 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002523SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524{
2525 /* First of all, we check the thpe of the supplied Python object.
2526 * There are three cases:
2527 * 1. NULL, or None - this is a deletion.
2528 * 2. A string - this is a replacement.
2529 * 3. Anything else - this is an error.
2530 */
2531 if (line == Py_None || line == NULL)
2532 {
2533 buf_T *savebuf = curbuf;
2534
2535 PyErr_Clear();
2536 curbuf = buf;
2537
2538 if (u_savedel((linenr_T)n, 1L) == FAIL)
2539 PyErr_SetVim(_("cannot save undo information"));
2540 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2541 PyErr_SetVim(_("cannot delete line"));
2542 else
2543 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002545 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002546 deleted_lines_mark((linenr_T)n, 1L);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 }
2548
2549 curbuf = savebuf;
2550
2551 if (PyErr_Occurred() || VimErrorCheck())
2552 return FAIL;
2553
2554 if (len_change)
2555 *len_change = -1;
2556
2557 return OK;
2558 }
2559 else if (PyString_Check(line))
2560 {
2561 char *save = StringToLine(line);
2562 buf_T *savebuf = curbuf;
2563
2564 if (save == NULL)
2565 return FAIL;
2566
2567 /* We do not need to free "save" if ml_replace() consumes it. */
2568 PyErr_Clear();
2569 curbuf = buf;
2570
2571 if (u_savesub((linenr_T)n) == FAIL)
2572 {
2573 PyErr_SetVim(_("cannot save undo information"));
2574 vim_free(save);
2575 }
2576 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2577 {
2578 PyErr_SetVim(_("cannot replace line"));
2579 vim_free(save);
2580 }
2581 else
2582 changed_bytes((linenr_T)n, 0);
2583
2584 curbuf = savebuf;
2585
Bram Moolenaar454ec052007-03-08 09:20:28 +00002586 /* Check that the cursor is not beyond the end of the line now. */
2587 if (buf == curwin->w_buffer)
2588 check_cursor_col();
2589
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 if (PyErr_Occurred() || VimErrorCheck())
2591 return FAIL;
2592
2593 if (len_change)
2594 *len_change = 0;
2595
2596 return OK;
2597 }
2598 else
2599 {
2600 PyErr_BadArgument();
2601 return FAIL;
2602 }
2603}
2604
2605/* Replace a range of lines in the specified buffer. The line numbers are in
2606 * Vim format (1-based). The range is from lo up to, but not including, hi.
2607 * The replacement lines are given as a Python list of string objects. The
2608 * list is checked for validity and correct format. Errors are returned as a
2609 * value of FAIL. The return value is OK on success.
2610 * If OK is returned and len_change is not NULL, *len_change
2611 * is set to the change in the buffer length.
2612 */
2613 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002614SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615{
2616 /* First of all, we check the thpe of the supplied Python object.
2617 * There are three cases:
2618 * 1. NULL, or None - this is a deletion.
2619 * 2. A list - this is a replacement.
2620 * 3. Anything else - this is an error.
2621 */
2622 if (list == Py_None || list == NULL)
2623 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002624 PyInt i;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002625 PyInt n = (int)(hi - lo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 buf_T *savebuf = curbuf;
2627
2628 PyErr_Clear();
2629 curbuf = buf;
2630
2631 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2632 PyErr_SetVim(_("cannot save undo information"));
2633 else
2634 {
2635 for (i = 0; i < n; ++i)
2636 {
2637 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2638 {
2639 PyErr_SetVim(_("cannot delete line"));
2640 break;
2641 }
2642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002644 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002645 deleted_lines_mark((linenr_T)lo, (long)i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 }
2647
2648 curbuf = savebuf;
2649
2650 if (PyErr_Occurred() || VimErrorCheck())
2651 return FAIL;
2652
2653 if (len_change)
2654 *len_change = -n;
2655
2656 return OK;
2657 }
2658 else if (PyList_Check(list))
2659 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002660 PyInt i;
2661 PyInt new_len = PyList_Size(list);
2662 PyInt old_len = hi - lo;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002663 PyInt extra = 0; /* lines added to text, can be negative */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 char **array;
2665 buf_T *savebuf;
2666
2667 if (new_len == 0) /* avoid allocating zero bytes */
2668 array = NULL;
2669 else
2670 {
2671 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2672 if (array == NULL)
2673 {
2674 PyErr_NoMemory();
2675 return FAIL;
2676 }
2677 }
2678
2679 for (i = 0; i < new_len; ++i)
2680 {
2681 PyObject *line = PyList_GetItem(list, i);
2682
2683 array[i] = StringToLine(line);
2684 if (array[i] == NULL)
2685 {
2686 while (i)
2687 vim_free(array[--i]);
2688 vim_free(array);
2689 return FAIL;
2690 }
2691 }
2692
2693 savebuf = curbuf;
2694
2695 PyErr_Clear();
2696 curbuf = buf;
2697
2698 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2699 PyErr_SetVim(_("cannot save undo information"));
2700
2701 /* If the size of the range is reducing (ie, new_len < old_len) we
2702 * need to delete some old_len. We do this at the start, by
2703 * repeatedly deleting line "lo".
2704 */
2705 if (!PyErr_Occurred())
2706 {
2707 for (i = 0; i < old_len - new_len; ++i)
2708 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2709 {
2710 PyErr_SetVim(_("cannot delete line"));
2711 break;
2712 }
2713 extra -= i;
2714 }
2715
2716 /* For as long as possible, replace the existing old_len with the
2717 * new old_len. This is a more efficient operation, as it requires
2718 * less memory allocation and freeing.
2719 */
2720 if (!PyErr_Occurred())
2721 {
2722 for (i = 0; i < old_len && i < new_len; ++i)
2723 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2724 == FAIL)
2725 {
2726 PyErr_SetVim(_("cannot replace line"));
2727 break;
2728 }
2729 }
2730 else
2731 i = 0;
2732
2733 /* Now we may need to insert the remaining new old_len. If we do, we
2734 * must free the strings as we finish with them (we can't pass the
2735 * responsibility to vim in this case).
2736 */
2737 if (!PyErr_Occurred())
2738 {
2739 while (i < new_len)
2740 {
2741 if (ml_append((linenr_T)(lo + i - 1),
2742 (char_u *)array[i], 0, FALSE) == FAIL)
2743 {
2744 PyErr_SetVim(_("cannot insert line"));
2745 break;
2746 }
2747 vim_free(array[i]);
2748 ++i;
2749 ++extra;
2750 }
2751 }
2752
2753 /* Free any left-over old_len, as a result of an error */
2754 while (i < new_len)
2755 {
2756 vim_free(array[i]);
2757 ++i;
2758 }
2759
2760 /* Free the array of old_len. All of its contents have now
2761 * been dealt with (either freed, or the responsibility passed
2762 * to vim.
2763 */
2764 vim_free(array);
2765
2766 /* Adjust marks. Invalidate any which lie in the
2767 * changed range, and move any in the remainder of the buffer.
2768 */
2769 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2770 (long)MAXLNUM, (long)extra);
2771 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2772
2773 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002774 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775
2776 curbuf = savebuf;
2777
2778 if (PyErr_Occurred() || VimErrorCheck())
2779 return FAIL;
2780
2781 if (len_change)
2782 *len_change = new_len - old_len;
2783
2784 return OK;
2785 }
2786 else
2787 {
2788 PyErr_BadArgument();
2789 return FAIL;
2790 }
2791}
2792
2793/* Insert a number of lines into the specified buffer after the specifed line.
2794 * The line number is in Vim format (1-based). The lines to be inserted are
2795 * given as a Python list of string objects or as a single string. The lines
2796 * to be added are checked for validity and correct format. Errors are
2797 * returned as a value of FAIL. The return value is OK on success.
2798 * If OK is returned and len_change is not NULL, *len_change
2799 * is set to the change in the buffer length.
2800 */
2801 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00002802InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803{
2804 /* First of all, we check the type of the supplied Python object.
2805 * It must be a string or a list, or the call is in error.
2806 */
2807 if (PyString_Check(lines))
2808 {
2809 char *str = StringToLine(lines);
2810 buf_T *savebuf;
2811
2812 if (str == NULL)
2813 return FAIL;
2814
2815 savebuf = curbuf;
2816
2817 PyErr_Clear();
2818 curbuf = buf;
2819
2820 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2821 PyErr_SetVim(_("cannot save undo information"));
2822 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2823 PyErr_SetVim(_("cannot insert line"));
2824 else
2825 appended_lines_mark((linenr_T)n, 1L);
2826
2827 vim_free(str);
2828 curbuf = savebuf;
2829 update_screen(VALID);
2830
2831 if (PyErr_Occurred() || VimErrorCheck())
2832 return FAIL;
2833
2834 if (len_change)
2835 *len_change = 1;
2836
2837 return OK;
2838 }
2839 else if (PyList_Check(lines))
2840 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002841 PyInt i;
2842 PyInt size = PyList_Size(lines);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843 char **array;
2844 buf_T *savebuf;
2845
2846 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2847 if (array == NULL)
2848 {
2849 PyErr_NoMemory();
2850 return FAIL;
2851 }
2852
2853 for (i = 0; i < size; ++i)
2854 {
2855 PyObject *line = PyList_GetItem(lines, i);
2856 array[i] = StringToLine(line);
2857
2858 if (array[i] == NULL)
2859 {
2860 while (i)
2861 vim_free(array[--i]);
2862 vim_free(array);
2863 return FAIL;
2864 }
2865 }
2866
2867 savebuf = curbuf;
2868
2869 PyErr_Clear();
2870 curbuf = buf;
2871
2872 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2873 PyErr_SetVim(_("cannot save undo information"));
2874 else
2875 {
2876 for (i = 0; i < size; ++i)
2877 {
2878 if (ml_append((linenr_T)(n + i),
2879 (char_u *)array[i], 0, FALSE) == FAIL)
2880 {
2881 PyErr_SetVim(_("cannot insert line"));
2882
2883 /* Free the rest of the lines */
2884 while (i < size)
2885 vim_free(array[i++]);
2886
2887 break;
2888 }
2889 vim_free(array[i]);
2890 }
2891 if (i > 0)
2892 appended_lines_mark((linenr_T)n, (long)i);
2893 }
2894
2895 /* Free the array of lines. All of its contents have now
2896 * been freed.
2897 */
2898 vim_free(array);
2899
2900 curbuf = savebuf;
2901 update_screen(VALID);
2902
2903 if (PyErr_Occurred() || VimErrorCheck())
2904 return FAIL;
2905
2906 if (len_change)
2907 *len_change = size;
2908
2909 return OK;
2910 }
2911 else
2912 {
2913 PyErr_BadArgument();
2914 return FAIL;
2915 }
2916}
2917
2918/* Convert a Vim line into a Python string.
2919 * All internal newlines are replaced by null characters.
2920 *
2921 * On errors, the Python exception data is set, and NULL is returned.
2922 */
2923 static PyObject *
2924LineToString(const char *str)
2925{
2926 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002927 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928 char *p;
2929
2930 /* Allocate an Python string object, with uninitialised contents. We
2931 * must do it this way, so that we can modify the string in place
2932 * later. See the Python source, Objects/stringobject.c for details.
2933 */
2934 result = PyString_FromStringAndSize(NULL, len);
2935 if (result == NULL)
2936 return NULL;
2937
2938 p = PyString_AsString(result);
2939
2940 while (*str)
2941 {
2942 if (*str == '\n')
2943 *p = '\0';
2944 else
2945 *p = *str;
2946
2947 ++p;
2948 ++str;
2949 }
2950
2951 return result;
2952}
2953
2954/* Convert a Python string into a Vim line.
2955 *
2956 * The result is in allocated memory. All internal nulls are replaced by
2957 * newline characters. It is an error for the string to contain newline
2958 * characters.
2959 *
2960 * On errors, the Python exception data is set, and NULL is returned.
2961 */
2962 static char *
2963StringToLine(PyObject *obj)
2964{
2965 const char *str;
2966 char *save;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00002967 PyInt len;
2968 PyInt i;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002969 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970
2971 if (obj == NULL || !PyString_Check(obj))
2972 {
2973 PyErr_BadArgument();
2974 return NULL;
2975 }
2976
2977 str = PyString_AsString(obj);
2978 len = PyString_Size(obj);
2979
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002980 /*
2981 * Error checking: String must not contain newlines, as we
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 * are replacing a single line, and we must replace it with
2983 * a single line.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002984 * A trailing newline is removed, so that append(f.readlines()) works.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002986 p = memchr(str, '\n', len);
2987 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002989 if (p == str + len - 1)
2990 --len;
2991 else
2992 {
2993 PyErr_SetVim(_("string cannot contain newlines"));
2994 return NULL;
2995 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996 }
2997
2998 /* Create a copy of the string, with internal nulls replaced by
2999 * newline characters, as is the vim convention.
3000 */
3001 save = (char *)alloc((unsigned)(len+1));
3002 if (save == NULL)
3003 {
3004 PyErr_NoMemory();
3005 return NULL;
3006 }
3007
3008 for (i = 0; i < len; ++i)
3009 {
3010 if (str[i] == '\0')
3011 save[i] = '\n';
3012 else
3013 save[i] = str[i];
3014 }
3015
3016 save[i] = '\0';
3017
3018 return save;
3019}
3020
3021/* Check to see whether a Vim error has been reported, or a keyboard
3022 * interrupt has been detected.
3023 */
3024 static int
3025VimErrorCheck(void)
3026{
3027 if (got_int)
3028 {
3029 PyErr_SetNone(PyExc_KeyboardInterrupt);
3030 return 1;
3031 }
3032 else if (did_emsg && !PyErr_Occurred())
3033 {
3034 PyErr_SetNone(VimError);
3035 return 1;
3036 }
3037
3038 return 0;
3039}
3040
3041
3042/* Don't generate a prototype for the next function, it generates an error on
3043 * newer Python versions. */
3044#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
3045
3046 char *
3047Py_GetProgramName(void)
3048{
3049 return "vim";
3050}
3051#endif /* Python 1.4 */