blob: 374ad2ce69cc57f4c486db5768f3c0d78bd5d242 [file] [log] [blame]
Bram Moolenaardb913952012-06-29 12:54:53 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * Python extensions by Paul Moore.
11 * Changes for Unix by David Leonard.
12 *
13 * This consists of four parts:
14 * 1. Python interpreter main program
15 * 2. Python output stream: writes output via [e]msg().
16 * 3. Implementation of the Vim module for Python
17 * 4. Utility functions for handling the interface between Vim and Python.
18 */
19
20#include "vim.h"
21
Bram Moolenaar071d4272004-06-13 20:20:40 +000022#include <limits.h>
23
24/* Python.h defines _POSIX_THREADS itself (if needed) */
25#ifdef _POSIX_THREADS
26# undef _POSIX_THREADS
27#endif
28
Bram Moolenaar860cae12010-06-05 23:22:07 +020029#if defined(_WIN32) && defined(HAVE_FCNTL_H)
Bram Moolenaar071d4272004-06-13 20:20:40 +000030# undef HAVE_FCNTL_H
31#endif
32
33#ifdef _DEBUG
34# undef _DEBUG
35#endif
36
37#ifdef HAVE_STDARG_H
38# undef HAVE_STDARG_H /* Python's config.h defines it as well. */
39#endif
Bram Moolenaarbe2c9ae2009-11-11 14:06:59 +000040#ifdef _POSIX_C_SOURCE
41# undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
42#endif
43#ifdef _XOPEN_SOURCE
44# undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
45#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000046
Bram Moolenaar2c45e942008-06-04 11:35:26 +000047#define PY_SSIZE_T_CLEAN
48
Bram Moolenaar071d4272004-06-13 20:20:40 +000049#include <Python.h>
50#if defined(MACOS) && !defined(MACOS_X_UNIX)
51# include "macglue.h"
52# include <CodeFragments.h>
53#endif
54#undef main /* Defined in python.h - aargh */
55#undef HAVE_FCNTL_H /* Clash with os_win32.h */
56
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020057static void init_structs(void);
58
Bram Moolenaardb913952012-06-29 12:54:53 +020059#define PyBytes_FromString PyString_FromString
60
Bram Moolenaar19e60942011-06-19 00:27:51 +020061/* No-op conversion functions, use with care! */
62#define PyString_AsBytes(obj) (obj)
63#define PyString_FreeBytes(obj)
64
Bram Moolenaar071d4272004-06-13 20:20:40 +000065#if !defined(FEAT_PYTHON) && defined(PROTO)
66/* Use this to be able to generate prototypes without python being used. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000067# define PyObject Py_ssize_t
68# define PyThreadState Py_ssize_t
69# define PyTypeObject Py_ssize_t
70struct PyMethodDef { Py_ssize_t a; };
71# define PySequenceMethods Py_ssize_t
Bram Moolenaar071d4272004-06-13 20:20:40 +000072#endif
73
Bram Moolenaar2afa3232012-06-29 16:28:28 +020074#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
75# define PY_USE_CAPSULE
76#endif
77
Bram Moolenaar2c45e942008-06-04 11:35:26 +000078#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
79# define PyInt Py_ssize_t
80# define PyInquiry lenfunc
81# define PyIntArgFunc ssizeargfunc
82# define PyIntIntArgFunc ssizessizeargfunc
83# define PyIntObjArgProc ssizeobjargproc
84# define PyIntIntObjArgProc ssizessizeobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000085# define Py_ssize_t_fmt "n"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000086#else
87# define PyInt int
88# define PyInquiry inquiry
89# define PyIntArgFunc intargfunc
90# define PyIntIntArgFunc intintargfunc
91# define PyIntObjArgProc intobjargproc
92# define PyIntIntObjArgProc intintobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000093# define Py_ssize_t_fmt "i"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000094#endif
95
Bram Moolenaar071d4272004-06-13 20:20:40 +000096/* Parser flags */
97#define single_input 256
98#define file_input 257
99#define eval_input 258
100
101#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
102 /* Python 2.3: can invoke ":python" recursively. */
103# define PY_CAN_RECURSE
104#endif
105
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200106# if defined(DYNAMIC_PYTHON) || defined(PROTO)
107# ifndef DYNAMIC_PYTHON
108# define HINSTANCE long_u /* for generating prototypes */
109# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000110
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200111# ifndef WIN3264
112# include <dlfcn.h>
113# define FARPROC void*
114# define HINSTANCE void*
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100115# if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200116# define load_dll(n) dlopen((n), RTLD_LAZY)
117# else
118# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
119# endif
120# define close_dll dlclose
121# define symbol_from_dll dlsym
122# else
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200123# define load_dll vimLoadLib
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200124# define close_dll FreeLibrary
125# define symbol_from_dll GetProcAddress
126# endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200127
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000128/* This makes if_python.c compile without warnings against Python 2.5
129 * on Win32 and Win64. */
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200130# undef PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200131# undef PyRun_String
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200132# undef PyArg_Parse
133# undef PyArg_ParseTuple
134# undef Py_BuildValue
135# undef Py_InitModule4
136# undef Py_InitModule4_64
Bram Moolenaardb913952012-06-29 12:54:53 +0200137# undef PyObject_CallMethod
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000138
Bram Moolenaar071d4272004-06-13 20:20:40 +0000139/*
140 * Wrapper defines
141 */
142# define PyArg_Parse dll_PyArg_Parse
143# define PyArg_ParseTuple dll_PyArg_ParseTuple
Bram Moolenaar19e60942011-06-19 00:27:51 +0200144# define PyMem_Free dll_PyMem_Free
Bram Moolenaardb913952012-06-29 12:54:53 +0200145# define PyMem_Malloc dll_PyMem_Malloc
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146# define PyDict_SetItemString dll_PyDict_SetItemString
147# define PyErr_BadArgument dll_PyErr_BadArgument
148# define PyErr_Clear dll_PyErr_Clear
149# define PyErr_NoMemory dll_PyErr_NoMemory
150# define PyErr_Occurred dll_PyErr_Occurred
151# define PyErr_SetNone dll_PyErr_SetNone
152# define PyErr_SetString dll_PyErr_SetString
153# define PyEval_InitThreads dll_PyEval_InitThreads
154# define PyEval_RestoreThread dll_PyEval_RestoreThread
155# define PyEval_SaveThread dll_PyEval_SaveThread
156# ifdef PY_CAN_RECURSE
157# define PyGILState_Ensure dll_PyGILState_Ensure
158# define PyGILState_Release dll_PyGILState_Release
159# endif
160# define PyInt_AsLong dll_PyInt_AsLong
161# define PyInt_FromLong dll_PyInt_FromLong
Bram Moolenaardb913952012-06-29 12:54:53 +0200162# define PyLong_AsLong dll_PyLong_AsLong
163# define PyLong_FromLong dll_PyLong_FromLong
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164# define PyInt_Type (*dll_PyInt_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200165# define PyLong_Type (*dll_PyLong_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000167# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168# define PyList_New dll_PyList_New
169# define PyList_SetItem dll_PyList_SetItem
170# define PyList_Size dll_PyList_Size
171# define PyList_Type (*dll_PyList_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200172# define PySequence_Check dll_PySequence_Check
173# define PySequence_Size dll_PySequence_Size
174# define PySequence_GetItem dll_PySequence_GetItem
175# define PyTuple_Size dll_PyTuple_Size
176# define PyTuple_GetItem dll_PyTuple_GetItem
177# define PyTuple_Type (*dll_PyTuple_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000179# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180# define PyDict_GetItemString dll_PyDict_GetItemString
Bram Moolenaardb913952012-06-29 12:54:53 +0200181# define PyDict_Next dll_PyDict_Next
182# ifdef PyMapping_Items
183# define PY_NO_MAPPING_ITEMS
184# else
185# define PyMapping_Items dll_PyMapping_Items
186# endif
187# define PyObject_CallMethod dll_PyObject_CallMethod
188# define PyMapping_Check dll_PyMapping_Check
189# define PyIter_Next dll_PyIter_Next
Bram Moolenaar071d4272004-06-13 20:20:40 +0000190# define PyModule_GetDict dll_PyModule_GetDict
191# define PyRun_SimpleString dll_PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200192# define PyRun_String dll_PyRun_String
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193# define PyString_AsString dll_PyString_AsString
194# define PyString_FromString dll_PyString_FromString
195# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
196# define PyString_Size dll_PyString_Size
197# define PyString_Type (*dll_PyString_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200198# define PyUnicode_Type (*dll_PyUnicode_Type)
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200199# undef PyUnicode_AsEncodedString
200# define PyUnicode_AsEncodedString py_PyUnicode_AsEncodedString
Bram Moolenaardb913952012-06-29 12:54:53 +0200201# define PyFloat_AsDouble dll_PyFloat_AsDouble
202# define PyFloat_FromDouble dll_PyFloat_FromDouble
203# define PyFloat_Type (*dll_PyFloat_Type)
204# define PyImport_AddModule (*dll_PyImport_AddModule)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205# define PySys_SetObject dll_PySys_SetObject
206# define PySys_SetArgv dll_PySys_SetArgv
207# define PyType_Type (*dll_PyType_Type)
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100208# define PyType_Ready (*dll_PyType_Ready)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209# define Py_BuildValue dll_Py_BuildValue
210# define Py_FindMethod dll_Py_FindMethod
211# define Py_InitModule4 dll_Py_InitModule4
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100212# define Py_SetPythonHome dll_Py_SetPythonHome
Bram Moolenaar071d4272004-06-13 20:20:40 +0000213# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000214# define Py_Finalize dll_Py_Finalize
215# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216# define _PyObject_New dll__PyObject_New
Bram Moolenaardb913952012-06-29 12:54:53 +0200217# define _PyObject_NextNotImplemented (*dll__PyObject_NextNotImplemented)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218# define _Py_NoneStruct (*dll__Py_NoneStruct)
219# define PyObject_Init dll__PyObject_Init
Bram Moolenaardb913952012-06-29 12:54:53 +0200220# define PyObject_GetIter dll_PyObject_GetIter
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
222# define PyType_IsSubtype dll_PyType_IsSubtype
223# endif
224# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
225# define PyObject_Malloc dll_PyObject_Malloc
226# define PyObject_Free dll_PyObject_Free
227# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200228# ifdef PY_USE_CAPSULE
229# define PyCapsule_New dll_PyCapsule_New
230# define PyCapsule_GetPointer dll_PyCapsule_GetPointer
231# else
232# define PyCObject_FromVoidPtr dll_PyCObject_FromVoidPtr
233# define PyCObject_AsVoidPtr dll_PyCObject_AsVoidPtr
234# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000235
236/*
237 * Pointers for dynamic link
238 */
239static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
240static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200241static int(*dll_PyMem_Free)(void *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200242static void* (*dll_PyMem_Malloc)(size_t);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
244static int(*dll_PyErr_BadArgument)(void);
245static void(*dll_PyErr_Clear)(void);
246static PyObject*(*dll_PyErr_NoMemory)(void);
247static PyObject*(*dll_PyErr_Occurred)(void);
248static void(*dll_PyErr_SetNone)(PyObject *);
249static void(*dll_PyErr_SetString)(PyObject *, const char *);
250static void(*dll_PyEval_InitThreads)(void);
251static void(*dll_PyEval_RestoreThread)(PyThreadState *);
252static PyThreadState*(*dll_PyEval_SaveThread)(void);
253# ifdef PY_CAN_RECURSE
254static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
255static void (*dll_PyGILState_Release)(PyGILState_STATE);
Bram Moolenaardb913952012-06-29 12:54:53 +0200256# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257static long(*dll_PyInt_AsLong)(PyObject *);
258static PyObject*(*dll_PyInt_FromLong)(long);
Bram Moolenaardb913952012-06-29 12:54:53 +0200259static long(*dll_PyLong_AsLong)(PyObject *);
260static PyObject*(*dll_PyLong_FromLong)(long);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000261static PyTypeObject* dll_PyInt_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200262static PyTypeObject* dll_PyLong_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000263static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000264static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000265static PyObject*(*dll_PyList_New)(PyInt size);
266static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
267static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268static PyTypeObject* dll_PyList_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200269static int (*dll_PySequence_Check)(PyObject *);
270static PyInt(*dll_PySequence_Size)(PyObject *);
271static PyObject*(*dll_PySequence_GetItem)(PyObject *, PyInt);
272static PyInt(*dll_PyTuple_Size)(PyObject *);
273static PyObject*(*dll_PyTuple_GetItem)(PyObject *, PyInt);
274static PyTypeObject* dll_PyTuple_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000276static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200278static int (*dll_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
279# ifndef PY_NO_MAPPING_ITEMS
280static PyObject* (*dll_PyMapping_Items)(PyObject *);
281# endif
282static PyObject* (*dll_PyObject_CallMethod)(PyObject *, char *, PyObject *);
283static int (*dll_PyMapping_Check)(PyObject *);
284static PyObject* (*dll_PyIter_Next)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285static PyObject*(*dll_PyModule_GetDict)(PyObject *);
286static int(*dll_PyRun_SimpleString)(char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200287static PyObject *(*dll_PyRun_String)(char *, int, PyObject *, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288static char*(*dll_PyString_AsString)(PyObject *);
289static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000290static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
291static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292static PyTypeObject* dll_PyString_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200293static PyTypeObject* dll_PyUnicode_Type;
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200294static PyObject *(*py_PyUnicode_AsEncodedString)(PyObject *, char *, char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200295static double(*dll_PyFloat_AsDouble)(PyObject *);
296static PyObject*(*dll_PyFloat_FromDouble)(double);
297static PyTypeObject* dll_PyFloat_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298static int(*dll_PySys_SetObject)(char *, PyObject *);
299static int(*dll_PySys_SetArgv)(int, char **);
300static PyTypeObject* dll_PyType_Type;
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100301static int (*dll_PyType_Ready)(PyTypeObject *type);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000302static PyObject*(*dll_Py_BuildValue)(char *, ...);
303static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
304static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
Bram Moolenaardb913952012-06-29 12:54:53 +0200305static PyObject*(*dll_PyImport_AddModule)(char *);
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100306static void(*dll_Py_SetPythonHome)(char *home);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000308static void(*dll_Py_Finalize)(void);
309static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000310static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
311static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200312static PyObject* (*dll_PyObject_GetIter)(PyObject *);
313static iternextfunc dll__PyObject_NextNotImplemented;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314static PyObject* dll__Py_NoneStruct;
315# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
316static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
317# endif
318# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
319static void* (*dll_PyObject_Malloc)(size_t);
320static void (*dll_PyObject_Free)(void*);
321# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200322# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +0200323static PyObject* (*dll_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
324static void* (*dll_PyCapsule_GetPointer)(PyObject *, char *);
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200325# else
326static PyCObject* (*dll_PyCObject_FromVoidPtr)(void *cobj, void (*destr)(void *));
327static void* (*dll_PyCObject_AsVoidPtr)(PyCObject *);
328# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000329
330static HINSTANCE hinstPython = 0; /* Instance of python.dll */
331
332/* Imported exception objects */
333static PyObject *imp_PyExc_AttributeError;
334static PyObject *imp_PyExc_IndexError;
335static PyObject *imp_PyExc_KeyboardInterrupt;
336static PyObject *imp_PyExc_TypeError;
337static PyObject *imp_PyExc_ValueError;
338
339# define PyExc_AttributeError imp_PyExc_AttributeError
340# define PyExc_IndexError imp_PyExc_IndexError
341# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
342# define PyExc_TypeError imp_PyExc_TypeError
343# define PyExc_ValueError imp_PyExc_ValueError
344
345/*
346 * Table of name to function pointer of python.
347 */
348# define PYTHON_PROC FARPROC
349static struct
350{
351 char *name;
352 PYTHON_PROC *ptr;
353} python_funcname_table[] =
354{
355 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
356 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
Bram Moolenaar19e60942011-06-19 00:27:51 +0200357 {"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free},
Bram Moolenaardb913952012-06-29 12:54:53 +0200358 {"PyMem_Malloc", (PYTHON_PROC*)&dll_PyMem_Malloc},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
360 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
361 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
362 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
363 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
364 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
365 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
366 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
367 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
368 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
369# ifdef PY_CAN_RECURSE
370 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
371 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
372# endif
373 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
374 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
Bram Moolenaardb913952012-06-29 12:54:53 +0200375 {"PyLong_AsLong", (PYTHON_PROC*)&dll_PyLong_AsLong},
376 {"PyLong_FromLong", (PYTHON_PROC*)&dll_PyLong_FromLong},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000377 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200378 {"PyLong_Type", (PYTHON_PROC*)&dll_PyLong_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000380 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
382 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
383 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
384 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200385 {"PySequence_GetItem", (PYTHON_PROC*)&dll_PySequence_GetItem},
386 {"PySequence_Size", (PYTHON_PROC*)&dll_PySequence_Size},
387 {"PySequence_Check", (PYTHON_PROC*)&dll_PySequence_Check},
388 {"PyTuple_GetItem", (PYTHON_PROC*)&dll_PyTuple_GetItem},
389 {"PyTuple_Size", (PYTHON_PROC*)&dll_PyTuple_Size},
390 {"PyTuple_Type", (PYTHON_PROC*)&dll_PyTuple_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000391 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
392 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200393 {"PyDict_Next", (PYTHON_PROC*)&dll_PyDict_Next},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000394 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaardb913952012-06-29 12:54:53 +0200395# ifndef PY_NO_MAPPING_ITEMS
396 {"PyMapping_Items", (PYTHON_PROC*)&dll_PyMapping_Items},
397# endif
398 {"PyObject_CallMethod", (PYTHON_PROC*)&dll_PyObject_CallMethod},
399 {"PyMapping_Check", (PYTHON_PROC*)&dll_PyMapping_Check},
400 {"PyIter_Next", (PYTHON_PROC*)&dll_PyIter_Next},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
402 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200403 {"PyRun_String", (PYTHON_PROC*)&dll_PyRun_String},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
405 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
406 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
407 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
408 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200409 {"PyUnicode_Type", (PYTHON_PROC*)&dll_PyUnicode_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200410 {"PyFloat_Type", (PYTHON_PROC*)&dll_PyFloat_Type},
411 {"PyFloat_AsDouble", (PYTHON_PROC*)&dll_PyFloat_AsDouble},
412 {"PyFloat_FromDouble", (PYTHON_PROC*)&dll_PyFloat_FromDouble},
413 {"PyImport_AddModule", (PYTHON_PROC*)&dll_PyImport_AddModule},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
415 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
416 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100417 {"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
419 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200420# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000 \
421 && SIZEOF_SIZE_T != SIZEOF_INT
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000422 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
423# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000425# endif
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100426 {"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000428 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
429 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
431 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
Bram Moolenaardb913952012-06-29 12:54:53 +0200432 {"PyObject_GetIter", (PYTHON_PROC*)&dll_PyObject_GetIter},
433 {"_PyObject_NextNotImplemented", (PYTHON_PROC*)&dll__PyObject_NextNotImplemented},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
435# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
436 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
437# endif
438# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
439 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
440 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
441# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200442# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +0200443 {"PyCapsule_New", (PYTHON_PROC*)&dll_PyCapsule_New},
444 {"PyCapsule_GetPointer", (PYTHON_PROC*)&dll_PyCapsule_GetPointer},
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200445# else
446 {"PyCObject_FromVoidPtr", (PYTHON_PROC*)&dll_PyCObject_FromVoidPtr},
447 {"PyCObject_AsVoidPtr", (PYTHON_PROC*)&dll_PyCObject_AsVoidPtr},
448# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 {"", NULL},
450};
451
452/*
453 * Free python.dll
454 */
455 static void
456end_dynamic_python(void)
457{
458 if (hinstPython)
459 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200460 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 hinstPython = 0;
462 }
463}
464
465/*
466 * Load library and get all pointers.
467 * Parameter 'libname' provides name of DLL.
468 * Return OK or FAIL.
469 */
470 static int
471python_runtime_link_init(char *libname, int verbose)
472{
473 int i;
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200474 void *ucs_as_encoded_string;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100476#if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200477 /* Can't have Python and Python3 loaded at the same time.
478 * It cause a crash, because RTLD_GLOBAL is needed for
479 * standard C extension libraries of one or both python versions. */
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200480 if (python3_loaded())
481 {
Bram Moolenaar9dc93ae2011-08-28 16:00:19 +0200482 if (verbose)
483 EMSG(_("E836: This Vim cannot execute :python after using :py3"));
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200484 return FAIL;
485 }
486#endif
487
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488 if (hinstPython)
489 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200490 hinstPython = load_dll(libname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491 if (!hinstPython)
492 {
493 if (verbose)
494 EMSG2(_(e_loadlib), libname);
495 return FAIL;
496 }
497
498 for (i = 0; python_funcname_table[i].ptr; ++i)
499 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200500 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501 python_funcname_table[i].name)) == NULL)
502 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200503 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504 hinstPython = 0;
505 if (verbose)
506 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
507 return FAIL;
508 }
509 }
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200510
511 /* Load unicode functions separately as only the ucs2 or the ucs4 functions
512 * will be present in the library. */
513 ucs_as_encoded_string = symbol_from_dll(hinstPython,
514 "PyUnicodeUCS2_AsEncodedString");
515 if (ucs_as_encoded_string == NULL)
516 ucs_as_encoded_string = symbol_from_dll(hinstPython,
517 "PyUnicodeUCS4_AsEncodedString");
518 if (ucs_as_encoded_string != NULL)
519 py_PyUnicode_AsEncodedString = ucs_as_encoded_string;
520 else
521 {
522 close_dll(hinstPython);
523 hinstPython = 0;
524 if (verbose)
525 EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*");
526 return FAIL;
527 }
528
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529 return OK;
530}
531
532/*
533 * If python is enabled (there is installed python on Windows system) return
534 * TRUE, else FALSE.
535 */
536 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000537python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538{
539 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
540}
541
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200542/*
543 * Load the standard Python exceptions - don't import the symbols from the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 * DLL, as this can cause errors (importing data symbols is not reliable).
545 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546 static void
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200547get_exceptions(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000548{
549 PyObject *exmod = PyImport_ImportModule("exceptions");
550 PyObject *exdict = PyModule_GetDict(exmod);
551 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
552 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
553 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
554 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
555 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
556 Py_XINCREF(imp_PyExc_AttributeError);
557 Py_XINCREF(imp_PyExc_IndexError);
558 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
559 Py_XINCREF(imp_PyExc_TypeError);
560 Py_XINCREF(imp_PyExc_ValueError);
561 Py_XDECREF(exmod);
562}
563#endif /* DYNAMIC_PYTHON */
564
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200565static PyObject *BufferNew (buf_T *);
566static PyObject *WindowNew(win_T *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200567static PyObject *DictionaryNew(dict_T *);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200568static PyObject *LineToString(const char *);
569
570static PyTypeObject RangeType;
571
Bram Moolenaardb913952012-06-29 12:54:53 +0200572static int initialised = 0;
573#define PYINITIALISED initialised
574
575/* Add conversion from PyInt? */
576#define DICTKEY_GET(err) \
577 if (!PyString_Check(keyObject)) \
578 { \
579 PyErr_SetString(PyExc_TypeError, _("only string keys are allowed")); \
580 return err; \
581 } \
582 key = (char_u *) PyString_AsString(keyObject);
583#define DICTKEY_UNREF
584#define DICTKEY_DECL
585
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200586/*
587 * Include the code shared with if_python3.c
588 */
589#include "if_py_both.h"
590
591
Bram Moolenaar071d4272004-06-13 20:20:40 +0000592/******************************************************
593 * Internal function prototypes.
594 */
595
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000596static PyInt RangeStart;
597static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598
Bram Moolenaardb913952012-06-29 12:54:53 +0200599static PyObject *globals;
600
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601static void PythonIO_Flush(void);
602static int PythonIO_Init(void);
603static int PythonMod_Init(void);
604
605/* Utility functions for the vim/python interface
606 * ----------------------------------------------
607 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000609static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611
612/******************************************************
613 * 1. Python interpreter main program.
614 */
615
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
617typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000618#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000620#ifdef PY_CAN_RECURSE
621static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
622#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000623static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000624#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625
626/*
627 * Suspend a thread of the Python interpreter, other threads are allowed to
628 * run.
629 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000630 static void
631Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000633#ifdef PY_CAN_RECURSE
634 PyGILState_Release(pygilstate);
635#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000636 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000637#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638}
639
640/*
641 * Restore a thread of the Python interpreter, waits for other threads to
642 * block.
643 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000644 static void
645Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000647#ifdef PY_CAN_RECURSE
648 pygilstate = PyGILState_Ensure();
649#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650 PyEval_RestoreThread(saved_python_thread);
651 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000653}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654
Bram Moolenaar071d4272004-06-13 20:20:40 +0000655 void
656python_end()
657{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000658 static int recurse = 0;
659
660 /* If a crash occurs while doing this, don't try again. */
661 if (recurse != 0)
662 return;
663
664 ++recurse;
665
Bram Moolenaar071d4272004-06-13 20:20:40 +0000666#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000667 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000668 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000669 Python_RestoreThread(); /* enter python */
670 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000671 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000673#else
674 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000675 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000676 Python_RestoreThread(); /* enter python */
677 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000678 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000680
681 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682}
683
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200684#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
685 int
686python_loaded()
687{
688 return (hinstPython != 0);
689}
690#endif
691
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 static int
693Python_Init(void)
694{
695 if (!initialised)
696 {
697#ifdef DYNAMIC_PYTHON
698 if (!python_enabled(TRUE))
699 {
700 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
701 goto fail;
702 }
703#endif
704
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100705#ifdef PYTHON_HOME
706 Py_SetPythonHome(PYTHON_HOME);
707#endif
708
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200709 init_structs();
710
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711#if !defined(MACOS) || defined(MACOS_X_UNIX)
712 Py_Initialize();
713#else
714 PyMac_Initialize();
715#endif
716 /* initialise threads */
717 PyEval_InitThreads();
718
719#ifdef DYNAMIC_PYTHON
720 get_exceptions();
721#endif
722
723 if (PythonIO_Init())
724 goto fail;
725
726 if (PythonMod_Init())
727 goto fail;
728
Bram Moolenaardb913952012-06-29 12:54:53 +0200729 globals = PyModule_GetDict(PyImport_AddModule("__main__"));
730
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000731 /* Remove the element from sys.path that was added because of our
732 * argv[0] value in PythonMod_Init(). Previously we used an empty
733 * string, but dependinding on the OS we then get an empty entry or
734 * the current directory in sys.path. */
735 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
736
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000737 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739
740 initialised = 1;
741 }
742
743 return 0;
744
745fail:
746 /* We call PythonIO_Flush() here to print any Python errors.
747 * This is OK, as it is possible to call this function even
748 * if PythonIO_Init() has not completed successfully (it will
749 * not do anything in this case).
750 */
751 PythonIO_Flush();
752 return -1;
753}
754
755/*
756 * External interface
757 */
758 static void
Bram Moolenaardb913952012-06-29 12:54:53 +0200759DoPythonCommand(exarg_T *eap, const char *cmd, typval_T *rettv)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000761#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000762 static int recursive = 0;
763#endif
764#if defined(MACOS) && !defined(MACOS_X_UNIX)
765 GrafPtr oldPort;
766#endif
767#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
768 char *saved_locale;
769#endif
770
771#ifndef PY_CAN_RECURSE
772 if (recursive)
773 {
774 EMSG(_("E659: Cannot invoke Python recursively"));
775 return;
776 }
777 ++recursive;
778#endif
779
780#if defined(MACOS) && !defined(MACOS_X_UNIX)
781 GetPort(&oldPort);
782 /* Check if the Python library is available */
783 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
784 goto theend;
785#endif
786 if (Python_Init())
787 goto theend;
788
Bram Moolenaardb913952012-06-29 12:54:53 +0200789 if (rettv == NULL)
790 {
791 RangeStart = eap->line1;
792 RangeEnd = eap->line2;
793 }
794 else
795 {
796 RangeStart = (PyInt) curwin->w_cursor.lnum;
797 RangeEnd = RangeStart;
798 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 Python_Release_Vim(); /* leave vim */
800
801#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
802 /* Python only works properly when the LC_NUMERIC locale is "C". */
803 saved_locale = setlocale(LC_NUMERIC, NULL);
804 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
805 saved_locale = NULL;
806 else
807 {
808 /* Need to make a copy, value may change when setting new locale. */
809 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
810 (void)setlocale(LC_NUMERIC, "C");
811 }
812#endif
813
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815
Bram Moolenaardb913952012-06-29 12:54:53 +0200816 if (rettv == NULL)
817 PyRun_SimpleString((char *)(cmd));
818 else
819 {
820 PyObject *r;
821
822 r = PyRun_String((char *)(cmd), Py_eval_input, globals, globals);
823 if (r == NULL)
824 EMSG(_("E858: Eval did not return a valid python object"));
825 else
826 {
827 if (ConvertFromPyObject(r, rettv) == -1)
828 EMSG(_("E859: Failed to convert returned python object to vim value"));
829 Py_DECREF(r);
830 }
831 PyErr_Clear();
832 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835
836#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
837 if (saved_locale != NULL)
838 {
839 (void)setlocale(LC_NUMERIC, saved_locale);
840 vim_free(saved_locale);
841 }
842#endif
843
844 Python_Lock_Vim(); /* enter vim */
845 PythonIO_Flush();
846#if defined(MACOS) && !defined(MACOS_X_UNIX)
847 SetPort(oldPort);
848#endif
849
850theend:
851#ifndef PY_CAN_RECURSE
852 --recursive;
853#endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200854 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855}
856
857/*
858 * ":python"
859 */
860 void
861ex_python(exarg_T *eap)
862{
863 char_u *script;
864
865 script = script_get(eap, eap->arg);
866 if (!eap->skip)
867 {
868 if (script == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200869 DoPythonCommand(eap, (char *)eap->arg, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000870 else
Bram Moolenaardb913952012-06-29 12:54:53 +0200871 DoPythonCommand(eap, (char *)script, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872 }
873 vim_free(script);
874}
875
876#define BUFFER_SIZE 1024
877
878/*
879 * ":pyfile"
880 */
881 void
882ex_pyfile(exarg_T *eap)
883{
884 static char buffer[BUFFER_SIZE];
885 const char *file = (char *)eap->arg;
886 char *p;
887
888 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
889 * stdio file pointer, but Vim and the Python DLL are compiled with
890 * different options under Windows, meaning that stdio pointers aren't
891 * compatible between the two. Yuk.
892 *
893 * Put the string "execfile('file')" into buffer. But, we need to
894 * escape any backslashes or single quotes in the file name, so that
895 * Python won't mangle the file name.
896 */
897 strcpy(buffer, "execfile('");
898 p = buffer + 10; /* size of "execfile('" */
899
900 while (*file && p < buffer + (BUFFER_SIZE - 3))
901 {
902 if (*file == '\\' || *file == '\'')
903 *p++ = '\\';
904 *p++ = *file++;
905 }
906
907 /* If we didn't finish the file name, we hit a buffer overflow */
908 if (*file != '\0')
909 return;
910
911 /* Put in the terminating "')" and a null */
912 *p++ = '\'';
913 *p++ = ')';
914 *p++ = '\0';
915
916 /* Execute the file */
Bram Moolenaardb913952012-06-29 12:54:53 +0200917 DoPythonCommand(eap, buffer, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918}
919
920/******************************************************
921 * 2. Python output stream: writes output via [e]msg().
922 */
923
924/* Implementation functions
925 */
926
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927 static PyObject *
928OutputGetattr(PyObject *self, char *name)
929{
930 if (strcmp(name, "softspace") == 0)
931 return PyInt_FromLong(((OutputObject *)(self))->softspace);
932
933 return Py_FindMethod(OutputMethods, self, name);
934}
935
936 static int
937OutputSetattr(PyObject *self, char *name, PyObject *val)
938{
Bram Moolenaardb913952012-06-29 12:54:53 +0200939 if (val == NULL)
940 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
942 return -1;
943 }
944
945 if (strcmp(name, "softspace") == 0)
946 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200947 if (!PyInt_Check(val))
948 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
950 return -1;
951 }
952
953 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
954 return 0;
955 }
956
957 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
958 return -1;
959}
960
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961/***************/
962
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 static int
964PythonIO_Init(void)
965{
966 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +0100967 PyType_Ready(&OutputType);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200969 return PythonIO_Init_io();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970}
971
972/******************************************************
973 * 3. Implementation of the Vim module for Python
974 */
975
Bram Moolenaardb913952012-06-29 12:54:53 +0200976static PyObject *ConvertToPyObject(typval_T *);
977static int ConvertFromPyObject(PyObject *, typval_T *);
978
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979/* Window type - Implementation functions
980 * --------------------------------------
981 */
982
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
984
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985static void WindowDestructor(PyObject *);
986static PyObject *WindowGetattr(PyObject *, char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
988/* Buffer type - Implementation functions
989 * --------------------------------------
990 */
991
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
993
Bram Moolenaar071d4272004-06-13 20:20:40 +0000994static void BufferDestructor(PyObject *);
995static PyObject *BufferGetattr(PyObject *, char *);
996static PyObject *BufferRepr(PyObject *);
997
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000998static PyInt BufferLength(PyObject *);
999static PyObject *BufferItem(PyObject *, PyInt);
1000static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1001static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1002static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003
Bram Moolenaar071d4272004-06-13 20:20:40 +00001004/* Line range type - Implementation functions
1005 * --------------------------------------
1006 */
1007
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1009
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001010static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1011static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013/* Current objects type - Implementation functions
1014 * -----------------------------------------------
1015 */
1016
1017static PyObject *CurrentGetattr(PyObject *, char *);
1018static int CurrentSetattr(PyObject *, char *, PyObject *);
1019
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001021 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001023 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1024 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1025 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1026 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1027 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028};
1029
1030static PyTypeObject BufferType = {
1031 PyObject_HEAD_INIT(0)
1032 0,
1033 "buffer",
1034 sizeof(BufferObject),
1035 0,
1036
1037 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1038 (printfunc) 0, /* tp_print, print x */
1039 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1040 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1041 (cmpfunc) 0, /* tp_compare, x>y */
1042 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1043
1044 0, /* as number */
1045 &BufferAsSeq, /* as sequence */
1046 0, /* as mapping */
1047
1048 (hashfunc) 0, /* tp_hash, dict(x) */
1049 (ternaryfunc) 0, /* tp_call, x() */
1050 (reprfunc) 0, /* tp_str, str(x) */
1051};
1052
1053/* Buffer object - Implementation
1054 */
1055
1056 static PyObject *
1057BufferNew(buf_T *buf)
1058{
1059 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001060 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 * then we can get at it in buf_freeall() in vim. We then
1062 * need to create only ONE Python object per buffer - if
1063 * we try to create a second, just INCREF the existing one
1064 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001065 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066 * Question: what to do on a buf_freeall(). We'll probably
1067 * have to either delete the Python object (DECREF it to
1068 * zero - a bad idea, as it leaves dangling refs!) or
1069 * set the buf_T * value to an invalid value (-1?), which
1070 * means we need checks in all access functions... Bah.
1071 */
1072
1073 BufferObject *self;
1074
Bram Moolenaare344bea2005-09-01 20:46:49 +00001075 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001077 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078 Py_INCREF(self);
1079 }
1080 else
1081 {
1082 self = PyObject_NEW(BufferObject, &BufferType);
1083 if (self == NULL)
1084 return NULL;
1085 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001086 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 }
1088
1089 return (PyObject *)(self);
1090}
1091
1092 static void
1093BufferDestructor(PyObject *self)
1094{
1095 BufferObject *this = (BufferObject *)(self);
1096
1097 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001098 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099
Bram Moolenaar658ada62006-10-03 13:02:36 +00001100 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101}
1102
1103 static PyObject *
1104BufferGetattr(PyObject *self, char *name)
1105{
1106 BufferObject *this = (BufferObject *)(self);
1107
1108 if (CheckBuffer(this))
1109 return NULL;
1110
1111 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001112 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001114 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115 else if (strcmp(name,"__members__") == 0)
1116 return Py_BuildValue("[ss]", "name", "number");
1117 else
1118 return Py_FindMethod(BufferMethods, self, name);
1119}
1120
1121 static PyObject *
1122BufferRepr(PyObject *self)
1123{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001124 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 BufferObject *this = (BufferObject *)(self);
1126
1127 if (this->buf == INVALID_BUFFER_VALUE)
1128 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001129 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130 return PyString_FromString(repr);
1131 }
1132 else
1133 {
1134 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001135 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136
1137 if (name == NULL)
1138 name = "";
1139 len = strlen(name);
1140
1141 if (len > 35)
1142 name = name + (35 - len);
1143
Bram Moolenaar555b2802005-05-19 21:08:39 +00001144 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145
1146 return PyString_FromString(repr);
1147 }
1148}
1149
1150/******************/
1151
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001152 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153BufferLength(PyObject *self)
1154{
1155 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1156 if (CheckBuffer((BufferObject *)(self)))
1157 return -1; /* ??? */
1158
1159 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1160}
1161
1162 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001163BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164{
1165 return RBItem((BufferObject *)(self), n, 1,
1166 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1167}
1168
1169 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001170BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171{
1172 return RBSlice((BufferObject *)(self), lo, hi, 1,
1173 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1174}
1175
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001176 static PyInt
1177BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001179 return RBAsItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001180 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181 NULL);
1182}
1183
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001184 static PyInt
1185BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001187 return RBAsSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001188 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189 NULL);
1190}
1191
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001193 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001195 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1196 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1197 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1198 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1199 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200};
1201
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202/* Line range object - Implementation
1203 */
1204
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205 static void
1206RangeDestructor(PyObject *self)
1207{
1208 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001209 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210}
1211
1212 static PyObject *
1213RangeGetattr(PyObject *self, char *name)
1214{
1215 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001216 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001217 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001218 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219 else
1220 return Py_FindMethod(RangeMethods, self, name);
1221}
1222
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223/****************/
1224
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001225 static PyInt
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001226RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001228 return RBAsItem(((RangeObject *)(self))->buf, n, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 ((RangeObject *)(self))->start,
1230 ((RangeObject *)(self))->end,
1231 &((RangeObject *)(self))->end);
1232}
1233
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001234 static PyInt
1235RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001237 return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 ((RangeObject *)(self))->start,
1239 ((RangeObject *)(self))->end,
1240 &((RangeObject *)(self))->end);
1241}
1242
Bram Moolenaar071d4272004-06-13 20:20:40 +00001243/* Buffer list object - Definitions
1244 */
1245
1246typedef struct
1247{
1248 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001249} BufListObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250
1251static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001252 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001254 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1255 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1256 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1257 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1258 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259};
1260
1261static PyTypeObject BufListType = {
1262 PyObject_HEAD_INIT(0)
1263 0,
1264 "buffer list",
1265 sizeof(BufListObject),
1266 0,
1267
1268 (destructor) 0, /* tp_dealloc, refcount==0 */
1269 (printfunc) 0, /* tp_print, print x */
1270 (getattrfunc) 0, /* tp_getattr, x.attr */
1271 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1272 (cmpfunc) 0, /* tp_compare, x>y */
1273 (reprfunc) 0, /* tp_repr, `x`, print x */
1274
1275 0, /* as number */
1276 &BufListAsSeq, /* as sequence */
1277 0, /* as mapping */
1278
1279 (hashfunc) 0, /* tp_hash, dict(x) */
1280 (ternaryfunc) 0, /* tp_call, x() */
1281 (reprfunc) 0, /* tp_str, str(x) */
1282};
1283
Bram Moolenaar071d4272004-06-13 20:20:40 +00001284/* Window object - Definitions
1285 */
1286
1287static struct PyMethodDef WindowMethods[] = {
1288 /* name, function, calling, documentation */
1289 { NULL, NULL, 0, NULL }
1290};
1291
1292static PyTypeObject WindowType = {
1293 PyObject_HEAD_INIT(0)
1294 0,
1295 "window",
1296 sizeof(WindowObject),
1297 0,
1298
1299 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1300 (printfunc) 0, /* tp_print, print x */
1301 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1302 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1303 (cmpfunc) 0, /* tp_compare, x>y */
1304 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1305
1306 0, /* as number */
1307 0, /* as sequence */
1308 0, /* as mapping */
1309
1310 (hashfunc) 0, /* tp_hash, dict(x) */
1311 (ternaryfunc) 0, /* tp_call, x() */
1312 (reprfunc) 0, /* tp_str, str(x) */
1313};
1314
1315/* Window object - Implementation
1316 */
1317
1318 static PyObject *
1319WindowNew(win_T *win)
1320{
1321 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001322 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323 * then we can get at it in win_free() in vim. We then
1324 * need to create only ONE Python object per window - if
1325 * we try to create a second, just INCREF the existing one
1326 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001327 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328 * On a win_free() we set the Python object's win_T* field
1329 * to an invalid value. We trap all uses of a window
1330 * object, and reject them if the win_T* field is invalid.
1331 */
1332
1333 WindowObject *self;
1334
Bram Moolenaare344bea2005-09-01 20:46:49 +00001335 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001337 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001338 Py_INCREF(self);
1339 }
1340 else
1341 {
1342 self = PyObject_NEW(WindowObject, &WindowType);
1343 if (self == NULL)
1344 return NULL;
1345 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001346 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001347 }
1348
1349 return (PyObject *)(self);
1350}
1351
1352 static void
1353WindowDestructor(PyObject *self)
1354{
1355 WindowObject *this = (WindowObject *)(self);
1356
1357 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001358 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359
Bram Moolenaar658ada62006-10-03 13:02:36 +00001360 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361}
1362
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363 static PyObject *
1364WindowGetattr(PyObject *self, char *name)
1365{
1366 WindowObject *this = (WindowObject *)(self);
1367
1368 if (CheckWindow(this))
1369 return NULL;
1370
1371 if (strcmp(name, "buffer") == 0)
1372 return (PyObject *)BufferNew(this->win->w_buffer);
1373 else if (strcmp(name, "cursor") == 0)
1374 {
1375 pos_T *pos = &this->win->w_cursor;
1376
1377 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1378 }
1379 else if (strcmp(name, "height") == 0)
1380 return Py_BuildValue("l", (long)(this->win->w_height));
1381#ifdef FEAT_VERTSPLIT
1382 else if (strcmp(name, "width") == 0)
1383 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1384#endif
1385 else if (strcmp(name,"__members__") == 0)
1386 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1387 else
1388 return Py_FindMethod(WindowMethods, self, name);
1389}
1390
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391/* Window list object - Definitions
1392 */
1393
1394typedef struct
1395{
1396 PyObject_HEAD
1397}
1398WinListObject;
1399
1400static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001401 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001403 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1404 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
1405 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1406 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1407 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408};
1409
1410static PyTypeObject WinListType = {
1411 PyObject_HEAD_INIT(0)
1412 0,
1413 "window list",
1414 sizeof(WinListObject),
1415 0,
1416
1417 (destructor) 0, /* tp_dealloc, refcount==0 */
1418 (printfunc) 0, /* tp_print, print x */
1419 (getattrfunc) 0, /* tp_getattr, x.attr */
1420 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1421 (cmpfunc) 0, /* tp_compare, x>y */
1422 (reprfunc) 0, /* tp_repr, `x`, print x */
1423
1424 0, /* as number */
1425 &WinListAsSeq, /* as sequence */
1426 0, /* as mapping */
1427
1428 (hashfunc) 0, /* tp_hash, dict(x) */
1429 (ternaryfunc) 0, /* tp_call, x() */
1430 (reprfunc) 0, /* tp_str, str(x) */
1431};
1432
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433/* Current items object - Definitions
1434 */
1435
1436typedef struct
1437{
1438 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001439} CurrentObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441static PyTypeObject CurrentType = {
1442 PyObject_HEAD_INIT(0)
1443 0,
1444 "current data",
1445 sizeof(CurrentObject),
1446 0,
1447
1448 (destructor) 0, /* tp_dealloc, refcount==0 */
1449 (printfunc) 0, /* tp_print, print x */
1450 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
1451 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
1452 (cmpfunc) 0, /* tp_compare, x>y */
1453 (reprfunc) 0, /* tp_repr, `x`, print x */
1454
1455 0, /* as number */
1456 0, /* as sequence */
1457 0, /* as mapping */
1458
1459 (hashfunc) 0, /* tp_hash, dict(x) */
1460 (ternaryfunc) 0, /* tp_call, x() */
1461 (reprfunc) 0, /* tp_str, str(x) */
1462};
1463
1464/* Current items object - Implementation
1465 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001467CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468{
1469 if (strcmp(name, "buffer") == 0)
1470 return (PyObject *)BufferNew(curbuf);
1471 else if (strcmp(name, "window") == 0)
1472 return (PyObject *)WindowNew(curwin);
1473 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001474 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475 else if (strcmp(name, "range") == 0)
1476 return RangeNew(curbuf, RangeStart, RangeEnd);
1477 else if (strcmp(name,"__members__") == 0)
1478 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
1479 else
1480 {
1481 PyErr_SetString(PyExc_AttributeError, name);
1482 return NULL;
1483 }
1484}
1485
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001487CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488{
1489 if (strcmp(name, "line") == 0)
1490 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001491 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 return -1;
1493
1494 return 0;
1495 }
1496 else
1497 {
1498 PyErr_SetString(PyExc_AttributeError, name);
1499 return -1;
1500 }
1501}
1502
1503/* External interface
1504 */
1505
1506 void
1507python_buffer_free(buf_T *buf)
1508{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001509 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001511 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001513 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514 }
1515}
1516
1517#if defined(FEAT_WINDOWS) || defined(PROTO)
1518 void
1519python_window_free(win_T *win)
1520{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001521 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001522 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001523 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001524 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001525 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 }
1527}
1528#endif
1529
1530static BufListObject TheBufferList =
1531{
1532 PyObject_HEAD_INIT(&BufListType)
1533};
1534
1535static WinListObject TheWindowList =
1536{
1537 PyObject_HEAD_INIT(&WinListType)
1538};
1539
1540static CurrentObject TheCurrent =
1541{
1542 PyObject_HEAD_INIT(&CurrentType)
1543};
1544
1545 static int
1546PythonMod_Init(void)
1547{
1548 PyObject *mod;
1549 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00001550 /* The special value is removed from sys.path in Python_Init(). */
1551 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552
1553 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +01001554 PyType_Ready(&BufferType);
1555 PyType_Ready(&RangeType);
1556 PyType_Ready(&WindowType);
1557 PyType_Ready(&BufListType);
1558 PyType_Ready(&WinListType);
1559 PyType_Ready(&CurrentType);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560
1561 /* Set sys.argv[] to avoid a crash in warn(). */
1562 PySys_SetArgv(1, argv);
1563
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001564 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 dict = PyModule_GetDict(mod);
1566
1567 VimError = Py_BuildValue("s", "vim.error");
1568
1569 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00001570 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
1571 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
1572 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573
1574 if (PyErr_Occurred())
1575 return -1;
1576
1577 return 0;
1578}
1579
1580/*************************************************************************
1581 * 4. Utility functions for handling the interface between Vim and Python.
1582 */
1583
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584/* Convert a Vim line into a Python string.
1585 * All internal newlines are replaced by null characters.
1586 *
1587 * On errors, the Python exception data is set, and NULL is returned.
1588 */
1589 static PyObject *
1590LineToString(const char *str)
1591{
1592 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001593 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 char *p;
1595
1596 /* Allocate an Python string object, with uninitialised contents. We
1597 * must do it this way, so that we can modify the string in place
1598 * later. See the Python source, Objects/stringobject.c for details.
1599 */
1600 result = PyString_FromStringAndSize(NULL, len);
1601 if (result == NULL)
1602 return NULL;
1603
1604 p = PyString_AsString(result);
1605
1606 while (*str)
1607 {
1608 if (*str == '\n')
1609 *p = '\0';
1610 else
1611 *p = *str;
1612
1613 ++p;
1614 ++str;
1615 }
1616
1617 return result;
1618}
1619
Bram Moolenaardb913952012-06-29 12:54:53 +02001620static void DictionaryDestructor(PyObject *);
1621static PyObject *DictionaryGetattr(PyObject *, char*);
1622
1623static PyMappingMethods DictionaryAsMapping = {
1624 (PyInquiry) DictionaryLength,
1625 (binaryfunc) DictionaryItem,
1626 (objobjargproc) DictionaryAssItem,
1627};
1628
1629static PyTypeObject DictionaryType = {
1630 PyObject_HEAD_INIT(0)
1631 0,
1632 "vimdictionary",
1633 sizeof(DictionaryObject),
1634 0,
1635
1636 (destructor) DictionaryDestructor,
1637 (printfunc) 0,
1638 (getattrfunc) DictionaryGetattr,
1639 (setattrfunc) 0,
1640 (cmpfunc) 0,
1641 (reprfunc) 0,
1642
1643 0, /* as number */
1644 0, /* as sequence */
1645 &DictionaryAsMapping, /* as mapping */
1646
1647 (hashfunc) 0,
1648 (ternaryfunc) 0,
1649 (reprfunc) 0,
1650};
1651
1652 static void
1653DictionaryDestructor(PyObject *self)
1654{
1655 DictionaryObject *this = ((DictionaryObject *) (self));
1656
1657 pyll_remove(&this->ref, &lastdict);
1658 dict_unref(this->dict);
1659
1660 Py_DECREF(self);
1661}
1662
1663 static PyObject *
1664DictionaryGetattr(PyObject *self, char *name)
1665{
1666 return Py_FindMethod(DictionaryMethods, self, name);
1667}
1668
1669static void ListDestructor(PyObject *);
1670static PyObject *ListGetattr(PyObject *, char *);
1671
1672static PySequenceMethods ListAsSeq = {
1673 (PyInquiry) ListLength,
1674 (binaryfunc) 0,
1675 (PyIntArgFunc) 0,
1676 (PyIntArgFunc) ListItem,
1677 (PyIntIntArgFunc) ListSlice,
1678 (PyIntObjArgProc) ListAssItem,
1679 (PyIntIntObjArgProc) ListAssSlice,
1680 (objobjproc) 0,
1681#if PY_MAJOR_VERSION >= 2
1682 (binaryfunc) ListConcatInPlace,
1683 0,
1684#endif
1685};
1686
1687static PyTypeObject ListType = {
1688 PyObject_HEAD_INIT(0)
1689 0,
1690 "vimlist",
1691 sizeof(ListObject),
1692 0,
1693
1694 (destructor) ListDestructor,
1695 (printfunc) 0,
1696 (getattrfunc) ListGetattr,
1697 (setattrfunc) 0,
1698 (cmpfunc) 0,
1699 (reprfunc) 0,
1700
1701 0, /* as number */
1702 &ListAsSeq, /* as sequence */
1703 0, /* as mapping */
1704
1705 (hashfunc) 0,
1706 (ternaryfunc) 0,
1707 (reprfunc) 0,
1708};
1709
1710 static void
1711ListDestructor(PyObject *self)
1712{
1713 ListObject *this = ((ListObject *) (self));
1714
1715 pyll_remove(&this->ref, &lastlist);
1716 list_unref(this->list);
1717
1718 Py_DECREF(self);
1719}
1720
1721 static PyObject *
1722ListGetattr(PyObject *self, char *name)
1723{
1724 return Py_FindMethod(ListMethods, self, name);
1725}
1726
1727static void FunctionDestructor(PyObject *);
1728static PyObject *FunctionGetattr(PyObject *, char *);
1729
1730static PyTypeObject FunctionType = {
1731 PyObject_HEAD_INIT(0)
1732 0,
1733 "vimfunction",
1734 sizeof(FunctionObject),
1735 0,
1736
1737 (destructor) FunctionDestructor,
1738 (printfunc) 0,
1739 (getattrfunc) FunctionGetattr,
1740 (setattrfunc) 0,
1741 (cmpfunc) 0,
1742 (reprfunc) 0,
1743
1744 0, /* as number */
1745 0, /* as sequence */
1746 0, /* as mapping */
1747
1748 (hashfunc) 0,
1749 (ternaryfunc) FunctionCall,
1750 (reprfunc) 0,
1751};
1752
1753 static void
1754FunctionDestructor(PyObject *self)
1755{
1756 FunctionObject *this = (FunctionObject *) (self);
1757
1758 func_unref(this->name);
1759 PyMem_Del(this->name);
1760
1761 Py_DECREF(self);
1762}
1763
1764 static PyObject *
1765FunctionGetattr(PyObject *self, char *name)
1766{
1767 FunctionObject *this = (FunctionObject *)(self);
1768
1769 if (strcmp(name, "name") == 0)
1770 return PyString_FromString((char *)(this->name));
1771 else
1772 return Py_FindMethod(FunctionMethods, self, name);
1773}
1774
1775 void
1776do_pyeval (char_u *str, typval_T *rettv)
1777{
1778 DoPythonCommand(NULL, (char *) str, rettv);
1779 switch(rettv->v_type)
1780 {
1781 case VAR_DICT: ++rettv->vval.v_dict->dv_refcount; break;
1782 case VAR_LIST: ++rettv->vval.v_list->lv_refcount; break;
1783 case VAR_FUNC: func_ref(rettv->vval.v_string); break;
1784 }
1785}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
1787/* Don't generate a prototype for the next function, it generates an error on
1788 * newer Python versions. */
1789#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
1790
1791 char *
1792Py_GetProgramName(void)
1793{
1794 return "vim";
1795}
1796#endif /* Python 1.4 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001797
Bram Moolenaardb913952012-06-29 12:54:53 +02001798 void
1799set_ref_in_python (int copyID)
1800{
1801 set_ref_in_py(copyID);
1802}
1803
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001804 static void
1805init_structs(void)
1806{
1807 vim_memset(&OutputType, 0, sizeof(OutputType));
1808 OutputType.tp_name = "message";
1809 OutputType.tp_basicsize = sizeof(OutputObject);
1810 OutputType.tp_getattr = OutputGetattr;
1811 OutputType.tp_setattr = OutputSetattr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001812
1813 vim_memset(&RangeType, 0, sizeof(RangeType));
1814 RangeType.tp_name = "range";
1815 RangeType.tp_basicsize = sizeof(RangeObject);
1816 RangeType.tp_dealloc = RangeDestructor;
1817 RangeType.tp_getattr = RangeGetattr;
1818 RangeType.tp_repr = RangeRepr;
1819 RangeType.tp_as_sequence = &RangeAsSeq;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001820}