blob: d35e9abe63d53dd1830c81858e374aad9678efe9 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* 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#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 Moolenaar071d4272004-06-13 20:20:40 +000059#if !defined(FEAT_PYTHON) && defined(PROTO)
60/* Use this to be able to generate prototypes without python being used. */
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000061# define PyObject Py_ssize_t
62# define PyThreadState Py_ssize_t
63# define PyTypeObject Py_ssize_t
64struct PyMethodDef { Py_ssize_t a; };
65# define PySequenceMethods Py_ssize_t
Bram Moolenaar071d4272004-06-13 20:20:40 +000066#endif
67
Bram Moolenaar2c45e942008-06-04 11:35:26 +000068#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000
69# define PyInt Py_ssize_t
70# define PyInquiry lenfunc
71# define PyIntArgFunc ssizeargfunc
72# define PyIntIntArgFunc ssizessizeargfunc
73# define PyIntObjArgProc ssizeobjargproc
74# define PyIntIntObjArgProc ssizessizeobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000075# define Py_ssize_t_fmt "n"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000076#else
77# define PyInt int
78# define PyInquiry inquiry
79# define PyIntArgFunc intargfunc
80# define PyIntIntArgFunc intintargfunc
81# define PyIntObjArgProc intobjargproc
82# define PyIntIntObjArgProc intintobjargproc
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +000083# define Py_ssize_t_fmt "i"
Bram Moolenaar2c45e942008-06-04 11:35:26 +000084#endif
85
Bram Moolenaar071d4272004-06-13 20:20:40 +000086/* Parser flags */
87#define single_input 256
88#define file_input 257
89#define eval_input 258
90
91#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0
92 /* Python 2.3: can invoke ":python" recursively. */
93# define PY_CAN_RECURSE
94#endif
95
Bram Moolenaarb61f95c2010-08-09 22:06:13 +020096# if defined(DYNAMIC_PYTHON) || defined(PROTO)
97# ifndef DYNAMIC_PYTHON
98# define HINSTANCE long_u /* for generating prototypes */
99# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200101# ifndef WIN3264
102# include <dlfcn.h>
103# define FARPROC void*
104# define HINSTANCE void*
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100105# if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200106# define load_dll(n) dlopen((n), RTLD_LAZY)
107# else
108# define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
109# endif
110# define close_dll dlclose
111# define symbol_from_dll dlsym
112# else
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200113# define load_dll vimLoadLib
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200114# define close_dll FreeLibrary
115# define symbol_from_dll GetProcAddress
116# endif
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200117
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000118/* This makes if_python.c compile without warnings against Python 2.5
119 * on Win32 and Win64. */
Bram Moolenaarb61f95c2010-08-09 22:06:13 +0200120# undef PyRun_SimpleString
121# undef PyArg_Parse
122# undef PyArg_ParseTuple
123# undef Py_BuildValue
124# undef Py_InitModule4
125# undef Py_InitModule4_64
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000126
Bram Moolenaar071d4272004-06-13 20:20:40 +0000127/*
128 * Wrapper defines
129 */
130# define PyArg_Parse dll_PyArg_Parse
131# define PyArg_ParseTuple dll_PyArg_ParseTuple
132# define PyDict_SetItemString dll_PyDict_SetItemString
133# define PyErr_BadArgument dll_PyErr_BadArgument
134# define PyErr_Clear dll_PyErr_Clear
135# define PyErr_NoMemory dll_PyErr_NoMemory
136# define PyErr_Occurred dll_PyErr_Occurred
137# define PyErr_SetNone dll_PyErr_SetNone
138# define PyErr_SetString dll_PyErr_SetString
139# define PyEval_InitThreads dll_PyEval_InitThreads
140# define PyEval_RestoreThread dll_PyEval_RestoreThread
141# define PyEval_SaveThread dll_PyEval_SaveThread
142# ifdef PY_CAN_RECURSE
143# define PyGILState_Ensure dll_PyGILState_Ensure
144# define PyGILState_Release dll_PyGILState_Release
145# endif
146# define PyInt_AsLong dll_PyInt_AsLong
147# define PyInt_FromLong dll_PyInt_FromLong
148# define PyInt_Type (*dll_PyInt_Type)
149# define PyList_GetItem dll_PyList_GetItem
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000150# define PyList_Append dll_PyList_Append
Bram Moolenaar071d4272004-06-13 20:20:40 +0000151# define PyList_New dll_PyList_New
152# define PyList_SetItem dll_PyList_SetItem
153# define PyList_Size dll_PyList_Size
154# define PyList_Type (*dll_PyList_Type)
155# define PyImport_ImportModule dll_PyImport_ImportModule
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000156# define PyDict_New dll_PyDict_New
Bram Moolenaar071d4272004-06-13 20:20:40 +0000157# define PyDict_GetItemString dll_PyDict_GetItemString
158# define PyModule_GetDict dll_PyModule_GetDict
159# define PyRun_SimpleString dll_PyRun_SimpleString
160# define PyString_AsString dll_PyString_AsString
161# define PyString_FromString dll_PyString_FromString
162# define PyString_FromStringAndSize dll_PyString_FromStringAndSize
163# define PyString_Size dll_PyString_Size
164# define PyString_Type (*dll_PyString_Type)
165# define PySys_SetObject dll_PySys_SetObject
166# define PySys_SetArgv dll_PySys_SetArgv
167# define PyType_Type (*dll_PyType_Type)
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100168# define PyType_Ready (*dll_PyType_Ready)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000169# define Py_BuildValue dll_Py_BuildValue
170# define Py_FindMethod dll_Py_FindMethod
171# define Py_InitModule4 dll_Py_InitModule4
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100172# define Py_SetPythonHome dll_Py_SetPythonHome
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173# define Py_Initialize dll_Py_Initialize
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000174# define Py_Finalize dll_Py_Finalize
175# define Py_IsInitialized dll_Py_IsInitialized
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176# define _PyObject_New dll__PyObject_New
177# define _Py_NoneStruct (*dll__Py_NoneStruct)
178# define PyObject_Init dll__PyObject_Init
179# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
180# define PyType_IsSubtype dll_PyType_IsSubtype
181# endif
182# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
183# define PyObject_Malloc dll_PyObject_Malloc
184# define PyObject_Free dll_PyObject_Free
185# endif
186
187/*
188 * Pointers for dynamic link
189 */
190static int(*dll_PyArg_Parse)(PyObject *, char *, ...);
191static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...);
192static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
193static int(*dll_PyErr_BadArgument)(void);
194static void(*dll_PyErr_Clear)(void);
195static PyObject*(*dll_PyErr_NoMemory)(void);
196static PyObject*(*dll_PyErr_Occurred)(void);
197static void(*dll_PyErr_SetNone)(PyObject *);
198static void(*dll_PyErr_SetString)(PyObject *, const char *);
199static void(*dll_PyEval_InitThreads)(void);
200static void(*dll_PyEval_RestoreThread)(PyThreadState *);
201static PyThreadState*(*dll_PyEval_SaveThread)(void);
202# ifdef PY_CAN_RECURSE
203static PyGILState_STATE (*dll_PyGILState_Ensure)(void);
204static void (*dll_PyGILState_Release)(PyGILState_STATE);
205#endif
206static long(*dll_PyInt_AsLong)(PyObject *);
207static PyObject*(*dll_PyInt_FromLong)(long);
208static PyTypeObject* dll_PyInt_Type;
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000209static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000210static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000211static PyObject*(*dll_PyList_New)(PyInt size);
212static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *);
213static PyInt(*dll_PyList_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214static PyTypeObject* dll_PyList_Type;
215static PyObject*(*dll_PyImport_ImportModule)(const char *);
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000216static PyObject*(*dll_PyDict_New)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000217static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *);
218static PyObject*(*dll_PyModule_GetDict)(PyObject *);
219static int(*dll_PyRun_SimpleString)(char *);
220static char*(*dll_PyString_AsString)(PyObject *);
221static PyObject*(*dll_PyString_FromString)(const char *);
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000222static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt);
223static PyInt(*dll_PyString_Size)(PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224static PyTypeObject* dll_PyString_Type;
225static int(*dll_PySys_SetObject)(char *, PyObject *);
226static int(*dll_PySys_SetArgv)(int, char **);
227static PyTypeObject* dll_PyType_Type;
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100228static int (*dll_PyType_Ready)(PyTypeObject *type);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229static PyObject*(*dll_Py_BuildValue)(char *, ...);
230static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *);
231static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int);
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100232static void(*dll_Py_SetPythonHome)(char *home);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000233static void(*dll_Py_Initialize)(void);
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000234static void(*dll_Py_Finalize)(void);
235static int(*dll_Py_IsInitialized)(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *);
237static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *);
238static PyObject* dll__Py_NoneStruct;
239# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
240static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
241# endif
242# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
243static void* (*dll_PyObject_Malloc)(size_t);
244static void (*dll_PyObject_Free)(void*);
245# endif
246
247static HINSTANCE hinstPython = 0; /* Instance of python.dll */
248
249/* Imported exception objects */
250static PyObject *imp_PyExc_AttributeError;
251static PyObject *imp_PyExc_IndexError;
252static PyObject *imp_PyExc_KeyboardInterrupt;
253static PyObject *imp_PyExc_TypeError;
254static PyObject *imp_PyExc_ValueError;
255
256# define PyExc_AttributeError imp_PyExc_AttributeError
257# define PyExc_IndexError imp_PyExc_IndexError
258# define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt
259# define PyExc_TypeError imp_PyExc_TypeError
260# define PyExc_ValueError imp_PyExc_ValueError
261
262/*
263 * Table of name to function pointer of python.
264 */
265# define PYTHON_PROC FARPROC
266static struct
267{
268 char *name;
269 PYTHON_PROC *ptr;
270} python_funcname_table[] =
271{
272 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse},
273 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple},
274 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString},
275 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument},
276 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear},
277 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory},
278 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred},
279 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone},
280 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString},
281 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads},
282 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread},
283 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread},
284# ifdef PY_CAN_RECURSE
285 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure},
286 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release},
287# endif
288 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong},
289 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong},
290 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type},
291 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000292 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000293 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New},
294 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem},
295 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size},
296 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type},
297 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule},
298 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString},
Bram Moolenaar0ac93792006-01-21 22:16:51 +0000299 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000300 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict},
301 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString},
302 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString},
303 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString},
304 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize},
305 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size},
306 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type},
307 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject},
308 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv},
309 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type},
Bram Moolenaar30fec7b2011-03-26 18:32:05 +0100310 {"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue},
312 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000313# if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT
314 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4},
315# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4},
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000317# endif
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100318 {"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000319 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize},
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000320 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize},
321 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New},
323 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init},
324 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct},
325# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000
326 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype},
327# endif
328# if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000
329 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc},
330 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free},
331# endif
332 {"", NULL},
333};
334
335/*
336 * Free python.dll
337 */
338 static void
339end_dynamic_python(void)
340{
341 if (hinstPython)
342 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200343 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 hinstPython = 0;
345 }
346}
347
348/*
349 * Load library and get all pointers.
350 * Parameter 'libname' provides name of DLL.
351 * Return OK or FAIL.
352 */
353 static int
354python_runtime_link_init(char *libname, int verbose)
355{
356 int i;
357
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100358#if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3)
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200359 /* Can't have Python and Python3 loaded at the same time.
360 * It cause a crash, because RTLD_GLOBAL is needed for
361 * standard C extension libraries of one or both python versions. */
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200362 if (python3_loaded())
363 {
Bram Moolenaarb744b2f2010-08-13 16:22:57 +0200364 EMSG(_("E836: This Vim cannot execute :python after using :py3"));
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200365 return FAIL;
366 }
367#endif
368
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 if (hinstPython)
370 return OK;
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200371 hinstPython = load_dll(libname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372 if (!hinstPython)
373 {
374 if (verbose)
375 EMSG2(_(e_loadlib), libname);
376 return FAIL;
377 }
378
379 for (i = 0; python_funcname_table[i].ptr; ++i)
380 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200381 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000382 python_funcname_table[i].name)) == NULL)
383 {
Bram Moolenaarbd5e15f2010-07-17 21:19:38 +0200384 close_dll(hinstPython);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 hinstPython = 0;
386 if (verbose)
387 EMSG2(_(e_loadfunc), python_funcname_table[i].name);
388 return FAIL;
389 }
390 }
391 return OK;
392}
393
394/*
395 * If python is enabled (there is installed python on Windows system) return
396 * TRUE, else FALSE.
397 */
398 int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000399python_enabled(int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400{
401 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK;
402}
403
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200404/*
405 * Load the standard Python exceptions - don't import the symbols from the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 * DLL, as this can cause errors (importing data symbols is not reliable).
407 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000408 static void
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200409get_exceptions(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410{
411 PyObject *exmod = PyImport_ImportModule("exceptions");
412 PyObject *exdict = PyModule_GetDict(exmod);
413 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
414 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
415 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
416 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
417 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
418 Py_XINCREF(imp_PyExc_AttributeError);
419 Py_XINCREF(imp_PyExc_IndexError);
420 Py_XINCREF(imp_PyExc_KeyboardInterrupt);
421 Py_XINCREF(imp_PyExc_TypeError);
422 Py_XINCREF(imp_PyExc_ValueError);
423 Py_XDECREF(exmod);
424}
425#endif /* DYNAMIC_PYTHON */
426
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200427static PyObject *BufferNew (buf_T *);
428static PyObject *WindowNew(win_T *);
429static PyObject *LineToString(const char *);
430
431static PyTypeObject RangeType;
432
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200433/*
434 * Include the code shared with if_python3.c
435 */
436#include "if_py_both.h"
437
438
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439/******************************************************
440 * Internal function prototypes.
441 */
442
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000443static PyInt RangeStart;
444static PyInt RangeEnd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445
446static void PythonIO_Flush(void);
447static int PythonIO_Init(void);
448static int PythonMod_Init(void);
449
450/* Utility functions for the vim/python interface
451 * ----------------------------------------------
452 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000454static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000455
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456
457/******************************************************
458 * 1. Python interpreter main program.
459 */
460
461static int initialised = 0;
462
463#if PYTHON_API_VERSION < 1007 /* Python 1.4 */
464typedef PyObject PyThreadState;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000465#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000466
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000467#ifdef PY_CAN_RECURSE
468static PyGILState_STATE pygilstate = PyGILState_UNLOCKED;
469#else
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000470static PyThreadState *saved_python_thread = NULL;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000471#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472
473/*
474 * Suspend a thread of the Python interpreter, other threads are allowed to
475 * run.
476 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000477 static void
478Python_SaveThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000480#ifdef PY_CAN_RECURSE
481 PyGILState_Release(pygilstate);
482#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483 saved_python_thread = PyEval_SaveThread();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485}
486
487/*
488 * Restore a thread of the Python interpreter, waits for other threads to
489 * block.
490 */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000491 static void
492Python_RestoreThread(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000494#ifdef PY_CAN_RECURSE
495 pygilstate = PyGILState_Ensure();
496#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497 PyEval_RestoreThread(saved_python_thread);
498 saved_python_thread = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499#endif
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000500}
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 void
503python_end()
504{
Bram Moolenaara5792f52005-11-23 21:25:05 +0000505 static int recurse = 0;
506
507 /* If a crash occurs while doing this, don't try again. */
508 if (recurse != 0)
509 return;
510
511 ++recurse;
512
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513#ifdef DYNAMIC_PYTHON
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000514 if (hinstPython && Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000515 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000516 Python_RestoreThread(); /* enter python */
517 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 end_dynamic_python();
Bram Moolenaar0e21a3f2005-04-17 20:28:32 +0000520#else
521 if (Py_IsInitialized())
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000522 {
Bram Moolenaarc9b4b052006-04-30 18:54:39 +0000523 Python_RestoreThread(); /* enter python */
524 Py_Finalize();
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000525 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526#endif
Bram Moolenaara5792f52005-11-23 21:25:05 +0000527
528 --recurse;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529}
530
Bram Moolenaar4c3a3262010-07-24 15:42:14 +0200531#if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO)
532 int
533python_loaded()
534{
535 return (hinstPython != 0);
536}
537#endif
538
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 static int
540Python_Init(void)
541{
542 if (!initialised)
543 {
544#ifdef DYNAMIC_PYTHON
545 if (!python_enabled(TRUE))
546 {
547 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
548 goto fail;
549 }
550#endif
551
Bram Moolenaar644d37b2010-11-16 19:26:02 +0100552#ifdef PYTHON_HOME
553 Py_SetPythonHome(PYTHON_HOME);
554#endif
555
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200556 init_structs();
557
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558#if !defined(MACOS) || defined(MACOS_X_UNIX)
559 Py_Initialize();
560#else
561 PyMac_Initialize();
562#endif
563 /* initialise threads */
564 PyEval_InitThreads();
565
566#ifdef DYNAMIC_PYTHON
567 get_exceptions();
568#endif
569
570 if (PythonIO_Init())
571 goto fail;
572
573 if (PythonMod_Init())
574 goto fail;
575
Bram Moolenaar9774ecc2008-11-20 10:04:53 +0000576 /* Remove the element from sys.path that was added because of our
577 * argv[0] value in PythonMod_Init(). Previously we used an empty
578 * string, but dependinding on the OS we then get an empty entry or
579 * the current directory in sys.path. */
580 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");
581
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000582 /* the first python thread is vim's, release the lock */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583 Python_SaveThread();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000584
585 initialised = 1;
586 }
587
588 return 0;
589
590fail:
591 /* We call PythonIO_Flush() here to print any Python errors.
592 * This is OK, as it is possible to call this function even
593 * if PythonIO_Init() has not completed successfully (it will
594 * not do anything in this case).
595 */
596 PythonIO_Flush();
597 return -1;
598}
599
600/*
601 * External interface
602 */
603 static void
604DoPythonCommand(exarg_T *eap, const char *cmd)
605{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000606#ifndef PY_CAN_RECURSE
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 static int recursive = 0;
608#endif
609#if defined(MACOS) && !defined(MACOS_X_UNIX)
610 GrafPtr oldPort;
611#endif
612#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
613 char *saved_locale;
614#endif
615
616#ifndef PY_CAN_RECURSE
617 if (recursive)
618 {
619 EMSG(_("E659: Cannot invoke Python recursively"));
620 return;
621 }
622 ++recursive;
623#endif
624
625#if defined(MACOS) && !defined(MACOS_X_UNIX)
626 GetPort(&oldPort);
627 /* Check if the Python library is available */
628 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress)
629 goto theend;
630#endif
631 if (Python_Init())
632 goto theend;
633
634 RangeStart = eap->line1;
635 RangeEnd = eap->line2;
636 Python_Release_Vim(); /* leave vim */
637
638#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
639 /* Python only works properly when the LC_NUMERIC locale is "C". */
640 saved_locale = setlocale(LC_NUMERIC, NULL);
641 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
642 saved_locale = NULL;
643 else
644 {
645 /* Need to make a copy, value may change when setting new locale. */
646 saved_locale = (char *)vim_strsave((char_u *)saved_locale);
647 (void)setlocale(LC_NUMERIC, "C");
648 }
649#endif
650
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 Python_RestoreThread(); /* enter python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652
653 PyRun_SimpleString((char *)(cmd));
654
Bram Moolenaar071d4272004-06-13 20:20:40 +0000655 Python_SaveThread(); /* leave python */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656
657#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
658 if (saved_locale != NULL)
659 {
660 (void)setlocale(LC_NUMERIC, saved_locale);
661 vim_free(saved_locale);
662 }
663#endif
664
665 Python_Lock_Vim(); /* enter vim */
666 PythonIO_Flush();
667#if defined(MACOS) && !defined(MACOS_X_UNIX)
668 SetPort(oldPort);
669#endif
670
671theend:
672#ifndef PY_CAN_RECURSE
673 --recursive;
674#endif
675 return; /* keeps lint happy */
676}
677
678/*
679 * ":python"
680 */
681 void
682ex_python(exarg_T *eap)
683{
684 char_u *script;
685
686 script = script_get(eap, eap->arg);
687 if (!eap->skip)
688 {
689 if (script == NULL)
690 DoPythonCommand(eap, (char *)eap->arg);
691 else
692 DoPythonCommand(eap, (char *)script);
693 }
694 vim_free(script);
695}
696
697#define BUFFER_SIZE 1024
698
699/*
700 * ":pyfile"
701 */
702 void
703ex_pyfile(exarg_T *eap)
704{
705 static char buffer[BUFFER_SIZE];
706 const char *file = (char *)eap->arg;
707 char *p;
708
709 /* Have to do it like this. PyRun_SimpleFile requires you to pass a
710 * stdio file pointer, but Vim and the Python DLL are compiled with
711 * different options under Windows, meaning that stdio pointers aren't
712 * compatible between the two. Yuk.
713 *
714 * Put the string "execfile('file')" into buffer. But, we need to
715 * escape any backslashes or single quotes in the file name, so that
716 * Python won't mangle the file name.
717 */
718 strcpy(buffer, "execfile('");
719 p = buffer + 10; /* size of "execfile('" */
720
721 while (*file && p < buffer + (BUFFER_SIZE - 3))
722 {
723 if (*file == '\\' || *file == '\'')
724 *p++ = '\\';
725 *p++ = *file++;
726 }
727
728 /* If we didn't finish the file name, we hit a buffer overflow */
729 if (*file != '\0')
730 return;
731
732 /* Put in the terminating "')" and a null */
733 *p++ = '\'';
734 *p++ = ')';
735 *p++ = '\0';
736
737 /* Execute the file */
738 DoPythonCommand(eap, buffer);
739}
740
741/******************************************************
742 * 2. Python output stream: writes output via [e]msg().
743 */
744
745/* Implementation functions
746 */
747
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748 static PyObject *
749OutputGetattr(PyObject *self, char *name)
750{
751 if (strcmp(name, "softspace") == 0)
752 return PyInt_FromLong(((OutputObject *)(self))->softspace);
753
754 return Py_FindMethod(OutputMethods, self, name);
755}
756
757 static int
758OutputSetattr(PyObject *self, char *name, PyObject *val)
759{
760 if (val == NULL) {
761 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
762 return -1;
763 }
764
765 if (strcmp(name, "softspace") == 0)
766 {
767 if (!PyInt_Check(val)) {
768 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
769 return -1;
770 }
771
772 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
773 return 0;
774 }
775
776 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
777 return -1;
778}
779
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780/***************/
781
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 static int
783PythonIO_Init(void)
784{
785 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +0100786 PyType_Ready(&OutputType);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200788 return PythonIO_Init_io();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789}
790
791/******************************************************
792 * 3. Implementation of the Vim module for Python
793 */
794
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795/* Window type - Implementation functions
796 * --------------------------------------
797 */
798
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799#define WindowType_Check(obj) ((obj)->ob_type == &WindowType)
800
Bram Moolenaar071d4272004-06-13 20:20:40 +0000801static void WindowDestructor(PyObject *);
802static PyObject *WindowGetattr(PyObject *, char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000803
804/* Buffer type - Implementation functions
805 * --------------------------------------
806 */
807
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808#define BufferType_Check(obj) ((obj)->ob_type == &BufferType)
809
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810static void BufferDestructor(PyObject *);
811static PyObject *BufferGetattr(PyObject *, char *);
812static PyObject *BufferRepr(PyObject *);
813
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000814static PyInt BufferLength(PyObject *);
815static PyObject *BufferItem(PyObject *, PyInt);
816static PyObject *BufferSlice(PyObject *, PyInt, PyInt);
817static PyInt BufferAssItem(PyObject *, PyInt, PyObject *);
818static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820/* Line range type - Implementation functions
821 * --------------------------------------
822 */
823
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#define RangeType_Check(obj) ((obj)->ob_type == &RangeType)
825
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000826static PyInt RangeAssItem(PyObject *, PyInt, PyObject *);
827static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829/* Current objects type - Implementation functions
830 * -----------------------------------------------
831 */
832
833static PyObject *CurrentGetattr(PyObject *, char *);
834static int CurrentSetattr(PyObject *, char *, PyObject *);
835
Bram Moolenaar071d4272004-06-13 20:20:40 +0000836/* Common routines for buffers and line ranges
837 * -------------------------------------------
838 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200839
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000840 static PyInt
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000841RBAssSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842{
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000843 PyInt size;
844 PyInt len_change;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845
846 /* Self must be a valid buffer */
847 if (CheckBuffer(self))
848 return -1;
849
850 /* Sort out the slice range */
851 size = end - start + 1;
852
853 if (lo < 0)
854 lo = 0;
855 else if (lo > size)
856 lo = size;
857 if (hi < 0)
858 hi = 0;
859 if (hi < lo)
860 hi = lo;
861 else if (hi > size)
862 hi = size;
863
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200864 if (SetBufferLineList(self->buf, lo + start, hi + start,
865 val, &len_change) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 return -1;
867
868 if (new_end)
869 *new_end = end + len_change;
870
871 return 0;
872}
873
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874static PySequenceMethods BufferAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000875 (PyInquiry) BufferLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +0000877 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */
878 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */
879 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */
880 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */
881 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882};
883
884static PyTypeObject BufferType = {
885 PyObject_HEAD_INIT(0)
886 0,
887 "buffer",
888 sizeof(BufferObject),
889 0,
890
891 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */
892 (printfunc) 0, /* tp_print, print x */
893 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */
894 (setattrfunc) 0, /* tp_setattr, x.attr=v */
895 (cmpfunc) 0, /* tp_compare, x>y */
896 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */
897
898 0, /* as number */
899 &BufferAsSeq, /* as sequence */
900 0, /* as mapping */
901
902 (hashfunc) 0, /* tp_hash, dict(x) */
903 (ternaryfunc) 0, /* tp_call, x() */
904 (reprfunc) 0, /* tp_str, str(x) */
905};
906
907/* Buffer object - Implementation
908 */
909
910 static PyObject *
911BufferNew(buf_T *buf)
912{
913 /* We need to handle deletion of buffers underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +0000914 * If we add a "b_python_ref" field to the buf_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 * then we can get at it in buf_freeall() in vim. We then
916 * need to create only ONE Python object per buffer - if
917 * we try to create a second, just INCREF the existing one
918 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +0000919 * the buffer is stored in "b_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 * Question: what to do on a buf_freeall(). We'll probably
921 * have to either delete the Python object (DECREF it to
922 * zero - a bad idea, as it leaves dangling refs!) or
923 * set the buf_T * value to an invalid value (-1?), which
924 * means we need checks in all access functions... Bah.
925 */
926
927 BufferObject *self;
928
Bram Moolenaare344bea2005-09-01 20:46:49 +0000929 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930 {
Bram Moolenaare344bea2005-09-01 20:46:49 +0000931 self = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932 Py_INCREF(self);
933 }
934 else
935 {
936 self = PyObject_NEW(BufferObject, &BufferType);
937 if (self == NULL)
938 return NULL;
939 self->buf = buf;
Bram Moolenaare344bea2005-09-01 20:46:49 +0000940 buf->b_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941 }
942
943 return (PyObject *)(self);
944}
945
946 static void
947BufferDestructor(PyObject *self)
948{
949 BufferObject *this = (BufferObject *)(self);
950
951 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +0000952 this->buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953
Bram Moolenaar658ada62006-10-03 13:02:36 +0000954 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955}
956
957 static PyObject *
958BufferGetattr(PyObject *self, char *name)
959{
960 BufferObject *this = (BufferObject *)(self);
961
962 if (CheckBuffer(this))
963 return NULL;
964
965 if (strcmp(name, "name") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000966 return Py_BuildValue("s", this->buf->b_ffname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 else if (strcmp(name, "number") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000968 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969 else if (strcmp(name,"__members__") == 0)
970 return Py_BuildValue("[ss]", "name", "number");
971 else
972 return Py_FindMethod(BufferMethods, self, name);
973}
974
975 static PyObject *
976BufferRepr(PyObject *self)
977{
Bram Moolenaar555b2802005-05-19 21:08:39 +0000978 static char repr[100];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979 BufferObject *this = (BufferObject *)(self);
980
981 if (this->buf == INVALID_BUFFER_VALUE)
982 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000983 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000984 return PyString_FromString(repr);
985 }
986 else
987 {
988 char *name = (char *)this->buf->b_fname;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +0000989 PyInt len;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990
991 if (name == NULL)
992 name = "";
993 len = strlen(name);
994
995 if (len > 35)
996 name = name + (35 - len);
997
Bram Moolenaar555b2802005-05-19 21:08:39 +0000998 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999
1000 return PyString_FromString(repr);
1001 }
1002}
1003
1004/******************/
1005
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001006 static PyInt
Bram Moolenaar071d4272004-06-13 20:20:40 +00001007BufferLength(PyObject *self)
1008{
1009 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1010 if (CheckBuffer((BufferObject *)(self)))
1011 return -1; /* ??? */
1012
1013 return (((BufferObject *)(self))->buf->b_ml.ml_line_count);
1014}
1015
1016 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001017BufferItem(PyObject *self, PyInt n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018{
1019 return RBItem((BufferObject *)(self), n, 1,
1020 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1021}
1022
1023 static PyObject *
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001024BufferSlice(PyObject *self, PyInt lo, PyInt hi)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025{
1026 return RBSlice((BufferObject *)(self), lo, hi, 1,
1027 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count);
1028}
1029
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001030 static PyInt
1031BufferAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001032{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001033 return RBAsItem((BufferObject *)(self), n, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001034 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 NULL);
1036}
1037
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001038 static PyInt
1039BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040{
1041 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1,
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001042 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 NULL);
1044}
1045
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046static PySequenceMethods RangeAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001047 (PyInquiry) RangeLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001049 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */
1050 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */
1051 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */
1052 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */
1053 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054};
1055
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056/* Line range object - Implementation
1057 */
1058
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 static void
1060RangeDestructor(PyObject *self)
1061{
1062 Py_DECREF(((RangeObject *)(self))->buf);
Bram Moolenaar658ada62006-10-03 13:02:36 +00001063 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064}
1065
1066 static PyObject *
1067RangeGetattr(PyObject *self, char *name)
1068{
1069 if (strcmp(name, "start") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001070 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 else if (strcmp(name, "end") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001072 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 else
1074 return Py_FindMethod(RangeMethods, self, name);
1075}
1076
Bram Moolenaar071d4272004-06-13 20:20:40 +00001077/****************/
1078
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001079 static PyInt
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001080RangeAssItem(PyObject *self, PyInt n, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001082 return RBAsItem(((RangeObject *)(self))->buf, n, val,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 ((RangeObject *)(self))->start,
1084 ((RangeObject *)(self))->end,
1085 &((RangeObject *)(self))->end);
1086}
1087
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001088 static PyInt
1089RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090{
1091 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val,
1092 ((RangeObject *)(self))->start,
1093 ((RangeObject *)(self))->end,
1094 &((RangeObject *)(self))->end);
1095}
1096
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097/* Buffer list object - Definitions
1098 */
1099
1100typedef struct
1101{
1102 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001103} BufListObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104
1105static PySequenceMethods BufListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001106 (PyInquiry) BufListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001108 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1109 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */
1110 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1111 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1112 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113};
1114
1115static PyTypeObject BufListType = {
1116 PyObject_HEAD_INIT(0)
1117 0,
1118 "buffer list",
1119 sizeof(BufListObject),
1120 0,
1121
1122 (destructor) 0, /* tp_dealloc, refcount==0 */
1123 (printfunc) 0, /* tp_print, print x */
1124 (getattrfunc) 0, /* tp_getattr, x.attr */
1125 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1126 (cmpfunc) 0, /* tp_compare, x>y */
1127 (reprfunc) 0, /* tp_repr, `x`, print x */
1128
1129 0, /* as number */
1130 &BufListAsSeq, /* as sequence */
1131 0, /* as mapping */
1132
1133 (hashfunc) 0, /* tp_hash, dict(x) */
1134 (ternaryfunc) 0, /* tp_call, x() */
1135 (reprfunc) 0, /* tp_str, str(x) */
1136};
1137
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138/* Window object - Definitions
1139 */
1140
1141static struct PyMethodDef WindowMethods[] = {
1142 /* name, function, calling, documentation */
1143 { NULL, NULL, 0, NULL }
1144};
1145
1146static PyTypeObject WindowType = {
1147 PyObject_HEAD_INIT(0)
1148 0,
1149 "window",
1150 sizeof(WindowObject),
1151 0,
1152
1153 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */
1154 (printfunc) 0, /* tp_print, print x */
1155 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */
1156 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */
1157 (cmpfunc) 0, /* tp_compare, x>y */
1158 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */
1159
1160 0, /* as number */
1161 0, /* as sequence */
1162 0, /* as mapping */
1163
1164 (hashfunc) 0, /* tp_hash, dict(x) */
1165 (ternaryfunc) 0, /* tp_call, x() */
1166 (reprfunc) 0, /* tp_str, str(x) */
1167};
1168
1169/* Window object - Implementation
1170 */
1171
1172 static PyObject *
1173WindowNew(win_T *win)
1174{
1175 /* We need to handle deletion of windows underneath us.
Bram Moolenaare344bea2005-09-01 20:46:49 +00001176 * If we add a "w_python_ref" field to the win_T structure,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 * then we can get at it in win_free() in vim. We then
1178 * need to create only ONE Python object per window - if
1179 * we try to create a second, just INCREF the existing one
1180 * and return it. The (single) Python object referring to
Bram Moolenaare344bea2005-09-01 20:46:49 +00001181 * the window is stored in "w_python_ref".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 * On a win_free() we set the Python object's win_T* field
1183 * to an invalid value. We trap all uses of a window
1184 * object, and reject them if the win_T* field is invalid.
1185 */
1186
1187 WindowObject *self;
1188
Bram Moolenaare344bea2005-09-01 20:46:49 +00001189 if (win->w_python_ref)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001191 self = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 Py_INCREF(self);
1193 }
1194 else
1195 {
1196 self = PyObject_NEW(WindowObject, &WindowType);
1197 if (self == NULL)
1198 return NULL;
1199 self->win = win;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001200 win->w_python_ref = self;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201 }
1202
1203 return (PyObject *)(self);
1204}
1205
1206 static void
1207WindowDestructor(PyObject *self)
1208{
1209 WindowObject *this = (WindowObject *)(self);
1210
1211 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaare344bea2005-09-01 20:46:49 +00001212 this->win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213
Bram Moolenaar658ada62006-10-03 13:02:36 +00001214 Py_DECREF(self);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215}
1216
Bram Moolenaar071d4272004-06-13 20:20:40 +00001217 static PyObject *
1218WindowGetattr(PyObject *self, char *name)
1219{
1220 WindowObject *this = (WindowObject *)(self);
1221
1222 if (CheckWindow(this))
1223 return NULL;
1224
1225 if (strcmp(name, "buffer") == 0)
1226 return (PyObject *)BufferNew(this->win->w_buffer);
1227 else if (strcmp(name, "cursor") == 0)
1228 {
1229 pos_T *pos = &this->win->w_cursor;
1230
1231 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1232 }
1233 else if (strcmp(name, "height") == 0)
1234 return Py_BuildValue("l", (long)(this->win->w_height));
1235#ifdef FEAT_VERTSPLIT
1236 else if (strcmp(name, "width") == 0)
1237 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1238#endif
1239 else if (strcmp(name,"__members__") == 0)
1240 return Py_BuildValue("[sss]", "buffer", "cursor", "height");
1241 else
1242 return Py_FindMethod(WindowMethods, self, name);
1243}
1244
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245/* Window list object - Definitions
1246 */
1247
1248typedef struct
1249{
1250 PyObject_HEAD
1251}
1252WinListObject;
1253
1254static PySequenceMethods WinListAsSeq = {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001255 (PyInquiry) WinListLength, /* sq_length, len(x) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001256 (binaryfunc) 0, /* sq_concat, x+y */
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001257 (PyIntArgFunc) 0, /* sq_repeat, x*n */
1258 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */
1259 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */
1260 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */
1261 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001262};
1263
1264static PyTypeObject WinListType = {
1265 PyObject_HEAD_INIT(0)
1266 0,
1267 "window list",
1268 sizeof(WinListObject),
1269 0,
1270
1271 (destructor) 0, /* tp_dealloc, refcount==0 */
1272 (printfunc) 0, /* tp_print, print x */
1273 (getattrfunc) 0, /* tp_getattr, x.attr */
1274 (setattrfunc) 0, /* tp_setattr, x.attr=v */
1275 (cmpfunc) 0, /* tp_compare, x>y */
1276 (reprfunc) 0, /* tp_repr, `x`, print x */
1277
1278 0, /* as number */
1279 &WinListAsSeq, /* as sequence */
1280 0, /* as mapping */
1281
1282 (hashfunc) 0, /* tp_hash, dict(x) */
1283 (ternaryfunc) 0, /* tp_call, x() */
1284 (reprfunc) 0, /* tp_str, str(x) */
1285};
1286
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287/* Current items object - Definitions
1288 */
1289
1290typedef struct
1291{
1292 PyObject_HEAD
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001293} CurrentObject;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294
1295static PyTypeObject CurrentType = {
1296 PyObject_HEAD_INIT(0)
1297 0,
1298 "current data",
1299 sizeof(CurrentObject),
1300 0,
1301
1302 (destructor) 0, /* tp_dealloc, refcount==0 */
1303 (printfunc) 0, /* tp_print, print x */
1304 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */
1305 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */
1306 (cmpfunc) 0, /* tp_compare, x>y */
1307 (reprfunc) 0, /* tp_repr, `x`, print x */
1308
1309 0, /* as number */
1310 0, /* as sequence */
1311 0, /* as mapping */
1312
1313 (hashfunc) 0, /* tp_hash, dict(x) */
1314 (ternaryfunc) 0, /* tp_call, x() */
1315 (reprfunc) 0, /* tp_str, str(x) */
1316};
1317
1318/* Current items object - Implementation
1319 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320 static PyObject *
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001321CurrentGetattr(PyObject *self UNUSED, char *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322{
1323 if (strcmp(name, "buffer") == 0)
1324 return (PyObject *)BufferNew(curbuf);
1325 else if (strcmp(name, "window") == 0)
1326 return (PyObject *)WindowNew(curwin);
1327 else if (strcmp(name, "line") == 0)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001328 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329 else if (strcmp(name, "range") == 0)
1330 return RangeNew(curbuf, RangeStart, RangeEnd);
1331 else if (strcmp(name,"__members__") == 0)
1332 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
1333 else
1334 {
1335 PyErr_SetString(PyExc_AttributeError, name);
1336 return NULL;
1337 }
1338}
1339
Bram Moolenaar071d4272004-06-13 20:20:40 +00001340 static int
Bram Moolenaar4bdbbf72009-05-21 21:27:43 +00001341CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342{
1343 if (strcmp(name, "line") == 0)
1344 {
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001345 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001346 return -1;
1347
1348 return 0;
1349 }
1350 else
1351 {
1352 PyErr_SetString(PyExc_AttributeError, name);
1353 return -1;
1354 }
1355}
1356
1357/* External interface
1358 */
1359
1360 void
1361python_buffer_free(buf_T *buf)
1362{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001363 if (buf->b_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001365 BufferObject *bp = buf->b_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366 bp->buf = INVALID_BUFFER_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001367 buf->b_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 }
1369}
1370
1371#if defined(FEAT_WINDOWS) || defined(PROTO)
1372 void
1373python_window_free(win_T *win)
1374{
Bram Moolenaare344bea2005-09-01 20:46:49 +00001375 if (win->w_python_ref != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376 {
Bram Moolenaare344bea2005-09-01 20:46:49 +00001377 WindowObject *wp = win->w_python_ref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001378 wp->win = INVALID_WINDOW_VALUE;
Bram Moolenaare344bea2005-09-01 20:46:49 +00001379 win->w_python_ref = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380 }
1381}
1382#endif
1383
1384static BufListObject TheBufferList =
1385{
1386 PyObject_HEAD_INIT(&BufListType)
1387};
1388
1389static WinListObject TheWindowList =
1390{
1391 PyObject_HEAD_INIT(&WinListType)
1392};
1393
1394static CurrentObject TheCurrent =
1395{
1396 PyObject_HEAD_INIT(&CurrentType)
1397};
1398
1399 static int
1400PythonMod_Init(void)
1401{
1402 PyObject *mod;
1403 PyObject *dict;
Bram Moolenaar9774ecc2008-11-20 10:04:53 +00001404 /* The special value is removed from sys.path in Python_Init(). */
1405 static char *(argv[2]) = {"/must>not&exist/foo", NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406
1407 /* Fixups... */
Bram Moolenaar21377c82011-03-26 13:56:48 +01001408 PyType_Ready(&BufferType);
1409 PyType_Ready(&RangeType);
1410 PyType_Ready(&WindowType);
1411 PyType_Ready(&BufListType);
1412 PyType_Ready(&WinListType);
1413 PyType_Ready(&CurrentType);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001414
1415 /* Set sys.argv[] to avoid a crash in warn(). */
1416 PySys_SetArgv(1, argv);
1417
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001418 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001419 dict = PyModule_GetDict(mod);
1420
1421 VimError = Py_BuildValue("s", "vim.error");
1422
1423 PyDict_SetItemString(dict, "error", VimError);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00001424 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList);
1425 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent);
1426 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427
1428 if (PyErr_Occurred())
1429 return -1;
1430
1431 return 0;
1432}
1433
1434/*************************************************************************
1435 * 4. Utility functions for handling the interface between Vim and Python.
1436 */
1437
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438/* Replace a range of lines in the specified buffer. The line numbers are in
1439 * Vim format (1-based). The range is from lo up to, but not including, hi.
1440 * The replacement lines are given as a Python list of string objects. The
1441 * list is checked for validity and correct format. Errors are returned as a
1442 * value of FAIL. The return value is OK on success.
1443 * If OK is returned and len_change is not NULL, *len_change
1444 * is set to the change in the buffer length.
1445 */
1446 static int
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001447SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448{
1449 /* First of all, we check the thpe of the supplied Python object.
1450 * There are three cases:
1451 * 1. NULL, or None - this is a deletion.
1452 * 2. A list - this is a replacement.
1453 * 3. Anything else - this is an error.
1454 */
1455 if (list == Py_None || list == NULL)
1456 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001457 PyInt i;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001458 PyInt n = (int)(hi - lo);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 buf_T *savebuf = curbuf;
1460
1461 PyErr_Clear();
1462 curbuf = buf;
1463
1464 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
1465 PyErr_SetVim(_("cannot save undo information"));
1466 else
1467 {
1468 for (i = 0; i < n; ++i)
1469 {
1470 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1471 {
1472 PyErr_SetVim(_("cannot delete line"));
1473 break;
1474 }
1475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001476 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001477 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00001478 deleted_lines_mark((linenr_T)lo, (long)i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001479 }
1480
1481 curbuf = savebuf;
1482
1483 if (PyErr_Occurred() || VimErrorCheck())
1484 return FAIL;
1485
1486 if (len_change)
1487 *len_change = -n;
1488
1489 return OK;
1490 }
1491 else if (PyList_Check(list))
1492 {
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001493 PyInt i;
1494 PyInt new_len = PyList_Size(list);
1495 PyInt old_len = hi - lo;
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001496 PyInt extra = 0; /* lines added to text, can be negative */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 char **array;
1498 buf_T *savebuf;
1499
1500 if (new_len == 0) /* avoid allocating zero bytes */
1501 array = NULL;
1502 else
1503 {
1504 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
1505 if (array == NULL)
1506 {
1507 PyErr_NoMemory();
1508 return FAIL;
1509 }
1510 }
1511
1512 for (i = 0; i < new_len; ++i)
1513 {
1514 PyObject *line = PyList_GetItem(list, i);
1515
1516 array[i] = StringToLine(line);
1517 if (array[i] == NULL)
1518 {
1519 while (i)
1520 vim_free(array[--i]);
1521 vim_free(array);
1522 return FAIL;
1523 }
1524 }
1525
1526 savebuf = curbuf;
1527
1528 PyErr_Clear();
1529 curbuf = buf;
1530
1531 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
1532 PyErr_SetVim(_("cannot save undo information"));
1533
1534 /* If the size of the range is reducing (ie, new_len < old_len) we
1535 * need to delete some old_len. We do this at the start, by
1536 * repeatedly deleting line "lo".
1537 */
1538 if (!PyErr_Occurred())
1539 {
1540 for (i = 0; i < old_len - new_len; ++i)
1541 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1542 {
1543 PyErr_SetVim(_("cannot delete line"));
1544 break;
1545 }
1546 extra -= i;
1547 }
1548
1549 /* For as long as possible, replace the existing old_len with the
1550 * new old_len. This is a more efficient operation, as it requires
1551 * less memory allocation and freeing.
1552 */
1553 if (!PyErr_Occurred())
1554 {
1555 for (i = 0; i < old_len && i < new_len; ++i)
1556 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
1557 == FAIL)
1558 {
1559 PyErr_SetVim(_("cannot replace line"));
1560 break;
1561 }
1562 }
1563 else
1564 i = 0;
1565
1566 /* Now we may need to insert the remaining new old_len. If we do, we
1567 * must free the strings as we finish with them (we can't pass the
1568 * responsibility to vim in this case).
1569 */
1570 if (!PyErr_Occurred())
1571 {
1572 while (i < new_len)
1573 {
1574 if (ml_append((linenr_T)(lo + i - 1),
1575 (char_u *)array[i], 0, FALSE) == FAIL)
1576 {
1577 PyErr_SetVim(_("cannot insert line"));
1578 break;
1579 }
1580 vim_free(array[i]);
1581 ++i;
1582 ++extra;
1583 }
1584 }
1585
1586 /* Free any left-over old_len, as a result of an error */
1587 while (i < new_len)
1588 {
1589 vim_free(array[i]);
1590 ++i;
1591 }
1592
1593 /* Free the array of old_len. All of its contents have now
1594 * been dealt with (either freed, or the responsibility passed
1595 * to vim.
1596 */
1597 vim_free(array);
1598
1599 /* Adjust marks. Invalidate any which lie in the
1600 * changed range, and move any in the remainder of the buffer.
1601 */
1602 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
1603 (long)MAXLNUM, (long)extra);
1604 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
1605
1606 if (buf == curwin->w_buffer)
Bram Moolenaare7cb9cf2008-06-20 14:32:41 +00001607 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608
1609 curbuf = savebuf;
1610
1611 if (PyErr_Occurred() || VimErrorCheck())
1612 return FAIL;
1613
1614 if (len_change)
1615 *len_change = new_len - old_len;
1616
1617 return OK;
1618 }
1619 else
1620 {
1621 PyErr_BadArgument();
1622 return FAIL;
1623 }
1624}
1625
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626/* Convert a Vim line into a Python string.
1627 * All internal newlines are replaced by null characters.
1628 *
1629 * On errors, the Python exception data is set, and NULL is returned.
1630 */
1631 static PyObject *
1632LineToString(const char *str)
1633{
1634 PyObject *result;
Bram Moolenaar2c45e942008-06-04 11:35:26 +00001635 PyInt len = strlen(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 char *p;
1637
1638 /* Allocate an Python string object, with uninitialised contents. We
1639 * must do it this way, so that we can modify the string in place
1640 * later. See the Python source, Objects/stringobject.c for details.
1641 */
1642 result = PyString_FromStringAndSize(NULL, len);
1643 if (result == NULL)
1644 return NULL;
1645
1646 p = PyString_AsString(result);
1647
1648 while (*str)
1649 {
1650 if (*str == '\n')
1651 *p = '\0';
1652 else
1653 *p = *str;
1654
1655 ++p;
1656 ++str;
1657 }
1658
1659 return result;
1660}
1661
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662
1663/* Don't generate a prototype for the next function, it generates an error on
1664 * newer Python versions. */
1665#if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO)
1666
1667 char *
1668Py_GetProgramName(void)
1669{
1670 return "vim";
1671}
1672#endif /* Python 1.4 */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001673
1674 static void
1675init_structs(void)
1676{
1677 vim_memset(&OutputType, 0, sizeof(OutputType));
1678 OutputType.tp_name = "message";
1679 OutputType.tp_basicsize = sizeof(OutputObject);
1680 OutputType.tp_getattr = OutputGetattr;
1681 OutputType.tp_setattr = OutputSetattr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001682
1683 vim_memset(&RangeType, 0, sizeof(RangeType));
1684 RangeType.tp_name = "range";
1685 RangeType.tp_basicsize = sizeof(RangeObject);
1686 RangeType.tp_dealloc = RangeDestructor;
1687 RangeType.tp_getattr = RangeGetattr;
1688 RangeType.tp_repr = RangeRepr;
1689 RangeType.tp_as_sequence = &RangeAsSeq;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02001690}