blob: 0667b5eaa83dd4b44e271af529b4cb0b0453afb6 [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)
199# define PyUnicodeUCS4_AsEncodedString (*dll_PyUnicodeUCS4_AsEncodedString)
200# define PyFloat_AsDouble dll_PyFloat_AsDouble
201# define PyFloat_FromDouble dll_PyFloat_FromDouble
202# define PyFloat_Type (*dll_PyFloat_Type)
203# define PyImport_AddModule (*dll_PyImport_AddModule)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204# define PySys_SetObject dll_PySys_SetObject
205# define PySys_SetArgv dll_PySys_SetArgv
206# define PyType_Type (*dll_PyType_Type)
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100207# define PyType_Ready (*dll_PyType_Ready)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208# define Py_BuildValue dll_Py_BuildValue
209# define Py_FindMethod dll_Py_FindMethod
210# define Py_InitModule4 dll_Py_InitModule4
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100211# define Py_SetPythonHome dll_Py_SetPythonHome
Bram Moolenaar071d4272004-06-13 20:20:40 +0000212# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000213# define Py_Finalize dll_Py_Finalize
214# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215# define _PyObject_New dll__PyObject_New
Bram Moolenaardb913952012-06-29 12:54:53 +0200216# define _PyObject_NextNotImplemented (*dll__PyObject_NextNotImplemented)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217# define _Py_NoneStruct (*dll__Py_NoneStruct)
218# define PyObject_Init dll__PyObject_Init
Bram Moolenaardb913952012-06-29 12:54:53 +0200219# define PyObject_GetIter dll_PyObject_GetIter
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
221# define PyType_IsSubtype dll_PyType_IsSubtype
222# endif
223# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
224# define PyObject_Malloc dll_PyObject_Malloc
225# define PyObject_Free dll_PyObject_Free
226# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200227# ifdef PY_USE_CAPSULE
228# define PyCapsule_New dll_PyCapsule_New
229# define PyCapsule_GetPointer dll_PyCapsule_GetPointer
230# else
231# define PyCObject_FromVoidPtr dll_PyCObject_FromVoidPtr
232# define PyCObject_AsVoidPtr dll_PyCObject_AsVoidPtr
233# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234
235/*
236 * Pointers for dynamic link
237 */
238static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
239static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200240static int(*dll_PyMem_Free)(void *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200241static void* (*dll_PyMem_Malloc)(size_t);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000242static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
243static int(*dll_PyErr_BadArgument)(void);
244static void(*dll_PyErr_Clear)(void);
245static PyObject*(*dll_PyErr_NoMemory)(void);
246static PyObject*(*dll_PyErr_Occurred)(void);
247static void(*dll_PyErr_SetNone)(PyObject *);
248static void(*dll_PyErr_SetString)(PyObject *, const char *);
249static void(*dll_PyEval_InitThreads)(void);
250static void(*dll_PyEval_RestoreThread)(PyThreadState *);
251static PyThreadState*(*dll_PyEval_SaveThread)(void);
252# ifdef PY_CAN_RECURSE
253static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
254static void (*dll_PyGILState_Release)(PyGILState_STATE);
Bram Moolenaardb913952012-06-29 12:54:53 +0200255# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256static long(*dll_PyInt_AsLong)(PyObject *);
257static PyObject*(*dll_PyInt_FromLong)(long);
Bram Moolenaardb913952012-06-29 12:54:53 +0200258static long(*dll_PyLong_AsLong)(PyObject *);
259static PyObject*(*dll_PyLong_FromLong)(long);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260static PyTypeObject* dll_PyInt_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200261static PyTypeObject* dll_PyLong_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000262static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000263static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000264static PyObject*(*dll_PyList_New)(PyInt size);
265static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
266static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000267static PyTypeObject* dll_PyList_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200268static int (*dll_PySequence_Check)(PyObject *);
269static PyInt(*dll_PySequence_Size)(PyObject *);
270static PyObject*(*dll_PySequence_GetItem)(PyObject *, PyInt);
271static PyInt(*dll_PyTuple_Size)(PyObject *);
272static PyObject*(*dll_PyTuple_GetItem)(PyObject *, PyInt);
273static PyTypeObject* dll_PyTuple_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000275static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200277static int (*dll_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
278# ifndef PY_NO_MAPPING_ITEMS
279static PyObject* (*dll_PyMapping_Items)(PyObject *);
280# endif
281static PyObject* (*dll_PyObject_CallMethod)(PyObject *, char *, PyObject *);
282static int (*dll_PyMapping_Check)(PyObject *);
283static PyObject* (*dll_PyIter_Next)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284static PyObject*(*dll_PyModule_GetDict)(PyObject *);
285static int(*dll_PyRun_SimpleString)(char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200286static PyObject *(*dll_PyRun_String)(char *, int, PyObject *, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287static char*(*dll_PyString_AsString)(PyObject *);
288static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000289static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
290static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000291static PyTypeObject* dll_PyString_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200292static PyTypeObject* dll_PyUnicode_Type;
293static PyObject *(*PyUnicodeUCS4_AsEncodedString)(PyObject *, char *, char *);
294static double(*dll_PyFloat_AsDouble)(PyObject *);
295static PyObject*(*dll_PyFloat_FromDouble)(double);
296static PyTypeObject* dll_PyFloat_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297static int(*dll_PySys_SetObject)(char *, PyObject *);
298static int(*dll_PySys_SetArgv)(int, char **);
299static PyTypeObject* dll_PyType_Type;
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100300static int (*dll_PyType_Ready)(PyTypeObject *type);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000301static PyObject*(*dll_Py_BuildValue)(char *, ...);
302static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
303static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
Bram Moolenaardb913952012-06-29 12:54:53 +0200304static PyObject*(*dll_PyImport_AddModule)(char *);
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100305static void(*dll_Py_SetPythonHome)(char *home);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000307static void(*dll_Py_Finalize)(void);
308static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
310static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200311static PyObject* (*dll_PyObject_GetIter)(PyObject *);
312static iternextfunc dll__PyObject_NextNotImplemented;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000313static PyObject* dll__Py_NoneStruct;
314# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
315static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
316# endif
317# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
318static void* (*dll_PyObject_Malloc)(size_t);
319static void (*dll_PyObject_Free)(void*);
320# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200321# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +0200322static PyObject* (*dll_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
323static void* (*dll_PyCapsule_GetPointer)(PyObject *, char *);
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200324# else
325static PyCObject* (*dll_PyCObject_FromVoidPtr)(void *cobj, void (*destr)(void *));
326static void* (*dll_PyCObject_AsVoidPtr)(PyCObject *);
327# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328
329static HINSTANCE hinstPython = 0; /* Instance of python.dll */
330
331/* Imported exception objects */
332static PyObject *imp_PyExc_AttributeError;
333static PyObject *imp_PyExc_IndexError;
334static PyObject *imp_PyExc_KeyboardInterrupt;
335static PyObject *imp_PyExc_TypeError;
336static PyObject *imp_PyExc_ValueError;
337
338# define PyExc_AttributeError imp_PyExc_AttributeError
339# define PyExc_IndexError imp_PyExc_IndexError
340# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
341# define PyExc_TypeError imp_PyExc_TypeError
342# define PyExc_ValueError imp_PyExc_ValueError
343
344/*
345 * Table of name to function pointer of python.
346 */
347# define PYTHON_PROC FARPROC
348static struct
349{
350 char *name;
351 PYTHON_PROC *ptr;
352} python_funcname_table[] =
353{
354 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
355 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
Bram Moolenaar19e60942011-06-19 00:27:51 +0200356 {"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free},
Bram Moolenaardb913952012-06-29 12:54:53 +0200357 {"PyMem_Malloc", (PYTHON_PROC*)&dll_PyMem_Malloc},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
359 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
360 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
361 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
362 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
363 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
364 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
365 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
366 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
367 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
368# ifdef PY_CAN_RECURSE
369 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
370 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
371# endif
372 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
373 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
Bram Moolenaardb913952012-06-29 12:54:53 +0200374 {"PyLong_AsLong", (PYTHON_PROC*)&dll_PyLong_AsLong},
375 {"PyLong_FromLong", (PYTHON_PROC*)&dll_PyLong_FromLong},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200377 {"PyLong_Type", (PYTHON_PROC*)&dll_PyLong_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000378 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000379 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
381 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
382 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
383 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200384 {"PySequence_GetItem", (PYTHON_PROC*)&dll_PySequence_GetItem},
385 {"PySequence_Size", (PYTHON_PROC*)&dll_PySequence_Size},
386 {"PySequence_Check", (PYTHON_PROC*)&dll_PySequence_Check},
387 {"PyTuple_GetItem", (PYTHON_PROC*)&dll_PyTuple_GetItem},
388 {"PyTuple_Size", (PYTHON_PROC*)&dll_PyTuple_Size},
389 {"PyTuple_Type", (PYTHON_PROC*)&dll_PyTuple_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
391 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200392 {"PyDict_Next", (PYTHON_PROC*)&dll_PyDict_Next},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000393 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaardb913952012-06-29 12:54:53 +0200394# ifndef PY_NO_MAPPING_ITEMS
395 {"PyMapping_Items", (PYTHON_PROC*)&dll_PyMapping_Items},
396# endif
397 {"PyObject_CallMethod", (PYTHON_PROC*)&dll_PyObject_CallMethod},
398 {"PyMapping_Check", (PYTHON_PROC*)&dll_PyMapping_Check},
399 {"PyIter_Next", (PYTHON_PROC*)&dll_PyIter_Next},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
401 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200402 {"PyRun_String", (PYTHON_PROC*)&dll_PyRun_String},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000403 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
404 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
405 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
406 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
407 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200408 {"PyUnicode_Type", (PYTHON_PROC*)&dll_PyUnicode_Type},
409 {"PyUnicodeUCS4_AsEncodedString", (PYTHON_PROC*)&dll_PyUnicodeUCS4_AsEncodedString},
410 {"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;
474
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100475#if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200476 /* Can't have Python and Python3 loaded at the same time.
477 * It cause a crash, because RTLD_GLOBAL is needed for
478 * standard C extension libraries of one or both python versions. */
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200479 if (python3_loaded())
480 {
Bram Moolenaar9dc93ae2011-08-28 16:00:19 +0200481 if (verbose)
482 EMSG(_("E836: This Vim cannot execute :python after using :py3"));
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200483 return FAIL;
484 }
485#endif
486
Bram Moolenaar071d4272004-06-13 20:20:40 +0000487 if (hinstPython)
488 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200489 hinstPython = load_dll(libname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490 if (!hinstPython)
491 {
492 if (verbose)
493 EMSG2(_(e_loadlib), libname);
494 return FAIL;
495 }
496
497 for (i = 0; python_funcname_table[i].ptr; ++i)
498 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200499 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500 python_funcname_table[i].name)) == NULL)
501 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200502 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 hinstPython = 0;
504 if (verbose)
505 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
506 return FAIL;
507 }
508 }
509 return OK;
510}
511
512/*
513 * If python is enabled (there is installed python on Windows system) return
514 * TRUE, else FALSE.
515 */
516 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000517python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518{
519 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
520}
521
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200522/*
523 * Load the standard Python exceptions - don't import the symbols from the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 * DLL, as this can cause errors (importing data symbols is not reliable).
525 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526 static void
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200527get_exceptions(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528{
529 PyObject *exmod = PyImport_ImportModule("exceptions");
530 PyObject *exdict = PyModule_GetDict(exmod);
531 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
532 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
533 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
534 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
535 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
536 Py_XINCREF(imp_PyExc_AttributeError);
537 Py_XINCREF(imp_PyExc_IndexError);
538 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
539 Py_XINCREF(imp_PyExc_TypeError);
540 Py_XINCREF(imp_PyExc_ValueError);
541 Py_XDECREF(exmod);
542}
543#endif /* DYNAMIC_PYTHON */
544
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200545static PyObject *BufferNew (buf_T *);
546static PyObject *WindowNew(win_T *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200547static PyObject *DictionaryNew(dict_T *);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200548static PyObject *LineToString(const char *);
549
550static PyTypeObject RangeType;
551
Bram Moolenaardb913952012-06-29 12:54:53 +0200552static int initialised = 0;
553#define PYINITIALISED initialised
554
555/* Add conversion from PyInt? */
556#define DICTKEY_GET(err) \
557 if (!PyString_Check(keyObject)) \
558 { \
559 PyErr_SetString(PyExc_TypeError, _("only string keys are allowed")); \
560 return err; \
561 } \
562 key = (char_u *) PyString_AsString(keyObject);
563#define DICTKEY_UNREF
564#define DICTKEY_DECL
565
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200566/*
567 * Include the code shared with if_python3.c
568 */
569#include "if_py_both.h"
570
571
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572/******************************************************
573 * Internal function prototypes.
574 */
575
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000576static PyInt RangeStart;
577static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578
Bram Moolenaardb913952012-06-29 12:54:53 +0200579static PyObject *globals;
580
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581static void PythonIO_Flush(void);
582static int PythonIO_Init(void);
583static int PythonMod_Init(void);
584
585/* Utility functions for the vim/python interface
586 * ----------------------------------------------
587 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000589static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000590
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591
592/******************************************************
593 * 1. Python interpreter main program.
594 */
595
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
597typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000598#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000599
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000600#ifdef PY_CAN_RECURSE
601static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
602#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000603static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000604#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605
606/*
607 * Suspend a thread of the Python interpreter, other threads are allowed to
608 * run.
609 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000610 static void
611Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000613#ifdef PY_CAN_RECURSE
614 PyGILState_Release(pygilstate);
615#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000617#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618}
619
620/*
621 * Restore a thread of the Python interpreter, waits for other threads to
622 * block.
623 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000624 static void
625Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000627#ifdef PY_CAN_RECURSE
628 pygilstate = PyGILState_Ensure();
629#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 PyEval_RestoreThread(saved_python_thread);
631 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000633}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 void
636python_end()
637{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000638 static int recurse = 0;
639
640 /* If a crash occurs while doing this, don't try again. */
641 if (recurse != 0)
642 return;
643
644 ++recurse;
645
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000647 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000648 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000649 Python_RestoreThread(); /* enter python */
650 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000653#else
654 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000655 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000656 Python_RestoreThread(); /* enter python */
657 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000658 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000660
661 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662}
663
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200664#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
665 int
666python_loaded()
667{
668 return (hinstPython != 0);
669}
670#endif
671
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672 static int
673Python_Init(void)
674{
675 if (!initialised)
676 {
677#ifdef DYNAMIC_PYTHON
678 if (!python_enabled(TRUE))
679 {
680 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
681 goto fail;
682 }
683#endif
684
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100685#ifdef PYTHON_HOME
686 Py_SetPythonHome(PYTHON_HOME);
687#endif
688
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200689 init_structs();
690
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691#if !defined(MACOS) || defined(MACOS_X_UNIX)
692 Py_Initialize();
693#else
694 PyMac_Initialize();
695#endif
696 /* initialise threads */
697 PyEval_InitThreads();
698
699#ifdef DYNAMIC_PYTHON
700 get_exceptions();
701#endif
702
703 if (PythonIO_Init())
704 goto fail;
705
706 if (PythonMod_Init())
707 goto fail;
708
Bram Moolenaardb913952012-06-29 12:54:53 +0200709 globals = PyModule_GetDict(PyImport_AddModule("__main__"));
710
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000711 /* Remove the element from sys.path that was added because of our
712 * argv[0] value in PythonMod_Init(). Previously we used an empty
713 * string, but dependinding on the OS we then get an empty entry or
714 * the current directory in sys.path. */
715 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
716
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000717 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000718 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719
720 initialised = 1;
721 }
722
723 return 0;
724
725fail:
726 /* We call PythonIO_Flush() here to print any Python errors.
727 * This is OK, as it is possible to call this function even
728 * if PythonIO_Init() has not completed successfully (it will
729 * not do anything in this case).
730 */
731 PythonIO_Flush();
732 return -1;
733}
734
735/*
736 * External interface
737 */
738 static void
Bram Moolenaardb913952012-06-29 12:54:53 +0200739DoPythonCommand(exarg_T *eap, const char *cmd, typval_T *rettv)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000741#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 static int recursive = 0;
743#endif
744#if defined(MACOS) && !defined(MACOS_X_UNIX)
745 GrafPtr oldPort;
746#endif
747#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
748 char *saved_locale;
749#endif
750
751#ifndef PY_CAN_RECURSE
752 if (recursive)
753 {
754 EMSG(_("E659: Cannot invoke Python recursively"));
755 return;
756 }
757 ++recursive;
758#endif
759
760#if defined(MACOS) && !defined(MACOS_X_UNIX)
761 GetPort(&oldPort);
762 /* Check if the Python library is available */
763 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
764 goto theend;
765#endif
766 if (Python_Init())
767 goto theend;
768
Bram Moolenaardb913952012-06-29 12:54:53 +0200769 if (rettv == NULL)
770 {
771 RangeStart = eap->line1;
772 RangeEnd = eap->line2;
773 }
774 else
775 {
776 RangeStart = (PyInt) curwin->w_cursor.lnum;
777 RangeEnd = RangeStart;
778 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779 Python_Release_Vim(); /* leave vim */
780
781#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
782 /* Python only works properly when the LC_NUMERIC locale is "C". */
783 saved_locale = setlocale(LC_NUMERIC, NULL);
784 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
785 saved_locale = NULL;
786 else
787 {
788 /* Need to make a copy, value may change when setting new locale. */
789 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
790 (void)setlocale(LC_NUMERIC, "C");
791 }
792#endif
793
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795
Bram Moolenaardb913952012-06-29 12:54:53 +0200796 if (rettv == NULL)
797 PyRun_SimpleString((char *)(cmd));
798 else
799 {
800 PyObject *r;
801
802 r = PyRun_String((char *)(cmd), Py_eval_input, globals, globals);
803 if (r == NULL)
804 EMSG(_("E858: Eval did not return a valid python object"));
805 else
806 {
807 if (ConvertFromPyObject(r, rettv) == -1)
808 EMSG(_("E859: Failed to convert returned python object to vim value"));
809 Py_DECREF(r);
810 }
811 PyErr_Clear();
812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815
816#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
817 if (saved_locale != NULL)
818 {
819 (void)setlocale(LC_NUMERIC, saved_locale);
820 vim_free(saved_locale);
821 }
822#endif
823
824 Python_Lock_Vim(); /* enter vim */
825 PythonIO_Flush();
826#if defined(MACOS) && !defined(MACOS_X_UNIX)
827 SetPort(oldPort);
828#endif
829
830theend:
831#ifndef PY_CAN_RECURSE
832 --recursive;
833#endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200834 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835}
836
837/*
838 * ":python"
839 */
840 void
841ex_python(exarg_T *eap)
842{
843 char_u *script;
844
845 script = script_get(eap, eap->arg);
846 if (!eap->skip)
847 {
848 if (script == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200849 DoPythonCommand(eap, (char *)eap->arg, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850 else
Bram Moolenaardb913952012-06-29 12:54:53 +0200851 DoPythonCommand(eap, (char *)script, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852 }
853 vim_free(script);
854}
855
856#define BUFFER_SIZE 1024
857
858/*
859 * ":pyfile"
860 */
861 void
862ex_pyfile(exarg_T *eap)
863{
864 static char buffer[BUFFER_SIZE];
865 const char *file = (char *)eap->arg;
866 char *p;
867
868 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
869 * stdio file pointer, but Vim and the Python DLL are compiled with
870 * different options under Windows, meaning that stdio pointers aren't
871 * compatible between the two. Yuk.
872 *
873 * Put the string "execfile('file')" into buffer. But, we need to
874 * escape any backslashes or single quotes in the file name, so that
875 * Python won't mangle the file name.
876 */
877 strcpy(buffer, "execfile('");
878 p = buffer + 10; /* size of "execfile('" */
879
880 while (*file && p < buffer + (BUFFER_SIZE - 3))
881 {
882 if (*file == '\\' || *file == '\'')
883 *p++ = '\\';
884 *p++ = *file++;
885 }
886
887 /* If we didn't finish the file name, we hit a buffer overflow */
888 if (*file != '\0')
889 return;
890
891 /* Put in the terminating "')" and a null */
892 *p++ = '\'';
893 *p++ = ')';
894 *p++ = '\0';
895
896 /* Execute the file */
Bram Moolenaardb913952012-06-29 12:54:53 +0200897 DoPythonCommand(eap, buffer, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898}
899
900/******************************************************
901 * 2. Python output stream: writes output via [e]msg().
902 */
903
904/* Implementation functions
905 */
906
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907 static PyObject *
908OutputGetattr(PyObject *self, char *name)
909{
910 if (strcmp(name, "softspace") == 0)
911 return PyInt_FromLong(((OutputObject *)(self))->softspace);
912
913 return Py_FindMethod(OutputMethods, self, name);
914}
915
916 static int
917OutputSetattr(PyObject *self, char *name, PyObject *val)
918{
Bram Moolenaardb913952012-06-29 12:54:53 +0200919 if (val == NULL)
920 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
922 return -1;
923 }
924
925 if (strcmp(name, "softspace") == 0)
926 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200927 if (!PyInt_Check(val))
928 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
930 return -1;
931 }
932
933 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
934 return 0;
935 }
936
937 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
938 return -1;
939}
940
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941/***************/
942
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943 static int
944PythonIO_Init(void)
945{
946 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +0100947 PyType_Ready(&OutputType);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200949 return PythonIO_Init_io();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950}
951
952/******************************************************
953 * 3. Implementation of the Vim module for Python
954 */
955
Bram Moolenaardb913952012-06-29 12:54:53 +0200956static PyObject *ConvertToPyObject(typval_T *);
957static int ConvertFromPyObject(PyObject *, typval_T *);
958
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959/* Window type - Implementation functions
960 * --------------------------------------
961 */
962
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
964
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965static void WindowDestructor(PyObject *);
966static PyObject *WindowGetattr(PyObject *, char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967
968/* Buffer type - Implementation functions
969 * --------------------------------------
970 */
971
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
973
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974static void BufferDestructor(PyObject *);
975static PyObject *BufferGetattr(PyObject *, char *);
976static PyObject *BufferRepr(PyObject *);
977
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000978static PyInt BufferLength(PyObject *);
979static PyObject *BufferItem(PyObject *, PyInt);
980static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
981static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
982static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984/* Line range type - Implementation functions
985 * --------------------------------------
986 */
987
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
989
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000990static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
991static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993/* Current objects type - Implementation functions
994 * -----------------------------------------------
995 */
996
997static PyObject *CurrentGetattr(PyObject *, char *);
998static int CurrentSetattr(PyObject *, char *, PyObject *);
999
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001001 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001003 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
1004 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1005 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1006 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
1007 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001008};
1009
1010static PyTypeObject BufferType = {
1011 PyObject_HEAD_INIT(0)
1012 0,
1013 "buffer",
1014 sizeof(BufferObject),
1015 0,
1016
1017 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
1018 (printfunc) 0, /* tp_print, print x */
1019 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1020 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1021 (cmpfunc) 0, /* tp_compare, x>y */
1022 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1023
1024 0, /* as number */
1025 &BufferAsSeq, /* as sequence */
1026 0, /* as mapping */
1027
1028 (hashfunc) 0, /* tp_hash, dict(x) */
1029 (ternaryfunc) 0, /* tp_call, x() */
1030 (reprfunc) 0, /* tp_str, str(x) */
1031};
1032
1033/* Buffer object - Implementation
1034 */
1035
1036 static PyObject *
1037BufferNew(buf_T *buf)
1038{
1039 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001040 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041 * then we can get at it in buf_freeall() in vim. We then
1042 * need to create only ONE Python object per buffer - if
1043 * we try to create a second, just INCREF the existing one
1044 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001045 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046 * Question: what to do on a buf_freeall(). We'll probably
1047 * have to either delete the Python object (DECREF it to
1048 * zero - a bad idea, as it leaves dangling refs!) or
1049 * set the buf_T * value to an invalid value (-1?), which
1050 * means we need checks in all access functions... Bah.
1051 */
1052
1053 BufferObject *self;
1054
Bram Moolenaare344bea2005-09-01 20:46:49 +00001055 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001057 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 Py_INCREF(self);
1059 }
1060 else
1061 {
1062 self = PyObject_NEW(BufferObject, &BufferType);
1063 if (self == NULL)
1064 return NULL;
1065 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001066 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067 }
1068
1069 return (PyObject *)(self);
1070}
1071
1072 static void
1073BufferDestructor(PyObject *self)
1074{
1075 BufferObject *this = (BufferObject *)(self);
1076
1077 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001078 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079
Bram Moolenaar658ada62006-10-03 13:02:36 +00001080 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081}
1082
1083 static PyObject *
1084BufferGetattr(PyObject *self, char *name)
1085{
1086 BufferObject *this = (BufferObject *)(self);
1087
1088 if (CheckBuffer(this))
1089 return NULL;
1090
1091 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001092 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001094 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 else if (strcmp(name,"__members__") == 0)
1096 return Py_BuildValue("[ss]", "name", "number");
1097 else
1098 return Py_FindMethod(BufferMethods, self, name);
1099}
1100
1101 static PyObject *
1102BufferRepr(PyObject *self)
1103{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001104 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 BufferObject *this = (BufferObject *)(self);
1106
1107 if (this->buf == INVALID_BUFFER_VALUE)
1108 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001109 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110 return PyString_FromString(repr);
1111 }
1112 else
1113 {
1114 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001115 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116
1117 if (name == NULL)
1118 name = "";
1119 len = strlen(name);
1120
1121 if (len > 35)
1122 name = name + (35 - len);
1123
Bram Moolenaar555b2802005-05-19 21:08:39 +00001124 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125
1126 return PyString_FromString(repr);
1127 }
1128}
1129
1130/******************/
1131
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001132 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133BufferLength(PyObject *self)
1134{
1135 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1136 if (CheckBuffer((BufferObject *)(self)))
1137 return -1; /* ??? */
1138
1139 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1140}
1141
1142 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001143BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144{
1145 return RBItem((BufferObject *)(self), n, 1,
1146 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1147}
1148
1149 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001150BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151{
1152 return RBSlice((BufferObject *)(self), lo, hi, 1,
1153 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1154}
1155
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001156 static PyInt
1157BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001159 return RBAsItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001160 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161 NULL);
1162}
1163
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001164 static PyInt
1165BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001167 return RBAsSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001168 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169 NULL);
1170}
1171
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001173 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001175 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1176 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1177 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1178 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1179 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180};
1181
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182/* Line range object - Implementation
1183 */
1184
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 static void
1186RangeDestructor(PyObject *self)
1187{
1188 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001189 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190}
1191
1192 static PyObject *
1193RangeGetattr(PyObject *self, char *name)
1194{
1195 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001196 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001198 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199 else
1200 return Py_FindMethod(RangeMethods, self, name);
1201}
1202
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203/****************/
1204
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001205 static PyInt
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001206RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001208 return RBAsItem(((RangeObject *)(self))->buf, n, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209 ((RangeObject *)(self))->start,
1210 ((RangeObject *)(self))->end,
1211 &((RangeObject *)(self))->end);
1212}
1213
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001214 static PyInt
1215RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001217 return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001218 ((RangeObject *)(self))->start,
1219 ((RangeObject *)(self))->end,
1220 &((RangeObject *)(self))->end);
1221}
1222
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223/* Buffer list object - Definitions
1224 */
1225
1226typedef struct
1227{
1228 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001229} BufListObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230
1231static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001232 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001233 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001234 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1235 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1236 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1237 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1238 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239};
1240
1241static PyTypeObject BufListType = {
1242 PyObject_HEAD_INIT(0)
1243 0,
1244 "buffer list",
1245 sizeof(BufListObject),
1246 0,
1247
1248 (destructor) 0, /* tp_dealloc, refcount==0 */
1249 (printfunc) 0, /* tp_print, print x */
1250 (getattrfunc) 0, /* tp_getattr, x.attr */
1251 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1252 (cmpfunc) 0, /* tp_compare, x>y */
1253 (reprfunc) 0, /* tp_repr, `x`, print x */
1254
1255 0, /* as number */
1256 &BufListAsSeq, /* as sequence */
1257 0, /* as mapping */
1258
1259 (hashfunc) 0, /* tp_hash, dict(x) */
1260 (ternaryfunc) 0, /* tp_call, x() */
1261 (reprfunc) 0, /* tp_str, str(x) */
1262};
1263
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264/* Window object - Definitions
1265 */
1266
1267static struct PyMethodDef WindowMethods[] = {
1268 /* name, function, calling, documentation */
1269 { NULL, NULL, 0, NULL }
1270};
1271
1272static PyTypeObject WindowType = {
1273 PyObject_HEAD_INIT(0)
1274 0,
1275 "window",
1276 sizeof(WindowObject),
1277 0,
1278
1279 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1280 (printfunc) 0, /* tp_print, print x */
1281 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1282 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1283 (cmpfunc) 0, /* tp_compare, x>y */
1284 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1285
1286 0, /* as number */
1287 0, /* as sequence */
1288 0, /* as mapping */
1289
1290 (hashfunc) 0, /* tp_hash, dict(x) */
1291 (ternaryfunc) 0, /* tp_call, x() */
1292 (reprfunc) 0, /* tp_str, str(x) */
1293};
1294
1295/* Window object - Implementation
1296 */
1297
1298 static PyObject *
1299WindowNew(win_T *win)
1300{
1301 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001302 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 * then we can get at it in win_free() in vim. We then
1304 * need to create only ONE Python object per window - if
1305 * we try to create a second, just INCREF the existing one
1306 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001307 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 * On a win_free() we set the Python object's win_T* field
1309 * to an invalid value. We trap all uses of a window
1310 * object, and reject them if the win_T* field is invalid.
1311 */
1312
1313 WindowObject *self;
1314
Bram Moolenaare344bea2005-09-01 20:46:49 +00001315 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001317 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318 Py_INCREF(self);
1319 }
1320 else
1321 {
1322 self = PyObject_NEW(WindowObject, &WindowType);
1323 if (self == NULL)
1324 return NULL;
1325 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001326 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327 }
1328
1329 return (PyObject *)(self);
1330}
1331
1332 static void
1333WindowDestructor(PyObject *self)
1334{
1335 WindowObject *this = (WindowObject *)(self);
1336
1337 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001338 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001339
Bram Moolenaar658ada62006-10-03 13:02:36 +00001340 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341}
1342
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343 static PyObject *
1344WindowGetattr(PyObject *self, char *name)
1345{
1346 WindowObject *this = (WindowObject *)(self);
1347
1348 if (CheckWindow(this))
1349 return NULL;
1350
1351 if (strcmp(name, "buffer") == 0)
1352 return (PyObject *)BufferNew(this->win->w_buffer);
1353 else if (strcmp(name, "cursor") == 0)
1354 {
1355 pos_T *pos = &this->win->w_cursor;
1356
1357 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1358 }
1359 else if (strcmp(name, "height") == 0)
1360 return Py_BuildValue("l", (long)(this->win->w_height));
1361#ifdef FEAT_VERTSPLIT
1362 else if (strcmp(name, "width") == 0)
1363 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1364#endif
1365 else if (strcmp(name,"__members__") == 0)
1366 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1367 else
1368 return Py_FindMethod(WindowMethods, self, name);
1369}
1370
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371/* Window list object - Definitions
1372 */
1373
1374typedef struct
1375{
1376 PyObject_HEAD
1377}
1378WinListObject;
1379
1380static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001381 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001383 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1384 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
1385 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1386 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1387 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388};
1389
1390static PyTypeObject WinListType = {
1391 PyObject_HEAD_INIT(0)
1392 0,
1393 "window list",
1394 sizeof(WinListObject),
1395 0,
1396
1397 (destructor) 0, /* tp_dealloc, refcount==0 */
1398 (printfunc) 0, /* tp_print, print x */
1399 (getattrfunc) 0, /* tp_getattr, x.attr */
1400 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1401 (cmpfunc) 0, /* tp_compare, x>y */
1402 (reprfunc) 0, /* tp_repr, `x`, print x */
1403
1404 0, /* as number */
1405 &WinListAsSeq, /* as sequence */
1406 0, /* as mapping */
1407
1408 (hashfunc) 0, /* tp_hash, dict(x) */
1409 (ternaryfunc) 0, /* tp_call, x() */
1410 (reprfunc) 0, /* tp_str, str(x) */
1411};
1412
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413/* Current items object - Definitions
1414 */
1415
1416typedef struct
1417{
1418 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001419} CurrentObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420
1421static PyTypeObject CurrentType = {
1422 PyObject_HEAD_INIT(0)
1423 0,
1424 "current data",
1425 sizeof(CurrentObject),
1426 0,
1427
1428 (destructor) 0, /* tp_dealloc, refcount==0 */
1429 (printfunc) 0, /* tp_print, print x */
1430 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
1431 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
1432 (cmpfunc) 0, /* tp_compare, x>y */
1433 (reprfunc) 0, /* tp_repr, `x`, print x */
1434
1435 0, /* as number */
1436 0, /* as sequence */
1437 0, /* as mapping */
1438
1439 (hashfunc) 0, /* tp_hash, dict(x) */
1440 (ternaryfunc) 0, /* tp_call, x() */
1441 (reprfunc) 0, /* tp_str, str(x) */
1442};
1443
1444/* Current items object - Implementation
1445 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001447CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448{
1449 if (strcmp(name, "buffer") == 0)
1450 return (PyObject *)BufferNew(curbuf);
1451 else if (strcmp(name, "window") == 0)
1452 return (PyObject *)WindowNew(curwin);
1453 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001454 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 else if (strcmp(name, "range") == 0)
1456 return RangeNew(curbuf, RangeStart, RangeEnd);
1457 else if (strcmp(name,"__members__") == 0)
1458 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
1459 else
1460 {
1461 PyErr_SetString(PyExc_AttributeError, name);
1462 return NULL;
1463 }
1464}
1465
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001467CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468{
1469 if (strcmp(name, "line") == 0)
1470 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001471 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 return -1;
1473
1474 return 0;
1475 }
1476 else
1477 {
1478 PyErr_SetString(PyExc_AttributeError, name);
1479 return -1;
1480 }
1481}
1482
1483/* External interface
1484 */
1485
1486 void
1487python_buffer_free(buf_T *buf)
1488{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001489 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001491 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001493 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 }
1495}
1496
1497#if defined(FEAT_WINDOWS) || defined(PROTO)
1498 void
1499python_window_free(win_T *win)
1500{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001501 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001503 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001505 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506 }
1507}
1508#endif
1509
1510static BufListObject TheBufferList =
1511{
1512 PyObject_HEAD_INIT(&BufListType)
1513};
1514
1515static WinListObject TheWindowList =
1516{
1517 PyObject_HEAD_INIT(&WinListType)
1518};
1519
1520static CurrentObject TheCurrent =
1521{
1522 PyObject_HEAD_INIT(&CurrentType)
1523};
1524
1525 static int
1526PythonMod_Init(void)
1527{
1528 PyObject *mod;
1529 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00001530 /* The special value is removed from sys.path in Python_Init(). */
1531 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532
1533 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +01001534 PyType_Ready(&BufferType);
1535 PyType_Ready(&RangeType);
1536 PyType_Ready(&WindowType);
1537 PyType_Ready(&BufListType);
1538 PyType_Ready(&WinListType);
1539 PyType_Ready(&CurrentType);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001540
1541 /* Set sys.argv[] to avoid a crash in warn(). */
1542 PySys_SetArgv(1, argv);
1543
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001544 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 dict = PyModule_GetDict(mod);
1546
1547 VimError = Py_BuildValue("s", "vim.error");
1548
1549 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00001550 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
1551 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
1552 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553
1554 if (PyErr_Occurred())
1555 return -1;
1556
1557 return 0;
1558}
1559
1560/*************************************************************************
1561 * 4. Utility functions for handling the interface between Vim and Python.
1562 */
1563
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564/* Convert a Vim line into a Python string.
1565 * All internal newlines are replaced by null characters.
1566 *
1567 * On errors, the Python exception data is set, and NULL is returned.
1568 */
1569 static PyObject *
1570LineToString(const char *str)
1571{
1572 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001573 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 char *p;
1575
1576 /* Allocate an Python string object, with uninitialised contents. We
1577 * must do it this way, so that we can modify the string in place
1578 * later. See the Python source, Objects/stringobject.c for details.
1579 */
1580 result = PyString_FromStringAndSize(NULL, len);
1581 if (result == NULL)
1582 return NULL;
1583
1584 p = PyString_AsString(result);
1585
1586 while (*str)
1587 {
1588 if (*str == '\n')
1589 *p = '\0';
1590 else
1591 *p = *str;
1592
1593 ++p;
1594 ++str;
1595 }
1596
1597 return result;
1598}
1599
Bram Moolenaardb913952012-06-29 12:54:53 +02001600static void DictionaryDestructor(PyObject *);
1601static PyObject *DictionaryGetattr(PyObject *, char*);
1602
1603static PyMappingMethods DictionaryAsMapping = {
1604 (PyInquiry) DictionaryLength,
1605 (binaryfunc) DictionaryItem,
1606 (objobjargproc) DictionaryAssItem,
1607};
1608
1609static PyTypeObject DictionaryType = {
1610 PyObject_HEAD_INIT(0)
1611 0,
1612 "vimdictionary",
1613 sizeof(DictionaryObject),
1614 0,
1615
1616 (destructor) DictionaryDestructor,
1617 (printfunc) 0,
1618 (getattrfunc) DictionaryGetattr,
1619 (setattrfunc) 0,
1620 (cmpfunc) 0,
1621 (reprfunc) 0,
1622
1623 0, /* as number */
1624 0, /* as sequence */
1625 &DictionaryAsMapping, /* as mapping */
1626
1627 (hashfunc) 0,
1628 (ternaryfunc) 0,
1629 (reprfunc) 0,
1630};
1631
1632 static void
1633DictionaryDestructor(PyObject *self)
1634{
1635 DictionaryObject *this = ((DictionaryObject *) (self));
1636
1637 pyll_remove(&this->ref, &lastdict);
1638 dict_unref(this->dict);
1639
1640 Py_DECREF(self);
1641}
1642
1643 static PyObject *
1644DictionaryGetattr(PyObject *self, char *name)
1645{
1646 return Py_FindMethod(DictionaryMethods, self, name);
1647}
1648
1649static void ListDestructor(PyObject *);
1650static PyObject *ListGetattr(PyObject *, char *);
1651
1652static PySequenceMethods ListAsSeq = {
1653 (PyInquiry) ListLength,
1654 (binaryfunc) 0,
1655 (PyIntArgFunc) 0,
1656 (PyIntArgFunc) ListItem,
1657 (PyIntIntArgFunc) ListSlice,
1658 (PyIntObjArgProc) ListAssItem,
1659 (PyIntIntObjArgProc) ListAssSlice,
1660 (objobjproc) 0,
1661#if PY_MAJOR_VERSION >= 2
1662 (binaryfunc) ListConcatInPlace,
1663 0,
1664#endif
1665};
1666
1667static PyTypeObject ListType = {
1668 PyObject_HEAD_INIT(0)
1669 0,
1670 "vimlist",
1671 sizeof(ListObject),
1672 0,
1673
1674 (destructor) ListDestructor,
1675 (printfunc) 0,
1676 (getattrfunc) ListGetattr,
1677 (setattrfunc) 0,
1678 (cmpfunc) 0,
1679 (reprfunc) 0,
1680
1681 0, /* as number */
1682 &ListAsSeq, /* as sequence */
1683 0, /* as mapping */
1684
1685 (hashfunc) 0,
1686 (ternaryfunc) 0,
1687 (reprfunc) 0,
1688};
1689
1690 static void
1691ListDestructor(PyObject *self)
1692{
1693 ListObject *this = ((ListObject *) (self));
1694
1695 pyll_remove(&this->ref, &lastlist);
1696 list_unref(this->list);
1697
1698 Py_DECREF(self);
1699}
1700
1701 static PyObject *
1702ListGetattr(PyObject *self, char *name)
1703{
1704 return Py_FindMethod(ListMethods, self, name);
1705}
1706
1707static void FunctionDestructor(PyObject *);
1708static PyObject *FunctionGetattr(PyObject *, char *);
1709
1710static PyTypeObject FunctionType = {
1711 PyObject_HEAD_INIT(0)
1712 0,
1713 "vimfunction",
1714 sizeof(FunctionObject),
1715 0,
1716
1717 (destructor) FunctionDestructor,
1718 (printfunc) 0,
1719 (getattrfunc) FunctionGetattr,
1720 (setattrfunc) 0,
1721 (cmpfunc) 0,
1722 (reprfunc) 0,
1723
1724 0, /* as number */
1725 0, /* as sequence */
1726 0, /* as mapping */
1727
1728 (hashfunc) 0,
1729 (ternaryfunc) FunctionCall,
1730 (reprfunc) 0,
1731};
1732
1733 static void
1734FunctionDestructor(PyObject *self)
1735{
1736 FunctionObject *this = (FunctionObject *) (self);
1737
1738 func_unref(this->name);
1739 PyMem_Del(this->name);
1740
1741 Py_DECREF(self);
1742}
1743
1744 static PyObject *
1745FunctionGetattr(PyObject *self, char *name)
1746{
1747 FunctionObject *this = (FunctionObject *)(self);
1748
1749 if (strcmp(name, "name") == 0)
1750 return PyString_FromString((char *)(this->name));
1751 else
1752 return Py_FindMethod(FunctionMethods, self, name);
1753}
1754
1755 void
1756do_pyeval (char_u *str, typval_T *rettv)
1757{
1758 DoPythonCommand(NULL, (char *) str, rettv);
1759 switch(rettv->v_type)
1760 {
1761 case VAR_DICT: ++rettv->vval.v_dict->dv_refcount; break;
1762 case VAR_LIST: ++rettv->vval.v_list->lv_refcount; break;
1763 case VAR_FUNC: func_ref(rettv->vval.v_string); break;
1764 }
1765}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766
1767/* Don't generate a prototype for the next function, it generates an error on
1768 * newer Python versions. */
1769#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
1770
1771 char *
1772Py_GetProgramName(void)
1773{
1774 return "vim";
1775}
1776#endif /* Python 1.4 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001777
Bram Moolenaardb913952012-06-29 12:54:53 +02001778 void
1779set_ref_in_python (int copyID)
1780{
1781 set_ref_in_py(copyID);
1782}
1783
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001784 static void
1785init_structs(void)
1786{
1787 vim_memset(&OutputType, 0, sizeof(OutputType));
1788 OutputType.tp_name = "message";
1789 OutputType.tp_basicsize = sizeof(OutputObject);
1790 OutputType.tp_getattr = OutputGetattr;
1791 OutputType.tp_setattr = OutputSetattr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001792
1793 vim_memset(&RangeType, 0, sizeof(RangeType));
1794 RangeType.tp_name = "range";
1795 RangeType.tp_basicsize = sizeof(RangeObject);
1796 RangeType.tp_dealloc = RangeDestructor;
1797 RangeType.tp_getattr = RangeGetattr;
1798 RangeType.tp_repr = RangeRepr;
1799 RangeType.tp_as_sequence = &RangeAsSeq;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001800}