blob: 4362aee2995a0a02f670fd494a1c36b050166427 [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 Moolenaarca8a4df2010-07-31 19:54:14 +02001500#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1501
1502 static int
1503CheckWindow(WindowObject *this)
1504{
1505 if (this->win == INVALID_WINDOW_VALUE)
1506 {
1507 PyErr_SetVim(_("attempt to refer to deleted window"));
1508 return -1;
1509 }
1510
1511 return 0;
1512}
1513
1514static int WindowSetattr(PyObject *, char *, PyObject *);
1515static PyObject *WindowRepr(PyObject *);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001516static PyTypeObject WindowType;
1517
1518 static PyObject *
1519WindowAttr(WindowObject *this, char *name)
1520{
1521 if (strcmp(name, "buffer") == 0)
1522 return (PyObject *)BufferNew(this->win->w_buffer);
1523 else if (strcmp(name, "cursor") == 0)
1524 {
1525 pos_T *pos = &this->win->w_cursor;
1526
1527 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1528 }
1529 else if (strcmp(name, "height") == 0)
1530 return Py_BuildValue("l", (long)(this->win->w_height));
1531#ifdef FEAT_VERTSPLIT
1532 else if (strcmp(name, "width") == 0)
1533 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1534#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001535 else if (strcmp(name, "vars") == 0)
1536 return DictionaryNew(this->win->w_vars);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001537 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001538 return Py_BuildValue("[ssss]", "buffer", "cursor", "height", "vars");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001539 else
1540 return NULL;
1541}
1542
1543 static void
1544WindowDestructor(PyObject *self)
1545{
1546 WindowObject *this = (WindowObject *)(self);
1547
1548 if (this->win && this->win != INVALID_WINDOW_VALUE)
1549#if PY_MAJOR_VERSION >= 3
1550 this->win->w_python3_ref = NULL;
1551#else
1552 this->win->w_python_ref = NULL;
1553#endif
1554
1555 DESTRUCTOR_FINISH(self);
1556}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001557
1558 static int
1559WindowSetattr(PyObject *self, char *name, PyObject *val)
1560{
1561 WindowObject *this = (WindowObject *)(self);
1562
1563 if (CheckWindow(this))
1564 return -1;
1565
1566 if (strcmp(name, "buffer") == 0)
1567 {
1568 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1569 return -1;
1570 }
1571 else if (strcmp(name, "cursor") == 0)
1572 {
1573 long lnum;
1574 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001575
1576 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1577 return -1;
1578
1579 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1580 {
1581 PyErr_SetVim(_("cursor position outside buffer"));
1582 return -1;
1583 }
1584
1585 /* Check for keyboard interrupts */
1586 if (VimErrorCheck())
1587 return -1;
1588
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001589 this->win->w_cursor.lnum = lnum;
1590 this->win->w_cursor.col = col;
1591#ifdef FEAT_VIRTUALEDIT
1592 this->win->w_cursor.coladd = 0;
1593#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001594 /* When column is out of range silently correct it. */
1595 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001596
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001597 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001598 return 0;
1599 }
1600 else if (strcmp(name, "height") == 0)
1601 {
1602 int height;
1603 win_T *savewin;
1604
1605 if (!PyArg_Parse(val, "i", &height))
1606 return -1;
1607
1608#ifdef FEAT_GUI
1609 need_mouse_correct = TRUE;
1610#endif
1611 savewin = curwin;
1612 curwin = this->win;
1613 win_setheight(height);
1614 curwin = savewin;
1615
1616 /* Check for keyboard interrupts */
1617 if (VimErrorCheck())
1618 return -1;
1619
1620 return 0;
1621 }
1622#ifdef FEAT_VERTSPLIT
1623 else if (strcmp(name, "width") == 0)
1624 {
1625 int width;
1626 win_T *savewin;
1627
1628 if (!PyArg_Parse(val, "i", &width))
1629 return -1;
1630
1631#ifdef FEAT_GUI
1632 need_mouse_correct = TRUE;
1633#endif
1634 savewin = curwin;
1635 curwin = this->win;
1636 win_setwidth(width);
1637 curwin = savewin;
1638
1639 /* Check for keyboard interrupts */
1640 if (VimErrorCheck())
1641 return -1;
1642
1643 return 0;
1644 }
1645#endif
1646 else
1647 {
1648 PyErr_SetString(PyExc_AttributeError, name);
1649 return -1;
1650 }
1651}
1652
1653 static PyObject *
1654WindowRepr(PyObject *self)
1655{
1656 static char repr[100];
1657 WindowObject *this = (WindowObject *)(self);
1658
1659 if (this->win == INVALID_WINDOW_VALUE)
1660 {
1661 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1662 return PyString_FromString(repr);
1663 }
1664 else
1665 {
1666 int i = 0;
1667 win_T *w;
1668
1669 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
1670 ++i;
1671
1672 if (w == NULL)
1673 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1674 (self));
1675 else
1676 vim_snprintf(repr, 100, _("<window %d>"), i);
1677
1678 return PyString_FromString(repr);
1679 }
1680}
1681
1682/*
1683 * Window list object - Implementation
1684 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001685
1686typedef struct
1687{
1688 PyObject_HEAD
1689} WinListObject;
1690
1691static PyTypeObject WinListType;
1692static PySequenceMethods BufListAsSeq;
1693
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001694 static PyInt
1695WinListLength(PyObject *self UNUSED)
1696{
1697 win_T *w = firstwin;
1698 PyInt n = 0;
1699
1700 while (w != NULL)
1701 {
1702 ++n;
1703 w = W_NEXT(w);
1704 }
1705
1706 return n;
1707}
1708
1709 static PyObject *
1710WinListItem(PyObject *self UNUSED, PyInt n)
1711{
1712 win_T *w;
1713
1714 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1715 if (n == 0)
1716 return WindowNew(w);
1717
1718 PyErr_SetString(PyExc_IndexError, _("no such window"));
1719 return NULL;
1720}
1721
1722/* Convert a Python string into a Vim line.
1723 *
1724 * The result is in allocated memory. All internal nulls are replaced by
1725 * newline characters. It is an error for the string to contain newline
1726 * characters.
1727 *
1728 * On errors, the Python exception data is set, and NULL is returned.
1729 */
1730 static char *
1731StringToLine(PyObject *obj)
1732{
1733 const char *str;
1734 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001735 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001736 PyInt len;
1737 PyInt i;
1738 char *p;
1739
1740 if (obj == NULL || !PyString_Check(obj))
1741 {
1742 PyErr_BadArgument();
1743 return NULL;
1744 }
1745
Bram Moolenaar19e60942011-06-19 00:27:51 +02001746 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1747 str = PyString_AsString(bytes);
1748 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001749
1750 /*
1751 * Error checking: String must not contain newlines, as we
1752 * are replacing a single line, and we must replace it with
1753 * a single line.
1754 * A trailing newline is removed, so that append(f.readlines()) works.
1755 */
1756 p = memchr(str, '\n', len);
1757 if (p != NULL)
1758 {
1759 if (p == str + len - 1)
1760 --len;
1761 else
1762 {
1763 PyErr_SetVim(_("string cannot contain newlines"));
1764 return NULL;
1765 }
1766 }
1767
1768 /* Create a copy of the string, with internal nulls replaced by
1769 * newline characters, as is the vim convention.
1770 */
1771 save = (char *)alloc((unsigned)(len+1));
1772 if (save == NULL)
1773 {
1774 PyErr_NoMemory();
1775 return NULL;
1776 }
1777
1778 for (i = 0; i < len; ++i)
1779 {
1780 if (str[i] == '\0')
1781 save[i] = '\n';
1782 else
1783 save[i] = str[i];
1784 }
1785
1786 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001787 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001788
1789 return save;
1790}
1791
1792/* Get a line from the specified buffer. The line number is
1793 * in Vim format (1-based). The line is returned as a Python
1794 * string object.
1795 */
1796 static PyObject *
1797GetBufferLine(buf_T *buf, PyInt n)
1798{
1799 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1800}
1801
1802
1803/* Get a list of lines from the specified buffer. The line numbers
1804 * are in Vim format (1-based). The range is from lo up to, but not
1805 * including, hi. The list is returned as a Python list of string objects.
1806 */
1807 static PyObject *
1808GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1809{
1810 PyInt i;
1811 PyInt n = hi - lo;
1812 PyObject *list = PyList_New(n);
1813
1814 if (list == NULL)
1815 return NULL;
1816
1817 for (i = 0; i < n; ++i)
1818 {
1819 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1820
1821 /* Error check - was the Python string creation OK? */
1822 if (str == NULL)
1823 {
1824 Py_DECREF(list);
1825 return NULL;
1826 }
1827
1828 /* Set the list item */
1829 if (PyList_SetItem(list, i, str))
1830 {
1831 Py_DECREF(str);
1832 Py_DECREF(list);
1833 return NULL;
1834 }
1835 }
1836
1837 /* The ownership of the Python list is passed to the caller (ie,
1838 * the caller should Py_DECREF() the object when it is finished
1839 * with it).
1840 */
1841
1842 return list;
1843}
1844
1845/*
1846 * Check if deleting lines made the cursor position invalid.
1847 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1848 * deleted).
1849 */
1850 static void
1851py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1852{
1853 if (curwin->w_cursor.lnum >= lo)
1854 {
1855 /* Adjust the cursor position if it's in/after the changed
1856 * lines. */
1857 if (curwin->w_cursor.lnum >= hi)
1858 {
1859 curwin->w_cursor.lnum += extra;
1860 check_cursor_col();
1861 }
1862 else if (extra < 0)
1863 {
1864 curwin->w_cursor.lnum = lo;
1865 check_cursor();
1866 }
1867 else
1868 check_cursor_col();
1869 changed_cline_bef_curs();
1870 }
1871 invalidate_botline();
1872}
1873
Bram Moolenaar19e60942011-06-19 00:27:51 +02001874/*
1875 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001876 * in Vim format (1-based). The replacement line is given as
1877 * a Python string object. The object is checked for validity
1878 * and correct format. Errors are returned as a value of FAIL.
1879 * The return value is OK on success.
1880 * If OK is returned and len_change is not NULL, *len_change
1881 * is set to the change in the buffer length.
1882 */
1883 static int
1884SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
1885{
1886 /* First of all, we check the thpe of the supplied Python object.
1887 * There are three cases:
1888 * 1. NULL, or None - this is a deletion.
1889 * 2. A string - this is a replacement.
1890 * 3. Anything else - this is an error.
1891 */
1892 if (line == Py_None || line == NULL)
1893 {
1894 buf_T *savebuf = curbuf;
1895
1896 PyErr_Clear();
1897 curbuf = buf;
1898
1899 if (u_savedel((linenr_T)n, 1L) == FAIL)
1900 PyErr_SetVim(_("cannot save undo information"));
1901 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
1902 PyErr_SetVim(_("cannot delete line"));
1903 else
1904 {
1905 if (buf == curwin->w_buffer)
1906 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
1907 deleted_lines_mark((linenr_T)n, 1L);
1908 }
1909
1910 curbuf = savebuf;
1911
1912 if (PyErr_Occurred() || VimErrorCheck())
1913 return FAIL;
1914
1915 if (len_change)
1916 *len_change = -1;
1917
1918 return OK;
1919 }
1920 else if (PyString_Check(line))
1921 {
1922 char *save = StringToLine(line);
1923 buf_T *savebuf = curbuf;
1924
1925 if (save == NULL)
1926 return FAIL;
1927
1928 /* We do not need to free "save" if ml_replace() consumes it. */
1929 PyErr_Clear();
1930 curbuf = buf;
1931
1932 if (u_savesub((linenr_T)n) == FAIL)
1933 {
1934 PyErr_SetVim(_("cannot save undo information"));
1935 vim_free(save);
1936 }
1937 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
1938 {
1939 PyErr_SetVim(_("cannot replace line"));
1940 vim_free(save);
1941 }
1942 else
1943 changed_bytes((linenr_T)n, 0);
1944
1945 curbuf = savebuf;
1946
1947 /* Check that the cursor is not beyond the end of the line now. */
1948 if (buf == curwin->w_buffer)
1949 check_cursor_col();
1950
1951 if (PyErr_Occurred() || VimErrorCheck())
1952 return FAIL;
1953
1954 if (len_change)
1955 *len_change = 0;
1956
1957 return OK;
1958 }
1959 else
1960 {
1961 PyErr_BadArgument();
1962 return FAIL;
1963 }
1964}
1965
Bram Moolenaar19e60942011-06-19 00:27:51 +02001966/* Replace a range of lines in the specified buffer. The line numbers are in
1967 * Vim format (1-based). The range is from lo up to, but not including, hi.
1968 * The replacement lines are given as a Python list of string objects. The
1969 * list is checked for validity and correct format. Errors are returned as a
1970 * value of FAIL. The return value is OK on success.
1971 * If OK is returned and len_change is not NULL, *len_change
1972 * is set to the change in the buffer length.
1973 */
1974 static int
1975SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
1976{
1977 /* First of all, we check the thpe of the supplied Python object.
1978 * There are three cases:
1979 * 1. NULL, or None - this is a deletion.
1980 * 2. A list - this is a replacement.
1981 * 3. Anything else - this is an error.
1982 */
1983 if (list == Py_None || list == NULL)
1984 {
1985 PyInt i;
1986 PyInt n = (int)(hi - lo);
1987 buf_T *savebuf = curbuf;
1988
1989 PyErr_Clear();
1990 curbuf = buf;
1991
1992 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
1993 PyErr_SetVim(_("cannot save undo information"));
1994 else
1995 {
1996 for (i = 0; i < n; ++i)
1997 {
1998 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1999 {
2000 PyErr_SetVim(_("cannot delete line"));
2001 break;
2002 }
2003 }
2004 if (buf == curwin->w_buffer)
2005 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2006 deleted_lines_mark((linenr_T)lo, (long)i);
2007 }
2008
2009 curbuf = savebuf;
2010
2011 if (PyErr_Occurred() || VimErrorCheck())
2012 return FAIL;
2013
2014 if (len_change)
2015 *len_change = -n;
2016
2017 return OK;
2018 }
2019 else if (PyList_Check(list))
2020 {
2021 PyInt i;
2022 PyInt new_len = PyList_Size(list);
2023 PyInt old_len = hi - lo;
2024 PyInt extra = 0; /* lines added to text, can be negative */
2025 char **array;
2026 buf_T *savebuf;
2027
2028 if (new_len == 0) /* avoid allocating zero bytes */
2029 array = NULL;
2030 else
2031 {
2032 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2033 if (array == NULL)
2034 {
2035 PyErr_NoMemory();
2036 return FAIL;
2037 }
2038 }
2039
2040 for (i = 0; i < new_len; ++i)
2041 {
2042 PyObject *line = PyList_GetItem(list, i);
2043
2044 array[i] = StringToLine(line);
2045 if (array[i] == NULL)
2046 {
2047 while (i)
2048 vim_free(array[--i]);
2049 vim_free(array);
2050 return FAIL;
2051 }
2052 }
2053
2054 savebuf = curbuf;
2055
2056 PyErr_Clear();
2057 curbuf = buf;
2058
2059 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2060 PyErr_SetVim(_("cannot save undo information"));
2061
2062 /* If the size of the range is reducing (ie, new_len < old_len) we
2063 * need to delete some old_len. We do this at the start, by
2064 * repeatedly deleting line "lo".
2065 */
2066 if (!PyErr_Occurred())
2067 {
2068 for (i = 0; i < old_len - new_len; ++i)
2069 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2070 {
2071 PyErr_SetVim(_("cannot delete line"));
2072 break;
2073 }
2074 extra -= i;
2075 }
2076
2077 /* For as long as possible, replace the existing old_len with the
2078 * new old_len. This is a more efficient operation, as it requires
2079 * less memory allocation and freeing.
2080 */
2081 if (!PyErr_Occurred())
2082 {
2083 for (i = 0; i < old_len && i < new_len; ++i)
2084 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2085 == FAIL)
2086 {
2087 PyErr_SetVim(_("cannot replace line"));
2088 break;
2089 }
2090 }
2091 else
2092 i = 0;
2093
2094 /* Now we may need to insert the remaining new old_len. If we do, we
2095 * must free the strings as we finish with them (we can't pass the
2096 * responsibility to vim in this case).
2097 */
2098 if (!PyErr_Occurred())
2099 {
2100 while (i < new_len)
2101 {
2102 if (ml_append((linenr_T)(lo + i - 1),
2103 (char_u *)array[i], 0, FALSE) == FAIL)
2104 {
2105 PyErr_SetVim(_("cannot insert line"));
2106 break;
2107 }
2108 vim_free(array[i]);
2109 ++i;
2110 ++extra;
2111 }
2112 }
2113
2114 /* Free any left-over old_len, as a result of an error */
2115 while (i < new_len)
2116 {
2117 vim_free(array[i]);
2118 ++i;
2119 }
2120
2121 /* Free the array of old_len. All of its contents have now
2122 * been dealt with (either freed, or the responsibility passed
2123 * to vim.
2124 */
2125 vim_free(array);
2126
2127 /* Adjust marks. Invalidate any which lie in the
2128 * changed range, and move any in the remainder of the buffer.
2129 */
2130 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2131 (long)MAXLNUM, (long)extra);
2132 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2133
2134 if (buf == curwin->w_buffer)
2135 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2136
2137 curbuf = savebuf;
2138
2139 if (PyErr_Occurred() || VimErrorCheck())
2140 return FAIL;
2141
2142 if (len_change)
2143 *len_change = new_len - old_len;
2144
2145 return OK;
2146 }
2147 else
2148 {
2149 PyErr_BadArgument();
2150 return FAIL;
2151 }
2152}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002153
2154/* Insert a number of lines into the specified buffer after the specifed line.
2155 * The line number is in Vim format (1-based). The lines to be inserted are
2156 * given as a Python list of string objects or as a single string. The lines
2157 * to be added are checked for validity and correct format. Errors are
2158 * returned as a value of FAIL. The return value is OK on success.
2159 * If OK is returned and len_change is not NULL, *len_change
2160 * is set to the change in the buffer length.
2161 */
2162 static int
2163InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2164{
2165 /* First of all, we check the type of the supplied Python object.
2166 * It must be a string or a list, or the call is in error.
2167 */
2168 if (PyString_Check(lines))
2169 {
2170 char *str = StringToLine(lines);
2171 buf_T *savebuf;
2172
2173 if (str == NULL)
2174 return FAIL;
2175
2176 savebuf = curbuf;
2177
2178 PyErr_Clear();
2179 curbuf = buf;
2180
2181 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2182 PyErr_SetVim(_("cannot save undo information"));
2183 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2184 PyErr_SetVim(_("cannot insert line"));
2185 else
2186 appended_lines_mark((linenr_T)n, 1L);
2187
2188 vim_free(str);
2189 curbuf = savebuf;
2190 update_screen(VALID);
2191
2192 if (PyErr_Occurred() || VimErrorCheck())
2193 return FAIL;
2194
2195 if (len_change)
2196 *len_change = 1;
2197
2198 return OK;
2199 }
2200 else if (PyList_Check(lines))
2201 {
2202 PyInt i;
2203 PyInt size = PyList_Size(lines);
2204 char **array;
2205 buf_T *savebuf;
2206
2207 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2208 if (array == NULL)
2209 {
2210 PyErr_NoMemory();
2211 return FAIL;
2212 }
2213
2214 for (i = 0; i < size; ++i)
2215 {
2216 PyObject *line = PyList_GetItem(lines, i);
2217 array[i] = StringToLine(line);
2218
2219 if (array[i] == NULL)
2220 {
2221 while (i)
2222 vim_free(array[--i]);
2223 vim_free(array);
2224 return FAIL;
2225 }
2226 }
2227
2228 savebuf = curbuf;
2229
2230 PyErr_Clear();
2231 curbuf = buf;
2232
2233 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2234 PyErr_SetVim(_("cannot save undo information"));
2235 else
2236 {
2237 for (i = 0; i < size; ++i)
2238 {
2239 if (ml_append((linenr_T)(n + i),
2240 (char_u *)array[i], 0, FALSE) == FAIL)
2241 {
2242 PyErr_SetVim(_("cannot insert line"));
2243
2244 /* Free the rest of the lines */
2245 while (i < size)
2246 vim_free(array[i++]);
2247
2248 break;
2249 }
2250 vim_free(array[i]);
2251 }
2252 if (i > 0)
2253 appended_lines_mark((linenr_T)n, (long)i);
2254 }
2255
2256 /* Free the array of lines. All of its contents have now
2257 * been freed.
2258 */
2259 vim_free(array);
2260
2261 curbuf = savebuf;
2262 update_screen(VALID);
2263
2264 if (PyErr_Occurred() || VimErrorCheck())
2265 return FAIL;
2266
2267 if (len_change)
2268 *len_change = size;
2269
2270 return OK;
2271 }
2272 else
2273 {
2274 PyErr_BadArgument();
2275 return FAIL;
2276 }
2277}
2278
2279/*
2280 * Common routines for buffers and line ranges
2281 * -------------------------------------------
2282 */
2283
2284 static int
2285CheckBuffer(BufferObject *this)
2286{
2287 if (this->buf == INVALID_BUFFER_VALUE)
2288 {
2289 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2290 return -1;
2291 }
2292
2293 return 0;
2294}
2295
2296 static PyObject *
2297RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2298{
2299 if (CheckBuffer(self))
2300 return NULL;
2301
2302 if (n < 0 || n > end - start)
2303 {
2304 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2305 return NULL;
2306 }
2307
2308 return GetBufferLine(self->buf, n+start);
2309}
2310
2311 static PyObject *
2312RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2313{
2314 PyInt size;
2315
2316 if (CheckBuffer(self))
2317 return NULL;
2318
2319 size = end - start + 1;
2320
2321 if (lo < 0)
2322 lo = 0;
2323 else if (lo > size)
2324 lo = size;
2325 if (hi < 0)
2326 hi = 0;
2327 if (hi < lo)
2328 hi = lo;
2329 else if (hi > size)
2330 hi = size;
2331
2332 return GetBufferLineList(self->buf, lo+start, hi+start);
2333}
2334
2335 static PyInt
2336RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2337{
2338 PyInt len_change;
2339
2340 if (CheckBuffer(self))
2341 return -1;
2342
2343 if (n < 0 || n > end - start)
2344 {
2345 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2346 return -1;
2347 }
2348
2349 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2350 return -1;
2351
2352 if (new_end)
2353 *new_end = end + len_change;
2354
2355 return 0;
2356}
2357
Bram Moolenaar19e60942011-06-19 00:27:51 +02002358 static PyInt
2359RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2360{
2361 PyInt size;
2362 PyInt len_change;
2363
2364 /* Self must be a valid buffer */
2365 if (CheckBuffer(self))
2366 return -1;
2367
2368 /* Sort out the slice range */
2369 size = end - start + 1;
2370
2371 if (lo < 0)
2372 lo = 0;
2373 else if (lo > size)
2374 lo = size;
2375 if (hi < 0)
2376 hi = 0;
2377 if (hi < lo)
2378 hi = lo;
2379 else if (hi > size)
2380 hi = size;
2381
2382 if (SetBufferLineList(self->buf, lo + start, hi + start,
2383 val, &len_change) == FAIL)
2384 return -1;
2385
2386 if (new_end)
2387 *new_end = end + len_change;
2388
2389 return 0;
2390}
2391
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002392
2393 static PyObject *
2394RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2395{
2396 PyObject *lines;
2397 PyInt len_change;
2398 PyInt max;
2399 PyInt n;
2400
2401 if (CheckBuffer(self))
2402 return NULL;
2403
2404 max = n = end - start + 1;
2405
2406 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2407 return NULL;
2408
2409 if (n < 0 || n > max)
2410 {
2411 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2412 return NULL;
2413 }
2414
2415 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2416 return NULL;
2417
2418 if (new_end)
2419 *new_end = end + len_change;
2420
2421 Py_INCREF(Py_None);
2422 return Py_None;
2423}
2424
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002425/* Range object - Definitions
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002426 */
2427
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002428static PyTypeObject RangeType;
2429
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002430typedef struct
2431{
2432 PyObject_HEAD
2433 BufferObject *buf;
2434 PyInt start;
2435 PyInt end;
2436} RangeObject;
2437
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002438static void RangeDestructor(PyObject *);
2439static PySequenceMethods RangeAsSeq;
2440static PyMappingMethods RangeAsMapping;
2441
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002442 static PyObject *
2443RangeNew(buf_T *buf, PyInt start, PyInt end)
2444{
2445 BufferObject *bufr;
2446 RangeObject *self;
2447 self = PyObject_NEW(RangeObject, &RangeType);
2448 if (self == NULL)
2449 return NULL;
2450
2451 bufr = (BufferObject *)BufferNew(buf);
2452 if (bufr == NULL)
2453 {
2454 Py_DECREF(self);
2455 return NULL;
2456 }
2457 Py_INCREF(bufr);
2458
2459 self->buf = bufr;
2460 self->start = start;
2461 self->end = end;
2462
2463 return (PyObject *)(self);
2464}
2465
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002466 static void
2467RangeDestructor(PyObject *self)
2468{
2469 Py_DECREF(((RangeObject *)(self))->buf);
2470 DESTRUCTOR_FINISH(self);
2471}
2472
2473static PyTypeObject BufferType;
2474static PyObject *BufferRepr(PyObject *);
2475static PySequenceMethods BufferAsSeq;
2476static PyMappingMethods BufferAsMapping;
2477
2478 static void
2479BufferDestructor(PyObject *self)
2480{
2481 BufferObject *this = (BufferObject *)(self);
2482
2483 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2484#if PY_MAJOR_VERSION >= 3
2485 this->buf->b_python3_ref = NULL;
2486#else
2487 this->buf->b_python_ref = NULL;
2488#endif
2489
2490 DESTRUCTOR_FINISH(self);
2491}
2492
2493 static PyObject *
2494BufferAttr(BufferObject *this, char *name)
2495{
2496 if (strcmp(name, "name") == 0)
2497 return Py_BuildValue("s", this->buf->b_ffname);
2498 else if (strcmp(name, "number") == 0)
2499 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02002500 else if (strcmp(name, "vars") == 0)
2501 return DictionaryNew(this->buf->b_vars);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002502 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02002503 return Py_BuildValue("[sss]", "name", "number", "vars");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002504 else
2505 return NULL;
2506}
2507
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002508 static PyObject *
2509BufferAppend(PyObject *self, PyObject *args)
2510{
2511 return RBAppend((BufferObject *)(self), args, 1,
2512 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2513 NULL);
2514}
2515
2516 static PyObject *
2517BufferMark(PyObject *self, PyObject *args)
2518{
2519 pos_T *posp;
2520 char *pmark;
2521 char mark;
2522 buf_T *curbuf_save;
2523
2524 if (CheckBuffer((BufferObject *)(self)))
2525 return NULL;
2526
2527 if (!PyArg_ParseTuple(args, "s", &pmark))
2528 return NULL;
2529 mark = *pmark;
2530
2531 curbuf_save = curbuf;
2532 curbuf = ((BufferObject *)(self))->buf;
2533 posp = getmark(mark, FALSE);
2534 curbuf = curbuf_save;
2535
2536 if (posp == NULL)
2537 {
2538 PyErr_SetVim(_("invalid mark name"));
2539 return NULL;
2540 }
2541
2542 /* Ckeck for keyboard interrupt */
2543 if (VimErrorCheck())
2544 return NULL;
2545
2546 if (posp->lnum <= 0)
2547 {
2548 /* Or raise an error? */
2549 Py_INCREF(Py_None);
2550 return Py_None;
2551 }
2552
2553 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2554}
2555
2556 static PyObject *
2557BufferRange(PyObject *self, PyObject *args)
2558{
2559 PyInt start;
2560 PyInt end;
2561
2562 if (CheckBuffer((BufferObject *)(self)))
2563 return NULL;
2564
2565 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2566 return NULL;
2567
2568 return RangeNew(((BufferObject *)(self))->buf, start, end);
2569}
2570
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002571 static PyObject *
2572BufferRepr(PyObject *self)
2573{
2574 static char repr[100];
2575 BufferObject *this = (BufferObject *)(self);
2576
2577 if (this->buf == INVALID_BUFFER_VALUE)
2578 {
2579 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2580 return PyString_FromString(repr);
2581 }
2582 else
2583 {
2584 char *name = (char *)this->buf->b_fname;
2585 PyInt len;
2586
2587 if (name == NULL)
2588 name = "";
2589 len = strlen(name);
2590
2591 if (len > 35)
2592 name = name + (35 - len);
2593
2594 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2595
2596 return PyString_FromString(repr);
2597 }
2598}
2599
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002600static struct PyMethodDef BufferMethods[] = {
2601 /* name, function, calling, documentation */
2602 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2603 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2604 {"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 +01002605#if PY_VERSION_HEX >= 0x03000000
2606 {"__dir__", BufferDir, 4, "List its attributes" },
2607#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002608 { NULL, NULL, 0, NULL }
2609};
2610
2611 static PyObject *
2612RangeAppend(PyObject *self, PyObject *args)
2613{
2614 return RBAppend(((RangeObject *)(self))->buf, args,
2615 ((RangeObject *)(self))->start,
2616 ((RangeObject *)(self))->end,
2617 &((RangeObject *)(self))->end);
2618}
2619
2620 static PyInt
2621RangeLength(PyObject *self)
2622{
2623 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2624 if (CheckBuffer(((RangeObject *)(self))->buf))
2625 return -1; /* ??? */
2626
2627 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2628}
2629
2630 static PyObject *
2631RangeItem(PyObject *self, PyInt n)
2632{
2633 return RBItem(((RangeObject *)(self))->buf, n,
2634 ((RangeObject *)(self))->start,
2635 ((RangeObject *)(self))->end);
2636}
2637
2638 static PyObject *
2639RangeRepr(PyObject *self)
2640{
2641 static char repr[100];
2642 RangeObject *this = (RangeObject *)(self);
2643
2644 if (this->buf->buf == INVALID_BUFFER_VALUE)
2645 {
2646 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2647 (self));
2648 return PyString_FromString(repr);
2649 }
2650 else
2651 {
2652 char *name = (char *)this->buf->buf->b_fname;
2653 int len;
2654
2655 if (name == NULL)
2656 name = "";
2657 len = (int)strlen(name);
2658
2659 if (len > 45)
2660 name = name + (45 - len);
2661
2662 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2663 len > 45 ? "..." : "", name,
2664 this->start, this->end);
2665
2666 return PyString_FromString(repr);
2667 }
2668}
2669
2670 static PyObject *
2671RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2672{
2673 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2674 ((RangeObject *)(self))->start,
2675 ((RangeObject *)(self))->end);
2676}
2677
2678/*
2679 * Line range object - Definitions
2680 */
2681
2682static struct PyMethodDef RangeMethods[] = {
2683 /* name, function, calling, documentation */
2684 {"append", RangeAppend, 1, "Append data to the Vim range" },
2685 { NULL, NULL, 0, NULL }
2686};
2687
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002688/* Current items object - Implementation
2689 */
2690
2691static PyInt RangeStart;
2692static PyInt RangeEnd;
2693
2694 static PyObject *
2695CurrentGetattr(PyObject *self UNUSED, char *name)
2696{
2697 if (strcmp(name, "buffer") == 0)
2698 return (PyObject *)BufferNew(curbuf);
2699 else if (strcmp(name, "window") == 0)
2700 return (PyObject *)WindowNew(curwin);
2701 else if (strcmp(name, "line") == 0)
2702 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2703 else if (strcmp(name, "range") == 0)
2704 return RangeNew(curbuf, RangeStart, RangeEnd);
2705 else if (strcmp(name,"__members__") == 0)
2706 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2707 else
2708 {
2709 PyErr_SetString(PyExc_AttributeError, name);
2710 return NULL;
2711 }
2712}
2713
2714 static int
2715CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2716{
2717 if (strcmp(name, "line") == 0)
2718 {
2719 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2720 return -1;
2721
2722 return 0;
2723 }
2724 else
2725 {
2726 PyErr_SetString(PyExc_AttributeError, name);
2727 return -1;
2728 }
2729}
2730
Bram Moolenaardb913952012-06-29 12:54:53 +02002731 static void
2732set_ref_in_py(const int copyID)
2733{
2734 pylinkedlist_T *cur;
2735 dict_T *dd;
2736 list_T *ll;
2737
2738 if (lastdict != NULL)
2739 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
2740 {
2741 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
2742 if (dd->dv_copyID != copyID)
2743 {
2744 dd->dv_copyID = copyID;
2745 set_ref_in_ht(&dd->dv_hashtab, copyID);
2746 }
2747 }
2748
2749 if (lastlist != NULL)
2750 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
2751 {
2752 ll = ((ListObject *) (cur->pll_obj))->list;
2753 if (ll->lv_copyID != copyID)
2754 {
2755 ll->lv_copyID = copyID;
2756 set_ref_in_list(ll, copyID);
2757 }
2758 }
2759}
2760
2761 static int
2762set_string_copy(char_u *str, typval_T *tv)
2763{
2764 tv->vval.v_string = vim_strsave(str);
2765 if (tv->vval.v_string == NULL)
2766 {
2767 PyErr_NoMemory();
2768 return -1;
2769 }
2770 return 0;
2771}
2772
Bram Moolenaardb913952012-06-29 12:54:53 +02002773typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
2774
2775 static int
2776convert_dl(PyObject *obj, typval_T *tv,
2777 pytotvfunc py_to_tv, PyObject *lookupDict)
2778{
2779 PyObject *capsule;
2780 char hexBuf[sizeof(void *) * 2 + 3];
2781
2782 sprintf(hexBuf, "%p", obj);
2783
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002784# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002785 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002786# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002787 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002788# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02002789 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02002790 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002791# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002792 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02002793# else
2794 capsule = PyCObject_FromVoidPtr(tv, NULL);
2795# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002796 PyDict_SetItemString(lookupDict, hexBuf, capsule);
2797 Py_DECREF(capsule);
2798 if (py_to_tv(obj, tv, lookupDict) == -1)
2799 {
2800 tv->v_type = VAR_UNKNOWN;
2801 return -1;
2802 }
2803 /* As we are not using copy_tv which increments reference count we must
2804 * do it ourself. */
2805 switch(tv->v_type)
2806 {
2807 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
2808 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
2809 }
2810 }
2811 else
2812 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002813 typval_T *v;
2814
2815# ifdef PY_USE_CAPSULE
2816 v = PyCapsule_GetPointer(capsule, NULL);
2817# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002818 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002819# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002820 copy_tv(v, tv);
2821 }
2822 return 0;
2823}
2824
2825 static int
2826ConvertFromPyObject(PyObject *obj, typval_T *tv)
2827{
2828 PyObject *lookup_dict;
2829 int r;
2830
2831 lookup_dict = PyDict_New();
2832 r = _ConvertFromPyObject(obj, tv, lookup_dict);
2833 Py_DECREF(lookup_dict);
2834 return r;
2835}
2836
2837 static int
2838_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2839{
2840 if (obj->ob_type == &DictionaryType)
2841 {
2842 tv->v_type = VAR_DICT;
2843 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
2844 ++tv->vval.v_dict->dv_refcount;
2845 }
2846 else if (obj->ob_type == &ListType)
2847 {
2848 tv->v_type = VAR_LIST;
2849 tv->vval.v_list = (((ListObject *)(obj))->list);
2850 ++tv->vval.v_list->lv_refcount;
2851 }
2852 else if (obj->ob_type == &FunctionType)
2853 {
2854 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
2855 return -1;
2856
2857 tv->v_type = VAR_FUNC;
2858 func_ref(tv->vval.v_string);
2859 }
Bram Moolenaardb913952012-06-29 12:54:53 +02002860 else if (PyBytes_Check(obj))
2861 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002862 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02002863
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002864 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
2865 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002866 if (result == NULL)
2867 return -1;
2868
2869 if (set_string_copy(result, tv) == -1)
2870 return -1;
2871
2872 tv->v_type = VAR_STRING;
2873 }
2874 else if (PyUnicode_Check(obj))
2875 {
2876 PyObject *bytes;
2877 char_u *result;
2878
Bram Moolenaardb913952012-06-29 12:54:53 +02002879 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
2880 if (bytes == NULL)
2881 return -1;
2882
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002883 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
2884 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002885 if (result == NULL)
2886 return -1;
2887
2888 if (set_string_copy(result, tv) == -1)
2889 {
2890 Py_XDECREF(bytes);
2891 return -1;
2892 }
2893 Py_XDECREF(bytes);
2894
2895 tv->v_type = VAR_STRING;
2896 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02002897#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02002898 else if (PyInt_Check(obj))
2899 {
2900 tv->v_type = VAR_NUMBER;
2901 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
2902 }
2903#endif
2904 else if (PyLong_Check(obj))
2905 {
2906 tv->v_type = VAR_NUMBER;
2907 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
2908 }
2909 else if (PyDict_Check(obj))
2910 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
2911#ifdef FEAT_FLOAT
2912 else if (PyFloat_Check(obj))
2913 {
2914 tv->v_type = VAR_FLOAT;
2915 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
2916 }
2917#endif
2918 else if (PyIter_Check(obj))
2919 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
2920 else if (PySequence_Check(obj))
2921 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
2922 else if (PyMapping_Check(obj))
2923 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
2924 else
2925 {
2926 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
2927 return -1;
2928 }
2929 return 0;
2930}
2931
2932 static PyObject *
2933ConvertToPyObject(typval_T *tv)
2934{
2935 if (tv == NULL)
2936 {
2937 PyErr_SetVim(_("NULL reference passed"));
2938 return NULL;
2939 }
2940 switch (tv->v_type)
2941 {
2942 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02002943 return PyBytes_FromString(tv->vval.v_string == NULL
2944 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02002945 case VAR_NUMBER:
2946 return PyLong_FromLong((long) tv->vval.v_number);
2947#ifdef FEAT_FLOAT
2948 case VAR_FLOAT:
2949 return PyFloat_FromDouble((double) tv->vval.v_float);
2950#endif
2951 case VAR_LIST:
2952 return ListNew(tv->vval.v_list);
2953 case VAR_DICT:
2954 return DictionaryNew(tv->vval.v_dict);
2955 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02002956 return FunctionNew(tv->vval.v_string == NULL
2957 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02002958 case VAR_UNKNOWN:
2959 Py_INCREF(Py_None);
2960 return Py_None;
2961 default:
2962 PyErr_SetVim(_("internal error: invalid value type"));
2963 return NULL;
2964 }
2965}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002966
2967typedef struct
2968{
2969 PyObject_HEAD
2970} CurrentObject;
2971static PyTypeObject CurrentType;
2972
2973 static void
2974init_structs(void)
2975{
2976 vim_memset(&OutputType, 0, sizeof(OutputType));
2977 OutputType.tp_name = "vim.message";
2978 OutputType.tp_basicsize = sizeof(OutputObject);
2979 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
2980 OutputType.tp_doc = "vim message object";
2981 OutputType.tp_methods = OutputMethods;
2982#if PY_MAJOR_VERSION >= 3
2983 OutputType.tp_getattro = OutputGetattro;
2984 OutputType.tp_setattro = OutputSetattro;
2985 OutputType.tp_alloc = call_PyType_GenericAlloc;
2986 OutputType.tp_new = call_PyType_GenericNew;
2987 OutputType.tp_free = call_PyObject_Free;
2988#else
2989 OutputType.tp_getattr = OutputGetattr;
2990 OutputType.tp_setattr = OutputSetattr;
2991#endif
2992
2993 vim_memset(&BufferType, 0, sizeof(BufferType));
2994 BufferType.tp_name = "vim.buffer";
2995 BufferType.tp_basicsize = sizeof(BufferType);
2996 BufferType.tp_dealloc = BufferDestructor;
2997 BufferType.tp_repr = BufferRepr;
2998 BufferType.tp_as_sequence = &BufferAsSeq;
2999 BufferType.tp_as_mapping = &BufferAsMapping;
3000 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3001 BufferType.tp_doc = "vim buffer object";
3002 BufferType.tp_methods = BufferMethods;
3003#if PY_MAJOR_VERSION >= 3
3004 BufferType.tp_getattro = BufferGetattro;
3005 BufferType.tp_alloc = call_PyType_GenericAlloc;
3006 BufferType.tp_new = call_PyType_GenericNew;
3007 BufferType.tp_free = call_PyObject_Free;
3008#else
3009 BufferType.tp_getattr = BufferGetattr;
3010#endif
3011
3012 vim_memset(&WindowType, 0, sizeof(WindowType));
3013 WindowType.tp_name = "vim.window";
3014 WindowType.tp_basicsize = sizeof(WindowObject);
3015 WindowType.tp_dealloc = WindowDestructor;
3016 WindowType.tp_repr = WindowRepr;
3017 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3018 WindowType.tp_doc = "vim Window object";
3019 WindowType.tp_methods = WindowMethods;
3020#if PY_MAJOR_VERSION >= 3
3021 WindowType.tp_getattro = WindowGetattro;
3022 WindowType.tp_setattro = WindowSetattro;
3023 WindowType.tp_alloc = call_PyType_GenericAlloc;
3024 WindowType.tp_new = call_PyType_GenericNew;
3025 WindowType.tp_free = call_PyObject_Free;
3026#else
3027 WindowType.tp_getattr = WindowGetattr;
3028 WindowType.tp_setattr = WindowSetattr;
3029#endif
3030
3031 vim_memset(&BufListType, 0, sizeof(BufListType));
3032 BufListType.tp_name = "vim.bufferlist";
3033 BufListType.tp_basicsize = sizeof(BufListObject);
3034 BufListType.tp_as_sequence = &BufListAsSeq;
3035 BufListType.tp_flags = Py_TPFLAGS_DEFAULT;
3036 BufferType.tp_doc = "vim buffer list";
3037
3038 vim_memset(&WinListType, 0, sizeof(WinListType));
3039 WinListType.tp_name = "vim.windowlist";
3040 WinListType.tp_basicsize = sizeof(WinListType);
3041 WinListType.tp_as_sequence = &WinListAsSeq;
3042 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3043 WinListType.tp_doc = "vim window list";
3044
3045 vim_memset(&RangeType, 0, sizeof(RangeType));
3046 RangeType.tp_name = "vim.range";
3047 RangeType.tp_basicsize = sizeof(RangeObject);
3048 RangeType.tp_dealloc = RangeDestructor;
3049 RangeType.tp_repr = RangeRepr;
3050 RangeType.tp_as_sequence = &RangeAsSeq;
3051 RangeType.tp_as_mapping = &RangeAsMapping;
3052 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3053 RangeType.tp_doc = "vim Range object";
3054 RangeType.tp_methods = RangeMethods;
3055#if PY_MAJOR_VERSION >= 3
3056 RangeType.tp_getattro = RangeGetattro;
3057 RangeType.tp_alloc = call_PyType_GenericAlloc;
3058 RangeType.tp_new = call_PyType_GenericNew;
3059 RangeType.tp_free = call_PyObject_Free;
3060#else
3061 RangeType.tp_getattr = RangeGetattr;
3062#endif
3063
3064 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3065 CurrentType.tp_name = "vim.currentdata";
3066 CurrentType.tp_basicsize = sizeof(CurrentObject);
3067 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3068 CurrentType.tp_doc = "vim current object";
3069#if PY_MAJOR_VERSION >= 3
3070 CurrentType.tp_getattro = CurrentGetattro;
3071 CurrentType.tp_setattro = CurrentSetattro;
3072#else
3073 CurrentType.tp_getattr = CurrentGetattr;
3074 CurrentType.tp_setattr = CurrentSetattr;
3075#endif
3076
3077 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3078 DictionaryType.tp_name = "vim.dictionary";
3079 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3080 DictionaryType.tp_dealloc = DictionaryDestructor;
3081 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3082 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3083 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3084 DictionaryType.tp_methods = DictionaryMethods;
3085#if PY_MAJOR_VERSION >= 3
3086 DictionaryType.tp_getattro = DictionaryGetattro;
3087 DictionaryType.tp_setattro = DictionarySetattro;
3088#else
3089 DictionaryType.tp_getattr = DictionaryGetattr;
3090 DictionaryType.tp_setattr = DictionarySetattr;
3091#endif
3092
3093 vim_memset(&ListType, 0, sizeof(ListType));
3094 ListType.tp_name = "vim.list";
3095 ListType.tp_dealloc = ListDestructor;
3096 ListType.tp_basicsize = sizeof(ListObject);
3097 ListType.tp_as_sequence = &ListAsSeq;
3098 ListType.tp_as_mapping = &ListAsMapping;
3099 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3100 ListType.tp_doc = "list pushing modifications to vim structure";
3101 ListType.tp_methods = ListMethods;
3102#if PY_MAJOR_VERSION >= 3
3103 ListType.tp_getattro = ListGetattro;
3104 ListType.tp_setattro = ListSetattro;
3105#else
3106 ListType.tp_getattr = ListGetattr;
3107 ListType.tp_setattr = ListSetattr;
3108#endif
3109
3110 vim_memset(&FunctionType, 0, sizeof(FunctionType));
3111 FunctionType.tp_name = "vim.list";
3112 FunctionType.tp_basicsize = sizeof(FunctionObject);
3113 FunctionType.tp_dealloc = FunctionDestructor;
3114 FunctionType.tp_call = FunctionCall;
3115 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3116 FunctionType.tp_doc = "object that calls vim function";
3117 FunctionType.tp_methods = FunctionMethods;
3118#if PY_MAJOR_VERSION >= 3
3119 FunctionType.tp_getattro = FunctionGetattro;
3120#else
3121 FunctionType.tp_getattr = FunctionGetattr;
3122#endif
3123
3124#if PY_MAJOR_VERSION >= 3
3125 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3126 vimmodule.m_name = "vim";
3127 vimmodule.m_doc = "Vim Python interface\n";
3128 vimmodule.m_size = -1;
3129 vimmodule.m_methods = VimMethods;
3130#endif
3131}