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