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