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.
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.
24 /* Python.h defines _POSIX_THREADS itself (if needed) */
26 # undef _POSIX_THREADS
29 #if defined(_WIN32) && defined (HAVE_FCNTL_H)
38 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */
42 #if defined(MACOS) && !defined(MACOS_X_UNIX)
44 # include <CodeFragments.h>
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. */
52 # define PyThreadState int
53 # define PyTypeObject int
54 struct PyMethodDef
{ int a
; };
55 # define PySequenceMethods int
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
68 #if defined(DYNAMIC_PYTHON) || defined(PROTO)
69 # ifndef DYNAMIC_PYTHON
70 # define HINSTANCE int /* for generating prototypes */
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
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
126 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
127 # define PyObject_Malloc dll_PyObject_Malloc
128 # define PyObject_Free dll_PyObject_Free
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
);
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
*);
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*);
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
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
},
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
},
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
},
275 end_dynamic_python(void)
279 FreeLibrary(hinstPython
);
285 * Load library and get all pointers.
286 * Parameter 'libname' provides name of DLL.
290 python_runtime_link_init(char *libname
, int verbose
)
296 hinstPython
= LoadLibrary(libname
);
300 EMSG2(_(e_loadlib
), libname
);
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
);
312 EMSG2(_(e_loadfunc
), python_funcname_table
[i
].name
);
320 * If python is enabled (there is installed python on Windows system) return
324 python_enabled(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));
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
);
352 #endif /* DYNAMIC_PYTHON */
354 /******************************************************
355 * Internal function prototypes.
358 static void DoPythonCommand(exarg_T
*, const char *);
359 static int RangeStart
;
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
;
393 #ifdef PY_CAN_RECURSE
394 static PyGILState_STATE pygilstate
= PyGILState_UNLOCKED
;
396 static PyThreadState
*saved_python_thread
= NULL
;
400 * Suspend a thread of the Python interpreter, other threads are allowed to
404 Python_SaveThread(void)
406 #ifdef PY_CAN_RECURSE
407 PyGILState_Release(pygilstate
);
409 saved_python_thread
= PyEval_SaveThread();
414 * Restore a thread of the Python interpreter, waits for other threads to
418 Python_RestoreThread(void)
420 #ifdef PY_CAN_RECURSE
421 pygilstate
= PyGILState_Ensure();
423 PyEval_RestoreThread(saved_python_thread
);
424 saved_python_thread
= NULL
;
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)
445 static int recurse
= 0;
447 /* If a crash occurs while doing this, don't try again. */
453 #ifdef DYNAMIC_PYTHON
454 if (hinstPython
&& Py_IsInitialized())
456 Python_RestoreThread(); /* enter python */
459 end_dynamic_python();
461 if (Py_IsInitialized())
463 Python_RestoreThread(); /* enter python */
476 #ifdef DYNAMIC_PYTHON
477 if (!python_enabled(TRUE
))
479 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
484 #if !defined(MACOS) || defined(MACOS_X_UNIX)
489 /* initialise threads */
490 PyEval_InitThreads();
492 #ifdef DYNAMIC_PYTHON
499 if (PythonMod_Init())
502 /* the first python thread is vim's, release the lock */
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).
524 DoPythonCommand(exarg_T
*eap
, const char *cmd
)
526 #ifndef PY_CAN_RECURSE
527 static int recursive
= 0;
529 #if defined(MACOS) && !defined(MACOS_X_UNIX)
532 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
536 #ifndef PY_CAN_RECURSE
539 EMSG(_("E659: Cannot invoke Python recursively"));
545 #if defined(MACOS) && !defined(MACOS_X_UNIX)
547 /* Check if the Python library is available */
548 if ((Ptr
)PyMac_Initialize
== (Ptr
)kUnresolvedCFragSymbolAddress
)
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)
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");
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
);
585 Python_Lock_Vim(); /* enter vim */
587 #if defined(MACOS) && !defined(MACOS_X_UNIX)
592 #ifndef PY_CAN_RECURSE
595 return; /* keeps lint happy */
602 ex_python(exarg_T
*eap
)
606 script
= script_get(eap
, eap
->arg
);
610 DoPythonCommand(eap
, (char *)eap
->arg
);
612 DoPythonCommand(eap
, (char *)script
);
617 #define BUFFER_SIZE 1024
623 ex_pyfile(exarg_T
*eap
)
625 static char buffer
[BUFFER_SIZE
];
626 const char *file
= (char *)eap
->arg
;
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
== '\'')
648 /* If we didn't finish the file name, we hit a buffer overflow */
652 /* Put in the terminating "')" and a null */
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
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)
698 sizeof(OutputObject
),
703 (getattrfunc
) OutputGetattr
,
704 (setattrfunc
) OutputSetattr
,
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
);
729 OutputSetattr(PyObject
*self
, char *name
, PyObject
*val
)
732 PyErr_SetString(PyExc_AttributeError
, _("can't delete OutputObject attributes"));
736 if (strcmp(name
, "softspace") == 0)
738 if (!PyInt_Check(val
)) {
739 PyErr_SetString(PyExc_TypeError
, _("softspace must be an integer"));
743 ((OutputObject
*)(self
))->softspace
= PyInt_AsLong(val
);
747 PyErr_SetString(PyExc_AttributeError
, _("invalid attribute"));
754 OutputWrite(PyObject
*self
, PyObject
*args
)
758 int error
= ((OutputObject
*)(self
))->error
;
760 if (!PyArg_ParseTuple(args
, "s#", &str
, &len
))
763 Py_BEGIN_ALLOW_THREADS
765 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
766 Python_Release_Vim();
774 OutputWritelines(PyObject
*self
, PyObject
*args
)
779 int error
= ((OutputObject
*)(self
))->error
;
781 if (!PyArg_ParseTuple(args
, "O", &list
))
785 if (!PyList_Check(list
)) {
786 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
791 n
= PyList_Size(list
);
793 for (i
= 0; i
< n
; ++i
)
795 PyObject
*line
= PyList_GetItem(list
, i
);
799 if (!PyArg_Parse(line
, "s#", &str
, &len
)) {
800 PyErr_SetString(PyExc_TypeError
, _("writelines() requires list of strings"));
805 Py_BEGIN_ALLOW_THREADS
807 writer((writefn
)(error
? emsg
: msg
), (char_u
*)str
, len
);
808 Python_Release_Vim();
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
;
835 new_size
= buffer_size
;
839 if (new_size
!= buffer_size
)
841 new_buffer
= alloc((unsigned)new_size
);
842 if (new_buffer
== NULL
)
847 memcpy(new_buffer
, buffer
, buffer_len
);
852 buffer_size
= new_size
;
859 if (old_fn
&& buffer_len
)
861 buffer
[buffer_len
] = 0;
869 writer(writefn fn
, char_u
*str
, int n
)
873 if (fn
!= old_fn
&& old_fn
!= NULL
)
878 while (n
> 0 && (ptr
= memchr(str
, '\n', n
)) != NULL
)
882 buffer_ensure(buffer_len
+ len
+ 1);
884 memcpy(buffer
+ buffer_len
, str
, len
);
886 buffer
[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
);
901 static OutputObject Output
=
903 PyObject_HEAD_INIT(&OutputType
)
908 static OutputObject Error
=
910 PyObject_HEAD_INIT(&OutputType
)
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"));
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 * --------------------------------------
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 * --------------------------------------
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 * --------------------------------------
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
1063 VimCommand(PyObject
*self
, PyObject
*args
)
1068 if (!PyArg_ParseTuple(args
, "s", &cmd
))
1073 Py_BEGIN_ALLOW_THREADS
1076 do_cmdline_cmd((char_u
*)cmd
);
1077 update_screen(VALID
);
1079 Python_Release_Vim();
1080 Py_END_ALLOW_THREADS
1082 if (VimErrorCheck())
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.
1099 VimToPython(typval_T
*our_tv
, int depth
, PyObject
*lookupDict
)
1103 char ptrBuf
[NUMBUFLEN
];
1105 /* Avoid infinite recursion */
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
);
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
;
1138 result
= PyList_New(0);
1139 PyDict_SetItemString(lookupDict
, ptrBuf
, result
);
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
);
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
;
1163 for (hi
= ht
->ht_array
; todo
> 0; ++hi
)
1165 if (!HASHITEM_EMPTY(hi
))
1169 di
= dict_lookup(hi
);
1170 newObj
= VimToPython(&di
->di_tv
, depth
+ 1, lookupDict
);
1171 PyDict_SetItemString(result
, (char *)hi
->hi_key
, newObj
);
1188 VimEval(PyObject
*self
, PyObject
*args
)
1194 PyObject
*lookup_dict
;
1196 if (!PyArg_ParseTuple(args
, "s", &expr
))
1199 Py_BEGIN_ALLOW_THREADS
1201 our_tv
= eval_expr((char_u
*)expr
, NULL
);
1203 Python_Release_Vim();
1204 Py_END_ALLOW_THREADS
1208 PyErr_SetVim(_("invalid expression"));
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
1222 Python_Release_Vim();
1223 Py_END_ALLOW_THREADS
1227 PyErr_SetVim(_("expressions disabled at compile time"));
1232 /* Common routines for buffers and line ranges
1233 * -------------------------------------------
1236 CheckBuffer(BufferObject
*this)
1238 if (this->buf
== INVALID_BUFFER_VALUE
)
1240 PyErr_SetVim(_("attempt to refer to deleted buffer"));
1248 RBItem(BufferObject
*self
, int n
, int start
, int end
)
1250 if (CheckBuffer(self
))
1253 if (n
< 0 || n
> end
- start
)
1255 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1259 return GetBufferLine(self
->buf
, n
+start
);
1263 RBSlice(BufferObject
*self
, int lo
, int hi
, int start
, int end
)
1267 if (CheckBuffer(self
))
1270 size
= end
- start
+ 1;
1283 return GetBufferLineList(self
->buf
, lo
+start
, hi
+start
);
1287 RBAssItem(BufferObject
*self
, int n
, PyObject
*val
, int start
, int end
, int *new_end
)
1291 if (CheckBuffer(self
))
1294 if (n
< 0 || n
> end
- start
)
1296 PyErr_SetString(PyExc_IndexError
, _("line number out of range"));
1300 if (SetBufferLine(self
->buf
, n
+start
, val
, &len_change
) == FAIL
)
1304 *new_end
= end
+ len_change
;
1310 RBAssSlice(BufferObject
*self
, int lo
, int hi
, PyObject
*val
, int start
, int end
, int *new_end
)
1315 /* Self must be a valid buffer */
1316 if (CheckBuffer(self
))
1319 /* Sort out the slice range */
1320 size
= end
- start
+ 1;
1333 if (SetBufferLineList(self
->buf
, lo
+start
, hi
+start
, val
, &len_change
) == FAIL
)
1337 *new_end
= end
+ len_change
;
1343 RBAppend(BufferObject
*self
, PyObject
*args
, int start
, int end
, int *new_end
)
1350 if (CheckBuffer(self
))
1353 max
= n
= end
- start
+ 1;
1355 if (!PyArg_ParseTuple(args
, "O|i", &lines
, &n
))
1358 if (n
< 0 || n
> max
)
1360 PyErr_SetString(PyExc_ValueError
, _("line number out of range"));
1364 if (InsertBufferLines(self
->buf
, n
+ start
- 1, lines
, &len_change
) == FAIL
)
1368 *new_end
= end
+ len_change
;
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)
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 */
1411 &BufferAsSeq
, /* as sequence */
1414 (hashfunc
) 0, /* tp_hash, dict(x) */
1415 (ternaryfunc
) 0, /* tp_call, x() */
1416 (reprfunc
) 0, /* tp_str, str(x) */
1419 /* Buffer object - Implementation
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.
1441 if (buf
->b_python_ref
!= NULL
)
1443 self
= buf
->b_python_ref
;
1448 self
= PyObject_NEW(BufferObject
, &BufferType
);
1452 buf
->b_python_ref
= self
;
1455 return (PyObject
*)(self
);
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
;
1470 BufferGetattr(PyObject
*self
, char *name
)
1472 BufferObject
*this = (BufferObject
*)(self
);
1474 if (CheckBuffer(this))
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");
1484 return Py_FindMethod(BufferMethods
, self
, name
);
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>"),
1497 return PyString_FromString(repr
);
1501 char *name
= (char *)this->buf
->b_fname
;
1509 name
= name
+ (35 - len
);
1511 vim_snprintf(repr
, 100, "<buffer %s%s>", len
> 35 ? "..." : "", name
);
1513 return PyString_FromString(repr
);
1517 /******************/
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
);
1530 BufferItem(PyObject
*self
, int n
)
1532 return RBItem((BufferObject
*)(self
), n
, 1,
1533 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
);
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
);
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
,
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
,
1560 BufferAppend(PyObject
*self
, PyObject
*args
)
1562 return RBAppend((BufferObject
*)(self
), args
, 1,
1563 (int)((BufferObject
*)(self
))->buf
->b_ml
.ml_line_count
,
1568 BufferMark(PyObject
*self
, PyObject
*args
)
1574 if (CheckBuffer((BufferObject
*)(self
)))
1577 if (!PyArg_ParseTuple(args
, "c", &mark
))
1580 curbuf_save
= curbuf
;
1581 curbuf
= ((BufferObject
*)(self
))->buf
;
1582 posp
= getmark(mark
, FALSE
);
1583 curbuf
= curbuf_save
;
1587 PyErr_SetVim(_("invalid mark name"));
1591 /* Ckeck for keyboard interrupt */
1592 if (VimErrorCheck())
1595 if (posp
->lnum
<= 0)
1597 /* Or raise an error? */
1602 return Py_BuildValue("(ll)", (long)(posp
->lnum
), (long)(posp
->col
));
1606 BufferRange(PyObject
*self
, PyObject
*args
)
1611 if (CheckBuffer((BufferObject
*)(self
)))
1614 if (!PyArg_ParseTuple(args
, "ii", &start
, &end
))
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)
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 */
1654 &RangeAsSeq
, /* as sequence */
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
1666 RangeNew(buf_T
*buf
, int start
, int end
)
1670 self
= PyObject_NEW(RangeObject
, &RangeType
);
1674 bufr
= (BufferObject
*)BufferNew(buf
);
1683 self
->start
= start
;
1686 return (PyObject
*)(self
);
1690 RangeDestructor(PyObject
*self
)
1692 Py_DECREF(((RangeObject
*)(self
))->buf
);
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);
1704 return Py_FindMethod(RangeMethods
, self
, name
);
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>",
1717 return PyString_FromString(repr
);
1721 char *name
= (char *)this->buf
->buf
->b_fname
;
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
);
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);
1752 RangeItem(PyObject
*self
, int n
)
1754 return RBItem(((RangeObject
*)(self
))->buf
, n
,
1755 ((RangeObject
*)(self
))->start
,
1756 ((RangeObject
*)(self
))->end
);
1760 RangeSlice(PyObject
*self
, int lo
, int hi
)
1762 return RBSlice(((RangeObject
*)(self
))->buf
, lo
, hi
,
1763 ((RangeObject
*)(self
))->start
,
1764 ((RangeObject
*)(self
))->end
);
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
);
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
);
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
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)
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 */
1828 &BufListAsSeq
, /* as sequence */
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
1841 BufListLength(PyObject
*self
)
1843 buf_T
*b
= firstbuf
;
1857 BufListItem(PyObject
*self
, int n
)
1861 for (b
= firstbuf
; b
; b
= b
->b_next
, --n
)
1864 return BufferNew(b
);
1867 PyErr_SetString(PyExc_IndexError
, _("no such buffer"));
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)
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 */
1894 0, /* as sequence */
1897 (hashfunc
) 0, /* tp_hash, dict(x) */
1898 (ternaryfunc
) 0, /* tp_call, x() */
1899 (reprfunc
) 0, /* tp_str, str(x) */
1902 /* Window object - Implementation
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.
1922 if (win
->w_python_ref
)
1924 self
= win
->w_python_ref
;
1929 self
= PyObject_NEW(WindowObject
, &WindowType
);
1933 win
->w_python_ref
= self
;
1936 return (PyObject
*)(self
);
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
;
1951 CheckWindow(WindowObject
*this)
1953 if (this->win
== INVALID_WINDOW_VALUE
)
1955 PyErr_SetVim(_("attempt to refer to deleted window"));
1963 WindowGetattr(PyObject
*self
, char *name
)
1965 WindowObject
*this = (WindowObject
*)(self
);
1967 if (CheckWindow(this))
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
)));
1984 else if (strcmp(name
,"__members__") == 0)
1985 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1987 return Py_FindMethod(WindowMethods
, self
, name
);
1991 WindowSetattr(PyObject
*self
, char *name
, PyObject
*val
)
1993 WindowObject
*this = (WindowObject
*)(self
);
1995 if (CheckWindow(this))
1998 if (strcmp(name
, "buffer") == 0)
2000 PyErr_SetString(PyExc_TypeError
, _("readonly attribute"));
2003 else if (strcmp(name
, "cursor") == 0)
2008 if (!PyArg_Parse(val
, "(ll)", &lnum
, &col
))
2011 if (lnum
<= 0 || lnum
> this->win
->w_buffer
->b_ml
.ml_line_count
)
2013 PyErr_SetVim(_("cursor position outside buffer"));
2017 /* Check for keyboard interrupts */
2018 if (VimErrorCheck())
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
);
2029 else if (strcmp(name
, "height") == 0)
2034 if (!PyArg_Parse(val
, "i", &height
))
2038 need_mouse_correct
= TRUE
;
2042 win_setheight(height
);
2045 /* Check for keyboard interrupts */
2046 if (VimErrorCheck())
2051 #ifdef FEAT_VERTSPLIT
2052 else if (strcmp(name
, "width") == 0)
2057 if (!PyArg_Parse(val
, "i", &width
))
2061 need_mouse_correct
= TRUE
;
2065 win_setwidth(width
);
2068 /* Check for keyboard interrupts */
2069 if (VimErrorCheck())
2077 PyErr_SetString(PyExc_AttributeError
, name
);
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>"),
2092 return PyString_FromString(repr
);
2099 for (w
= firstwin
; w
!= NULL
&& w
!= this->win
; w
= W_NEXT(w
))
2103 vim_snprintf(repr
, 100, _("<window object (unknown) at %.8lX>"),
2106 vim_snprintf(repr
, 100, _("<window %d>"), i
);
2108 return PyString_FromString(repr
);
2112 /* Window list object - Definitions
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)
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 */
2146 &WinListAsSeq
, /* as sequence */
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
2158 WinListLength(PyObject
*self
)
2160 win_T
*w
= firstwin
;
2174 WinListItem(PyObject
*self
, int n
)
2178 for (w
= firstwin
; w
!= NULL
; w
= W_NEXT(w
), --n
)
2180 return WindowNew(w
);
2182 PyErr_SetString(PyExc_IndexError
, _("no such window"));
2186 /* Current items object - Definitions
2195 static PyTypeObject CurrentType
= {
2196 PyObject_HEAD_INIT(0)
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 */
2210 0, /* as sequence */
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
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");
2236 PyErr_SetString(PyExc_AttributeError
, name
);
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
)
2254 PyErr_SetString(PyExc_AttributeError
, name
);
2259 /* External interface
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)
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
;
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
)
2302 PythonMod_Init(void)
2306 static char *(argv
[2]) = {"", NULL
};
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())
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
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.
2354 GetBufferLineList(buf_T
*buf
, int lo
, int hi
)
2358 PyObject
*list
= PyList_New(n
);
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? */
2374 /* Set the list item */
2375 if (PyList_SetItem(list
, i
, str
))
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
2392 * Check if deleting lines made the cursor position invalid.
2393 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
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
2403 if (curwin
->w_cursor
.lnum
>= hi
)
2405 curwin
->w_cursor
.lnum
+= extra
;
2410 curwin
->w_cursor
.lnum
= lo
;
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.
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
;
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"));
2450 deleted_lines_mark((linenr_T
)n
, 1L);
2451 if (buf
== curwin
->w_buffer
)
2452 py_fix_cursor(n
, n
+ 1, -1);
2457 if (PyErr_Occurred() || VimErrorCheck())
2465 else if (PyString_Check(line
))
2467 char *save
= StringToLine(line
);
2468 buf_T
*savebuf
= curbuf
;
2473 /* We do not need to free "save" if ml_replace() consumes it. */
2477 if (u_savesub((linenr_T
)n
) == FAIL
)
2479 PyErr_SetVim(_("cannot save undo information"));
2482 else if (ml_replace((linenr_T
)n
, (char_u
*)save
, FALSE
) == FAIL
)
2484 PyErr_SetVim(_("cannot replace line"));
2488 changed_bytes((linenr_T
)n
, 0);
2492 /* Check that the cursor is not beyond the end of the line now. */
2493 if (buf
== curwin
->w_buffer
)
2496 if (PyErr_Occurred() || VimErrorCheck())
2506 PyErr_BadArgument();
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.
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
)
2532 buf_T
*savebuf
= curbuf
;
2537 if (u_savedel((linenr_T
)lo
, (long)n
) == FAIL
)
2538 PyErr_SetVim(_("cannot save undo information"));
2541 for (i
= 0; i
< n
; ++i
)
2543 if (ml_delete((linenr_T
)lo
, FALSE
) == FAIL
)
2545 PyErr_SetVim(_("cannot delete line"));
2549 deleted_lines_mark((linenr_T
)lo
, (long)i
);
2551 if (buf
== curwin
->w_buffer
)
2552 py_fix_cursor(lo
, hi
, -n
);
2557 if (PyErr_Occurred() || VimErrorCheck())
2565 else if (PyList_Check(list
))
2568 int new_len
= PyList_Size(list
);
2569 int old_len
= hi
- lo
;
2570 int extra
= 0; /* lines added to text, can be negative */
2574 if (new_len
== 0) /* avoid allocating zero bytes */
2578 array
= (char **)alloc((unsigned)(new_len
* sizeof(char *)));
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
)
2594 vim_free(array
[--i
]);
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"));
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
)
2633 PyErr_SetVim(_("cannot replace line"));
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())
2648 if (ml_append((linenr_T
)(lo
+ i
- 1),
2649 (char_u
*)array
[i
], 0, FALSE
) == FAIL
)
2651 PyErr_SetVim(_("cannot insert line"));
2660 /* Free any left-over old_len, as a result of an error */
2667 /* Free the array of old_len. All of its contents have now
2668 * been dealt with (either freed, or the responsibility passed
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
);
2685 if (PyErr_Occurred() || VimErrorCheck())
2689 *len_change
= new_len
- old_len
;
2695 PyErr_BadArgument();
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.
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
);
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"));
2732 appended_lines_mark((linenr_T
)n
, 1L);
2736 update_screen(VALID
);
2738 if (PyErr_Occurred() || VimErrorCheck())
2746 else if (PyList_Check(lines
))
2749 int size
= PyList_Size(lines
);
2753 array
= (char **)alloc((unsigned)(size
* sizeof(char *)));
2760 for (i
= 0; i
< size
; ++i
)
2762 PyObject
*line
= PyList_GetItem(lines
, i
);
2763 array
[i
] = StringToLine(line
);
2765 if (array
[i
] == NULL
)
2768 vim_free(array
[--i
]);
2779 if (u_save((linenr_T
)n
, (linenr_T
)(n
+ 1)) == FAIL
)
2780 PyErr_SetVim(_("cannot save undo information"));
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 */
2792 vim_free(array
[i
++]);
2799 appended_lines_mark((linenr_T
)n
, (long)i
);
2802 /* Free the array of lines. All of its contents have now
2808 update_screen(VALID
);
2810 if (PyErr_Occurred() || VimErrorCheck())
2820 PyErr_BadArgument();
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.
2831 LineToString(const char *str
)
2834 int len
= strlen(str
);
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
);
2845 p
= PyString_AsString(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
2867 * On errors, the Python exception data is set, and NULL is returned.
2870 StringToLine(PyObject
*obj
)
2878 if (obj
== NULL
|| !PyString_Check(obj
))
2880 PyErr_BadArgument();
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
2891 * A trailing newline is removed, so that append(f.readlines()) works.
2893 p
= memchr(str
, '\n', len
);
2896 if (p
== str
+ len
- 1)
2900 PyErr_SetVim(_("string cannot contain newlines"));
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));
2915 for (i
= 0; i
< len
; ++i
)
2928 /* Check to see whether a Vim error has been reported, or a keyboard
2929 * interrupt has been detected.
2936 PyErr_SetNone(PyExc_KeyboardInterrupt
);
2939 else if (did_emsg
&& !PyErr_Occurred())
2941 PyErr_SetNone(VimError
);
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)
2954 Py_GetProgramName(void)
2958 #endif /* Python 1.4 */