Recognize files with 'patch' and 'diff' extensions
[MacVim.git] / src / if_python.c
blob0e06d36e4bb24e45b0037682f2c1a9cbbbaf99c3
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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.
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.
20 #include "vim.h"
22 #include <limits.h>
24 /* Python.h defines _POSIX_THREADS itself (if needed) */
25 #ifdef _POSIX_THREADS
26 # undef _POSIX_THREADS
27 #endif
29 #if defined(_WIN32) && defined (HAVE_FCNTL_H)
30 # undef HAVE_FCNTL_H
31 #endif
33 #ifdef _DEBUG
34 # undef _DEBUG
35 #endif
37 #ifdef HAVE_STDARG_H
38 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */
39 #endif
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 */
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
54 struct PyMethodDef { int a; };
55 # define PySequenceMethods int
56 #endif
58 /* Parser flags */
59 #define single_input 256
60 #define file_input 257
61 #define eval_input 258
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
68 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
69 # ifndef DYNAMIC_PYTHON
70 # define HINSTANCE int /* for generating prototypes */
71 # endif
74 * Wrapper defines
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_Append dll_PyList_Append
97 # define PyList_New dll_PyList_New
98 # define PyList_SetItem dll_PyList_SetItem
99 # define PyList_Size dll_PyList_Size
100 # define PyList_Type (*dll_PyList_Type)
101 # define PyImport_ImportModule dll_PyImport_ImportModule
102 # define PyDict_New dll_PyDict_New
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
118 # define Py_Finalize dll_Py_Finalize
119 # define Py_IsInitialized dll_Py_IsInitialized
120 # 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
132 * Pointers for dynamic link
134 static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
135 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
136 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
137 static int(*dll_PyErr_BadArgument)(void);
138 static void(*dll_PyErr_Clear)(void);
139 static PyObject*(*dll_PyErr_NoMemory)(void);
140 static PyObject*(*dll_PyErr_Occurred)(void);
141 static void(*dll_PyErr_SetNone)(PyObject *);
142 static void(*dll_PyErr_SetString)(PyObject *, const char *);
143 static void(*dll_PyEval_InitThreads)(void);
144 static void(*dll_PyEval_RestoreThread)(PyThreadState *);
145 static PyThreadState*(*dll_PyEval_SaveThread)(void);
146 # ifdef PY_CAN_RECURSE
147 static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
148 static void (*dll_PyGILState_Release)(PyGILState_STATE);
149 #endif
150 static long(*dll_PyInt_AsLong)(PyObject *);
151 static PyObject*(*dll_PyInt_FromLong)(long);
152 static PyTypeObject* dll_PyInt_Type;
153 static PyObject*(*dll_PyList_GetItem)(PyObject *, int);
154 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
155 static PyObject*(*dll_PyList_New)(int size);
156 static int(*dll_PyList_SetItem)(PyObject *, int, PyObject *);
157 static int(*dll_PyList_Size)(PyObject *);
158 static PyTypeObject* dll_PyList_Type;
159 static PyObject*(*dll_PyImport_ImportModule)(const char *);
160 static PyObject*(*dll_PyDict_New)(void);
161 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
162 static PyObject*(*dll_PyModule_GetDict)(PyObject *);
163 static int(*dll_PyRun_SimpleString)(char *);
164 static char*(*dll_PyString_AsString)(PyObject *);
165 static PyObject*(*dll_PyString_FromString)(const char *);
166 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, int);
167 static int(*dll_PyString_Size)(PyObject *);
168 static PyTypeObject* dll_PyString_Type;
169 static int(*dll_PySys_SetObject)(char *, PyObject *);
170 static int(*dll_PySys_SetArgv)(int, char **);
171 static PyTypeObject* dll_PyType_Type;
172 static PyObject*(*dll_Py_BuildValue)(char *, ...);
173 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
174 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
175 static void(*dll_Py_Initialize)(void);
176 static void(*dll_Py_Finalize)(void);
177 static int(*dll_Py_IsInitialized)(void);
178 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
179 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
180 static PyObject* dll__Py_NoneStruct;
181 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
182 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
183 # endif
184 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
185 static void* (*dll_PyObject_Malloc)(size_t);
186 static void (*dll_PyObject_Free)(void*);
187 # endif
189 static HINSTANCE hinstPython = 0; /* Instance of python.dll */
191 /* Imported exception objects */
192 static PyObject *imp_PyExc_AttributeError;
193 static PyObject *imp_PyExc_IndexError;
194 static PyObject *imp_PyExc_KeyboardInterrupt;
195 static PyObject *imp_PyExc_TypeError;
196 static PyObject *imp_PyExc_ValueError;
198 # define PyExc_AttributeError imp_PyExc_AttributeError
199 # define PyExc_IndexError imp_PyExc_IndexError
200 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
201 # define PyExc_TypeError imp_PyExc_TypeError
202 # define PyExc_ValueError imp_PyExc_ValueError
205 * Table of name to function pointer of python.
207 # define PYTHON_PROC FARPROC
208 static struct
210 char *name;
211 PYTHON_PROC *ptr;
212 } python_funcname_table[] =
214 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
215 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
216 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
217 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
218 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
219 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
220 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
221 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
222 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
223 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
224 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
225 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
226 # ifdef PY_CAN_RECURSE
227 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
228 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
229 # endif
230 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
231 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
232 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
233 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
234 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
235 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
236 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
237 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
238 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
239 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
240 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
241 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
242 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
243 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
244 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
245 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
246 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
247 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
248 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
249 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
250 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
251 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
252 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
253 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
254 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
255 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
256 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
257 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
258 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
259 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
260 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
261 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
262 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
263 # endif
264 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
265 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
266 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
267 # endif
268 {"", NULL},
272 * Free python.dll
274 static void
275 end_dynamic_python(void)
277 if (hinstPython)
279 FreeLibrary(hinstPython);
280 hinstPython = 0;
285 * Load library and get all pointers.
286 * Parameter 'libname' provides name of DLL.
287 * Return OK or FAIL.
289 static int
290 python_runtime_link_init(char *libname, int verbose)
292 int i;
294 if (hinstPython)
295 return OK;
296 hinstPython = LoadLibrary(libname);
297 if (!hinstPython)
299 if (verbose)
300 EMSG2(_(e_loadlib), libname);
301 return FAIL;
304 for (i = 0; python_funcname_table[i].ptr; ++i)
306 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython,
307 python_funcname_table[i].name)) == NULL)
309 FreeLibrary(hinstPython);
310 hinstPython = 0;
311 if (verbose)
312 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
313 return FAIL;
316 return OK;
320 * If python is enabled (there is installed python on Windows system) return
321 * TRUE, else FALSE.
324 python_enabled(verbose)
325 int verbose;
327 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
330 /* Load the standard Python exceptions - don't import the symbols from the
331 * DLL, as this can cause errors (importing data symbols is not reliable).
333 static void get_exceptions __ARGS((void));
335 static void
336 get_exceptions()
338 PyObject *exmod = PyImport_ImportModule("exceptions");
339 PyObject *exdict = PyModule_GetDict(exmod);
340 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
341 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
342 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
343 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
344 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
345 Py_XINCREF(imp_PyExc_AttributeError);
346 Py_XINCREF(imp_PyExc_IndexError);
347 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
348 Py_XINCREF(imp_PyExc_TypeError);
349 Py_XINCREF(imp_PyExc_ValueError);
350 Py_XDECREF(exmod);
352 #endif /* DYNAMIC_PYTHON */
354 /******************************************************
355 * Internal function prototypes.
358 static void DoPythonCommand(exarg_T *, const char *);
359 static int RangeStart;
360 static int RangeEnd;
362 static void PythonIO_Flush(void);
363 static int PythonIO_Init(void);
364 static int PythonMod_Init(void);
366 /* Utility functions for the vim/python interface
367 * ----------------------------------------------
369 static PyObject *GetBufferLine(buf_T *, int);
370 static PyObject *GetBufferLineList(buf_T *, int, int);
372 static int SetBufferLine(buf_T *, int, PyObject *, int *);
373 static int SetBufferLineList(buf_T *, int, int, PyObject *, int *);
374 static int InsertBufferLines(buf_T *, int, PyObject *, int *);
376 static PyObject *LineToString(const char *);
377 static char *StringToLine(PyObject *);
379 static int VimErrorCheck(void);
381 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
383 /******************************************************
384 * 1. Python interpreter main program.
387 static int initialised = 0;
389 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */
390 typedef PyObject PyThreadState;
391 #endif
393 #ifdef PY_CAN_RECURSE
394 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
395 #else
396 static PyThreadState *saved_python_thread = NULL;
397 #endif
400 * Suspend a thread of the Python interpreter, other threads are allowed to
401 * run.
403 static void
404 Python_SaveThread(void)
406 #ifdef PY_CAN_RECURSE
407 PyGILState_Release(pygilstate);
408 #else
409 saved_python_thread = PyEval_SaveThread();
410 #endif
414 * Restore a thread of the Python interpreter, waits for other threads to
415 * block.
417 static void
418 Python_RestoreThread(void)
420 #ifdef PY_CAN_RECURSE
421 pygilstate = PyGILState_Ensure();
422 #else
423 PyEval_RestoreThread(saved_python_thread);
424 saved_python_thread = NULL;
425 #endif
429 * obtain a lock on the Vim data structures
431 static void Python_Lock_Vim(void)
436 * release a lock on the Vim data structures
438 static void Python_Release_Vim(void)
442 void
443 python_end()
445 static int recurse = 0;
447 /* If a crash occurs while doing this, don't try again. */
448 if (recurse != 0)
449 return;
451 ++recurse;
453 #ifdef DYNAMIC_PYTHON
454 if (hinstPython && Py_IsInitialized())
456 Python_RestoreThread(); /* enter python */
457 Py_Finalize();
459 end_dynamic_python();
460 #else
461 if (Py_IsInitialized())
463 Python_RestoreThread(); /* enter python */
464 Py_Finalize();
466 #endif
468 --recurse;
471 static int
472 Python_Init(void)
474 if (!initialised)
476 #ifdef DYNAMIC_PYTHON
477 if (!python_enabled(TRUE))
479 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
480 goto fail;
482 #endif
484 #if !defined(MACOS) || defined(MACOS_X_UNIX)
485 Py_Initialize();
486 #else
487 PyMac_Initialize();
488 #endif
489 /* initialise threads */
490 PyEval_InitThreads();
492 #ifdef DYNAMIC_PYTHON
493 get_exceptions();
494 #endif
496 if (PythonIO_Init())
497 goto fail;
499 if (PythonMod_Init())
500 goto fail;
502 /* the first python thread is vim's, release the lock */
503 Python_SaveThread();
505 initialised = 1;
508 return 0;
510 fail:
511 /* We call PythonIO_Flush() here to print any Python errors.
512 * This is OK, as it is possible to call this function even
513 * if PythonIO_Init() has not completed successfully (it will
514 * not do anything in this case).
516 PythonIO_Flush();
517 return -1;
521 * External interface
523 static void
524 DoPythonCommand(exarg_T *eap, const char *cmd)
526 #ifndef PY_CAN_RECURSE
527 static int recursive = 0;
528 #endif
529 #if defined(MACOS) && !defined(MACOS_X_UNIX)
530 GrafPtr oldPort;
531 #endif
532 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
533 char *saved_locale;
534 #endif
536 #ifndef PY_CAN_RECURSE
537 if (recursive)
539 EMSG(_("E659: Cannot invoke Python recursively"));
540 return;
542 ++recursive;
543 #endif
545 #if defined(MACOS) && !defined(MACOS_X_UNIX)
546 GetPort(&oldPort);
547 /* Check if the Python library is available */
548 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
549 goto theend;
550 #endif
551 if (Python_Init())
552 goto theend;
554 RangeStart = eap->line1;
555 RangeEnd = eap->line2;
556 Python_Release_Vim(); /* leave vim */
558 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
559 /* Python only works properly when the LC_NUMERIC locale is "C". */
560 saved_locale = setlocale(LC_NUMERIC, NULL);
561 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
562 saved_locale = NULL;
563 else
565 /* Need to make a copy, value may change when setting new locale. */
566 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
567 (void)setlocale(LC_NUMERIC, "C");
569 #endif
571 Python_RestoreThread(); /* enter python */
573 PyRun_SimpleString((char *)(cmd));
575 Python_SaveThread(); /* leave python */
577 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
578 if (saved_locale != NULL)
580 (void)setlocale(LC_NUMERIC, saved_locale);
581 vim_free(saved_locale);
583 #endif
585 Python_Lock_Vim(); /* enter vim */
586 PythonIO_Flush();
587 #if defined(MACOS) && !defined(MACOS_X_UNIX)
588 SetPort(oldPort);
589 #endif
591 theend:
592 #ifndef PY_CAN_RECURSE
593 --recursive;
594 #endif
595 return; /* keeps lint happy */
599 * ":python"
601 void
602 ex_python(exarg_T *eap)
604 char_u *script;
606 script = script_get(eap, eap->arg);
607 if (!eap->skip)
609 if (script == NULL)
610 DoPythonCommand(eap, (char *)eap->arg);
611 else
612 DoPythonCommand(eap, (char *)script);
614 vim_free(script);
617 #define BUFFER_SIZE 1024
620 * ":pyfile"
622 void
623 ex_pyfile(exarg_T *eap)
625 static char buffer[BUFFER_SIZE];
626 const char *file = (char *)eap->arg;
627 char *p;
629 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
630 * stdio file pointer, but Vim and the Python DLL are compiled with
631 * different options under Windows, meaning that stdio pointers aren't
632 * compatible between the two. Yuk.
634 * Put the string "execfile('file')" into buffer. But, we need to
635 * escape any backslashes or single quotes in the file name, so that
636 * Python won't mangle the file name.
638 strcpy(buffer, "execfile('");
639 p = buffer + 10; /* size of "execfile('" */
641 while (*file && p < buffer + (BUFFER_SIZE - 3))
643 if (*file == '\\' || *file == '\'')
644 *p++ = '\\';
645 *p++ = *file++;
648 /* If we didn't finish the file name, we hit a buffer overflow */
649 if (*file != '\0')
650 return;
652 /* Put in the terminating "')" and a null */
653 *p++ = '\'';
654 *p++ = ')';
655 *p++ = '\0';
657 /* Execute the file */
658 DoPythonCommand(eap, buffer);
661 /******************************************************
662 * 2. Python output stream: writes output via [e]msg().
665 /* Implementation functions
668 static PyObject *OutputGetattr(PyObject *, char *);
669 static int OutputSetattr(PyObject *, char *, PyObject *);
671 static PyObject *OutputWrite(PyObject *, PyObject *);
672 static PyObject *OutputWritelines(PyObject *, PyObject *);
674 typedef void (*writefn)(char_u *);
675 static void writer(writefn fn, char_u *str, int n);
677 /* Output object definition
680 typedef struct
682 PyObject_HEAD
683 long softspace;
684 long error;
685 } OutputObject;
687 static struct PyMethodDef OutputMethods[] = {
688 /* name, function, calling, documentation */
689 {"write", OutputWrite, 1, "" },
690 {"writelines", OutputWritelines, 1, "" },
691 { NULL, NULL, 0, NULL }
694 static PyTypeObject OutputType = {
695 PyObject_HEAD_INIT(0)
697 "message",
698 sizeof(OutputObject),
701 (destructor) 0,
702 (printfunc) 0,
703 (getattrfunc) OutputGetattr,
704 (setattrfunc) OutputSetattr,
705 (cmpfunc) 0,
706 (reprfunc) 0,
708 0, /* as number */
709 0, /* as sequence */
710 0, /* as mapping */
712 (hashfunc) 0,
713 (ternaryfunc) 0,
714 (reprfunc) 0
717 /*************/
719 static PyObject *
720 OutputGetattr(PyObject *self, char *name)
722 if (strcmp(name, "softspace") == 0)
723 return PyInt_FromLong(((OutputObject *)(self))->softspace);
725 return Py_FindMethod(OutputMethods, self, name);
728 static int
729 OutputSetattr(PyObject *self, char *name, PyObject *val)
731 if (val == NULL) {
732 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
733 return -1;
736 if (strcmp(name, "softspace") == 0)
738 if (!PyInt_Check(val)) {
739 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
740 return -1;
743 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
744 return 0;
747 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
748 return -1;
751 /*************/
753 static PyObject *
754 OutputWrite(PyObject *self, PyObject *args)
756 int len;
757 char *str;
758 int error = ((OutputObject *)(self))->error;
760 if (!PyArg_ParseTuple(args, "s#", &str, &len))
761 return NULL;
763 Py_BEGIN_ALLOW_THREADS
764 Python_Lock_Vim();
765 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
766 Python_Release_Vim();
767 Py_END_ALLOW_THREADS
769 Py_INCREF(Py_None);
770 return Py_None;
773 static PyObject *
774 OutputWritelines(PyObject *self, PyObject *args)
776 int n;
777 int i;
778 PyObject *list;
779 int error = ((OutputObject *)(self))->error;
781 if (!PyArg_ParseTuple(args, "O", &list))
782 return NULL;
783 Py_INCREF(list);
785 if (!PyList_Check(list)) {
786 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
787 Py_DECREF(list);
788 return NULL;
791 n = PyList_Size(list);
793 for (i = 0; i < n; ++i)
795 PyObject *line = PyList_GetItem(list, i);
796 char *str;
797 int len;
799 if (!PyArg_Parse(line, "s#", &str, &len)) {
800 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
801 Py_DECREF(list);
802 return NULL;
805 Py_BEGIN_ALLOW_THREADS
806 Python_Lock_Vim();
807 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
808 Python_Release_Vim();
809 Py_END_ALLOW_THREADS
812 Py_DECREF(list);
813 Py_INCREF(Py_None);
814 return Py_None;
817 /* Output buffer management
820 static char_u *buffer = NULL;
821 static int buffer_len = 0;
822 static int buffer_size = 0;
824 static writefn old_fn = NULL;
826 static void
827 buffer_ensure(int n)
829 int new_size;
830 char_u *new_buffer;
832 if (n < buffer_size)
833 return;
835 new_size = buffer_size;
836 while (new_size < n)
837 new_size += 80;
839 if (new_size != buffer_size)
841 new_buffer = alloc((unsigned)new_size);
842 if (new_buffer == NULL)
843 return;
845 if (buffer)
847 memcpy(new_buffer, buffer, buffer_len);
848 vim_free(buffer);
851 buffer = new_buffer;
852 buffer_size = new_size;
856 static void
857 PythonIO_Flush(void)
859 if (old_fn && buffer_len)
861 buffer[buffer_len] = 0;
862 old_fn(buffer);
865 buffer_len = 0;
868 static void
869 writer(writefn fn, char_u *str, int n)
871 char_u *ptr;
873 if (fn != old_fn && old_fn != NULL)
874 PythonIO_Flush();
876 old_fn = fn;
878 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
880 int len = ptr - str;
882 buffer_ensure(buffer_len + len + 1);
884 memcpy(buffer + buffer_len, str, len);
885 buffer_len += len;
886 buffer[buffer_len] = 0;
887 fn(buffer);
888 str = ptr + 1;
889 n -= len + 1;
890 buffer_len = 0;
893 /* Put the remaining text into the buffer for later printing */
894 buffer_ensure(buffer_len + n + 1);
895 memcpy(buffer + buffer_len, str, n);
896 buffer_len += n;
899 /***************/
901 static OutputObject Output =
903 PyObject_HEAD_INIT(&OutputType)
908 static OutputObject Error =
910 PyObject_HEAD_INIT(&OutputType)
915 static int
916 PythonIO_Init(void)
918 /* Fixups... */
919 OutputType.ob_type = &PyType_Type;
921 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
922 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
924 if (PyErr_Occurred())
926 EMSG(_("E264: Python: Error initialising I/O objects"));
927 return -1;
930 return 0;
933 /******************************************************
934 * 3. Implementation of the Vim module for Python
937 /* Vim module - Implementation functions
938 * -------------------------------------
941 static PyObject *VimError;
943 static PyObject *VimCommand(PyObject *, PyObject *);
944 static PyObject *VimEval(PyObject *, PyObject *);
946 /* Window type - Implementation functions
947 * --------------------------------------
950 typedef struct
952 PyObject_HEAD
953 win_T *win;
955 WindowObject;
957 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
959 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
961 static PyObject *WindowNew(win_T *);
963 static void WindowDestructor(PyObject *);
964 static PyObject *WindowGetattr(PyObject *, char *);
965 static int WindowSetattr(PyObject *, char *, PyObject *);
966 static PyObject *WindowRepr(PyObject *);
968 /* Buffer type - Implementation functions
969 * --------------------------------------
972 typedef struct
974 PyObject_HEAD
975 buf_T *buf;
977 BufferObject;
979 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
981 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
983 static PyObject *BufferNew (buf_T *);
985 static void BufferDestructor(PyObject *);
986 static PyObject *BufferGetattr(PyObject *, char *);
987 static PyObject *BufferRepr(PyObject *);
989 static int BufferLength(PyObject *);
990 static PyObject *BufferItem(PyObject *, int);
991 static PyObject *BufferSlice(PyObject *, int, int);
992 static int BufferAssItem(PyObject *, int, PyObject *);
993 static int BufferAssSlice(PyObject *, int, int, PyObject *);
995 static PyObject *BufferAppend(PyObject *, PyObject *);
996 static PyObject *BufferMark(PyObject *, PyObject *);
997 static PyObject *BufferRange(PyObject *, PyObject *);
999 /* Line range type - Implementation functions
1000 * --------------------------------------
1003 typedef struct
1005 PyObject_HEAD
1006 BufferObject *buf;
1007 int start;
1008 int end;
1010 RangeObject;
1012 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1014 static PyObject *RangeNew(buf_T *, int, int);
1016 static void RangeDestructor(PyObject *);
1017 static PyObject *RangeGetattr(PyObject *, char *);
1018 static PyObject *RangeRepr(PyObject *);
1020 static int RangeLength(PyObject *);
1021 static PyObject *RangeItem(PyObject *, int);
1022 static PyObject *RangeSlice(PyObject *, int, int);
1023 static int RangeAssItem(PyObject *, int, PyObject *);
1024 static int RangeAssSlice(PyObject *, int, int, PyObject *);
1026 static PyObject *RangeAppend(PyObject *, PyObject *);
1028 /* Window list type - Implementation functions
1029 * -------------------------------------------
1032 static int WinListLength(PyObject *);
1033 static PyObject *WinListItem(PyObject *, int);
1035 /* Buffer list type - Implementation functions
1036 * -------------------------------------------
1039 static int BufListLength(PyObject *);
1040 static PyObject *BufListItem(PyObject *, int);
1042 /* Current objects type - Implementation functions
1043 * -----------------------------------------------
1046 static PyObject *CurrentGetattr(PyObject *, char *);
1047 static int CurrentSetattr(PyObject *, char *, PyObject *);
1049 /* Vim module - Definitions
1052 static struct PyMethodDef VimMethods[] = {
1053 /* name, function, calling, documentation */
1054 {"command", VimCommand, 1, "" },
1055 {"eval", VimEval, 1, "" },
1056 { NULL, NULL, 0, NULL }
1059 /* Vim module - Implementation
1061 /*ARGSUSED*/
1062 static PyObject *
1063 VimCommand(PyObject *self, PyObject *args)
1065 char *cmd;
1066 PyObject *result;
1068 if (!PyArg_ParseTuple(args, "s", &cmd))
1069 return NULL;
1071 PyErr_Clear();
1073 Py_BEGIN_ALLOW_THREADS
1074 Python_Lock_Vim();
1076 do_cmdline_cmd((char_u *)cmd);
1077 update_screen(VALID);
1079 Python_Release_Vim();
1080 Py_END_ALLOW_THREADS
1082 if (VimErrorCheck())
1083 result = NULL;
1084 else
1085 result = Py_None;
1087 Py_XINCREF(result);
1088 return result;
1092 * Function to translate a typval_T into a PyObject; this will recursively
1093 * translate lists/dictionaries into their Python equivalents.
1095 * The depth parameter is too avoid infinite recursion, set it to 1 when
1096 * you call VimToPython.
1098 static PyObject *
1099 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
1101 PyObject *result;
1102 PyObject *newObj;
1103 char ptrBuf[NUMBUFLEN];
1105 /* Avoid infinite recursion */
1106 if (depth > 100)
1108 Py_INCREF(Py_None);
1109 result = Py_None;
1110 return result;
1113 /* Check if we run into a recursive loop. The item must be in lookupDict
1114 * then and we can use it again. */
1115 sprintf(ptrBuf, "%ld", (long)our_tv);
1116 result = PyDict_GetItemString(lookupDict, ptrBuf);
1117 if (result != NULL)
1118 Py_INCREF(result);
1119 else if (our_tv->v_type == VAR_STRING)
1121 result = Py_BuildValue("s", our_tv->vval.v_string);
1122 PyDict_SetItemString(lookupDict, ptrBuf, result);
1124 else if (our_tv->v_type == VAR_NUMBER)
1126 char buf[NUMBUFLEN];
1128 /* For backwards compatibility numbers are stored as strings. */
1129 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
1130 result = Py_BuildValue("s", buf);
1131 PyDict_SetItemString(lookupDict, ptrBuf, result);
1133 else if (our_tv->v_type == VAR_LIST)
1135 list_T *list = our_tv->vval.v_list;
1136 listitem_T *curr;
1138 result = PyList_New(0);
1139 PyDict_SetItemString(lookupDict, ptrBuf, result);
1141 if (list != NULL)
1143 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1145 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
1146 PyList_Append(result, newObj);
1147 Py_DECREF(newObj);
1151 else if (our_tv->v_type == VAR_DICT)
1153 result = PyDict_New();
1154 PyDict_SetItemString(lookupDict, ptrBuf, result);
1156 if (our_tv->vval.v_dict != NULL)
1158 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
1159 int todo = ht->ht_used;
1160 hashitem_T *hi;
1161 dictitem_T *di;
1163 for (hi = ht->ht_array; todo > 0; ++hi)
1165 if (!HASHITEM_EMPTY(hi))
1167 --todo;
1169 di = dict_lookup(hi);
1170 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
1171 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
1172 Py_DECREF(newObj);
1177 else
1179 Py_INCREF(Py_None);
1180 result = Py_None;
1183 return result;
1186 /*ARGSUSED*/
1187 static PyObject *
1188 VimEval(PyObject *self, PyObject *args)
1190 #ifdef FEAT_EVAL
1191 char *expr;
1192 typval_T *our_tv;
1193 PyObject *result;
1194 PyObject *lookup_dict;
1196 if (!PyArg_ParseTuple(args, "s", &expr))
1197 return NULL;
1199 Py_BEGIN_ALLOW_THREADS
1200 Python_Lock_Vim();
1201 our_tv = eval_expr((char_u *)expr, NULL);
1203 Python_Release_Vim();
1204 Py_END_ALLOW_THREADS
1206 if (our_tv == NULL)
1208 PyErr_SetVim(_("invalid expression"));
1209 return NULL;
1212 /* Convert the Vim type into a Python type. Create a dictionary that's
1213 * used to check for recursive loops. */
1214 lookup_dict = PyDict_New();
1215 result = VimToPython(our_tv, 1, lookup_dict);
1216 Py_DECREF(lookup_dict);
1219 Py_BEGIN_ALLOW_THREADS
1220 Python_Lock_Vim();
1221 free_tv(our_tv);
1222 Python_Release_Vim();
1223 Py_END_ALLOW_THREADS
1225 return result;
1226 #else
1227 PyErr_SetVim(_("expressions disabled at compile time"));
1228 return NULL;
1229 #endif
1232 /* Common routines for buffers and line ranges
1233 * -------------------------------------------
1235 static int
1236 CheckBuffer(BufferObject *this)
1238 if (this->buf == INVALID_BUFFER_VALUE)
1240 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1241 return -1;
1244 return 0;
1247 static PyObject *
1248 RBItem(BufferObject *self, int n, int start, int end)
1250 if (CheckBuffer(self))
1251 return NULL;
1253 if (n < 0 || n > end - start)
1255 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1256 return NULL;
1259 return GetBufferLine(self->buf, n+start);
1262 static PyObject *
1263 RBSlice(BufferObject *self, int lo, int hi, int start, int end)
1265 int size;
1267 if (CheckBuffer(self))
1268 return NULL;
1270 size = end - start + 1;
1272 if (lo < 0)
1273 lo = 0;
1274 else if (lo > size)
1275 lo = size;
1276 if (hi < 0)
1277 hi = 0;
1278 if (hi < lo)
1279 hi = lo;
1280 else if (hi > size)
1281 hi = size;
1283 return GetBufferLineList(self->buf, lo+start, hi+start);
1286 static int
1287 RBAssItem(BufferObject *self, int n, PyObject *val, int start, int end, int *new_end)
1289 int len_change;
1291 if (CheckBuffer(self))
1292 return -1;
1294 if (n < 0 || n > end - start)
1296 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1297 return -1;
1300 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1301 return -1;
1303 if (new_end)
1304 *new_end = end + len_change;
1306 return 0;
1309 static int
1310 RBAssSlice(BufferObject *self, int lo, int hi, PyObject *val, int start, int end, int *new_end)
1312 int size;
1313 int len_change;
1315 /* Self must be a valid buffer */
1316 if (CheckBuffer(self))
1317 return -1;
1319 /* Sort out the slice range */
1320 size = end - start + 1;
1322 if (lo < 0)
1323 lo = 0;
1324 else if (lo > size)
1325 lo = size;
1326 if (hi < 0)
1327 hi = 0;
1328 if (hi < lo)
1329 hi = lo;
1330 else if (hi > size)
1331 hi = size;
1333 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL)
1334 return -1;
1336 if (new_end)
1337 *new_end = end + len_change;
1339 return 0;
1342 static PyObject *
1343 RBAppend(BufferObject *self, PyObject *args, int start, int end, int *new_end)
1345 PyObject *lines;
1346 int len_change;
1347 int max;
1348 int n;
1350 if (CheckBuffer(self))
1351 return NULL;
1353 max = n = end - start + 1;
1355 if (!PyArg_ParseTuple(args, "O|i", &lines, &n))
1356 return NULL;
1358 if (n < 0 || n > max)
1360 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1361 return NULL;
1364 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1365 return NULL;
1367 if (new_end)
1368 *new_end = end + len_change;
1370 Py_INCREF(Py_None);
1371 return Py_None;
1375 /* Buffer object - Definitions
1378 static struct PyMethodDef BufferMethods[] = {
1379 /* name, function, calling, documentation */
1380 {"append", BufferAppend, 1, "" },
1381 {"mark", BufferMark, 1, "" },
1382 {"range", BufferRange, 1, "" },
1383 { NULL, NULL, 0, NULL }
1386 static PySequenceMethods BufferAsSeq = {
1387 (inquiry) BufferLength, /* sq_length, len(x) */
1388 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
1389 (intargfunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1390 (intargfunc) BufferItem, /* sq_item, x[i] */
1391 (intintargfunc) BufferSlice, /* sq_slice, x[i:j] */
1392 (intobjargproc) BufferAssItem, /* sq_ass_item, x[i]=v */
1393 (intintobjargproc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1396 static PyTypeObject BufferType = {
1397 PyObject_HEAD_INIT(0)
1399 "buffer",
1400 sizeof(BufferObject),
1403 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1404 (printfunc) 0, /* tp_print, print x */
1405 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1406 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1407 (cmpfunc) 0, /* tp_compare, x>y */
1408 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1410 0, /* as number */
1411 &BufferAsSeq, /* as sequence */
1412 0, /* as mapping */
1414 (hashfunc) 0, /* tp_hash, dict(x) */
1415 (ternaryfunc) 0, /* tp_call, x() */
1416 (reprfunc) 0, /* tp_str, str(x) */
1419 /* Buffer object - Implementation
1422 static PyObject *
1423 BufferNew(buf_T *buf)
1425 /* We need to handle deletion of buffers underneath us.
1426 * If we add a "b_python_ref" field to the buf_T structure,
1427 * then we can get at it in buf_freeall() in vim. We then
1428 * need to create only ONE Python object per buffer - if
1429 * we try to create a second, just INCREF the existing one
1430 * and return it. The (single) Python object referring to
1431 * the buffer is stored in "b_python_ref".
1432 * Question: what to do on a buf_freeall(). We'll probably
1433 * have to either delete the Python object (DECREF it to
1434 * zero - a bad idea, as it leaves dangling refs!) or
1435 * set the buf_T * value to an invalid value (-1?), which
1436 * means we need checks in all access functions... Bah.
1439 BufferObject *self;
1441 if (buf->b_python_ref != NULL)
1443 self = buf->b_python_ref;
1444 Py_INCREF(self);
1446 else
1448 self = PyObject_NEW(BufferObject, &BufferType);
1449 if (self == NULL)
1450 return NULL;
1451 self->buf = buf;
1452 buf->b_python_ref = self;
1455 return (PyObject *)(self);
1458 static void
1459 BufferDestructor(PyObject *self)
1461 BufferObject *this = (BufferObject *)(self);
1463 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
1464 this->buf->b_python_ref = NULL;
1466 Py_DECREF(self);
1469 static PyObject *
1470 BufferGetattr(PyObject *self, char *name)
1472 BufferObject *this = (BufferObject *)(self);
1474 if (CheckBuffer(this))
1475 return NULL;
1477 if (strcmp(name, "name") == 0)
1478 return Py_BuildValue("s",this->buf->b_ffname);
1479 else if (strcmp(name, "number") == 0)
1480 return Py_BuildValue("i",this->buf->b_fnum);
1481 else if (strcmp(name,"__members__") == 0)
1482 return Py_BuildValue("[ss]", "name", "number");
1483 else
1484 return Py_FindMethod(BufferMethods, self, name);
1487 static PyObject *
1488 BufferRepr(PyObject *self)
1490 static char repr[100];
1491 BufferObject *this = (BufferObject *)(self);
1493 if (this->buf == INVALID_BUFFER_VALUE)
1495 vim_snprintf(repr, 100, _("<buffer object (deleted) at %8lX>"),
1496 (long)(self));
1497 return PyString_FromString(repr);
1499 else
1501 char *name = (char *)this->buf->b_fname;
1502 int len;
1504 if (name == NULL)
1505 name = "";
1506 len = strlen(name);
1508 if (len > 35)
1509 name = name + (35 - len);
1511 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
1513 return PyString_FromString(repr);
1517 /******************/
1519 static int
1520 BufferLength(PyObject *self)
1522 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1523 if (CheckBuffer((BufferObject *)(self)))
1524 return -1; /* ??? */
1526 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1529 static PyObject *
1530 BufferItem(PyObject *self, int n)
1532 return RBItem((BufferObject *)(self), n, 1,
1533 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1536 static PyObject *
1537 BufferSlice(PyObject *self, int lo, int hi)
1539 return RBSlice((BufferObject *)(self), lo, hi, 1,
1540 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1543 static int
1544 BufferAssItem(PyObject *self, int n, PyObject *val)
1546 return RBAssItem((BufferObject *)(self), n, val, 1,
1547 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1548 NULL);
1551 static int
1552 BufferAssSlice(PyObject *self, int lo, int hi, PyObject *val)
1554 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
1555 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1556 NULL);
1559 static PyObject *
1560 BufferAppend(PyObject *self, PyObject *args)
1562 return RBAppend((BufferObject *)(self), args, 1,
1563 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1564 NULL);
1567 static PyObject *
1568 BufferMark(PyObject *self, PyObject *args)
1570 pos_T *posp;
1571 char mark;
1572 buf_T *curbuf_save;
1574 if (CheckBuffer((BufferObject *)(self)))
1575 return NULL;
1577 if (!PyArg_ParseTuple(args, "c", &mark))
1578 return NULL;
1580 curbuf_save = curbuf;
1581 curbuf = ((BufferObject *)(self))->buf;
1582 posp = getmark(mark, FALSE);
1583 curbuf = curbuf_save;
1585 if (posp == NULL)
1587 PyErr_SetVim(_("invalid mark name"));
1588 return NULL;
1591 /* Ckeck for keyboard interrupt */
1592 if (VimErrorCheck())
1593 return NULL;
1595 if (posp->lnum <= 0)
1597 /* Or raise an error? */
1598 Py_INCREF(Py_None);
1599 return Py_None;
1602 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1605 static PyObject *
1606 BufferRange(PyObject *self, PyObject *args)
1608 int start;
1609 int end;
1611 if (CheckBuffer((BufferObject *)(self)))
1612 return NULL;
1614 if (!PyArg_ParseTuple(args, "ii", &start, &end))
1615 return NULL;
1617 return RangeNew(((BufferObject *)(self))->buf, start, end);
1620 /* Line range object - Definitions
1623 static struct PyMethodDef RangeMethods[] = {
1624 /* name, function, calling, documentation */
1625 {"append", RangeAppend, 1, "" },
1626 { NULL, NULL, 0, NULL }
1629 static PySequenceMethods RangeAsSeq = {
1630 (inquiry) RangeLength, /* sq_length, len(x) */
1631 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1632 (intargfunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1633 (intargfunc) RangeItem, /* sq_item, x[i] */
1634 (intintargfunc) RangeSlice, /* sq_slice, x[i:j] */
1635 (intobjargproc) RangeAssItem, /* sq_ass_item, x[i]=v */
1636 (intintobjargproc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1639 static PyTypeObject RangeType = {
1640 PyObject_HEAD_INIT(0)
1642 "range",
1643 sizeof(RangeObject),
1646 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */
1647 (printfunc) 0, /* tp_print, print x */
1648 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */
1649 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1650 (cmpfunc) 0, /* tp_compare, x>y */
1651 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */
1653 0, /* as number */
1654 &RangeAsSeq, /* as sequence */
1655 0, /* as mapping */
1657 (hashfunc) 0, /* tp_hash, dict(x) */
1658 (ternaryfunc) 0, /* tp_call, x() */
1659 (reprfunc) 0, /* tp_str, str(x) */
1662 /* Line range object - Implementation
1665 static PyObject *
1666 RangeNew(buf_T *buf, int start, int end)
1668 BufferObject *bufr;
1669 RangeObject *self;
1670 self = PyObject_NEW(RangeObject, &RangeType);
1671 if (self == NULL)
1672 return NULL;
1674 bufr = (BufferObject *)BufferNew(buf);
1675 if (bufr == NULL)
1677 Py_DECREF(self);
1678 return NULL;
1680 Py_INCREF(bufr);
1682 self->buf = bufr;
1683 self->start = start;
1684 self->end = end;
1686 return (PyObject *)(self);
1689 static void
1690 RangeDestructor(PyObject *self)
1692 Py_DECREF(((RangeObject *)(self))->buf);
1693 Py_DECREF(self);
1696 static PyObject *
1697 RangeGetattr(PyObject *self, char *name)
1699 if (strcmp(name, "start") == 0)
1700 return Py_BuildValue("i",((RangeObject *)(self))->start - 1);
1701 else if (strcmp(name, "end") == 0)
1702 return Py_BuildValue("i",((RangeObject *)(self))->end - 1);
1703 else
1704 return Py_FindMethod(RangeMethods, self, name);
1707 static PyObject *
1708 RangeRepr(PyObject *self)
1710 static char repr[100];
1711 RangeObject *this = (RangeObject *)(self);
1713 if (this->buf->buf == INVALID_BUFFER_VALUE)
1715 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %8lX>",
1716 (long)(self));
1717 return PyString_FromString(repr);
1719 else
1721 char *name = (char *)this->buf->buf->b_fname;
1722 int len;
1724 if (name == NULL)
1725 name = "";
1726 len = strlen(name);
1728 if (len > 45)
1729 name = name + (45 - len);
1731 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1732 len > 45 ? "..." : "", name,
1733 this->start, this->end);
1735 return PyString_FromString(repr);
1739 /****************/
1741 static int
1742 RangeLength(PyObject *self)
1744 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1745 if (CheckBuffer(((RangeObject *)(self))->buf))
1746 return -1; /* ??? */
1748 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1751 static PyObject *
1752 RangeItem(PyObject *self, int n)
1754 return RBItem(((RangeObject *)(self))->buf, n,
1755 ((RangeObject *)(self))->start,
1756 ((RangeObject *)(self))->end);
1759 static PyObject *
1760 RangeSlice(PyObject *self, int lo, int hi)
1762 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1763 ((RangeObject *)(self))->start,
1764 ((RangeObject *)(self))->end);
1767 static int
1768 RangeAssItem(PyObject *self, int n, PyObject *val)
1770 return RBAssItem(((RangeObject *)(self))->buf, n, val,
1771 ((RangeObject *)(self))->start,
1772 ((RangeObject *)(self))->end,
1773 &((RangeObject *)(self))->end);
1776 static int
1777 RangeAssSlice(PyObject *self, int lo, int hi, PyObject *val)
1779 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1780 ((RangeObject *)(self))->start,
1781 ((RangeObject *)(self))->end,
1782 &((RangeObject *)(self))->end);
1785 static PyObject *
1786 RangeAppend(PyObject *self, PyObject *args)
1788 return RBAppend(((RangeObject *)(self))->buf, args,
1789 ((RangeObject *)(self))->start,
1790 ((RangeObject *)(self))->end,
1791 &((RangeObject *)(self))->end);
1794 /* Buffer list object - Definitions
1797 typedef struct
1799 PyObject_HEAD
1801 BufListObject;
1803 static PySequenceMethods BufListAsSeq = {
1804 (inquiry) BufListLength, /* sq_length, len(x) */
1805 (binaryfunc) 0, /* sq_concat, x+y */
1806 (intargfunc) 0, /* sq_repeat, x*n */
1807 (intargfunc) BufListItem, /* sq_item, x[i] */
1808 (intintargfunc) 0, /* sq_slice, x[i:j] */
1809 (intobjargproc) 0, /* sq_ass_item, x[i]=v */
1810 (intintobjargproc) 0, /* sq_ass_slice, x[i:j]=v */
1813 static PyTypeObject BufListType = {
1814 PyObject_HEAD_INIT(0)
1816 "buffer list",
1817 sizeof(BufListObject),
1820 (destructor) 0, /* tp_dealloc, refcount==0 */
1821 (printfunc) 0, /* tp_print, print x */
1822 (getattrfunc) 0, /* tp_getattr, x.attr */
1823 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1824 (cmpfunc) 0, /* tp_compare, x>y */
1825 (reprfunc) 0, /* tp_repr, `x`, print x */
1827 0, /* as number */
1828 &BufListAsSeq, /* as sequence */
1829 0, /* as mapping */
1831 (hashfunc) 0, /* tp_hash, dict(x) */
1832 (ternaryfunc) 0, /* tp_call, x() */
1833 (reprfunc) 0, /* tp_str, str(x) */
1836 /* Buffer list object - Implementation
1839 /*ARGSUSED*/
1840 static int
1841 BufListLength(PyObject *self)
1843 buf_T *b = firstbuf;
1844 int n = 0;
1846 while (b)
1848 ++n;
1849 b = b->b_next;
1852 return n;
1855 /*ARGSUSED*/
1856 static PyObject *
1857 BufListItem(PyObject *self, int n)
1859 buf_T *b;
1861 for (b = firstbuf; b; b = b->b_next, --n)
1863 if (n == 0)
1864 return BufferNew(b);
1867 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
1868 return NULL;
1871 /* Window object - Definitions
1874 static struct PyMethodDef WindowMethods[] = {
1875 /* name, function, calling, documentation */
1876 { NULL, NULL, 0, NULL }
1879 static PyTypeObject WindowType = {
1880 PyObject_HEAD_INIT(0)
1882 "window",
1883 sizeof(WindowObject),
1886 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1887 (printfunc) 0, /* tp_print, print x */
1888 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1889 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1890 (cmpfunc) 0, /* tp_compare, x>y */
1891 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1893 0, /* as number */
1894 0, /* as sequence */
1895 0, /* as mapping */
1897 (hashfunc) 0, /* tp_hash, dict(x) */
1898 (ternaryfunc) 0, /* tp_call, x() */
1899 (reprfunc) 0, /* tp_str, str(x) */
1902 /* Window object - Implementation
1905 static PyObject *
1906 WindowNew(win_T *win)
1908 /* We need to handle deletion of windows underneath us.
1909 * If we add a "w_python_ref" field to the win_T structure,
1910 * then we can get at it in win_free() in vim. We then
1911 * need to create only ONE Python object per window - if
1912 * we try to create a second, just INCREF the existing one
1913 * and return it. The (single) Python object referring to
1914 * the window is stored in "w_python_ref".
1915 * On a win_free() we set the Python object's win_T* field
1916 * to an invalid value. We trap all uses of a window
1917 * object, and reject them if the win_T* field is invalid.
1920 WindowObject *self;
1922 if (win->w_python_ref)
1924 self = win->w_python_ref;
1925 Py_INCREF(self);
1927 else
1929 self = PyObject_NEW(WindowObject, &WindowType);
1930 if (self == NULL)
1931 return NULL;
1932 self->win = win;
1933 win->w_python_ref = self;
1936 return (PyObject *)(self);
1939 static void
1940 WindowDestructor(PyObject *self)
1942 WindowObject *this = (WindowObject *)(self);
1944 if (this->win && this->win != INVALID_WINDOW_VALUE)
1945 this->win->w_python_ref = NULL;
1947 Py_DECREF(self);
1950 static int
1951 CheckWindow(WindowObject *this)
1953 if (this->win == INVALID_WINDOW_VALUE)
1955 PyErr_SetVim(_("attempt to refer to deleted window"));
1956 return -1;
1959 return 0;
1962 static PyObject *
1963 WindowGetattr(PyObject *self, char *name)
1965 WindowObject *this = (WindowObject *)(self);
1967 if (CheckWindow(this))
1968 return NULL;
1970 if (strcmp(name, "buffer") == 0)
1971 return (PyObject *)BufferNew(this->win->w_buffer);
1972 else if (strcmp(name, "cursor") == 0)
1974 pos_T *pos = &this->win->w_cursor;
1976 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1978 else if (strcmp(name, "height") == 0)
1979 return Py_BuildValue("l", (long)(this->win->w_height));
1980 #ifdef FEAT_VERTSPLIT
1981 else if (strcmp(name, "width") == 0)
1982 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1983 #endif
1984 else if (strcmp(name,"__members__") == 0)
1985 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1986 else
1987 return Py_FindMethod(WindowMethods, self, name);
1990 static int
1991 WindowSetattr(PyObject *self, char *name, PyObject *val)
1993 WindowObject *this = (WindowObject *)(self);
1995 if (CheckWindow(this))
1996 return -1;
1998 if (strcmp(name, "buffer") == 0)
2000 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
2001 return -1;
2003 else if (strcmp(name, "cursor") == 0)
2005 long lnum;
2006 long col;
2008 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
2009 return -1;
2011 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
2013 PyErr_SetVim(_("cursor position outside buffer"));
2014 return -1;
2017 /* Check for keyboard interrupts */
2018 if (VimErrorCheck())
2019 return -1;
2021 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */
2023 this->win->w_cursor.lnum = lnum;
2024 this->win->w_cursor.col = col;
2025 update_screen(VALID);
2027 return 0;
2029 else if (strcmp(name, "height") == 0)
2031 int height;
2032 win_T *savewin;
2034 if (!PyArg_Parse(val, "i", &height))
2035 return -1;
2037 #ifdef FEAT_GUI
2038 need_mouse_correct = TRUE;
2039 #endif
2040 savewin = curwin;
2041 curwin = this->win;
2042 win_setheight(height);
2043 curwin = savewin;
2045 /* Check for keyboard interrupts */
2046 if (VimErrorCheck())
2047 return -1;
2049 return 0;
2051 #ifdef FEAT_VERTSPLIT
2052 else if (strcmp(name, "width") == 0)
2054 int width;
2055 win_T *savewin;
2057 if (!PyArg_Parse(val, "i", &width))
2058 return -1;
2060 #ifdef FEAT_GUI
2061 need_mouse_correct = TRUE;
2062 #endif
2063 savewin = curwin;
2064 curwin = this->win;
2065 win_setwidth(width);
2066 curwin = savewin;
2068 /* Check for keyboard interrupts */
2069 if (VimErrorCheck())
2070 return -1;
2072 return 0;
2074 #endif
2075 else
2077 PyErr_SetString(PyExc_AttributeError, name);
2078 return -1;
2082 static PyObject *
2083 WindowRepr(PyObject *self)
2085 static char repr[100];
2086 WindowObject *this = (WindowObject *)(self);
2088 if (this->win == INVALID_WINDOW_VALUE)
2090 vim_snprintf(repr, 100, _("<window object (deleted) at %.8lX>"),
2091 (long)(self));
2092 return PyString_FromString(repr);
2094 else
2096 int i = 0;
2097 win_T *w;
2099 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
2100 ++i;
2102 if (w == NULL)
2103 vim_snprintf(repr, 100, _("<window object (unknown) at %.8lX>"),
2104 (long)(self));
2105 else
2106 vim_snprintf(repr, 100, _("<window %d>"), i);
2108 return PyString_FromString(repr);
2112 /* Window list object - Definitions
2115 typedef struct
2117 PyObject_HEAD
2119 WinListObject;
2121 static PySequenceMethods WinListAsSeq = {
2122 (inquiry) WinListLength, /* sq_length, len(x) */
2123 (binaryfunc) 0, /* sq_concat, x+y */
2124 (intargfunc) 0, /* sq_repeat, x*n */
2125 (intargfunc) WinListItem, /* sq_item, x[i] */
2126 (intintargfunc) 0, /* sq_slice, x[i:j] */
2127 (intobjargproc) 0, /* sq_ass_item, x[i]=v */
2128 (intintobjargproc) 0, /* sq_ass_slice, x[i:j]=v */
2131 static PyTypeObject WinListType = {
2132 PyObject_HEAD_INIT(0)
2134 "window list",
2135 sizeof(WinListObject),
2138 (destructor) 0, /* tp_dealloc, refcount==0 */
2139 (printfunc) 0, /* tp_print, print x */
2140 (getattrfunc) 0, /* tp_getattr, x.attr */
2141 (setattrfunc) 0, /* tp_setattr, x.attr=v */
2142 (cmpfunc) 0, /* tp_compare, x>y */
2143 (reprfunc) 0, /* tp_repr, `x`, print x */
2145 0, /* as number */
2146 &WinListAsSeq, /* as sequence */
2147 0, /* as mapping */
2149 (hashfunc) 0, /* tp_hash, dict(x) */
2150 (ternaryfunc) 0, /* tp_call, x() */
2151 (reprfunc) 0, /* tp_str, str(x) */
2154 /* Window list object - Implementation
2156 /*ARGSUSED*/
2157 static int
2158 WinListLength(PyObject *self)
2160 win_T *w = firstwin;
2161 int n = 0;
2163 while (w != NULL)
2165 ++n;
2166 w = W_NEXT(w);
2169 return n;
2172 /*ARGSUSED*/
2173 static PyObject *
2174 WinListItem(PyObject *self, int n)
2176 win_T *w;
2178 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2179 if (n == 0)
2180 return WindowNew(w);
2182 PyErr_SetString(PyExc_IndexError, _("no such window"));
2183 return NULL;
2186 /* Current items object - Definitions
2189 typedef struct
2191 PyObject_HEAD
2193 CurrentObject;
2195 static PyTypeObject CurrentType = {
2196 PyObject_HEAD_INIT(0)
2198 "current data",
2199 sizeof(CurrentObject),
2202 (destructor) 0, /* tp_dealloc, refcount==0 */
2203 (printfunc) 0, /* tp_print, print x */
2204 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
2205 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
2206 (cmpfunc) 0, /* tp_compare, x>y */
2207 (reprfunc) 0, /* tp_repr, `x`, print x */
2209 0, /* as number */
2210 0, /* as sequence */
2211 0, /* as mapping */
2213 (hashfunc) 0, /* tp_hash, dict(x) */
2214 (ternaryfunc) 0, /* tp_call, x() */
2215 (reprfunc) 0, /* tp_str, str(x) */
2218 /* Current items object - Implementation
2220 /*ARGSUSED*/
2221 static PyObject *
2222 CurrentGetattr(PyObject *self, char *name)
2224 if (strcmp(name, "buffer") == 0)
2225 return (PyObject *)BufferNew(curbuf);
2226 else if (strcmp(name, "window") == 0)
2227 return (PyObject *)WindowNew(curwin);
2228 else if (strcmp(name, "line") == 0)
2229 return GetBufferLine(curbuf, (int)curwin->w_cursor.lnum);
2230 else if (strcmp(name, "range") == 0)
2231 return RangeNew(curbuf, RangeStart, RangeEnd);
2232 else if (strcmp(name,"__members__") == 0)
2233 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2234 else
2236 PyErr_SetString(PyExc_AttributeError, name);
2237 return NULL;
2241 /*ARGSUSED*/
2242 static int
2243 CurrentSetattr(PyObject *self, char *name, PyObject *value)
2245 if (strcmp(name, "line") == 0)
2247 if (SetBufferLine(curbuf, (int)curwin->w_cursor.lnum, value, NULL) == FAIL)
2248 return -1;
2250 return 0;
2252 else
2254 PyErr_SetString(PyExc_AttributeError, name);
2255 return -1;
2259 /* External interface
2262 void
2263 python_buffer_free(buf_T *buf)
2265 if (buf->b_python_ref != NULL)
2267 BufferObject *bp = buf->b_python_ref;
2268 bp->buf = INVALID_BUFFER_VALUE;
2269 buf->b_python_ref = NULL;
2273 #if defined(FEAT_WINDOWS) || defined(PROTO)
2274 void
2275 python_window_free(win_T *win)
2277 if (win->w_python_ref != NULL)
2279 WindowObject *wp = win->w_python_ref;
2280 wp->win = INVALID_WINDOW_VALUE;
2281 win->w_python_ref = NULL;
2284 #endif
2286 static BufListObject TheBufferList =
2288 PyObject_HEAD_INIT(&BufListType)
2291 static WinListObject TheWindowList =
2293 PyObject_HEAD_INIT(&WinListType)
2296 static CurrentObject TheCurrent =
2298 PyObject_HEAD_INIT(&CurrentType)
2301 static int
2302 PythonMod_Init(void)
2304 PyObject *mod;
2305 PyObject *dict;
2306 static char *(argv[2]) = {"", NULL};
2308 /* Fixups... */
2309 BufferType.ob_type = &PyType_Type;
2310 RangeType.ob_type = &PyType_Type;
2311 WindowType.ob_type = &PyType_Type;
2312 BufListType.ob_type = &PyType_Type;
2313 WinListType.ob_type = &PyType_Type;
2314 CurrentType.ob_type = &PyType_Type;
2316 /* Set sys.argv[] to avoid a crash in warn(). */
2317 PySys_SetArgv(1, argv);
2319 mod = Py_InitModule("vim", VimMethods);
2320 dict = PyModule_GetDict(mod);
2322 VimError = Py_BuildValue("s", "vim.error");
2324 PyDict_SetItemString(dict, "error", VimError);
2325 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
2326 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
2327 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
2329 if (PyErr_Occurred())
2330 return -1;
2332 return 0;
2335 /*************************************************************************
2336 * 4. Utility functions for handling the interface between Vim and Python.
2339 /* Get a line from the specified buffer. The line number is
2340 * in Vim format (1-based). The line is returned as a Python
2341 * string object.
2343 static PyObject *
2344 GetBufferLine(buf_T *buf, int n)
2346 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2349 /* Get a list of lines from the specified buffer. The line numbers
2350 * are in Vim format (1-based). The range is from lo up to, but not
2351 * including, hi. The list is returned as a Python list of string objects.
2353 static PyObject *
2354 GetBufferLineList(buf_T *buf, int lo, int hi)
2356 int i;
2357 int n = hi - lo;
2358 PyObject *list = PyList_New(n);
2360 if (list == NULL)
2361 return NULL;
2363 for (i = 0; i < n; ++i)
2365 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2367 /* Error check - was the Python string creation OK? */
2368 if (str == NULL)
2370 Py_DECREF(list);
2371 return NULL;
2374 /* Set the list item */
2375 if (PyList_SetItem(list, i, str))
2377 Py_DECREF(str);
2378 Py_DECREF(list);
2379 return NULL;
2383 /* The ownership of the Python list is passed to the caller (ie,
2384 * the caller should Py_DECREF() the object when it is finished
2385 * with it).
2388 return list;
2392 * Check if deleting lines made the cursor position invalid.
2393 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2394 * deleted).
2396 static void
2397 py_fix_cursor(int lo, int hi, int extra)
2399 if (curwin->w_cursor.lnum >= lo)
2401 /* Adjust the cursor position if it's in/after the changed
2402 * lines. */
2403 if (curwin->w_cursor.lnum >= hi)
2405 curwin->w_cursor.lnum += extra;
2406 check_cursor_col();
2408 else if (extra < 0)
2410 curwin->w_cursor.lnum = lo;
2411 check_cursor();
2413 else
2414 check_cursor_col();
2415 changed_cline_bef_curs();
2417 invalidate_botline();
2420 /* Replace a line in the specified buffer. The line number is
2421 * in Vim format (1-based). The replacement line is given as
2422 * a Python string object. The object is checked for validity
2423 * and correct format. Errors are returned as a value of FAIL.
2424 * The return value is OK on success.
2425 * If OK is returned and len_change is not NULL, *len_change
2426 * is set to the change in the buffer length.
2428 static int
2429 SetBufferLine(buf_T *buf, int n, PyObject *line, int *len_change)
2431 /* First of all, we check the thpe of the supplied Python object.
2432 * There are three cases:
2433 * 1. NULL, or None - this is a deletion.
2434 * 2. A string - this is a replacement.
2435 * 3. Anything else - this is an error.
2437 if (line == Py_None || line == NULL)
2439 buf_T *savebuf = curbuf;
2441 PyErr_Clear();
2442 curbuf = buf;
2444 if (u_savedel((linenr_T)n, 1L) == FAIL)
2445 PyErr_SetVim(_("cannot save undo information"));
2446 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2447 PyErr_SetVim(_("cannot delete line"));
2448 else
2450 deleted_lines_mark((linenr_T)n, 1L);
2451 if (buf == curwin->w_buffer)
2452 py_fix_cursor(n, n + 1, -1);
2455 curbuf = savebuf;
2457 if (PyErr_Occurred() || VimErrorCheck())
2458 return FAIL;
2460 if (len_change)
2461 *len_change = -1;
2463 return OK;
2465 else if (PyString_Check(line))
2467 char *save = StringToLine(line);
2468 buf_T *savebuf = curbuf;
2470 if (save == NULL)
2471 return FAIL;
2473 /* We do not need to free "save" if ml_replace() consumes it. */
2474 PyErr_Clear();
2475 curbuf = buf;
2477 if (u_savesub((linenr_T)n) == FAIL)
2479 PyErr_SetVim(_("cannot save undo information"));
2480 vim_free(save);
2482 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2484 PyErr_SetVim(_("cannot replace line"));
2485 vim_free(save);
2487 else
2488 changed_bytes((linenr_T)n, 0);
2490 curbuf = savebuf;
2492 /* Check that the cursor is not beyond the end of the line now. */
2493 if (buf == curwin->w_buffer)
2494 check_cursor_col();
2496 if (PyErr_Occurred() || VimErrorCheck())
2497 return FAIL;
2499 if (len_change)
2500 *len_change = 0;
2502 return OK;
2504 else
2506 PyErr_BadArgument();
2507 return FAIL;
2511 /* Replace a range of lines in the specified buffer. The line numbers are in
2512 * Vim format (1-based). The range is from lo up to, but not including, hi.
2513 * The replacement lines are given as a Python list of string objects. The
2514 * list is checked for validity and correct format. Errors are returned as a
2515 * value of FAIL. The return value is OK on success.
2516 * If OK is returned and len_change is not NULL, *len_change
2517 * is set to the change in the buffer length.
2519 static int
2520 SetBufferLineList(buf_T *buf, int lo, int hi, PyObject *list, int *len_change)
2522 /* First of all, we check the thpe of the supplied Python object.
2523 * There are three cases:
2524 * 1. NULL, or None - this is a deletion.
2525 * 2. A list - this is a replacement.
2526 * 3. Anything else - this is an error.
2528 if (list == Py_None || list == NULL)
2530 int i;
2531 int n = hi - lo;
2532 buf_T *savebuf = curbuf;
2534 PyErr_Clear();
2535 curbuf = buf;
2537 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2538 PyErr_SetVim(_("cannot save undo information"));
2539 else
2541 for (i = 0; i < n; ++i)
2543 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2545 PyErr_SetVim(_("cannot delete line"));
2546 break;
2549 deleted_lines_mark((linenr_T)lo, (long)i);
2551 if (buf == curwin->w_buffer)
2552 py_fix_cursor(lo, hi, -n);
2555 curbuf = savebuf;
2557 if (PyErr_Occurred() || VimErrorCheck())
2558 return FAIL;
2560 if (len_change)
2561 *len_change = -n;
2563 return OK;
2565 else if (PyList_Check(list))
2567 int i;
2568 int new_len = PyList_Size(list);
2569 int old_len = hi - lo;
2570 int extra = 0; /* lines added to text, can be negative */
2571 char **array;
2572 buf_T *savebuf;
2574 if (new_len == 0) /* avoid allocating zero bytes */
2575 array = NULL;
2576 else
2578 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2579 if (array == NULL)
2581 PyErr_NoMemory();
2582 return FAIL;
2586 for (i = 0; i < new_len; ++i)
2588 PyObject *line = PyList_GetItem(list, i);
2590 array[i] = StringToLine(line);
2591 if (array[i] == NULL)
2593 while (i)
2594 vim_free(array[--i]);
2595 vim_free(array);
2596 return FAIL;
2600 savebuf = curbuf;
2602 PyErr_Clear();
2603 curbuf = buf;
2605 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2606 PyErr_SetVim(_("cannot save undo information"));
2608 /* If the size of the range is reducing (ie, new_len < old_len) we
2609 * need to delete some old_len. We do this at the start, by
2610 * repeatedly deleting line "lo".
2612 if (!PyErr_Occurred())
2614 for (i = 0; i < old_len - new_len; ++i)
2615 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2617 PyErr_SetVim(_("cannot delete line"));
2618 break;
2620 extra -= i;
2623 /* For as long as possible, replace the existing old_len with the
2624 * new old_len. This is a more efficient operation, as it requires
2625 * less memory allocation and freeing.
2627 if (!PyErr_Occurred())
2629 for (i = 0; i < old_len && i < new_len; ++i)
2630 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2631 == FAIL)
2633 PyErr_SetVim(_("cannot replace line"));
2634 break;
2637 else
2638 i = 0;
2640 /* Now we may need to insert the remaining new old_len. If we do, we
2641 * must free the strings as we finish with them (we can't pass the
2642 * responsibility to vim in this case).
2644 if (!PyErr_Occurred())
2646 while (i < new_len)
2648 if (ml_append((linenr_T)(lo + i - 1),
2649 (char_u *)array[i], 0, FALSE) == FAIL)
2651 PyErr_SetVim(_("cannot insert line"));
2652 break;
2654 vim_free(array[i]);
2655 ++i;
2656 ++extra;
2660 /* Free any left-over old_len, as a result of an error */
2661 while (i < new_len)
2663 vim_free(array[i]);
2664 ++i;
2667 /* Free the array of old_len. All of its contents have now
2668 * been dealt with (either freed, or the responsibility passed
2669 * to vim.
2671 vim_free(array);
2673 /* Adjust marks. Invalidate any which lie in the
2674 * changed range, and move any in the remainder of the buffer.
2676 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2677 (long)MAXLNUM, (long)extra);
2678 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2680 if (buf == curwin->w_buffer)
2681 py_fix_cursor(lo, hi, extra);
2683 curbuf = savebuf;
2685 if (PyErr_Occurred() || VimErrorCheck())
2686 return FAIL;
2688 if (len_change)
2689 *len_change = new_len - old_len;
2691 return OK;
2693 else
2695 PyErr_BadArgument();
2696 return FAIL;
2700 /* Insert a number of lines into the specified buffer after the specifed line.
2701 * The line number is in Vim format (1-based). The lines to be inserted are
2702 * given as a Python list of string objects or as a single string. The lines
2703 * to be added are checked for validity and correct format. Errors are
2704 * returned as a value of FAIL. The return value is OK on success.
2705 * If OK is returned and len_change is not NULL, *len_change
2706 * is set to the change in the buffer length.
2708 static int
2709 InsertBufferLines(buf_T *buf, int n, PyObject *lines, int *len_change)
2711 /* First of all, we check the type of the supplied Python object.
2712 * It must be a string or a list, or the call is in error.
2714 if (PyString_Check(lines))
2716 char *str = StringToLine(lines);
2717 buf_T *savebuf;
2719 if (str == NULL)
2720 return FAIL;
2722 savebuf = curbuf;
2724 PyErr_Clear();
2725 curbuf = buf;
2727 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2728 PyErr_SetVim(_("cannot save undo information"));
2729 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2730 PyErr_SetVim(_("cannot insert line"));
2731 else
2732 appended_lines_mark((linenr_T)n, 1L);
2734 vim_free(str);
2735 curbuf = savebuf;
2736 update_screen(VALID);
2738 if (PyErr_Occurred() || VimErrorCheck())
2739 return FAIL;
2741 if (len_change)
2742 *len_change = 1;
2744 return OK;
2746 else if (PyList_Check(lines))
2748 int i;
2749 int size = PyList_Size(lines);
2750 char **array;
2751 buf_T *savebuf;
2753 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2754 if (array == NULL)
2756 PyErr_NoMemory();
2757 return FAIL;
2760 for (i = 0; i < size; ++i)
2762 PyObject *line = PyList_GetItem(lines, i);
2763 array[i] = StringToLine(line);
2765 if (array[i] == NULL)
2767 while (i)
2768 vim_free(array[--i]);
2769 vim_free(array);
2770 return FAIL;
2774 savebuf = curbuf;
2776 PyErr_Clear();
2777 curbuf = buf;
2779 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2780 PyErr_SetVim(_("cannot save undo information"));
2781 else
2783 for (i = 0; i < size; ++i)
2785 if (ml_append((linenr_T)(n + i),
2786 (char_u *)array[i], 0, FALSE) == FAIL)
2788 PyErr_SetVim(_("cannot insert line"));
2790 /* Free the rest of the lines */
2791 while (i < size)
2792 vim_free(array[i++]);
2794 break;
2796 vim_free(array[i]);
2798 if (i > 0)
2799 appended_lines_mark((linenr_T)n, (long)i);
2802 /* Free the array of lines. All of its contents have now
2803 * been freed.
2805 vim_free(array);
2807 curbuf = savebuf;
2808 update_screen(VALID);
2810 if (PyErr_Occurred() || VimErrorCheck())
2811 return FAIL;
2813 if (len_change)
2814 *len_change = size;
2816 return OK;
2818 else
2820 PyErr_BadArgument();
2821 return FAIL;
2825 /* Convert a Vim line into a Python string.
2826 * All internal newlines are replaced by null characters.
2828 * On errors, the Python exception data is set, and NULL is returned.
2830 static PyObject *
2831 LineToString(const char *str)
2833 PyObject *result;
2834 int len = strlen(str);
2835 char *p;
2837 /* Allocate an Python string object, with uninitialised contents. We
2838 * must do it this way, so that we can modify the string in place
2839 * later. See the Python source, Objects/stringobject.c for details.
2841 result = PyString_FromStringAndSize(NULL, len);
2842 if (result == NULL)
2843 return NULL;
2845 p = PyString_AsString(result);
2847 while (*str)
2849 if (*str == '\n')
2850 *p = '\0';
2851 else
2852 *p = *str;
2854 ++p;
2855 ++str;
2858 return result;
2861 /* Convert a Python string into a Vim line.
2863 * The result is in allocated memory. All internal nulls are replaced by
2864 * newline characters. It is an error for the string to contain newline
2865 * characters.
2867 * On errors, the Python exception data is set, and NULL is returned.
2869 static char *
2870 StringToLine(PyObject *obj)
2872 const char *str;
2873 char *save;
2874 int len;
2875 int i;
2876 char *p;
2878 if (obj == NULL || !PyString_Check(obj))
2880 PyErr_BadArgument();
2881 return NULL;
2884 str = PyString_AsString(obj);
2885 len = PyString_Size(obj);
2888 * Error checking: String must not contain newlines, as we
2889 * are replacing a single line, and we must replace it with
2890 * a single line.
2891 * A trailing newline is removed, so that append(f.readlines()) works.
2893 p = memchr(str, '\n', len);
2894 if (p != NULL)
2896 if (p == str + len - 1)
2897 --len;
2898 else
2900 PyErr_SetVim(_("string cannot contain newlines"));
2901 return NULL;
2905 /* Create a copy of the string, with internal nulls replaced by
2906 * newline characters, as is the vim convention.
2908 save = (char *)alloc((unsigned)(len+1));
2909 if (save == NULL)
2911 PyErr_NoMemory();
2912 return NULL;
2915 for (i = 0; i < len; ++i)
2917 if (str[i] == '\0')
2918 save[i] = '\n';
2919 else
2920 save[i] = str[i];
2923 save[i] = '\0';
2925 return save;
2928 /* Check to see whether a Vim error has been reported, or a keyboard
2929 * interrupt has been detected.
2931 static int
2932 VimErrorCheck(void)
2934 if (got_int)
2936 PyErr_SetNone(PyExc_KeyboardInterrupt);
2937 return 1;
2939 else if (did_emsg && !PyErr_Occurred())
2941 PyErr_SetNone(VimError);
2942 return 1;
2945 return 0;
2949 /* Don't generate a prototype for the next function, it generates an error on
2950 * newer Python versions. */
2951 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
2953 char *
2954 Py_GetProgramName(void)
2956 return "vim";
2958 #endif /* Python 1.4 */