blob: b13e73942315f6537e434813080548c860f566d2 [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
47#include <Python.h>
48#if defined(MACOS) && !defined(MACOS_X_UNIX)
49# include "macglue.h"
50# include <CodeFragments.h>
51#endif
52#undef main /* Defined in python.h - aargh */
53#undef HAVE_FCNTL_H /* Clash with os_win32.h */
54
Bram Moolenaare8cdcef2012-09-12 20:21:43 +020055#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
56# define PY_SSIZE_T_CLEAN
57#endif
58
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020059static void init_structs(void);
60
Bram Moolenaardb913952012-06-29 12:54:53 +020061#define PyBytes_FromString PyString_FromString
62
Bram Moolenaar19e60942011-06-19 00:27:51 +020063/* No-op conversion functions, use with care! */
64#define PyString_AsBytes(obj) (obj)
65#define PyString_FreeBytes(obj)
66
Bram Moolenaar071d4272004-06-13 20:20:40 +000067#if !defined(FEAT_PYTHON) && defined(PROTO)
68/* Use this to be able to generate prototypes without python being used. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000069# define PyObject Py_ssize_t
70# define PyThreadState Py_ssize_t
71# define PyTypeObject Py_ssize_t
72struct PyMethodDef { Py_ssize_t a; };
73# define PySequenceMethods Py_ssize_t
Bram Moolenaar071d4272004-06-13 20:20:40 +000074#endif
75
Bram Moolenaar2afa3232012-06-29 16:28:28 +020076#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
77# define PY_USE_CAPSULE
78#endif
79
Bram Moolenaar2c45e942008-06-04 11:35:26 +000080#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
81# define PyInt Py_ssize_t
82# define PyInquiry lenfunc
83# define PyIntArgFunc ssizeargfunc
84# define PyIntIntArgFunc ssizessizeargfunc
85# define PyIntObjArgProc ssizeobjargproc
86# define PyIntIntObjArgProc ssizessizeobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000087# define Py_ssize_t_fmt "n"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000088#else
89# define PyInt int
Bram Moolenaar4d1da492013-04-24 13:39:15 +020090# define lenfunc inquiry
Bram Moolenaar2c45e942008-06-04 11:35:26 +000091# define PyInquiry inquiry
92# define PyIntArgFunc intargfunc
93# define PyIntIntArgFunc intintargfunc
94# define PyIntObjArgProc intobjargproc
95# define PyIntIntObjArgProc intintobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000096# define Py_ssize_t_fmt "i"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000097#endif
98
Bram Moolenaar071d4272004-06-13 20:20:40 +000099/* Parser flags */
100#define single_input 256
101#define file_input 257
102#define eval_input 258
103
104#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
105 /* Python 2.3: can invoke ":python" recursively. */
106# define PY_CAN_RECURSE
107#endif
108
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200109# if defined(DYNAMIC_PYTHON) || defined(PROTO)
110# ifndef DYNAMIC_PYTHON
111# define HINSTANCE long_u /* for generating prototypes */
112# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000113
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200114# ifndef WIN3264
115# include <dlfcn.h>
116# define FARPROC void*
117# define HINSTANCE void*
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100118# if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200119# define load_dll(n) dlopen((n), RTLD_LAZY)
120# else
121# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
122# endif
123# define close_dll dlclose
124# define symbol_from_dll dlsym
125# else
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200126# define load_dll vimLoadLib
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200127# define close_dll FreeLibrary
128# define symbol_from_dll GetProcAddress
129# endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200130
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000131/* This makes if_python.c compile without warnings against Python 2.5
132 * on Win32 and Win64. */
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200133# undef PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200134# undef PyRun_String
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200135# undef PyArg_Parse
136# undef PyArg_ParseTuple
137# undef Py_BuildValue
138# undef Py_InitModule4
139# undef Py_InitModule4_64
Bram Moolenaardb913952012-06-29 12:54:53 +0200140# undef PyObject_CallMethod
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000141
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142/*
143 * Wrapper defines
144 */
145# define PyArg_Parse dll_PyArg_Parse
146# define PyArg_ParseTuple dll_PyArg_ParseTuple
Bram Moolenaar19e60942011-06-19 00:27:51 +0200147# define PyMem_Free dll_PyMem_Free
Bram Moolenaardb913952012-06-29 12:54:53 +0200148# define PyMem_Malloc dll_PyMem_Malloc
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149# define PyDict_SetItemString dll_PyDict_SetItemString
150# define PyErr_BadArgument dll_PyErr_BadArgument
151# define PyErr_Clear dll_PyErr_Clear
Bram Moolenaar4d369872013-02-20 16:09:43 +0100152# define PyErr_PrintEx dll_PyErr_PrintEx
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153# define PyErr_NoMemory dll_PyErr_NoMemory
154# define PyErr_Occurred dll_PyErr_Occurred
155# define PyErr_SetNone dll_PyErr_SetNone
156# define PyErr_SetString dll_PyErr_SetString
157# define PyEval_InitThreads dll_PyEval_InitThreads
158# define PyEval_RestoreThread dll_PyEval_RestoreThread
159# define PyEval_SaveThread dll_PyEval_SaveThread
160# ifdef PY_CAN_RECURSE
161# define PyGILState_Ensure dll_PyGILState_Ensure
162# define PyGILState_Release dll_PyGILState_Release
163# endif
164# define PyInt_AsLong dll_PyInt_AsLong
165# define PyInt_FromLong dll_PyInt_FromLong
Bram Moolenaardb913952012-06-29 12:54:53 +0200166# define PyLong_AsLong dll_PyLong_AsLong
167# define PyLong_FromLong dll_PyLong_FromLong
Bram Moolenaar66b79852012-09-21 14:00:35 +0200168# define PyBool_Type (*dll_PyBool_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169# define PyInt_Type (*dll_PyInt_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200170# define PyLong_Type (*dll_PyLong_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000172# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173# define PyList_New dll_PyList_New
174# define PyList_SetItem dll_PyList_SetItem
175# define PyList_Size dll_PyList_Size
176# define PyList_Type (*dll_PyList_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200177# define PySequence_Check dll_PySequence_Check
178# define PySequence_Size dll_PySequence_Size
179# define PySequence_GetItem dll_PySequence_GetItem
180# define PyTuple_Size dll_PyTuple_Size
181# define PyTuple_GetItem dll_PyTuple_GetItem
182# define PyTuple_Type (*dll_PyTuple_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000183# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000184# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000185# define PyDict_GetItemString dll_PyDict_GetItemString
Bram Moolenaardb913952012-06-29 12:54:53 +0200186# define PyDict_Next dll_PyDict_Next
187# ifdef PyMapping_Items
188# define PY_NO_MAPPING_ITEMS
189# else
190# define PyMapping_Items dll_PyMapping_Items
191# endif
192# define PyObject_CallMethod dll_PyObject_CallMethod
193# define PyMapping_Check dll_PyMapping_Check
194# define PyIter_Next dll_PyIter_Next
Bram Moolenaar071d4272004-06-13 20:20:40 +0000195# define PyModule_GetDict dll_PyModule_GetDict
196# define PyRun_SimpleString dll_PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200197# define PyRun_String dll_PyRun_String
Bram Moolenaar071d4272004-06-13 20:20:40 +0000198# define PyString_AsString dll_PyString_AsString
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200199# define PyString_AsStringAndSize dll_PyString_AsStringAndSize
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200# define PyString_FromString dll_PyString_FromString
201# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
202# define PyString_Size dll_PyString_Size
203# define PyString_Type (*dll_PyString_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200204# define PyUnicode_Type (*dll_PyUnicode_Type)
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200205# undef PyUnicode_AsEncodedString
206# define PyUnicode_AsEncodedString py_PyUnicode_AsEncodedString
Bram Moolenaardb913952012-06-29 12:54:53 +0200207# define PyFloat_AsDouble dll_PyFloat_AsDouble
208# define PyFloat_FromDouble dll_PyFloat_FromDouble
209# define PyFloat_Type (*dll_PyFloat_Type)
210# define PyImport_AddModule (*dll_PyImport_AddModule)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211# define PySys_SetObject dll_PySys_SetObject
212# define PySys_SetArgv dll_PySys_SetArgv
213# define PyType_Type (*dll_PyType_Type)
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100214# define PyType_Ready (*dll_PyType_Ready)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215# define Py_BuildValue dll_Py_BuildValue
216# define Py_FindMethod dll_Py_FindMethod
217# define Py_InitModule4 dll_Py_InitModule4
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100218# define Py_SetPythonHome dll_Py_SetPythonHome
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000220# define Py_Finalize dll_Py_Finalize
221# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000222# define _PyObject_New dll__PyObject_New
Bram Moolenaare7211222012-06-30 13:21:08 +0200223# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
224# define _PyObject_NextNotImplemented (*dll__PyObject_NextNotImplemented)
225# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000226# define _Py_NoneStruct (*dll__Py_NoneStruct)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200227# define _Py_ZeroStruct (*dll__Py_ZeroStruct)
228# define _Py_TrueStruct (*dll__Py_TrueStruct)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229# define PyObject_Init dll__PyObject_Init
Bram Moolenaardb913952012-06-29 12:54:53 +0200230# define PyObject_GetIter dll_PyObject_GetIter
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
232# define PyType_IsSubtype dll_PyType_IsSubtype
233# endif
234# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
235# define PyObject_Malloc dll_PyObject_Malloc
236# define PyObject_Free dll_PyObject_Free
237# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200238# ifdef PY_USE_CAPSULE
239# define PyCapsule_New dll_PyCapsule_New
240# define PyCapsule_GetPointer dll_PyCapsule_GetPointer
241# else
242# define PyCObject_FromVoidPtr dll_PyCObject_FromVoidPtr
243# define PyCObject_AsVoidPtr dll_PyCObject_AsVoidPtr
244# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245
246/*
247 * Pointers for dynamic link
248 */
249static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
250static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200251static int(*dll_PyMem_Free)(void *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200252static void* (*dll_PyMem_Malloc)(size_t);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
254static int(*dll_PyErr_BadArgument)(void);
255static void(*dll_PyErr_Clear)(void);
Bram Moolenaar4d369872013-02-20 16:09:43 +0100256static void(*dll_PyErr_PrintEx)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257static PyObject*(*dll_PyErr_NoMemory)(void);
258static PyObject*(*dll_PyErr_Occurred)(void);
259static void(*dll_PyErr_SetNone)(PyObject *);
260static void(*dll_PyErr_SetString)(PyObject *, const char *);
261static void(*dll_PyEval_InitThreads)(void);
262static void(*dll_PyEval_RestoreThread)(PyThreadState *);
263static PyThreadState*(*dll_PyEval_SaveThread)(void);
264# ifdef PY_CAN_RECURSE
265static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
266static void (*dll_PyGILState_Release)(PyGILState_STATE);
Bram Moolenaardb913952012-06-29 12:54:53 +0200267# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268static long(*dll_PyInt_AsLong)(PyObject *);
269static PyObject*(*dll_PyInt_FromLong)(long);
Bram Moolenaardb913952012-06-29 12:54:53 +0200270static long(*dll_PyLong_AsLong)(PyObject *);
271static PyObject*(*dll_PyLong_FromLong)(long);
Bram Moolenaar66b79852012-09-21 14:00:35 +0200272static PyTypeObject* dll_PyBool_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000273static PyTypeObject* dll_PyInt_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200274static PyTypeObject* dll_PyLong_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000275static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000276static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000277static PyObject*(*dll_PyList_New)(PyInt size);
278static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
279static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280static PyTypeObject* dll_PyList_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200281static int (*dll_PySequence_Check)(PyObject *);
282static PyInt(*dll_PySequence_Size)(PyObject *);
283static PyObject*(*dll_PySequence_GetItem)(PyObject *, PyInt);
284static PyInt(*dll_PyTuple_Size)(PyObject *);
285static PyObject*(*dll_PyTuple_GetItem)(PyObject *, PyInt);
286static PyTypeObject* dll_PyTuple_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000288static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000289static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200290static int (*dll_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
291# ifndef PY_NO_MAPPING_ITEMS
292static PyObject* (*dll_PyMapping_Items)(PyObject *);
293# endif
294static PyObject* (*dll_PyObject_CallMethod)(PyObject *, char *, PyObject *);
295static int (*dll_PyMapping_Check)(PyObject *);
296static PyObject* (*dll_PyIter_Next)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297static PyObject*(*dll_PyModule_GetDict)(PyObject *);
298static int(*dll_PyRun_SimpleString)(char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200299static PyObject *(*dll_PyRun_String)(char *, int, PyObject *, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000300static char*(*dll_PyString_AsString)(PyObject *);
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200301static int(*dll_PyString_AsStringAndSize)(PyObject *, char **, int *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000302static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000303static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
304static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000305static PyTypeObject* dll_PyString_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200306static PyTypeObject* dll_PyUnicode_Type;
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200307static PyObject *(*py_PyUnicode_AsEncodedString)(PyObject *, char *, char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200308static double(*dll_PyFloat_AsDouble)(PyObject *);
309static PyObject*(*dll_PyFloat_FromDouble)(double);
310static PyTypeObject* dll_PyFloat_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311static int(*dll_PySys_SetObject)(char *, PyObject *);
312static int(*dll_PySys_SetArgv)(int, char **);
313static PyTypeObject* dll_PyType_Type;
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100314static int (*dll_PyType_Ready)(PyTypeObject *type);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315static PyObject*(*dll_Py_BuildValue)(char *, ...);
316static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
317static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
Bram Moolenaardb913952012-06-29 12:54:53 +0200318static PyObject*(*dll_PyImport_AddModule)(char *);
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100319static void(*dll_Py_SetPythonHome)(char *home);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000320static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000321static void(*dll_Py_Finalize)(void);
322static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
324static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200325static PyObject* (*dll_PyObject_GetIter)(PyObject *);
Bram Moolenaare7211222012-06-30 13:21:08 +0200326# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
Bram Moolenaardb913952012-06-29 12:54:53 +0200327static iternextfunc dll__PyObject_NextNotImplemented;
Bram Moolenaare7211222012-06-30 13:21:08 +0200328# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000329static PyObject* dll__Py_NoneStruct;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200330static PyObject* _Py_ZeroStruct;
331static PyObject* dll__Py_TrueStruct;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
333static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
334# endif
335# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
336static void* (*dll_PyObject_Malloc)(size_t);
337static void (*dll_PyObject_Free)(void*);
338# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200339# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +0200340static PyObject* (*dll_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
341static void* (*dll_PyCapsule_GetPointer)(PyObject *, char *);
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200342# else
Bram Moolenaar221d6872012-06-30 13:34:34 +0200343static PyObject* (*dll_PyCObject_FromVoidPtr)(void *cobj, void (*destr)(void *));
344static void* (*dll_PyCObject_AsVoidPtr)(PyObject *);
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200345# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346
347static HINSTANCE hinstPython = 0; /* Instance of python.dll */
348
349/* Imported exception objects */
350static PyObject *imp_PyExc_AttributeError;
351static PyObject *imp_PyExc_IndexError;
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200352static PyObject *imp_PyExc_KeyError;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353static PyObject *imp_PyExc_KeyboardInterrupt;
354static PyObject *imp_PyExc_TypeError;
355static PyObject *imp_PyExc_ValueError;
356
357# define PyExc_AttributeError imp_PyExc_AttributeError
358# define PyExc_IndexError imp_PyExc_IndexError
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200359# define PyExc_KeyError imp_PyExc_KeyError
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
361# define PyExc_TypeError imp_PyExc_TypeError
362# define PyExc_ValueError imp_PyExc_ValueError
363
364/*
365 * Table of name to function pointer of python.
366 */
367# define PYTHON_PROC FARPROC
368static struct
369{
370 char *name;
371 PYTHON_PROC *ptr;
372} python_funcname_table[] =
373{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200374#ifndef PY_SSIZE_T_CLEAN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000375 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
376 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200377 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
378#else
379 {"_PyArg_Parse_SizeT", (PYTHON_PROC*)&dll_PyArg_Parse},
380 {"_PyArg_ParseTuple_SizeT", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
381 {"_Py_BuildValue_SizeT", (PYTHON_PROC*)&dll_Py_BuildValue},
382#endif
Bram Moolenaar19e60942011-06-19 00:27:51 +0200383 {"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free},
Bram Moolenaardb913952012-06-29 12:54:53 +0200384 {"PyMem_Malloc", (PYTHON_PROC*)&dll_PyMem_Malloc},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
386 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
387 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
Bram Moolenaar4d369872013-02-20 16:09:43 +0100388 {"PyErr_PrintEx", (PYTHON_PROC*)&dll_PyErr_PrintEx},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
390 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
391 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
392 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
393 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
394 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
395 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
396# ifdef PY_CAN_RECURSE
397 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
398 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
399# endif
400 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
401 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
Bram Moolenaardb913952012-06-29 12:54:53 +0200402 {"PyLong_AsLong", (PYTHON_PROC*)&dll_PyLong_AsLong},
403 {"PyLong_FromLong", (PYTHON_PROC*)&dll_PyLong_FromLong},
Bram Moolenaar66b79852012-09-21 14:00:35 +0200404 {"PyBool_Type", (PYTHON_PROC*)&dll_PyBool_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000405 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200406 {"PyLong_Type", (PYTHON_PROC*)&dll_PyLong_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000408 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
410 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
411 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
412 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200413 {"PySequence_GetItem", (PYTHON_PROC*)&dll_PySequence_GetItem},
414 {"PySequence_Size", (PYTHON_PROC*)&dll_PySequence_Size},
415 {"PySequence_Check", (PYTHON_PROC*)&dll_PySequence_Check},
416 {"PyTuple_GetItem", (PYTHON_PROC*)&dll_PyTuple_GetItem},
417 {"PyTuple_Size", (PYTHON_PROC*)&dll_PyTuple_Size},
418 {"PyTuple_Type", (PYTHON_PROC*)&dll_PyTuple_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
420 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200421 {"PyDict_Next", (PYTHON_PROC*)&dll_PyDict_Next},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000422 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaardb913952012-06-29 12:54:53 +0200423# ifndef PY_NO_MAPPING_ITEMS
424 {"PyMapping_Items", (PYTHON_PROC*)&dll_PyMapping_Items},
425# endif
426 {"PyObject_CallMethod", (PYTHON_PROC*)&dll_PyObject_CallMethod},
427 {"PyMapping_Check", (PYTHON_PROC*)&dll_PyMapping_Check},
428 {"PyIter_Next", (PYTHON_PROC*)&dll_PyIter_Next},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
430 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200431 {"PyRun_String", (PYTHON_PROC*)&dll_PyRun_String},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200433 {"PyString_AsStringAndSize", (PYTHON_PROC*)&dll_PyString_AsStringAndSize},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
435 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
436 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
437 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200438 {"PyUnicode_Type", (PYTHON_PROC*)&dll_PyUnicode_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200439 {"PyFloat_Type", (PYTHON_PROC*)&dll_PyFloat_Type},
440 {"PyFloat_AsDouble", (PYTHON_PROC*)&dll_PyFloat_AsDouble},
441 {"PyFloat_FromDouble", (PYTHON_PROC*)&dll_PyFloat_FromDouble},
442 {"PyImport_AddModule", (PYTHON_PROC*)&dll_PyImport_AddModule},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
444 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
445 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100446 {"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200448# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000 \
449 && SIZEOF_SIZE_T != SIZEOF_INT
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000450 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
451# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000453# endif
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100454 {"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000456 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
457 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
459 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
Bram Moolenaardb913952012-06-29 12:54:53 +0200460 {"PyObject_GetIter", (PYTHON_PROC*)&dll_PyObject_GetIter},
Bram Moolenaare7211222012-06-30 13:21:08 +0200461# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
Bram Moolenaardb913952012-06-29 12:54:53 +0200462 {"_PyObject_NextNotImplemented", (PYTHON_PROC*)&dll__PyObject_NextNotImplemented},
Bram Moolenaare7211222012-06-30 13:21:08 +0200463# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
Bram Moolenaar66b79852012-09-21 14:00:35 +0200465 {"_Py_ZeroStruct", (PYTHON_PROC*)&dll__Py_ZeroStruct},
466 {"_Py_TrueStruct", (PYTHON_PROC*)&dll__Py_TrueStruct},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
468 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
469# endif
470# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
471 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
472 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
473# endif
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200474# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +0200475 {"PyCapsule_New", (PYTHON_PROC*)&dll_PyCapsule_New},
476 {"PyCapsule_GetPointer", (PYTHON_PROC*)&dll_PyCapsule_GetPointer},
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200477# else
478 {"PyCObject_FromVoidPtr", (PYTHON_PROC*)&dll_PyCObject_FromVoidPtr},
479 {"PyCObject_AsVoidPtr", (PYTHON_PROC*)&dll_PyCObject_AsVoidPtr},
480# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481 {"", NULL},
482};
483
484/*
485 * Free python.dll
486 */
487 static void
488end_dynamic_python(void)
489{
490 if (hinstPython)
491 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200492 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 hinstPython = 0;
494 }
495}
496
497/*
498 * Load library and get all pointers.
499 * Parameter 'libname' provides name of DLL.
500 * Return OK or FAIL.
501 */
502 static int
503python_runtime_link_init(char *libname, int verbose)
504{
505 int i;
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200506 void *ucs_as_encoded_string;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100508#if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200509 /* Can't have Python and Python3 loaded at the same time.
510 * It cause a crash, because RTLD_GLOBAL is needed for
511 * standard C extension libraries of one or both python versions. */
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200512 if (python3_loaded())
513 {
Bram Moolenaar9dc93ae2011-08-28 16:00:19 +0200514 if (verbose)
515 EMSG(_("E836: This Vim cannot execute :python after using :py3"));
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200516 return FAIL;
517 }
518#endif
519
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520 if (hinstPython)
521 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200522 hinstPython = load_dll(libname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 if (!hinstPython)
524 {
525 if (verbose)
526 EMSG2(_(e_loadlib), libname);
527 return FAIL;
528 }
529
530 for (i = 0; python_funcname_table[i].ptr; ++i)
531 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200532 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 python_funcname_table[i].name)) == NULL)
534 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200535 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 hinstPython = 0;
537 if (verbose)
538 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
539 return FAIL;
540 }
541 }
Bram Moolenaarcc3e85f2012-06-29 19:14:52 +0200542
543 /* Load unicode functions separately as only the ucs2 or the ucs4 functions
544 * will be present in the library. */
545 ucs_as_encoded_string = symbol_from_dll(hinstPython,
546 "PyUnicodeUCS2_AsEncodedString");
547 if (ucs_as_encoded_string == NULL)
548 ucs_as_encoded_string = symbol_from_dll(hinstPython,
549 "PyUnicodeUCS4_AsEncodedString");
550 if (ucs_as_encoded_string != NULL)
551 py_PyUnicode_AsEncodedString = ucs_as_encoded_string;
552 else
553 {
554 close_dll(hinstPython);
555 hinstPython = 0;
556 if (verbose)
557 EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*");
558 return FAIL;
559 }
560
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561 return OK;
562}
563
564/*
565 * If python is enabled (there is installed python on Windows system) return
566 * TRUE, else FALSE.
567 */
568 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000569python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570{
571 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
572}
573
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200574/*
575 * Load the standard Python exceptions - don't import the symbols from the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 * DLL, as this can cause errors (importing data symbols is not reliable).
577 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578 static void
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200579get_exceptions(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580{
581 PyObject *exmod = PyImport_ImportModule("exceptions");
582 PyObject *exdict = PyModule_GetDict(exmod);
583 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
584 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200585 imp_PyExc_KeyError = PyDict_GetItemString(exdict, "KeyError");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
587 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
588 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
589 Py_XINCREF(imp_PyExc_AttributeError);
590 Py_XINCREF(imp_PyExc_IndexError);
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200591 Py_XINCREF(imp_PyExc_KeyError);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000592 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
593 Py_XINCREF(imp_PyExc_TypeError);
594 Py_XINCREF(imp_PyExc_ValueError);
595 Py_XDECREF(exmod);
596}
597#endif /* DYNAMIC_PYTHON */
598
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200599static PyObject *BufferNew (buf_T *);
600static PyObject *WindowNew(win_T *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200601static PyObject *DictionaryNew(dict_T *);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200602static PyObject *LineToString(const char *);
603
Bram Moolenaardb913952012-06-29 12:54:53 +0200604static int initialised = 0;
605#define PYINITIALISED initialised
606
Bram Moolenaardb913952012-06-29 12:54:53 +0200607#define DICTKEY_GET(err) \
608 if (!PyString_Check(keyObject)) \
609 { \
610 PyErr_SetString(PyExc_TypeError, _("only string keys are allowed")); \
611 return err; \
612 } \
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200613 if (PyString_AsStringAndSize(keyObject, (char **) &key, NULL) == -1) \
614 return err;
615
Bram Moolenaardb913952012-06-29 12:54:53 +0200616#define DICTKEY_UNREF
617#define DICTKEY_DECL
618
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200619#define DESTRUCTOR_FINISH(self) Py_DECREF(self);
620
621static PyObject *OutputGetattr(PyObject *, char *);
622static PyObject *BufferGetattr(PyObject *, char *);
623static PyObject *WindowGetattr(PyObject *, char *);
624static PyObject *RangeGetattr(PyObject *, char *);
625static PyObject *DictionaryGetattr(PyObject *, char*);
626static PyObject *ListGetattr(PyObject *, char *);
627static PyObject *FunctionGetattr(PyObject *, char *);
628
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200629/*
630 * Include the code shared with if_python3.c
631 */
632#include "if_py_both.h"
633
634
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635/******************************************************
636 * Internal function prototypes.
637 */
638
Bram Moolenaardb913952012-06-29 12:54:53 +0200639static PyObject *globals;
640
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641static void PythonIO_Flush(void);
642static int PythonIO_Init(void);
643static int PythonMod_Init(void);
644
645/* Utility functions for the vim/python interface
646 * ----------------------------------------------
647 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000649static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651
652/******************************************************
653 * 1. Python interpreter main program.
654 */
655
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
657typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000658#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000660#ifdef PY_CAN_RECURSE
661static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
662#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000663static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000664#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665
666/*
667 * Suspend a thread of the Python interpreter, other threads are allowed to
668 * run.
669 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000670 static void
671Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000673#ifdef PY_CAN_RECURSE
674 PyGILState_Release(pygilstate);
675#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678}
679
680/*
681 * Restore a thread of the Python interpreter, waits for other threads to
682 * block.
683 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000684 static void
685Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000687#ifdef PY_CAN_RECURSE
688 pygilstate = PyGILState_Ensure();
689#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 PyEval_RestoreThread(saved_python_thread);
691 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000693}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695 void
696python_end()
697{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000698 static int recurse = 0;
699
700 /* If a crash occurs while doing this, don't try again. */
701 if (recurse != 0)
702 return;
703
704 ++recurse;
705
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000707 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000708 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000709 Python_RestoreThread(); /* enter python */
710 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000711 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000713#else
714 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000715 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000716 Python_RestoreThread(); /* enter python */
717 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000719#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000720
721 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722}
723
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200724#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
725 int
726python_loaded()
727{
728 return (hinstPython != 0);
729}
730#endif
731
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 static int
733Python_Init(void)
734{
735 if (!initialised)
736 {
737#ifdef DYNAMIC_PYTHON
738 if (!python_enabled(TRUE))
739 {
740 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
741 goto fail;
742 }
743#endif
744
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100745#ifdef PYTHON_HOME
746 Py_SetPythonHome(PYTHON_HOME);
747#endif
748
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200749 init_structs();
750
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751#if !defined(MACOS) || defined(MACOS_X_UNIX)
752 Py_Initialize();
753#else
754 PyMac_Initialize();
755#endif
Bram Moolenaar02366252013-01-30 11:44:39 +0100756 /* Initialise threads, and below save the state using
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100757 * PyEval_SaveThread. Without the call to PyEval_SaveThread, thread
Bram Moolenaar02366252013-01-30 11:44:39 +0100758 * specific state (such as the system trace hook), will be lost
759 * between invocations of Python code. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 PyEval_InitThreads();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761#ifdef DYNAMIC_PYTHON
762 get_exceptions();
763#endif
764
765 if (PythonIO_Init())
766 goto fail;
767
768 if (PythonMod_Init())
769 goto fail;
770
Bram Moolenaardb913952012-06-29 12:54:53 +0200771 globals = PyModule_GetDict(PyImport_AddModule("__main__"));
772
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000773 /* Remove the element from sys.path that was added because of our
774 * argv[0] value in PythonMod_Init(). Previously we used an empty
775 * string, but dependinding on the OS we then get an empty entry or
776 * the current directory in sys.path. */
777 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
778
Bram Moolenaar76d711c2013-02-13 14:17:08 +0100779 /* lock is created and acquired in PyEval_InitThreads() and thread
780 * state is created in Py_Initialize()
781 * there _PyGILState_NoteThreadState() also sets gilcounter to 1
782 * (python must have threads enabled!)
783 * so the following does both: unlock GIL and save thread state in TLS
784 * without deleting thread state
785 */
786 PyEval_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787
788 initialised = 1;
789 }
790
791 return 0;
792
793fail:
794 /* We call PythonIO_Flush() here to print any Python errors.
795 * This is OK, as it is possible to call this function even
796 * if PythonIO_Init() has not completed successfully (it will
797 * not do anything in this case).
798 */
799 PythonIO_Flush();
800 return -1;
801}
802
803/*
804 * External interface
805 */
806 static void
Bram Moolenaardb913952012-06-29 12:54:53 +0200807DoPythonCommand(exarg_T *eap, const char *cmd, typval_T *rettv)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000809#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810 static int recursive = 0;
811#endif
812#if defined(MACOS) && !defined(MACOS_X_UNIX)
813 GrafPtr oldPort;
814#endif
815#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
816 char *saved_locale;
817#endif
818
819#ifndef PY_CAN_RECURSE
820 if (recursive)
821 {
822 EMSG(_("E659: Cannot invoke Python recursively"));
823 return;
824 }
825 ++recursive;
826#endif
827
828#if defined(MACOS) && !defined(MACOS_X_UNIX)
829 GetPort(&oldPort);
830 /* Check if the Python library is available */
831 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
832 goto theend;
833#endif
834 if (Python_Init())
835 goto theend;
836
Bram Moolenaardb913952012-06-29 12:54:53 +0200837 if (rettv == NULL)
838 {
839 RangeStart = eap->line1;
840 RangeEnd = eap->line2;
841 }
842 else
843 {
844 RangeStart = (PyInt) curwin->w_cursor.lnum;
845 RangeEnd = RangeStart;
846 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 Python_Release_Vim(); /* leave vim */
848
849#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
850 /* Python only works properly when the LC_NUMERIC locale is "C". */
851 saved_locale = setlocale(LC_NUMERIC, NULL);
852 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
853 saved_locale = NULL;
854 else
855 {
856 /* Need to make a copy, value may change when setting new locale. */
857 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
858 (void)setlocale(LC_NUMERIC, "C");
859 }
860#endif
861
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000863
Bram Moolenaardb913952012-06-29 12:54:53 +0200864 if (rettv == NULL)
865 PyRun_SimpleString((char *)(cmd));
866 else
867 {
868 PyObject *r;
869
870 r = PyRun_String((char *)(cmd), Py_eval_input, globals, globals);
871 if (r == NULL)
Bram Moolenaar4d369872013-02-20 16:09:43 +0100872 {
873 if (PyErr_Occurred() && !msg_silent)
874 PyErr_PrintEx(0);
Bram Moolenaardb913952012-06-29 12:54:53 +0200875 EMSG(_("E858: Eval did not return a valid python object"));
Bram Moolenaar4d369872013-02-20 16:09:43 +0100876 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200877 else
878 {
879 if (ConvertFromPyObject(r, rettv) == -1)
880 EMSG(_("E859: Failed to convert returned python object to vim value"));
881 Py_DECREF(r);
882 }
883 PyErr_Clear();
884 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
888#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
889 if (saved_locale != NULL)
890 {
891 (void)setlocale(LC_NUMERIC, saved_locale);
892 vim_free(saved_locale);
893 }
894#endif
895
896 Python_Lock_Vim(); /* enter vim */
897 PythonIO_Flush();
898#if defined(MACOS) && !defined(MACOS_X_UNIX)
899 SetPort(oldPort);
900#endif
901
902theend:
903#ifndef PY_CAN_RECURSE
904 --recursive;
905#endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200906 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907}
908
909/*
910 * ":python"
911 */
912 void
913ex_python(exarg_T *eap)
914{
915 char_u *script;
916
917 script = script_get(eap, eap->arg);
918 if (!eap->skip)
919 {
920 if (script == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200921 DoPythonCommand(eap, (char *)eap->arg, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 else
Bram Moolenaardb913952012-06-29 12:54:53 +0200923 DoPythonCommand(eap, (char *)script, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924 }
925 vim_free(script);
926}
927
928#define BUFFER_SIZE 1024
929
930/*
931 * ":pyfile"
932 */
933 void
934ex_pyfile(exarg_T *eap)
935{
936 static char buffer[BUFFER_SIZE];
937 const char *file = (char *)eap->arg;
938 char *p;
939
940 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
941 * stdio file pointer, but Vim and the Python DLL are compiled with
942 * different options under Windows, meaning that stdio pointers aren't
943 * compatible between the two. Yuk.
944 *
945 * Put the string "execfile('file')" into buffer. But, we need to
946 * escape any backslashes or single quotes in the file name, so that
947 * Python won't mangle the file name.
948 */
949 strcpy(buffer, "execfile('");
950 p = buffer + 10; /* size of "execfile('" */
951
952 while (*file && p < buffer + (BUFFER_SIZE - 3))
953 {
954 if (*file == '\\' || *file == '\'')
955 *p++ = '\\';
956 *p++ = *file++;
957 }
958
959 /* If we didn't finish the file name, we hit a buffer overflow */
960 if (*file != '\0')
961 return;
962
963 /* Put in the terminating "')" and a null */
964 *p++ = '\'';
965 *p++ = ')';
966 *p++ = '\0';
967
968 /* Execute the file */
Bram Moolenaardb913952012-06-29 12:54:53 +0200969 DoPythonCommand(eap, buffer, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970}
971
972/******************************************************
973 * 2. Python output stream: writes output via [e]msg().
974 */
975
976/* Implementation functions
977 */
978
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979 static PyObject *
980OutputGetattr(PyObject *self, char *name)
981{
982 if (strcmp(name, "softspace") == 0)
983 return PyInt_FromLong(((OutputObject *)(self))->softspace);
984
985 return Py_FindMethod(OutputMethods, self, name);
986}
987
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988/***************/
989
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990 static int
991PythonIO_Init(void)
992{
993 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +0100994 PyType_Ready(&OutputType);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200996 return PythonIO_Init_io();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997}
998
999/******************************************************
1000 * 3. Implementation of the Vim module for Python
1001 */
1002
Bram Moolenaardb913952012-06-29 12:54:53 +02001003static PyObject *ConvertToPyObject(typval_T *);
1004static int ConvertFromPyObject(PyObject *, typval_T *);
1005
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006/* Window type - Implementation functions
1007 * --------------------------------------
1008 */
1009
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
1011
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012/* Buffer type - Implementation functions
1013 * --------------------------------------
1014 */
1015
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
1017
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001018static PyInt BufferLength(PyObject *);
1019static PyObject *BufferItem(PyObject *, PyInt);
1020static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
1021static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
1022static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024/* Line range type - Implementation functions
1025 * --------------------------------------
1026 */
1027
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
1029
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001030static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
1031static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033/* Current objects type - Implementation functions
1034 * -----------------------------------------------
1035 */
1036
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001038 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar77fceb82012-09-05 18:54:48 +02001039 (binaryfunc) 0, /* BufferConcat, sq_concat, x+y */
1040 (PyIntArgFunc) 0, /* BufferRepeat, sq_repeat, x*n */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001041 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
1042 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
1043 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001044 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
1045 (objobjproc) 0,
1046#if PY_MAJOR_VERSION >= 2
1047 (binaryfunc) 0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 0,
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001049#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050};
1051
1052/* Buffer object - Implementation
1053 */
1054
1055 static PyObject *
1056BufferNew(buf_T *buf)
1057{
1058 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001059 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001060 * then we can get at it in buf_freeall() in vim. We then
1061 * need to create only ONE Python object per buffer - if
1062 * we try to create a second, just INCREF the existing one
1063 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001064 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 * Question: what to do on a buf_freeall(). We'll probably
1066 * have to either delete the Python object (DECREF it to
1067 * zero - a bad idea, as it leaves dangling refs!) or
1068 * set the buf_T * value to an invalid value (-1?), which
1069 * means we need checks in all access functions... Bah.
1070 */
1071
1072 BufferObject *self;
1073
Bram Moolenaare344bea2005-09-01 20:46:49 +00001074 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001076 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077 Py_INCREF(self);
1078 }
1079 else
1080 {
1081 self = PyObject_NEW(BufferObject, &BufferType);
1082 if (self == NULL)
1083 return NULL;
1084 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001085 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 }
1087
1088 return (PyObject *)(self);
1089}
1090
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 static PyObject *
1092BufferGetattr(PyObject *self, char *name)
1093{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001094 PyObject *r;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001096 if (CheckBuffer((BufferObject *)(self)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 return NULL;
1098
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001099 r = BufferAttr((BufferObject *)(self), name);
1100 if (r || PyErr_Occurred())
1101 return r;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 else
1103 return Py_FindMethod(BufferMethods, self, name);
1104}
1105
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106/******************/
1107
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001108 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109BufferLength(PyObject *self)
1110{
1111 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1112 if (CheckBuffer((BufferObject *)(self)))
1113 return -1; /* ??? */
1114
1115 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1116}
1117
1118 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001119BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120{
1121 return RBItem((BufferObject *)(self), n, 1,
1122 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1123}
1124
1125 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001126BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127{
1128 return RBSlice((BufferObject *)(self), lo, hi, 1,
1129 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1130}
1131
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001132 static PyInt
1133BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001135 return RBAsItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001136 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137 NULL);
1138}
1139
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001140 static PyInt
1141BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001143 return RBAsSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001144 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145 NULL);
1146}
1147
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148static PySequenceMethods RangeAsSeq = {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001149 (PyInquiry) RangeLength, /* sq_length, len(x) */
1150 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
1151 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1152 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1153 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1154 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1155 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
1156 (objobjproc) 0,
1157#if PY_MAJOR_VERSION >= 2
1158 (binaryfunc) 0,
1159 0,
1160#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161};
1162
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163/* Line range object - Implementation
1164 */
1165
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166 static PyObject *
1167RangeGetattr(PyObject *self, char *name)
1168{
1169 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001170 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001172 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173 else
1174 return Py_FindMethod(RangeMethods, self, name);
1175}
1176
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177/****************/
1178
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001179 static PyInt
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001180RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001182 return RBAsItem(((RangeObject *)(self))->buf, n, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 ((RangeObject *)(self))->start,
1184 ((RangeObject *)(self))->end,
1185 &((RangeObject *)(self))->end);
1186}
1187
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001188 static PyInt
1189RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001191 return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 ((RangeObject *)(self))->start,
1193 ((RangeObject *)(self))->end,
1194 &((RangeObject *)(self))->end);
1195}
1196
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197/* Buffer list object - Definitions
1198 */
1199
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001201 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001203 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1204 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1205 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1206 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001207 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1208 (objobjproc) 0,
1209#if PY_MAJOR_VERSION >= 2
1210 (binaryfunc) 0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 0,
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001212#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213};
1214
1215/* Window object - Implementation
1216 */
1217
1218 static PyObject *
1219WindowNew(win_T *win)
1220{
1221 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001222 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 * then we can get at it in win_free() in vim. We then
1224 * need to create only ONE Python object per window - if
1225 * we try to create a second, just INCREF the existing one
1226 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001227 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001228 * On a win_free() we set the Python object's win_T* field
1229 * to an invalid value. We trap all uses of a window
1230 * object, and reject them if the win_T* field is invalid.
1231 */
1232
1233 WindowObject *self;
1234
Bram Moolenaare344bea2005-09-01 20:46:49 +00001235 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001237 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 Py_INCREF(self);
1239 }
1240 else
1241 {
1242 self = PyObject_NEW(WindowObject, &WindowType);
1243 if (self == NULL)
1244 return NULL;
1245 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001246 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001247 }
1248
1249 return (PyObject *)(self);
1250}
1251
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252 static PyObject *
1253WindowGetattr(PyObject *self, char *name)
1254{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001255 PyObject *r;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001256
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001257 if (CheckWindow((WindowObject *)(self)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001258 return NULL;
1259
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001260 r = WindowAttr((WindowObject *)(self), name);
1261 if (r || PyErr_Occurred())
1262 return r;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263 else
1264 return Py_FindMethod(WindowMethods, self, name);
1265}
1266
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267/* Window list object - Definitions
1268 */
1269
Bram Moolenaar071d4272004-06-13 20:20:40 +00001270static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001271 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001273 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1274 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
1275 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1276 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001277 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
1278 (objobjproc) 0,
1279#if PY_MAJOR_VERSION >= 2
1280 (binaryfunc) 0,
1281 0,
1282#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283};
1284
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285/* External interface
1286 */
1287
1288 void
1289python_buffer_free(buf_T *buf)
1290{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001291 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001293 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001295 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296 }
1297}
1298
1299#if defined(FEAT_WINDOWS) || defined(PROTO)
1300 void
1301python_window_free(win_T *win)
1302{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001303 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001305 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001307 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 }
1309}
1310#endif
1311
1312static BufListObject TheBufferList =
1313{
1314 PyObject_HEAD_INIT(&BufListType)
1315};
1316
1317static WinListObject TheWindowList =
1318{
1319 PyObject_HEAD_INIT(&WinListType)
1320};
1321
1322static CurrentObject TheCurrent =
1323{
1324 PyObject_HEAD_INIT(&CurrentType)
1325};
1326
1327 static int
1328PythonMod_Init(void)
1329{
1330 PyObject *mod;
1331 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00001332 /* The special value is removed from sys.path in Python_Init(). */
1333 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00001334
1335 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +01001336 PyType_Ready(&BufferType);
1337 PyType_Ready(&RangeType);
1338 PyType_Ready(&WindowType);
1339 PyType_Ready(&BufListType);
1340 PyType_Ready(&WinListType);
1341 PyType_Ready(&CurrentType);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342
1343 /* Set sys.argv[] to avoid a crash in warn(). */
1344 PySys_SetArgv(1, argv);
1345
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001346 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001347 dict = PyModule_GetDict(mod);
1348
1349 VimError = Py_BuildValue("s", "vim.error");
1350
1351 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00001352 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
1353 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
1354 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar66b79852012-09-21 14:00:35 +02001355 PyDict_SetItemString(dict, "VAR_LOCKED", PyInt_FromLong(VAR_LOCKED));
1356 PyDict_SetItemString(dict, "VAR_FIXED", PyInt_FromLong(VAR_FIXED));
1357 PyDict_SetItemString(dict, "VAR_SCOPE", PyInt_FromLong(VAR_SCOPE));
1358 PyDict_SetItemString(dict, "VAR_DEF_SCOPE", PyInt_FromLong(VAR_DEF_SCOPE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001359
1360 if (PyErr_Occurred())
1361 return -1;
1362
1363 return 0;
1364}
1365
1366/*************************************************************************
1367 * 4. Utility functions for handling the interface between Vim and Python.
1368 */
1369
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370/* Convert a Vim line into a Python string.
1371 * All internal newlines are replaced by null characters.
1372 *
1373 * On errors, the Python exception data is set, and NULL is returned.
1374 */
1375 static PyObject *
1376LineToString(const char *str)
1377{
1378 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001379 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380 char *p;
1381
1382 /* Allocate an Python string object, with uninitialised contents. We
1383 * must do it this way, so that we can modify the string in place
1384 * later. See the Python source, Objects/stringobject.c for details.
1385 */
1386 result = PyString_FromStringAndSize(NULL, len);
1387 if (result == NULL)
1388 return NULL;
1389
1390 p = PyString_AsString(result);
1391
1392 while (*str)
1393 {
1394 if (*str == '\n')
1395 *p = '\0';
1396 else
1397 *p = *str;
1398
1399 ++p;
1400 ++str;
1401 }
1402
1403 return result;
1404}
1405
Bram Moolenaardb913952012-06-29 12:54:53 +02001406 static PyObject *
1407DictionaryGetattr(PyObject *self, char *name)
1408{
Bram Moolenaar66b79852012-09-21 14:00:35 +02001409 DictionaryObject *this = ((DictionaryObject *) (self));
1410
1411 if (strcmp(name, "locked") == 0)
1412 return PyInt_FromLong(this->dict->dv_lock);
1413 else if (strcmp(name, "scope") == 0)
1414 return PyInt_FromLong(this->dict->dv_scope);
1415
Bram Moolenaardb913952012-06-29 12:54:53 +02001416 return Py_FindMethod(DictionaryMethods, self, name);
1417}
1418
Bram Moolenaardb913952012-06-29 12:54:53 +02001419static PySequenceMethods ListAsSeq = {
1420 (PyInquiry) ListLength,
1421 (binaryfunc) 0,
1422 (PyIntArgFunc) 0,
1423 (PyIntArgFunc) ListItem,
1424 (PyIntIntArgFunc) ListSlice,
1425 (PyIntObjArgProc) ListAssItem,
1426 (PyIntIntObjArgProc) ListAssSlice,
1427 (objobjproc) 0,
1428#if PY_MAJOR_VERSION >= 2
1429 (binaryfunc) ListConcatInPlace,
1430 0,
1431#endif
1432};
1433
Bram Moolenaardb913952012-06-29 12:54:53 +02001434 static PyObject *
1435ListGetattr(PyObject *self, char *name)
1436{
Bram Moolenaar66b79852012-09-21 14:00:35 +02001437 if (strcmp(name, "locked") == 0)
1438 return PyInt_FromLong(((ListObject *)(self))->list->lv_lock);
1439
Bram Moolenaardb913952012-06-29 12:54:53 +02001440 return Py_FindMethod(ListMethods, self, name);
1441}
1442
Bram Moolenaardb913952012-06-29 12:54:53 +02001443 static PyObject *
1444FunctionGetattr(PyObject *self, char *name)
1445{
1446 FunctionObject *this = (FunctionObject *)(self);
1447
1448 if (strcmp(name, "name") == 0)
1449 return PyString_FromString((char *)(this->name));
1450 else
1451 return Py_FindMethod(FunctionMethods, self, name);
1452}
1453
1454 void
1455do_pyeval (char_u *str, typval_T *rettv)
1456{
1457 DoPythonCommand(NULL, (char *) str, rettv);
1458 switch(rettv->v_type)
1459 {
1460 case VAR_DICT: ++rettv->vval.v_dict->dv_refcount; break;
1461 case VAR_LIST: ++rettv->vval.v_list->lv_refcount; break;
1462 case VAR_FUNC: func_ref(rettv->vval.v_string); break;
Bram Moolenaar77fceb82012-09-05 18:54:48 +02001463 case VAR_UNKNOWN:
1464 rettv->v_type = VAR_NUMBER;
1465 rettv->vval.v_number = 0;
1466 break;
Bram Moolenaardb913952012-06-29 12:54:53 +02001467 }
1468}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469
1470/* Don't generate a prototype for the next function, it generates an error on
1471 * newer Python versions. */
1472#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
1473
1474 char *
1475Py_GetProgramName(void)
1476{
1477 return "vim";
1478}
1479#endif /* Python 1.4 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001480
Bram Moolenaardb913952012-06-29 12:54:53 +02001481 void
1482set_ref_in_python (int copyID)
1483{
1484 set_ref_in_py(copyID);
1485}