blob: 4bd5bae7d4b1ea954ef5cbdd6ca5383872267612 [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
17typedef int Py_ssize_t; /* Python 2.4 and earlier don't have this type. */
18#endif
19
Bram Moolenaar91805fc2011-06-26 04:01:44 +020020#ifdef FEAT_MBYTE
21# define ENC_OPT p_enc
22#else
23# define ENC_OPT "latin1"
24#endif
25
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020026#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
27
28#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
29#define INVALID_WINDOW_VALUE ((win_T *)(-1))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +020030#define INVALID_TABPAGE_VALUE ((tabpage_T *)(-1))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020031
32static int ConvertFromPyObject(PyObject *, typval_T *);
33static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
34
35static PyInt RangeStart;
36static PyInt RangeEnd;
37
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020038/*
39 * obtain a lock on the Vim data structures
40 */
41 static void
42Python_Lock_Vim(void)
43{
44}
45
46/*
47 * release a lock on the Vim data structures
48 */
49 static void
50Python_Release_Vim(void)
51{
52}
53
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020054/* Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020055 */
56
Bram Moolenaar2eea1982010-09-21 16:49:37 +020057/* Function to write a line, points to either msg() or emsg(). */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020058typedef void (*writefn)(char_u *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020059
60static PyTypeObject OutputType;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020061
62typedef struct
63{
64 PyObject_HEAD
65 long softspace;
66 long error;
67} OutputObject;
68
Bram Moolenaar77045652012-09-21 13:46:06 +020069 static int
70OutputSetattr(PyObject *self, char *name, PyObject *val)
71{
72 if (val == NULL)
73 {
Bram Moolenaar8661b172013-05-15 15:44:28 +020074 PyErr_SetString(PyExc_AttributeError,
75 _("can't delete OutputObject attributes"));
Bram Moolenaar77045652012-09-21 13:46:06 +020076 return -1;
77 }
78
79 if (strcmp(name, "softspace") == 0)
80 {
81 if (!PyInt_Check(val))
82 {
83 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
84 return -1;
85 }
86
87 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
88 return 0;
89 }
90
91 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
92 return -1;
93}
94
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020095/* Buffer IO, we write one whole line at a time. */
96static garray_T io_ga = {0, 0, 1, 80, NULL};
97static writefn old_fn = NULL;
98
99 static void
100PythonIO_Flush(void)
101{
102 if (old_fn != NULL && io_ga.ga_len > 0)
103 {
104 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
105 old_fn((char_u *)io_ga.ga_data);
106 }
107 io_ga.ga_len = 0;
108}
109
110 static void
111writer(writefn fn, char_u *str, PyInt n)
112{
113 char_u *ptr;
114
115 /* Flush when switching output function. */
116 if (fn != old_fn)
117 PythonIO_Flush();
118 old_fn = fn;
119
120 /* Write each NL separated line. Text after the last NL is kept for
121 * writing later. */
122 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
123 {
124 PyInt len = ptr - str;
125
126 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
127 break;
128
129 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
130 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
131 fn((char_u *)io_ga.ga_data);
132 str = ptr + 1;
133 n -= len + 1;
134 io_ga.ga_len = 0;
135 }
136
137 /* Put the remaining text into io_ga for later printing. */
138 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
139 {
140 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
141 io_ga.ga_len += (int)n;
142 }
143}
144
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200145 static PyObject *
146OutputWrite(PyObject *self, PyObject *args)
147{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200148 Py_ssize_t len = 0;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200149 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200150 int error = ((OutputObject *)(self))->error;
151
Bram Moolenaar27564802011-09-07 19:30:21 +0200152 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200153 return NULL;
154
155 Py_BEGIN_ALLOW_THREADS
156 Python_Lock_Vim();
157 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
158 Python_Release_Vim();
159 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200160 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200161
162 Py_INCREF(Py_None);
163 return Py_None;
164}
165
166 static PyObject *
167OutputWritelines(PyObject *self, PyObject *args)
168{
169 PyInt n;
170 PyInt i;
171 PyObject *list;
172 int error = ((OutputObject *)(self))->error;
173
174 if (!PyArg_ParseTuple(args, "O", &list))
175 return NULL;
176 Py_INCREF(list);
177
Bram Moolenaardb913952012-06-29 12:54:53 +0200178 if (!PyList_Check(list))
179 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200180 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
181 Py_DECREF(list);
182 return NULL;
183 }
184
185 n = PyList_Size(list);
186
187 for (i = 0; i < n; ++i)
188 {
189 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200190 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200191 PyInt len;
192
Bram Moolenaardb913952012-06-29 12:54:53 +0200193 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
194 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200195 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
196 Py_DECREF(list);
197 return NULL;
198 }
199
200 Py_BEGIN_ALLOW_THREADS
201 Python_Lock_Vim();
202 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
203 Python_Release_Vim();
204 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200205 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200206 }
207
208 Py_DECREF(list);
209 Py_INCREF(Py_None);
210 return Py_None;
211}
212
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100213 static PyObject *
214OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
215{
216 /* do nothing */
217 Py_INCREF(Py_None);
218 return Py_None;
219}
220
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200221/***************/
222
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200223static struct PyMethodDef OutputMethods[] = {
224 /* name, function, calling, documentation */
225 {"write", OutputWrite, 1, ""},
226 {"writelines", OutputWritelines, 1, ""},
227 {"flush", OutputFlush, 1, ""},
228 { NULL, NULL, 0, NULL}
229};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200230
231static OutputObject Output =
232{
233 PyObject_HEAD_INIT(&OutputType)
234 0,
235 0
236};
237
238static OutputObject Error =
239{
240 PyObject_HEAD_INIT(&OutputType)
241 0,
242 1
243};
244
245 static int
246PythonIO_Init_io(void)
247{
248 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
249 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
250
251 if (PyErr_Occurred())
252 {
253 EMSG(_("E264: Python: Error initialising I/O objects"));
254 return -1;
255 }
256
257 return 0;
258}
259
260
261static PyObject *VimError;
262
263/* Check to see whether a Vim error has been reported, or a keyboard
264 * interrupt has been detected.
265 */
266 static int
267VimErrorCheck(void)
268{
269 if (got_int)
270 {
271 PyErr_SetNone(PyExc_KeyboardInterrupt);
272 return 1;
273 }
274 else if (did_emsg && !PyErr_Occurred())
275 {
276 PyErr_SetNone(VimError);
277 return 1;
278 }
279
280 return 0;
281}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200282
283/* Vim module - Implementation
284 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200285
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200286 static PyObject *
287VimCommand(PyObject *self UNUSED, PyObject *args)
288{
289 char *cmd;
290 PyObject *result;
291
292 if (!PyArg_ParseTuple(args, "s", &cmd))
293 return NULL;
294
295 PyErr_Clear();
296
297 Py_BEGIN_ALLOW_THREADS
298 Python_Lock_Vim();
299
300 do_cmdline_cmd((char_u *)cmd);
301 update_screen(VALID);
302
303 Python_Release_Vim();
304 Py_END_ALLOW_THREADS
305
306 if (VimErrorCheck())
307 result = NULL;
308 else
309 result = Py_None;
310
311 Py_XINCREF(result);
312 return result;
313}
314
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200315/*
316 * Function to translate a typval_T into a PyObject; this will recursively
317 * translate lists/dictionaries into their Python equivalents.
318 *
319 * The depth parameter is to avoid infinite recursion, set it to 1 when
320 * you call VimToPython.
321 */
322 static PyObject *
323VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
324{
325 PyObject *result;
326 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200327 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200328
329 /* Avoid infinite recursion */
330 if (depth > 100)
331 {
332 Py_INCREF(Py_None);
333 result = Py_None;
334 return result;
335 }
336
337 /* Check if we run into a recursive loop. The item must be in lookupDict
338 * then and we can use it again. */
339 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
340 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
341 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200342 sprintf(ptrBuf, "%p",
343 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
344 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200345 result = PyDict_GetItemString(lookupDict, ptrBuf);
346 if (result != NULL)
347 {
348 Py_INCREF(result);
349 return result;
350 }
351 }
352
353 if (our_tv->v_type == VAR_STRING)
354 {
Bram Moolenaard1f13fd2012-10-05 21:30:07 +0200355 result = Py_BuildValue("s", our_tv->vval.v_string == NULL
356 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200357 }
358 else if (our_tv->v_type == VAR_NUMBER)
359 {
360 char buf[NUMBUFLEN];
361
362 /* For backwards compatibility numbers are stored as strings. */
363 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
364 result = Py_BuildValue("s", buf);
365 }
366# ifdef FEAT_FLOAT
367 else if (our_tv->v_type == VAR_FLOAT)
368 {
369 char buf[NUMBUFLEN];
370
371 sprintf(buf, "%f", our_tv->vval.v_float);
372 result = Py_BuildValue("s", buf);
373 }
374# endif
375 else if (our_tv->v_type == VAR_LIST)
376 {
377 list_T *list = our_tv->vval.v_list;
378 listitem_T *curr;
379
380 result = PyList_New(0);
381
382 if (list != NULL)
383 {
384 PyDict_SetItemString(lookupDict, ptrBuf, result);
385
386 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
387 {
388 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
389 PyList_Append(result, newObj);
390 Py_DECREF(newObj);
391 }
392 }
393 }
394 else if (our_tv->v_type == VAR_DICT)
395 {
396 result = PyDict_New();
397
398 if (our_tv->vval.v_dict != NULL)
399 {
400 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
401 long_u todo = ht->ht_used;
402 hashitem_T *hi;
403 dictitem_T *di;
404
405 PyDict_SetItemString(lookupDict, ptrBuf, result);
406
407 for (hi = ht->ht_array; todo > 0; ++hi)
408 {
409 if (!HASHITEM_EMPTY(hi))
410 {
411 --todo;
412
413 di = dict_lookup(hi);
414 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
415 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
416 Py_DECREF(newObj);
417 }
418 }
419 }
420 }
421 else
422 {
423 Py_INCREF(Py_None);
424 result = Py_None;
425 }
426
427 return result;
428}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200429
430 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200431VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200432{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200433 char *expr;
434 typval_T *our_tv;
435 PyObject *result;
436 PyObject *lookup_dict;
437
438 if (!PyArg_ParseTuple(args, "s", &expr))
439 return NULL;
440
441 Py_BEGIN_ALLOW_THREADS
442 Python_Lock_Vim();
443 our_tv = eval_expr((char_u *)expr, NULL);
444
445 Python_Release_Vim();
446 Py_END_ALLOW_THREADS
447
448 if (our_tv == NULL)
449 {
450 PyErr_SetVim(_("invalid expression"));
451 return NULL;
452 }
453
454 /* Convert the Vim type into a Python type. Create a dictionary that's
455 * used to check for recursive loops. */
456 lookup_dict = PyDict_New();
457 result = VimToPython(our_tv, 1, lookup_dict);
458 Py_DECREF(lookup_dict);
459
460
461 Py_BEGIN_ALLOW_THREADS
462 Python_Lock_Vim();
463 free_tv(our_tv);
464 Python_Release_Vim();
465 Py_END_ALLOW_THREADS
466
467 return result;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200468}
469
Bram Moolenaardb913952012-06-29 12:54:53 +0200470static PyObject *ConvertToPyObject(typval_T *);
471
472 static PyObject *
473VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
474{
Bram Moolenaardb913952012-06-29 12:54:53 +0200475 char *expr;
476 typval_T *our_tv;
477 PyObject *result;
478
479 if (!PyArg_ParseTuple(args, "s", &expr))
480 return NULL;
481
482 Py_BEGIN_ALLOW_THREADS
483 Python_Lock_Vim();
484 our_tv = eval_expr((char_u *)expr, NULL);
485
486 Python_Release_Vim();
487 Py_END_ALLOW_THREADS
488
489 if (our_tv == NULL)
490 {
491 PyErr_SetVim(_("invalid expression"));
492 return NULL;
493 }
494
495 result = ConvertToPyObject(our_tv);
496 Py_BEGIN_ALLOW_THREADS
497 Python_Lock_Vim();
498 free_tv(our_tv);
499 Python_Release_Vim();
500 Py_END_ALLOW_THREADS
501
502 return result;
Bram Moolenaardb913952012-06-29 12:54:53 +0200503}
504
505 static PyObject *
506VimStrwidth(PyObject *self UNUSED, PyObject *args)
507{
508 char *expr;
509
510 if (!PyArg_ParseTuple(args, "s", &expr))
511 return NULL;
512
Bram Moolenaara54bf402012-12-05 16:30:07 +0100513 return PyLong_FromLong(
514#ifdef FEAT_MBYTE
515 mb_string2cells((char_u *)expr, (int)STRLEN(expr))
516#else
517 STRLEN(expr)
518#endif
519 );
Bram Moolenaardb913952012-06-29 12:54:53 +0200520}
521
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200522/*
523 * Vim module - Definitions
524 */
525
526static struct PyMethodDef VimMethods[] = {
527 /* name, function, calling, documentation */
528 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
529 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200530 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
531 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200532 { NULL, NULL, 0, NULL }
533};
534
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200535/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200536 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200537 */
538
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200539static PyTypeObject IterType;
540
541typedef PyObject *(*nextfun)(void **);
542typedef void (*destructorfun)(void *);
543
544/* Main purpose of this object is removing the need for do python initialization
545 * (i.e. PyType_Ready and setting type attributes) for a big bunch of objects.
546 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200547
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200548typedef struct
549{
550 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200551 void *cur;
552 nextfun next;
553 destructorfun destruct;
554} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200555
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200556 static PyObject *
557IterNew(void *start, destructorfun destruct, nextfun next)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200558{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200559 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200560
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200561 self = PyObject_NEW(IterObject, &IterType);
562 self->cur = start;
563 self->next = next;
564 self->destruct = destruct;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200565
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200566 return (PyObject *)(self);
567}
568
569 static void
570IterDestructor(PyObject *self)
571{
572 IterObject *this = (IterObject *)(self);
573
574 this->destruct(this->cur);
575
576 DESTRUCTOR_FINISH(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200577}
578
579 static PyObject *
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200580IterNext(PyObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200581{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200582 IterObject *this = (IterObject *)(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200583
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200584 return this->next(&this->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200585}
586
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200587 static PyObject *
588IterIter(PyObject *self)
589{
590 return self;
591}
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200592
Bram Moolenaardb913952012-06-29 12:54:53 +0200593typedef struct pylinkedlist_S {
594 struct pylinkedlist_S *pll_next;
595 struct pylinkedlist_S *pll_prev;
596 PyObject *pll_obj;
597} pylinkedlist_T;
598
599static pylinkedlist_T *lastdict = NULL;
600static pylinkedlist_T *lastlist = NULL;
601
602 static void
603pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
604{
605 if (ref->pll_prev == NULL)
606 {
607 if (ref->pll_next == NULL)
608 {
609 *last = NULL;
610 return;
611 }
612 }
613 else
614 ref->pll_prev->pll_next = ref->pll_next;
615
616 if (ref->pll_next == NULL)
617 *last = ref->pll_prev;
618 else
619 ref->pll_next->pll_prev = ref->pll_prev;
620}
621
622 static void
623pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
624{
625 if (*last == NULL)
626 ref->pll_prev = NULL;
627 else
628 {
629 (*last)->pll_next = ref;
630 ref->pll_prev = *last;
631 }
632 ref->pll_next = NULL;
633 ref->pll_obj = self;
634 *last = ref;
635}
636
637static PyTypeObject DictionaryType;
638
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200639#define DICTKEY_GET_NOTEMPTY(err) \
640 DICTKEY_GET(err) \
641 if (*key == NUL) \
642 { \
643 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
644 return err; \
645 }
646
Bram Moolenaardb913952012-06-29 12:54:53 +0200647typedef struct
648{
649 PyObject_HEAD
650 dict_T *dict;
651 pylinkedlist_T ref;
652} DictionaryObject;
653
654 static PyObject *
655DictionaryNew(dict_T *dict)
656{
657 DictionaryObject *self;
658
659 self = PyObject_NEW(DictionaryObject, &DictionaryType);
660 if (self == NULL)
661 return NULL;
662 self->dict = dict;
663 ++dict->dv_refcount;
664
665 pyll_add((PyObject *)(self), &self->ref, &lastdict);
666
667 return (PyObject *)(self);
668}
669
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200670 static void
671DictionaryDestructor(PyObject *self)
672{
673 DictionaryObject *this = ((DictionaryObject *) (self));
674
675 pyll_remove(&this->ref, &lastdict);
676 dict_unref(this->dict);
677
678 DESTRUCTOR_FINISH(self);
679}
680
Bram Moolenaardb913952012-06-29 12:54:53 +0200681 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200682DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200683{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200684 DictionaryObject *this = (DictionaryObject *)(self);
685
Bram Moolenaar66b79852012-09-21 14:00:35 +0200686 if (val == NULL)
687 {
688 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
689 return -1;
690 }
691
692 if (strcmp(name, "locked") == 0)
693 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200694 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200695 {
696 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
697 return -1;
698 }
699 else
700 {
Bram Moolenaarb983f752013-05-15 16:11:50 +0200701 int istrue = PyObject_IsTrue(val);
702 if (istrue == -1)
703 return -1;
704 else if (istrue)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200705 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200706 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200707 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200708 }
709 return 0;
710 }
711 else
712 {
713 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
714 return -1;
715 }
716}
717
718 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200719DictionaryLength(PyObject *self)
720{
721 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
722}
723
724 static PyObject *
725DictionaryItem(PyObject *self, PyObject *keyObject)
726{
727 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200728 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200729 DICTKEY_DECL
730
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200731 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200732
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200733 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
734
Bram Moolenaar696c2112012-09-21 13:43:14 +0200735 DICTKEY_UNREF
736
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200737 if (di == NULL)
738 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200739 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200740 return NULL;
741 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200742
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200743 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200744}
745
746 static PyInt
747DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
748{
749 char_u *key;
750 typval_T tv;
751 dict_T *d = ((DictionaryObject *)(self))->dict;
752 dictitem_T *di;
753 DICTKEY_DECL
754
755 if (d->dv_lock)
756 {
757 PyErr_SetVim(_("dict is locked"));
758 return -1;
759 }
760
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200761 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200762
763 di = dict_find(d, key, -1);
764
765 if (valObject == NULL)
766 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200767 hashitem_T *hi;
768
Bram Moolenaardb913952012-06-29 12:54:53 +0200769 if (di == NULL)
770 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200771 DICTKEY_UNREF
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200772 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaardb913952012-06-29 12:54:53 +0200773 return -1;
774 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200775 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200776 hash_remove(&d->dv_hashtab, hi);
777 dictitem_free(di);
778 return 0;
779 }
780
781 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200782 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200783
784 if (di == NULL)
785 {
786 di = dictitem_alloc(key);
787 if (di == NULL)
788 {
789 PyErr_NoMemory();
790 return -1;
791 }
792 di->di_tv.v_lock = 0;
793
794 if (dict_add(d, di) == FAIL)
795 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200796 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200797 vim_free(di);
798 PyErr_SetVim(_("failed to add key to dictionary"));
799 return -1;
800 }
801 }
802 else
803 clear_tv(&di->di_tv);
804
805 DICTKEY_UNREF
806
807 copy_tv(&tv, &di->di_tv);
808 return 0;
809}
810
811 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100812DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200813{
814 dict_T *dict = ((DictionaryObject *)(self))->dict;
815 long_u todo = dict->dv_hashtab.ht_used;
816 Py_ssize_t i = 0;
817 PyObject *r;
818 hashitem_T *hi;
819
820 r = PyList_New(todo);
821 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
822 {
823 if (!HASHITEM_EMPTY(hi))
824 {
825 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
826 --todo;
827 ++i;
828 }
829 }
830 return r;
831}
832
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200833static PyMappingMethods DictionaryAsMapping = {
834 (lenfunc) DictionaryLength,
835 (binaryfunc) DictionaryItem,
836 (objobjargproc) DictionaryAssItem,
837};
838
Bram Moolenaardb913952012-06-29 12:54:53 +0200839static struct PyMethodDef DictionaryMethods[] = {
840 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
841 { NULL, NULL, 0, NULL }
842};
843
844static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200845static PySequenceMethods ListAsSeq;
846static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200847
848typedef struct
849{
850 PyObject_HEAD
851 list_T *list;
852 pylinkedlist_T ref;
853} ListObject;
854
855 static PyObject *
856ListNew(list_T *list)
857{
858 ListObject *self;
859
860 self = PyObject_NEW(ListObject, &ListType);
861 if (self == NULL)
862 return NULL;
863 self->list = list;
864 ++list->lv_refcount;
865
866 pyll_add((PyObject *)(self), &self->ref, &lastlist);
867
868 return (PyObject *)(self);
869}
870
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200871 static void
872ListDestructor(PyObject *self)
873{
874 ListObject *this = (ListObject *)(self);
875
876 pyll_remove(&this->ref, &lastlist);
877 list_unref(this->list);
878
879 DESTRUCTOR_FINISH(self);
880}
881
Bram Moolenaardb913952012-06-29 12:54:53 +0200882 static int
883list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
884{
885 Py_ssize_t i;
886 Py_ssize_t lsize = PySequence_Size(obj);
887 PyObject *litem;
888 listitem_T *li;
889
890 for(i=0; i<lsize; i++)
891 {
892 li = listitem_alloc();
893 if (li == NULL)
894 {
895 PyErr_NoMemory();
896 return -1;
897 }
898 li->li_tv.v_lock = 0;
899
900 litem = PySequence_GetItem(obj, i);
901 if (litem == NULL)
902 return -1;
903 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
904 return -1;
905
906 list_append(l, li);
907 }
908 return 0;
909}
910
Bram Moolenaardb913952012-06-29 12:54:53 +0200911 static PyInt
912ListLength(PyObject *self)
913{
914 return ((PyInt) (((ListObject *) (self))->list->lv_len));
915}
916
917 static PyObject *
918ListItem(PyObject *self, Py_ssize_t index)
919{
920 listitem_T *li;
921
922 if (index>=ListLength(self))
923 {
Bram Moolenaar8661b172013-05-15 15:44:28 +0200924 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +0200925 return NULL;
926 }
927 li = list_find(((ListObject *) (self))->list, (long) index);
928 if (li == NULL)
929 {
930 PyErr_SetVim(_("internal error: failed to get vim list item"));
931 return NULL;
932 }
933 return ConvertToPyObject(&li->li_tv);
934}
935
936#define PROC_RANGE \
937 if (last < 0) {\
938 if (last < -size) \
939 last = 0; \
940 else \
941 last += size; \
942 } \
943 if (first < 0) \
944 first = 0; \
945 if (first > size) \
946 first = size; \
947 if (last > size) \
948 last = size;
949
950 static PyObject *
951ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
952{
953 PyInt i;
954 PyInt size = ListLength(self);
955 PyInt n;
956 PyObject *list;
957 int reversed = 0;
958
959 PROC_RANGE
960 if (first >= last)
961 first = last;
962
963 n = last-first;
964 list = PyList_New(n);
965 if (list == NULL)
966 return NULL;
967
968 for (i = 0; i < n; ++i)
969 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200970 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +0200971 if (item == NULL)
972 {
973 Py_DECREF(list);
974 return NULL;
975 }
976
977 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
978 {
979 Py_DECREF(item);
980 Py_DECREF(list);
981 return NULL;
982 }
983 }
984
985 return list;
986}
987
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200988typedef struct
989{
990 listwatch_T lw;
991 list_T *list;
992} listiterinfo_T;
993
994 static void
995ListIterDestruct(listiterinfo_T *lii)
996{
997 list_rem_watch(lii->list, &lii->lw);
998 PyMem_Free(lii);
999}
1000
1001 static PyObject *
1002ListIterNext(listiterinfo_T **lii)
1003{
1004 PyObject *r;
1005
1006 if (!((*lii)->lw.lw_item))
1007 return NULL;
1008
1009 if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
1010 return NULL;
1011
1012 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
1013
1014 return r;
1015}
1016
1017 static PyObject *
1018ListIter(PyObject *self)
1019{
1020 listiterinfo_T *lii;
1021 list_T *l = ((ListObject *) (self))->list;
1022
1023 if (!(lii = PyMem_New(listiterinfo_T, 1)))
1024 {
1025 PyErr_NoMemory();
1026 return NULL;
1027 }
1028
1029 list_add_watch(l, &lii->lw);
1030 lii->lw.lw_item = l->lv_first;
1031 lii->list = l;
1032
1033 return IterNew(lii,
1034 (destructorfun) ListIterDestruct, (nextfun) ListIterNext);
1035}
1036
Bram Moolenaardb913952012-06-29 12:54:53 +02001037 static int
1038ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1039{
1040 typval_T tv;
1041 list_T *l = ((ListObject *) (self))->list;
1042 listitem_T *li;
1043 Py_ssize_t length = ListLength(self);
1044
1045 if (l->lv_lock)
1046 {
1047 PyErr_SetVim(_("list is locked"));
1048 return -1;
1049 }
1050 if (index>length || (index==length && obj==NULL))
1051 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001052 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001053 return -1;
1054 }
1055
1056 if (obj == NULL)
1057 {
1058 li = list_find(l, (long) index);
1059 list_remove(l, li, li);
1060 clear_tv(&li->li_tv);
1061 vim_free(li);
1062 return 0;
1063 }
1064
1065 if (ConvertFromPyObject(obj, &tv) == -1)
1066 return -1;
1067
1068 if (index == length)
1069 {
1070 if (list_append_tv(l, &tv) == FAIL)
1071 {
1072 PyErr_SetVim(_("Failed to add item to list"));
1073 return -1;
1074 }
1075 }
1076 else
1077 {
1078 li = list_find(l, (long) index);
1079 clear_tv(&li->li_tv);
1080 copy_tv(&tv, &li->li_tv);
1081 }
1082 return 0;
1083}
1084
1085 static int
1086ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1087{
1088 PyInt size = ListLength(self);
1089 Py_ssize_t i;
1090 Py_ssize_t lsize;
1091 PyObject *litem;
1092 listitem_T *li;
1093 listitem_T *next;
1094 typval_T v;
1095 list_T *l = ((ListObject *) (self))->list;
1096
1097 if (l->lv_lock)
1098 {
1099 PyErr_SetVim(_("list is locked"));
1100 return -1;
1101 }
1102
1103 PROC_RANGE
1104
1105 if (first == size)
1106 li = NULL;
1107 else
1108 {
1109 li = list_find(l, (long) first);
1110 if (li == NULL)
1111 {
1112 PyErr_SetVim(_("internal error: no vim list item"));
1113 return -1;
1114 }
1115 if (last > first)
1116 {
1117 i = last - first;
1118 while (i-- && li != NULL)
1119 {
1120 next = li->li_next;
1121 listitem_remove(l, li);
1122 li = next;
1123 }
1124 }
1125 }
1126
1127 if (obj == NULL)
1128 return 0;
1129
1130 if (!PyList_Check(obj))
1131 {
1132 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1133 return -1;
1134 }
1135
1136 lsize = PyList_Size(obj);
1137
1138 for(i=0; i<lsize; i++)
1139 {
1140 litem = PyList_GetItem(obj, i);
1141 if (litem == NULL)
1142 return -1;
1143 if (ConvertFromPyObject(litem, &v) == -1)
1144 return -1;
1145 if (list_insert_tv(l, &v, li) == FAIL)
1146 {
1147 PyErr_SetVim(_("internal error: failed to add item to list"));
1148 return -1;
1149 }
1150 }
1151 return 0;
1152}
1153
1154 static PyObject *
1155ListConcatInPlace(PyObject *self, PyObject *obj)
1156{
1157 list_T *l = ((ListObject *) (self))->list;
1158 PyObject *lookup_dict;
1159
1160 if (l->lv_lock)
1161 {
1162 PyErr_SetVim(_("list is locked"));
1163 return NULL;
1164 }
1165
1166 if (!PySequence_Check(obj))
1167 {
1168 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1169 return NULL;
1170 }
1171
1172 lookup_dict = PyDict_New();
1173 if (list_py_concat(l, obj, lookup_dict) == -1)
1174 {
1175 Py_DECREF(lookup_dict);
1176 return NULL;
1177 }
1178 Py_DECREF(lookup_dict);
1179
1180 Py_INCREF(self);
1181 return self;
1182}
1183
Bram Moolenaar66b79852012-09-21 14:00:35 +02001184 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001185ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001186{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001187 ListObject *this = (ListObject *)(self);
1188
Bram Moolenaar66b79852012-09-21 14:00:35 +02001189 if (val == NULL)
1190 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001191 PyErr_SetString(PyExc_AttributeError,
1192 _("cannot delete vim.dictionary attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001193 return -1;
1194 }
1195
1196 if (strcmp(name, "locked") == 0)
1197 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001198 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001199 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001200 PyErr_SetString(PyExc_TypeError, _("cannot modify fixed list"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001201 return -1;
1202 }
1203 else
1204 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02001205 int istrue = PyObject_IsTrue(val);
1206 if (istrue == -1)
1207 return -1;
1208 else if (istrue)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001209 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001210 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001211 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001212 }
1213 return 0;
1214 }
1215 else
1216 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001217 PyErr_SetString(PyExc_AttributeError, _("cannot set this attribute"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001218 return -1;
1219 }
1220}
1221
Bram Moolenaardb913952012-06-29 12:54:53 +02001222static struct PyMethodDef ListMethods[] = {
1223 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1224 { NULL, NULL, 0, NULL }
1225};
1226
1227typedef struct
1228{
1229 PyObject_HEAD
1230 char_u *name;
1231} FunctionObject;
1232
1233static PyTypeObject FunctionType;
1234
1235 static PyObject *
1236FunctionNew(char_u *name)
1237{
1238 FunctionObject *self;
1239
1240 self = PyObject_NEW(FunctionObject, &FunctionType);
1241 if (self == NULL)
1242 return NULL;
1243 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1244 if (self->name == NULL)
1245 {
1246 PyErr_NoMemory();
1247 return NULL;
1248 }
1249 STRCPY(self->name, name);
1250 func_ref(name);
1251 return (PyObject *)(self);
1252}
1253
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001254 static void
1255FunctionDestructor(PyObject *self)
1256{
1257 FunctionObject *this = (FunctionObject *) (self);
1258
1259 func_unref(this->name);
1260 PyMem_Del(this->name);
1261
1262 DESTRUCTOR_FINISH(self);
1263}
1264
Bram Moolenaardb913952012-06-29 12:54:53 +02001265 static PyObject *
1266FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1267{
1268 FunctionObject *this = (FunctionObject *)(self);
1269 char_u *name = this->name;
1270 typval_T args;
1271 typval_T selfdicttv;
1272 typval_T rettv;
1273 dict_T *selfdict = NULL;
1274 PyObject *selfdictObject;
1275 PyObject *result;
1276 int error;
1277
1278 if (ConvertFromPyObject(argsObject, &args) == -1)
1279 return NULL;
1280
1281 if (kwargs != NULL)
1282 {
1283 selfdictObject = PyDict_GetItemString(kwargs, "self");
1284 if (selfdictObject != NULL)
1285 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001286 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001287 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001288 PyErr_SetString(PyExc_TypeError,
1289 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001290 clear_tv(&args);
1291 return NULL;
1292 }
1293 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1294 return NULL;
1295 selfdict = selfdicttv.vval.v_dict;
1296 }
1297 }
1298
Bram Moolenaar71700b82013-05-15 17:49:05 +02001299 Py_BEGIN_ALLOW_THREADS
1300 Python_Lock_Vim();
1301
Bram Moolenaardb913952012-06-29 12:54:53 +02001302 error = func_call(name, &args, selfdict, &rettv);
Bram Moolenaar71700b82013-05-15 17:49:05 +02001303
1304 Python_Release_Vim();
1305 Py_END_ALLOW_THREADS
1306
Bram Moolenaardb913952012-06-29 12:54:53 +02001307 if (error != OK)
1308 {
1309 result = NULL;
1310 PyErr_SetVim(_("failed to run function"));
1311 }
1312 else
1313 result = ConvertToPyObject(&rettv);
1314
1315 /* FIXME Check what should really be cleared. */
1316 clear_tv(&args);
1317 clear_tv(&rettv);
1318 /*
1319 * if (selfdict!=NULL)
1320 * clear_tv(selfdicttv);
1321 */
1322
1323 return result;
1324}
1325
1326static struct PyMethodDef FunctionMethods[] = {
1327 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1328 { NULL, NULL, 0, NULL }
1329};
1330
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001331/*
1332 * Options object
1333 */
1334
1335static PyTypeObject OptionsType;
1336
1337typedef int (*checkfun)(void *);
1338
1339typedef struct
1340{
1341 PyObject_HEAD
1342 int opt_type;
1343 void *from;
1344 checkfun Check;
1345 PyObject *fromObj;
1346} OptionsObject;
1347
1348 static PyObject *
1349OptionsItem(OptionsObject *this, PyObject *keyObject)
1350{
1351 char_u *key;
1352 int flags;
1353 long numval;
1354 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001355 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001356
1357 if (this->Check(this->from))
1358 return NULL;
1359
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001360 DICTKEY_GET_NOTEMPTY(NULL)
1361
1362 flags = get_option_value_strict(key, &numval, &stringval,
1363 this->opt_type, this->from);
1364
1365 DICTKEY_UNREF
1366
1367 if (flags == 0)
1368 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001369 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001370 return NULL;
1371 }
1372
1373 if (flags & SOPT_UNSET)
1374 {
1375 Py_INCREF(Py_None);
1376 return Py_None;
1377 }
1378 else if (flags & SOPT_BOOL)
1379 {
1380 PyObject *r;
1381 r = numval ? Py_True : Py_False;
1382 Py_INCREF(r);
1383 return r;
1384 }
1385 else if (flags & SOPT_NUM)
1386 return PyInt_FromLong(numval);
1387 else if (flags & SOPT_STRING)
1388 {
1389 if (stringval)
1390 return PyBytes_FromString((char *) stringval);
1391 else
1392 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001393 PyErr_SetString(PyExc_RuntimeError,
1394 _("unable to get option value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001395 return NULL;
1396 }
1397 }
1398 else
1399 {
1400 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1401 return NULL;
1402 }
1403}
1404
1405 static int
1406set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1407 char_u *key;
1408 int numval;
1409 char_u *stringval;
1410 int opt_flags;
1411 int opt_type;
1412 void *from;
1413{
1414 win_T *save_curwin;
1415 tabpage_T *save_curtab;
1416 aco_save_T aco;
1417 int r = 0;
1418
1419 switch (opt_type)
1420 {
1421 case SREQ_WIN:
1422 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1423 == FAIL)
1424 {
1425 PyErr_SetVim("Problem while switching windows.");
1426 return -1;
1427 }
1428 set_option_value(key, numval, stringval, opt_flags);
1429 restore_win(save_curwin, save_curtab);
1430 break;
1431 case SREQ_BUF:
1432 aucmd_prepbuf(&aco, (buf_T *) from);
1433 set_option_value(key, numval, stringval, opt_flags);
1434 aucmd_restbuf(&aco);
1435 break;
1436 case SREQ_GLOBAL:
1437 set_option_value(key, numval, stringval, opt_flags);
1438 break;
1439 }
1440 return r;
1441}
1442
1443 static int
1444OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1445{
1446 char_u *key;
1447 int flags;
1448 int opt_flags;
1449 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001450 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001451
1452 if (this->Check(this->from))
1453 return -1;
1454
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001455 DICTKEY_GET_NOTEMPTY(-1)
1456
1457 flags = get_option_value_strict(key, NULL, NULL,
1458 this->opt_type, this->from);
1459
1460 DICTKEY_UNREF
1461
1462 if (flags == 0)
1463 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001464 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001465 return -1;
1466 }
1467
1468 if (valObject == NULL)
1469 {
1470 if (this->opt_type == SREQ_GLOBAL)
1471 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001472 PyErr_SetString(PyExc_ValueError,
1473 _("unable to unset global option"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001474 return -1;
1475 }
1476 else if (!(flags & SOPT_GLOBAL))
1477 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001478 PyErr_SetString(PyExc_ValueError, _("unable to unset option "
1479 "without global value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001480 return -1;
1481 }
1482 else
1483 {
1484 unset_global_local_option(key, this->from);
1485 return 0;
1486 }
1487 }
1488
1489 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1490
1491 if (flags & SOPT_BOOL)
1492 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02001493 int istrue = PyObject_IsTrue(valObject);
1494 if (istrue == -1)
1495 return -1;
1496 r = set_option_value_for(key, istrue, NULL,
Bram Moolenaar03db85b2013-05-15 14:51:35 +02001497 opt_flags, this->opt_type, this->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001498 }
1499 else if (flags & SOPT_NUM)
1500 {
1501 int val;
1502
1503#if PY_MAJOR_VERSION < 3
1504 if (PyInt_Check(valObject))
1505 val = PyInt_AsLong(valObject);
1506 else
1507#endif
1508 if (PyLong_Check(valObject))
1509 val = PyLong_AsLong(valObject);
1510 else
1511 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001512 PyErr_SetString(PyExc_TypeError, _("object must be integer"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001513 return -1;
1514 }
1515
1516 r = set_option_value_for(key, val, NULL, opt_flags,
1517 this->opt_type, this->from);
1518 }
1519 else
1520 {
1521 char_u *val;
1522 if (PyBytes_Check(valObject))
1523 {
1524
1525 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1526 return -1;
1527 if (val == NULL)
1528 return -1;
1529
1530 val = vim_strsave(val);
1531 }
1532 else if (PyUnicode_Check(valObject))
1533 {
1534 PyObject *bytes;
1535
1536 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1537 if (bytes == NULL)
1538 return -1;
1539
1540 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1541 return -1;
1542 if (val == NULL)
1543 return -1;
1544
1545 val = vim_strsave(val);
1546 Py_XDECREF(bytes);
1547 }
1548 else
1549 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001550 PyErr_SetString(PyExc_TypeError, _("object must be string"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001551 return -1;
1552 }
1553
1554 r = set_option_value_for(key, 0, val, opt_flags,
1555 this->opt_type, this->from);
1556 vim_free(val);
1557 }
1558
1559 return r;
1560}
1561
1562 static int
1563dummy_check(void *arg UNUSED)
1564{
1565 return 0;
1566}
1567
1568 static PyObject *
1569OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1570{
1571 OptionsObject *self;
1572
1573 self = PyObject_NEW(OptionsObject, &OptionsType);
1574 if (self == NULL)
1575 return NULL;
1576
1577 self->opt_type = opt_type;
1578 self->from = from;
1579 self->Check = Check;
1580 self->fromObj = fromObj;
1581 if (fromObj)
1582 Py_INCREF(fromObj);
1583
1584 return (PyObject *)(self);
1585}
1586
1587 static void
1588OptionsDestructor(PyObject *self)
1589{
1590 if (((OptionsObject *)(self))->fromObj)
1591 Py_DECREF(((OptionsObject *)(self))->fromObj);
1592 DESTRUCTOR_FINISH(self);
1593}
1594
1595static PyMappingMethods OptionsAsMapping = {
1596 (lenfunc) NULL,
1597 (binaryfunc) OptionsItem,
1598 (objobjargproc) OptionsAssItem,
1599};
1600
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001601/* Tabpage object
1602 */
1603
1604typedef struct
1605{
1606 PyObject_HEAD
1607 tabpage_T *tab;
1608} TabPageObject;
1609
1610static PyObject *WinListNew(TabPageObject *tabObject);
1611
1612static PyTypeObject TabPageType;
1613
1614 static int
1615CheckTabPage(TabPageObject *this)
1616{
1617 if (this->tab == INVALID_TABPAGE_VALUE)
1618 {
1619 PyErr_SetVim(_("attempt to refer to deleted tab page"));
1620 return -1;
1621 }
1622
1623 return 0;
1624}
1625
1626 static PyObject *
1627TabPageNew(tabpage_T *tab)
1628{
1629 TabPageObject *self;
1630
1631 if (TAB_PYTHON_REF(tab))
1632 {
1633 self = TAB_PYTHON_REF(tab);
1634 Py_INCREF(self);
1635 }
1636 else
1637 {
1638 self = PyObject_NEW(TabPageObject, &TabPageType);
1639 if (self == NULL)
1640 return NULL;
1641 self->tab = tab;
1642 TAB_PYTHON_REF(tab) = self;
1643 }
1644
1645 return (PyObject *)(self);
1646}
1647
1648 static void
1649TabPageDestructor(PyObject *self)
1650{
1651 TabPageObject *this = (TabPageObject *)(self);
1652
1653 if (this->tab && this->tab != INVALID_TABPAGE_VALUE)
1654 TAB_PYTHON_REF(this->tab) = NULL;
1655
1656 DESTRUCTOR_FINISH(self);
1657}
1658
1659 static PyObject *
1660TabPageAttr(TabPageObject *this, char *name)
1661{
1662 if (strcmp(name, "windows") == 0)
1663 return WinListNew(this);
1664 else if (strcmp(name, "number") == 0)
1665 return PyLong_FromLong((long) get_tab_number(this->tab));
1666 else if (strcmp(name, "vars") == 0)
1667 return DictionaryNew(this->tab->tp_vars);
1668 else if (strcmp(name, "window") == 0)
1669 {
1670 /* For current tab window.c does not bother to set or update tp_curwin
1671 */
1672 if (this->tab == curtab)
1673 return WindowNew(curwin);
1674 else
1675 return WindowNew(this->tab->tp_curwin);
1676 }
1677 return NULL;
1678}
1679
1680 static PyObject *
1681TabPageRepr(PyObject *self)
1682{
1683 static char repr[100];
1684 TabPageObject *this = (TabPageObject *)(self);
1685
1686 if (this->tab == INVALID_TABPAGE_VALUE)
1687 {
1688 vim_snprintf(repr, 100, _("<tabpage object (deleted) at %p>"), (self));
1689 return PyString_FromString(repr);
1690 }
1691 else
1692 {
1693 int t = get_tab_number(this->tab);
1694
1695 if (t == 0)
1696 vim_snprintf(repr, 100, _("<tabpage object (unknown) at %p>"),
1697 (self));
1698 else
1699 vim_snprintf(repr, 100, _("<tabpage %d>"), t - 1);
1700
1701 return PyString_FromString(repr);
1702 }
1703}
1704
1705static struct PyMethodDef TabPageMethods[] = {
1706 /* name, function, calling, documentation */
1707 { NULL, NULL, 0, NULL }
1708};
1709
1710/*
1711 * Window list object
1712 */
1713
1714static PyTypeObject TabListType;
1715static PySequenceMethods TabListAsSeq;
1716
1717typedef struct
1718{
1719 PyObject_HEAD
1720} TabListObject;
1721
1722 static PyInt
1723TabListLength(PyObject *self UNUSED)
1724{
1725 tabpage_T *tp = first_tabpage;
1726 PyInt n = 0;
1727
1728 while (tp != NULL)
1729 {
1730 ++n;
1731 tp = tp->tp_next;
1732 }
1733
1734 return n;
1735}
1736
1737 static PyObject *
1738TabListItem(PyObject *self UNUSED, PyInt n)
1739{
1740 tabpage_T *tp;
1741
1742 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, --n)
1743 if (n == 0)
1744 return TabPageNew(tp);
1745
1746 PyErr_SetString(PyExc_IndexError, _("no such tab page"));
1747 return NULL;
1748}
1749
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001750/* Window object
1751 */
1752
1753typedef struct
1754{
1755 PyObject_HEAD
1756 win_T *win;
1757} WindowObject;
1758
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001759static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001760
1761 static int
1762CheckWindow(WindowObject *this)
1763{
1764 if (this->win == INVALID_WINDOW_VALUE)
1765 {
1766 PyErr_SetVim(_("attempt to refer to deleted window"));
1767 return -1;
1768 }
1769
1770 return 0;
1771}
1772
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001773 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001774WindowNew(win_T *win)
1775{
1776 /* We need to handle deletion of windows underneath us.
1777 * If we add a "w_python*_ref" field to the win_T structure,
1778 * then we can get at it in win_free() in vim. We then
1779 * need to create only ONE Python object per window - if
1780 * we try to create a second, just INCREF the existing one
1781 * and return it. The (single) Python object referring to
1782 * the window is stored in "w_python*_ref".
1783 * On a win_free() we set the Python object's win_T* field
1784 * to an invalid value. We trap all uses of a window
1785 * object, and reject them if the win_T* field is invalid.
1786 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001787 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001788 * w_python_ref and w_python3_ref fields respectively.
1789 */
1790
1791 WindowObject *self;
1792
1793 if (WIN_PYTHON_REF(win))
1794 {
1795 self = WIN_PYTHON_REF(win);
1796 Py_INCREF(self);
1797 }
1798 else
1799 {
1800 self = PyObject_NEW(WindowObject, &WindowType);
1801 if (self == NULL)
1802 return NULL;
1803 self->win = win;
1804 WIN_PYTHON_REF(win) = self;
1805 }
1806
1807 return (PyObject *)(self);
1808}
1809
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001810 static void
1811WindowDestructor(PyObject *self)
1812{
1813 WindowObject *this = (WindowObject *)(self);
1814
1815 if (this->win && this->win != INVALID_WINDOW_VALUE)
1816 WIN_PYTHON_REF(this->win) = NULL;
1817
1818 DESTRUCTOR_FINISH(self);
1819}
1820
Bram Moolenaar971db462013-05-12 18:44:48 +02001821 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001822WindowAttr(WindowObject *this, char *name)
1823{
1824 if (strcmp(name, "buffer") == 0)
1825 return (PyObject *)BufferNew(this->win->w_buffer);
1826 else if (strcmp(name, "cursor") == 0)
1827 {
1828 pos_T *pos = &this->win->w_cursor;
1829
1830 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1831 }
1832 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001833 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001834#ifdef FEAT_WINDOWS
1835 else if (strcmp(name, "row") == 0)
1836 return PyLong_FromLong((long)(this->win->w_winrow));
1837#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001838#ifdef FEAT_VERTSPLIT
1839 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001840 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001841 else if (strcmp(name, "col") == 0)
1842 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001843#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001844 else if (strcmp(name, "vars") == 0)
1845 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001846 else if (strcmp(name, "options") == 0)
1847 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1848 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001849 else if (strcmp(name, "number") == 0)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001850 return PyLong_FromLong((long) get_win_number(this->win, firstwin));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001851 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001852 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1853 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001854 else
1855 return NULL;
1856}
1857
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001858 static int
1859WindowSetattr(PyObject *self, char *name, PyObject *val)
1860{
1861 WindowObject *this = (WindowObject *)(self);
1862
1863 if (CheckWindow(this))
1864 return -1;
1865
1866 if (strcmp(name, "buffer") == 0)
1867 {
1868 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1869 return -1;
1870 }
1871 else if (strcmp(name, "cursor") == 0)
1872 {
1873 long lnum;
1874 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001875
1876 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1877 return -1;
1878
1879 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1880 {
1881 PyErr_SetVim(_("cursor position outside buffer"));
1882 return -1;
1883 }
1884
1885 /* Check for keyboard interrupts */
1886 if (VimErrorCheck())
1887 return -1;
1888
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001889 this->win->w_cursor.lnum = lnum;
1890 this->win->w_cursor.col = col;
1891#ifdef FEAT_VIRTUALEDIT
1892 this->win->w_cursor.coladd = 0;
1893#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001894 /* When column is out of range silently correct it. */
1895 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001896
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001897 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001898 return 0;
1899 }
1900 else if (strcmp(name, "height") == 0)
1901 {
1902 int height;
1903 win_T *savewin;
1904
1905 if (!PyArg_Parse(val, "i", &height))
1906 return -1;
1907
1908#ifdef FEAT_GUI
1909 need_mouse_correct = TRUE;
1910#endif
1911 savewin = curwin;
1912 curwin = this->win;
1913 win_setheight(height);
1914 curwin = savewin;
1915
1916 /* Check for keyboard interrupts */
1917 if (VimErrorCheck())
1918 return -1;
1919
1920 return 0;
1921 }
1922#ifdef FEAT_VERTSPLIT
1923 else if (strcmp(name, "width") == 0)
1924 {
1925 int width;
1926 win_T *savewin;
1927
1928 if (!PyArg_Parse(val, "i", &width))
1929 return -1;
1930
1931#ifdef FEAT_GUI
1932 need_mouse_correct = TRUE;
1933#endif
1934 savewin = curwin;
1935 curwin = this->win;
1936 win_setwidth(width);
1937 curwin = savewin;
1938
1939 /* Check for keyboard interrupts */
1940 if (VimErrorCheck())
1941 return -1;
1942
1943 return 0;
1944 }
1945#endif
1946 else
1947 {
1948 PyErr_SetString(PyExc_AttributeError, name);
1949 return -1;
1950 }
1951}
1952
1953 static PyObject *
1954WindowRepr(PyObject *self)
1955{
1956 static char repr[100];
1957 WindowObject *this = (WindowObject *)(self);
1958
1959 if (this->win == INVALID_WINDOW_VALUE)
1960 {
1961 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1962 return PyString_FromString(repr);
1963 }
1964 else
1965 {
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001966 int w = get_win_number(this->win, firstwin);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001967
Bram Moolenaar6d216452013-05-12 19:00:41 +02001968 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001969 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1970 (self));
1971 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001972 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001973
1974 return PyString_FromString(repr);
1975 }
1976}
1977
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001978static struct PyMethodDef WindowMethods[] = {
1979 /* name, function, calling, documentation */
1980 { NULL, NULL, 0, NULL }
1981};
1982
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001983/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001984 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001985 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001986
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001987static PyTypeObject WinListType;
1988static PySequenceMethods WinListAsSeq;
1989
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001990typedef struct
1991{
1992 PyObject_HEAD
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001993 TabPageObject *tabObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001994} WinListObject;
1995
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001996 static PyObject *
1997WinListNew(TabPageObject *tabObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001998{
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001999 WinListObject *self;
2000
2001 self = PyObject_NEW(WinListObject, &WinListType);
2002 self->tabObject = tabObject;
2003 Py_INCREF(tabObject);
2004
2005 return (PyObject *)(self);
2006}
2007
2008 static void
2009WinListDestructor(PyObject *self)
2010{
2011 TabPageObject *tabObject = ((WinListObject *)(self))->tabObject;
2012
2013 if (tabObject)
2014 Py_DECREF((PyObject *)(tabObject));
2015
2016 DESTRUCTOR_FINISH(self);
2017}
2018
2019 static win_T *
2020get_firstwin(WinListObject *this)
2021{
2022 if (this->tabObject)
2023 {
2024 if (CheckTabPage(this->tabObject))
2025 return NULL;
2026 /* For current tab window.c does not bother to set or update tp_firstwin
2027 */
2028 else if (this->tabObject->tab == curtab)
2029 return firstwin;
2030 else
2031 return this->tabObject->tab->tp_firstwin;
2032 }
2033 else
2034 return firstwin;
2035}
2036
2037 static PyInt
2038WinListLength(PyObject *self)
2039{
2040 win_T *w;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002041 PyInt n = 0;
2042
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002043 if (!(w = get_firstwin((WinListObject *)(self))))
2044 return -1;
2045
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002046 while (w != NULL)
2047 {
2048 ++n;
2049 w = W_NEXT(w);
2050 }
2051
2052 return n;
2053}
2054
2055 static PyObject *
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002056WinListItem(PyObject *self, PyInt n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002057{
2058 win_T *w;
2059
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002060 if (!(w = get_firstwin((WinListObject *)(self))))
2061 return NULL;
2062
2063 for (; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002064 if (n == 0)
2065 return WindowNew(w);
2066
2067 PyErr_SetString(PyExc_IndexError, _("no such window"));
2068 return NULL;
2069}
2070
2071/* Convert a Python string into a Vim line.
2072 *
2073 * The result is in allocated memory. All internal nulls are replaced by
2074 * newline characters. It is an error for the string to contain newline
2075 * characters.
2076 *
2077 * On errors, the Python exception data is set, and NULL is returned.
2078 */
2079 static char *
2080StringToLine(PyObject *obj)
2081{
2082 const char *str;
2083 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002084 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002085 PyInt len;
2086 PyInt i;
2087 char *p;
2088
2089 if (obj == NULL || !PyString_Check(obj))
2090 {
2091 PyErr_BadArgument();
2092 return NULL;
2093 }
2094
Bram Moolenaar19e60942011-06-19 00:27:51 +02002095 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
2096 str = PyString_AsString(bytes);
2097 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002098
2099 /*
2100 * Error checking: String must not contain newlines, as we
2101 * are replacing a single line, and we must replace it with
2102 * a single line.
2103 * A trailing newline is removed, so that append(f.readlines()) works.
2104 */
2105 p = memchr(str, '\n', len);
2106 if (p != NULL)
2107 {
2108 if (p == str + len - 1)
2109 --len;
2110 else
2111 {
2112 PyErr_SetVim(_("string cannot contain newlines"));
2113 return NULL;
2114 }
2115 }
2116
2117 /* Create a copy of the string, with internal nulls replaced by
2118 * newline characters, as is the vim convention.
2119 */
2120 save = (char *)alloc((unsigned)(len+1));
2121 if (save == NULL)
2122 {
2123 PyErr_NoMemory();
2124 return NULL;
2125 }
2126
2127 for (i = 0; i < len; ++i)
2128 {
2129 if (str[i] == '\0')
2130 save[i] = '\n';
2131 else
2132 save[i] = str[i];
2133 }
2134
2135 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02002136 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002137
2138 return save;
2139}
2140
2141/* Get a line from the specified buffer. The line number is
2142 * in Vim format (1-based). The line is returned as a Python
2143 * string object.
2144 */
2145 static PyObject *
2146GetBufferLine(buf_T *buf, PyInt n)
2147{
2148 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2149}
2150
2151
2152/* Get a list of lines from the specified buffer. The line numbers
2153 * are in Vim format (1-based). The range is from lo up to, but not
2154 * including, hi. The list is returned as a Python list of string objects.
2155 */
2156 static PyObject *
2157GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2158{
2159 PyInt i;
2160 PyInt n = hi - lo;
2161 PyObject *list = PyList_New(n);
2162
2163 if (list == NULL)
2164 return NULL;
2165
2166 for (i = 0; i < n; ++i)
2167 {
2168 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2169
2170 /* Error check - was the Python string creation OK? */
2171 if (str == NULL)
2172 {
2173 Py_DECREF(list);
2174 return NULL;
2175 }
2176
2177 /* Set the list item */
2178 if (PyList_SetItem(list, i, str))
2179 {
2180 Py_DECREF(str);
2181 Py_DECREF(list);
2182 return NULL;
2183 }
2184 }
2185
2186 /* The ownership of the Python list is passed to the caller (ie,
2187 * the caller should Py_DECREF() the object when it is finished
2188 * with it).
2189 */
2190
2191 return list;
2192}
2193
2194/*
2195 * Check if deleting lines made the cursor position invalid.
2196 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2197 * deleted).
2198 */
2199 static void
2200py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2201{
2202 if (curwin->w_cursor.lnum >= lo)
2203 {
2204 /* Adjust the cursor position if it's in/after the changed
2205 * lines. */
2206 if (curwin->w_cursor.lnum >= hi)
2207 {
2208 curwin->w_cursor.lnum += extra;
2209 check_cursor_col();
2210 }
2211 else if (extra < 0)
2212 {
2213 curwin->w_cursor.lnum = lo;
2214 check_cursor();
2215 }
2216 else
2217 check_cursor_col();
2218 changed_cline_bef_curs();
2219 }
2220 invalidate_botline();
2221}
2222
Bram Moolenaar19e60942011-06-19 00:27:51 +02002223/*
2224 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002225 * in Vim format (1-based). The replacement line is given as
2226 * a Python string object. The object is checked for validity
2227 * and correct format. Errors are returned as a value of FAIL.
2228 * The return value is OK on success.
2229 * If OK is returned and len_change is not NULL, *len_change
2230 * is set to the change in the buffer length.
2231 */
2232 static int
2233SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2234{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002235 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002236 * There are three cases:
2237 * 1. NULL, or None - this is a deletion.
2238 * 2. A string - this is a replacement.
2239 * 3. Anything else - this is an error.
2240 */
2241 if (line == Py_None || line == NULL)
2242 {
2243 buf_T *savebuf = curbuf;
2244
2245 PyErr_Clear();
2246 curbuf = buf;
2247
2248 if (u_savedel((linenr_T)n, 1L) == FAIL)
2249 PyErr_SetVim(_("cannot save undo information"));
2250 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2251 PyErr_SetVim(_("cannot delete line"));
2252 else
2253 {
2254 if (buf == curwin->w_buffer)
2255 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2256 deleted_lines_mark((linenr_T)n, 1L);
2257 }
2258
2259 curbuf = savebuf;
2260
2261 if (PyErr_Occurred() || VimErrorCheck())
2262 return FAIL;
2263
2264 if (len_change)
2265 *len_change = -1;
2266
2267 return OK;
2268 }
2269 else if (PyString_Check(line))
2270 {
2271 char *save = StringToLine(line);
2272 buf_T *savebuf = curbuf;
2273
2274 if (save == NULL)
2275 return FAIL;
2276
2277 /* We do not need to free "save" if ml_replace() consumes it. */
2278 PyErr_Clear();
2279 curbuf = buf;
2280
2281 if (u_savesub((linenr_T)n) == FAIL)
2282 {
2283 PyErr_SetVim(_("cannot save undo information"));
2284 vim_free(save);
2285 }
2286 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2287 {
2288 PyErr_SetVim(_("cannot replace line"));
2289 vim_free(save);
2290 }
2291 else
2292 changed_bytes((linenr_T)n, 0);
2293
2294 curbuf = savebuf;
2295
2296 /* Check that the cursor is not beyond the end of the line now. */
2297 if (buf == curwin->w_buffer)
2298 check_cursor_col();
2299
2300 if (PyErr_Occurred() || VimErrorCheck())
2301 return FAIL;
2302
2303 if (len_change)
2304 *len_change = 0;
2305
2306 return OK;
2307 }
2308 else
2309 {
2310 PyErr_BadArgument();
2311 return FAIL;
2312 }
2313}
2314
Bram Moolenaar19e60942011-06-19 00:27:51 +02002315/* Replace a range of lines in the specified buffer. The line numbers are in
2316 * Vim format (1-based). The range is from lo up to, but not including, hi.
2317 * The replacement lines are given as a Python list of string objects. The
2318 * list is checked for validity and correct format. Errors are returned as a
2319 * value of FAIL. The return value is OK on success.
2320 * If OK is returned and len_change is not NULL, *len_change
2321 * is set to the change in the buffer length.
2322 */
2323 static int
2324SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2325{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002326 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002327 * There are three cases:
2328 * 1. NULL, or None - this is a deletion.
2329 * 2. A list - this is a replacement.
2330 * 3. Anything else - this is an error.
2331 */
2332 if (list == Py_None || list == NULL)
2333 {
2334 PyInt i;
2335 PyInt n = (int)(hi - lo);
2336 buf_T *savebuf = curbuf;
2337
2338 PyErr_Clear();
2339 curbuf = buf;
2340
2341 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2342 PyErr_SetVim(_("cannot save undo information"));
2343 else
2344 {
2345 for (i = 0; i < n; ++i)
2346 {
2347 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2348 {
2349 PyErr_SetVim(_("cannot delete line"));
2350 break;
2351 }
2352 }
2353 if (buf == curwin->w_buffer)
2354 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2355 deleted_lines_mark((linenr_T)lo, (long)i);
2356 }
2357
2358 curbuf = savebuf;
2359
2360 if (PyErr_Occurred() || VimErrorCheck())
2361 return FAIL;
2362
2363 if (len_change)
2364 *len_change = -n;
2365
2366 return OK;
2367 }
2368 else if (PyList_Check(list))
2369 {
2370 PyInt i;
2371 PyInt new_len = PyList_Size(list);
2372 PyInt old_len = hi - lo;
2373 PyInt extra = 0; /* lines added to text, can be negative */
2374 char **array;
2375 buf_T *savebuf;
2376
2377 if (new_len == 0) /* avoid allocating zero bytes */
2378 array = NULL;
2379 else
2380 {
2381 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2382 if (array == NULL)
2383 {
2384 PyErr_NoMemory();
2385 return FAIL;
2386 }
2387 }
2388
2389 for (i = 0; i < new_len; ++i)
2390 {
2391 PyObject *line = PyList_GetItem(list, i);
2392
2393 array[i] = StringToLine(line);
2394 if (array[i] == NULL)
2395 {
2396 while (i)
2397 vim_free(array[--i]);
2398 vim_free(array);
2399 return FAIL;
2400 }
2401 }
2402
2403 savebuf = curbuf;
2404
2405 PyErr_Clear();
2406 curbuf = buf;
2407
2408 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2409 PyErr_SetVim(_("cannot save undo information"));
2410
2411 /* If the size of the range is reducing (ie, new_len < old_len) we
2412 * need to delete some old_len. We do this at the start, by
2413 * repeatedly deleting line "lo".
2414 */
2415 if (!PyErr_Occurred())
2416 {
2417 for (i = 0; i < old_len - new_len; ++i)
2418 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2419 {
2420 PyErr_SetVim(_("cannot delete line"));
2421 break;
2422 }
2423 extra -= i;
2424 }
2425
2426 /* For as long as possible, replace the existing old_len with the
2427 * new old_len. This is a more efficient operation, as it requires
2428 * less memory allocation and freeing.
2429 */
2430 if (!PyErr_Occurred())
2431 {
2432 for (i = 0; i < old_len && i < new_len; ++i)
2433 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2434 == FAIL)
2435 {
2436 PyErr_SetVim(_("cannot replace line"));
2437 break;
2438 }
2439 }
2440 else
2441 i = 0;
2442
2443 /* Now we may need to insert the remaining new old_len. If we do, we
2444 * must free the strings as we finish with them (we can't pass the
2445 * responsibility to vim in this case).
2446 */
2447 if (!PyErr_Occurred())
2448 {
2449 while (i < new_len)
2450 {
2451 if (ml_append((linenr_T)(lo + i - 1),
2452 (char_u *)array[i], 0, FALSE) == FAIL)
2453 {
2454 PyErr_SetVim(_("cannot insert line"));
2455 break;
2456 }
2457 vim_free(array[i]);
2458 ++i;
2459 ++extra;
2460 }
2461 }
2462
2463 /* Free any left-over old_len, as a result of an error */
2464 while (i < new_len)
2465 {
2466 vim_free(array[i]);
2467 ++i;
2468 }
2469
2470 /* Free the array of old_len. All of its contents have now
2471 * been dealt with (either freed, or the responsibility passed
2472 * to vim.
2473 */
2474 vim_free(array);
2475
2476 /* Adjust marks. Invalidate any which lie in the
2477 * changed range, and move any in the remainder of the buffer.
2478 */
2479 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2480 (long)MAXLNUM, (long)extra);
2481 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2482
2483 if (buf == curwin->w_buffer)
2484 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2485
2486 curbuf = savebuf;
2487
2488 if (PyErr_Occurred() || VimErrorCheck())
2489 return FAIL;
2490
2491 if (len_change)
2492 *len_change = new_len - old_len;
2493
2494 return OK;
2495 }
2496 else
2497 {
2498 PyErr_BadArgument();
2499 return FAIL;
2500 }
2501}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002502
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002503/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002504 * The line number is in Vim format (1-based). The lines to be inserted are
2505 * given as a Python list of string objects or as a single string. The lines
2506 * to be added are checked for validity and correct format. Errors are
2507 * returned as a value of FAIL. The return value is OK on success.
2508 * If OK is returned and len_change is not NULL, *len_change
2509 * is set to the change in the buffer length.
2510 */
2511 static int
2512InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2513{
2514 /* First of all, we check the type of the supplied Python object.
2515 * It must be a string or a list, or the call is in error.
2516 */
2517 if (PyString_Check(lines))
2518 {
2519 char *str = StringToLine(lines);
2520 buf_T *savebuf;
2521
2522 if (str == NULL)
2523 return FAIL;
2524
2525 savebuf = curbuf;
2526
2527 PyErr_Clear();
2528 curbuf = buf;
2529
2530 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2531 PyErr_SetVim(_("cannot save undo information"));
2532 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2533 PyErr_SetVim(_("cannot insert line"));
2534 else
2535 appended_lines_mark((linenr_T)n, 1L);
2536
2537 vim_free(str);
2538 curbuf = savebuf;
2539 update_screen(VALID);
2540
2541 if (PyErr_Occurred() || VimErrorCheck())
2542 return FAIL;
2543
2544 if (len_change)
2545 *len_change = 1;
2546
2547 return OK;
2548 }
2549 else if (PyList_Check(lines))
2550 {
2551 PyInt i;
2552 PyInt size = PyList_Size(lines);
2553 char **array;
2554 buf_T *savebuf;
2555
2556 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2557 if (array == NULL)
2558 {
2559 PyErr_NoMemory();
2560 return FAIL;
2561 }
2562
2563 for (i = 0; i < size; ++i)
2564 {
2565 PyObject *line = PyList_GetItem(lines, i);
2566 array[i] = StringToLine(line);
2567
2568 if (array[i] == NULL)
2569 {
2570 while (i)
2571 vim_free(array[--i]);
2572 vim_free(array);
2573 return FAIL;
2574 }
2575 }
2576
2577 savebuf = curbuf;
2578
2579 PyErr_Clear();
2580 curbuf = buf;
2581
2582 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2583 PyErr_SetVim(_("cannot save undo information"));
2584 else
2585 {
2586 for (i = 0; i < size; ++i)
2587 {
2588 if (ml_append((linenr_T)(n + i),
2589 (char_u *)array[i], 0, FALSE) == FAIL)
2590 {
2591 PyErr_SetVim(_("cannot insert line"));
2592
2593 /* Free the rest of the lines */
2594 while (i < size)
2595 vim_free(array[i++]);
2596
2597 break;
2598 }
2599 vim_free(array[i]);
2600 }
2601 if (i > 0)
2602 appended_lines_mark((linenr_T)n, (long)i);
2603 }
2604
2605 /* Free the array of lines. All of its contents have now
2606 * been freed.
2607 */
2608 vim_free(array);
2609
2610 curbuf = savebuf;
2611 update_screen(VALID);
2612
2613 if (PyErr_Occurred() || VimErrorCheck())
2614 return FAIL;
2615
2616 if (len_change)
2617 *len_change = size;
2618
2619 return OK;
2620 }
2621 else
2622 {
2623 PyErr_BadArgument();
2624 return FAIL;
2625 }
2626}
2627
2628/*
2629 * Common routines for buffers and line ranges
2630 * -------------------------------------------
2631 */
2632
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002633typedef struct
2634{
2635 PyObject_HEAD
2636 buf_T *buf;
2637} BufferObject;
2638
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002639 static int
2640CheckBuffer(BufferObject *this)
2641{
2642 if (this->buf == INVALID_BUFFER_VALUE)
2643 {
2644 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2645 return -1;
2646 }
2647
2648 return 0;
2649}
2650
2651 static PyObject *
2652RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2653{
2654 if (CheckBuffer(self))
2655 return NULL;
2656
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002657 if (end == -1)
2658 end = self->buf->b_ml.ml_line_count;
2659
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002660 if (n < 0)
2661 n += end - start + 1;
2662
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002663 if (n < 0 || n > end - start)
2664 {
2665 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2666 return NULL;
2667 }
2668
2669 return GetBufferLine(self->buf, n+start);
2670}
2671
2672 static PyObject *
2673RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2674{
2675 PyInt size;
2676
2677 if (CheckBuffer(self))
2678 return NULL;
2679
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002680 if (end == -1)
2681 end = self->buf->b_ml.ml_line_count;
2682
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002683 size = end - start + 1;
2684
2685 if (lo < 0)
2686 lo = 0;
2687 else if (lo > size)
2688 lo = size;
2689 if (hi < 0)
2690 hi = 0;
2691 if (hi < lo)
2692 hi = lo;
2693 else if (hi > size)
2694 hi = size;
2695
2696 return GetBufferLineList(self->buf, lo+start, hi+start);
2697}
2698
2699 static PyInt
2700RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2701{
2702 PyInt len_change;
2703
2704 if (CheckBuffer(self))
2705 return -1;
2706
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002707 if (end == -1)
2708 end = self->buf->b_ml.ml_line_count;
2709
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002710 if (n < 0)
2711 n += end - start + 1;
2712
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002713 if (n < 0 || n > end - start)
2714 {
2715 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2716 return -1;
2717 }
2718
2719 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2720 return -1;
2721
2722 if (new_end)
2723 *new_end = end + len_change;
2724
2725 return 0;
2726}
2727
Bram Moolenaar19e60942011-06-19 00:27:51 +02002728 static PyInt
2729RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2730{
2731 PyInt size;
2732 PyInt len_change;
2733
2734 /* Self must be a valid buffer */
2735 if (CheckBuffer(self))
2736 return -1;
2737
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002738 if (end == -1)
2739 end = self->buf->b_ml.ml_line_count;
2740
Bram Moolenaar19e60942011-06-19 00:27:51 +02002741 /* Sort out the slice range */
2742 size = end - start + 1;
2743
2744 if (lo < 0)
2745 lo = 0;
2746 else if (lo > size)
2747 lo = size;
2748 if (hi < 0)
2749 hi = 0;
2750 if (hi < lo)
2751 hi = lo;
2752 else if (hi > size)
2753 hi = size;
2754
2755 if (SetBufferLineList(self->buf, lo + start, hi + start,
2756 val, &len_change) == FAIL)
2757 return -1;
2758
2759 if (new_end)
2760 *new_end = end + len_change;
2761
2762 return 0;
2763}
2764
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002765
2766 static PyObject *
2767RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2768{
2769 PyObject *lines;
2770 PyInt len_change;
2771 PyInt max;
2772 PyInt n;
2773
2774 if (CheckBuffer(self))
2775 return NULL;
2776
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002777 if (end == -1)
2778 end = self->buf->b_ml.ml_line_count;
2779
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002780 max = n = end - start + 1;
2781
2782 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2783 return NULL;
2784
2785 if (n < 0 || n > max)
2786 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02002787 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002788 return NULL;
2789 }
2790
2791 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2792 return NULL;
2793
2794 if (new_end)
2795 *new_end = end + len_change;
2796
2797 Py_INCREF(Py_None);
2798 return Py_None;
2799}
2800
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002801/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002802 */
2803
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002804static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002805static PySequenceMethods RangeAsSeq;
2806static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002807
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002808typedef struct
2809{
2810 PyObject_HEAD
2811 BufferObject *buf;
2812 PyInt start;
2813 PyInt end;
2814} RangeObject;
2815
2816 static PyObject *
2817RangeNew(buf_T *buf, PyInt start, PyInt end)
2818{
2819 BufferObject *bufr;
2820 RangeObject *self;
2821 self = PyObject_NEW(RangeObject, &RangeType);
2822 if (self == NULL)
2823 return NULL;
2824
2825 bufr = (BufferObject *)BufferNew(buf);
2826 if (bufr == NULL)
2827 {
2828 Py_DECREF(self);
2829 return NULL;
2830 }
2831 Py_INCREF(bufr);
2832
2833 self->buf = bufr;
2834 self->start = start;
2835 self->end = end;
2836
2837 return (PyObject *)(self);
2838}
2839
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002840 static void
2841RangeDestructor(PyObject *self)
2842{
2843 Py_DECREF(((RangeObject *)(self))->buf);
2844 DESTRUCTOR_FINISH(self);
2845}
2846
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002847 static PyInt
2848RangeLength(PyObject *self)
2849{
2850 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2851 if (CheckBuffer(((RangeObject *)(self))->buf))
2852 return -1; /* ??? */
2853
2854 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2855}
2856
2857 static PyObject *
2858RangeItem(PyObject *self, PyInt n)
2859{
2860 return RBItem(((RangeObject *)(self))->buf, n,
2861 ((RangeObject *)(self))->start,
2862 ((RangeObject *)(self))->end);
2863}
2864
2865 static PyObject *
2866RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2867{
2868 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2869 ((RangeObject *)(self))->start,
2870 ((RangeObject *)(self))->end);
2871}
2872
2873 static PyObject *
2874RangeAppend(PyObject *self, PyObject *args)
2875{
2876 return RBAppend(((RangeObject *)(self))->buf, args,
2877 ((RangeObject *)(self))->start,
2878 ((RangeObject *)(self))->end,
2879 &((RangeObject *)(self))->end);
2880}
2881
2882 static PyObject *
2883RangeRepr(PyObject *self)
2884{
2885 static char repr[100];
2886 RangeObject *this = (RangeObject *)(self);
2887
2888 if (this->buf->buf == INVALID_BUFFER_VALUE)
2889 {
2890 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2891 (self));
2892 return PyString_FromString(repr);
2893 }
2894 else
2895 {
2896 char *name = (char *)this->buf->buf->b_fname;
2897 int len;
2898
2899 if (name == NULL)
2900 name = "";
2901 len = (int)strlen(name);
2902
2903 if (len > 45)
2904 name = name + (45 - len);
2905
2906 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2907 len > 45 ? "..." : "", name,
2908 this->start, this->end);
2909
2910 return PyString_FromString(repr);
2911 }
2912}
2913
2914static struct PyMethodDef RangeMethods[] = {
2915 /* name, function, calling, documentation */
2916 {"append", RangeAppend, 1, "Append data to the Vim range" },
2917 { NULL, NULL, 0, NULL }
2918};
2919
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002920static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002921static PySequenceMethods BufferAsSeq;
2922static PyMappingMethods BufferAsMapping;
2923
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002924 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002925BufferNew(buf_T *buf)
2926{
2927 /* We need to handle deletion of buffers underneath us.
2928 * If we add a "b_python*_ref" field to the buf_T structure,
2929 * then we can get at it in buf_freeall() in vim. We then
2930 * need to create only ONE Python object per buffer - if
2931 * we try to create a second, just INCREF the existing one
2932 * and return it. The (single) Python object referring to
2933 * the buffer is stored in "b_python*_ref".
2934 * Question: what to do on a buf_freeall(). We'll probably
2935 * have to either delete the Python object (DECREF it to
2936 * zero - a bad idea, as it leaves dangling refs!) or
2937 * set the buf_T * value to an invalid value (-1?), which
2938 * means we need checks in all access functions... Bah.
2939 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002940 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02002941 * b_python_ref and b_python3_ref fields respectively.
2942 */
2943
2944 BufferObject *self;
2945
2946 if (BUF_PYTHON_REF(buf) != NULL)
2947 {
2948 self = BUF_PYTHON_REF(buf);
2949 Py_INCREF(self);
2950 }
2951 else
2952 {
2953 self = PyObject_NEW(BufferObject, &BufferType);
2954 if (self == NULL)
2955 return NULL;
2956 self->buf = buf;
2957 BUF_PYTHON_REF(buf) = self;
2958 }
2959
2960 return (PyObject *)(self);
2961}
2962
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002963 static void
2964BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002965{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002966 BufferObject *this = (BufferObject *)(self);
2967
2968 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2969 BUF_PYTHON_REF(this->buf) = NULL;
2970
2971 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002972}
2973
Bram Moolenaar971db462013-05-12 18:44:48 +02002974 static PyInt
2975BufferLength(PyObject *self)
2976{
2977 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2978 if (CheckBuffer((BufferObject *)(self)))
2979 return -1; /* ??? */
2980
2981 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2982}
2983
2984 static PyObject *
2985BufferItem(PyObject *self, PyInt n)
2986{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002987 return RBItem((BufferObject *)(self), n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002988}
2989
2990 static PyObject *
2991BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2992{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002993 return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002994}
2995
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002996 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002997BufferAttr(BufferObject *this, char *name)
2998{
2999 if (strcmp(name, "name") == 0)
3000 return Py_BuildValue("s", this->buf->b_ffname);
3001 else if (strcmp(name, "number") == 0)
3002 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
3003 else if (strcmp(name, "vars") == 0)
3004 return DictionaryNew(this->buf->b_vars);
3005 else if (strcmp(name, "options") == 0)
3006 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
3007 (PyObject *) this);
3008 else if (strcmp(name,"__members__") == 0)
3009 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
3010 else
3011 return NULL;
3012}
3013
3014 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003015BufferAppend(PyObject *self, PyObject *args)
3016{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02003017 return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003018}
3019
3020 static PyObject *
3021BufferMark(PyObject *self, PyObject *args)
3022{
3023 pos_T *posp;
3024 char *pmark;
3025 char mark;
3026 buf_T *curbuf_save;
3027
3028 if (CheckBuffer((BufferObject *)(self)))
3029 return NULL;
3030
3031 if (!PyArg_ParseTuple(args, "s", &pmark))
3032 return NULL;
3033 mark = *pmark;
3034
3035 curbuf_save = curbuf;
3036 curbuf = ((BufferObject *)(self))->buf;
3037 posp = getmark(mark, FALSE);
3038 curbuf = curbuf_save;
3039
3040 if (posp == NULL)
3041 {
3042 PyErr_SetVim(_("invalid mark name"));
3043 return NULL;
3044 }
3045
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003046 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003047 if (VimErrorCheck())
3048 return NULL;
3049
3050 if (posp->lnum <= 0)
3051 {
3052 /* Or raise an error? */
3053 Py_INCREF(Py_None);
3054 return Py_None;
3055 }
3056
3057 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
3058}
3059
3060 static PyObject *
3061BufferRange(PyObject *self, PyObject *args)
3062{
3063 PyInt start;
3064 PyInt end;
3065
3066 if (CheckBuffer((BufferObject *)(self)))
3067 return NULL;
3068
3069 if (!PyArg_ParseTuple(args, "nn", &start, &end))
3070 return NULL;
3071
3072 return RangeNew(((BufferObject *)(self))->buf, start, end);
3073}
3074
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003075 static PyObject *
3076BufferRepr(PyObject *self)
3077{
3078 static char repr[100];
3079 BufferObject *this = (BufferObject *)(self);
3080
3081 if (this->buf == INVALID_BUFFER_VALUE)
3082 {
3083 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
3084 return PyString_FromString(repr);
3085 }
3086 else
3087 {
3088 char *name = (char *)this->buf->b_fname;
3089 PyInt len;
3090
3091 if (name == NULL)
3092 name = "";
3093 len = strlen(name);
3094
3095 if (len > 35)
3096 name = name + (35 - len);
3097
3098 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
3099
3100 return PyString_FromString(repr);
3101 }
3102}
3103
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003104static struct PyMethodDef BufferMethods[] = {
3105 /* name, function, calling, documentation */
3106 {"append", BufferAppend, 1, "Append data to Vim buffer" },
3107 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
3108 {"range", BufferRange, 1, "Return a range object which represents the part of the given buffer between line numbers s and e" },
Bram Moolenaar7f85d292012-02-04 20:17:26 +01003109#if PY_VERSION_HEX >= 0x03000000
3110 {"__dir__", BufferDir, 4, "List its attributes" },
3111#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003112 { NULL, NULL, 0, NULL }
3113};
3114
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003115/*
3116 * Buffer list object - Implementation
3117 */
3118
3119static PyTypeObject BufMapType;
3120
3121typedef struct
3122{
3123 PyObject_HEAD
3124} BufMapObject;
3125
3126 static PyInt
3127BufMapLength(PyObject *self UNUSED)
3128{
3129 buf_T *b = firstbuf;
3130 PyInt n = 0;
3131
3132 while (b)
3133 {
3134 ++n;
3135 b = b->b_next;
3136 }
3137
3138 return n;
3139}
3140
3141 static PyObject *
3142BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
3143{
3144 buf_T *b;
3145 int bnr;
3146
3147#if PY_MAJOR_VERSION < 3
3148 if (PyInt_Check(keyObject))
3149 bnr = PyInt_AsLong(keyObject);
3150 else
3151#endif
3152 if (PyLong_Check(keyObject))
3153 bnr = PyLong_AsLong(keyObject);
3154 else
3155 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003156 PyErr_SetString(PyExc_TypeError, _("key must be integer"));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003157 return NULL;
3158 }
3159
3160 b = buflist_findnr(bnr);
3161
3162 if (b)
3163 return BufferNew(b);
3164 else
3165 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003166 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003167 return NULL;
3168 }
3169}
3170
3171 static void
3172BufMapIterDestruct(PyObject *buffer)
3173{
3174 /* Iteration was stopped before all buffers were processed */
3175 if (buffer)
3176 {
3177 Py_DECREF(buffer);
3178 }
3179}
3180
3181 static PyObject *
3182BufMapIterNext(PyObject **buffer)
3183{
3184 PyObject *next;
3185 PyObject *r;
3186
3187 if (!*buffer)
3188 return NULL;
3189
3190 r = *buffer;
3191
3192 if (CheckBuffer((BufferObject *)(r)))
3193 {
3194 *buffer = NULL;
3195 return NULL;
3196 }
3197
3198 if (!((BufferObject *)(r))->buf->b_next)
3199 next = NULL;
3200 else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
3201 return NULL;
3202 *buffer = next;
3203 /* Do not increment reference: we no longer hold it (decref), but whoever on
3204 * other side will hold (incref). Decref+incref = nothing.
3205 */
3206 return r;
3207}
3208
3209 static PyObject *
3210BufMapIter(PyObject *self UNUSED)
3211{
3212 PyObject *buffer;
3213
3214 buffer = BufferNew(firstbuf);
3215 return IterNew(buffer,
3216 (destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext);
3217}
3218
3219static PyMappingMethods BufMapAsMapping = {
3220 (lenfunc) BufMapLength,
3221 (binaryfunc) BufMapItem,
3222 (objobjargproc) 0,
3223};
3224
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003225/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003226 */
3227
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003228 static PyObject *
3229CurrentGetattr(PyObject *self UNUSED, char *name)
3230{
3231 if (strcmp(name, "buffer") == 0)
3232 return (PyObject *)BufferNew(curbuf);
3233 else if (strcmp(name, "window") == 0)
3234 return (PyObject *)WindowNew(curwin);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003235 else if (strcmp(name, "tabpage") == 0)
3236 return (PyObject *)TabPageNew(curtab);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003237 else if (strcmp(name, "line") == 0)
3238 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3239 else if (strcmp(name, "range") == 0)
3240 return RangeNew(curbuf, RangeStart, RangeEnd);
3241 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003242 return Py_BuildValue("[sssss]", "buffer", "window", "line", "range",
3243 "tabpage");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003244 else
3245 {
3246 PyErr_SetString(PyExc_AttributeError, name);
3247 return NULL;
3248 }
3249}
3250
3251 static int
3252CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3253{
3254 if (strcmp(name, "line") == 0)
3255 {
3256 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3257 return -1;
3258
3259 return 0;
3260 }
Bram Moolenaare7614592013-05-15 15:51:08 +02003261 else if (strcmp(name, "buffer") == 0)
3262 {
3263 int count;
3264
3265 if (value->ob_type != &BufferType)
3266 {
3267 PyErr_SetString(PyExc_TypeError, _("expected vim.buffer object"));
3268 return -1;
3269 }
3270
3271 if (CheckBuffer((BufferObject *)(value)))
3272 return -1;
3273 count = ((BufferObject *)(value))->buf->b_fnum;
3274
3275 if (do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, count, 0) == FAIL)
3276 {
3277 PyErr_SetVim(_("failed to switch to given buffer"));
3278 return -1;
3279 }
3280
3281 return 0;
3282 }
3283 else if (strcmp(name, "window") == 0)
3284 {
3285 int count;
3286
3287 if (value->ob_type != &WindowType)
3288 {
3289 PyErr_SetString(PyExc_TypeError, _("expected vim.window object"));
3290 return -1;
3291 }
3292
3293 if (CheckWindow((WindowObject *)(value)))
3294 return -1;
3295 count = get_win_number(((WindowObject *)(value))->win, firstwin);
3296
3297 if (!count)
3298 {
3299 PyErr_SetString(PyExc_ValueError,
3300 _("failed to find window in the current tab page"));
3301 return -1;
3302 }
3303
3304 win_goto(((WindowObject *)(value))->win);
3305 if (((WindowObject *)(value))->win != curwin)
3306 {
3307 PyErr_SetString(PyExc_RuntimeError,
3308 _("did not switch to the specified window"));
3309 return -1;
3310 }
3311
3312 return 0;
3313 }
3314 else if (strcmp(name, "tabpage") == 0)
3315 {
3316 if (value->ob_type != &TabPageType)
3317 {
3318 PyErr_SetString(PyExc_TypeError, _("expected vim.tabpage object"));
3319 return -1;
3320 }
3321
3322 if (CheckTabPage((TabPageObject *)(value)))
3323 return -1;
3324
3325 goto_tabpage_tp(((TabPageObject *)(value))->tab, TRUE, TRUE);
3326 if (((TabPageObject *)(value))->tab != curtab)
3327 {
3328 PyErr_SetString(PyExc_RuntimeError,
3329 _("did not switch to the specified tab page"));
3330 return -1;
3331 }
3332
3333 return 0;
3334 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003335 else
3336 {
3337 PyErr_SetString(PyExc_AttributeError, name);
3338 return -1;
3339 }
3340}
3341
Bram Moolenaardb913952012-06-29 12:54:53 +02003342 static void
3343set_ref_in_py(const int copyID)
3344{
3345 pylinkedlist_T *cur;
3346 dict_T *dd;
3347 list_T *ll;
3348
3349 if (lastdict != NULL)
3350 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3351 {
3352 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3353 if (dd->dv_copyID != copyID)
3354 {
3355 dd->dv_copyID = copyID;
3356 set_ref_in_ht(&dd->dv_hashtab, copyID);
3357 }
3358 }
3359
3360 if (lastlist != NULL)
3361 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3362 {
3363 ll = ((ListObject *) (cur->pll_obj))->list;
3364 if (ll->lv_copyID != copyID)
3365 {
3366 ll->lv_copyID = copyID;
3367 set_ref_in_list(ll, copyID);
3368 }
3369 }
3370}
3371
3372 static int
3373set_string_copy(char_u *str, typval_T *tv)
3374{
3375 tv->vval.v_string = vim_strsave(str);
3376 if (tv->vval.v_string == NULL)
3377 {
3378 PyErr_NoMemory();
3379 return -1;
3380 }
3381 return 0;
3382}
3383
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003384 static int
3385pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3386{
3387 dict_T *d;
3388 char_u *key;
3389 dictitem_T *di;
3390 PyObject *keyObject;
3391 PyObject *valObject;
3392 Py_ssize_t iter = 0;
3393
3394 d = dict_alloc();
3395 if (d == NULL)
3396 {
3397 PyErr_NoMemory();
3398 return -1;
3399 }
3400
3401 tv->v_type = VAR_DICT;
3402 tv->vval.v_dict = d;
3403
3404 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
3405 {
3406 DICTKEY_DECL
3407
3408 if (keyObject == NULL)
3409 return -1;
3410 if (valObject == NULL)
3411 return -1;
3412
3413 DICTKEY_GET_NOTEMPTY(-1)
3414
3415 di = dictitem_alloc(key);
3416
3417 DICTKEY_UNREF
3418
3419 if (di == NULL)
3420 {
3421 PyErr_NoMemory();
3422 return -1;
3423 }
3424 di->di_tv.v_lock = 0;
3425
3426 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3427 {
3428 vim_free(di);
3429 return -1;
3430 }
3431 if (dict_add(d, di) == FAIL)
3432 {
3433 vim_free(di);
3434 PyErr_SetVim(_("failed to add key to dictionary"));
3435 return -1;
3436 }
3437 }
3438 return 0;
3439}
3440
3441 static int
3442pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3443{
3444 dict_T *d;
3445 char_u *key;
3446 dictitem_T *di;
3447 PyObject *list;
3448 PyObject *litem;
3449 PyObject *keyObject;
3450 PyObject *valObject;
3451 Py_ssize_t lsize;
3452
3453 d = dict_alloc();
3454 if (d == NULL)
3455 {
3456 PyErr_NoMemory();
3457 return -1;
3458 }
3459
3460 tv->v_type = VAR_DICT;
3461 tv->vval.v_dict = d;
3462
3463 list = PyMapping_Items(obj);
3464 if (list == NULL)
3465 return -1;
3466 lsize = PyList_Size(list);
3467 while (lsize--)
3468 {
3469 DICTKEY_DECL
3470
3471 litem = PyList_GetItem(list, lsize);
3472 if (litem == NULL)
3473 {
3474 Py_DECREF(list);
3475 return -1;
3476 }
3477
3478 keyObject = PyTuple_GetItem(litem, 0);
3479 if (keyObject == NULL)
3480 {
3481 Py_DECREF(list);
3482 Py_DECREF(litem);
3483 return -1;
3484 }
3485
3486 DICTKEY_GET_NOTEMPTY(-1)
3487
3488 valObject = PyTuple_GetItem(litem, 1);
3489 if (valObject == NULL)
3490 {
3491 Py_DECREF(list);
3492 Py_DECREF(litem);
3493 return -1;
3494 }
3495
3496 di = dictitem_alloc(key);
3497
3498 DICTKEY_UNREF
3499
3500 if (di == NULL)
3501 {
3502 Py_DECREF(list);
3503 Py_DECREF(litem);
3504 PyErr_NoMemory();
3505 return -1;
3506 }
3507 di->di_tv.v_lock = 0;
3508
3509 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3510 {
3511 vim_free(di);
3512 Py_DECREF(list);
3513 Py_DECREF(litem);
3514 return -1;
3515 }
3516 if (dict_add(d, di) == FAIL)
3517 {
3518 vim_free(di);
3519 Py_DECREF(list);
3520 Py_DECREF(litem);
3521 PyErr_SetVim(_("failed to add key to dictionary"));
3522 return -1;
3523 }
3524 Py_DECREF(litem);
3525 }
3526 Py_DECREF(list);
3527 return 0;
3528}
3529
3530 static int
3531pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3532{
3533 list_T *l;
3534
3535 l = list_alloc();
3536 if (l == NULL)
3537 {
3538 PyErr_NoMemory();
3539 return -1;
3540 }
3541
3542 tv->v_type = VAR_LIST;
3543 tv->vval.v_list = l;
3544
3545 if (list_py_concat(l, obj, lookupDict) == -1)
3546 return -1;
3547
3548 return 0;
3549}
3550
3551 static int
3552pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3553{
3554 PyObject *iterator = PyObject_GetIter(obj);
3555 PyObject *item;
3556 list_T *l;
3557 listitem_T *li;
3558
3559 l = list_alloc();
3560
3561 if (l == NULL)
3562 {
3563 PyErr_NoMemory();
3564 return -1;
3565 }
3566
3567 tv->vval.v_list = l;
3568 tv->v_type = VAR_LIST;
3569
3570
3571 if (iterator == NULL)
3572 return -1;
3573
3574 while ((item = PyIter_Next(obj)))
3575 {
3576 li = listitem_alloc();
3577 if (li == NULL)
3578 {
3579 PyErr_NoMemory();
3580 return -1;
3581 }
3582 li->li_tv.v_lock = 0;
3583
3584 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3585 return -1;
3586
3587 list_append(l, li);
3588
3589 Py_DECREF(item);
3590 }
3591
3592 Py_DECREF(iterator);
3593 return 0;
3594}
3595
Bram Moolenaardb913952012-06-29 12:54:53 +02003596typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3597
3598 static int
3599convert_dl(PyObject *obj, typval_T *tv,
3600 pytotvfunc py_to_tv, PyObject *lookupDict)
3601{
3602 PyObject *capsule;
3603 char hexBuf[sizeof(void *) * 2 + 3];
3604
3605 sprintf(hexBuf, "%p", obj);
3606
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003607# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003608 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003609# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003610 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003611# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003612 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003613 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003614# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003615 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003616# else
3617 capsule = PyCObject_FromVoidPtr(tv, NULL);
3618# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003619 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3620 Py_DECREF(capsule);
3621 if (py_to_tv(obj, tv, lookupDict) == -1)
3622 {
3623 tv->v_type = VAR_UNKNOWN;
3624 return -1;
3625 }
3626 /* As we are not using copy_tv which increments reference count we must
3627 * do it ourself. */
3628 switch(tv->v_type)
3629 {
3630 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3631 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3632 }
3633 }
3634 else
3635 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003636 typval_T *v;
3637
3638# ifdef PY_USE_CAPSULE
3639 v = PyCapsule_GetPointer(capsule, NULL);
3640# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003641 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003642# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003643 copy_tv(v, tv);
3644 }
3645 return 0;
3646}
3647
3648 static int
3649ConvertFromPyObject(PyObject *obj, typval_T *tv)
3650{
3651 PyObject *lookup_dict;
3652 int r;
3653
3654 lookup_dict = PyDict_New();
3655 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3656 Py_DECREF(lookup_dict);
3657 return r;
3658}
3659
3660 static int
3661_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3662{
3663 if (obj->ob_type == &DictionaryType)
3664 {
3665 tv->v_type = VAR_DICT;
3666 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3667 ++tv->vval.v_dict->dv_refcount;
3668 }
3669 else if (obj->ob_type == &ListType)
3670 {
3671 tv->v_type = VAR_LIST;
3672 tv->vval.v_list = (((ListObject *)(obj))->list);
3673 ++tv->vval.v_list->lv_refcount;
3674 }
3675 else if (obj->ob_type == &FunctionType)
3676 {
3677 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3678 return -1;
3679
3680 tv->v_type = VAR_FUNC;
3681 func_ref(tv->vval.v_string);
3682 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003683 else if (PyBytes_Check(obj))
3684 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003685 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003686
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003687 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3688 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003689 if (result == NULL)
3690 return -1;
3691
3692 if (set_string_copy(result, tv) == -1)
3693 return -1;
3694
3695 tv->v_type = VAR_STRING;
3696 }
3697 else if (PyUnicode_Check(obj))
3698 {
3699 PyObject *bytes;
3700 char_u *result;
3701
Bram Moolenaardb913952012-06-29 12:54:53 +02003702 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3703 if (bytes == NULL)
3704 return -1;
3705
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003706 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3707 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003708 if (result == NULL)
3709 return -1;
3710
3711 if (set_string_copy(result, tv) == -1)
3712 {
3713 Py_XDECREF(bytes);
3714 return -1;
3715 }
3716 Py_XDECREF(bytes);
3717
3718 tv->v_type = VAR_STRING;
3719 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003720#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003721 else if (PyInt_Check(obj))
3722 {
3723 tv->v_type = VAR_NUMBER;
3724 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3725 }
3726#endif
3727 else if (PyLong_Check(obj))
3728 {
3729 tv->v_type = VAR_NUMBER;
3730 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3731 }
3732 else if (PyDict_Check(obj))
3733 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3734#ifdef FEAT_FLOAT
3735 else if (PyFloat_Check(obj))
3736 {
3737 tv->v_type = VAR_FLOAT;
3738 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3739 }
3740#endif
3741 else if (PyIter_Check(obj))
3742 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3743 else if (PySequence_Check(obj))
3744 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3745 else if (PyMapping_Check(obj))
3746 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3747 else
3748 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003749 PyErr_SetString(PyExc_TypeError,
3750 _("unable to convert to vim structure"));
Bram Moolenaardb913952012-06-29 12:54:53 +02003751 return -1;
3752 }
3753 return 0;
3754}
3755
3756 static PyObject *
3757ConvertToPyObject(typval_T *tv)
3758{
3759 if (tv == NULL)
3760 {
3761 PyErr_SetVim(_("NULL reference passed"));
3762 return NULL;
3763 }
3764 switch (tv->v_type)
3765 {
3766 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003767 return PyBytes_FromString(tv->vval.v_string == NULL
3768 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003769 case VAR_NUMBER:
3770 return PyLong_FromLong((long) tv->vval.v_number);
3771#ifdef FEAT_FLOAT
3772 case VAR_FLOAT:
3773 return PyFloat_FromDouble((double) tv->vval.v_float);
3774#endif
3775 case VAR_LIST:
3776 return ListNew(tv->vval.v_list);
3777 case VAR_DICT:
3778 return DictionaryNew(tv->vval.v_dict);
3779 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003780 return FunctionNew(tv->vval.v_string == NULL
3781 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003782 case VAR_UNKNOWN:
3783 Py_INCREF(Py_None);
3784 return Py_None;
3785 default:
3786 PyErr_SetVim(_("internal error: invalid value type"));
3787 return NULL;
3788 }
3789}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003790
3791typedef struct
3792{
3793 PyObject_HEAD
3794} CurrentObject;
3795static PyTypeObject CurrentType;
3796
3797 static void
3798init_structs(void)
3799{
3800 vim_memset(&OutputType, 0, sizeof(OutputType));
3801 OutputType.tp_name = "vim.message";
3802 OutputType.tp_basicsize = sizeof(OutputObject);
3803 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3804 OutputType.tp_doc = "vim message object";
3805 OutputType.tp_methods = OutputMethods;
3806#if PY_MAJOR_VERSION >= 3
3807 OutputType.tp_getattro = OutputGetattro;
3808 OutputType.tp_setattro = OutputSetattro;
3809 OutputType.tp_alloc = call_PyType_GenericAlloc;
3810 OutputType.tp_new = call_PyType_GenericNew;
3811 OutputType.tp_free = call_PyObject_Free;
3812#else
3813 OutputType.tp_getattr = OutputGetattr;
3814 OutputType.tp_setattr = OutputSetattr;
3815#endif
3816
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003817 vim_memset(&IterType, 0, sizeof(IterType));
3818 IterType.tp_name = "vim.iter";
3819 IterType.tp_basicsize = sizeof(IterObject);
3820 IterType.tp_flags = Py_TPFLAGS_DEFAULT;
3821 IterType.tp_doc = "generic iterator object";
3822 IterType.tp_iter = IterIter;
3823 IterType.tp_iternext = IterNext;
Bram Moolenaar2cd73622013-05-15 19:07:47 +02003824 IterType.tp_dealloc = IterDestructor;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003825
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003826 vim_memset(&BufferType, 0, sizeof(BufferType));
3827 BufferType.tp_name = "vim.buffer";
3828 BufferType.tp_basicsize = sizeof(BufferType);
3829 BufferType.tp_dealloc = BufferDestructor;
3830 BufferType.tp_repr = BufferRepr;
3831 BufferType.tp_as_sequence = &BufferAsSeq;
3832 BufferType.tp_as_mapping = &BufferAsMapping;
3833 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3834 BufferType.tp_doc = "vim buffer object";
3835 BufferType.tp_methods = BufferMethods;
3836#if PY_MAJOR_VERSION >= 3
3837 BufferType.tp_getattro = BufferGetattro;
3838 BufferType.tp_alloc = call_PyType_GenericAlloc;
3839 BufferType.tp_new = call_PyType_GenericNew;
3840 BufferType.tp_free = call_PyObject_Free;
3841#else
3842 BufferType.tp_getattr = BufferGetattr;
3843#endif
3844
3845 vim_memset(&WindowType, 0, sizeof(WindowType));
3846 WindowType.tp_name = "vim.window";
3847 WindowType.tp_basicsize = sizeof(WindowObject);
3848 WindowType.tp_dealloc = WindowDestructor;
3849 WindowType.tp_repr = WindowRepr;
3850 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3851 WindowType.tp_doc = "vim Window object";
3852 WindowType.tp_methods = WindowMethods;
3853#if PY_MAJOR_VERSION >= 3
3854 WindowType.tp_getattro = WindowGetattro;
3855 WindowType.tp_setattro = WindowSetattro;
3856 WindowType.tp_alloc = call_PyType_GenericAlloc;
3857 WindowType.tp_new = call_PyType_GenericNew;
3858 WindowType.tp_free = call_PyObject_Free;
3859#else
3860 WindowType.tp_getattr = WindowGetattr;
3861 WindowType.tp_setattr = WindowSetattr;
3862#endif
3863
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003864 vim_memset(&TabPageType, 0, sizeof(TabPageType));
3865 TabPageType.tp_name = "vim.tabpage";
3866 TabPageType.tp_basicsize = sizeof(TabPageObject);
3867 TabPageType.tp_dealloc = TabPageDestructor;
3868 TabPageType.tp_repr = TabPageRepr;
3869 TabPageType.tp_flags = Py_TPFLAGS_DEFAULT;
3870 TabPageType.tp_doc = "vim tab page object";
3871 TabPageType.tp_methods = TabPageMethods;
3872#if PY_MAJOR_VERSION >= 3
3873 TabPageType.tp_getattro = TabPageGetattro;
3874 TabPageType.tp_alloc = call_PyType_GenericAlloc;
3875 TabPageType.tp_new = call_PyType_GenericNew;
3876 TabPageType.tp_free = call_PyObject_Free;
3877#else
3878 TabPageType.tp_getattr = TabPageGetattr;
3879#endif
3880
Bram Moolenaardfa38d42013-05-15 13:38:47 +02003881 vim_memset(&BufMapType, 0, sizeof(BufMapType));
3882 BufMapType.tp_name = "vim.bufferlist";
3883 BufMapType.tp_basicsize = sizeof(BufMapObject);
3884 BufMapType.tp_as_mapping = &BufMapAsMapping;
3885 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003886 BufMapType.tp_iter = BufMapIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003887 BufferType.tp_doc = "vim buffer list";
3888
3889 vim_memset(&WinListType, 0, sizeof(WinListType));
3890 WinListType.tp_name = "vim.windowlist";
3891 WinListType.tp_basicsize = sizeof(WinListType);
3892 WinListType.tp_as_sequence = &WinListAsSeq;
3893 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3894 WinListType.tp_doc = "vim window list";
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003895 WinListType.tp_dealloc = WinListDestructor;
3896
3897 vim_memset(&TabListType, 0, sizeof(TabListType));
3898 TabListType.tp_name = "vim.tabpagelist";
3899 TabListType.tp_basicsize = sizeof(TabListType);
3900 TabListType.tp_as_sequence = &TabListAsSeq;
3901 TabListType.tp_flags = Py_TPFLAGS_DEFAULT;
3902 TabListType.tp_doc = "vim tab page list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003903
3904 vim_memset(&RangeType, 0, sizeof(RangeType));
3905 RangeType.tp_name = "vim.range";
3906 RangeType.tp_basicsize = sizeof(RangeObject);
3907 RangeType.tp_dealloc = RangeDestructor;
3908 RangeType.tp_repr = RangeRepr;
3909 RangeType.tp_as_sequence = &RangeAsSeq;
3910 RangeType.tp_as_mapping = &RangeAsMapping;
3911 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3912 RangeType.tp_doc = "vim Range object";
3913 RangeType.tp_methods = RangeMethods;
3914#if PY_MAJOR_VERSION >= 3
3915 RangeType.tp_getattro = RangeGetattro;
3916 RangeType.tp_alloc = call_PyType_GenericAlloc;
3917 RangeType.tp_new = call_PyType_GenericNew;
3918 RangeType.tp_free = call_PyObject_Free;
3919#else
3920 RangeType.tp_getattr = RangeGetattr;
3921#endif
3922
3923 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3924 CurrentType.tp_name = "vim.currentdata";
3925 CurrentType.tp_basicsize = sizeof(CurrentObject);
3926 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3927 CurrentType.tp_doc = "vim current object";
3928#if PY_MAJOR_VERSION >= 3
3929 CurrentType.tp_getattro = CurrentGetattro;
3930 CurrentType.tp_setattro = CurrentSetattro;
3931#else
3932 CurrentType.tp_getattr = CurrentGetattr;
3933 CurrentType.tp_setattr = CurrentSetattr;
3934#endif
3935
3936 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3937 DictionaryType.tp_name = "vim.dictionary";
3938 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3939 DictionaryType.tp_dealloc = DictionaryDestructor;
3940 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3941 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3942 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3943 DictionaryType.tp_methods = DictionaryMethods;
3944#if PY_MAJOR_VERSION >= 3
3945 DictionaryType.tp_getattro = DictionaryGetattro;
3946 DictionaryType.tp_setattro = DictionarySetattro;
3947#else
3948 DictionaryType.tp_getattr = DictionaryGetattr;
3949 DictionaryType.tp_setattr = DictionarySetattr;
3950#endif
3951
3952 vim_memset(&ListType, 0, sizeof(ListType));
3953 ListType.tp_name = "vim.list";
3954 ListType.tp_dealloc = ListDestructor;
3955 ListType.tp_basicsize = sizeof(ListObject);
3956 ListType.tp_as_sequence = &ListAsSeq;
3957 ListType.tp_as_mapping = &ListAsMapping;
3958 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3959 ListType.tp_doc = "list pushing modifications to vim structure";
3960 ListType.tp_methods = ListMethods;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003961 ListType.tp_iter = ListIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003962#if PY_MAJOR_VERSION >= 3
3963 ListType.tp_getattro = ListGetattro;
3964 ListType.tp_setattro = ListSetattro;
3965#else
3966 ListType.tp_getattr = ListGetattr;
3967 ListType.tp_setattr = ListSetattr;
3968#endif
3969
3970 vim_memset(&FunctionType, 0, sizeof(FunctionType));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003971 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003972 FunctionType.tp_basicsize = sizeof(FunctionObject);
3973 FunctionType.tp_dealloc = FunctionDestructor;
3974 FunctionType.tp_call = FunctionCall;
3975 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3976 FunctionType.tp_doc = "object that calls vim function";
3977 FunctionType.tp_methods = FunctionMethods;
3978#if PY_MAJOR_VERSION >= 3
3979 FunctionType.tp_getattro = FunctionGetattro;
3980#else
3981 FunctionType.tp_getattr = FunctionGetattr;
3982#endif
3983
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003984 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3985 OptionsType.tp_name = "vim.options";
3986 OptionsType.tp_basicsize = sizeof(OptionsObject);
3987 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3988 OptionsType.tp_doc = "object for manipulating options";
3989 OptionsType.tp_as_mapping = &OptionsAsMapping;
3990 OptionsType.tp_dealloc = OptionsDestructor;
3991
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003992#if PY_MAJOR_VERSION >= 3
3993 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3994 vimmodule.m_name = "vim";
3995 vimmodule.m_doc = "Vim Python interface\n";
3996 vimmodule.m_size = -1;
3997 vimmodule.m_methods = VimMethods;
3998#endif
3999}