blob: f20f3ff5bf80c64a51eeac34fdbe7030a286b40f [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/*
10 * Python extensions by Paul Moore, David Leonard, Roland Puntaier.
11 *
12 * Common code for if_python.c and if_python3.c.
13 */
14
Bram Moolenaarc1a995d2012-08-08 16:05:07 +020015#if PY_VERSION_HEX < 0x02050000
16typedef int Py_ssize_t; /* Python 2.4 and earlier don't have this type. */
17#endif
18
Bram Moolenaar91805fc2011-06-26 04:01:44 +020019#ifdef FEAT_MBYTE
20# define ENC_OPT p_enc
21#else
22# define ENC_OPT "latin1"
23#endif
24
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020025/*
26 * obtain a lock on the Vim data structures
27 */
28 static void
29Python_Lock_Vim(void)
30{
31}
32
33/*
34 * release a lock on the Vim data structures
35 */
36 static void
37Python_Release_Vim(void)
38{
39}
40
41/* Output object definition
42 */
43
44static PyObject *OutputWrite(PyObject *, PyObject *);
45static PyObject *OutputWritelines(PyObject *, PyObject *);
Bram Moolenaara29a37d2011-03-22 15:47:44 +010046static PyObject *OutputFlush(PyObject *, PyObject *);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020047
Bram Moolenaar2eea1982010-09-21 16:49:37 +020048/* Function to write a line, points to either msg() or emsg(). */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020049typedef void (*writefn)(char_u *);
50static void writer(writefn fn, char_u *str, PyInt n);
51
52typedef struct
53{
54 PyObject_HEAD
55 long softspace;
56 long error;
57} OutputObject;
58
59static struct PyMethodDef OutputMethods[] = {
60 /* name, function, calling, documentation */
Bram Moolenaara29a37d2011-03-22 15:47:44 +010061 {"write", OutputWrite, 1, ""},
62 {"writelines", OutputWritelines, 1, ""},
Bram Moolenaar2afa3232012-06-29 16:28:28 +020063 {"flush", OutputFlush, 1, ""},
Bram Moolenaara29a37d2011-03-22 15:47:44 +010064 { NULL, NULL, 0, NULL}
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020065};
66
Bram Moolenaarca8a4df2010-07-31 19:54:14 +020067#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
68
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020069/*************/
70
71/* Output buffer management
72 */
73
Bram Moolenaar77045652012-09-21 13:46:06 +020074 static int
75OutputSetattr(PyObject *self, char *name, PyObject *val)
76{
77 if (val == NULL)
78 {
79 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
80 return -1;
81 }
82
83 if (strcmp(name, "softspace") == 0)
84 {
85 if (!PyInt_Check(val))
86 {
87 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
88 return -1;
89 }
90
91 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
92 return 0;
93 }
94
95 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
96 return -1;
97}
98
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020099 static PyObject *
100OutputWrite(PyObject *self, PyObject *args)
101{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200102 Py_ssize_t len = 0;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200103 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200104 int error = ((OutputObject *)(self))->error;
105
Bram Moolenaar27564802011-09-07 19:30:21 +0200106 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200107 return NULL;
108
109 Py_BEGIN_ALLOW_THREADS
110 Python_Lock_Vim();
111 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
112 Python_Release_Vim();
113 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200114 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200115
116 Py_INCREF(Py_None);
117 return Py_None;
118}
119
120 static PyObject *
121OutputWritelines(PyObject *self, PyObject *args)
122{
123 PyInt n;
124 PyInt i;
125 PyObject *list;
126 int error = ((OutputObject *)(self))->error;
127
128 if (!PyArg_ParseTuple(args, "O", &list))
129 return NULL;
130 Py_INCREF(list);
131
Bram Moolenaardb913952012-06-29 12:54:53 +0200132 if (!PyList_Check(list))
133 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200134 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
135 Py_DECREF(list);
136 return NULL;
137 }
138
139 n = PyList_Size(list);
140
141 for (i = 0; i < n; ++i)
142 {
143 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200144 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200145 PyInt len;
146
Bram Moolenaardb913952012-06-29 12:54:53 +0200147 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
148 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200149 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
150 Py_DECREF(list);
151 return NULL;
152 }
153
154 Py_BEGIN_ALLOW_THREADS
155 Python_Lock_Vim();
156 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
157 Python_Release_Vim();
158 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200159 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200160 }
161
162 Py_DECREF(list);
163 Py_INCREF(Py_None);
164 return Py_None;
165}
166
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100167 static PyObject *
168OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
169{
170 /* do nothing */
171 Py_INCREF(Py_None);
172 return Py_None;
173}
174
175
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200176/* Buffer IO, we write one whole line at a time. */
177static garray_T io_ga = {0, 0, 1, 80, NULL};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200178static writefn old_fn = NULL;
179
180 static void
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200181PythonIO_Flush(void)
182{
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200183 if (old_fn != NULL && io_ga.ga_len > 0)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200184 {
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200185 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
186 old_fn((char_u *)io_ga.ga_data);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200187 }
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200188 io_ga.ga_len = 0;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200189}
190
191 static void
192writer(writefn fn, char_u *str, PyInt n)
193{
194 char_u *ptr;
195
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200196 /* Flush when switching output function. */
197 if (fn != old_fn)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200198 PythonIO_Flush();
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200199 old_fn = fn;
200
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200201 /* Write each NL separated line. Text after the last NL is kept for
202 * writing later. */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200203 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
204 {
205 PyInt len = ptr - str;
206
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200207 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200208 break;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200209
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200210 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
211 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
212 fn((char_u *)io_ga.ga_data);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200213 str = ptr + 1;
214 n -= len + 1;
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200215 io_ga.ga_len = 0;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200216 }
217
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200218 /* Put the remaining text into io_ga for later printing. */
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200219 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200220 {
221 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200222 io_ga.ga_len += (int)n;
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200223 }
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200224}
225
226/***************/
227
228static PyTypeObject OutputType;
229
230static OutputObject Output =
231{
232 PyObject_HEAD_INIT(&OutputType)
233 0,
234 0
235};
236
237static OutputObject Error =
238{
239 PyObject_HEAD_INIT(&OutputType)
240 0,
241 1
242};
243
244 static int
245PythonIO_Init_io(void)
246{
247 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
248 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
249
250 if (PyErr_Occurred())
251 {
252 EMSG(_("E264: Python: Error initialising I/O objects"));
253 return -1;
254 }
255
256 return 0;
257}
258
259
260static PyObject *VimError;
261
262/* Check to see whether a Vim error has been reported, or a keyboard
263 * interrupt has been detected.
264 */
265 static int
266VimErrorCheck(void)
267{
268 if (got_int)
269 {
270 PyErr_SetNone(PyExc_KeyboardInterrupt);
271 return 1;
272 }
273 else if (did_emsg && !PyErr_Occurred())
274 {
275 PyErr_SetNone(VimError);
276 return 1;
277 }
278
279 return 0;
280}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200281
282/* Vim module - Implementation
283 */
284 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
533typedef struct
534{
535 PyObject_HEAD
536 buf_T *buf;
Bram Moolenaardb913952012-06-29 12:54:53 +0200537} BufferObject;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200538
539#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
540
541/*
542 * Buffer list object - Implementation
543 */
544
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200545typedef struct
546{
547 PyObject_HEAD
548} BufListObject;
549
550static PyTypeObject BufListType;
551static PySequenceMethods WinListAsSeq;
552
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200553 static PyInt
554BufListLength(PyObject *self UNUSED)
555{
556 buf_T *b = firstbuf;
557 PyInt n = 0;
558
559 while (b)
560 {
561 ++n;
562 b = b->b_next;
563 }
564
565 return n;
566}
567
568 static PyObject *
569BufListItem(PyObject *self UNUSED, PyInt n)
570{
571 buf_T *b;
572
573 for (b = firstbuf; b; b = b->b_next, --n)
574 {
575 if (n == 0)
576 return BufferNew(b);
577 }
578
579 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
580 return NULL;
581}
582
583typedef struct
584{
585 PyObject_HEAD
586 win_T *win;
587} WindowObject;
588
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200589static struct PyMethodDef WindowMethods[] = {
590 /* name, function, calling, documentation */
591 { NULL, NULL, 0, NULL }
592};
593
Bram Moolenaardb913952012-06-29 12:54:53 +0200594static int ConvertFromPyObject(PyObject *, typval_T *);
595static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
596
597typedef struct pylinkedlist_S {
598 struct pylinkedlist_S *pll_next;
599 struct pylinkedlist_S *pll_prev;
600 PyObject *pll_obj;
601} pylinkedlist_T;
602
603static pylinkedlist_T *lastdict = NULL;
604static pylinkedlist_T *lastlist = NULL;
605
606 static void
607pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
608{
609 if (ref->pll_prev == NULL)
610 {
611 if (ref->pll_next == NULL)
612 {
613 *last = NULL;
614 return;
615 }
616 }
617 else
618 ref->pll_prev->pll_next = ref->pll_next;
619
620 if (ref->pll_next == NULL)
621 *last = ref->pll_prev;
622 else
623 ref->pll_next->pll_prev = ref->pll_prev;
624}
625
626 static void
627pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
628{
629 if (*last == NULL)
630 ref->pll_prev = NULL;
631 else
632 {
633 (*last)->pll_next = ref;
634 ref->pll_prev = *last;
635 }
636 ref->pll_next = NULL;
637 ref->pll_obj = self;
638 *last = ref;
639}
640
641static PyTypeObject DictionaryType;
642
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200643#define DICTKEY_GET_NOTEMPTY(err) \
644 DICTKEY_GET(err) \
645 if (*key == NUL) \
646 { \
647 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
648 return err; \
649 }
650
Bram Moolenaardb913952012-06-29 12:54:53 +0200651typedef struct
652{
653 PyObject_HEAD
654 dict_T *dict;
655 pylinkedlist_T ref;
656} DictionaryObject;
657
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200658static PyInt DictionaryAssItem(PyObject *, PyObject *, PyObject *);
659static PyInt DictionaryLength(PyObject *);
660static PyObject *DictionaryItem(PyObject *, PyObject *);
661
662static PyMappingMethods DictionaryAsMapping = {
663 (lenfunc) DictionaryLength,
664 (binaryfunc) DictionaryItem,
665 (objobjargproc) DictionaryAssItem,
666};
667
Bram Moolenaardb913952012-06-29 12:54:53 +0200668 static PyObject *
669DictionaryNew(dict_T *dict)
670{
671 DictionaryObject *self;
672
673 self = PyObject_NEW(DictionaryObject, &DictionaryType);
674 if (self == NULL)
675 return NULL;
676 self->dict = dict;
677 ++dict->dv_refcount;
678
679 pyll_add((PyObject *)(self), &self->ref, &lastdict);
680
681 return (PyObject *)(self);
682}
683
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200684 static void
685DictionaryDestructor(PyObject *self)
686{
687 DictionaryObject *this = ((DictionaryObject *) (self));
688
689 pyll_remove(&this->ref, &lastdict);
690 dict_unref(this->dict);
691
692 DESTRUCTOR_FINISH(self);
693}
694
Bram Moolenaardb913952012-06-29 12:54:53 +0200695 static int
696pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
697{
698 dict_T *d;
699 char_u *key;
700 dictitem_T *di;
701 PyObject *keyObject;
702 PyObject *valObject;
703 Py_ssize_t iter = 0;
704
705 d = dict_alloc();
706 if (d == NULL)
707 {
708 PyErr_NoMemory();
709 return -1;
710 }
711
712 tv->v_type = VAR_DICT;
713 tv->vval.v_dict = d;
714
715 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
716 {
717 DICTKEY_DECL
718
719 if (keyObject == NULL)
720 return -1;
721 if (valObject == NULL)
722 return -1;
723
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200724 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200725
726 di = dictitem_alloc(key);
727
728 DICTKEY_UNREF
729
730 if (di == NULL)
731 {
732 PyErr_NoMemory();
733 return -1;
734 }
735 di->di_tv.v_lock = 0;
736
737 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
738 {
739 vim_free(di);
740 return -1;
741 }
742 if (dict_add(d, di) == FAIL)
743 {
744 vim_free(di);
745 PyErr_SetVim(_("failed to add key to dictionary"));
746 return -1;
747 }
748 }
749 return 0;
750}
751
752 static int
753pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
754{
755 dict_T *d;
756 char_u *key;
757 dictitem_T *di;
758 PyObject *list;
759 PyObject *litem;
760 PyObject *keyObject;
761 PyObject *valObject;
762 Py_ssize_t lsize;
763
764 d = dict_alloc();
765 if (d == NULL)
766 {
767 PyErr_NoMemory();
768 return -1;
769 }
770
771 tv->v_type = VAR_DICT;
772 tv->vval.v_dict = d;
773
774 list = PyMapping_Items(obj);
Bram Moolenaar7a26dd82013-04-24 13:10:41 +0200775 if (list == NULL)
776 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200777 lsize = PyList_Size(list);
778 while (lsize--)
779 {
780 DICTKEY_DECL
781
782 litem = PyList_GetItem(list, lsize);
783 if (litem == NULL)
784 {
785 Py_DECREF(list);
786 return -1;
787 }
788
789 keyObject = PyTuple_GetItem(litem, 0);
790 if (keyObject == NULL)
791 {
792 Py_DECREF(list);
793 Py_DECREF(litem);
794 return -1;
795 }
796
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200797 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200798
799 valObject = PyTuple_GetItem(litem, 1);
800 if (valObject == NULL)
801 {
802 Py_DECREF(list);
803 Py_DECREF(litem);
804 return -1;
805 }
806
807 di = dictitem_alloc(key);
808
809 DICTKEY_UNREF
810
811 if (di == NULL)
812 {
813 Py_DECREF(list);
814 Py_DECREF(litem);
815 PyErr_NoMemory();
816 return -1;
817 }
818 di->di_tv.v_lock = 0;
819
820 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
821 {
822 vim_free(di);
823 Py_DECREF(list);
824 Py_DECREF(litem);
825 return -1;
826 }
827 if (dict_add(d, di) == FAIL)
828 {
829 vim_free(di);
830 Py_DECREF(list);
831 Py_DECREF(litem);
832 PyErr_SetVim(_("failed to add key to dictionary"));
833 return -1;
834 }
835 Py_DECREF(litem);
836 }
837 Py_DECREF(list);
838 return 0;
839}
840
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200841 static int
842DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200843{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200844 DictionaryObject *this = (DictionaryObject *)(self);
845
Bram Moolenaar66b79852012-09-21 14:00:35 +0200846 if (val == NULL)
847 {
848 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
849 return -1;
850 }
851
852 if (strcmp(name, "locked") == 0)
853 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200854 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200855 {
856 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
857 return -1;
858 }
859 else
860 {
861 if (!PyBool_Check(val))
862 {
863 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
864 return -1;
865 }
866
867 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200868 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200869 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200870 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200871 }
872 return 0;
873 }
874 else
875 {
876 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
877 return -1;
878 }
879}
880
881 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200882DictionaryLength(PyObject *self)
883{
884 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
885}
886
887 static PyObject *
888DictionaryItem(PyObject *self, PyObject *keyObject)
889{
890 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200891 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200892 DICTKEY_DECL
893
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200894 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200895
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200896 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
897
Bram Moolenaar696c2112012-09-21 13:43:14 +0200898 DICTKEY_UNREF
899
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200900 if (di == NULL)
901 {
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200902 PyErr_SetString(PyExc_KeyError, _("no such key in dictionary"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200903 return NULL;
904 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200905
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200906 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200907}
908
909 static PyInt
910DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
911{
912 char_u *key;
913 typval_T tv;
914 dict_T *d = ((DictionaryObject *)(self))->dict;
915 dictitem_T *di;
916 DICTKEY_DECL
917
918 if (d->dv_lock)
919 {
920 PyErr_SetVim(_("dict is locked"));
921 return -1;
922 }
923
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200924 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200925
926 di = dict_find(d, key, -1);
927
928 if (valObject == NULL)
929 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200930 hashitem_T *hi;
931
Bram Moolenaardb913952012-06-29 12:54:53 +0200932 if (di == NULL)
933 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200934 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200935 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
936 return -1;
937 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200938 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200939 hash_remove(&d->dv_hashtab, hi);
940 dictitem_free(di);
941 return 0;
942 }
943
944 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200945 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200946
947 if (di == NULL)
948 {
949 di = dictitem_alloc(key);
950 if (di == NULL)
951 {
952 PyErr_NoMemory();
953 return -1;
954 }
955 di->di_tv.v_lock = 0;
956
957 if (dict_add(d, di) == FAIL)
958 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200959 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200960 vim_free(di);
961 PyErr_SetVim(_("failed to add key to dictionary"));
962 return -1;
963 }
964 }
965 else
966 clear_tv(&di->di_tv);
967
968 DICTKEY_UNREF
969
970 copy_tv(&tv, &di->di_tv);
971 return 0;
972}
973
974 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100975DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200976{
977 dict_T *dict = ((DictionaryObject *)(self))->dict;
978 long_u todo = dict->dv_hashtab.ht_used;
979 Py_ssize_t i = 0;
980 PyObject *r;
981 hashitem_T *hi;
982
983 r = PyList_New(todo);
984 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
985 {
986 if (!HASHITEM_EMPTY(hi))
987 {
988 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
989 --todo;
990 ++i;
991 }
992 }
993 return r;
994}
995
996static struct PyMethodDef DictionaryMethods[] = {
997 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
998 { NULL, NULL, 0, NULL }
999};
1000
1001static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001002static PySequenceMethods ListAsSeq;
1003static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +02001004
1005typedef struct
1006{
1007 PyObject_HEAD
1008 list_T *list;
1009 pylinkedlist_T ref;
1010} ListObject;
1011
1012 static PyObject *
1013ListNew(list_T *list)
1014{
1015 ListObject *self;
1016
1017 self = PyObject_NEW(ListObject, &ListType);
1018 if (self == NULL)
1019 return NULL;
1020 self->list = list;
1021 ++list->lv_refcount;
1022
1023 pyll_add((PyObject *)(self), &self->ref, &lastlist);
1024
1025 return (PyObject *)(self);
1026}
1027
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001028 static void
1029ListDestructor(PyObject *self)
1030{
1031 ListObject *this = (ListObject *)(self);
1032
1033 pyll_remove(&this->ref, &lastlist);
1034 list_unref(this->list);
1035
1036 DESTRUCTOR_FINISH(self);
1037}
1038
Bram Moolenaardb913952012-06-29 12:54:53 +02001039 static int
1040list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
1041{
1042 Py_ssize_t i;
1043 Py_ssize_t lsize = PySequence_Size(obj);
1044 PyObject *litem;
1045 listitem_T *li;
1046
1047 for(i=0; i<lsize; i++)
1048 {
1049 li = listitem_alloc();
1050 if (li == NULL)
1051 {
1052 PyErr_NoMemory();
1053 return -1;
1054 }
1055 li->li_tv.v_lock = 0;
1056
1057 litem = PySequence_GetItem(obj, i);
1058 if (litem == NULL)
1059 return -1;
1060 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
1061 return -1;
1062
1063 list_append(l, li);
1064 }
1065 return 0;
1066}
1067
1068 static int
1069pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
1070{
1071 list_T *l;
1072
1073 l = list_alloc();
1074 if (l == NULL)
1075 {
1076 PyErr_NoMemory();
1077 return -1;
1078 }
1079
1080 tv->v_type = VAR_LIST;
1081 tv->vval.v_list = l;
1082
1083 if (list_py_concat(l, obj, lookupDict) == -1)
1084 return -1;
1085
1086 return 0;
1087}
1088
1089 static int
1090pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
1091{
1092 PyObject *iterator = PyObject_GetIter(obj);
1093 PyObject *item;
1094 list_T *l;
1095 listitem_T *li;
1096
1097 l = list_alloc();
1098
1099 if (l == NULL)
1100 {
1101 PyErr_NoMemory();
1102 return -1;
1103 }
1104
1105 tv->vval.v_list = l;
1106 tv->v_type = VAR_LIST;
1107
1108
1109 if (iterator == NULL)
1110 return -1;
1111
1112 while ((item = PyIter_Next(obj)))
1113 {
1114 li = listitem_alloc();
1115 if (li == NULL)
1116 {
1117 PyErr_NoMemory();
1118 return -1;
1119 }
1120 li->li_tv.v_lock = 0;
1121
1122 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
1123 return -1;
1124
1125 list_append(l, li);
1126
1127 Py_DECREF(item);
1128 }
1129
1130 Py_DECREF(iterator);
1131 return 0;
1132}
1133
1134 static PyInt
1135ListLength(PyObject *self)
1136{
1137 return ((PyInt) (((ListObject *) (self))->list->lv_len));
1138}
1139
1140 static PyObject *
1141ListItem(PyObject *self, Py_ssize_t index)
1142{
1143 listitem_T *li;
1144
1145 if (index>=ListLength(self))
1146 {
1147 PyErr_SetString(PyExc_IndexError, "list index out of range");
1148 return NULL;
1149 }
1150 li = list_find(((ListObject *) (self))->list, (long) index);
1151 if (li == NULL)
1152 {
1153 PyErr_SetVim(_("internal error: failed to get vim list item"));
1154 return NULL;
1155 }
1156 return ConvertToPyObject(&li->li_tv);
1157}
1158
1159#define PROC_RANGE \
1160 if (last < 0) {\
1161 if (last < -size) \
1162 last = 0; \
1163 else \
1164 last += size; \
1165 } \
1166 if (first < 0) \
1167 first = 0; \
1168 if (first > size) \
1169 first = size; \
1170 if (last > size) \
1171 last = size;
1172
1173 static PyObject *
1174ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
1175{
1176 PyInt i;
1177 PyInt size = ListLength(self);
1178 PyInt n;
1179 PyObject *list;
1180 int reversed = 0;
1181
1182 PROC_RANGE
1183 if (first >= last)
1184 first = last;
1185
1186 n = last-first;
1187 list = PyList_New(n);
1188 if (list == NULL)
1189 return NULL;
1190
1191 for (i = 0; i < n; ++i)
1192 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +02001193 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +02001194 if (item == NULL)
1195 {
1196 Py_DECREF(list);
1197 return NULL;
1198 }
1199
1200 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
1201 {
1202 Py_DECREF(item);
1203 Py_DECREF(list);
1204 return NULL;
1205 }
1206 }
1207
1208 return list;
1209}
1210
1211 static int
1212ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1213{
1214 typval_T tv;
1215 list_T *l = ((ListObject *) (self))->list;
1216 listitem_T *li;
1217 Py_ssize_t length = ListLength(self);
1218
1219 if (l->lv_lock)
1220 {
1221 PyErr_SetVim(_("list is locked"));
1222 return -1;
1223 }
1224 if (index>length || (index==length && obj==NULL))
1225 {
1226 PyErr_SetString(PyExc_IndexError, "list index out of range");
1227 return -1;
1228 }
1229
1230 if (obj == NULL)
1231 {
1232 li = list_find(l, (long) index);
1233 list_remove(l, li, li);
1234 clear_tv(&li->li_tv);
1235 vim_free(li);
1236 return 0;
1237 }
1238
1239 if (ConvertFromPyObject(obj, &tv) == -1)
1240 return -1;
1241
1242 if (index == length)
1243 {
1244 if (list_append_tv(l, &tv) == FAIL)
1245 {
1246 PyErr_SetVim(_("Failed to add item to list"));
1247 return -1;
1248 }
1249 }
1250 else
1251 {
1252 li = list_find(l, (long) index);
1253 clear_tv(&li->li_tv);
1254 copy_tv(&tv, &li->li_tv);
1255 }
1256 return 0;
1257}
1258
1259 static int
1260ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1261{
1262 PyInt size = ListLength(self);
1263 Py_ssize_t i;
1264 Py_ssize_t lsize;
1265 PyObject *litem;
1266 listitem_T *li;
1267 listitem_T *next;
1268 typval_T v;
1269 list_T *l = ((ListObject *) (self))->list;
1270
1271 if (l->lv_lock)
1272 {
1273 PyErr_SetVim(_("list is locked"));
1274 return -1;
1275 }
1276
1277 PROC_RANGE
1278
1279 if (first == size)
1280 li = NULL;
1281 else
1282 {
1283 li = list_find(l, (long) first);
1284 if (li == NULL)
1285 {
1286 PyErr_SetVim(_("internal error: no vim list item"));
1287 return -1;
1288 }
1289 if (last > first)
1290 {
1291 i = last - first;
1292 while (i-- && li != NULL)
1293 {
1294 next = li->li_next;
1295 listitem_remove(l, li);
1296 li = next;
1297 }
1298 }
1299 }
1300
1301 if (obj == NULL)
1302 return 0;
1303
1304 if (!PyList_Check(obj))
1305 {
1306 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1307 return -1;
1308 }
1309
1310 lsize = PyList_Size(obj);
1311
1312 for(i=0; i<lsize; i++)
1313 {
1314 litem = PyList_GetItem(obj, i);
1315 if (litem == NULL)
1316 return -1;
1317 if (ConvertFromPyObject(litem, &v) == -1)
1318 return -1;
1319 if (list_insert_tv(l, &v, li) == FAIL)
1320 {
1321 PyErr_SetVim(_("internal error: failed to add item to list"));
1322 return -1;
1323 }
1324 }
1325 return 0;
1326}
1327
1328 static PyObject *
1329ListConcatInPlace(PyObject *self, PyObject *obj)
1330{
1331 list_T *l = ((ListObject *) (self))->list;
1332 PyObject *lookup_dict;
1333
1334 if (l->lv_lock)
1335 {
1336 PyErr_SetVim(_("list is locked"));
1337 return NULL;
1338 }
1339
1340 if (!PySequence_Check(obj))
1341 {
1342 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1343 return NULL;
1344 }
1345
1346 lookup_dict = PyDict_New();
1347 if (list_py_concat(l, obj, lookup_dict) == -1)
1348 {
1349 Py_DECREF(lookup_dict);
1350 return NULL;
1351 }
1352 Py_DECREF(lookup_dict);
1353
1354 Py_INCREF(self);
1355 return self;
1356}
1357
Bram Moolenaar66b79852012-09-21 14:00:35 +02001358 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001359ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001360{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001361 ListObject *this = (ListObject *)(self);
1362
Bram Moolenaar66b79852012-09-21 14:00:35 +02001363 if (val == NULL)
1364 {
1365 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
1366 return -1;
1367 }
1368
1369 if (strcmp(name, "locked") == 0)
1370 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001371 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001372 {
1373 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
1374 return -1;
1375 }
1376 else
1377 {
1378 if (!PyBool_Check(val))
1379 {
1380 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
1381 return -1;
1382 }
1383
1384 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001385 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001386 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001387 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001388 }
1389 return 0;
1390 }
1391 else
1392 {
1393 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
1394 return -1;
1395 }
1396}
1397
Bram Moolenaardb913952012-06-29 12:54:53 +02001398static struct PyMethodDef ListMethods[] = {
1399 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1400 { NULL, NULL, 0, NULL }
1401};
1402
1403typedef struct
1404{
1405 PyObject_HEAD
1406 char_u *name;
1407} FunctionObject;
1408
1409static PyTypeObject FunctionType;
1410
1411 static PyObject *
1412FunctionNew(char_u *name)
1413{
1414 FunctionObject *self;
1415
1416 self = PyObject_NEW(FunctionObject, &FunctionType);
1417 if (self == NULL)
1418 return NULL;
1419 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1420 if (self->name == NULL)
1421 {
1422 PyErr_NoMemory();
1423 return NULL;
1424 }
1425 STRCPY(self->name, name);
1426 func_ref(name);
1427 return (PyObject *)(self);
1428}
1429
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001430 static void
1431FunctionDestructor(PyObject *self)
1432{
1433 FunctionObject *this = (FunctionObject *) (self);
1434
1435 func_unref(this->name);
1436 PyMem_Del(this->name);
1437
1438 DESTRUCTOR_FINISH(self);
1439}
1440
Bram Moolenaardb913952012-06-29 12:54:53 +02001441 static PyObject *
1442FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1443{
1444 FunctionObject *this = (FunctionObject *)(self);
1445 char_u *name = this->name;
1446 typval_T args;
1447 typval_T selfdicttv;
1448 typval_T rettv;
1449 dict_T *selfdict = NULL;
1450 PyObject *selfdictObject;
1451 PyObject *result;
1452 int error;
1453
1454 if (ConvertFromPyObject(argsObject, &args) == -1)
1455 return NULL;
1456
1457 if (kwargs != NULL)
1458 {
1459 selfdictObject = PyDict_GetItemString(kwargs, "self");
1460 if (selfdictObject != NULL)
1461 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001462 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001463 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001464 PyErr_SetString(PyExc_TypeError,
1465 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001466 clear_tv(&args);
1467 return NULL;
1468 }
1469 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1470 return NULL;
1471 selfdict = selfdicttv.vval.v_dict;
1472 }
1473 }
1474
1475 error = func_call(name, &args, selfdict, &rettv);
1476 if (error != OK)
1477 {
1478 result = NULL;
1479 PyErr_SetVim(_("failed to run function"));
1480 }
1481 else
1482 result = ConvertToPyObject(&rettv);
1483
1484 /* FIXME Check what should really be cleared. */
1485 clear_tv(&args);
1486 clear_tv(&rettv);
1487 /*
1488 * if (selfdict!=NULL)
1489 * clear_tv(selfdicttv);
1490 */
1491
1492 return result;
1493}
1494
1495static struct PyMethodDef FunctionMethods[] = {
1496 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1497 { NULL, NULL, 0, NULL }
1498};
1499
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001500/*
1501 * Options object
1502 */
1503
1504static PyTypeObject OptionsType;
1505
1506typedef int (*checkfun)(void *);
1507
1508typedef struct
1509{
1510 PyObject_HEAD
1511 int opt_type;
1512 void *from;
1513 checkfun Check;
1514 PyObject *fromObj;
1515} OptionsObject;
1516
1517 static PyObject *
1518OptionsItem(OptionsObject *this, PyObject *keyObject)
1519{
1520 char_u *key;
1521 int flags;
1522 long numval;
1523 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001524 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001525
1526 if (this->Check(this->from))
1527 return NULL;
1528
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001529 DICTKEY_GET_NOTEMPTY(NULL)
1530
1531 flags = get_option_value_strict(key, &numval, &stringval,
1532 this->opt_type, this->from);
1533
1534 DICTKEY_UNREF
1535
1536 if (flags == 0)
1537 {
1538 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1539 return NULL;
1540 }
1541
1542 if (flags & SOPT_UNSET)
1543 {
1544 Py_INCREF(Py_None);
1545 return Py_None;
1546 }
1547 else if (flags & SOPT_BOOL)
1548 {
1549 PyObject *r;
1550 r = numval ? Py_True : Py_False;
1551 Py_INCREF(r);
1552 return r;
1553 }
1554 else if (flags & SOPT_NUM)
1555 return PyInt_FromLong(numval);
1556 else if (flags & SOPT_STRING)
1557 {
1558 if (stringval)
1559 return PyBytes_FromString((char *) stringval);
1560 else
1561 {
1562 PyErr_SetString(PyExc_ValueError, "Unable to get option value");
1563 return NULL;
1564 }
1565 }
1566 else
1567 {
1568 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1569 return NULL;
1570 }
1571}
1572
1573 static int
1574set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1575 char_u *key;
1576 int numval;
1577 char_u *stringval;
1578 int opt_flags;
1579 int opt_type;
1580 void *from;
1581{
1582 win_T *save_curwin;
1583 tabpage_T *save_curtab;
1584 aco_save_T aco;
1585 int r = 0;
1586
1587 switch (opt_type)
1588 {
1589 case SREQ_WIN:
1590 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1591 == FAIL)
1592 {
1593 PyErr_SetVim("Problem while switching windows.");
1594 return -1;
1595 }
1596 set_option_value(key, numval, stringval, opt_flags);
1597 restore_win(save_curwin, save_curtab);
1598 break;
1599 case SREQ_BUF:
1600 aucmd_prepbuf(&aco, (buf_T *) from);
1601 set_option_value(key, numval, stringval, opt_flags);
1602 aucmd_restbuf(&aco);
1603 break;
1604 case SREQ_GLOBAL:
1605 set_option_value(key, numval, stringval, opt_flags);
1606 break;
1607 }
1608 return r;
1609}
1610
1611 static int
1612OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1613{
1614 char_u *key;
1615 int flags;
1616 int opt_flags;
1617 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001618 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001619
1620 if (this->Check(this->from))
1621 return -1;
1622
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001623 DICTKEY_GET_NOTEMPTY(-1)
1624
1625 flags = get_option_value_strict(key, NULL, NULL,
1626 this->opt_type, this->from);
1627
1628 DICTKEY_UNREF
1629
1630 if (flags == 0)
1631 {
1632 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1633 return -1;
1634 }
1635
1636 if (valObject == NULL)
1637 {
1638 if (this->opt_type == SREQ_GLOBAL)
1639 {
1640 PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
1641 return -1;
1642 }
1643 else if (!(flags & SOPT_GLOBAL))
1644 {
1645 PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
1646 "global value");
1647 return -1;
1648 }
1649 else
1650 {
1651 unset_global_local_option(key, this->from);
1652 return 0;
1653 }
1654 }
1655
1656 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1657
1658 if (flags & SOPT_BOOL)
1659 {
1660 if (!PyBool_Check(valObject))
1661 {
1662 PyErr_SetString(PyExc_ValueError, "Object must be boolean");
1663 return -1;
1664 }
1665
1666 r = set_option_value_for(key, (valObject == Py_True), NULL, opt_flags,
1667 this->opt_type, this->from);
1668 }
1669 else if (flags & SOPT_NUM)
1670 {
1671 int val;
1672
1673#if PY_MAJOR_VERSION < 3
1674 if (PyInt_Check(valObject))
1675 val = PyInt_AsLong(valObject);
1676 else
1677#endif
1678 if (PyLong_Check(valObject))
1679 val = PyLong_AsLong(valObject);
1680 else
1681 {
1682 PyErr_SetString(PyExc_ValueError, "Object must be integer");
1683 return -1;
1684 }
1685
1686 r = set_option_value_for(key, val, NULL, opt_flags,
1687 this->opt_type, this->from);
1688 }
1689 else
1690 {
1691 char_u *val;
1692 if (PyBytes_Check(valObject))
1693 {
1694
1695 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1696 return -1;
1697 if (val == NULL)
1698 return -1;
1699
1700 val = vim_strsave(val);
1701 }
1702 else if (PyUnicode_Check(valObject))
1703 {
1704 PyObject *bytes;
1705
1706 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1707 if (bytes == NULL)
1708 return -1;
1709
1710 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1711 return -1;
1712 if (val == NULL)
1713 return -1;
1714
1715 val = vim_strsave(val);
1716 Py_XDECREF(bytes);
1717 }
1718 else
1719 {
1720 PyErr_SetString(PyExc_ValueError, "Object must be string");
1721 return -1;
1722 }
1723
1724 r = set_option_value_for(key, 0, val, opt_flags,
1725 this->opt_type, this->from);
1726 vim_free(val);
1727 }
1728
1729 return r;
1730}
1731
1732 static int
1733dummy_check(void *arg UNUSED)
1734{
1735 return 0;
1736}
1737
1738 static PyObject *
1739OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1740{
1741 OptionsObject *self;
1742
1743 self = PyObject_NEW(OptionsObject, &OptionsType);
1744 if (self == NULL)
1745 return NULL;
1746
1747 self->opt_type = opt_type;
1748 self->from = from;
1749 self->Check = Check;
1750 self->fromObj = fromObj;
1751 if (fromObj)
1752 Py_INCREF(fromObj);
1753
1754 return (PyObject *)(self);
1755}
1756
1757 static void
1758OptionsDestructor(PyObject *self)
1759{
1760 if (((OptionsObject *)(self))->fromObj)
1761 Py_DECREF(((OptionsObject *)(self))->fromObj);
1762 DESTRUCTOR_FINISH(self);
1763}
1764
1765static PyMappingMethods OptionsAsMapping = {
1766 (lenfunc) NULL,
1767 (binaryfunc) OptionsItem,
1768 (objobjargproc) OptionsAssItem,
1769};
1770
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001771#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1772
1773 static int
1774CheckWindow(WindowObject *this)
1775{
1776 if (this->win == INVALID_WINDOW_VALUE)
1777 {
1778 PyErr_SetVim(_("attempt to refer to deleted window"));
1779 return -1;
1780 }
1781
1782 return 0;
1783}
1784
Bram Moolenaar971db462013-05-12 18:44:48 +02001785/* Window object
1786 */
1787
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001788static int WindowSetattr(PyObject *, char *, PyObject *);
1789static PyObject *WindowRepr(PyObject *);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001790static PyTypeObject WindowType;
1791
1792 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001793WindowNew(win_T *win)
1794{
1795 /* We need to handle deletion of windows underneath us.
1796 * If we add a "w_python*_ref" field to the win_T structure,
1797 * then we can get at it in win_free() in vim. We then
1798 * need to create only ONE Python object per window - if
1799 * we try to create a second, just INCREF the existing one
1800 * and return it. The (single) Python object referring to
1801 * the window is stored in "w_python*_ref".
1802 * On a win_free() we set the Python object's win_T* field
1803 * to an invalid value. We trap all uses of a window
1804 * object, and reject them if the win_T* field is invalid.
1805 *
1806 * Python2 and Python3 get different fields and different objects:
1807 * w_python_ref and w_python3_ref fields respectively.
1808 */
1809
1810 WindowObject *self;
1811
1812 if (WIN_PYTHON_REF(win))
1813 {
1814 self = WIN_PYTHON_REF(win);
1815 Py_INCREF(self);
1816 }
1817 else
1818 {
1819 self = PyObject_NEW(WindowObject, &WindowType);
1820 if (self == NULL)
1821 return NULL;
1822 self->win = win;
1823 WIN_PYTHON_REF(win) = self;
1824 }
1825
1826 return (PyObject *)(self);
1827}
1828
1829 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001830WindowAttr(WindowObject *this, char *name)
1831{
1832 if (strcmp(name, "buffer") == 0)
1833 return (PyObject *)BufferNew(this->win->w_buffer);
1834 else if (strcmp(name, "cursor") == 0)
1835 {
1836 pos_T *pos = &this->win->w_cursor;
1837
1838 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1839 }
1840 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001841 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001842#ifdef FEAT_WINDOWS
1843 else if (strcmp(name, "row") == 0)
1844 return PyLong_FromLong((long)(this->win->w_winrow));
1845#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001846#ifdef FEAT_VERTSPLIT
1847 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001848 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001849 else if (strcmp(name, "col") == 0)
1850 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001851#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001852 else if (strcmp(name, "vars") == 0)
1853 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001854 else if (strcmp(name, "options") == 0)
1855 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1856 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001857 else if (strcmp(name, "number") == 0)
1858 return PyLong_FromLong((long) get_win_number(this->win));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001859 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001860 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1861 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001862 else
1863 return NULL;
1864}
1865
1866 static void
1867WindowDestructor(PyObject *self)
1868{
1869 WindowObject *this = (WindowObject *)(self);
1870
1871 if (this->win && this->win != INVALID_WINDOW_VALUE)
Bram Moolenaar971db462013-05-12 18:44:48 +02001872 WIN_PYTHON_REF(this->win) = NULL;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001873
1874 DESTRUCTOR_FINISH(self);
1875}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001876
1877 static int
1878WindowSetattr(PyObject *self, char *name, PyObject *val)
1879{
1880 WindowObject *this = (WindowObject *)(self);
1881
1882 if (CheckWindow(this))
1883 return -1;
1884
1885 if (strcmp(name, "buffer") == 0)
1886 {
1887 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1888 return -1;
1889 }
1890 else if (strcmp(name, "cursor") == 0)
1891 {
1892 long lnum;
1893 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001894
1895 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1896 return -1;
1897
1898 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1899 {
1900 PyErr_SetVim(_("cursor position outside buffer"));
1901 return -1;
1902 }
1903
1904 /* Check for keyboard interrupts */
1905 if (VimErrorCheck())
1906 return -1;
1907
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001908 this->win->w_cursor.lnum = lnum;
1909 this->win->w_cursor.col = col;
1910#ifdef FEAT_VIRTUALEDIT
1911 this->win->w_cursor.coladd = 0;
1912#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001913 /* When column is out of range silently correct it. */
1914 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001915
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001916 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001917 return 0;
1918 }
1919 else if (strcmp(name, "height") == 0)
1920 {
1921 int height;
1922 win_T *savewin;
1923
1924 if (!PyArg_Parse(val, "i", &height))
1925 return -1;
1926
1927#ifdef FEAT_GUI
1928 need_mouse_correct = TRUE;
1929#endif
1930 savewin = curwin;
1931 curwin = this->win;
1932 win_setheight(height);
1933 curwin = savewin;
1934
1935 /* Check for keyboard interrupts */
1936 if (VimErrorCheck())
1937 return -1;
1938
1939 return 0;
1940 }
1941#ifdef FEAT_VERTSPLIT
1942 else if (strcmp(name, "width") == 0)
1943 {
1944 int width;
1945 win_T *savewin;
1946
1947 if (!PyArg_Parse(val, "i", &width))
1948 return -1;
1949
1950#ifdef FEAT_GUI
1951 need_mouse_correct = TRUE;
1952#endif
1953 savewin = curwin;
1954 curwin = this->win;
1955 win_setwidth(width);
1956 curwin = savewin;
1957
1958 /* Check for keyboard interrupts */
1959 if (VimErrorCheck())
1960 return -1;
1961
1962 return 0;
1963 }
1964#endif
1965 else
1966 {
1967 PyErr_SetString(PyExc_AttributeError, name);
1968 return -1;
1969 }
1970}
1971
1972 static PyObject *
1973WindowRepr(PyObject *self)
1974{
1975 static char repr[100];
1976 WindowObject *this = (WindowObject *)(self);
1977
1978 if (this->win == INVALID_WINDOW_VALUE)
1979 {
1980 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1981 return PyString_FromString(repr);
1982 }
1983 else
1984 {
Bram Moolenaar6d216452013-05-12 19:00:41 +02001985 int w = get_win_number(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001986
Bram Moolenaar6d216452013-05-12 19:00:41 +02001987 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001988 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1989 (self));
1990 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001991 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001992
1993 return PyString_FromString(repr);
1994 }
1995}
1996
1997/*
1998 * Window list object - Implementation
1999 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002000
2001typedef struct
2002{
2003 PyObject_HEAD
2004} WinListObject;
2005
2006static PyTypeObject WinListType;
2007static PySequenceMethods BufListAsSeq;
2008
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002009 static PyInt
2010WinListLength(PyObject *self UNUSED)
2011{
2012 win_T *w = firstwin;
2013 PyInt n = 0;
2014
2015 while (w != NULL)
2016 {
2017 ++n;
2018 w = W_NEXT(w);
2019 }
2020
2021 return n;
2022}
2023
2024 static PyObject *
2025WinListItem(PyObject *self UNUSED, PyInt n)
2026{
2027 win_T *w;
2028
2029 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
2030 if (n == 0)
2031 return WindowNew(w);
2032
2033 PyErr_SetString(PyExc_IndexError, _("no such window"));
2034 return NULL;
2035}
2036
2037/* Convert a Python string into a Vim line.
2038 *
2039 * The result is in allocated memory. All internal nulls are replaced by
2040 * newline characters. It is an error for the string to contain newline
2041 * characters.
2042 *
2043 * On errors, the Python exception data is set, and NULL is returned.
2044 */
2045 static char *
2046StringToLine(PyObject *obj)
2047{
2048 const char *str;
2049 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002050 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002051 PyInt len;
2052 PyInt i;
2053 char *p;
2054
2055 if (obj == NULL || !PyString_Check(obj))
2056 {
2057 PyErr_BadArgument();
2058 return NULL;
2059 }
2060
Bram Moolenaar19e60942011-06-19 00:27:51 +02002061 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
2062 str = PyString_AsString(bytes);
2063 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002064
2065 /*
2066 * Error checking: String must not contain newlines, as we
2067 * are replacing a single line, and we must replace it with
2068 * a single line.
2069 * A trailing newline is removed, so that append(f.readlines()) works.
2070 */
2071 p = memchr(str, '\n', len);
2072 if (p != NULL)
2073 {
2074 if (p == str + len - 1)
2075 --len;
2076 else
2077 {
2078 PyErr_SetVim(_("string cannot contain newlines"));
2079 return NULL;
2080 }
2081 }
2082
2083 /* Create a copy of the string, with internal nulls replaced by
2084 * newline characters, as is the vim convention.
2085 */
2086 save = (char *)alloc((unsigned)(len+1));
2087 if (save == NULL)
2088 {
2089 PyErr_NoMemory();
2090 return NULL;
2091 }
2092
2093 for (i = 0; i < len; ++i)
2094 {
2095 if (str[i] == '\0')
2096 save[i] = '\n';
2097 else
2098 save[i] = str[i];
2099 }
2100
2101 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02002102 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002103
2104 return save;
2105}
2106
2107/* Get a line from the specified buffer. The line number is
2108 * in Vim format (1-based). The line is returned as a Python
2109 * string object.
2110 */
2111 static PyObject *
2112GetBufferLine(buf_T *buf, PyInt n)
2113{
2114 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2115}
2116
2117
2118/* Get a list of lines from the specified buffer. The line numbers
2119 * are in Vim format (1-based). The range is from lo up to, but not
2120 * including, hi. The list is returned as a Python list of string objects.
2121 */
2122 static PyObject *
2123GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2124{
2125 PyInt i;
2126 PyInt n = hi - lo;
2127 PyObject *list = PyList_New(n);
2128
2129 if (list == NULL)
2130 return NULL;
2131
2132 for (i = 0; i < n; ++i)
2133 {
2134 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2135
2136 /* Error check - was the Python string creation OK? */
2137 if (str == NULL)
2138 {
2139 Py_DECREF(list);
2140 return NULL;
2141 }
2142
2143 /* Set the list item */
2144 if (PyList_SetItem(list, i, str))
2145 {
2146 Py_DECREF(str);
2147 Py_DECREF(list);
2148 return NULL;
2149 }
2150 }
2151
2152 /* The ownership of the Python list is passed to the caller (ie,
2153 * the caller should Py_DECREF() the object when it is finished
2154 * with it).
2155 */
2156
2157 return list;
2158}
2159
2160/*
2161 * Check if deleting lines made the cursor position invalid.
2162 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2163 * deleted).
2164 */
2165 static void
2166py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2167{
2168 if (curwin->w_cursor.lnum >= lo)
2169 {
2170 /* Adjust the cursor position if it's in/after the changed
2171 * lines. */
2172 if (curwin->w_cursor.lnum >= hi)
2173 {
2174 curwin->w_cursor.lnum += extra;
2175 check_cursor_col();
2176 }
2177 else if (extra < 0)
2178 {
2179 curwin->w_cursor.lnum = lo;
2180 check_cursor();
2181 }
2182 else
2183 check_cursor_col();
2184 changed_cline_bef_curs();
2185 }
2186 invalidate_botline();
2187}
2188
Bram Moolenaar19e60942011-06-19 00:27:51 +02002189/*
2190 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002191 * in Vim format (1-based). The replacement line is given as
2192 * a Python string object. The object is checked for validity
2193 * and correct format. Errors are returned as a value of FAIL.
2194 * The return value is OK on success.
2195 * If OK is returned and len_change is not NULL, *len_change
2196 * is set to the change in the buffer length.
2197 */
2198 static int
2199SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2200{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002201 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002202 * There are three cases:
2203 * 1. NULL, or None - this is a deletion.
2204 * 2. A string - this is a replacement.
2205 * 3. Anything else - this is an error.
2206 */
2207 if (line == Py_None || line == NULL)
2208 {
2209 buf_T *savebuf = curbuf;
2210
2211 PyErr_Clear();
2212 curbuf = buf;
2213
2214 if (u_savedel((linenr_T)n, 1L) == FAIL)
2215 PyErr_SetVim(_("cannot save undo information"));
2216 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2217 PyErr_SetVim(_("cannot delete line"));
2218 else
2219 {
2220 if (buf == curwin->w_buffer)
2221 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2222 deleted_lines_mark((linenr_T)n, 1L);
2223 }
2224
2225 curbuf = savebuf;
2226
2227 if (PyErr_Occurred() || VimErrorCheck())
2228 return FAIL;
2229
2230 if (len_change)
2231 *len_change = -1;
2232
2233 return OK;
2234 }
2235 else if (PyString_Check(line))
2236 {
2237 char *save = StringToLine(line);
2238 buf_T *savebuf = curbuf;
2239
2240 if (save == NULL)
2241 return FAIL;
2242
2243 /* We do not need to free "save" if ml_replace() consumes it. */
2244 PyErr_Clear();
2245 curbuf = buf;
2246
2247 if (u_savesub((linenr_T)n) == FAIL)
2248 {
2249 PyErr_SetVim(_("cannot save undo information"));
2250 vim_free(save);
2251 }
2252 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2253 {
2254 PyErr_SetVim(_("cannot replace line"));
2255 vim_free(save);
2256 }
2257 else
2258 changed_bytes((linenr_T)n, 0);
2259
2260 curbuf = savebuf;
2261
2262 /* Check that the cursor is not beyond the end of the line now. */
2263 if (buf == curwin->w_buffer)
2264 check_cursor_col();
2265
2266 if (PyErr_Occurred() || VimErrorCheck())
2267 return FAIL;
2268
2269 if (len_change)
2270 *len_change = 0;
2271
2272 return OK;
2273 }
2274 else
2275 {
2276 PyErr_BadArgument();
2277 return FAIL;
2278 }
2279}
2280
Bram Moolenaar19e60942011-06-19 00:27:51 +02002281/* Replace a range of lines in the specified buffer. The line numbers are in
2282 * Vim format (1-based). The range is from lo up to, but not including, hi.
2283 * The replacement lines are given as a Python list of string objects. The
2284 * list is checked for validity and correct format. Errors are returned as a
2285 * value of FAIL. The return value is OK on success.
2286 * If OK is returned and len_change is not NULL, *len_change
2287 * is set to the change in the buffer length.
2288 */
2289 static int
2290SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2291{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002292 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002293 * There are three cases:
2294 * 1. NULL, or None - this is a deletion.
2295 * 2. A list - this is a replacement.
2296 * 3. Anything else - this is an error.
2297 */
2298 if (list == Py_None || list == NULL)
2299 {
2300 PyInt i;
2301 PyInt n = (int)(hi - lo);
2302 buf_T *savebuf = curbuf;
2303
2304 PyErr_Clear();
2305 curbuf = buf;
2306
2307 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2308 PyErr_SetVim(_("cannot save undo information"));
2309 else
2310 {
2311 for (i = 0; i < n; ++i)
2312 {
2313 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2314 {
2315 PyErr_SetVim(_("cannot delete line"));
2316 break;
2317 }
2318 }
2319 if (buf == curwin->w_buffer)
2320 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2321 deleted_lines_mark((linenr_T)lo, (long)i);
2322 }
2323
2324 curbuf = savebuf;
2325
2326 if (PyErr_Occurred() || VimErrorCheck())
2327 return FAIL;
2328
2329 if (len_change)
2330 *len_change = -n;
2331
2332 return OK;
2333 }
2334 else if (PyList_Check(list))
2335 {
2336 PyInt i;
2337 PyInt new_len = PyList_Size(list);
2338 PyInt old_len = hi - lo;
2339 PyInt extra = 0; /* lines added to text, can be negative */
2340 char **array;
2341 buf_T *savebuf;
2342
2343 if (new_len == 0) /* avoid allocating zero bytes */
2344 array = NULL;
2345 else
2346 {
2347 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2348 if (array == NULL)
2349 {
2350 PyErr_NoMemory();
2351 return FAIL;
2352 }
2353 }
2354
2355 for (i = 0; i < new_len; ++i)
2356 {
2357 PyObject *line = PyList_GetItem(list, i);
2358
2359 array[i] = StringToLine(line);
2360 if (array[i] == NULL)
2361 {
2362 while (i)
2363 vim_free(array[--i]);
2364 vim_free(array);
2365 return FAIL;
2366 }
2367 }
2368
2369 savebuf = curbuf;
2370
2371 PyErr_Clear();
2372 curbuf = buf;
2373
2374 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2375 PyErr_SetVim(_("cannot save undo information"));
2376
2377 /* If the size of the range is reducing (ie, new_len < old_len) we
2378 * need to delete some old_len. We do this at the start, by
2379 * repeatedly deleting line "lo".
2380 */
2381 if (!PyErr_Occurred())
2382 {
2383 for (i = 0; i < old_len - new_len; ++i)
2384 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2385 {
2386 PyErr_SetVim(_("cannot delete line"));
2387 break;
2388 }
2389 extra -= i;
2390 }
2391
2392 /* For as long as possible, replace the existing old_len with the
2393 * new old_len. This is a more efficient operation, as it requires
2394 * less memory allocation and freeing.
2395 */
2396 if (!PyErr_Occurred())
2397 {
2398 for (i = 0; i < old_len && i < new_len; ++i)
2399 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2400 == FAIL)
2401 {
2402 PyErr_SetVim(_("cannot replace line"));
2403 break;
2404 }
2405 }
2406 else
2407 i = 0;
2408
2409 /* Now we may need to insert the remaining new old_len. If we do, we
2410 * must free the strings as we finish with them (we can't pass the
2411 * responsibility to vim in this case).
2412 */
2413 if (!PyErr_Occurred())
2414 {
2415 while (i < new_len)
2416 {
2417 if (ml_append((linenr_T)(lo + i - 1),
2418 (char_u *)array[i], 0, FALSE) == FAIL)
2419 {
2420 PyErr_SetVim(_("cannot insert line"));
2421 break;
2422 }
2423 vim_free(array[i]);
2424 ++i;
2425 ++extra;
2426 }
2427 }
2428
2429 /* Free any left-over old_len, as a result of an error */
2430 while (i < new_len)
2431 {
2432 vim_free(array[i]);
2433 ++i;
2434 }
2435
2436 /* Free the array of old_len. All of its contents have now
2437 * been dealt with (either freed, or the responsibility passed
2438 * to vim.
2439 */
2440 vim_free(array);
2441
2442 /* Adjust marks. Invalidate any which lie in the
2443 * changed range, and move any in the remainder of the buffer.
2444 */
2445 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2446 (long)MAXLNUM, (long)extra);
2447 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2448
2449 if (buf == curwin->w_buffer)
2450 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2451
2452 curbuf = savebuf;
2453
2454 if (PyErr_Occurred() || VimErrorCheck())
2455 return FAIL;
2456
2457 if (len_change)
2458 *len_change = new_len - old_len;
2459
2460 return OK;
2461 }
2462 else
2463 {
2464 PyErr_BadArgument();
2465 return FAIL;
2466 }
2467}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002468
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002469/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002470 * The line number is in Vim format (1-based). The lines to be inserted are
2471 * given as a Python list of string objects or as a single string. The lines
2472 * to be added are checked for validity and correct format. Errors are
2473 * returned as a value of FAIL. The return value is OK on success.
2474 * If OK is returned and len_change is not NULL, *len_change
2475 * is set to the change in the buffer length.
2476 */
2477 static int
2478InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2479{
2480 /* First of all, we check the type of the supplied Python object.
2481 * It must be a string or a list, or the call is in error.
2482 */
2483 if (PyString_Check(lines))
2484 {
2485 char *str = StringToLine(lines);
2486 buf_T *savebuf;
2487
2488 if (str == NULL)
2489 return FAIL;
2490
2491 savebuf = curbuf;
2492
2493 PyErr_Clear();
2494 curbuf = buf;
2495
2496 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2497 PyErr_SetVim(_("cannot save undo information"));
2498 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2499 PyErr_SetVim(_("cannot insert line"));
2500 else
2501 appended_lines_mark((linenr_T)n, 1L);
2502
2503 vim_free(str);
2504 curbuf = savebuf;
2505 update_screen(VALID);
2506
2507 if (PyErr_Occurred() || VimErrorCheck())
2508 return FAIL;
2509
2510 if (len_change)
2511 *len_change = 1;
2512
2513 return OK;
2514 }
2515 else if (PyList_Check(lines))
2516 {
2517 PyInt i;
2518 PyInt size = PyList_Size(lines);
2519 char **array;
2520 buf_T *savebuf;
2521
2522 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2523 if (array == NULL)
2524 {
2525 PyErr_NoMemory();
2526 return FAIL;
2527 }
2528
2529 for (i = 0; i < size; ++i)
2530 {
2531 PyObject *line = PyList_GetItem(lines, i);
2532 array[i] = StringToLine(line);
2533
2534 if (array[i] == NULL)
2535 {
2536 while (i)
2537 vim_free(array[--i]);
2538 vim_free(array);
2539 return FAIL;
2540 }
2541 }
2542
2543 savebuf = curbuf;
2544
2545 PyErr_Clear();
2546 curbuf = buf;
2547
2548 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2549 PyErr_SetVim(_("cannot save undo information"));
2550 else
2551 {
2552 for (i = 0; i < size; ++i)
2553 {
2554 if (ml_append((linenr_T)(n + i),
2555 (char_u *)array[i], 0, FALSE) == FAIL)
2556 {
2557 PyErr_SetVim(_("cannot insert line"));
2558
2559 /* Free the rest of the lines */
2560 while (i < size)
2561 vim_free(array[i++]);
2562
2563 break;
2564 }
2565 vim_free(array[i]);
2566 }
2567 if (i > 0)
2568 appended_lines_mark((linenr_T)n, (long)i);
2569 }
2570
2571 /* Free the array of lines. All of its contents have now
2572 * been freed.
2573 */
2574 vim_free(array);
2575
2576 curbuf = savebuf;
2577 update_screen(VALID);
2578
2579 if (PyErr_Occurred() || VimErrorCheck())
2580 return FAIL;
2581
2582 if (len_change)
2583 *len_change = size;
2584
2585 return OK;
2586 }
2587 else
2588 {
2589 PyErr_BadArgument();
2590 return FAIL;
2591 }
2592}
2593
2594/*
2595 * Common routines for buffers and line ranges
2596 * -------------------------------------------
2597 */
2598
2599 static int
2600CheckBuffer(BufferObject *this)
2601{
2602 if (this->buf == INVALID_BUFFER_VALUE)
2603 {
2604 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2605 return -1;
2606 }
2607
2608 return 0;
2609}
2610
2611 static PyObject *
2612RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2613{
2614 if (CheckBuffer(self))
2615 return NULL;
2616
2617 if (n < 0 || n > end - start)
2618 {
2619 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2620 return NULL;
2621 }
2622
2623 return GetBufferLine(self->buf, n+start);
2624}
2625
2626 static PyObject *
2627RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2628{
2629 PyInt size;
2630
2631 if (CheckBuffer(self))
2632 return NULL;
2633
2634 size = end - start + 1;
2635
2636 if (lo < 0)
2637 lo = 0;
2638 else if (lo > size)
2639 lo = size;
2640 if (hi < 0)
2641 hi = 0;
2642 if (hi < lo)
2643 hi = lo;
2644 else if (hi > size)
2645 hi = size;
2646
2647 return GetBufferLineList(self->buf, lo+start, hi+start);
2648}
2649
2650 static PyInt
2651RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2652{
2653 PyInt len_change;
2654
2655 if (CheckBuffer(self))
2656 return -1;
2657
2658 if (n < 0 || n > end - start)
2659 {
2660 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2661 return -1;
2662 }
2663
2664 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2665 return -1;
2666
2667 if (new_end)
2668 *new_end = end + len_change;
2669
2670 return 0;
2671}
2672
Bram Moolenaar19e60942011-06-19 00:27:51 +02002673 static PyInt
2674RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2675{
2676 PyInt size;
2677 PyInt len_change;
2678
2679 /* Self must be a valid buffer */
2680 if (CheckBuffer(self))
2681 return -1;
2682
2683 /* Sort out the slice range */
2684 size = end - start + 1;
2685
2686 if (lo < 0)
2687 lo = 0;
2688 else if (lo > size)
2689 lo = size;
2690 if (hi < 0)
2691 hi = 0;
2692 if (hi < lo)
2693 hi = lo;
2694 else if (hi > size)
2695 hi = size;
2696
2697 if (SetBufferLineList(self->buf, lo + start, hi + start,
2698 val, &len_change) == FAIL)
2699 return -1;
2700
2701 if (new_end)
2702 *new_end = end + len_change;
2703
2704 return 0;
2705}
2706
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002707
2708 static PyObject *
2709RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2710{
2711 PyObject *lines;
2712 PyInt len_change;
2713 PyInt max;
2714 PyInt n;
2715
2716 if (CheckBuffer(self))
2717 return NULL;
2718
2719 max = n = end - start + 1;
2720
2721 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2722 return NULL;
2723
2724 if (n < 0 || n > max)
2725 {
2726 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2727 return NULL;
2728 }
2729
2730 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2731 return NULL;
2732
2733 if (new_end)
2734 *new_end = end + len_change;
2735
2736 Py_INCREF(Py_None);
2737 return Py_None;
2738}
2739
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002740/* Range object - Definitions
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002741 */
2742
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002743static PyTypeObject RangeType;
2744
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002745typedef struct
2746{
2747 PyObject_HEAD
2748 BufferObject *buf;
2749 PyInt start;
2750 PyInt end;
2751} RangeObject;
2752
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002753static void RangeDestructor(PyObject *);
2754static PySequenceMethods RangeAsSeq;
2755static PyMappingMethods RangeAsMapping;
2756
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002757 static PyObject *
2758RangeNew(buf_T *buf, PyInt start, PyInt end)
2759{
2760 BufferObject *bufr;
2761 RangeObject *self;
2762 self = PyObject_NEW(RangeObject, &RangeType);
2763 if (self == NULL)
2764 return NULL;
2765
2766 bufr = (BufferObject *)BufferNew(buf);
2767 if (bufr == NULL)
2768 {
2769 Py_DECREF(self);
2770 return NULL;
2771 }
2772 Py_INCREF(bufr);
2773
2774 self->buf = bufr;
2775 self->start = start;
2776 self->end = end;
2777
2778 return (PyObject *)(self);
2779}
2780
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002781 static void
2782RangeDestructor(PyObject *self)
2783{
2784 Py_DECREF(((RangeObject *)(self))->buf);
2785 DESTRUCTOR_FINISH(self);
2786}
2787
2788static PyTypeObject BufferType;
2789static PyObject *BufferRepr(PyObject *);
2790static PySequenceMethods BufferAsSeq;
2791static PyMappingMethods BufferAsMapping;
2792
2793 static void
2794BufferDestructor(PyObject *self)
2795{
2796 BufferObject *this = (BufferObject *)(self);
2797
2798 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
Bram Moolenaar971db462013-05-12 18:44:48 +02002799 BUF_PYTHON_REF(this->buf) = NULL;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002800
2801 DESTRUCTOR_FINISH(self);
2802}
2803
2804 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002805BufferNew(buf_T *buf)
2806{
2807 /* We need to handle deletion of buffers underneath us.
2808 * If we add a "b_python*_ref" field to the buf_T structure,
2809 * then we can get at it in buf_freeall() in vim. We then
2810 * need to create only ONE Python object per buffer - if
2811 * we try to create a second, just INCREF the existing one
2812 * and return it. The (single) Python object referring to
2813 * the buffer is stored in "b_python*_ref".
2814 * Question: what to do on a buf_freeall(). We'll probably
2815 * have to either delete the Python object (DECREF it to
2816 * zero - a bad idea, as it leaves dangling refs!) or
2817 * set the buf_T * value to an invalid value (-1?), which
2818 * means we need checks in all access functions... Bah.
2819 *
2820 * Python2 and Python3 get different fields and different objects:
2821 * b_python_ref and b_python3_ref fields respectively.
2822 */
2823
2824 BufferObject *self;
2825
2826 if (BUF_PYTHON_REF(buf) != NULL)
2827 {
2828 self = BUF_PYTHON_REF(buf);
2829 Py_INCREF(self);
2830 }
2831 else
2832 {
2833 self = PyObject_NEW(BufferObject, &BufferType);
2834 if (self == NULL)
2835 return NULL;
2836 self->buf = buf;
2837 BUF_PYTHON_REF(buf) = self;
2838 }
2839
2840 return (PyObject *)(self);
2841}
2842
2843 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002844BufferAttr(BufferObject *this, char *name)
2845{
2846 if (strcmp(name, "name") == 0)
2847 return Py_BuildValue("s", this->buf->b_ffname);
2848 else if (strcmp(name, "number") == 0)
2849 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02002850 else if (strcmp(name, "vars") == 0)
2851 return DictionaryNew(this->buf->b_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02002852 else if (strcmp(name, "options") == 0)
2853 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2854 (PyObject *) this);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002855 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02002856 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002857 else
2858 return NULL;
2859}
2860
Bram Moolenaar971db462013-05-12 18:44:48 +02002861 static PyInt
2862BufferLength(PyObject *self)
2863{
2864 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2865 if (CheckBuffer((BufferObject *)(self)))
2866 return -1; /* ??? */
2867
2868 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2869}
2870
2871 static PyObject *
2872BufferItem(PyObject *self, PyInt n)
2873{
2874 return RBItem((BufferObject *)(self), n, 1,
2875 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count);
2876}
2877
2878 static PyObject *
2879BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2880{
2881 return RBSlice((BufferObject *)(self), lo, hi, 1,
2882 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count);
2883}
2884
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002885 static PyObject *
2886BufferAppend(PyObject *self, PyObject *args)
2887{
2888 return RBAppend((BufferObject *)(self), args, 1,
2889 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2890 NULL);
2891}
2892
2893 static PyObject *
2894BufferMark(PyObject *self, PyObject *args)
2895{
2896 pos_T *posp;
2897 char *pmark;
2898 char mark;
2899 buf_T *curbuf_save;
2900
2901 if (CheckBuffer((BufferObject *)(self)))
2902 return NULL;
2903
2904 if (!PyArg_ParseTuple(args, "s", &pmark))
2905 return NULL;
2906 mark = *pmark;
2907
2908 curbuf_save = curbuf;
2909 curbuf = ((BufferObject *)(self))->buf;
2910 posp = getmark(mark, FALSE);
2911 curbuf = curbuf_save;
2912
2913 if (posp == NULL)
2914 {
2915 PyErr_SetVim(_("invalid mark name"));
2916 return NULL;
2917 }
2918
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002919 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002920 if (VimErrorCheck())
2921 return NULL;
2922
2923 if (posp->lnum <= 0)
2924 {
2925 /* Or raise an error? */
2926 Py_INCREF(Py_None);
2927 return Py_None;
2928 }
2929
2930 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2931}
2932
2933 static PyObject *
2934BufferRange(PyObject *self, PyObject *args)
2935{
2936 PyInt start;
2937 PyInt end;
2938
2939 if (CheckBuffer((BufferObject *)(self)))
2940 return NULL;
2941
2942 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2943 return NULL;
2944
2945 return RangeNew(((BufferObject *)(self))->buf, start, end);
2946}
2947
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002948 static PyObject *
2949BufferRepr(PyObject *self)
2950{
2951 static char repr[100];
2952 BufferObject *this = (BufferObject *)(self);
2953
2954 if (this->buf == INVALID_BUFFER_VALUE)
2955 {
2956 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2957 return PyString_FromString(repr);
2958 }
2959 else
2960 {
2961 char *name = (char *)this->buf->b_fname;
2962 PyInt len;
2963
2964 if (name == NULL)
2965 name = "";
2966 len = strlen(name);
2967
2968 if (len > 35)
2969 name = name + (35 - len);
2970
2971 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2972
2973 return PyString_FromString(repr);
2974 }
2975}
2976
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002977static struct PyMethodDef BufferMethods[] = {
2978 /* name, function, calling, documentation */
2979 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2980 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2981 {"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 +01002982#if PY_VERSION_HEX >= 0x03000000
2983 {"__dir__", BufferDir, 4, "List its attributes" },
2984#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002985 { NULL, NULL, 0, NULL }
2986};
2987
2988 static PyObject *
2989RangeAppend(PyObject *self, PyObject *args)
2990{
2991 return RBAppend(((RangeObject *)(self))->buf, args,
2992 ((RangeObject *)(self))->start,
2993 ((RangeObject *)(self))->end,
2994 &((RangeObject *)(self))->end);
2995}
2996
2997 static PyInt
2998RangeLength(PyObject *self)
2999{
3000 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
3001 if (CheckBuffer(((RangeObject *)(self))->buf))
3002 return -1; /* ??? */
3003
3004 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
3005}
3006
3007 static PyObject *
3008RangeItem(PyObject *self, PyInt n)
3009{
3010 return RBItem(((RangeObject *)(self))->buf, n,
3011 ((RangeObject *)(self))->start,
3012 ((RangeObject *)(self))->end);
3013}
3014
3015 static PyObject *
3016RangeRepr(PyObject *self)
3017{
3018 static char repr[100];
3019 RangeObject *this = (RangeObject *)(self);
3020
3021 if (this->buf->buf == INVALID_BUFFER_VALUE)
3022 {
3023 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
3024 (self));
3025 return PyString_FromString(repr);
3026 }
3027 else
3028 {
3029 char *name = (char *)this->buf->buf->b_fname;
3030 int len;
3031
3032 if (name == NULL)
3033 name = "";
3034 len = (int)strlen(name);
3035
3036 if (len > 45)
3037 name = name + (45 - len);
3038
3039 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
3040 len > 45 ? "..." : "", name,
3041 this->start, this->end);
3042
3043 return PyString_FromString(repr);
3044 }
3045}
3046
3047 static PyObject *
3048RangeSlice(PyObject *self, PyInt lo, PyInt hi)
3049{
3050 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
3051 ((RangeObject *)(self))->start,
3052 ((RangeObject *)(self))->end);
3053}
3054
3055/*
3056 * Line range object - Definitions
3057 */
3058
3059static struct PyMethodDef RangeMethods[] = {
3060 /* name, function, calling, documentation */
3061 {"append", RangeAppend, 1, "Append data to the Vim range" },
3062 { NULL, NULL, 0, NULL }
3063};
3064
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003065/* Current items object - Implementation
3066 */
3067
3068static PyInt RangeStart;
3069static PyInt RangeEnd;
3070
3071 static PyObject *
3072CurrentGetattr(PyObject *self UNUSED, char *name)
3073{
3074 if (strcmp(name, "buffer") == 0)
3075 return (PyObject *)BufferNew(curbuf);
3076 else if (strcmp(name, "window") == 0)
3077 return (PyObject *)WindowNew(curwin);
3078 else if (strcmp(name, "line") == 0)
3079 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3080 else if (strcmp(name, "range") == 0)
3081 return RangeNew(curbuf, RangeStart, RangeEnd);
3082 else if (strcmp(name,"__members__") == 0)
3083 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
3084 else
3085 {
3086 PyErr_SetString(PyExc_AttributeError, name);
3087 return NULL;
3088 }
3089}
3090
3091 static int
3092CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3093{
3094 if (strcmp(name, "line") == 0)
3095 {
3096 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3097 return -1;
3098
3099 return 0;
3100 }
3101 else
3102 {
3103 PyErr_SetString(PyExc_AttributeError, name);
3104 return -1;
3105 }
3106}
3107
Bram Moolenaardb913952012-06-29 12:54:53 +02003108 static void
3109set_ref_in_py(const int copyID)
3110{
3111 pylinkedlist_T *cur;
3112 dict_T *dd;
3113 list_T *ll;
3114
3115 if (lastdict != NULL)
3116 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3117 {
3118 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3119 if (dd->dv_copyID != copyID)
3120 {
3121 dd->dv_copyID = copyID;
3122 set_ref_in_ht(&dd->dv_hashtab, copyID);
3123 }
3124 }
3125
3126 if (lastlist != NULL)
3127 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3128 {
3129 ll = ((ListObject *) (cur->pll_obj))->list;
3130 if (ll->lv_copyID != copyID)
3131 {
3132 ll->lv_copyID = copyID;
3133 set_ref_in_list(ll, copyID);
3134 }
3135 }
3136}
3137
3138 static int
3139set_string_copy(char_u *str, typval_T *tv)
3140{
3141 tv->vval.v_string = vim_strsave(str);
3142 if (tv->vval.v_string == NULL)
3143 {
3144 PyErr_NoMemory();
3145 return -1;
3146 }
3147 return 0;
3148}
3149
Bram Moolenaardb913952012-06-29 12:54:53 +02003150typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3151
3152 static int
3153convert_dl(PyObject *obj, typval_T *tv,
3154 pytotvfunc py_to_tv, PyObject *lookupDict)
3155{
3156 PyObject *capsule;
3157 char hexBuf[sizeof(void *) * 2 + 3];
3158
3159 sprintf(hexBuf, "%p", obj);
3160
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003161# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003162 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003163# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003164 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003165# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003166 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003167 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003168# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003169 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003170# else
3171 capsule = PyCObject_FromVoidPtr(tv, NULL);
3172# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003173 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3174 Py_DECREF(capsule);
3175 if (py_to_tv(obj, tv, lookupDict) == -1)
3176 {
3177 tv->v_type = VAR_UNKNOWN;
3178 return -1;
3179 }
3180 /* As we are not using copy_tv which increments reference count we must
3181 * do it ourself. */
3182 switch(tv->v_type)
3183 {
3184 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3185 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3186 }
3187 }
3188 else
3189 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003190 typval_T *v;
3191
3192# ifdef PY_USE_CAPSULE
3193 v = PyCapsule_GetPointer(capsule, NULL);
3194# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003195 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003196# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003197 copy_tv(v, tv);
3198 }
3199 return 0;
3200}
3201
3202 static int
3203ConvertFromPyObject(PyObject *obj, typval_T *tv)
3204{
3205 PyObject *lookup_dict;
3206 int r;
3207
3208 lookup_dict = PyDict_New();
3209 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3210 Py_DECREF(lookup_dict);
3211 return r;
3212}
3213
3214 static int
3215_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3216{
3217 if (obj->ob_type == &DictionaryType)
3218 {
3219 tv->v_type = VAR_DICT;
3220 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3221 ++tv->vval.v_dict->dv_refcount;
3222 }
3223 else if (obj->ob_type == &ListType)
3224 {
3225 tv->v_type = VAR_LIST;
3226 tv->vval.v_list = (((ListObject *)(obj))->list);
3227 ++tv->vval.v_list->lv_refcount;
3228 }
3229 else if (obj->ob_type == &FunctionType)
3230 {
3231 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3232 return -1;
3233
3234 tv->v_type = VAR_FUNC;
3235 func_ref(tv->vval.v_string);
3236 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003237 else if (PyBytes_Check(obj))
3238 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003239 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003240
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003241 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3242 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003243 if (result == NULL)
3244 return -1;
3245
3246 if (set_string_copy(result, tv) == -1)
3247 return -1;
3248
3249 tv->v_type = VAR_STRING;
3250 }
3251 else if (PyUnicode_Check(obj))
3252 {
3253 PyObject *bytes;
3254 char_u *result;
3255
Bram Moolenaardb913952012-06-29 12:54:53 +02003256 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3257 if (bytes == NULL)
3258 return -1;
3259
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003260 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3261 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003262 if (result == NULL)
3263 return -1;
3264
3265 if (set_string_copy(result, tv) == -1)
3266 {
3267 Py_XDECREF(bytes);
3268 return -1;
3269 }
3270 Py_XDECREF(bytes);
3271
3272 tv->v_type = VAR_STRING;
3273 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003274#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003275 else if (PyInt_Check(obj))
3276 {
3277 tv->v_type = VAR_NUMBER;
3278 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3279 }
3280#endif
3281 else if (PyLong_Check(obj))
3282 {
3283 tv->v_type = VAR_NUMBER;
3284 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3285 }
3286 else if (PyDict_Check(obj))
3287 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3288#ifdef FEAT_FLOAT
3289 else if (PyFloat_Check(obj))
3290 {
3291 tv->v_type = VAR_FLOAT;
3292 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3293 }
3294#endif
3295 else if (PyIter_Check(obj))
3296 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3297 else if (PySequence_Check(obj))
3298 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3299 else if (PyMapping_Check(obj))
3300 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3301 else
3302 {
3303 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
3304 return -1;
3305 }
3306 return 0;
3307}
3308
3309 static PyObject *
3310ConvertToPyObject(typval_T *tv)
3311{
3312 if (tv == NULL)
3313 {
3314 PyErr_SetVim(_("NULL reference passed"));
3315 return NULL;
3316 }
3317 switch (tv->v_type)
3318 {
3319 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003320 return PyBytes_FromString(tv->vval.v_string == NULL
3321 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003322 case VAR_NUMBER:
3323 return PyLong_FromLong((long) tv->vval.v_number);
3324#ifdef FEAT_FLOAT
3325 case VAR_FLOAT:
3326 return PyFloat_FromDouble((double) tv->vval.v_float);
3327#endif
3328 case VAR_LIST:
3329 return ListNew(tv->vval.v_list);
3330 case VAR_DICT:
3331 return DictionaryNew(tv->vval.v_dict);
3332 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003333 return FunctionNew(tv->vval.v_string == NULL
3334 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003335 case VAR_UNKNOWN:
3336 Py_INCREF(Py_None);
3337 return Py_None;
3338 default:
3339 PyErr_SetVim(_("internal error: invalid value type"));
3340 return NULL;
3341 }
3342}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003343
3344typedef struct
3345{
3346 PyObject_HEAD
3347} CurrentObject;
3348static PyTypeObject CurrentType;
3349
3350 static void
3351init_structs(void)
3352{
3353 vim_memset(&OutputType, 0, sizeof(OutputType));
3354 OutputType.tp_name = "vim.message";
3355 OutputType.tp_basicsize = sizeof(OutputObject);
3356 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3357 OutputType.tp_doc = "vim message object";
3358 OutputType.tp_methods = OutputMethods;
3359#if PY_MAJOR_VERSION >= 3
3360 OutputType.tp_getattro = OutputGetattro;
3361 OutputType.tp_setattro = OutputSetattro;
3362 OutputType.tp_alloc = call_PyType_GenericAlloc;
3363 OutputType.tp_new = call_PyType_GenericNew;
3364 OutputType.tp_free = call_PyObject_Free;
3365#else
3366 OutputType.tp_getattr = OutputGetattr;
3367 OutputType.tp_setattr = OutputSetattr;
3368#endif
3369
3370 vim_memset(&BufferType, 0, sizeof(BufferType));
3371 BufferType.tp_name = "vim.buffer";
3372 BufferType.tp_basicsize = sizeof(BufferType);
3373 BufferType.tp_dealloc = BufferDestructor;
3374 BufferType.tp_repr = BufferRepr;
3375 BufferType.tp_as_sequence = &BufferAsSeq;
3376 BufferType.tp_as_mapping = &BufferAsMapping;
3377 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3378 BufferType.tp_doc = "vim buffer object";
3379 BufferType.tp_methods = BufferMethods;
3380#if PY_MAJOR_VERSION >= 3
3381 BufferType.tp_getattro = BufferGetattro;
3382 BufferType.tp_alloc = call_PyType_GenericAlloc;
3383 BufferType.tp_new = call_PyType_GenericNew;
3384 BufferType.tp_free = call_PyObject_Free;
3385#else
3386 BufferType.tp_getattr = BufferGetattr;
3387#endif
3388
3389 vim_memset(&WindowType, 0, sizeof(WindowType));
3390 WindowType.tp_name = "vim.window";
3391 WindowType.tp_basicsize = sizeof(WindowObject);
3392 WindowType.tp_dealloc = WindowDestructor;
3393 WindowType.tp_repr = WindowRepr;
3394 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3395 WindowType.tp_doc = "vim Window object";
3396 WindowType.tp_methods = WindowMethods;
3397#if PY_MAJOR_VERSION >= 3
3398 WindowType.tp_getattro = WindowGetattro;
3399 WindowType.tp_setattro = WindowSetattro;
3400 WindowType.tp_alloc = call_PyType_GenericAlloc;
3401 WindowType.tp_new = call_PyType_GenericNew;
3402 WindowType.tp_free = call_PyObject_Free;
3403#else
3404 WindowType.tp_getattr = WindowGetattr;
3405 WindowType.tp_setattr = WindowSetattr;
3406#endif
3407
3408 vim_memset(&BufListType, 0, sizeof(BufListType));
3409 BufListType.tp_name = "vim.bufferlist";
3410 BufListType.tp_basicsize = sizeof(BufListObject);
3411 BufListType.tp_as_sequence = &BufListAsSeq;
3412 BufListType.tp_flags = Py_TPFLAGS_DEFAULT;
3413 BufferType.tp_doc = "vim buffer list";
3414
3415 vim_memset(&WinListType, 0, sizeof(WinListType));
3416 WinListType.tp_name = "vim.windowlist";
3417 WinListType.tp_basicsize = sizeof(WinListType);
3418 WinListType.tp_as_sequence = &WinListAsSeq;
3419 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3420 WinListType.tp_doc = "vim window list";
3421
3422 vim_memset(&RangeType, 0, sizeof(RangeType));
3423 RangeType.tp_name = "vim.range";
3424 RangeType.tp_basicsize = sizeof(RangeObject);
3425 RangeType.tp_dealloc = RangeDestructor;
3426 RangeType.tp_repr = RangeRepr;
3427 RangeType.tp_as_sequence = &RangeAsSeq;
3428 RangeType.tp_as_mapping = &RangeAsMapping;
3429 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3430 RangeType.tp_doc = "vim Range object";
3431 RangeType.tp_methods = RangeMethods;
3432#if PY_MAJOR_VERSION >= 3
3433 RangeType.tp_getattro = RangeGetattro;
3434 RangeType.tp_alloc = call_PyType_GenericAlloc;
3435 RangeType.tp_new = call_PyType_GenericNew;
3436 RangeType.tp_free = call_PyObject_Free;
3437#else
3438 RangeType.tp_getattr = RangeGetattr;
3439#endif
3440
3441 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3442 CurrentType.tp_name = "vim.currentdata";
3443 CurrentType.tp_basicsize = sizeof(CurrentObject);
3444 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3445 CurrentType.tp_doc = "vim current object";
3446#if PY_MAJOR_VERSION >= 3
3447 CurrentType.tp_getattro = CurrentGetattro;
3448 CurrentType.tp_setattro = CurrentSetattro;
3449#else
3450 CurrentType.tp_getattr = CurrentGetattr;
3451 CurrentType.tp_setattr = CurrentSetattr;
3452#endif
3453
3454 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3455 DictionaryType.tp_name = "vim.dictionary";
3456 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3457 DictionaryType.tp_dealloc = DictionaryDestructor;
3458 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3459 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3460 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3461 DictionaryType.tp_methods = DictionaryMethods;
3462#if PY_MAJOR_VERSION >= 3
3463 DictionaryType.tp_getattro = DictionaryGetattro;
3464 DictionaryType.tp_setattro = DictionarySetattro;
3465#else
3466 DictionaryType.tp_getattr = DictionaryGetattr;
3467 DictionaryType.tp_setattr = DictionarySetattr;
3468#endif
3469
3470 vim_memset(&ListType, 0, sizeof(ListType));
3471 ListType.tp_name = "vim.list";
3472 ListType.tp_dealloc = ListDestructor;
3473 ListType.tp_basicsize = sizeof(ListObject);
3474 ListType.tp_as_sequence = &ListAsSeq;
3475 ListType.tp_as_mapping = &ListAsMapping;
3476 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3477 ListType.tp_doc = "list pushing modifications to vim structure";
3478 ListType.tp_methods = ListMethods;
3479#if PY_MAJOR_VERSION >= 3
3480 ListType.tp_getattro = ListGetattro;
3481 ListType.tp_setattro = ListSetattro;
3482#else
3483 ListType.tp_getattr = ListGetattr;
3484 ListType.tp_setattr = ListSetattr;
3485#endif
3486
3487 vim_memset(&FunctionType, 0, sizeof(FunctionType));
3488 FunctionType.tp_name = "vim.list";
3489 FunctionType.tp_basicsize = sizeof(FunctionObject);
3490 FunctionType.tp_dealloc = FunctionDestructor;
3491 FunctionType.tp_call = FunctionCall;
3492 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3493 FunctionType.tp_doc = "object that calls vim function";
3494 FunctionType.tp_methods = FunctionMethods;
3495#if PY_MAJOR_VERSION >= 3
3496 FunctionType.tp_getattro = FunctionGetattro;
3497#else
3498 FunctionType.tp_getattr = FunctionGetattr;
3499#endif
3500
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003501 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3502 OptionsType.tp_name = "vim.options";
3503 OptionsType.tp_basicsize = sizeof(OptionsObject);
3504 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3505 OptionsType.tp_doc = "object for manipulating options";
3506 OptionsType.tp_as_mapping = &OptionsAsMapping;
3507 OptionsType.tp_dealloc = OptionsDestructor;
3508
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003509#if PY_MAJOR_VERSION >= 3
3510 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3511 vimmodule.m_name = "vim";
3512 vimmodule.m_doc = "Vim Python interface\n";
3513 vimmodule.m_size = -1;
3514 vimmodule.m_methods = VimMethods;
3515#endif
3516}