blob: d8b0f70d9db097c0613de23b8c0b060d5067a508 [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))
30
31static int ConvertFromPyObject(PyObject *, typval_T *);
32static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
33
34static PyInt RangeStart;
35static PyInt RangeEnd;
36
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020037/*
38 * obtain a lock on the Vim data structures
39 */
40 static void
41Python_Lock_Vim(void)
42{
43}
44
45/*
46 * release a lock on the Vim data structures
47 */
48 static void
49Python_Release_Vim(void)
50{
51}
52
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020053/* Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020054 */
55
Bram Moolenaar2eea1982010-09-21 16:49:37 +020056/* Function to write a line, points to either msg() or emsg(). */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020057typedef void (*writefn)(char_u *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020058
59static PyTypeObject OutputType;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020060
61typedef struct
62{
63 PyObject_HEAD
64 long softspace;
65 long error;
66} OutputObject;
67
Bram Moolenaar77045652012-09-21 13:46:06 +020068 static int
69OutputSetattr(PyObject *self, char *name, PyObject *val)
70{
71 if (val == NULL)
72 {
73 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
74 return -1;
75 }
76
77 if (strcmp(name, "softspace") == 0)
78 {
79 if (!PyInt_Check(val))
80 {
81 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
82 return -1;
83 }
84
85 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
86 return 0;
87 }
88
89 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
90 return -1;
91}
92
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020093/* Buffer IO, we write one whole line at a time. */
94static garray_T io_ga = {0, 0, 1, 80, NULL};
95static writefn old_fn = NULL;
96
97 static void
98PythonIO_Flush(void)
99{
100 if (old_fn != NULL && io_ga.ga_len > 0)
101 {
102 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
103 old_fn((char_u *)io_ga.ga_data);
104 }
105 io_ga.ga_len = 0;
106}
107
108 static void
109writer(writefn fn, char_u *str, PyInt n)
110{
111 char_u *ptr;
112
113 /* Flush when switching output function. */
114 if (fn != old_fn)
115 PythonIO_Flush();
116 old_fn = fn;
117
118 /* Write each NL separated line. Text after the last NL is kept for
119 * writing later. */
120 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
121 {
122 PyInt len = ptr - str;
123
124 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
125 break;
126
127 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
128 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
129 fn((char_u *)io_ga.ga_data);
130 str = ptr + 1;
131 n -= len + 1;
132 io_ga.ga_len = 0;
133 }
134
135 /* Put the remaining text into io_ga for later printing. */
136 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
137 {
138 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
139 io_ga.ga_len += (int)n;
140 }
141}
142
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200143 static PyObject *
144OutputWrite(PyObject *self, PyObject *args)
145{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200146 Py_ssize_t len = 0;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200147 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200148 int error = ((OutputObject *)(self))->error;
149
Bram Moolenaar27564802011-09-07 19:30:21 +0200150 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200151 return NULL;
152
153 Py_BEGIN_ALLOW_THREADS
154 Python_Lock_Vim();
155 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
156 Python_Release_Vim();
157 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200158 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200159
160 Py_INCREF(Py_None);
161 return Py_None;
162}
163
164 static PyObject *
165OutputWritelines(PyObject *self, PyObject *args)
166{
167 PyInt n;
168 PyInt i;
169 PyObject *list;
170 int error = ((OutputObject *)(self))->error;
171
172 if (!PyArg_ParseTuple(args, "O", &list))
173 return NULL;
174 Py_INCREF(list);
175
Bram Moolenaardb913952012-06-29 12:54:53 +0200176 if (!PyList_Check(list))
177 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200178 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
179 Py_DECREF(list);
180 return NULL;
181 }
182
183 n = PyList_Size(list);
184
185 for (i = 0; i < n; ++i)
186 {
187 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200188 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200189 PyInt len;
190
Bram Moolenaardb913952012-06-29 12:54:53 +0200191 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
192 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200193 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
194 Py_DECREF(list);
195 return NULL;
196 }
197
198 Py_BEGIN_ALLOW_THREADS
199 Python_Lock_Vim();
200 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
201 Python_Release_Vim();
202 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200203 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200204 }
205
206 Py_DECREF(list);
207 Py_INCREF(Py_None);
208 return Py_None;
209}
210
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100211 static PyObject *
212OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
213{
214 /* do nothing */
215 Py_INCREF(Py_None);
216 return Py_None;
217}
218
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200219/***************/
220
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200221static struct PyMethodDef OutputMethods[] = {
222 /* name, function, calling, documentation */
223 {"write", OutputWrite, 1, ""},
224 {"writelines", OutputWritelines, 1, ""},
225 {"flush", OutputFlush, 1, ""},
226 { NULL, NULL, 0, NULL}
227};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200228
229static OutputObject Output =
230{
231 PyObject_HEAD_INIT(&OutputType)
232 0,
233 0
234};
235
236static OutputObject Error =
237{
238 PyObject_HEAD_INIT(&OutputType)
239 0,
240 1
241};
242
243 static int
244PythonIO_Init_io(void)
245{
246 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
247 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
248
249 if (PyErr_Occurred())
250 {
251 EMSG(_("E264: Python: Error initialising I/O objects"));
252 return -1;
253 }
254
255 return 0;
256}
257
258
259static PyObject *VimError;
260
261/* Check to see whether a Vim error has been reported, or a keyboard
262 * interrupt has been detected.
263 */
264 static int
265VimErrorCheck(void)
266{
267 if (got_int)
268 {
269 PyErr_SetNone(PyExc_KeyboardInterrupt);
270 return 1;
271 }
272 else if (did_emsg && !PyErr_Occurred())
273 {
274 PyErr_SetNone(VimError);
275 return 1;
276 }
277
278 return 0;
279}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200280
281/* Vim module - Implementation
282 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200283
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200284 static PyObject *
285VimCommand(PyObject *self UNUSED, PyObject *args)
286{
287 char *cmd;
288 PyObject *result;
289
290 if (!PyArg_ParseTuple(args, "s", &cmd))
291 return NULL;
292
293 PyErr_Clear();
294
295 Py_BEGIN_ALLOW_THREADS
296 Python_Lock_Vim();
297
298 do_cmdline_cmd((char_u *)cmd);
299 update_screen(VALID);
300
301 Python_Release_Vim();
302 Py_END_ALLOW_THREADS
303
304 if (VimErrorCheck())
305 result = NULL;
306 else
307 result = Py_None;
308
309 Py_XINCREF(result);
310 return result;
311}
312
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200313/*
314 * Function to translate a typval_T into a PyObject; this will recursively
315 * translate lists/dictionaries into their Python equivalents.
316 *
317 * The depth parameter is to avoid infinite recursion, set it to 1 when
318 * you call VimToPython.
319 */
320 static PyObject *
321VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
322{
323 PyObject *result;
324 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200325 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200326
327 /* Avoid infinite recursion */
328 if (depth > 100)
329 {
330 Py_INCREF(Py_None);
331 result = Py_None;
332 return result;
333 }
334
335 /* Check if we run into a recursive loop. The item must be in lookupDict
336 * then and we can use it again. */
337 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
338 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
339 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200340 sprintf(ptrBuf, "%p",
341 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
342 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200343 result = PyDict_GetItemString(lookupDict, ptrBuf);
344 if (result != NULL)
345 {
346 Py_INCREF(result);
347 return result;
348 }
349 }
350
351 if (our_tv->v_type == VAR_STRING)
352 {
Bram Moolenaard1f13fd2012-10-05 21:30:07 +0200353 result = Py_BuildValue("s", our_tv->vval.v_string == NULL
354 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200355 }
356 else if (our_tv->v_type == VAR_NUMBER)
357 {
358 char buf[NUMBUFLEN];
359
360 /* For backwards compatibility numbers are stored as strings. */
361 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
362 result = Py_BuildValue("s", buf);
363 }
364# ifdef FEAT_FLOAT
365 else if (our_tv->v_type == VAR_FLOAT)
366 {
367 char buf[NUMBUFLEN];
368
369 sprintf(buf, "%f", our_tv->vval.v_float);
370 result = Py_BuildValue("s", buf);
371 }
372# endif
373 else if (our_tv->v_type == VAR_LIST)
374 {
375 list_T *list = our_tv->vval.v_list;
376 listitem_T *curr;
377
378 result = PyList_New(0);
379
380 if (list != NULL)
381 {
382 PyDict_SetItemString(lookupDict, ptrBuf, result);
383
384 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
385 {
386 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
387 PyList_Append(result, newObj);
388 Py_DECREF(newObj);
389 }
390 }
391 }
392 else if (our_tv->v_type == VAR_DICT)
393 {
394 result = PyDict_New();
395
396 if (our_tv->vval.v_dict != NULL)
397 {
398 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
399 long_u todo = ht->ht_used;
400 hashitem_T *hi;
401 dictitem_T *di;
402
403 PyDict_SetItemString(lookupDict, ptrBuf, result);
404
405 for (hi = ht->ht_array; todo > 0; ++hi)
406 {
407 if (!HASHITEM_EMPTY(hi))
408 {
409 --todo;
410
411 di = dict_lookup(hi);
412 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
413 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
414 Py_DECREF(newObj);
415 }
416 }
417 }
418 }
419 else
420 {
421 Py_INCREF(Py_None);
422 result = Py_None;
423 }
424
425 return result;
426}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200427
428 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200429VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200430{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200431 char *expr;
432 typval_T *our_tv;
433 PyObject *result;
434 PyObject *lookup_dict;
435
436 if (!PyArg_ParseTuple(args, "s", &expr))
437 return NULL;
438
439 Py_BEGIN_ALLOW_THREADS
440 Python_Lock_Vim();
441 our_tv = eval_expr((char_u *)expr, NULL);
442
443 Python_Release_Vim();
444 Py_END_ALLOW_THREADS
445
446 if (our_tv == NULL)
447 {
448 PyErr_SetVim(_("invalid expression"));
449 return NULL;
450 }
451
452 /* Convert the Vim type into a Python type. Create a dictionary that's
453 * used to check for recursive loops. */
454 lookup_dict = PyDict_New();
455 result = VimToPython(our_tv, 1, lookup_dict);
456 Py_DECREF(lookup_dict);
457
458
459 Py_BEGIN_ALLOW_THREADS
460 Python_Lock_Vim();
461 free_tv(our_tv);
462 Python_Release_Vim();
463 Py_END_ALLOW_THREADS
464
465 return result;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200466}
467
Bram Moolenaardb913952012-06-29 12:54:53 +0200468static PyObject *ConvertToPyObject(typval_T *);
469
470 static PyObject *
471VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
472{
Bram Moolenaardb913952012-06-29 12:54:53 +0200473 char *expr;
474 typval_T *our_tv;
475 PyObject *result;
476
477 if (!PyArg_ParseTuple(args, "s", &expr))
478 return NULL;
479
480 Py_BEGIN_ALLOW_THREADS
481 Python_Lock_Vim();
482 our_tv = eval_expr((char_u *)expr, NULL);
483
484 Python_Release_Vim();
485 Py_END_ALLOW_THREADS
486
487 if (our_tv == NULL)
488 {
489 PyErr_SetVim(_("invalid expression"));
490 return NULL;
491 }
492
493 result = ConvertToPyObject(our_tv);
494 Py_BEGIN_ALLOW_THREADS
495 Python_Lock_Vim();
496 free_tv(our_tv);
497 Python_Release_Vim();
498 Py_END_ALLOW_THREADS
499
500 return result;
Bram Moolenaardb913952012-06-29 12:54:53 +0200501}
502
503 static PyObject *
504VimStrwidth(PyObject *self UNUSED, PyObject *args)
505{
506 char *expr;
507
508 if (!PyArg_ParseTuple(args, "s", &expr))
509 return NULL;
510
Bram Moolenaara54bf402012-12-05 16:30:07 +0100511 return PyLong_FromLong(
512#ifdef FEAT_MBYTE
513 mb_string2cells((char_u *)expr, (int)STRLEN(expr))
514#else
515 STRLEN(expr)
516#endif
517 );
Bram Moolenaardb913952012-06-29 12:54:53 +0200518}
519
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200520/*
521 * Vim module - Definitions
522 */
523
524static struct PyMethodDef VimMethods[] = {
525 /* name, function, calling, documentation */
526 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
527 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200528 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
529 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200530 { NULL, NULL, 0, NULL }
531};
532
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200533/*
534 * Buffer list object - Implementation
535 */
536
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200537static PyTypeObject BufListType;
538static PySequenceMethods BufListAsSeq;
539
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200540typedef struct
541{
542 PyObject_HEAD
543} BufListObject;
544
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200545 static PyInt
546BufListLength(PyObject *self UNUSED)
547{
548 buf_T *b = firstbuf;
549 PyInt n = 0;
550
551 while (b)
552 {
553 ++n;
554 b = b->b_next;
555 }
556
557 return n;
558}
559
560 static PyObject *
561BufListItem(PyObject *self UNUSED, PyInt n)
562{
563 buf_T *b;
564
565 for (b = firstbuf; b; b = b->b_next, --n)
566 {
567 if (n == 0)
568 return BufferNew(b);
569 }
570
571 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
572 return NULL;
573}
574
Bram Moolenaardb913952012-06-29 12:54:53 +0200575typedef struct pylinkedlist_S {
576 struct pylinkedlist_S *pll_next;
577 struct pylinkedlist_S *pll_prev;
578 PyObject *pll_obj;
579} pylinkedlist_T;
580
581static pylinkedlist_T *lastdict = NULL;
582static pylinkedlist_T *lastlist = NULL;
583
584 static void
585pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
586{
587 if (ref->pll_prev == NULL)
588 {
589 if (ref->pll_next == NULL)
590 {
591 *last = NULL;
592 return;
593 }
594 }
595 else
596 ref->pll_prev->pll_next = ref->pll_next;
597
598 if (ref->pll_next == NULL)
599 *last = ref->pll_prev;
600 else
601 ref->pll_next->pll_prev = ref->pll_prev;
602}
603
604 static void
605pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
606{
607 if (*last == NULL)
608 ref->pll_prev = NULL;
609 else
610 {
611 (*last)->pll_next = ref;
612 ref->pll_prev = *last;
613 }
614 ref->pll_next = NULL;
615 ref->pll_obj = self;
616 *last = ref;
617}
618
619static PyTypeObject DictionaryType;
620
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200621#define DICTKEY_GET_NOTEMPTY(err) \
622 DICTKEY_GET(err) \
623 if (*key == NUL) \
624 { \
625 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
626 return err; \
627 }
628
Bram Moolenaardb913952012-06-29 12:54:53 +0200629typedef struct
630{
631 PyObject_HEAD
632 dict_T *dict;
633 pylinkedlist_T ref;
634} DictionaryObject;
635
636 static PyObject *
637DictionaryNew(dict_T *dict)
638{
639 DictionaryObject *self;
640
641 self = PyObject_NEW(DictionaryObject, &DictionaryType);
642 if (self == NULL)
643 return NULL;
644 self->dict = dict;
645 ++dict->dv_refcount;
646
647 pyll_add((PyObject *)(self), &self->ref, &lastdict);
648
649 return (PyObject *)(self);
650}
651
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200652 static void
653DictionaryDestructor(PyObject *self)
654{
655 DictionaryObject *this = ((DictionaryObject *) (self));
656
657 pyll_remove(&this->ref, &lastdict);
658 dict_unref(this->dict);
659
660 DESTRUCTOR_FINISH(self);
661}
662
Bram Moolenaardb913952012-06-29 12:54:53 +0200663 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200664DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200665{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200666 DictionaryObject *this = (DictionaryObject *)(self);
667
Bram Moolenaar66b79852012-09-21 14:00:35 +0200668 if (val == NULL)
669 {
670 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
671 return -1;
672 }
673
674 if (strcmp(name, "locked") == 0)
675 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200676 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200677 {
678 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
679 return -1;
680 }
681 else
682 {
683 if (!PyBool_Check(val))
684 {
685 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
686 return -1;
687 }
688
689 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200690 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200691 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200692 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200693 }
694 return 0;
695 }
696 else
697 {
698 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
699 return -1;
700 }
701}
702
703 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200704DictionaryLength(PyObject *self)
705{
706 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
707}
708
709 static PyObject *
710DictionaryItem(PyObject *self, PyObject *keyObject)
711{
712 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200713 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200714 DICTKEY_DECL
715
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200716 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200717
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200718 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
719
Bram Moolenaar696c2112012-09-21 13:43:14 +0200720 DICTKEY_UNREF
721
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200722 if (di == NULL)
723 {
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200724 PyErr_SetString(PyExc_KeyError, _("no such key in dictionary"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200725 return NULL;
726 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200727
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200728 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200729}
730
731 static PyInt
732DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
733{
734 char_u *key;
735 typval_T tv;
736 dict_T *d = ((DictionaryObject *)(self))->dict;
737 dictitem_T *di;
738 DICTKEY_DECL
739
740 if (d->dv_lock)
741 {
742 PyErr_SetVim(_("dict is locked"));
743 return -1;
744 }
745
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200746 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200747
748 di = dict_find(d, key, -1);
749
750 if (valObject == NULL)
751 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200752 hashitem_T *hi;
753
Bram Moolenaardb913952012-06-29 12:54:53 +0200754 if (di == NULL)
755 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200756 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200757 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
758 return -1;
759 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200760 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200761 hash_remove(&d->dv_hashtab, hi);
762 dictitem_free(di);
763 return 0;
764 }
765
766 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200767 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200768
769 if (di == NULL)
770 {
771 di = dictitem_alloc(key);
772 if (di == NULL)
773 {
774 PyErr_NoMemory();
775 return -1;
776 }
777 di->di_tv.v_lock = 0;
778
779 if (dict_add(d, di) == FAIL)
780 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200781 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200782 vim_free(di);
783 PyErr_SetVim(_("failed to add key to dictionary"));
784 return -1;
785 }
786 }
787 else
788 clear_tv(&di->di_tv);
789
790 DICTKEY_UNREF
791
792 copy_tv(&tv, &di->di_tv);
793 return 0;
794}
795
796 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100797DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200798{
799 dict_T *dict = ((DictionaryObject *)(self))->dict;
800 long_u todo = dict->dv_hashtab.ht_used;
801 Py_ssize_t i = 0;
802 PyObject *r;
803 hashitem_T *hi;
804
805 r = PyList_New(todo);
806 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
807 {
808 if (!HASHITEM_EMPTY(hi))
809 {
810 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
811 --todo;
812 ++i;
813 }
814 }
815 return r;
816}
817
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200818static PyMappingMethods DictionaryAsMapping = {
819 (lenfunc) DictionaryLength,
820 (binaryfunc) DictionaryItem,
821 (objobjargproc) DictionaryAssItem,
822};
823
Bram Moolenaardb913952012-06-29 12:54:53 +0200824static struct PyMethodDef DictionaryMethods[] = {
825 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
826 { NULL, NULL, 0, NULL }
827};
828
829static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200830static PySequenceMethods ListAsSeq;
831static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200832
833typedef struct
834{
835 PyObject_HEAD
836 list_T *list;
837 pylinkedlist_T ref;
838} ListObject;
839
840 static PyObject *
841ListNew(list_T *list)
842{
843 ListObject *self;
844
845 self = PyObject_NEW(ListObject, &ListType);
846 if (self == NULL)
847 return NULL;
848 self->list = list;
849 ++list->lv_refcount;
850
851 pyll_add((PyObject *)(self), &self->ref, &lastlist);
852
853 return (PyObject *)(self);
854}
855
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200856 static void
857ListDestructor(PyObject *self)
858{
859 ListObject *this = (ListObject *)(self);
860
861 pyll_remove(&this->ref, &lastlist);
862 list_unref(this->list);
863
864 DESTRUCTOR_FINISH(self);
865}
866
Bram Moolenaardb913952012-06-29 12:54:53 +0200867 static int
868list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
869{
870 Py_ssize_t i;
871 Py_ssize_t lsize = PySequence_Size(obj);
872 PyObject *litem;
873 listitem_T *li;
874
875 for(i=0; i<lsize; i++)
876 {
877 li = listitem_alloc();
878 if (li == NULL)
879 {
880 PyErr_NoMemory();
881 return -1;
882 }
883 li->li_tv.v_lock = 0;
884
885 litem = PySequence_GetItem(obj, i);
886 if (litem == NULL)
887 return -1;
888 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
889 return -1;
890
891 list_append(l, li);
892 }
893 return 0;
894}
895
Bram Moolenaardb913952012-06-29 12:54:53 +0200896 static PyInt
897ListLength(PyObject *self)
898{
899 return ((PyInt) (((ListObject *) (self))->list->lv_len));
900}
901
902 static PyObject *
903ListItem(PyObject *self, Py_ssize_t index)
904{
905 listitem_T *li;
906
907 if (index>=ListLength(self))
908 {
909 PyErr_SetString(PyExc_IndexError, "list index out of range");
910 return NULL;
911 }
912 li = list_find(((ListObject *) (self))->list, (long) index);
913 if (li == NULL)
914 {
915 PyErr_SetVim(_("internal error: failed to get vim list item"));
916 return NULL;
917 }
918 return ConvertToPyObject(&li->li_tv);
919}
920
921#define PROC_RANGE \
922 if (last < 0) {\
923 if (last < -size) \
924 last = 0; \
925 else \
926 last += size; \
927 } \
928 if (first < 0) \
929 first = 0; \
930 if (first > size) \
931 first = size; \
932 if (last > size) \
933 last = size;
934
935 static PyObject *
936ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
937{
938 PyInt i;
939 PyInt size = ListLength(self);
940 PyInt n;
941 PyObject *list;
942 int reversed = 0;
943
944 PROC_RANGE
945 if (first >= last)
946 first = last;
947
948 n = last-first;
949 list = PyList_New(n);
950 if (list == NULL)
951 return NULL;
952
953 for (i = 0; i < n; ++i)
954 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200955 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +0200956 if (item == NULL)
957 {
958 Py_DECREF(list);
959 return NULL;
960 }
961
962 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
963 {
964 Py_DECREF(item);
965 Py_DECREF(list);
966 return NULL;
967 }
968 }
969
970 return list;
971}
972
973 static int
974ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
975{
976 typval_T tv;
977 list_T *l = ((ListObject *) (self))->list;
978 listitem_T *li;
979 Py_ssize_t length = ListLength(self);
980
981 if (l->lv_lock)
982 {
983 PyErr_SetVim(_("list is locked"));
984 return -1;
985 }
986 if (index>length || (index==length && obj==NULL))
987 {
988 PyErr_SetString(PyExc_IndexError, "list index out of range");
989 return -1;
990 }
991
992 if (obj == NULL)
993 {
994 li = list_find(l, (long) index);
995 list_remove(l, li, li);
996 clear_tv(&li->li_tv);
997 vim_free(li);
998 return 0;
999 }
1000
1001 if (ConvertFromPyObject(obj, &tv) == -1)
1002 return -1;
1003
1004 if (index == length)
1005 {
1006 if (list_append_tv(l, &tv) == FAIL)
1007 {
1008 PyErr_SetVim(_("Failed to add item to list"));
1009 return -1;
1010 }
1011 }
1012 else
1013 {
1014 li = list_find(l, (long) index);
1015 clear_tv(&li->li_tv);
1016 copy_tv(&tv, &li->li_tv);
1017 }
1018 return 0;
1019}
1020
1021 static int
1022ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1023{
1024 PyInt size = ListLength(self);
1025 Py_ssize_t i;
1026 Py_ssize_t lsize;
1027 PyObject *litem;
1028 listitem_T *li;
1029 listitem_T *next;
1030 typval_T v;
1031 list_T *l = ((ListObject *) (self))->list;
1032
1033 if (l->lv_lock)
1034 {
1035 PyErr_SetVim(_("list is locked"));
1036 return -1;
1037 }
1038
1039 PROC_RANGE
1040
1041 if (first == size)
1042 li = NULL;
1043 else
1044 {
1045 li = list_find(l, (long) first);
1046 if (li == NULL)
1047 {
1048 PyErr_SetVim(_("internal error: no vim list item"));
1049 return -1;
1050 }
1051 if (last > first)
1052 {
1053 i = last - first;
1054 while (i-- && li != NULL)
1055 {
1056 next = li->li_next;
1057 listitem_remove(l, li);
1058 li = next;
1059 }
1060 }
1061 }
1062
1063 if (obj == NULL)
1064 return 0;
1065
1066 if (!PyList_Check(obj))
1067 {
1068 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1069 return -1;
1070 }
1071
1072 lsize = PyList_Size(obj);
1073
1074 for(i=0; i<lsize; i++)
1075 {
1076 litem = PyList_GetItem(obj, i);
1077 if (litem == NULL)
1078 return -1;
1079 if (ConvertFromPyObject(litem, &v) == -1)
1080 return -1;
1081 if (list_insert_tv(l, &v, li) == FAIL)
1082 {
1083 PyErr_SetVim(_("internal error: failed to add item to list"));
1084 return -1;
1085 }
1086 }
1087 return 0;
1088}
1089
1090 static PyObject *
1091ListConcatInPlace(PyObject *self, PyObject *obj)
1092{
1093 list_T *l = ((ListObject *) (self))->list;
1094 PyObject *lookup_dict;
1095
1096 if (l->lv_lock)
1097 {
1098 PyErr_SetVim(_("list is locked"));
1099 return NULL;
1100 }
1101
1102 if (!PySequence_Check(obj))
1103 {
1104 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1105 return NULL;
1106 }
1107
1108 lookup_dict = PyDict_New();
1109 if (list_py_concat(l, obj, lookup_dict) == -1)
1110 {
1111 Py_DECREF(lookup_dict);
1112 return NULL;
1113 }
1114 Py_DECREF(lookup_dict);
1115
1116 Py_INCREF(self);
1117 return self;
1118}
1119
Bram Moolenaar66b79852012-09-21 14:00:35 +02001120 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001121ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001122{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001123 ListObject *this = (ListObject *)(self);
1124
Bram Moolenaar66b79852012-09-21 14:00:35 +02001125 if (val == NULL)
1126 {
1127 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
1128 return -1;
1129 }
1130
1131 if (strcmp(name, "locked") == 0)
1132 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001133 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001134 {
1135 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
1136 return -1;
1137 }
1138 else
1139 {
1140 if (!PyBool_Check(val))
1141 {
1142 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
1143 return -1;
1144 }
1145
1146 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001147 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001148 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001149 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001150 }
1151 return 0;
1152 }
1153 else
1154 {
1155 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
1156 return -1;
1157 }
1158}
1159
Bram Moolenaardb913952012-06-29 12:54:53 +02001160static struct PyMethodDef ListMethods[] = {
1161 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1162 { NULL, NULL, 0, NULL }
1163};
1164
1165typedef struct
1166{
1167 PyObject_HEAD
1168 char_u *name;
1169} FunctionObject;
1170
1171static PyTypeObject FunctionType;
1172
1173 static PyObject *
1174FunctionNew(char_u *name)
1175{
1176 FunctionObject *self;
1177
1178 self = PyObject_NEW(FunctionObject, &FunctionType);
1179 if (self == NULL)
1180 return NULL;
1181 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1182 if (self->name == NULL)
1183 {
1184 PyErr_NoMemory();
1185 return NULL;
1186 }
1187 STRCPY(self->name, name);
1188 func_ref(name);
1189 return (PyObject *)(self);
1190}
1191
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001192 static void
1193FunctionDestructor(PyObject *self)
1194{
1195 FunctionObject *this = (FunctionObject *) (self);
1196
1197 func_unref(this->name);
1198 PyMem_Del(this->name);
1199
1200 DESTRUCTOR_FINISH(self);
1201}
1202
Bram Moolenaardb913952012-06-29 12:54:53 +02001203 static PyObject *
1204FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1205{
1206 FunctionObject *this = (FunctionObject *)(self);
1207 char_u *name = this->name;
1208 typval_T args;
1209 typval_T selfdicttv;
1210 typval_T rettv;
1211 dict_T *selfdict = NULL;
1212 PyObject *selfdictObject;
1213 PyObject *result;
1214 int error;
1215
1216 if (ConvertFromPyObject(argsObject, &args) == -1)
1217 return NULL;
1218
1219 if (kwargs != NULL)
1220 {
1221 selfdictObject = PyDict_GetItemString(kwargs, "self");
1222 if (selfdictObject != NULL)
1223 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001224 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001225 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001226 PyErr_SetString(PyExc_TypeError,
1227 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001228 clear_tv(&args);
1229 return NULL;
1230 }
1231 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1232 return NULL;
1233 selfdict = selfdicttv.vval.v_dict;
1234 }
1235 }
1236
1237 error = func_call(name, &args, selfdict, &rettv);
1238 if (error != OK)
1239 {
1240 result = NULL;
1241 PyErr_SetVim(_("failed to run function"));
1242 }
1243 else
1244 result = ConvertToPyObject(&rettv);
1245
1246 /* FIXME Check what should really be cleared. */
1247 clear_tv(&args);
1248 clear_tv(&rettv);
1249 /*
1250 * if (selfdict!=NULL)
1251 * clear_tv(selfdicttv);
1252 */
1253
1254 return result;
1255}
1256
1257static struct PyMethodDef FunctionMethods[] = {
1258 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1259 { NULL, NULL, 0, NULL }
1260};
1261
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001262/*
1263 * Options object
1264 */
1265
1266static PyTypeObject OptionsType;
1267
1268typedef int (*checkfun)(void *);
1269
1270typedef struct
1271{
1272 PyObject_HEAD
1273 int opt_type;
1274 void *from;
1275 checkfun Check;
1276 PyObject *fromObj;
1277} OptionsObject;
1278
1279 static PyObject *
1280OptionsItem(OptionsObject *this, PyObject *keyObject)
1281{
1282 char_u *key;
1283 int flags;
1284 long numval;
1285 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001286 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001287
1288 if (this->Check(this->from))
1289 return NULL;
1290
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001291 DICTKEY_GET_NOTEMPTY(NULL)
1292
1293 flags = get_option_value_strict(key, &numval, &stringval,
1294 this->opt_type, this->from);
1295
1296 DICTKEY_UNREF
1297
1298 if (flags == 0)
1299 {
1300 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1301 return NULL;
1302 }
1303
1304 if (flags & SOPT_UNSET)
1305 {
1306 Py_INCREF(Py_None);
1307 return Py_None;
1308 }
1309 else if (flags & SOPT_BOOL)
1310 {
1311 PyObject *r;
1312 r = numval ? Py_True : Py_False;
1313 Py_INCREF(r);
1314 return r;
1315 }
1316 else if (flags & SOPT_NUM)
1317 return PyInt_FromLong(numval);
1318 else if (flags & SOPT_STRING)
1319 {
1320 if (stringval)
1321 return PyBytes_FromString((char *) stringval);
1322 else
1323 {
1324 PyErr_SetString(PyExc_ValueError, "Unable to get option value");
1325 return NULL;
1326 }
1327 }
1328 else
1329 {
1330 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1331 return NULL;
1332 }
1333}
1334
1335 static int
1336set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1337 char_u *key;
1338 int numval;
1339 char_u *stringval;
1340 int opt_flags;
1341 int opt_type;
1342 void *from;
1343{
1344 win_T *save_curwin;
1345 tabpage_T *save_curtab;
1346 aco_save_T aco;
1347 int r = 0;
1348
1349 switch (opt_type)
1350 {
1351 case SREQ_WIN:
1352 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1353 == FAIL)
1354 {
1355 PyErr_SetVim("Problem while switching windows.");
1356 return -1;
1357 }
1358 set_option_value(key, numval, stringval, opt_flags);
1359 restore_win(save_curwin, save_curtab);
1360 break;
1361 case SREQ_BUF:
1362 aucmd_prepbuf(&aco, (buf_T *) from);
1363 set_option_value(key, numval, stringval, opt_flags);
1364 aucmd_restbuf(&aco);
1365 break;
1366 case SREQ_GLOBAL:
1367 set_option_value(key, numval, stringval, opt_flags);
1368 break;
1369 }
1370 return r;
1371}
1372
1373 static int
1374OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1375{
1376 char_u *key;
1377 int flags;
1378 int opt_flags;
1379 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001380 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001381
1382 if (this->Check(this->from))
1383 return -1;
1384
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001385 DICTKEY_GET_NOTEMPTY(-1)
1386
1387 flags = get_option_value_strict(key, NULL, NULL,
1388 this->opt_type, this->from);
1389
1390 DICTKEY_UNREF
1391
1392 if (flags == 0)
1393 {
1394 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1395 return -1;
1396 }
1397
1398 if (valObject == NULL)
1399 {
1400 if (this->opt_type == SREQ_GLOBAL)
1401 {
1402 PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
1403 return -1;
1404 }
1405 else if (!(flags & SOPT_GLOBAL))
1406 {
1407 PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
1408 "global value");
1409 return -1;
1410 }
1411 else
1412 {
1413 unset_global_local_option(key, this->from);
1414 return 0;
1415 }
1416 }
1417
1418 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1419
1420 if (flags & SOPT_BOOL)
1421 {
1422 if (!PyBool_Check(valObject))
1423 {
1424 PyErr_SetString(PyExc_ValueError, "Object must be boolean");
1425 return -1;
1426 }
1427
1428 r = set_option_value_for(key, (valObject == Py_True), NULL, opt_flags,
1429 this->opt_type, this->from);
1430 }
1431 else if (flags & SOPT_NUM)
1432 {
1433 int val;
1434
1435#if PY_MAJOR_VERSION < 3
1436 if (PyInt_Check(valObject))
1437 val = PyInt_AsLong(valObject);
1438 else
1439#endif
1440 if (PyLong_Check(valObject))
1441 val = PyLong_AsLong(valObject);
1442 else
1443 {
1444 PyErr_SetString(PyExc_ValueError, "Object must be integer");
1445 return -1;
1446 }
1447
1448 r = set_option_value_for(key, val, NULL, opt_flags,
1449 this->opt_type, this->from);
1450 }
1451 else
1452 {
1453 char_u *val;
1454 if (PyBytes_Check(valObject))
1455 {
1456
1457 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1458 return -1;
1459 if (val == NULL)
1460 return -1;
1461
1462 val = vim_strsave(val);
1463 }
1464 else if (PyUnicode_Check(valObject))
1465 {
1466 PyObject *bytes;
1467
1468 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1469 if (bytes == NULL)
1470 return -1;
1471
1472 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1473 return -1;
1474 if (val == NULL)
1475 return -1;
1476
1477 val = vim_strsave(val);
1478 Py_XDECREF(bytes);
1479 }
1480 else
1481 {
1482 PyErr_SetString(PyExc_ValueError, "Object must be string");
1483 return -1;
1484 }
1485
1486 r = set_option_value_for(key, 0, val, opt_flags,
1487 this->opt_type, this->from);
1488 vim_free(val);
1489 }
1490
1491 return r;
1492}
1493
1494 static int
1495dummy_check(void *arg UNUSED)
1496{
1497 return 0;
1498}
1499
1500 static PyObject *
1501OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1502{
1503 OptionsObject *self;
1504
1505 self = PyObject_NEW(OptionsObject, &OptionsType);
1506 if (self == NULL)
1507 return NULL;
1508
1509 self->opt_type = opt_type;
1510 self->from = from;
1511 self->Check = Check;
1512 self->fromObj = fromObj;
1513 if (fromObj)
1514 Py_INCREF(fromObj);
1515
1516 return (PyObject *)(self);
1517}
1518
1519 static void
1520OptionsDestructor(PyObject *self)
1521{
1522 if (((OptionsObject *)(self))->fromObj)
1523 Py_DECREF(((OptionsObject *)(self))->fromObj);
1524 DESTRUCTOR_FINISH(self);
1525}
1526
1527static PyMappingMethods OptionsAsMapping = {
1528 (lenfunc) NULL,
1529 (binaryfunc) OptionsItem,
1530 (objobjargproc) OptionsAssItem,
1531};
1532
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001533/* Window object
1534 */
1535
1536typedef struct
1537{
1538 PyObject_HEAD
1539 win_T *win;
1540} WindowObject;
1541
1542static int WindowSetattr(PyObject *, char *, PyObject *);
1543static PyObject *WindowRepr(PyObject *);
1544static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001545
1546 static int
1547CheckWindow(WindowObject *this)
1548{
1549 if (this->win == INVALID_WINDOW_VALUE)
1550 {
1551 PyErr_SetVim(_("attempt to refer to deleted window"));
1552 return -1;
1553 }
1554
1555 return 0;
1556}
1557
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001558 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001559WindowNew(win_T *win)
1560{
1561 /* We need to handle deletion of windows underneath us.
1562 * If we add a "w_python*_ref" field to the win_T structure,
1563 * then we can get at it in win_free() in vim. We then
1564 * need to create only ONE Python object per window - if
1565 * we try to create a second, just INCREF the existing one
1566 * and return it. The (single) Python object referring to
1567 * the window is stored in "w_python*_ref".
1568 * On a win_free() we set the Python object's win_T* field
1569 * to an invalid value. We trap all uses of a window
1570 * object, and reject them if the win_T* field is invalid.
1571 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001572 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001573 * w_python_ref and w_python3_ref fields respectively.
1574 */
1575
1576 WindowObject *self;
1577
1578 if (WIN_PYTHON_REF(win))
1579 {
1580 self = WIN_PYTHON_REF(win);
1581 Py_INCREF(self);
1582 }
1583 else
1584 {
1585 self = PyObject_NEW(WindowObject, &WindowType);
1586 if (self == NULL)
1587 return NULL;
1588 self->win = win;
1589 WIN_PYTHON_REF(win) = self;
1590 }
1591
1592 return (PyObject *)(self);
1593}
1594
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001595 static void
1596WindowDestructor(PyObject *self)
1597{
1598 WindowObject *this = (WindowObject *)(self);
1599
1600 if (this->win && this->win != INVALID_WINDOW_VALUE)
1601 WIN_PYTHON_REF(this->win) = NULL;
1602
1603 DESTRUCTOR_FINISH(self);
1604}
1605
Bram Moolenaar971db462013-05-12 18:44:48 +02001606 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001607WindowAttr(WindowObject *this, char *name)
1608{
1609 if (strcmp(name, "buffer") == 0)
1610 return (PyObject *)BufferNew(this->win->w_buffer);
1611 else if (strcmp(name, "cursor") == 0)
1612 {
1613 pos_T *pos = &this->win->w_cursor;
1614
1615 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1616 }
1617 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001618 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001619#ifdef FEAT_WINDOWS
1620 else if (strcmp(name, "row") == 0)
1621 return PyLong_FromLong((long)(this->win->w_winrow));
1622#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001623#ifdef FEAT_VERTSPLIT
1624 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001625 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001626 else if (strcmp(name, "col") == 0)
1627 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001628#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001629 else if (strcmp(name, "vars") == 0)
1630 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001631 else if (strcmp(name, "options") == 0)
1632 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1633 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001634 else if (strcmp(name, "number") == 0)
1635 return PyLong_FromLong((long) get_win_number(this->win));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001636 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001637 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1638 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001639 else
1640 return NULL;
1641}
1642
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001643 static int
1644WindowSetattr(PyObject *self, char *name, PyObject *val)
1645{
1646 WindowObject *this = (WindowObject *)(self);
1647
1648 if (CheckWindow(this))
1649 return -1;
1650
1651 if (strcmp(name, "buffer") == 0)
1652 {
1653 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1654 return -1;
1655 }
1656 else if (strcmp(name, "cursor") == 0)
1657 {
1658 long lnum;
1659 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001660
1661 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1662 return -1;
1663
1664 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1665 {
1666 PyErr_SetVim(_("cursor position outside buffer"));
1667 return -1;
1668 }
1669
1670 /* Check for keyboard interrupts */
1671 if (VimErrorCheck())
1672 return -1;
1673
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001674 this->win->w_cursor.lnum = lnum;
1675 this->win->w_cursor.col = col;
1676#ifdef FEAT_VIRTUALEDIT
1677 this->win->w_cursor.coladd = 0;
1678#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001679 /* When column is out of range silently correct it. */
1680 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001681
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001682 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001683 return 0;
1684 }
1685 else if (strcmp(name, "height") == 0)
1686 {
1687 int height;
1688 win_T *savewin;
1689
1690 if (!PyArg_Parse(val, "i", &height))
1691 return -1;
1692
1693#ifdef FEAT_GUI
1694 need_mouse_correct = TRUE;
1695#endif
1696 savewin = curwin;
1697 curwin = this->win;
1698 win_setheight(height);
1699 curwin = savewin;
1700
1701 /* Check for keyboard interrupts */
1702 if (VimErrorCheck())
1703 return -1;
1704
1705 return 0;
1706 }
1707#ifdef FEAT_VERTSPLIT
1708 else if (strcmp(name, "width") == 0)
1709 {
1710 int width;
1711 win_T *savewin;
1712
1713 if (!PyArg_Parse(val, "i", &width))
1714 return -1;
1715
1716#ifdef FEAT_GUI
1717 need_mouse_correct = TRUE;
1718#endif
1719 savewin = curwin;
1720 curwin = this->win;
1721 win_setwidth(width);
1722 curwin = savewin;
1723
1724 /* Check for keyboard interrupts */
1725 if (VimErrorCheck())
1726 return -1;
1727
1728 return 0;
1729 }
1730#endif
1731 else
1732 {
1733 PyErr_SetString(PyExc_AttributeError, name);
1734 return -1;
1735 }
1736}
1737
1738 static PyObject *
1739WindowRepr(PyObject *self)
1740{
1741 static char repr[100];
1742 WindowObject *this = (WindowObject *)(self);
1743
1744 if (this->win == INVALID_WINDOW_VALUE)
1745 {
1746 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1747 return PyString_FromString(repr);
1748 }
1749 else
1750 {
Bram Moolenaar6d216452013-05-12 19:00:41 +02001751 int w = get_win_number(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001752
Bram Moolenaar6d216452013-05-12 19:00:41 +02001753 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001754 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1755 (self));
1756 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001757 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001758
1759 return PyString_FromString(repr);
1760 }
1761}
1762
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001763static struct PyMethodDef WindowMethods[] = {
1764 /* name, function, calling, documentation */
1765 { NULL, NULL, 0, NULL }
1766};
1767
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001768/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001769 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001770 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001771
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001772static PyTypeObject WinListType;
1773static PySequenceMethods WinListAsSeq;
1774
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001775typedef struct
1776{
1777 PyObject_HEAD
1778} WinListObject;
1779
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001780 static PyInt
1781WinListLength(PyObject *self UNUSED)
1782{
1783 win_T *w = firstwin;
1784 PyInt n = 0;
1785
1786 while (w != NULL)
1787 {
1788 ++n;
1789 w = W_NEXT(w);
1790 }
1791
1792 return n;
1793}
1794
1795 static PyObject *
1796WinListItem(PyObject *self UNUSED, PyInt n)
1797{
1798 win_T *w;
1799
1800 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1801 if (n == 0)
1802 return WindowNew(w);
1803
1804 PyErr_SetString(PyExc_IndexError, _("no such window"));
1805 return NULL;
1806}
1807
1808/* Convert a Python string into a Vim line.
1809 *
1810 * The result is in allocated memory. All internal nulls are replaced by
1811 * newline characters. It is an error for the string to contain newline
1812 * characters.
1813 *
1814 * On errors, the Python exception data is set, and NULL is returned.
1815 */
1816 static char *
1817StringToLine(PyObject *obj)
1818{
1819 const char *str;
1820 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001821 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001822 PyInt len;
1823 PyInt i;
1824 char *p;
1825
1826 if (obj == NULL || !PyString_Check(obj))
1827 {
1828 PyErr_BadArgument();
1829 return NULL;
1830 }
1831
Bram Moolenaar19e60942011-06-19 00:27:51 +02001832 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1833 str = PyString_AsString(bytes);
1834 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001835
1836 /*
1837 * Error checking: String must not contain newlines, as we
1838 * are replacing a single line, and we must replace it with
1839 * a single line.
1840 * A trailing newline is removed, so that append(f.readlines()) works.
1841 */
1842 p = memchr(str, '\n', len);
1843 if (p != NULL)
1844 {
1845 if (p == str + len - 1)
1846 --len;
1847 else
1848 {
1849 PyErr_SetVim(_("string cannot contain newlines"));
1850 return NULL;
1851 }
1852 }
1853
1854 /* Create a copy of the string, with internal nulls replaced by
1855 * newline characters, as is the vim convention.
1856 */
1857 save = (char *)alloc((unsigned)(len+1));
1858 if (save == NULL)
1859 {
1860 PyErr_NoMemory();
1861 return NULL;
1862 }
1863
1864 for (i = 0; i < len; ++i)
1865 {
1866 if (str[i] == '\0')
1867 save[i] = '\n';
1868 else
1869 save[i] = str[i];
1870 }
1871
1872 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001873 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001874
1875 return save;
1876}
1877
1878/* Get a line from the specified buffer. The line number is
1879 * in Vim format (1-based). The line is returned as a Python
1880 * string object.
1881 */
1882 static PyObject *
1883GetBufferLine(buf_T *buf, PyInt n)
1884{
1885 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1886}
1887
1888
1889/* Get a list of lines from the specified buffer. The line numbers
1890 * are in Vim format (1-based). The range is from lo up to, but not
1891 * including, hi. The list is returned as a Python list of string objects.
1892 */
1893 static PyObject *
1894GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1895{
1896 PyInt i;
1897 PyInt n = hi - lo;
1898 PyObject *list = PyList_New(n);
1899
1900 if (list == NULL)
1901 return NULL;
1902
1903 for (i = 0; i < n; ++i)
1904 {
1905 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1906
1907 /* Error check - was the Python string creation OK? */
1908 if (str == NULL)
1909 {
1910 Py_DECREF(list);
1911 return NULL;
1912 }
1913
1914 /* Set the list item */
1915 if (PyList_SetItem(list, i, str))
1916 {
1917 Py_DECREF(str);
1918 Py_DECREF(list);
1919 return NULL;
1920 }
1921 }
1922
1923 /* The ownership of the Python list is passed to the caller (ie,
1924 * the caller should Py_DECREF() the object when it is finished
1925 * with it).
1926 */
1927
1928 return list;
1929}
1930
1931/*
1932 * Check if deleting lines made the cursor position invalid.
1933 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1934 * deleted).
1935 */
1936 static void
1937py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1938{
1939 if (curwin->w_cursor.lnum >= lo)
1940 {
1941 /* Adjust the cursor position if it's in/after the changed
1942 * lines. */
1943 if (curwin->w_cursor.lnum >= hi)
1944 {
1945 curwin->w_cursor.lnum += extra;
1946 check_cursor_col();
1947 }
1948 else if (extra < 0)
1949 {
1950 curwin->w_cursor.lnum = lo;
1951 check_cursor();
1952 }
1953 else
1954 check_cursor_col();
1955 changed_cline_bef_curs();
1956 }
1957 invalidate_botline();
1958}
1959
Bram Moolenaar19e60942011-06-19 00:27:51 +02001960/*
1961 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001962 * in Vim format (1-based). The replacement line is given as
1963 * a Python string object. The object is checked for validity
1964 * and correct format. Errors are returned as a value of FAIL.
1965 * The return value is OK on success.
1966 * If OK is returned and len_change is not NULL, *len_change
1967 * is set to the change in the buffer length.
1968 */
1969 static int
1970SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
1971{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001972 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001973 * There are three cases:
1974 * 1. NULL, or None - this is a deletion.
1975 * 2. A string - this is a replacement.
1976 * 3. Anything else - this is an error.
1977 */
1978 if (line == Py_None || line == NULL)
1979 {
1980 buf_T *savebuf = curbuf;
1981
1982 PyErr_Clear();
1983 curbuf = buf;
1984
1985 if (u_savedel((linenr_T)n, 1L) == FAIL)
1986 PyErr_SetVim(_("cannot save undo information"));
1987 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
1988 PyErr_SetVim(_("cannot delete line"));
1989 else
1990 {
1991 if (buf == curwin->w_buffer)
1992 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
1993 deleted_lines_mark((linenr_T)n, 1L);
1994 }
1995
1996 curbuf = savebuf;
1997
1998 if (PyErr_Occurred() || VimErrorCheck())
1999 return FAIL;
2000
2001 if (len_change)
2002 *len_change = -1;
2003
2004 return OK;
2005 }
2006 else if (PyString_Check(line))
2007 {
2008 char *save = StringToLine(line);
2009 buf_T *savebuf = curbuf;
2010
2011 if (save == NULL)
2012 return FAIL;
2013
2014 /* We do not need to free "save" if ml_replace() consumes it. */
2015 PyErr_Clear();
2016 curbuf = buf;
2017
2018 if (u_savesub((linenr_T)n) == FAIL)
2019 {
2020 PyErr_SetVim(_("cannot save undo information"));
2021 vim_free(save);
2022 }
2023 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2024 {
2025 PyErr_SetVim(_("cannot replace line"));
2026 vim_free(save);
2027 }
2028 else
2029 changed_bytes((linenr_T)n, 0);
2030
2031 curbuf = savebuf;
2032
2033 /* Check that the cursor is not beyond the end of the line now. */
2034 if (buf == curwin->w_buffer)
2035 check_cursor_col();
2036
2037 if (PyErr_Occurred() || VimErrorCheck())
2038 return FAIL;
2039
2040 if (len_change)
2041 *len_change = 0;
2042
2043 return OK;
2044 }
2045 else
2046 {
2047 PyErr_BadArgument();
2048 return FAIL;
2049 }
2050}
2051
Bram Moolenaar19e60942011-06-19 00:27:51 +02002052/* Replace a range of lines in the specified buffer. The line numbers are in
2053 * Vim format (1-based). The range is from lo up to, but not including, hi.
2054 * The replacement lines are given as a Python list of string objects. The
2055 * list is checked for validity and correct format. Errors are returned as a
2056 * value of FAIL. The return value is OK on success.
2057 * If OK is returned and len_change is not NULL, *len_change
2058 * is set to the change in the buffer length.
2059 */
2060 static int
2061SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2062{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002063 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002064 * There are three cases:
2065 * 1. NULL, or None - this is a deletion.
2066 * 2. A list - this is a replacement.
2067 * 3. Anything else - this is an error.
2068 */
2069 if (list == Py_None || list == NULL)
2070 {
2071 PyInt i;
2072 PyInt n = (int)(hi - lo);
2073 buf_T *savebuf = curbuf;
2074
2075 PyErr_Clear();
2076 curbuf = buf;
2077
2078 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2079 PyErr_SetVim(_("cannot save undo information"));
2080 else
2081 {
2082 for (i = 0; i < n; ++i)
2083 {
2084 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2085 {
2086 PyErr_SetVim(_("cannot delete line"));
2087 break;
2088 }
2089 }
2090 if (buf == curwin->w_buffer)
2091 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2092 deleted_lines_mark((linenr_T)lo, (long)i);
2093 }
2094
2095 curbuf = savebuf;
2096
2097 if (PyErr_Occurred() || VimErrorCheck())
2098 return FAIL;
2099
2100 if (len_change)
2101 *len_change = -n;
2102
2103 return OK;
2104 }
2105 else if (PyList_Check(list))
2106 {
2107 PyInt i;
2108 PyInt new_len = PyList_Size(list);
2109 PyInt old_len = hi - lo;
2110 PyInt extra = 0; /* lines added to text, can be negative */
2111 char **array;
2112 buf_T *savebuf;
2113
2114 if (new_len == 0) /* avoid allocating zero bytes */
2115 array = NULL;
2116 else
2117 {
2118 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2119 if (array == NULL)
2120 {
2121 PyErr_NoMemory();
2122 return FAIL;
2123 }
2124 }
2125
2126 for (i = 0; i < new_len; ++i)
2127 {
2128 PyObject *line = PyList_GetItem(list, i);
2129
2130 array[i] = StringToLine(line);
2131 if (array[i] == NULL)
2132 {
2133 while (i)
2134 vim_free(array[--i]);
2135 vim_free(array);
2136 return FAIL;
2137 }
2138 }
2139
2140 savebuf = curbuf;
2141
2142 PyErr_Clear();
2143 curbuf = buf;
2144
2145 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2146 PyErr_SetVim(_("cannot save undo information"));
2147
2148 /* If the size of the range is reducing (ie, new_len < old_len) we
2149 * need to delete some old_len. We do this at the start, by
2150 * repeatedly deleting line "lo".
2151 */
2152 if (!PyErr_Occurred())
2153 {
2154 for (i = 0; i < old_len - new_len; ++i)
2155 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2156 {
2157 PyErr_SetVim(_("cannot delete line"));
2158 break;
2159 }
2160 extra -= i;
2161 }
2162
2163 /* For as long as possible, replace the existing old_len with the
2164 * new old_len. This is a more efficient operation, as it requires
2165 * less memory allocation and freeing.
2166 */
2167 if (!PyErr_Occurred())
2168 {
2169 for (i = 0; i < old_len && i < new_len; ++i)
2170 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2171 == FAIL)
2172 {
2173 PyErr_SetVim(_("cannot replace line"));
2174 break;
2175 }
2176 }
2177 else
2178 i = 0;
2179
2180 /* Now we may need to insert the remaining new old_len. If we do, we
2181 * must free the strings as we finish with them (we can't pass the
2182 * responsibility to vim in this case).
2183 */
2184 if (!PyErr_Occurred())
2185 {
2186 while (i < new_len)
2187 {
2188 if (ml_append((linenr_T)(lo + i - 1),
2189 (char_u *)array[i], 0, FALSE) == FAIL)
2190 {
2191 PyErr_SetVim(_("cannot insert line"));
2192 break;
2193 }
2194 vim_free(array[i]);
2195 ++i;
2196 ++extra;
2197 }
2198 }
2199
2200 /* Free any left-over old_len, as a result of an error */
2201 while (i < new_len)
2202 {
2203 vim_free(array[i]);
2204 ++i;
2205 }
2206
2207 /* Free the array of old_len. All of its contents have now
2208 * been dealt with (either freed, or the responsibility passed
2209 * to vim.
2210 */
2211 vim_free(array);
2212
2213 /* Adjust marks. Invalidate any which lie in the
2214 * changed range, and move any in the remainder of the buffer.
2215 */
2216 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2217 (long)MAXLNUM, (long)extra);
2218 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2219
2220 if (buf == curwin->w_buffer)
2221 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2222
2223 curbuf = savebuf;
2224
2225 if (PyErr_Occurred() || VimErrorCheck())
2226 return FAIL;
2227
2228 if (len_change)
2229 *len_change = new_len - old_len;
2230
2231 return OK;
2232 }
2233 else
2234 {
2235 PyErr_BadArgument();
2236 return FAIL;
2237 }
2238}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002239
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002240/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002241 * The line number is in Vim format (1-based). The lines to be inserted are
2242 * given as a Python list of string objects or as a single string. The lines
2243 * to be added are checked for validity and correct format. Errors are
2244 * returned as a value of FAIL. The return value is OK on success.
2245 * If OK is returned and len_change is not NULL, *len_change
2246 * is set to the change in the buffer length.
2247 */
2248 static int
2249InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2250{
2251 /* First of all, we check the type of the supplied Python object.
2252 * It must be a string or a list, or the call is in error.
2253 */
2254 if (PyString_Check(lines))
2255 {
2256 char *str = StringToLine(lines);
2257 buf_T *savebuf;
2258
2259 if (str == NULL)
2260 return FAIL;
2261
2262 savebuf = curbuf;
2263
2264 PyErr_Clear();
2265 curbuf = buf;
2266
2267 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2268 PyErr_SetVim(_("cannot save undo information"));
2269 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2270 PyErr_SetVim(_("cannot insert line"));
2271 else
2272 appended_lines_mark((linenr_T)n, 1L);
2273
2274 vim_free(str);
2275 curbuf = savebuf;
2276 update_screen(VALID);
2277
2278 if (PyErr_Occurred() || VimErrorCheck())
2279 return FAIL;
2280
2281 if (len_change)
2282 *len_change = 1;
2283
2284 return OK;
2285 }
2286 else if (PyList_Check(lines))
2287 {
2288 PyInt i;
2289 PyInt size = PyList_Size(lines);
2290 char **array;
2291 buf_T *savebuf;
2292
2293 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2294 if (array == NULL)
2295 {
2296 PyErr_NoMemory();
2297 return FAIL;
2298 }
2299
2300 for (i = 0; i < size; ++i)
2301 {
2302 PyObject *line = PyList_GetItem(lines, i);
2303 array[i] = StringToLine(line);
2304
2305 if (array[i] == NULL)
2306 {
2307 while (i)
2308 vim_free(array[--i]);
2309 vim_free(array);
2310 return FAIL;
2311 }
2312 }
2313
2314 savebuf = curbuf;
2315
2316 PyErr_Clear();
2317 curbuf = buf;
2318
2319 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2320 PyErr_SetVim(_("cannot save undo information"));
2321 else
2322 {
2323 for (i = 0; i < size; ++i)
2324 {
2325 if (ml_append((linenr_T)(n + i),
2326 (char_u *)array[i], 0, FALSE) == FAIL)
2327 {
2328 PyErr_SetVim(_("cannot insert line"));
2329
2330 /* Free the rest of the lines */
2331 while (i < size)
2332 vim_free(array[i++]);
2333
2334 break;
2335 }
2336 vim_free(array[i]);
2337 }
2338 if (i > 0)
2339 appended_lines_mark((linenr_T)n, (long)i);
2340 }
2341
2342 /* Free the array of lines. All of its contents have now
2343 * been freed.
2344 */
2345 vim_free(array);
2346
2347 curbuf = savebuf;
2348 update_screen(VALID);
2349
2350 if (PyErr_Occurred() || VimErrorCheck())
2351 return FAIL;
2352
2353 if (len_change)
2354 *len_change = size;
2355
2356 return OK;
2357 }
2358 else
2359 {
2360 PyErr_BadArgument();
2361 return FAIL;
2362 }
2363}
2364
2365/*
2366 * Common routines for buffers and line ranges
2367 * -------------------------------------------
2368 */
2369
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002370typedef struct
2371{
2372 PyObject_HEAD
2373 buf_T *buf;
2374} BufferObject;
2375
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002376 static int
2377CheckBuffer(BufferObject *this)
2378{
2379 if (this->buf == INVALID_BUFFER_VALUE)
2380 {
2381 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2382 return -1;
2383 }
2384
2385 return 0;
2386}
2387
2388 static PyObject *
2389RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2390{
2391 if (CheckBuffer(self))
2392 return NULL;
2393
2394 if (n < 0 || n > end - start)
2395 {
2396 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2397 return NULL;
2398 }
2399
2400 return GetBufferLine(self->buf, n+start);
2401}
2402
2403 static PyObject *
2404RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2405{
2406 PyInt size;
2407
2408 if (CheckBuffer(self))
2409 return NULL;
2410
2411 size = end - start + 1;
2412
2413 if (lo < 0)
2414 lo = 0;
2415 else if (lo > size)
2416 lo = size;
2417 if (hi < 0)
2418 hi = 0;
2419 if (hi < lo)
2420 hi = lo;
2421 else if (hi > size)
2422 hi = size;
2423
2424 return GetBufferLineList(self->buf, lo+start, hi+start);
2425}
2426
2427 static PyInt
2428RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2429{
2430 PyInt len_change;
2431
2432 if (CheckBuffer(self))
2433 return -1;
2434
2435 if (n < 0 || n > end - start)
2436 {
2437 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2438 return -1;
2439 }
2440
2441 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2442 return -1;
2443
2444 if (new_end)
2445 *new_end = end + len_change;
2446
2447 return 0;
2448}
2449
Bram Moolenaar19e60942011-06-19 00:27:51 +02002450 static PyInt
2451RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2452{
2453 PyInt size;
2454 PyInt len_change;
2455
2456 /* Self must be a valid buffer */
2457 if (CheckBuffer(self))
2458 return -1;
2459
2460 /* Sort out the slice range */
2461 size = end - start + 1;
2462
2463 if (lo < 0)
2464 lo = 0;
2465 else if (lo > size)
2466 lo = size;
2467 if (hi < 0)
2468 hi = 0;
2469 if (hi < lo)
2470 hi = lo;
2471 else if (hi > size)
2472 hi = size;
2473
2474 if (SetBufferLineList(self->buf, lo + start, hi + start,
2475 val, &len_change) == FAIL)
2476 return -1;
2477
2478 if (new_end)
2479 *new_end = end + len_change;
2480
2481 return 0;
2482}
2483
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002484
2485 static PyObject *
2486RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2487{
2488 PyObject *lines;
2489 PyInt len_change;
2490 PyInt max;
2491 PyInt n;
2492
2493 if (CheckBuffer(self))
2494 return NULL;
2495
2496 max = n = end - start + 1;
2497
2498 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2499 return NULL;
2500
2501 if (n < 0 || n > max)
2502 {
2503 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2504 return NULL;
2505 }
2506
2507 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2508 return NULL;
2509
2510 if (new_end)
2511 *new_end = end + len_change;
2512
2513 Py_INCREF(Py_None);
2514 return Py_None;
2515}
2516
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002517/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002518 */
2519
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002520static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002521static PySequenceMethods RangeAsSeq;
2522static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002523
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002524typedef struct
2525{
2526 PyObject_HEAD
2527 BufferObject *buf;
2528 PyInt start;
2529 PyInt end;
2530} RangeObject;
2531
2532 static PyObject *
2533RangeNew(buf_T *buf, PyInt start, PyInt end)
2534{
2535 BufferObject *bufr;
2536 RangeObject *self;
2537 self = PyObject_NEW(RangeObject, &RangeType);
2538 if (self == NULL)
2539 return NULL;
2540
2541 bufr = (BufferObject *)BufferNew(buf);
2542 if (bufr == NULL)
2543 {
2544 Py_DECREF(self);
2545 return NULL;
2546 }
2547 Py_INCREF(bufr);
2548
2549 self->buf = bufr;
2550 self->start = start;
2551 self->end = end;
2552
2553 return (PyObject *)(self);
2554}
2555
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002556 static void
2557RangeDestructor(PyObject *self)
2558{
2559 Py_DECREF(((RangeObject *)(self))->buf);
2560 DESTRUCTOR_FINISH(self);
2561}
2562
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002563 static PyInt
2564RangeLength(PyObject *self)
2565{
2566 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2567 if (CheckBuffer(((RangeObject *)(self))->buf))
2568 return -1; /* ??? */
2569
2570 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2571}
2572
2573 static PyObject *
2574RangeItem(PyObject *self, PyInt n)
2575{
2576 return RBItem(((RangeObject *)(self))->buf, n,
2577 ((RangeObject *)(self))->start,
2578 ((RangeObject *)(self))->end);
2579}
2580
2581 static PyObject *
2582RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2583{
2584 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2585 ((RangeObject *)(self))->start,
2586 ((RangeObject *)(self))->end);
2587}
2588
2589 static PyObject *
2590RangeAppend(PyObject *self, PyObject *args)
2591{
2592 return RBAppend(((RangeObject *)(self))->buf, args,
2593 ((RangeObject *)(self))->start,
2594 ((RangeObject *)(self))->end,
2595 &((RangeObject *)(self))->end);
2596}
2597
2598 static PyObject *
2599RangeRepr(PyObject *self)
2600{
2601 static char repr[100];
2602 RangeObject *this = (RangeObject *)(self);
2603
2604 if (this->buf->buf == INVALID_BUFFER_VALUE)
2605 {
2606 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2607 (self));
2608 return PyString_FromString(repr);
2609 }
2610 else
2611 {
2612 char *name = (char *)this->buf->buf->b_fname;
2613 int len;
2614
2615 if (name == NULL)
2616 name = "";
2617 len = (int)strlen(name);
2618
2619 if (len > 45)
2620 name = name + (45 - len);
2621
2622 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2623 len > 45 ? "..." : "", name,
2624 this->start, this->end);
2625
2626 return PyString_FromString(repr);
2627 }
2628}
2629
2630static struct PyMethodDef RangeMethods[] = {
2631 /* name, function, calling, documentation */
2632 {"append", RangeAppend, 1, "Append data to the Vim range" },
2633 { NULL, NULL, 0, NULL }
2634};
2635
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002636static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002637static PySequenceMethods BufferAsSeq;
2638static PyMappingMethods BufferAsMapping;
2639
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002640 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002641BufferNew(buf_T *buf)
2642{
2643 /* We need to handle deletion of buffers underneath us.
2644 * If we add a "b_python*_ref" field to the buf_T structure,
2645 * then we can get at it in buf_freeall() in vim. We then
2646 * need to create only ONE Python object per buffer - if
2647 * we try to create a second, just INCREF the existing one
2648 * and return it. The (single) Python object referring to
2649 * the buffer is stored in "b_python*_ref".
2650 * Question: what to do on a buf_freeall(). We'll probably
2651 * have to either delete the Python object (DECREF it to
2652 * zero - a bad idea, as it leaves dangling refs!) or
2653 * set the buf_T * value to an invalid value (-1?), which
2654 * means we need checks in all access functions... Bah.
2655 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002656 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02002657 * b_python_ref and b_python3_ref fields respectively.
2658 */
2659
2660 BufferObject *self;
2661
2662 if (BUF_PYTHON_REF(buf) != NULL)
2663 {
2664 self = BUF_PYTHON_REF(buf);
2665 Py_INCREF(self);
2666 }
2667 else
2668 {
2669 self = PyObject_NEW(BufferObject, &BufferType);
2670 if (self == NULL)
2671 return NULL;
2672 self->buf = buf;
2673 BUF_PYTHON_REF(buf) = self;
2674 }
2675
2676 return (PyObject *)(self);
2677}
2678
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002679 static void
2680BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002681{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002682 BufferObject *this = (BufferObject *)(self);
2683
2684 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2685 BUF_PYTHON_REF(this->buf) = NULL;
2686
2687 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002688}
2689
Bram Moolenaar971db462013-05-12 18:44:48 +02002690 static PyInt
2691BufferLength(PyObject *self)
2692{
2693 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2694 if (CheckBuffer((BufferObject *)(self)))
2695 return -1; /* ??? */
2696
2697 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2698}
2699
2700 static PyObject *
2701BufferItem(PyObject *self, PyInt n)
2702{
2703 return RBItem((BufferObject *)(self), n, 1,
2704 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count);
2705}
2706
2707 static PyObject *
2708BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2709{
2710 return RBSlice((BufferObject *)(self), lo, hi, 1,
2711 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count);
2712}
2713
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002714 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002715BufferAttr(BufferObject *this, char *name)
2716{
2717 if (strcmp(name, "name") == 0)
2718 return Py_BuildValue("s", this->buf->b_ffname);
2719 else if (strcmp(name, "number") == 0)
2720 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
2721 else if (strcmp(name, "vars") == 0)
2722 return DictionaryNew(this->buf->b_vars);
2723 else if (strcmp(name, "options") == 0)
2724 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2725 (PyObject *) this);
2726 else if (strcmp(name,"__members__") == 0)
2727 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
2728 else
2729 return NULL;
2730}
2731
2732 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002733BufferAppend(PyObject *self, PyObject *args)
2734{
2735 return RBAppend((BufferObject *)(self), args, 1,
2736 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2737 NULL);
2738}
2739
2740 static PyObject *
2741BufferMark(PyObject *self, PyObject *args)
2742{
2743 pos_T *posp;
2744 char *pmark;
2745 char mark;
2746 buf_T *curbuf_save;
2747
2748 if (CheckBuffer((BufferObject *)(self)))
2749 return NULL;
2750
2751 if (!PyArg_ParseTuple(args, "s", &pmark))
2752 return NULL;
2753 mark = *pmark;
2754
2755 curbuf_save = curbuf;
2756 curbuf = ((BufferObject *)(self))->buf;
2757 posp = getmark(mark, FALSE);
2758 curbuf = curbuf_save;
2759
2760 if (posp == NULL)
2761 {
2762 PyErr_SetVim(_("invalid mark name"));
2763 return NULL;
2764 }
2765
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002766 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002767 if (VimErrorCheck())
2768 return NULL;
2769
2770 if (posp->lnum <= 0)
2771 {
2772 /* Or raise an error? */
2773 Py_INCREF(Py_None);
2774 return Py_None;
2775 }
2776
2777 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2778}
2779
2780 static PyObject *
2781BufferRange(PyObject *self, PyObject *args)
2782{
2783 PyInt start;
2784 PyInt end;
2785
2786 if (CheckBuffer((BufferObject *)(self)))
2787 return NULL;
2788
2789 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2790 return NULL;
2791
2792 return RangeNew(((BufferObject *)(self))->buf, start, end);
2793}
2794
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002795 static PyObject *
2796BufferRepr(PyObject *self)
2797{
2798 static char repr[100];
2799 BufferObject *this = (BufferObject *)(self);
2800
2801 if (this->buf == INVALID_BUFFER_VALUE)
2802 {
2803 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2804 return PyString_FromString(repr);
2805 }
2806 else
2807 {
2808 char *name = (char *)this->buf->b_fname;
2809 PyInt len;
2810
2811 if (name == NULL)
2812 name = "";
2813 len = strlen(name);
2814
2815 if (len > 35)
2816 name = name + (35 - len);
2817
2818 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2819
2820 return PyString_FromString(repr);
2821 }
2822}
2823
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002824static struct PyMethodDef BufferMethods[] = {
2825 /* name, function, calling, documentation */
2826 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2827 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2828 {"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 +01002829#if PY_VERSION_HEX >= 0x03000000
2830 {"__dir__", BufferDir, 4, "List its attributes" },
2831#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002832 { NULL, NULL, 0, NULL }
2833};
2834
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002835/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002836 */
2837
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002838 static PyObject *
2839CurrentGetattr(PyObject *self UNUSED, char *name)
2840{
2841 if (strcmp(name, "buffer") == 0)
2842 return (PyObject *)BufferNew(curbuf);
2843 else if (strcmp(name, "window") == 0)
2844 return (PyObject *)WindowNew(curwin);
2845 else if (strcmp(name, "line") == 0)
2846 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2847 else if (strcmp(name, "range") == 0)
2848 return RangeNew(curbuf, RangeStart, RangeEnd);
2849 else if (strcmp(name,"__members__") == 0)
2850 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2851 else
2852 {
2853 PyErr_SetString(PyExc_AttributeError, name);
2854 return NULL;
2855 }
2856}
2857
2858 static int
2859CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2860{
2861 if (strcmp(name, "line") == 0)
2862 {
2863 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2864 return -1;
2865
2866 return 0;
2867 }
2868 else
2869 {
2870 PyErr_SetString(PyExc_AttributeError, name);
2871 return -1;
2872 }
2873}
2874
Bram Moolenaardb913952012-06-29 12:54:53 +02002875 static void
2876set_ref_in_py(const int copyID)
2877{
2878 pylinkedlist_T *cur;
2879 dict_T *dd;
2880 list_T *ll;
2881
2882 if (lastdict != NULL)
2883 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
2884 {
2885 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
2886 if (dd->dv_copyID != copyID)
2887 {
2888 dd->dv_copyID = copyID;
2889 set_ref_in_ht(&dd->dv_hashtab, copyID);
2890 }
2891 }
2892
2893 if (lastlist != NULL)
2894 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
2895 {
2896 ll = ((ListObject *) (cur->pll_obj))->list;
2897 if (ll->lv_copyID != copyID)
2898 {
2899 ll->lv_copyID = copyID;
2900 set_ref_in_list(ll, copyID);
2901 }
2902 }
2903}
2904
2905 static int
2906set_string_copy(char_u *str, typval_T *tv)
2907{
2908 tv->vval.v_string = vim_strsave(str);
2909 if (tv->vval.v_string == NULL)
2910 {
2911 PyErr_NoMemory();
2912 return -1;
2913 }
2914 return 0;
2915}
2916
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002917 static int
2918pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2919{
2920 dict_T *d;
2921 char_u *key;
2922 dictitem_T *di;
2923 PyObject *keyObject;
2924 PyObject *valObject;
2925 Py_ssize_t iter = 0;
2926
2927 d = dict_alloc();
2928 if (d == NULL)
2929 {
2930 PyErr_NoMemory();
2931 return -1;
2932 }
2933
2934 tv->v_type = VAR_DICT;
2935 tv->vval.v_dict = d;
2936
2937 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
2938 {
2939 DICTKEY_DECL
2940
2941 if (keyObject == NULL)
2942 return -1;
2943 if (valObject == NULL)
2944 return -1;
2945
2946 DICTKEY_GET_NOTEMPTY(-1)
2947
2948 di = dictitem_alloc(key);
2949
2950 DICTKEY_UNREF
2951
2952 if (di == NULL)
2953 {
2954 PyErr_NoMemory();
2955 return -1;
2956 }
2957 di->di_tv.v_lock = 0;
2958
2959 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
2960 {
2961 vim_free(di);
2962 return -1;
2963 }
2964 if (dict_add(d, di) == FAIL)
2965 {
2966 vim_free(di);
2967 PyErr_SetVim(_("failed to add key to dictionary"));
2968 return -1;
2969 }
2970 }
2971 return 0;
2972}
2973
2974 static int
2975pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2976{
2977 dict_T *d;
2978 char_u *key;
2979 dictitem_T *di;
2980 PyObject *list;
2981 PyObject *litem;
2982 PyObject *keyObject;
2983 PyObject *valObject;
2984 Py_ssize_t lsize;
2985
2986 d = dict_alloc();
2987 if (d == NULL)
2988 {
2989 PyErr_NoMemory();
2990 return -1;
2991 }
2992
2993 tv->v_type = VAR_DICT;
2994 tv->vval.v_dict = d;
2995
2996 list = PyMapping_Items(obj);
2997 if (list == NULL)
2998 return -1;
2999 lsize = PyList_Size(list);
3000 while (lsize--)
3001 {
3002 DICTKEY_DECL
3003
3004 litem = PyList_GetItem(list, lsize);
3005 if (litem == NULL)
3006 {
3007 Py_DECREF(list);
3008 return -1;
3009 }
3010
3011 keyObject = PyTuple_GetItem(litem, 0);
3012 if (keyObject == NULL)
3013 {
3014 Py_DECREF(list);
3015 Py_DECREF(litem);
3016 return -1;
3017 }
3018
3019 DICTKEY_GET_NOTEMPTY(-1)
3020
3021 valObject = PyTuple_GetItem(litem, 1);
3022 if (valObject == NULL)
3023 {
3024 Py_DECREF(list);
3025 Py_DECREF(litem);
3026 return -1;
3027 }
3028
3029 di = dictitem_alloc(key);
3030
3031 DICTKEY_UNREF
3032
3033 if (di == NULL)
3034 {
3035 Py_DECREF(list);
3036 Py_DECREF(litem);
3037 PyErr_NoMemory();
3038 return -1;
3039 }
3040 di->di_tv.v_lock = 0;
3041
3042 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3043 {
3044 vim_free(di);
3045 Py_DECREF(list);
3046 Py_DECREF(litem);
3047 return -1;
3048 }
3049 if (dict_add(d, di) == FAIL)
3050 {
3051 vim_free(di);
3052 Py_DECREF(list);
3053 Py_DECREF(litem);
3054 PyErr_SetVim(_("failed to add key to dictionary"));
3055 return -1;
3056 }
3057 Py_DECREF(litem);
3058 }
3059 Py_DECREF(list);
3060 return 0;
3061}
3062
3063 static int
3064pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3065{
3066 list_T *l;
3067
3068 l = list_alloc();
3069 if (l == NULL)
3070 {
3071 PyErr_NoMemory();
3072 return -1;
3073 }
3074
3075 tv->v_type = VAR_LIST;
3076 tv->vval.v_list = l;
3077
3078 if (list_py_concat(l, obj, lookupDict) == -1)
3079 return -1;
3080
3081 return 0;
3082}
3083
3084 static int
3085pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3086{
3087 PyObject *iterator = PyObject_GetIter(obj);
3088 PyObject *item;
3089 list_T *l;
3090 listitem_T *li;
3091
3092 l = list_alloc();
3093
3094 if (l == NULL)
3095 {
3096 PyErr_NoMemory();
3097 return -1;
3098 }
3099
3100 tv->vval.v_list = l;
3101 tv->v_type = VAR_LIST;
3102
3103
3104 if (iterator == NULL)
3105 return -1;
3106
3107 while ((item = PyIter_Next(obj)))
3108 {
3109 li = listitem_alloc();
3110 if (li == NULL)
3111 {
3112 PyErr_NoMemory();
3113 return -1;
3114 }
3115 li->li_tv.v_lock = 0;
3116
3117 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3118 return -1;
3119
3120 list_append(l, li);
3121
3122 Py_DECREF(item);
3123 }
3124
3125 Py_DECREF(iterator);
3126 return 0;
3127}
3128
Bram Moolenaardb913952012-06-29 12:54:53 +02003129typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3130
3131 static int
3132convert_dl(PyObject *obj, typval_T *tv,
3133 pytotvfunc py_to_tv, PyObject *lookupDict)
3134{
3135 PyObject *capsule;
3136 char hexBuf[sizeof(void *) * 2 + 3];
3137
3138 sprintf(hexBuf, "%p", obj);
3139
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003140# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003141 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003142# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003143 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003144# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003145 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003146 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003147# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003148 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003149# else
3150 capsule = PyCObject_FromVoidPtr(tv, NULL);
3151# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003152 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3153 Py_DECREF(capsule);
3154 if (py_to_tv(obj, tv, lookupDict) == -1)
3155 {
3156 tv->v_type = VAR_UNKNOWN;
3157 return -1;
3158 }
3159 /* As we are not using copy_tv which increments reference count we must
3160 * do it ourself. */
3161 switch(tv->v_type)
3162 {
3163 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3164 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3165 }
3166 }
3167 else
3168 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003169 typval_T *v;
3170
3171# ifdef PY_USE_CAPSULE
3172 v = PyCapsule_GetPointer(capsule, NULL);
3173# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003174 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003175# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003176 copy_tv(v, tv);
3177 }
3178 return 0;
3179}
3180
3181 static int
3182ConvertFromPyObject(PyObject *obj, typval_T *tv)
3183{
3184 PyObject *lookup_dict;
3185 int r;
3186
3187 lookup_dict = PyDict_New();
3188 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3189 Py_DECREF(lookup_dict);
3190 return r;
3191}
3192
3193 static int
3194_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3195{
3196 if (obj->ob_type == &DictionaryType)
3197 {
3198 tv->v_type = VAR_DICT;
3199 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3200 ++tv->vval.v_dict->dv_refcount;
3201 }
3202 else if (obj->ob_type == &ListType)
3203 {
3204 tv->v_type = VAR_LIST;
3205 tv->vval.v_list = (((ListObject *)(obj))->list);
3206 ++tv->vval.v_list->lv_refcount;
3207 }
3208 else if (obj->ob_type == &FunctionType)
3209 {
3210 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3211 return -1;
3212
3213 tv->v_type = VAR_FUNC;
3214 func_ref(tv->vval.v_string);
3215 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003216 else if (PyBytes_Check(obj))
3217 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003218 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003219
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003220 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3221 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003222 if (result == NULL)
3223 return -1;
3224
3225 if (set_string_copy(result, tv) == -1)
3226 return -1;
3227
3228 tv->v_type = VAR_STRING;
3229 }
3230 else if (PyUnicode_Check(obj))
3231 {
3232 PyObject *bytes;
3233 char_u *result;
3234
Bram Moolenaardb913952012-06-29 12:54:53 +02003235 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3236 if (bytes == NULL)
3237 return -1;
3238
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003239 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3240 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003241 if (result == NULL)
3242 return -1;
3243
3244 if (set_string_copy(result, tv) == -1)
3245 {
3246 Py_XDECREF(bytes);
3247 return -1;
3248 }
3249 Py_XDECREF(bytes);
3250
3251 tv->v_type = VAR_STRING;
3252 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003253#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003254 else if (PyInt_Check(obj))
3255 {
3256 tv->v_type = VAR_NUMBER;
3257 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3258 }
3259#endif
3260 else if (PyLong_Check(obj))
3261 {
3262 tv->v_type = VAR_NUMBER;
3263 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3264 }
3265 else if (PyDict_Check(obj))
3266 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3267#ifdef FEAT_FLOAT
3268 else if (PyFloat_Check(obj))
3269 {
3270 tv->v_type = VAR_FLOAT;
3271 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3272 }
3273#endif
3274 else if (PyIter_Check(obj))
3275 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3276 else if (PySequence_Check(obj))
3277 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3278 else if (PyMapping_Check(obj))
3279 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3280 else
3281 {
3282 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
3283 return -1;
3284 }
3285 return 0;
3286}
3287
3288 static PyObject *
3289ConvertToPyObject(typval_T *tv)
3290{
3291 if (tv == NULL)
3292 {
3293 PyErr_SetVim(_("NULL reference passed"));
3294 return NULL;
3295 }
3296 switch (tv->v_type)
3297 {
3298 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003299 return PyBytes_FromString(tv->vval.v_string == NULL
3300 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003301 case VAR_NUMBER:
3302 return PyLong_FromLong((long) tv->vval.v_number);
3303#ifdef FEAT_FLOAT
3304 case VAR_FLOAT:
3305 return PyFloat_FromDouble((double) tv->vval.v_float);
3306#endif
3307 case VAR_LIST:
3308 return ListNew(tv->vval.v_list);
3309 case VAR_DICT:
3310 return DictionaryNew(tv->vval.v_dict);
3311 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003312 return FunctionNew(tv->vval.v_string == NULL
3313 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003314 case VAR_UNKNOWN:
3315 Py_INCREF(Py_None);
3316 return Py_None;
3317 default:
3318 PyErr_SetVim(_("internal error: invalid value type"));
3319 return NULL;
3320 }
3321}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003322
3323typedef struct
3324{
3325 PyObject_HEAD
3326} CurrentObject;
3327static PyTypeObject CurrentType;
3328
3329 static void
3330init_structs(void)
3331{
3332 vim_memset(&OutputType, 0, sizeof(OutputType));
3333 OutputType.tp_name = "vim.message";
3334 OutputType.tp_basicsize = sizeof(OutputObject);
3335 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3336 OutputType.tp_doc = "vim message object";
3337 OutputType.tp_methods = OutputMethods;
3338#if PY_MAJOR_VERSION >= 3
3339 OutputType.tp_getattro = OutputGetattro;
3340 OutputType.tp_setattro = OutputSetattro;
3341 OutputType.tp_alloc = call_PyType_GenericAlloc;
3342 OutputType.tp_new = call_PyType_GenericNew;
3343 OutputType.tp_free = call_PyObject_Free;
3344#else
3345 OutputType.tp_getattr = OutputGetattr;
3346 OutputType.tp_setattr = OutputSetattr;
3347#endif
3348
3349 vim_memset(&BufferType, 0, sizeof(BufferType));
3350 BufferType.tp_name = "vim.buffer";
3351 BufferType.tp_basicsize = sizeof(BufferType);
3352 BufferType.tp_dealloc = BufferDestructor;
3353 BufferType.tp_repr = BufferRepr;
3354 BufferType.tp_as_sequence = &BufferAsSeq;
3355 BufferType.tp_as_mapping = &BufferAsMapping;
3356 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3357 BufferType.tp_doc = "vim buffer object";
3358 BufferType.tp_methods = BufferMethods;
3359#if PY_MAJOR_VERSION >= 3
3360 BufferType.tp_getattro = BufferGetattro;
3361 BufferType.tp_alloc = call_PyType_GenericAlloc;
3362 BufferType.tp_new = call_PyType_GenericNew;
3363 BufferType.tp_free = call_PyObject_Free;
3364#else
3365 BufferType.tp_getattr = BufferGetattr;
3366#endif
3367
3368 vim_memset(&WindowType, 0, sizeof(WindowType));
3369 WindowType.tp_name = "vim.window";
3370 WindowType.tp_basicsize = sizeof(WindowObject);
3371 WindowType.tp_dealloc = WindowDestructor;
3372 WindowType.tp_repr = WindowRepr;
3373 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3374 WindowType.tp_doc = "vim Window object";
3375 WindowType.tp_methods = WindowMethods;
3376#if PY_MAJOR_VERSION >= 3
3377 WindowType.tp_getattro = WindowGetattro;
3378 WindowType.tp_setattro = WindowSetattro;
3379 WindowType.tp_alloc = call_PyType_GenericAlloc;
3380 WindowType.tp_new = call_PyType_GenericNew;
3381 WindowType.tp_free = call_PyObject_Free;
3382#else
3383 WindowType.tp_getattr = WindowGetattr;
3384 WindowType.tp_setattr = WindowSetattr;
3385#endif
3386
3387 vim_memset(&BufListType, 0, sizeof(BufListType));
3388 BufListType.tp_name = "vim.bufferlist";
3389 BufListType.tp_basicsize = sizeof(BufListObject);
3390 BufListType.tp_as_sequence = &BufListAsSeq;
3391 BufListType.tp_flags = Py_TPFLAGS_DEFAULT;
3392 BufferType.tp_doc = "vim buffer list";
3393
3394 vim_memset(&WinListType, 0, sizeof(WinListType));
3395 WinListType.tp_name = "vim.windowlist";
3396 WinListType.tp_basicsize = sizeof(WinListType);
3397 WinListType.tp_as_sequence = &WinListAsSeq;
3398 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3399 WinListType.tp_doc = "vim window list";
3400
3401 vim_memset(&RangeType, 0, sizeof(RangeType));
3402 RangeType.tp_name = "vim.range";
3403 RangeType.tp_basicsize = sizeof(RangeObject);
3404 RangeType.tp_dealloc = RangeDestructor;
3405 RangeType.tp_repr = RangeRepr;
3406 RangeType.tp_as_sequence = &RangeAsSeq;
3407 RangeType.tp_as_mapping = &RangeAsMapping;
3408 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3409 RangeType.tp_doc = "vim Range object";
3410 RangeType.tp_methods = RangeMethods;
3411#if PY_MAJOR_VERSION >= 3
3412 RangeType.tp_getattro = RangeGetattro;
3413 RangeType.tp_alloc = call_PyType_GenericAlloc;
3414 RangeType.tp_new = call_PyType_GenericNew;
3415 RangeType.tp_free = call_PyObject_Free;
3416#else
3417 RangeType.tp_getattr = RangeGetattr;
3418#endif
3419
3420 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3421 CurrentType.tp_name = "vim.currentdata";
3422 CurrentType.tp_basicsize = sizeof(CurrentObject);
3423 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3424 CurrentType.tp_doc = "vim current object";
3425#if PY_MAJOR_VERSION >= 3
3426 CurrentType.tp_getattro = CurrentGetattro;
3427 CurrentType.tp_setattro = CurrentSetattro;
3428#else
3429 CurrentType.tp_getattr = CurrentGetattr;
3430 CurrentType.tp_setattr = CurrentSetattr;
3431#endif
3432
3433 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3434 DictionaryType.tp_name = "vim.dictionary";
3435 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3436 DictionaryType.tp_dealloc = DictionaryDestructor;
3437 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3438 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3439 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3440 DictionaryType.tp_methods = DictionaryMethods;
3441#if PY_MAJOR_VERSION >= 3
3442 DictionaryType.tp_getattro = DictionaryGetattro;
3443 DictionaryType.tp_setattro = DictionarySetattro;
3444#else
3445 DictionaryType.tp_getattr = DictionaryGetattr;
3446 DictionaryType.tp_setattr = DictionarySetattr;
3447#endif
3448
3449 vim_memset(&ListType, 0, sizeof(ListType));
3450 ListType.tp_name = "vim.list";
3451 ListType.tp_dealloc = ListDestructor;
3452 ListType.tp_basicsize = sizeof(ListObject);
3453 ListType.tp_as_sequence = &ListAsSeq;
3454 ListType.tp_as_mapping = &ListAsMapping;
3455 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3456 ListType.tp_doc = "list pushing modifications to vim structure";
3457 ListType.tp_methods = ListMethods;
3458#if PY_MAJOR_VERSION >= 3
3459 ListType.tp_getattro = ListGetattro;
3460 ListType.tp_setattro = ListSetattro;
3461#else
3462 ListType.tp_getattr = ListGetattr;
3463 ListType.tp_setattr = ListSetattr;
3464#endif
3465
3466 vim_memset(&FunctionType, 0, sizeof(FunctionType));
3467 FunctionType.tp_name = "vim.list";
3468 FunctionType.tp_basicsize = sizeof(FunctionObject);
3469 FunctionType.tp_dealloc = FunctionDestructor;
3470 FunctionType.tp_call = FunctionCall;
3471 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3472 FunctionType.tp_doc = "object that calls vim function";
3473 FunctionType.tp_methods = FunctionMethods;
3474#if PY_MAJOR_VERSION >= 3
3475 FunctionType.tp_getattro = FunctionGetattro;
3476#else
3477 FunctionType.tp_getattr = FunctionGetattr;
3478#endif
3479
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003480 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3481 OptionsType.tp_name = "vim.options";
3482 OptionsType.tp_basicsize = sizeof(OptionsObject);
3483 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3484 OptionsType.tp_doc = "object for manipulating options";
3485 OptionsType.tp_as_mapping = &OptionsAsMapping;
3486 OptionsType.tp_dealloc = OptionsDestructor;
3487
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003488#if PY_MAJOR_VERSION >= 3
3489 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3490 vimmodule.m_name = "vim";
3491 vimmodule.m_doc = "Vim Python interface\n";
3492 vimmodule.m_size = -1;
3493 vimmodule.m_methods = VimMethods;
3494#endif
3495}