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