blob: 3643f8be27cd847b8bc3a185ae17ef97f024c402 [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.
Yee Cheng Chinf7f746b2023-09-30 12:28:50 +0200108static PyObject* Vim_PyObject_New(PyTypeObject *type, size_t objsize)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200109{
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
Yee Cheng Chinf7f746b2023-09-30 12:28:50 +0200171static PyTypeObject* AddHeapType(struct typeobject_wrapper* type_object)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200172{
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.
Yee Cheng Chinf7f746b2023-09-30 12:28:50 +0200257static PyObject* Vim_PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200258{
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}
Yee Cheng Chinf7f746b2023-09-30 12:28:50 +0200268static int Vim_PyRun_SimpleString(const char *str)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200269{
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
Ken Takata073cb022024-07-28 17:08:15 +0200361#if PY_VERSION_HEX < 0x30c00a7
Bram Moolenaarb999ba22019-02-14 13:28:45 +0100362static PyObject *py_find_module;
Ken Takata073cb022024-07-28 17:08:15 +0200363#endif
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200364
365static PyObject *VimError;
366
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200367/*
368 * obtain a lock on the Vim data structures
369 */
370 static void
371Python_Lock_Vim(void)
372{
373}
374
375/*
376 * release a lock on the Vim data structures
377 */
378 static void
379Python_Release_Vim(void)
380{
381}
382
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200383/*
384 * The "todecref" argument holds a pointer to PyObject * that must be
385 * DECREF'ed after returned char_u * is no longer needed or NULL if all what
386 * was needed to generate returned value is object.
387 *
388 * Use Py_XDECREF to decrement reference count.
389 */
390 static char_u *
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200391StringToChars(PyObject *obj, PyObject **todecref)
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200392{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200393 char_u *str;
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200394
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200395 if (PyBytes_Check(obj))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200396 {
397
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200398 if (PyBytes_AsStringAndSize(obj, (char **) &str, NULL) == -1
399 || str == NULL)
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200400 return NULL;
401
402 *todecref = NULL;
403 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200404 else if (PyUnicode_Check(obj))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200405 {
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200406 PyObject *bytes;
407
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +0100408 if (!(bytes = PyUnicode_AsEncodedString(obj, ENC_OPT,
409 ERRORS_ENCODE_ARG)))
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200410 return NULL;
411
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +0100412 if (PyBytes_AsStringAndSize(bytes, (char **) &str, NULL) == -1
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200413 || str == NULL)
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200414 {
415 Py_DECREF(bytes);
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200416 return NULL;
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200417 }
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200418
419 *todecref = bytes;
420 }
421 else
422 {
Bram Moolenaarc476e522013-06-23 13:46:40 +0200423#if PY_MAJOR_VERSION < 3
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200424 PyErr_FORMAT_TYPE(N_("expected str() or unicode() instance, but got %s"),
425 obj);
Bram Moolenaarc476e522013-06-23 13:46:40 +0200426#else
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200427 PyErr_FORMAT_TYPE(N_("expected bytes() or str() instance, but got %s"),
428 obj);
Bram Moolenaarc476e522013-06-23 13:46:40 +0200429#endif
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200430 return NULL;
431 }
432
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200433 return (char_u *) str;
Bram Moolenaare9ba5162013-05-29 22:02:22 +0200434}
435
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200436#define NUMBER_LONG 1
437#define NUMBER_INT 2
438#define NUMBER_NATURAL 4
439#define NUMBER_UNSIGNED 8
440
441 static int
442NumberToLong(PyObject *obj, long *result, int flags)
443{
444#if PY_MAJOR_VERSION < 3
445 if (PyInt_Check(obj))
446 {
447 *result = PyInt_AsLong(obj);
448 if (PyErr_Occurred())
449 return -1;
450 }
451 else
452#endif
453 if (PyLong_Check(obj))
454 {
455 *result = PyLong_AsLong(obj);
456 if (PyErr_Occurred())
457 return -1;
458 }
459 else if (PyNumber_Check(obj))
460 {
461 PyObject *num;
462
463 if (!(num = PyNumber_Long(obj)))
464 return -1;
465
466 *result = PyLong_AsLong(num);
467
468 Py_DECREF(num);
469
470 if (PyErr_Occurred())
471 return -1;
472 }
473 else
474 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200475#if PY_MAJOR_VERSION < 3
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200476 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200477 N_("expected int(), long() or something supporting "
Bram Moolenaarc1c3d682013-06-24 21:21:58 +0200478 "coercing to long(), but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200479 obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200480#else
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200481 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200482 N_("expected int() or something supporting coercing to int(), "
Bram Moolenaarc1c3d682013-06-24 21:21:58 +0200483 "but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200484 obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200485#endif
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200486 return -1;
487 }
488
489 if (flags & NUMBER_INT)
490 {
491 if (*result > INT_MAX)
492 {
493 PyErr_SET_STRING(PyExc_OverflowError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200494 N_("value is too large to fit into C int type"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200495 return -1;
496 }
497 else if (*result < INT_MIN)
498 {
499 PyErr_SET_STRING(PyExc_OverflowError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200500 N_("value is too small to fit into C int type"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200501 return -1;
502 }
503 }
504
505 if (flags & NUMBER_NATURAL)
506 {
507 if (*result <= 0)
508 {
509 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar4de6a212014-03-08 16:13:44 +0100510 N_("number must be greater than zero"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200511 return -1;
512 }
513 }
514 else if (flags & NUMBER_UNSIGNED)
515 {
516 if (*result < 0)
517 {
518 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200519 N_("number must be greater or equal to zero"));
Bram Moolenaar141be8a2013-06-23 14:16:57 +0200520 return -1;
521 }
522 }
523
524 return 0;
525}
526
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200527 static int
528add_string(PyObject *list, char *s)
529{
530 PyObject *string;
531
532 if (!(string = PyString_FromString(s)))
533 return -1;
Bram Moolenaar808c2bc2013-06-23 13:11:18 +0200534
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200535 if (PyList_Append(list, string))
536 {
537 Py_DECREF(string);
538 return -1;
539 }
540
541 Py_DECREF(string);
542 return 0;
543}
544
545 static PyObject *
546ObjectDir(PyObject *self, char **attributes)
547{
548 PyMethodDef *method;
549 char **attr;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200550 PyObject *ret;
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200551
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200552 if (!(ret = PyList_New(0)))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200553 return NULL;
554
555 if (self)
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200556 for (method = Py_TYPE_GET_TP_METHODS(self->ob_type) ; method->ml_name != NULL ; ++method)
Bram Moolenaar41009372013-07-01 22:03:04 +0200557 if (add_string(ret, (char *)method->ml_name))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200558 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200559 Py_DECREF(ret);
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200560 return NULL;
561 }
562
563 for (attr = attributes ; *attr ; ++attr)
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200564 if (add_string(ret, *attr))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200565 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200566 Py_DECREF(ret);
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200567 return NULL;
568 }
569
570#if PY_MAJOR_VERSION < 3
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200571 if (add_string(ret, "__members__"))
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200572 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200573 Py_DECREF(ret);
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200574 return NULL;
575 }
576#endif
577
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200578 return ret;
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200579}
580
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100581// Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200582
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100583// Function to write a line, points to either msg() or emsg().
Bram Moolenaarefc0d942020-10-11 18:05:02 +0200584typedef int (*writefn)(char *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200585
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200586DEFINE_PY_TYPE_OBJECT(OutputType);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200587
588typedef struct
589{
590 PyObject_HEAD
591 long softspace;
592 long error;
593} OutputObject;
594
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200595static char *OutputAttrs[] = {
596 "softspace",
597 NULL
598};
599
600 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200601OutputDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200602{
603 return ObjectDir(self, OutputAttrs);
604}
605
Bram Moolenaar77045652012-09-21 13:46:06 +0200606 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +0200607OutputSetattr(PyObject *self_obj, char *name, PyObject *valObject)
Bram Moolenaar77045652012-09-21 13:46:06 +0200608{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +0200609 OutputObject *self = (OutputObject*)self_obj;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200610 if (valObject == NULL)
Bram Moolenaar77045652012-09-21 13:46:06 +0200611 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +0200612 PyErr_SET_STRING(PyExc_AttributeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200613 N_("can't delete OutputObject attributes"));
Bram Moolenaar77045652012-09-21 13:46:06 +0200614 return -1;
615 }
616
617 if (strcmp(name, "softspace") == 0)
618 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200619 if (NumberToLong(valObject, &(self->softspace), NUMBER_UNSIGNED))
Bram Moolenaar77045652012-09-21 13:46:06 +0200620 return -1;
Bram Moolenaar77045652012-09-21 13:46:06 +0200621 return 0;
622 }
623
Bram Moolenaar6f1404f2013-06-23 16:04:08 +0200624 PyErr_FORMAT(PyExc_AttributeError, N_("invalid attribute: %s"), name);
Bram Moolenaar77045652012-09-21 13:46:06 +0200625 return -1;
626}
627
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100628// Buffer IO, we write one whole line at a time.
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200629static garray_T io_ga = {0, 0, 1, 80, NULL};
630static writefn old_fn = NULL;
631
632 static void
633PythonIO_Flush(void)
634{
635 if (old_fn != NULL && io_ga.ga_len > 0)
636 {
Bram Moolenaarefc0d942020-10-11 18:05:02 +0200637 ((char *)io_ga.ga_data)[io_ga.ga_len] = NUL;
638 old_fn((char *)io_ga.ga_data);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200639 }
640 io_ga.ga_len = 0;
641}
642
643 static void
644writer(writefn fn, char_u *str, PyInt n)
645{
646 char_u *ptr;
647
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100648 // Flush when switching output function.
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200649 if (fn != old_fn)
650 PythonIO_Flush();
651 old_fn = fn;
652
Bram Moolenaarb98678a2019-10-19 15:18:44 +0200653 // Write each NL separated line. Text after the last NL is kept for
654 // writing later.
655 // For normal messages: Do not output when "got_int" was set. This avoids
656 // a loop gone crazy flooding the terminal with messages. Also for when
657 // "q" is pressed at the more-prompt.
658 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL
659 && (fn == (writefn)emsg || !got_int))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200660 {
661 PyInt len = ptr - str;
662
663 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
664 break;
665
666 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
667 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
Bram Moolenaarefc0d942020-10-11 18:05:02 +0200668 fn((char *)io_ga.ga_data);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200669 str = ptr + 1;
670 n -= len + 1;
671 io_ga.ga_len = 0;
672 }
673
Bram Moolenaarb98678a2019-10-19 15:18:44 +0200674 // Put the remaining text into io_ga for later printing.
675 if (n > 0 && (fn == (writefn)emsg || !got_int)
676 && ga_grow(&io_ga, (int)(n + 1)) == OK)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200677 {
678 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
679 io_ga.ga_len += (int)n;
680 }
681}
682
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200683 static int
684write_output(OutputObject *self, PyObject *string)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200685{
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200686 Py_ssize_t len = 0;
687 char *str = NULL;
688 int error = self->error;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200689
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200690 if (!PyArg_Parse(string, "et#", ENC_OPT, &str, &len))
691 return -1;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200692
693 Py_BEGIN_ALLOW_THREADS
694 Python_Lock_Vim();
Bram Moolenaar7f3a2842019-05-18 15:02:25 +0200695 if (error)
696 emsg_severe = TRUE;
Bram Moolenaar32526b32019-01-19 17:43:09 +0100697 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200698 Python_Release_Vim();
699 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200700 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200701
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200702 return 0;
703}
704
705 static PyObject *
706OutputWrite(OutputObject *self, PyObject *string)
707{
708 if (write_output(self, string))
709 return NULL;
710
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200711 Py_INCREF(Py_None);
712 return Py_None;
713}
714
715 static PyObject *
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200716OutputWritelines(OutputObject *self, PyObject *seq)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200717{
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200718 PyObject *iterator;
719 PyObject *item;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200720
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200721 if (!(iterator = PyObject_GetIter(seq)))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200722 return NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200723
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200724 while ((item = PyIter_Next(iterator)))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200725 {
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200726 if (write_output(self, item))
Bram Moolenaardb913952012-06-29 12:54:53 +0200727 {
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200728 Py_DECREF(iterator);
729 Py_DECREF(item);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200730 return NULL;
731 }
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200732 Py_DECREF(item);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200733 }
734
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200735 Py_DECREF(iterator);
736
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100737 // Iterator may have finished due to an exception
Bram Moolenaar01a7a722013-05-30 12:26:58 +0200738 if (PyErr_Occurred())
739 return NULL;
740
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200741 Py_INCREF(Py_None);
742 return Py_None;
743}
744
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100745 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200746AlwaysNone(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100747{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100748 // do nothing
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100749 Py_INCREF(Py_None);
750 return Py_None;
751}
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200752#define ALWAYS_NONE AlwaysNone(NULL, NULL)
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100753
Bram Moolenaard4247472015-11-02 13:28:59 +0100754 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200755AlwaysFalse(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaard4247472015-11-02 13:28:59 +0100756{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100757 // do nothing
Bram Moolenaare7427f42015-11-10 13:24:20 +0100758 PyObject *ret = Py_False;
759 Py_INCREF(ret);
760 return ret;
Bram Moolenaard4247472015-11-02 13:28:59 +0100761}
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200762#define ALWAYS_FALSE AlwaysFalse(NULL, NULL)
Bram Moolenaard4247472015-11-02 13:28:59 +0100763
764 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200765AlwaysTrue(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaard4247472015-11-02 13:28:59 +0100766{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100767 // do nothing
Bram Moolenaare7427f42015-11-10 13:24:20 +0100768 PyObject *ret = Py_True;
769 Py_INCREF(ret);
770 return ret;
Bram Moolenaard4247472015-11-02 13:28:59 +0100771}
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +0200772#define ALWAYS_TRUE AlwaysTrue(NULL, NULL)
Bram Moolenaard4247472015-11-02 13:28:59 +0100773
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200774/***************/
775
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200776static struct PyMethodDef OutputMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100777 // name, function, calling, doc
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +0200778 {"write", (PyCFunction)OutputWrite, METH_O, ""},
779 {"writelines", (PyCFunction)OutputWritelines, METH_O, ""},
Bram Moolenaard4247472015-11-02 13:28:59 +0100780 {"flush", (PyCFunction)AlwaysNone, METH_NOARGS, ""},
781 {"close", (PyCFunction)AlwaysNone, METH_NOARGS, ""},
782 {"isatty", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
783 {"readable", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
784 {"seekable", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
785 {"writable", (PyCFunction)AlwaysTrue, METH_NOARGS, ""},
Bram Moolenaar6d4431e2016-04-21 20:00:56 +0200786 {"closed", (PyCFunction)AlwaysFalse, METH_NOARGS, ""},
Bram Moolenaardd8aca62013-05-29 22:36:10 +0200787 {"__dir__", (PyCFunction)OutputDir, METH_NOARGS, ""},
Bram Moolenaar182dc4f2013-05-21 19:01:55 +0200788 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200789};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200790
791static OutputObject Output =
792{
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200793 PyObject_HEAD_INIT_TYPE(OutputType)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200794 0,
795 0
796};
797
798static OutputObject Error =
799{
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200800 PyObject_HEAD_INIT_TYPE(OutputType)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200801 0,
802 1
803};
804
805 static int
806PythonIO_Init_io(void)
807{
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +0200808 if (PySys_SetObject("stdout", (PyObject *)(void *)&Output))
809 return -1;
810 if (PySys_SetObject("stderr", (PyObject *)(void *)&Error))
811 return -1;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200812
813 if (PyErr_Occurred())
814 {
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000815 emsg(_(e_python_error_initialising_io_object));
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200816 return -1;
817 }
818
819 return 0;
820}
821
Bram Moolenaar79a494d2018-07-22 04:30:21 +0200822#if PY_VERSION_HEX < 0x030700f0
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200823static PyObject *call_load_module(char *name, int len, PyObject *find_module_result);
824
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200825typedef struct
826{
827 PyObject_HEAD
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200828 char *fullname;
829 PyObject *result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200830} LoaderObject;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +0200831DEFINE_PY_TYPE_OBJECT(LoaderType);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200832
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200833 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +0200834LoaderDestructor(PyObject *self_obj)
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200835{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +0200836 LoaderObject *self = (LoaderObject*)self_obj;
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200837 vim_free(self->fullname);
838 Py_XDECREF(self->result);
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200839 DESTRUCTOR_FINISH(self);
840}
841
842 static PyObject *
843LoaderLoadModule(LoaderObject *self, PyObject *args UNUSED)
844{
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200845 char *fullname = self->fullname;
846 PyObject *result = self->result;
847 PyObject *module;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200848
Bram Moolenaar447bd5a2018-08-07 19:45:27 +0200849 if (!fullname)
850 {
851 module = result ? result : Py_None;
852 Py_INCREF(module);
853 return module;
854 }
855
856 module = call_load_module(fullname, (int)STRLEN(fullname), result);
857
858 self->fullname = NULL;
859 self->result = module;
860
861 vim_free(fullname);
862 Py_DECREF(result);
863
864 if (!module)
865 {
866 if (PyErr_Occurred())
867 return NULL;
868
869 Py_INCREF(Py_None);
870 return Py_None;
871 }
872
873 Py_INCREF(module);
874 return module;
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200875}
876
877static struct PyMethodDef LoaderMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100878 // name, function, calling, doc
Bram Moolenaar81c40c52013-06-12 14:41:04 +0200879 {"load_module", (PyCFunction)LoaderLoadModule, METH_VARARGS, ""},
880 { NULL, NULL, 0, NULL}
881};
Bram Moolenaar79a494d2018-07-22 04:30:21 +0200882#endif
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200883
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100884/*
885 * Check to see whether a Vim error has been reported, or a keyboard
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200886 * interrupt has been detected.
887 */
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200888 static void
889VimTryStart(void)
890{
891 ++trylevel;
892}
893
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200894 static int
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200895VimTryEnd(void)
896{
897 --trylevel;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100898 // Without this it stops processing all subsequent Vim script commands and
899 // generates strange error messages if I e.g. try calling Test() in a cycle
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200900 did_emsg = FALSE;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100901 // Keyboard interrupt should be preferred over anything else
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200902 if (got_int)
903 {
Bram Moolenaar4315f262014-01-31 14:54:04 +0100904 if (did_throw)
Bram Moolenaard6b8a522013-11-11 01:05:48 +0100905 discard_current_exception();
Bram Moolenaard6b8a522013-11-11 01:05:48 +0100906 got_int = FALSE;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200907 PyErr_SetNone(PyExc_KeyboardInterrupt);
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200908 return -1;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200909 }
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100910 else if (msg_list != NULL && *msg_list != NULL)
911 {
912 int should_free;
Bram Moolenaarb1443b42019-01-13 23:51:14 +0100913 char *msg;
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100914
915 msg = get_exception_string(*msg_list, ET_ERROR, NULL, &should_free);
916
917 if (msg == NULL)
918 {
919 PyErr_NoMemory();
920 return -1;
921 }
922
Bram Moolenaarb1443b42019-01-13 23:51:14 +0100923 PyErr_SetVim(msg);
Bram Moolenaar9fee7d42013-11-28 17:04:43 +0100924
925 free_global_msglist();
926
927 if (should_free)
928 vim_free(msg);
929
930 return -1;
931 }
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200932 else if (!did_throw)
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200933 return (PyErr_Occurred() ? -1 : 0);
Bram Moolenaar86181df2020-05-11 23:14:04 +0200934 // Python exception is preferred over Vim one; unlikely to occur though
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200935 else if (PyErr_Occurred())
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200936 {
Bram Moolenaar4315f262014-01-31 14:54:04 +0100937 discard_current_exception();
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200938 return -1;
939 }
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100940 // Finally transform Vim script exception to python one
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200941 else
942 {
Bram Moolenaar41009372013-07-01 22:03:04 +0200943 PyErr_SetVim((char *)current_exception->value);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200944 discard_current_exception();
Bram Moolenaar841fbd22013-06-23 14:37:07 +0200945 return -1;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200946 }
947}
948
949 static int
950VimCheckInterrupt(void)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200951{
952 if (got_int)
953 {
954 PyErr_SetNone(PyExc_KeyboardInterrupt);
955 return 1;
956 }
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200957 return 0;
958}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200959
Bram Moolenaar9bf703d2019-11-30 19:44:38 +0100960// Vim module - Implementation
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200961
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200962 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +0200963VimCommand(PyObject *self UNUSED, PyObject *string)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200964{
Bram Moolenaar389a1792013-06-23 13:00:44 +0200965 char_u *cmd;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200966 PyObject *ret;
Bram Moolenaar389a1792013-06-23 13:00:44 +0200967 PyObject *todecref;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200968
Bram Moolenaar389a1792013-06-23 13:00:44 +0200969 if (!(cmd = StringToChars(string, &todecref)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200970 return NULL;
971
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200972 Py_BEGIN_ALLOW_THREADS
973 Python_Lock_Vim();
974
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200975 VimTryStart();
Bram Moolenaar389a1792013-06-23 13:00:44 +0200976 do_cmdline_cmd(cmd);
Bram Moolenaara4d158b2022-08-14 14:17:45 +0100977 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200978
979 Python_Release_Vim();
980 Py_END_ALLOW_THREADS
981
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200982 if (VimTryEnd())
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200983 ret = NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200984 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200985 ret = Py_None;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200986
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200987 Py_XINCREF(ret);
Bram Moolenaar389a1792013-06-23 13:00:44 +0200988 Py_XDECREF(todecref);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +0200989 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200990}
991
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200992/*
993 * Function to translate a typval_T into a PyObject; this will recursively
994 * translate lists/dictionaries into their Python equivalents.
995 *
996 * The depth parameter is to avoid infinite recursion, set it to 1 when
997 * you call VimToPython.
998 */
999 static PyObject *
Bram Moolenaarb38caae2013-05-29 22:39:52 +02001000VimToPython(typval_T *our_tv, int depth, PyObject *lookup_dict)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001001{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001002 PyObject *ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001003 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +02001004 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001005
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001006 // Avoid infinite recursion
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001007 if (depth > 100)
1008 {
1009 Py_INCREF(Py_None);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001010 ret = Py_None;
1011 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001012 }
1013
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001014 // Check if we run into a recursive loop. The item must be in lookup_dict
1015 // then and we can use it again.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001016 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
1017 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
1018 {
Bram Moolenaardb913952012-06-29 12:54:53 +02001019 sprintf(ptrBuf, "%p",
1020 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
1021 : (void *)our_tv->vval.v_dict);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001022
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001023 if ((ret = PyDict_GetItemString(lookup_dict, ptrBuf)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001024 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001025 Py_INCREF(ret);
1026 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001027 }
1028 }
1029
1030 if (our_tv->v_type == VAR_STRING)
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001031 ret = PyString_FromString(our_tv->vval.v_string == NULL
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02001032 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001033 else if (our_tv->v_type == VAR_NUMBER)
1034 {
1035 char buf[NUMBUFLEN];
1036
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001037 // For backwards compatibility numbers are stored as strings.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001038 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
Bram Moolenaar41009372013-07-01 22:03:04 +02001039 ret = PyString_FromString((char *)buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001040 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001041 else if (our_tv->v_type == VAR_FLOAT)
1042 {
1043 char buf[NUMBUFLEN];
1044
1045 sprintf(buf, "%f", our_tv->vval.v_float);
Bram Moolenaar41009372013-07-01 22:03:04 +02001046 ret = PyString_FromString((char *)buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001047 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001048 else if (our_tv->v_type == VAR_LIST)
1049 {
1050 list_T *list = our_tv->vval.v_list;
1051 listitem_T *curr;
1052
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001053 if (list == NULL)
1054 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001055
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001056 if (!(ret = PyList_New(0)))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001057 return NULL;
1058
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001059 if (PyDict_SetItemString(lookup_dict, ptrBuf, ret))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001060 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001061 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001062 return NULL;
1063 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001064
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02001065 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001066 FOR_ALL_LIST_ITEMS(list, curr)
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001067 {
Bram Moolenaarb38caae2013-05-29 22:39:52 +02001068 if (!(newObj = VimToPython(&curr->li_tv, depth + 1, lookup_dict)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001069 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001070 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001071 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001072 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001073 if (PyList_Append(ret, newObj))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001074 {
1075 Py_DECREF(newObj);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001076 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001077 return NULL;
1078 }
1079 Py_DECREF(newObj);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001080 }
1081 }
1082 else if (our_tv->v_type == VAR_DICT)
1083 {
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001084
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001085 hashtab_T *ht;
1086 long_u todo;
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001087 hashitem_T *hi;
1088 dictitem_T *di;
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001089
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001090 if (our_tv->vval.v_dict == NULL)
1091 return NULL;
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001092 ht = &our_tv->vval.v_dict->dv_hashtab;
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001093
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001094 if (!(ret = PyDict_New()))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001095 return NULL;
1096
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001097 if (PyDict_SetItemString(lookup_dict, ptrBuf, ret))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001098 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001099 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001100 return NULL;
1101 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001102
Bram Moolenaar24a6ff82015-02-10 18:41:58 +01001103 todo = ht->ht_used;
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001104 for (hi = ht->ht_array; todo > 0; ++hi)
1105 {
1106 if (!HASHITEM_EMPTY(hi))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001107 {
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001108 --todo;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001109
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001110 di = dict_lookup(hi);
Bram Moolenaarb38caae2013-05-29 22:39:52 +02001111 if (!(newObj = VimToPython(&di->di_tv, depth + 1, lookup_dict)))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001112 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001113 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001114 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001115 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001116 if (PyDict_SetItemString(ret, (char *)hi->hi_key, newObj))
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001117 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001118 Py_DECREF(ret);
Bram Moolenaar21642ed2013-05-29 22:20:01 +02001119 Py_DECREF(newObj);
1120 return NULL;
1121 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001122 }
1123 }
1124 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001125 else if (our_tv->v_type == VAR_BOOL)
Bram Moolenaar520e1e42016-01-23 19:46:28 +01001126 {
1127 if (our_tv->vval.v_number == VVAL_FALSE)
1128 {
1129 ret = Py_False;
1130 Py_INCREF(ret);
1131 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001132 else
Bram Moolenaar520e1e42016-01-23 19:46:28 +01001133 {
1134 ret = Py_True;
1135 Py_INCREF(ret);
1136 }
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01001137 return ret;
1138 }
1139 else if (our_tv->v_type == VAR_SPECIAL)
1140 {
1141 Py_INCREF(Py_None);
1142 ret = Py_None;
Bram Moolenaar520e1e42016-01-23 19:46:28 +01001143 return ret;
1144 }
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01001145 else if (our_tv->v_type == VAR_BLOB)
1146 ret = PyBytes_FromStringAndSize(
1147 (char*) our_tv->vval.v_blob->bv_ga.ga_data,
1148 (Py_ssize_t) our_tv->vval.v_blob->bv_ga.ga_len);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001149 else
1150 {
1151 Py_INCREF(Py_None);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001152 ret = Py_None;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001153 }
1154
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001155 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001156}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001157
1158 static PyObject *
Bram Moolenaar774267b2013-05-21 20:51:59 +02001159VimEval(PyObject *self UNUSED, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001160{
Bram Moolenaar389a1792013-06-23 13:00:44 +02001161 char_u *expr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001162 typval_T *our_tv;
Bram Moolenaar389a1792013-06-23 13:00:44 +02001163 PyObject *string;
1164 PyObject *todecref;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001165 PyObject *ret;
Bram Moolenaar389a1792013-06-23 13:00:44 +02001166 PyObject *lookup_dict;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001167
Bram Moolenaar389a1792013-06-23 13:00:44 +02001168 if (!PyArg_ParseTuple(args, "O", &string))
1169 return NULL;
1170
1171 if (!(expr = StringToChars(string, &todecref)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001172 return NULL;
1173
1174 Py_BEGIN_ALLOW_THREADS
1175 Python_Lock_Vim();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001176 VimTryStart();
Bram Moolenaar389a1792013-06-23 13:00:44 +02001177 our_tv = eval_expr(expr, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001178 Python_Release_Vim();
1179 Py_END_ALLOW_THREADS
1180
Bram Moolenaar389a1792013-06-23 13:00:44 +02001181 Py_XDECREF(todecref);
1182
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001183 if (VimTryEnd())
1184 return NULL;
1185
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001186 if (our_tv == NULL)
1187 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001188 PyErr_SET_VIM(N_("invalid expression"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001189 return NULL;
1190 }
1191
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001192 // Convert the Vim type into a Python type. Create a dictionary that's
1193 // used to check for recursive loops.
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02001194 if (!(lookup_dict = PyDict_New()))
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001195 ret = NULL;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02001196 else
1197 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001198 ret = VimToPython(our_tv, 1, lookup_dict);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02001199 Py_DECREF(lookup_dict);
1200 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001201
1202
1203 Py_BEGIN_ALLOW_THREADS
1204 Python_Lock_Vim();
1205 free_tv(our_tv);
1206 Python_Release_Vim();
1207 Py_END_ALLOW_THREADS
1208
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001209 return ret;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001210}
1211
Bram Moolenaardb913952012-06-29 12:54:53 +02001212static PyObject *ConvertToPyObject(typval_T *);
1213
1214 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02001215VimEvalPy(PyObject *self UNUSED, PyObject *string)
Bram Moolenaardb913952012-06-29 12:54:53 +02001216{
Bram Moolenaardb913952012-06-29 12:54:53 +02001217 typval_T *our_tv;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001218 PyObject *ret;
Bram Moolenaar389a1792013-06-23 13:00:44 +02001219 char_u *expr;
1220 PyObject *todecref;
Bram Moolenaardb913952012-06-29 12:54:53 +02001221
Bram Moolenaar389a1792013-06-23 13:00:44 +02001222 if (!(expr = StringToChars(string, &todecref)))
Bram Moolenaardb913952012-06-29 12:54:53 +02001223 return NULL;
1224
1225 Py_BEGIN_ALLOW_THREADS
1226 Python_Lock_Vim();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001227 VimTryStart();
Bram Moolenaar389a1792013-06-23 13:00:44 +02001228 our_tv = eval_expr(expr, NULL);
Bram Moolenaardb913952012-06-29 12:54:53 +02001229 Python_Release_Vim();
1230 Py_END_ALLOW_THREADS
1231
Bram Moolenaar389a1792013-06-23 13:00:44 +02001232 Py_XDECREF(todecref);
1233
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001234 if (VimTryEnd())
1235 return NULL;
1236
Bram Moolenaardb913952012-06-29 12:54:53 +02001237 if (our_tv == NULL)
1238 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001239 PyErr_SET_VIM(N_("invalid expression"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001240 return NULL;
1241 }
1242
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001243 ret = ConvertToPyObject(our_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +02001244 Py_BEGIN_ALLOW_THREADS
1245 Python_Lock_Vim();
1246 free_tv(our_tv);
1247 Python_Release_Vim();
1248 Py_END_ALLOW_THREADS
1249
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001250 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02001251}
1252
1253 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02001254VimStrwidth(PyObject *self UNUSED, PyObject *string)
Bram Moolenaardb913952012-06-29 12:54:53 +02001255{
Bram Moolenaar389a1792013-06-23 13:00:44 +02001256 char_u *str;
1257 PyObject *todecref;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001258 int len;
Bram Moolenaardb913952012-06-29 12:54:53 +02001259
Bram Moolenaar389a1792013-06-23 13:00:44 +02001260 if (!(str = StringToChars(string, &todecref)))
Bram Moolenaardb913952012-06-29 12:54:53 +02001261 return NULL;
1262
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001263 len = mb_string2cells(str, (int)STRLEN(str));
Bram Moolenaar389a1792013-06-23 13:00:44 +02001264
1265 Py_XDECREF(todecref);
1266
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001267 return PyLong_FromLong(len);
Bram Moolenaardb913952012-06-29 12:54:53 +02001268}
1269
Bram Moolenaarf4258302013-06-02 18:20:17 +02001270 static PyObject *
1271_VimChdir(PyObject *_chdir, PyObject *args, PyObject *kwargs)
1272{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001273 PyObject *ret;
Bram Moolenaarf4258302013-06-02 18:20:17 +02001274 PyObject *newwd;
1275 PyObject *todecref;
1276 char_u *new_dir;
1277
Bram Moolenaard4209d22013-06-05 20:34:15 +02001278 if (_chdir == NULL)
1279 return NULL;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001280 if (!(ret = PyObject_Call(_chdir, args, kwargs)))
Bram Moolenaarf4258302013-06-02 18:20:17 +02001281 return NULL;
1282
1283 if (!(newwd = PyObject_CallFunctionObjArgs(py_getcwd, NULL)))
1284 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001285 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001286 return NULL;
1287 }
1288
1289 if (!(new_dir = StringToChars(newwd, &todecref)))
1290 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001291 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001292 Py_DECREF(newwd);
1293 return NULL;
1294 }
1295
1296 VimTryStart();
1297
1298 if (vim_chdir(new_dir))
1299 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001300 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001301 Py_DECREF(newwd);
1302 Py_XDECREF(todecref);
1303
1304 if (VimTryEnd())
1305 return NULL;
1306
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001307 PyErr_SET_VIM(N_("failed to change directory"));
Bram Moolenaarf4258302013-06-02 18:20:17 +02001308 return NULL;
1309 }
1310
1311 Py_DECREF(newwd);
1312 Py_XDECREF(todecref);
1313
Bram Moolenaar1063f3d2019-05-07 22:06:52 +02001314 post_chdir(CDSCOPE_GLOBAL);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001315
1316 if (VimTryEnd())
1317 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001318 Py_DECREF(ret);
Bram Moolenaarf4258302013-06-02 18:20:17 +02001319 return NULL;
1320 }
1321
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001322 return ret;
Bram Moolenaarf4258302013-06-02 18:20:17 +02001323}
1324
1325 static PyObject *
1326VimChdir(PyObject *self UNUSED, PyObject *args, PyObject *kwargs)
1327{
1328 return _VimChdir(py_chdir, args, kwargs);
1329}
1330
1331 static PyObject *
1332VimFchdir(PyObject *self UNUSED, PyObject *args, PyObject *kwargs)
1333{
1334 return _VimChdir(py_fchdir, args, kwargs);
1335}
1336
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001337typedef struct {
1338 PyObject *callable;
1339 PyObject *result;
1340} map_rtp_data;
1341
1342 static void
1343map_rtp_callback(char_u *path, void *_data)
1344{
1345 void **data = (void **) _data;
1346 PyObject *pathObject;
1347 map_rtp_data *mr_data = *((map_rtp_data **) data);
1348
Bram Moolenaar41009372013-07-01 22:03:04 +02001349 if (!(pathObject = PyString_FromString((char *)path)))
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001350 {
1351 *data = NULL;
1352 return;
1353 }
1354
1355 mr_data->result = PyObject_CallFunctionObjArgs(mr_data->callable,
1356 pathObject, NULL);
1357
1358 Py_DECREF(pathObject);
1359
1360 if (!mr_data->result || mr_data->result != Py_None)
1361 *data = NULL;
1362 else
1363 {
1364 Py_DECREF(mr_data->result);
1365 mr_data->result = NULL;
1366 }
1367}
1368
1369 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02001370VimForeachRTP(PyObject *self UNUSED, PyObject *callable)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001371{
1372 map_rtp_data data;
1373
Bram Moolenaar389a1792013-06-23 13:00:44 +02001374 data.callable = callable;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001375 data.result = NULL;
1376
Bram Moolenaar7f8989d2016-03-12 22:11:39 +01001377 do_in_runtimepath(NULL, 0, &map_rtp_callback, &data);
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001378
1379 if (data.result == NULL)
1380 {
1381 if (PyErr_Occurred())
1382 return NULL;
1383 else
1384 {
1385 Py_INCREF(Py_None);
1386 return Py_None;
1387 }
1388 }
1389 return data.result;
1390}
1391
1392/*
1393 * _vim_runtimepath_ special path implementation.
1394 */
1395
1396 static void
1397map_finder_callback(char_u *path, void *_data)
1398{
1399 void **data = (void **) _data;
1400 PyObject *list = *((PyObject **) data);
1401 PyObject *pathObject1, *pathObject2;
1402 char *pathbuf;
1403 size_t pathlen;
1404
1405 pathlen = STRLEN(path);
1406
1407#if PY_MAJOR_VERSION < 3
1408# define PY_MAIN_DIR_STRING "python2"
1409#else
1410# define PY_MAIN_DIR_STRING "python3"
1411#endif
1412#define PY_ALTERNATE_DIR_STRING "pythonx"
1413
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001414#define PYTHONX_STRING_LENGTH 7 // STRLEN("pythonx")
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001415 if (!(pathbuf = PyMem_New(char,
1416 pathlen + STRLEN(PATHSEPSTR) + PYTHONX_STRING_LENGTH + 1)))
1417 {
1418 PyErr_NoMemory();
1419 *data = NULL;
1420 return;
1421 }
1422
1423 mch_memmove(pathbuf, path, pathlen + 1);
1424 add_pathsep((char_u *) pathbuf);
1425
1426 pathlen = STRLEN(pathbuf);
1427 mch_memmove(pathbuf + pathlen, PY_MAIN_DIR_STRING,
1428 PYTHONX_STRING_LENGTH + 1);
1429
1430 if (!(pathObject1 = PyString_FromString(pathbuf)))
1431 {
1432 *data = NULL;
1433 PyMem_Free(pathbuf);
1434 return;
1435 }
1436
1437 mch_memmove(pathbuf + pathlen, PY_ALTERNATE_DIR_STRING,
1438 PYTHONX_STRING_LENGTH + 1);
1439
1440 if (!(pathObject2 = PyString_FromString(pathbuf)))
1441 {
1442 Py_DECREF(pathObject1);
1443 PyMem_Free(pathbuf);
1444 *data = NULL;
1445 return;
1446 }
1447
1448 PyMem_Free(pathbuf);
1449
1450 if (PyList_Append(list, pathObject1)
1451 || PyList_Append(list, pathObject2))
1452 *data = NULL;
1453
1454 Py_DECREF(pathObject1);
1455 Py_DECREF(pathObject2);
1456}
1457
1458 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001459Vim_GetPaths(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001460{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001461 PyObject *ret;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001462
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001463 if (!(ret = PyList_New(0)))
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001464 return NULL;
1465
Bram Moolenaar7f8989d2016-03-12 22:11:39 +01001466 do_in_runtimepath(NULL, 0, &map_finder_callback, ret);
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001467
1468 if (PyErr_Occurred())
1469 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001470 Py_DECREF(ret);
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001471 return NULL;
1472 }
1473
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001474 return ret;
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001475}
1476
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001477#if PY_VERSION_HEX >= 0x030700f0
1478 static PyObject *
1479FinderFindSpec(PyObject *self, PyObject *args)
1480{
1481 char *fullname;
1482 PyObject *paths;
1483 PyObject *target = Py_None;
1484 PyObject *spec;
1485
1486 if (!PyArg_ParseTuple(args, "s|O", &fullname, &target))
1487 return NULL;
1488
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001489 if (!(paths = Vim_GetPaths(self, NULL)))
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001490 return NULL;
1491
Bram Moolenaarde5b3802019-03-30 12:51:22 +01001492 spec = PyObject_CallFunction(py_find_spec, "sOO", fullname, paths, target);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001493
1494 Py_DECREF(paths);
1495
1496 if (!spec)
1497 {
1498 if (PyErr_Occurred())
1499 return NULL;
1500
1501 Py_INCREF(Py_None);
1502 return Py_None;
1503 }
1504
1505 return spec;
1506}
Bram Moolenaar0b0ad352019-05-20 21:52:45 +02001507
1508 static PyObject *
1509FinderFindModule(PyObject* self UNUSED, PyObject* args UNUSED)
1510{
1511 // Apparently returning None works.
1512 Py_INCREF(Py_None);
1513 return Py_None;
1514}
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001515#else
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001516 static PyObject *
1517call_load_module(char *name, int len, PyObject *find_module_result)
1518{
1519 PyObject *fd, *pathname, *description;
1520
Bram Moolenaarc476e522013-06-23 13:46:40 +02001521 if (!PyTuple_Check(find_module_result))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001522 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001523 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001524 N_("expected 3-tuple as imp.find_module() result, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001525 find_module_result);
Bram Moolenaarc476e522013-06-23 13:46:40 +02001526 return NULL;
1527 }
1528 if (PyTuple_GET_SIZE(find_module_result) != 3)
1529 {
1530 PyErr_FORMAT(PyExc_TypeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001531 N_("expected 3-tuple as imp.find_module() result, but got "
1532 "tuple of size %d"),
Bram Moolenaarc476e522013-06-23 13:46:40 +02001533 (int) PyTuple_GET_SIZE(find_module_result));
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001534 return NULL;
1535 }
1536
1537 if (!(fd = PyTuple_GET_ITEM(find_module_result, 0))
1538 || !(pathname = PyTuple_GET_ITEM(find_module_result, 1))
1539 || !(description = PyTuple_GET_ITEM(find_module_result, 2)))
1540 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02001541 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001542 N_("internal error: imp.find_module returned tuple with NULL"));
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001543 return NULL;
1544 }
1545
1546 return PyObject_CallFunction(py_load_module,
1547 "s#OOO", name, len, fd, pathname, description);
1548}
1549
1550 static PyObject *
1551find_module(char *fullname, char *tail, PyObject *new_path)
1552{
1553 PyObject *find_module_result;
1554 PyObject *module;
1555 char *dot;
1556
Bram Moolenaar41009372013-07-01 22:03:04 +02001557 if ((dot = (char *)vim_strchr((char_u *) tail, '.')))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001558 {
1559 /*
Bram Moolenaaredb07a22013-06-12 18:13:38 +02001560 * There is a dot in the name: call find_module recursively without the
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001561 * first component
1562 */
1563 PyObject *newest_path;
1564 int partlen = (int) (dot - 1 - tail);
1565
1566 if (!(find_module_result = PyObject_CallFunction(py_find_module,
1567 "s#O", tail, partlen, new_path)))
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001568 {
1569 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ImportError))
1570 PyErr_Clear();
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001571 return NULL;
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001572 }
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001573
1574 if (!(module = call_load_module(
1575 fullname,
1576 ((int) (tail - fullname)) + partlen,
1577 find_module_result)))
1578 {
1579 Py_DECREF(find_module_result);
1580 return NULL;
1581 }
1582
1583 Py_DECREF(find_module_result);
1584
1585 if (!(newest_path = PyObject_GetAttrString(module, "__path__")))
1586 {
1587 Py_DECREF(module);
1588 return NULL;
1589 }
1590
1591 Py_DECREF(module);
1592
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001593 find_module_result = find_module(fullname, dot + 1, newest_path);
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001594
1595 Py_DECREF(newest_path);
1596
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001597 return find_module_result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001598 }
1599 else
1600 {
1601 if (!(find_module_result = PyObject_CallFunction(py_find_module,
1602 "sO", tail, new_path)))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001603 {
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001604 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_ImportError))
1605 PyErr_Clear();
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001606 return NULL;
1607 }
1608
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001609 return find_module_result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001610 }
1611}
1612
1613 static PyObject *
1614FinderFindModule(PyObject *self, PyObject *args)
1615{
1616 char *fullname;
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001617 PyObject *result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001618 PyObject *new_path;
1619 LoaderObject *loader;
1620
1621 if (!PyArg_ParseTuple(args, "s", &fullname))
1622 return NULL;
1623
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001624 if (!(new_path = Vim_GetPaths(self, NULL)))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001625 return NULL;
1626
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001627 result = find_module(fullname, fullname, new_path);
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001628
1629 Py_DECREF(new_path);
1630
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001631 if (!result)
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001632 {
Bram Moolenaar7e85d3d2013-06-23 16:40:39 +02001633 if (PyErr_Occurred())
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001634 return NULL;
Bram Moolenaar7e85d3d2013-06-23 16:40:39 +02001635
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001636 Py_INCREF(Py_None);
1637 return Py_None;
1638 }
1639
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001640 if (!(fullname = (char *)vim_strsave((char_u *)fullname)))
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001641 {
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001642 Py_DECREF(result);
1643 PyErr_NoMemory();
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001644 return NULL;
1645 }
1646
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001647 if (!(loader = PyObject_NEW(LoaderObject, LoaderTypePtr)))
Bram Moolenaar447bd5a2018-08-07 19:45:27 +02001648 {
1649 vim_free(fullname);
1650 Py_DECREF(result);
1651 return NULL;
1652 }
1653
1654 loader->fullname = fullname;
1655 loader->result = result;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001656
1657 return (PyObject *) loader;
1658}
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001659#endif
Bram Moolenaar81c40c52013-06-12 14:41:04 +02001660
1661 static PyObject *
1662VimPathHook(PyObject *self UNUSED, PyObject *args)
1663{
1664 char *path;
1665
1666 if (PyArg_ParseTuple(args, "s", &path)
1667 && STRCMP(path, vim_special_path) == 0)
1668 {
1669 Py_INCREF(vim_module);
1670 return vim_module;
1671 }
1672
1673 PyErr_Clear();
1674 PyErr_SetNone(PyExc_ImportError);
1675 return NULL;
1676}
1677
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001678/*
1679 * Vim module - Definitions
1680 */
1681
1682static struct PyMethodDef VimMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001683 // name, function, calling, documentation
Bram Moolenaar389a1792013-06-23 13:00:44 +02001684 {"command", VimCommand, METH_O, "Execute a Vim ex-mode command" },
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001685 {"eval", VimEval, METH_VARARGS, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar86181df2020-05-11 23:14:04 +02001686 {"bindeval", VimEvalPy, METH_O, "Like eval(), but returns objects attached to Vim ones"},
Bram Moolenaar389a1792013-06-23 13:00:44 +02001687 {"strwidth", VimStrwidth, METH_O, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001688 {"chdir", (PyCFunction)(void *)VimChdir, METH_VARARGS|METH_KEYWORDS, "Change directory"},
1689 {"fchdir", (PyCFunction)(void *)VimFchdir, METH_VARARGS|METH_KEYWORDS, "Change directory"},
Bram Moolenaar389a1792013-06-23 13:00:44 +02001690 {"foreach_rtp", VimForeachRTP, METH_O, "Call given callable for each path in &rtp"},
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001691#if PY_VERSION_HEX >= 0x030700f0
1692 {"find_spec", FinderFindSpec, METH_VARARGS, "Internal use only, returns spec object for any input it receives"},
Bram Moolenaar79a494d2018-07-22 04:30:21 +02001693#endif
Bram Moolenaar0b0ad352019-05-20 21:52:45 +02001694 {"find_module", FinderFindModule, METH_VARARGS, "Internal use only, returns loader object for any input it receives"},
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02001695 {"path_hook", VimPathHook, METH_VARARGS, "Hook function to install in sys.path_hooks"},
1696 {"_get_paths", (PyCFunction)Vim_GetPaths, METH_NOARGS, "Get &rtp-based additions to sys.path"},
1697 { NULL, NULL, 0, NULL}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001698};
1699
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001700/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001701 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001702 */
1703
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001704DEFINE_PY_TYPE_OBJECT(IterType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001705
1706typedef PyObject *(*nextfun)(void **);
1707typedef void (*destructorfun)(void *);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001708typedef int (*traversefun)(void *, visitproc, void *);
1709typedef int (*clearfun)(void **);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001710
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001711// Main purpose of this object is removing the need for do python
1712// initialization (i.e. PyType_Ready and setting type attributes) for a big
1713// bunch of objects.
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001714typedef struct
1715{
1716 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001717 void *cur;
1718 nextfun next;
1719 destructorfun destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001720 traversefun traverse;
1721 clearfun clear;
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001722 PyObject *iter_object;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001723} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001724
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001725 static PyObject *
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001726IterNew(void *start, destructorfun destruct, nextfun next, traversefun traverse,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001727 clearfun clear, PyObject *iter_object)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001728{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001729 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001730
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001731 self = PyObject_GC_New(IterObject, IterTypePtr);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001732 self->cur = start;
1733 self->next = next;
1734 self->destruct = destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001735 self->traverse = traverse;
1736 self->clear = clear;
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001737 self->iter_object = iter_object;
1738
1739 if (iter_object)
1740 Py_INCREF(iter_object);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001741
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001742 return (PyObject *)(self);
1743}
1744
1745 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001746IterDestructor(PyObject *self_obj)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001747{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001748 IterObject *self = (IterObject*)self_obj;
Bram Moolenaar423a85a2020-08-29 12:57:16 +02001749 if (self->iter_object)
1750 Py_DECREF(self->iter_object);
Bram Moolenaar774267b2013-05-21 20:51:59 +02001751 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaard6e39182013-05-21 18:30:34 +02001752 self->destruct(self->cur);
Bram Moolenaar774267b2013-05-21 20:51:59 +02001753 PyObject_GC_Del((void *)(self));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001754}
1755
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001756 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001757IterTraverse(PyObject *self_obj, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001758{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001759 IterObject *self = (IterObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001760 if (self->traverse != NULL)
1761 return self->traverse(self->cur, visit, arg);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001762 else
1763 return 0;
1764}
1765
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001766// Mac OSX defines clear() somewhere.
Bram Moolenaar9e74e302013-05-17 21:20:17 +02001767#ifdef clear
1768# undef clear
1769#endif
1770
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001771 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001772IterClear(PyObject *self_obj)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001773{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001774 IterObject *self = (IterObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001775 if (self->clear != NULL)
1776 return self->clear(&self->cur);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001777 else
1778 return 0;
1779}
1780
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001781 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001782IterNext(PyObject *self_obj)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001783{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001784 IterObject *self = (IterObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001785 return self->next(&self->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001786}
1787
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001788 static PyObject *
1789IterIter(PyObject *self)
1790{
Bram Moolenaar1bcabe12013-05-29 22:52:32 +02001791 Py_INCREF(self);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001792 return self;
1793}
Bram Moolenaardfa38d42013-05-15 13:38:47 +02001794
Bram Moolenaardb913952012-06-29 12:54:53 +02001795typedef struct pylinkedlist_S {
1796 struct pylinkedlist_S *pll_next;
1797 struct pylinkedlist_S *pll_prev;
1798 PyObject *pll_obj;
1799} pylinkedlist_T;
1800
1801static pylinkedlist_T *lastdict = NULL;
1802static pylinkedlist_T *lastlist = NULL;
Bram Moolenaar8110a092016-04-14 15:56:09 +02001803static pylinkedlist_T *lastfunc = NULL;
Bram Moolenaardb913952012-06-29 12:54:53 +02001804
1805 static void
1806pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
1807{
1808 if (ref->pll_prev == NULL)
1809 {
1810 if (ref->pll_next == NULL)
1811 {
1812 *last = NULL;
1813 return;
1814 }
1815 }
1816 else
1817 ref->pll_prev->pll_next = ref->pll_next;
1818
1819 if (ref->pll_next == NULL)
1820 *last = ref->pll_prev;
1821 else
1822 ref->pll_next->pll_prev = ref->pll_prev;
1823}
1824
1825 static void
1826pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
1827{
1828 if (*last == NULL)
1829 ref->pll_prev = NULL;
1830 else
1831 {
1832 (*last)->pll_next = ref;
1833 ref->pll_prev = *last;
1834 }
1835 ref->pll_next = NULL;
1836 ref->pll_obj = self;
1837 *last = ref;
1838}
1839
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001840DEFINE_PY_TYPE_OBJECT(DictionaryType);
Bram Moolenaardb913952012-06-29 12:54:53 +02001841
1842typedef struct
1843{
1844 PyObject_HEAD
1845 dict_T *dict;
1846 pylinkedlist_T ref;
1847} DictionaryObject;
1848
Bram Moolenaara9922d62013-05-30 13:01:18 +02001849static PyObject *DictionaryUpdate(DictionaryObject *, PyObject *, PyObject *);
1850
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001851#define NEW_DICTIONARY(dict) DictionaryNew(DictionaryTypePtr, dict)
Bram Moolenaara9922d62013-05-30 13:01:18 +02001852
Bram Moolenaardb913952012-06-29 12:54:53 +02001853 static PyObject *
Bram Moolenaara9922d62013-05-30 13:01:18 +02001854DictionaryNew(PyTypeObject *subtype, dict_T *dict)
Bram Moolenaardb913952012-06-29 12:54:53 +02001855{
1856 DictionaryObject *self;
1857
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02001858 self = (DictionaryObject *) Py_TYPE_GET_TP_ALLOC(subtype)(subtype, 0);
Bram Moolenaardb913952012-06-29 12:54:53 +02001859 if (self == NULL)
1860 return NULL;
1861 self->dict = dict;
1862 ++dict->dv_refcount;
1863
1864 pyll_add((PyObject *)(self), &self->ref, &lastdict);
1865
1866 return (PyObject *)(self);
1867}
1868
Bram Moolenaara9922d62013-05-30 13:01:18 +02001869 static dict_T *
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02001870py_dict_alloc(void)
Bram Moolenaara9922d62013-05-30 13:01:18 +02001871{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001872 dict_T *ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001873
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001874 if (!(ret = dict_alloc()))
Bram Moolenaara9922d62013-05-30 13:01:18 +02001875 {
1876 PyErr_NoMemory();
1877 return NULL;
1878 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001879 ++ret->dv_refcount;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001880
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001881 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001882}
1883
1884 static PyObject *
1885DictionaryConstructor(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
1886{
1887 DictionaryObject *self;
1888 dict_T *dict;
1889
1890 if (!(dict = py_dict_alloc()))
1891 return NULL;
1892
1893 self = (DictionaryObject *) DictionaryNew(subtype, dict);
1894
1895 --dict->dv_refcount;
1896
1897 if (kwargs || PyTuple_Size(args))
1898 {
1899 PyObject *tmp;
1900 if (!(tmp = DictionaryUpdate(self, args, kwargs)))
1901 {
1902 Py_DECREF(self);
1903 return NULL;
1904 }
1905
1906 Py_DECREF(tmp);
1907 }
1908
1909 return (PyObject *)(self);
1910}
1911
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001912 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001913DictionaryDestructor(PyObject *self_obj)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001914{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001915 DictionaryObject *self = (DictionaryObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001916 pyll_remove(&self->ref, &lastdict);
1917 dict_unref(self->dict);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001918
1919 DESTRUCTOR_FINISH(self);
1920}
1921
Bram Moolenaardd8aca62013-05-29 22:36:10 +02001922static char *DictionaryAttrs[] = {
1923 "locked", "scope",
1924 NULL
1925};
1926
1927 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02001928DictionaryDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02001929{
1930 return ObjectDir(self, DictionaryAttrs);
1931}
1932
Bram Moolenaardb913952012-06-29 12:54:53 +02001933 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001934DictionarySetattr(PyObject *self_obj, char *name, PyObject *valObject)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001935{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02001936 DictionaryObject *self = (DictionaryObject*)self_obj;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001937 if (valObject == NULL)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001938 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02001939 PyErr_SET_STRING(PyExc_AttributeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001940 N_("cannot delete vim.Dictionary attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001941 return -1;
1942 }
1943
1944 if (strcmp(name, "locked") == 0)
1945 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001946 if (self->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001947 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001948 PyErr_SET_STRING(PyExc_TypeError,
1949 N_("cannot modify fixed dictionary"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001950 return -1;
1951 }
1952 else
1953 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001954 int istrue = PyObject_IsTrue(valObject);
Bram Moolenaarb983f752013-05-15 16:11:50 +02001955 if (istrue == -1)
1956 return -1;
1957 else if (istrue)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001958 self->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001959 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02001960 self->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001961 }
1962 return 0;
1963 }
1964 else
1965 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02001966 PyErr_FORMAT(PyExc_AttributeError, N_("cannot set attribute %s"), name);
Bram Moolenaar66b79852012-09-21 14:00:35 +02001967 return -1;
1968 }
1969}
1970
1971 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02001972DictionaryLength(DictionaryObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +02001973{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001974 return ((PyInt) (self->dict->dv_hashtab.ht_used));
Bram Moolenaardb913952012-06-29 12:54:53 +02001975}
1976
Bram Moolenaara9922d62013-05-30 13:01:18 +02001977#define DICT_FLAG_HAS_DEFAULT 0x01
1978#define DICT_FLAG_POP 0x02
1979#define DICT_FLAG_NONE_DEFAULT 0x04
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01001980#define DICT_FLAG_RETURN_BOOL 0x08 // Incompatible with DICT_FLAG_POP
Bram Moolenaara9922d62013-05-30 13:01:18 +02001981#define DICT_FLAG_RETURN_PAIR 0x10
1982
Bram Moolenaardb913952012-06-29 12:54:53 +02001983 static PyObject *
Bram Moolenaara9922d62013-05-30 13:01:18 +02001984_DictionaryItem(DictionaryObject *self, PyObject *args, int flags)
Bram Moolenaardb913952012-06-29 12:54:53 +02001985{
Bram Moolenaara9922d62013-05-30 13:01:18 +02001986 PyObject *keyObject;
1987 PyObject *defObject = ((flags & DICT_FLAG_NONE_DEFAULT)? Py_None : NULL);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02001988 PyObject *ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02001989 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +02001990 dictitem_T *di;
Bram Moolenaara9922d62013-05-30 13:01:18 +02001991 dict_T *dict = self->dict;
1992 hashitem_T *hi;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02001993 PyObject *todecref;
Bram Moolenaardb913952012-06-29 12:54:53 +02001994
Bram Moolenaara9922d62013-05-30 13:01:18 +02001995 if (flags & DICT_FLAG_HAS_DEFAULT)
1996 {
1997 if (!PyArg_ParseTuple(args, "O|O", &keyObject, &defObject))
1998 return NULL;
1999 }
2000 else
2001 keyObject = args;
2002
2003 if (flags & DICT_FLAG_RETURN_BOOL)
2004 defObject = Py_False;
2005
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002006 if (!(key = StringToChars(keyObject, &todecref)))
2007 return NULL;
2008
2009 if (*key == NUL)
2010 {
2011 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02002012 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002013 return NULL;
2014 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002015
Bram Moolenaara9922d62013-05-30 13:01:18 +02002016 hi = hash_find(&dict->dv_hashtab, key);
Bram Moolenaar231e1a12012-09-05 18:45:28 +02002017
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002018 Py_XDECREF(todecref);
Bram Moolenaar696c2112012-09-21 13:43:14 +02002019
Bram Moolenaara9922d62013-05-30 13:01:18 +02002020 if (HASHITEM_EMPTY(hi))
Bram Moolenaar231e1a12012-09-05 18:45:28 +02002021 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002022 if (defObject)
2023 {
2024 Py_INCREF(defObject);
2025 return defObject;
2026 }
2027 else
2028 {
2029 PyErr_SetObject(PyExc_KeyError, keyObject);
2030 return NULL;
2031 }
2032 }
2033 else if (flags & DICT_FLAG_RETURN_BOOL)
2034 {
Bram Moolenaar0e4eebd2014-02-12 22:08:49 +01002035 ret = Py_True;
2036 Py_INCREF(ret);
2037 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002038 }
2039
2040 di = dict_lookup(hi);
2041
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002042 if (!(ret = ConvertToPyObject(&di->di_tv)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002043 return NULL;
2044
2045 if (flags & DICT_FLAG_POP)
2046 {
2047 if (dict->dv_lock)
2048 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002049 RAISE_LOCKED_DICTIONARY;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002050 Py_DECREF(ret);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002051 return NULL;
2052 }
2053
Bram Moolenaaref2c3252022-11-25 16:31:51 +00002054 hash_remove(&dict->dv_hashtab, hi, "Python remove variable");
Bram Moolenaara9922d62013-05-30 13:01:18 +02002055 dictitem_free(di);
2056 }
2057
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002058 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002059}
2060
2061 static PyObject *
2062DictionaryItem(DictionaryObject *self, PyObject *keyObject)
2063{
2064 return _DictionaryItem(self, keyObject, 0);
2065}
2066
2067 static int
2068DictionaryContains(DictionaryObject *self, PyObject *keyObject)
2069{
2070 PyObject *rObj = _DictionaryItem(self, keyObject, DICT_FLAG_RETURN_BOOL);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002071 int ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002072
Bram Moolenaarba2d7ff2013-11-04 00:34:53 +01002073 if (rObj == NULL)
2074 return -1;
2075
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002076 ret = (rObj == Py_True);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002077
Bram Moolenaardee2e312013-06-23 16:35:47 +02002078 Py_DECREF(rObj);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002079
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002080 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002081}
2082
2083typedef struct
2084{
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002085 int dii_changed;
2086 hashtab_T *dii_ht;
2087 hashitem_T *dii_hi;
2088 long_u dii_todo;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002089} dictiterinfo_T;
2090
2091 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02002092DictionaryIterNext(void **arg)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002093{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002094 PyObject *ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02002095 dictiterinfo_T **dii = (dictiterinfo_T**)arg;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002096
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002097 if (!(*dii)->dii_todo)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002098 return NULL;
2099
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002100 if ((*dii)->dii_ht->ht_changed != (*dii)->dii_changed)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002101 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02002102 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002103 N_("hashtab changed during iteration"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +02002104 return NULL;
2105 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002106
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002107 while (((*dii)->dii_todo) && HASHITEM_EMPTY((*dii)->dii_hi))
2108 ++((*dii)->dii_hi);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002109
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002110 --((*dii)->dii_todo);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002111
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002112 if (!(ret = PyBytes_FromString((char *)(*dii)->dii_hi->hi_key)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002113 return NULL;
2114
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002115 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002116}
2117
2118 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02002119DictionaryIter(PyObject *self_obj)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002120{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02002121 DictionaryObject *self = (DictionaryObject*)self_obj;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002122 dictiterinfo_T *dii;
2123 hashtab_T *ht;
2124
2125 if (!(dii = PyMem_New(dictiterinfo_T, 1)))
2126 {
2127 PyErr_NoMemory();
2128 return NULL;
2129 }
2130
2131 ht = &self->dict->dv_hashtab;
Bram Moolenaar1f22cc52020-07-14 21:08:49 +02002132 dii->dii_changed = ht->ht_changed;
2133 dii->dii_ht = ht;
2134 dii->dii_hi = ht->ht_array;
2135 dii->dii_todo = ht->ht_used;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002136
2137 return IterNew(dii,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02002138 PyMem_Free, DictionaryIterNext,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02002139 NULL, NULL, (PyObject *)self);
Bram Moolenaardb913952012-06-29 12:54:53 +02002140}
2141
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002142 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02002143DictionaryAssItem(
2144 DictionaryObject *self, PyObject *keyObject, PyObject *valObject)
Bram Moolenaardb913952012-06-29 12:54:53 +02002145{
2146 char_u *key;
2147 typval_T tv;
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002148 dict_T *dict = self->dict;
Bram Moolenaardb913952012-06-29 12:54:53 +02002149 dictitem_T *di;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002150 PyObject *todecref;
Bram Moolenaardb913952012-06-29 12:54:53 +02002151
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002152 if (dict->dv_lock)
Bram Moolenaardb913952012-06-29 12:54:53 +02002153 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002154 RAISE_LOCKED_DICTIONARY;
Bram Moolenaardb913952012-06-29 12:54:53 +02002155 return -1;
2156 }
2157
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002158 if (!(key = StringToChars(keyObject, &todecref)))
2159 return -1;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02002160
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002161 if (*key == NUL)
2162 {
2163 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar78b59572013-06-02 18:54:21 +02002164 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002165 return -1;
2166 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002167
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002168 di = dict_find(dict, key, -1);
Bram Moolenaardb913952012-06-29 12:54:53 +02002169
2170 if (valObject == NULL)
2171 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +02002172 hashitem_T *hi;
2173
Bram Moolenaardb913952012-06-29 12:54:53 +02002174 if (di == NULL)
2175 {
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002176 Py_XDECREF(todecref);
Bram Moolenaar4d188da2013-05-15 15:35:09 +02002177 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaardb913952012-06-29 12:54:53 +02002178 return -1;
2179 }
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002180 hi = hash_find(&dict->dv_hashtab, di->di_key);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00002181 hash_remove(&dict->dv_hashtab, hi, "Python remove item");
Bram Moolenaardb913952012-06-29 12:54:53 +02002182 dictitem_free(di);
Bram Moolenaar78b59572013-06-02 18:54:21 +02002183 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002184 return 0;
2185 }
2186
2187 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaar78b59572013-06-02 18:54:21 +02002188 {
2189 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002190 return -1;
Bram Moolenaar78b59572013-06-02 18:54:21 +02002191 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002192
2193 if (di == NULL)
2194 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002195 if (!(di = dictitem_alloc(key)))
Bram Moolenaardb913952012-06-29 12:54:53 +02002196 {
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002197 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002198 PyErr_NoMemory();
2199 return -1;
2200 }
Bram Moolenaara9922d62013-05-30 13:01:18 +02002201 di->di_tv.v_type = VAR_UNKNOWN;
Bram Moolenaardb913952012-06-29 12:54:53 +02002202
Bram Moolenaarb38caae2013-05-29 22:39:52 +02002203 if (dict_add(dict, di) == FAIL)
Bram Moolenaardb913952012-06-29 12:54:53 +02002204 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002205 dictitem_free(di);
Bram Moolenaarc476e522013-06-23 13:46:40 +02002206 RAISE_KEY_ADD_FAIL(key);
2207 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002208 return -1;
2209 }
2210 }
2211 else
2212 clear_tv(&di->di_tv);
2213
Bram Moolenaar35eacd72013-05-30 22:06:33 +02002214 Py_XDECREF(todecref);
Bram Moolenaardb913952012-06-29 12:54:53 +02002215
2216 copy_tv(&tv, &di->di_tv);
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02002217 clear_tv(&tv);
Bram Moolenaardb913952012-06-29 12:54:53 +02002218 return 0;
2219}
2220
Bram Moolenaara9922d62013-05-30 13:01:18 +02002221typedef PyObject *(*hi_to_py)(hashitem_T *);
2222
Bram Moolenaardb913952012-06-29 12:54:53 +02002223 static PyObject *
Bram Moolenaara9922d62013-05-30 13:01:18 +02002224DictionaryListObjects(DictionaryObject *self, hi_to_py hiconvert)
Bram Moolenaardb913952012-06-29 12:54:53 +02002225{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002226 dict_T *dict = self->dict;
Bram Moolenaardb913952012-06-29 12:54:53 +02002227 long_u todo = dict->dv_hashtab.ht_used;
2228 Py_ssize_t i = 0;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002229 PyObject *ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02002230 hashitem_T *hi;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002231 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +02002232
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002233 ret = PyList_New(todo);
Bram Moolenaardb913952012-06-29 12:54:53 +02002234 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
2235 {
2236 if (!HASHITEM_EMPTY(hi))
2237 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02002238 if (!(newObj = hiconvert(hi)))
2239 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002240 Py_DECREF(ret);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002241 return NULL;
2242 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002243 PyList_SET_ITEM(ret, i, newObj);
Bram Moolenaardb913952012-06-29 12:54:53 +02002244 --todo;
2245 ++i;
2246 }
2247 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002248 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02002249}
2250
Bram Moolenaara9922d62013-05-30 13:01:18 +02002251 static PyObject *
2252dict_key(hashitem_T *hi)
2253{
2254 return PyBytes_FromString((char *)(hi->hi_key));
2255}
2256
2257 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002258DictionaryListKeys(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002259{
2260 return DictionaryListObjects(self, dict_key);
2261}
2262
2263 static PyObject *
2264dict_val(hashitem_T *hi)
2265{
2266 dictitem_T *di;
2267
2268 di = dict_lookup(hi);
2269 return ConvertToPyObject(&di->di_tv);
2270}
2271
2272 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002273DictionaryListValues(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002274{
2275 return DictionaryListObjects(self, dict_val);
2276}
2277
2278 static PyObject *
2279dict_item(hashitem_T *hi)
2280{
2281 PyObject *keyObject;
2282 PyObject *valObject;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002283 PyObject *ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002284
2285 if (!(keyObject = dict_key(hi)))
2286 return NULL;
2287
2288 if (!(valObject = dict_val(hi)))
2289 {
2290 Py_DECREF(keyObject);
2291 return NULL;
2292 }
2293
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002294 ret = Py_BuildValue("(OO)", keyObject, valObject);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002295
2296 Py_DECREF(keyObject);
2297 Py_DECREF(valObject);
2298
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002299 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002300}
2301
2302 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002303DictionaryListItems(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002304{
2305 return DictionaryListObjects(self, dict_item);
2306}
2307
2308 static PyObject *
2309DictionaryUpdate(DictionaryObject *self, PyObject *args, PyObject *kwargs)
2310{
2311 dict_T *dict = self->dict;
2312
2313 if (dict->dv_lock)
2314 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002315 RAISE_LOCKED_DICTIONARY;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002316 return NULL;
2317 }
2318
2319 if (kwargs)
2320 {
2321 typval_T tv;
2322
2323 if (ConvertFromPyMapping(kwargs, &tv) == -1)
2324 return NULL;
2325
2326 VimTryStart();
Bram Moolenaar7a3fe3e2021-07-22 14:58:47 +02002327 dict_extend(self->dict, tv.vval.v_dict, (char_u *) "force", NULL);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002328 clear_tv(&tv);
2329 if (VimTryEnd())
2330 return NULL;
2331 }
2332 else
2333 {
Bram Moolenaar2d5f38f2014-02-11 18:47:27 +01002334 PyObject *obj = NULL;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002335
Bram Moolenaar2d5f38f2014-02-11 18:47:27 +01002336 if (!PyArg_ParseTuple(args, "|O", &obj))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002337 return NULL;
2338
Bram Moolenaar2d5f38f2014-02-11 18:47:27 +01002339 if (obj == NULL)
2340 {
2341 Py_INCREF(Py_None);
2342 return Py_None;
2343 }
2344
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002345 if (PyObject_HasAttrString(obj, "keys"))
2346 return DictionaryUpdate(self, NULL, obj);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002347 else
2348 {
2349 PyObject *iterator;
2350 PyObject *item;
2351
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002352 if (!(iterator = PyObject_GetIter(obj)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002353 return NULL;
2354
2355 while ((item = PyIter_Next(iterator)))
2356 {
2357 PyObject *fast;
2358 PyObject *keyObject;
2359 PyObject *valObject;
2360 PyObject *todecref;
2361 char_u *key;
2362 dictitem_T *di;
Bram Moolenaar9ed7d342017-11-09 22:10:33 +01002363 hashitem_T *hi;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002364
2365 if (!(fast = PySequence_Fast(item, "")))
2366 {
2367 Py_DECREF(iterator);
2368 Py_DECREF(item);
2369 return NULL;
2370 }
2371
2372 Py_DECREF(item);
2373
2374 if (PySequence_Fast_GET_SIZE(fast) != 2)
2375 {
2376 Py_DECREF(iterator);
2377 Py_DECREF(fast);
Bram Moolenaarc476e522013-06-23 13:46:40 +02002378 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002379 N_("expected sequence element of size 2, "
2380 "but got sequence of size %d"),
Bram Moolenaardee2e312013-06-23 16:35:47 +02002381 (int) PySequence_Fast_GET_SIZE(fast));
Bram Moolenaara9922d62013-05-30 13:01:18 +02002382 return NULL;
2383 }
2384
2385 keyObject = PySequence_Fast_GET_ITEM(fast, 0);
2386
2387 if (!(key = StringToChars(keyObject, &todecref)))
2388 {
2389 Py_DECREF(iterator);
2390 Py_DECREF(fast);
2391 return NULL;
2392 }
2393
2394 di = dictitem_alloc(key);
2395
2396 Py_XDECREF(todecref);
2397
2398 if (di == NULL)
2399 {
2400 Py_DECREF(fast);
2401 Py_DECREF(iterator);
2402 PyErr_NoMemory();
2403 return NULL;
2404 }
Bram Moolenaara9922d62013-05-30 13:01:18 +02002405 di->di_tv.v_type = VAR_UNKNOWN;
2406
2407 valObject = PySequence_Fast_GET_ITEM(fast, 1);
2408
2409 if (ConvertFromPyObject(valObject, &di->di_tv) == -1)
2410 {
2411 Py_DECREF(iterator);
2412 Py_DECREF(fast);
2413 dictitem_free(di);
2414 return NULL;
2415 }
2416
2417 Py_DECREF(fast);
2418
Bram Moolenaar9ed7d342017-11-09 22:10:33 +01002419 hi = hash_find(&dict->dv_hashtab, di->di_key);
2420 if (!HASHITEM_EMPTY(hi) || dict_add(dict, di) == FAIL)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002421 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02002422 RAISE_KEY_ADD_FAIL(di->di_key);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002423 Py_DECREF(iterator);
2424 dictitem_free(di);
Bram Moolenaara9922d62013-05-30 13:01:18 +02002425 return NULL;
2426 }
2427 }
2428
2429 Py_DECREF(iterator);
2430
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002431 // Iterator may have finished due to an exception
Bram Moolenaara9922d62013-05-30 13:01:18 +02002432 if (PyErr_Occurred())
2433 return NULL;
2434 }
2435 }
2436 Py_INCREF(Py_None);
2437 return Py_None;
2438}
2439
2440 static PyObject *
2441DictionaryGet(DictionaryObject *self, PyObject *args)
2442{
2443 return _DictionaryItem(self, args,
2444 DICT_FLAG_HAS_DEFAULT|DICT_FLAG_NONE_DEFAULT);
2445}
2446
2447 static PyObject *
2448DictionaryPop(DictionaryObject *self, PyObject *args)
2449{
2450 return _DictionaryItem(self, args, DICT_FLAG_HAS_DEFAULT|DICT_FLAG_POP);
2451}
2452
2453 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002454DictionaryPopItem(DictionaryObject *self, PyObject *args UNUSED)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002455{
Bram Moolenaarde71b562013-06-02 17:41:54 +02002456 hashitem_T *hi;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002457 PyObject *ret;
Bram Moolenaarde71b562013-06-02 17:41:54 +02002458 PyObject *valObject;
2459 dictitem_T *di;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002460
Bram Moolenaarde71b562013-06-02 17:41:54 +02002461 if (self->dict->dv_hashtab.ht_used == 0)
2462 {
2463 PyErr_SetNone(PyExc_KeyError);
2464 return NULL;
2465 }
2466
2467 hi = self->dict->dv_hashtab.ht_array;
2468 while (HASHITEM_EMPTY(hi))
2469 ++hi;
2470
2471 di = dict_lookup(hi);
2472
2473 if (!(valObject = ConvertToPyObject(&di->di_tv)))
Bram Moolenaara9922d62013-05-30 13:01:18 +02002474 return NULL;
2475
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002476 if (!(ret = Py_BuildValue("(" Py_bytes_fmt "O)", hi->hi_key, valObject)))
Bram Moolenaarde71b562013-06-02 17:41:54 +02002477 {
2478 Py_DECREF(valObject);
2479 return NULL;
2480 }
2481
Bram Moolenaaref2c3252022-11-25 16:31:51 +00002482 hash_remove(&self->dict->dv_hashtab, hi, "Python pop item");
Bram Moolenaarde71b562013-06-02 17:41:54 +02002483 dictitem_free(di);
2484
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002485 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02002486}
2487
2488 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02002489DictionaryHasKey(DictionaryObject *self, PyObject *keyObject)
Bram Moolenaara9922d62013-05-30 13:01:18 +02002490{
Bram Moolenaara9922d62013-05-30 13:01:18 +02002491 return _DictionaryItem(self, keyObject, DICT_FLAG_RETURN_BOOL);
2492}
2493
2494static PySequenceMethods DictionaryAsSeq = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002495 0, // sq_length
2496 0, // sq_concat
2497 0, // sq_repeat
2498 0, // sq_item
2499 0, // sq_slice
2500 0, // sq_ass_item
2501 0, // sq_ass_slice
2502 (objobjproc) DictionaryContains, // sq_contains
2503 0, // sq_inplace_concat
2504 0, // sq_inplace_repeat
Bram Moolenaara9922d62013-05-30 13:01:18 +02002505};
2506
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002507static PyMappingMethods DictionaryAsMapping = {
2508 (lenfunc) DictionaryLength,
2509 (binaryfunc) DictionaryItem,
2510 (objobjargproc) DictionaryAssItem,
2511};
2512
Bram Moolenaardb913952012-06-29 12:54:53 +02002513static struct PyMethodDef DictionaryMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02002514 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
Bram Moolenaara9922d62013-05-30 13:01:18 +02002515 {"values", (PyCFunction)DictionaryListValues, METH_NOARGS, ""},
2516 {"items", (PyCFunction)DictionaryListItems, METH_NOARGS, ""},
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02002517 {"update", (PyCFunction)(void *)DictionaryUpdate, METH_VARARGS|METH_KEYWORDS, ""},
Bram Moolenaara9922d62013-05-30 13:01:18 +02002518 {"get", (PyCFunction)DictionaryGet, METH_VARARGS, ""},
2519 {"pop", (PyCFunction)DictionaryPop, METH_VARARGS, ""},
Bram Moolenaarde71b562013-06-02 17:41:54 +02002520 {"popitem", (PyCFunction)DictionaryPopItem, METH_NOARGS, ""},
Bram Moolenaar389a1792013-06-23 13:00:44 +02002521 {"has_key", (PyCFunction)DictionaryHasKey, METH_O, ""},
Bram Moolenaardd8aca62013-05-29 22:36:10 +02002522 {"__dir__", (PyCFunction)DictionaryDir, METH_NOARGS, ""},
2523 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02002524};
2525
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02002526DEFINE_PY_TYPE_OBJECT(ListType);
Bram Moolenaardb913952012-06-29 12:54:53 +02002527
2528typedef struct
2529{
2530 PyObject_HEAD
2531 list_T *list;
2532 pylinkedlist_T ref;
2533} ListObject;
2534
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02002535#define NEW_LIST(list) ListNew(ListTypePtr, list)
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002536
Bram Moolenaardb913952012-06-29 12:54:53 +02002537 static PyObject *
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002538ListNew(PyTypeObject *subtype, list_T *list)
Bram Moolenaardb913952012-06-29 12:54:53 +02002539{
2540 ListObject *self;
2541
Bram Moolenaarab589462020-07-06 21:03:06 +02002542 if (list == NULL)
2543 return NULL;
2544
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02002545 self = (ListObject *) Py_TYPE_GET_TP_ALLOC(subtype)(subtype, 0);
Bram Moolenaardb913952012-06-29 12:54:53 +02002546 if (self == NULL)
2547 return NULL;
2548 self->list = list;
2549 ++list->lv_refcount;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002550 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaardb913952012-06-29 12:54:53 +02002551
2552 pyll_add((PyObject *)(self), &self->ref, &lastlist);
2553
2554 return (PyObject *)(self);
2555}
2556
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002557 static list_T *
Bram Moolenaarfb97f282013-07-09 17:42:46 +02002558py_list_alloc(void)
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002559{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002560 list_T *ret;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002561
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002562 if (!(ret = list_alloc()))
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002563 {
2564 PyErr_NoMemory();
2565 return NULL;
2566 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002567 ++ret->lv_refcount;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002568
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02002569 return ret;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002570}
2571
2572 static int
2573list_py_concat(list_T *l, PyObject *obj, PyObject *lookup_dict)
2574{
2575 PyObject *iterator;
2576 PyObject *item;
2577 listitem_T *li;
2578
2579 if (!(iterator = PyObject_GetIter(obj)))
2580 return -1;
2581
2582 while ((item = PyIter_Next(iterator)))
2583 {
2584 if (!(li = listitem_alloc()))
2585 {
2586 PyErr_NoMemory();
2587 Py_DECREF(item);
2588 Py_DECREF(iterator);
2589 return -1;
2590 }
2591 li->li_tv.v_lock = 0;
2592 li->li_tv.v_type = VAR_UNKNOWN;
2593
2594 if (_ConvertFromPyObject(item, &li->li_tv, lookup_dict) == -1)
2595 {
2596 Py_DECREF(item);
2597 Py_DECREF(iterator);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002598 listitem_free(l, li);
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002599 return -1;
2600 }
2601
2602 Py_DECREF(item);
2603
2604 list_append(l, li);
2605 }
2606
2607 Py_DECREF(iterator);
2608
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002609 // Iterator may have finished due to an exception
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002610 if (PyErr_Occurred())
2611 return -1;
2612
2613 return 0;
2614}
2615
2616 static PyObject *
2617ListConstructor(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
2618{
2619 list_T *list;
2620 PyObject *obj = NULL;
2621
2622 if (kwargs)
2623 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02002624 PyErr_SET_STRING(PyExc_TypeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002625 N_("list constructor does not accept keyword arguments"));
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02002626 return NULL;
2627 }
2628
2629 if (!PyArg_ParseTuple(args, "|O", &obj))
2630 return NULL;
2631
2632 if (!(list = py_list_alloc()))
2633 return NULL;
2634
2635 if (obj)
2636 {
2637 PyObject *lookup_dict;
2638
2639 if (!(lookup_dict = PyDict_New()))
2640 {
2641 list_unref(list);
2642 return NULL;
2643 }
2644
2645 if (list_py_concat(list, obj, lookup_dict) == -1)
2646 {
2647 Py_DECREF(lookup_dict);
2648 list_unref(list);
2649 return NULL;
2650 }
2651
2652 Py_DECREF(lookup_dict);
2653 }
2654
2655 return ListNew(subtype, list);
2656}
2657
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002658 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02002659ListDestructor(PyObject *self_obj)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002660{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02002661 ListObject *self = (ListObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02002662 pyll_remove(&self->ref, &lastlist);
2663 list_unref(self->list);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002664
2665 DESTRUCTOR_FINISH(self);
2666}
2667
Bram Moolenaardb913952012-06-29 12:54:53 +02002668 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02002669ListLength(ListObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +02002670{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002671 return ((PyInt) (self->list->lv_len));
Bram Moolenaardb913952012-06-29 12:54:53 +02002672}
2673
2674 static PyObject *
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002675ListIndex(ListObject *self, Py_ssize_t index)
Bram Moolenaardb913952012-06-29 12:54:53 +02002676{
2677 listitem_T *li;
2678
Bram Moolenaard6e39182013-05-21 18:30:34 +02002679 if (index >= ListLength(self))
Bram Moolenaardb913952012-06-29 12:54:53 +02002680 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02002681 PyErr_SET_STRING(PyExc_IndexError, N_("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +02002682 return NULL;
2683 }
Bram Moolenaard6e39182013-05-21 18:30:34 +02002684 li = list_find(self->list, (long) index);
Bram Moolenaardb913952012-06-29 12:54:53 +02002685 if (li == NULL)
2686 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002687 // No more suitable format specifications in python-2.3
Bram Moolenaar86181df2020-05-11 23:14:04 +02002688 PyErr_VIM_FORMAT(N_("internal error: failed to get Vim list item %d"),
Bram Moolenaarc476e522013-06-23 13:46:40 +02002689 (int) index);
Bram Moolenaardb913952012-06-29 12:54:53 +02002690 return NULL;
2691 }
2692 return ConvertToPyObject(&li->li_tv);
2693}
2694
Bram Moolenaardb913952012-06-29 12:54:53 +02002695 static PyObject *
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002696ListSlice(ListObject *self, Py_ssize_t first, Py_ssize_t step,
2697 Py_ssize_t slicelen)
Bram Moolenaardb913952012-06-29 12:54:53 +02002698{
2699 PyInt i;
Bram Moolenaardb913952012-06-29 12:54:53 +02002700 PyObject *list;
Bram Moolenaardb913952012-06-29 12:54:53 +02002701
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002702 if (step == 0)
2703 {
2704 PyErr_SET_STRING(PyExc_ValueError, N_("slice step cannot be zero"));
2705 return NULL;
2706 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002707
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002708 list = PyList_New(slicelen);
Bram Moolenaardb913952012-06-29 12:54:53 +02002709 if (list == NULL)
2710 return NULL;
2711
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002712 for (i = 0; i < slicelen; ++i)
Bram Moolenaardb913952012-06-29 12:54:53 +02002713 {
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002714 PyObject *item;
2715
2716 item = ListIndex(self, first + i*step);
Bram Moolenaardb913952012-06-29 12:54:53 +02002717 if (item == NULL)
2718 {
2719 Py_DECREF(list);
2720 return NULL;
2721 }
2722
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002723 PyList_SET_ITEM(list, i, item);
Bram Moolenaardb913952012-06-29 12:54:53 +02002724 }
2725
2726 return list;
2727}
2728
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002729 static PyObject *
2730ListItem(ListObject *self, PyObject* idx)
2731{
2732#if PY_MAJOR_VERSION < 3
2733 if (PyInt_Check(idx))
2734 {
2735 long _idx = PyInt_AsLong(idx);
2736 return ListIndex(self, _idx);
2737 }
2738 else
2739#endif
2740 if (PyLong_Check(idx))
2741 {
2742 long _idx = PyLong_AsLong(idx);
2743 return ListIndex(self, _idx);
2744 }
2745 else if (PySlice_Check(idx))
2746 {
2747 Py_ssize_t start, stop, step, slicelen;
2748
Bram Moolenaar922a4662014-03-30 16:11:43 +02002749 if (PySlice_GetIndicesEx((PySliceObject_T *)idx, ListLength(self),
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002750 &start, &stop, &step, &slicelen) < 0)
2751 return NULL;
2752 return ListSlice(self, start, step, slicelen);
2753 }
2754 else
2755 {
2756 RAISE_INVALID_INDEX_TYPE(idx);
2757 return NULL;
2758 }
2759}
2760
2761 static void
2762list_restore(Py_ssize_t numadded, Py_ssize_t numreplaced, Py_ssize_t slicelen,
2763 list_T *l, listitem_T **lis, listitem_T *lastaddedli)
2764{
2765 while (numreplaced--)
2766 {
2767 list_insert(l, lis[numreplaced], lis[slicelen + numreplaced]);
2768 listitem_remove(l, lis[slicelen + numreplaced]);
2769 }
2770 while (numadded--)
2771 {
2772 listitem_T *next;
2773
2774 next = lastaddedli->li_prev;
2775 listitem_remove(l, lastaddedli);
2776 lastaddedli = next;
2777 }
2778}
2779
2780 static int
2781ListAssSlice(ListObject *self, Py_ssize_t first,
2782 Py_ssize_t step, Py_ssize_t slicelen, PyObject *obj)
2783{
2784 PyObject *iterator;
2785 PyObject *item;
2786 listitem_T *li;
2787 listitem_T *lastaddedli = NULL;
2788 listitem_T *next;
2789 typval_T v;
2790 list_T *l = self->list;
2791 PyInt i;
2792 PyInt j;
2793 PyInt numreplaced = 0;
2794 PyInt numadded = 0;
2795 PyInt size;
Bram Moolenaar3b522612014-02-11 16:00:35 +01002796 listitem_T **lis = NULL;
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002797
2798 size = ListLength(self);
2799
2800 if (l->lv_lock)
2801 {
2802 RAISE_LOCKED_LIST;
2803 return -1;
2804 }
2805
2806 if (step == 0)
2807 {
2808 PyErr_SET_STRING(PyExc_ValueError, N_("slice step cannot be zero"));
2809 return -1;
2810 }
2811
2812 if (step != 1 && slicelen == 0)
2813 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002814 // Nothing to do. Only error out if obj has some items.
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002815 int ret = 0;
2816
2817 if (obj == NULL)
2818 return 0;
2819
2820 if (!(iterator = PyObject_GetIter(obj)))
2821 return -1;
2822
2823 if ((item = PyIter_Next(iterator)))
2824 {
2825 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar4de6a212014-03-08 16:13:44 +01002826 N_("attempt to assign sequence of size greater than %d "
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002827 "to extended slice"), 0);
2828 Py_DECREF(item);
2829 ret = -1;
2830 }
2831 Py_DECREF(iterator);
2832 return ret;
2833 }
2834
2835 if (obj != NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01002836 // XXX May allocate zero bytes.
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002837 if (!(lis = PyMem_New(listitem_T *, slicelen * 2)))
2838 {
2839 PyErr_NoMemory();
2840 return -1;
2841 }
2842
2843 if (first == size)
2844 li = NULL;
2845 else
2846 {
2847 li = list_find(l, (long) first);
2848 if (li == NULL)
2849 {
Bram Moolenaar86181df2020-05-11 23:14:04 +02002850 PyErr_VIM_FORMAT(N_("internal error: no Vim list item %d"),
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002851 (int)first);
2852 if (obj != NULL)
2853 PyMem_Free(lis);
2854 return -1;
2855 }
2856 i = slicelen;
2857 while (i-- && li != NULL)
2858 {
2859 j = step;
2860 next = li;
2861 if (step > 0)
2862 while (next != NULL && ((next = next->li_next) != NULL) && --j);
2863 else
2864 while (next != NULL && ((next = next->li_prev) != NULL) && ++j);
2865
2866 if (obj == NULL)
2867 listitem_remove(l, li);
2868 else
2869 lis[slicelen - i - 1] = li;
2870
2871 li = next;
2872 }
2873 if (li == NULL && i != -1)
2874 {
2875 PyErr_SET_VIM(N_("internal error: not enough list items"));
2876 if (obj != NULL)
2877 PyMem_Free(lis);
2878 return -1;
2879 }
2880 }
2881
2882 if (obj == NULL)
2883 return 0;
2884
2885 if (!(iterator = PyObject_GetIter(obj)))
2886 {
2887 PyMem_Free(lis);
2888 return -1;
2889 }
2890
2891 i = 0;
2892 while ((item = PyIter_Next(iterator)))
2893 {
2894 if (ConvertFromPyObject(item, &v) == -1)
2895 {
2896 Py_DECREF(iterator);
2897 Py_DECREF(item);
2898 PyMem_Free(lis);
2899 return -1;
2900 }
2901 Py_DECREF(item);
2902 if (list_insert_tv(l, &v, numreplaced < slicelen
2903 ? lis[numreplaced]
2904 : li) == FAIL)
2905 {
2906 clear_tv(&v);
2907 PyErr_SET_VIM(N_("internal error: failed to add item to list"));
2908 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2909 PyMem_Free(lis);
2910 return -1;
2911 }
2912 if (numreplaced < slicelen)
2913 {
2914 lis[slicelen + numreplaced] = lis[numreplaced]->li_prev;
Bram Moolenaar3ec7f4e2014-05-07 17:31:37 +02002915 vimlist_remove(l, lis[numreplaced], lis[numreplaced]);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002916 numreplaced++;
2917 }
2918 else
2919 {
2920 if (li)
2921 lastaddedli = li->li_prev;
2922 else
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01002923 lastaddedli = l->lv_u.mat.lv_last;
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002924 numadded++;
2925 }
2926 clear_tv(&v);
2927 if (step != 1 && i >= slicelen)
2928 {
2929 Py_DECREF(iterator);
2930 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar4de6a212014-03-08 16:13:44 +01002931 N_("attempt to assign sequence of size greater than %d "
Bram Moolenaar403b3cf2014-02-15 15:59:03 +01002932 "to extended slice"), (int) slicelen);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002933 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2934 PyMem_Free(lis);
2935 return -1;
2936 }
2937 ++i;
2938 }
2939 Py_DECREF(iterator);
2940
2941 if (step != 1 && i != slicelen)
2942 {
2943 PyErr_FORMAT2(PyExc_ValueError,
Bram Moolenaar403b3cf2014-02-15 15:59:03 +01002944 N_("attempt to assign sequence of size %d to extended slice "
2945 "of size %d"), (int) i, (int) slicelen);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002946 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2947 PyMem_Free(lis);
2948 return -1;
2949 }
2950
2951 if (PyErr_Occurred())
2952 {
2953 list_restore(numadded, numreplaced, slicelen, l, lis, lastaddedli);
2954 PyMem_Free(lis);
2955 return -1;
2956 }
2957
2958 for (i = 0; i < numreplaced; i++)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002959 listitem_free(l, lis[i]);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002960 if (step == 1)
2961 for (i = numreplaced; i < slicelen; i++)
2962 listitem_remove(l, lis[i]);
2963
2964 PyMem_Free(lis);
2965
2966 return 0;
2967}
2968
2969 static int
2970ListAssIndex(ListObject *self, Py_ssize_t index, PyObject *obj)
2971{
2972 typval_T tv;
2973 list_T *l = self->list;
2974 listitem_T *li;
2975 Py_ssize_t length = ListLength(self);
2976
2977 if (l->lv_lock)
2978 {
2979 RAISE_LOCKED_LIST;
2980 return -1;
2981 }
2982 if (index > length || (index == length && obj == NULL))
2983 {
2984 PyErr_SET_STRING(PyExc_IndexError, N_("list index out of range"));
2985 return -1;
2986 }
2987
2988 if (obj == NULL)
2989 {
2990 li = list_find(l, (long) index);
Bram Moolenaarab589462020-07-06 21:03:06 +02002991 if (li == NULL)
2992 {
2993 PyErr_VIM_FORMAT(N_("internal error: failed to get Vim "
2994 "list item %d"), (int) index);
2995 return -1;
2996 }
Bram Moolenaar3ec7f4e2014-05-07 17:31:37 +02002997 vimlist_remove(l, li, li);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01002998 clear_tv(&li->li_tv);
2999 vim_free(li);
3000 return 0;
3001 }
3002
3003 if (ConvertFromPyObject(obj, &tv) == -1)
3004 return -1;
3005
3006 if (index == length)
3007 {
3008 if (list_append_tv(l, &tv) == FAIL)
3009 {
3010 clear_tv(&tv);
3011 PyErr_SET_VIM(N_("failed to add item to list"));
3012 return -1;
3013 }
3014 }
3015 else
3016 {
3017 li = list_find(l, (long) index);
Bram Moolenaarab589462020-07-06 21:03:06 +02003018 if (li == NULL)
3019 {
3020 PyErr_VIM_FORMAT(N_("internal error: failed to get Vim "
3021 "list item %d"), (int) index);
3022 return -1;
3023 }
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003024 clear_tv(&li->li_tv);
3025 copy_tv(&tv, &li->li_tv);
3026 clear_tv(&tv);
3027 }
3028 return 0;
3029}
3030
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003031 static int
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003032ListAssItem(ListObject *self, PyObject *idx, PyObject *obj)
3033{
3034#if PY_MAJOR_VERSION < 3
3035 if (PyInt_Check(idx))
3036 {
3037 long _idx = PyInt_AsLong(idx);
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003038 return (int)ListAssIndex(self, _idx, obj);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003039 }
3040 else
3041#endif
3042 if (PyLong_Check(idx))
3043 {
3044 long _idx = PyLong_AsLong(idx);
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003045 return (int)ListAssIndex(self, _idx, obj);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003046 }
3047 else if (PySlice_Check(idx))
3048 {
3049 Py_ssize_t start, stop, step, slicelen;
3050
Bram Moolenaar922a4662014-03-30 16:11:43 +02003051 if (PySlice_GetIndicesEx((PySliceObject_T *)idx, ListLength(self),
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003052 &start, &stop, &step, &slicelen) < 0)
3053 return -1;
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003054 return (int)ListAssSlice(self, start, step, slicelen,
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003055 obj);
3056 }
3057 else
3058 {
3059 RAISE_INVALID_INDEX_TYPE(idx);
3060 return -1;
3061 }
3062}
3063
3064 static PyObject *
3065ListConcatInPlace(ListObject *self, PyObject *obj)
3066{
3067 list_T *l = self->list;
3068 PyObject *lookup_dict;
3069
3070 if (l->lv_lock)
3071 {
3072 RAISE_LOCKED_LIST;
3073 return NULL;
3074 }
3075
3076 if (!(lookup_dict = PyDict_New()))
3077 return NULL;
3078
3079 if (list_py_concat(l, obj, lookup_dict) == -1)
3080 {
3081 Py_DECREF(lookup_dict);
3082 return NULL;
3083 }
3084 Py_DECREF(lookup_dict);
3085
Ken Takata9abd7152024-08-10 09:44:20 +02003086 Py_INCREF((PyObject *)self);
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003087 return (PyObject *)(self);
3088}
3089
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003090typedef struct
3091{
3092 listwatch_T lw;
3093 list_T *list;
3094} listiterinfo_T;
3095
3096 static void
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003097ListIterDestruct(void *arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003098{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003099 listiterinfo_T *lii = (listiterinfo_T*)arg;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003100 list_rem_watch(lii->list, &lii->lw);
Bram Moolenaar21578272021-02-21 19:12:47 +01003101 list_unref(lii->list);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003102 PyMem_Free(lii);
3103}
3104
3105 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003106ListIterNext(void **arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003107{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003108 PyObject *ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003109 listiterinfo_T **lii = (listiterinfo_T**)arg;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003110
3111 if (!((*lii)->lw.lw_item))
3112 return NULL;
3113
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003114 if (!(ret = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003115 return NULL;
3116
3117 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
3118
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003119 return ret;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003120}
3121
3122 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003123ListIter(PyObject *self_obj)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003124{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003125 ListObject *self = (ListObject*)self_obj;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003126 listiterinfo_T *lii;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003127 list_T *l = self->list;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003128
3129 if (!(lii = PyMem_New(listiterinfo_T, 1)))
3130 {
3131 PyErr_NoMemory();
3132 return NULL;
3133 }
3134
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003135 CHECK_LIST_MATERIALIZE(l);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003136 list_add_watch(l, &lii->lw);
3137 lii->lw.lw_item = l->lv_first;
3138 lii->list = l;
Bram Moolenaar21578272021-02-21 19:12:47 +01003139 ++l->lv_refcount;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003140
3141 return IterNew(lii,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003142 ListIterDestruct, ListIterNext,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02003143 NULL, NULL, (PyObject *)self);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003144}
3145
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003146static char *ListAttrs[] = {
3147 "locked",
3148 NULL
3149};
3150
3151 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003152ListDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003153{
3154 return ObjectDir(self, ListAttrs);
3155}
3156
Bram Moolenaar66b79852012-09-21 14:00:35 +02003157 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003158ListSetattr(PyObject *self_obj, char *name, PyObject *valObject)
Bram Moolenaar66b79852012-09-21 14:00:35 +02003159{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003160 ListObject *self = (ListObject*)self_obj;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003161 if (valObject == NULL)
Bram Moolenaar66b79852012-09-21 14:00:35 +02003162 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02003163 PyErr_SET_STRING(PyExc_AttributeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003164 N_("cannot delete vim.List attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02003165 return -1;
3166 }
3167
3168 if (strcmp(name, "locked") == 0)
3169 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003170 if (self->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02003171 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003172 PyErr_SET_STRING(PyExc_TypeError, N_("cannot modify fixed list"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02003173 return -1;
3174 }
3175 else
3176 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003177 int istrue = PyObject_IsTrue(valObject);
Bram Moolenaarb983f752013-05-15 16:11:50 +02003178 if (istrue == -1)
3179 return -1;
3180 else if (istrue)
Bram Moolenaard6e39182013-05-21 18:30:34 +02003181 self->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02003182 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02003183 self->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02003184 }
3185 return 0;
3186 }
3187 else
3188 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003189 PyErr_FORMAT(PyExc_AttributeError, N_("cannot set attribute %s"), name);
Bram Moolenaar66b79852012-09-21 14:00:35 +02003190 return -1;
3191 }
3192}
3193
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003194static PySequenceMethods ListAsSeq = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003195 (lenfunc) ListLength, // sq_length, len(x)
3196 (binaryfunc) 0, // RangeConcat, sq_concat, x+y
3197 0, // RangeRepeat, sq_repeat, x*n
3198 (PyIntArgFunc) ListIndex, // sq_item, x[i]
3199 0, // was_sq_slice, x[i:j]
3200 (PyIntObjArgProc) ListAssIndex, // sq_as_item, x[i]=v
3201 0, // was_sq_ass_slice, x[i:j]=v
3202 0, // sq_contains
3203 (binaryfunc) ListConcatInPlace,// sq_inplace_concat
3204 0, // sq_inplace_repeat
Bram Moolenaar063a46b2014-01-14 16:36:51 +01003205};
3206
3207static PyMappingMethods ListAsMapping = {
3208 /* mp_length */ (lenfunc) ListLength,
3209 /* mp_subscript */ (binaryfunc) ListItem,
3210 /* mp_ass_subscript */ (objobjargproc) ListAssItem,
3211};
3212
Bram Moolenaardb913952012-06-29 12:54:53 +02003213static struct PyMethodDef ListMethods[] = {
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003214 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
3215 {"__dir__", (PyCFunction)ListDir, METH_NOARGS, ""},
3216 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02003217};
3218
3219typedef struct
3220{
3221 PyObject_HEAD
3222 char_u *name;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003223 int argc;
3224 typval_T *argv;
3225 dict_T *self;
3226 pylinkedlist_T ref;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003227 int auto_rebind;
Bram Moolenaardb913952012-06-29 12:54:53 +02003228} FunctionObject;
3229
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003230DEFINE_PY_TYPE_OBJECT(FunctionType);
Bram Moolenaardb913952012-06-29 12:54:53 +02003231
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003232#define NEW_FUNCTION(name, argc, argv, self, pt_auto) \
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003233 FunctionNew(FunctionTypePtr, (name), (argc), (argv), (self), (pt_auto))
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003234
Bram Moolenaardb913952012-06-29 12:54:53 +02003235 static PyObject *
Bram Moolenaar8110a092016-04-14 15:56:09 +02003236FunctionNew(PyTypeObject *subtype, char_u *name, int argc, typval_T *argv,
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003237 dict_T *selfdict, int auto_rebind)
Bram Moolenaardb913952012-06-29 12:54:53 +02003238{
3239 FunctionObject *self;
3240
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003241 self = (FunctionObject *) Py_TYPE_GET_TP_ALLOC(subtype)(subtype, 0);
Bram Moolenaardb913952012-06-29 12:54:53 +02003242 if (self == NULL)
3243 return NULL;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003244
Keith Thompson184f71c2024-01-04 21:19:04 +01003245 if (isdigit((unsigned char)*name))
Bram Moolenaardb913952012-06-29 12:54:53 +02003246 {
Bram Moolenaara14bb7e2020-04-28 00:02:41 +02003247 if (!translated_function_exists(name, FALSE))
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003248 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02003249 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003250 N_("unnamed function %s does not exist"), name);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003251 return NULL;
3252 }
3253 self->name = vim_strsave(name);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003254 }
3255 else
Bram Moolenaar9123c0b2018-12-22 18:59:06 +01003256 {
3257 char_u *p;
3258
3259 if ((p = get_expanded_name(name,
3260 vim_strchr(name, AUTOLOAD_CHAR) == NULL)) == NULL)
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003261 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003262 PyErr_FORMAT(PyExc_ValueError,
3263 N_("function %s does not exist"), name);
Bram Moolenaar018acca2013-05-30 13:37:28 +02003264 return NULL;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003265 }
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003266
Bram Moolenaar9123c0b2018-12-22 18:59:06 +01003267 if (p[0] == K_SPECIAL && p[1] == KS_EXTRA && p[2] == (int)KE_SNR)
3268 {
3269 char_u *np;
3270 size_t len = STRLEN(p) + 1;
3271
Bram Moolenaar51e14382019-05-25 20:21:28 +02003272 if ((np = alloc(len + 2)) == NULL)
Bram Moolenaar9123c0b2018-12-22 18:59:06 +01003273 {
3274 vim_free(p);
3275 return NULL;
3276 }
3277 mch_memmove(np, "<SNR>", 5);
3278 mch_memmove(np + 5, p + 3, len - 3);
3279 vim_free(p);
3280 self->name = np;
3281 }
3282 else
3283 self->name = p;
3284 }
3285
Bram Moolenaar2d3d60a2016-08-01 16:27:23 +02003286 func_ref(self->name);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003287 self->argc = argc;
3288 self->argv = argv;
3289 self->self = selfdict;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003290 self->auto_rebind = selfdict == NULL ? TRUE : auto_rebind;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003291
3292 if (self->argv || self->self)
3293 pyll_add((PyObject *)(self), &self->ref, &lastfunc);
3294
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003295 return (PyObject *)(self);
3296}
3297
3298 static PyObject *
3299FunctionConstructor(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
3300{
3301 PyObject *self;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003302 PyObject *selfdictObject;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003303 PyObject *autoRebindObject;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003304 PyObject *argsObject = NULL;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003305 char_u *name;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003306 typval_T selfdicttv;
3307 typval_T argstv;
3308 list_T *argslist = NULL;
3309 dict_T *selfdict = NULL;
3310 int argc = 0;
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003311 int auto_rebind = TRUE;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003312 typval_T *argv = NULL;
3313 typval_T *curtv;
3314 listitem_T *li;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003315
Bram Moolenaar8110a092016-04-14 15:56:09 +02003316 if (kwargs != NULL)
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003317 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02003318 selfdictObject = PyDict_GetItemString(kwargs, "self");
3319 if (selfdictObject != NULL)
3320 {
3321 if (ConvertFromPyMapping(selfdictObject, &selfdicttv) == -1)
3322 return NULL;
3323 selfdict = selfdicttv.vval.v_dict;
3324 }
3325 argsObject = PyDict_GetItemString(kwargs, "args");
3326 if (argsObject != NULL)
3327 {
3328 if (ConvertFromPySequence(argsObject, &argstv) == -1)
3329 {
3330 dict_unref(selfdict);
3331 return NULL;
3332 }
3333 argslist = argstv.vval.v_list;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003334 CHECK_LIST_MATERIALIZE(argslist);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003335
3336 argc = argslist->lv_len;
3337 if (argc != 0)
3338 {
3339 argv = PyMem_New(typval_T, (size_t) argc);
Bram Moolenaarfe4b1862016-04-15 21:47:54 +02003340 if (argv == NULL)
3341 {
3342 PyErr_NoMemory();
3343 dict_unref(selfdict);
3344 list_unref(argslist);
3345 return NULL;
3346 }
Bram Moolenaar8110a092016-04-14 15:56:09 +02003347 curtv = argv;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003348 FOR_ALL_LIST_ITEMS(argslist, li)
Bram Moolenaar8110a092016-04-14 15:56:09 +02003349 copy_tv(&li->li_tv, curtv++);
3350 }
3351 list_unref(argslist);
3352 }
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003353 if (selfdict != NULL)
3354 {
3355 auto_rebind = FALSE;
3356 autoRebindObject = PyDict_GetItemString(kwargs, "auto_rebind");
3357 if (autoRebindObject != NULL)
3358 {
3359 auto_rebind = PyObject_IsTrue(autoRebindObject);
3360 if (auto_rebind == -1)
3361 {
3362 dict_unref(selfdict);
3363 list_unref(argslist);
3364 return NULL;
3365 }
3366 }
3367 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003368 }
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003369
Bram Moolenaar389a1792013-06-23 13:00:44 +02003370 if (!PyArg_ParseTuple(args, "et", "ascii", &name))
Bram Moolenaar8110a092016-04-14 15:56:09 +02003371 {
3372 dict_unref(selfdict);
3373 while (argc--)
3374 clear_tv(&argv[argc]);
3375 PyMem_Free(argv);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003376 return NULL;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003377 }
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003378
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003379 self = FunctionNew(subtype, name, argc, argv, selfdict, auto_rebind);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003380
Bram Moolenaar389a1792013-06-23 13:00:44 +02003381 PyMem_Free(name);
3382
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003383 return self;
Bram Moolenaardb913952012-06-29 12:54:53 +02003384}
3385
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003386 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003387FunctionDestructor(PyObject *self_obj)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003388{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003389 FunctionObject *self = (FunctionObject*)self_obj;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003390 int i;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003391 func_unref(self->name);
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02003392 vim_free(self->name);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003393 for (i = 0; i < self->argc; ++i)
3394 clear_tv(&self->argv[i]);
3395 PyMem_Free(self->argv);
3396 dict_unref(self->self);
3397 if (self->argv || self->self)
3398 pyll_remove(&self->ref, &lastfunc);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003399
3400 DESTRUCTOR_FINISH(self);
3401}
3402
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003403static char *FunctionAttrs[] = {
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003404 "softspace", "args", "self", "auto_rebind",
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003405 NULL
3406};
3407
3408 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003409FunctionDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003410{
3411 return ObjectDir(self, FunctionAttrs);
3412}
3413
Bram Moolenaardb913952012-06-29 12:54:53 +02003414 static PyObject *
Bram Moolenaar8110a092016-04-14 15:56:09 +02003415FunctionAttr(FunctionObject *self, char *name)
3416{
3417 list_T *list;
3418 int i;
3419 if (strcmp(name, "name") == 0)
3420 return PyString_FromString((char *)(self->name));
3421 else if (strcmp(name, "args") == 0)
3422 {
Bram Moolenaar9f289532016-08-26 16:39:03 +02003423 if (self->argv == NULL || (list = list_alloc()) == NULL)
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003424 return ALWAYS_NONE;
Bram Moolenaar9f289532016-08-26 16:39:03 +02003425
Bram Moolenaar8110a092016-04-14 15:56:09 +02003426 for (i = 0; i < self->argc; ++i)
3427 list_append_tv(list, &self->argv[i]);
3428 return NEW_LIST(list);
3429 }
3430 else if (strcmp(name, "self") == 0)
3431 return self->self == NULL
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003432 ? ALWAYS_NONE
Bram Moolenaar8110a092016-04-14 15:56:09 +02003433 : NEW_DICTIONARY(self->self);
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003434 else if (strcmp(name, "auto_rebind") == 0)
3435 return self->auto_rebind
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02003436 ? ALWAYS_TRUE
3437 : ALWAYS_FALSE;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003438 else if (strcmp(name, "__members__") == 0)
3439 return ObjectDir(NULL, FunctionAttrs);
3440 return NULL;
3441}
3442
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003443/*
3444 * Populate partial_T given function object.
Bram Moolenaar8110a092016-04-14 15:56:09 +02003445 *
3446 * "exported" should be set to true when it is needed to construct a partial
3447 * that may be stored in a variable (i.e. may be freed by Vim).
3448 */
3449 static void
3450set_partial(FunctionObject *self, partial_T *pt, int exported)
3451{
Bram Moolenaar8110a092016-04-14 15:56:09 +02003452 int i;
3453
3454 pt->pt_name = self->name;
3455 if (self->argv)
3456 {
3457 pt->pt_argc = self->argc;
3458 if (exported)
3459 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003460 pt->pt_argv = ALLOC_CLEAR_MULT(typval_T, self->argc);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003461 for (i = 0; i < pt->pt_argc; ++i)
3462 copy_tv(&self->argv[i], &pt->pt_argv[i]);
3463 }
3464 else
3465 pt->pt_argv = self->argv;
3466 }
3467 else
3468 {
3469 pt->pt_argc = 0;
3470 pt->pt_argv = NULL;
3471 }
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003472 pt->pt_auto = self->auto_rebind || !exported;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003473 pt->pt_dict = self->self;
3474 if (exported && self->self)
3475 ++pt->pt_dict->dv_refcount;
3476 if (exported)
3477 pt->pt_name = vim_strsave(pt->pt_name);
3478 pt->pt_refcount = 1;
3479}
3480
3481 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003482FunctionCall(PyObject *self_obj, PyObject *argsObject, PyObject *kwargs)
Bram Moolenaardb913952012-06-29 12:54:53 +02003483{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003484 FunctionObject *self = (FunctionObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003485 char_u *name = self->name;
Bram Moolenaardb913952012-06-29 12:54:53 +02003486 typval_T args;
3487 typval_T selfdicttv;
3488 typval_T rettv;
3489 dict_T *selfdict = NULL;
3490 PyObject *selfdictObject;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003491 PyObject *ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02003492 int error;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003493 partial_T pt;
3494 partial_T *pt_ptr = NULL;
Bram Moolenaardb913952012-06-29 12:54:53 +02003495
Bram Moolenaar8110a092016-04-14 15:56:09 +02003496 if (ConvertFromPySequence(argsObject, &args) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +02003497 return NULL;
3498
3499 if (kwargs != NULL)
3500 {
3501 selfdictObject = PyDict_GetItemString(kwargs, "self");
3502 if (selfdictObject != NULL)
3503 {
Bram Moolenaara9922d62013-05-30 13:01:18 +02003504 if (ConvertFromPyMapping(selfdictObject, &selfdicttv) == -1)
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003505 {
3506 clear_tv(&args);
Bram Moolenaardb913952012-06-29 12:54:53 +02003507 return NULL;
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003508 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003509 selfdict = selfdicttv.vval.v_dict;
3510 }
3511 }
3512
Bram Moolenaar8110a092016-04-14 15:56:09 +02003513 if (self->argv || self->self)
3514 {
Bram Moolenaara80faa82020-04-12 19:37:17 +02003515 CLEAR_FIELD(pt);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003516 set_partial(self, &pt, FALSE);
3517 pt_ptr = &pt;
3518 }
3519
Bram Moolenaar71700b82013-05-15 17:49:05 +02003520 Py_BEGIN_ALLOW_THREADS
3521 Python_Lock_Vim();
3522
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003523 VimTryStart();
Bram Moolenaar8110a092016-04-14 15:56:09 +02003524 error = func_call(name, &args, pt_ptr, selfdict, &rettv);
Bram Moolenaar71700b82013-05-15 17:49:05 +02003525
3526 Python_Release_Vim();
3527 Py_END_ALLOW_THREADS
3528
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003529 if (VimTryEnd())
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003530 ret = NULL;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003531 else if (error != OK)
Bram Moolenaardb913952012-06-29 12:54:53 +02003532 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003533 ret = NULL;
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003534 PyErr_VIM_FORMAT(N_("failed to run function %s"), (char *)name);
Bram Moolenaardb913952012-06-29 12:54:53 +02003535 }
3536 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003537 ret = ConvertToPyObject(&rettv);
Bram Moolenaardb913952012-06-29 12:54:53 +02003538
Bram Moolenaardb913952012-06-29 12:54:53 +02003539 clear_tv(&args);
3540 clear_tv(&rettv);
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003541 if (selfdict != NULL)
3542 clear_tv(&selfdicttv);
Bram Moolenaardb913952012-06-29 12:54:53 +02003543
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003544 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02003545}
3546
Bram Moolenaara5b725c2013-05-30 12:43:54 +02003547 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003548FunctionRepr(PyObject *self_obj)
Bram Moolenaara5b725c2013-05-30 12:43:54 +02003549{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003550 FunctionObject *self = (FunctionObject*)self_obj;
Bram Moolenaar8110a092016-04-14 15:56:09 +02003551 PyObject *ret;
3552 garray_T repr_ga;
3553 int i;
3554 char_u *tofree = NULL;
3555 typval_T tv;
3556 char_u numbuf[NUMBUFLEN];
3557
Bram Moolenaar04935fb2022-01-08 16:19:22 +00003558 ga_init2(&repr_ga, sizeof(char), 70);
Bram Moolenaar8110a092016-04-14 15:56:09 +02003559 ga_concat(&repr_ga, (char_u *)"<vim.Function '");
3560 if (self->name)
3561 ga_concat(&repr_ga, self->name);
3562 else
3563 ga_concat(&repr_ga, (char_u *)"<NULL>");
3564 ga_append(&repr_ga, '\'');
3565 if (self->argv)
3566 {
3567 ga_concat(&repr_ga, (char_u *)", args=[");
3568 ++emsg_silent;
3569 for (i = 0; i < self->argc; i++)
3570 {
3571 if (i != 0)
3572 ga_concat(&repr_ga, (char_u *)", ");
3573 ga_concat(&repr_ga, tv2string(&self->argv[i], &tofree, numbuf,
3574 get_copyID()));
3575 vim_free(tofree);
3576 }
3577 --emsg_silent;
3578 ga_append(&repr_ga, ']');
3579 }
3580 if (self->self)
3581 {
3582 ga_concat(&repr_ga, (char_u *)", self=");
3583 tv.v_type = VAR_DICT;
3584 tv.vval.v_dict = self->self;
3585 ++emsg_silent;
3586 ga_concat(&repr_ga, tv2string(&tv, &tofree, numbuf, get_copyID()));
3587 --emsg_silent;
3588 vim_free(tofree);
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02003589 if (self->auto_rebind)
3590 ga_concat(&repr_ga, (char_u *)", auto_rebind=True");
Bram Moolenaar8110a092016-04-14 15:56:09 +02003591 }
3592 ga_append(&repr_ga, '>');
3593 ret = PyString_FromString((char *)repr_ga.ga_data);
3594 ga_clear(&repr_ga);
3595 return ret;
Bram Moolenaara5b725c2013-05-30 12:43:54 +02003596}
3597
Bram Moolenaardb913952012-06-29 12:54:53 +02003598static struct PyMethodDef FunctionMethods[] = {
Bram Moolenaardd8aca62013-05-29 22:36:10 +02003599 {"__dir__", (PyCFunction)FunctionDir, METH_NOARGS, ""},
3600 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02003601};
3602
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003603/*
3604 * Options object
3605 */
3606
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003607DEFINE_PY_TYPE_OBJECT(OptionsType);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003608
3609typedef int (*checkfun)(void *);
3610
3611typedef struct
3612{
3613 PyObject_HEAD
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003614 int opt_type;
3615 void *from;
3616 checkfun Check;
3617 PyObject *fromObj;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003618} OptionsObject;
3619
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003620 static int
3621dummy_check(void *arg UNUSED)
3622{
3623 return 0;
3624}
3625
3626 static PyObject *
3627OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
3628{
3629 OptionsObject *self;
3630
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003631 self = PyObject_GC_New(OptionsObject, OptionsTypePtr);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003632 if (self == NULL)
3633 return NULL;
3634
3635 self->opt_type = opt_type;
3636 self->from = from;
3637 self->Check = Check;
3638 self->fromObj = fromObj;
3639 if (fromObj)
3640 Py_INCREF(fromObj);
3641
3642 return (PyObject *)(self);
3643}
3644
3645 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003646OptionsDestructor(PyObject *self_obj)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003647{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003648 OptionsObject *self = (OptionsObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02003649 PyObject_GC_UnTrack((void *)(self));
3650 Py_XDECREF(self->fromObj);
3651 PyObject_GC_Del((void *)(self));
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003652}
3653
3654 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003655OptionsTraverse(PyObject *self_obj, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003656{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003657 OptionsObject *self = (OptionsObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003658 Py_VISIT(self->fromObj);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003659 return 0;
3660}
3661
3662 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003663OptionsClear(PyObject *self_obj)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003664{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003665 OptionsObject *self = (OptionsObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02003666 Py_CLEAR(self->fromObj);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003667 return 0;
3668}
3669
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003670 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003671OptionsItem(OptionsObject *self, PyObject *keyObject)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003672{
3673 char_u *key;
3674 int flags;
3675 long numval;
3676 char_u *stringval;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003677 PyObject *todecref;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003678
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02003679 if (self->Check(self->fromObj))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003680 return NULL;
3681
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003682 if (!(key = StringToChars(keyObject, &todecref)))
3683 return NULL;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003684
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003685 if (*key == NUL)
3686 {
3687 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003688 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003689 return NULL;
3690 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003691
3692 flags = get_option_value_strict(key, &numval, &stringval,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003693 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003694
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003695 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003696
3697 if (flags == 0)
3698 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003699 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003700 return NULL;
3701 }
3702
3703 if (flags & SOPT_UNSET)
3704 {
3705 Py_INCREF(Py_None);
3706 return Py_None;
3707 }
3708 else if (flags & SOPT_BOOL)
3709 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003710 PyObject *ret;
3711 ret = numval ? Py_True : Py_False;
3712 Py_INCREF(ret);
3713 return ret;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003714 }
3715 else if (flags & SOPT_NUM)
3716 return PyInt_FromLong(numval);
3717 else if (flags & SOPT_STRING)
3718 {
3719 if (stringval)
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003720 {
Bram Moolenaar41009372013-07-01 22:03:04 +02003721 PyObject *ret = PyBytes_FromString((char *)stringval);
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003722 vim_free(stringval);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003723 return ret;
Bram Moolenaar0b9aecc2013-05-21 22:13:41 +02003724 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003725 else
3726 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02003727 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003728 N_("unable to get option value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003729 return NULL;
3730 }
3731 }
3732 else
3733 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003734 PyErr_SET_VIM(N_("internal error: unknown option type"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003735 return NULL;
3736 }
3737}
3738
3739 static int
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003740OptionsContains(OptionsObject *self, PyObject *keyObject)
3741{
3742 char_u *key;
3743 PyObject *todecref;
3744
3745 if (!(key = StringToChars(keyObject, &todecref)))
3746 return -1;
3747
3748 if (*key == NUL)
3749 {
3750 Py_XDECREF(todecref);
3751 return 0;
3752 }
3753
3754 if (get_option_value_strict(key, NULL, NULL, self->opt_type, NULL))
3755 {
3756 Py_XDECREF(todecref);
3757 return 1;
3758 }
3759 else
3760 {
3761 Py_XDECREF(todecref);
3762 return 0;
3763 }
3764}
3765
3766typedef struct
3767{
3768 void *lastoption;
3769 int opt_type;
3770} optiterinfo_T;
3771
3772 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003773OptionsIterNext(void **arg)
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003774{
3775 char_u *name;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003776 optiterinfo_T **oii = (optiterinfo_T**)arg;
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003777
3778 if ((name = option_iter_next(&((*oii)->lastoption), (*oii)->opt_type)))
3779 return PyString_FromString((char *)name);
3780
3781 return NULL;
3782}
3783
3784 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003785OptionsIter(PyObject *self_obj)
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003786{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02003787 OptionsObject *self = (OptionsObject*)self_obj;
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003788 optiterinfo_T *oii;
3789
3790 if (!(oii = PyMem_New(optiterinfo_T, 1)))
3791 {
3792 PyErr_NoMemory();
3793 return NULL;
3794 }
3795
3796 oii->opt_type = self->opt_type;
3797 oii->lastoption = NULL;
3798
3799 return IterNew(oii,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02003800 PyMem_Free, OptionsIterNext,
Bram Moolenaar423a85a2020-08-29 12:57:16 +02003801 NULL, NULL, (PyObject *)self);
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003802}
3803
3804 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02003805set_option_value_err(char_u *key, int numval, char_u *stringval, int opt_flags)
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003806{
Bram Moolenaarb1443b42019-01-13 23:51:14 +01003807 char *errmsg;
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003808
3809 if ((errmsg = set_option_value(key, numval, stringval, opt_flags)))
3810 {
3811 if (VimTryEnd())
3812 return FAIL;
Bram Moolenaarb1443b42019-01-13 23:51:14 +01003813 PyErr_SetVim(errmsg);
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003814 return FAIL;
3815 }
3816 return OK;
3817}
3818
3819 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02003820set_option_value_for(
3821 char_u *key,
3822 int numval,
3823 char_u *stringval,
3824 int opt_flags,
3825 int opt_type,
3826 void *from)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003827{
Bram Moolenaar18f47402022-01-06 13:24:51 +00003828 switchwin_T switchwin;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003829 bufref_T save_curbuf;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003830 int set_ret = 0;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003831
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003832 VimTryStart();
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003833 switch (opt_type)
3834 {
3835 case SREQ_WIN:
Bram Moolenaar18f47402022-01-06 13:24:51 +00003836 if (switch_win(&switchwin, (win_T *)from,
Bram Moolenaard6949742013-06-16 14:18:28 +02003837 win_find_tabpage((win_T *)from), FALSE) == FAIL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003838 {
Bram Moolenaar18f47402022-01-06 13:24:51 +00003839 restore_win(&switchwin, TRUE);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003840 if (VimTryEnd())
3841 return -1;
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003842 PyErr_SET_VIM(N_("problem while switching windows"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003843 return -1;
3844 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003845 set_ret = set_option_value_err(key, numval, stringval, opt_flags);
Bram Moolenaar18f47402022-01-06 13:24:51 +00003846 restore_win(&switchwin, TRUE);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003847 break;
3848 case SREQ_BUF:
Bram Moolenaar105bc352013-05-17 16:03:57 +02003849 switch_buffer(&save_curbuf, (buf_T *)from);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003850 set_ret = set_option_value_err(key, numval, stringval, opt_flags);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003851 restore_buffer(&save_curbuf);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003852 break;
3853 case SREQ_GLOBAL:
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003854 set_ret = set_option_value_err(key, numval, stringval, opt_flags);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003855 break;
3856 }
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003857 if (set_ret == FAIL)
3858 return -1;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003859 return VimTryEnd();
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003860}
3861
3862 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02003863OptionsAssItem(OptionsObject *self, PyObject *keyObject, PyObject *valObject)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003864{
3865 char_u *key;
3866 int flags;
3867 int opt_flags;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003868 int ret = 0;
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003869 PyObject *todecref;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003870
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02003871 if (self->Check(self->fromObj))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003872 return -1;
3873
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003874 if (!(key = StringToChars(keyObject, &todecref)))
3875 return -1;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003876
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003877 if (*key == NUL)
3878 {
3879 RAISE_NO_EMPTY_KEYS;
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02003880 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003881 return -1;
3882 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003883
3884 flags = get_option_value_strict(key, NULL, NULL,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003885 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003886
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003887 if (flags == 0)
3888 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003889 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003890 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003891 return -1;
3892 }
3893
3894 if (valObject == NULL)
3895 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003896 if (self->opt_type == SREQ_GLOBAL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003897 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02003898 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003899 N_("unable to unset global option %s"), key);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003900 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003901 return -1;
3902 }
3903 else if (!(flags & SOPT_GLOBAL))
3904 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02003905 PyErr_FORMAT(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02003906 N_("unable to unset option %s "
3907 "which does not have global value"), key);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003908 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003909 return -1;
3910 }
3911 else
3912 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003913 unset_global_local_option(key, self->from);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003914 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003915 return 0;
3916 }
3917 }
3918
Bram Moolenaard6e39182013-05-21 18:30:34 +02003919 opt_flags = (self->opt_type ? OPT_LOCAL : OPT_GLOBAL);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003920
3921 if (flags & SOPT_BOOL)
3922 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02003923 int istrue = PyObject_IsTrue(valObject);
Bram Moolenaarc96ebe72013-05-21 22:38:18 +02003924
Bram Moolenaarb983f752013-05-15 16:11:50 +02003925 if (istrue == -1)
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003926 ret = -1;
Bram Moolenaar1bc24282013-05-29 21:37:35 +02003927 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003928 ret = set_option_value_for(key, istrue, NULL,
Bram Moolenaar1bc24282013-05-29 21:37:35 +02003929 opt_flags, self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003930 }
3931 else if (flags & SOPT_NUM)
3932 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +02003933 long val;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003934
Bram Moolenaar141be8a2013-06-23 14:16:57 +02003935 if (NumberToLong(valObject, &val, NUMBER_INT))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003936 {
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003937 Py_XDECREF(todecref);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003938 return -1;
3939 }
3940
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003941 ret = set_option_value_for(key, (int) val, NULL, opt_flags,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003942 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003943 }
3944 else
3945 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003946 char_u *val;
Bram Moolenaarc2401d62013-12-07 14:28:43 +01003947 PyObject *todecref2;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02003948
Bram Moolenaarc2401d62013-12-07 14:28:43 +01003949 if ((val = StringToChars(valObject, &todecref2)))
3950 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003951 ret = set_option_value_for(key, 0, val, opt_flags,
Bram Moolenaare9ba5162013-05-29 22:02:22 +02003952 self->opt_type, self->from);
Bram Moolenaarc2401d62013-12-07 14:28:43 +01003953 Py_XDECREF(todecref2);
3954 }
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003955 else
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003956 ret = -1;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003957 }
3958
Bram Moolenaar35eacd72013-05-30 22:06:33 +02003959 Py_XDECREF(todecref);
Bram Moolenaar1bc24282013-05-29 21:37:35 +02003960
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02003961 return ret;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003962}
3963
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003964static PySequenceMethods OptionsAsSeq = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003965 0, // sq_length
3966 0, // sq_concat
3967 0, // sq_repeat
3968 0, // sq_item
3969 0, // sq_slice
3970 0, // sq_ass_item
3971 0, // sq_ass_slice
3972 (objobjproc) OptionsContains, // sq_contains
3973 0, // sq_inplace_concat
3974 0, // sq_inplace_repeat
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01003975};
3976
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003977static PyMappingMethods OptionsAsMapping = {
3978 (lenfunc) NULL,
3979 (binaryfunc) OptionsItem,
3980 (objobjargproc) OptionsAssItem,
3981};
3982
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01003983// Tabpage object
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003984
3985typedef struct
3986{
3987 PyObject_HEAD
3988 tabpage_T *tab;
3989} TabPageObject;
3990
3991static PyObject *WinListNew(TabPageObject *tabObject);
3992
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02003993DEFINE_PY_TYPE_OBJECT(TabPageType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003994
3995 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02003996CheckTabPage(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003997{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003998 if (self->tab == INVALID_TABPAGE_VALUE)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003999 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004000 PyErr_SET_VIM(N_("attempt to refer to deleted tab page"));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004001 return -1;
4002 }
4003
4004 return 0;
4005}
4006
4007 static PyObject *
4008TabPageNew(tabpage_T *tab)
4009{
4010 TabPageObject *self;
4011
4012 if (TAB_PYTHON_REF(tab))
4013 {
4014 self = TAB_PYTHON_REF(tab);
Ken Takata9abd7152024-08-10 09:44:20 +02004015 Py_INCREF((PyObject *)self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004016 }
4017 else
4018 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004019 self = PyObject_NEW(TabPageObject, TabPageTypePtr);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004020 if (self == NULL)
4021 return NULL;
4022 self->tab = tab;
4023 TAB_PYTHON_REF(tab) = self;
4024 }
4025
4026 return (PyObject *)(self);
4027}
4028
4029 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004030TabPageDestructor(PyObject *self_obj)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004031{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004032 TabPageObject *self = (TabPageObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004033 if (self->tab && self->tab != INVALID_TABPAGE_VALUE)
4034 TAB_PYTHON_REF(self->tab) = NULL;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004035
4036 DESTRUCTOR_FINISH(self);
4037}
4038
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004039static char *TabPageAttrs[] = {
4040 "windows", "number", "vars", "window", "valid",
4041 NULL
4042};
4043
4044 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02004045TabPageDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004046{
4047 return ObjectDir(self, TabPageAttrs);
4048}
4049
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004050 static PyObject *
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004051TabPageAttrValid(TabPageObject *self, char *name)
4052{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004053 PyObject *ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004054
4055 if (strcmp(name, "valid") != 0)
4056 return NULL;
4057
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004058 ret = ((self->tab == INVALID_TABPAGE_VALUE) ? Py_False : Py_True);
4059 Py_INCREF(ret);
4060 return ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004061}
4062
4063 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004064TabPageAttr(TabPageObject *self, char *name)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004065{
4066 if (strcmp(name, "windows") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004067 return WinListNew(self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004068 else if (strcmp(name, "number") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004069 return PyLong_FromLong((long) get_tab_number(self->tab));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004070 else if (strcmp(name, "vars") == 0)
Bram Moolenaara9922d62013-05-30 13:01:18 +02004071 return NEW_DICTIONARY(self->tab->tp_vars);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004072 else if (strcmp(name, "window") == 0)
4073 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004074 // For current tab window.c does not bother to set or update tp_curwin
Bram Moolenaard6e39182013-05-21 18:30:34 +02004075 if (self->tab == curtab)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004076 return WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004077 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004078 return WindowNew(self->tab->tp_curwin, self->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004079 }
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004080 else if (strcmp(name, "__members__") == 0)
4081 return ObjectDir(NULL, TabPageAttrs);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004082 return NULL;
4083}
4084
4085 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004086TabPageRepr(PyObject *self_obj)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004087{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004088 TabPageObject *self = (TabPageObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004089 if (self->tab == INVALID_TABPAGE_VALUE)
Dominique Pellec14f6672022-01-09 12:57:48 +00004090 return PyString_FromFormat("<tabpage object (deleted) at %p>", (void *)self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004091 else
4092 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004093 int t = get_tab_number(self->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004094
4095 if (t == 0)
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004096 return PyString_FromFormat("<tabpage object (unknown) at %p>",
Dominique Pellec14f6672022-01-09 12:57:48 +00004097 (void *)self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004098 else
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004099 return PyString_FromFormat("<tabpage %d>", t - 1);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004100 }
4101}
4102
4103static struct PyMethodDef TabPageMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004104 // name, function, calling, documentation
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004105 {"__dir__", (PyCFunction)TabPageDir, METH_NOARGS, ""},
4106 { NULL, NULL, 0, NULL}
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004107};
4108
4109/*
4110 * Window list object
4111 */
4112
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004113DEFINE_PY_TYPE_OBJECT(TabListType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004114static PySequenceMethods TabListAsSeq;
4115
4116typedef struct
4117{
4118 PyObject_HEAD
4119} TabListObject;
4120
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004121static TabListObject TheTabPageList =
4122{
4123 PyObject_HEAD_INIT_TYPE(TabListType)
4124};
4125
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004126 static PyInt
4127TabListLength(PyObject *self UNUSED)
4128{
4129 tabpage_T *tp = first_tabpage;
4130 PyInt n = 0;
4131
4132 while (tp != NULL)
4133 {
4134 ++n;
4135 tp = tp->tp_next;
4136 }
4137
4138 return n;
4139}
4140
4141 static PyObject *
4142TabListItem(PyObject *self UNUSED, PyInt n)
4143{
4144 tabpage_T *tp;
4145
4146 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, --n)
4147 if (n == 0)
4148 return TabPageNew(tp);
4149
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004150 PyErr_SET_STRING(PyExc_IndexError, N_("no such tab page"));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004151 return NULL;
4152}
4153
Bram Moolenaar6c85e7f2013-06-23 12:51:32 +02004154/*
4155 * Window object
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004156 */
4157
4158typedef struct
4159{
4160 PyObject_HEAD
4161 win_T *win;
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004162 TabPageObject *tabObject;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004163} WindowObject;
4164
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004165DEFINE_PY_TYPE_OBJECT(WindowType);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004166
4167 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02004168CheckWindow(WindowObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004169{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004170 if (self->win == INVALID_WINDOW_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004171 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004172 PyErr_SET_VIM(N_("attempt to refer to deleted window"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004173 return -1;
4174 }
4175
4176 return 0;
4177}
4178
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02004179 static int
4180CheckWindowCb(void *self)
4181{
4182 return CheckWindow((WindowObject*)self);
4183}
4184
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004185 static PyObject *
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004186WindowNew(win_T *win, tabpage_T *tab)
Bram Moolenaar971db462013-05-12 18:44:48 +02004187{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004188 /*
4189 * We need to handle deletion of windows underneath us.
Bram Moolenaar971db462013-05-12 18:44:48 +02004190 * If we add a "w_python*_ref" field to the win_T structure,
4191 * then we can get at it in win_free() in vim. We then
4192 * need to create only ONE Python object per window - if
4193 * we try to create a second, just INCREF the existing one
4194 * and return it. The (single) Python object referring to
4195 * the window is stored in "w_python*_ref".
4196 * On a win_free() we set the Python object's win_T* field
4197 * to an invalid value. We trap all uses of a window
4198 * object, and reject them if the win_T* field is invalid.
4199 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004200 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02004201 * w_python_ref and w_python3_ref fields respectively.
4202 */
4203
4204 WindowObject *self;
4205
4206 if (WIN_PYTHON_REF(win))
4207 {
4208 self = WIN_PYTHON_REF(win);
Ken Takata9abd7152024-08-10 09:44:20 +02004209 Py_INCREF((PyObject *)self);
Bram Moolenaar971db462013-05-12 18:44:48 +02004210 }
4211 else
4212 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004213 self = PyObject_GC_New(WindowObject, WindowTypePtr);
Bram Moolenaar971db462013-05-12 18:44:48 +02004214 if (self == NULL)
4215 return NULL;
4216 self->win = win;
4217 WIN_PYTHON_REF(win) = self;
4218 }
4219
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004220 self->tabObject = ((TabPageObject *)(TabPageNew(tab)));
4221
Bram Moolenaar971db462013-05-12 18:44:48 +02004222 return (PyObject *)(self);
4223}
4224
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004225 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004226WindowDestructor(PyObject *self_obj)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004227{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004228 WindowObject *self = (WindowObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02004229 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaard6e39182013-05-21 18:30:34 +02004230 if (self->win && self->win != INVALID_WINDOW_VALUE)
4231 WIN_PYTHON_REF(self->win) = NULL;
Bram Moolenaarab589462020-07-06 21:03:06 +02004232 Py_XDECREF(((PyObject *)(self->tabObject)));
Bram Moolenaar774267b2013-05-21 20:51:59 +02004233 PyObject_GC_Del((void *)(self));
4234}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004235
Bram Moolenaar774267b2013-05-21 20:51:59 +02004236 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004237WindowTraverse(PyObject *self_obj, visitproc visit, void *arg)
Bram Moolenaar774267b2013-05-21 20:51:59 +02004238{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004239 WindowObject *self = (WindowObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02004240 Py_VISIT(((PyObject *)(self->tabObject)));
4241 return 0;
4242}
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004243
Bram Moolenaar774267b2013-05-21 20:51:59 +02004244 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004245WindowClear(PyObject *self_obj)
Bram Moolenaar774267b2013-05-21 20:51:59 +02004246{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004247 WindowObject *self = (WindowObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02004248 Py_CLEAR(self->tabObject);
4249 return 0;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004250}
4251
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004252 static win_T *
4253get_firstwin(TabPageObject *tabObject)
4254{
4255 if (tabObject)
4256 {
4257 if (CheckTabPage(tabObject))
4258 return NULL;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004259 // For current tab window.c does not bother to set or update tp_firstwin
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004260 else if (tabObject->tab == curtab)
4261 return firstwin;
4262 else
4263 return tabObject->tab->tp_firstwin;
4264 }
4265 else
4266 return firstwin;
4267}
Bram Moolenaare950f992018-06-10 13:55:55 +02004268
4269// Use the same order as in the WindowAttr() function.
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004270static char *WindowAttrs[] = {
Bram Moolenaare950f992018-06-10 13:55:55 +02004271 "buffer",
4272 "cursor",
4273 "height",
4274 "row",
4275 "width",
4276 "col",
4277 "vars",
4278 "options",
4279 "number",
4280 "tabpage",
4281 "valid",
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004282 NULL
4283};
4284
4285 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02004286WindowDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004287{
4288 return ObjectDir(self, WindowAttrs);
4289}
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004290
Bram Moolenaar971db462013-05-12 18:44:48 +02004291 static PyObject *
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004292WindowAttrValid(WindowObject *self, char *name)
4293{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004294 PyObject *ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004295
4296 if (strcmp(name, "valid") != 0)
4297 return NULL;
4298
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004299 ret = ((self->win == INVALID_WINDOW_VALUE) ? Py_False : Py_True);
4300 Py_INCREF(ret);
4301 return ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02004302}
4303
4304 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004305WindowAttr(WindowObject *self, char *name)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004306{
4307 if (strcmp(name, "buffer") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004308 return (PyObject *)BufferNew(self->win->w_buffer);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004309 else if (strcmp(name, "cursor") == 0)
4310 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004311 pos_T *pos = &self->win->w_cursor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004312
4313 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
4314 }
4315 else if (strcmp(name, "height") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004316 return PyLong_FromLong((long)(self->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02004317 else if (strcmp(name, "row") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004318 return PyLong_FromLong((long)(self->win->w_winrow));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004319 else if (strcmp(name, "width") == 0)
Bram Moolenaar02631462017-09-22 15:20:32 +02004320 return PyLong_FromLong((long)(self->win->w_width));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02004321 else if (strcmp(name, "col") == 0)
Bram Moolenaar53f81742017-09-22 14:35:51 +02004322 return PyLong_FromLong((long)(self->win->w_wincol));
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02004323 else if (strcmp(name, "vars") == 0)
Bram Moolenaara9922d62013-05-30 13:01:18 +02004324 return NEW_DICTIONARY(self->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02004325 else if (strcmp(name, "options") == 0)
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02004326 return OptionsNew(SREQ_WIN, self->win, CheckWindowCb,
Bram Moolenaard6e39182013-05-21 18:30:34 +02004327 (PyObject *) self);
Bram Moolenaar6d216452013-05-12 19:00:41 +02004328 else if (strcmp(name, "number") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004329 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004330 if (CheckTabPage(self->tabObject))
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004331 return NULL;
4332 return PyLong_FromLong((long)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004333 get_win_number(self->win, get_firstwin(self->tabObject)));
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004334 }
4335 else if (strcmp(name, "tabpage") == 0)
4336 {
Ken Takata9abd7152024-08-10 09:44:20 +02004337 Py_INCREF((PyObject *)self->tabObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004338 return (PyObject *)(self->tabObject);
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02004339 }
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004340 else if (strcmp(name, "__members__") == 0)
4341 return ObjectDir(NULL, WindowAttrs);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004342 else
4343 return NULL;
4344}
4345
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004346 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004347WindowSetattr(PyObject *self_obj, char *name, PyObject *valObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004348{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004349 WindowObject *self = (WindowObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004350 if (CheckWindow(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004351 return -1;
4352
4353 if (strcmp(name, "buffer") == 0)
4354 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004355 PyErr_SET_STRING(PyExc_TypeError, N_("readonly attribute: buffer"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004356 return -1;
4357 }
4358 else if (strcmp(name, "cursor") == 0)
4359 {
4360 long lnum;
4361 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004362
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004363 if (!PyArg_Parse(valObject, "(ll)", &lnum, &col))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004364 return -1;
4365
Bram Moolenaard6e39182013-05-21 18:30:34 +02004366 if (lnum <= 0 || lnum > self->win->w_buffer->b_ml.ml_line_count)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004367 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004368 PyErr_SET_VIM(N_("cursor position outside buffer"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004369 return -1;
4370 }
4371
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004372 // Check for keyboard interrupts
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004373 if (VimCheckInterrupt())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004374 return -1;
4375
Bram Moolenaard6e39182013-05-21 18:30:34 +02004376 self->win->w_cursor.lnum = lnum;
4377 self->win->w_cursor.col = col;
Bram Moolenaar53901442018-07-25 22:02:36 +02004378 self->win->w_set_curswant = TRUE;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004379 self->win->w_cursor.coladd = 0;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004380 // When column is out of range silently correct it.
Bram Moolenaard6e39182013-05-21 18:30:34 +02004381 check_cursor_col_win(self->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004382
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004383 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004384 return 0;
4385 }
4386 else if (strcmp(name, "height") == 0)
4387 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004388 long height;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004389 win_T *savewin;
4390
Bram Moolenaardee2e312013-06-23 16:35:47 +02004391 if (NumberToLong(valObject, &height, NUMBER_INT|NUMBER_UNSIGNED))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004392 return -1;
4393
4394#ifdef FEAT_GUI
4395 need_mouse_correct = TRUE;
4396#endif
4397 savewin = curwin;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004398 curwin = self->win;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004399 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004400
4401 VimTryStart();
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004402 win_setheight((int) height);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004403 curwin = savewin;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004404 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004405 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004406 return -1;
4407
4408 return 0;
4409 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004410 else if (strcmp(name, "width") == 0)
4411 {
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004412 long width;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004413 win_T *savewin;
4414
Bram Moolenaardee2e312013-06-23 16:35:47 +02004415 if (NumberToLong(valObject, &width, NUMBER_INT|NUMBER_UNSIGNED))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004416 return -1;
4417
4418#ifdef FEAT_GUI
4419 need_mouse_correct = TRUE;
4420#endif
4421 savewin = curwin;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004422 curwin = self->win;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004423 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004424
4425 VimTryStart();
Bram Moolenaar141be8a2013-06-23 14:16:57 +02004426 win_setwidth((int) width);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004427 curwin = savewin;
Bram Moolenaar6c87bbb2022-12-10 11:17:11 +00004428 curbuf = curwin->w_buffer;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004429 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004430 return -1;
4431
4432 return 0;
4433 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004434 else
4435 {
4436 PyErr_SetString(PyExc_AttributeError, name);
4437 return -1;
4438 }
4439}
4440
4441 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004442WindowRepr(PyObject *self_obj)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004443{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02004444 WindowObject *self = (WindowObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004445 if (self->win == INVALID_WINDOW_VALUE)
Dominique Pellec14f6672022-01-09 12:57:48 +00004446 return PyString_FromFormat("<window object (deleted) at %p>", (void *)self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004447 else
4448 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02004449 int w = get_win_number(self->win, firstwin);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004450
Bram Moolenaar6d216452013-05-12 19:00:41 +02004451 if (w == 0)
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004452 return PyString_FromFormat("<window object (unknown) at %p>",
Dominique Pellec14f6672022-01-09 12:57:48 +00004453 (void *)self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004454 else
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02004455 return PyString_FromFormat("<window %d>", w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004456 }
4457}
4458
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004459static struct PyMethodDef WindowMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004460 // name, function, calling, documentation
Bram Moolenaardd8aca62013-05-29 22:36:10 +02004461 {"__dir__", (PyCFunction)WindowDir, METH_NOARGS, ""},
4462 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004463};
4464
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004465/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004466 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004467 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004468
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004469DEFINE_PY_TYPE_OBJECT(WinListType);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02004470static PySequenceMethods WinListAsSeq;
4471
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004472typedef struct
4473{
4474 PyObject_HEAD
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004475 TabPageObject *tabObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004476} WinListObject;
4477
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004478static WinListObject TheWindowList =
4479{
4480 PyObject_HEAD_INIT_TYPE(WinListType)
4481 NULL
4482};
4483
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004484 static PyObject *
4485WinListNew(TabPageObject *tabObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004486{
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004487 WinListObject *self;
4488
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004489 self = PyObject_NEW(WinListObject, WinListTypePtr);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004490 self->tabObject = tabObject;
Ken Takata9abd7152024-08-10 09:44:20 +02004491 Py_INCREF((PyObject *)tabObject);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004492
4493 return (PyObject *)(self);
4494}
4495
4496 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02004497WinListDestructor(WinListObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004498{
Bram Moolenaard6e39182013-05-21 18:30:34 +02004499 TabPageObject *tabObject = self->tabObject;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004500
4501 if (tabObject)
Bram Moolenaar425154d2013-05-24 18:58:43 +02004502 {
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004503 Py_DECREF((PyObject *)(tabObject));
Bram Moolenaar425154d2013-05-24 18:58:43 +02004504 }
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004505
4506 DESTRUCTOR_FINISH(self);
4507}
4508
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004509 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02004510WinListLength(WinListObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004511{
4512 win_T *w;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004513 PyInt n = 0;
4514
Bram Moolenaard6e39182013-05-21 18:30:34 +02004515 if (!(w = get_firstwin(self->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004516 return -1;
4517
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004518 while (w != NULL)
4519 {
4520 ++n;
4521 w = W_NEXT(w);
4522 }
4523
4524 return n;
4525}
4526
4527 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02004528WinListItem(WinListObject *self, PyInt n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004529{
4530 win_T *w;
4531
Bram Moolenaard6e39182013-05-21 18:30:34 +02004532 if (!(w = get_firstwin(self->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004533 return NULL;
4534
4535 for (; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004536 if (n == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02004537 return WindowNew(w, self->tabObject? self->tabObject->tab: curtab);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004538
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004539 PyErr_SET_STRING(PyExc_IndexError, N_("no such window"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004540 return NULL;
4541}
4542
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004543/*
4544 * Convert a Python string into a Vim line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004545 *
4546 * The result is in allocated memory. All internal nulls are replaced by
4547 * newline characters. It is an error for the string to contain newline
4548 * characters.
4549 *
4550 * On errors, the Python exception data is set, and NULL is returned.
4551 */
4552 static char *
4553StringToLine(PyObject *obj)
4554{
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004555 char *str;
4556 char *save;
4557 PyObject *bytes = NULL;
Bram Moolenaardee2e312013-06-23 16:35:47 +02004558 Py_ssize_t len = 0;
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004559 PyInt i;
4560 char *p;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004561
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004562 if (PyBytes_Check(obj))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004563 {
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004564 if (PyBytes_AsStringAndSize(obj, &str, &len) == -1
4565 || str == NULL)
4566 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004567 }
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004568 else if (PyUnicode_Check(obj))
4569 {
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01004570 if (!(bytes = PyUnicode_AsEncodedString(obj, ENC_OPT,
4571 ERRORS_ENCODE_ARG)))
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004572 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004573
Bram Moolenaardaa27022013-06-24 22:33:30 +02004574 if (PyBytes_AsStringAndSize(bytes, &str, &len) == -1
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004575 || str == NULL)
4576 {
4577 Py_DECREF(bytes);
4578 return NULL;
4579 }
4580 }
Bram Moolenaardaa27022013-06-24 22:33:30 +02004581 else
4582 {
4583#if PY_MAJOR_VERSION < 3
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004584 PyErr_FORMAT_TYPE(
Bram Moolenaardaa27022013-06-24 22:33:30 +02004585 N_("expected str() or unicode() instance, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004586 obj);
Bram Moolenaardaa27022013-06-24 22:33:30 +02004587#else
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004588 PyErr_FORMAT_TYPE(
Bram Moolenaardaa27022013-06-24 22:33:30 +02004589 N_("expected bytes() or str() instance, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02004590 obj);
Bram Moolenaardaa27022013-06-24 22:33:30 +02004591#endif
4592 return NULL;
4593 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004594
4595 /*
4596 * Error checking: String must not contain newlines, as we
4597 * are replacing a single line, and we must replace it with
4598 * a single line.
4599 * A trailing newline is removed, so that append(f.readlines()) works.
4600 */
4601 p = memchr(str, '\n', len);
4602 if (p != NULL)
4603 {
4604 if (p == str + len - 1)
4605 --len;
4606 else
4607 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004608 PyErr_SET_VIM(N_("string cannot contain newlines"));
Bram Moolenaar841fbd22013-06-23 14:37:07 +02004609 Py_XDECREF(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004610 return NULL;
4611 }
4612 }
4613
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004614 /*
4615 * Create a copy of the string, with internal nulls replaced by
Bram Moolenaar86181df2020-05-11 23:14:04 +02004616 * newline characters, as is the Vim convention.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004617 */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004618 save = alloc(len+1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004619 if (save == NULL)
4620 {
4621 PyErr_NoMemory();
Bram Moolenaar841fbd22013-06-23 14:37:07 +02004622 Py_XDECREF(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004623 return NULL;
4624 }
4625
4626 for (i = 0; i < len; ++i)
4627 {
4628 if (str[i] == '\0')
4629 save[i] = '\n';
4630 else
4631 save[i] = str[i];
4632 }
4633
4634 save[i] = '\0';
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004635 Py_XDECREF(bytes); // Python 2 does nothing here
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004636
4637 return save;
4638}
4639
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004640/*
4641 * Get a line from the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004642 * in Vim format (1-based). The line is returned as a Python
4643 * string object.
4644 */
4645 static PyObject *
4646GetBufferLine(buf_T *buf, PyInt n)
4647{
4648 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
4649}
4650
4651
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004652/*
4653 * Get a list of lines from the specified buffer. The line numbers
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004654 * are in Vim format (1-based). The range is from lo up to, but not
4655 * including, hi. The list is returned as a Python list of string objects.
4656 */
4657 static PyObject *
4658GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
4659{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004660 PyInt i;
4661 PyInt n = hi - lo;
4662 PyObject *list = PyList_New(n);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004663
4664 if (list == NULL)
4665 return NULL;
4666
4667 for (i = 0; i < n; ++i)
4668 {
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02004669 linenr_T lnum = (linenr_T)(lo + i);
4670 char *text;
4671 PyObject *string;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004672
Bram Moolenaarbb790dc2020-07-07 20:12:54 +02004673 if (lnum > buf->b_ml.ml_line_count)
4674 text = "";
4675 else
4676 text = (char *)ml_get_buf(buf, lnum, FALSE);
4677 string = LineToString(text);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004678 if (string == NULL)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004679 {
4680 Py_DECREF(list);
4681 return NULL;
4682 }
4683
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004684 PyList_SET_ITEM(list, i, string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004685 }
4686
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004687 // The ownership of the Python list is passed to the caller (ie,
4688 // the caller should Py_DECREF() the object when it is finished
4689 // with it).
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004690
4691 return list;
4692}
4693
4694/*
4695 * Check if deleting lines made the cursor position invalid.
4696 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
4697 * deleted).
4698 */
4699 static void
4700py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
4701{
4702 if (curwin->w_cursor.lnum >= lo)
4703 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004704 // Adjust the cursor position if it's in/after the changed
4705 // lines.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004706 if (curwin->w_cursor.lnum >= hi)
4707 {
4708 curwin->w_cursor.lnum += extra;
4709 check_cursor_col();
4710 }
4711 else if (extra < 0)
4712 {
4713 curwin->w_cursor.lnum = lo;
4714 check_cursor();
4715 }
4716 else
4717 check_cursor_col();
4718 changed_cline_bef_curs();
4719 }
4720 invalidate_botline();
4721}
4722
Bram Moolenaar19e60942011-06-19 00:27:51 +02004723/*
4724 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004725 * in Vim format (1-based). The replacement line is given as
4726 * a Python string object. The object is checked for validity
4727 * and correct format. Errors are returned as a value of FAIL.
4728 * The return value is OK on success.
4729 * If OK is returned and len_change is not NULL, *len_change
4730 * is set to the change in the buffer length.
4731 */
4732 static int
4733SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
4734{
Bram Moolenaar45e5fd12017-06-04 14:58:02 +02004735 bufref_T save_curbuf = {NULL, 0, 0};
Bram Moolenaar18f47402022-01-06 13:24:51 +00004736 switchwin_T switchwin;
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004737
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004738 // First of all, we check the type of the supplied Python object.
4739 // There are three cases:
4740 // 1. NULL, or None - this is a deletion.
4741 // 2. A string - this is a replacement.
4742 // 3. Anything else - this is an error.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004743 if (line == Py_None || line == NULL)
4744 {
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004745 PyErr_Clear();
Bram Moolenaar18f47402022-01-06 13:24:51 +00004746 switchwin.sw_curwin = NULL;
4747 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004748
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004749 VimTryStart();
4750
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004751 if (u_savedel((linenr_T)n, 1L) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02004752 RAISE_UNDO_FAIL;
Bram Moolenaarca70c072020-05-30 20:30:46 +02004753 else if (ml_delete((linenr_T)n) == FAIL)
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004754 RAISE_DELETE_LINE_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004755 else
4756 {
Bram Moolenaar18f47402022-01-06 13:24:51 +00004757 if (buf == curbuf && (switchwin.sw_curwin != NULL
Bram Moolenaar63dbfd32019-03-23 17:41:59 +01004758 || save_curbuf.br_buf == NULL))
4759 // Using an existing window for the buffer, adjust the cursor
4760 // position.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004761 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004762 if (save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004763 // Only adjust marks if we managed to switch to a window that
4764 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004765 deleted_lines_mark((linenr_T)n, 1L);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004766 }
4767
Bram Moolenaar18f47402022-01-06 13:24:51 +00004768 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004769
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004770 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004771 return FAIL;
4772
4773 if (len_change)
4774 *len_change = -1;
4775
4776 return OK;
4777 }
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004778 else if (PyBytes_Check(line) || PyUnicode_Check(line))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004779 {
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02004780 char *save = StringToLine(line);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004781
4782 if (save == NULL)
4783 return FAIL;
4784
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004785 VimTryStart();
4786
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004787 // We do not need to free "save" if ml_replace() consumes it.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004788 PyErr_Clear();
Bram Moolenaar18f47402022-01-06 13:24:51 +00004789 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004790
4791 if (u_savesub((linenr_T)n) == FAIL)
4792 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02004793 RAISE_UNDO_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004794 vim_free(save);
4795 }
4796 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
4797 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004798 RAISE_REPLACE_LINE_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004799 vim_free(save);
4800 }
4801 else
4802 changed_bytes((linenr_T)n, 0);
4803
Bram Moolenaar18f47402022-01-06 13:24:51 +00004804 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004805
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004806 // Check that the cursor is not beyond the end of the line now.
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004807 if (buf == curbuf)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004808 check_cursor_col();
4809
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004810 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02004811 return FAIL;
4812
4813 if (len_change)
4814 *len_change = 0;
4815
4816 return OK;
4817 }
4818 else
4819 {
4820 PyErr_BadArgument();
4821 return FAIL;
4822 }
4823}
4824
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004825/*
4826 * Replace a range of lines in the specified buffer. The line numbers are in
Bram Moolenaar19e60942011-06-19 00:27:51 +02004827 * Vim format (1-based). The range is from lo up to, but not including, hi.
4828 * The replacement lines are given as a Python list of string objects. The
4829 * list is checked for validity and correct format. Errors are returned as a
4830 * value of FAIL. The return value is OK on success.
4831 * If OK is returned and len_change is not NULL, *len_change
4832 * is set to the change in the buffer length.
4833 */
4834 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02004835SetBufferLineList(
4836 buf_T *buf,
4837 PyInt lo,
4838 PyInt hi,
4839 PyObject *list,
4840 PyInt *len_change)
Bram Moolenaar19e60942011-06-19 00:27:51 +02004841{
Bram Moolenaar45e5fd12017-06-04 14:58:02 +02004842 bufref_T save_curbuf = {NULL, 0, 0};
Bram Moolenaar18f47402022-01-06 13:24:51 +00004843 switchwin_T switchwin;
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004844
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004845 // First of all, we check the type of the supplied Python object.
4846 // There are three cases:
4847 // 1. NULL, or None - this is a deletion.
4848 // 2. A list - this is a replacement.
4849 // 3. Anything else - this is an error.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004850 if (list == Py_None || list == NULL)
4851 {
4852 PyInt i;
4853 PyInt n = (int)(hi - lo);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004854
4855 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004856 VimTryStart();
Bram Moolenaar18f47402022-01-06 13:24:51 +00004857 switchwin.sw_curwin = NULL;
4858 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004859
4860 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02004861 RAISE_UNDO_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004862 else
4863 {
4864 for (i = 0; i < n; ++i)
4865 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02004866 if (ml_delete((linenr_T)lo) == FAIL)
Bram Moolenaar19e60942011-06-19 00:27:51 +02004867 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004868 RAISE_DELETE_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004869 break;
4870 }
4871 }
Bram Moolenaar18f47402022-01-06 13:24:51 +00004872 if (buf == curbuf && (switchwin.sw_curwin != NULL
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004873 || save_curbuf.br_buf == NULL))
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004874 // Using an existing window for the buffer, adjust the cursor
4875 // position.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004876 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004877 if (save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004878 // Only adjust marks if we managed to switch to a window that
4879 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaaraf003f62013-07-24 17:11:46 +02004880 deleted_lines_mark((linenr_T)lo, (long)i);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004881 }
4882
Bram Moolenaar18f47402022-01-06 13:24:51 +00004883 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004884
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004885 if (VimTryEnd())
Bram Moolenaar19e60942011-06-19 00:27:51 +02004886 return FAIL;
4887
4888 if (len_change)
4889 *len_change = -n;
4890
4891 return OK;
4892 }
4893 else if (PyList_Check(list))
4894 {
4895 PyInt i;
4896 PyInt new_len = PyList_Size(list);
4897 PyInt old_len = hi - lo;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004898 PyInt extra = 0; // lines added to text, can be negative
Bram Moolenaar19e60942011-06-19 00:27:51 +02004899 char **array;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004900
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004901 if (new_len == 0) // avoid allocating zero bytes
Bram Moolenaar19e60942011-06-19 00:27:51 +02004902 array = NULL;
4903 else
4904 {
Bram Moolenaare9ba5162013-05-29 22:02:22 +02004905 array = PyMem_New(char *, new_len);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004906 if (array == NULL)
4907 {
4908 PyErr_NoMemory();
4909 return FAIL;
4910 }
4911 }
4912
4913 for (i = 0; i < new_len; ++i)
4914 {
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02004915 PyObject *line;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004916
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02004917 if (!(line = PyList_GetItem(list, i)) ||
4918 !(array[i] = StringToLine(line)))
Bram Moolenaar19e60942011-06-19 00:27:51 +02004919 {
4920 while (i)
4921 vim_free(array[--i]);
Bram Moolenaare9ba5162013-05-29 22:02:22 +02004922 PyMem_Free(array);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004923 return FAIL;
4924 }
4925 }
4926
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02004927 VimTryStart();
Bram Moolenaar19e60942011-06-19 00:27:51 +02004928 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02004929
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004930 // START of region without "return". Must call restore_buffer()!
Bram Moolenaar18f47402022-01-06 13:24:51 +00004931 switchwin.sw_curwin = NULL;
4932 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004933
4934 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02004935 RAISE_UNDO_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004936
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004937 // If the size of the range is reducing (ie, new_len < old_len) we
4938 // need to delete some old_len. We do this at the start, by
4939 // repeatedly deleting line "lo".
Bram Moolenaar19e60942011-06-19 00:27:51 +02004940 if (!PyErr_Occurred())
4941 {
4942 for (i = 0; i < old_len - new_len; ++i)
Bram Moolenaarca70c072020-05-30 20:30:46 +02004943 if (ml_delete((linenr_T)lo) == FAIL)
Bram Moolenaar19e60942011-06-19 00:27:51 +02004944 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004945 RAISE_DELETE_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004946 break;
4947 }
4948 extra -= i;
4949 }
4950
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004951 // For as long as possible, replace the existing old_len with the
4952 // new old_len. This is a more efficient operation, as it requires
4953 // less memory allocation and freeing.
Bram Moolenaar19e60942011-06-19 00:27:51 +02004954 if (!PyErr_Occurred())
4955 {
4956 for (i = 0; i < old_len && i < new_len; ++i)
4957 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
4958 == FAIL)
4959 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004960 RAISE_REPLACE_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004961 break;
4962 }
4963 }
4964 else
4965 i = 0;
4966
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004967 // Now we may need to insert the remaining new old_len. If we do, we
4968 // must free the strings as we finish with them (we can't pass the
Bram Moolenaar86181df2020-05-11 23:14:04 +02004969 // responsibility to Vim in this case).
Bram Moolenaar19e60942011-06-19 00:27:51 +02004970 if (!PyErr_Occurred())
4971 {
4972 while (i < new_len)
4973 {
4974 if (ml_append((linenr_T)(lo + i - 1),
4975 (char_u *)array[i], 0, FALSE) == FAIL)
4976 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02004977 RAISE_INSERT_LINE_FAIL;
Bram Moolenaar19e60942011-06-19 00:27:51 +02004978 break;
4979 }
4980 vim_free(array[i]);
4981 ++i;
4982 ++extra;
4983 }
4984 }
4985
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004986 // Free any left-over old_len, as a result of an error
Bram Moolenaar19e60942011-06-19 00:27:51 +02004987 while (i < new_len)
4988 {
4989 vim_free(array[i]);
4990 ++i;
4991 }
4992
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004993 // Free the array of old_len. All of its contents have now
4994 // been dealt with (either freed, or the responsibility passed
4995 // to vim.
Bram Moolenaare9ba5162013-05-29 22:02:22 +02004996 PyMem_Free(array);
Bram Moolenaar19e60942011-06-19 00:27:51 +02004997
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01004998 // Adjust marks. Invalidate any which lie in the
4999 // changed range, and move any in the remainder of the buffer.
5000 // Only adjust marks if we managed to switch to a window that holds
5001 // the buffer, otherwise line numbers will be invalid.
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005002 if (save_curbuf.br_buf == NULL)
Bram Moolenaar37233f62022-05-22 12:23:48 +01005003 {
Bram Moolenaaraf003f62013-07-24 17:11:46 +02005004 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
Bram Moolenaar19e60942011-06-19 00:27:51 +02005005 (long)MAXLNUM, (long)extra);
Bram Moolenaar37233f62022-05-22 12:23:48 +01005006 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
5007 }
Bram Moolenaar19e60942011-06-19 00:27:51 +02005008
Bram Moolenaar18f47402022-01-06 13:24:51 +00005009 if (buf == curbuf && (switchwin.sw_curwin != NULL
Bram Moolenaar63dbfd32019-03-23 17:41:59 +01005010 || save_curbuf.br_buf == NULL))
5011 // Using an existing window for the buffer, adjust the cursor
5012 // position.
Bram Moolenaar19e60942011-06-19 00:27:51 +02005013 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
5014
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005015 // END of region without "return".
Bram Moolenaar18f47402022-01-06 13:24:51 +00005016 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02005017
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005018 if (VimTryEnd())
Bram Moolenaar19e60942011-06-19 00:27:51 +02005019 return FAIL;
5020
5021 if (len_change)
5022 *len_change = new_len - old_len;
5023
5024 return OK;
5025 }
5026 else
5027 {
5028 PyErr_BadArgument();
5029 return FAIL;
5030 }
5031}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005032
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005033/*
5034 * Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005035 * The line number is in Vim format (1-based). The lines to be inserted are
5036 * given as a Python list of string objects or as a single string. The lines
5037 * to be added are checked for validity and correct format. Errors are
5038 * returned as a value of FAIL. The return value is OK on success.
5039 * If OK is returned and len_change is not NULL, *len_change
5040 * is set to the change in the buffer length.
5041 */
5042 static int
5043InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
5044{
Bram Moolenaar45e5fd12017-06-04 14:58:02 +02005045 bufref_T save_curbuf = {NULL, 0, 0};
Bram Moolenaar18f47402022-01-06 13:24:51 +00005046 switchwin_T switchwin;
Bram Moolenaar95064ec2013-07-17 17:15:25 +02005047
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005048 // First of all, we check the type of the supplied Python object.
5049 // It must be a string or a list, or the call is in error.
Bram Moolenaar808c2bc2013-06-23 13:11:18 +02005050 if (PyBytes_Check(lines) || PyUnicode_Check(lines))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005051 {
Bram Moolenaar95064ec2013-07-17 17:15:25 +02005052 char *str = StringToLine(lines);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005053
5054 if (str == NULL)
5055 return FAIL;
5056
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005057 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005058 VimTryStart();
Bram Moolenaar18f47402022-01-06 13:24:51 +00005059 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005060
Bram Moolenaar95064ec2013-07-17 17:15:25 +02005061 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02005062 RAISE_UNDO_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005063 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005064 RAISE_INSERT_LINE_FAIL;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005065 else if (save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005066 // Only adjust marks if we managed to switch to a window that
5067 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005068 appended_lines_mark((linenr_T)n, 1L);
5069
5070 vim_free(str);
Bram Moolenaar18f47402022-01-06 13:24:51 +00005071 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005072 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005073
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005074 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005075 return FAIL;
5076
5077 if (len_change)
5078 *len_change = 1;
5079
5080 return OK;
5081 }
5082 else if (PyList_Check(lines))
5083 {
5084 PyInt i;
5085 PyInt size = PyList_Size(lines);
5086 char **array;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005087
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005088 array = PyMem_New(char *, size);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005089 if (array == NULL)
5090 {
5091 PyErr_NoMemory();
5092 return FAIL;
5093 }
5094
5095 for (i = 0; i < size; ++i)
5096 {
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005097 PyObject *line;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005098
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005099 if (!(line = PyList_GetItem(lines, i)) ||
5100 !(array[i] = StringToLine(line)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005101 {
5102 while (i)
5103 vim_free(array[--i]);
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005104 PyMem_Free(array);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005105 return FAIL;
5106 }
5107 }
5108
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005109 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005110 VimTryStart();
Bram Moolenaar18f47402022-01-06 13:24:51 +00005111 switch_to_win_for_buf(buf, &switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005112
5113 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
Bram Moolenaarc476e522013-06-23 13:46:40 +02005114 RAISE_UNDO_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005115 else
5116 {
5117 for (i = 0; i < size; ++i)
5118 {
5119 if (ml_append((linenr_T)(n + i),
5120 (char_u *)array[i], 0, FALSE) == FAIL)
5121 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005122 RAISE_INSERT_LINE_FAIL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005123
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005124 // Free the rest of the lines
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005125 while (i < size)
5126 vim_free(array[i++]);
5127
5128 break;
5129 }
5130 vim_free(array[i]);
5131 }
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005132 if (i > 0 && save_curbuf.br_buf == NULL)
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005133 // Only adjust marks if we managed to switch to a window that
5134 // holds the buffer, otherwise line numbers will be invalid.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005135 appended_lines_mark((linenr_T)n, (long)i);
5136 }
5137
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005138 // Free the array of lines. All of its contents have now
5139 // been freed.
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005140 PyMem_Free(array);
Bram Moolenaar18f47402022-01-06 13:24:51 +00005141 restore_win_for_buf(&switchwin, &save_curbuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005142
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005143 update_screen(UPD_VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005144
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005145 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005146 return FAIL;
5147
5148 if (len_change)
5149 *len_change = size;
5150
5151 return OK;
5152 }
5153 else
5154 {
5155 PyErr_BadArgument();
5156 return FAIL;
5157 }
5158}
5159
5160/*
5161 * Common routines for buffers and line ranges
5162 * -------------------------------------------
5163 */
5164
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005165typedef struct
5166{
5167 PyObject_HEAD
5168 buf_T *buf;
5169} BufferObject;
5170
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005171 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02005172CheckBuffer(BufferObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005173{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005174 if (self->buf == INVALID_BUFFER_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005175 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005176 PyErr_SET_VIM(N_("attempt to refer to deleted buffer"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005177 return -1;
5178 }
5179
5180 return 0;
5181}
5182
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005183 static int
5184CheckBufferCb(void *self)
5185{
5186 return CheckBuffer((BufferObject*)self);
5187}
5188
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005189 static PyObject *
5190RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
5191{
5192 if (CheckBuffer(self))
5193 return NULL;
5194
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005195 if (end == -1)
5196 end = self->buf->b_ml.ml_line_count;
5197
Bram Moolenaarbd80f352013-05-12 21:16:23 +02005198 if (n < 0)
5199 n += end - start + 1;
5200
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005201 if (n < 0 || n > end - start)
5202 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005203 PyErr_SET_STRING(PyExc_IndexError, N_("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005204 return NULL;
5205 }
5206
5207 return GetBufferLine(self->buf, n+start);
5208}
5209
5210 static PyObject *
5211RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
5212{
5213 PyInt size;
5214
5215 if (CheckBuffer(self))
5216 return NULL;
5217
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005218 if (end == -1)
5219 end = self->buf->b_ml.ml_line_count;
5220
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005221 size = end - start + 1;
5222
5223 if (lo < 0)
5224 lo = 0;
5225 else if (lo > size)
5226 lo = size;
5227 if (hi < 0)
5228 hi = 0;
5229 if (hi < lo)
5230 hi = lo;
5231 else if (hi > size)
5232 hi = size;
5233
5234 return GetBufferLineList(self->buf, lo+start, hi+start);
5235}
5236
5237 static PyInt
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005238RBAsItem(
5239 BufferObject *self,
5240 PyInt n,
5241 PyObject *valObject,
5242 PyInt start,
5243 PyInt end,
5244 PyInt *new_end)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005245{
5246 PyInt len_change;
5247
5248 if (CheckBuffer(self))
5249 return -1;
5250
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005251 if (end == -1)
5252 end = self->buf->b_ml.ml_line_count;
5253
Bram Moolenaarbd80f352013-05-12 21:16:23 +02005254 if (n < 0)
5255 n += end - start + 1;
5256
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005257 if (n < 0 || n > end - start)
5258 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005259 PyErr_SET_STRING(PyExc_IndexError, N_("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005260 return -1;
5261 }
5262
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005263 if (SetBufferLine(self->buf, n+start, valObject, &len_change) == FAIL)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005264 return -1;
5265
5266 if (new_end)
5267 *new_end = end + len_change;
5268
5269 return 0;
5270}
5271
Bram Moolenaar19e60942011-06-19 00:27:51 +02005272 static PyInt
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005273RBAsSlice(
5274 BufferObject *self,
5275 PyInt lo,
5276 PyInt hi,
5277 PyObject *valObject,
5278 PyInt start,
5279 PyInt end,
5280 PyInt *new_end)
Bram Moolenaar19e60942011-06-19 00:27:51 +02005281{
5282 PyInt size;
5283 PyInt len_change;
5284
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005285 // Self must be a valid buffer
Bram Moolenaar19e60942011-06-19 00:27:51 +02005286 if (CheckBuffer(self))
5287 return -1;
5288
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005289 if (end == -1)
5290 end = self->buf->b_ml.ml_line_count;
5291
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005292 // Sort out the slice range
Bram Moolenaar19e60942011-06-19 00:27:51 +02005293 size = end - start + 1;
5294
5295 if (lo < 0)
5296 lo = 0;
5297 else if (lo > size)
5298 lo = size;
5299 if (hi < 0)
5300 hi = 0;
5301 if (hi < lo)
5302 hi = lo;
5303 else if (hi > size)
5304 hi = size;
5305
5306 if (SetBufferLineList(self->buf, lo + start, hi + start,
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005307 valObject, &len_change) == FAIL)
Bram Moolenaar19e60942011-06-19 00:27:51 +02005308 return -1;
5309
5310 if (new_end)
5311 *new_end = end + len_change;
5312
5313 return 0;
5314}
5315
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005316
5317 static PyObject *
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005318RBAppend(
5319 BufferObject *self,
5320 PyObject *args,
5321 PyInt start,
5322 PyInt end,
5323 PyInt *new_end)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005324{
5325 PyObject *lines;
5326 PyInt len_change;
5327 PyInt max;
5328 PyInt n;
5329
5330 if (CheckBuffer(self))
5331 return NULL;
5332
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02005333 if (end == -1)
5334 end = self->buf->b_ml.ml_line_count;
5335
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005336 max = n = end - start + 1;
5337
5338 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
5339 return NULL;
5340
5341 if (n < 0 || n > max)
5342 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005343 PyErr_SET_STRING(PyExc_IndexError, N_("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005344 return NULL;
5345 }
5346
5347 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
5348 return NULL;
5349
5350 if (new_end)
5351 *new_end = end + len_change;
5352
5353 Py_INCREF(Py_None);
5354 return Py_None;
5355}
5356
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005357// Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005358
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005359DEFINE_PY_TYPE_OBJECT(RangeType);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005360static PySequenceMethods RangeAsSeq;
5361static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005362
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005363typedef struct
5364{
5365 PyObject_HEAD
5366 BufferObject *buf;
5367 PyInt start;
5368 PyInt end;
5369} RangeObject;
5370
5371 static PyObject *
5372RangeNew(buf_T *buf, PyInt start, PyInt end)
5373{
5374 BufferObject *bufr;
5375 RangeObject *self;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005376 self = PyObject_GC_New(RangeObject, RangeTypePtr);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005377 if (self == NULL)
5378 return NULL;
5379
5380 bufr = (BufferObject *)BufferNew(buf);
5381 if (bufr == NULL)
5382 {
5383 Py_DECREF(self);
5384 return NULL;
5385 }
Ken Takata9abd7152024-08-10 09:44:20 +02005386 Py_INCREF((PyObject *)bufr);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005387
5388 self->buf = bufr;
5389 self->start = start;
5390 self->end = end;
5391
5392 return (PyObject *)(self);
5393}
5394
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005395 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005396RangeDestructor(PyObject *self_obj)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005397{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005398 RangeObject *self = (RangeObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005399 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005400 Py_XDECREF(self->buf);
Bram Moolenaar774267b2013-05-21 20:51:59 +02005401 PyObject_GC_Del((void *)(self));
5402}
5403
5404 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005405RangeTraverse(PyObject *self_obj, visitproc visit, void *arg)
Bram Moolenaar774267b2013-05-21 20:51:59 +02005406{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005407 RangeObject *self = (RangeObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005408 Py_VISIT(((PyObject *)(self->buf)));
5409 return 0;
5410}
5411
5412 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005413RangeClear(PyObject *self_obj)
Bram Moolenaar774267b2013-05-21 20:51:59 +02005414{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005415 RangeObject *self = (RangeObject*)self_obj;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005416 Py_CLEAR(self->buf);
5417 return 0;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005418}
5419
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005420 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02005421RangeLength(RangeObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005422{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005423 // HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION?
Bram Moolenaard6e39182013-05-21 18:30:34 +02005424 if (CheckBuffer(self->buf))
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005425 return -1; // ???
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005426
Bram Moolenaard6e39182013-05-21 18:30:34 +02005427 return (self->end - self->start + 1);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005428}
5429
5430 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005431RangeItem(RangeObject *self, PyInt n)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005432{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005433 return RBItem(self->buf, n, self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005434}
5435
5436 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005437RangeSlice(RangeObject *self, PyInt lo, PyInt hi)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005438{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005439 return RBSlice(self->buf, lo, hi, self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005440}
5441
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005442static char *RangeAttrs[] = {
5443 "start", "end",
5444 NULL
5445};
5446
5447 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02005448RangeDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005449{
5450 return ObjectDir(self, RangeAttrs);
5451}
5452
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005453 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005454RangeAppend(RangeObject *self, PyObject *args)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005455{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005456 return RBAppend(self->buf, args, self->start, self->end, &self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005457}
5458
5459 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005460RangeRepr(PyObject *self_obj)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005461{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005462 RangeObject *self = (RangeObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02005463 if (self->buf->buf == INVALID_BUFFER_VALUE)
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005464 return PyString_FromFormat("<range object (for deleted buffer) at %p>",
Dominique Pellec14f6672022-01-09 12:57:48 +00005465 (void *)self);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005466 else
5467 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02005468 char *name = (char *)self->buf->buf->b_fname;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005469
5470 if (name == NULL)
5471 name = "";
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005472
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005473 return PyString_FromFormat("<range %s (%d:%d)>",
Bram Moolenaarf62d9422013-05-30 19:01:24 +02005474 name, (int)self->start, (int)self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005475 }
5476}
5477
5478static struct PyMethodDef RangeMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005479 // name, function, calling, documentation
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02005480 {"append", (PyCFunction)RangeAppend, METH_VARARGS, "Append data to the Vim range" },
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005481 {"__dir__", (PyCFunction)RangeDir, METH_NOARGS, ""},
5482 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005483};
5484
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005485DEFINE_PY_TYPE_OBJECT(BufferType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005486static PySequenceMethods BufferAsSeq;
5487static PyMappingMethods BufferAsMapping;
5488
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005489 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02005490BufferNew(buf_T *buf)
5491{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005492 /*
5493 * We need to handle deletion of buffers underneath us.
Bram Moolenaar971db462013-05-12 18:44:48 +02005494 * If we add a "b_python*_ref" field to the buf_T structure,
5495 * then we can get at it in buf_freeall() in vim. We then
5496 * need to create only ONE Python object per buffer - if
5497 * we try to create a second, just INCREF the existing one
5498 * and return it. The (single) Python object referring to
5499 * the buffer is stored in "b_python*_ref".
5500 * Question: what to do on a buf_freeall(). We'll probably
5501 * have to either delete the Python object (DECREF it to
5502 * zero - a bad idea, as it leaves dangling refs!) or
5503 * set the buf_T * value to an invalid value (-1?), which
5504 * means we need checks in all access functions... Bah.
5505 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005506 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02005507 * b_python_ref and b_python3_ref fields respectively.
5508 */
5509
5510 BufferObject *self;
5511
5512 if (BUF_PYTHON_REF(buf) != NULL)
5513 {
5514 self = BUF_PYTHON_REF(buf);
Ken Takata9abd7152024-08-10 09:44:20 +02005515 Py_INCREF((PyObject *)self);
Bram Moolenaar971db462013-05-12 18:44:48 +02005516 }
5517 else
5518 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005519 self = PyObject_NEW(BufferObject, BufferTypePtr);
Bram Moolenaar971db462013-05-12 18:44:48 +02005520 if (self == NULL)
5521 return NULL;
5522 self->buf = buf;
5523 BUF_PYTHON_REF(buf) = self;
5524 }
5525
5526 return (PyObject *)(self);
5527}
5528
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005529 static void
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005530BufferDestructor(PyObject *self_obj)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005531{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005532 BufferObject *self = (BufferObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02005533 if (self->buf && self->buf != INVALID_BUFFER_VALUE)
5534 BUF_PYTHON_REF(self->buf) = NULL;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005535
5536 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005537}
5538
Bram Moolenaar971db462013-05-12 18:44:48 +02005539 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02005540BufferLength(BufferObject *self)
Bram Moolenaar971db462013-05-12 18:44:48 +02005541{
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005542 // HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION?
Bram Moolenaard6e39182013-05-21 18:30:34 +02005543 if (CheckBuffer(self))
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005544 return -1; // ???
Bram Moolenaar971db462013-05-12 18:44:48 +02005545
Bram Moolenaard6e39182013-05-21 18:30:34 +02005546 return (PyInt)(self->buf->b_ml.ml_line_count);
Bram Moolenaar971db462013-05-12 18:44:48 +02005547}
5548
5549 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005550BufferItem(BufferObject *self, PyInt n)
Bram Moolenaar971db462013-05-12 18:44:48 +02005551{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005552 return RBItem(self, n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02005553}
5554
5555 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005556BufferSlice(BufferObject *self, PyInt lo, PyInt hi)
Bram Moolenaar971db462013-05-12 18:44:48 +02005557{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005558 return RBSlice(self, lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02005559}
5560
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005561static char *BufferAttrs[] = {
5562 "name", "number", "vars", "options", "valid",
5563 NULL
5564};
5565
5566 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02005567BufferDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005568{
5569 return ObjectDir(self, BufferAttrs);
5570}
5571
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005572 static PyObject *
Bram Moolenaar9e822c02013-05-29 22:15:30 +02005573BufferAttrValid(BufferObject *self, char *name)
5574{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005575 PyObject *ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02005576
5577 if (strcmp(name, "valid") != 0)
5578 return NULL;
5579
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005580 ret = ((self->buf == INVALID_BUFFER_VALUE) ? Py_False : Py_True);
5581 Py_INCREF(ret);
5582 return ret;
Bram Moolenaar9e822c02013-05-29 22:15:30 +02005583}
5584
5585 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005586BufferAttr(BufferObject *self, char *name)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005587{
5588 if (strcmp(name, "name") == 0)
Bram Moolenaar432b09c2013-05-29 22:26:18 +02005589 return PyString_FromString((self->buf->b_ffname == NULL
Bram Moolenaar41009372013-07-01 22:03:04 +02005590 ? "" : (char *)self->buf->b_ffname));
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005591 else if (strcmp(name, "number") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02005592 return Py_BuildValue(Py_ssize_t_fmt, self->buf->b_fnum);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005593 else if (strcmp(name, "vars") == 0)
Bram Moolenaara9922d62013-05-30 13:01:18 +02005594 return NEW_DICTIONARY(self->buf->b_vars);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005595 else if (strcmp(name, "options") == 0)
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005596 return OptionsNew(SREQ_BUF, self->buf, CheckBufferCb,
Bram Moolenaard6e39182013-05-21 18:30:34 +02005597 (PyObject *) self);
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005598 else if (strcmp(name, "__members__") == 0)
5599 return ObjectDir(NULL, BufferAttrs);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005600 else
5601 return NULL;
5602}
5603
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005604 static int
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005605BufferSetattr(PyObject *self_obj, char *name, PyObject *valObject)
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005606{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005607 BufferObject *self = (BufferObject*)self_obj;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005608 if (CheckBuffer(self))
5609 return -1;
5610
5611 if (strcmp(name, "name") == 0)
5612 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005613 char_u *val;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005614 aco_save_T aco;
Bram Moolenaar37199892022-11-29 13:46:48 +00005615 int ren_ret = OK;
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005616 PyObject *todecref;
5617
5618 if (!(val = StringToChars(valObject, &todecref)))
5619 return -1;
5620
5621 VimTryStart();
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005622 // Using aucmd_*: autocommands will be executed by rename_buffer
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005623 aucmd_prepbuf(&aco, self->buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00005624 if (curbuf == self->buf)
5625 {
5626 ren_ret = rename_buffer(val);
5627 aucmd_restbuf(&aco);
5628 }
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005629 Py_XDECREF(todecref);
5630 if (VimTryEnd())
5631 return -1;
5632
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005633 if (ren_ret == FAIL)
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005634 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005635 PyErr_SET_VIM(N_("failed to rename buffer"));
Bram Moolenaare9ba5162013-05-29 22:02:22 +02005636 return -1;
5637 }
5638 return 0;
5639 }
5640 else
5641 {
5642 PyErr_SetString(PyExc_AttributeError, name);
5643 return -1;
5644 }
5645}
5646
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02005647 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005648BufferAppend(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005649{
Bram Moolenaard6e39182013-05-21 18:30:34 +02005650 return RBAppend(self, args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005651}
5652
5653 static PyObject *
Bram Moolenaar389a1792013-06-23 13:00:44 +02005654BufferMark(BufferObject *self, PyObject *pmarkObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005655{
5656 pos_T *posp;
Bram Moolenaar389a1792013-06-23 13:00:44 +02005657 char_u *pmark;
5658 char_u mark;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005659 bufref_T savebuf;
Bram Moolenaar389a1792013-06-23 13:00:44 +02005660 PyObject *todecref;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005661
Bram Moolenaard6e39182013-05-21 18:30:34 +02005662 if (CheckBuffer(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005663 return NULL;
5664
Bram Moolenaar389a1792013-06-23 13:00:44 +02005665 if (!(pmark = StringToChars(pmarkObject, &todecref)))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005666 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005667
Bram Moolenaar389a1792013-06-23 13:00:44 +02005668 if (pmark[0] == '\0' || pmark[1] != '\0')
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005669 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005670 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005671 N_("mark name must be a single character"));
Bram Moolenaar841fbd22013-06-23 14:37:07 +02005672 Py_XDECREF(todecref);
Bram Moolenaar494ff7e2013-05-30 13:17:17 +02005673 return NULL;
5674 }
5675
5676 mark = *pmark;
Bram Moolenaar389a1792013-06-23 13:00:44 +02005677
5678 Py_XDECREF(todecref);
5679
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005680 VimTryStart();
Bram Moolenaard6e39182013-05-21 18:30:34 +02005681 switch_buffer(&savebuf, self->buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005682 posp = getmark(mark, FALSE);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02005683 restore_buffer(&savebuf);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005684 if (VimTryEnd())
5685 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005686
5687 if (posp == NULL)
5688 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005689 PyErr_SET_VIM(N_("invalid mark name"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005690 return NULL;
5691 }
5692
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005693 if (posp->lnum <= 0)
5694 {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005695 // Or raise an error?
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005696 Py_INCREF(Py_None);
5697 return Py_None;
5698 }
5699
5700 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
5701}
5702
5703 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02005704BufferRange(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005705{
5706 PyInt start;
5707 PyInt end;
5708
Bram Moolenaard6e39182013-05-21 18:30:34 +02005709 if (CheckBuffer(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005710 return NULL;
5711
5712 if (!PyArg_ParseTuple(args, "nn", &start, &end))
5713 return NULL;
5714
Bram Moolenaard6e39182013-05-21 18:30:34 +02005715 return RangeNew(self->buf, start, end);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005716}
5717
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005718 static PyObject *
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005719BufferRepr(PyObject *self_obj)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005720{
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005721 BufferObject *self = (BufferObject*)self_obj;
Bram Moolenaard6e39182013-05-21 18:30:34 +02005722 if (self->buf == INVALID_BUFFER_VALUE)
Dominique Pellec14f6672022-01-09 12:57:48 +00005723 return PyString_FromFormat("<buffer object (deleted) at %p>", (void *)self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005724 else
5725 {
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005726 char *name = (char *)self->buf->b_fname;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005727
5728 if (name == NULL)
5729 name = "";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005730
Bram Moolenaar1a3b5692013-05-30 12:40:39 +02005731 return PyString_FromFormat("<buffer %s>", name);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005732 }
5733}
5734
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005735static struct PyMethodDef BufferMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005736 // name, function, calling, documentation
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02005737 {"append", (PyCFunction)BufferAppend, METH_VARARGS, "Append data to Vim buffer" },
Bram Moolenaar389a1792013-06-23 13:00:44 +02005738 {"mark", (PyCFunction)BufferMark, METH_O, "Return (row,col) representing position of named mark" },
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02005739 {"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 +02005740 {"__dir__", (PyCFunction)BufferDir, METH_NOARGS, ""},
5741 { NULL, NULL, 0, NULL}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005742};
5743
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005744/*
5745 * Buffer list object - Implementation
5746 */
5747
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005748DEFINE_PY_TYPE_OBJECT(BufMapType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005749
5750typedef struct
5751{
5752 PyObject_HEAD
5753} BufMapObject;
5754
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005755static BufMapObject TheBufferMap =
5756{
5757 PyObject_HEAD_INIT_TYPE(BufMapType)
5758};
5759
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005760 static PyInt
5761BufMapLength(PyObject *self UNUSED)
5762{
5763 buf_T *b = firstbuf;
5764 PyInt n = 0;
5765
5766 while (b)
5767 {
5768 ++n;
5769 b = b->b_next;
5770 }
5771
5772 return n;
5773}
5774
5775 static PyObject *
5776BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
5777{
5778 buf_T *b;
Bram Moolenaar141be8a2013-06-23 14:16:57 +02005779 long bnr;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005780
Bram Moolenaar141be8a2013-06-23 14:16:57 +02005781 if (NumberToLong(keyObject, &bnr, NUMBER_INT|NUMBER_NATURAL))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005782 return NULL;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005783
Bram Moolenaar141be8a2013-06-23 14:16:57 +02005784 b = buflist_findnr((int) bnr);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005785
5786 if (b)
5787 return BufferNew(b);
5788 else
5789 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02005790 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005791 return NULL;
5792 }
5793}
5794
5795 static void
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005796BufMapIterDestruct(void* arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005797{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005798 PyObject *buffer = (PyObject*)arg;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005799 // Iteration was stopped before all buffers were processed
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005800 if (buffer)
5801 {
5802 Py_DECREF(buffer);
5803 }
5804}
5805
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005806 static int
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005807BufMapIterTraverse(void *iter, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005808{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005809 PyObject *buffer = (PyObject*)iter;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005810 if (buffer)
5811 Py_VISIT(buffer);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005812 return 0;
5813}
5814
5815 static int
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005816BufMapIterClear(void **iter)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005817{
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005818 PyObject **buffer = (PyObject**)iter;
Bram Moolenaar774267b2013-05-21 20:51:59 +02005819 if (*buffer)
5820 Py_CLEAR(*buffer);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02005821 return 0;
5822}
5823
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005824 static PyObject *
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005825BufMapIterNext(void **arg)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005826{
5827 PyObject *next;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005828 PyObject *ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005829 PyObject **buffer = (PyObject**)arg;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005830
5831 if (!*buffer)
5832 return NULL;
5833
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005834 ret = *buffer;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005835
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005836 if (CheckBuffer((BufferObject *)(ret)))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005837 {
5838 *buffer = NULL;
5839 return NULL;
5840 }
5841
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005842 if (!((BufferObject *)(ret))->buf->b_next)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005843 next = NULL;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005844 else if (!(next = BufferNew(((BufferObject *)(ret))->buf->b_next)))
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005845 return NULL;
5846 *buffer = next;
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005847 // Do not increment reference: we no longer hold it (decref), but whoever
5848 // on other side will hold (incref). Decref+incref = nothing.
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005849 return ret;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005850}
5851
5852 static PyObject *
Bram Moolenaar423a85a2020-08-29 12:57:16 +02005853BufMapIter(PyObject *self)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005854{
5855 PyObject *buffer;
5856
5857 buffer = BufferNew(firstbuf);
5858 return IterNew(buffer,
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02005859 BufMapIterDestruct, BufMapIterNext,
5860 BufMapIterTraverse, BufMapIterClear,
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02005861 self);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02005862}
5863
5864static PyMappingMethods BufMapAsMapping = {
5865 (lenfunc) BufMapLength,
5866 (binaryfunc) BufMapItem,
5867 (objobjargproc) 0,
5868};
5869
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01005870// Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02005871
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005872static char *CurrentAttrs[] = {
5873 "buffer", "window", "line", "range", "tabpage",
5874 NULL
5875};
5876
5877 static PyObject *
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02005878CurrentDir(PyObject *self, PyObject *args UNUSED)
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005879{
5880 return ObjectDir(self, CurrentAttrs);
5881}
5882
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005883 static PyObject *
5884CurrentGetattr(PyObject *self UNUSED, char *name)
5885{
5886 if (strcmp(name, "buffer") == 0)
5887 return (PyObject *)BufferNew(curbuf);
5888 else if (strcmp(name, "window") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02005889 return (PyObject *)WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02005890 else if (strcmp(name, "tabpage") == 0)
5891 return (PyObject *)TabPageNew(curtab);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005892 else if (strcmp(name, "line") == 0)
5893 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
5894 else if (strcmp(name, "range") == 0)
5895 return RangeNew(curbuf, RangeStart, RangeEnd);
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005896 else if (strcmp(name, "__members__") == 0)
5897 return ObjectDir(NULL, CurrentAttrs);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005898 else
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005899#if PY_MAJOR_VERSION < 3
5900 return Py_FindMethod(WindowMethods, self, name);
5901#else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005902 return NULL;
Bram Moolenaardd8aca62013-05-29 22:36:10 +02005903#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005904}
5905
5906 static int
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005907CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *valObject)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005908{
5909 if (strcmp(name, "line") == 0)
5910 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005911 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, valObject,
5912 NULL) == FAIL)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02005913 return -1;
5914
5915 return 0;
5916 }
Bram Moolenaare7614592013-05-15 15:51:08 +02005917 else if (strcmp(name, "buffer") == 0)
5918 {
5919 int count;
5920
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005921 if (valObject->ob_type != BufferTypePtr)
Bram Moolenaare7614592013-05-15 15:51:08 +02005922 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005923 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005924 N_("expected vim.Buffer object, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005925 valObject);
Bram Moolenaare7614592013-05-15 15:51:08 +02005926 return -1;
5927 }
5928
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005929 if (CheckBuffer((BufferObject *)(valObject)))
Bram Moolenaare7614592013-05-15 15:51:08 +02005930 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005931 count = ((BufferObject *)(valObject))->buf->b_fnum;
Bram Moolenaare7614592013-05-15 15:51:08 +02005932
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005933 VimTryStart();
Bram Moolenaare7614592013-05-15 15:51:08 +02005934 if (do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, count, 0) == FAIL)
5935 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005936 if (VimTryEnd())
5937 return -1;
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005938 PyErr_VIM_FORMAT(N_("failed to switch to buffer %d"), count);
Bram Moolenaare7614592013-05-15 15:51:08 +02005939 return -1;
5940 }
5941
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005942 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02005943 }
5944 else if (strcmp(name, "window") == 0)
5945 {
5946 int count;
5947
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005948 if (valObject->ob_type != WindowTypePtr)
Bram Moolenaare7614592013-05-15 15:51:08 +02005949 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005950 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005951 N_("expected vim.Window object, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005952 valObject);
Bram Moolenaare7614592013-05-15 15:51:08 +02005953 return -1;
5954 }
5955
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005956 if (CheckWindow((WindowObject *)(valObject)))
Bram Moolenaare7614592013-05-15 15:51:08 +02005957 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005958 count = get_win_number(((WindowObject *)(valObject))->win, firstwin);
Bram Moolenaare7614592013-05-15 15:51:08 +02005959
5960 if (!count)
5961 {
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005962 PyErr_SET_STRING(PyExc_ValueError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005963 N_("failed to find window in the current tab page"));
Bram Moolenaare7614592013-05-15 15:51:08 +02005964 return -1;
5965 }
5966
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005967 VimTryStart();
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005968 win_goto(((WindowObject *)(valObject))->win);
5969 if (((WindowObject *)(valObject))->win != curwin)
Bram Moolenaare7614592013-05-15 15:51:08 +02005970 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005971 if (VimTryEnd())
5972 return -1;
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005973 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005974 N_("did not switch to the specified window"));
Bram Moolenaare7614592013-05-15 15:51:08 +02005975 return -1;
5976 }
5977
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005978 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02005979 }
5980 else if (strcmp(name, "tabpage") == 0)
5981 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005982 if (valObject->ob_type != TabPageTypePtr)
Bram Moolenaare7614592013-05-15 15:51:08 +02005983 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005984 PyErr_FORMAT_TYPE(
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02005985 N_("expected vim.TabPage object, but got %s"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02005986 valObject);
Bram Moolenaare7614592013-05-15 15:51:08 +02005987 return -1;
5988 }
5989
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005990 if (CheckTabPage((TabPageObject *)(valObject)))
Bram Moolenaare7614592013-05-15 15:51:08 +02005991 return -1;
5992
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005993 VimTryStart();
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02005994 goto_tabpage_tp(((TabPageObject *)(valObject))->tab, TRUE, TRUE);
5995 if (((TabPageObject *)(valObject))->tab != curtab)
Bram Moolenaare7614592013-05-15 15:51:08 +02005996 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02005997 if (VimTryEnd())
5998 return -1;
Bram Moolenaar0bd80cc2013-06-23 13:28:17 +02005999 PyErr_SET_STRING(PyExc_RuntimeError,
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02006000 N_("did not switch to the specified tab page"));
Bram Moolenaare7614592013-05-15 15:51:08 +02006001 return -1;
6002 }
6003
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02006004 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02006005 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006006 else
6007 {
6008 PyErr_SetString(PyExc_AttributeError, name);
6009 return -1;
6010 }
6011}
6012
Bram Moolenaardd8aca62013-05-29 22:36:10 +02006013static struct PyMethodDef CurrentMethods[] = {
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006014 // name, function, calling, documentation
Bram Moolenaardd8aca62013-05-29 22:36:10 +02006015 {"__dir__", (PyCFunction)CurrentDir, METH_NOARGS, ""},
6016 { NULL, NULL, 0, NULL}
6017};
6018
Bram Moolenaardb913952012-06-29 12:54:53 +02006019 static void
Yee Cheng Chin2ce070c2023-09-19 20:30:22 +02006020init_range_cmd(void *arg)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006021{
Yee Cheng Chin2ce070c2023-09-19 20:30:22 +02006022 exarg_T *eap = (exarg_T*)arg;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006023 RangeStart = eap->line1;
6024 RangeEnd = eap->line2;
6025}
6026
6027 static void
Yee Cheng Chin2ce070c2023-09-19 20:30:22 +02006028init_range_eval(void *rettv UNUSED)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006029{
6030 RangeStart = (PyInt) curwin->w_cursor.lnum;
6031 RangeEnd = RangeStart;
6032}
6033
6034 static void
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006035run_cmd(const char *cmd, void *arg UNUSED
6036#ifdef PY_CAN_RECURSE
6037 , PyGILState_STATE *pygilstate UNUSED
6038#endif
6039 )
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006040{
Bram Moolenaar41009372013-07-01 22:03:04 +02006041 PyObject *run_ret;
6042 run_ret = PyRun_String((char *)cmd, Py_file_input, globals, globals);
6043 if (run_ret != NULL)
6044 {
6045 Py_DECREF(run_ret);
6046 }
6047 else if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit))
6048 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006049 emsg(_(e_cant_handle_systemexit_of_python_exception_in_vim));
Bram Moolenaar41009372013-07-01 22:03:04 +02006050 PyErr_Clear();
6051 }
6052 else
6053 PyErr_PrintEx(1);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006054}
6055
6056static const char *code_hdr = "def " DOPY_FUNC "(line, linenr):\n ";
6057static int code_hdr_len = 30;
6058
6059 static void
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006060run_do(const char *cmd, void *arg UNUSED
6061#ifdef PY_CAN_RECURSE
6062 , PyGILState_STATE *pygilstate
6063#endif
6064 )
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006065{
6066 PyInt lnum;
6067 size_t len;
6068 char *code;
6069 int status;
6070 PyObject *pyfunc, *pymain;
Bram Moolenaar41009372013-07-01 22:03:04 +02006071 PyObject *run_ret;
Bram Moolenaara58883b2017-01-29 21:31:09 +01006072 buf_T *was_curbuf = curbuf;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006073
Bram Moolenaar4ac66762013-05-28 22:31:46 +02006074 if (u_save((linenr_T)RangeStart - 1, (linenr_T)RangeEnd + 1) != OK)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006075 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006076 emsg(_("cannot save undo information"));
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006077 return;
6078 }
6079
6080 len = code_hdr_len + STRLEN(cmd);
6081 code = PyMem_New(char, len + 1);
6082 memcpy(code, code_hdr, code_hdr_len);
6083 STRCPY(code + code_hdr_len, cmd);
Bram Moolenaar41009372013-07-01 22:03:04 +02006084 run_ret = PyRun_String(code, Py_file_input, globals, globals);
6085 status = -1;
6086 if (run_ret != NULL)
6087 {
6088 status = 0;
6089 Py_DECREF(run_ret);
6090 }
6091 else if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit))
6092 {
6093 PyMem_Free(code);
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006094 emsg(_(e_cant_handle_systemexit_of_python_exception_in_vim));
Bram Moolenaar41009372013-07-01 22:03:04 +02006095 PyErr_Clear();
6096 return;
6097 }
6098 else
6099 PyErr_PrintEx(1);
6100
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006101 PyMem_Free(code);
6102
6103 if (status)
6104 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006105 emsg(_("failed to run the code"));
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006106 return;
6107 }
6108
6109 status = 0;
6110 pymain = PyImport_AddModule("__main__");
6111 pyfunc = PyObject_GetAttrString(pymain, DOPY_FUNC);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006112#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006113 PyGILState_Release(*pygilstate);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006114#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006115
6116 for (lnum = RangeStart; lnum <= RangeEnd; ++lnum)
6117 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006118 PyObject *line;
6119 PyObject *linenr;
6120 PyObject *ret;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006121
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006122#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006123 *pygilstate = PyGILState_Ensure();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006124#endif
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006125 // Check the line number, the command my have deleted lines.
Bram Moolenaara58883b2017-01-29 21:31:09 +01006126 if (lnum > curbuf->b_ml.ml_line_count
6127 || !(line = GetBufferLine(curbuf, lnum)))
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006128 goto err;
6129 if (!(linenr = PyInt_FromLong((long) lnum)))
6130 {
6131 Py_DECREF(line);
6132 goto err;
6133 }
6134 ret = PyObject_CallFunctionObjArgs(pyfunc, line, linenr, NULL);
6135 Py_DECREF(line);
6136 Py_DECREF(linenr);
6137 if (!ret)
6138 goto err;
6139
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006140 // Check that the command didn't switch to another buffer.
zeertzjqe99f0682024-01-29 19:32:39 +01006141 // Check the line number, the command my have deleted lines.
6142 if (curbuf != was_curbuf || lnum > curbuf->b_ml.ml_line_count)
Bram Moolenaara58883b2017-01-29 21:31:09 +01006143 {
6144 Py_XDECREF(ret);
6145 goto err;
6146 }
6147
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006148 if (ret != Py_None)
6149 if (SetBufferLine(curbuf, lnum, ret, NULL) == FAIL)
Bram Moolenaara58883b2017-01-29 21:31:09 +01006150 {
6151 Py_XDECREF(ret);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006152 goto err;
Bram Moolenaara58883b2017-01-29 21:31:09 +01006153 }
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006154
6155 Py_XDECREF(ret);
6156 PythonIO_Flush();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006157#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006158 PyGILState_Release(*pygilstate);
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006159#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006160 }
6161 goto out;
6162err:
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006163#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006164 *pygilstate = PyGILState_Ensure();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006165#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006166 PyErr_PrintEx(0);
6167 PythonIO_Flush();
6168 status = 1;
6169out:
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006170#ifdef PY_CAN_RECURSE
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006171 if (!status)
6172 *pygilstate = PyGILState_Ensure();
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006173#endif
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006174 Py_DECREF(pyfunc);
6175 PyObject_SetAttrString(pymain, DOPY_FUNC, NULL);
6176 if (status)
6177 return;
6178 check_cursor();
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006179 update_curbuf(UPD_NOT_VALID);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006180}
6181
6182 static void
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02006183run_eval(const char *cmd, void *arg
Bram Moolenaar2a0f3d32013-05-21 22:23:56 +02006184#ifdef PY_CAN_RECURSE
6185 , PyGILState_STATE *pygilstate UNUSED
6186#endif
6187 )
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006188{
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006189 PyObject *run_ret;
Yee Cheng Chind606fcc2023-09-20 19:59:47 +02006190 typval_T *rettv = (typval_T*)arg;
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006191
Bram Moolenaar41009372013-07-01 22:03:04 +02006192 run_ret = PyRun_String((char *)cmd, Py_eval_input, globals, globals);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006193 if (run_ret == NULL)
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006194 {
Bram Moolenaar91aeaf42013-07-06 13:02:30 +02006195 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit))
Bram Moolenaar41009372013-07-01 22:03:04 +02006196 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006197 emsg(_(e_cant_handle_systemexit_of_python_exception_in_vim));
Bram Moolenaar41009372013-07-01 22:03:04 +02006198 PyErr_Clear();
6199 }
Bram Moolenaar91aeaf42013-07-06 13:02:30 +02006200 else
6201 {
6202 if (PyErr_Occurred() && !msg_silent)
6203 PyErr_PrintEx(0);
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006204 emsg(_(e_eval_did_not_return_valid_python_object));
Bram Moolenaar91aeaf42013-07-06 13:02:30 +02006205 }
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006206 }
6207 else
6208 {
Bram Moolenaarde323092017-11-09 19:56:08 +01006209 if (ConvertFromPyObject(run_ret, rettv) == -1)
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006210 emsg(_(e_failed_to_convert_returned_python_object_to_vim_value));
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006211 Py_DECREF(run_ret);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02006212 }
6213 PyErr_Clear();
6214}
6215
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006216 static int
Bram Moolenaardb913952012-06-29 12:54:53 +02006217set_ref_in_py(const int copyID)
6218{
6219 pylinkedlist_T *cur;
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006220 list_T *ll;
6221 int i;
6222 int abort = FALSE;
Bram Moolenaar8110a092016-04-14 15:56:09 +02006223 FunctionObject *func;
Bram Moolenaardb913952012-06-29 12:54:53 +02006224
6225 if (lastdict != NULL)
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006226 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02006227 for (cur = lastdict ; !abort && cur != NULL ; cur = cur->pll_prev)
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006228 abort = set_ref_in_dict(((DictionaryObject *)(cur->pll_obj))->dict,
6229 copyID);
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006230 }
Bram Moolenaardb913952012-06-29 12:54:53 +02006231
6232 if (lastlist != NULL)
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006233 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02006234 for (cur = lastlist ; !abort && cur != NULL ; cur = cur->pll_prev)
Bram Moolenaardb913952012-06-29 12:54:53 +02006235 {
6236 ll = ((ListObject *) (cur->pll_obj))->list;
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006237 abort = set_ref_in_list(ll, copyID);
Bram Moolenaardb913952012-06-29 12:54:53 +02006238 }
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006239 }
6240
Bram Moolenaar8110a092016-04-14 15:56:09 +02006241 if (lastfunc != NULL)
6242 {
6243 for (cur = lastfunc ; !abort && cur != NULL ; cur = cur->pll_prev)
6244 {
6245 func = (FunctionObject *) cur->pll_obj;
Bram Moolenaar7be3ab22019-06-23 01:46:15 +02006246 abort = set_ref_in_dict(func->self, copyID);
Bram Moolenaar8110a092016-04-14 15:56:09 +02006247 if (func->argc)
6248 for (i = 0; !abort && i < func->argc; ++i)
6249 abort = abort
6250 || set_ref_in_item(&func->argv[i], copyID, NULL, NULL);
6251 }
6252 }
6253
Bram Moolenaar2459a5e2015-02-03 12:55:18 +01006254 return abort;
Bram Moolenaardb913952012-06-29 12:54:53 +02006255}
6256
6257 static int
6258set_string_copy(char_u *str, typval_T *tv)
6259{
6260 tv->vval.v_string = vim_strsave(str);
6261 if (tv->vval.v_string == NULL)
6262 {
6263 PyErr_NoMemory();
6264 return -1;
6265 }
6266 return 0;
6267}
6268
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006269 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006270pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006271{
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006272 dict_T *dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006273 char_u *key;
6274 dictitem_T *di;
6275 PyObject *keyObject;
6276 PyObject *valObject;
6277 Py_ssize_t iter = 0;
6278
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006279 if (!(dict = py_dict_alloc()))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006280 return -1;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006281
6282 tv->v_type = VAR_DICT;
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006283 tv->vval.v_dict = dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006284
6285 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
6286 {
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006287 PyObject *todecref = NULL;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006288
Bram Moolenaara03e6312013-05-29 22:49:26 +02006289 if (keyObject == NULL || valObject == NULL)
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006290 {
6291 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006292 return -1;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006293 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006294
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006295 if (!(key = StringToChars(keyObject, &todecref)))
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006296 {
6297 dict_unref(dict);
6298 return -1;
6299 }
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02006300
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006301 if (*key == NUL)
6302 {
6303 dict_unref(dict);
6304 Py_XDECREF(todecref);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006305 RAISE_NO_EMPTY_KEYS;
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006306 return -1;
6307 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006308
6309 di = dictitem_alloc(key);
6310
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006311 Py_XDECREF(todecref);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006312
6313 if (di == NULL)
6314 {
6315 PyErr_NoMemory();
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006316 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006317 return -1;
6318 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006319
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006320 if (_ConvertFromPyObject(valObject, &di->di_tv, lookup_dict) == -1)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006321 {
6322 vim_free(di);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006323 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006324 return -1;
6325 }
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006326
6327 if (dict_add(dict, di) == FAIL)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006328 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02006329 RAISE_KEY_ADD_FAIL(di->di_key);
Bram Moolenaara03e6312013-05-29 22:49:26 +02006330 clear_tv(&di->di_tv);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006331 vim_free(di);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006332 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006333 return -1;
6334 }
6335 }
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006336
6337 --dict->dv_refcount;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006338 return 0;
6339}
6340
6341 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006342pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006343{
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006344 dict_T *dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006345 char_u *key;
6346 dictitem_T *di;
6347 PyObject *list;
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006348 PyObject *iterator;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006349 PyObject *keyObject;
6350 PyObject *valObject;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006351
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006352 if (!(dict = py_dict_alloc()))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006353 return -1;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006354
6355 tv->v_type = VAR_DICT;
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006356 tv->vval.v_dict = dict;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006357
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006358 if (!(list = PyMapping_Keys(obj)))
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006359 {
6360 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006361 return -1;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006362 }
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006363
6364 if (!(iterator = PyObject_GetIter(list)))
6365 {
6366 dict_unref(dict);
6367 Py_DECREF(list);
6368 return -1;
6369 }
6370 Py_DECREF(list);
6371
6372 while ((keyObject = PyIter_Next(iterator)))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006373 {
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006374 PyObject *todecref;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006375
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006376 if (!(key = StringToChars(keyObject, &todecref)))
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006377 {
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006378 Py_DECREF(keyObject);
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006379 Py_DECREF(iterator);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006380 dict_unref(dict);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006381 return -1;
6382 }
Bram Moolenaar4f2109d2013-06-02 18:07:37 +02006383
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006384 if (*key == NUL)
6385 {
6386 Py_DECREF(keyObject);
6387 Py_DECREF(iterator);
6388 Py_XDECREF(todecref);
6389 dict_unref(dict);
Bram Moolenaar35eacd72013-05-30 22:06:33 +02006390 RAISE_NO_EMPTY_KEYS;
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006391 return -1;
6392 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006393
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006394 if (!(valObject = PyObject_GetItem(obj, keyObject)))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006395 {
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006396 Py_DECREF(keyObject);
6397 Py_DECREF(iterator);
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006398 Py_XDECREF(todecref);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006399 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006400 return -1;
6401 }
6402
6403 di = dictitem_alloc(key);
6404
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006405 Py_DECREF(keyObject);
Bram Moolenaarfc714b32013-05-30 14:52:37 +02006406 Py_XDECREF(todecref);
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006407
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006408 if (di == NULL)
6409 {
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006410 Py_DECREF(iterator);
6411 Py_DECREF(valObject);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006412 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006413 PyErr_NoMemory();
6414 return -1;
6415 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006416
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006417 if (_ConvertFromPyObject(valObject, &di->di_tv, lookup_dict) == -1)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006418 {
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006419 Py_DECREF(iterator);
6420 Py_DECREF(valObject);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006421 vim_free(di);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006422 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006423 return -1;
6424 }
Bram Moolenaara03e6312013-05-29 22:49:26 +02006425
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006426 Py_DECREF(valObject);
6427
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006428 if (dict_add(dict, di) == FAIL)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006429 {
Bram Moolenaarc476e522013-06-23 13:46:40 +02006430 RAISE_KEY_ADD_FAIL(di->di_key);
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006431 Py_DECREF(iterator);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006432 dictitem_free(di);
6433 dict_unref(dict);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006434 return -1;
6435 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006436 }
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006437 Py_DECREF(iterator);
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006438 --dict->dv_refcount;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006439 return 0;
6440}
6441
6442 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006443pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006444{
6445 list_T *l;
6446
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006447 if (!(l = py_list_alloc()))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006448 return -1;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006449
6450 tv->v_type = VAR_LIST;
6451 tv->vval.v_list = l;
6452
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006453 if (list_py_concat(l, obj, lookup_dict) == -1)
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006454 {
6455 list_unref(l);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006456 return -1;
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006457 }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006458
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006459 --l->lv_refcount;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02006460 return 0;
6461}
6462
Bram Moolenaardb913952012-06-29 12:54:53 +02006463typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
6464
6465 static int
6466convert_dl(PyObject *obj, typval_T *tv,
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006467 pytotvfunc py_to_tv, PyObject *lookup_dict)
Bram Moolenaardb913952012-06-29 12:54:53 +02006468{
6469 PyObject *capsule;
6470 char hexBuf[sizeof(void *) * 2 + 3];
6471
Bram Moolenaar792f0e32018-02-27 17:27:13 +01006472 sprintf(hexBuf, "%p", (void *)obj);
Bram Moolenaardb913952012-06-29 12:54:53 +02006473
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006474#ifdef PY_USE_CAPSULE
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006475 capsule = PyDict_GetItemString(lookup_dict, hexBuf);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006476#else
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006477 capsule = (PyObject *)PyDict_GetItemString(lookup_dict, hexBuf);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006478#endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02006479 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02006480 {
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006481#ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02006482 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006483#else
Bram Moolenaar221d6872012-06-30 13:34:34 +02006484 capsule = PyCObject_FromVoidPtr(tv, NULL);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006485#endif
Bram Moolenaara03e6312013-05-29 22:49:26 +02006486 if (PyDict_SetItemString(lookup_dict, hexBuf, capsule))
6487 {
6488 Py_DECREF(capsule);
6489 tv->v_type = VAR_UNKNOWN;
6490 return -1;
6491 }
Bram Moolenaar841fbd22013-06-23 14:37:07 +02006492
6493 Py_DECREF(capsule);
6494
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006495 if (py_to_tv(obj, tv, lookup_dict) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +02006496 {
6497 tv->v_type = VAR_UNKNOWN;
6498 return -1;
6499 }
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006500 // As we are not using copy_tv which increments reference count we must
6501 // do it ourself.
Bram Moolenaar81e7a9c2016-02-06 19:57:20 +01006502 if (tv->v_type == VAR_DICT)
6503 ++tv->vval.v_dict->dv_refcount;
6504 else if (tv->v_type == VAR_LIST)
6505 ++tv->vval.v_list->lv_refcount;
Bram Moolenaardb913952012-06-29 12:54:53 +02006506 }
6507 else
6508 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02006509 typval_T *v;
6510
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006511#ifdef PY_USE_CAPSULE
Bram Moolenaar2afa3232012-06-29 16:28:28 +02006512 v = PyCapsule_GetPointer(capsule, NULL);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006513#else
Bram Moolenaar221d6872012-06-30 13:34:34 +02006514 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaarb999ba22019-02-14 13:28:45 +01006515#endif
Bram Moolenaardb913952012-06-29 12:54:53 +02006516 copy_tv(v, tv);
6517 }
6518 return 0;
6519}
6520
6521 static int
Bram Moolenaara9922d62013-05-30 13:01:18 +02006522ConvertFromPyMapping(PyObject *obj, typval_T *tv)
6523{
6524 PyObject *lookup_dict;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006525 int ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006526
6527 if (!(lookup_dict = PyDict_New()))
6528 return -1;
6529
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006530 if (PyType_IsSubtype(obj->ob_type, DictionaryTypePtr))
Bram Moolenaara9922d62013-05-30 13:01:18 +02006531 {
6532 tv->v_type = VAR_DICT;
6533 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
6534 ++tv->vval.v_dict->dv_refcount;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006535 ret = 0;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006536 }
6537 else if (PyDict_Check(obj))
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006538 ret = convert_dl(obj, tv, pydict_to_tv, lookup_dict);
Bram Moolenaara9922d62013-05-30 13:01:18 +02006539 else if (PyMapping_Check(obj))
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006540 ret = convert_dl(obj, tv, pymap_to_tv, lookup_dict);
Bram Moolenaara9922d62013-05-30 13:01:18 +02006541 else
6542 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006543 PyErr_FORMAT_TYPE(
Bram Moolenaar86181df2020-05-11 23:14:04 +02006544 N_("unable to convert %s to a Vim dictionary"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006545 obj);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006546 ret = -1;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006547 }
6548 Py_DECREF(lookup_dict);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006549 return ret;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006550}
6551
6552 static int
Bram Moolenaar8110a092016-04-14 15:56:09 +02006553ConvertFromPySequence(PyObject *obj, typval_T *tv)
6554{
6555 PyObject *lookup_dict;
Bram Moolenaar66210042016-04-15 20:40:41 +02006556 int ret;
Bram Moolenaar8110a092016-04-14 15:56:09 +02006557
6558 if (!(lookup_dict = PyDict_New()))
6559 return -1;
6560
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006561 if (PyType_IsSubtype(obj->ob_type, ListTypePtr))
Bram Moolenaar8110a092016-04-14 15:56:09 +02006562 {
6563 tv->v_type = VAR_LIST;
6564 tv->vval.v_list = (((ListObject *)(obj))->list);
6565 ++tv->vval.v_list->lv_refcount;
Bram Moolenaar66210042016-04-15 20:40:41 +02006566 ret = 0;
Bram Moolenaar8110a092016-04-14 15:56:09 +02006567 }
6568 else if (PyIter_Check(obj) || PySequence_Check(obj))
Bram Moolenaar66210042016-04-15 20:40:41 +02006569 ret = convert_dl(obj, tv, pyseq_to_tv, lookup_dict);
Bram Moolenaar8110a092016-04-14 15:56:09 +02006570 else
6571 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006572 PyErr_FORMAT_TYPE(
Bram Moolenaar86181df2020-05-11 23:14:04 +02006573 N_("unable to convert %s to a Vim list"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006574 obj);
Bram Moolenaar8110a092016-04-14 15:56:09 +02006575 ret = -1;
6576 }
6577 Py_DECREF(lookup_dict);
6578 return ret;
6579}
6580
6581 static int
Bram Moolenaardb913952012-06-29 12:54:53 +02006582ConvertFromPyObject(PyObject *obj, typval_T *tv)
6583{
6584 PyObject *lookup_dict;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006585 int ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02006586
Bram Moolenaar9bb77d62013-05-30 12:14:49 +02006587 if (!(lookup_dict = PyDict_New()))
6588 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006589 ret = _ConvertFromPyObject(obj, tv, lookup_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006590 Py_DECREF(lookup_dict);
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006591 return ret;
Bram Moolenaardb913952012-06-29 12:54:53 +02006592}
6593
6594 static int
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006595_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookup_dict)
Bram Moolenaardb913952012-06-29 12:54:53 +02006596{
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006597 if (PyType_IsSubtype(obj->ob_type, DictionaryTypePtr))
Bram Moolenaardb913952012-06-29 12:54:53 +02006598 {
6599 tv->v_type = VAR_DICT;
6600 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
6601 ++tv->vval.v_dict->dv_refcount;
6602 }
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006603 else if (PyType_IsSubtype(obj->ob_type, ListTypePtr))
Bram Moolenaardb913952012-06-29 12:54:53 +02006604 {
6605 tv->v_type = VAR_LIST;
6606 tv->vval.v_list = (((ListObject *)(obj))->list);
6607 ++tv->vval.v_list->lv_refcount;
6608 }
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006609 else if (PyType_IsSubtype(obj->ob_type, FunctionTypePtr))
Bram Moolenaardb913952012-06-29 12:54:53 +02006610 {
Bram Moolenaar8110a092016-04-14 15:56:09 +02006611 FunctionObject *func = (FunctionObject *) obj;
6612 if (func->self != NULL || func->argv != NULL)
6613 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006614 partial_T *pt = ALLOC_CLEAR_ONE(partial_T);
6615
Bram Moolenaar8110a092016-04-14 15:56:09 +02006616 set_partial(func, pt, TRUE);
6617 tv->vval.v_partial = pt;
6618 tv->v_type = VAR_PARTIAL;
6619 }
6620 else
6621 {
6622 if (set_string_copy(func->name, tv) == -1)
6623 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02006624
Bram Moolenaar8110a092016-04-14 15:56:09 +02006625 tv->v_type = VAR_FUNC;
6626 }
6627 func_ref(func->name);
Bram Moolenaardb913952012-06-29 12:54:53 +02006628 }
Bram Moolenaardb913952012-06-29 12:54:53 +02006629 else if (PyBytes_Check(obj))
6630 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006631 char_u *str;
Bram Moolenaardb913952012-06-29 12:54:53 +02006632
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006633 if (PyBytes_AsStringAndSize(obj, (char **) &str, NULL) == -1)
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02006634 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006635 if (str == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02006636 return -1;
6637
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006638 if (set_string_copy(str, tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +02006639 return -1;
6640
6641 tv->v_type = VAR_STRING;
6642 }
6643 else if (PyUnicode_Check(obj))
6644 {
6645 PyObject *bytes;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006646 char_u *str;
Bram Moolenaardb913952012-06-29 12:54:53 +02006647
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01006648 bytes = PyUnicode_AsEncodedString(obj, ENC_OPT, ERRORS_ENCODE_ARG);
Bram Moolenaardb913952012-06-29 12:54:53 +02006649 if (bytes == NULL)
6650 return -1;
6651
Bram Moolenaar2e2f52a2020-12-21 16:03:02 +01006652 if (PyBytes_AsStringAndSize(bytes, (char **) &str, NULL) == -1)
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02006653 return -1;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006654 if (str == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02006655 return -1;
6656
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02006657 if (set_string_copy(str, tv))
Bram Moolenaardb913952012-06-29 12:54:53 +02006658 {
6659 Py_XDECREF(bytes);
6660 return -1;
6661 }
6662 Py_XDECREF(bytes);
6663
6664 tv->v_type = VAR_STRING;
6665 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02006666#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02006667 else if (PyInt_Check(obj))
6668 {
6669 tv->v_type = VAR_NUMBER;
6670 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +02006671 if (PyErr_Occurred())
6672 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02006673 }
6674#endif
6675 else if (PyLong_Check(obj))
6676 {
6677 tv->v_type = VAR_NUMBER;
6678 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
Bram Moolenaar141be8a2013-06-23 14:16:57 +02006679 if (PyErr_Occurred())
6680 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02006681 }
6682 else if (PyDict_Check(obj))
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006683 return convert_dl(obj, tv, pydict_to_tv, lookup_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006684 else if (PyFloat_Check(obj))
6685 {
6686 tv->v_type = VAR_FLOAT;
6687 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
6688 }
Bram Moolenaarbcb40972013-05-30 13:22:13 +02006689 else if (PyObject_HasAttrString(obj, "keys"))
6690 return convert_dl(obj, tv, pymap_to_tv, lookup_dict);
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01006691 // PyObject_GetIter can create built-in iterator for any sequence object
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006692 else if (PyIter_Check(obj) || PySequence_Check(obj))
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006693 return convert_dl(obj, tv, pyseq_to_tv, lookup_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006694 else if (PyMapping_Check(obj))
Bram Moolenaarb38caae2013-05-29 22:39:52 +02006695 return convert_dl(obj, tv, pymap_to_tv, lookup_dict);
Bram Moolenaar141be8a2013-06-23 14:16:57 +02006696 else if (PyNumber_Check(obj))
6697 {
6698 PyObject *num;
6699
6700 if (!(num = PyNumber_Long(obj)))
6701 return -1;
6702
6703 tv->v_type = VAR_NUMBER;
6704 tv->vval.v_number = (varnumber_T) PyLong_AsLong(num);
6705
6706 Py_DECREF(num);
6707 }
Bram Moolenaarde323092017-11-09 19:56:08 +01006708 else if (obj == Py_None)
6709 {
6710 tv->v_type = VAR_SPECIAL;
6711 tv->vval.v_number = VVAL_NONE;
6712 }
Bram Moolenaardb913952012-06-29 12:54:53 +02006713 else
6714 {
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006715 PyErr_FORMAT_TYPE(
Bram Moolenaar86181df2020-05-11 23:14:04 +02006716 N_("unable to convert %s to a Vim structure"),
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006717 obj);
Bram Moolenaardb913952012-06-29 12:54:53 +02006718 return -1;
6719 }
6720 return 0;
6721}
6722
6723 static PyObject *
6724ConvertToPyObject(typval_T *tv)
6725{
Bram Moolenaar8110a092016-04-14 15:56:09 +02006726 typval_T *argv;
6727 int i;
Bram Moolenaardb913952012-06-29 12:54:53 +02006728 if (tv == NULL)
6729 {
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02006730 PyErr_SET_VIM(N_("internal error: NULL reference passed"));
Bram Moolenaardb913952012-06-29 12:54:53 +02006731 return NULL;
6732 }
6733 switch (tv->v_type)
6734 {
6735 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02006736 return PyBytes_FromString(tv->vval.v_string == NULL
6737 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02006738 case VAR_NUMBER:
6739 return PyLong_FromLong((long) tv->vval.v_number);
Bram Moolenaardb913952012-06-29 12:54:53 +02006740 case VAR_FLOAT:
6741 return PyFloat_FromDouble((double) tv->vval.v_float);
Bram Moolenaardb913952012-06-29 12:54:53 +02006742 case VAR_LIST:
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006743 return NEW_LIST(tv->vval.v_list);
Bram Moolenaardb913952012-06-29 12:54:53 +02006744 case VAR_DICT:
Bram Moolenaara9922d62013-05-30 13:01:18 +02006745 return NEW_DICTIONARY(tv->vval.v_dict);
Bram Moolenaardb913952012-06-29 12:54:53 +02006746 case VAR_FUNC:
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02006747 return NEW_FUNCTION(tv->vval.v_string == NULL
Bram Moolenaar8110a092016-04-14 15:56:09 +02006748 ? (char_u *)"" : tv->vval.v_string,
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02006749 0, NULL, NULL, TRUE);
Bram Moolenaar4c908612016-03-24 21:58:12 +01006750 case VAR_PARTIAL:
Bram Moolenaar8110a092016-04-14 15:56:09 +02006751 if (tv->vval.v_partial->pt_argc)
6752 {
6753 argv = PyMem_New(typval_T, (size_t)tv->vval.v_partial->pt_argc);
6754 for (i = 0; i < tv->vval.v_partial->pt_argc; i++)
6755 copy_tv(&tv->vval.v_partial->pt_argv[i], &argv[i]);
6756 }
6757 else
6758 argv = NULL;
6759 if (tv->vval.v_partial->pt_dict != NULL)
6760 tv->vval.v_partial->pt_dict->dv_refcount++;
Bram Moolenaar4c908612016-03-24 21:58:12 +01006761 return NEW_FUNCTION(tv->vval.v_partial == NULL
Bram Moolenaar437bafe2016-08-01 15:40:54 +02006762 ? (char_u *)"" : partial_name(tv->vval.v_partial),
Bram Moolenaar8110a092016-04-14 15:56:09 +02006763 tv->vval.v_partial->pt_argc, argv,
Bram Moolenaar2177f9f2016-05-25 20:39:09 +02006764 tv->vval.v_partial->pt_dict,
6765 tv->vval.v_partial->pt_auto);
Bram Moolenaar6e5ea8d2019-01-12 22:47:31 +01006766 case VAR_BLOB:
6767 return PyBytes_FromStringAndSize(
6768 (char*) tv->vval.v_blob->bv_ga.ga_data,
6769 (Py_ssize_t) tv->vval.v_blob->bv_ga.ga_len);
Bram Moolenaardb913952012-06-29 12:54:53 +02006770 case VAR_UNKNOWN:
Bram Moolenaar4c683752020-04-05 21:38:23 +02006771 case VAR_ANY:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01006772 case VAR_VOID:
Bram Moolenaar4c908612016-03-24 21:58:12 +01006773 case VAR_CHANNEL:
6774 case VAR_JOB:
Bram Moolenaarf18332f2021-05-07 17:55:55 +02006775 case VAR_INSTR:
Bram Moolenaar00b28d62022-12-08 15:32:33 +00006776 case VAR_CLASS:
6777 case VAR_OBJECT:
Yegappan Lakshmananec3cebb2023-10-27 19:35:26 +02006778 case VAR_TYPEALIAS:
Bram Moolenaardb913952012-06-29 12:54:53 +02006779 Py_INCREF(Py_None);
6780 return Py_None;
Bram Moolenaar9b4a15d2020-01-11 16:05:23 +01006781 case VAR_BOOL:
Bram Moolenaar4c908612016-03-24 21:58:12 +01006782 case VAR_SPECIAL:
6783 switch (tv->vval.v_number)
6784 {
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02006785 case VVAL_FALSE: return ALWAYS_FALSE;
6786 case VVAL_TRUE: return ALWAYS_TRUE;
Bram Moolenaar4c908612016-03-24 21:58:12 +01006787 case VVAL_NONE:
Bram Moolenaar4ce5fe42020-10-21 21:01:59 +02006788 case VVAL_NULL: return ALWAYS_NONE;
Bram Moolenaar4c908612016-03-24 21:58:12 +01006789 }
Bram Moolenaar6f1404f2013-06-23 16:04:08 +02006790 PyErr_SET_VIM(N_("internal error: invalid value type"));
Bram Moolenaardb913952012-06-29 12:54:53 +02006791 return NULL;
6792 }
Bram Moolenaar4c908612016-03-24 21:58:12 +01006793 return NULL;
Bram Moolenaardb913952012-06-29 12:54:53 +02006794}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006795
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006796DEFINE_PY_TYPE_OBJECT(CurrentType);
6797
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006798typedef struct
6799{
6800 PyObject_HEAD
6801} CurrentObject;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006802
6803static CurrentObject TheCurrent =
6804{
6805 PyObject_HEAD_INIT_TYPE(CurrentType)
6806};
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006807
6808 static void
6809init_structs(void)
6810{
Bram Moolenaara80faa82020-04-12 19:37:17 +02006811 CLEAR_FIELD(OutputType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006812 OutputType.tp_name = "vim.message";
6813 OutputType.tp_basicsize = sizeof(OutputObject);
6814 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
6815 OutputType.tp_doc = "vim message object";
6816 OutputType.tp_methods = OutputMethods;
6817#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006818 OutputType.tp_getattro = OutputGetattro;
6819 OutputType.tp_setattro = OutputSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006820 OutputType.tp_alloc = call_PyType_GenericAlloc;
6821 OutputType.tp_new = call_PyType_GenericNew;
6822 OutputType.tp_free = call_PyObject_Free;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006823# ifndef USE_LIMITED_API
6824 // The std printer type is only exposed in full API. It is not essential
6825 // anyway and so in limited API we don't set it.
Bram Moolenaard4a8c982018-05-15 22:31:18 +02006826 OutputType.tp_base = &PyStdPrinter_Type;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006827# endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006828#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006829 OutputType.tp_getattr = OutputGetattr;
6830 OutputType.tp_setattr = OutputSetattr;
Bram Moolenaard4a8c982018-05-15 22:31:18 +02006831 // Disabled, because this causes a crash in test86
6832 // OutputType.tp_base = &PyFile_Type;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006833#endif
6834
Bram Moolenaara80faa82020-04-12 19:37:17 +02006835 CLEAR_FIELD(IterType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006836 IterType.tp_name = "vim.iter";
6837 IterType.tp_basicsize = sizeof(IterObject);
Bram Moolenaar07b88642013-05-29 22:58:32 +02006838 IterType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006839 IterType.tp_doc = "generic iterator object";
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006840 IterType.tp_iter = IterIter;
6841 IterType.tp_iternext = IterNext;
6842 IterType.tp_dealloc = IterDestructor;
6843 IterType.tp_traverse = IterTraverse;
6844 IterType.tp_clear = IterClear;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006845
Bram Moolenaara80faa82020-04-12 19:37:17 +02006846 CLEAR_FIELD(BufferType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006847 BufferType.tp_name = "vim.buffer";
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006848 BufferType.tp_basicsize = sizeof(BufferObject);
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006849 BufferType.tp_dealloc = BufferDestructor;
6850 BufferType.tp_repr = BufferRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006851 BufferType.tp_as_sequence = &BufferAsSeq;
6852 BufferType.tp_as_mapping = &BufferAsMapping;
6853 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
6854 BufferType.tp_doc = "vim buffer object";
6855 BufferType.tp_methods = BufferMethods;
6856#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006857 BufferType.tp_getattro = BufferGetattro;
6858 BufferType.tp_setattro = BufferSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006859 BufferType.tp_alloc = call_PyType_GenericAlloc;
6860 BufferType.tp_new = call_PyType_GenericNew;
6861 BufferType.tp_free = call_PyObject_Free;
6862#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006863 BufferType.tp_getattr = BufferGetattr;
6864 BufferType.tp_setattr = BufferSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006865#endif
6866
Bram Moolenaara80faa82020-04-12 19:37:17 +02006867 CLEAR_FIELD(WindowType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006868 WindowType.tp_name = "vim.window";
6869 WindowType.tp_basicsize = sizeof(WindowObject);
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006870 WindowType.tp_dealloc = WindowDestructor;
6871 WindowType.tp_repr = WindowRepr;
Bram Moolenaar07b88642013-05-29 22:58:32 +02006872 WindowType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006873 WindowType.tp_doc = "vim Window object";
6874 WindowType.tp_methods = WindowMethods;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006875 WindowType.tp_traverse = WindowTraverse;
6876 WindowType.tp_clear = WindowClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006877#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006878 WindowType.tp_getattro = WindowGetattro;
6879 WindowType.tp_setattro = WindowSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006880 WindowType.tp_alloc = call_PyType_GenericAlloc;
6881 WindowType.tp_new = call_PyType_GenericNew;
6882 WindowType.tp_free = call_PyObject_Free;
6883#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006884 WindowType.tp_getattr = WindowGetattr;
6885 WindowType.tp_setattr = WindowSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006886#endif
6887
Bram Moolenaara80faa82020-04-12 19:37:17 +02006888 CLEAR_FIELD(TabPageType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006889 TabPageType.tp_name = "vim.tabpage";
6890 TabPageType.tp_basicsize = sizeof(TabPageObject);
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006891 TabPageType.tp_dealloc = TabPageDestructor;
6892 TabPageType.tp_repr = TabPageRepr;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006893 TabPageType.tp_flags = Py_TPFLAGS_DEFAULT;
6894 TabPageType.tp_doc = "vim tab page object";
6895 TabPageType.tp_methods = TabPageMethods;
6896#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006897 TabPageType.tp_getattro = TabPageGetattro;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006898 TabPageType.tp_alloc = call_PyType_GenericAlloc;
6899 TabPageType.tp_new = call_PyType_GenericNew;
6900 TabPageType.tp_free = call_PyObject_Free;
6901#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006902 TabPageType.tp_getattr = TabPageGetattr;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006903#endif
6904
Bram Moolenaara80faa82020-04-12 19:37:17 +02006905 CLEAR_FIELD(BufMapType);
Bram Moolenaardfa38d42013-05-15 13:38:47 +02006906 BufMapType.tp_name = "vim.bufferlist";
6907 BufMapType.tp_basicsize = sizeof(BufMapObject);
6908 BufMapType.tp_as_mapping = &BufMapAsMapping;
6909 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02006910 BufMapType.tp_iter = BufMapIter;
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006911 BufMapType.tp_doc = "vim buffer list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006912
Bram Moolenaara80faa82020-04-12 19:37:17 +02006913 CLEAR_FIELD(WinListType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006914 WinListType.tp_name = "vim.windowlist";
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006915 WinListType.tp_basicsize = sizeof(WinListObject);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006916 WinListType.tp_as_sequence = &WinListAsSeq;
6917 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
6918 WinListType.tp_doc = "vim window list";
Bram Moolenaard6e39182013-05-21 18:30:34 +02006919 WinListType.tp_dealloc = (destructor)WinListDestructor;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006920
Bram Moolenaara80faa82020-04-12 19:37:17 +02006921 CLEAR_FIELD(TabListType);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006922 TabListType.tp_name = "vim.tabpagelist";
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02006923 TabListType.tp_basicsize = sizeof(TabListObject);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02006924 TabListType.tp_as_sequence = &TabListAsSeq;
6925 TabListType.tp_flags = Py_TPFLAGS_DEFAULT;
6926 TabListType.tp_doc = "vim tab page list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006927
Bram Moolenaara80faa82020-04-12 19:37:17 +02006928 CLEAR_FIELD(RangeType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006929 RangeType.tp_name = "vim.range";
6930 RangeType.tp_basicsize = sizeof(RangeObject);
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006931 RangeType.tp_dealloc = RangeDestructor;
6932 RangeType.tp_repr = RangeRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006933 RangeType.tp_as_sequence = &RangeAsSeq;
6934 RangeType.tp_as_mapping = &RangeAsMapping;
Bram Moolenaar07b88642013-05-29 22:58:32 +02006935 RangeType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006936 RangeType.tp_doc = "vim Range object";
6937 RangeType.tp_methods = RangeMethods;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006938 RangeType.tp_traverse = RangeTraverse;
6939 RangeType.tp_clear = RangeClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006940#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006941 RangeType.tp_getattro = RangeGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006942 RangeType.tp_alloc = call_PyType_GenericAlloc;
6943 RangeType.tp_new = call_PyType_GenericNew;
6944 RangeType.tp_free = call_PyObject_Free;
6945#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006946 RangeType.tp_getattr = RangeGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006947#endif
6948
Bram Moolenaara80faa82020-04-12 19:37:17 +02006949 CLEAR_FIELD(CurrentType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006950 CurrentType.tp_name = "vim.currentdata";
6951 CurrentType.tp_basicsize = sizeof(CurrentObject);
6952 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
6953 CurrentType.tp_doc = "vim current object";
Bram Moolenaardd8aca62013-05-29 22:36:10 +02006954 CurrentType.tp_methods = CurrentMethods;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006955#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006956 CurrentType.tp_getattro = CurrentGetattro;
6957 CurrentType.tp_setattro = CurrentSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006958#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006959 CurrentType.tp_getattr = CurrentGetattr;
6960 CurrentType.tp_setattr = CurrentSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006961#endif
6962
Bram Moolenaara80faa82020-04-12 19:37:17 +02006963 CLEAR_FIELD(DictionaryType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006964 DictionaryType.tp_name = "vim.dictionary";
6965 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006966 DictionaryType.tp_dealloc = DictionaryDestructor;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006967 DictionaryType.tp_as_sequence = &DictionaryAsSeq;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006968 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
Bram Moolenaara9922d62013-05-30 13:01:18 +02006969 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
Bram Moolenaar86181df2020-05-11 23:14:04 +02006970 DictionaryType.tp_doc = "dictionary pushing modifications to Vim structure";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006971 DictionaryType.tp_methods = DictionaryMethods;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006972 DictionaryType.tp_iter = DictionaryIter;
6973 DictionaryType.tp_new = DictionaryConstructor;
6974 DictionaryType.tp_alloc = PyType_GenericAlloc;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006975#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006976 DictionaryType.tp_getattro = DictionaryGetattro;
6977 DictionaryType.tp_setattro = DictionarySetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006978#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006979 DictionaryType.tp_getattr = DictionaryGetattr;
6980 DictionaryType.tp_setattr = DictionarySetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006981#endif
6982
Bram Moolenaara80faa82020-04-12 19:37:17 +02006983 CLEAR_FIELD(ListType);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006984 ListType.tp_name = "vim.list";
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006985 ListType.tp_dealloc = ListDestructor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006986 ListType.tp_basicsize = sizeof(ListObject);
6987 ListType.tp_as_sequence = &ListAsSeq;
6988 ListType.tp_as_mapping = &ListAsMapping;
Bram Moolenaar78cddbe2013-05-30 13:05:58 +02006989 ListType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
Bram Moolenaar86181df2020-05-11 23:14:04 +02006990 ListType.tp_doc = "list pushing modifications to Vim structure";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006991 ListType.tp_methods = ListMethods;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006992 ListType.tp_iter = ListIter;
6993 ListType.tp_new = ListConstructor;
6994 ListType.tp_alloc = PyType_GenericAlloc;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006995#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006996 ListType.tp_getattro = ListGetattro;
6997 ListType.tp_setattro = ListSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02006998#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02006999 ListType.tp_getattr = ListGetattr;
7000 ListType.tp_setattr = ListSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007001#endif
7002
Bram Moolenaara80faa82020-04-12 19:37:17 +02007003 CLEAR_FIELD(FunctionType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02007004 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007005 FunctionType.tp_basicsize = sizeof(FunctionObject);
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007006 FunctionType.tp_dealloc = FunctionDestructor;
7007 FunctionType.tp_call = FunctionCall;
Bram Moolenaar355fd9b2013-05-30 13:14:13 +02007008 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE;
Bram Moolenaar86181df2020-05-11 23:14:04 +02007009 FunctionType.tp_doc = "object that calls Vim function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007010 FunctionType.tp_methods = FunctionMethods;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007011 FunctionType.tp_repr = FunctionRepr;
7012 FunctionType.tp_new = FunctionConstructor;
7013 FunctionType.tp_alloc = PyType_GenericAlloc;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007014#if PY_MAJOR_VERSION >= 3
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007015 FunctionType.tp_getattro = FunctionGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007016#else
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007017 FunctionType.tp_getattr = FunctionGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007018#endif
7019
Bram Moolenaara80faa82020-04-12 19:37:17 +02007020 CLEAR_FIELD(OptionsType);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02007021 OptionsType.tp_name = "vim.options";
7022 OptionsType.tp_basicsize = sizeof(OptionsObject);
Bram Moolenaar1028f4d2014-01-14 16:55:00 +01007023 OptionsType.tp_as_sequence = &OptionsAsSeq;
Bram Moolenaar07b88642013-05-29 22:58:32 +02007024 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_GC;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02007025 OptionsType.tp_doc = "object for manipulating options";
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007026 OptionsType.tp_iter = OptionsIter;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02007027 OptionsType.tp_as_mapping = &OptionsAsMapping;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007028 OptionsType.tp_dealloc = OptionsDestructor;
7029 OptionsType.tp_traverse = OptionsTraverse;
7030 OptionsType.tp_clear = OptionsClear;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02007031
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007032#if PY_VERSION_HEX < 0x030700f0
Bram Moolenaara80faa82020-04-12 19:37:17 +02007033 CLEAR_FIELD(LoaderType);
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007034 LoaderType.tp_name = "vim.Loader";
7035 LoaderType.tp_basicsize = sizeof(LoaderObject);
7036 LoaderType.tp_flags = Py_TPFLAGS_DEFAULT;
7037 LoaderType.tp_doc = "vim message object";
7038 LoaderType.tp_methods = LoaderMethods;
Yee Cheng Chin02c51b12023-09-21 16:40:12 +02007039 LoaderType.tp_dealloc = LoaderDestructor;
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007040#endif
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007041
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007042#if PY_MAJOR_VERSION >= 3
Bram Moolenaara80faa82020-04-12 19:37:17 +02007043 CLEAR_FIELD(vimmodule);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02007044 vimmodule.m_name = "vim";
7045 vimmodule.m_doc = "Vim Python interface\n";
7046 vimmodule.m_size = -1;
7047 vimmodule.m_methods = VimMethods;
7048#endif
7049}
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007050
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007051 static int
Bram Moolenaarfb97f282013-07-09 17:42:46 +02007052init_types(void)
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007053{
7054 PYTYPE_READY(IterType);
7055 PYTYPE_READY(BufferType);
7056 PYTYPE_READY(RangeType);
7057 PYTYPE_READY(WindowType);
7058 PYTYPE_READY(TabPageType);
7059 PYTYPE_READY(BufMapType);
7060 PYTYPE_READY(WinListType);
7061 PYTYPE_READY(TabListType);
7062 PYTYPE_READY(CurrentType);
7063 PYTYPE_READY(DictionaryType);
7064 PYTYPE_READY(ListType);
7065 PYTYPE_READY(FunctionType);
7066 PYTYPE_READY(OptionsType);
7067 PYTYPE_READY(OutputType);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007068#if PY_VERSION_HEX < 0x030700f0
Bram Moolenaar9f3685a2013-06-12 14:20:36 +02007069 PYTYPE_READY(LoaderType);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007070#endif
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007071
7072#ifdef USE_LIMITED_API
7073 // We need to finish initializing all the static objects because the types
7074 // are only just allocated on the heap now.
7075 // Each PyObject_HEAD_INIT_TYPE should correspond to a
7076 // PyObject_FINISH_INIT_TYPE below.
7077 PyObject_FINISH_INIT_TYPE(Output, OutputType);
7078 PyObject_FINISH_INIT_TYPE(Error, OutputType);
7079 PyObject_FINISH_INIT_TYPE(TheBufferMap, BufMapType);
7080 PyObject_FINISH_INIT_TYPE(TheWindowList, WinListType);
7081 PyObject_FINISH_INIT_TYPE(TheCurrent, CurrentType);
7082 PyObject_FINISH_INIT_TYPE(TheTabPageList, TabListType);
7083#endif
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007084 return 0;
7085}
7086
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007087#ifdef USE_LIMITED_API
7088 static void
7089shutdown_types(void)
7090{
7091 PYTYPE_CLEANUP(IterType);
7092 PYTYPE_CLEANUP(BufferType);
7093 PYTYPE_CLEANUP(RangeType);
7094 PYTYPE_CLEANUP(WindowType);
7095 PYTYPE_CLEANUP(TabPageType);
7096 PYTYPE_CLEANUP(BufMapType);
7097 PYTYPE_CLEANUP(WinListType);
7098 PYTYPE_CLEANUP(TabListType);
7099 PYTYPE_CLEANUP(CurrentType);
7100 PYTYPE_CLEANUP(DictionaryType);
7101 PYTYPE_CLEANUP(ListType);
7102 PYTYPE_CLEANUP(FunctionType);
7103 PYTYPE_CLEANUP(OptionsType);
7104 PYTYPE_CLEANUP(OutputType);
7105# if PY_VERSION_HEX < 0x030700f0
7106 PYTYPE_CLEANUP(LoaderType);
7107# endif
7108}
7109#endif
7110
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007111 static int
Bram Moolenaar5ab9d982013-06-16 14:25:57 +02007112init_sys_path(void)
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007113{
7114 PyObject *path;
7115 PyObject *path_hook;
7116 PyObject *path_hooks;
7117
7118 if (!(path_hook = PyObject_GetAttrString(vim_module, "path_hook")))
7119 return -1;
7120
7121 if (!(path_hooks = PySys_GetObject("path_hooks")))
7122 {
7123 PyErr_Clear();
7124 path_hooks = PyList_New(1);
7125 PyList_SET_ITEM(path_hooks, 0, path_hook);
7126 if (PySys_SetObject("path_hooks", path_hooks))
7127 {
7128 Py_DECREF(path_hooks);
7129 return -1;
7130 }
7131 Py_DECREF(path_hooks);
7132 }
7133 else if (PyList_Check(path_hooks))
7134 {
7135 if (PyList_Append(path_hooks, path_hook))
7136 {
7137 Py_DECREF(path_hook);
7138 return -1;
7139 }
7140 Py_DECREF(path_hook);
7141 }
7142 else
7143 {
7144 VimTryStart();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007145 emsg(_("Failed to set path hook: sys.path_hooks is not a list\n"
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007146 "You should now do the following:\n"
7147 "- append vim.path_hook to sys.path_hooks\n"
7148 "- append vim.VIM_SPECIAL_PATH to sys.path\n"));
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01007149 VimTryEnd(); // Discard the error
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007150 Py_DECREF(path_hook);
7151 return 0;
7152 }
7153
7154 if (!(path = PySys_GetObject("path")))
7155 {
7156 PyErr_Clear();
7157 path = PyList_New(1);
7158 Py_INCREF(vim_special_path_object);
7159 PyList_SET_ITEM(path, 0, vim_special_path_object);
7160 if (PySys_SetObject("path", path))
7161 {
7162 Py_DECREF(path);
7163 return -1;
7164 }
7165 Py_DECREF(path);
7166 }
7167 else if (PyList_Check(path))
7168 {
7169 if (PyList_Append(path, vim_special_path_object))
7170 return -1;
7171 }
7172 else
7173 {
7174 VimTryStart();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007175 emsg(_("Failed to set path: sys.path is not a list\n"
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007176 "You should now append vim.VIM_SPECIAL_PATH to sys.path"));
Bram Moolenaar9bf703d2019-11-30 19:44:38 +01007177 VimTryEnd(); // Discard the error
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007178 }
7179
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007180 return 0;
7181}
7182
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007183static struct numeric_constant {
7184 char *name;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007185 int val;
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007186} numeric_constants[] = {
7187 {"VAR_LOCKED", VAR_LOCKED},
7188 {"VAR_FIXED", VAR_FIXED},
7189 {"VAR_SCOPE", VAR_SCOPE},
7190 {"VAR_DEF_SCOPE", VAR_DEF_SCOPE},
7191};
7192
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007193struct object_constant {
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007194 char *name;
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007195 PyObject *valObject;
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007196};
7197
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007198#define ADD_OBJECT(m, name, obj) \
Bram Moolenaardee2e312013-06-23 16:35:47 +02007199 if (PyModule_AddObject(m, name, obj)) \
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007200 return -1;
7201
7202#define ADD_CHECKED_OBJECT(m, name, obj) \
7203 { \
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007204 PyObject *valObject = obj; \
7205 if (!valObject) \
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007206 return -1; \
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007207 ADD_OBJECT(m, name, valObject); \
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007208 }
7209
7210 static int
Bram Moolenaardee2e312013-06-23 16:35:47 +02007211populate_module(PyObject *m)
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007212{
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007213 int i;
7214 PyObject *other_module;
Bram Moolenaarf9c9b322013-06-10 20:47:36 +02007215 PyObject *attr;
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007216 PyObject *imp;
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007217#if PY_VERSION_HEX >= 0x030700f0
7218 PyObject *dict;
7219 PyObject *cls;
7220#endif
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007221
7222 for (i = 0; i < (int)(sizeof(numeric_constants)
7223 / sizeof(struct numeric_constant));
7224 ++i)
7225 ADD_CHECKED_OBJECT(m, numeric_constants[i].name,
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007226 PyInt_FromLong(numeric_constants[i].val));
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007227
Yee Cheng Chinc13b3d12023-08-20 21:18:38 +02007228 struct object_constant object_constants[] = {
7229 {"buffers", (PyObject *)(void *)&TheBufferMap},
7230 {"windows", (PyObject *)(void *)&TheWindowList},
7231 {"tabpages", (PyObject *)(void *)&TheTabPageList},
7232 {"current", (PyObject *)(void *)&TheCurrent},
7233
7234 {"Buffer", (PyObject *)BufferTypePtr},
7235 {"Range", (PyObject *)RangeTypePtr},
7236 {"Window", (PyObject *)WindowTypePtr},
7237 {"TabPage", (PyObject *)TabPageTypePtr},
7238 {"Dictionary", (PyObject *)DictionaryTypePtr},
7239 {"List", (PyObject *)ListTypePtr},
7240 {"Function", (PyObject *)FunctionTypePtr},
7241 {"Options", (PyObject *)OptionsTypePtr},
7242#if PY_VERSION_HEX < 0x030700f0
7243 {"_Loader", (PyObject *)LoaderTypePtr},
7244#endif
7245 };
7246
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007247 for (i = 0; i < (int)(sizeof(object_constants)
7248 / sizeof(struct object_constant));
7249 ++i)
7250 {
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007251 PyObject *valObject;
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007252
Bram Moolenaarc4b99e02013-06-23 14:30:47 +02007253 valObject = object_constants[i].valObject;
7254 Py_INCREF(valObject);
7255 ADD_OBJECT(m, object_constants[i].name, valObject);
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007256 }
7257
7258 if (!(VimError = PyErr_NewException("vim.error", NULL, NULL)))
7259 return -1;
7260 ADD_OBJECT(m, "error", VimError);
7261
Bram Moolenaarda6c0332019-09-01 16:01:30 +02007262 ADD_CHECKED_OBJECT(m, "vars", NEW_DICTIONARY(get_globvar_dict()));
7263 ADD_CHECKED_OBJECT(m, "vvars", NEW_DICTIONARY(get_vimvar_dict()));
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007264 ADD_CHECKED_OBJECT(m, "options",
7265 OptionsNew(SREQ_GLOBAL, NULL, dummy_check, NULL));
Bram Moolenaarf4258302013-06-02 18:20:17 +02007266
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007267 if (!(other_module = PyImport_ImportModule("os")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007268 return -1;
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007269 ADD_OBJECT(m, "os", other_module);
Bram Moolenaarf4258302013-06-02 18:20:17 +02007270
Bram Moolenaar22081f42016-06-01 20:38:34 +02007271#if PY_MAJOR_VERSION >= 3
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007272 if (!(py_getcwd = PyObject_GetAttrString(other_module, "getcwd")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007273 return -1;
Bram Moolenaar22081f42016-06-01 20:38:34 +02007274#else
7275 if (!(py_getcwd = PyObject_GetAttrString(other_module, "getcwdu")))
7276 return -1;
7277#endif
Bram Moolenaarf4258302013-06-02 18:20:17 +02007278 ADD_OBJECT(m, "_getcwd", py_getcwd)
7279
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007280 if (!(py_chdir = PyObject_GetAttrString(other_module, "chdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007281 return -1;
7282 ADD_OBJECT(m, "_chdir", py_chdir);
Bram Moolenaardee2e312013-06-23 16:35:47 +02007283 if (!(attr = PyObject_GetAttrString(m, "chdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007284 return -1;
Bram Moolenaarf9c9b322013-06-10 20:47:36 +02007285 if (PyObject_SetAttrString(other_module, "chdir", attr))
7286 {
7287 Py_DECREF(attr);
7288 return -1;
7289 }
7290 Py_DECREF(attr);
Bram Moolenaarf4258302013-06-02 18:20:17 +02007291
Bram Moolenaarc1ba10c2013-06-10 20:39:03 +02007292 if ((py_fchdir = PyObject_GetAttrString(other_module, "fchdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007293 {
7294 ADD_OBJECT(m, "_fchdir", py_fchdir);
Bram Moolenaardee2e312013-06-23 16:35:47 +02007295 if (!(attr = PyObject_GetAttrString(m, "fchdir")))
Bram Moolenaarf4258302013-06-02 18:20:17 +02007296 return -1;
Bram Moolenaarf9c9b322013-06-10 20:47:36 +02007297 if (PyObject_SetAttrString(other_module, "fchdir", attr))
7298 {
7299 Py_DECREF(attr);
7300 return -1;
7301 }
7302 Py_DECREF(attr);
Bram Moolenaarf4258302013-06-02 18:20:17 +02007303 }
Bram Moolenaare9056b12013-06-03 20:04:48 +02007304 else
7305 PyErr_Clear();
Bram Moolenaarf4258302013-06-02 18:20:17 +02007306
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007307 if (!(vim_special_path_object = PyString_FromString(vim_special_path)))
7308 return -1;
7309
7310 ADD_OBJECT(m, "VIM_SPECIAL_PATH", vim_special_path_object);
7311
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007312#if PY_VERSION_HEX >= 0x030700f0
7313 if (!(imp = PyImport_ImportModule("importlib.machinery")))
7314 return -1;
7315
7316 dict = PyModule_GetDict(imp);
7317
7318 if (!(cls = PyDict_GetItemString(dict, "PathFinder")))
7319 {
7320 Py_DECREF(imp);
7321 return -1;
7322 }
7323
7324 if (!(py_find_spec = PyObject_GetAttrString(cls, "find_spec")))
7325 {
7326 Py_DECREF(imp);
7327 return -1;
7328 }
7329
Christian Brabandtf0905a82024-05-17 18:30:01 +02007330# if PY_VERSION_HEX < 0x30c00a7
7331 // find_module has been removed as of Python 3.12.0a7
Bram Moolenaarb999ba22019-02-14 13:28:45 +01007332 if ((py_find_module = PyObject_GetAttrString(cls, "find_module")))
Bram Moolenaar9f1983d2022-05-12 20:35:35 +01007333 ADD_OBJECT(m, "_find_module", py_find_module);
Christian Brabandtf0905a82024-05-17 18:30:01 +02007334# endif
Bram Moolenaarb999ba22019-02-14 13:28:45 +01007335
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007336 Py_DECREF(imp);
7337
7338 ADD_OBJECT(m, "_find_spec", py_find_spec);
7339#else
Bram Moolenaar81c40c52013-06-12 14:41:04 +02007340 if (!(imp = PyImport_ImportModule("imp")))
7341 return -1;
7342
7343 if (!(py_find_module = PyObject_GetAttrString(imp, "find_module")))
7344 {
7345 Py_DECREF(imp);
7346 return -1;
7347 }
7348
7349 if (!(py_load_module = PyObject_GetAttrString(imp, "load_module")))
7350 {
7351 Py_DECREF(py_find_module);
7352 Py_DECREF(imp);
7353 return -1;
7354 }
7355
7356 Py_DECREF(imp);
7357
Bram Moolenaar9f3685a2013-06-12 14:20:36 +02007358 ADD_OBJECT(m, "_find_module", py_find_module);
7359 ADD_OBJECT(m, "_load_module", py_load_module);
Bram Moolenaar79a494d2018-07-22 04:30:21 +02007360#endif
Bram Moolenaarc09a6d62013-06-10 21:27:29 +02007361
Bram Moolenaar1dc28782013-05-21 19:11:01 +02007362 return 0;
7363}