blob: 23d58d1225e8a956d89a527de591ee8ae50d4ddb [file] [log] [blame]
Bram Moolenaardb913952012-06-29 12:54:53 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * Python extensions by Paul Moore.
11 * Changes for Unix by David Leonard.
12 *
13 * This consists of four parts:
14 * 1. Python interpreter main program
15 * 2. Python output stream: writes output via [e]msg().
16 * 3. Implementation of the Vim module for Python
17 * 4. Utility functions for handling the interface between Vim and Python.
18 */
19
20#include "vim.h"
21
Bram Moolenaar071d4272004-06-13 20:20:40 +000022#include <limits.h>
23
24/* Python.h defines _POSIX_THREADS itself (if needed) */
25#ifdef _POSIX_THREADS
26# undef _POSIX_THREADS
27#endif
28
Bram Moolenaar860cae12010-06-05 23:22:07 +020029#if defined(_WIN32) && defined(HAVE_FCNTL_H)
Bram Moolenaar071d4272004-06-13 20:20:40 +000030# undef HAVE_FCNTL_H
31#endif
32
33#ifdef _DEBUG
34# undef _DEBUG
35#endif
36
37#ifdef HAVE_STDARG_H
38# undef HAVE_STDARG_H /* Python's config.h defines it as well. */
39#endif
Bram Moolenaarbe2c9ae2009-11-11 14:06:59 +000040#ifdef _POSIX_C_SOURCE
41# undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */
42#endif
43#ifdef _XOPEN_SOURCE
44# undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */
45#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000046
Bram Moolenaar2c45e942008-06-04 11:35:26 +000047#define PY_SSIZE_T_CLEAN
48
Bram Moolenaar071d4272004-06-13 20:20:40 +000049#include <Python.h>
50#if defined(MACOS) && !defined(MACOS_X_UNIX)
51# include "macglue.h"
52# include <CodeFragments.h>
53#endif
54#undef main /* Defined in python.h - aargh */
55#undef HAVE_FCNTL_H /* Clash with os_win32.h */
56
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020057static void init_structs(void);
58
Bram Moolenaardb913952012-06-29 12:54:53 +020059#define PyBytes_FromString PyString_FromString
60
Bram Moolenaar19e60942011-06-19 00:27:51 +020061/* No-op conversion functions, use with care! */
62#define PyString_AsBytes(obj) (obj)
63#define PyString_FreeBytes(obj)
64
Bram Moolenaar071d4272004-06-13 20:20:40 +000065#if !defined(FEAT_PYTHON) && defined(PROTO)
66/* Use this to be able to generate prototypes without python being used. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000067# define PyObject Py_ssize_t
68# define PyThreadState Py_ssize_t
69# define PyTypeObject Py_ssize_t
70struct PyMethodDef { Py_ssize_t a; };
71# define PySequenceMethods Py_ssize_t
Bram Moolenaar071d4272004-06-13 20:20:40 +000072#endif
73
Bram Moolenaar2c45e942008-06-04 11:35:26 +000074#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
75# define PyInt Py_ssize_t
76# define PyInquiry lenfunc
77# define PyIntArgFunc ssizeargfunc
78# define PyIntIntArgFunc ssizessizeargfunc
79# define PyIntObjArgProc ssizeobjargproc
80# define PyIntIntObjArgProc ssizessizeobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000081# define Py_ssize_t_fmt "n"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000082#else
83# define PyInt int
84# define PyInquiry inquiry
85# define PyIntArgFunc intargfunc
86# define PyIntIntArgFunc intintargfunc
87# define PyIntObjArgProc intobjargproc
88# define PyIntIntObjArgProc intintobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000089# define Py_ssize_t_fmt "i"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000090#endif
91
Bram Moolenaar071d4272004-06-13 20:20:40 +000092/* Parser flags */
93#define single_input 256
94#define file_input 257
95#define eval_input 258
96
97#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
98 /* Python 2.3: can invoke ":python" recursively. */
99# define PY_CAN_RECURSE
100#endif
101
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200102# if defined(DYNAMIC_PYTHON) || defined(PROTO)
103# ifndef DYNAMIC_PYTHON
104# define HINSTANCE long_u /* for generating prototypes */
105# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000106
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200107# ifndef WIN3264
108# include <dlfcn.h>
109# define FARPROC void*
110# define HINSTANCE void*
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100111# if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200112# define load_dll(n) dlopen((n), RTLD_LAZY)
113# else
114# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
115# endif
116# define close_dll dlclose
117# define symbol_from_dll dlsym
118# else
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200119# define load_dll vimLoadLib
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200120# define close_dll FreeLibrary
121# define symbol_from_dll GetProcAddress
122# endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200123
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000124/* This makes if_python.c compile without warnings against Python 2.5
125 * on Win32 and Win64. */
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200126# undef PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200127# undef PyRun_String
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200128# undef PyArg_Parse
129# undef PyArg_ParseTuple
130# undef Py_BuildValue
131# undef Py_InitModule4
132# undef Py_InitModule4_64
Bram Moolenaardb913952012-06-29 12:54:53 +0200133# undef PyObject_CallMethod
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000134
Bram Moolenaar071d4272004-06-13 20:20:40 +0000135/*
136 * Wrapper defines
137 */
138# define PyArg_Parse dll_PyArg_Parse
139# define PyArg_ParseTuple dll_PyArg_ParseTuple
Bram Moolenaar19e60942011-06-19 00:27:51 +0200140# define PyMem_Free dll_PyMem_Free
Bram Moolenaardb913952012-06-29 12:54:53 +0200141# define PyMem_Malloc dll_PyMem_Malloc
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142# define PyDict_SetItemString dll_PyDict_SetItemString
143# define PyErr_BadArgument dll_PyErr_BadArgument
144# define PyErr_Clear dll_PyErr_Clear
145# define PyErr_NoMemory dll_PyErr_NoMemory
146# define PyErr_Occurred dll_PyErr_Occurred
147# define PyErr_SetNone dll_PyErr_SetNone
148# define PyErr_SetString dll_PyErr_SetString
149# define PyEval_InitThreads dll_PyEval_InitThreads
150# define PyEval_RestoreThread dll_PyEval_RestoreThread
151# define PyEval_SaveThread dll_PyEval_SaveThread
152# ifdef PY_CAN_RECURSE
153# define PyGILState_Ensure dll_PyGILState_Ensure
154# define PyGILState_Release dll_PyGILState_Release
155# endif
156# define PyInt_AsLong dll_PyInt_AsLong
157# define PyInt_FromLong dll_PyInt_FromLong
Bram Moolenaardb913952012-06-29 12:54:53 +0200158# define PyLong_AsLong dll_PyLong_AsLong
159# define PyLong_FromLong dll_PyLong_FromLong
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160# define PyInt_Type (*dll_PyInt_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200161# define PyLong_Type (*dll_PyLong_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000163# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164# define PyList_New dll_PyList_New
165# define PyList_SetItem dll_PyList_SetItem
166# define PyList_Size dll_PyList_Size
167# define PyList_Type (*dll_PyList_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200168# define PySequence_Check dll_PySequence_Check
169# define PySequence_Size dll_PySequence_Size
170# define PySequence_GetItem dll_PySequence_GetItem
171# define PyTuple_Size dll_PyTuple_Size
172# define PyTuple_GetItem dll_PyTuple_GetItem
173# define PyTuple_Type (*dll_PyTuple_Type)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000175# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176# define PyDict_GetItemString dll_PyDict_GetItemString
Bram Moolenaardb913952012-06-29 12:54:53 +0200177# define PyDict_Next dll_PyDict_Next
178# ifdef PyMapping_Items
179# define PY_NO_MAPPING_ITEMS
180# else
181# define PyMapping_Items dll_PyMapping_Items
182# endif
183# define PyObject_CallMethod dll_PyObject_CallMethod
184# define PyMapping_Check dll_PyMapping_Check
185# define PyIter_Next dll_PyIter_Next
Bram Moolenaar071d4272004-06-13 20:20:40 +0000186# define PyModule_GetDict dll_PyModule_GetDict
187# define PyRun_SimpleString dll_PyRun_SimpleString
Bram Moolenaardb913952012-06-29 12:54:53 +0200188# define PyRun_String dll_PyRun_String
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189# define PyString_AsString dll_PyString_AsString
190# define PyString_FromString dll_PyString_FromString
191# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
192# define PyString_Size dll_PyString_Size
193# define PyString_Type (*dll_PyString_Type)
Bram Moolenaardb913952012-06-29 12:54:53 +0200194# define PyUnicode_Type (*dll_PyUnicode_Type)
195# define PyUnicodeUCS4_AsEncodedString (*dll_PyUnicodeUCS4_AsEncodedString)
196# define PyFloat_AsDouble dll_PyFloat_AsDouble
197# define PyFloat_FromDouble dll_PyFloat_FromDouble
198# define PyFloat_Type (*dll_PyFloat_Type)
199# define PyImport_AddModule (*dll_PyImport_AddModule)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200# define PySys_SetObject dll_PySys_SetObject
201# define PySys_SetArgv dll_PySys_SetArgv
202# define PyType_Type (*dll_PyType_Type)
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100203# define PyType_Ready (*dll_PyType_Ready)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204# define Py_BuildValue dll_Py_BuildValue
205# define Py_FindMethod dll_Py_FindMethod
206# define Py_InitModule4 dll_Py_InitModule4
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100207# define Py_SetPythonHome dll_Py_SetPythonHome
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000209# define Py_Finalize dll_Py_Finalize
210# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211# define _PyObject_New dll__PyObject_New
Bram Moolenaardb913952012-06-29 12:54:53 +0200212# define _PyObject_NextNotImplemented (*dll__PyObject_NextNotImplemented)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000213# define _Py_NoneStruct (*dll__Py_NoneStruct)
214# define PyObject_Init dll__PyObject_Init
Bram Moolenaardb913952012-06-29 12:54:53 +0200215# define PyObject_GetIter dll_PyObject_GetIter
Bram Moolenaar071d4272004-06-13 20:20:40 +0000216# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
217# define PyType_IsSubtype dll_PyType_IsSubtype
218# endif
219# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
220# define PyObject_Malloc dll_PyObject_Malloc
221# define PyObject_Free dll_PyObject_Free
222# endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200223# define PyCapsule_New dll_PyCapsule_New
224# define PyCapsule_GetPointer dll_PyCapsule_GetPointer
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225
226/*
227 * Pointers for dynamic link
228 */
229static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
230static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200231static int(*dll_PyMem_Free)(void *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200232static void* (*dll_PyMem_Malloc)(size_t);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000233static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
234static int(*dll_PyErr_BadArgument)(void);
235static void(*dll_PyErr_Clear)(void);
236static PyObject*(*dll_PyErr_NoMemory)(void);
237static PyObject*(*dll_PyErr_Occurred)(void);
238static void(*dll_PyErr_SetNone)(PyObject *);
239static void(*dll_PyErr_SetString)(PyObject *, const char *);
240static void(*dll_PyEval_InitThreads)(void);
241static void(*dll_PyEval_RestoreThread)(PyThreadState *);
242static PyThreadState*(*dll_PyEval_SaveThread)(void);
243# ifdef PY_CAN_RECURSE
244static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
245static void (*dll_PyGILState_Release)(PyGILState_STATE);
Bram Moolenaardb913952012-06-29 12:54:53 +0200246# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247static long(*dll_PyInt_AsLong)(PyObject *);
248static PyObject*(*dll_PyInt_FromLong)(long);
Bram Moolenaardb913952012-06-29 12:54:53 +0200249static long(*dll_PyLong_AsLong)(PyObject *);
250static PyObject*(*dll_PyLong_FromLong)(long);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251static PyTypeObject* dll_PyInt_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200252static PyTypeObject* dll_PyLong_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000253static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000254static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000255static PyObject*(*dll_PyList_New)(PyInt size);
256static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
257static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258static PyTypeObject* dll_PyList_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200259static int (*dll_PySequence_Check)(PyObject *);
260static PyInt(*dll_PySequence_Size)(PyObject *);
261static PyObject*(*dll_PySequence_GetItem)(PyObject *, PyInt);
262static PyInt(*dll_PyTuple_Size)(PyObject *);
263static PyObject*(*dll_PyTuple_GetItem)(PyObject *, PyInt);
264static PyTypeObject* dll_PyTuple_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000265static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000266static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000267static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200268static int (*dll_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
269# ifndef PY_NO_MAPPING_ITEMS
270static PyObject* (*dll_PyMapping_Items)(PyObject *);
271# endif
272static PyObject* (*dll_PyObject_CallMethod)(PyObject *, char *, PyObject *);
273static int (*dll_PyMapping_Check)(PyObject *);
274static PyObject* (*dll_PyIter_Next)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275static PyObject*(*dll_PyModule_GetDict)(PyObject *);
276static int(*dll_PyRun_SimpleString)(char *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200277static PyObject *(*dll_PyRun_String)(char *, int, PyObject *, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000278static char*(*dll_PyString_AsString)(PyObject *);
279static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000280static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
281static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000282static PyTypeObject* dll_PyString_Type;
Bram Moolenaardb913952012-06-29 12:54:53 +0200283static PyTypeObject* dll_PyUnicode_Type;
284static PyObject *(*PyUnicodeUCS4_AsEncodedString)(PyObject *, char *, char *);
285static double(*dll_PyFloat_AsDouble)(PyObject *);
286static PyObject*(*dll_PyFloat_FromDouble)(double);
287static PyTypeObject* dll_PyFloat_Type;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288static int(*dll_PySys_SetObject)(char *, PyObject *);
289static int(*dll_PySys_SetArgv)(int, char **);
290static PyTypeObject* dll_PyType_Type;
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100291static int (*dll_PyType_Ready)(PyTypeObject *type);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292static PyObject*(*dll_Py_BuildValue)(char *, ...);
293static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
294static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
Bram Moolenaardb913952012-06-29 12:54:53 +0200295static PyObject*(*dll_PyImport_AddModule)(char *);
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100296static void(*dll_Py_SetPythonHome)(char *home);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000298static void(*dll_Py_Finalize)(void);
299static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000300static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
301static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200302static PyObject* (*dll_PyObject_GetIter)(PyObject *);
303static iternextfunc dll__PyObject_NextNotImplemented;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000304static PyObject* dll__Py_NoneStruct;
305# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
306static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
307# endif
308# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
309static void* (*dll_PyObject_Malloc)(size_t);
310static void (*dll_PyObject_Free)(void*);
311# endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200312static PyObject* (*dll_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
313static void* (*dll_PyCapsule_GetPointer)(PyObject *, char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314
315static HINSTANCE hinstPython = 0; /* Instance of python.dll */
316
317/* Imported exception objects */
318static PyObject *imp_PyExc_AttributeError;
319static PyObject *imp_PyExc_IndexError;
320static PyObject *imp_PyExc_KeyboardInterrupt;
321static PyObject *imp_PyExc_TypeError;
322static PyObject *imp_PyExc_ValueError;
323
324# define PyExc_AttributeError imp_PyExc_AttributeError
325# define PyExc_IndexError imp_PyExc_IndexError
326# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
327# define PyExc_TypeError imp_PyExc_TypeError
328# define PyExc_ValueError imp_PyExc_ValueError
329
330/*
331 * Table of name to function pointer of python.
332 */
333# define PYTHON_PROC FARPROC
334static struct
335{
336 char *name;
337 PYTHON_PROC *ptr;
338} python_funcname_table[] =
339{
340 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
341 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
Bram Moolenaar19e60942011-06-19 00:27:51 +0200342 {"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free},
Bram Moolenaardb913952012-06-29 12:54:53 +0200343 {"PyMem_Malloc", (PYTHON_PROC*)&dll_PyMem_Malloc},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
345 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
346 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
347 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
348 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
349 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
350 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
351 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
352 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
353 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
354# ifdef PY_CAN_RECURSE
355 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
356 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
357# endif
358 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
359 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
Bram Moolenaardb913952012-06-29 12:54:53 +0200360 {"PyLong_AsLong", (PYTHON_PROC*)&dll_PyLong_AsLong},
361 {"PyLong_FromLong", (PYTHON_PROC*)&dll_PyLong_FromLong},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200363 {"PyLong_Type", (PYTHON_PROC*)&dll_PyLong_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000365 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
367 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
368 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
369 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200370 {"PySequence_GetItem", (PYTHON_PROC*)&dll_PySequence_GetItem},
371 {"PySequence_Size", (PYTHON_PROC*)&dll_PySequence_Size},
372 {"PySequence_Check", (PYTHON_PROC*)&dll_PySequence_Check},
373 {"PyTuple_GetItem", (PYTHON_PROC*)&dll_PyTuple_GetItem},
374 {"PyTuple_Size", (PYTHON_PROC*)&dll_PyTuple_Size},
375 {"PyTuple_Type", (PYTHON_PROC*)&dll_PyTuple_Type},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
377 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200378 {"PyDict_Next", (PYTHON_PROC*)&dll_PyDict_Next},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000379 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaardb913952012-06-29 12:54:53 +0200380# ifndef PY_NO_MAPPING_ITEMS
381 {"PyMapping_Items", (PYTHON_PROC*)&dll_PyMapping_Items},
382# endif
383 {"PyObject_CallMethod", (PYTHON_PROC*)&dll_PyObject_CallMethod},
384 {"PyMapping_Check", (PYTHON_PROC*)&dll_PyMapping_Check},
385 {"PyIter_Next", (PYTHON_PROC*)&dll_PyIter_Next},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
387 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
Bram Moolenaardb913952012-06-29 12:54:53 +0200388 {"PyRun_String", (PYTHON_PROC*)&dll_PyRun_String},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
390 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
391 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
392 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
393 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
Bram Moolenaardb913952012-06-29 12:54:53 +0200394 {"PyUnicode_Type", (PYTHON_PROC*)&dll_PyUnicode_Type},
395 {"PyUnicodeUCS4_AsEncodedString", (PYTHON_PROC*)&dll_PyUnicodeUCS4_AsEncodedString},
396 {"PyFloat_Type", (PYTHON_PROC*)&dll_PyFloat_Type},
397 {"PyFloat_AsDouble", (PYTHON_PROC*)&dll_PyFloat_AsDouble},
398 {"PyFloat_FromDouble", (PYTHON_PROC*)&dll_PyFloat_FromDouble},
399 {"PyImport_AddModule", (PYTHON_PROC*)&dll_PyImport_AddModule},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
401 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
402 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100403 {"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
405 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000406# if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
407 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
408# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000410# endif
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100411 {"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000413 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
414 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
416 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
Bram Moolenaardb913952012-06-29 12:54:53 +0200417 {"PyObject_GetIter", (PYTHON_PROC*)&dll_PyObject_GetIter},
418 {"_PyObject_NextNotImplemented", (PYTHON_PROC*)&dll__PyObject_NextNotImplemented},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
420# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
421 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
422# endif
423# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
424 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
425 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
426# endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200427 {"PyCapsule_New", (PYTHON_PROC*)&dll_PyCapsule_New},
428 {"PyCapsule_GetPointer", (PYTHON_PROC*)&dll_PyCapsule_GetPointer},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 {"", NULL},
430};
431
432/*
433 * Free python.dll
434 */
435 static void
436end_dynamic_python(void)
437{
438 if (hinstPython)
439 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200440 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 hinstPython = 0;
442 }
443}
444
445/*
446 * Load library and get all pointers.
447 * Parameter 'libname' provides name of DLL.
448 * Return OK or FAIL.
449 */
450 static int
451python_runtime_link_init(char *libname, int verbose)
452{
453 int i;
454
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100455#if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200456 /* Can't have Python and Python3 loaded at the same time.
457 * It cause a crash, because RTLD_GLOBAL is needed for
458 * standard C extension libraries of one or both python versions. */
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200459 if (python3_loaded())
460 {
Bram Moolenaar9dc93ae2011-08-28 16:00:19 +0200461 if (verbose)
462 EMSG(_("E836: This Vim cannot execute :python after using :py3"));
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200463 return FAIL;
464 }
465#endif
466
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467 if (hinstPython)
468 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200469 hinstPython = load_dll(libname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 if (!hinstPython)
471 {
472 if (verbose)
473 EMSG2(_(e_loadlib), libname);
474 return FAIL;
475 }
476
477 for (i = 0; python_funcname_table[i].ptr; ++i)
478 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200479 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480 python_funcname_table[i].name)) == NULL)
481 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200482 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483 hinstPython = 0;
484 if (verbose)
485 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
486 return FAIL;
487 }
488 }
489 return OK;
490}
491
492/*
493 * If python is enabled (there is installed python on Windows system) return
494 * TRUE, else FALSE.
495 */
496 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000497python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498{
499 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
500}
501
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200502/*
503 * Load the standard Python exceptions - don't import the symbols from the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504 * DLL, as this can cause errors (importing data symbols is not reliable).
505 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 static void
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200507get_exceptions(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508{
509 PyObject *exmod = PyImport_ImportModule("exceptions");
510 PyObject *exdict = PyModule_GetDict(exmod);
511 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
512 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
513 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
514 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
515 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
516 Py_XINCREF(imp_PyExc_AttributeError);
517 Py_XINCREF(imp_PyExc_IndexError);
518 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
519 Py_XINCREF(imp_PyExc_TypeError);
520 Py_XINCREF(imp_PyExc_ValueError);
521 Py_XDECREF(exmod);
522}
523#endif /* DYNAMIC_PYTHON */
524
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200525static PyObject *BufferNew (buf_T *);
526static PyObject *WindowNew(win_T *);
Bram Moolenaardb913952012-06-29 12:54:53 +0200527static PyObject *DictionaryNew(dict_T *);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200528static PyObject *LineToString(const char *);
529
530static PyTypeObject RangeType;
531
Bram Moolenaardb913952012-06-29 12:54:53 +0200532static int initialised = 0;
533#define PYINITIALISED initialised
534
535/* Add conversion from PyInt? */
536#define DICTKEY_GET(err) \
537 if (!PyString_Check(keyObject)) \
538 { \
539 PyErr_SetString(PyExc_TypeError, _("only string keys are allowed")); \
540 return err; \
541 } \
542 key = (char_u *) PyString_AsString(keyObject);
543#define DICTKEY_UNREF
544#define DICTKEY_DECL
545
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200546/*
547 * Include the code shared with if_python3.c
548 */
549#include "if_py_both.h"
550
551
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552/******************************************************
553 * Internal function prototypes.
554 */
555
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000556static PyInt RangeStart;
557static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558
Bram Moolenaardb913952012-06-29 12:54:53 +0200559static PyObject *globals;
560
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561static void PythonIO_Flush(void);
562static int PythonIO_Init(void);
563static int PythonMod_Init(void);
564
565/* Utility functions for the vim/python interface
566 * ----------------------------------------------
567 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000568
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000569static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000570
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571
572/******************************************************
573 * 1. Python interpreter main program.
574 */
575
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
577typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000578#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000580#ifdef PY_CAN_RECURSE
581static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
582#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000583static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000584#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585
586/*
587 * Suspend a thread of the Python interpreter, other threads are allowed to
588 * run.
589 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000590 static void
591Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000592{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000593#ifdef PY_CAN_RECURSE
594 PyGILState_Release(pygilstate);
595#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598}
599
600/*
601 * Restore a thread of the Python interpreter, waits for other threads to
602 * block.
603 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000604 static void
605Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000607#ifdef PY_CAN_RECURSE
608 pygilstate = PyGILState_Ensure();
609#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 PyEval_RestoreThread(saved_python_thread);
611 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000613}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 void
616python_end()
617{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000618 static int recurse = 0;
619
620 /* If a crash occurs while doing this, don't try again. */
621 if (recurse != 0)
622 return;
623
624 ++recurse;
625
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000627 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000628 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000629 Python_RestoreThread(); /* enter python */
630 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000633#else
634 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000635 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000636 Python_RestoreThread(); /* enter python */
637 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000638 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000639#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000640
641 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642}
643
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200644#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
645 int
646python_loaded()
647{
648 return (hinstPython != 0);
649}
650#endif
651
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 static int
653Python_Init(void)
654{
655 if (!initialised)
656 {
657#ifdef DYNAMIC_PYTHON
658 if (!python_enabled(TRUE))
659 {
660 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
661 goto fail;
662 }
663#endif
664
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100665#ifdef PYTHON_HOME
666 Py_SetPythonHome(PYTHON_HOME);
667#endif
668
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200669 init_structs();
670
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671#if !defined(MACOS) || defined(MACOS_X_UNIX)
672 Py_Initialize();
673#else
674 PyMac_Initialize();
675#endif
676 /* initialise threads */
677 PyEval_InitThreads();
678
679#ifdef DYNAMIC_PYTHON
680 get_exceptions();
681#endif
682
683 if (PythonIO_Init())
684 goto fail;
685
686 if (PythonMod_Init())
687 goto fail;
688
Bram Moolenaardb913952012-06-29 12:54:53 +0200689 globals = PyModule_GetDict(PyImport_AddModule("__main__"));
690
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000691 /* Remove the element from sys.path that was added because of our
692 * argv[0] value in PythonMod_Init(). Previously we used an empty
693 * string, but dependinding on the OS we then get an empty entry or
694 * the current directory in sys.path. */
695 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
696
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000697 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699
700 initialised = 1;
701 }
702
703 return 0;
704
705fail:
706 /* We call PythonIO_Flush() here to print any Python errors.
707 * This is OK, as it is possible to call this function even
708 * if PythonIO_Init() has not completed successfully (it will
709 * not do anything in this case).
710 */
711 PythonIO_Flush();
712 return -1;
713}
714
715/*
716 * External interface
717 */
718 static void
Bram Moolenaardb913952012-06-29 12:54:53 +0200719DoPythonCommand(exarg_T *eap, const char *cmd, typval_T *rettv)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000721#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 static int recursive = 0;
723#endif
724#if defined(MACOS) && !defined(MACOS_X_UNIX)
725 GrafPtr oldPort;
726#endif
727#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
728 char *saved_locale;
729#endif
730
731#ifndef PY_CAN_RECURSE
732 if (recursive)
733 {
734 EMSG(_("E659: Cannot invoke Python recursively"));
735 return;
736 }
737 ++recursive;
738#endif
739
740#if defined(MACOS) && !defined(MACOS_X_UNIX)
741 GetPort(&oldPort);
742 /* Check if the Python library is available */
743 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
744 goto theend;
745#endif
746 if (Python_Init())
747 goto theend;
748
Bram Moolenaardb913952012-06-29 12:54:53 +0200749 if (rettv == NULL)
750 {
751 RangeStart = eap->line1;
752 RangeEnd = eap->line2;
753 }
754 else
755 {
756 RangeStart = (PyInt) curwin->w_cursor.lnum;
757 RangeEnd = RangeStart;
758 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000759 Python_Release_Vim(); /* leave vim */
760
761#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
762 /* Python only works properly when the LC_NUMERIC locale is "C". */
763 saved_locale = setlocale(LC_NUMERIC, NULL);
764 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
765 saved_locale = NULL;
766 else
767 {
768 /* Need to make a copy, value may change when setting new locale. */
769 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
770 (void)setlocale(LC_NUMERIC, "C");
771 }
772#endif
773
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775
Bram Moolenaardb913952012-06-29 12:54:53 +0200776 if (rettv == NULL)
777 PyRun_SimpleString((char *)(cmd));
778 else
779 {
780 PyObject *r;
781
782 r = PyRun_String((char *)(cmd), Py_eval_input, globals, globals);
783 if (r == NULL)
784 EMSG(_("E858: Eval did not return a valid python object"));
785 else
786 {
787 if (ConvertFromPyObject(r, rettv) == -1)
788 EMSG(_("E859: Failed to convert returned python object to vim value"));
789 Py_DECREF(r);
790 }
791 PyErr_Clear();
792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795
796#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
797 if (saved_locale != NULL)
798 {
799 (void)setlocale(LC_NUMERIC, saved_locale);
800 vim_free(saved_locale);
801 }
802#endif
803
804 Python_Lock_Vim(); /* enter vim */
805 PythonIO_Flush();
806#if defined(MACOS) && !defined(MACOS_X_UNIX)
807 SetPort(oldPort);
808#endif
809
810theend:
811#ifndef PY_CAN_RECURSE
812 --recursive;
813#endif
Bram Moolenaardb913952012-06-29 12:54:53 +0200814 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000815}
816
817/*
818 * ":python"
819 */
820 void
821ex_python(exarg_T *eap)
822{
823 char_u *script;
824
825 script = script_get(eap, eap->arg);
826 if (!eap->skip)
827 {
828 if (script == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200829 DoPythonCommand(eap, (char *)eap->arg, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830 else
Bram Moolenaardb913952012-06-29 12:54:53 +0200831 DoPythonCommand(eap, (char *)script, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832 }
833 vim_free(script);
834}
835
836#define BUFFER_SIZE 1024
837
838/*
839 * ":pyfile"
840 */
841 void
842ex_pyfile(exarg_T *eap)
843{
844 static char buffer[BUFFER_SIZE];
845 const char *file = (char *)eap->arg;
846 char *p;
847
848 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
849 * stdio file pointer, but Vim and the Python DLL are compiled with
850 * different options under Windows, meaning that stdio pointers aren't
851 * compatible between the two. Yuk.
852 *
853 * Put the string "execfile('file')" into buffer. But, we need to
854 * escape any backslashes or single quotes in the file name, so that
855 * Python won't mangle the file name.
856 */
857 strcpy(buffer, "execfile('");
858 p = buffer + 10; /* size of "execfile('" */
859
860 while (*file && p < buffer + (BUFFER_SIZE - 3))
861 {
862 if (*file == '\\' || *file == '\'')
863 *p++ = '\\';
864 *p++ = *file++;
865 }
866
867 /* If we didn't finish the file name, we hit a buffer overflow */
868 if (*file != '\0')
869 return;
870
871 /* Put in the terminating "')" and a null */
872 *p++ = '\'';
873 *p++ = ')';
874 *p++ = '\0';
875
876 /* Execute the file */
Bram Moolenaardb913952012-06-29 12:54:53 +0200877 DoPythonCommand(eap, buffer, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878}
879
880/******************************************************
881 * 2. Python output stream: writes output via [e]msg().
882 */
883
884/* Implementation functions
885 */
886
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 static PyObject *
888OutputGetattr(PyObject *self, char *name)
889{
890 if (strcmp(name, "softspace") == 0)
891 return PyInt_FromLong(((OutputObject *)(self))->softspace);
892
893 return Py_FindMethod(OutputMethods, self, name);
894}
895
896 static int
897OutputSetattr(PyObject *self, char *name, PyObject *val)
898{
Bram Moolenaardb913952012-06-29 12:54:53 +0200899 if (val == NULL)
900 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
902 return -1;
903 }
904
905 if (strcmp(name, "softspace") == 0)
906 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200907 if (!PyInt_Check(val))
908 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
910 return -1;
911 }
912
913 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
914 return 0;
915 }
916
917 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
918 return -1;
919}
920
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921/***************/
922
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923 static int
924PythonIO_Init(void)
925{
926 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +0100927 PyType_Ready(&OutputType);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200929 return PythonIO_Init_io();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930}
931
932/******************************************************
933 * 3. Implementation of the Vim module for Python
934 */
935
Bram Moolenaardb913952012-06-29 12:54:53 +0200936static PyObject *ConvertToPyObject(typval_T *);
937static int ConvertFromPyObject(PyObject *, typval_T *);
938
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939/* Window type - Implementation functions
940 * --------------------------------------
941 */
942
Bram Moolenaar071d4272004-06-13 20:20:40 +0000943#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
944
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945static void WindowDestructor(PyObject *);
946static PyObject *WindowGetattr(PyObject *, char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947
948/* Buffer type - Implementation functions
949 * --------------------------------------
950 */
951
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
953
Bram Moolenaar071d4272004-06-13 20:20:40 +0000954static void BufferDestructor(PyObject *);
955static PyObject *BufferGetattr(PyObject *, char *);
956static PyObject *BufferRepr(PyObject *);
957
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000958static PyInt BufferLength(PyObject *);
959static PyObject *BufferItem(PyObject *, PyInt);
960static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
961static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
962static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964/* Line range type - Implementation functions
965 * --------------------------------------
966 */
967
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
969
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000970static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
971static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973/* Current objects type - Implementation functions
974 * -----------------------------------------------
975 */
976
977static PyObject *CurrentGetattr(PyObject *, char *);
978static int CurrentSetattr(PyObject *, char *, PyObject *);
979
Bram Moolenaar071d4272004-06-13 20:20:40 +0000980static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000981 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000983 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
984 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
985 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
986 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
987 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988};
989
990static PyTypeObject BufferType = {
991 PyObject_HEAD_INIT(0)
992 0,
993 "buffer",
994 sizeof(BufferObject),
995 0,
996
997 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
998 (printfunc) 0, /* tp_print, print x */
999 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
1000 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1001 (cmpfunc) 0, /* tp_compare, x>y */
1002 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
1003
1004 0, /* as number */
1005 &BufferAsSeq, /* as sequence */
1006 0, /* as mapping */
1007
1008 (hashfunc) 0, /* tp_hash, dict(x) */
1009 (ternaryfunc) 0, /* tp_call, x() */
1010 (reprfunc) 0, /* tp_str, str(x) */
1011};
1012
1013/* Buffer object - Implementation
1014 */
1015
1016 static PyObject *
1017BufferNew(buf_T *buf)
1018{
1019 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001020 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001021 * then we can get at it in buf_freeall() in vim. We then
1022 * need to create only ONE Python object per buffer - if
1023 * we try to create a second, just INCREF the existing one
1024 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001025 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 * Question: what to do on a buf_freeall(). We'll probably
1027 * have to either delete the Python object (DECREF it to
1028 * zero - a bad idea, as it leaves dangling refs!) or
1029 * set the buf_T * value to an invalid value (-1?), which
1030 * means we need checks in all access functions... Bah.
1031 */
1032
1033 BufferObject *self;
1034
Bram Moolenaare344bea2005-09-01 20:46:49 +00001035 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001037 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 Py_INCREF(self);
1039 }
1040 else
1041 {
1042 self = PyObject_NEW(BufferObject, &BufferType);
1043 if (self == NULL)
1044 return NULL;
1045 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001046 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 }
1048
1049 return (PyObject *)(self);
1050}
1051
1052 static void
1053BufferDestructor(PyObject *self)
1054{
1055 BufferObject *this = (BufferObject *)(self);
1056
1057 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001058 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059
Bram Moolenaar658ada62006-10-03 13:02:36 +00001060 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061}
1062
1063 static PyObject *
1064BufferGetattr(PyObject *self, char *name)
1065{
1066 BufferObject *this = (BufferObject *)(self);
1067
1068 if (CheckBuffer(this))
1069 return NULL;
1070
1071 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001072 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001074 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 else if (strcmp(name,"__members__") == 0)
1076 return Py_BuildValue("[ss]", "name", "number");
1077 else
1078 return Py_FindMethod(BufferMethods, self, name);
1079}
1080
1081 static PyObject *
1082BufferRepr(PyObject *self)
1083{
Bram Moolenaar555b2802005-05-19 21:08:39 +00001084 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 BufferObject *this = (BufferObject *)(self);
1086
1087 if (this->buf == INVALID_BUFFER_VALUE)
1088 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001089 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090 return PyString_FromString(repr);
1091 }
1092 else
1093 {
1094 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001095 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096
1097 if (name == NULL)
1098 name = "";
1099 len = strlen(name);
1100
1101 if (len > 35)
1102 name = name + (35 - len);
1103
Bram Moolenaar555b2802005-05-19 21:08:39 +00001104 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105
1106 return PyString_FromString(repr);
1107 }
1108}
1109
1110/******************/
1111
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001112 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113BufferLength(PyObject *self)
1114{
1115 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1116 if (CheckBuffer((BufferObject *)(self)))
1117 return -1; /* ??? */
1118
1119 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1120}
1121
1122 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001123BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124{
1125 return RBItem((BufferObject *)(self), n, 1,
1126 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1127}
1128
1129 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001130BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131{
1132 return RBSlice((BufferObject *)(self), lo, hi, 1,
1133 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1134}
1135
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001136 static PyInt
1137BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001139 return RBAsItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001140 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141 NULL);
1142}
1143
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001144 static PyInt
1145BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001147 return RBAsSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001148 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149 NULL);
1150}
1151
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001153 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001155 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1156 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1157 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1158 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1159 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160};
1161
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162/* Line range object - Implementation
1163 */
1164
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 static void
1166RangeDestructor(PyObject *self)
1167{
1168 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001169 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001170}
1171
1172 static PyObject *
1173RangeGetattr(PyObject *self, char *name)
1174{
1175 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001176 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001178 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179 else
1180 return Py_FindMethod(RangeMethods, self, name);
1181}
1182
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183/****************/
1184
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001185 static PyInt
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001186RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001188 return RBAsItem(((RangeObject *)(self))->buf, n, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189 ((RangeObject *)(self))->start,
1190 ((RangeObject *)(self))->end,
1191 &((RangeObject *)(self))->end);
1192}
1193
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001194 static PyInt
1195RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196{
Bram Moolenaar19e60942011-06-19 00:27:51 +02001197 return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 ((RangeObject *)(self))->start,
1199 ((RangeObject *)(self))->end,
1200 &((RangeObject *)(self))->end);
1201}
1202
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203/* Buffer list object - Definitions
1204 */
1205
1206typedef struct
1207{
1208 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001209} BufListObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210
1211static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001212 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001214 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1215 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1216 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1217 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1218 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001219};
1220
1221static PyTypeObject BufListType = {
1222 PyObject_HEAD_INIT(0)
1223 0,
1224 "buffer list",
1225 sizeof(BufListObject),
1226 0,
1227
1228 (destructor) 0, /* tp_dealloc, refcount==0 */
1229 (printfunc) 0, /* tp_print, print x */
1230 (getattrfunc) 0, /* tp_getattr, x.attr */
1231 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1232 (cmpfunc) 0, /* tp_compare, x>y */
1233 (reprfunc) 0, /* tp_repr, `x`, print x */
1234
1235 0, /* as number */
1236 &BufListAsSeq, /* as sequence */
1237 0, /* as mapping */
1238
1239 (hashfunc) 0, /* tp_hash, dict(x) */
1240 (ternaryfunc) 0, /* tp_call, x() */
1241 (reprfunc) 0, /* tp_str, str(x) */
1242};
1243
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244/* Window object - Definitions
1245 */
1246
1247static struct PyMethodDef WindowMethods[] = {
1248 /* name, function, calling, documentation */
1249 { NULL, NULL, 0, NULL }
1250};
1251
1252static PyTypeObject WindowType = {
1253 PyObject_HEAD_INIT(0)
1254 0,
1255 "window",
1256 sizeof(WindowObject),
1257 0,
1258
1259 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1260 (printfunc) 0, /* tp_print, print x */
1261 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1262 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1263 (cmpfunc) 0, /* tp_compare, x>y */
1264 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1265
1266 0, /* as number */
1267 0, /* as sequence */
1268 0, /* as mapping */
1269
1270 (hashfunc) 0, /* tp_hash, dict(x) */
1271 (ternaryfunc) 0, /* tp_call, x() */
1272 (reprfunc) 0, /* tp_str, str(x) */
1273};
1274
1275/* Window object - Implementation
1276 */
1277
1278 static PyObject *
1279WindowNew(win_T *win)
1280{
1281 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001282 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283 * then we can get at it in win_free() in vim. We then
1284 * need to create only ONE Python object per window - if
1285 * we try to create a second, just INCREF the existing one
1286 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001287 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288 * On a win_free() we set the Python object's win_T* field
1289 * to an invalid value. We trap all uses of a window
1290 * object, and reject them if the win_T* field is invalid.
1291 */
1292
1293 WindowObject *self;
1294
Bram Moolenaare344bea2005-09-01 20:46:49 +00001295 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001297 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298 Py_INCREF(self);
1299 }
1300 else
1301 {
1302 self = PyObject_NEW(WindowObject, &WindowType);
1303 if (self == NULL)
1304 return NULL;
1305 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001306 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001307 }
1308
1309 return (PyObject *)(self);
1310}
1311
1312 static void
1313WindowDestructor(PyObject *self)
1314{
1315 WindowObject *this = (WindowObject *)(self);
1316
1317 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001318 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319
Bram Moolenaar658ada62006-10-03 13:02:36 +00001320 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321}
1322
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323 static PyObject *
1324WindowGetattr(PyObject *self, char *name)
1325{
1326 WindowObject *this = (WindowObject *)(self);
1327
1328 if (CheckWindow(this))
1329 return NULL;
1330
1331 if (strcmp(name, "buffer") == 0)
1332 return (PyObject *)BufferNew(this->win->w_buffer);
1333 else if (strcmp(name, "cursor") == 0)
1334 {
1335 pos_T *pos = &this->win->w_cursor;
1336
1337 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1338 }
1339 else if (strcmp(name, "height") == 0)
1340 return Py_BuildValue("l", (long)(this->win->w_height));
1341#ifdef FEAT_VERTSPLIT
1342 else if (strcmp(name, "width") == 0)
1343 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1344#endif
1345 else if (strcmp(name,"__members__") == 0)
1346 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1347 else
1348 return Py_FindMethod(WindowMethods, self, name);
1349}
1350
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351/* Window list object - Definitions
1352 */
1353
1354typedef struct
1355{
1356 PyObject_HEAD
1357}
1358WinListObject;
1359
1360static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001361 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001363 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1364 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
1365 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1366 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1367 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368};
1369
1370static PyTypeObject WinListType = {
1371 PyObject_HEAD_INIT(0)
1372 0,
1373 "window list",
1374 sizeof(WinListObject),
1375 0,
1376
1377 (destructor) 0, /* tp_dealloc, refcount==0 */
1378 (printfunc) 0, /* tp_print, print x */
1379 (getattrfunc) 0, /* tp_getattr, x.attr */
1380 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1381 (cmpfunc) 0, /* tp_compare, x>y */
1382 (reprfunc) 0, /* tp_repr, `x`, print x */
1383
1384 0, /* as number */
1385 &WinListAsSeq, /* as sequence */
1386 0, /* as mapping */
1387
1388 (hashfunc) 0, /* tp_hash, dict(x) */
1389 (ternaryfunc) 0, /* tp_call, x() */
1390 (reprfunc) 0, /* tp_str, str(x) */
1391};
1392
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393/* Current items object - Definitions
1394 */
1395
1396typedef struct
1397{
1398 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001399} CurrentObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400
1401static PyTypeObject CurrentType = {
1402 PyObject_HEAD_INIT(0)
1403 0,
1404 "current data",
1405 sizeof(CurrentObject),
1406 0,
1407
1408 (destructor) 0, /* tp_dealloc, refcount==0 */
1409 (printfunc) 0, /* tp_print, print x */
1410 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
1411 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
1412 (cmpfunc) 0, /* tp_compare, x>y */
1413 (reprfunc) 0, /* tp_repr, `x`, print x */
1414
1415 0, /* as number */
1416 0, /* as sequence */
1417 0, /* as mapping */
1418
1419 (hashfunc) 0, /* tp_hash, dict(x) */
1420 (ternaryfunc) 0, /* tp_call, x() */
1421 (reprfunc) 0, /* tp_str, str(x) */
1422};
1423
1424/* Current items object - Implementation
1425 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001427CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428{
1429 if (strcmp(name, "buffer") == 0)
1430 return (PyObject *)BufferNew(curbuf);
1431 else if (strcmp(name, "window") == 0)
1432 return (PyObject *)WindowNew(curwin);
1433 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001434 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435 else if (strcmp(name, "range") == 0)
1436 return RangeNew(curbuf, RangeStart, RangeEnd);
1437 else if (strcmp(name,"__members__") == 0)
1438 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
1439 else
1440 {
1441 PyErr_SetString(PyExc_AttributeError, name);
1442 return NULL;
1443 }
1444}
1445
Bram Moolenaar071d4272004-06-13 20:20:40 +00001446 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001447CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448{
1449 if (strcmp(name, "line") == 0)
1450 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001451 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001452 return -1;
1453
1454 return 0;
1455 }
1456 else
1457 {
1458 PyErr_SetString(PyExc_AttributeError, name);
1459 return -1;
1460 }
1461}
1462
1463/* External interface
1464 */
1465
1466 void
1467python_buffer_free(buf_T *buf)
1468{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001469 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001471 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001473 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474 }
1475}
1476
1477#if defined(FEAT_WINDOWS) || defined(PROTO)
1478 void
1479python_window_free(win_T *win)
1480{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001481 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001483 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001484 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001485 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 }
1487}
1488#endif
1489
1490static BufListObject TheBufferList =
1491{
1492 PyObject_HEAD_INIT(&BufListType)
1493};
1494
1495static WinListObject TheWindowList =
1496{
1497 PyObject_HEAD_INIT(&WinListType)
1498};
1499
1500static CurrentObject TheCurrent =
1501{
1502 PyObject_HEAD_INIT(&CurrentType)
1503};
1504
1505 static int
1506PythonMod_Init(void)
1507{
1508 PyObject *mod;
1509 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00001510 /* The special value is removed from sys.path in Python_Init(). */
1511 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512
1513 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +01001514 PyType_Ready(&BufferType);
1515 PyType_Ready(&RangeType);
1516 PyType_Ready(&WindowType);
1517 PyType_Ready(&BufListType);
1518 PyType_Ready(&WinListType);
1519 PyType_Ready(&CurrentType);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001520
1521 /* Set sys.argv[] to avoid a crash in warn(). */
1522 PySys_SetArgv(1, argv);
1523
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001524 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 dict = PyModule_GetDict(mod);
1526
1527 VimError = Py_BuildValue("s", "vim.error");
1528
1529 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00001530 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
1531 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
1532 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533
1534 if (PyErr_Occurred())
1535 return -1;
1536
1537 return 0;
1538}
1539
1540/*************************************************************************
1541 * 4. Utility functions for handling the interface between Vim and Python.
1542 */
1543
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544/* Convert a Vim line into a Python string.
1545 * All internal newlines are replaced by null characters.
1546 *
1547 * On errors, the Python exception data is set, and NULL is returned.
1548 */
1549 static PyObject *
1550LineToString(const char *str)
1551{
1552 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001553 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554 char *p;
1555
1556 /* Allocate an Python string object, with uninitialised contents. We
1557 * must do it this way, so that we can modify the string in place
1558 * later. See the Python source, Objects/stringobject.c for details.
1559 */
1560 result = PyString_FromStringAndSize(NULL, len);
1561 if (result == NULL)
1562 return NULL;
1563
1564 p = PyString_AsString(result);
1565
1566 while (*str)
1567 {
1568 if (*str == '\n')
1569 *p = '\0';
1570 else
1571 *p = *str;
1572
1573 ++p;
1574 ++str;
1575 }
1576
1577 return result;
1578}
1579
Bram Moolenaardb913952012-06-29 12:54:53 +02001580static void DictionaryDestructor(PyObject *);
1581static PyObject *DictionaryGetattr(PyObject *, char*);
1582
1583static PyMappingMethods DictionaryAsMapping = {
1584 (PyInquiry) DictionaryLength,
1585 (binaryfunc) DictionaryItem,
1586 (objobjargproc) DictionaryAssItem,
1587};
1588
1589static PyTypeObject DictionaryType = {
1590 PyObject_HEAD_INIT(0)
1591 0,
1592 "vimdictionary",
1593 sizeof(DictionaryObject),
1594 0,
1595
1596 (destructor) DictionaryDestructor,
1597 (printfunc) 0,
1598 (getattrfunc) DictionaryGetattr,
1599 (setattrfunc) 0,
1600 (cmpfunc) 0,
1601 (reprfunc) 0,
1602
1603 0, /* as number */
1604 0, /* as sequence */
1605 &DictionaryAsMapping, /* as mapping */
1606
1607 (hashfunc) 0,
1608 (ternaryfunc) 0,
1609 (reprfunc) 0,
1610};
1611
1612 static void
1613DictionaryDestructor(PyObject *self)
1614{
1615 DictionaryObject *this = ((DictionaryObject *) (self));
1616
1617 pyll_remove(&this->ref, &lastdict);
1618 dict_unref(this->dict);
1619
1620 Py_DECREF(self);
1621}
1622
1623 static PyObject *
1624DictionaryGetattr(PyObject *self, char *name)
1625{
1626 return Py_FindMethod(DictionaryMethods, self, name);
1627}
1628
1629static void ListDestructor(PyObject *);
1630static PyObject *ListGetattr(PyObject *, char *);
1631
1632static PySequenceMethods ListAsSeq = {
1633 (PyInquiry) ListLength,
1634 (binaryfunc) 0,
1635 (PyIntArgFunc) 0,
1636 (PyIntArgFunc) ListItem,
1637 (PyIntIntArgFunc) ListSlice,
1638 (PyIntObjArgProc) ListAssItem,
1639 (PyIntIntObjArgProc) ListAssSlice,
1640 (objobjproc) 0,
1641#if PY_MAJOR_VERSION >= 2
1642 (binaryfunc) ListConcatInPlace,
1643 0,
1644#endif
1645};
1646
1647static PyTypeObject ListType = {
1648 PyObject_HEAD_INIT(0)
1649 0,
1650 "vimlist",
1651 sizeof(ListObject),
1652 0,
1653
1654 (destructor) ListDestructor,
1655 (printfunc) 0,
1656 (getattrfunc) ListGetattr,
1657 (setattrfunc) 0,
1658 (cmpfunc) 0,
1659 (reprfunc) 0,
1660
1661 0, /* as number */
1662 &ListAsSeq, /* as sequence */
1663 0, /* as mapping */
1664
1665 (hashfunc) 0,
1666 (ternaryfunc) 0,
1667 (reprfunc) 0,
1668};
1669
1670 static void
1671ListDestructor(PyObject *self)
1672{
1673 ListObject *this = ((ListObject *) (self));
1674
1675 pyll_remove(&this->ref, &lastlist);
1676 list_unref(this->list);
1677
1678 Py_DECREF(self);
1679}
1680
1681 static PyObject *
1682ListGetattr(PyObject *self, char *name)
1683{
1684 return Py_FindMethod(ListMethods, self, name);
1685}
1686
1687static void FunctionDestructor(PyObject *);
1688static PyObject *FunctionGetattr(PyObject *, char *);
1689
1690static PyTypeObject FunctionType = {
1691 PyObject_HEAD_INIT(0)
1692 0,
1693 "vimfunction",
1694 sizeof(FunctionObject),
1695 0,
1696
1697 (destructor) FunctionDestructor,
1698 (printfunc) 0,
1699 (getattrfunc) FunctionGetattr,
1700 (setattrfunc) 0,
1701 (cmpfunc) 0,
1702 (reprfunc) 0,
1703
1704 0, /* as number */
1705 0, /* as sequence */
1706 0, /* as mapping */
1707
1708 (hashfunc) 0,
1709 (ternaryfunc) FunctionCall,
1710 (reprfunc) 0,
1711};
1712
1713 static void
1714FunctionDestructor(PyObject *self)
1715{
1716 FunctionObject *this = (FunctionObject *) (self);
1717
1718 func_unref(this->name);
1719 PyMem_Del(this->name);
1720
1721 Py_DECREF(self);
1722}
1723
1724 static PyObject *
1725FunctionGetattr(PyObject *self, char *name)
1726{
1727 FunctionObject *this = (FunctionObject *)(self);
1728
1729 if (strcmp(name, "name") == 0)
1730 return PyString_FromString((char *)(this->name));
1731 else
1732 return Py_FindMethod(FunctionMethods, self, name);
1733}
1734
1735 void
1736do_pyeval (char_u *str, typval_T *rettv)
1737{
1738 DoPythonCommand(NULL, (char *) str, rettv);
1739 switch(rettv->v_type)
1740 {
1741 case VAR_DICT: ++rettv->vval.v_dict->dv_refcount; break;
1742 case VAR_LIST: ++rettv->vval.v_list->lv_refcount; break;
1743 case VAR_FUNC: func_ref(rettv->vval.v_string); break;
1744 }
1745}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746
1747/* Don't generate a prototype for the next function, it generates an error on
1748 * newer Python versions. */
1749#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
1750
1751 char *
1752Py_GetProgramName(void)
1753{
1754 return "vim";
1755}
1756#endif /* Python 1.4 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001757
Bram Moolenaardb913952012-06-29 12:54:53 +02001758 void
1759set_ref_in_python (int copyID)
1760{
1761 set_ref_in_py(copyID);
1762}
1763
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001764 static void
1765init_structs(void)
1766{
1767 vim_memset(&OutputType, 0, sizeof(OutputType));
1768 OutputType.tp_name = "message";
1769 OutputType.tp_basicsize = sizeof(OutputObject);
1770 OutputType.tp_getattr = OutputGetattr;
1771 OutputType.tp_setattr = OutputSetattr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001772
1773 vim_memset(&RangeType, 0, sizeof(RangeType));
1774 RangeType.tp_name = "range";
1775 RangeType.tp_basicsize = sizeof(RangeObject);
1776 RangeType.tp_dealloc = RangeDestructor;
1777 RangeType.tp_getattr = RangeGetattr;
1778 RangeType.tp_repr = RangeRepr;
1779 RangeType.tp_as_sequence = &RangeAsSeq;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001780}