blob: 8ddbaca198b3ef08c8f489f300e98ab37a586b9d [file] [log] [blame]
Bram Moolenaardb913952012-06-29 12:54:53 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar170bf1a2010-07-24 23:51:45 +02002 *
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/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020010 * Python extensions by Paul Moore, David Leonard, Roland Puntaier, Nikolay
11 * Pavlov.
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020012 *
13 * Common code for if_python.c and if_python3.c.
14 */
15
Bram Moolenaarc1a995d2012-08-08 16:05:07 +020016#if PY_VERSION_HEX < 0x02050000
Bram Moolenaar9bf703d2019-11-30 19:44:38 +010017typedef int Py_ssize_t; // Python 2.4 and earlier don't have this type.
Bram Moolenaarc1a995d2012-08-08 16:05:07 +020018#endif
19
Bram Moolenaard518f952020-01-01 15:04:17 +010020// Use values that are known to work, others may make Vim crash.
21#define ENC_OPT (enc_utf8 ? "utf-8" : enc_dbcs ? "euc-jp" : (char *)p_enc)
Bram Moolenaard620aa92013-05-17 16:40:06 +020022#define DOPY_FUNC "_vim_pydo"
Bram Moolenaar91805fc2011-06-26 04:01:44 +020023
Bram Moolenaarc09a6d62013-06-10 21:27:29 +020024static const char *vim_special_path = "_vim_path_";
25
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +020026#define PyErr_SET_STRING(exc, str) PyErr_SetString(exc, _(str))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020027#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +020028#define PyErr_SET_VIM(str) PyErr_SET_STRING(VimError, str)
Bram Moolenaar063a46b2014-01-14 16:36:51 +010029#define PyErr_FORMAT(exc, str, arg) PyErr_Format(exc, _(str), arg)
30#define PyErr_FORMAT2(exc, str, arg1, arg2) PyErr_Format(exc, _(str), arg1,arg2)
31#define PyErr_VIM_FORMAT(str, arg) PyErr_FORMAT(VimError, str, arg)
Bram Moolenaarc476e522013-06-23 13:46:40 +020032
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +020033#ifdef USE_LIMITED_API
34// Limited Python API. Need to call only exposed functions and remap macros.
35// PyTypeObject is an opaque struct.
36
37typedef struct {
38 lenfunc sq_length;
39 binaryfunc sq_concat;
40 ssizeargfunc sq_repeat;
41 ssizeargfunc sq_item;
42 void *was_sq_slice;
43 ssizeobjargproc sq_ass_item;
44 void *was_sq_ass_slice;
45 objobjproc sq_contains;
46
47 binaryfunc sq_inplace_concat;
48 ssizeargfunc sq_inplace_repeat;
49} PySequenceMethods;
50
51typedef struct {
52 lenfunc mp_length;
53 binaryfunc mp_subscript;
54 objobjargproc mp_ass_subscript;
55} PyMappingMethods;
56
57// This struct emulates the concrete _typeobject struct to allow the code to
58// work the same way in both limited and full Python APIs.
59struct typeobject_wrapper {
60 const char *tp_name;
61 Py_ssize_t tp_basicsize;
62 unsigned long tp_flags;
63
64 // When adding new slots below, also need to make sure we add ADD_TP_SLOT
65 // call in AddHeapType for it.
66
67 destructor tp_dealloc;
68 reprfunc tp_repr;
69
70 PySequenceMethods *tp_as_sequence;
71 PyMappingMethods *tp_as_mapping;
72
73 ternaryfunc tp_call;
74 getattrofunc tp_getattro;
75 setattrofunc tp_setattro;
76
77 const char *tp_doc;
78
79 traverseproc tp_traverse;
80
81 inquiry tp_clear;
82
83 getiterfunc tp_iter;
84 iternextfunc tp_iternext;
85
86 struct PyMethodDef *tp_methods;
87 struct _typeobject *tp_base;
88 allocfunc tp_alloc;
89 newfunc tp_new;
90 freefunc tp_free;
91};
92
93# define DEFINE_PY_TYPE_OBJECT(type) \
94 static struct typeobject_wrapper type; \
95 static PyTypeObject* type##Ptr = NULL
96
97// PyObject_HEAD_INIT_TYPE and PyObject_FINISH_INIT_TYPE need to come in pairs
98// We first initialize with NULL because the type is not allocated until
99// init_types() is called later. It's in FINISH_INIT_TYPE where we fill the
100// type in with the newly allocated type.
101# define PyObject_HEAD_INIT_TYPE(type) PyObject_HEAD_INIT(NULL)
102# define PyObject_FINISH_INIT_TYPE(obj, type) obj.ob_base.ob_type = type##Ptr
103
104# define Py_TYPE_GET_TP_ALLOC(type) ((allocfunc)PyType_GetSlot(type, Py_tp_alloc))
105# define Py_TYPE_GET_TP_METHODS(type) ((PyMethodDef *)PyType_GetSlot(type, Py_tp_methods))
106
107// PyObject_NEW is not part of stable ABI, but PyObject_Malloc/Init are.
108PyObject* Vim_PyObject_New(PyTypeObject *type, size_t objsize)
109{
110 PyObject *obj = (PyObject *)PyObject_Malloc(objsize);
111 if (obj == NULL)
Yegappan Lakshmanand4e4ecb2023-08-27 18:35:45 +0200112 return PyErr_NoMemory();
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200113 return PyObject_Init(obj, type);
114}
115# undef PyObject_NEW
116# define PyObject_NEW(type, typeobj) ((type *)Vim_PyObject_New(typeobj, sizeof(type)))
117
118// This is a somewhat convoluted because limited API doesn't expose an easy way
119// to get the tp_name field, and so we have to manually reconstruct it as
120// "__module__.__name__" (with __module__ omitted for builtins to emulate
121// Python behavior). Also, some of the more convenient functions like
122// PyUnicode_AsUTF8AndSize and PyType_GetQualName() are not available until
123// late Python 3 versions, and won't be available if you set Py_LIMITED_API too
124// low.
125# define PyErr_FORMAT_TYPE(msg, obj) \
126 do { \
127 PyObject* qualname = PyObject_GetAttrString((PyObject*)(obj)->ob_type, "__qualname__"); \
128 if (qualname == NULL) \
129 { \
130 PyErr_FORMAT(PyExc_TypeError, msg, "(NULL)"); \
131 break; \
132 } \
133 PyObject* module = PyObject_GetAttrString((PyObject*)(obj)->ob_type, "__module__"); \
134 PyObject* full; \
135 if (module == NULL || PyUnicode_CompareWithASCIIString(module, "builtins") == 0 \
136 || PyUnicode_CompareWithASCIIString(module, "__main__") == 0) \
137 { \
138 full = qualname; \
139 Py_INCREF(full); \
140 } \
141 else \
142 full = PyUnicode_FromFormat("%U.%U", module, qualname); \
143 PyObject* full_bytes = PyUnicode_AsUTF8String(full); \
144 const char* full_str = PyBytes_AsString(full_bytes); \
145 full_str = full_str == NULL ? "(NULL)" : full_str; \
146 PyErr_FORMAT(PyExc_TypeError, msg, full_str); \
147 Py_DECREF(qualname); \
148 Py_XDECREF(module); \
149 Py_XDECREF(full); \
150 Py_XDECREF(full_bytes); \
Christian Brabandt75dc1ed2023-08-20 23:19:24 +0200151 } while (0)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200152
153# define PyList_GET_ITEM(list, i) PyList_GetItem(list, i)
154# define PyList_GET_SIZE(o) PyList_Size(o)
155# define PyTuple_GET_ITEM(o, pos) PyTuple_GetItem(o, pos)
156# define PyTuple_GET_SIZE(o) PyTuple_Size(o)
157
158// PyList_SET_ITEM and PyList_SetItem have slightly different behaviors. The
159// former will leave the old item dangling, and the latter will decref on it.
160// Since we only use this on new lists, this difference doesn't matter.
161# define PyList_SET_ITEM(list, i, item) PyList_SetItem(list, i, item)
162
163# if Py_LIMITED_API < 0x03080000
164// PyIter_check only became part of stable ABI in 3.8, and there is no easy way
165// to check for it in the API. We simply return false as a compromise. This
166// does mean we should avoid compiling with stable ABI < 3.8.
167# undef PyIter_Check
168# define PyIter_Check(obj) (FALSE)
169# endif
170
171PyTypeObject* AddHeapType(struct typeobject_wrapper* type_object)
172{
173 PyType_Spec type_spec;
174 type_spec.name = type_object->tp_name;
175 type_spec.basicsize = type_object->tp_basicsize;
176 type_spec.itemsize = 0;
177 type_spec.flags = type_object->tp_flags;
178
179 // We just need to statically allocate a large enough buffer that can hold
180 // all slots. We need to leave a null-terminated slot at the end.
181 PyType_Slot slots[40] = { {0, NULL} };
182 size_t slot_i = 0;
183
184# define ADD_TP_SLOT(slot_name) \
185 if (slot_i >= 40) return NULL; /* this should never happen */ \
186 if (type_object->slot_name != NULL) \
187 { \
188 slots[slot_i].slot = Py_##slot_name; \
189 slots[slot_i].pfunc = (void*)type_object->slot_name; \
190 ++slot_i; \
191 }
192# define ADD_TP_SUB_SLOT(sub_slot, slot_name) \
193 if (slot_i >= 40) return NULL; /* this should never happen */ \
194 if (type_object->sub_slot != NULL && type_object->sub_slot->slot_name != NULL) \
195 { \
196 slots[slot_i].slot = Py_##slot_name; \
197 slots[slot_i].pfunc = (void*)type_object->sub_slot->slot_name; \
198 ++slot_i; \
199 }
200
201 ADD_TP_SLOT(tp_dealloc)
202 ADD_TP_SLOT(tp_repr)
203 ADD_TP_SLOT(tp_call)
204 ADD_TP_SLOT(tp_getattro)
205 ADD_TP_SLOT(tp_setattro)
206 ADD_TP_SLOT(tp_doc)
207 ADD_TP_SLOT(tp_traverse)
208 ADD_TP_SLOT(tp_clear)
209 ADD_TP_SLOT(tp_iter)
210 ADD_TP_SLOT(tp_iternext)
211 ADD_TP_SLOT(tp_methods)
212 ADD_TP_SLOT(tp_base)
213 ADD_TP_SLOT(tp_alloc)
214 ADD_TP_SLOT(tp_new)
215 ADD_TP_SLOT(tp_free)
216
217 ADD_TP_SUB_SLOT(tp_as_sequence, sq_length)
218 ADD_TP_SUB_SLOT(tp_as_sequence, sq_concat)
219 ADD_TP_SUB_SLOT(tp_as_sequence, sq_repeat)
220 ADD_TP_SUB_SLOT(tp_as_sequence, sq_item)
221 ADD_TP_SUB_SLOT(tp_as_sequence, sq_ass_item)
222 ADD_TP_SUB_SLOT(tp_as_sequence, sq_contains)
223 ADD_TP_SUB_SLOT(tp_as_sequence, sq_inplace_concat)
224 ADD_TP_SUB_SLOT(tp_as_sequence, sq_inplace_repeat)
225
226 ADD_TP_SUB_SLOT(tp_as_mapping, mp_length)
227 ADD_TP_SUB_SLOT(tp_as_mapping, mp_subscript)
228 ADD_TP_SUB_SLOT(tp_as_mapping, mp_ass_subscript)
229# undef ADD_TP_SLOT
230# undef ADD_TP_SUB_SLOT
231
232 type_spec.slots = slots;
233
234 PyObject* newtype = PyType_FromSpec(&type_spec);
235 return (PyTypeObject*)newtype;
236}
237
238// Add a heap type, since static types do not work in limited API
239// Each PYTYPE_READY is paired with PYTYPE_CLEANUP.
240//
241// Note that we don't call Py_DECREF(type##Ptr) in clean up. The reason for
242// that in 3.7, it's possible to de-allocate a heap type before all instances
243// are cleared, leading to a crash, whereas in 3.8 the semantics were changed
244// and instances hold strong references to types. Since these types are
245// designed to be static, just keep them around to avoid having to write
246// version-specific handling. Vim does not re-start the Python runtime so there
247// will be no long-term leak.
248# define PYTYPE_READY(type) \
249 type##Ptr = AddHeapType(&(type)); \
250 if (type##Ptr == NULL) \
251 return -1;
252# define PYTYPE_CLEANUP(type) \
253 type##Ptr = NULL;
254
255// Limited API does not provide PyRun_* functions. Need to implement manually
256// using PyCompile and PyEval.
257PyObject* Vim_PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
258{
259 // Just pass "" for filename for now.
260 PyObject* compiled = Py_CompileString(str, "", start);
261 if (compiled == NULL)
262 return NULL;
263
264 PyObject* eval_result = PyEval_EvalCode(compiled, globals, locals);
265 Py_DECREF(compiled);
266 return eval_result;
267}
268int Vim_PyRun_SimpleString(const char *str)
269{
270 // This function emulates CPython's implementation.
271 PyObject* m = PyImport_AddModule("__main__");
272 if (m == NULL)
Yegappan Lakshmanand4e4ecb2023-08-27 18:35:45 +0200273 return -1;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200274 PyObject* d = PyModule_GetDict(m);
275 PyObject* output = Vim_PyRun_String(str, Py_file_input, d, d);
276 if (output == NULL)
277 {
278 PyErr_PrintEx(TRUE);
279 return -1;
280 }
281 Py_DECREF(output);
282 return 0;
283}
284#define PyRun_String Vim_PyRun_String
285#define PyRun_SimpleString Vim_PyRun_SimpleString
286
287#else // !defined(USE_LIMITED_API)
288
289// Full Python API. Can make use of structs and macros directly.
290# define DEFINE_PY_TYPE_OBJECT(type) \
291 static PyTypeObject type; \
292 static PyTypeObject* type##Ptr = &type
293# define PyObject_HEAD_INIT_TYPE(type) PyObject_HEAD_INIT(&type)
294
295# define Py_TYPE_GET_TP_ALLOC(type) type->tp_alloc
296# define Py_TYPE_GET_TP_METHODS(type) type->tp_methods
297
298# define Py_TYPE_NAME(obj) ((obj)->ob_type->tp_name == NULL \
Bram Moolenaarc476e522013-06-23 13:46:40 +0200299 ? "(NULL)" \
kylo2529dac9b12022-03-27 20:05:17 +0100300 : (obj)->ob_type->tp_name)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200301# define PyErr_FORMAT_TYPE(msg, obj) \
302 PyErr_FORMAT(PyExc_TypeError, msg, \
303 Py_TYPE_NAME(obj))
304
305// Add a static type
306# define PYTYPE_READY(type) \
307 if (PyType_Ready(type##Ptr)) \
308 return -1;
309
310#endif
311
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200312
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +0200313#define RAISE_NO_EMPTY_KEYS PyErr_SET_STRING(PyExc_ValueError, \
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200314 N_("empty keys are not allowed"))
315#define RAISE_LOCKED_DICTIONARY PyErr_SET_VIM(N_("dictionary is locked"))
316#define RAISE_LOCKED_LIST PyErr_SET_VIM(N_("list is locked"))
317#define RAISE_UNDO_FAIL PyErr_SET_VIM(N_("cannot save undo information"))
318#define RAISE_DELETE_LINE_FAIL PyErr_SET_VIM(N_("cannot delete line"))
319#define RAISE_INSERT_LINE_FAIL PyErr_SET_VIM(N_("cannot insert line"))
320#define RAISE_REPLACE_LINE_FAIL PyErr_SET_VIM(N_("cannot replace line"))
Bram Moolenaarc476e522013-06-23 13:46:40 +0200321#define RAISE_KEY_ADD_FAIL(key) \
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200322 PyErr_VIM_FORMAT(N_("failed to add key '%s' to dictionary"), key)
Bram Moolenaarc476e522013-06-23 13:46:40 +0200323#define RAISE_INVALID_INDEX_TYPE(idx) \
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200324 PyErr_FORMAT_TYPE(N_("index must be int or slice, not %s"), idx);
Bram Moolenaar35eacd72013-05-30 22:06:33 +0200325
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200326#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
327#define INVALID_WINDOW_VALUE ((win_T *)(-1))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +0200328#define INVALID_TABPAGE_VALUE ((tabpage_T *)(-1))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200329
Bram Moolenaarb52f4c02013-05-21 18:19:38 +0200330typedef void (*rangeinitializer)(void *);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +0200331typedef void (*runner)(const char *, void *
332#ifdef PY_CAN_RECURSE
333 , PyGILState_STATE *
334#endif
335 );
Bram Moolenaarb52f4c02013-05-21 18:19:38 +0200336
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200337static int ConvertFromPyObject(PyObject *, typval_T *);
338static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
Bram Moolenaara9922d62013-05-30 13:01:18 +0200339static int ConvertFromPyMapping(PyObject *, typval_T *);
Bram Moolenaar8110a092016-04-14 15:56:09 +0200340static int ConvertFromPySequence(PyObject *, typval_T *);
Bram Moolenaarcabf80f2013-05-17 16:18:33 +0200341static PyObject *WindowNew(win_T *, tabpage_T *);
342static PyObject *BufferNew (buf_T *);
343static PyObject *LineToString(const char *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200344
345static PyInt RangeStart;
346static PyInt RangeEnd;
347
Bram Moolenaarb52f4c02013-05-21 18:19:38 +0200348static PyObject *globals;
349
Bram Moolenaarf4258302013-06-02 18:20:17 +0200350static PyObject *py_chdir;
351static PyObject *py_fchdir;
352static PyObject *py_getcwd;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +0200353static PyObject *vim_module;
354static PyObject *vim_special_path_object;
Bram Moolenaarf4258302013-06-02 18:20:17 +0200355
Bram Moolenaar79a494d2018-07-22 04:30:21 +0200356#if PY_VERSION_HEX >= 0x030700f0
357static PyObject *py_find_spec;
358#else
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200359static PyObject *py_load_module;
Bram Moolenaar79a494d2018-07-22 04:30:21 +0200360#endif
Bram Moolenaarb999ba22019-02-14 13:28:45 +0100361static PyObject *py_find_module;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200362
363static PyObject *VimError;
364
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200365/*
366 * obtain a lock on the Vim data structures
367 */
368 static void
369Python_Lock_Vim(void)
370{
371}
372
373/*
374 * release a lock on the Vim data structures
375 */
376 static void
377Python_Release_Vim(void)
378{
379}
380
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200381/*
382 * The "todecref" argument holds a pointer to PyObject * that must be
383 * DECREF'ed after returned char_u * is no longer needed or NULL if all what
384 * was needed to generate returned value is object.
385 *
386 * Use Py_XDECREF to decrement reference count.
387 */
388 static char_u *
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200389StringToChars(PyObject *obj, PyObject **todecref)
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200390{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200391 char_u *str;
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200392
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200393 if (PyBytes_Check(obj))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200394 {
395
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200396 if (PyBytes_AsStringAndSize(obj, (char **) &str, NULL) == -1
397 || str == NULL)
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200398 return NULL;
399
400 *todecref = NULL;
401 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200402 else if (PyUnicode_Check(obj))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200403 {
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200404 PyObject *bytes;
405
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +0100406 if (!(bytes = PyUnicode_AsEncodedString(obj, ENC_OPT,
407 ERRORS_ENCODE_ARG)))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200408 return NULL;
409
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +0100410 if (PyBytes_AsStringAndSize(bytes, (char **) &str, NULL) == -1
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200411 || str == NULL)
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200412 {
413 Py_DECREF(bytes);
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200414 return NULL;
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200415 }
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200416
417 *todecref = bytes;
418 }
419 else
420 {
Bram Moolenaarc476e522013-06-23 13:46:40 +0200421#if PY_MAJOR_VERSION < 3
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200422 PyErr_FORMAT_TYPE(N_("expected str() or unicode() instance, but got %s"),
423 obj);
Bram Moolenaarc476e522013-06-23 13:46:40 +0200424#else
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200425 PyErr_FORMAT_TYPE(N_("expected bytes() or str() instance, but got %s"),
426 obj);
Bram Moolenaarc476e522013-06-23 13:46:40 +0200427#endif
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200428 return NULL;
429 }
430
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200431 return (char_u *) str;
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200432}
433
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200434#define NUMBER_LONG 1
435#define NUMBER_INT 2
436#define NUMBER_NATURAL 4
437#define NUMBER_UNSIGNED 8
438
439 static int
440NumberToLong(PyObject *obj, long *result, int flags)
441{
442#if PY_MAJOR_VERSION < 3
443 if (PyInt_Check(obj))
444 {
445 *result = PyInt_AsLong(obj);
446 if (PyErr_Occurred())
447 return -1;
448 }
449 else
450#endif
451 if (PyLong_Check(obj))
452 {
453 *result = PyLong_AsLong(obj);
454 if (PyErr_Occurred())
455 return -1;
456 }
457 else if (PyNumber_Check(obj))
458 {
459 PyObject *num;
460
461 if (!(num = PyNumber_Long(obj)))
462 return -1;
463
464 *result = PyLong_AsLong(num);
465
466 Py_DECREF(num);
467
468 if (PyErr_Occurred())
469 return -1;
470 }
471 else
472 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200473#if PY_MAJOR_VERSION < 3
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200474 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200475 N_("expected int(), long() or something supporting "
Bram Moolenaarc1c3d682013-06-24 21:21:58 +0200476 "coercing to long(), but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200477 obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200478#else
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200479 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200480 N_("expected int() or something supporting coercing to int(), "
Bram Moolenaarc1c3d682013-06-24 21:21:58 +0200481 "but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200482 obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200483#endif
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200484 return -1;
485 }
486
487 if (flags & NUMBER_INT)
488 {
489 if (*result > INT_MAX)
490 {
491 PyErr_SET_STRING(PyExc_OverflowError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200492 N_("value is too large to fit into C int type"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200493 return -1;
494 }
495 else if (*result < INT_MIN)
496 {
497 PyErr_SET_STRING(PyExc_OverflowError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200498 N_("value is too small to fit into C int type"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200499 return -1;
500 }
501 }
502
503 if (flags & NUMBER_NATURAL)
504 {
505 if (*result <= 0)
506 {
507 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar4de6a212014-03-08 16:13:44 +0100508 N_("number must be greater than zero"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200509 return -1;
510 }
511 }
512 else if (flags & NUMBER_UNSIGNED)
513 {
514 if (*result < 0)
515 {
516 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200517 N_("number must be greater or equal to zero"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200518 return -1;
519 }
520 }
521
522 return 0;
523}
524
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200525 static int
526add_string(PyObject *list, char *s)
527{
528 PyObject *string;
529
530 if (!(string = PyString_FromString(s)))
531 return -1;
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200532
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200533 if (PyList_Append(list, string))
534 {
535 Py_DECREF(string);
536 return -1;
537 }
538
539 Py_DECREF(string);
540 return 0;
541}
542
543 static PyObject *
544ObjectDir(PyObject *self, char **attributes)
545{
546 PyMethodDef *method;
547 char **attr;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200548 PyObject *ret;
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200549
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200550 if (!(ret = PyList_New(0)))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200551 return NULL;
552
553 if (self)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200554 for (method = Py_TYPE_GET_TP_METHODS(self->ob_type) ; method->ml_name != NULL ; ++method)
Bram Moolenaar41009372013-07-01 22:03:04 +0200555 if (add_string(ret, (char *)method->ml_name))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200556 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200557 Py_DECREF(ret);
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200558 return NULL;
559 }
560
561 for (attr = attributes ; *attr ; ++attr)
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200562 if (add_string(ret, *attr))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200563 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200564 Py_DECREF(ret);
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200565 return NULL;
566 }
567
568#if PY_MAJOR_VERSION < 3
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200569 if (add_string(ret, "__members__"))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200570 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200571 Py_DECREF(ret);
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200572 return NULL;
573 }
574#endif
575
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200576 return ret;
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200577}
578
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100579// Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200580
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100581// Function to write a line, points to either msg() or emsg().
Bram Moolenaarefc0d942020-10-11 18:05:02 +0200582typedef int (*writefn)(char *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200583
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200584DEFINE_PY_TYPE_OBJECT(OutputType);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200585
586typedef struct
587{
588 PyObject_HEAD
589 long softspace;
590 long error;
591} OutputObject;
592
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200593static char *OutputAttrs[] = {
594 "softspace",
595 NULL
596};
597
598 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200599OutputDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200600{
601 return ObjectDir(self, OutputAttrs);
602}
603
Bram Moolenaar77045652012-09-21 13:46:06 +0200604 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200605OutputSetattr(OutputObject *self, char *name, PyObject *valObject)
Bram Moolenaar77045652012-09-21 13:46:06 +0200606{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200607 if (valObject == NULL)
Bram Moolenaar77045652012-09-21 13:46:06 +0200608 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +0200609 PyErr_SET_STRING(PyExc_AttributeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200610 N_("can't delete OutputObject attributes"));
Bram Moolenaar77045652012-09-21 13:46:06 +0200611 return -1;
612 }
613
614 if (strcmp(name, "softspace") == 0)
615 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200616 if (NumberToLong(valObject, &(self->softspace), NUMBER_UNSIGNED))
Bram Moolenaar77045652012-09-21 13:46:06 +0200617 return -1;
Bram Moolenaar77045652012-09-21 13:46:06 +0200618 return 0;
619 }
620
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200621 PyErr_FORMAT(PyExc_AttributeError, N_("invalid attribute: %s"), name);
Bram Moolenaar77045652012-09-21 13:46:06 +0200622 return -1;
623}
624
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100625// Buffer IO, we write one whole line at a time.
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200626static garray_T io_ga = {0, 0, 1, 80, NULL};
627static writefn old_fn = NULL;
628
629 static void
630PythonIO_Flush(void)
631{
632 if (old_fn != NULL && io_ga.ga_len > 0)
633 {
Bram Moolenaarefc0d942020-10-11 18:05:02 +0200634 ((char *)io_ga.ga_data)[io_ga.ga_len] = NUL;
635 old_fn((char *)io_ga.ga_data);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200636 }
637 io_ga.ga_len = 0;
638}
639
640 static void
641writer(writefn fn, char_u *str, PyInt n)
642{
643 char_u *ptr;
644
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100645 // Flush when switching output function.
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200646 if (fn != old_fn)
647 PythonIO_Flush();
648 old_fn = fn;
649
Bram Moolenaarb98678a2019-10-19 15:18:44 +0200650 // Write each NL separated line. Text after the last NL is kept for
651 // writing later.
652 // For normal messages: Do not output when "got_int" was set. This avoids
653 // a loop gone crazy flooding the terminal with messages. Also for when
654 // "q" is pressed at the more-prompt.
655 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL
656 && (fn == (writefn)emsg || !got_int))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200657 {
658 PyInt len = ptr - str;
659
660 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
661 break;
662
663 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
664 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
Bram Moolenaarefc0d942020-10-11 18:05:02 +0200665 fn((char *)io_ga.ga_data);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200666 str = ptr + 1;
667 n -= len + 1;
668 io_ga.ga_len = 0;
669 }
670
Bram Moolenaarb98678a2019-10-19 15:18:44 +0200671 // Put the remaining text into io_ga for later printing.
672 if (n > 0 && (fn == (writefn)emsg || !got_int)
673 && ga_grow(&io_ga, (int)(n + 1)) == OK)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200674 {
675 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
676 io_ga.ga_len += (int)n;
677 }
678}
679
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200680 static int
681write_output(OutputObject *self, PyObject *string)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200682{
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200683 Py_ssize_t len = 0;
684 char *str = NULL;
685 int error = self->error;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200686
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200687 if (!PyArg_Parse(string, "et#", ENC_OPT, &str, &len))
688 return -1;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200689
690 Py_BEGIN_ALLOW_THREADS
691 Python_Lock_Vim();
Bram Moolenaar7f3a2842019-05-18 15:02:25 +0200692 if (error)
693 emsg_severe = TRUE;
Bram Moolenaar32526b32019-01-19 17:43:09 +0100694 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200695 Python_Release_Vim();
696 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200697 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200698
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200699 return 0;
700}
701
702 static PyObject *
703OutputWrite(OutputObject *self, PyObject *string)
704{
705 if (write_output(self, string))
706 return NULL;
707
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200708 Py_INCREF(Py_None);
709 return Py_None;
710}
711
712 static PyObject *
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200713OutputWritelines(OutputObject *self, PyObject *seq)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200714{
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200715 PyObject *iterator;
716 PyObject *item;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200717
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200718 if (!(iterator = PyObject_GetIter(seq)))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200719 return NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200720
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200721 while ((item = PyIter_Next(iterator)))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200722 {
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200723 if (write_output(self, item))
Bram Moolenaardb913952012-06-29 12:54:53 +0200724 {
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200725 Py_DECREF(iterator);
726 Py_DECREF(item);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200727 return NULL;
728 }
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200729 Py_DECREF(item);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200730 }
731
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200732 Py_DECREF(iterator);
733
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100734 // Iterator may have finished due to an exception
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200735 if (PyErr_Occurred())
736 return NULL;
737
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200738 Py_INCREF(Py_None);
739 return Py_None;
740}
741
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100742 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200743AlwaysNone(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100744{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100745 // do nothing
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100746 Py_INCREF(Py_None);
747 return Py_None;
748}
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200749#define ALWAYS_NONE AlwaysNone(NULL, NULL)
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100750
Bram Moolenaard4247472015-11-02 13:28:59 +0100751 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200752AlwaysFalse(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaard4247472015-11-02 13:28:59 +0100753{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100754 // do nothing
Bram Moolenaare7427f42015-11-10 13:24:20 +0100755 PyObject *ret = Py_False;
756 Py_INCREF(ret);
757 return ret;
Bram Moolenaard4247472015-11-02 13:28:59 +0100758}
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200759#define ALWAYS_FALSE AlwaysFalse(NULL, NULL)
Bram Moolenaard4247472015-11-02 13:28:59 +0100760
761 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200762AlwaysTrue(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaard4247472015-11-02 13:28:59 +0100763{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100764 // do nothing
Bram Moolenaare7427f42015-11-10 13:24:20 +0100765 PyObject *ret = Py_True;
766 Py_INCREF(ret);
767 return ret;
Bram Moolenaard4247472015-11-02 13:28:59 +0100768}
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200769#define ALWAYS_TRUE AlwaysTrue(NULL, NULL)
Bram Moolenaard4247472015-11-02 13:28:59 +0100770
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200771/***************/
772
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200773static struct PyMethodDef OutputMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100774 // name, function, calling, doc
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200775 {"write", (PyCFunction)OutputWrite, METH_O, ""},
776 {"writelines", (PyCFunction)OutputWritelines, METH_O, ""},
Bram Moolenaard4247472015-11-02 13:28:59 +0100777 {"flush", (PyCFunction)AlwaysNone, METH_NOARGS, ""},
778 {"close", (PyCFunction)AlwaysNone, METH_NOARGS, ""},
779 {"isatty", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
780 {"readable", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
781 {"seekable", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
782 {"writable", (PyCFunction)AlwaysTrue, METH_NOARGS, ""},
Bram Moolenaar6d4431e2016-04-21 20:00:56 +0200783 {"closed", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200784 {"__dir__", (PyCFunction)OutputDir, METH_NOARGS, ""},
Bram Moolenaar182dc4f2013-05-21 19:01:55 +0200785 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200786};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200787
788static OutputObject Output =
789{
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200790 PyObject_HEAD_INIT_TYPE(OutputType)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200791 0,
792 0
793};
794
795static OutputObject Error =
796{
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200797 PyObject_HEAD_INIT_TYPE(OutputType)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200798 0,
799 1
800};
801
802 static int
803PythonIO_Init_io(void)
804{
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +0200805 if (PySys_SetObject("stdout", (PyObject *)(void *)&Output))
806 return -1;
807 if (PySys_SetObject("stderr", (PyObject *)(void *)&Error))
808 return -1;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200809
810 if (PyErr_Occurred())
811 {
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000812 emsg(_(e_python_error_initialising_io_object));
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200813 return -1;
814 }
815
816 return 0;
817}
818
Bram Moolenaar79a494d2018-07-22 04:30:21 +0200819#if PY_VERSION_HEX < 0x030700f0
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200820static PyObject *call_load_module(char *name, int len, PyObject *find_module_result);
821
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200822typedef struct
823{
824 PyObject_HEAD
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200825 char *fullname;
826 PyObject *result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200827} LoaderObject;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200828DEFINE_PY_TYPE_OBJECT(LoaderType);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200829
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200830 static void
831LoaderDestructor(LoaderObject *self)
832{
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200833 vim_free(self->fullname);
834 Py_XDECREF(self->result);
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200835 DESTRUCTOR_FINISH(self);
836}
837
838 static PyObject *
839LoaderLoadModule(LoaderObject *self, PyObject *args UNUSED)
840{
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200841 char *fullname = self->fullname;
842 PyObject *result = self->result;
843 PyObject *module;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200844
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200845 if (!fullname)
846 {
847 module = result ? result : Py_None;
848 Py_INCREF(module);
849 return module;
850 }
851
852 module = call_load_module(fullname, (int)STRLEN(fullname), result);
853
854 self->fullname = NULL;
855 self->result = module;
856
857 vim_free(fullname);
858 Py_DECREF(result);
859
860 if (!module)
861 {
862 if (PyErr_Occurred())
863 return NULL;
864
865 Py_INCREF(Py_None);
866 return Py_None;
867 }
868
869 Py_INCREF(module);
870 return module;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200871}
872
873static struct PyMethodDef LoaderMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100874 // name, function, calling, doc
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200875 {"load_module", (PyCFunction)LoaderLoadModule, METH_VARARGS, ""},
876 { NULL, NULL, 0, NULL}
877};
Bram Moolenaar79a494d2018-07-22 04:30:21 +0200878#endif
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200879
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100880/*
881 * Check to see whether a Vim error has been reported, or a keyboard
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200882 * interrupt has been detected.
883 */
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200884 static void
885VimTryStart(void)
886{
887 ++trylevel;
888}
889
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200890 static int
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200891VimTryEnd(void)
892{
893 --trylevel;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100894 // Without this it stops processing all subsequent Vim script commands and
895 // generates strange error messages if I e.g. try calling Test() in a cycle
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200896 did_emsg = FALSE;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100897 // Keyboard interrupt should be preferred over anything else
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200898 if (got_int)
899 {
Bram Moolenaar4315f262014-01-31 14:54:04 +0100900 if (did_throw)
Bram Moolenaard6b8a522013-11-11 01:05:48 +0100901 discard_current_exception();
Bram Moolenaard6b8a522013-11-11 01:05:48 +0100902 got_int = FALSE;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200903 PyErr_SetNone(PyExc_KeyboardInterrupt);
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200904 return -1;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200905 }
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100906 else if (msg_list != NULL && *msg_list != NULL)
907 {
908 int should_free;
Bram Moolenaarb1443b42019-01-13 23:51:14 +0100909 char *msg;
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100910
911 msg = get_exception_string(*msg_list, ET_ERROR, NULL, &should_free);
912
913 if (msg == NULL)
914 {
915 PyErr_NoMemory();
916 return -1;
917 }
918
Bram Moolenaarb1443b42019-01-13 23:51:14 +0100919 PyErr_SetVim(msg);
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100920
921 free_global_msglist();
922
923 if (should_free)
924 vim_free(msg);
925
926 return -1;
927 }
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200928 else if (!did_throw)
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200929 return (PyErr_Occurred() ? -1 : 0);
Bram Moolenaar86181df2020-05-11 23:14:04 +0200930 // Python exception is preferred over Vim one; unlikely to occur though
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200931 else if (PyErr_Occurred())
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200932 {
Bram Moolenaar4315f262014-01-31 14:54:04 +0100933 discard_current_exception();
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200934 return -1;
935 }
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100936 // Finally transform Vim script exception to python one
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200937 else
938 {
Bram Moolenaar41009372013-07-01 22:03:04 +0200939 PyErr_SetVim((char *)current_exception->value);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200940 discard_current_exception();
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200941 return -1;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200942 }
943}
944
945 static int
946VimCheckInterrupt(void)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200947{
948 if (got_int)
949 {
950 PyErr_SetNone(PyExc_KeyboardInterrupt);
951 return 1;
952 }
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200953 return 0;
954}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200955
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100956// Vim module - Implementation
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200957
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200958 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +0200959VimCommand(PyObject *self UNUSED, PyObject *string)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200960{
Bram Moolenaar389a1792013-06-23 13:00:44 +0200961 char_u *cmd;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200962 PyObject *ret;
Bram Moolenaar389a1792013-06-23 13:00:44 +0200963 PyObject *todecref;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200964
Bram Moolenaar389a1792013-06-23 13:00:44 +0200965 if (!(cmd = StringToChars(string, &todecref)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200966 return NULL;
967
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200968 Py_BEGIN_ALLOW_THREADS
969 Python_Lock_Vim();
970
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200971 VimTryStart();
Bram Moolenaar389a1792013-06-23 13:00:44 +0200972 do_cmdline_cmd(cmd);
Bram Moolenaara4d158b2022-08-14 14:17:45 +0100973 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200974
975 Python_Release_Vim();
976 Py_END_ALLOW_THREADS
977
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200978 if (VimTryEnd())
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200979 ret = NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200980 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200981 ret = Py_None;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200982
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200983 Py_XINCREF(ret);
Bram Moolenaar389a1792013-06-23 13:00:44 +0200984 Py_XDECREF(todecref);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200985 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200986}
987
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200988/*
989 * Function to translate a typval_T into a PyObject; this will recursively
990 * translate lists/dictionaries into their Python equivalents.
991 *
992 * The depth parameter is to avoid infinite recursion, set it to 1 when
993 * you call VimToPython.
994 */
995 static PyObject *
Bram Moolenaarb38caae2013-05-29 22:39:52 +0200996VimToPython(typval_T *our_tv, int depth, PyObject *lookup_dict)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200997{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200998 PyObject *ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200999 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +02001000 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001001
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001002 // Avoid infinite recursion
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001003 if (depth > 100)
1004 {
1005 Py_INCREF(Py_None);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001006 ret = Py_None;
1007 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001008 }
1009
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001010 // Check if we run into a recursive loop. The item must be in lookup_dict
1011 // then and we can use it again.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001012 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1013 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1014 {
Bram Moolenaardb913952012-06-29 12:54:53 +02001015 sprintf(ptrBuf, "%p",
1016 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
1017 : (void *)our_tv->vval.v_dict);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001018
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001019 if ((ret = PyDict_GetItemString(lookup_dict, ptrBuf)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001020 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001021 Py_INCREF(ret);
1022 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001023 }
1024 }
1025
1026 if (our_tv->v_type == VAR_STRING)
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001027 ret = PyString_FromString(our_tv->vval.v_string == NULL
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02001028 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001029 else if (our_tv->v_type == VAR_NUMBER)
1030 {
1031 char buf[NUMBUFLEN];
1032
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001033 // For backwards compatibility numbers are stored as strings.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001034 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
Bram Moolenaar41009372013-07-01 22:03:04 +02001035 ret = PyString_FromString((char *)buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001036 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001037 else if (our_tv->v_type == VAR_FLOAT)
1038 {
1039 char buf[NUMBUFLEN];
1040
1041 sprintf(buf, "%f", our_tv->vval.v_float);
Bram Moolenaar41009372013-07-01 22:03:04 +02001042 ret = PyString_FromString((char *)buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001043 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001044 else if (our_tv->v_type == VAR_LIST)
1045 {
1046 list_T *list = our_tv->vval.v_list;
1047 listitem_T *curr;
1048
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001049 if (list == NULL)
1050 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001051
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001052 if (!(ret = PyList_New(0)))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001053 return NULL;
1054
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001055 if (PyDict_SetItemString(lookup_dict, ptrBuf, ret))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001056 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001057 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001058 return NULL;
1059 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001060
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02001061 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001062 FOR_ALL_LIST_ITEMS(list, curr)
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001063 {
Bram Moolenaarb38caae2013-05-29 22:39:52 +02001064 if (!(newObj = VimToPython(&curr->li_tv, depth + 1, lookup_dict)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001065 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001066 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001067 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001068 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001069 if (PyList_Append(ret, newObj))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001070 {
1071 Py_DECREF(newObj);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001072 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001073 return NULL;
1074 }
1075 Py_DECREF(newObj);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001076 }
1077 }
1078 else if (our_tv->v_type == VAR_DICT)
1079 {
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001080
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001081 hashtab_T *ht;
1082 long_u todo;
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001083 hashitem_T *hi;
1084 dictitem_T *di;
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001085
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001086 if (our_tv->vval.v_dict == NULL)
1087 return NULL;
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001088 ht = &our_tv->vval.v_dict->dv_hashtab;
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001089
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001090 if (!(ret = PyDict_New()))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001091 return NULL;
1092
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001093 if (PyDict_SetItemString(lookup_dict, ptrBuf, ret))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001094 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001095 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001096 return NULL;
1097 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001098
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001099 todo = ht->ht_used;
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001100 for (hi = ht->ht_array; todo > 0; ++hi)
1101 {
1102 if (!HASHITEM_EMPTY(hi))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001103 {
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001104 --todo;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001105
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001106 di = dict_lookup(hi);
Bram Moolenaarb38caae2013-05-29 22:39:52 +02001107 if (!(newObj = VimToPython(&di->di_tv, depth + 1, lookup_dict)))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001108 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001109 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001110 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001111 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001112 if (PyDict_SetItemString(ret, (char *)hi->hi_key, newObj))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001113 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001114 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001115 Py_DECREF(newObj);
1116 return NULL;
1117 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001118 }
1119 }
1120 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001121 else if (our_tv->v_type == VAR_BOOL)
Bram Moolenaar520e1e42016-01-23 19:46:28 +01001122 {
1123 if (our_tv->vval.v_number == VVAL_FALSE)
1124 {
1125 ret = Py_False;
1126 Py_INCREF(ret);
1127 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001128 else
Bram Moolenaar520e1e42016-01-23 19:46:28 +01001129 {
1130 ret = Py_True;
1131 Py_INCREF(ret);
1132 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001133 return ret;
1134 }
1135 else if (our_tv->v_type == VAR_SPECIAL)
1136 {
1137 Py_INCREF(Py_None);
1138 ret = Py_None;
Bram Moolenaar520e1e42016-01-23 19:46:28 +01001139 return ret;
1140 }
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01001141 else if (our_tv->v_type == VAR_BLOB)
1142 ret = PyBytes_FromStringAndSize(
1143 (char*) our_tv->vval.v_blob->bv_ga.ga_data,
1144 (Py_ssize_t) our_tv->vval.v_blob->bv_ga.ga_len);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001145 else
1146 {
1147 Py_INCREF(Py_None);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001148 ret = Py_None;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001149 }
1150
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001151 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001152}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001153
1154 static PyObject *
Bram Moolenaar774267b2013-05-21 20:51:59 +02001155VimEval(PyObject *self UNUSED, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001156{
Bram Moolenaar389a1792013-06-23 13:00:44 +02001157 char_u *expr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001158 typval_T *our_tv;
Bram Moolenaar389a1792013-06-23 13:00:44 +02001159 PyObject *string;
1160 PyObject *todecref;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001161 PyObject *ret;
Bram Moolenaar389a1792013-06-23 13:00:44 +02001162 PyObject *lookup_dict;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001163
Bram Moolenaar389a1792013-06-23 13:00:44 +02001164 if (!PyArg_ParseTuple(args, "O", &string))
1165 return NULL;
1166
1167 if (!(expr = StringToChars(string, &todecref)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001168 return NULL;
1169
1170 Py_BEGIN_ALLOW_THREADS
1171 Python_Lock_Vim();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001172 VimTryStart();
Bram Moolenaar389a1792013-06-23 13:00:44 +02001173 our_tv = eval_expr(expr, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001174 Python_Release_Vim();
1175 Py_END_ALLOW_THREADS
1176
Bram Moolenaar389a1792013-06-23 13:00:44 +02001177 Py_XDECREF(todecref);
1178
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001179 if (VimTryEnd())
1180 return NULL;
1181
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001182 if (our_tv == NULL)
1183 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001184 PyErr_SET_VIM(N_("invalid expression"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001185 return NULL;
1186 }
1187
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001188 // Convert the Vim type into a Python type. Create a dictionary that's
1189 // used to check for recursive loops.
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02001190 if (!(lookup_dict = PyDict_New()))
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001191 ret = NULL;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02001192 else
1193 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001194 ret = VimToPython(our_tv, 1, lookup_dict);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02001195 Py_DECREF(lookup_dict);
1196 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001197
1198
1199 Py_BEGIN_ALLOW_THREADS
1200 Python_Lock_Vim();
1201 free_tv(our_tv);
1202 Python_Release_Vim();
1203 Py_END_ALLOW_THREADS
1204
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001205 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001206}
1207
Bram Moolenaardb913952012-06-29 12:54:53 +02001208static PyObject *ConvertToPyObject(typval_T *);
1209
1210 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02001211VimEvalPy(PyObject *self UNUSED, PyObject *string)
Bram Moolenaardb913952012-06-29 12:54:53 +02001212{
Bram Moolenaardb913952012-06-29 12:54:53 +02001213 typval_T *our_tv;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001214 PyObject *ret;
Bram Moolenaar389a1792013-06-23 13:00:44 +02001215 char_u *expr;
1216 PyObject *todecref;
Bram Moolenaardb913952012-06-29 12:54:53 +02001217
Bram Moolenaar389a1792013-06-23 13:00:44 +02001218 if (!(expr = StringToChars(string, &todecref)))
Bram Moolenaardb913952012-06-29 12:54:53 +02001219 return NULL;
1220
1221 Py_BEGIN_ALLOW_THREADS
1222 Python_Lock_Vim();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001223 VimTryStart();
Bram Moolenaar389a1792013-06-23 13:00:44 +02001224 our_tv = eval_expr(expr, NULL);
Bram Moolenaardb913952012-06-29 12:54:53 +02001225 Python_Release_Vim();
1226 Py_END_ALLOW_THREADS
1227
Bram Moolenaar389a1792013-06-23 13:00:44 +02001228 Py_XDECREF(todecref);
1229
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001230 if (VimTryEnd())
1231 return NULL;
1232
Bram Moolenaardb913952012-06-29 12:54:53 +02001233 if (our_tv == NULL)
1234 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001235 PyErr_SET_VIM(N_("invalid expression"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001236 return NULL;
1237 }
1238
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001239 ret = ConvertToPyObject(our_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +02001240 Py_BEGIN_ALLOW_THREADS
1241 Python_Lock_Vim();
1242 free_tv(our_tv);
1243 Python_Release_Vim();
1244 Py_END_ALLOW_THREADS
1245
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001246 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02001247}
1248
1249 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02001250VimStrwidth(PyObject *self UNUSED, PyObject *string)
Bram Moolenaardb913952012-06-29 12:54:53 +02001251{
Bram Moolenaar389a1792013-06-23 13:00:44 +02001252 char_u *str;
1253 PyObject *todecref;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001254 int len;
Bram Moolenaardb913952012-06-29 12:54:53 +02001255
Bram Moolenaar389a1792013-06-23 13:00:44 +02001256 if (!(str = StringToChars(string, &todecref)))
Bram Moolenaardb913952012-06-29 12:54:53 +02001257 return NULL;
1258
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001259 len = mb_string2cells(str, (int)STRLEN(str));
Bram Moolenaar389a1792013-06-23 13:00:44 +02001260
1261 Py_XDECREF(todecref);
1262
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001263 return PyLong_FromLong(len);
Bram Moolenaardb913952012-06-29 12:54:53 +02001264}
1265
Bram Moolenaarf4258302013-06-02 18:20:17 +02001266 static PyObject *
1267_VimChdir(PyObject *_chdir, PyObject *args, PyObject *kwargs)
1268{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001269 PyObject *ret;
Bram Moolenaarf4258302013-06-02 18:20:17 +02001270 PyObject *newwd;
1271 PyObject *todecref;
1272 char_u *new_dir;
1273
Bram Moolenaard4209d22013-06-05 20:34:15 +02001274 if (_chdir == NULL)
1275 return NULL;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001276 if (!(ret = PyObject_Call(_chdir, args, kwargs)))
Bram Moolenaarf4258302013-06-02 18:20:17 +02001277 return NULL;
1278
1279 if (!(newwd = PyObject_CallFunctionObjArgs(py_getcwd, NULL)))
1280 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001281 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001282 return NULL;
1283 }
1284
1285 if (!(new_dir = StringToChars(newwd, &todecref)))
1286 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001287 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001288 Py_DECREF(newwd);
1289 return NULL;
1290 }
1291
1292 VimTryStart();
1293
1294 if (vim_chdir(new_dir))
1295 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001296 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001297 Py_DECREF(newwd);
1298 Py_XDECREF(todecref);
1299
1300 if (VimTryEnd())
1301 return NULL;
1302
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001303 PyErr_SET_VIM(N_("failed to change directory"));
Bram Moolenaarf4258302013-06-02 18:20:17 +02001304 return NULL;
1305 }
1306
1307 Py_DECREF(newwd);
1308 Py_XDECREF(todecref);
1309
Bram Moolenaar1063f3d2019-05-07 22:06:52 +02001310 post_chdir(CDSCOPE_GLOBAL);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001311
1312 if (VimTryEnd())
1313 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001314 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001315 return NULL;
1316 }
1317
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001318 return ret;
Bram Moolenaarf4258302013-06-02 18:20:17 +02001319}
1320
1321 static PyObject *
1322VimChdir(PyObject *self UNUSED, PyObject *args, PyObject *kwargs)
1323{
1324 return _VimChdir(py_chdir, args, kwargs);
1325}
1326
1327 static PyObject *
1328VimFchdir(PyObject *self UNUSED, PyObject *args, PyObject *kwargs)
1329{
1330 return _VimChdir(py_fchdir, args, kwargs);
1331}
1332
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001333typedef struct {
1334 PyObject *callable;
1335 PyObject *result;
1336} map_rtp_data;
1337
1338 static void
1339map_rtp_callback(char_u *path, void *_data)
1340{
1341 void **data = (void **) _data;
1342 PyObject *pathObject;
1343 map_rtp_data *mr_data = *((map_rtp_data **) data);
1344
Bram Moolenaar41009372013-07-01 22:03:04 +02001345 if (!(pathObject = PyString_FromString((char *)path)))
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001346 {
1347 *data = NULL;
1348 return;
1349 }
1350
1351 mr_data->result = PyObject_CallFunctionObjArgs(mr_data->callable,
1352 pathObject, NULL);
1353
1354 Py_DECREF(pathObject);
1355
1356 if (!mr_data->result || mr_data->result != Py_None)
1357 *data = NULL;
1358 else
1359 {
1360 Py_DECREF(mr_data->result);
1361 mr_data->result = NULL;
1362 }
1363}
1364
1365 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02001366VimForeachRTP(PyObject *self UNUSED, PyObject *callable)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001367{
1368 map_rtp_data data;
1369
Bram Moolenaar389a1792013-06-23 13:00:44 +02001370 data.callable = callable;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001371 data.result = NULL;
1372
Bram Moolenaar7f8989d2016-03-12 22:11:39 +01001373 do_in_runtimepath(NULL, 0, &map_rtp_callback, &data);
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001374
1375 if (data.result == NULL)
1376 {
1377 if (PyErr_Occurred())
1378 return NULL;
1379 else
1380 {
1381 Py_INCREF(Py_None);
1382 return Py_None;
1383 }
1384 }
1385 return data.result;
1386}
1387
1388/*
1389 * _vim_runtimepath_ special path implementation.
1390 */
1391
1392 static void
1393map_finder_callback(char_u *path, void *_data)
1394{
1395 void **data = (void **) _data;
1396 PyObject *list = *((PyObject **) data);
1397 PyObject *pathObject1, *pathObject2;
1398 char *pathbuf;
1399 size_t pathlen;
1400
1401 pathlen = STRLEN(path);
1402
1403#if PY_MAJOR_VERSION < 3
1404# define PY_MAIN_DIR_STRING "python2"
1405#else
1406# define PY_MAIN_DIR_STRING "python3"
1407#endif
1408#define PY_ALTERNATE_DIR_STRING "pythonx"
1409
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001410#define PYTHONX_STRING_LENGTH 7 // STRLEN("pythonx")
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001411 if (!(pathbuf = PyMem_New(char,
1412 pathlen + STRLEN(PATHSEPSTR) + PYTHONX_STRING_LENGTH + 1)))
1413 {
1414 PyErr_NoMemory();
1415 *data = NULL;
1416 return;
1417 }
1418
1419 mch_memmove(pathbuf, path, pathlen + 1);
1420 add_pathsep((char_u *) pathbuf);
1421
1422 pathlen = STRLEN(pathbuf);
1423 mch_memmove(pathbuf + pathlen, PY_MAIN_DIR_STRING,
1424 PYTHONX_STRING_LENGTH + 1);
1425
1426 if (!(pathObject1 = PyString_FromString(pathbuf)))
1427 {
1428 *data = NULL;
1429 PyMem_Free(pathbuf);
1430 return;
1431 }
1432
1433 mch_memmove(pathbuf + pathlen, PY_ALTERNATE_DIR_STRING,
1434 PYTHONX_STRING_LENGTH + 1);
1435
1436 if (!(pathObject2 = PyString_FromString(pathbuf)))
1437 {
1438 Py_DECREF(pathObject1);
1439 PyMem_Free(pathbuf);
1440 *data = NULL;
1441 return;
1442 }
1443
1444 PyMem_Free(pathbuf);
1445
1446 if (PyList_Append(list, pathObject1)
1447 || PyList_Append(list, pathObject2))
1448 *data = NULL;
1449
1450 Py_DECREF(pathObject1);
1451 Py_DECREF(pathObject2);
1452}
1453
1454 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001455Vim_GetPaths(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001456{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001457 PyObject *ret;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001458
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001459 if (!(ret = PyList_New(0)))
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001460 return NULL;
1461
Bram Moolenaar7f8989d2016-03-12 22:11:39 +01001462 do_in_runtimepath(NULL, 0, &map_finder_callback, ret);
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001463
1464 if (PyErr_Occurred())
1465 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001466 Py_DECREF(ret);
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001467 return NULL;
1468 }
1469
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001470 return ret;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001471}
1472
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001473#if PY_VERSION_HEX >= 0x030700f0
1474 static PyObject *
1475FinderFindSpec(PyObject *self, PyObject *args)
1476{
1477 char *fullname;
1478 PyObject *paths;
1479 PyObject *target = Py_None;
1480 PyObject *spec;
1481
1482 if (!PyArg_ParseTuple(args, "s|O", &fullname, &target))
1483 return NULL;
1484
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001485 if (!(paths = Vim_GetPaths(self, NULL)))
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001486 return NULL;
1487
Bram Moolenaarde5b3802019-03-30 12:51:22 +01001488 spec = PyObject_CallFunction(py_find_spec, "sOO", fullname, paths, target);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001489
1490 Py_DECREF(paths);
1491
1492 if (!spec)
1493 {
1494 if (PyErr_Occurred())
1495 return NULL;
1496
1497 Py_INCREF(Py_None);
1498 return Py_None;
1499 }
1500
1501 return spec;
1502}
Bram Moolenaar0b0ad352019-05-20 21:52:45 +02001503
1504 static PyObject *
1505FinderFindModule(PyObject* self UNUSED, PyObject* args UNUSED)
1506{
1507 // Apparently returning None works.
1508 Py_INCREF(Py_None);
1509 return Py_None;
1510}
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001511#else
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001512 static PyObject *
1513call_load_module(char *name, int len, PyObject *find_module_result)
1514{
1515 PyObject *fd, *pathname, *description;
1516
Bram Moolenaarc476e522013-06-23 13:46:40 +02001517 if (!PyTuple_Check(find_module_result))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001518 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001519 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001520 N_("expected 3-tuple as imp.find_module() result, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001521 find_module_result);
Bram Moolenaarc476e522013-06-23 13:46:40 +02001522 return NULL;
1523 }
1524 if (PyTuple_GET_SIZE(find_module_result) != 3)
1525 {
1526 PyErr_FORMAT(PyExc_TypeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001527 N_("expected 3-tuple as imp.find_module() result, but got "
1528 "tuple of size %d"),
Bram Moolenaarc476e522013-06-23 13:46:40 +02001529 (int) PyTuple_GET_SIZE(find_module_result));
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001530 return NULL;
1531 }
1532
1533 if (!(fd = PyTuple_GET_ITEM(find_module_result, 0))
1534 || !(pathname = PyTuple_GET_ITEM(find_module_result, 1))
1535 || !(description = PyTuple_GET_ITEM(find_module_result, 2)))
1536 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02001537 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001538 N_("internal error: imp.find_module returned tuple with NULL"));
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001539 return NULL;
1540 }
1541
1542 return PyObject_CallFunction(py_load_module,
1543 "s#OOO", name, len, fd, pathname, description);
1544}
1545
1546 static PyObject *
1547find_module(char *fullname, char *tail, PyObject *new_path)
1548{
1549 PyObject *find_module_result;
1550 PyObject *module;
1551 char *dot;
1552
Bram Moolenaar41009372013-07-01 22:03:04 +02001553 if ((dot = (char *)vim_strchr((char_u *) tail, '.')))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001554 {
1555 /*
Bram Moolenaaredb07a22013-06-12 18:13:38 +02001556 * There is a dot in the name: call find_module recursively without the
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001557 * first component
1558 */
1559 PyObject *newest_path;
1560 int partlen = (int) (dot - 1 - tail);
1561
1562 if (!(find_module_result = PyObject_CallFunction(py_find_module,
1563 "s#O", tail, partlen, new_path)))
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001564 {
1565 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ImportError))
1566 PyErr_Clear();
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001567 return NULL;
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001568 }
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001569
1570 if (!(module = call_load_module(
1571 fullname,
1572 ((int) (tail - fullname)) + partlen,
1573 find_module_result)))
1574 {
1575 Py_DECREF(find_module_result);
1576 return NULL;
1577 }
1578
1579 Py_DECREF(find_module_result);
1580
1581 if (!(newest_path = PyObject_GetAttrString(module, "__path__")))
1582 {
1583 Py_DECREF(module);
1584 return NULL;
1585 }
1586
1587 Py_DECREF(module);
1588
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001589 find_module_result = find_module(fullname, dot + 1, newest_path);
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001590
1591 Py_DECREF(newest_path);
1592
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001593 return find_module_result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001594 }
1595 else
1596 {
1597 if (!(find_module_result = PyObject_CallFunction(py_find_module,
1598 "sO", tail, new_path)))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001599 {
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001600 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ImportError))
1601 PyErr_Clear();
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001602 return NULL;
1603 }
1604
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001605 return find_module_result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001606 }
1607}
1608
1609 static PyObject *
1610FinderFindModule(PyObject *self, PyObject *args)
1611{
1612 char *fullname;
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001613 PyObject *result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001614 PyObject *new_path;
1615 LoaderObject *loader;
1616
1617 if (!PyArg_ParseTuple(args, "s", &fullname))
1618 return NULL;
1619
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001620 if (!(new_path = Vim_GetPaths(self, NULL)))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001621 return NULL;
1622
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001623 result = find_module(fullname, fullname, new_path);
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001624
1625 Py_DECREF(new_path);
1626
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001627 if (!result)
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001628 {
Bram Moolenaar7e85d3d2013-06-23 16:40:39 +02001629 if (PyErr_Occurred())
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001630 return NULL;
Bram Moolenaar7e85d3d2013-06-23 16:40:39 +02001631
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001632 Py_INCREF(Py_None);
1633 return Py_None;
1634 }
1635
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001636 if (!(fullname = (char *)vim_strsave((char_u *)fullname)))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001637 {
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001638 Py_DECREF(result);
1639 PyErr_NoMemory();
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001640 return NULL;
1641 }
1642
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001643 if (!(loader = PyObject_NEW(LoaderObject, LoaderTypePtr)))
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001644 {
1645 vim_free(fullname);
1646 Py_DECREF(result);
1647 return NULL;
1648 }
1649
1650 loader->fullname = fullname;
1651 loader->result = result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001652
1653 return (PyObject *) loader;
1654}
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001655#endif
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001656
1657 static PyObject *
1658VimPathHook(PyObject *self UNUSED, PyObject *args)
1659{
1660 char *path;
1661
1662 if (PyArg_ParseTuple(args, "s", &path)
1663 && STRCMP(path, vim_special_path) == 0)
1664 {
1665 Py_INCREF(vim_module);
1666 return vim_module;
1667 }
1668
1669 PyErr_Clear();
1670 PyErr_SetNone(PyExc_ImportError);
1671 return NULL;
1672}
1673
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001674/*
1675 * Vim module - Definitions
1676 */
1677
1678static struct PyMethodDef VimMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001679 // name, function, calling, documentation
Bram Moolenaar389a1792013-06-23 13:00:44 +02001680 {"command", VimCommand, METH_O, "Execute a Vim ex-mode command" },
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001681 {"eval", VimEval, METH_VARARGS, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar86181df2020-05-11 23:14:04 +02001682 {"bindeval", VimEvalPy, METH_O, "Like eval(), but returns objects attached to Vim ones"},
Bram Moolenaar389a1792013-06-23 13:00:44 +02001683 {"strwidth", VimStrwidth, METH_O, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001684 {"chdir", (PyCFunction)(void *)VimChdir, METH_VARARGS|METH_KEYWORDS, "Change directory"},
1685 {"fchdir", (PyCFunction)(void *)VimFchdir, METH_VARARGS|METH_KEYWORDS, "Change directory"},
Bram Moolenaar389a1792013-06-23 13:00:44 +02001686 {"foreach_rtp", VimForeachRTP, METH_O, "Call given callable for each path in &rtp"},
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001687#if PY_VERSION_HEX >= 0x030700f0
1688 {"find_spec", FinderFindSpec, METH_VARARGS, "Internal use only, returns spec object for any input it receives"},
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001689#endif
Bram Moolenaar0b0ad352019-05-20 21:52:45 +02001690 {"find_module", FinderFindModule, METH_VARARGS, "Internal use only, returns loader object for any input it receives"},
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001691 {"path_hook", VimPathHook, METH_VARARGS, "Hook function to install in sys.path_hooks"},
1692 {"_get_paths", (PyCFunction)Vim_GetPaths, METH_NOARGS, "Get &rtp-based additions to sys.path"},
1693 { NULL, NULL, 0, NULL}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001694};
1695
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001696/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001697 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001698 */
1699
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001700DEFINE_PY_TYPE_OBJECT(IterType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001701
1702typedef PyObject *(*nextfun)(void **);
1703typedef void (*destructorfun)(void *);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001704typedef int (*traversefun)(void *, visitproc, void *);
1705typedef int (*clearfun)(void **);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001706
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001707// Main purpose of this object is removing the need for do python
1708// initialization (i.e. PyType_Ready and setting type attributes) for a big
1709// bunch of objects.
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001710typedef struct
1711{
1712 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001713 void *cur;
1714 nextfun next;
1715 destructorfun destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001716 traversefun traverse;
1717 clearfun clear;
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001718 PyObject *iter_object;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001719} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001720
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001721 static PyObject *
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001722IterNew(void *start, destructorfun destruct, nextfun next, traversefun traverse,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001723 clearfun clear, PyObject *iter_object)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001724{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001725 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001726
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001727 self = PyObject_GC_New(IterObject, IterTypePtr);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001728 self->cur = start;
1729 self->next = next;
1730 self->destruct = destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001731 self->traverse = traverse;
1732 self->clear = clear;
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001733 self->iter_object = iter_object;
1734
1735 if (iter_object)
1736 Py_INCREF(iter_object);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001737
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001738 return (PyObject *)(self);
1739}
1740
1741 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02001742IterDestructor(IterObject *self)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001743{
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001744 if (self->iter_object)
1745 Py_DECREF(self->iter_object);
Bram Moolenaar774267b2013-05-21 20:51:59 +02001746 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaard6e39182013-05-21 18:30:34 +02001747 self->destruct(self->cur);
Bram Moolenaar774267b2013-05-21 20:51:59 +02001748 PyObject_GC_Del((void *)(self));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001749}
1750
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001751 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001752IterTraverse(IterObject *self, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001753{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001754 if (self->traverse != NULL)
1755 return self->traverse(self->cur, visit, arg);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001756 else
1757 return 0;
1758}
1759
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001760// Mac OSX defines clear() somewhere.
Bram Moolenaar9e74e302013-05-17 21:20:17 +02001761#ifdef clear
1762# undef clear
1763#endif
1764
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001765 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001766IterClear(IterObject *self)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001767{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001768 if (self->clear != NULL)
1769 return self->clear(&self->cur);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001770 else
1771 return 0;
1772}
1773
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001774 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001775IterNext(IterObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001776{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001777 return self->next(&self->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001778}
1779
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001780 static PyObject *
1781IterIter(PyObject *self)
1782{
Bram Moolenaar1bcabe12013-05-29 22:52:32 +02001783 Py_INCREF(self);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001784 return self;
1785}
Bram Moolenaardfa38d42013-05-15 13:38:47 +02001786
Bram Moolenaardb913952012-06-29 12:54:53 +02001787typedef struct pylinkedlist_S {
1788 struct pylinkedlist_S *pll_next;
1789 struct pylinkedlist_S *pll_prev;
1790 PyObject *pll_obj;
1791} pylinkedlist_T;
1792
1793static pylinkedlist_T *lastdict = NULL;
1794static pylinkedlist_T *lastlist = NULL;
Bram Moolenaar8110a092016-04-14 15:56:09 +02001795static pylinkedlist_T *lastfunc = NULL;
Bram Moolenaardb913952012-06-29 12:54:53 +02001796
1797 static void
1798pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
1799{
1800 if (ref->pll_prev == NULL)
1801 {
1802 if (ref->pll_next == NULL)
1803 {
1804 *last = NULL;
1805 return;
1806 }
1807 }
1808 else
1809 ref->pll_prev->pll_next = ref->pll_next;
1810
1811 if (ref->pll_next == NULL)
1812 *last = ref->pll_prev;
1813 else
1814 ref->pll_next->pll_prev = ref->pll_prev;
1815}
1816
1817 static void
1818pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
1819{
1820 if (*last == NULL)
1821 ref->pll_prev = NULL;
1822 else
1823 {
1824 (*last)->pll_next = ref;
1825 ref->pll_prev = *last;
1826 }
1827 ref->pll_next = NULL;
1828 ref->pll_obj = self;
1829 *last = ref;
1830}
1831
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001832DEFINE_PY_TYPE_OBJECT(DictionaryType);
Bram Moolenaardb913952012-06-29 12:54:53 +02001833
1834typedef struct
1835{
1836 PyObject_HEAD
1837 dict_T *dict;
1838 pylinkedlist_T ref;
1839} DictionaryObject;
1840
Bram Moolenaara9922d62013-05-30 13:01:18 +02001841static PyObject *DictionaryUpdate(DictionaryObject *, PyObject *, PyObject *);
1842
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001843#define NEW_DICTIONARY(dict) DictionaryNew(DictionaryTypePtr, dict)
Bram Moolenaara9922d62013-05-30 13:01:18 +02001844
Bram Moolenaardb913952012-06-29 12:54:53 +02001845 static PyObject *
Bram Moolenaara9922d62013-05-30 13:01:18 +02001846DictionaryNew(PyTypeObject *subtype, dict_T *dict)
Bram Moolenaardb913952012-06-29 12:54:53 +02001847{
1848 DictionaryObject *self;
1849
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001850 self = (DictionaryObject *) Py_TYPE_GET_TP_ALLOC(subtype)(subtype, 0);
Bram Moolenaardb913952012-06-29 12:54:53 +02001851 if (self == NULL)
1852 return NULL;
1853 self->dict = dict;
1854 ++dict->dv_refcount;
1855
1856 pyll_add((PyObject *)(self), &self->ref, &lastdict);
1857
1858 return (PyObject *)(self);
1859}
1860
Bram Moolenaara9922d62013-05-30 13:01:18 +02001861 static dict_T *
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02001862py_dict_alloc(void)
Bram Moolenaara9922d62013-05-30 13:01:18 +02001863{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001864 dict_T *ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001865
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001866 if (!(ret = dict_alloc()))
Bram Moolenaara9922d62013-05-30 13:01:18 +02001867 {
1868 PyErr_NoMemory();
1869 return NULL;
1870 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001871 ++ret->dv_refcount;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001872
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001873 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001874}
1875
1876 static PyObject *
1877DictionaryConstructor(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
1878{
1879 DictionaryObject *self;
1880 dict_T *dict;
1881
1882 if (!(dict = py_dict_alloc()))
1883 return NULL;
1884
1885 self = (DictionaryObject *) DictionaryNew(subtype, dict);
1886
1887 --dict->dv_refcount;
1888
1889 if (kwargs || PyTuple_Size(args))
1890 {
1891 PyObject *tmp;
1892 if (!(tmp = DictionaryUpdate(self, args, kwargs)))
1893 {
1894 Py_DECREF(self);
1895 return NULL;
1896 }
1897
1898 Py_DECREF(tmp);
1899 }
1900
1901 return (PyObject *)(self);
1902}
1903
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001904 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02001905DictionaryDestructor(DictionaryObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001906{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001907 pyll_remove(&self->ref, &lastdict);
1908 dict_unref(self->dict);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001909
1910 DESTRUCTOR_FINISH(self);
1911}
1912
Bram Moolenaardd8aca62013-05-29 22:36:10 +02001913static char *DictionaryAttrs[] = {
1914 "locked", "scope",
1915 NULL
1916};
1917
1918 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001919DictionaryDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02001920{
1921 return ObjectDir(self, DictionaryAttrs);
1922}
1923
Bram Moolenaardb913952012-06-29 12:54:53 +02001924 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001925DictionarySetattr(DictionaryObject *self, char *name, PyObject *valObject)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001926{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001927 if (valObject == NULL)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001928 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02001929 PyErr_SET_STRING(PyExc_AttributeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001930 N_("cannot delete vim.Dictionary attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001931 return -1;
1932 }
1933
1934 if (strcmp(name, "locked") == 0)
1935 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001936 if (self->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001937 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001938 PyErr_SET_STRING(PyExc_TypeError,
1939 N_("cannot modify fixed dictionary"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001940 return -1;
1941 }
1942 else
1943 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001944 int istrue = PyObject_IsTrue(valObject);
Bram Moolenaarb983f752013-05-15 16:11:50 +02001945 if (istrue == -1)
1946 return -1;
1947 else if (istrue)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001948 self->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001949 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02001950 self->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001951 }
1952 return 0;
1953 }
1954 else
1955 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001956 PyErr_FORMAT(PyExc_AttributeError, N_("cannot set attribute %s"), name);
Bram Moolenaar66b79852012-09-21 14:00:35 +02001957 return -1;
1958 }
1959}
1960
1961 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02001962DictionaryLength(DictionaryObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +02001963{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001964 return ((PyInt) (self->dict->dv_hashtab.ht_used));
Bram Moolenaardb913952012-06-29 12:54:53 +02001965}
1966
Bram Moolenaara9922d62013-05-30 13:01:18 +02001967#define DICT_FLAG_HAS_DEFAULT 0x01
1968#define DICT_FLAG_POP 0x02
1969#define DICT_FLAG_NONE_DEFAULT 0x04
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001970#define DICT_FLAG_RETURN_BOOL 0x08 // Incompatible with DICT_FLAG_POP
Bram Moolenaara9922d62013-05-30 13:01:18 +02001971#define DICT_FLAG_RETURN_PAIR 0x10
1972
Bram Moolenaardb913952012-06-29 12:54:53 +02001973 static PyObject *
Bram Moolenaara9922d62013-05-30 13:01:18 +02001974_DictionaryItem(DictionaryObject *self, PyObject *args, int flags)
Bram Moolenaardb913952012-06-29 12:54:53 +02001975{
Bram Moolenaara9922d62013-05-30 13:01:18 +02001976 PyObject *keyObject;
1977 PyObject *defObject = ((flags & DICT_FLAG_NONE_DEFAULT)? Py_None : NULL);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001978 PyObject *ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02001979 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +02001980 dictitem_T *di;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001981 dict_T *dict = self->dict;
1982 hashitem_T *hi;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02001983 PyObject *todecref;
Bram Moolenaardb913952012-06-29 12:54:53 +02001984
Bram Moolenaara9922d62013-05-30 13:01:18 +02001985 if (flags & DICT_FLAG_HAS_DEFAULT)
1986 {
1987 if (!PyArg_ParseTuple(args, "O|O", &keyObject, &defObject))
1988 return NULL;
1989 }
1990 else
1991 keyObject = args;
1992
1993 if (flags & DICT_FLAG_RETURN_BOOL)
1994 defObject = Py_False;
1995
Bram Moolenaar35eacd72013-05-30 22:06:33 +02001996 if (!(key = StringToChars(keyObject, &todecref)))
1997 return NULL;
1998
1999 if (*key == NUL)
2000 {
2001 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02002002 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002003 return NULL;
2004 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002005
Bram Moolenaara9922d62013-05-30 13:01:18 +02002006 hi = hash_find(&dict->dv_hashtab, key);
Bram Moolenaar231e1a12012-09-05 18:45:28 +02002007
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002008 Py_XDECREF(todecref);
Bram Moolenaar696c2112012-09-21 13:43:14 +02002009
Bram Moolenaara9922d62013-05-30 13:01:18 +02002010 if (HASHITEM_EMPTY(hi))
Bram Moolenaar231e1a12012-09-05 18:45:28 +02002011 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002012 if (defObject)
2013 {
2014 Py_INCREF(defObject);
2015 return defObject;
2016 }
2017 else
2018 {
2019 PyErr_SetObject(PyExc_KeyError, keyObject);
2020 return NULL;
2021 }
2022 }
2023 else if (flags & DICT_FLAG_RETURN_BOOL)
2024 {
Bram Moolenaar0e4eebd2014-02-12 22:08:49 +01002025 ret = Py_True;
2026 Py_INCREF(ret);
2027 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002028 }
2029
2030 di = dict_lookup(hi);
2031
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002032 if (!(ret = ConvertToPyObject(&di->di_tv)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002033 return NULL;
2034
2035 if (flags & DICT_FLAG_POP)
2036 {
2037 if (dict->dv_lock)
2038 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002039 RAISE_LOCKED_DICTIONARY;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002040 Py_DECREF(ret);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002041 return NULL;
2042 }
2043
Bram Moolenaaref2c3252022-11-25 16:31:51 +00002044 hash_remove(&dict->dv_hashtab, hi, "Python remove variable");
Bram Moolenaara9922d62013-05-30 13:01:18 +02002045 dictitem_free(di);
2046 }
2047
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002048 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002049}
2050
2051 static PyObject *
2052DictionaryItem(DictionaryObject *self, PyObject *keyObject)
2053{
2054 return _DictionaryItem(self, keyObject, 0);
2055}
2056
2057 static int
2058DictionaryContains(DictionaryObject *self, PyObject *keyObject)
2059{
2060 PyObject *rObj = _DictionaryItem(self, keyObject, DICT_FLAG_RETURN_BOOL);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002061 int ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002062
Bram Moolenaarba2d7ff2013-11-04 00:34:53 +01002063 if (rObj == NULL)
2064 return -1;
2065
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002066 ret = (rObj == Py_True);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002067
Bram Moolenaardee2e312013-06-23 16:35:47 +02002068 Py_DECREF(rObj);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002069
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002070 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002071}
2072
2073typedef struct
2074{
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002075 int dii_changed;
2076 hashtab_T *dii_ht;
2077 hashitem_T *dii_hi;
2078 long_u dii_todo;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002079} dictiterinfo_T;
2080
2081 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02002082DictionaryIterNext(void **arg)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002083{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002084 PyObject *ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02002085 dictiterinfo_T **dii = (dictiterinfo_T**)arg;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002086
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002087 if (!(*dii)->dii_todo)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002088 return NULL;
2089
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002090 if ((*dii)->dii_ht->ht_changed != (*dii)->dii_changed)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002091 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02002092 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002093 N_("hashtab changed during iteration"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +02002094 return NULL;
2095 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002096
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002097 while (((*dii)->dii_todo) && HASHITEM_EMPTY((*dii)->dii_hi))
2098 ++((*dii)->dii_hi);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002099
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002100 --((*dii)->dii_todo);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002101
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002102 if (!(ret = PyBytes_FromString((char *)(*dii)->dii_hi->hi_key)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002103 return NULL;
2104
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002105 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002106}
2107
2108 static PyObject *
2109DictionaryIter(DictionaryObject *self)
2110{
2111 dictiterinfo_T *dii;
2112 hashtab_T *ht;
2113
2114 if (!(dii = PyMem_New(dictiterinfo_T, 1)))
2115 {
2116 PyErr_NoMemory();
2117 return NULL;
2118 }
2119
2120 ht = &self->dict->dv_hashtab;
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002121 dii->dii_changed = ht->ht_changed;
2122 dii->dii_ht = ht;
2123 dii->dii_hi = ht->ht_array;
2124 dii->dii_todo = ht->ht_used;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002125
2126 return IterNew(dii,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02002127 PyMem_Free, DictionaryIterNext,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02002128 NULL, NULL, (PyObject *)self);
Bram Moolenaardb913952012-06-29 12:54:53 +02002129}
2130
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002131 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02002132DictionaryAssItem(
2133 DictionaryObject *self, PyObject *keyObject, PyObject *valObject)
Bram Moolenaardb913952012-06-29 12:54:53 +02002134{
2135 char_u *key;
2136 typval_T tv;
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002137 dict_T *dict = self->dict;
Bram Moolenaardb913952012-06-29 12:54:53 +02002138 dictitem_T *di;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002139 PyObject *todecref;
Bram Moolenaardb913952012-06-29 12:54:53 +02002140
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002141 if (dict->dv_lock)
Bram Moolenaardb913952012-06-29 12:54:53 +02002142 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002143 RAISE_LOCKED_DICTIONARY;
Bram Moolenaardb913952012-06-29 12:54:53 +02002144 return -1;
2145 }
2146
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002147 if (!(key = StringToChars(keyObject, &todecref)))
2148 return -1;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02002149
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002150 if (*key == NUL)
2151 {
2152 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar78b59572013-06-02 18:54:21 +02002153 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002154 return -1;
2155 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002156
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002157 di = dict_find(dict, key, -1);
Bram Moolenaardb913952012-06-29 12:54:53 +02002158
2159 if (valObject == NULL)
2160 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +02002161 hashitem_T *hi;
2162
Bram Moolenaardb913952012-06-29 12:54:53 +02002163 if (di == NULL)
2164 {
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002165 Py_XDECREF(todecref);
Bram Moolenaar4d188da2013-05-15 15:35:09 +02002166 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaardb913952012-06-29 12:54:53 +02002167 return -1;
2168 }
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002169 hi = hash_find(&dict->dv_hashtab, di->di_key);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00002170 hash_remove(&dict->dv_hashtab, hi, "Python remove item");
Bram Moolenaardb913952012-06-29 12:54:53 +02002171 dictitem_free(di);
Bram Moolenaar78b59572013-06-02 18:54:21 +02002172 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002173 return 0;
2174 }
2175
2176 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaar78b59572013-06-02 18:54:21 +02002177 {
2178 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002179 return -1;
Bram Moolenaar78b59572013-06-02 18:54:21 +02002180 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002181
2182 if (di == NULL)
2183 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002184 if (!(di = dictitem_alloc(key)))
Bram Moolenaardb913952012-06-29 12:54:53 +02002185 {
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002186 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002187 PyErr_NoMemory();
2188 return -1;
2189 }
Bram Moolenaara9922d62013-05-30 13:01:18 +02002190 di->di_tv.v_type = VAR_UNKNOWN;
Bram Moolenaardb913952012-06-29 12:54:53 +02002191
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002192 if (dict_add(dict, di) == FAIL)
Bram Moolenaardb913952012-06-29 12:54:53 +02002193 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002194 dictitem_free(di);
Bram Moolenaarc476e522013-06-23 13:46:40 +02002195 RAISE_KEY_ADD_FAIL(key);
2196 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002197 return -1;
2198 }
2199 }
2200 else
2201 clear_tv(&di->di_tv);
2202
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002203 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002204
2205 copy_tv(&tv, &di->di_tv);
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02002206 clear_tv(&tv);
Bram Moolenaardb913952012-06-29 12:54:53 +02002207 return 0;
2208}
2209
Bram Moolenaara9922d62013-05-30 13:01:18 +02002210typedef PyObject *(*hi_to_py)(hashitem_T *);
2211
Bram Moolenaardb913952012-06-29 12:54:53 +02002212 static PyObject *
Bram Moolenaara9922d62013-05-30 13:01:18 +02002213DictionaryListObjects(DictionaryObject *self, hi_to_py hiconvert)
Bram Moolenaardb913952012-06-29 12:54:53 +02002214{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002215 dict_T *dict = self->dict;
Bram Moolenaardb913952012-06-29 12:54:53 +02002216 long_u todo = dict->dv_hashtab.ht_used;
2217 Py_ssize_t i = 0;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002218 PyObject *ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02002219 hashitem_T *hi;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002220 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +02002221
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002222 ret = PyList_New(todo);
Bram Moolenaardb913952012-06-29 12:54:53 +02002223 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
2224 {
2225 if (!HASHITEM_EMPTY(hi))
2226 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002227 if (!(newObj = hiconvert(hi)))
2228 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002229 Py_DECREF(ret);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002230 return NULL;
2231 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002232 PyList_SET_ITEM(ret, i, newObj);
Bram Moolenaardb913952012-06-29 12:54:53 +02002233 --todo;
2234 ++i;
2235 }
2236 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002237 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02002238}
2239
Bram Moolenaara9922d62013-05-30 13:01:18 +02002240 static PyObject *
2241dict_key(hashitem_T *hi)
2242{
2243 return PyBytes_FromString((char *)(hi->hi_key));
2244}
2245
2246 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002247DictionaryListKeys(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002248{
2249 return DictionaryListObjects(self, dict_key);
2250}
2251
2252 static PyObject *
2253dict_val(hashitem_T *hi)
2254{
2255 dictitem_T *di;
2256
2257 di = dict_lookup(hi);
2258 return ConvertToPyObject(&di->di_tv);
2259}
2260
2261 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002262DictionaryListValues(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002263{
2264 return DictionaryListObjects(self, dict_val);
2265}
2266
2267 static PyObject *
2268dict_item(hashitem_T *hi)
2269{
2270 PyObject *keyObject;
2271 PyObject *valObject;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002272 PyObject *ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002273
2274 if (!(keyObject = dict_key(hi)))
2275 return NULL;
2276
2277 if (!(valObject = dict_val(hi)))
2278 {
2279 Py_DECREF(keyObject);
2280 return NULL;
2281 }
2282
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002283 ret = Py_BuildValue("(OO)", keyObject, valObject);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002284
2285 Py_DECREF(keyObject);
2286 Py_DECREF(valObject);
2287
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002288 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002289}
2290
2291 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002292DictionaryListItems(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002293{
2294 return DictionaryListObjects(self, dict_item);
2295}
2296
2297 static PyObject *
2298DictionaryUpdate(DictionaryObject *self, PyObject *args, PyObject *kwargs)
2299{
2300 dict_T *dict = self->dict;
2301
2302 if (dict->dv_lock)
2303 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002304 RAISE_LOCKED_DICTIONARY;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002305 return NULL;
2306 }
2307
2308 if (kwargs)
2309 {
2310 typval_T tv;
2311
2312 if (ConvertFromPyMapping(kwargs, &tv) == -1)
2313 return NULL;
2314
2315 VimTryStart();
Bram Moolenaar7a3fe3e2021-07-22 14:58:47 +02002316 dict_extend(self->dict, tv.vval.v_dict, (char_u *) "force", NULL);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002317 clear_tv(&tv);
2318 if (VimTryEnd())
2319 return NULL;
2320 }
2321 else
2322 {
Bram Moolenaar2d5f38f2014-02-11 18:47:27 +01002323 PyObject *obj = NULL;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002324
Bram Moolenaar2d5f38f2014-02-11 18:47:27 +01002325 if (!PyArg_ParseTuple(args, "|O", &obj))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002326 return NULL;
2327
Bram Moolenaar2d5f38f2014-02-11 18:47:27 +01002328 if (obj == NULL)
2329 {
2330 Py_INCREF(Py_None);
2331 return Py_None;
2332 }
2333
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002334 if (PyObject_HasAttrString(obj, "keys"))
2335 return DictionaryUpdate(self, NULL, obj);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002336 else
2337 {
2338 PyObject *iterator;
2339 PyObject *item;
2340
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002341 if (!(iterator = PyObject_GetIter(obj)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002342 return NULL;
2343
2344 while ((item = PyIter_Next(iterator)))
2345 {
2346 PyObject *fast;
2347 PyObject *keyObject;
2348 PyObject *valObject;
2349 PyObject *todecref;
2350 char_u *key;
2351 dictitem_T *di;
Bram Moolenaar9ed7d342017-11-09 22:10:33 +01002352 hashitem_T *hi;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002353
2354 if (!(fast = PySequence_Fast(item, "")))
2355 {
2356 Py_DECREF(iterator);
2357 Py_DECREF(item);
2358 return NULL;
2359 }
2360
2361 Py_DECREF(item);
2362
2363 if (PySequence_Fast_GET_SIZE(fast) != 2)
2364 {
2365 Py_DECREF(iterator);
2366 Py_DECREF(fast);
Bram Moolenaarc476e522013-06-23 13:46:40 +02002367 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002368 N_("expected sequence element of size 2, "
2369 "but got sequence of size %d"),
Bram Moolenaardee2e312013-06-23 16:35:47 +02002370 (int) PySequence_Fast_GET_SIZE(fast));
Bram Moolenaara9922d62013-05-30 13:01:18 +02002371 return NULL;
2372 }
2373
2374 keyObject = PySequence_Fast_GET_ITEM(fast, 0);
2375
2376 if (!(key = StringToChars(keyObject, &todecref)))
2377 {
2378 Py_DECREF(iterator);
2379 Py_DECREF(fast);
2380 return NULL;
2381 }
2382
2383 di = dictitem_alloc(key);
2384
2385 Py_XDECREF(todecref);
2386
2387 if (di == NULL)
2388 {
2389 Py_DECREF(fast);
2390 Py_DECREF(iterator);
2391 PyErr_NoMemory();
2392 return NULL;
2393 }
Bram Moolenaara9922d62013-05-30 13:01:18 +02002394 di->di_tv.v_type = VAR_UNKNOWN;
2395
2396 valObject = PySequence_Fast_GET_ITEM(fast, 1);
2397
2398 if (ConvertFromPyObject(valObject, &di->di_tv) == -1)
2399 {
2400 Py_DECREF(iterator);
2401 Py_DECREF(fast);
2402 dictitem_free(di);
2403 return NULL;
2404 }
2405
2406 Py_DECREF(fast);
2407
Bram Moolenaar9ed7d342017-11-09 22:10:33 +01002408 hi = hash_find(&dict->dv_hashtab, di->di_key);
2409 if (!HASHITEM_EMPTY(hi) || dict_add(dict, di) == FAIL)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002410 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002411 RAISE_KEY_ADD_FAIL(di->di_key);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002412 Py_DECREF(iterator);
2413 dictitem_free(di);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002414 return NULL;
2415 }
2416 }
2417
2418 Py_DECREF(iterator);
2419
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002420 // Iterator may have finished due to an exception
Bram Moolenaara9922d62013-05-30 13:01:18 +02002421 if (PyErr_Occurred())
2422 return NULL;
2423 }
2424 }
2425 Py_INCREF(Py_None);
2426 return Py_None;
2427}
2428
2429 static PyObject *
2430DictionaryGet(DictionaryObject *self, PyObject *args)
2431{
2432 return _DictionaryItem(self, args,
2433 DICT_FLAG_HAS_DEFAULT|DICT_FLAG_NONE_DEFAULT);
2434}
2435
2436 static PyObject *
2437DictionaryPop(DictionaryObject *self, PyObject *args)
2438{
2439 return _DictionaryItem(self, args, DICT_FLAG_HAS_DEFAULT|DICT_FLAG_POP);
2440}
2441
2442 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002443DictionaryPopItem(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002444{
Bram Moolenaarde71b562013-06-02 17:41:54 +02002445 hashitem_T *hi;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002446 PyObject *ret;
Bram Moolenaarde71b562013-06-02 17:41:54 +02002447 PyObject *valObject;
2448 dictitem_T *di;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002449
Bram Moolenaarde71b562013-06-02 17:41:54 +02002450 if (self->dict->dv_hashtab.ht_used == 0)
2451 {
2452 PyErr_SetNone(PyExc_KeyError);
2453 return NULL;
2454 }
2455
2456 hi = self->dict->dv_hashtab.ht_array;
2457 while (HASHITEM_EMPTY(hi))
2458 ++hi;
2459
2460 di = dict_lookup(hi);
2461
2462 if (!(valObject = ConvertToPyObject(&di->di_tv)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002463 return NULL;
2464
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002465 if (!(ret = Py_BuildValue("(" Py_bytes_fmt "O)", hi->hi_key, valObject)))
Bram Moolenaarde71b562013-06-02 17:41:54 +02002466 {
2467 Py_DECREF(valObject);
2468 return NULL;
2469 }
2470
Bram Moolenaaref2c3252022-11-25 16:31:51 +00002471 hash_remove(&self->dict->dv_hashtab, hi, "Python pop item");
Bram Moolenaarde71b562013-06-02 17:41:54 +02002472 dictitem_free(di);
2473
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002474 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002475}
2476
2477 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02002478DictionaryHasKey(DictionaryObject *self, PyObject *keyObject)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002479{
Bram Moolenaara9922d62013-05-30 13:01:18 +02002480 return _DictionaryItem(self, keyObject, DICT_FLAG_RETURN_BOOL);
2481}
2482
2483static PySequenceMethods DictionaryAsSeq = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002484 0, // sq_length
2485 0, // sq_concat
2486 0, // sq_repeat
2487 0, // sq_item
2488 0, // sq_slice
2489 0, // sq_ass_item
2490 0, // sq_ass_slice
2491 (objobjproc) DictionaryContains, // sq_contains
2492 0, // sq_inplace_concat
2493 0, // sq_inplace_repeat
Bram Moolenaara9922d62013-05-30 13:01:18 +02002494};
2495
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002496static PyMappingMethods DictionaryAsMapping = {
2497 (lenfunc) DictionaryLength,
2498 (binaryfunc) DictionaryItem,
2499 (objobjargproc) DictionaryAssItem,
2500};
2501
Bram Moolenaardb913952012-06-29 12:54:53 +02002502static struct PyMethodDef DictionaryMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02002503 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
Bram Moolenaara9922d62013-05-30 13:01:18 +02002504 {"values", (PyCFunction)DictionaryListValues, METH_NOARGS, ""},
2505 {"items", (PyCFunction)DictionaryListItems, METH_NOARGS, ""},
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002506 {"update", (PyCFunction)(void *)DictionaryUpdate, METH_VARARGS|METH_KEYWORDS, ""},
Bram Moolenaara9922d62013-05-30 13:01:18 +02002507 {"get", (PyCFunction)DictionaryGet, METH_VARARGS, ""},
2508 {"pop", (PyCFunction)DictionaryPop, METH_VARARGS, ""},
Bram Moolenaarde71b562013-06-02 17:41:54 +02002509 {"popitem", (PyCFunction)DictionaryPopItem, METH_NOARGS, ""},
Bram Moolenaar389a1792013-06-23 13:00:44 +02002510 {"has_key", (PyCFunction)DictionaryHasKey, METH_O, ""},
Bram Moolenaardd8aca62013-05-29 22:36:10 +02002511 {"__dir__", (PyCFunction)DictionaryDir, METH_NOARGS, ""},
2512 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02002513};
2514
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02002515DEFINE_PY_TYPE_OBJECT(ListType);
Bram Moolenaardb913952012-06-29 12:54:53 +02002516
2517typedef struct
2518{
2519 PyObject_HEAD
2520 list_T *list;
2521 pylinkedlist_T ref;
2522} ListObject;
2523
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02002524#define NEW_LIST(list) ListNew(ListTypePtr, list)
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002525
Bram Moolenaardb913952012-06-29 12:54:53 +02002526 static PyObject *
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002527ListNew(PyTypeObject *subtype, list_T *list)
Bram Moolenaardb913952012-06-29 12:54:53 +02002528{
2529 ListObject *self;
2530
Bram Moolenaarab589462020-07-06 21:03:06 +02002531 if (list == NULL)
2532 return NULL;
2533
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02002534 self = (ListObject *) Py_TYPE_GET_TP_ALLOC(subtype)(subtype, 0);
Bram Moolenaardb913952012-06-29 12:54:53 +02002535 if (self == NULL)
2536 return NULL;
2537 self->list = list;
2538 ++list->lv_refcount;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002539 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaardb913952012-06-29 12:54:53 +02002540
2541 pyll_add((PyObject *)(self), &self->ref, &lastlist);
2542
2543 return (PyObject *)(self);
2544}
2545
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002546 static list_T *
Bram Moolenaarfb97f282013-07-09 17:42:46 +02002547py_list_alloc(void)
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002548{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002549 list_T *ret;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002550
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002551 if (!(ret = list_alloc()))
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002552 {
2553 PyErr_NoMemory();
2554 return NULL;
2555 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002556 ++ret->lv_refcount;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002557
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002558 return ret;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002559}
2560
2561 static int
2562list_py_concat(list_T *l, PyObject *obj, PyObject *lookup_dict)
2563{
2564 PyObject *iterator;
2565 PyObject *item;
2566 listitem_T *li;
2567
2568 if (!(iterator = PyObject_GetIter(obj)))
2569 return -1;
2570
2571 while ((item = PyIter_Next(iterator)))
2572 {
2573 if (!(li = listitem_alloc()))
2574 {
2575 PyErr_NoMemory();
2576 Py_DECREF(item);
2577 Py_DECREF(iterator);
2578 return -1;
2579 }
2580 li->li_tv.v_lock = 0;
2581 li->li_tv.v_type = VAR_UNKNOWN;
2582
2583 if (_ConvertFromPyObject(item, &li->li_tv, lookup_dict) == -1)
2584 {
2585 Py_DECREF(item);
2586 Py_DECREF(iterator);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002587 listitem_free(l, li);
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002588 return -1;
2589 }
2590
2591 Py_DECREF(item);
2592
2593 list_append(l, li);
2594 }
2595
2596 Py_DECREF(iterator);
2597
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002598 // Iterator may have finished due to an exception
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002599 if (PyErr_Occurred())
2600 return -1;
2601
2602 return 0;
2603}
2604
2605 static PyObject *
2606ListConstructor(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
2607{
2608 list_T *list;
2609 PyObject *obj = NULL;
2610
2611 if (kwargs)
2612 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02002613 PyErr_SET_STRING(PyExc_TypeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002614 N_("list constructor does not accept keyword arguments"));
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002615 return NULL;
2616 }
2617
2618 if (!PyArg_ParseTuple(args, "|O", &obj))
2619 return NULL;
2620
2621 if (!(list = py_list_alloc()))
2622 return NULL;
2623
2624 if (obj)
2625 {
2626 PyObject *lookup_dict;
2627
2628 if (!(lookup_dict = PyDict_New()))
2629 {
2630 list_unref(list);
2631 return NULL;
2632 }
2633
2634 if (list_py_concat(list, obj, lookup_dict) == -1)
2635 {
2636 Py_DECREF(lookup_dict);
2637 list_unref(list);
2638 return NULL;
2639 }
2640
2641 Py_DECREF(lookup_dict);
2642 }
2643
2644 return ListNew(subtype, list);
2645}
2646
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002647 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02002648ListDestructor(ListObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002649{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002650 pyll_remove(&self->ref, &lastlist);
2651 list_unref(self->list);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002652
2653 DESTRUCTOR_FINISH(self);
2654}
2655
Bram Moolenaardb913952012-06-29 12:54:53 +02002656 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02002657ListLength(ListObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +02002658{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002659 return ((PyInt) (self->list->lv_len));
Bram Moolenaardb913952012-06-29 12:54:53 +02002660}
2661
2662 static PyObject *
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002663ListIndex(ListObject *self, Py_ssize_t index)
Bram Moolenaardb913952012-06-29 12:54:53 +02002664{
2665 listitem_T *li;
2666
Bram Moolenaard6e39182013-05-21 18:30:34 +02002667 if (index >= ListLength(self))
Bram Moolenaardb913952012-06-29 12:54:53 +02002668 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002669 PyErr_SET_STRING(PyExc_IndexError, N_("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +02002670 return NULL;
2671 }
Bram Moolenaard6e39182013-05-21 18:30:34 +02002672 li = list_find(self->list, (long) index);
Bram Moolenaardb913952012-06-29 12:54:53 +02002673 if (li == NULL)
2674 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002675 // No more suitable format specifications in python-2.3
Bram Moolenaar86181df2020-05-11 23:14:04 +02002676 PyErr_VIM_FORMAT(N_("internal error: failed to get Vim list item %d"),
Bram Moolenaarc476e522013-06-23 13:46:40 +02002677 (int) index);
Bram Moolenaardb913952012-06-29 12:54:53 +02002678 return NULL;
2679 }
2680 return ConvertToPyObject(&li->li_tv);
2681}
2682
Bram Moolenaardb913952012-06-29 12:54:53 +02002683 static PyObject *
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002684ListSlice(ListObject *self, Py_ssize_t first, Py_ssize_t step,
2685 Py_ssize_t slicelen)
Bram Moolenaardb913952012-06-29 12:54:53 +02002686{
2687 PyInt i;
Bram Moolenaardb913952012-06-29 12:54:53 +02002688 PyObject *list;
Bram Moolenaardb913952012-06-29 12:54:53 +02002689
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002690 if (step == 0)
2691 {
2692 PyErr_SET_STRING(PyExc_ValueError, N_("slice step cannot be zero"));
2693 return NULL;
2694 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002695
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002696 list = PyList_New(slicelen);
Bram Moolenaardb913952012-06-29 12:54:53 +02002697 if (list == NULL)
2698 return NULL;
2699
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002700 for (i = 0; i < slicelen; ++i)
Bram Moolenaardb913952012-06-29 12:54:53 +02002701 {
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002702 PyObject *item;
2703
2704 item = ListIndex(self, first + i*step);
Bram Moolenaardb913952012-06-29 12:54:53 +02002705 if (item == NULL)
2706 {
2707 Py_DECREF(list);
2708 return NULL;
2709 }
2710
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002711 PyList_SET_ITEM(list, i, item);
Bram Moolenaardb913952012-06-29 12:54:53 +02002712 }
2713
2714 return list;
2715}
2716
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002717 static PyObject *
2718ListItem(ListObject *self, PyObject* idx)
2719{
2720#if PY_MAJOR_VERSION < 3
2721 if (PyInt_Check(idx))
2722 {
2723 long _idx = PyInt_AsLong(idx);
2724 return ListIndex(self, _idx);
2725 }
2726 else
2727#endif
2728 if (PyLong_Check(idx))
2729 {
2730 long _idx = PyLong_AsLong(idx);
2731 return ListIndex(self, _idx);
2732 }
2733 else if (PySlice_Check(idx))
2734 {
2735 Py_ssize_t start, stop, step, slicelen;
2736
Bram Moolenaar922a4662014-03-30 16:11:43 +02002737 if (PySlice_GetIndicesEx((PySliceObject_T *)idx, ListLength(self),
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002738 &start, &stop, &step, &slicelen) < 0)
2739 return NULL;
2740 return ListSlice(self, start, step, slicelen);
2741 }
2742 else
2743 {
2744 RAISE_INVALID_INDEX_TYPE(idx);
2745 return NULL;
2746 }
2747}
2748
2749 static void
2750list_restore(Py_ssize_t numadded, Py_ssize_t numreplaced, Py_ssize_t slicelen,
2751 list_T *l, listitem_T **lis, listitem_T *lastaddedli)
2752{
2753 while (numreplaced--)
2754 {
2755 list_insert(l, lis[numreplaced], lis[slicelen + numreplaced]);
2756 listitem_remove(l, lis[slicelen + numreplaced]);
2757 }
2758 while (numadded--)
2759 {
2760 listitem_T *next;
2761
2762 next = lastaddedli->li_prev;
2763 listitem_remove(l, lastaddedli);
2764 lastaddedli = next;
2765 }
2766}
2767
2768 static int
2769ListAssSlice(ListObject *self, Py_ssize_t first,
2770 Py_ssize_t step, Py_ssize_t slicelen, PyObject *obj)
2771{
2772 PyObject *iterator;
2773 PyObject *item;
2774 listitem_T *li;
2775 listitem_T *lastaddedli = NULL;
2776 listitem_T *next;
2777 typval_T v;
2778 list_T *l = self->list;
2779 PyInt i;
2780 PyInt j;
2781 PyInt numreplaced = 0;
2782 PyInt numadded = 0;
2783 PyInt size;
Bram Moolenaar3b522612014-02-11 16:00:35 +01002784 listitem_T **lis = NULL;
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002785
2786 size = ListLength(self);
2787
2788 if (l->lv_lock)
2789 {
2790 RAISE_LOCKED_LIST;
2791 return -1;
2792 }
2793
2794 if (step == 0)
2795 {
2796 PyErr_SET_STRING(PyExc_ValueError, N_("slice step cannot be zero"));
2797 return -1;
2798 }
2799
2800 if (step != 1 && slicelen == 0)
2801 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002802 // Nothing to do. Only error out if obj has some items.
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002803 int ret = 0;
2804
2805 if (obj == NULL)
2806 return 0;
2807
2808 if (!(iterator = PyObject_GetIter(obj)))
2809 return -1;
2810
2811 if ((item = PyIter_Next(iterator)))
2812 {
2813 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar4de6a212014-03-08 16:13:44 +01002814 N_("attempt to assign sequence of size greater than %d "
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002815 "to extended slice"), 0);
2816 Py_DECREF(item);
2817 ret = -1;
2818 }
2819 Py_DECREF(iterator);
2820 return ret;
2821 }
2822
2823 if (obj != NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002824 // XXX May allocate zero bytes.
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002825 if (!(lis = PyMem_New(listitem_T *, slicelen * 2)))
2826 {
2827 PyErr_NoMemory();
2828 return -1;
2829 }
2830
2831 if (first == size)
2832 li = NULL;
2833 else
2834 {
2835 li = list_find(l, (long) first);
2836 if (li == NULL)
2837 {
Bram Moolenaar86181df2020-05-11 23:14:04 +02002838 PyErr_VIM_FORMAT(N_("internal error: no Vim list item %d"),
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002839 (int)first);
2840 if (obj != NULL)
2841 PyMem_Free(lis);
2842 return -1;
2843 }
2844 i = slicelen;
2845 while (i-- && li != NULL)
2846 {
2847 j = step;
2848 next = li;
2849 if (step > 0)
2850 while (next != NULL && ((next = next->li_next) != NULL) && --j);
2851 else
2852 while (next != NULL && ((next = next->li_prev) != NULL) && ++j);
2853
2854 if (obj == NULL)
2855 listitem_remove(l, li);
2856 else
2857 lis[slicelen - i - 1] = li;
2858
2859 li = next;
2860 }
2861 if (li == NULL && i != -1)
2862 {
2863 PyErr_SET_VIM(N_("internal error: not enough list items"));
2864 if (obj != NULL)
2865 PyMem_Free(lis);
2866 return -1;
2867 }
2868 }
2869
2870 if (obj == NULL)
2871 return 0;
2872
2873 if (!(iterator = PyObject_GetIter(obj)))
2874 {
2875 PyMem_Free(lis);
2876 return -1;
2877 }
2878
2879 i = 0;
2880 while ((item = PyIter_Next(iterator)))
2881 {
2882 if (ConvertFromPyObject(item, &v) == -1)
2883 {
2884 Py_DECREF(iterator);
2885 Py_DECREF(item);
2886 PyMem_Free(lis);
2887 return -1;
2888 }
2889 Py_DECREF(item);
2890 if (list_insert_tv(l, &v, numreplaced < slicelen
2891 ? lis[numreplaced]
2892 : li) == FAIL)
2893 {
2894 clear_tv(&v);
2895 PyErr_SET_VIM(N_("internal error: failed to add item to list"));
2896 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2897 PyMem_Free(lis);
2898 return -1;
2899 }
2900 if (numreplaced < slicelen)
2901 {
2902 lis[slicelen + numreplaced] = lis[numreplaced]->li_prev;
Bram Moolenaar3ec7f4e2014-05-07 17:31:37 +02002903 vimlist_remove(l, lis[numreplaced], lis[numreplaced]);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002904 numreplaced++;
2905 }
2906 else
2907 {
2908 if (li)
2909 lastaddedli = li->li_prev;
2910 else
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01002911 lastaddedli = l->lv_u.mat.lv_last;
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002912 numadded++;
2913 }
2914 clear_tv(&v);
2915 if (step != 1 && i >= slicelen)
2916 {
2917 Py_DECREF(iterator);
2918 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar4de6a212014-03-08 16:13:44 +01002919 N_("attempt to assign sequence of size greater than %d "
Bram Moolenaar403b3cf2014-02-15 15:59:03 +01002920 "to extended slice"), (int) slicelen);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002921 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2922 PyMem_Free(lis);
2923 return -1;
2924 }
2925 ++i;
2926 }
2927 Py_DECREF(iterator);
2928
2929 if (step != 1 && i != slicelen)
2930 {
2931 PyErr_FORMAT2(PyExc_ValueError,
Bram Moolenaar403b3cf2014-02-15 15:59:03 +01002932 N_("attempt to assign sequence of size %d to extended slice "
2933 "of size %d"), (int) i, (int) slicelen);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002934 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2935 PyMem_Free(lis);
2936 return -1;
2937 }
2938
2939 if (PyErr_Occurred())
2940 {
2941 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2942 PyMem_Free(lis);
2943 return -1;
2944 }
2945
2946 for (i = 0; i < numreplaced; i++)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002947 listitem_free(l, lis[i]);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002948 if (step == 1)
2949 for (i = numreplaced; i < slicelen; i++)
2950 listitem_remove(l, lis[i]);
2951
2952 PyMem_Free(lis);
2953
2954 return 0;
2955}
2956
2957 static int
2958ListAssIndex(ListObject *self, Py_ssize_t index, PyObject *obj)
2959{
2960 typval_T tv;
2961 list_T *l = self->list;
2962 listitem_T *li;
2963 Py_ssize_t length = ListLength(self);
2964
2965 if (l->lv_lock)
2966 {
2967 RAISE_LOCKED_LIST;
2968 return -1;
2969 }
2970 if (index > length || (index == length && obj == NULL))
2971 {
2972 PyErr_SET_STRING(PyExc_IndexError, N_("list index out of range"));
2973 return -1;
2974 }
2975
2976 if (obj == NULL)
2977 {
2978 li = list_find(l, (long) index);
Bram Moolenaarab589462020-07-06 21:03:06 +02002979 if (li == NULL)
2980 {
2981 PyErr_VIM_FORMAT(N_("internal error: failed to get Vim "
2982 "list item %d"), (int) index);
2983 return -1;
2984 }
Bram Moolenaar3ec7f4e2014-05-07 17:31:37 +02002985 vimlist_remove(l, li, li);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002986 clear_tv(&li->li_tv);
2987 vim_free(li);
2988 return 0;
2989 }
2990
2991 if (ConvertFromPyObject(obj, &tv) == -1)
2992 return -1;
2993
2994 if (index == length)
2995 {
2996 if (list_append_tv(l, &tv) == FAIL)
2997 {
2998 clear_tv(&tv);
2999 PyErr_SET_VIM(N_("failed to add item to list"));
3000 return -1;
3001 }
3002 }
3003 else
3004 {
3005 li = list_find(l, (long) index);
Bram Moolenaarab589462020-07-06 21:03:06 +02003006 if (li == NULL)
3007 {
3008 PyErr_VIM_FORMAT(N_("internal error: failed to get Vim "
3009 "list item %d"), (int) index);
3010 return -1;
3011 }
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003012 clear_tv(&li->li_tv);
3013 copy_tv(&tv, &li->li_tv);
3014 clear_tv(&tv);
3015 }
3016 return 0;
3017}
3018
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003019 static int
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003020ListAssItem(ListObject *self, PyObject *idx, PyObject *obj)
3021{
3022#if PY_MAJOR_VERSION < 3
3023 if (PyInt_Check(idx))
3024 {
3025 long _idx = PyInt_AsLong(idx);
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003026 return (int)ListAssIndex(self, _idx, obj);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003027 }
3028 else
3029#endif
3030 if (PyLong_Check(idx))
3031 {
3032 long _idx = PyLong_AsLong(idx);
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003033 return (int)ListAssIndex(self, _idx, obj);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003034 }
3035 else if (PySlice_Check(idx))
3036 {
3037 Py_ssize_t start, stop, step, slicelen;
3038
Bram Moolenaar922a4662014-03-30 16:11:43 +02003039 if (PySlice_GetIndicesEx((PySliceObject_T *)idx, ListLength(self),
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003040 &start, &stop, &step, &slicelen) < 0)
3041 return -1;
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003042 return (int)ListAssSlice(self, start, step, slicelen,
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003043 obj);
3044 }
3045 else
3046 {
3047 RAISE_INVALID_INDEX_TYPE(idx);
3048 return -1;
3049 }
3050}
3051
3052 static PyObject *
3053ListConcatInPlace(ListObject *self, PyObject *obj)
3054{
3055 list_T *l = self->list;
3056 PyObject *lookup_dict;
3057
3058 if (l->lv_lock)
3059 {
3060 RAISE_LOCKED_LIST;
3061 return NULL;
3062 }
3063
3064 if (!(lookup_dict = PyDict_New()))
3065 return NULL;
3066
3067 if (list_py_concat(l, obj, lookup_dict) == -1)
3068 {
3069 Py_DECREF(lookup_dict);
3070 return NULL;
3071 }
3072 Py_DECREF(lookup_dict);
3073
3074 Py_INCREF(self);
3075 return (PyObject *)(self);
3076}
3077
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003078typedef struct
3079{
3080 listwatch_T lw;
3081 list_T *list;
3082} listiterinfo_T;
3083
3084 static void
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003085ListIterDestruct(void *arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003086{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003087 listiterinfo_T *lii = (listiterinfo_T*)arg;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003088 list_rem_watch(lii->list, &lii->lw);
Bram Moolenaar21578272021-02-21 19:12:47 +01003089 list_unref(lii->list);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003090 PyMem_Free(lii);
3091}
3092
3093 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003094ListIterNext(void **arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003095{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003096 PyObject *ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003097 listiterinfo_T **lii = (listiterinfo_T**)arg;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003098
3099 if (!((*lii)->lw.lw_item))
3100 return NULL;
3101
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003102 if (!(ret = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003103 return NULL;
3104
3105 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
3106
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003107 return ret;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003108}
3109
3110 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003111ListIter(ListObject *self)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003112{
3113 listiterinfo_T *lii;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003114 list_T *l = self->list;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003115
3116 if (!(lii = PyMem_New(listiterinfo_T, 1)))
3117 {
3118 PyErr_NoMemory();
3119 return NULL;
3120 }
3121
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003122 CHECK_LIST_MATERIALIZE(l);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003123 list_add_watch(l, &lii->lw);
3124 lii->lw.lw_item = l->lv_first;
3125 lii->list = l;
Bram Moolenaar21578272021-02-21 19:12:47 +01003126 ++l->lv_refcount;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003127
3128 return IterNew(lii,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003129 ListIterDestruct, ListIterNext,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02003130 NULL, NULL, (PyObject *)self);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003131}
3132
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003133static char *ListAttrs[] = {
3134 "locked",
3135 NULL
3136};
3137
3138 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003139ListDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003140{
3141 return ObjectDir(self, ListAttrs);
3142}
3143
Bram Moolenaar66b79852012-09-21 14:00:35 +02003144 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003145ListSetattr(ListObject *self, char *name, PyObject *valObject)
Bram Moolenaar66b79852012-09-21 14:00:35 +02003146{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003147 if (valObject == NULL)
Bram Moolenaar66b79852012-09-21 14:00:35 +02003148 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02003149 PyErr_SET_STRING(PyExc_AttributeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003150 N_("cannot delete vim.List attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02003151 return -1;
3152 }
3153
3154 if (strcmp(name, "locked") == 0)
3155 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003156 if (self->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02003157 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003158 PyErr_SET_STRING(PyExc_TypeError, N_("cannot modify fixed list"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02003159 return -1;
3160 }
3161 else
3162 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003163 int istrue = PyObject_IsTrue(valObject);
Bram Moolenaarb983f752013-05-15 16:11:50 +02003164 if (istrue == -1)
3165 return -1;
3166 else if (istrue)
Bram Moolenaard6e39182013-05-21 18:30:34 +02003167 self->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02003168 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02003169 self->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02003170 }
3171 return 0;
3172 }
3173 else
3174 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003175 PyErr_FORMAT(PyExc_AttributeError, N_("cannot set attribute %s"), name);
Bram Moolenaar66b79852012-09-21 14:00:35 +02003176 return -1;
3177 }
3178}
3179
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003180static PySequenceMethods ListAsSeq = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003181 (lenfunc) ListLength, // sq_length, len(x)
3182 (binaryfunc) 0, // RangeConcat, sq_concat, x+y
3183 0, // RangeRepeat, sq_repeat, x*n
3184 (PyIntArgFunc) ListIndex, // sq_item, x[i]
3185 0, // was_sq_slice, x[i:j]
3186 (PyIntObjArgProc) ListAssIndex, // sq_as_item, x[i]=v
3187 0, // was_sq_ass_slice, x[i:j]=v
3188 0, // sq_contains
3189 (binaryfunc) ListConcatInPlace,// sq_inplace_concat
3190 0, // sq_inplace_repeat
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003191};
3192
3193static PyMappingMethods ListAsMapping = {
3194 /* mp_length */ (lenfunc) ListLength,
3195 /* mp_subscript */ (binaryfunc) ListItem,
3196 /* mp_ass_subscript */ (objobjargproc) ListAssItem,
3197};
3198
Bram Moolenaardb913952012-06-29 12:54:53 +02003199static struct PyMethodDef ListMethods[] = {
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003200 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
3201 {"__dir__", (PyCFunction)ListDir, METH_NOARGS, ""},
3202 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02003203};
3204
3205typedef struct
3206{
3207 PyObject_HEAD
3208 char_u *name;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003209 int argc;
3210 typval_T *argv;
3211 dict_T *self;
3212 pylinkedlist_T ref;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003213 int auto_rebind;
Bram Moolenaardb913952012-06-29 12:54:53 +02003214} FunctionObject;
3215
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003216DEFINE_PY_TYPE_OBJECT(FunctionType);
Bram Moolenaardb913952012-06-29 12:54:53 +02003217
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003218#define NEW_FUNCTION(name, argc, argv, self, pt_auto) \
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003219 FunctionNew(FunctionTypePtr, (name), (argc), (argv), (self), (pt_auto))
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003220
Bram Moolenaardb913952012-06-29 12:54:53 +02003221 static PyObject *
Bram Moolenaar8110a092016-04-14 15:56:09 +02003222FunctionNew(PyTypeObject *subtype, char_u *name, int argc, typval_T *argv,
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003223 dict_T *selfdict, int auto_rebind)
Bram Moolenaardb913952012-06-29 12:54:53 +02003224{
3225 FunctionObject *self;
3226
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003227 self = (FunctionObject *) Py_TYPE_GET_TP_ALLOC(subtype)(subtype, 0);
Bram Moolenaardb913952012-06-29 12:54:53 +02003228 if (self == NULL)
3229 return NULL;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003230
3231 if (isdigit(*name))
Bram Moolenaardb913952012-06-29 12:54:53 +02003232 {
Bram Moolenaara14bb7e2020-04-28 00:02:41 +02003233 if (!translated_function_exists(name, FALSE))
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003234 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02003235 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003236 N_("unnamed function %s does not exist"), name);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003237 return NULL;
3238 }
3239 self->name = vim_strsave(name);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003240 }
3241 else
Bram Moolenaar9123c0b2018-12-22 18:59:06 +01003242 {
3243 char_u *p;
3244
3245 if ((p = get_expanded_name(name,
3246 vim_strchr(name, AUTOLOAD_CHAR) == NULL)) == NULL)
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003247 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003248 PyErr_FORMAT(PyExc_ValueError,
3249 N_("function %s does not exist"), name);
Bram Moolenaar018acca2013-05-30 13:37:28 +02003250 return NULL;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003251 }
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003252
Bram Moolenaar9123c0b2018-12-22 18:59:06 +01003253 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA && p[2] == (int)KE_SNR)
3254 {
3255 char_u *np;
3256 size_t len = STRLEN(p) + 1;
3257
Bram Moolenaar51e14382019-05-25 20:21:28 +02003258 if ((np = alloc(len + 2)) == NULL)
Bram Moolenaar9123c0b2018-12-22 18:59:06 +01003259 {
3260 vim_free(p);
3261 return NULL;
3262 }
3263 mch_memmove(np, "<SNR>", 5);
3264 mch_memmove(np + 5, p + 3, len - 3);
3265 vim_free(p);
3266 self->name = np;
3267 }
3268 else
3269 self->name = p;
3270 }
3271
Bram Moolenaar2d3d60a2016-08-01 16:27:23 +02003272 func_ref(self->name);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003273 self->argc = argc;
3274 self->argv = argv;
3275 self->self = selfdict;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003276 self->auto_rebind = selfdict == NULL ? TRUE : auto_rebind;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003277
3278 if (self->argv || self->self)
3279 pyll_add((PyObject *)(self), &self->ref, &lastfunc);
3280
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003281 return (PyObject *)(self);
3282}
3283
3284 static PyObject *
3285FunctionConstructor(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
3286{
3287 PyObject *self;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003288 PyObject *selfdictObject;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003289 PyObject *autoRebindObject;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003290 PyObject *argsObject = NULL;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003291 char_u *name;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003292 typval_T selfdicttv;
3293 typval_T argstv;
3294 list_T *argslist = NULL;
3295 dict_T *selfdict = NULL;
3296 int argc = 0;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003297 int auto_rebind = TRUE;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003298 typval_T *argv = NULL;
3299 typval_T *curtv;
3300 listitem_T *li;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003301
Bram Moolenaar8110a092016-04-14 15:56:09 +02003302 if (kwargs != NULL)
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003303 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02003304 selfdictObject = PyDict_GetItemString(kwargs, "self");
3305 if (selfdictObject != NULL)
3306 {
3307 if (ConvertFromPyMapping(selfdictObject, &selfdicttv) == -1)
3308 return NULL;
3309 selfdict = selfdicttv.vval.v_dict;
3310 }
3311 argsObject = PyDict_GetItemString(kwargs, "args");
3312 if (argsObject != NULL)
3313 {
3314 if (ConvertFromPySequence(argsObject, &argstv) == -1)
3315 {
3316 dict_unref(selfdict);
3317 return NULL;
3318 }
3319 argslist = argstv.vval.v_list;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003320 CHECK_LIST_MATERIALIZE(argslist);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003321
3322 argc = argslist->lv_len;
3323 if (argc != 0)
3324 {
3325 argv = PyMem_New(typval_T, (size_t) argc);
Bram Moolenaarfe4b1862016-04-15 21:47:54 +02003326 if (argv == NULL)
3327 {
3328 PyErr_NoMemory();
3329 dict_unref(selfdict);
3330 list_unref(argslist);
3331 return NULL;
3332 }
Bram Moolenaar8110a092016-04-14 15:56:09 +02003333 curtv = argv;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003334 FOR_ALL_LIST_ITEMS(argslist, li)
Bram Moolenaar8110a092016-04-14 15:56:09 +02003335 copy_tv(&li->li_tv, curtv++);
3336 }
3337 list_unref(argslist);
3338 }
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003339 if (selfdict != NULL)
3340 {
3341 auto_rebind = FALSE;
3342 autoRebindObject = PyDict_GetItemString(kwargs, "auto_rebind");
3343 if (autoRebindObject != NULL)
3344 {
3345 auto_rebind = PyObject_IsTrue(autoRebindObject);
3346 if (auto_rebind == -1)
3347 {
3348 dict_unref(selfdict);
3349 list_unref(argslist);
3350 return NULL;
3351 }
3352 }
3353 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003354 }
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003355
Bram Moolenaar389a1792013-06-23 13:00:44 +02003356 if (!PyArg_ParseTuple(args, "et", "ascii", &name))
Bram Moolenaar8110a092016-04-14 15:56:09 +02003357 {
3358 dict_unref(selfdict);
3359 while (argc--)
3360 clear_tv(&argv[argc]);
3361 PyMem_Free(argv);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003362 return NULL;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003363 }
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003364
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003365 self = FunctionNew(subtype, name, argc, argv, selfdict, auto_rebind);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003366
Bram Moolenaar389a1792013-06-23 13:00:44 +02003367 PyMem_Free(name);
3368
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003369 return self;
Bram Moolenaardb913952012-06-29 12:54:53 +02003370}
3371
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003372 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02003373FunctionDestructor(FunctionObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003374{
Bram Moolenaar8110a092016-04-14 15:56:09 +02003375 int i;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003376 func_unref(self->name);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003377 vim_free(self->name);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003378 for (i = 0; i < self->argc; ++i)
3379 clear_tv(&self->argv[i]);
3380 PyMem_Free(self->argv);
3381 dict_unref(self->self);
3382 if (self->argv || self->self)
3383 pyll_remove(&self->ref, &lastfunc);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003384
3385 DESTRUCTOR_FINISH(self);
3386}
3387
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003388static char *FunctionAttrs[] = {
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003389 "softspace", "args", "self", "auto_rebind",
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003390 NULL
3391};
3392
3393 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003394FunctionDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003395{
3396 return ObjectDir(self, FunctionAttrs);
3397}
3398
Bram Moolenaardb913952012-06-29 12:54:53 +02003399 static PyObject *
Bram Moolenaar8110a092016-04-14 15:56:09 +02003400FunctionAttr(FunctionObject *self, char *name)
3401{
3402 list_T *list;
3403 int i;
3404 if (strcmp(name, "name") == 0)
3405 return PyString_FromString((char *)(self->name));
3406 else if (strcmp(name, "args") == 0)
3407 {
Bram Moolenaar9f289532016-08-26 16:39:03 +02003408 if (self->argv == NULL || (list = list_alloc()) == NULL)
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003409 return ALWAYS_NONE;
Bram Moolenaar9f289532016-08-26 16:39:03 +02003410
Bram Moolenaar8110a092016-04-14 15:56:09 +02003411 for (i = 0; i < self->argc; ++i)
3412 list_append_tv(list, &self->argv[i]);
3413 return NEW_LIST(list);
3414 }
3415 else if (strcmp(name, "self") == 0)
3416 return self->self == NULL
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003417 ? ALWAYS_NONE
Bram Moolenaar8110a092016-04-14 15:56:09 +02003418 : NEW_DICTIONARY(self->self);
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003419 else if (strcmp(name, "auto_rebind") == 0)
3420 return self->auto_rebind
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003421 ? ALWAYS_TRUE
3422 : ALWAYS_FALSE;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003423 else if (strcmp(name, "__members__") == 0)
3424 return ObjectDir(NULL, FunctionAttrs);
3425 return NULL;
3426}
3427
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003428/*
3429 * Populate partial_T given function object.
Bram Moolenaar8110a092016-04-14 15:56:09 +02003430 *
3431 * "exported" should be set to true when it is needed to construct a partial
3432 * that may be stored in a variable (i.e. may be freed by Vim).
3433 */
3434 static void
3435set_partial(FunctionObject *self, partial_T *pt, int exported)
3436{
Bram Moolenaar8110a092016-04-14 15:56:09 +02003437 int i;
3438
3439 pt->pt_name = self->name;
3440 if (self->argv)
3441 {
3442 pt->pt_argc = self->argc;
3443 if (exported)
3444 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003445 pt->pt_argv = ALLOC_CLEAR_MULT(typval_T, self->argc);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003446 for (i = 0; i < pt->pt_argc; ++i)
3447 copy_tv(&self->argv[i], &pt->pt_argv[i]);
3448 }
3449 else
3450 pt->pt_argv = self->argv;
3451 }
3452 else
3453 {
3454 pt->pt_argc = 0;
3455 pt->pt_argv = NULL;
3456 }
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003457 pt->pt_auto = self->auto_rebind || !exported;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003458 pt->pt_dict = self->self;
3459 if (exported && self->self)
3460 ++pt->pt_dict->dv_refcount;
3461 if (exported)
3462 pt->pt_name = vim_strsave(pt->pt_name);
3463 pt->pt_refcount = 1;
3464}
3465
3466 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003467FunctionCall(FunctionObject *self, PyObject *argsObject, PyObject *kwargs)
Bram Moolenaardb913952012-06-29 12:54:53 +02003468{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003469 char_u *name = self->name;
Bram Moolenaardb913952012-06-29 12:54:53 +02003470 typval_T args;
3471 typval_T selfdicttv;
3472 typval_T rettv;
3473 dict_T *selfdict = NULL;
3474 PyObject *selfdictObject;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003475 PyObject *ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02003476 int error;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003477 partial_T pt;
3478 partial_T *pt_ptr = NULL;
Bram Moolenaardb913952012-06-29 12:54:53 +02003479
Bram Moolenaar8110a092016-04-14 15:56:09 +02003480 if (ConvertFromPySequence(argsObject, &args) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +02003481 return NULL;
3482
3483 if (kwargs != NULL)
3484 {
3485 selfdictObject = PyDict_GetItemString(kwargs, "self");
3486 if (selfdictObject != NULL)
3487 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02003488 if (ConvertFromPyMapping(selfdictObject, &selfdicttv) == -1)
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003489 {
3490 clear_tv(&args);
Bram Moolenaardb913952012-06-29 12:54:53 +02003491 return NULL;
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003492 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003493 selfdict = selfdicttv.vval.v_dict;
3494 }
3495 }
3496
Bram Moolenaar8110a092016-04-14 15:56:09 +02003497 if (self->argv || self->self)
3498 {
Bram Moolenaara80faa82020-04-12 19:37:17 +02003499 CLEAR_FIELD(pt);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003500 set_partial(self, &pt, FALSE);
3501 pt_ptr = &pt;
3502 }
3503
Bram Moolenaar71700b82013-05-15 17:49:05 +02003504 Py_BEGIN_ALLOW_THREADS
3505 Python_Lock_Vim();
3506
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003507 VimTryStart();
Bram Moolenaar8110a092016-04-14 15:56:09 +02003508 error = func_call(name, &args, pt_ptr, selfdict, &rettv);
Bram Moolenaar71700b82013-05-15 17:49:05 +02003509
3510 Python_Release_Vim();
3511 Py_END_ALLOW_THREADS
3512
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003513 if (VimTryEnd())
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003514 ret = NULL;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003515 else if (error != OK)
Bram Moolenaardb913952012-06-29 12:54:53 +02003516 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003517 ret = NULL;
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003518 PyErr_VIM_FORMAT(N_("failed to run function %s"), (char *)name);
Bram Moolenaardb913952012-06-29 12:54:53 +02003519 }
3520 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003521 ret = ConvertToPyObject(&rettv);
Bram Moolenaardb913952012-06-29 12:54:53 +02003522
Bram Moolenaardb913952012-06-29 12:54:53 +02003523 clear_tv(&args);
3524 clear_tv(&rettv);
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003525 if (selfdict != NULL)
3526 clear_tv(&selfdicttv);
Bram Moolenaardb913952012-06-29 12:54:53 +02003527
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003528 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02003529}
3530
Bram Moolenaara5b725c2013-05-30 12:43:54 +02003531 static PyObject *
3532FunctionRepr(FunctionObject *self)
3533{
Bram Moolenaar8110a092016-04-14 15:56:09 +02003534 PyObject *ret;
3535 garray_T repr_ga;
3536 int i;
3537 char_u *tofree = NULL;
3538 typval_T tv;
3539 char_u numbuf[NUMBUFLEN];
3540
Bram Moolenaar04935fb2022-01-08 16:19:22 +00003541 ga_init2(&repr_ga, sizeof(char), 70);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003542 ga_concat(&repr_ga, (char_u *)"<vim.Function '");
3543 if (self->name)
3544 ga_concat(&repr_ga, self->name);
3545 else
3546 ga_concat(&repr_ga, (char_u *)"<NULL>");
3547 ga_append(&repr_ga, '\'');
3548 if (self->argv)
3549 {
3550 ga_concat(&repr_ga, (char_u *)", args=[");
3551 ++emsg_silent;
3552 for (i = 0; i < self->argc; i++)
3553 {
3554 if (i != 0)
3555 ga_concat(&repr_ga, (char_u *)", ");
3556 ga_concat(&repr_ga, tv2string(&self->argv[i], &tofree, numbuf,
3557 get_copyID()));
3558 vim_free(tofree);
3559 }
3560 --emsg_silent;
3561 ga_append(&repr_ga, ']');
3562 }
3563 if (self->self)
3564 {
3565 ga_concat(&repr_ga, (char_u *)", self=");
3566 tv.v_type = VAR_DICT;
3567 tv.vval.v_dict = self->self;
3568 ++emsg_silent;
3569 ga_concat(&repr_ga, tv2string(&tv, &tofree, numbuf, get_copyID()));
3570 --emsg_silent;
3571 vim_free(tofree);
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003572 if (self->auto_rebind)
3573 ga_concat(&repr_ga, (char_u *)", auto_rebind=True");
Bram Moolenaar8110a092016-04-14 15:56:09 +02003574 }
3575 ga_append(&repr_ga, '>');
3576 ret = PyString_FromString((char *)repr_ga.ga_data);
3577 ga_clear(&repr_ga);
3578 return ret;
Bram Moolenaara5b725c2013-05-30 12:43:54 +02003579}
3580
Bram Moolenaardb913952012-06-29 12:54:53 +02003581static struct PyMethodDef FunctionMethods[] = {
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003582 {"__dir__", (PyCFunction)FunctionDir, METH_NOARGS, ""},
3583 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02003584};
3585
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003586/*
3587 * Options object
3588 */
3589
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003590DEFINE_PY_TYPE_OBJECT(OptionsType);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003591
3592typedef int (*checkfun)(void *);
3593
3594typedef struct
3595{
3596 PyObject_HEAD
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003597 int opt_type;
3598 void *from;
3599 checkfun Check;
3600 PyObject *fromObj;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003601} OptionsObject;
3602
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003603 static int
3604dummy_check(void *arg UNUSED)
3605{
3606 return 0;
3607}
3608
3609 static PyObject *
3610OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
3611{
3612 OptionsObject *self;
3613
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003614 self = PyObject_GC_New(OptionsObject, OptionsTypePtr);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003615 if (self == NULL)
3616 return NULL;
3617
3618 self->opt_type = opt_type;
3619 self->from = from;
3620 self->Check = Check;
3621 self->fromObj = fromObj;
3622 if (fromObj)
3623 Py_INCREF(fromObj);
3624
3625 return (PyObject *)(self);
3626}
3627
3628 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02003629OptionsDestructor(OptionsObject *self)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003630{
Bram Moolenaar774267b2013-05-21 20:51:59 +02003631 PyObject_GC_UnTrack((void *)(self));
3632 Py_XDECREF(self->fromObj);
3633 PyObject_GC_Del((void *)(self));
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003634}
3635
3636 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02003637OptionsTraverse(OptionsObject *self, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003638{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003639 Py_VISIT(self->fromObj);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003640 return 0;
3641}
3642
3643 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02003644OptionsClear(OptionsObject *self)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003645{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003646 Py_CLEAR(self->fromObj);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003647 return 0;
3648}
3649
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003650 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003651OptionsItem(OptionsObject *self, PyObject *keyObject)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003652{
3653 char_u *key;
3654 int flags;
3655 long numval;
3656 char_u *stringval;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003657 PyObject *todecref;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003658
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02003659 if (self->Check(self->fromObj))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003660 return NULL;
3661
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003662 if (!(key = StringToChars(keyObject, &todecref)))
3663 return NULL;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003664
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003665 if (*key == NUL)
3666 {
3667 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003668 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003669 return NULL;
3670 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003671
3672 flags = get_option_value_strict(key, &numval, &stringval,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003673 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003674
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003675 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003676
3677 if (flags == 0)
3678 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003679 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003680 return NULL;
3681 }
3682
3683 if (flags & SOPT_UNSET)
3684 {
3685 Py_INCREF(Py_None);
3686 return Py_None;
3687 }
3688 else if (flags & SOPT_BOOL)
3689 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003690 PyObject *ret;
3691 ret = numval ? Py_True : Py_False;
3692 Py_INCREF(ret);
3693 return ret;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003694 }
3695 else if (flags & SOPT_NUM)
3696 return PyInt_FromLong(numval);
3697 else if (flags & SOPT_STRING)
3698 {
3699 if (stringval)
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003700 {
Bram Moolenaar41009372013-07-01 22:03:04 +02003701 PyObject *ret = PyBytes_FromString((char *)stringval);
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003702 vim_free(stringval);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003703 return ret;
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003704 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003705 else
3706 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02003707 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003708 N_("unable to get option value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003709 return NULL;
3710 }
3711 }
3712 else
3713 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003714 PyErr_SET_VIM(N_("internal error: unknown option type"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003715 return NULL;
3716 }
3717}
3718
3719 static int
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003720OptionsContains(OptionsObject *self, PyObject *keyObject)
3721{
3722 char_u *key;
3723 PyObject *todecref;
3724
3725 if (!(key = StringToChars(keyObject, &todecref)))
3726 return -1;
3727
3728 if (*key == NUL)
3729 {
3730 Py_XDECREF(todecref);
3731 return 0;
3732 }
3733
3734 if (get_option_value_strict(key, NULL, NULL, self->opt_type, NULL))
3735 {
3736 Py_XDECREF(todecref);
3737 return 1;
3738 }
3739 else
3740 {
3741 Py_XDECREF(todecref);
3742 return 0;
3743 }
3744}
3745
3746typedef struct
3747{
3748 void *lastoption;
3749 int opt_type;
3750} optiterinfo_T;
3751
3752 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003753OptionsIterNext(void **arg)
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003754{
3755 char_u *name;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003756 optiterinfo_T **oii = (optiterinfo_T**)arg;
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003757
3758 if ((name = option_iter_next(&((*oii)->lastoption), (*oii)->opt_type)))
3759 return PyString_FromString((char *)name);
3760
3761 return NULL;
3762}
3763
3764 static PyObject *
3765OptionsIter(OptionsObject *self)
3766{
3767 optiterinfo_T *oii;
3768
3769 if (!(oii = PyMem_New(optiterinfo_T, 1)))
3770 {
3771 PyErr_NoMemory();
3772 return NULL;
3773 }
3774
3775 oii->opt_type = self->opt_type;
3776 oii->lastoption = NULL;
3777
3778 return IterNew(oii,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003779 PyMem_Free, OptionsIterNext,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02003780 NULL, NULL, (PyObject *)self);
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003781}
3782
3783 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02003784set_option_value_err(char_u *key, int numval, char_u *stringval, int opt_flags)
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003785{
Bram Moolenaarb1443b42019-01-13 23:51:14 +01003786 char *errmsg;
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003787
3788 if ((errmsg = set_option_value(key, numval, stringval, opt_flags)))
3789 {
3790 if (VimTryEnd())
3791 return FAIL;
Bram Moolenaarb1443b42019-01-13 23:51:14 +01003792 PyErr_SetVim(errmsg);
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003793 return FAIL;
3794 }
3795 return OK;
3796}
3797
3798 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02003799set_option_value_for(
3800 char_u *key,
3801 int numval,
3802 char_u *stringval,
3803 int opt_flags,
3804 int opt_type,
3805 void *from)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003806{
Bram Moolenaar18f47402022-01-06 13:24:51 +00003807 switchwin_T switchwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003808 bufref_T save_curbuf;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003809 int set_ret = 0;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003810
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003811 VimTryStart();
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003812 switch (opt_type)
3813 {
3814 case SREQ_WIN:
Bram Moolenaar18f47402022-01-06 13:24:51 +00003815 if (switch_win(&switchwin, (win_T *)from,
Bram Moolenaard6949742013-06-16 14:18:28 +02003816 win_find_tabpage((win_T *)from), FALSE) == FAIL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003817 {
Bram Moolenaar18f47402022-01-06 13:24:51 +00003818 restore_win(&switchwin, TRUE);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003819 if (VimTryEnd())
3820 return -1;
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003821 PyErr_SET_VIM(N_("problem while switching windows"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003822 return -1;
3823 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003824 set_ret = set_option_value_err(key, numval, stringval, opt_flags);
Bram Moolenaar18f47402022-01-06 13:24:51 +00003825 restore_win(&switchwin, TRUE);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003826 break;
3827 case SREQ_BUF:
Bram Moolenaar105bc352013-05-17 16:03:57 +02003828 switch_buffer(&save_curbuf, (buf_T *)from);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003829 set_ret = set_option_value_err(key, numval, stringval, opt_flags);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003830 restore_buffer(&save_curbuf);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003831 break;
3832 case SREQ_GLOBAL:
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003833 set_ret = set_option_value_err(key, numval, stringval, opt_flags);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003834 break;
3835 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003836 if (set_ret == FAIL)
3837 return -1;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003838 return VimTryEnd();
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003839}
3840
3841 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02003842OptionsAssItem(OptionsObject *self, PyObject *keyObject, PyObject *valObject)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003843{
3844 char_u *key;
3845 int flags;
3846 int opt_flags;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003847 int ret = 0;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003848 PyObject *todecref;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003849
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02003850 if (self->Check(self->fromObj))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003851 return -1;
3852
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003853 if (!(key = StringToChars(keyObject, &todecref)))
3854 return -1;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003855
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003856 if (*key == NUL)
3857 {
3858 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003859 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003860 return -1;
3861 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003862
3863 flags = get_option_value_strict(key, NULL, NULL,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003864 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003865
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003866 if (flags == 0)
3867 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003868 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003869 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003870 return -1;
3871 }
3872
3873 if (valObject == NULL)
3874 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003875 if (self->opt_type == SREQ_GLOBAL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003876 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02003877 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003878 N_("unable to unset global option %s"), key);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003879 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003880 return -1;
3881 }
3882 else if (!(flags & SOPT_GLOBAL))
3883 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02003884 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003885 N_("unable to unset option %s "
3886 "which does not have global value"), key);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003887 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003888 return -1;
3889 }
3890 else
3891 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003892 unset_global_local_option(key, self->from);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003893 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003894 return 0;
3895 }
3896 }
3897
Bram Moolenaard6e39182013-05-21 18:30:34 +02003898 opt_flags = (self->opt_type ? OPT_LOCAL : OPT_GLOBAL);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003899
3900 if (flags & SOPT_BOOL)
3901 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02003902 int istrue = PyObject_IsTrue(valObject);
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003903
Bram Moolenaarb983f752013-05-15 16:11:50 +02003904 if (istrue == -1)
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003905 ret = -1;
Bram Moolenaar1bc24282013-05-29 21:37:35 +02003906 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003907 ret = set_option_value_for(key, istrue, NULL,
Bram Moolenaar1bc24282013-05-29 21:37:35 +02003908 opt_flags, self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003909 }
3910 else if (flags & SOPT_NUM)
3911 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +02003912 long val;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003913
Bram Moolenaar141be8a2013-06-23 14:16:57 +02003914 if (NumberToLong(valObject, &val, NUMBER_INT))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003915 {
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003916 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003917 return -1;
3918 }
3919
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003920 ret = set_option_value_for(key, (int) val, NULL, opt_flags,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003921 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003922 }
3923 else
3924 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003925 char_u *val;
Bram Moolenaarc2401d62013-12-07 14:28:43 +01003926 PyObject *todecref2;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02003927
Bram Moolenaarc2401d62013-12-07 14:28:43 +01003928 if ((val = StringToChars(valObject, &todecref2)))
3929 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003930 ret = set_option_value_for(key, 0, val, opt_flags,
Bram Moolenaare9ba5162013-05-29 22:02:22 +02003931 self->opt_type, self->from);
Bram Moolenaarc2401d62013-12-07 14:28:43 +01003932 Py_XDECREF(todecref2);
3933 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003934 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003935 ret = -1;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003936 }
3937
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003938 Py_XDECREF(todecref);
Bram Moolenaar1bc24282013-05-29 21:37:35 +02003939
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003940 return ret;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003941}
3942
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003943static PySequenceMethods OptionsAsSeq = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003944 0, // sq_length
3945 0, // sq_concat
3946 0, // sq_repeat
3947 0, // sq_item
3948 0, // sq_slice
3949 0, // sq_ass_item
3950 0, // sq_ass_slice
3951 (objobjproc) OptionsContains, // sq_contains
3952 0, // sq_inplace_concat
3953 0, // sq_inplace_repeat
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003954};
3955
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003956static PyMappingMethods OptionsAsMapping = {
3957 (lenfunc) NULL,
3958 (binaryfunc) OptionsItem,
3959 (objobjargproc) OptionsAssItem,
3960};
3961
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003962// Tabpage object
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003963
3964typedef struct
3965{
3966 PyObject_HEAD
3967 tabpage_T *tab;
3968} TabPageObject;
3969
3970static PyObject *WinListNew(TabPageObject *tabObject);
3971
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003972DEFINE_PY_TYPE_OBJECT(TabPageType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003973
3974 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02003975CheckTabPage(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003976{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003977 if (self->tab == INVALID_TABPAGE_VALUE)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003978 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003979 PyErr_SET_VIM(N_("attempt to refer to deleted tab page"));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003980 return -1;
3981 }
3982
3983 return 0;
3984}
3985
3986 static PyObject *
3987TabPageNew(tabpage_T *tab)
3988{
3989 TabPageObject *self;
3990
3991 if (TAB_PYTHON_REF(tab))
3992 {
3993 self = TAB_PYTHON_REF(tab);
3994 Py_INCREF(self);
3995 }
3996 else
3997 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003998 self = PyObject_NEW(TabPageObject, TabPageTypePtr);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003999 if (self == NULL)
4000 return NULL;
4001 self->tab = tab;
4002 TAB_PYTHON_REF(tab) = self;
4003 }
4004
4005 return (PyObject *)(self);
4006}
4007
4008 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02004009TabPageDestructor(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004010{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004011 if (self->tab && self->tab != INVALID_TABPAGE_VALUE)
4012 TAB_PYTHON_REF(self->tab) = NULL;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004013
4014 DESTRUCTOR_FINISH(self);
4015}
4016
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004017static char *TabPageAttrs[] = {
4018 "windows", "number", "vars", "window", "valid",
4019 NULL
4020};
4021
4022 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02004023TabPageDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004024{
4025 return ObjectDir(self, TabPageAttrs);
4026}
4027
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004028 static PyObject *
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004029TabPageAttrValid(TabPageObject *self, char *name)
4030{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004031 PyObject *ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004032
4033 if (strcmp(name, "valid") != 0)
4034 return NULL;
4035
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004036 ret = ((self->tab == INVALID_TABPAGE_VALUE) ? Py_False : Py_True);
4037 Py_INCREF(ret);
4038 return ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004039}
4040
4041 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004042TabPageAttr(TabPageObject *self, char *name)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004043{
4044 if (strcmp(name, "windows") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004045 return WinListNew(self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004046 else if (strcmp(name, "number") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004047 return PyLong_FromLong((long) get_tab_number(self->tab));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004048 else if (strcmp(name, "vars") == 0)
Bram Moolenaara9922d62013-05-30 13:01:18 +02004049 return NEW_DICTIONARY(self->tab->tp_vars);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004050 else if (strcmp(name, "window") == 0)
4051 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004052 // For current tab window.c does not bother to set or update tp_curwin
Bram Moolenaard6e39182013-05-21 18:30:34 +02004053 if (self->tab == curtab)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004054 return WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004055 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004056 return WindowNew(self->tab->tp_curwin, self->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004057 }
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004058 else if (strcmp(name, "__members__") == 0)
4059 return ObjectDir(NULL, TabPageAttrs);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004060 return NULL;
4061}
4062
4063 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004064TabPageRepr(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004065{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004066 if (self->tab == INVALID_TABPAGE_VALUE)
Dominique Pellec14f6672022-01-09 12:57:48 +00004067 return PyString_FromFormat("<tabpage object (deleted) at %p>", (void *)self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004068 else
4069 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004070 int t = get_tab_number(self->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004071
4072 if (t == 0)
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004073 return PyString_FromFormat("<tabpage object (unknown) at %p>",
Dominique Pellec14f6672022-01-09 12:57:48 +00004074 (void *)self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004075 else
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004076 return PyString_FromFormat("<tabpage %d>", t - 1);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004077 }
4078}
4079
4080static struct PyMethodDef TabPageMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004081 // name, function, calling, documentation
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004082 {"__dir__", (PyCFunction)TabPageDir, METH_NOARGS, ""},
4083 { NULL, NULL, 0, NULL}
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004084};
4085
4086/*
4087 * Window list object
4088 */
4089
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004090DEFINE_PY_TYPE_OBJECT(TabListType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004091static PySequenceMethods TabListAsSeq;
4092
4093typedef struct
4094{
4095 PyObject_HEAD
4096} TabListObject;
4097
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004098static TabListObject TheTabPageList =
4099{
4100 PyObject_HEAD_INIT_TYPE(TabListType)
4101};
4102
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004103 static PyInt
4104TabListLength(PyObject *self UNUSED)
4105{
4106 tabpage_T *tp = first_tabpage;
4107 PyInt n = 0;
4108
4109 while (tp != NULL)
4110 {
4111 ++n;
4112 tp = tp->tp_next;
4113 }
4114
4115 return n;
4116}
4117
4118 static PyObject *
4119TabListItem(PyObject *self UNUSED, PyInt n)
4120{
4121 tabpage_T *tp;
4122
4123 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, --n)
4124 if (n == 0)
4125 return TabPageNew(tp);
4126
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004127 PyErr_SET_STRING(PyExc_IndexError, N_("no such tab page"));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004128 return NULL;
4129}
4130
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +02004131/*
4132 * Window object
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004133 */
4134
4135typedef struct
4136{
4137 PyObject_HEAD
4138 win_T *win;
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004139 TabPageObject *tabObject;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004140} WindowObject;
4141
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004142DEFINE_PY_TYPE_OBJECT(WindowType);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004143
4144 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02004145CheckWindow(WindowObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004146{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004147 if (self->win == INVALID_WINDOW_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004148 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004149 PyErr_SET_VIM(N_("attempt to refer to deleted window"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004150 return -1;
4151 }
4152
4153 return 0;
4154}
4155
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02004156 static int
4157CheckWindowCb(void *self)
4158{
4159 return CheckWindow((WindowObject*)self);
4160}
4161
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004162 static PyObject *
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004163WindowNew(win_T *win, tabpage_T *tab)
Bram Moolenaar971db462013-05-12 18:44:48 +02004164{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004165 /*
4166 * We need to handle deletion of windows underneath us.
Bram Moolenaar971db462013-05-12 18:44:48 +02004167 * If we add a "w_python*_ref" field to the win_T structure,
4168 * then we can get at it in win_free() in vim. We then
4169 * need to create only ONE Python object per window - if
4170 * we try to create a second, just INCREF the existing one
4171 * and return it. The (single) Python object referring to
4172 * the window is stored in "w_python*_ref".
4173 * On a win_free() we set the Python object's win_T* field
4174 * to an invalid value. We trap all uses of a window
4175 * object, and reject them if the win_T* field is invalid.
4176 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004177 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02004178 * w_python_ref and w_python3_ref fields respectively.
4179 */
4180
4181 WindowObject *self;
4182
4183 if (WIN_PYTHON_REF(win))
4184 {
4185 self = WIN_PYTHON_REF(win);
4186 Py_INCREF(self);
4187 }
4188 else
4189 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004190 self = PyObject_GC_New(WindowObject, WindowTypePtr);
Bram Moolenaar971db462013-05-12 18:44:48 +02004191 if (self == NULL)
4192 return NULL;
4193 self->win = win;
4194 WIN_PYTHON_REF(win) = self;
4195 }
4196
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004197 self->tabObject = ((TabPageObject *)(TabPageNew(tab)));
4198
Bram Moolenaar971db462013-05-12 18:44:48 +02004199 return (PyObject *)(self);
4200}
4201
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004202 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02004203WindowDestructor(WindowObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004204{
Bram Moolenaar774267b2013-05-21 20:51:59 +02004205 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaard6e39182013-05-21 18:30:34 +02004206 if (self->win && self->win != INVALID_WINDOW_VALUE)
4207 WIN_PYTHON_REF(self->win) = NULL;
Bram Moolenaarab589462020-07-06 21:03:06 +02004208 Py_XDECREF(((PyObject *)(self->tabObject)));
Bram Moolenaar774267b2013-05-21 20:51:59 +02004209 PyObject_GC_Del((void *)(self));
4210}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004211
Bram Moolenaar774267b2013-05-21 20:51:59 +02004212 static int
4213WindowTraverse(WindowObject *self, visitproc visit, void *arg)
4214{
4215 Py_VISIT(((PyObject *)(self->tabObject)));
4216 return 0;
4217}
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004218
Bram Moolenaar774267b2013-05-21 20:51:59 +02004219 static int
4220WindowClear(WindowObject *self)
4221{
4222 Py_CLEAR(self->tabObject);
4223 return 0;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004224}
4225
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004226 static win_T *
4227get_firstwin(TabPageObject *tabObject)
4228{
4229 if (tabObject)
4230 {
4231 if (CheckTabPage(tabObject))
4232 return NULL;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004233 // For current tab window.c does not bother to set or update tp_firstwin
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004234 else if (tabObject->tab == curtab)
4235 return firstwin;
4236 else
4237 return tabObject->tab->tp_firstwin;
4238 }
4239 else
4240 return firstwin;
4241}
Bram Moolenaare950f992018-06-10 13:55:55 +02004242
4243// Use the same order as in the WindowAttr() function.
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004244static char *WindowAttrs[] = {
Bram Moolenaare950f992018-06-10 13:55:55 +02004245 "buffer",
4246 "cursor",
4247 "height",
4248 "row",
4249 "width",
4250 "col",
4251 "vars",
4252 "options",
4253 "number",
4254 "tabpage",
4255 "valid",
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004256 NULL
4257};
4258
4259 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02004260WindowDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004261{
4262 return ObjectDir(self, WindowAttrs);
4263}
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004264
Bram Moolenaar971db462013-05-12 18:44:48 +02004265 static PyObject *
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004266WindowAttrValid(WindowObject *self, char *name)
4267{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004268 PyObject *ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004269
4270 if (strcmp(name, "valid") != 0)
4271 return NULL;
4272
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004273 ret = ((self->win == INVALID_WINDOW_VALUE) ? Py_False : Py_True);
4274 Py_INCREF(ret);
4275 return ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004276}
4277
4278 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004279WindowAttr(WindowObject *self, char *name)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004280{
4281 if (strcmp(name, "buffer") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004282 return (PyObject *)BufferNew(self->win->w_buffer);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004283 else if (strcmp(name, "cursor") == 0)
4284 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004285 pos_T *pos = &self->win->w_cursor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004286
4287 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
4288 }
4289 else if (strcmp(name, "height") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004290 return PyLong_FromLong((long)(self->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02004291 else if (strcmp(name, "row") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004292 return PyLong_FromLong((long)(self->win->w_winrow));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004293 else if (strcmp(name, "width") == 0)
Bram Moolenaar02631462017-09-22 15:20:32 +02004294 return PyLong_FromLong((long)(self->win->w_width));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02004295 else if (strcmp(name, "col") == 0)
Bram Moolenaar53f81742017-09-22 14:35:51 +02004296 return PyLong_FromLong((long)(self->win->w_wincol));
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02004297 else if (strcmp(name, "vars") == 0)
Bram Moolenaara9922d62013-05-30 13:01:18 +02004298 return NEW_DICTIONARY(self->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02004299 else if (strcmp(name, "options") == 0)
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02004300 return OptionsNew(SREQ_WIN, self->win, CheckWindowCb,
Bram Moolenaard6e39182013-05-21 18:30:34 +02004301 (PyObject *) self);
Bram Moolenaar6d216452013-05-12 19:00:41 +02004302 else if (strcmp(name, "number") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004303 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004304 if (CheckTabPage(self->tabObject))
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004305 return NULL;
4306 return PyLong_FromLong((long)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004307 get_win_number(self->win, get_firstwin(self->tabObject)));
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004308 }
4309 else if (strcmp(name, "tabpage") == 0)
4310 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004311 Py_INCREF(self->tabObject);
4312 return (PyObject *)(self->tabObject);
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004313 }
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004314 else if (strcmp(name, "__members__") == 0)
4315 return ObjectDir(NULL, WindowAttrs);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004316 else
4317 return NULL;
4318}
4319
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004320 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004321WindowSetattr(WindowObject *self, char *name, PyObject *valObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004322{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004323 if (CheckWindow(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004324 return -1;
4325
4326 if (strcmp(name, "buffer") == 0)
4327 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004328 PyErr_SET_STRING(PyExc_TypeError, N_("readonly attribute: buffer"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004329 return -1;
4330 }
4331 else if (strcmp(name, "cursor") == 0)
4332 {
4333 long lnum;
4334 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004335
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004336 if (!PyArg_Parse(valObject, "(ll)", &lnum, &col))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004337 return -1;
4338
Bram Moolenaard6e39182013-05-21 18:30:34 +02004339 if (lnum <= 0 || lnum > self->win->w_buffer->b_ml.ml_line_count)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004340 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004341 PyErr_SET_VIM(N_("cursor position outside buffer"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004342 return -1;
4343 }
4344
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004345 // Check for keyboard interrupts
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004346 if (VimCheckInterrupt())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004347 return -1;
4348
Bram Moolenaard6e39182013-05-21 18:30:34 +02004349 self->win->w_cursor.lnum = lnum;
4350 self->win->w_cursor.col = col;
Bram Moolenaar53901442018-07-25 22:02:36 +02004351 self->win->w_set_curswant = TRUE;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004352 self->win->w_cursor.coladd = 0;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004353 // When column is out of range silently correct it.
Bram Moolenaard6e39182013-05-21 18:30:34 +02004354 check_cursor_col_win(self->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004355
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004356 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004357 return 0;
4358 }
4359 else if (strcmp(name, "height") == 0)
4360 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004361 long height;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004362 win_T *savewin;
4363
Bram Moolenaardee2e312013-06-23 16:35:47 +02004364 if (NumberToLong(valObject, &height, NUMBER_INT|NUMBER_UNSIGNED))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004365 return -1;
4366
4367#ifdef FEAT_GUI
4368 need_mouse_correct = TRUE;
4369#endif
4370 savewin = curwin;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004371 curwin = self->win;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004372 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004373
4374 VimTryStart();
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004375 win_setheight((int) height);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004376 curwin = savewin;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004377 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004378 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004379 return -1;
4380
4381 return 0;
4382 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004383 else if (strcmp(name, "width") == 0)
4384 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004385 long width;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004386 win_T *savewin;
4387
Bram Moolenaardee2e312013-06-23 16:35:47 +02004388 if (NumberToLong(valObject, &width, NUMBER_INT|NUMBER_UNSIGNED))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004389 return -1;
4390
4391#ifdef FEAT_GUI
4392 need_mouse_correct = TRUE;
4393#endif
4394 savewin = curwin;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004395 curwin = self->win;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004396 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004397
4398 VimTryStart();
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004399 win_setwidth((int) width);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004400 curwin = savewin;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004401 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004402 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004403 return -1;
4404
4405 return 0;
4406 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004407 else
4408 {
4409 PyErr_SetString(PyExc_AttributeError, name);
4410 return -1;
4411 }
4412}
4413
4414 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004415WindowRepr(WindowObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004416{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004417 if (self->win == INVALID_WINDOW_VALUE)
Dominique Pellec14f6672022-01-09 12:57:48 +00004418 return PyString_FromFormat("<window object (deleted) at %p>", (void *)self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004419 else
4420 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004421 int w = get_win_number(self->win, firstwin);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004422
Bram Moolenaar6d216452013-05-12 19:00:41 +02004423 if (w == 0)
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004424 return PyString_FromFormat("<window object (unknown) at %p>",
Dominique Pellec14f6672022-01-09 12:57:48 +00004425 (void *)self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004426 else
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004427 return PyString_FromFormat("<window %d>", w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004428 }
4429}
4430
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004431static struct PyMethodDef WindowMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004432 // name, function, calling, documentation
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004433 {"__dir__", (PyCFunction)WindowDir, METH_NOARGS, ""},
4434 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004435};
4436
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004437/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004438 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004439 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004440
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004441DEFINE_PY_TYPE_OBJECT(WinListType);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004442static PySequenceMethods WinListAsSeq;
4443
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004444typedef struct
4445{
4446 PyObject_HEAD
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004447 TabPageObject *tabObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004448} WinListObject;
4449
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004450static WinListObject TheWindowList =
4451{
4452 PyObject_HEAD_INIT_TYPE(WinListType)
4453 NULL
4454};
4455
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004456 static PyObject *
4457WinListNew(TabPageObject *tabObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004458{
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004459 WinListObject *self;
4460
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004461 self = PyObject_NEW(WinListObject, WinListTypePtr);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004462 self->tabObject = tabObject;
4463 Py_INCREF(tabObject);
4464
4465 return (PyObject *)(self);
4466}
4467
4468 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02004469WinListDestructor(WinListObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004470{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004471 TabPageObject *tabObject = self->tabObject;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004472
4473 if (tabObject)
Bram Moolenaar425154d2013-05-24 18:58:43 +02004474 {
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004475 Py_DECREF((PyObject *)(tabObject));
Bram Moolenaar425154d2013-05-24 18:58:43 +02004476 }
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004477
4478 DESTRUCTOR_FINISH(self);
4479}
4480
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004481 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02004482WinListLength(WinListObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004483{
4484 win_T *w;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004485 PyInt n = 0;
4486
Bram Moolenaard6e39182013-05-21 18:30:34 +02004487 if (!(w = get_firstwin(self->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004488 return -1;
4489
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004490 while (w != NULL)
4491 {
4492 ++n;
4493 w = W_NEXT(w);
4494 }
4495
4496 return n;
4497}
4498
4499 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004500WinListItem(WinListObject *self, PyInt n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004501{
4502 win_T *w;
4503
Bram Moolenaard6e39182013-05-21 18:30:34 +02004504 if (!(w = get_firstwin(self->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004505 return NULL;
4506
4507 for (; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004508 if (n == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004509 return WindowNew(w, self->tabObject? self->tabObject->tab: curtab);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004510
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004511 PyErr_SET_STRING(PyExc_IndexError, N_("no such window"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004512 return NULL;
4513}
4514
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004515/*
4516 * Convert a Python string into a Vim line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004517 *
4518 * The result is in allocated memory. All internal nulls are replaced by
4519 * newline characters. It is an error for the string to contain newline
4520 * characters.
4521 *
4522 * On errors, the Python exception data is set, and NULL is returned.
4523 */
4524 static char *
4525StringToLine(PyObject *obj)
4526{
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004527 char *str;
4528 char *save;
4529 PyObject *bytes = NULL;
Bram Moolenaardee2e312013-06-23 16:35:47 +02004530 Py_ssize_t len = 0;
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004531 PyInt i;
4532 char *p;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004533
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004534 if (PyBytes_Check(obj))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004535 {
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004536 if (PyBytes_AsStringAndSize(obj, &str, &len) == -1
4537 || str == NULL)
4538 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004539 }
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004540 else if (PyUnicode_Check(obj))
4541 {
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01004542 if (!(bytes = PyUnicode_AsEncodedString(obj, ENC_OPT,
4543 ERRORS_ENCODE_ARG)))
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004544 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004545
Bram Moolenaardaa27022013-06-24 22:33:30 +02004546 if (PyBytes_AsStringAndSize(bytes, &str, &len) == -1
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004547 || str == NULL)
4548 {
4549 Py_DECREF(bytes);
4550 return NULL;
4551 }
4552 }
Bram Moolenaardaa27022013-06-24 22:33:30 +02004553 else
4554 {
4555#if PY_MAJOR_VERSION < 3
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004556 PyErr_FORMAT_TYPE(
Bram Moolenaardaa27022013-06-24 22:33:30 +02004557 N_("expected str() or unicode() instance, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004558 obj);
Bram Moolenaardaa27022013-06-24 22:33:30 +02004559#else
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004560 PyErr_FORMAT_TYPE(
Bram Moolenaardaa27022013-06-24 22:33:30 +02004561 N_("expected bytes() or str() instance, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004562 obj);
Bram Moolenaardaa27022013-06-24 22:33:30 +02004563#endif
4564 return NULL;
4565 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004566
4567 /*
4568 * Error checking: String must not contain newlines, as we
4569 * are replacing a single line, and we must replace it with
4570 * a single line.
4571 * A trailing newline is removed, so that append(f.readlines()) works.
4572 */
4573 p = memchr(str, '\n', len);
4574 if (p != NULL)
4575 {
4576 if (p == str + len - 1)
4577 --len;
4578 else
4579 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004580 PyErr_SET_VIM(N_("string cannot contain newlines"));
Bram Moolenaar841fbd22013-06-23 14:37:07 +02004581 Py_XDECREF(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004582 return NULL;
4583 }
4584 }
4585
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004586 /*
4587 * Create a copy of the string, with internal nulls replaced by
Bram Moolenaar86181df2020-05-11 23:14:04 +02004588 * newline characters, as is the Vim convention.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004589 */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004590 save = alloc(len+1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004591 if (save == NULL)
4592 {
4593 PyErr_NoMemory();
Bram Moolenaar841fbd22013-06-23 14:37:07 +02004594 Py_XDECREF(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004595 return NULL;
4596 }
4597
4598 for (i = 0; i < len; ++i)
4599 {
4600 if (str[i] == '\0')
4601 save[i] = '\n';
4602 else
4603 save[i] = str[i];
4604 }
4605
4606 save[i] = '\0';
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004607 Py_XDECREF(bytes); // Python 2 does nothing here
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004608
4609 return save;
4610}
4611
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004612/*
4613 * Get a line from the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004614 * in Vim format (1-based). The line is returned as a Python
4615 * string object.
4616 */
4617 static PyObject *
4618GetBufferLine(buf_T *buf, PyInt n)
4619{
4620 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
4621}
4622
4623
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004624/*
4625 * Get a list of lines from the specified buffer. The line numbers
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004626 * are in Vim format (1-based). The range is from lo up to, but not
4627 * including, hi. The list is returned as a Python list of string objects.
4628 */
4629 static PyObject *
4630GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
4631{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004632 PyInt i;
4633 PyInt n = hi - lo;
4634 PyObject *list = PyList_New(n);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004635
4636 if (list == NULL)
4637 return NULL;
4638
4639 for (i = 0; i < n; ++i)
4640 {
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02004641 linenr_T lnum = (linenr_T)(lo + i);
4642 char *text;
4643 PyObject *string;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004644
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02004645 if (lnum > buf->b_ml.ml_line_count)
4646 text = "";
4647 else
4648 text = (char *)ml_get_buf(buf, lnum, FALSE);
4649 string = LineToString(text);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004650 if (string == NULL)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004651 {
4652 Py_DECREF(list);
4653 return NULL;
4654 }
4655
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004656 PyList_SET_ITEM(list, i, string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004657 }
4658
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004659 // The ownership of the Python list is passed to the caller (ie,
4660 // the caller should Py_DECREF() the object when it is finished
4661 // with it).
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004662
4663 return list;
4664}
4665
4666/*
4667 * Check if deleting lines made the cursor position invalid.
4668 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
4669 * deleted).
4670 */
4671 static void
4672py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
4673{
4674 if (curwin->w_cursor.lnum >= lo)
4675 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004676 // Adjust the cursor position if it's in/after the changed
4677 // lines.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004678 if (curwin->w_cursor.lnum >= hi)
4679 {
4680 curwin->w_cursor.lnum += extra;
4681 check_cursor_col();
4682 }
4683 else if (extra < 0)
4684 {
4685 curwin->w_cursor.lnum = lo;
4686 check_cursor();
4687 }
4688 else
4689 check_cursor_col();
4690 changed_cline_bef_curs();
4691 }
4692 invalidate_botline();
4693}
4694
Bram Moolenaar19e60942011-06-19 00:27:51 +02004695/*
4696 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004697 * in Vim format (1-based). The replacement line is given as
4698 * a Python string object. The object is checked for validity
4699 * and correct format. Errors are returned as a value of FAIL.
4700 * The return value is OK on success.
4701 * If OK is returned and len_change is not NULL, *len_change
4702 * is set to the change in the buffer length.
4703 */
4704 static int
4705SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
4706{
Bram Moolenaar45e5fd12017-06-04 14:58:02 +02004707 bufref_T save_curbuf = {NULL, 0, 0};
Bram Moolenaar18f47402022-01-06 13:24:51 +00004708 switchwin_T switchwin;
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004709
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004710 // First of all, we check the type of the supplied Python object.
4711 // There are three cases:
4712 // 1. NULL, or None - this is a deletion.
4713 // 2. A string - this is a replacement.
4714 // 3. Anything else - this is an error.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004715 if (line == Py_None || line == NULL)
4716 {
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004717 PyErr_Clear();
Bram Moolenaar18f47402022-01-06 13:24:51 +00004718 switchwin.sw_curwin = NULL;
4719 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004720
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004721 VimTryStart();
4722
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004723 if (u_savedel((linenr_T)n, 1L) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02004724 RAISE_UNDO_FAIL;
Bram Moolenaarca70c072020-05-30 20:30:46 +02004725 else if (ml_delete((linenr_T)n) == FAIL)
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004726 RAISE_DELETE_LINE_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004727 else
4728 {
Bram Moolenaar18f47402022-01-06 13:24:51 +00004729 if (buf == curbuf && (switchwin.sw_curwin != NULL
Bram Moolenaar63dbfd32019-03-23 17:41:59 +01004730 || save_curbuf.br_buf == NULL))
4731 // Using an existing window for the buffer, adjust the cursor
4732 // position.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004733 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004734 if (save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004735 // Only adjust marks if we managed to switch to a window that
4736 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004737 deleted_lines_mark((linenr_T)n, 1L);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004738 }
4739
Bram Moolenaar18f47402022-01-06 13:24:51 +00004740 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004741
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004742 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004743 return FAIL;
4744
4745 if (len_change)
4746 *len_change = -1;
4747
4748 return OK;
4749 }
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004750 else if (PyBytes_Check(line) || PyUnicode_Check(line))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004751 {
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004752 char *save = StringToLine(line);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004753
4754 if (save == NULL)
4755 return FAIL;
4756
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004757 VimTryStart();
4758
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004759 // We do not need to free "save" if ml_replace() consumes it.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004760 PyErr_Clear();
Bram Moolenaar18f47402022-01-06 13:24:51 +00004761 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004762
4763 if (u_savesub((linenr_T)n) == FAIL)
4764 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02004765 RAISE_UNDO_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004766 vim_free(save);
4767 }
4768 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
4769 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004770 RAISE_REPLACE_LINE_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004771 vim_free(save);
4772 }
4773 else
4774 changed_bytes((linenr_T)n, 0);
4775
Bram Moolenaar18f47402022-01-06 13:24:51 +00004776 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004777
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004778 // Check that the cursor is not beyond the end of the line now.
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004779 if (buf == curbuf)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004780 check_cursor_col();
4781
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004782 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004783 return FAIL;
4784
4785 if (len_change)
4786 *len_change = 0;
4787
4788 return OK;
4789 }
4790 else
4791 {
4792 PyErr_BadArgument();
4793 return FAIL;
4794 }
4795}
4796
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004797/*
4798 * Replace a range of lines in the specified buffer. The line numbers are in
Bram Moolenaar19e60942011-06-19 00:27:51 +02004799 * Vim format (1-based). The range is from lo up to, but not including, hi.
4800 * The replacement lines are given as a Python list of string objects. The
4801 * list is checked for validity and correct format. Errors are returned as a
4802 * value of FAIL. The return value is OK on success.
4803 * If OK is returned and len_change is not NULL, *len_change
4804 * is set to the change in the buffer length.
4805 */
4806 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004807SetBufferLineList(
4808 buf_T *buf,
4809 PyInt lo,
4810 PyInt hi,
4811 PyObject *list,
4812 PyInt *len_change)
Bram Moolenaar19e60942011-06-19 00:27:51 +02004813{
Bram Moolenaar45e5fd12017-06-04 14:58:02 +02004814 bufref_T save_curbuf = {NULL, 0, 0};
Bram Moolenaar18f47402022-01-06 13:24:51 +00004815 switchwin_T switchwin;
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004816
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004817 // First of all, we check the type of the supplied Python object.
4818 // There are three cases:
4819 // 1. NULL, or None - this is a deletion.
4820 // 2. A list - this is a replacement.
4821 // 3. Anything else - this is an error.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004822 if (list == Py_None || list == NULL)
4823 {
4824 PyInt i;
4825 PyInt n = (int)(hi - lo);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004826
4827 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004828 VimTryStart();
Bram Moolenaar18f47402022-01-06 13:24:51 +00004829 switchwin.sw_curwin = NULL;
4830 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004831
4832 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02004833 RAISE_UNDO_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004834 else
4835 {
4836 for (i = 0; i < n; ++i)
4837 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02004838 if (ml_delete((linenr_T)lo) == FAIL)
Bram Moolenaar19e60942011-06-19 00:27:51 +02004839 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004840 RAISE_DELETE_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004841 break;
4842 }
4843 }
Bram Moolenaar18f47402022-01-06 13:24:51 +00004844 if (buf == curbuf && (switchwin.sw_curwin != NULL
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004845 || save_curbuf.br_buf == NULL))
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004846 // Using an existing window for the buffer, adjust the cursor
4847 // position.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004848 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004849 if (save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004850 // Only adjust marks if we managed to switch to a window that
4851 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004852 deleted_lines_mark((linenr_T)lo, (long)i);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004853 }
4854
Bram Moolenaar18f47402022-01-06 13:24:51 +00004855 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004856
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004857 if (VimTryEnd())
Bram Moolenaar19e60942011-06-19 00:27:51 +02004858 return FAIL;
4859
4860 if (len_change)
4861 *len_change = -n;
4862
4863 return OK;
4864 }
4865 else if (PyList_Check(list))
4866 {
4867 PyInt i;
4868 PyInt new_len = PyList_Size(list);
4869 PyInt old_len = hi - lo;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004870 PyInt extra = 0; // lines added to text, can be negative
Bram Moolenaar19e60942011-06-19 00:27:51 +02004871 char **array;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004872
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004873 if (new_len == 0) // avoid allocating zero bytes
Bram Moolenaar19e60942011-06-19 00:27:51 +02004874 array = NULL;
4875 else
4876 {
Bram Moolenaare9ba5162013-05-29 22:02:22 +02004877 array = PyMem_New(char *, new_len);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004878 if (array == NULL)
4879 {
4880 PyErr_NoMemory();
4881 return FAIL;
4882 }
4883 }
4884
4885 for (i = 0; i < new_len; ++i)
4886 {
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02004887 PyObject *line;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004888
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02004889 if (!(line = PyList_GetItem(list, i)) ||
4890 !(array[i] = StringToLine(line)))
Bram Moolenaar19e60942011-06-19 00:27:51 +02004891 {
4892 while (i)
4893 vim_free(array[--i]);
Bram Moolenaare9ba5162013-05-29 22:02:22 +02004894 PyMem_Free(array);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004895 return FAIL;
4896 }
4897 }
4898
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004899 VimTryStart();
Bram Moolenaar19e60942011-06-19 00:27:51 +02004900 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02004901
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004902 // START of region without "return". Must call restore_buffer()!
Bram Moolenaar18f47402022-01-06 13:24:51 +00004903 switchwin.sw_curwin = NULL;
4904 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004905
4906 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02004907 RAISE_UNDO_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004908
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004909 // If the size of the range is reducing (ie, new_len < old_len) we
4910 // need to delete some old_len. We do this at the start, by
4911 // repeatedly deleting line "lo".
Bram Moolenaar19e60942011-06-19 00:27:51 +02004912 if (!PyErr_Occurred())
4913 {
4914 for (i = 0; i < old_len - new_len; ++i)
Bram Moolenaarca70c072020-05-30 20:30:46 +02004915 if (ml_delete((linenr_T)lo) == FAIL)
Bram Moolenaar19e60942011-06-19 00:27:51 +02004916 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004917 RAISE_DELETE_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004918 break;
4919 }
4920 extra -= i;
4921 }
4922
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004923 // For as long as possible, replace the existing old_len with the
4924 // new old_len. This is a more efficient operation, as it requires
4925 // less memory allocation and freeing.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004926 if (!PyErr_Occurred())
4927 {
4928 for (i = 0; i < old_len && i < new_len; ++i)
4929 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
4930 == FAIL)
4931 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004932 RAISE_REPLACE_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004933 break;
4934 }
4935 }
4936 else
4937 i = 0;
4938
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004939 // Now we may need to insert the remaining new old_len. If we do, we
4940 // must free the strings as we finish with them (we can't pass the
Bram Moolenaar86181df2020-05-11 23:14:04 +02004941 // responsibility to Vim in this case).
Bram Moolenaar19e60942011-06-19 00:27:51 +02004942 if (!PyErr_Occurred())
4943 {
4944 while (i < new_len)
4945 {
4946 if (ml_append((linenr_T)(lo + i - 1),
4947 (char_u *)array[i], 0, FALSE) == FAIL)
4948 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004949 RAISE_INSERT_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004950 break;
4951 }
4952 vim_free(array[i]);
4953 ++i;
4954 ++extra;
4955 }
4956 }
4957
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004958 // Free any left-over old_len, as a result of an error
Bram Moolenaar19e60942011-06-19 00:27:51 +02004959 while (i < new_len)
4960 {
4961 vim_free(array[i]);
4962 ++i;
4963 }
4964
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004965 // Free the array of old_len. All of its contents have now
4966 // been dealt with (either freed, or the responsibility passed
4967 // to vim.
Bram Moolenaare9ba5162013-05-29 22:02:22 +02004968 PyMem_Free(array);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004969
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004970 // Adjust marks. Invalidate any which lie in the
4971 // changed range, and move any in the remainder of the buffer.
4972 // Only adjust marks if we managed to switch to a window that holds
4973 // the buffer, otherwise line numbers will be invalid.
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004974 if (save_curbuf.br_buf == NULL)
Bram Moolenaar37233f62022-05-22 12:23:48 +01004975 {
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004976 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
Bram Moolenaar19e60942011-06-19 00:27:51 +02004977 (long)MAXLNUM, (long)extra);
Bram Moolenaar37233f62022-05-22 12:23:48 +01004978 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
4979 }
Bram Moolenaar19e60942011-06-19 00:27:51 +02004980
Bram Moolenaar18f47402022-01-06 13:24:51 +00004981 if (buf == curbuf && (switchwin.sw_curwin != NULL
Bram Moolenaar63dbfd32019-03-23 17:41:59 +01004982 || save_curbuf.br_buf == NULL))
4983 // Using an existing window for the buffer, adjust the cursor
4984 // position.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004985 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
4986
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004987 // END of region without "return".
Bram Moolenaar18f47402022-01-06 13:24:51 +00004988 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004989
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004990 if (VimTryEnd())
Bram Moolenaar19e60942011-06-19 00:27:51 +02004991 return FAIL;
4992
4993 if (len_change)
4994 *len_change = new_len - old_len;
4995
4996 return OK;
4997 }
4998 else
4999 {
5000 PyErr_BadArgument();
5001 return FAIL;
5002 }
5003}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005004
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005005/*
5006 * Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005007 * The line number is in Vim format (1-based). The lines to be inserted are
5008 * given as a Python list of string objects or as a single string. The lines
5009 * to be added are checked for validity and correct format. Errors are
5010 * returned as a value of FAIL. The return value is OK on success.
5011 * If OK is returned and len_change is not NULL, *len_change
5012 * is set to the change in the buffer length.
5013 */
5014 static int
5015InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
5016{
Bram Moolenaar45e5fd12017-06-04 14:58:02 +02005017 bufref_T save_curbuf = {NULL, 0, 0};
Bram Moolenaar18f47402022-01-06 13:24:51 +00005018 switchwin_T switchwin;
Bram Moolenaar95064ec2013-07-17 17:15:25 +02005019
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005020 // First of all, we check the type of the supplied Python object.
5021 // It must be a string or a list, or the call is in error.
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02005022 if (PyBytes_Check(lines) || PyUnicode_Check(lines))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005023 {
Bram Moolenaar95064ec2013-07-17 17:15:25 +02005024 char *str = StringToLine(lines);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005025
5026 if (str == NULL)
5027 return FAIL;
5028
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005029 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005030 VimTryStart();
Bram Moolenaar18f47402022-01-06 13:24:51 +00005031 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005032
Bram Moolenaar95064ec2013-07-17 17:15:25 +02005033 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02005034 RAISE_UNDO_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005035 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005036 RAISE_INSERT_LINE_FAIL;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005037 else if (save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005038 // Only adjust marks if we managed to switch to a window that
5039 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005040 appended_lines_mark((linenr_T)n, 1L);
5041
5042 vim_free(str);
Bram Moolenaar18f47402022-01-06 13:24:51 +00005043 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005044 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005045
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005046 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005047 return FAIL;
5048
5049 if (len_change)
5050 *len_change = 1;
5051
5052 return OK;
5053 }
5054 else if (PyList_Check(lines))
5055 {
5056 PyInt i;
5057 PyInt size = PyList_Size(lines);
5058 char **array;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005059
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005060 array = PyMem_New(char *, size);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005061 if (array == NULL)
5062 {
5063 PyErr_NoMemory();
5064 return FAIL;
5065 }
5066
5067 for (i = 0; i < size; ++i)
5068 {
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005069 PyObject *line;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005070
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005071 if (!(line = PyList_GetItem(lines, i)) ||
5072 !(array[i] = StringToLine(line)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005073 {
5074 while (i)
5075 vim_free(array[--i]);
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005076 PyMem_Free(array);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005077 return FAIL;
5078 }
5079 }
5080
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005081 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005082 VimTryStart();
Bram Moolenaar18f47402022-01-06 13:24:51 +00005083 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005084
5085 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02005086 RAISE_UNDO_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005087 else
5088 {
5089 for (i = 0; i < size; ++i)
5090 {
5091 if (ml_append((linenr_T)(n + i),
5092 (char_u *)array[i], 0, FALSE) == FAIL)
5093 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005094 RAISE_INSERT_LINE_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005095
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005096 // Free the rest of the lines
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005097 while (i < size)
5098 vim_free(array[i++]);
5099
5100 break;
5101 }
5102 vim_free(array[i]);
5103 }
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005104 if (i > 0 && save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005105 // Only adjust marks if we managed to switch to a window that
5106 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005107 appended_lines_mark((linenr_T)n, (long)i);
5108 }
5109
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005110 // Free the array of lines. All of its contents have now
5111 // been freed.
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005112 PyMem_Free(array);
Bram Moolenaar18f47402022-01-06 13:24:51 +00005113 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005114
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005115 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005116
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005117 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005118 return FAIL;
5119
5120 if (len_change)
5121 *len_change = size;
5122
5123 return OK;
5124 }
5125 else
5126 {
5127 PyErr_BadArgument();
5128 return FAIL;
5129 }
5130}
5131
5132/*
5133 * Common routines for buffers and line ranges
5134 * -------------------------------------------
5135 */
5136
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005137typedef struct
5138{
5139 PyObject_HEAD
5140 buf_T *buf;
5141} BufferObject;
5142
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005143 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02005144CheckBuffer(BufferObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005145{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005146 if (self->buf == INVALID_BUFFER_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005147 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005148 PyErr_SET_VIM(N_("attempt to refer to deleted buffer"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005149 return -1;
5150 }
5151
5152 return 0;
5153}
5154
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005155 static int
5156CheckBufferCb(void *self)
5157{
5158 return CheckBuffer((BufferObject*)self);
5159}
5160
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005161 static PyObject *
5162RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
5163{
5164 if (CheckBuffer(self))
5165 return NULL;
5166
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005167 if (end == -1)
5168 end = self->buf->b_ml.ml_line_count;
5169
Bram Moolenaarbd80f352013-05-12 21:16:23 +02005170 if (n < 0)
5171 n += end - start + 1;
5172
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005173 if (n < 0 || n > end - start)
5174 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005175 PyErr_SET_STRING(PyExc_IndexError, N_("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005176 return NULL;
5177 }
5178
5179 return GetBufferLine(self->buf, n+start);
5180}
5181
5182 static PyObject *
5183RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
5184{
5185 PyInt size;
5186
5187 if (CheckBuffer(self))
5188 return NULL;
5189
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005190 if (end == -1)
5191 end = self->buf->b_ml.ml_line_count;
5192
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005193 size = end - start + 1;
5194
5195 if (lo < 0)
5196 lo = 0;
5197 else if (lo > size)
5198 lo = size;
5199 if (hi < 0)
5200 hi = 0;
5201 if (hi < lo)
5202 hi = lo;
5203 else if (hi > size)
5204 hi = size;
5205
5206 return GetBufferLineList(self->buf, lo+start, hi+start);
5207}
5208
5209 static PyInt
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005210RBAsItem(
5211 BufferObject *self,
5212 PyInt n,
5213 PyObject *valObject,
5214 PyInt start,
5215 PyInt end,
5216 PyInt *new_end)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005217{
5218 PyInt len_change;
5219
5220 if (CheckBuffer(self))
5221 return -1;
5222
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005223 if (end == -1)
5224 end = self->buf->b_ml.ml_line_count;
5225
Bram Moolenaarbd80f352013-05-12 21:16:23 +02005226 if (n < 0)
5227 n += end - start + 1;
5228
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005229 if (n < 0 || n > end - start)
5230 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005231 PyErr_SET_STRING(PyExc_IndexError, N_("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005232 return -1;
5233 }
5234
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005235 if (SetBufferLine(self->buf, n+start, valObject, &len_change) == FAIL)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005236 return -1;
5237
5238 if (new_end)
5239 *new_end = end + len_change;
5240
5241 return 0;
5242}
5243
Bram Moolenaar19e60942011-06-19 00:27:51 +02005244 static PyInt
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005245RBAsSlice(
5246 BufferObject *self,
5247 PyInt lo,
5248 PyInt hi,
5249 PyObject *valObject,
5250 PyInt start,
5251 PyInt end,
5252 PyInt *new_end)
Bram Moolenaar19e60942011-06-19 00:27:51 +02005253{
5254 PyInt size;
5255 PyInt len_change;
5256
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005257 // Self must be a valid buffer
Bram Moolenaar19e60942011-06-19 00:27:51 +02005258 if (CheckBuffer(self))
5259 return -1;
5260
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005261 if (end == -1)
5262 end = self->buf->b_ml.ml_line_count;
5263
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005264 // Sort out the slice range
Bram Moolenaar19e60942011-06-19 00:27:51 +02005265 size = end - start + 1;
5266
5267 if (lo < 0)
5268 lo = 0;
5269 else if (lo > size)
5270 lo = size;
5271 if (hi < 0)
5272 hi = 0;
5273 if (hi < lo)
5274 hi = lo;
5275 else if (hi > size)
5276 hi = size;
5277
5278 if (SetBufferLineList(self->buf, lo + start, hi + start,
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005279 valObject, &len_change) == FAIL)
Bram Moolenaar19e60942011-06-19 00:27:51 +02005280 return -1;
5281
5282 if (new_end)
5283 *new_end = end + len_change;
5284
5285 return 0;
5286}
5287
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005288
5289 static PyObject *
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005290RBAppend(
5291 BufferObject *self,
5292 PyObject *args,
5293 PyInt start,
5294 PyInt end,
5295 PyInt *new_end)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005296{
5297 PyObject *lines;
5298 PyInt len_change;
5299 PyInt max;
5300 PyInt n;
5301
5302 if (CheckBuffer(self))
5303 return NULL;
5304
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005305 if (end == -1)
5306 end = self->buf->b_ml.ml_line_count;
5307
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005308 max = n = end - start + 1;
5309
5310 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
5311 return NULL;
5312
5313 if (n < 0 || n > max)
5314 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005315 PyErr_SET_STRING(PyExc_IndexError, N_("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005316 return NULL;
5317 }
5318
5319 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
5320 return NULL;
5321
5322 if (new_end)
5323 *new_end = end + len_change;
5324
5325 Py_INCREF(Py_None);
5326 return Py_None;
5327}
5328
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005329// Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005330
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005331DEFINE_PY_TYPE_OBJECT(RangeType);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005332static PySequenceMethods RangeAsSeq;
5333static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005334
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005335typedef struct
5336{
5337 PyObject_HEAD
5338 BufferObject *buf;
5339 PyInt start;
5340 PyInt end;
5341} RangeObject;
5342
5343 static PyObject *
5344RangeNew(buf_T *buf, PyInt start, PyInt end)
5345{
5346 BufferObject *bufr;
5347 RangeObject *self;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005348 self = PyObject_GC_New(RangeObject, RangeTypePtr);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005349 if (self == NULL)
5350 return NULL;
5351
5352 bufr = (BufferObject *)BufferNew(buf);
5353 if (bufr == NULL)
5354 {
5355 Py_DECREF(self);
5356 return NULL;
5357 }
5358 Py_INCREF(bufr);
5359
5360 self->buf = bufr;
5361 self->start = start;
5362 self->end = end;
5363
5364 return (PyObject *)(self);
5365}
5366
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005367 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02005368RangeDestructor(RangeObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005369{
Bram Moolenaar774267b2013-05-21 20:51:59 +02005370 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005371 Py_XDECREF(self->buf);
Bram Moolenaar774267b2013-05-21 20:51:59 +02005372 PyObject_GC_Del((void *)(self));
5373}
5374
5375 static int
5376RangeTraverse(RangeObject *self, visitproc visit, void *arg)
5377{
5378 Py_VISIT(((PyObject *)(self->buf)));
5379 return 0;
5380}
5381
5382 static int
5383RangeClear(RangeObject *self)
5384{
5385 Py_CLEAR(self->buf);
5386 return 0;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005387}
5388
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005389 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02005390RangeLength(RangeObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005391{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005392 // HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION?
Bram Moolenaard6e39182013-05-21 18:30:34 +02005393 if (CheckBuffer(self->buf))
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005394 return -1; // ???
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005395
Bram Moolenaard6e39182013-05-21 18:30:34 +02005396 return (self->end - self->start + 1);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005397}
5398
5399 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005400RangeItem(RangeObject *self, PyInt n)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005401{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005402 return RBItem(self->buf, n, self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005403}
5404
5405 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005406RangeSlice(RangeObject *self, PyInt lo, PyInt hi)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005407{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005408 return RBSlice(self->buf, lo, hi, self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005409}
5410
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005411static char *RangeAttrs[] = {
5412 "start", "end",
5413 NULL
5414};
5415
5416 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02005417RangeDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005418{
5419 return ObjectDir(self, RangeAttrs);
5420}
5421
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005422 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005423RangeAppend(RangeObject *self, PyObject *args)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005424{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005425 return RBAppend(self->buf, args, self->start, self->end, &self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005426}
5427
5428 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005429RangeRepr(RangeObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005430{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005431 if (self->buf->buf == INVALID_BUFFER_VALUE)
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005432 return PyString_FromFormat("<range object (for deleted buffer) at %p>",
Dominique Pellec14f6672022-01-09 12:57:48 +00005433 (void *)self);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005434 else
5435 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02005436 char *name = (char *)self->buf->buf->b_fname;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005437
5438 if (name == NULL)
5439 name = "";
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005440
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005441 return PyString_FromFormat("<range %s (%d:%d)>",
Bram Moolenaarf62d9422013-05-30 19:01:24 +02005442 name, (int)self->start, (int)self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005443 }
5444}
5445
5446static struct PyMethodDef RangeMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005447 // name, function, calling, documentation
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02005448 {"append", (PyCFunction)RangeAppend, METH_VARARGS, "Append data to the Vim range" },
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005449 {"__dir__", (PyCFunction)RangeDir, METH_NOARGS, ""},
5450 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005451};
5452
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005453DEFINE_PY_TYPE_OBJECT(BufferType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005454static PySequenceMethods BufferAsSeq;
5455static PyMappingMethods BufferAsMapping;
5456
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005457 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02005458BufferNew(buf_T *buf)
5459{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005460 /*
5461 * We need to handle deletion of buffers underneath us.
Bram Moolenaar971db462013-05-12 18:44:48 +02005462 * If we add a "b_python*_ref" field to the buf_T structure,
5463 * then we can get at it in buf_freeall() in vim. We then
5464 * need to create only ONE Python object per buffer - if
5465 * we try to create a second, just INCREF the existing one
5466 * and return it. The (single) Python object referring to
5467 * the buffer is stored in "b_python*_ref".
5468 * Question: what to do on a buf_freeall(). We'll probably
5469 * have to either delete the Python object (DECREF it to
5470 * zero - a bad idea, as it leaves dangling refs!) or
5471 * set the buf_T * value to an invalid value (-1?), which
5472 * means we need checks in all access functions... Bah.
5473 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005474 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02005475 * b_python_ref and b_python3_ref fields respectively.
5476 */
5477
5478 BufferObject *self;
5479
5480 if (BUF_PYTHON_REF(buf) != NULL)
5481 {
5482 self = BUF_PYTHON_REF(buf);
5483 Py_INCREF(self);
5484 }
5485 else
5486 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005487 self = PyObject_NEW(BufferObject, BufferTypePtr);
Bram Moolenaar971db462013-05-12 18:44:48 +02005488 if (self == NULL)
5489 return NULL;
5490 self->buf = buf;
5491 BUF_PYTHON_REF(buf) = self;
5492 }
5493
5494 return (PyObject *)(self);
5495}
5496
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005497 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02005498BufferDestructor(BufferObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005499{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005500 if (self->buf && self->buf != INVALID_BUFFER_VALUE)
5501 BUF_PYTHON_REF(self->buf) = NULL;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005502
5503 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005504}
5505
Bram Moolenaar971db462013-05-12 18:44:48 +02005506 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02005507BufferLength(BufferObject *self)
Bram Moolenaar971db462013-05-12 18:44:48 +02005508{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005509 // HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION?
Bram Moolenaard6e39182013-05-21 18:30:34 +02005510 if (CheckBuffer(self))
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005511 return -1; // ???
Bram Moolenaar971db462013-05-12 18:44:48 +02005512
Bram Moolenaard6e39182013-05-21 18:30:34 +02005513 return (PyInt)(self->buf->b_ml.ml_line_count);
Bram Moolenaar971db462013-05-12 18:44:48 +02005514}
5515
5516 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005517BufferItem(BufferObject *self, PyInt n)
Bram Moolenaar971db462013-05-12 18:44:48 +02005518{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005519 return RBItem(self, n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02005520}
5521
5522 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005523BufferSlice(BufferObject *self, PyInt lo, PyInt hi)
Bram Moolenaar971db462013-05-12 18:44:48 +02005524{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005525 return RBSlice(self, lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02005526}
5527
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005528static char *BufferAttrs[] = {
5529 "name", "number", "vars", "options", "valid",
5530 NULL
5531};
5532
5533 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02005534BufferDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005535{
5536 return ObjectDir(self, BufferAttrs);
5537}
5538
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005539 static PyObject *
Bram Moolenaar9e822c02013-05-29 22:15:30 +02005540BufferAttrValid(BufferObject *self, char *name)
5541{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005542 PyObject *ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02005543
5544 if (strcmp(name, "valid") != 0)
5545 return NULL;
5546
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005547 ret = ((self->buf == INVALID_BUFFER_VALUE) ? Py_False : Py_True);
5548 Py_INCREF(ret);
5549 return ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02005550}
5551
5552 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005553BufferAttr(BufferObject *self, char *name)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005554{
5555 if (strcmp(name, "name") == 0)
Bram Moolenaar432b09c2013-05-29 22:26:18 +02005556 return PyString_FromString((self->buf->b_ffname == NULL
Bram Moolenaar41009372013-07-01 22:03:04 +02005557 ? "" : (char *)self->buf->b_ffname));
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005558 else if (strcmp(name, "number") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02005559 return Py_BuildValue(Py_ssize_t_fmt, self->buf->b_fnum);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005560 else if (strcmp(name, "vars") == 0)
Bram Moolenaara9922d62013-05-30 13:01:18 +02005561 return NEW_DICTIONARY(self->buf->b_vars);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005562 else if (strcmp(name, "options") == 0)
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005563 return OptionsNew(SREQ_BUF, self->buf, CheckBufferCb,
Bram Moolenaard6e39182013-05-21 18:30:34 +02005564 (PyObject *) self);
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005565 else if (strcmp(name, "__members__") == 0)
5566 return ObjectDir(NULL, BufferAttrs);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005567 else
5568 return NULL;
5569}
5570
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005571 static int
5572BufferSetattr(BufferObject *self, char *name, PyObject *valObject)
5573{
5574 if (CheckBuffer(self))
5575 return -1;
5576
5577 if (strcmp(name, "name") == 0)
5578 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005579 char_u *val;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005580 aco_save_T aco;
Bram Moolenaar37199892022-11-29 13:46:48 +00005581 int ren_ret = OK;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005582 PyObject *todecref;
5583
5584 if (!(val = StringToChars(valObject, &todecref)))
5585 return -1;
5586
5587 VimTryStart();
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005588 // Using aucmd_*: autocommands will be executed by rename_buffer
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005589 aucmd_prepbuf(&aco, self->buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005590 if (curbuf == self->buf)
5591 {
5592 ren_ret = rename_buffer(val);
5593 aucmd_restbuf(&aco);
5594 }
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005595 Py_XDECREF(todecref);
5596 if (VimTryEnd())
5597 return -1;
5598
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005599 if (ren_ret == FAIL)
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005600 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005601 PyErr_SET_VIM(N_("failed to rename buffer"));
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005602 return -1;
5603 }
5604 return 0;
5605 }
5606 else
5607 {
5608 PyErr_SetString(PyExc_AttributeError, name);
5609 return -1;
5610 }
5611}
5612
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005613 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005614BufferAppend(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005615{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005616 return RBAppend(self, args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005617}
5618
5619 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02005620BufferMark(BufferObject *self, PyObject *pmarkObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005621{
5622 pos_T *posp;
Bram Moolenaar389a1792013-06-23 13:00:44 +02005623 char_u *pmark;
5624 char_u mark;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005625 bufref_T savebuf;
Bram Moolenaar389a1792013-06-23 13:00:44 +02005626 PyObject *todecref;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005627
Bram Moolenaard6e39182013-05-21 18:30:34 +02005628 if (CheckBuffer(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005629 return NULL;
5630
Bram Moolenaar389a1792013-06-23 13:00:44 +02005631 if (!(pmark = StringToChars(pmarkObject, &todecref)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005632 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005633
Bram Moolenaar389a1792013-06-23 13:00:44 +02005634 if (pmark[0] == '\0' || pmark[1] != '\0')
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005635 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005636 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005637 N_("mark name must be a single character"));
Bram Moolenaar841fbd22013-06-23 14:37:07 +02005638 Py_XDECREF(todecref);
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005639 return NULL;
5640 }
5641
5642 mark = *pmark;
Bram Moolenaar389a1792013-06-23 13:00:44 +02005643
5644 Py_XDECREF(todecref);
5645
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005646 VimTryStart();
Bram Moolenaard6e39182013-05-21 18:30:34 +02005647 switch_buffer(&savebuf, self->buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005648 posp = getmark(mark, FALSE);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005649 restore_buffer(&savebuf);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005650 if (VimTryEnd())
5651 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005652
5653 if (posp == NULL)
5654 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005655 PyErr_SET_VIM(N_("invalid mark name"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005656 return NULL;
5657 }
5658
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005659 if (posp->lnum <= 0)
5660 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005661 // Or raise an error?
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005662 Py_INCREF(Py_None);
5663 return Py_None;
5664 }
5665
5666 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
5667}
5668
5669 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005670BufferRange(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005671{
5672 PyInt start;
5673 PyInt end;
5674
Bram Moolenaard6e39182013-05-21 18:30:34 +02005675 if (CheckBuffer(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005676 return NULL;
5677
5678 if (!PyArg_ParseTuple(args, "nn", &start, &end))
5679 return NULL;
5680
Bram Moolenaard6e39182013-05-21 18:30:34 +02005681 return RangeNew(self->buf, start, end);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005682}
5683
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005684 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005685BufferRepr(BufferObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005686{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005687 if (self->buf == INVALID_BUFFER_VALUE)
Dominique Pellec14f6672022-01-09 12:57:48 +00005688 return PyString_FromFormat("<buffer object (deleted) at %p>", (void *)self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005689 else
5690 {
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005691 char *name = (char *)self->buf->b_fname;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005692
5693 if (name == NULL)
5694 name = "";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005695
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005696 return PyString_FromFormat("<buffer %s>", name);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005697 }
5698}
5699
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005700static struct PyMethodDef BufferMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005701 // name, function, calling, documentation
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02005702 {"append", (PyCFunction)BufferAppend, METH_VARARGS, "Append data to Vim buffer" },
Bram Moolenaar389a1792013-06-23 13:00:44 +02005703 {"mark", (PyCFunction)BufferMark, METH_O, "Return (row,col) representing position of named mark" },
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02005704 {"range", (PyCFunction)BufferRange, METH_VARARGS, "Return a range object which represents the part of the given buffer between line numbers s and e" },
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005705 {"__dir__", (PyCFunction)BufferDir, METH_NOARGS, ""},
5706 { NULL, NULL, 0, NULL}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005707};
5708
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005709/*
5710 * Buffer list object - Implementation
5711 */
5712
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005713DEFINE_PY_TYPE_OBJECT(BufMapType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005714
5715typedef struct
5716{
5717 PyObject_HEAD
5718} BufMapObject;
5719
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005720static BufMapObject TheBufferMap =
5721{
5722 PyObject_HEAD_INIT_TYPE(BufMapType)
5723};
5724
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005725 static PyInt
5726BufMapLength(PyObject *self UNUSED)
5727{
5728 buf_T *b = firstbuf;
5729 PyInt n = 0;
5730
5731 while (b)
5732 {
5733 ++n;
5734 b = b->b_next;
5735 }
5736
5737 return n;
5738}
5739
5740 static PyObject *
5741BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
5742{
5743 buf_T *b;
Bram Moolenaar141be8a2013-06-23 14:16:57 +02005744 long bnr;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005745
Bram Moolenaar141be8a2013-06-23 14:16:57 +02005746 if (NumberToLong(keyObject, &bnr, NUMBER_INT|NUMBER_NATURAL))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005747 return NULL;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005748
Bram Moolenaar141be8a2013-06-23 14:16:57 +02005749 b = buflist_findnr((int) bnr);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005750
5751 if (b)
5752 return BufferNew(b);
5753 else
5754 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02005755 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005756 return NULL;
5757 }
5758}
5759
5760 static void
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005761BufMapIterDestruct(void* arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005762{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005763 PyObject *buffer = (PyObject*)arg;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005764 // Iteration was stopped before all buffers were processed
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005765 if (buffer)
5766 {
5767 Py_DECREF(buffer);
5768 }
5769}
5770
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005771 static int
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005772BufMapIterTraverse(void *iter, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005773{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005774 PyObject *buffer = (PyObject*)iter;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005775 if (buffer)
5776 Py_VISIT(buffer);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005777 return 0;
5778}
5779
5780 static int
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005781BufMapIterClear(void **iter)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005782{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005783 PyObject **buffer = (PyObject**)iter;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005784 if (*buffer)
5785 Py_CLEAR(*buffer);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005786 return 0;
5787}
5788
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005789 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005790BufMapIterNext(void **arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005791{
5792 PyObject *next;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005793 PyObject *ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005794 PyObject **buffer = (PyObject**)arg;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005795
5796 if (!*buffer)
5797 return NULL;
5798
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005799 ret = *buffer;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005800
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005801 if (CheckBuffer((BufferObject *)(ret)))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005802 {
5803 *buffer = NULL;
5804 return NULL;
5805 }
5806
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005807 if (!((BufferObject *)(ret))->buf->b_next)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005808 next = NULL;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005809 else if (!(next = BufferNew(((BufferObject *)(ret))->buf->b_next)))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005810 return NULL;
5811 *buffer = next;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005812 // Do not increment reference: we no longer hold it (decref), but whoever
5813 // on other side will hold (incref). Decref+incref = nothing.
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005814 return ret;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005815}
5816
5817 static PyObject *
Bram Moolenaar423a85a2020-08-29 12:57:16 +02005818BufMapIter(PyObject *self)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005819{
5820 PyObject *buffer;
5821
5822 buffer = BufferNew(firstbuf);
5823 return IterNew(buffer,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005824 BufMapIterDestruct, BufMapIterNext,
5825 BufMapIterTraverse, BufMapIterClear,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02005826 (PyObject *)self);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005827}
5828
5829static PyMappingMethods BufMapAsMapping = {
5830 (lenfunc) BufMapLength,
5831 (binaryfunc) BufMapItem,
5832 (objobjargproc) 0,
5833};
5834
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005835// Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005836
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005837static char *CurrentAttrs[] = {
5838 "buffer", "window", "line", "range", "tabpage",
5839 NULL
5840};
5841
5842 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02005843CurrentDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005844{
5845 return ObjectDir(self, CurrentAttrs);
5846}
5847
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005848 static PyObject *
5849CurrentGetattr(PyObject *self UNUSED, char *name)
5850{
5851 if (strcmp(name, "buffer") == 0)
5852 return (PyObject *)BufferNew(curbuf);
5853 else if (strcmp(name, "window") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02005854 return (PyObject *)WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005855 else if (strcmp(name, "tabpage") == 0)
5856 return (PyObject *)TabPageNew(curtab);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005857 else if (strcmp(name, "line") == 0)
5858 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
5859 else if (strcmp(name, "range") == 0)
5860 return RangeNew(curbuf, RangeStart, RangeEnd);
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005861 else if (strcmp(name, "__members__") == 0)
5862 return ObjectDir(NULL, CurrentAttrs);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005863 else
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005864#if PY_MAJOR_VERSION < 3
5865 return Py_FindMethod(WindowMethods, self, name);
5866#else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005867 return NULL;
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005868#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005869}
5870
5871 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005872CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *valObject)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005873{
5874 if (strcmp(name, "line") == 0)
5875 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005876 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, valObject,
5877 NULL) == FAIL)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005878 return -1;
5879
5880 return 0;
5881 }
Bram Moolenaare7614592013-05-15 15:51:08 +02005882 else if (strcmp(name, "buffer") == 0)
5883 {
5884 int count;
5885
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005886 if (valObject->ob_type != BufferTypePtr)
Bram Moolenaare7614592013-05-15 15:51:08 +02005887 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005888 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005889 N_("expected vim.Buffer object, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005890 valObject);
Bram Moolenaare7614592013-05-15 15:51:08 +02005891 return -1;
5892 }
5893
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005894 if (CheckBuffer((BufferObject *)(valObject)))
Bram Moolenaare7614592013-05-15 15:51:08 +02005895 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005896 count = ((BufferObject *)(valObject))->buf->b_fnum;
Bram Moolenaare7614592013-05-15 15:51:08 +02005897
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005898 VimTryStart();
Bram Moolenaare7614592013-05-15 15:51:08 +02005899 if (do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, count, 0) == FAIL)
5900 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005901 if (VimTryEnd())
5902 return -1;
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005903 PyErr_VIM_FORMAT(N_("failed to switch to buffer %d"), count);
Bram Moolenaare7614592013-05-15 15:51:08 +02005904 return -1;
5905 }
5906
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005907 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02005908 }
5909 else if (strcmp(name, "window") == 0)
5910 {
5911 int count;
5912
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005913 if (valObject->ob_type != WindowTypePtr)
Bram Moolenaare7614592013-05-15 15:51:08 +02005914 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005915 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005916 N_("expected vim.Window object, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005917 valObject);
Bram Moolenaare7614592013-05-15 15:51:08 +02005918 return -1;
5919 }
5920
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005921 if (CheckWindow((WindowObject *)(valObject)))
Bram Moolenaare7614592013-05-15 15:51:08 +02005922 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005923 count = get_win_number(((WindowObject *)(valObject))->win, firstwin);
Bram Moolenaare7614592013-05-15 15:51:08 +02005924
5925 if (!count)
5926 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005927 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005928 N_("failed to find window in the current tab page"));
Bram Moolenaare7614592013-05-15 15:51:08 +02005929 return -1;
5930 }
5931
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005932 VimTryStart();
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005933 win_goto(((WindowObject *)(valObject))->win);
5934 if (((WindowObject *)(valObject))->win != curwin)
Bram Moolenaare7614592013-05-15 15:51:08 +02005935 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005936 if (VimTryEnd())
5937 return -1;
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005938 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005939 N_("did not switch to the specified window"));
Bram Moolenaare7614592013-05-15 15:51:08 +02005940 return -1;
5941 }
5942
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005943 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02005944 }
5945 else if (strcmp(name, "tabpage") == 0)
5946 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005947 if (valObject->ob_type != TabPageTypePtr)
Bram Moolenaare7614592013-05-15 15:51:08 +02005948 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005949 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005950 N_("expected vim.TabPage object, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005951 valObject);
Bram Moolenaare7614592013-05-15 15:51:08 +02005952 return -1;
5953 }
5954
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005955 if (CheckTabPage((TabPageObject *)(valObject)))
Bram Moolenaare7614592013-05-15 15:51:08 +02005956 return -1;
5957
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005958 VimTryStart();
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005959 goto_tabpage_tp(((TabPageObject *)(valObject))->tab, TRUE, TRUE);
5960 if (((TabPageObject *)(valObject))->tab != curtab)
Bram Moolenaare7614592013-05-15 15:51:08 +02005961 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005962 if (VimTryEnd())
5963 return -1;
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005964 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005965 N_("did not switch to the specified tab page"));
Bram Moolenaare7614592013-05-15 15:51:08 +02005966 return -1;
5967 }
5968
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005969 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02005970 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005971 else
5972 {
5973 PyErr_SetString(PyExc_AttributeError, name);
5974 return -1;
5975 }
5976}
5977
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005978static struct PyMethodDef CurrentMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005979 // name, function, calling, documentation
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005980 {"__dir__", (PyCFunction)CurrentDir, METH_NOARGS, ""},
5981 { NULL, NULL, 0, NULL}
5982};
5983
Bram Moolenaardb913952012-06-29 12:54:53 +02005984 static void
Yee Cheng Chin2ce070c2023-09-19 20:30:22 +02005985init_range_cmd(void *arg)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02005986{
Yee Cheng Chin2ce070c2023-09-19 20:30:22 +02005987 exarg_T *eap = (exarg_T*)arg;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02005988 RangeStart = eap->line1;
5989 RangeEnd = eap->line2;
5990}
5991
5992 static void
Yee Cheng Chin2ce070c2023-09-19 20:30:22 +02005993init_range_eval(void *rettv UNUSED)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02005994{
5995 RangeStart = (PyInt) curwin->w_cursor.lnum;
5996 RangeEnd = RangeStart;
5997}
5998
5999 static void
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006000run_cmd(const char *cmd, void *arg UNUSED
6001#ifdef PY_CAN_RECURSE
6002 , PyGILState_STATE *pygilstate UNUSED
6003#endif
6004 )
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006005{
Bram Moolenaar41009372013-07-01 22:03:04 +02006006 PyObject *run_ret;
6007 run_ret = PyRun_String((char *)cmd, Py_file_input, globals, globals);
6008 if (run_ret != NULL)
6009 {
6010 Py_DECREF(run_ret);
6011 }
6012 else if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit))
6013 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006014 emsg(_(e_cant_handle_systemexit_of_python_exception_in_vim));
Bram Moolenaar41009372013-07-01 22:03:04 +02006015 PyErr_Clear();
6016 }
6017 else
6018 PyErr_PrintEx(1);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006019}
6020
6021static const char *code_hdr = "def " DOPY_FUNC "(line, linenr):\n ";
6022static int code_hdr_len = 30;
6023
6024 static void
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006025run_do(const char *cmd, void *arg UNUSED
6026#ifdef PY_CAN_RECURSE
6027 , PyGILState_STATE *pygilstate
6028#endif
6029 )
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006030{
6031 PyInt lnum;
6032 size_t len;
6033 char *code;
6034 int status;
6035 PyObject *pyfunc, *pymain;
Bram Moolenaar41009372013-07-01 22:03:04 +02006036 PyObject *run_ret;
Bram Moolenaara58883b2017-01-29 21:31:09 +01006037 buf_T *was_curbuf = curbuf;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006038
Bram Moolenaar4ac66762013-05-28 22:31:46 +02006039 if (u_save((linenr_T)RangeStart - 1, (linenr_T)RangeEnd + 1) != OK)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006040 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006041 emsg(_("cannot save undo information"));
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006042 return;
6043 }
6044
6045 len = code_hdr_len + STRLEN(cmd);
6046 code = PyMem_New(char, len + 1);
6047 memcpy(code, code_hdr, code_hdr_len);
6048 STRCPY(code + code_hdr_len, cmd);
Bram Moolenaar41009372013-07-01 22:03:04 +02006049 run_ret = PyRun_String(code, Py_file_input, globals, globals);
6050 status = -1;
6051 if (run_ret != NULL)
6052 {
6053 status = 0;
6054 Py_DECREF(run_ret);
6055 }
6056 else if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit))
6057 {
6058 PyMem_Free(code);
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006059 emsg(_(e_cant_handle_systemexit_of_python_exception_in_vim));
Bram Moolenaar41009372013-07-01 22:03:04 +02006060 PyErr_Clear();
6061 return;
6062 }
6063 else
6064 PyErr_PrintEx(1);
6065
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006066 PyMem_Free(code);
6067
6068 if (status)
6069 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006070 emsg(_("failed to run the code"));
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006071 return;
6072 }
6073
6074 status = 0;
6075 pymain = PyImport_AddModule("__main__");
6076 pyfunc = PyObject_GetAttrString(pymain, DOPY_FUNC);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006077#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006078 PyGILState_Release(*pygilstate);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006079#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006080
6081 for (lnum = RangeStart; lnum <= RangeEnd; ++lnum)
6082 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006083 PyObject *line;
6084 PyObject *linenr;
6085 PyObject *ret;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006086
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006087#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006088 *pygilstate = PyGILState_Ensure();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006089#endif
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006090 // Check the line number, the command my have deleted lines.
Bram Moolenaara58883b2017-01-29 21:31:09 +01006091 if (lnum > curbuf->b_ml.ml_line_count
6092 || !(line = GetBufferLine(curbuf, lnum)))
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006093 goto err;
6094 if (!(linenr = PyInt_FromLong((long) lnum)))
6095 {
6096 Py_DECREF(line);
6097 goto err;
6098 }
6099 ret = PyObject_CallFunctionObjArgs(pyfunc, line, linenr, NULL);
6100 Py_DECREF(line);
6101 Py_DECREF(linenr);
6102 if (!ret)
6103 goto err;
6104
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006105 // Check that the command didn't switch to another buffer.
Bram Moolenaara58883b2017-01-29 21:31:09 +01006106 if (curbuf != was_curbuf)
6107 {
6108 Py_XDECREF(ret);
6109 goto err;
6110 }
6111
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006112 if (ret != Py_None)
6113 if (SetBufferLine(curbuf, lnum, ret, NULL) == FAIL)
Bram Moolenaara58883b2017-01-29 21:31:09 +01006114 {
6115 Py_XDECREF(ret);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006116 goto err;
Bram Moolenaara58883b2017-01-29 21:31:09 +01006117 }
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006118
6119 Py_XDECREF(ret);
6120 PythonIO_Flush();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006121#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006122 PyGILState_Release(*pygilstate);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006123#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006124 }
6125 goto out;
6126err:
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006127#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006128 *pygilstate = PyGILState_Ensure();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006129#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006130 PyErr_PrintEx(0);
6131 PythonIO_Flush();
6132 status = 1;
6133out:
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006134#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006135 if (!status)
6136 *pygilstate = PyGILState_Ensure();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006137#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006138 Py_DECREF(pyfunc);
6139 PyObject_SetAttrString(pymain, DOPY_FUNC, NULL);
6140 if (status)
6141 return;
6142 check_cursor();
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006143 update_curbuf(UPD_NOT_VALID);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006144}
6145
6146 static void
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02006147run_eval(const char *cmd, void *arg
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006148#ifdef PY_CAN_RECURSE
6149 , PyGILState_STATE *pygilstate UNUSED
6150#endif
6151 )
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006152{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006153 PyObject *run_ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02006154 typval_T *rettv = (typval_T*)arg;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006155
Bram Moolenaar41009372013-07-01 22:03:04 +02006156 run_ret = PyRun_String((char *)cmd, Py_eval_input, globals, globals);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006157 if (run_ret == NULL)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006158 {
Bram Moolenaar91aeaf42013-07-06 13:02:30 +02006159 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit))
Bram Moolenaar41009372013-07-01 22:03:04 +02006160 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006161 emsg(_(e_cant_handle_systemexit_of_python_exception_in_vim));
Bram Moolenaar41009372013-07-01 22:03:04 +02006162 PyErr_Clear();
6163 }
Bram Moolenaar91aeaf42013-07-06 13:02:30 +02006164 else
6165 {
6166 if (PyErr_Occurred() && !msg_silent)
6167 PyErr_PrintEx(0);
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006168 emsg(_(e_eval_did_not_return_valid_python_object));
Bram Moolenaar91aeaf42013-07-06 13:02:30 +02006169 }
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006170 }
6171 else
6172 {
Bram Moolenaarde323092017-11-09 19:56:08 +01006173 if (ConvertFromPyObject(run_ret, rettv) == -1)
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006174 emsg(_(e_failed_to_convert_returned_python_object_to_vim_value));
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006175 Py_DECREF(run_ret);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006176 }
6177 PyErr_Clear();
6178}
6179
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006180 static int
Bram Moolenaardb913952012-06-29 12:54:53 +02006181set_ref_in_py(const int copyID)
6182{
6183 pylinkedlist_T *cur;
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006184 list_T *ll;
6185 int i;
6186 int abort = FALSE;
Bram Moolenaar8110a092016-04-14 15:56:09 +02006187 FunctionObject *func;
Bram Moolenaardb913952012-06-29 12:54:53 +02006188
6189 if (lastdict != NULL)
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006190 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02006191 for (cur = lastdict ; !abort && cur != NULL ; cur = cur->pll_prev)
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006192 abort = set_ref_in_dict(((DictionaryObject *)(cur->pll_obj))->dict,
6193 copyID);
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006194 }
Bram Moolenaardb913952012-06-29 12:54:53 +02006195
6196 if (lastlist != NULL)
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006197 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02006198 for (cur = lastlist ; !abort && cur != NULL ; cur = cur->pll_prev)
Bram Moolenaardb913952012-06-29 12:54:53 +02006199 {
6200 ll = ((ListObject *) (cur->pll_obj))->list;
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006201 abort = set_ref_in_list(ll, copyID);
Bram Moolenaardb913952012-06-29 12:54:53 +02006202 }
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006203 }
6204
Bram Moolenaar8110a092016-04-14 15:56:09 +02006205 if (lastfunc != NULL)
6206 {
6207 for (cur = lastfunc ; !abort && cur != NULL ; cur = cur->pll_prev)
6208 {
6209 func = (FunctionObject *) cur->pll_obj;
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006210 abort = set_ref_in_dict(func->self, copyID);
Bram Moolenaar8110a092016-04-14 15:56:09 +02006211 if (func->argc)
6212 for (i = 0; !abort && i < func->argc; ++i)
6213 abort = abort
6214 || set_ref_in_item(&func->argv[i], copyID, NULL, NULL);
6215 }
6216 }
6217
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006218 return abort;
Bram Moolenaardb913952012-06-29 12:54:53 +02006219}
6220
6221 static int
6222set_string_copy(char_u *str, typval_T *tv)
6223{
6224 tv->vval.v_string = vim_strsave(str);
6225 if (tv->vval.v_string == NULL)
6226 {
6227 PyErr_NoMemory();
6228 return -1;
6229 }
6230 return 0;
6231}
6232
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006233 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006234pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006235{
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006236 dict_T *dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006237 char_u *key;
6238 dictitem_T *di;
6239 PyObject *keyObject;
6240 PyObject *valObject;
6241 Py_ssize_t iter = 0;
6242
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006243 if (!(dict = py_dict_alloc()))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006244 return -1;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006245
6246 tv->v_type = VAR_DICT;
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006247 tv->vval.v_dict = dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006248
6249 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
6250 {
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006251 PyObject *todecref = NULL;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006252
Bram Moolenaara03e6312013-05-29 22:49:26 +02006253 if (keyObject == NULL || valObject == NULL)
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006254 {
6255 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006256 return -1;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006257 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006258
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006259 if (!(key = StringToChars(keyObject, &todecref)))
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006260 {
6261 dict_unref(dict);
6262 return -1;
6263 }
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02006264
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006265 if (*key == NUL)
6266 {
6267 dict_unref(dict);
6268 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006269 RAISE_NO_EMPTY_KEYS;
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006270 return -1;
6271 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006272
6273 di = dictitem_alloc(key);
6274
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006275 Py_XDECREF(todecref);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006276
6277 if (di == NULL)
6278 {
6279 PyErr_NoMemory();
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006280 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006281 return -1;
6282 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006283
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006284 if (_ConvertFromPyObject(valObject, &di->di_tv, lookup_dict) == -1)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006285 {
6286 vim_free(di);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006287 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006288 return -1;
6289 }
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006290
6291 if (dict_add(dict, di) == FAIL)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006292 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02006293 RAISE_KEY_ADD_FAIL(di->di_key);
Bram Moolenaara03e6312013-05-29 22:49:26 +02006294 clear_tv(&di->di_tv);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006295 vim_free(di);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006296 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006297 return -1;
6298 }
6299 }
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006300
6301 --dict->dv_refcount;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006302 return 0;
6303}
6304
6305 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006306pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006307{
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006308 dict_T *dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006309 char_u *key;
6310 dictitem_T *di;
6311 PyObject *list;
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006312 PyObject *iterator;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006313 PyObject *keyObject;
6314 PyObject *valObject;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006315
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006316 if (!(dict = py_dict_alloc()))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006317 return -1;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006318
6319 tv->v_type = VAR_DICT;
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006320 tv->vval.v_dict = dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006321
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006322 if (!(list = PyMapping_Keys(obj)))
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006323 {
6324 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006325 return -1;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006326 }
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006327
6328 if (!(iterator = PyObject_GetIter(list)))
6329 {
6330 dict_unref(dict);
6331 Py_DECREF(list);
6332 return -1;
6333 }
6334 Py_DECREF(list);
6335
6336 while ((keyObject = PyIter_Next(iterator)))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006337 {
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006338 PyObject *todecref;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006339
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006340 if (!(key = StringToChars(keyObject, &todecref)))
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006341 {
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006342 Py_DECREF(keyObject);
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006343 Py_DECREF(iterator);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006344 dict_unref(dict);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006345 return -1;
6346 }
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02006347
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006348 if (*key == NUL)
6349 {
6350 Py_DECREF(keyObject);
6351 Py_DECREF(iterator);
6352 Py_XDECREF(todecref);
6353 dict_unref(dict);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006354 RAISE_NO_EMPTY_KEYS;
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006355 return -1;
6356 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006357
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006358 if (!(valObject = PyObject_GetItem(obj, keyObject)))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006359 {
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006360 Py_DECREF(keyObject);
6361 Py_DECREF(iterator);
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006362 Py_XDECREF(todecref);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006363 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006364 return -1;
6365 }
6366
6367 di = dictitem_alloc(key);
6368
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006369 Py_DECREF(keyObject);
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006370 Py_XDECREF(todecref);
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006371
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006372 if (di == NULL)
6373 {
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006374 Py_DECREF(iterator);
6375 Py_DECREF(valObject);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006376 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006377 PyErr_NoMemory();
6378 return -1;
6379 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006380
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006381 if (_ConvertFromPyObject(valObject, &di->di_tv, lookup_dict) == -1)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006382 {
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006383 Py_DECREF(iterator);
6384 Py_DECREF(valObject);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006385 vim_free(di);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006386 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006387 return -1;
6388 }
Bram Moolenaara03e6312013-05-29 22:49:26 +02006389
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006390 Py_DECREF(valObject);
6391
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006392 if (dict_add(dict, di) == FAIL)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006393 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02006394 RAISE_KEY_ADD_FAIL(di->di_key);
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006395 Py_DECREF(iterator);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006396 dictitem_free(di);
6397 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006398 return -1;
6399 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006400 }
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006401 Py_DECREF(iterator);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006402 --dict->dv_refcount;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006403 return 0;
6404}
6405
6406 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006407pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006408{
6409 list_T *l;
6410
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006411 if (!(l = py_list_alloc()))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006412 return -1;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006413
6414 tv->v_type = VAR_LIST;
6415 tv->vval.v_list = l;
6416
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006417 if (list_py_concat(l, obj, lookup_dict) == -1)
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006418 {
6419 list_unref(l);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006420 return -1;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006421 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006422
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006423 --l->lv_refcount;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006424 return 0;
6425}
6426
Bram Moolenaardb913952012-06-29 12:54:53 +02006427typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
6428
6429 static int
6430convert_dl(PyObject *obj, typval_T *tv,
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006431 pytotvfunc py_to_tv, PyObject *lookup_dict)
Bram Moolenaardb913952012-06-29 12:54:53 +02006432{
6433 PyObject *capsule;
6434 char hexBuf[sizeof(void *) * 2 + 3];
6435
Bram Moolenaar792f0e32018-02-27 17:27:13 +01006436 sprintf(hexBuf, "%p", (void *)obj);
Bram Moolenaardb913952012-06-29 12:54:53 +02006437
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006438#ifdef PY_USE_CAPSULE
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006439 capsule = PyDict_GetItemString(lookup_dict, hexBuf);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006440#else
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006441 capsule = (PyObject *)PyDict_GetItemString(lookup_dict, hexBuf);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006442#endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02006443 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02006444 {
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006445#ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02006446 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006447#else
Bram Moolenaar221d6872012-06-30 13:34:34 +02006448 capsule = PyCObject_FromVoidPtr(tv, NULL);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006449#endif
Bram Moolenaara03e6312013-05-29 22:49:26 +02006450 if (PyDict_SetItemString(lookup_dict, hexBuf, capsule))
6451 {
6452 Py_DECREF(capsule);
6453 tv->v_type = VAR_UNKNOWN;
6454 return -1;
6455 }
Bram Moolenaar841fbd22013-06-23 14:37:07 +02006456
6457 Py_DECREF(capsule);
6458
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006459 if (py_to_tv(obj, tv, lookup_dict) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +02006460 {
6461 tv->v_type = VAR_UNKNOWN;
6462 return -1;
6463 }
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006464 // As we are not using copy_tv which increments reference count we must
6465 // do it ourself.
Bram Moolenaar81e7a9c2016-02-06 19:57:20 +01006466 if (tv->v_type == VAR_DICT)
6467 ++tv->vval.v_dict->dv_refcount;
6468 else if (tv->v_type == VAR_LIST)
6469 ++tv->vval.v_list->lv_refcount;
Bram Moolenaardb913952012-06-29 12:54:53 +02006470 }
6471 else
6472 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02006473 typval_T *v;
6474
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006475#ifdef PY_USE_CAPSULE
Bram Moolenaar2afa3232012-06-29 16:28:28 +02006476 v = PyCapsule_GetPointer(capsule, NULL);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006477#else
Bram Moolenaar221d6872012-06-30 13:34:34 +02006478 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006479#endif
Bram Moolenaardb913952012-06-29 12:54:53 +02006480 copy_tv(v, tv);
6481 }
6482 return 0;
6483}
6484
6485 static int
Bram Moolenaara9922d62013-05-30 13:01:18 +02006486ConvertFromPyMapping(PyObject *obj, typval_T *tv)
6487{
6488 PyObject *lookup_dict;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006489 int ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006490
6491 if (!(lookup_dict = PyDict_New()))
6492 return -1;
6493
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006494 if (PyType_IsSubtype(obj->ob_type, DictionaryTypePtr))
Bram Moolenaara9922d62013-05-30 13:01:18 +02006495 {
6496 tv->v_type = VAR_DICT;
6497 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
6498 ++tv->vval.v_dict->dv_refcount;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006499 ret = 0;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006500 }
6501 else if (PyDict_Check(obj))
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006502 ret = convert_dl(obj, tv, pydict_to_tv, lookup_dict);
Bram Moolenaara9922d62013-05-30 13:01:18 +02006503 else if (PyMapping_Check(obj))
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006504 ret = convert_dl(obj, tv, pymap_to_tv, lookup_dict);
Bram Moolenaara9922d62013-05-30 13:01:18 +02006505 else
6506 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006507 PyErr_FORMAT_TYPE(
Bram Moolenaar86181df2020-05-11 23:14:04 +02006508 N_("unable to convert %s to a Vim dictionary"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006509 obj);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006510 ret = -1;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006511 }
6512 Py_DECREF(lookup_dict);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006513 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006514}
6515
6516 static int
Bram Moolenaar8110a092016-04-14 15:56:09 +02006517ConvertFromPySequence(PyObject *obj, typval_T *tv)
6518{
6519 PyObject *lookup_dict;
Bram Moolenaar66210042016-04-15 20:40:41 +02006520 int ret;
Bram Moolenaar8110a092016-04-14 15:56:09 +02006521
6522 if (!(lookup_dict = PyDict_New()))
6523 return -1;
6524
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006525 if (PyType_IsSubtype(obj->ob_type, ListTypePtr))
Bram Moolenaar8110a092016-04-14 15:56:09 +02006526 {
6527 tv->v_type = VAR_LIST;
6528 tv->vval.v_list = (((ListObject *)(obj))->list);
6529 ++tv->vval.v_list->lv_refcount;
Bram Moolenaar66210042016-04-15 20:40:41 +02006530 ret = 0;
Bram Moolenaar8110a092016-04-14 15:56:09 +02006531 }
6532 else if (PyIter_Check(obj) || PySequence_Check(obj))
Bram Moolenaar66210042016-04-15 20:40:41 +02006533 ret = convert_dl(obj, tv, pyseq_to_tv, lookup_dict);
Bram Moolenaar8110a092016-04-14 15:56:09 +02006534 else
6535 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006536 PyErr_FORMAT_TYPE(
Bram Moolenaar86181df2020-05-11 23:14:04 +02006537 N_("unable to convert %s to a Vim list"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006538 obj);
Bram Moolenaar8110a092016-04-14 15:56:09 +02006539 ret = -1;
6540 }
6541 Py_DECREF(lookup_dict);
6542 return ret;
6543}
6544
6545 static int
Bram Moolenaardb913952012-06-29 12:54:53 +02006546ConvertFromPyObject(PyObject *obj, typval_T *tv)
6547{
6548 PyObject *lookup_dict;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006549 int ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02006550
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006551 if (!(lookup_dict = PyDict_New()))
6552 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006553 ret = _ConvertFromPyObject(obj, tv, lookup_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006554 Py_DECREF(lookup_dict);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006555 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02006556}
6557
6558 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006559_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaardb913952012-06-29 12:54:53 +02006560{
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006561 if (PyType_IsSubtype(obj->ob_type, DictionaryTypePtr))
Bram Moolenaardb913952012-06-29 12:54:53 +02006562 {
6563 tv->v_type = VAR_DICT;
6564 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
6565 ++tv->vval.v_dict->dv_refcount;
6566 }
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006567 else if (PyType_IsSubtype(obj->ob_type, ListTypePtr))
Bram Moolenaardb913952012-06-29 12:54:53 +02006568 {
6569 tv->v_type = VAR_LIST;
6570 tv->vval.v_list = (((ListObject *)(obj))->list);
6571 ++tv->vval.v_list->lv_refcount;
6572 }
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006573 else if (PyType_IsSubtype(obj->ob_type, FunctionTypePtr))
Bram Moolenaardb913952012-06-29 12:54:53 +02006574 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02006575 FunctionObject *func = (FunctionObject *) obj;
6576 if (func->self != NULL || func->argv != NULL)
6577 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006578 partial_T *pt = ALLOC_CLEAR_ONE(partial_T);
6579
Bram Moolenaar8110a092016-04-14 15:56:09 +02006580 set_partial(func, pt, TRUE);
6581 tv->vval.v_partial = pt;
6582 tv->v_type = VAR_PARTIAL;
6583 }
6584 else
6585 {
6586 if (set_string_copy(func->name, tv) == -1)
6587 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02006588
Bram Moolenaar8110a092016-04-14 15:56:09 +02006589 tv->v_type = VAR_FUNC;
6590 }
6591 func_ref(func->name);
Bram Moolenaardb913952012-06-29 12:54:53 +02006592 }
Bram Moolenaardb913952012-06-29 12:54:53 +02006593 else if (PyBytes_Check(obj))
6594 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006595 char_u *str;
Bram Moolenaardb913952012-06-29 12:54:53 +02006596
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006597 if (PyBytes_AsStringAndSize(obj, (char **) &str, NULL) == -1)
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02006598 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006599 if (str == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02006600 return -1;
6601
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006602 if (set_string_copy(str, tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +02006603 return -1;
6604
6605 tv->v_type = VAR_STRING;
6606 }
6607 else if (PyUnicode_Check(obj))
6608 {
6609 PyObject *bytes;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006610 char_u *str;
Bram Moolenaardb913952012-06-29 12:54:53 +02006611
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01006612 bytes = PyUnicode_AsEncodedString(obj, ENC_OPT, ERRORS_ENCODE_ARG);
Bram Moolenaardb913952012-06-29 12:54:53 +02006613 if (bytes == NULL)
6614 return -1;
6615
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01006616 if (PyBytes_AsStringAndSize(bytes, (char **) &str, NULL) == -1)
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02006617 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006618 if (str == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02006619 return -1;
6620
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006621 if (set_string_copy(str, tv))
Bram Moolenaardb913952012-06-29 12:54:53 +02006622 {
6623 Py_XDECREF(bytes);
6624 return -1;
6625 }
6626 Py_XDECREF(bytes);
6627
6628 tv->v_type = VAR_STRING;
6629 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02006630#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02006631 else if (PyInt_Check(obj))
6632 {
6633 tv->v_type = VAR_NUMBER;
6634 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +02006635 if (PyErr_Occurred())
6636 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02006637 }
6638#endif
6639 else if (PyLong_Check(obj))
6640 {
6641 tv->v_type = VAR_NUMBER;
6642 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +02006643 if (PyErr_Occurred())
6644 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02006645 }
6646 else if (PyDict_Check(obj))
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006647 return convert_dl(obj, tv, pydict_to_tv, lookup_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006648 else if (PyFloat_Check(obj))
6649 {
6650 tv->v_type = VAR_FLOAT;
6651 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
6652 }
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006653 else if (PyObject_HasAttrString(obj, "keys"))
6654 return convert_dl(obj, tv, pymap_to_tv, lookup_dict);
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006655 // PyObject_GetIter can create built-in iterator for any sequence object
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006656 else if (PyIter_Check(obj) || PySequence_Check(obj))
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006657 return convert_dl(obj, tv, pyseq_to_tv, lookup_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006658 else if (PyMapping_Check(obj))
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006659 return convert_dl(obj, tv, pymap_to_tv, lookup_dict);
Bram Moolenaar141be8a2013-06-23 14:16:57 +02006660 else if (PyNumber_Check(obj))
6661 {
6662 PyObject *num;
6663
6664 if (!(num = PyNumber_Long(obj)))
6665 return -1;
6666
6667 tv->v_type = VAR_NUMBER;
6668 tv->vval.v_number = (varnumber_T) PyLong_AsLong(num);
6669
6670 Py_DECREF(num);
6671 }
Bram Moolenaarde323092017-11-09 19:56:08 +01006672 else if (obj == Py_None)
6673 {
6674 tv->v_type = VAR_SPECIAL;
6675 tv->vval.v_number = VVAL_NONE;
6676 }
Bram Moolenaardb913952012-06-29 12:54:53 +02006677 else
6678 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006679 PyErr_FORMAT_TYPE(
Bram Moolenaar86181df2020-05-11 23:14:04 +02006680 N_("unable to convert %s to a Vim structure"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006681 obj);
Bram Moolenaardb913952012-06-29 12:54:53 +02006682 return -1;
6683 }
6684 return 0;
6685}
6686
6687 static PyObject *
6688ConvertToPyObject(typval_T *tv)
6689{
Bram Moolenaar8110a092016-04-14 15:56:09 +02006690 typval_T *argv;
6691 int i;
Bram Moolenaardb913952012-06-29 12:54:53 +02006692 if (tv == NULL)
6693 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02006694 PyErr_SET_VIM(N_("internal error: NULL reference passed"));
Bram Moolenaardb913952012-06-29 12:54:53 +02006695 return NULL;
6696 }
6697 switch (tv->v_type)
6698 {
6699 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02006700 return PyBytes_FromString(tv->vval.v_string == NULL
6701 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02006702 case VAR_NUMBER:
6703 return PyLong_FromLong((long) tv->vval.v_number);
Bram Moolenaardb913952012-06-29 12:54:53 +02006704 case VAR_FLOAT:
6705 return PyFloat_FromDouble((double) tv->vval.v_float);
Bram Moolenaardb913952012-06-29 12:54:53 +02006706 case VAR_LIST:
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006707 return NEW_LIST(tv->vval.v_list);
Bram Moolenaardb913952012-06-29 12:54:53 +02006708 case VAR_DICT:
Bram Moolenaara9922d62013-05-30 13:01:18 +02006709 return NEW_DICTIONARY(tv->vval.v_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006710 case VAR_FUNC:
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02006711 return NEW_FUNCTION(tv->vval.v_string == NULL
Bram Moolenaar8110a092016-04-14 15:56:09 +02006712 ? (char_u *)"" : tv->vval.v_string,
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02006713 0, NULL, NULL, TRUE);
Bram Moolenaar4c908612016-03-24 21:58:12 +01006714 case VAR_PARTIAL:
Bram Moolenaar8110a092016-04-14 15:56:09 +02006715 if (tv->vval.v_partial->pt_argc)
6716 {
6717 argv = PyMem_New(typval_T, (size_t)tv->vval.v_partial->pt_argc);
6718 for (i = 0; i < tv->vval.v_partial->pt_argc; i++)
6719 copy_tv(&tv->vval.v_partial->pt_argv[i], &argv[i]);
6720 }
6721 else
6722 argv = NULL;
6723 if (tv->vval.v_partial->pt_dict != NULL)
6724 tv->vval.v_partial->pt_dict->dv_refcount++;
Bram Moolenaar4c908612016-03-24 21:58:12 +01006725 return NEW_FUNCTION(tv->vval.v_partial == NULL
Bram Moolenaar437bafe2016-08-01 15:40:54 +02006726 ? (char_u *)"" : partial_name(tv->vval.v_partial),
Bram Moolenaar8110a092016-04-14 15:56:09 +02006727 tv->vval.v_partial->pt_argc, argv,
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02006728 tv->vval.v_partial->pt_dict,
6729 tv->vval.v_partial->pt_auto);
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01006730 case VAR_BLOB:
6731 return PyBytes_FromStringAndSize(
6732 (char*) tv->vval.v_blob->bv_ga.ga_data,
6733 (Py_ssize_t) tv->vval.v_blob->bv_ga.ga_len);
Bram Moolenaardb913952012-06-29 12:54:53 +02006734 case VAR_UNKNOWN:
Bram Moolenaar4c683752020-04-05 21:38:23 +02006735 case VAR_ANY:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01006736 case VAR_VOID:
Bram Moolenaar4c908612016-03-24 21:58:12 +01006737 case VAR_CHANNEL:
6738 case VAR_JOB:
Bram Moolenaarf18332f2021-05-07 17:55:55 +02006739 case VAR_INSTR:
Bram Moolenaar00b28d62022-12-08 15:32:33 +00006740 case VAR_CLASS:
6741 case VAR_OBJECT:
Bram Moolenaardb913952012-06-29 12:54:53 +02006742 Py_INCREF(Py_None);
6743 return Py_None;
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01006744 case VAR_BOOL:
Bram Moolenaar4c908612016-03-24 21:58:12 +01006745 case VAR_SPECIAL:
6746 switch (tv->vval.v_number)
6747 {
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02006748 case VVAL_FALSE: return ALWAYS_FALSE;
6749 case VVAL_TRUE: return ALWAYS_TRUE;
Bram Moolenaar4c908612016-03-24 21:58:12 +01006750 case VVAL_NONE:
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02006751 case VVAL_NULL: return ALWAYS_NONE;
Bram Moolenaar4c908612016-03-24 21:58:12 +01006752 }
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02006753 PyErr_SET_VIM(N_("internal error: invalid value type"));
Bram Moolenaardb913952012-06-29 12:54:53 +02006754 return NULL;
6755 }
Bram Moolenaar4c908612016-03-24 21:58:12 +01006756 return NULL;
Bram Moolenaardb913952012-06-29 12:54:53 +02006757}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006758
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006759DEFINE_PY_TYPE_OBJECT(CurrentType);
6760
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006761typedef struct
6762{
6763 PyObject_HEAD
6764} CurrentObject;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006765
6766static CurrentObject TheCurrent =
6767{
6768 PyObject_HEAD_INIT_TYPE(CurrentType)
6769};
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006770
6771 static void
6772init_structs(void)
6773{
Bram Moolenaara80faa82020-04-12 19:37:17 +02006774 CLEAR_FIELD(OutputType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006775 OutputType.tp_name = "vim.message";
6776 OutputType.tp_basicsize = sizeof(OutputObject);
6777 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
6778 OutputType.tp_doc = "vim message object";
6779 OutputType.tp_methods = OutputMethods;
6780#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006781 OutputType.tp_getattro = (getattrofunc)OutputGetattro;
6782 OutputType.tp_setattro = (setattrofunc)OutputSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006783 OutputType.tp_alloc = call_PyType_GenericAlloc;
6784 OutputType.tp_new = call_PyType_GenericNew;
6785 OutputType.tp_free = call_PyObject_Free;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006786# ifndef USE_LIMITED_API
6787 // The std printer type is only exposed in full API. It is not essential
6788 // anyway and so in limited API we don't set it.
Bram Moolenaard4a8c982018-05-15 22:31:18 +02006789 OutputType.tp_base = &PyStdPrinter_Type;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006790# endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006791#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006792 OutputType.tp_getattr = (getattrfunc)OutputGetattr;
6793 OutputType.tp_setattr = (setattrfunc)OutputSetattr;
Bram Moolenaard4a8c982018-05-15 22:31:18 +02006794 // Disabled, because this causes a crash in test86
6795 // OutputType.tp_base = &PyFile_Type;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006796#endif
6797
Bram Moolenaara80faa82020-04-12 19:37:17 +02006798 CLEAR_FIELD(IterType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006799 IterType.tp_name = "vim.iter";
6800 IterType.tp_basicsize = sizeof(IterObject);
Bram Moolenaar07b88642013-05-29 22:58:32 +02006801 IterType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006802 IterType.tp_doc = "generic iterator object";
Bram Moolenaard6e39182013-05-21 18:30:34 +02006803 IterType.tp_iter = (getiterfunc)IterIter;
6804 IterType.tp_iternext = (iternextfunc)IterNext;
6805 IterType.tp_dealloc = (destructor)IterDestructor;
6806 IterType.tp_traverse = (traverseproc)IterTraverse;
6807 IterType.tp_clear = (inquiry)IterClear;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006808
Bram Moolenaara80faa82020-04-12 19:37:17 +02006809 CLEAR_FIELD(BufferType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006810 BufferType.tp_name = "vim.buffer";
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006811 BufferType.tp_basicsize = sizeof(BufferObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02006812 BufferType.tp_dealloc = (destructor)BufferDestructor;
6813 BufferType.tp_repr = (reprfunc)BufferRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006814 BufferType.tp_as_sequence = &BufferAsSeq;
6815 BufferType.tp_as_mapping = &BufferAsMapping;
6816 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
6817 BufferType.tp_doc = "vim buffer object";
6818 BufferType.tp_methods = BufferMethods;
6819#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006820 BufferType.tp_getattro = (getattrofunc)BufferGetattro;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02006821 BufferType.tp_setattro = (setattrofunc)BufferSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006822 BufferType.tp_alloc = call_PyType_GenericAlloc;
6823 BufferType.tp_new = call_PyType_GenericNew;
6824 BufferType.tp_free = call_PyObject_Free;
6825#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006826 BufferType.tp_getattr = (getattrfunc)BufferGetattr;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02006827 BufferType.tp_setattr = (setattrfunc)BufferSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006828#endif
6829
Bram Moolenaara80faa82020-04-12 19:37:17 +02006830 CLEAR_FIELD(WindowType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006831 WindowType.tp_name = "vim.window";
6832 WindowType.tp_basicsize = sizeof(WindowObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02006833 WindowType.tp_dealloc = (destructor)WindowDestructor;
6834 WindowType.tp_repr = (reprfunc)WindowRepr;
Bram Moolenaar07b88642013-05-29 22:58:32 +02006835 WindowType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006836 WindowType.tp_doc = "vim Window object";
6837 WindowType.tp_methods = WindowMethods;
Bram Moolenaard6e39182013-05-21 18:30:34 +02006838 WindowType.tp_traverse = (traverseproc)WindowTraverse;
6839 WindowType.tp_clear = (inquiry)WindowClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006840#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006841 WindowType.tp_getattro = (getattrofunc)WindowGetattro;
6842 WindowType.tp_setattro = (setattrofunc)WindowSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006843 WindowType.tp_alloc = call_PyType_GenericAlloc;
6844 WindowType.tp_new = call_PyType_GenericNew;
6845 WindowType.tp_free = call_PyObject_Free;
6846#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006847 WindowType.tp_getattr = (getattrfunc)WindowGetattr;
6848 WindowType.tp_setattr = (setattrfunc)WindowSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006849#endif
6850
Bram Moolenaara80faa82020-04-12 19:37:17 +02006851 CLEAR_FIELD(TabPageType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006852 TabPageType.tp_name = "vim.tabpage";
6853 TabPageType.tp_basicsize = sizeof(TabPageObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02006854 TabPageType.tp_dealloc = (destructor)TabPageDestructor;
6855 TabPageType.tp_repr = (reprfunc)TabPageRepr;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006856 TabPageType.tp_flags = Py_TPFLAGS_DEFAULT;
6857 TabPageType.tp_doc = "vim tab page object";
6858 TabPageType.tp_methods = TabPageMethods;
6859#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006860 TabPageType.tp_getattro = (getattrofunc)TabPageGetattro;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006861 TabPageType.tp_alloc = call_PyType_GenericAlloc;
6862 TabPageType.tp_new = call_PyType_GenericNew;
6863 TabPageType.tp_free = call_PyObject_Free;
6864#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006865 TabPageType.tp_getattr = (getattrfunc)TabPageGetattr;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006866#endif
6867
Bram Moolenaara80faa82020-04-12 19:37:17 +02006868 CLEAR_FIELD(BufMapType);
Bram Moolenaardfa38d42013-05-15 13:38:47 +02006869 BufMapType.tp_name = "vim.bufferlist";
6870 BufMapType.tp_basicsize = sizeof(BufMapObject);
6871 BufMapType.tp_as_mapping = &BufMapAsMapping;
6872 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006873 BufMapType.tp_iter = BufMapIter;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006874 BufMapType.tp_doc = "vim buffer list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006875
Bram Moolenaara80faa82020-04-12 19:37:17 +02006876 CLEAR_FIELD(WinListType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006877 WinListType.tp_name = "vim.windowlist";
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006878 WinListType.tp_basicsize = sizeof(WinListObject);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006879 WinListType.tp_as_sequence = &WinListAsSeq;
6880 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
6881 WinListType.tp_doc = "vim window list";
Bram Moolenaard6e39182013-05-21 18:30:34 +02006882 WinListType.tp_dealloc = (destructor)WinListDestructor;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006883
Bram Moolenaara80faa82020-04-12 19:37:17 +02006884 CLEAR_FIELD(TabListType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006885 TabListType.tp_name = "vim.tabpagelist";
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006886 TabListType.tp_basicsize = sizeof(TabListObject);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006887 TabListType.tp_as_sequence = &TabListAsSeq;
6888 TabListType.tp_flags = Py_TPFLAGS_DEFAULT;
6889 TabListType.tp_doc = "vim tab page list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006890
Bram Moolenaara80faa82020-04-12 19:37:17 +02006891 CLEAR_FIELD(RangeType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006892 RangeType.tp_name = "vim.range";
6893 RangeType.tp_basicsize = sizeof(RangeObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02006894 RangeType.tp_dealloc = (destructor)RangeDestructor;
6895 RangeType.tp_repr = (reprfunc)RangeRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006896 RangeType.tp_as_sequence = &RangeAsSeq;
6897 RangeType.tp_as_mapping = &RangeAsMapping;
Bram Moolenaar07b88642013-05-29 22:58:32 +02006898 RangeType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006899 RangeType.tp_doc = "vim Range object";
6900 RangeType.tp_methods = RangeMethods;
Bram Moolenaar774267b2013-05-21 20:51:59 +02006901 RangeType.tp_traverse = (traverseproc)RangeTraverse;
6902 RangeType.tp_clear = (inquiry)RangeClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006903#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006904 RangeType.tp_getattro = (getattrofunc)RangeGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006905 RangeType.tp_alloc = call_PyType_GenericAlloc;
6906 RangeType.tp_new = call_PyType_GenericNew;
6907 RangeType.tp_free = call_PyObject_Free;
6908#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006909 RangeType.tp_getattr = (getattrfunc)RangeGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006910#endif
6911
Bram Moolenaara80faa82020-04-12 19:37:17 +02006912 CLEAR_FIELD(CurrentType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006913 CurrentType.tp_name = "vim.currentdata";
6914 CurrentType.tp_basicsize = sizeof(CurrentObject);
6915 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
6916 CurrentType.tp_doc = "vim current object";
Bram Moolenaardd8aca62013-05-29 22:36:10 +02006917 CurrentType.tp_methods = CurrentMethods;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006918#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006919 CurrentType.tp_getattro = (getattrofunc)CurrentGetattro;
6920 CurrentType.tp_setattro = (setattrofunc)CurrentSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006921#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006922 CurrentType.tp_getattr = (getattrfunc)CurrentGetattr;
6923 CurrentType.tp_setattr = (setattrfunc)CurrentSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006924#endif
6925
Bram Moolenaara80faa82020-04-12 19:37:17 +02006926 CLEAR_FIELD(DictionaryType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006927 DictionaryType.tp_name = "vim.dictionary";
6928 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02006929 DictionaryType.tp_dealloc = (destructor)DictionaryDestructor;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006930 DictionaryType.tp_as_sequence = &DictionaryAsSeq;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006931 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006932 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
Bram Moolenaar86181df2020-05-11 23:14:04 +02006933 DictionaryType.tp_doc = "dictionary pushing modifications to Vim structure";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006934 DictionaryType.tp_methods = DictionaryMethods;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006935 DictionaryType.tp_iter = (getiterfunc)DictionaryIter;
6936 DictionaryType.tp_new = (newfunc)DictionaryConstructor;
6937 DictionaryType.tp_alloc = (allocfunc)PyType_GenericAlloc;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006938#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006939 DictionaryType.tp_getattro = (getattrofunc)DictionaryGetattro;
6940 DictionaryType.tp_setattro = (setattrofunc)DictionarySetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006941#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006942 DictionaryType.tp_getattr = (getattrfunc)DictionaryGetattr;
6943 DictionaryType.tp_setattr = (setattrfunc)DictionarySetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006944#endif
6945
Bram Moolenaara80faa82020-04-12 19:37:17 +02006946 CLEAR_FIELD(ListType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006947 ListType.tp_name = "vim.list";
Bram Moolenaard6e39182013-05-21 18:30:34 +02006948 ListType.tp_dealloc = (destructor)ListDestructor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006949 ListType.tp_basicsize = sizeof(ListObject);
6950 ListType.tp_as_sequence = &ListAsSeq;
6951 ListType.tp_as_mapping = &ListAsMapping;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006952 ListType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
Bram Moolenaar86181df2020-05-11 23:14:04 +02006953 ListType.tp_doc = "list pushing modifications to Vim structure";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006954 ListType.tp_methods = ListMethods;
Bram Moolenaard6e39182013-05-21 18:30:34 +02006955 ListType.tp_iter = (getiterfunc)ListIter;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006956 ListType.tp_new = (newfunc)ListConstructor;
6957 ListType.tp_alloc = (allocfunc)PyType_GenericAlloc;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006958#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006959 ListType.tp_getattro = (getattrofunc)ListGetattro;
6960 ListType.tp_setattro = (setattrofunc)ListSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006961#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006962 ListType.tp_getattr = (getattrfunc)ListGetattr;
6963 ListType.tp_setattr = (setattrfunc)ListSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006964#endif
6965
Bram Moolenaara80faa82020-04-12 19:37:17 +02006966 CLEAR_FIELD(FunctionType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006967 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006968 FunctionType.tp_basicsize = sizeof(FunctionObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02006969 FunctionType.tp_dealloc = (destructor)FunctionDestructor;
6970 FunctionType.tp_call = (ternaryfunc)FunctionCall;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02006971 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
Bram Moolenaar86181df2020-05-11 23:14:04 +02006972 FunctionType.tp_doc = "object that calls Vim function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006973 FunctionType.tp_methods = FunctionMethods;
Bram Moolenaara5b725c2013-05-30 12:43:54 +02006974 FunctionType.tp_repr = (reprfunc)FunctionRepr;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02006975 FunctionType.tp_new = (newfunc)FunctionConstructor;
6976 FunctionType.tp_alloc = (allocfunc)PyType_GenericAlloc;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006977#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02006978 FunctionType.tp_getattro = (getattrofunc)FunctionGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006979#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02006980 FunctionType.tp_getattr = (getattrfunc)FunctionGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006981#endif
6982
Bram Moolenaara80faa82020-04-12 19:37:17 +02006983 CLEAR_FIELD(OptionsType);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02006984 OptionsType.tp_name = "vim.options";
6985 OptionsType.tp_basicsize = sizeof(OptionsObject);
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01006986 OptionsType.tp_as_sequence = &OptionsAsSeq;
Bram Moolenaar07b88642013-05-29 22:58:32 +02006987 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02006988 OptionsType.tp_doc = "object for manipulating options";
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01006989 OptionsType.tp_iter = (getiterfunc)OptionsIter;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02006990 OptionsType.tp_as_mapping = &OptionsAsMapping;
Bram Moolenaard6e39182013-05-21 18:30:34 +02006991 OptionsType.tp_dealloc = (destructor)OptionsDestructor;
6992 OptionsType.tp_traverse = (traverseproc)OptionsTraverse;
6993 OptionsType.tp_clear = (inquiry)OptionsClear;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02006994
Bram Moolenaar79a494d2018-07-22 04:30:21 +02006995#if PY_VERSION_HEX < 0x030700f0
Bram Moolenaara80faa82020-04-12 19:37:17 +02006996 CLEAR_FIELD(LoaderType);
Bram Moolenaar81c40c52013-06-12 14:41:04 +02006997 LoaderType.tp_name = "vim.Loader";
6998 LoaderType.tp_basicsize = sizeof(LoaderObject);
6999 LoaderType.tp_flags = Py_TPFLAGS_DEFAULT;
7000 LoaderType.tp_doc = "vim message object";
7001 LoaderType.tp_methods = LoaderMethods;
7002 LoaderType.tp_dealloc = (destructor)LoaderDestructor;
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007003#endif
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007004
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007005#if PY_MAJOR_VERSION >= 3
Bram Moolenaara80faa82020-04-12 19:37:17 +02007006 CLEAR_FIELD(vimmodule);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007007 vimmodule.m_name = "vim";
7008 vimmodule.m_doc = "Vim Python interface\n";
7009 vimmodule.m_size = -1;
7010 vimmodule.m_methods = VimMethods;
7011#endif
7012}
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007013
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007014 static int
Bram Moolenaarfb97f282013-07-09 17:42:46 +02007015init_types(void)
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007016{
7017 PYTYPE_READY(IterType);
7018 PYTYPE_READY(BufferType);
7019 PYTYPE_READY(RangeType);
7020 PYTYPE_READY(WindowType);
7021 PYTYPE_READY(TabPageType);
7022 PYTYPE_READY(BufMapType);
7023 PYTYPE_READY(WinListType);
7024 PYTYPE_READY(TabListType);
7025 PYTYPE_READY(CurrentType);
7026 PYTYPE_READY(DictionaryType);
7027 PYTYPE_READY(ListType);
7028 PYTYPE_READY(FunctionType);
7029 PYTYPE_READY(OptionsType);
7030 PYTYPE_READY(OutputType);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007031#if PY_VERSION_HEX < 0x030700f0
Bram Moolenaar9f3685a2013-06-12 14:20:36 +02007032 PYTYPE_READY(LoaderType);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007033#endif
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007034
7035#ifdef USE_LIMITED_API
7036 // We need to finish initializing all the static objects because the types
7037 // are only just allocated on the heap now.
7038 // Each PyObject_HEAD_INIT_TYPE should correspond to a
7039 // PyObject_FINISH_INIT_TYPE below.
7040 PyObject_FINISH_INIT_TYPE(Output, OutputType);
7041 PyObject_FINISH_INIT_TYPE(Error, OutputType);
7042 PyObject_FINISH_INIT_TYPE(TheBufferMap, BufMapType);
7043 PyObject_FINISH_INIT_TYPE(TheWindowList, WinListType);
7044 PyObject_FINISH_INIT_TYPE(TheCurrent, CurrentType);
7045 PyObject_FINISH_INIT_TYPE(TheTabPageList, TabListType);
7046#endif
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007047 return 0;
7048}
7049
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007050#ifdef USE_LIMITED_API
7051 static void
7052shutdown_types(void)
7053{
7054 PYTYPE_CLEANUP(IterType);
7055 PYTYPE_CLEANUP(BufferType);
7056 PYTYPE_CLEANUP(RangeType);
7057 PYTYPE_CLEANUP(WindowType);
7058 PYTYPE_CLEANUP(TabPageType);
7059 PYTYPE_CLEANUP(BufMapType);
7060 PYTYPE_CLEANUP(WinListType);
7061 PYTYPE_CLEANUP(TabListType);
7062 PYTYPE_CLEANUP(CurrentType);
7063 PYTYPE_CLEANUP(DictionaryType);
7064 PYTYPE_CLEANUP(ListType);
7065 PYTYPE_CLEANUP(FunctionType);
7066 PYTYPE_CLEANUP(OptionsType);
7067 PYTYPE_CLEANUP(OutputType);
7068# if PY_VERSION_HEX < 0x030700f0
7069 PYTYPE_CLEANUP(LoaderType);
7070# endif
7071}
7072#endif
7073
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007074 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02007075init_sys_path(void)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007076{
7077 PyObject *path;
7078 PyObject *path_hook;
7079 PyObject *path_hooks;
7080
7081 if (!(path_hook = PyObject_GetAttrString(vim_module, "path_hook")))
7082 return -1;
7083
7084 if (!(path_hooks = PySys_GetObject("path_hooks")))
7085 {
7086 PyErr_Clear();
7087 path_hooks = PyList_New(1);
7088 PyList_SET_ITEM(path_hooks, 0, path_hook);
7089 if (PySys_SetObject("path_hooks", path_hooks))
7090 {
7091 Py_DECREF(path_hooks);
7092 return -1;
7093 }
7094 Py_DECREF(path_hooks);
7095 }
7096 else if (PyList_Check(path_hooks))
7097 {
7098 if (PyList_Append(path_hooks, path_hook))
7099 {
7100 Py_DECREF(path_hook);
7101 return -1;
7102 }
7103 Py_DECREF(path_hook);
7104 }
7105 else
7106 {
7107 VimTryStart();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007108 emsg(_("Failed to set path hook: sys.path_hooks is not a list\n"
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007109 "You should now do the following:\n"
7110 "- append vim.path_hook to sys.path_hooks\n"
7111 "- append vim.VIM_SPECIAL_PATH to sys.path\n"));
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01007112 VimTryEnd(); // Discard the error
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007113 Py_DECREF(path_hook);
7114 return 0;
7115 }
7116
7117 if (!(path = PySys_GetObject("path")))
7118 {
7119 PyErr_Clear();
7120 path = PyList_New(1);
7121 Py_INCREF(vim_special_path_object);
7122 PyList_SET_ITEM(path, 0, vim_special_path_object);
7123 if (PySys_SetObject("path", path))
7124 {
7125 Py_DECREF(path);
7126 return -1;
7127 }
7128 Py_DECREF(path);
7129 }
7130 else if (PyList_Check(path))
7131 {
7132 if (PyList_Append(path, vim_special_path_object))
7133 return -1;
7134 }
7135 else
7136 {
7137 VimTryStart();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007138 emsg(_("Failed to set path: sys.path is not a list\n"
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007139 "You should now append vim.VIM_SPECIAL_PATH to sys.path"));
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01007140 VimTryEnd(); // Discard the error
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007141 }
7142
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007143 return 0;
7144}
7145
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007146static struct numeric_constant {
7147 char *name;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007148 int val;
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007149} numeric_constants[] = {
7150 {"VAR_LOCKED", VAR_LOCKED},
7151 {"VAR_FIXED", VAR_FIXED},
7152 {"VAR_SCOPE", VAR_SCOPE},
7153 {"VAR_DEF_SCOPE", VAR_DEF_SCOPE},
7154};
7155
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007156struct object_constant {
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007157 char *name;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007158 PyObject *valObject;
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007159};
7160
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007161#define ADD_OBJECT(m, name, obj) \
Bram Moolenaardee2e312013-06-23 16:35:47 +02007162 if (PyModule_AddObject(m, name, obj)) \
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007163 return -1;
7164
7165#define ADD_CHECKED_OBJECT(m, name, obj) \
7166 { \
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007167 PyObject *valObject = obj; \
7168 if (!valObject) \
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007169 return -1; \
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007170 ADD_OBJECT(m, name, valObject); \
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007171 }
7172
7173 static int
Bram Moolenaardee2e312013-06-23 16:35:47 +02007174populate_module(PyObject *m)
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007175{
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007176 int i;
7177 PyObject *other_module;
Bram Moolenaarf9c9b322013-06-10 20:47:36 +02007178 PyObject *attr;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007179 PyObject *imp;
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007180#if PY_VERSION_HEX >= 0x030700f0
7181 PyObject *dict;
7182 PyObject *cls;
7183#endif
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007184
7185 for (i = 0; i < (int)(sizeof(numeric_constants)
7186 / sizeof(struct numeric_constant));
7187 ++i)
7188 ADD_CHECKED_OBJECT(m, numeric_constants[i].name,
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007189 PyInt_FromLong(numeric_constants[i].val));
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007190
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007191 struct object_constant object_constants[] = {
7192 {"buffers", (PyObject *)(void *)&TheBufferMap},
7193 {"windows", (PyObject *)(void *)&TheWindowList},
7194 {"tabpages", (PyObject *)(void *)&TheTabPageList},
7195 {"current", (PyObject *)(void *)&TheCurrent},
7196
7197 {"Buffer", (PyObject *)BufferTypePtr},
7198 {"Range", (PyObject *)RangeTypePtr},
7199 {"Window", (PyObject *)WindowTypePtr},
7200 {"TabPage", (PyObject *)TabPageTypePtr},
7201 {"Dictionary", (PyObject *)DictionaryTypePtr},
7202 {"List", (PyObject *)ListTypePtr},
7203 {"Function", (PyObject *)FunctionTypePtr},
7204 {"Options", (PyObject *)OptionsTypePtr},
7205#if PY_VERSION_HEX < 0x030700f0
7206 {"_Loader", (PyObject *)LoaderTypePtr},
7207#endif
7208 };
7209
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007210 for (i = 0; i < (int)(sizeof(object_constants)
7211 / sizeof(struct object_constant));
7212 ++i)
7213 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007214 PyObject *valObject;
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007215
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007216 valObject = object_constants[i].valObject;
7217 Py_INCREF(valObject);
7218 ADD_OBJECT(m, object_constants[i].name, valObject);
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007219 }
7220
7221 if (!(VimError = PyErr_NewException("vim.error", NULL, NULL)))
7222 return -1;
7223 ADD_OBJECT(m, "error", VimError);
7224
Bram Moolenaarda6c0332019-09-01 16:01:30 +02007225 ADD_CHECKED_OBJECT(m, "vars", NEW_DICTIONARY(get_globvar_dict()));
7226 ADD_CHECKED_OBJECT(m, "vvars", NEW_DICTIONARY(get_vimvar_dict()));
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007227 ADD_CHECKED_OBJECT(m, "options",
7228 OptionsNew(SREQ_GLOBAL, NULL, dummy_check, NULL));
Bram Moolenaarf4258302013-06-02 18:20:17 +02007229
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007230 if (!(other_module = PyImport_ImportModule("os")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007231 return -1;
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007232 ADD_OBJECT(m, "os", other_module);
Bram Moolenaarf4258302013-06-02 18:20:17 +02007233
Bram Moolenaar22081f42016-06-01 20:38:34 +02007234#if PY_MAJOR_VERSION >= 3
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007235 if (!(py_getcwd = PyObject_GetAttrString(other_module, "getcwd")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007236 return -1;
Bram Moolenaar22081f42016-06-01 20:38:34 +02007237#else
7238 if (!(py_getcwd = PyObject_GetAttrString(other_module, "getcwdu")))
7239 return -1;
7240#endif
Bram Moolenaarf4258302013-06-02 18:20:17 +02007241 ADD_OBJECT(m, "_getcwd", py_getcwd)
7242
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007243 if (!(py_chdir = PyObject_GetAttrString(other_module, "chdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007244 return -1;
7245 ADD_OBJECT(m, "_chdir", py_chdir);
Bram Moolenaardee2e312013-06-23 16:35:47 +02007246 if (!(attr = PyObject_GetAttrString(m, "chdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007247 return -1;
Bram Moolenaarf9c9b322013-06-10 20:47:36 +02007248 if (PyObject_SetAttrString(other_module, "chdir", attr))
7249 {
7250 Py_DECREF(attr);
7251 return -1;
7252 }
7253 Py_DECREF(attr);
Bram Moolenaarf4258302013-06-02 18:20:17 +02007254
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007255 if ((py_fchdir = PyObject_GetAttrString(other_module, "fchdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007256 {
7257 ADD_OBJECT(m, "_fchdir", py_fchdir);
Bram Moolenaardee2e312013-06-23 16:35:47 +02007258 if (!(attr = PyObject_GetAttrString(m, "fchdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007259 return -1;
Bram Moolenaarf9c9b322013-06-10 20:47:36 +02007260 if (PyObject_SetAttrString(other_module, "fchdir", attr))
7261 {
7262 Py_DECREF(attr);
7263 return -1;
7264 }
7265 Py_DECREF(attr);
Bram Moolenaarf4258302013-06-02 18:20:17 +02007266 }
Bram Moolenaare9056b12013-06-03 20:04:48 +02007267 else
7268 PyErr_Clear();
Bram Moolenaarf4258302013-06-02 18:20:17 +02007269
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007270 if (!(vim_special_path_object = PyString_FromString(vim_special_path)))
7271 return -1;
7272
7273 ADD_OBJECT(m, "VIM_SPECIAL_PATH", vim_special_path_object);
7274
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007275#if PY_VERSION_HEX >= 0x030700f0
7276 if (!(imp = PyImport_ImportModule("importlib.machinery")))
7277 return -1;
7278
7279 dict = PyModule_GetDict(imp);
7280
7281 if (!(cls = PyDict_GetItemString(dict, "PathFinder")))
7282 {
7283 Py_DECREF(imp);
7284 return -1;
7285 }
7286
7287 if (!(py_find_spec = PyObject_GetAttrString(cls, "find_spec")))
7288 {
7289 Py_DECREF(imp);
7290 return -1;
7291 }
7292
Bram Moolenaarb999ba22019-02-14 13:28:45 +01007293 if ((py_find_module = PyObject_GetAttrString(cls, "find_module")))
7294 {
7295 // find_module() is deprecated, this may stop working in some later
7296 // version.
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007297 ADD_OBJECT(m, "_find_module", py_find_module);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01007298 }
7299
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007300 Py_DECREF(imp);
7301
7302 ADD_OBJECT(m, "_find_spec", py_find_spec);
7303#else
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007304 if (!(imp = PyImport_ImportModule("imp")))
7305 return -1;
7306
7307 if (!(py_find_module = PyObject_GetAttrString(imp, "find_module")))
7308 {
7309 Py_DECREF(imp);
7310 return -1;
7311 }
7312
7313 if (!(py_load_module = PyObject_GetAttrString(imp, "load_module")))
7314 {
7315 Py_DECREF(py_find_module);
7316 Py_DECREF(imp);
7317 return -1;
7318 }
7319
7320 Py_DECREF(imp);
7321
Bram Moolenaar9f3685a2013-06-12 14:20:36 +02007322 ADD_OBJECT(m, "_find_module", py_find_module);
7323 ADD_OBJECT(m, "_load_module", py_load_module);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007324#endif
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007325
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007326 return 0;
7327}