blob: 0c10f8dbc717ccbdf1e98a19100cb00250303e02 [file] [log] [blame]
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001/* vi:set ts=8 sts=4 sw=4:
2 *
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/*
21 * Roland Puntaier 2009/sept/16:
22 * Adaptations to support both python3.x and python2.x
23 */
24
Bram Moolenaar0c1f3f42011-02-25 15:18:50 +010025/* uncomment this if used with the debug version of python */
26/* #define Py_DEBUG */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +020027
28#include "vim.h"
29
30#include <limits.h>
31
32/* Python.h defines _POSIX_THREADS itself (if needed) */
33#ifdef _POSIX_THREADS
34# undef _POSIX_THREADS
35#endif
36
Bram Moolenaard68554d2010-07-25 13:43:20 +020037#if defined(_WIN32) && defined(HAVE_FCNTL_H)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +020038# undef HAVE_FCNTL_H
39#endif
40
41#ifdef _DEBUG
42# undef _DEBUG
43#endif
44
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +020045#define PY_SSIZE_T_CLEAN
46
47#ifdef F_BLANK
48# undef F_BLANK
49#endif
50
Bram Moolenaar6df6f472010-07-18 18:04:50 +020051#ifdef HAVE_STDARG_H
52# undef HAVE_STDARG_H /* Python's config.h defines it as well. */
53#endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +020054#ifdef _POSIX_C_SOURCE /* defined in feature.h */
55# undef _POSIX_C_SOURCE
56#endif
Bram Moolenaar6df6f472010-07-18 18:04:50 +020057#ifdef _XOPEN_SOURCE
58# undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
59#endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +020060
61#include <Python.h>
62#if defined(MACOS) && !defined(MACOS_X_UNIX)
63# include "macglue.h"
64# include <CodeFragments.h>
65#endif
66#undef main /* Defined in python.h - aargh */
67#undef HAVE_FCNTL_H /* Clash with os_win32.h */
68
69static void init_structs(void);
70
Bram Moolenaar3d64a312011-07-15 15:54:44 +020071/* The "surrogateescape" error handler is new in Python 3.1 */
72#if PY_VERSION_HEX >= 0x030100f0
73# define CODEC_ERROR_HANDLER "surrogateescape"
74#else
75# define CODEC_ERROR_HANDLER NULL
76#endif
77
Bram Moolenaar2afa3232012-06-29 16:28:28 +020078/* Python 3 does not support CObjects, always use Capsules */
79#define PY_USE_CAPSULE
80
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020081#define PyInt Py_ssize_t
Bram Moolenaarca8a4df2010-07-31 19:54:14 +020082#define PyString_Check(obj) PyUnicode_Check(obj)
Bram Moolenaardb913952012-06-29 12:54:53 +020083#define PyString_AsBytes(obj) PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, CODEC_ERROR_HANDLER)
Bram Moolenaar19e60942011-06-19 00:27:51 +020084#define PyString_FreeBytes(obj) Py_XDECREF(bytes)
85#define PyString_AsString(obj) PyBytes_AsString(obj)
86#define PyString_Size(obj) PyBytes_GET_SIZE(bytes)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +020087#define PyString_FromString(repr) PyUnicode_FromString(repr)
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +020088#define PyString_AsStringAndSize(obj, buffer, len) PyBytes_AsStringAndSize(obj, buffer, len)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020089
Bram Moolenaar0c1f3f42011-02-25 15:18:50 +010090#if defined(DYNAMIC_PYTHON3) || defined(PROTO)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +020091
Bram Moolenaarb61f95c2010-08-09 22:06:13 +020092# ifndef WIN3264
93# include <dlfcn.h>
94# define FARPROC void*
95# define HINSTANCE void*
Bram Moolenaar644d37b2010-11-16 19:26:02 +010096# if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
Bram Moolenaarb61f95c2010-08-09 22:06:13 +020097# define load_dll(n) dlopen((n), RTLD_LAZY)
98# else
99# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
100# endif
101# define close_dll dlclose
102# define symbol_from_dll dlsym
103# else
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200104# define load_dll vimLoadLib
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200105# define close_dll FreeLibrary
106# define symbol_from_dll GetProcAddress
107# endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200108/*
109 * Wrapper defines
110 */
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200111# undef PyArg_Parse
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200112# define PyArg_Parse py3_PyArg_Parse
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200113# undef PyArg_ParseTuple
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200114# define PyArg_ParseTuple py3_PyArg_ParseTuple
Bram Moolenaar19e60942011-06-19 00:27:51 +0200115# define PyMem_Free py3_PyMem_Free
Bram Moolenaardb913952012-06-29 12:54:53 +0200116# define PyMem_Malloc py3_PyMem_Malloc
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200117# define PyDict_SetItemString py3_PyDict_SetItemString
118# define PyErr_BadArgument py3_PyErr_BadArgument
119# define PyErr_Clear py3_PyErr_Clear
120# define PyErr_NoMemory py3_PyErr_NoMemory
121# define PyErr_Occurred py3_PyErr_Occurred
122# define PyErr_SetNone py3_PyErr_SetNone
123# define PyErr_SetString py3_PyErr_SetString
124# define PyEval_InitThreads py3_PyEval_InitThreads
125# define PyEval_RestoreThread py3_PyEval_RestoreThread
126# define PyEval_SaveThread py3_PyEval_SaveThread
127# define PyGILState_Ensure py3_PyGILState_Ensure
128# define PyGILState_Release py3_PyGILState_Release
129# define PyLong_AsLong py3_PyLong_AsLong
130# define PyLong_FromLong py3_PyLong_FromLong
131# define PyList_GetItem py3_PyList_GetItem
132# define PyList_Append py3_PyList_Append
133# define PyList_New py3_PyList_New
134# define PyList_SetItem py3_PyList_SetItem
135# define PyList_Size py3_PyList_Size
Bram Moolenaardb913952012-06-29 12:54:53 +0200136# define PySequence_Check py3_PySequence_Check
137# define PySequence_Size py3_PySequence_Size
138# define PySequence_GetItem py3_PySequence_GetItem
139# define PyTuple_Size py3_PyTuple_Size
140# define PyTuple_GetItem py3_PyTuple_GetItem
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200141# define PySlice_GetIndicesEx py3_PySlice_GetIndicesEx
142# define PyImport_ImportModule py3_PyImport_ImportModule
Bram Moolenaardb913952012-06-29 12:54:53 +0200143# define PyImport_AddModule py3_PyImport_AddModule
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200144# define PyObject_Init py3__PyObject_Init
145# define PyDict_New py3_PyDict_New
146# define PyDict_GetItemString py3_PyDict_GetItemString
Bram Moolenaardb913952012-06-29 12:54:53 +0200147# define PyDict_Next py3_PyDict_Next
148# define PyMapping_Check py3_PyMapping_Check
149# define PyMapping_Items py3_PyMapping_Items
150# define PyIter_Next py3_PyIter_Next
151# define PyObject_GetIter py3_PyObject_GetIter
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200152# define PyModule_GetDict py3_PyModule_GetDict
153#undef PyRun_SimpleString
154# define PyRun_SimpleString py3_PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200155#undef PyRun_String
156# define PyRun_String py3_PyRun_String
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200157# define PySys_SetObject py3_PySys_SetObject
158# define PySys_SetArgv py3_PySys_SetArgv
159# define PyType_Type (*py3_PyType_Type)
160# define PyType_Ready py3_PyType_Ready
161#undef Py_BuildValue
162# define Py_BuildValue py3_Py_BuildValue
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100163# define Py_SetPythonHome py3_Py_SetPythonHome
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200164# define Py_Initialize py3_Py_Initialize
165# define Py_Finalize py3_Py_Finalize
166# define Py_IsInitialized py3_Py_IsInitialized
167# define _Py_NoneStruct (*py3__Py_NoneStruct)
Bram Moolenaardb913952012-06-29 12:54:53 +0200168# define _PyObject_NextNotImplemented (*py3__PyObject_NextNotImplemented)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200169# define PyModule_AddObject py3_PyModule_AddObject
170# define PyImport_AppendInittab py3_PyImport_AppendInittab
171# define _PyUnicode_AsString py3__PyUnicode_AsString
Bram Moolenaar19e60942011-06-19 00:27:51 +0200172# undef PyUnicode_AsEncodedString
173# define PyUnicode_AsEncodedString py3_PyUnicode_AsEncodedString
174# undef PyBytes_AsString
175# define PyBytes_AsString py3_PyBytes_AsString
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200176# define PyBytes_AsStringAndSize py3_PyBytes_AsStringAndSize
Bram Moolenaardb913952012-06-29 12:54:53 +0200177# undef PyBytes_FromString
178# define PyBytes_FromString py3_PyBytes_FromString
179# define PyFloat_FromDouble py3_PyFloat_FromDouble
180# define PyFloat_AsDouble py3_PyFloat_AsDouble
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200181# define PyObject_GenericGetAttr py3_PyObject_GenericGetAttr
182# define PySlice_Type (*py3_PySlice_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200183# define PyFloat_Type (*py3_PyFloat_Type)
Bram Moolenaar19e60942011-06-19 00:27:51 +0200184# define PyErr_NewException py3_PyErr_NewException
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200185# ifdef Py_DEBUG
186# define _Py_NegativeRefcount py3__Py_NegativeRefcount
187# define _Py_RefTotal (*py3__Py_RefTotal)
188# define _Py_Dealloc py3__Py_Dealloc
189# define _PyObject_DebugMalloc py3__PyObject_DebugMalloc
190# define _PyObject_DebugFree py3__PyObject_DebugFree
191# else
192# define PyObject_Malloc py3_PyObject_Malloc
193# define PyObject_Free py3_PyObject_Free
194# endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200195# define PyType_GenericAlloc py3_PyType_GenericAlloc
196# define PyType_GenericNew py3_PyType_GenericNew
197# define PyModule_Create2 py3_PyModule_Create2
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200198# undef PyUnicode_FromString
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200199# define PyUnicode_FromString py3_PyUnicode_FromString
Bram Moolenaar19e60942011-06-19 00:27:51 +0200200# undef PyUnicode_Decode
201# define PyUnicode_Decode py3_PyUnicode_Decode
Bram Moolenaardb913952012-06-29 12:54:53 +0200202# define PyType_IsSubtype py3_PyType_IsSubtype
203# define PyCapsule_New py3_PyCapsule_New
204# define PyCapsule_GetPointer py3_PyCapsule_GetPointer
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200205
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200206# ifdef Py_DEBUG
207# undef PyObject_NEW
208# define PyObject_NEW(type, typeobj) \
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200209( (type *) PyObject_Init( \
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200210 (PyObject *) _PyObject_DebugMalloc( _PyObject_SIZE(typeobj) ), (typeobj)) )
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200211# endif
212
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200213/*
214 * Pointers for dynamic link
215 */
216static int (*py3_PySys_SetArgv)(int, wchar_t **);
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100217static void (*py3_Py_SetPythonHome)(wchar_t *home);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200218static void (*py3_Py_Initialize)(void);
219static PyObject* (*py3_PyList_New)(Py_ssize_t size);
220static PyGILState_STATE (*py3_PyGILState_Ensure)(void);
221static void (*py3_PyGILState_Release)(PyGILState_STATE);
222static int (*py3_PySys_SetObject)(char *, PyObject *);
223static PyObject* (*py3_PyList_Append)(PyObject *, PyObject *);
224static Py_ssize_t (*py3_PyList_Size)(PyObject *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200225static int (*py3_PySequence_Check)(PyObject *);
226static Py_ssize_t (*py3_PySequence_Size)(PyObject *);
227static PyObject* (*py3_PySequence_GetItem)(PyObject *, Py_ssize_t);
228static Py_ssize_t (*py3_PyTuple_Size)(PyObject *);
229static PyObject* (*py3_PyTuple_GetItem)(PyObject *, Py_ssize_t);
230static int (*py3_PyMapping_Check)(PyObject *);
231static PyObject* (*py3_PyMapping_Items)(PyObject *);
Bram Moolenaar314ed4b2011-09-14 18:59:39 +0200232static int (*py3_PySlice_GetIndicesEx)(PyObject *r, Py_ssize_t length,
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200233 Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200234static PyObject* (*py3_PyErr_NoMemory)(void);
235static void (*py3_Py_Finalize)(void);
236static void (*py3_PyErr_SetString)(PyObject *, const char *);
237static int (*py3_PyRun_SimpleString)(char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200238static PyObject* (*py3_PyRun_String)(char *, int, PyObject *, PyObject *);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200239static PyObject* (*py3_PyList_GetItem)(PyObject *, Py_ssize_t);
240static PyObject* (*py3_PyImport_ImportModule)(const char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200241static PyObject* (*py3_PyImport_AddModule)(const char *);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200242static int (*py3_PyErr_BadArgument)(void);
243static PyTypeObject* py3_PyType_Type;
244static PyObject* (*py3_PyErr_Occurred)(void);
245static PyObject* (*py3_PyModule_GetDict)(PyObject *);
246static int (*py3_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *);
247static PyObject* (*py3_PyDict_GetItemString)(PyObject *, const char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200248static int (*py3_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200249static PyObject* (*py3_PyLong_FromLong)(long);
250static PyObject* (*py3_PyDict_New)(void);
Bram Moolenaardb913952012-06-29 12:54:53 +0200251static PyObject* (*py3_PyIter_Next)(PyObject *);
252static PyObject* (*py3_PyObject_GetIter)(PyObject *);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200253static PyObject* (*py3_Py_BuildValue)(char *, ...);
254static int (*py3_PyType_Ready)(PyTypeObject *type);
255static int (*py3_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
256static PyObject* (*py3_PyUnicode_FromString)(const char *u);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200257static PyObject* (*py3_PyUnicode_Decode)(const char *u, Py_ssize_t size,
258 const char *encoding, const char *errors);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200259static long (*py3_PyLong_AsLong)(PyObject *);
260static void (*py3_PyErr_SetNone)(PyObject *);
261static void (*py3_PyEval_InitThreads)(void);
262static void(*py3_PyEval_RestoreThread)(PyThreadState *);
263static PyThreadState*(*py3_PyEval_SaveThread)(void);
264static int (*py3_PyArg_Parse)(PyObject *, char *, ...);
265static int (*py3_PyArg_ParseTuple)(PyObject *, char *, ...);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200266static int (*py3_PyMem_Free)(void *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200267static void* (*py3_PyMem_Malloc)(size_t);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200268static int (*py3_Py_IsInitialized)(void);
269static void (*py3_PyErr_Clear)(void);
270static PyObject*(*py3__PyObject_Init)(PyObject *, PyTypeObject *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200271static iternextfunc py3__PyObject_NextNotImplemented;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200272static PyObject* py3__Py_NoneStruct;
273static int (*py3_PyModule_AddObject)(PyObject *m, const char *name, PyObject *o);
274static int (*py3_PyImport_AppendInittab)(const char *name, PyObject* (*initfunc)(void));
275static char* (*py3__PyUnicode_AsString)(PyObject *unicode);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200276static PyObject* (*py3_PyUnicode_AsEncodedString)(PyObject *unicode, const char* encoding, const char* errors);
277static char* (*py3_PyBytes_AsString)(PyObject *bytes);
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200278static int (*py3_PyBytes_AsStringAndSize)(PyObject *bytes, char **buffer, int *length);
Bram Moolenaardb913952012-06-29 12:54:53 +0200279static PyObject* (*py3_PyBytes_FromString)(char *str);
280static PyObject* (*py3_PyFloat_FromDouble)(double num);
281static double (*py3_PyFloat_AsDouble)(PyObject *);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200282static PyObject* (*py3_PyObject_GenericGetAttr)(PyObject *obj, PyObject *name);
283static PyObject* (*py3_PyModule_Create2)(struct PyModuleDef* module, int module_api_version);
284static PyObject* (*py3_PyType_GenericAlloc)(PyTypeObject *type, Py_ssize_t nitems);
285static PyObject* (*py3_PyType_GenericNew)(PyTypeObject *type, PyObject *args, PyObject *kwds);
286static PyTypeObject* py3_PySlice_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200287static PyTypeObject* py3_PyFloat_Type;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200288static PyObject* (*py3_PyErr_NewException)(char *name, PyObject *base, PyObject *dict);
Bram Moolenaardb913952012-06-29 12:54:53 +0200289static PyObject* (*py3_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
290static void* (*py3_PyCapsule_GetPointer)(PyObject *, char *);
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200291# ifdef Py_DEBUG
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200292 static void (*py3__Py_NegativeRefcount)(const char *fname, int lineno, PyObject *op);
293 static Py_ssize_t* py3__Py_RefTotal;
294 static void (*py3__Py_Dealloc)(PyObject *obj);
295 static void (*py3__PyObject_DebugFree)(void*);
296 static void* (*py3__PyObject_DebugMalloc)(size_t);
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200297# else
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200298 static void (*py3_PyObject_Free)(void*);
299 static void* (*py3_PyObject_Malloc)(size_t);
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200300# endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200301static int (*py3_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200302
303static HINSTANCE hinstPy3 = 0; /* Instance of python.dll */
304
305/* Imported exception objects */
306static PyObject *p3imp_PyExc_AttributeError;
307static PyObject *p3imp_PyExc_IndexError;
308static PyObject *p3imp_PyExc_KeyboardInterrupt;
309static PyObject *p3imp_PyExc_TypeError;
310static PyObject *p3imp_PyExc_ValueError;
311
312# define PyExc_AttributeError p3imp_PyExc_AttributeError
313# define PyExc_IndexError p3imp_PyExc_IndexError
314# define PyExc_KeyboardInterrupt p3imp_PyExc_KeyboardInterrupt
315# define PyExc_TypeError p3imp_PyExc_TypeError
316# define PyExc_ValueError p3imp_PyExc_ValueError
317
318/*
319 * Table of name to function pointer of python.
320 */
321# define PYTHON_PROC FARPROC
322static struct
323{
324 char *name;
325 PYTHON_PROC *ptr;
326} py3_funcname_table[] =
327{
328 {"PySys_SetArgv", (PYTHON_PROC*)&py3_PySys_SetArgv},
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100329 {"Py_SetPythonHome", (PYTHON_PROC*)&py3_Py_SetPythonHome},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200330 {"Py_Initialize", (PYTHON_PROC*)&py3_Py_Initialize},
331 {"PyArg_ParseTuple", (PYTHON_PROC*)&py3_PyArg_ParseTuple},
Bram Moolenaar19e60942011-06-19 00:27:51 +0200332 {"PyMem_Free", (PYTHON_PROC*)&py3_PyMem_Free},
Bram Moolenaardb913952012-06-29 12:54:53 +0200333 {"PyMem_Malloc", (PYTHON_PROC*)&py3_PyMem_Malloc},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200334 {"PyList_New", (PYTHON_PROC*)&py3_PyList_New},
335 {"PyGILState_Ensure", (PYTHON_PROC*)&py3_PyGILState_Ensure},
336 {"PyGILState_Release", (PYTHON_PROC*)&py3_PyGILState_Release},
337 {"PySys_SetObject", (PYTHON_PROC*)&py3_PySys_SetObject},
338 {"PyList_Append", (PYTHON_PROC*)&py3_PyList_Append},
339 {"PyList_Size", (PYTHON_PROC*)&py3_PyList_Size},
Bram Moolenaardb913952012-06-29 12:54:53 +0200340 {"PySequence_Check", (PYTHON_PROC*)&py3_PySequence_Check},
341 {"PySequence_Size", (PYTHON_PROC*)&py3_PySequence_Size},
342 {"PySequence_GetItem", (PYTHON_PROC*)&py3_PySequence_GetItem},
343 {"PyTuple_Size", (PYTHON_PROC*)&py3_PyTuple_Size},
344 {"PyTuple_GetItem", (PYTHON_PROC*)&py3_PyTuple_GetItem},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200345 {"PySlice_GetIndicesEx", (PYTHON_PROC*)&py3_PySlice_GetIndicesEx},
346 {"PyErr_NoMemory", (PYTHON_PROC*)&py3_PyErr_NoMemory},
347 {"Py_Finalize", (PYTHON_PROC*)&py3_Py_Finalize},
348 {"PyErr_SetString", (PYTHON_PROC*)&py3_PyErr_SetString},
349 {"PyRun_SimpleString", (PYTHON_PROC*)&py3_PyRun_SimpleString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200350 {"PyRun_String", (PYTHON_PROC*)&py3_PyRun_String},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200351 {"PyList_GetItem", (PYTHON_PROC*)&py3_PyList_GetItem},
352 {"PyImport_ImportModule", (PYTHON_PROC*)&py3_PyImport_ImportModule},
Bram Moolenaardb913952012-06-29 12:54:53 +0200353 {"PyImport_AddModule", (PYTHON_PROC*)&py3_PyImport_AddModule},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200354 {"PyErr_BadArgument", (PYTHON_PROC*)&py3_PyErr_BadArgument},
355 {"PyType_Type", (PYTHON_PROC*)&py3_PyType_Type},
356 {"PyErr_Occurred", (PYTHON_PROC*)&py3_PyErr_Occurred},
357 {"PyModule_GetDict", (PYTHON_PROC*)&py3_PyModule_GetDict},
358 {"PyList_SetItem", (PYTHON_PROC*)&py3_PyList_SetItem},
359 {"PyDict_GetItemString", (PYTHON_PROC*)&py3_PyDict_GetItemString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200360 {"PyDict_Next", (PYTHON_PROC*)&py3_PyDict_Next},
361 {"PyMapping_Check", (PYTHON_PROC*)&py3_PyMapping_Check},
362 {"PyMapping_Items", (PYTHON_PROC*)&py3_PyMapping_Items},
363 {"PyIter_Next", (PYTHON_PROC*)&py3_PyIter_Next},
364 {"PyObject_GetIter", (PYTHON_PROC*)&py3_PyObject_GetIter},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200365 {"PyLong_FromLong", (PYTHON_PROC*)&py3_PyLong_FromLong},
366 {"PyDict_New", (PYTHON_PROC*)&py3_PyDict_New},
367 {"Py_BuildValue", (PYTHON_PROC*)&py3_Py_BuildValue},
368 {"PyType_Ready", (PYTHON_PROC*)&py3_PyType_Ready},
369 {"PyDict_SetItemString", (PYTHON_PROC*)&py3_PyDict_SetItemString},
370 {"PyLong_AsLong", (PYTHON_PROC*)&py3_PyLong_AsLong},
371 {"PyErr_SetNone", (PYTHON_PROC*)&py3_PyErr_SetNone},
372 {"PyEval_InitThreads", (PYTHON_PROC*)&py3_PyEval_InitThreads},
373 {"PyEval_RestoreThread", (PYTHON_PROC*)&py3_PyEval_RestoreThread},
374 {"PyEval_SaveThread", (PYTHON_PROC*)&py3_PyEval_SaveThread},
375 {"PyArg_Parse", (PYTHON_PROC*)&py3_PyArg_Parse},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200376 {"Py_IsInitialized", (PYTHON_PROC*)&py3_Py_IsInitialized},
Bram Moolenaardb913952012-06-29 12:54:53 +0200377 {"_PyObject_NextNotImplemented", (PYTHON_PROC*)&py3__PyObject_NextNotImplemented},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200378 {"_Py_NoneStruct", (PYTHON_PROC*)&py3__Py_NoneStruct},
379 {"PyErr_Clear", (PYTHON_PROC*)&py3_PyErr_Clear},
380 {"PyObject_Init", (PYTHON_PROC*)&py3__PyObject_Init},
381 {"PyModule_AddObject", (PYTHON_PROC*)&py3_PyModule_AddObject},
382 {"PyImport_AppendInittab", (PYTHON_PROC*)&py3_PyImport_AppendInittab},
383 {"_PyUnicode_AsString", (PYTHON_PROC*)&py3__PyUnicode_AsString},
Bram Moolenaar19e60942011-06-19 00:27:51 +0200384 {"PyBytes_AsString", (PYTHON_PROC*)&py3_PyBytes_AsString},
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200385 {"PyBytes_AsStringAndSize", (PYTHON_PROC*)&py3_PyBytes_AsStringAndSize},
Bram Moolenaardb913952012-06-29 12:54:53 +0200386 {"PyBytes_FromString", (PYTHON_PROC*)&py3_PyBytes_FromString},
387 {"PyFloat_FromDouble", (PYTHON_PROC*)&py3_PyFloat_FromDouble},
388 {"PyFloat_AsDouble", (PYTHON_PROC*)&py3_PyFloat_AsDouble},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200389 {"PyObject_GenericGetAttr", (PYTHON_PROC*)&py3_PyObject_GenericGetAttr},
390 {"PyModule_Create2", (PYTHON_PROC*)&py3_PyModule_Create2},
391 {"PyType_GenericAlloc", (PYTHON_PROC*)&py3_PyType_GenericAlloc},
392 {"PyType_GenericNew", (PYTHON_PROC*)&py3_PyType_GenericNew},
393 {"PySlice_Type", (PYTHON_PROC*)&py3_PySlice_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200394 {"PyFloat_Type", (PYTHON_PROC*)&py3_PyFloat_Type},
Bram Moolenaar19e60942011-06-19 00:27:51 +0200395 {"PyErr_NewException", (PYTHON_PROC*)&py3_PyErr_NewException},
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200396# ifdef Py_DEBUG
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200397 {"_Py_NegativeRefcount", (PYTHON_PROC*)&py3__Py_NegativeRefcount},
398 {"_Py_RefTotal", (PYTHON_PROC*)&py3__Py_RefTotal},
399 {"_Py_Dealloc", (PYTHON_PROC*)&py3__Py_Dealloc},
400 {"_PyObject_DebugFree", (PYTHON_PROC*)&py3__PyObject_DebugFree},
401 {"_PyObject_DebugMalloc", (PYTHON_PROC*)&py3__PyObject_DebugMalloc},
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200402# else
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200403 {"PyObject_Malloc", (PYTHON_PROC*)&py3_PyObject_Malloc},
404 {"PyObject_Free", (PYTHON_PROC*)&py3_PyObject_Free},
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200405# endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200406 {"PyType_IsSubtype", (PYTHON_PROC*)&py3_PyType_IsSubtype},
407 {"PyCapsule_New", (PYTHON_PROC*)&py3_PyCapsule_New},
408 {"PyCapsule_GetPointer", (PYTHON_PROC*)&py3_PyCapsule_GetPointer},
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200409 {"", NULL},
410};
411
412/*
413 * Free python.dll
414 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200415 static void
416end_dynamic_python3(void)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200417{
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200418 if (hinstPy3 != 0)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200419 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200420 close_dll(hinstPy3);
421 hinstPy3 = 0;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200422 }
423}
424
425/*
426 * Load library and get all pointers.
427 * Parameter 'libname' provides name of DLL.
428 * Return OK or FAIL.
429 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200430 static int
431py3_runtime_link_init(char *libname, int verbose)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200432{
433 int i;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200434 void *ucs_from_string, *ucs_decode, *ucs_as_encoded_string;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200435
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100436# if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON)
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200437 /* Can't have Python and Python3 loaded at the same time.
438 * It cause a crash, because RTLD_GLOBAL is needed for
439 * standard C extension libraries of one or both python versions. */
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200440 if (python_loaded())
441 {
Bram Moolenaar9dc93ae2011-08-28 16:00:19 +0200442 if (verbose)
443 EMSG(_("E837: This Vim cannot execute :py3 after using :python"));
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200444 return FAIL;
445 }
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200446# endif
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200447
448 if (hinstPy3 != 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200449 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200450 hinstPy3 = load_dll(libname);
451
452 if (!hinstPy3)
453 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200454 if (verbose)
455 EMSG2(_(e_loadlib), libname);
456 return FAIL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200457 }
458
459 for (i = 0; py3_funcname_table[i].ptr; ++i)
460 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200461 if ((*py3_funcname_table[i].ptr = symbol_from_dll(hinstPy3,
462 py3_funcname_table[i].name)) == NULL)
463 {
464 close_dll(hinstPy3);
465 hinstPy3 = 0;
466 if (verbose)
467 EMSG2(_(e_loadfunc), py3_funcname_table[i].name);
468 return FAIL;
469 }
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200470 }
471
Bram Moolenaar69154f22010-07-18 21:42:34 +0200472 /* Load unicode functions separately as only the ucs2 or the ucs4 functions
473 * will be present in the library. */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200474 ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_FromString");
Bram Moolenaar19e60942011-06-19 00:27:51 +0200475 ucs_decode = symbol_from_dll(hinstPy3,
476 "PyUnicodeUCS2_Decode");
477 ucs_as_encoded_string = symbol_from_dll(hinstPy3,
478 "PyUnicodeUCS2_AsEncodedString");
479 if (!ucs_from_string || !ucs_decode || !ucs_as_encoded_string)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200480 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200481 ucs_from_string = symbol_from_dll(hinstPy3,
482 "PyUnicodeUCS4_FromString");
Bram Moolenaar19e60942011-06-19 00:27:51 +0200483 ucs_decode = symbol_from_dll(hinstPy3,
484 "PyUnicodeUCS4_Decode");
485 ucs_as_encoded_string = symbol_from_dll(hinstPy3,
486 "PyUnicodeUCS4_AsEncodedString");
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200487 }
Bram Moolenaar19e60942011-06-19 00:27:51 +0200488 if (ucs_from_string && ucs_decode && ucs_as_encoded_string)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200489 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200490 py3_PyUnicode_FromString = ucs_from_string;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200491 py3_PyUnicode_Decode = ucs_decode;
492 py3_PyUnicode_AsEncodedString = ucs_as_encoded_string;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200493 }
494 else
495 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200496 close_dll(hinstPy3);
497 hinstPy3 = 0;
498 if (verbose)
499 EMSG2(_(e_loadfunc), "PyUnicode_UCSX_*");
500 return FAIL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200501 }
502
503 return OK;
504}
505
506/*
507 * If python is enabled (there is installed python on Windows system) return
508 * TRUE, else FALSE.
509 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200510 int
511python3_enabled(int verbose)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200512{
513 return py3_runtime_link_init(DYNAMIC_PYTHON3_DLL, verbose) == OK;
514}
515
516/* Load the standard Python exceptions - don't import the symbols from the
517 * DLL, as this can cause errors (importing data symbols is not reliable).
518 */
519static void get_py3_exceptions __ARGS((void));
520
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200521 static void
522get_py3_exceptions()
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200523{
524 PyObject *exmod = PyImport_ImportModule("builtins");
525 PyObject *exdict = PyModule_GetDict(exmod);
526 p3imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
527 p3imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
528 p3imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
529 p3imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
530 p3imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
531 Py_XINCREF(p3imp_PyExc_AttributeError);
532 Py_XINCREF(p3imp_PyExc_IndexError);
533 Py_XINCREF(p3imp_PyExc_KeyboardInterrupt);
534 Py_XINCREF(p3imp_PyExc_TypeError);
535 Py_XINCREF(p3imp_PyExc_ValueError);
536 Py_XDECREF(exmod);
537}
538#endif /* DYNAMIC_PYTHON3 */
539
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200540static PyObject *BufferNew (buf_T *);
541static PyObject *WindowNew(win_T *);
542static PyObject *LineToString(const char *);
Bram Moolenaar7f85d292012-02-04 20:17:26 +0100543static PyObject *BufferDir(PyObject *, PyObject *);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200544
545static PyTypeObject RangeType;
546
Bram Moolenaardb913952012-06-29 12:54:53 +0200547static int py3initialised = 0;
548
549#define PYINITIALISED py3initialised
550
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200551#define DICTKEY_DECL PyObject *bytes = NULL;
552
Bram Moolenaardb913952012-06-29 12:54:53 +0200553#define DICTKEY_GET(err) \
554 if (PyBytes_Check(keyObject)) \
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200555 { \
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +0200556 if (PyString_AsStringAndSize(keyObject, (char **) &key, NULL) == -1) \
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200557 return err; \
558 } \
Bram Moolenaardb913952012-06-29 12:54:53 +0200559 else if (PyUnicode_Check(keyObject)) \
560 { \
561 bytes = PyString_AsBytes(keyObject); \
562 if (bytes == NULL) \
563 return err; \
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +0200564 if (PyString_AsStringAndSize(bytes, (char **) &key, NULL) == -1) \
Bram Moolenaardb913952012-06-29 12:54:53 +0200565 return err; \
566 } \
567 else \
568 { \
569 PyErr_SetString(PyExc_TypeError, _("only string keys are allowed")); \
570 return err; \
571 }
Bram Moolenaarcdab9052012-09-05 19:03:56 +0200572
Bram Moolenaardb913952012-06-29 12:54:53 +0200573#define DICTKEY_UNREF \
574 if (bytes != NULL) \
575 Py_XDECREF(bytes);
576
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200577/*
578 * Include the code shared with if_python.c
579 */
580#include "if_py_both.h"
581
Bram Moolenaardb913952012-06-29 12:54:53 +0200582#define PY3OBJ_DELETED(obj) (obj->ob_base.ob_refcnt<=0)
583
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200584 static void
585call_PyObject_Free(void *p)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200586{
587#ifdef Py_DEBUG
588 _PyObject_DebugFree(p);
589#else
590 PyObject_Free(p);
591#endif
592}
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200593
594 static PyObject *
595call_PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200596{
597 return PyType_GenericNew(type,args,kwds);
598}
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200599
600 static PyObject *
601call_PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200602{
603 return PyType_GenericAlloc(type,nitems);
604}
605
606/******************************************************
607 * Internal function prototypes.
608 */
609
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200610static Py_ssize_t RangeStart;
611static Py_ssize_t RangeEnd;
612
Bram Moolenaardb913952012-06-29 12:54:53 +0200613static PyObject *globals;
614
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200615static int PythonIO_Init(void);
616static void PythonIO_Fini(void);
Bram Moolenaar69154f22010-07-18 21:42:34 +0200617PyMODINIT_FUNC Py3Init_vim(void);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200618
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200619/******************************************************
620 * 1. Python interpreter main program.
621 */
622
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200623static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
624
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200625 void
626python3_end()
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200627{
628 static int recurse = 0;
629
630 /* If a crash occurs while doing this, don't try again. */
631 if (recurse != 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200632 return;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200633
634 ++recurse;
635
636#ifdef DYNAMIC_PYTHON3
637 if (hinstPy3)
638#endif
639 if (Py_IsInitialized())
640 {
641 // acquire lock before finalizing
642 pygilstate = PyGILState_Ensure();
643
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200644 PythonIO_Fini();
645 Py_Finalize();
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200646 }
647
648#ifdef DYNAMIC_PYTHON3
649 end_dynamic_python3();
650#endif
651
652 --recurse;
653}
654
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200655#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON)) || defined(PROTO)
656 int
657python3_loaded()
658{
659 return (hinstPy3 != 0);
660}
661#endif
662
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200663 static int
664Python3_Init(void)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200665{
666 if (!py3initialised)
667 {
668#ifdef DYNAMIC_PYTHON3
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200669 if (!python3_enabled(TRUE))
670 {
671 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
672 goto fail;
673 }
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200674#endif
675
676 init_structs();
677
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100678
679#ifdef PYTHON3_HOME
680 Py_SetPythonHome(PYTHON3_HOME);
681#endif
682
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200683#if !defined(MACOS) || defined(MACOS_X_UNIX)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200684 Py_Initialize();
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200685#else
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200686 PyMac_Initialize();
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200687#endif
Bram Moolenaar456f2bb2011-06-12 21:37:13 +0200688 /* initialise threads, must be after Py_Initialize() */
689 PyEval_InitThreads();
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200690
691#ifdef DYNAMIC_PYTHON3
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200692 get_py3_exceptions();
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200693#endif
694
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200695 if (PythonIO_Init())
696 goto fail;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200697
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200698 PyImport_AppendInittab("vim", Py3Init_vim);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200699
Bram Moolenaardb913952012-06-29 12:54:53 +0200700 globals = PyModule_GetDict(PyImport_AddModule("__main__"));
701
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200702 /* Remove the element from sys.path that was added because of our
703 * argv[0] value in Py3Init_vim(). Previously we used an empty
704 * string, but dependinding on the OS we then get an empty entry or
Bram Moolenaar19e60942011-06-19 00:27:51 +0200705 * the current directory in sys.path.
706 * Only after vim has been imported, the element does exist in
707 * sys.path.
708 */
709 PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))");
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200710
711 // lock is created and acquired in PyEval_InitThreads() and thread
712 // state is created in Py_Initialize()
713 // there _PyGILState_NoteThreadState() also sets gilcounter to 1
714 // (python must have threads enabled!)
715 // so the following does both: unlock GIL and save thread state in TLS
716 // without deleting thread state
717 PyGILState_Release(pygilstate);
718
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200719 py3initialised = 1;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200720 }
721
722 return 0;
723
724fail:
725 /* We call PythonIO_Flush() here to print any Python errors.
726 * This is OK, as it is possible to call this function even
727 * if PythonIO_Init() has not completed successfully (it will
728 * not do anything in this case).
729 */
730 PythonIO_Flush();
731 return -1;
732}
733
734/*
735 * External interface
736 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200737 static void
Bram Moolenaardb913952012-06-29 12:54:53 +0200738DoPy3Command(exarg_T *eap, const char *cmd, typval_T *rettv)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200739{
740#if defined(MACOS) && !defined(MACOS_X_UNIX)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200741 GrafPtr oldPort;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200742#endif
743#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200744 char *saved_locale;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200745#endif
Bram Moolenaar19e60942011-06-19 00:27:51 +0200746 PyObject *cmdstr;
747 PyObject *cmdbytes;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200748
749#if defined(MACOS) && !defined(MACOS_X_UNIX)
750 GetPort(&oldPort);
751 /* Check if the Python library is available */
752 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200753 goto theend;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200754#endif
755 if (Python3_Init())
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200756 goto theend;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200757
Bram Moolenaardb913952012-06-29 12:54:53 +0200758 if (rettv == NULL)
759 {
760 RangeStart = eap->line1;
761 RangeEnd = eap->line2;
762 }
763 else
764 {
765 RangeStart = (PyInt) curwin->w_cursor.lnum;
766 RangeEnd = RangeStart;
767 }
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200768 Python_Release_Vim(); /* leave vim */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200769
770#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
771 /* Python only works properly when the LC_NUMERIC locale is "C". */
772 saved_locale = setlocale(LC_NUMERIC, NULL);
773 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200774 saved_locale = NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200775 else
776 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200777 /* Need to make a copy, value may change when setting new locale. */
778 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
779 (void)setlocale(LC_NUMERIC, "C");
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200780 }
781#endif
782
783 pygilstate = PyGILState_Ensure();
784
Bram Moolenaar19e60942011-06-19 00:27:51 +0200785 /* PyRun_SimpleString expects a UTF-8 string. Wrong encoding may cause
786 * SyntaxError (unicode error). */
Bram Moolenaar3d64a312011-07-15 15:54:44 +0200787 cmdstr = PyUnicode_Decode(cmd, strlen(cmd),
788 (char *)ENC_OPT, CODEC_ERROR_HANDLER);
789 cmdbytes = PyUnicode_AsEncodedString(cmdstr, "utf-8", CODEC_ERROR_HANDLER);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200790 Py_XDECREF(cmdstr);
Bram Moolenaardb913952012-06-29 12:54:53 +0200791 if (rettv == NULL)
792 PyRun_SimpleString(PyBytes_AsString(cmdbytes));
793 else
794 {
795 PyObject *r;
796
797 r = PyRun_String(PyBytes_AsString(cmdbytes), Py_eval_input,
798 globals, globals);
799 if (r == NULL)
800 EMSG(_("E860: Eval did not return a valid python 3 object"));
801 else
802 {
803 if (ConvertFromPyObject(r, rettv) == -1)
804 EMSG(_("E861: Failed to convert returned python 3 object to vim value"));
805 Py_DECREF(r);
806 }
807 PyErr_Clear();
808 }
Bram Moolenaar19e60942011-06-19 00:27:51 +0200809 Py_XDECREF(cmdbytes);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200810
811 PyGILState_Release(pygilstate);
812
813#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
814 if (saved_locale != NULL)
815 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200816 (void)setlocale(LC_NUMERIC, saved_locale);
817 vim_free(saved_locale);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200818 }
819#endif
820
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200821 Python_Lock_Vim(); /* enter vim */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200822 PythonIO_Flush();
823#if defined(MACOS) && !defined(MACOS_X_UNIX)
824 SetPort(oldPort);
825#endif
826
827theend:
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200828 return; /* keeps lint happy */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200829}
830
831/*
Bram Moolenaar368373e2010-07-19 20:46:22 +0200832 * ":py3"
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200833 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200834 void
835ex_py3(exarg_T *eap)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200836{
837 char_u *script;
838
839 script = script_get(eap, eap->arg);
840 if (!eap->skip)
841 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200842 if (script == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200843 DoPy3Command(eap, (char *)eap->arg, NULL);
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200844 else
Bram Moolenaardb913952012-06-29 12:54:53 +0200845 DoPy3Command(eap, (char *)script, NULL);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200846 }
847 vim_free(script);
848}
849
850#define BUFFER_SIZE 2048
851
852/*
Bram Moolenaar6df6f472010-07-18 18:04:50 +0200853 * ":py3file"
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200854 */
855 void
856ex_py3file(exarg_T *eap)
857{
858 static char buffer[BUFFER_SIZE];
859 const char *file;
860 char *p;
861 int i;
862
863 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
864 * stdio file pointer, but Vim and the Python DLL are compiled with
865 * different options under Windows, meaning that stdio pointers aren't
866 * compatible between the two. Yuk.
867 *
Bram Moolenaar19e60942011-06-19 00:27:51 +0200868 * construct: exec(compile(open('a_filename', 'rb').read(), 'a_filename', 'exec'))
869 *
870 * Using bytes so that Python can detect the source encoding as it normally
871 * does. The doc does not say "compile" accept bytes, though.
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200872 *
873 * We need to escape any backslashes or single quotes in the file name, so that
874 * Python won't mangle the file name.
875 */
876
877 strcpy(buffer, "exec(compile(open('");
878 p = buffer + 19; /* size of "exec(compile(open('" */
879
880 for (i=0; i<2; ++i)
881 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200882 file = (char *)eap->arg;
883 while (*file && p < buffer + (BUFFER_SIZE - 3))
884 {
885 if (*file == '\\' || *file == '\'')
886 *p++ = '\\';
887 *p++ = *file++;
888 }
889 /* If we didn't finish the file name, we hit a buffer overflow */
890 if (*file != '\0')
891 return;
892 if (i==0)
893 {
Bram Moolenaar19e60942011-06-19 00:27:51 +0200894 strcpy(p,"','rb').read(),'");
895 p += 16;
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200896 }
897 else
898 {
899 strcpy(p,"','exec'))");
900 p += 10;
901 }
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200902 }
903
904
905 /* Execute the file */
Bram Moolenaardb913952012-06-29 12:54:53 +0200906 DoPy3Command(eap, buffer, NULL);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200907}
908
909/******************************************************
910 * 2. Python output stream: writes output via [e]msg().
911 */
912
913/* Implementation functions
914 */
915
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200916 static PyObject *
917OutputGetattro(PyObject *self, PyObject *nameobj)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200918{
919 char *name = "";
920 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200921 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200922
923 if (strcmp(name, "softspace") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200924 return PyLong_FromLong(((OutputObject *)(self))->softspace);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200925
926 return PyObject_GenericGetAttr(self, nameobj);
927}
928
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200929 static int
930OutputSetattro(PyObject *self, PyObject *nameobj, PyObject *val)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200931{
932 char *name = "";
933 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200934 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200935
Bram Moolenaardb913952012-06-29 12:54:53 +0200936 if (val == NULL)
937 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200938 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
939 return -1;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200940 }
941
942 if (strcmp(name, "softspace") == 0)
943 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200944 if (!PyLong_Check(val))
945 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200946 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
947 return -1;
948 }
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200949
Bram Moolenaar55d5c032010-07-17 23:52:29 +0200950 ((OutputObject *)(self))->softspace = PyLong_AsLong(val);
951 return 0;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200952 }
953
954 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
955 return -1;
956}
957
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200958/***************/
959
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200960 static int
961PythonIO_Init(void)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200962{
963 PyType_Ready(&OutputType);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200964 return PythonIO_Init_io();
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200965}
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200966
967 static void
968PythonIO_Fini(void)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200969{
970 PySys_SetObject("stdout", NULL);
971 PySys_SetObject("stderr", NULL);
972}
973
974/******************************************************
975 * 3. Implementation of the Vim module for Python
976 */
977
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200978/* Window type - Implementation functions
979 * --------------------------------------
980 */
981
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200982#define WindowType_Check(obj) ((obj)->ob_base.ob_type == &WindowType)
983
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200984/* Buffer type - Implementation functions
985 * --------------------------------------
986 */
987
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200988#define BufferType_Check(obj) ((obj)->ob_base.ob_type == &BufferType)
989
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200990static Py_ssize_t BufferLength(PyObject *);
991static PyObject *BufferItem(PyObject *, Py_ssize_t);
Bram Moolenaarba4897e2011-09-14 15:01:58 +0200992static PyObject* BufferSubscript(PyObject *self, PyObject *idx);
993static Py_ssize_t BufferAsSubscript(PyObject *self, PyObject *idx, PyObject *val);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200994
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200995
996/* Line range type - Implementation functions
997 * --------------------------------------
998 */
999
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001000#define RangeType_Check(obj) ((obj)->ob_base.ob_type == &RangeType)
1001
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001002static PyObject* RangeSubscript(PyObject *self, PyObject *idx);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001003static Py_ssize_t RangeAsItem(PyObject *, Py_ssize_t, PyObject *);
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001004static Py_ssize_t RangeAsSubscript(PyObject *self, PyObject *idx, PyObject *val);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001005
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001006/* Current objects type - Implementation functions
1007 * -----------------------------------------------
1008 */
1009
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001010static PySequenceMethods BufferAsSeq = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001011 (lenfunc) BufferLength, /* sq_length, len(x) */
1012 (binaryfunc) 0, /* sq_concat, x+y */
1013 (ssizeargfunc) 0, /* sq_repeat, x*n */
1014 (ssizeargfunc) BufferItem, /* sq_item, x[i] */
1015 0, /* was_sq_slice, x[i:j] */
Bram Moolenaar19e60942011-06-19 00:27:51 +02001016 0, /* sq_ass_item, x[i]=v */
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001017 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001018 0, /* sq_contains */
1019 0, /* sq_inplace_concat */
1020 0, /* sq_inplace_repeat */
1021};
1022
1023PyMappingMethods BufferAsMapping = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001024 /* mp_length */ (lenfunc)BufferLength,
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001025 /* mp_subscript */ (binaryfunc)BufferSubscript,
Bram Moolenaar19e60942011-06-19 00:27:51 +02001026 /* mp_ass_subscript */ (objobjargproc)BufferAsSubscript,
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001027};
1028
1029
1030/* Buffer object - Definitions
1031 */
1032
1033static PyTypeObject BufferType;
1034
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001035 static PyObject *
1036BufferNew(buf_T *buf)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001037{
1038 /* We need to handle deletion of buffers underneath us.
1039 * If we add a "b_python3_ref" field to the buf_T structure,
1040 * then we can get at it in buf_freeall() in vim. We then
1041 * need to create only ONE Python object per buffer - if
1042 * we try to create a second, just INCREF the existing one
1043 * and return it. The (single) Python object referring to
1044 * the buffer is stored in "b_python3_ref".
1045 * Question: what to do on a buf_freeall(). We'll probably
1046 * have to either delete the Python object (DECREF it to
1047 * zero - a bad idea, as it leaves dangling refs!) or
1048 * set the buf_T * value to an invalid value (-1?), which
1049 * means we need checks in all access functions... Bah.
1050 */
1051
1052 BufferObject *self;
1053
1054 if (buf->b_python3_ref != NULL)
1055 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001056 self = buf->b_python3_ref;
1057 Py_INCREF(self);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001058 }
1059 else
1060 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001061 self = PyObject_NEW(BufferObject, &BufferType);
1062 buf->b_python3_ref = self;
1063 if (self == NULL)
1064 return NULL;
1065 self->buf = buf;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001066 }
1067
1068 return (PyObject *)(self);
1069}
1070
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001071 static void
1072BufferDestructor(PyObject *self)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001073{
1074 BufferObject *this = (BufferObject *)(self);
1075
1076 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001077 this->buf->b_python3_ref = NULL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001078
1079 Py_TYPE(self)->tp_free((PyObject*)self);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001080}
1081
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001082 static PyObject *
1083BufferGetattro(PyObject *self, PyObject*nameobj)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001084{
1085 BufferObject *this = (BufferObject *)(self);
1086
1087 char *name = "";
1088 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001089 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001090
1091 if (CheckBuffer(this))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001092 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001093
1094 if (strcmp(name, "name") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001095 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001096 else if (strcmp(name, "number") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001097 return Py_BuildValue("n", this->buf->b_fnum);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001098 else
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001099 return PyObject_GenericGetAttr(self, nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001100}
1101
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001102 static PyObject *
Bram Moolenaar7f85d292012-02-04 20:17:26 +01001103BufferDir(PyObject *self UNUSED, PyObject *args UNUSED)
1104{
1105 return Py_BuildValue("[sssss]", "name", "number",
1106 "append", "mark", "range");
1107}
1108
1109 static PyObject *
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001110BufferRepr(PyObject *self)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001111{
1112 static char repr[100];
1113 BufferObject *this = (BufferObject *)(self);
1114
1115 if (this->buf == INVALID_BUFFER_VALUE)
1116 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001117 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
1118 return PyUnicode_FromString(repr);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001119 }
1120 else
1121 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001122 char *name = (char *)this->buf->b_fname;
1123 Py_ssize_t len;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001124
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001125 if (name == NULL)
1126 name = "";
1127 len = strlen(name);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001128
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001129 if (len > 35)
1130 name = name + (35 - len);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001131
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001132 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001133
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001134 return PyUnicode_FromString(repr);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001135 }
1136}
1137
1138/******************/
1139
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001140 static Py_ssize_t
1141BufferLength(PyObject *self)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001142{
1143 if (CheckBuffer((BufferObject *)(self)))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001144 return -1;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001145
1146 return (Py_ssize_t)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
1147}
1148
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001149 static PyObject *
1150BufferItem(PyObject *self, Py_ssize_t n)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001151{
1152 return RBItem((BufferObject *)(self), n, 1,
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001153 (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001154}
1155
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001156 static PyObject *
1157BufferSlice(PyObject *self, Py_ssize_t lo, Py_ssize_t hi)
1158{
1159 return RBSlice((BufferObject *)(self), lo, hi, 1,
1160 (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1161}
1162
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001163 static PyObject *
1164BufferSubscript(PyObject *self, PyObject* idx)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001165{
Bram Moolenaardb913952012-06-29 12:54:53 +02001166 if (PyLong_Check(idx))
1167 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001168 long _idx = PyLong_AsLong(idx);
1169 return BufferItem(self,_idx);
Bram Moolenaardb913952012-06-29 12:54:53 +02001170 } else if (PySlice_Check(idx))
1171 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001172 Py_ssize_t start, stop, step, slicelen;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001173
Bram Moolenaar9e8edf62011-09-14 15:41:58 +02001174 if (PySlice_GetIndicesEx((PyObject *)idx,
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001175 (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count+1,
1176 &start, &stop,
Bram Moolenaardb913952012-06-29 12:54:53 +02001177 &step, &slicelen) < 0)
1178 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001179 return NULL;
1180 }
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001181 return BufferSlice(self, start, stop);
Bram Moolenaardb913952012-06-29 12:54:53 +02001182 }
1183 else
1184 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001185 PyErr_SetString(PyExc_IndexError, "Index must be int or slice");
1186 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001187 }
1188}
1189
Bram Moolenaar19e60942011-06-19 00:27:51 +02001190 static Py_ssize_t
1191BufferAsSubscript(PyObject *self, PyObject* idx, PyObject* val)
1192{
Bram Moolenaardb913952012-06-29 12:54:53 +02001193 if (PyLong_Check(idx))
1194 {
Bram Moolenaar19e60942011-06-19 00:27:51 +02001195 long n = PyLong_AsLong(idx);
1196 return RBAsItem((BufferObject *)(self), n, val, 1,
1197 (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1198 NULL);
Bram Moolenaardb913952012-06-29 12:54:53 +02001199 } else if (PySlice_Check(idx))
1200 {
Bram Moolenaar19e60942011-06-19 00:27:51 +02001201 Py_ssize_t start, stop, step, slicelen;
1202
Bram Moolenaar9e8edf62011-09-14 15:41:58 +02001203 if (PySlice_GetIndicesEx((PyObject *)idx,
Bram Moolenaar19e60942011-06-19 00:27:51 +02001204 (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count+1,
1205 &start, &stop,
Bram Moolenaardb913952012-06-29 12:54:53 +02001206 &step, &slicelen) < 0)
1207 {
Bram Moolenaar19e60942011-06-19 00:27:51 +02001208 return -1;
1209 }
1210 return RBAsSlice((BufferObject *)(self), start, stop, val, 1,
1211 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1212 NULL);
Bram Moolenaardb913952012-06-29 12:54:53 +02001213 }
1214 else
1215 {
Bram Moolenaar19e60942011-06-19 00:27:51 +02001216 PyErr_SetString(PyExc_IndexError, "Index must be int or slice");
1217 return -1;
1218 }
1219}
1220
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001221static PySequenceMethods RangeAsSeq = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001222 (lenfunc) RangeLength, /* sq_length, len(x) */
1223 (binaryfunc) 0, /* RangeConcat, sq_concat, x+y */
1224 (ssizeargfunc) 0, /* RangeRepeat, sq_repeat, x*n */
1225 (ssizeargfunc) RangeItem, /* sq_item, x[i] */
1226 0, /* was_sq_slice, x[i:j] */
1227 (ssizeobjargproc) RangeAsItem, /* sq_as_item, x[i]=v */
1228 0, /* sq_ass_slice, x[i:j]=v */
1229 0, /* sq_contains */
1230 0, /* sq_inplace_concat */
1231 0, /* sq_inplace_repeat */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001232};
1233
1234PyMappingMethods RangeAsMapping = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001235 /* mp_length */ (lenfunc)RangeLength,
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001236 /* mp_subscript */ (binaryfunc)RangeSubscript,
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001237 /* mp_ass_subscript */ (objobjargproc)RangeAsSubscript,
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001238};
1239
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001240/* Line range object - Implementation
1241 */
1242
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001243 static void
1244RangeDestructor(PyObject *self)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001245{
1246 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02001247 Py_TYPE(self)->tp_free((PyObject*)self);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001248}
1249
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001250 static PyObject *
1251RangeGetattro(PyObject *self, PyObject *nameobj)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001252{
1253 char *name = "";
1254 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001255 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001256
1257 if (strcmp(name, "start") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001258 return Py_BuildValue("n", ((RangeObject *)(self))->start - 1);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001259 else if (strcmp(name, "end") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001260 return Py_BuildValue("n", ((RangeObject *)(self))->end - 1);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001261 else
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001262 return PyObject_GenericGetAttr(self, nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001263}
1264
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001265/****************/
1266
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001267 static Py_ssize_t
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001268RangeAsItem(PyObject *self, Py_ssize_t n, PyObject *val)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001269{
1270 return RBAsItem(((RangeObject *)(self))->buf, n, val,
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001271 ((RangeObject *)(self))->start,
1272 ((RangeObject *)(self))->end,
1273 &((RangeObject *)(self))->end);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001274}
1275
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001276 static Py_ssize_t
1277RangeAsSlice(PyObject *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *val)
1278{
1279 return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
1280 ((RangeObject *)(self))->start,
1281 ((RangeObject *)(self))->end,
1282 &((RangeObject *)(self))->end);
1283}
1284
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001285 static PyObject *
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001286RangeSubscript(PyObject *self, PyObject* idx)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001287{
Bram Moolenaardb913952012-06-29 12:54:53 +02001288 if (PyLong_Check(idx))
1289 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001290 long _idx = PyLong_AsLong(idx);
1291 return RangeItem(self,_idx);
Bram Moolenaardb913952012-06-29 12:54:53 +02001292 } else if (PySlice_Check(idx))
1293 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001294 Py_ssize_t start, stop, step, slicelen;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001295
Bram Moolenaar9e8edf62011-09-14 15:41:58 +02001296 if (PySlice_GetIndicesEx((PyObject *)idx,
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001297 ((RangeObject *)(self))->end-((RangeObject *)(self))->start+1,
1298 &start, &stop,
Bram Moolenaardb913952012-06-29 12:54:53 +02001299 &step, &slicelen) < 0)
1300 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001301 return NULL;
1302 }
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001303 return RangeSlice(self, start, stop);
Bram Moolenaardb913952012-06-29 12:54:53 +02001304 }
1305 else
1306 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001307 PyErr_SetString(PyExc_IndexError, "Index must be int or slice");
1308 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001309 }
1310}
1311
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001312 static Py_ssize_t
1313RangeAsSubscript(PyObject *self, PyObject *idx, PyObject *val)
1314{
Bram Moolenaardb913952012-06-29 12:54:53 +02001315 if (PyLong_Check(idx))
1316 {
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001317 long n = PyLong_AsLong(idx);
1318 return RangeAsItem(self, n, val);
Bram Moolenaardb913952012-06-29 12:54:53 +02001319 } else if (PySlice_Check(idx))
1320 {
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001321 Py_ssize_t start, stop, step, slicelen;
1322
Bram Moolenaar9e8edf62011-09-14 15:41:58 +02001323 if (PySlice_GetIndicesEx((PyObject *)idx,
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001324 ((RangeObject *)(self))->end-((RangeObject *)(self))->start+1,
1325 &start, &stop,
Bram Moolenaardb913952012-06-29 12:54:53 +02001326 &step, &slicelen) < 0)
1327 {
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001328 return -1;
1329 }
1330 return RangeAsSlice(self, start, stop, val);
Bram Moolenaardb913952012-06-29 12:54:53 +02001331 }
1332 else
1333 {
Bram Moolenaarba4897e2011-09-14 15:01:58 +02001334 PyErr_SetString(PyExc_IndexError, "Index must be int or slice");
1335 return -1;
1336 }
1337}
1338
1339
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001340/* Buffer list object - Definitions
1341 */
1342
1343typedef struct
1344{
1345 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001346} BufListObject;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001347
1348static PySequenceMethods BufListAsSeq = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001349 (lenfunc) BufListLength, /* sq_length, len(x) */
1350 (binaryfunc) 0, /* sq_concat, x+y */
1351 (ssizeargfunc) 0, /* sq_repeat, x*n */
1352 (ssizeargfunc) BufListItem, /* sq_item, x[i] */
1353 0, /* was_sq_slice, x[i:j] */
1354 (ssizeobjargproc) 0, /* sq_as_item, x[i]=v */
1355 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001356 0, /* sq_contains */
1357 0, /* sq_inplace_concat */
1358 0, /* sq_inplace_repeat */
1359};
1360
1361static PyTypeObject BufListType;
1362
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001363/* Window object - Definitions
1364 */
1365
1366static struct PyMethodDef WindowMethods[] = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001367 /* name, function, calling, documentation */
1368 { NULL, NULL, 0, NULL }
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001369};
1370
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001371static PyTypeObject WindowType;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001372
1373/* Window object - Implementation
1374 */
1375
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001376 static PyObject *
1377WindowNew(win_T *win)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001378{
1379 /* We need to handle deletion of windows underneath us.
1380 * If we add a "w_python3_ref" field to the win_T structure,
1381 * then we can get at it in win_free() in vim. We then
1382 * need to create only ONE Python object per window - if
1383 * we try to create a second, just INCREF the existing one
1384 * and return it. The (single) Python object referring to
1385 * the window is stored in "w_python3_ref".
1386 * On a win_free() we set the Python object's win_T* field
1387 * to an invalid value. We trap all uses of a window
1388 * object, and reject them if the win_T* field is invalid.
1389 */
1390
1391 WindowObject *self;
1392
1393 if (win->w_python3_ref)
1394 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001395 self = win->w_python3_ref;
1396 Py_INCREF(self);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001397 }
1398 else
1399 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001400 self = PyObject_NEW(WindowObject, &WindowType);
1401 if (self == NULL)
1402 return NULL;
1403 self->win = win;
1404 win->w_python3_ref = self;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001405 }
1406
1407 return (PyObject *)(self);
1408}
1409
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001410 static void
1411WindowDestructor(PyObject *self)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001412{
1413 WindowObject *this = (WindowObject *)(self);
1414
1415 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001416 this->win->w_python3_ref = NULL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001417
1418 Py_TYPE(self)->tp_free((PyObject*)self);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001419}
1420
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001421 static PyObject *
1422WindowGetattro(PyObject *self, PyObject *nameobj)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001423{
1424 WindowObject *this = (WindowObject *)(self);
1425
1426 char *name = "";
1427 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001428 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001429
1430
1431 if (CheckWindow(this))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001432 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001433
1434 if (strcmp(name, "buffer") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001435 return (PyObject *)BufferNew(this->win->w_buffer);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001436 else if (strcmp(name, "cursor") == 0)
1437 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001438 pos_T *pos = &this->win->w_cursor;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001439
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001440 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001441 }
1442 else if (strcmp(name, "height") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001443 return Py_BuildValue("l", (long)(this->win->w_height));
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001444#ifdef FEAT_VERTSPLIT
1445 else if (strcmp(name, "width") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001446 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001447#endif
1448 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001449 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001450 else
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001451 return PyObject_GenericGetAttr(self, nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001452}
1453
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001454 static int
1455WindowSetattro(PyObject *self, PyObject *nameobj, PyObject *val)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001456{
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001457 char *name = "";
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001458
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001459 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001460 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001461
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001462 return WindowSetattr(self, name, val);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001463}
1464
1465/* Window list object - Definitions
1466 */
1467
1468typedef struct
1469{
1470 PyObject_HEAD
1471}
1472WinListObject;
1473
1474static PySequenceMethods WinListAsSeq = {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001475 (lenfunc) WinListLength, /* sq_length, len(x) */
1476 (binaryfunc) 0, /* sq_concat, x+y */
1477 (ssizeargfunc) 0, /* sq_repeat, x*n */
1478 (ssizeargfunc) WinListItem, /* sq_item, x[i] */
1479 0, /* sq_slice, x[i:j] */
1480 (ssizeobjargproc)0, /* sq_as_item, x[i]=v */
1481 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001482 0, /* sq_contains */
1483 0, /* sq_inplace_concat */
1484 0, /* sq_inplace_repeat */
1485};
1486
1487static PyTypeObject WinListType;
1488
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001489/* Current items object - Definitions
1490 */
1491
1492typedef struct
1493{
1494 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001495} CurrentObject;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001496
1497static PyTypeObject CurrentType;
1498
1499/* Current items object - Implementation
1500 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001501 static PyObject *
1502CurrentGetattro(PyObject *self UNUSED, PyObject *nameobj)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001503{
1504 char *name = "";
1505 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001506 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001507
1508 if (strcmp(name, "buffer") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001509 return (PyObject *)BufferNew(curbuf);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001510 else if (strcmp(name, "window") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001511 return (PyObject *)WindowNew(curwin);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001512 else if (strcmp(name, "line") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001513 return GetBufferLine(curbuf, (Py_ssize_t)curwin->w_cursor.lnum);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001514 else if (strcmp(name, "range") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001515 return RangeNew(curbuf, RangeStart, RangeEnd);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001516 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001517 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001518 else
1519 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001520 PyErr_SetString(PyExc_AttributeError, name);
1521 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001522 }
1523}
1524
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001525 static int
1526CurrentSetattro(PyObject *self UNUSED, PyObject *nameobj, PyObject *value)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001527{
1528 char *name = "";
1529 if (PyUnicode_Check(nameobj))
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001530 name = _PyUnicode_AsString(nameobj);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001531
1532 if (strcmp(name, "line") == 0)
1533 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001534 if (SetBufferLine(curbuf, (Py_ssize_t)curwin->w_cursor.lnum, value, NULL) == FAIL)
1535 return -1;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001536
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001537 return 0;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001538 }
1539 else
1540 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001541 PyErr_SetString(PyExc_AttributeError, name);
1542 return -1;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001543 }
1544}
1545
Bram Moolenaardb913952012-06-29 12:54:53 +02001546/* Dictionary object - Definitions
1547 */
1548
1549static PyInt DictionaryLength(PyObject *);
1550
1551static PyMappingMethods DictionaryAsMapping = {
1552 /* mp_length */ (lenfunc) DictionaryLength,
1553 /* mp_subscript */ (binaryfunc) DictionaryItem,
1554 /* mp_ass_subscript */ (objobjargproc) DictionaryAssItem,
1555};
1556
1557static PyTypeObject DictionaryType;
1558
1559 static void
1560DictionaryDestructor(PyObject *self)
1561{
1562 DictionaryObject *this = (DictionaryObject *)(self);
1563
1564 pyll_remove(&this->ref, &lastdict);
1565 dict_unref(this->dict);
1566
1567 Py_TYPE(self)->tp_free((PyObject*)self);
1568}
1569
1570/* List object - Definitions
1571 */
1572
1573static PyInt ListLength(PyObject *);
1574static PyObject *ListItem(PyObject *, Py_ssize_t);
1575
1576static PySequenceMethods ListAsSeq = {
1577 (lenfunc) ListLength, /* sq_length, len(x) */
1578 (binaryfunc) 0, /* RangeConcat, sq_concat, x+y */
1579 (ssizeargfunc) 0, /* RangeRepeat, sq_repeat, x*n */
1580 (ssizeargfunc) ListItem, /* sq_item, x[i] */
1581 (void *) 0, /* was_sq_slice, x[i:j] */
1582 (ssizeobjargproc) ListAssItem, /* sq_as_item, x[i]=v */
1583 (void *) 0, /* was_sq_ass_slice, x[i:j]=v */
1584 0, /* sq_contains */
1585 (binaryfunc) ListConcatInPlace,/* sq_inplace_concat */
1586 0, /* sq_inplace_repeat */
1587};
1588
1589static PyObject *ListSubscript(PyObject *, PyObject *);
1590static Py_ssize_t ListAsSubscript(PyObject *, PyObject *, PyObject *);
1591
1592static PyMappingMethods ListAsMapping = {
1593 /* mp_length */ (lenfunc) ListLength,
1594 /* mp_subscript */ (binaryfunc) ListSubscript,
1595 /* mp_ass_subscript */ (objobjargproc) ListAsSubscript,
1596};
1597
1598static PyTypeObject ListType;
1599
1600 static PyObject *
1601ListSubscript(PyObject *self, PyObject* idxObject)
1602{
1603 if (PyLong_Check(idxObject))
1604 {
1605 long idx = PyLong_AsLong(idxObject);
1606 return ListItem(self, idx);
1607 }
1608 else if (PySlice_Check(idxObject))
1609 {
1610 Py_ssize_t start, stop, step, slicelen;
1611
1612 if (PySlice_GetIndicesEx(idxObject, ListLength(self), &start, &stop,
1613 &step, &slicelen) < 0)
1614 return NULL;
1615 return ListSlice(self, start, stop);
1616 }
1617 else
1618 {
1619 PyErr_SetString(PyExc_IndexError, "Index must be int or slice");
1620 return NULL;
1621 }
1622}
1623
1624 static Py_ssize_t
1625ListAsSubscript(PyObject *self, PyObject *idxObject, PyObject *obj)
1626{
1627 if (PyLong_Check(idxObject))
1628 {
1629 long idx = PyLong_AsLong(idxObject);
1630 return ListAssItem(self, idx, obj);
1631 }
1632 else if (PySlice_Check(idxObject))
1633 {
1634 Py_ssize_t start, stop, step, slicelen;
1635
1636 if (PySlice_GetIndicesEx(idxObject, ListLength(self), &start, &stop,
1637 &step, &slicelen) < 0)
1638 return -1;
1639 return ListAssSlice(self, start, stop, obj);
1640 }
1641 else
1642 {
1643 PyErr_SetString(PyExc_IndexError, "Index must be int or slice");
1644 return -1;
1645 }
1646}
1647
1648 static void
1649ListDestructor(PyObject *self)
1650{
1651 ListObject *this = (ListObject *)(self);
1652
1653 pyll_remove(&this->ref, &lastlist);
1654 list_unref(this->list);
1655
1656 Py_TYPE(self)->tp_free((PyObject*)self);
1657}
1658
1659/* Function object - Definitions
1660 */
1661
1662 static void
1663FunctionDestructor(PyObject *self)
1664{
1665 FunctionObject *this = (FunctionObject *) (self);
1666
1667 func_unref(this->name);
1668 PyMem_Del(this->name);
1669
1670 Py_TYPE(self)->tp_free((PyObject*)self);
1671}
1672
1673 static PyObject *
1674FunctionGetattro(PyObject *self, PyObject *nameobj)
1675{
1676 FunctionObject *this = (FunctionObject *)(self);
1677 char *name = "";
1678 if (PyUnicode_Check(nameobj))
1679 name = _PyUnicode_AsString(nameobj);
1680
1681 if (strcmp(name, "name") == 0)
1682 return PyUnicode_FromString((char *)(this->name));
1683
1684 return PyObject_GenericGetAttr(self, nameobj);
1685}
1686
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001687/* External interface
1688 */
1689
1690 void
1691python3_buffer_free(buf_T *buf)
1692{
1693 if (buf->b_python3_ref != NULL)
1694 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001695 BufferObject *bp = buf->b_python3_ref;
1696 bp->buf = INVALID_BUFFER_VALUE;
1697 buf->b_python3_ref = NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001698 }
1699}
1700
1701#if defined(FEAT_WINDOWS) || defined(PROTO)
1702 void
1703python3_window_free(win_T *win)
1704{
1705 if (win->w_python3_ref != NULL)
1706 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001707 WindowObject *wp = win->w_python3_ref;
1708 wp->win = INVALID_WINDOW_VALUE;
1709 win->w_python3_ref = NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001710 }
1711}
1712#endif
1713
1714static BufListObject TheBufferList =
1715{
1716 PyObject_HEAD_INIT(&BufListType)
1717};
1718
1719static WinListObject TheWindowList =
1720{
1721 PyObject_HEAD_INIT(&WinListType)
1722};
1723
1724static CurrentObject TheCurrent =
1725{
1726 PyObject_HEAD_INIT(&CurrentType)
1727};
1728
1729PyDoc_STRVAR(vim_module_doc,"vim python interface\n");
1730
1731static struct PyModuleDef vimmodule;
1732
Bram Moolenaar69154f22010-07-18 21:42:34 +02001733#ifndef PROTO
1734PyMODINIT_FUNC Py3Init_vim(void)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001735{
1736 PyObject *mod;
1737 /* The special value is removed from sys.path in Python3_Init(). */
1738 static wchar_t *(argv[2]) = {L"/must>not&exist/foo", NULL};
1739
1740 PyType_Ready(&BufferType);
1741 PyType_Ready(&RangeType);
1742 PyType_Ready(&WindowType);
1743 PyType_Ready(&BufListType);
1744 PyType_Ready(&WinListType);
1745 PyType_Ready(&CurrentType);
Bram Moolenaardb913952012-06-29 12:54:53 +02001746 PyType_Ready(&DictionaryType);
1747 PyType_Ready(&ListType);
1748 PyType_Ready(&FunctionType);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001749
1750 /* Set sys.argv[] to avoid a crash in warn(). */
1751 PySys_SetArgv(1, argv);
1752
1753 mod = PyModule_Create(&vimmodule);
Bram Moolenaar19e60942011-06-19 00:27:51 +02001754 if (mod == NULL)
1755 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001756
Bram Moolenaar19e60942011-06-19 00:27:51 +02001757 VimError = PyErr_NewException("vim.error", NULL, NULL);
1758 Py_INCREF(VimError);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001759
1760 PyModule_AddObject(mod, "error", VimError);
1761 Py_INCREF((PyObject *)(void *)&TheBufferList);
1762 PyModule_AddObject(mod, "buffers", (PyObject *)(void *)&TheBufferList);
1763 Py_INCREF((PyObject *)(void *)&TheCurrent);
1764 PyModule_AddObject(mod, "current", (PyObject *)(void *)&TheCurrent);
1765 Py_INCREF((PyObject *)(void *)&TheWindowList);
1766 PyModule_AddObject(mod, "windows", (PyObject *)(void *)&TheWindowList);
1767
1768 if (PyErr_Occurred())
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001769 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001770
1771 return mod;
1772}
Bram Moolenaar69154f22010-07-18 21:42:34 +02001773#endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001774
1775/*************************************************************************
1776 * 4. Utility functions for handling the interface between Vim and Python.
1777 */
1778
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001779/* Convert a Vim line into a Python string.
1780 * All internal newlines are replaced by null characters.
1781 *
1782 * On errors, the Python exception data is set, and NULL is returned.
1783 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001784 static PyObject *
1785LineToString(const char *str)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001786{
1787 PyObject *result;
1788 Py_ssize_t len = strlen(str);
1789 char *tmp,*p;
1790
1791 tmp = (char *)alloc((unsigned)(len+1));
1792 p = tmp;
1793 if (p == NULL)
1794 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001795 PyErr_NoMemory();
1796 return NULL;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001797 }
1798
1799 while (*str)
1800 {
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001801 if (*str == '\n')
1802 *p = '\0';
1803 else
1804 *p = *str;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001805
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001806 ++p;
1807 ++str;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001808 }
1809 *p = '\0';
1810
Bram Moolenaar3d64a312011-07-15 15:54:44 +02001811 result = PyUnicode_Decode(tmp, len, (char *)ENC_OPT, CODEC_ERROR_HANDLER);
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001812
1813 vim_free(tmp);
1814 return result;
1815}
1816
Bram Moolenaardb913952012-06-29 12:54:53 +02001817 void
1818do_py3eval (char_u *str, typval_T *rettv)
1819{
1820 DoPy3Command(NULL, (char *) str, rettv);
1821 switch(rettv->v_type)
1822 {
1823 case VAR_DICT: ++rettv->vval.v_dict->dv_refcount; break;
1824 case VAR_LIST: ++rettv->vval.v_list->lv_refcount; break;
1825 case VAR_FUNC: func_ref(rettv->vval.v_string); break;
Bram Moolenaar77fceb82012-09-05 18:54:48 +02001826 case VAR_UNKNOWN:
1827 rettv->v_type = VAR_NUMBER;
1828 rettv->vval.v_number = 0;
1829 break;
Bram Moolenaardb913952012-06-29 12:54:53 +02001830 }
1831}
1832
1833 void
1834set_ref_in_python3 (int copyID)
1835{
1836 set_ref_in_py(copyID);
1837}
1838
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001839 static void
1840init_structs(void)
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001841{
1842 vim_memset(&OutputType, 0, sizeof(OutputType));
1843 OutputType.tp_name = "vim.message";
1844 OutputType.tp_basicsize = sizeof(OutputObject);
1845 OutputType.tp_getattro = OutputGetattro;
1846 OutputType.tp_setattro = OutputSetattro;
1847 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
1848 OutputType.tp_doc = "vim message object";
1849 OutputType.tp_methods = OutputMethods;
1850 OutputType.tp_alloc = call_PyType_GenericAlloc;
1851 OutputType.tp_new = call_PyType_GenericNew;
1852 OutputType.tp_free = call_PyObject_Free;
1853
1854 vim_memset(&BufferType, 0, sizeof(BufferType));
1855 BufferType.tp_name = "vim.buffer";
1856 BufferType.tp_basicsize = sizeof(BufferType);
1857 BufferType.tp_dealloc = BufferDestructor;
1858 BufferType.tp_repr = BufferRepr;
1859 BufferType.tp_as_sequence = &BufferAsSeq;
1860 BufferType.tp_as_mapping = &BufferAsMapping;
1861 BufferType.tp_getattro = BufferGetattro;
1862 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
1863 BufferType.tp_doc = "vim buffer object";
1864 BufferType.tp_methods = BufferMethods;
1865 BufferType.tp_alloc = call_PyType_GenericAlloc;
1866 BufferType.tp_new = call_PyType_GenericNew;
1867 BufferType.tp_free = call_PyObject_Free;
1868
Bram Moolenaar55d5c032010-07-17 23:52:29 +02001869 vim_memset(&WindowType, 0, sizeof(WindowType));
1870 WindowType.tp_name = "vim.window";
1871 WindowType.tp_basicsize = sizeof(WindowObject);
1872 WindowType.tp_dealloc = WindowDestructor;
1873 WindowType.tp_repr = WindowRepr;
1874 WindowType.tp_getattro = WindowGetattro;
1875 WindowType.tp_setattro = WindowSetattro;
1876 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
1877 WindowType.tp_doc = "vim Window object";
1878 WindowType.tp_methods = WindowMethods;
1879 WindowType.tp_alloc = call_PyType_GenericAlloc;
1880 WindowType.tp_new = call_PyType_GenericNew;
1881 WindowType.tp_free = call_PyObject_Free;
1882
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001883 vim_memset(&BufListType, 0, sizeof(BufListType));
1884 BufListType.tp_name = "vim.bufferlist";
1885 BufListType.tp_basicsize = sizeof(BufListObject);
1886 BufListType.tp_as_sequence = &BufListAsSeq;
1887 BufListType.tp_flags = Py_TPFLAGS_DEFAULT;
1888 BufferType.tp_doc = "vim buffer list";
1889
1890 vim_memset(&WinListType, 0, sizeof(WinListType));
1891 WinListType.tp_name = "vim.windowlist";
1892 WinListType.tp_basicsize = sizeof(WinListType);
1893 WinListType.tp_as_sequence = &WinListAsSeq;
1894 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
1895 WinListType.tp_doc = "vim window list";
1896
1897 vim_memset(&RangeType, 0, sizeof(RangeType));
1898 RangeType.tp_name = "vim.range";
1899 RangeType.tp_basicsize = sizeof(RangeObject);
1900 RangeType.tp_dealloc = RangeDestructor;
1901 RangeType.tp_repr = RangeRepr;
1902 RangeType.tp_as_sequence = &RangeAsSeq;
1903 RangeType.tp_as_mapping = &RangeAsMapping;
1904 RangeType.tp_getattro = RangeGetattro;
1905 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
1906 RangeType.tp_doc = "vim Range object";
1907 RangeType.tp_methods = RangeMethods;
1908 RangeType.tp_alloc = call_PyType_GenericAlloc;
1909 RangeType.tp_new = call_PyType_GenericNew;
1910 RangeType.tp_free = call_PyObject_Free;
1911
1912 vim_memset(&CurrentType, 0, sizeof(CurrentType));
1913 CurrentType.tp_name = "vim.currentdata";
1914 CurrentType.tp_basicsize = sizeof(CurrentObject);
1915 CurrentType.tp_getattro = CurrentGetattro;
1916 CurrentType.tp_setattro = CurrentSetattro;
1917 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
1918 CurrentType.tp_doc = "vim current object";
1919
Bram Moolenaardb913952012-06-29 12:54:53 +02001920 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
1921 DictionaryType.tp_name = "vim.dictionary";
1922 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
1923 DictionaryType.tp_dealloc = DictionaryDestructor;
1924 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
1925 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
1926 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
1927 DictionaryType.tp_methods = DictionaryMethods;
1928
1929 vim_memset(&ListType, 0, sizeof(ListType));
1930 ListType.tp_name = "vim.list";
1931 ListType.tp_dealloc = ListDestructor;
1932 ListType.tp_basicsize = sizeof(ListObject);
1933 ListType.tp_as_sequence = &ListAsSeq;
1934 ListType.tp_as_mapping = &ListAsMapping;
1935 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
1936 ListType.tp_doc = "list pushing modifications to vim structure";
1937 ListType.tp_methods = ListMethods;
1938
1939 vim_memset(&FunctionType, 0, sizeof(FunctionType));
1940 FunctionType.tp_name = "vim.list";
1941 FunctionType.tp_basicsize = sizeof(FunctionObject);
1942 FunctionType.tp_getattro = FunctionGetattro;
1943 FunctionType.tp_dealloc = FunctionDestructor;
1944 FunctionType.tp_call = FunctionCall;
1945 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
1946 FunctionType.tp_doc = "object that calls vim function";
1947 FunctionType.tp_methods = FunctionMethods;
1948
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +02001949 vim_memset(&vimmodule, 0, sizeof(vimmodule));
1950 vimmodule.m_name = "vim";
1951 vimmodule.m_doc = vim_module_doc;
1952 vimmodule.m_size = -1;
1953 vimmodule.m_methods = VimMethods;
1954}