blob: c1b3bf81762904e451ddaa1e617a637fa613829a [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * Python extensions by Paul Moore.
11 * Changes for Unix by David Leonard.
12 *
13 * This consists of four parts:
14 * 1. Python interpreter main program
15 * 2. Python output stream: writes output via [e]msg().
16 * 3. Implementation of the Vim module for Python
17 * 4. Utility functions for handling the interface between Vim and Python.
18 */
19
20#include "vim.h"
21
Bram Moolenaar071d4272004-06-13 20:20:40 +000022#include <limits.h>
23
24/* Python.h defines _POSIX_THREADS itself (if needed) */
25#ifdef _POSIX_THREADS
26# undef _POSIX_THREADS
27#endif
28
29#if defined(_WIN32) && defined (HAVE_FCNTL_H)
30# undef HAVE_FCNTL_H
31#endif
32
33#ifdef _DEBUG
34# undef _DEBUG
35#endif
36
37#ifdef HAVE_STDARG_H
38# undef HAVE_STDARG_H /* Python's config.h defines it as well. */
39#endif
40
41#include <Python.h>
42#if defined(MACOS) && !defined(MACOS_X_UNIX)
43# include "macglue.h"
44# include <CodeFragments.h>
45#endif
46#undef main /* Defined in python.h - aargh */
47#undef HAVE_FCNTL_H /* Clash with os_win32.h */
48
49#if !defined(FEAT_PYTHON) && defined(PROTO)
50/* Use this to be able to generate prototypes without python being used. */
51# define PyObject int
52# define PyThreadState int
53# define PyTypeObject int
54struct PyMethodDef { int a; };
55# define PySequenceMethods int
56#endif
57
58/* Parser flags */
59#define single_input 256
60#define file_input 257
61#define eval_input 258
62
63#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
64 /* Python 2.3: can invoke ":python" recursively. */
65# define PY_CAN_RECURSE
66#endif
67
68#if defined(DYNAMIC_PYTHON) || defined(PROTO)
69# ifndef DYNAMIC_PYTHON
70# define HINSTANCE int /* for generating prototypes */
71# endif
72
73/*
74 * Wrapper defines
75 */
76# define PyArg_Parse dll_PyArg_Parse
77# define PyArg_ParseTuple dll_PyArg_ParseTuple
78# define PyDict_SetItemString dll_PyDict_SetItemString
79# define PyErr_BadArgument dll_PyErr_BadArgument
80# define PyErr_Clear dll_PyErr_Clear
81# define PyErr_NoMemory dll_PyErr_NoMemory
82# define PyErr_Occurred dll_PyErr_Occurred
83# define PyErr_SetNone dll_PyErr_SetNone
84# define PyErr_SetString dll_PyErr_SetString
85# define PyEval_InitThreads dll_PyEval_InitThreads
86# define PyEval_RestoreThread dll_PyEval_RestoreThread
87# define PyEval_SaveThread dll_PyEval_SaveThread
88# ifdef PY_CAN_RECURSE
89# define PyGILState_Ensure dll_PyGILState_Ensure
90# define PyGILState_Release dll_PyGILState_Release
91# endif
92# define PyInt_AsLong dll_PyInt_AsLong
93# define PyInt_FromLong dll_PyInt_FromLong
94# define PyInt_Type (*dll_PyInt_Type)
95# define PyList_GetItem dll_PyList_GetItem
96# define PyList_New dll_PyList_New
97# define PyList_SetItem dll_PyList_SetItem
98# define PyList_Size dll_PyList_Size
99# define PyList_Type (*dll_PyList_Type)
100# define PyImport_ImportModule dll_PyImport_ImportModule
101# define PyDict_GetItemString dll_PyDict_GetItemString
102# define PyModule_GetDict dll_PyModule_GetDict
103# define PyRun_SimpleString dll_PyRun_SimpleString
104# define PyString_AsString dll_PyString_AsString
105# define PyString_FromString dll_PyString_FromString
106# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
107# define PyString_Size dll_PyString_Size
108# define PyString_Type (*dll_PyString_Type)
109# define PySys_SetObject dll_PySys_SetObject
110# define PySys_SetArgv dll_PySys_SetArgv
111# define PyType_Type (*dll_PyType_Type)
112# define Py_BuildValue dll_Py_BuildValue
113# define Py_FindMethod dll_Py_FindMethod
114# define Py_InitModule4 dll_Py_InitModule4
115# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000116# define Py_Finalize dll_Py_Finalize
117# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000118# define _PyObject_New dll__PyObject_New
119# define _Py_NoneStruct (*dll__Py_NoneStruct)
120# define PyObject_Init dll__PyObject_Init
121# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
122# define PyType_IsSubtype dll_PyType_IsSubtype
123# endif
124# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
125# define PyObject_Malloc dll_PyObject_Malloc
126# define PyObject_Free dll_PyObject_Free
127# endif
128
129/*
130 * Pointers for dynamic link
131 */
132static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
133static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
134static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
135static int(*dll_PyErr_BadArgument)(void);
136static void(*dll_PyErr_Clear)(void);
137static PyObject*(*dll_PyErr_NoMemory)(void);
138static PyObject*(*dll_PyErr_Occurred)(void);
139static void(*dll_PyErr_SetNone)(PyObject *);
140static void(*dll_PyErr_SetString)(PyObject *, const char *);
141static void(*dll_PyEval_InitThreads)(void);
142static void(*dll_PyEval_RestoreThread)(PyThreadState *);
143static PyThreadState*(*dll_PyEval_SaveThread)(void);
144# ifdef PY_CAN_RECURSE
145static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
146static void (*dll_PyGILState_Release)(PyGILState_STATE);
147#endif
148static long(*dll_PyInt_AsLong)(PyObject *);
149static PyObject*(*dll_PyInt_FromLong)(long);
150static PyTypeObject* dll_PyInt_Type;
151static PyObject*(*dll_PyList_GetItem)(PyObject *, int);
152static PyObject*(*dll_PyList_New)(int size);
153static int(*dll_PyList_SetItem)(PyObject *, int, PyObject *);
154static int(*dll_PyList_Size)(PyObject *);
155static PyTypeObject* dll_PyList_Type;
156static PyObject*(*dll_PyImport_ImportModule)(const char *);
157static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
158static PyObject*(*dll_PyModule_GetDict)(PyObject *);
159static int(*dll_PyRun_SimpleString)(char *);
160static char*(*dll_PyString_AsString)(PyObject *);
161static PyObject*(*dll_PyString_FromString)(const char *);
162static PyObject*(*dll_PyString_FromStringAndSize)(const char *, int);
163static int(*dll_PyString_Size)(PyObject *);
164static PyTypeObject* dll_PyString_Type;
165static int(*dll_PySys_SetObject)(char *, PyObject *);
166static int(*dll_PySys_SetArgv)(int, char **);
167static PyTypeObject* dll_PyType_Type;
168static PyObject*(*dll_Py_BuildValue)(char *, ...);
169static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
170static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
171static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000172static void(*dll_Py_Finalize)(void);
173static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
175static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
176static PyObject* dll__Py_NoneStruct;
177# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
178static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
179# endif
180# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
181static void* (*dll_PyObject_Malloc)(size_t);
182static void (*dll_PyObject_Free)(void*);
183# endif
184
185static HINSTANCE hinstPython = 0; /* Instance of python.dll */
186
187/* Imported exception objects */
188static PyObject *imp_PyExc_AttributeError;
189static PyObject *imp_PyExc_IndexError;
190static PyObject *imp_PyExc_KeyboardInterrupt;
191static PyObject *imp_PyExc_TypeError;
192static PyObject *imp_PyExc_ValueError;
193
194# define PyExc_AttributeError imp_PyExc_AttributeError
195# define PyExc_IndexError imp_PyExc_IndexError
196# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
197# define PyExc_TypeError imp_PyExc_TypeError
198# define PyExc_ValueError imp_PyExc_ValueError
199
200/*
201 * Table of name to function pointer of python.
202 */
203# define PYTHON_PROC FARPROC
204static struct
205{
206 char *name;
207 PYTHON_PROC *ptr;
208} python_funcname_table[] =
209{
210 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
211 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
212 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
213 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
214 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
215 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
216 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
217 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
218 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
219 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
220 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
221 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
222# ifdef PY_CAN_RECURSE
223 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
224 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
225# endif
226 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
227 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
228 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
229 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
230 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
231 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
232 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
233 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
234 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
235 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
236 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
237 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
238 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
239 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
240 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
241 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
242 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
243 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
244 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
245 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
246 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
247 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
248 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
249 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000250 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
251 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000252 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
253 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
254 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
255# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
256 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
257# endif
258# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
259 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
260 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
261# endif
262 {"", NULL},
263};
264
265/*
266 * Free python.dll
267 */
268 static void
269end_dynamic_python(void)
270{
271 if (hinstPython)
272 {
273 FreeLibrary(hinstPython);
274 hinstPython = 0;
275 }
276}
277
278/*
279 * Load library and get all pointers.
280 * Parameter 'libname' provides name of DLL.
281 * Return OK or FAIL.
282 */
283 static int
284python_runtime_link_init(char *libname, int verbose)
285{
286 int i;
287
288 if (hinstPython)
289 return OK;
290 hinstPython = LoadLibrary(libname);
291 if (!hinstPython)
292 {
293 if (verbose)
294 EMSG2(_(e_loadlib), libname);
295 return FAIL;
296 }
297
298 for (i = 0; python_funcname_table[i].ptr; ++i)
299 {
300 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
301 python_funcname_table[i].name)) == NULL)
302 {
303 FreeLibrary(hinstPython);
304 hinstPython = 0;
305 if (verbose)
306 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
307 return FAIL;
308 }
309 }
310 return OK;
311}
312
313/*
314 * If python is enabled (there is installed python on Windows system) return
315 * TRUE, else FALSE.
316 */
317 int
318python_enabled(verbose)
319 int verbose;
320{
321 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
322}
323
324/* Load the standard Python exceptions - don't import the symbols from the
325 * DLL, as this can cause errors (importing data symbols is not reliable).
326 */
327static void get_exceptions __ARGS((void));
328
329 static void
330get_exceptions()
331{
332 PyObject *exmod = PyImport_ImportModule("exceptions");
333 PyObject *exdict = PyModule_GetDict(exmod);
334 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
335 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
336 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
337 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
338 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
339 Py_XINCREF(imp_PyExc_AttributeError);
340 Py_XINCREF(imp_PyExc_IndexError);
341 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
342 Py_XINCREF(imp_PyExc_TypeError);
343 Py_XINCREF(imp_PyExc_ValueError);
344 Py_XDECREF(exmod);
345}
346#endif /* DYNAMIC_PYTHON */
347
348/******************************************************
349 * Internal function prototypes.
350 */
351
352static void DoPythonCommand(exarg_T *, const char *);
353static int RangeStart;
354static int RangeEnd;
355
356static void PythonIO_Flush(void);
357static int PythonIO_Init(void);
358static int PythonMod_Init(void);
359
360/* Utility functions for the vim/python interface
361 * ----------------------------------------------
362 */
363static PyObject *GetBufferLine(buf_T *, int);
364static PyObject *GetBufferLineList(buf_T *, int, int);
365
366static int SetBufferLine(buf_T *, int, PyObject *, int *);
367static int SetBufferLineList(buf_T *, int, int, PyObject *, int *);
368static int InsertBufferLines(buf_T *, int, PyObject *, int *);
369
370static PyObject *LineToString(const char *);
371static char *StringToLine(PyObject *);
372
373static int VimErrorCheck(void);
374
375#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
376
377/******************************************************
378 * 1. Python interpreter main program.
379 */
380
381static int initialised = 0;
382
383#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
384typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000385#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000387#ifdef PY_CAN_RECURSE
388static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
389#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000390static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000391#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392
393/*
394 * Suspend a thread of the Python interpreter, other threads are allowed to
395 * run.
396 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000397 static void
398Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000400#ifdef PY_CAN_RECURSE
401 PyGILState_Release(pygilstate);
402#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000404#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000405}
406
407/*
408 * Restore a thread of the Python interpreter, waits for other threads to
409 * block.
410 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000411 static void
412Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000413{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000414#ifdef PY_CAN_RECURSE
415 pygilstate = PyGILState_Ensure();
416#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417 PyEval_RestoreThread(saved_python_thread);
418 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000420}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421
422/*
423 * obtain a lock on the Vim data structures
424 */
425static void Python_Lock_Vim(void)
426{
427}
428
429/*
430 * release a lock on the Vim data structures
431 */
432static void Python_Release_Vim(void)
433{
434}
435
436 void
437python_end()
438{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000439 static int recurse = 0;
440
441 /* If a crash occurs while doing this, don't try again. */
442 if (recurse != 0)
443 return;
444
445 ++recurse;
446
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000448 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000449 {
450 Python_RestoreThread(); /* enter python */
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000451 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000454#else
455 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000456 {
457 Python_RestoreThread(); /* enter python */
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000458 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000461
462 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463}
464
465 static int
466Python_Init(void)
467{
468 if (!initialised)
469 {
470#ifdef DYNAMIC_PYTHON
471 if (!python_enabled(TRUE))
472 {
473 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
474 goto fail;
475 }
476#endif
477
478#if !defined(MACOS) || defined(MACOS_X_UNIX)
479 Py_Initialize();
480#else
481 PyMac_Initialize();
482#endif
483 /* initialise threads */
484 PyEval_InitThreads();
485
486#ifdef DYNAMIC_PYTHON
487 get_exceptions();
488#endif
489
490 if (PythonIO_Init())
491 goto fail;
492
493 if (PythonMod_Init())
494 goto fail;
495
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000496 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498
499 initialised = 1;
500 }
501
502 return 0;
503
504fail:
505 /* We call PythonIO_Flush() here to print any Python errors.
506 * This is OK, as it is possible to call this function even
507 * if PythonIO_Init() has not completed successfully (it will
508 * not do anything in this case).
509 */
510 PythonIO_Flush();
511 return -1;
512}
513
514/*
515 * External interface
516 */
517 static void
518DoPythonCommand(exarg_T *eap, const char *cmd)
519{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000520#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521 static int recursive = 0;
522#endif
523#if defined(MACOS) && !defined(MACOS_X_UNIX)
524 GrafPtr oldPort;
525#endif
526#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
527 char *saved_locale;
528#endif
529
530#ifndef PY_CAN_RECURSE
531 if (recursive)
532 {
533 EMSG(_("E659: Cannot invoke Python recursively"));
534 return;
535 }
536 ++recursive;
537#endif
538
539#if defined(MACOS) && !defined(MACOS_X_UNIX)
540 GetPort(&oldPort);
541 /* Check if the Python library is available */
542 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
543 goto theend;
544#endif
545 if (Python_Init())
546 goto theend;
547
548 RangeStart = eap->line1;
549 RangeEnd = eap->line2;
550 Python_Release_Vim(); /* leave vim */
551
552#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
553 /* Python only works properly when the LC_NUMERIC locale is "C". */
554 saved_locale = setlocale(LC_NUMERIC, NULL);
555 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
556 saved_locale = NULL;
557 else
558 {
559 /* Need to make a copy, value may change when setting new locale. */
560 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
561 (void)setlocale(LC_NUMERIC, "C");
562 }
563#endif
564
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566
567 PyRun_SimpleString((char *)(cmd));
568
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570
571#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
572 if (saved_locale != NULL)
573 {
574 (void)setlocale(LC_NUMERIC, saved_locale);
575 vim_free(saved_locale);
576 }
577#endif
578
579 Python_Lock_Vim(); /* enter vim */
580 PythonIO_Flush();
581#if defined(MACOS) && !defined(MACOS_X_UNIX)
582 SetPort(oldPort);
583#endif
584
585theend:
586#ifndef PY_CAN_RECURSE
587 --recursive;
588#endif
589 return; /* keeps lint happy */
590}
591
592/*
593 * ":python"
594 */
595 void
596ex_python(exarg_T *eap)
597{
598 char_u *script;
599
600 script = script_get(eap, eap->arg);
601 if (!eap->skip)
602 {
603 if (script == NULL)
604 DoPythonCommand(eap, (char *)eap->arg);
605 else
606 DoPythonCommand(eap, (char *)script);
607 }
608 vim_free(script);
609}
610
611#define BUFFER_SIZE 1024
612
613/*
614 * ":pyfile"
615 */
616 void
617ex_pyfile(exarg_T *eap)
618{
619 static char buffer[BUFFER_SIZE];
620 const char *file = (char *)eap->arg;
621 char *p;
622
623 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
624 * stdio file pointer, but Vim and the Python DLL are compiled with
625 * different options under Windows, meaning that stdio pointers aren't
626 * compatible between the two. Yuk.
627 *
628 * Put the string "execfile('file')" into buffer. But, we need to
629 * escape any backslashes or single quotes in the file name, so that
630 * Python won't mangle the file name.
631 */
632 strcpy(buffer, "execfile('");
633 p = buffer + 10; /* size of "execfile('" */
634
635 while (*file && p < buffer + (BUFFER_SIZE - 3))
636 {
637 if (*file == '\\' || *file == '\'')
638 *p++ = '\\';
639 *p++ = *file++;
640 }
641
642 /* If we didn't finish the file name, we hit a buffer overflow */
643 if (*file != '\0')
644 return;
645
646 /* Put in the terminating "')" and a null */
647 *p++ = '\'';
648 *p++ = ')';
649 *p++ = '\0';
650
651 /* Execute the file */
652 DoPythonCommand(eap, buffer);
653}
654
655/******************************************************
656 * 2. Python output stream: writes output via [e]msg().
657 */
658
659/* Implementation functions
660 */
661
662static PyObject *OutputGetattr(PyObject *, char *);
663static int OutputSetattr(PyObject *, char *, PyObject *);
664
665static PyObject *OutputWrite(PyObject *, PyObject *);
666static PyObject *OutputWritelines(PyObject *, PyObject *);
667
668typedef void (*writefn)(char_u *);
669static void writer(writefn fn, char_u *str, int n);
670
671/* Output object definition
672 */
673
674typedef struct
675{
676 PyObject_HEAD
677 long softspace;
678 long error;
679} OutputObject;
680
681static struct PyMethodDef OutputMethods[] = {
682 /* name, function, calling, documentation */
683 {"write", OutputWrite, 1, "" },
684 {"writelines", OutputWritelines, 1, "" },
685 { NULL, NULL, 0, NULL }
686};
687
688static PyTypeObject OutputType = {
689 PyObject_HEAD_INIT(0)
690 0,
691 "message",
692 sizeof(OutputObject),
693 0,
694
695 (destructor) 0,
696 (printfunc) 0,
697 (getattrfunc) OutputGetattr,
698 (setattrfunc) OutputSetattr,
699 (cmpfunc) 0,
700 (reprfunc) 0,
701
702 0, /* as number */
703 0, /* as sequence */
704 0, /* as mapping */
705
706 (hashfunc) 0,
707 (ternaryfunc) 0,
708 (reprfunc) 0
709};
710
711/*************/
712
713 static PyObject *
714OutputGetattr(PyObject *self, char *name)
715{
716 if (strcmp(name, "softspace") == 0)
717 return PyInt_FromLong(((OutputObject *)(self))->softspace);
718
719 return Py_FindMethod(OutputMethods, self, name);
720}
721
722 static int
723OutputSetattr(PyObject *self, char *name, PyObject *val)
724{
725 if (val == NULL) {
726 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
727 return -1;
728 }
729
730 if (strcmp(name, "softspace") == 0)
731 {
732 if (!PyInt_Check(val)) {
733 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
734 return -1;
735 }
736
737 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
738 return 0;
739 }
740
741 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
742 return -1;
743}
744
745/*************/
746
747 static PyObject *
748OutputWrite(PyObject *self, PyObject *args)
749{
750 int len;
751 char *str;
752 int error = ((OutputObject *)(self))->error;
753
754 if (!PyArg_ParseTuple(args, "s#", &str, &len))
755 return NULL;
756
757 Py_BEGIN_ALLOW_THREADS
758 Python_Lock_Vim();
759 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
760 Python_Release_Vim();
761 Py_END_ALLOW_THREADS
762
763 Py_INCREF(Py_None);
764 return Py_None;
765}
766
767 static PyObject *
768OutputWritelines(PyObject *self, PyObject *args)
769{
770 int n;
771 int i;
772 PyObject *list;
773 int error = ((OutputObject *)(self))->error;
774
775 if (!PyArg_ParseTuple(args, "O", &list))
776 return NULL;
777 Py_INCREF(list);
778
779 if (!PyList_Check(list)) {
780 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
781 Py_DECREF(list);
782 return NULL;
783 }
784
785 n = PyList_Size(list);
786
787 for (i = 0; i < n; ++i)
788 {
789 PyObject *line = PyList_GetItem(list, i);
790 char *str;
791 int len;
792
793 if (!PyArg_Parse(line, "s#", &str, &len)) {
794 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
795 Py_DECREF(list);
796 return NULL;
797 }
798
799 Py_BEGIN_ALLOW_THREADS
800 Python_Lock_Vim();
801 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
802 Python_Release_Vim();
803 Py_END_ALLOW_THREADS
804 }
805
806 Py_DECREF(list);
807 Py_INCREF(Py_None);
808 return Py_None;
809}
810
811/* Output buffer management
812 */
813
814static char_u *buffer = NULL;
815static int buffer_len = 0;
816static int buffer_size = 0;
817
818static writefn old_fn = NULL;
819
820 static void
821buffer_ensure(int n)
822{
823 int new_size;
824 char_u *new_buffer;
825
826 if (n < buffer_size)
827 return;
828
829 new_size = buffer_size;
830 while (new_size < n)
831 new_size += 80;
832
833 if (new_size != buffer_size)
834 {
835 new_buffer = alloc((unsigned)new_size);
836 if (new_buffer == NULL)
837 return;
838
839 if (buffer)
840 {
841 memcpy(new_buffer, buffer, buffer_len);
842 vim_free(buffer);
843 }
844
845 buffer = new_buffer;
846 buffer_size = new_size;
847 }
848}
849
850 static void
851PythonIO_Flush(void)
852{
853 if (old_fn && buffer_len)
854 {
855 buffer[buffer_len] = 0;
856 old_fn(buffer);
857 }
858
859 buffer_len = 0;
860}
861
862 static void
863writer(writefn fn, char_u *str, int n)
864{
865 char_u *ptr;
866
867 if (fn != old_fn && old_fn != NULL)
868 PythonIO_Flush();
869
870 old_fn = fn;
871
872 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
873 {
874 int len = ptr - str;
875
876 buffer_ensure(buffer_len + len + 1);
877
878 memcpy(buffer + buffer_len, str, len);
879 buffer_len += len;
880 buffer[buffer_len] = 0;
881 fn(buffer);
882 str = ptr + 1;
883 n -= len + 1;
884 buffer_len = 0;
885 }
886
887 /* Put the remaining text into the buffer for later printing */
888 buffer_ensure(buffer_len + n + 1);
889 memcpy(buffer + buffer_len, str, n);
890 buffer_len += n;
891}
892
893/***************/
894
895static OutputObject Output =
896{
897 PyObject_HEAD_INIT(&OutputType)
898 0,
899 0
900};
901
902static OutputObject Error =
903{
904 PyObject_HEAD_INIT(&OutputType)
905 0,
906 1
907};
908
909 static int
910PythonIO_Init(void)
911{
912 /* Fixups... */
913 OutputType.ob_type = &PyType_Type;
914
Bram Moolenaar7df2d662005-01-25 22:18:08 +0000915 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
916 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917
918 if (PyErr_Occurred())
919 {
920 EMSG(_("E264: Python: Error initialising I/O objects"));
921 return -1;
922 }
923
924 return 0;
925}
926
927/******************************************************
928 * 3. Implementation of the Vim module for Python
929 */
930
931/* Vim module - Implementation functions
932 * -------------------------------------
933 */
934
935static PyObject *VimError;
936
937static PyObject *VimCommand(PyObject *, PyObject *);
938static PyObject *VimEval(PyObject *, PyObject *);
939
940/* Window type - Implementation functions
941 * --------------------------------------
942 */
943
944typedef struct
945{
946 PyObject_HEAD
947 win_T *win;
948}
949WindowObject;
950
951#define INVALID_WINDOW_VALUE ((win_T *)(-1))
952
953#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
954
955static PyObject *WindowNew(win_T *);
956
957static void WindowDestructor(PyObject *);
958static PyObject *WindowGetattr(PyObject *, char *);
959static int WindowSetattr(PyObject *, char *, PyObject *);
960static PyObject *WindowRepr(PyObject *);
961
962/* Buffer type - Implementation functions
963 * --------------------------------------
964 */
965
966typedef struct
967{
968 PyObject_HEAD
969 buf_T *buf;
970}
971BufferObject;
972
973#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
974
975#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
976
977static PyObject *BufferNew (buf_T *);
978
979static void BufferDestructor(PyObject *);
980static PyObject *BufferGetattr(PyObject *, char *);
981static PyObject *BufferRepr(PyObject *);
982
983static int BufferLength(PyObject *);
984static PyObject *BufferItem(PyObject *, int);
985static PyObject *BufferSlice(PyObject *, int, int);
986static int BufferAssItem(PyObject *, int, PyObject *);
987static int BufferAssSlice(PyObject *, int, int, PyObject *);
988
989static PyObject *BufferAppend(PyObject *, PyObject *);
990static PyObject *BufferMark(PyObject *, PyObject *);
991static PyObject *BufferRange(PyObject *, PyObject *);
992
993/* Line range type - Implementation functions
994 * --------------------------------------
995 */
996
997typedef struct
998{
999 PyObject_HEAD
1000 BufferObject *buf;
1001 int start;
1002 int end;
1003}
1004RangeObject;
1005
1006#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1007
1008static PyObject *RangeNew(buf_T *, int, int);
1009
1010static void RangeDestructor(PyObject *);
1011static PyObject *RangeGetattr(PyObject *, char *);
1012static PyObject *RangeRepr(PyObject *);
1013
1014static int RangeLength(PyObject *);
1015static PyObject *RangeItem(PyObject *, int);
1016static PyObject *RangeSlice(PyObject *, int, int);
1017static int RangeAssItem(PyObject *, int, PyObject *);
1018static int RangeAssSlice(PyObject *, int, int, PyObject *);
1019
1020static PyObject *RangeAppend(PyObject *, PyObject *);
1021
1022/* Window list type - Implementation functions
1023 * -------------------------------------------
1024 */
1025
1026static int WinListLength(PyObject *);
1027static PyObject *WinListItem(PyObject *, int);
1028
1029/* Buffer list type - Implementation functions
1030 * -------------------------------------------
1031 */
1032
1033static int BufListLength(PyObject *);
1034static PyObject *BufListItem(PyObject *, int);
1035
1036/* Current objects type - Implementation functions
1037 * -----------------------------------------------
1038 */
1039
1040static PyObject *CurrentGetattr(PyObject *, char *);
1041static int CurrentSetattr(PyObject *, char *, PyObject *);
1042
1043/* Vim module - Definitions
1044 */
1045
1046static struct PyMethodDef VimMethods[] = {
1047 /* name, function, calling, documentation */
1048 {"command", VimCommand, 1, "" },
1049 {"eval", VimEval, 1, "" },
1050 { NULL, NULL, 0, NULL }
1051};
1052
1053/* Vim module - Implementation
1054 */
1055/*ARGSUSED*/
1056 static PyObject *
1057VimCommand(PyObject *self, PyObject *args)
1058{
1059 char *cmd;
1060 PyObject *result;
1061
1062 if (!PyArg_ParseTuple(args, "s", &cmd))
1063 return NULL;
1064
1065 PyErr_Clear();
1066
1067 Py_BEGIN_ALLOW_THREADS
1068 Python_Lock_Vim();
1069
1070 do_cmdline_cmd((char_u *)cmd);
1071 update_screen(VALID);
1072
1073 Python_Release_Vim();
1074 Py_END_ALLOW_THREADS
1075
1076 if (VimErrorCheck())
1077 result = NULL;
1078 else
1079 result = Py_None;
1080
1081 Py_XINCREF(result);
1082 return result;
1083}
1084
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001085/*
1086 * Function to translate a typval_T into a PyObject; this will recursively
1087 * translate lists/dictionaries into their Python equivalents.
1088 *
1089 * The depth parameter is too avoid infinite recursion, set it to 1 when
1090 * you call VimToPython.
1091 */
1092 static PyObject *
1093VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1094{
1095 PyObject *result;
1096 PyObject *newObj;
1097 char ptrBuf[NUMBUFLEN];
1098
1099 /* Avoid infinite recursion */
1100 if (depth > 100)
1101 {
1102 Py_INCREF(Py_None);
1103 result = Py_None;
1104 return result;
1105 }
1106
1107 /* Check if we run into a recursive loop. The item must be in lookupDict
1108 * then and we can use it again. */
1109 sprintf(ptrBuf, "%ld", (long)our_tv);
1110 result = PyDict_GetItemString(lookupDict, ptrBuf);
1111 if (result != NULL)
1112 Py_INCREF(result);
1113 else if (our_tv->v_type == VAR_STRING)
1114 {
1115 result = Py_BuildValue("s", our_tv->vval.v_string);
1116 PyDict_SetItemString(lookupDict, ptrBuf, result);
1117 }
1118 else if (our_tv->v_type == VAR_NUMBER)
1119 {
1120 char buf[NUMBUFLEN];
1121
1122 /* For backwards compatibility numbers are stored as strings. */
1123 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1124 result = Py_BuildValue("s", buf);
1125 PyDict_SetItemString(lookupDict, ptrBuf, result);
1126 }
1127 else if (our_tv->v_type == VAR_LIST)
1128 {
1129 list_T *list = our_tv->vval.v_list;
1130 listitem_T *curr;
1131
1132 result = PyList_New(0);
1133 PyDict_SetItemString(lookupDict, ptrBuf, result);
1134
1135 if (list != NULL)
1136 {
1137 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1138 {
1139 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1140 PyList_Append(result, newObj);
1141 Py_DECREF(newObj);
1142 }
1143 }
1144 }
1145 else if (our_tv->v_type == VAR_DICT)
1146 {
1147 result = PyDict_New();
1148 PyDict_SetItemString(lookupDict, ptrBuf, result);
1149
1150 if (our_tv->vval.v_dict != NULL)
1151 {
1152 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1153 int todo = ht->ht_used;
1154 hashitem_T *hi;
1155 dictitem_T *di;
1156
1157 for (hi = ht->ht_array; todo > 0; ++hi)
1158 {
1159 if (!HASHITEM_EMPTY(hi))
1160 {
1161 --todo;
1162
1163 di = dict_lookup(hi);
1164 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1165 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1166 Py_DECREF(newObj);
1167 }
1168 }
1169 }
1170 }
1171 else
1172 {
1173 Py_INCREF(Py_None);
1174 result = Py_None;
1175 }
1176
1177 return result;
1178}
1179
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180/*ARGSUSED*/
1181 static PyObject *
1182VimEval(PyObject *self, PyObject *args)
1183{
1184#ifdef FEAT_EVAL
1185 char *expr;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001186 typval_T *our_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187 PyObject *result;
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001188 PyObject *lookup_dict;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189
1190 if (!PyArg_ParseTuple(args, "s", &expr))
1191 return NULL;
1192
1193 Py_BEGIN_ALLOW_THREADS
1194 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001195 our_tv = eval_expr((char_u *)expr, NULL);
1196
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197 Python_Release_Vim();
1198 Py_END_ALLOW_THREADS
1199
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001200 if (our_tv == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201 {
1202 PyErr_SetVim(_("invalid expression"));
1203 return NULL;
1204 }
1205
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001206 /* Convert the Vim type into a Python type. Create a dictionary that's
1207 * used to check for recursive loops. */
1208 lookup_dict = PyDict_New();
1209 result = VimToPython(our_tv, 1, lookup_dict);
1210 Py_DECREF(lookup_dict);
1211
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212
1213 Py_BEGIN_ALLOW_THREADS
1214 Python_Lock_Vim();
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00001215 free_tv(our_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 Python_Release_Vim();
1217 Py_END_ALLOW_THREADS
1218
1219 return result;
1220#else
1221 PyErr_SetVim(_("expressions disabled at compile time"));
1222 return NULL;
1223#endif
1224}
1225
1226/* Common routines for buffers and line ranges
1227 * -------------------------------------------
1228 */
1229 static int
1230CheckBuffer(BufferObject *this)
1231{
1232 if (this->buf == INVALID_BUFFER_VALUE)
1233 {
1234 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1235 return -1;
1236 }
1237
1238 return 0;
1239}
1240
1241 static PyObject *
1242RBItem(BufferObject *self, int n, int start, int end)
1243{
1244 if (CheckBuffer(self))
1245 return NULL;
1246
1247 if (n < 0 || n > end - start)
1248 {
1249 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1250 return NULL;
1251 }
1252
1253 return GetBufferLine(self->buf, n+start);
1254}
1255
1256 static PyObject *
1257RBSlice(BufferObject *self, int lo, int hi, int start, int end)
1258{
1259 int size;
1260
1261 if (CheckBuffer(self))
1262 return NULL;
1263
1264 size = end - start + 1;
1265
1266 if (lo < 0)
1267 lo = 0;
1268 else if (lo > size)
1269 lo = size;
1270 if (hi < 0)
1271 hi = 0;
1272 if (hi < lo)
1273 hi = lo;
1274 else if (hi > size)
1275 hi = size;
1276
1277 return GetBufferLineList(self->buf, lo+start, hi+start);
1278}
1279
1280 static int
1281RBAssItem(BufferObject *self, int n, PyObject *val, int start, int end, int *new_end)
1282{
1283 int len_change;
1284
1285 if (CheckBuffer(self))
1286 return -1;
1287
1288 if (n < 0 || n > end - start)
1289 {
1290 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1291 return -1;
1292 }
1293
1294 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1295 return -1;
1296
1297 if (new_end)
1298 *new_end = end + len_change;
1299
1300 return 0;
1301}
1302
1303 static int
1304RBAssSlice(BufferObject *self, int lo, int hi, PyObject *val, int start, int end, int *new_end)
1305{
1306 int size;
1307 int len_change;
1308
1309 /* Self must be a valid buffer */
1310 if (CheckBuffer(self))
1311 return -1;
1312
1313 /* Sort out the slice range */
1314 size = end - start + 1;
1315
1316 if (lo < 0)
1317 lo = 0;
1318 else if (lo > size)
1319 lo = size;
1320 if (hi < 0)
1321 hi = 0;
1322 if (hi < lo)
1323 hi = lo;
1324 else if (hi > size)
1325 hi = size;
1326
1327 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1328 return -1;
1329
1330 if (new_end)
1331 *new_end = end + len_change;
1332
1333 return 0;
1334}
1335
1336 static PyObject *
1337RBAppend(BufferObject *self, PyObject *args, int start, int end, int *new_end)
1338{
1339 PyObject *lines;
1340 int len_change;
1341 int max;
1342 int n;
1343
1344 if (CheckBuffer(self))
1345 return NULL;
1346
1347 max = n = end - start + 1;
1348
1349 if (!PyArg_ParseTuple(args, "O|i", &lines, &n))
1350 return NULL;
1351
1352 if (n < 0 || n > max)
1353 {
1354 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1355 return NULL;
1356 }
1357
1358 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1359 return NULL;
1360
1361 if (new_end)
1362 *new_end = end + len_change;
1363
1364 Py_INCREF(Py_None);
1365 return Py_None;
1366}
1367
1368
1369/* Buffer object - Definitions
1370 */
1371
1372static struct PyMethodDef BufferMethods[] = {
1373 /* name, function, calling, documentation */
1374 {"append", BufferAppend, 1, "" },
1375 {"mark", BufferMark, 1, "" },
1376 {"range", BufferRange, 1, "" },
1377 { NULL, NULL, 0, NULL }
1378};
1379
1380static PySequenceMethods BufferAsSeq = {
1381 (inquiry) BufferLength, /* sq_length, len(x) */
1382 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1383 (intargfunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1384 (intargfunc) BufferItem, /* sq_item, x[i] */
1385 (intintargfunc) BufferSlice, /* sq_slice, x[i:j] */
1386 (intobjargproc) BufferAssItem, /* sq_ass_item, x[i]=v */
1387 (intintobjargproc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1388};
1389
1390static PyTypeObject BufferType = {
1391 PyObject_HEAD_INIT(0)
1392 0,
1393 "buffer",
1394 sizeof(BufferObject),
1395 0,
1396
1397 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1398 (printfunc) 0, /* tp_print, print x */
1399 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1400 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1401 (cmpfunc) 0, /* tp_compare, x>y */
1402 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1403
1404 0, /* as number */
1405 &BufferAsSeq, /* as sequence */
1406 0, /* as mapping */
1407
1408 (hashfunc) 0, /* tp_hash, dict(x) */
1409 (ternaryfunc) 0, /* tp_call, x() */
1410 (reprfunc) 0, /* tp_str, str(x) */
1411};
1412
1413/* Buffer object - Implementation
1414 */
1415
1416 static PyObject *
1417BufferNew(buf_T *buf)
1418{
1419 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001420 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421 * then we can get at it in buf_freeall() in vim. We then
1422 * need to create only ONE Python object per buffer - if
1423 * we try to create a second, just INCREF the existing one
1424 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001425 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426 * Question: what to do on a buf_freeall(). We'll probably
1427 * have to either delete the Python object (DECREF it to
1428 * zero - a bad idea, as it leaves dangling refs!) or
1429 * set the buf_T * value to an invalid value (-1?), which
1430 * means we need checks in all access functions... Bah.
1431 */
1432
1433 BufferObject *self;
1434
Bram Moolenaare344bea2005-09-01 20:46:49 +00001435 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001436 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001437 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 Py_INCREF(self);
1439 }
1440 else
1441 {
1442 self = PyObject_NEW(BufferObject, &BufferType);
1443 if (self == NULL)
1444 return NULL;
1445 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001446 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 }
1448
1449 return (PyObject *)(self);
1450}
1451
1452 static void
1453BufferDestructor(PyObject *self)
1454{
1455 BufferObject *this = (BufferObject *)(self);
1456
1457 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001458 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459
1460 PyMem_DEL(self);
1461}
1462
1463 static PyObject *
1464BufferGetattr(PyObject *self, char *name)
1465{
1466 BufferObject *this = (BufferObject *)(self);
1467
1468 if (CheckBuffer(this))
1469 return NULL;
1470
1471 if (strcmp(name, "name") == 0)
1472 return Py_BuildValue("s",this->buf->b_ffname);
1473 else if (strcmp(name, "number") == 0)
1474 return Py_BuildValue("i",this->buf->b_fnum);
1475 else if (strcmp(name,"__members__") == 0)
1476 return Py_BuildValue("[ss]", "name", "number");
1477 else
1478 return Py_FindMethod(BufferMethods, self, name);
1479}
1480
1481 static PyObject *
1482BufferRepr(PyObject *self)
1483{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001484 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485 BufferObject *this = (BufferObject *)(self);
1486
1487 if (this->buf == INVALID_BUFFER_VALUE)
1488 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00001489 vim_snprintf(repr, 100, _("<buffer object (deleted) at %8lX>"),
1490 (long)(self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 return PyString_FromString(repr);
1492 }
1493 else
1494 {
1495 char *name = (char *)this->buf->b_fname;
1496 int len;
1497
1498 if (name == NULL)
1499 name = "";
1500 len = strlen(name);
1501
1502 if (len > 35)
1503 name = name + (35 - len);
1504
Bram Moolenaar555b2802005-05-19 21:08:39 +00001505 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506
1507 return PyString_FromString(repr);
1508 }
1509}
1510
1511/******************/
1512
1513 static int
1514BufferLength(PyObject *self)
1515{
1516 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1517 if (CheckBuffer((BufferObject *)(self)))
1518 return -1; /* ??? */
1519
1520 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1521}
1522
1523 static PyObject *
1524BufferItem(PyObject *self, int n)
1525{
1526 return RBItem((BufferObject *)(self), n, 1,
1527 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1528}
1529
1530 static PyObject *
1531BufferSlice(PyObject *self, int lo, int hi)
1532{
1533 return RBSlice((BufferObject *)(self), lo, hi, 1,
1534 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1535}
1536
1537 static int
1538BufferAssItem(PyObject *self, int n, PyObject *val)
1539{
1540 return RBAssItem((BufferObject *)(self), n, val, 1,
1541 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1542 NULL);
1543}
1544
1545 static int
1546BufferAssSlice(PyObject *self, int lo, int hi, PyObject *val)
1547{
1548 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1549 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1550 NULL);
1551}
1552
1553 static PyObject *
1554BufferAppend(PyObject *self, PyObject *args)
1555{
1556 return RBAppend((BufferObject *)(self), args, 1,
1557 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1558 NULL);
1559}
1560
1561 static PyObject *
1562BufferMark(PyObject *self, PyObject *args)
1563{
1564 pos_T *posp;
1565 char mark;
1566 buf_T *curbuf_save;
1567
1568 if (CheckBuffer((BufferObject *)(self)))
1569 return NULL;
1570
1571 if (!PyArg_ParseTuple(args, "c", &mark))
1572 return NULL;
1573
1574 curbuf_save = curbuf;
1575 curbuf = ((BufferObject *)(self))->buf;
1576 posp = getmark(mark, FALSE);
1577 curbuf = curbuf_save;
1578
1579 if (posp == NULL)
1580 {
1581 PyErr_SetVim(_("invalid mark name"));
1582 return NULL;
1583 }
1584
1585 /* Ckeck for keyboard interrupt */
1586 if (VimErrorCheck())
1587 return NULL;
1588
1589 if (posp->lnum <= 0)
1590 {
1591 /* Or raise an error? */
1592 Py_INCREF(Py_None);
1593 return Py_None;
1594 }
1595
1596 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1597}
1598
1599 static PyObject *
1600BufferRange(PyObject *self, PyObject *args)
1601{
1602 int start;
1603 int end;
1604
1605 if (CheckBuffer((BufferObject *)(self)))
1606 return NULL;
1607
1608 if (!PyArg_ParseTuple(args, "ii", &start, &end))
1609 return NULL;
1610
1611 return RangeNew(((BufferObject *)(self))->buf, start, end);
1612}
1613
1614/* Line range object - Definitions
1615 */
1616
1617static struct PyMethodDef RangeMethods[] = {
1618 /* name, function, calling, documentation */
1619 {"append", RangeAppend, 1, "" },
1620 { NULL, NULL, 0, NULL }
1621};
1622
1623static PySequenceMethods RangeAsSeq = {
1624 (inquiry) RangeLength, /* sq_length, len(x) */
1625 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1626 (intargfunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1627 (intargfunc) RangeItem, /* sq_item, x[i] */
1628 (intintargfunc) RangeSlice, /* sq_slice, x[i:j] */
1629 (intobjargproc) RangeAssItem, /* sq_ass_item, x[i]=v */
1630 (intintobjargproc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1631};
1632
1633static PyTypeObject RangeType = {
1634 PyObject_HEAD_INIT(0)
1635 0,
1636 "range",
1637 sizeof(RangeObject),
1638 0,
1639
1640 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1641 (printfunc) 0, /* tp_print, print x */
1642 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1643 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1644 (cmpfunc) 0, /* tp_compare, x>y */
1645 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1646
1647 0, /* as number */
1648 &RangeAsSeq, /* as sequence */
1649 0, /* as mapping */
1650
1651 (hashfunc) 0, /* tp_hash, dict(x) */
1652 (ternaryfunc) 0, /* tp_call, x() */
1653 (reprfunc) 0, /* tp_str, str(x) */
1654};
1655
1656/* Line range object - Implementation
1657 */
1658
1659 static PyObject *
1660RangeNew(buf_T *buf, int start, int end)
1661{
1662 BufferObject *bufr;
1663 RangeObject *self;
1664 self = PyObject_NEW(RangeObject, &RangeType);
1665 if (self == NULL)
1666 return NULL;
1667
1668 bufr = (BufferObject *)BufferNew(buf);
1669 if (bufr == NULL)
1670 {
1671 PyMem_DEL(self);
1672 return NULL;
1673 }
1674 Py_INCREF(bufr);
1675
1676 self->buf = bufr;
1677 self->start = start;
1678 self->end = end;
1679
1680 return (PyObject *)(self);
1681}
1682
1683 static void
1684RangeDestructor(PyObject *self)
1685{
1686 Py_DECREF(((RangeObject *)(self))->buf);
1687 PyMem_DEL(self);
1688}
1689
1690 static PyObject *
1691RangeGetattr(PyObject *self, char *name)
1692{
1693 if (strcmp(name, "start") == 0)
1694 return Py_BuildValue("i",((RangeObject *)(self))->start - 1);
1695 else if (strcmp(name, "end") == 0)
1696 return Py_BuildValue("i",((RangeObject *)(self))->end - 1);
1697 else
1698 return Py_FindMethod(RangeMethods, self, name);
1699}
1700
1701 static PyObject *
1702RangeRepr(PyObject *self)
1703{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001704 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 RangeObject *this = (RangeObject *)(self);
1706
1707 if (this->buf->buf == INVALID_BUFFER_VALUE)
1708 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00001709 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %8lX>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 (long)(self));
1711 return PyString_FromString(repr);
1712 }
1713 else
1714 {
1715 char *name = (char *)this->buf->buf->b_fname;
1716 int len;
1717
1718 if (name == NULL)
1719 name = "";
1720 len = strlen(name);
1721
1722 if (len > 45)
1723 name = name + (45 - len);
1724
Bram Moolenaar555b2802005-05-19 21:08:39 +00001725 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 len > 45 ? "..." : "", name,
1727 this->start, this->end);
1728
1729 return PyString_FromString(repr);
1730 }
1731}
1732
1733/****************/
1734
1735 static int
1736RangeLength(PyObject *self)
1737{
1738 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1739 if (CheckBuffer(((RangeObject *)(self))->buf))
1740 return -1; /* ??? */
1741
1742 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1743}
1744
1745 static PyObject *
1746RangeItem(PyObject *self, int n)
1747{
1748 return RBItem(((RangeObject *)(self))->buf, n,
1749 ((RangeObject *)(self))->start,
1750 ((RangeObject *)(self))->end);
1751}
1752
1753 static PyObject *
1754RangeSlice(PyObject *self, int lo, int hi)
1755{
1756 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1757 ((RangeObject *)(self))->start,
1758 ((RangeObject *)(self))->end);
1759}
1760
1761 static int
1762RangeAssItem(PyObject *self, int n, PyObject *val)
1763{
1764 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1765 ((RangeObject *)(self))->start,
1766 ((RangeObject *)(self))->end,
1767 &((RangeObject *)(self))->end);
1768}
1769
1770 static int
1771RangeAssSlice(PyObject *self, int lo, int hi, PyObject *val)
1772{
1773 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1774 ((RangeObject *)(self))->start,
1775 ((RangeObject *)(self))->end,
1776 &((RangeObject *)(self))->end);
1777}
1778
1779 static PyObject *
1780RangeAppend(PyObject *self, PyObject *args)
1781{
1782 return RBAppend(((RangeObject *)(self))->buf, args,
1783 ((RangeObject *)(self))->start,
1784 ((RangeObject *)(self))->end,
1785 &((RangeObject *)(self))->end);
1786}
1787
1788/* Buffer list object - Definitions
1789 */
1790
1791typedef struct
1792{
1793 PyObject_HEAD
1794}
1795BufListObject;
1796
1797static PySequenceMethods BufListAsSeq = {
1798 (inquiry) BufListLength, /* sq_length, len(x) */
1799 (binaryfunc) 0, /* sq_concat, x+y */
1800 (intargfunc) 0, /* sq_repeat, x*n */
1801 (intargfunc) BufListItem, /* sq_item, x[i] */
1802 (intintargfunc) 0, /* sq_slice, x[i:j] */
1803 (intobjargproc) 0, /* sq_ass_item, x[i]=v */
1804 (intintobjargproc) 0, /* sq_ass_slice, x[i:j]=v */
1805};
1806
1807static PyTypeObject BufListType = {
1808 PyObject_HEAD_INIT(0)
1809 0,
1810 "buffer list",
1811 sizeof(BufListObject),
1812 0,
1813
1814 (destructor) 0, /* tp_dealloc, refcount==0 */
1815 (printfunc) 0, /* tp_print, print x */
1816 (getattrfunc) 0, /* tp_getattr, x.attr */
1817 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1818 (cmpfunc) 0, /* tp_compare, x>y */
1819 (reprfunc) 0, /* tp_repr, `x`, print x */
1820
1821 0, /* as number */
1822 &BufListAsSeq, /* as sequence */
1823 0, /* as mapping */
1824
1825 (hashfunc) 0, /* tp_hash, dict(x) */
1826 (ternaryfunc) 0, /* tp_call, x() */
1827 (reprfunc) 0, /* tp_str, str(x) */
1828};
1829
1830/* Buffer list object - Implementation
1831 */
1832
1833/*ARGSUSED*/
1834 static int
1835BufListLength(PyObject *self)
1836{
1837 buf_T *b = firstbuf;
1838 int n = 0;
1839
1840 while (b)
1841 {
1842 ++n;
1843 b = b->b_next;
1844 }
1845
1846 return n;
1847}
1848
1849/*ARGSUSED*/
1850 static PyObject *
1851BufListItem(PyObject *self, int n)
1852{
1853 buf_T *b;
1854
1855 for (b = firstbuf; b; b = b->b_next, --n)
1856 {
1857 if (n == 0)
1858 return BufferNew(b);
1859 }
1860
1861 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1862 return NULL;
1863}
1864
1865/* Window object - Definitions
1866 */
1867
1868static struct PyMethodDef WindowMethods[] = {
1869 /* name, function, calling, documentation */
1870 { NULL, NULL, 0, NULL }
1871};
1872
1873static PyTypeObject WindowType = {
1874 PyObject_HEAD_INIT(0)
1875 0,
1876 "window",
1877 sizeof(WindowObject),
1878 0,
1879
1880 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1881 (printfunc) 0, /* tp_print, print x */
1882 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1883 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1884 (cmpfunc) 0, /* tp_compare, x>y */
1885 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1886
1887 0, /* as number */
1888 0, /* as sequence */
1889 0, /* as mapping */
1890
1891 (hashfunc) 0, /* tp_hash, dict(x) */
1892 (ternaryfunc) 0, /* tp_call, x() */
1893 (reprfunc) 0, /* tp_str, str(x) */
1894};
1895
1896/* Window object - Implementation
1897 */
1898
1899 static PyObject *
1900WindowNew(win_T *win)
1901{
1902 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001903 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904 * then we can get at it in win_free() in vim. We then
1905 * need to create only ONE Python object per window - if
1906 * we try to create a second, just INCREF the existing one
1907 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001908 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 * On a win_free() we set the Python object's win_T* field
1910 * to an invalid value. We trap all uses of a window
1911 * object, and reject them if the win_T* field is invalid.
1912 */
1913
1914 WindowObject *self;
1915
Bram Moolenaare344bea2005-09-01 20:46:49 +00001916 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001918 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001919 Py_INCREF(self);
1920 }
1921 else
1922 {
1923 self = PyObject_NEW(WindowObject, &WindowType);
1924 if (self == NULL)
1925 return NULL;
1926 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001927 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 }
1929
1930 return (PyObject *)(self);
1931}
1932
1933 static void
1934WindowDestructor(PyObject *self)
1935{
1936 WindowObject *this = (WindowObject *)(self);
1937
1938 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001939 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940
1941 PyMem_DEL(self);
1942}
1943
1944 static int
1945CheckWindow(WindowObject *this)
1946{
1947 if (this->win == INVALID_WINDOW_VALUE)
1948 {
1949 PyErr_SetVim(_("attempt to refer to deleted window"));
1950 return -1;
1951 }
1952
1953 return 0;
1954}
1955
1956 static PyObject *
1957WindowGetattr(PyObject *self, char *name)
1958{
1959 WindowObject *this = (WindowObject *)(self);
1960
1961 if (CheckWindow(this))
1962 return NULL;
1963
1964 if (strcmp(name, "buffer") == 0)
1965 return (PyObject *)BufferNew(this->win->w_buffer);
1966 else if (strcmp(name, "cursor") == 0)
1967 {
1968 pos_T *pos = &this->win->w_cursor;
1969
1970 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1971 }
1972 else if (strcmp(name, "height") == 0)
1973 return Py_BuildValue("l", (long)(this->win->w_height));
1974#ifdef FEAT_VERTSPLIT
1975 else if (strcmp(name, "width") == 0)
1976 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1977#endif
1978 else if (strcmp(name,"__members__") == 0)
1979 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1980 else
1981 return Py_FindMethod(WindowMethods, self, name);
1982}
1983
1984 static int
1985WindowSetattr(PyObject *self, char *name, PyObject *val)
1986{
1987 WindowObject *this = (WindowObject *)(self);
1988
1989 if (CheckWindow(this))
1990 return -1;
1991
1992 if (strcmp(name, "buffer") == 0)
1993 {
1994 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1995 return -1;
1996 }
1997 else if (strcmp(name, "cursor") == 0)
1998 {
1999 long lnum;
2000 long col;
2001
2002 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2003 return -1;
2004
2005 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2006 {
2007 PyErr_SetVim(_("cursor position outside buffer"));
2008 return -1;
2009 }
2010
2011 /* Check for keyboard interrupts */
2012 if (VimErrorCheck())
2013 return -1;
2014
2015 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2016
2017 this->win->w_cursor.lnum = lnum;
2018 this->win->w_cursor.col = col;
2019 update_screen(VALID);
2020
2021 return 0;
2022 }
2023 else if (strcmp(name, "height") == 0)
2024 {
2025 int height;
2026 win_T *savewin;
2027
2028 if (!PyArg_Parse(val, "i", &height))
2029 return -1;
2030
2031#ifdef FEAT_GUI
2032 need_mouse_correct = TRUE;
2033#endif
2034 savewin = curwin;
2035 curwin = this->win;
2036 win_setheight(height);
2037 curwin = savewin;
2038
2039 /* Check for keyboard interrupts */
2040 if (VimErrorCheck())
2041 return -1;
2042
2043 return 0;
2044 }
2045#ifdef FEAT_VERTSPLIT
2046 else if (strcmp(name, "width") == 0)
2047 {
2048 int width;
2049 win_T *savewin;
2050
2051 if (!PyArg_Parse(val, "i", &width))
2052 return -1;
2053
2054#ifdef FEAT_GUI
2055 need_mouse_correct = TRUE;
2056#endif
2057 savewin = curwin;
2058 curwin = this->win;
2059 win_setwidth(width);
2060 curwin = savewin;
2061
2062 /* Check for keyboard interrupts */
2063 if (VimErrorCheck())
2064 return -1;
2065
2066 return 0;
2067 }
2068#endif
2069 else
2070 {
2071 PyErr_SetString(PyExc_AttributeError, name);
2072 return -1;
2073 }
2074}
2075
2076 static PyObject *
2077WindowRepr(PyObject *self)
2078{
Bram Moolenaar555b2802005-05-19 21:08:39 +00002079 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 WindowObject *this = (WindowObject *)(self);
2081
2082 if (this->win == INVALID_WINDOW_VALUE)
2083 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00002084 vim_snprintf(repr, 100, _("<window object (deleted) at %.8lX>"),
2085 (long)(self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 return PyString_FromString(repr);
2087 }
2088 else
2089 {
2090 int i = 0;
2091 win_T *w;
2092
2093 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2094 ++i;
2095
2096 if (w == NULL)
Bram Moolenaar555b2802005-05-19 21:08:39 +00002097 vim_snprintf(repr, 100, _("<window object (unknown) at %.8lX>"),
2098 (long)(self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 else
Bram Moolenaar555b2802005-05-19 21:08:39 +00002100 vim_snprintf(repr, 100, _("<window %d>"), i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002101
2102 return PyString_FromString(repr);
2103 }
2104}
2105
2106/* Window list object - Definitions
2107 */
2108
2109typedef struct
2110{
2111 PyObject_HEAD
2112}
2113WinListObject;
2114
2115static PySequenceMethods WinListAsSeq = {
2116 (inquiry) WinListLength, /* sq_length, len(x) */
2117 (binaryfunc) 0, /* sq_concat, x+y */
2118 (intargfunc) 0, /* sq_repeat, x*n */
2119 (intargfunc) WinListItem, /* sq_item, x[i] */
2120 (intintargfunc) 0, /* sq_slice, x[i:j] */
2121 (intobjargproc) 0, /* sq_ass_item, x[i]=v */
2122 (intintobjargproc) 0, /* sq_ass_slice, x[i:j]=v */
2123};
2124
2125static PyTypeObject WinListType = {
2126 PyObject_HEAD_INIT(0)
2127 0,
2128 "window list",
2129 sizeof(WinListObject),
2130 0,
2131
2132 (destructor) 0, /* tp_dealloc, refcount==0 */
2133 (printfunc) 0, /* tp_print, print x */
2134 (getattrfunc) 0, /* tp_getattr, x.attr */
2135 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2136 (cmpfunc) 0, /* tp_compare, x>y */
2137 (reprfunc) 0, /* tp_repr, `x`, print x */
2138
2139 0, /* as number */
2140 &WinListAsSeq, /* as sequence */
2141 0, /* as mapping */
2142
2143 (hashfunc) 0, /* tp_hash, dict(x) */
2144 (ternaryfunc) 0, /* tp_call, x() */
2145 (reprfunc) 0, /* tp_str, str(x) */
2146};
2147
2148/* Window list object - Implementation
2149 */
2150/*ARGSUSED*/
2151 static int
2152WinListLength(PyObject *self)
2153{
2154 win_T *w = firstwin;
2155 int n = 0;
2156
2157 while (w)
2158 {
2159 ++n;
2160 w = W_NEXT(w);
2161 }
2162
2163 return n;
2164}
2165
2166/*ARGSUSED*/
2167 static PyObject *
2168WinListItem(PyObject *self, int n)
2169{
2170 win_T *w;
2171
2172 for (w = firstwin; w; w = W_NEXT(w), --n)
2173 if (n == 0)
2174 return WindowNew(w);
2175
2176 PyErr_SetString(PyExc_IndexError, _("no such window"));
2177 return NULL;
2178}
2179
2180/* Current items object - Definitions
2181 */
2182
2183typedef struct
2184{
2185 PyObject_HEAD
2186}
2187CurrentObject;
2188
2189static PyTypeObject CurrentType = {
2190 PyObject_HEAD_INIT(0)
2191 0,
2192 "current data",
2193 sizeof(CurrentObject),
2194 0,
2195
2196 (destructor) 0, /* tp_dealloc, refcount==0 */
2197 (printfunc) 0, /* tp_print, print x */
2198 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2199 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2200 (cmpfunc) 0, /* tp_compare, x>y */
2201 (reprfunc) 0, /* tp_repr, `x`, print x */
2202
2203 0, /* as number */
2204 0, /* as sequence */
2205 0, /* as mapping */
2206
2207 (hashfunc) 0, /* tp_hash, dict(x) */
2208 (ternaryfunc) 0, /* tp_call, x() */
2209 (reprfunc) 0, /* tp_str, str(x) */
2210};
2211
2212/* Current items object - Implementation
2213 */
2214/*ARGSUSED*/
2215 static PyObject *
2216CurrentGetattr(PyObject *self, char *name)
2217{
2218 if (strcmp(name, "buffer") == 0)
2219 return (PyObject *)BufferNew(curbuf);
2220 else if (strcmp(name, "window") == 0)
2221 return (PyObject *)WindowNew(curwin);
2222 else if (strcmp(name, "line") == 0)
2223 return GetBufferLine(curbuf, (int)curwin->w_cursor.lnum);
2224 else if (strcmp(name, "range") == 0)
2225 return RangeNew(curbuf, RangeStart, RangeEnd);
2226 else if (strcmp(name,"__members__") == 0)
2227 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2228 else
2229 {
2230 PyErr_SetString(PyExc_AttributeError, name);
2231 return NULL;
2232 }
2233}
2234
2235/*ARGSUSED*/
2236 static int
2237CurrentSetattr(PyObject *self, char *name, PyObject *value)
2238{
2239 if (strcmp(name, "line") == 0)
2240 {
2241 if (SetBufferLine(curbuf, (int)curwin->w_cursor.lnum, value, NULL) == FAIL)
2242 return -1;
2243
2244 return 0;
2245 }
2246 else
2247 {
2248 PyErr_SetString(PyExc_AttributeError, name);
2249 return -1;
2250 }
2251}
2252
2253/* External interface
2254 */
2255
2256 void
2257python_buffer_free(buf_T *buf)
2258{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002259 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002261 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002263 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 }
2265}
2266
2267#if defined(FEAT_WINDOWS) || defined(PROTO)
2268 void
2269python_window_free(win_T *win)
2270{
Bram Moolenaare344bea2005-09-01 20:46:49 +00002271 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002272 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00002273 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00002275 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 }
2277}
2278#endif
2279
2280static BufListObject TheBufferList =
2281{
2282 PyObject_HEAD_INIT(&BufListType)
2283};
2284
2285static WinListObject TheWindowList =
2286{
2287 PyObject_HEAD_INIT(&WinListType)
2288};
2289
2290static CurrentObject TheCurrent =
2291{
2292 PyObject_HEAD_INIT(&CurrentType)
2293};
2294
2295 static int
2296PythonMod_Init(void)
2297{
2298 PyObject *mod;
2299 PyObject *dict;
2300 static char *(argv[2]) = {"", NULL};
2301
2302 /* Fixups... */
2303 BufferType.ob_type = &PyType_Type;
2304 RangeType.ob_type = &PyType_Type;
2305 WindowType.ob_type = &PyType_Type;
2306 BufListType.ob_type = &PyType_Type;
2307 WinListType.ob_type = &PyType_Type;
2308 CurrentType.ob_type = &PyType_Type;
2309
2310 /* Set sys.argv[] to avoid a crash in warn(). */
2311 PySys_SetArgv(1, argv);
2312
2313 mod = Py_InitModule("vim", VimMethods);
2314 dict = PyModule_GetDict(mod);
2315
2316 VimError = Py_BuildValue("s", "vim.error");
2317
2318 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00002319 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2320 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2321 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322
2323 if (PyErr_Occurred())
2324 return -1;
2325
2326 return 0;
2327}
2328
2329/*************************************************************************
2330 * 4. Utility functions for handling the interface between Vim and Python.
2331 */
2332
2333/* Get a line from the specified buffer. The line number is
2334 * in Vim format (1-based). The line is returned as a Python
2335 * string object.
2336 */
2337 static PyObject *
2338GetBufferLine(buf_T *buf, int n)
2339{
2340 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2341}
2342
2343/* Get a list of lines from the specified buffer. The line numbers
2344 * are in Vim format (1-based). The range is from lo up to, but not
2345 * including, hi. The list is returned as a Python list of string objects.
2346 */
2347 static PyObject *
2348GetBufferLineList(buf_T *buf, int lo, int hi)
2349{
2350 int i;
2351 int n = hi - lo;
2352 PyObject *list = PyList_New(n);
2353
2354 if (list == NULL)
2355 return NULL;
2356
2357 for (i = 0; i < n; ++i)
2358 {
2359 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2360
2361 /* Error check - was the Python string creation OK? */
2362 if (str == NULL)
2363 {
2364 Py_DECREF(list);
2365 return NULL;
2366 }
2367
2368 /* Set the list item */
2369 if (PyList_SetItem(list, i, str))
2370 {
2371 Py_DECREF(str);
2372 Py_DECREF(list);
2373 return NULL;
2374 }
2375 }
2376
2377 /* The ownership of the Python list is passed to the caller (ie,
2378 * the caller should Py_DECREF() the object when it is finished
2379 * with it).
2380 */
2381
2382 return list;
2383}
2384
2385/*
2386 * Check if deleting lines made the cursor position invalid.
2387 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2388 * deleted).
2389 */
2390 static void
2391py_fix_cursor(int lo, int hi, int extra)
2392{
2393 if (curwin->w_cursor.lnum >= lo)
2394 {
2395 /* Adjust the cursor position if it's in/after the changed
2396 * lines. */
2397 if (curwin->w_cursor.lnum >= hi)
2398 {
2399 curwin->w_cursor.lnum += extra;
2400 check_cursor_col();
2401 }
2402 else if (extra < 0)
2403 {
2404 curwin->w_cursor.lnum = lo;
2405 check_cursor();
2406 }
2407 changed_cline_bef_curs();
2408 }
2409 invalidate_botline();
2410}
2411
2412/* Replace a line in the specified buffer. The line number is
2413 * in Vim format (1-based). The replacement line is given as
2414 * a Python string object. The object is checked for validity
2415 * and correct format. Errors are returned as a value of FAIL.
2416 * The return value is OK on success.
2417 * If OK is returned and len_change is not NULL, *len_change
2418 * is set to the change in the buffer length.
2419 */
2420 static int
2421SetBufferLine(buf_T *buf, int n, PyObject *line, int *len_change)
2422{
2423 /* First of all, we check the thpe of the supplied Python object.
2424 * There are three cases:
2425 * 1. NULL, or None - this is a deletion.
2426 * 2. A string - this is a replacement.
2427 * 3. Anything else - this is an error.
2428 */
2429 if (line == Py_None || line == NULL)
2430 {
2431 buf_T *savebuf = curbuf;
2432
2433 PyErr_Clear();
2434 curbuf = buf;
2435
2436 if (u_savedel((linenr_T)n, 1L) == FAIL)
2437 PyErr_SetVim(_("cannot save undo information"));
2438 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2439 PyErr_SetVim(_("cannot delete line"));
2440 else
2441 {
2442 deleted_lines_mark((linenr_T)n, 1L);
2443 if (buf == curwin->w_buffer)
2444 py_fix_cursor(n, n + 1, -1);
2445 }
2446
2447 curbuf = savebuf;
2448
2449 if (PyErr_Occurred() || VimErrorCheck())
2450 return FAIL;
2451
2452 if (len_change)
2453 *len_change = -1;
2454
2455 return OK;
2456 }
2457 else if (PyString_Check(line))
2458 {
2459 char *save = StringToLine(line);
2460 buf_T *savebuf = curbuf;
2461
2462 if (save == NULL)
2463 return FAIL;
2464
2465 /* We do not need to free "save" if ml_replace() consumes it. */
2466 PyErr_Clear();
2467 curbuf = buf;
2468
2469 if (u_savesub((linenr_T)n) == FAIL)
2470 {
2471 PyErr_SetVim(_("cannot save undo information"));
2472 vim_free(save);
2473 }
2474 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2475 {
2476 PyErr_SetVim(_("cannot replace line"));
2477 vim_free(save);
2478 }
2479 else
2480 changed_bytes((linenr_T)n, 0);
2481
2482 curbuf = savebuf;
2483
2484 if (PyErr_Occurred() || VimErrorCheck())
2485 return FAIL;
2486
2487 if (len_change)
2488 *len_change = 0;
2489
2490 return OK;
2491 }
2492 else
2493 {
2494 PyErr_BadArgument();
2495 return FAIL;
2496 }
2497}
2498
2499/* Replace a range of lines in the specified buffer. The line numbers are in
2500 * Vim format (1-based). The range is from lo up to, but not including, hi.
2501 * The replacement lines are given as a Python list of string objects. The
2502 * list is checked for validity and correct format. Errors are returned as a
2503 * value of FAIL. The return value is OK on success.
2504 * If OK is returned and len_change is not NULL, *len_change
2505 * is set to the change in the buffer length.
2506 */
2507 static int
2508SetBufferLineList(buf_T *buf, int lo, int hi, PyObject *list, int *len_change)
2509{
2510 /* First of all, we check the thpe of the supplied Python object.
2511 * There are three cases:
2512 * 1. NULL, or None - this is a deletion.
2513 * 2. A list - this is a replacement.
2514 * 3. Anything else - this is an error.
2515 */
2516 if (list == Py_None || list == NULL)
2517 {
2518 int i;
2519 int n = hi - lo;
2520 buf_T *savebuf = curbuf;
2521
2522 PyErr_Clear();
2523 curbuf = buf;
2524
2525 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2526 PyErr_SetVim(_("cannot save undo information"));
2527 else
2528 {
2529 for (i = 0; i < n; ++i)
2530 {
2531 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2532 {
2533 PyErr_SetVim(_("cannot delete line"));
2534 break;
2535 }
2536 }
2537 deleted_lines_mark((linenr_T)lo, (long)i);
2538
2539 if (buf == curwin->w_buffer)
2540 py_fix_cursor(lo, hi, -n);
2541 }
2542
2543 curbuf = savebuf;
2544
2545 if (PyErr_Occurred() || VimErrorCheck())
2546 return FAIL;
2547
2548 if (len_change)
2549 *len_change = -n;
2550
2551 return OK;
2552 }
2553 else if (PyList_Check(list))
2554 {
2555 int i;
2556 int new_len = PyList_Size(list);
2557 int old_len = hi - lo;
2558 int extra = 0; /* lines added to text, can be negative */
2559 char **array;
2560 buf_T *savebuf;
2561
2562 if (new_len == 0) /* avoid allocating zero bytes */
2563 array = NULL;
2564 else
2565 {
2566 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2567 if (array == NULL)
2568 {
2569 PyErr_NoMemory();
2570 return FAIL;
2571 }
2572 }
2573
2574 for (i = 0; i < new_len; ++i)
2575 {
2576 PyObject *line = PyList_GetItem(list, i);
2577
2578 array[i] = StringToLine(line);
2579 if (array[i] == NULL)
2580 {
2581 while (i)
2582 vim_free(array[--i]);
2583 vim_free(array);
2584 return FAIL;
2585 }
2586 }
2587
2588 savebuf = curbuf;
2589
2590 PyErr_Clear();
2591 curbuf = buf;
2592
2593 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2594 PyErr_SetVim(_("cannot save undo information"));
2595
2596 /* If the size of the range is reducing (ie, new_len < old_len) we
2597 * need to delete some old_len. We do this at the start, by
2598 * repeatedly deleting line "lo".
2599 */
2600 if (!PyErr_Occurred())
2601 {
2602 for (i = 0; i < old_len - new_len; ++i)
2603 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2604 {
2605 PyErr_SetVim(_("cannot delete line"));
2606 break;
2607 }
2608 extra -= i;
2609 }
2610
2611 /* For as long as possible, replace the existing old_len with the
2612 * new old_len. This is a more efficient operation, as it requires
2613 * less memory allocation and freeing.
2614 */
2615 if (!PyErr_Occurred())
2616 {
2617 for (i = 0; i < old_len && i < new_len; ++i)
2618 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2619 == FAIL)
2620 {
2621 PyErr_SetVim(_("cannot replace line"));
2622 break;
2623 }
2624 }
2625 else
2626 i = 0;
2627
2628 /* Now we may need to insert the remaining new old_len. If we do, we
2629 * must free the strings as we finish with them (we can't pass the
2630 * responsibility to vim in this case).
2631 */
2632 if (!PyErr_Occurred())
2633 {
2634 while (i < new_len)
2635 {
2636 if (ml_append((linenr_T)(lo + i - 1),
2637 (char_u *)array[i], 0, FALSE) == FAIL)
2638 {
2639 PyErr_SetVim(_("cannot insert line"));
2640 break;
2641 }
2642 vim_free(array[i]);
2643 ++i;
2644 ++extra;
2645 }
2646 }
2647
2648 /* Free any left-over old_len, as a result of an error */
2649 while (i < new_len)
2650 {
2651 vim_free(array[i]);
2652 ++i;
2653 }
2654
2655 /* Free the array of old_len. All of its contents have now
2656 * been dealt with (either freed, or the responsibility passed
2657 * to vim.
2658 */
2659 vim_free(array);
2660
2661 /* Adjust marks. Invalidate any which lie in the
2662 * changed range, and move any in the remainder of the buffer.
2663 */
2664 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2665 (long)MAXLNUM, (long)extra);
2666 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2667
2668 if (buf == curwin->w_buffer)
2669 py_fix_cursor(lo, hi, extra);
2670
2671 curbuf = savebuf;
2672
2673 if (PyErr_Occurred() || VimErrorCheck())
2674 return FAIL;
2675
2676 if (len_change)
2677 *len_change = new_len - old_len;
2678
2679 return OK;
2680 }
2681 else
2682 {
2683 PyErr_BadArgument();
2684 return FAIL;
2685 }
2686}
2687
2688/* Insert a number of lines into the specified buffer after the specifed line.
2689 * The line number is in Vim format (1-based). The lines to be inserted are
2690 * given as a Python list of string objects or as a single string. The lines
2691 * to be added are checked for validity and correct format. Errors are
2692 * returned as a value of FAIL. The return value is OK on success.
2693 * If OK is returned and len_change is not NULL, *len_change
2694 * is set to the change in the buffer length.
2695 */
2696 static int
2697InsertBufferLines(buf_T *buf, int n, PyObject *lines, int *len_change)
2698{
2699 /* First of all, we check the type of the supplied Python object.
2700 * It must be a string or a list, or the call is in error.
2701 */
2702 if (PyString_Check(lines))
2703 {
2704 char *str = StringToLine(lines);
2705 buf_T *savebuf;
2706
2707 if (str == NULL)
2708 return FAIL;
2709
2710 savebuf = curbuf;
2711
2712 PyErr_Clear();
2713 curbuf = buf;
2714
2715 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2716 PyErr_SetVim(_("cannot save undo information"));
2717 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2718 PyErr_SetVim(_("cannot insert line"));
2719 else
2720 appended_lines_mark((linenr_T)n, 1L);
2721
2722 vim_free(str);
2723 curbuf = savebuf;
2724 update_screen(VALID);
2725
2726 if (PyErr_Occurred() || VimErrorCheck())
2727 return FAIL;
2728
2729 if (len_change)
2730 *len_change = 1;
2731
2732 return OK;
2733 }
2734 else if (PyList_Check(lines))
2735 {
2736 int i;
2737 int size = PyList_Size(lines);
2738 char **array;
2739 buf_T *savebuf;
2740
2741 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2742 if (array == NULL)
2743 {
2744 PyErr_NoMemory();
2745 return FAIL;
2746 }
2747
2748 for (i = 0; i < size; ++i)
2749 {
2750 PyObject *line = PyList_GetItem(lines, i);
2751 array[i] = StringToLine(line);
2752
2753 if (array[i] == NULL)
2754 {
2755 while (i)
2756 vim_free(array[--i]);
2757 vim_free(array);
2758 return FAIL;
2759 }
2760 }
2761
2762 savebuf = curbuf;
2763
2764 PyErr_Clear();
2765 curbuf = buf;
2766
2767 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2768 PyErr_SetVim(_("cannot save undo information"));
2769 else
2770 {
2771 for (i = 0; i < size; ++i)
2772 {
2773 if (ml_append((linenr_T)(n + i),
2774 (char_u *)array[i], 0, FALSE) == FAIL)
2775 {
2776 PyErr_SetVim(_("cannot insert line"));
2777
2778 /* Free the rest of the lines */
2779 while (i < size)
2780 vim_free(array[i++]);
2781
2782 break;
2783 }
2784 vim_free(array[i]);
2785 }
2786 if (i > 0)
2787 appended_lines_mark((linenr_T)n, (long)i);
2788 }
2789
2790 /* Free the array of lines. All of its contents have now
2791 * been freed.
2792 */
2793 vim_free(array);
2794
2795 curbuf = savebuf;
2796 update_screen(VALID);
2797
2798 if (PyErr_Occurred() || VimErrorCheck())
2799 return FAIL;
2800
2801 if (len_change)
2802 *len_change = size;
2803
2804 return OK;
2805 }
2806 else
2807 {
2808 PyErr_BadArgument();
2809 return FAIL;
2810 }
2811}
2812
2813/* Convert a Vim line into a Python string.
2814 * All internal newlines are replaced by null characters.
2815 *
2816 * On errors, the Python exception data is set, and NULL is returned.
2817 */
2818 static PyObject *
2819LineToString(const char *str)
2820{
2821 PyObject *result;
2822 int len = strlen(str);
2823 char *p;
2824
2825 /* Allocate an Python string object, with uninitialised contents. We
2826 * must do it this way, so that we can modify the string in place
2827 * later. See the Python source, Objects/stringobject.c for details.
2828 */
2829 result = PyString_FromStringAndSize(NULL, len);
2830 if (result == NULL)
2831 return NULL;
2832
2833 p = PyString_AsString(result);
2834
2835 while (*str)
2836 {
2837 if (*str == '\n')
2838 *p = '\0';
2839 else
2840 *p = *str;
2841
2842 ++p;
2843 ++str;
2844 }
2845
2846 return result;
2847}
2848
2849/* Convert a Python string into a Vim line.
2850 *
2851 * The result is in allocated memory. All internal nulls are replaced by
2852 * newline characters. It is an error for the string to contain newline
2853 * characters.
2854 *
2855 * On errors, the Python exception data is set, and NULL is returned.
2856 */
2857 static char *
2858StringToLine(PyObject *obj)
2859{
2860 const char *str;
2861 char *save;
2862 int len;
2863 int i;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002864 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865
2866 if (obj == NULL || !PyString_Check(obj))
2867 {
2868 PyErr_BadArgument();
2869 return NULL;
2870 }
2871
2872 str = PyString_AsString(obj);
2873 len = PyString_Size(obj);
2874
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002875 /*
2876 * Error checking: String must not contain newlines, as we
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 * are replacing a single line, and we must replace it with
2878 * a single line.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002879 * A trailing newline is removed, so that append(f.readlines()) works.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 */
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002881 p = memchr(str, '\n', len);
2882 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 {
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002884 if (p == str + len - 1)
2885 --len;
2886 else
2887 {
2888 PyErr_SetVim(_("string cannot contain newlines"));
2889 return NULL;
2890 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 }
2892
2893 /* Create a copy of the string, with internal nulls replaced by
2894 * newline characters, as is the vim convention.
2895 */
2896 save = (char *)alloc((unsigned)(len+1));
2897 if (save == NULL)
2898 {
2899 PyErr_NoMemory();
2900 return NULL;
2901 }
2902
2903 for (i = 0; i < len; ++i)
2904 {
2905 if (str[i] == '\0')
2906 save[i] = '\n';
2907 else
2908 save[i] = str[i];
2909 }
2910
2911 save[i] = '\0';
2912
2913 return save;
2914}
2915
2916/* Check to see whether a Vim error has been reported, or a keyboard
2917 * interrupt has been detected.
2918 */
2919 static int
2920VimErrorCheck(void)
2921{
2922 if (got_int)
2923 {
2924 PyErr_SetNone(PyExc_KeyboardInterrupt);
2925 return 1;
2926 }
2927 else if (did_emsg && !PyErr_Occurred())
2928 {
2929 PyErr_SetNone(VimError);
2930 return 1;
2931 }
2932
2933 return 0;
2934}
2935
2936
2937/* Don't generate a prototype for the next function, it generates an error on
2938 * newer Python versions. */
2939#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
2940
2941 char *
2942Py_GetProgramName(void)
2943{
2944 return "vim";
2945}
2946#endif /* Python 1.4 */