blob: 0f9f3538ab2bc874d5f94b824dd0eecc691b7d52 [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;
1524
1525 if (this->Check(this->from))
1526 return NULL;
1527
1528 DICTKEY_DECL
1529
1530 DICTKEY_GET_NOTEMPTY(NULL)
1531
1532 flags = get_option_value_strict(key, &numval, &stringval,
1533 this->opt_type, this->from);
1534
1535 DICTKEY_UNREF
1536
1537 if (flags == 0)
1538 {
1539 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1540 return NULL;
1541 }
1542
1543 if (flags & SOPT_UNSET)
1544 {
1545 Py_INCREF(Py_None);
1546 return Py_None;
1547 }
1548 else if (flags & SOPT_BOOL)
1549 {
1550 PyObject *r;
1551 r = numval ? Py_True : Py_False;
1552 Py_INCREF(r);
1553 return r;
1554 }
1555 else if (flags & SOPT_NUM)
1556 return PyInt_FromLong(numval);
1557 else if (flags & SOPT_STRING)
1558 {
1559 if (stringval)
1560 return PyBytes_FromString((char *) stringval);
1561 else
1562 {
1563 PyErr_SetString(PyExc_ValueError, "Unable to get option value");
1564 return NULL;
1565 }
1566 }
1567 else
1568 {
1569 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1570 return NULL;
1571 }
1572}
1573
1574 static int
1575set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1576 char_u *key;
1577 int numval;
1578 char_u *stringval;
1579 int opt_flags;
1580 int opt_type;
1581 void *from;
1582{
1583 win_T *save_curwin;
1584 tabpage_T *save_curtab;
1585 aco_save_T aco;
1586 int r = 0;
1587
1588 switch (opt_type)
1589 {
1590 case SREQ_WIN:
1591 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1592 == FAIL)
1593 {
1594 PyErr_SetVim("Problem while switching windows.");
1595 return -1;
1596 }
1597 set_option_value(key, numval, stringval, opt_flags);
1598 restore_win(save_curwin, save_curtab);
1599 break;
1600 case SREQ_BUF:
1601 aucmd_prepbuf(&aco, (buf_T *) from);
1602 set_option_value(key, numval, stringval, opt_flags);
1603 aucmd_restbuf(&aco);
1604 break;
1605 case SREQ_GLOBAL:
1606 set_option_value(key, numval, stringval, opt_flags);
1607 break;
1608 }
1609 return r;
1610}
1611
1612 static int
1613OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1614{
1615 char_u *key;
1616 int flags;
1617 int opt_flags;
1618 int r = 0;
1619
1620 if (this->Check(this->from))
1621 return -1;
1622
1623 DICTKEY_DECL
1624
1625 DICTKEY_GET_NOTEMPTY(-1)
1626
1627 flags = get_option_value_strict(key, NULL, NULL,
1628 this->opt_type, this->from);
1629
1630 DICTKEY_UNREF
1631
1632 if (flags == 0)
1633 {
1634 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1635 return -1;
1636 }
1637
1638 if (valObject == NULL)
1639 {
1640 if (this->opt_type == SREQ_GLOBAL)
1641 {
1642 PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
1643 return -1;
1644 }
1645 else if (!(flags & SOPT_GLOBAL))
1646 {
1647 PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
1648 "global value");
1649 return -1;
1650 }
1651 else
1652 {
1653 unset_global_local_option(key, this->from);
1654 return 0;
1655 }
1656 }
1657
1658 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1659
1660 if (flags & SOPT_BOOL)
1661 {
1662 if (!PyBool_Check(valObject))
1663 {
1664 PyErr_SetString(PyExc_ValueError, "Object must be boolean");
1665 return -1;
1666 }
1667
1668 r = set_option_value_for(key, (valObject == Py_True), NULL, opt_flags,
1669 this->opt_type, this->from);
1670 }
1671 else if (flags & SOPT_NUM)
1672 {
1673 int val;
1674
1675#if PY_MAJOR_VERSION < 3
1676 if (PyInt_Check(valObject))
1677 val = PyInt_AsLong(valObject);
1678 else
1679#endif
1680 if (PyLong_Check(valObject))
1681 val = PyLong_AsLong(valObject);
1682 else
1683 {
1684 PyErr_SetString(PyExc_ValueError, "Object must be integer");
1685 return -1;
1686 }
1687
1688 r = set_option_value_for(key, val, NULL, opt_flags,
1689 this->opt_type, this->from);
1690 }
1691 else
1692 {
1693 char_u *val;
1694 if (PyBytes_Check(valObject))
1695 {
1696
1697 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1698 return -1;
1699 if (val == NULL)
1700 return -1;
1701
1702 val = vim_strsave(val);
1703 }
1704 else if (PyUnicode_Check(valObject))
1705 {
1706 PyObject *bytes;
1707
1708 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1709 if (bytes == NULL)
1710 return -1;
1711
1712 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1713 return -1;
1714 if (val == NULL)
1715 return -1;
1716
1717 val = vim_strsave(val);
1718 Py_XDECREF(bytes);
1719 }
1720 else
1721 {
1722 PyErr_SetString(PyExc_ValueError, "Object must be string");
1723 return -1;
1724 }
1725
1726 r = set_option_value_for(key, 0, val, opt_flags,
1727 this->opt_type, this->from);
1728 vim_free(val);
1729 }
1730
1731 return r;
1732}
1733
1734 static int
1735dummy_check(void *arg UNUSED)
1736{
1737 return 0;
1738}
1739
1740 static PyObject *
1741OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1742{
1743 OptionsObject *self;
1744
1745 self = PyObject_NEW(OptionsObject, &OptionsType);
1746 if (self == NULL)
1747 return NULL;
1748
1749 self->opt_type = opt_type;
1750 self->from = from;
1751 self->Check = Check;
1752 self->fromObj = fromObj;
1753 if (fromObj)
1754 Py_INCREF(fromObj);
1755
1756 return (PyObject *)(self);
1757}
1758
1759 static void
1760OptionsDestructor(PyObject *self)
1761{
1762 if (((OptionsObject *)(self))->fromObj)
1763 Py_DECREF(((OptionsObject *)(self))->fromObj);
1764 DESTRUCTOR_FINISH(self);
1765}
1766
1767static PyMappingMethods OptionsAsMapping = {
1768 (lenfunc) NULL,
1769 (binaryfunc) OptionsItem,
1770 (objobjargproc) OptionsAssItem,
1771};
1772
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001773#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1774
1775 static int
1776CheckWindow(WindowObject *this)
1777{
1778 if (this->win == INVALID_WINDOW_VALUE)
1779 {
1780 PyErr_SetVim(_("attempt to refer to deleted window"));
1781 return -1;
1782 }
1783
1784 return 0;
1785}
1786
1787static int WindowSetattr(PyObject *, char *, PyObject *);
1788static PyObject *WindowRepr(PyObject *);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001789static PyTypeObject WindowType;
1790
1791 static PyObject *
1792WindowAttr(WindowObject *this, char *name)
1793{
1794 if (strcmp(name, "buffer") == 0)
1795 return (PyObject *)BufferNew(this->win->w_buffer);
1796 else if (strcmp(name, "cursor") == 0)
1797 {
1798 pos_T *pos = &this->win->w_cursor;
1799
1800 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1801 }
1802 else if (strcmp(name, "height") == 0)
1803 return Py_BuildValue("l", (long)(this->win->w_height));
1804#ifdef FEAT_VERTSPLIT
1805 else if (strcmp(name, "width") == 0)
1806 return Py_BuildValue("l", (long)(W_WIDTH(this->win)));
1807#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001808 else if (strcmp(name, "vars") == 0)
1809 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001810 else if (strcmp(name, "options") == 0)
1811 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1812 (PyObject *) this);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001813 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001814 return Py_BuildValue("[sssss]", "buffer", "cursor", "height", "vars",
1815 "options");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001816 else
1817 return NULL;
1818}
1819
1820 static void
1821WindowDestructor(PyObject *self)
1822{
1823 WindowObject *this = (WindowObject *)(self);
1824
1825 if (this->win && this->win != INVALID_WINDOW_VALUE)
1826#if PY_MAJOR_VERSION >= 3
1827 this->win->w_python3_ref = NULL;
1828#else
1829 this->win->w_python_ref = NULL;
1830#endif
1831
1832 DESTRUCTOR_FINISH(self);
1833}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001834
1835 static int
1836WindowSetattr(PyObject *self, char *name, PyObject *val)
1837{
1838 WindowObject *this = (WindowObject *)(self);
1839
1840 if (CheckWindow(this))
1841 return -1;
1842
1843 if (strcmp(name, "buffer") == 0)
1844 {
1845 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1846 return -1;
1847 }
1848 else if (strcmp(name, "cursor") == 0)
1849 {
1850 long lnum;
1851 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001852
1853 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1854 return -1;
1855
1856 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1857 {
1858 PyErr_SetVim(_("cursor position outside buffer"));
1859 return -1;
1860 }
1861
1862 /* Check for keyboard interrupts */
1863 if (VimErrorCheck())
1864 return -1;
1865
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001866 this->win->w_cursor.lnum = lnum;
1867 this->win->w_cursor.col = col;
1868#ifdef FEAT_VIRTUALEDIT
1869 this->win->w_cursor.coladd = 0;
1870#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001871 /* When column is out of range silently correct it. */
1872 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001873
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001874 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001875 return 0;
1876 }
1877 else if (strcmp(name, "height") == 0)
1878 {
1879 int height;
1880 win_T *savewin;
1881
1882 if (!PyArg_Parse(val, "i", &height))
1883 return -1;
1884
1885#ifdef FEAT_GUI
1886 need_mouse_correct = TRUE;
1887#endif
1888 savewin = curwin;
1889 curwin = this->win;
1890 win_setheight(height);
1891 curwin = savewin;
1892
1893 /* Check for keyboard interrupts */
1894 if (VimErrorCheck())
1895 return -1;
1896
1897 return 0;
1898 }
1899#ifdef FEAT_VERTSPLIT
1900 else if (strcmp(name, "width") == 0)
1901 {
1902 int width;
1903 win_T *savewin;
1904
1905 if (!PyArg_Parse(val, "i", &width))
1906 return -1;
1907
1908#ifdef FEAT_GUI
1909 need_mouse_correct = TRUE;
1910#endif
1911 savewin = curwin;
1912 curwin = this->win;
1913 win_setwidth(width);
1914 curwin = savewin;
1915
1916 /* Check for keyboard interrupts */
1917 if (VimErrorCheck())
1918 return -1;
1919
1920 return 0;
1921 }
1922#endif
1923 else
1924 {
1925 PyErr_SetString(PyExc_AttributeError, name);
1926 return -1;
1927 }
1928}
1929
1930 static PyObject *
1931WindowRepr(PyObject *self)
1932{
1933 static char repr[100];
1934 WindowObject *this = (WindowObject *)(self);
1935
1936 if (this->win == INVALID_WINDOW_VALUE)
1937 {
1938 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1939 return PyString_FromString(repr);
1940 }
1941 else
1942 {
1943 int i = 0;
1944 win_T *w;
1945
1946 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
1947 ++i;
1948
1949 if (w == NULL)
1950 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1951 (self));
1952 else
1953 vim_snprintf(repr, 100, _("<window %d>"), i);
1954
1955 return PyString_FromString(repr);
1956 }
1957}
1958
1959/*
1960 * Window list object - Implementation
1961 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001962
1963typedef struct
1964{
1965 PyObject_HEAD
1966} WinListObject;
1967
1968static PyTypeObject WinListType;
1969static PySequenceMethods BufListAsSeq;
1970
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001971 static PyInt
1972WinListLength(PyObject *self UNUSED)
1973{
1974 win_T *w = firstwin;
1975 PyInt n = 0;
1976
1977 while (w != NULL)
1978 {
1979 ++n;
1980 w = W_NEXT(w);
1981 }
1982
1983 return n;
1984}
1985
1986 static PyObject *
1987WinListItem(PyObject *self UNUSED, PyInt n)
1988{
1989 win_T *w;
1990
1991 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1992 if (n == 0)
1993 return WindowNew(w);
1994
1995 PyErr_SetString(PyExc_IndexError, _("no such window"));
1996 return NULL;
1997}
1998
1999/* Convert a Python string into a Vim line.
2000 *
2001 * The result is in allocated memory. All internal nulls are replaced by
2002 * newline characters. It is an error for the string to contain newline
2003 * characters.
2004 *
2005 * On errors, the Python exception data is set, and NULL is returned.
2006 */
2007 static char *
2008StringToLine(PyObject *obj)
2009{
2010 const char *str;
2011 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002012 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002013 PyInt len;
2014 PyInt i;
2015 char *p;
2016
2017 if (obj == NULL || !PyString_Check(obj))
2018 {
2019 PyErr_BadArgument();
2020 return NULL;
2021 }
2022
Bram Moolenaar19e60942011-06-19 00:27:51 +02002023 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
2024 str = PyString_AsString(bytes);
2025 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002026
2027 /*
2028 * Error checking: String must not contain newlines, as we
2029 * are replacing a single line, and we must replace it with
2030 * a single line.
2031 * A trailing newline is removed, so that append(f.readlines()) works.
2032 */
2033 p = memchr(str, '\n', len);
2034 if (p != NULL)
2035 {
2036 if (p == str + len - 1)
2037 --len;
2038 else
2039 {
2040 PyErr_SetVim(_("string cannot contain newlines"));
2041 return NULL;
2042 }
2043 }
2044
2045 /* Create a copy of the string, with internal nulls replaced by
2046 * newline characters, as is the vim convention.
2047 */
2048 save = (char *)alloc((unsigned)(len+1));
2049 if (save == NULL)
2050 {
2051 PyErr_NoMemory();
2052 return NULL;
2053 }
2054
2055 for (i = 0; i < len; ++i)
2056 {
2057 if (str[i] == '\0')
2058 save[i] = '\n';
2059 else
2060 save[i] = str[i];
2061 }
2062
2063 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02002064 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002065
2066 return save;
2067}
2068
2069/* Get a line from the specified buffer. The line number is
2070 * in Vim format (1-based). The line is returned as a Python
2071 * string object.
2072 */
2073 static PyObject *
2074GetBufferLine(buf_T *buf, PyInt n)
2075{
2076 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2077}
2078
2079
2080/* Get a list of lines from the specified buffer. The line numbers
2081 * are in Vim format (1-based). The range is from lo up to, but not
2082 * including, hi. The list is returned as a Python list of string objects.
2083 */
2084 static PyObject *
2085GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2086{
2087 PyInt i;
2088 PyInt n = hi - lo;
2089 PyObject *list = PyList_New(n);
2090
2091 if (list == NULL)
2092 return NULL;
2093
2094 for (i = 0; i < n; ++i)
2095 {
2096 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2097
2098 /* Error check - was the Python string creation OK? */
2099 if (str == NULL)
2100 {
2101 Py_DECREF(list);
2102 return NULL;
2103 }
2104
2105 /* Set the list item */
2106 if (PyList_SetItem(list, i, str))
2107 {
2108 Py_DECREF(str);
2109 Py_DECREF(list);
2110 return NULL;
2111 }
2112 }
2113
2114 /* The ownership of the Python list is passed to the caller (ie,
2115 * the caller should Py_DECREF() the object when it is finished
2116 * with it).
2117 */
2118
2119 return list;
2120}
2121
2122/*
2123 * Check if deleting lines made the cursor position invalid.
2124 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2125 * deleted).
2126 */
2127 static void
2128py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2129{
2130 if (curwin->w_cursor.lnum >= lo)
2131 {
2132 /* Adjust the cursor position if it's in/after the changed
2133 * lines. */
2134 if (curwin->w_cursor.lnum >= hi)
2135 {
2136 curwin->w_cursor.lnum += extra;
2137 check_cursor_col();
2138 }
2139 else if (extra < 0)
2140 {
2141 curwin->w_cursor.lnum = lo;
2142 check_cursor();
2143 }
2144 else
2145 check_cursor_col();
2146 changed_cline_bef_curs();
2147 }
2148 invalidate_botline();
2149}
2150
Bram Moolenaar19e60942011-06-19 00:27:51 +02002151/*
2152 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002153 * in Vim format (1-based). The replacement line is given as
2154 * a Python string object. The object is checked for validity
2155 * and correct format. Errors are returned as a value of FAIL.
2156 * The return value is OK on success.
2157 * If OK is returned and len_change is not NULL, *len_change
2158 * is set to the change in the buffer length.
2159 */
2160 static int
2161SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2162{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002163 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002164 * There are three cases:
2165 * 1. NULL, or None - this is a deletion.
2166 * 2. A string - this is a replacement.
2167 * 3. Anything else - this is an error.
2168 */
2169 if (line == Py_None || line == NULL)
2170 {
2171 buf_T *savebuf = curbuf;
2172
2173 PyErr_Clear();
2174 curbuf = buf;
2175
2176 if (u_savedel((linenr_T)n, 1L) == FAIL)
2177 PyErr_SetVim(_("cannot save undo information"));
2178 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2179 PyErr_SetVim(_("cannot delete line"));
2180 else
2181 {
2182 if (buf == curwin->w_buffer)
2183 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2184 deleted_lines_mark((linenr_T)n, 1L);
2185 }
2186
2187 curbuf = savebuf;
2188
2189 if (PyErr_Occurred() || VimErrorCheck())
2190 return FAIL;
2191
2192 if (len_change)
2193 *len_change = -1;
2194
2195 return OK;
2196 }
2197 else if (PyString_Check(line))
2198 {
2199 char *save = StringToLine(line);
2200 buf_T *savebuf = curbuf;
2201
2202 if (save == NULL)
2203 return FAIL;
2204
2205 /* We do not need to free "save" if ml_replace() consumes it. */
2206 PyErr_Clear();
2207 curbuf = buf;
2208
2209 if (u_savesub((linenr_T)n) == FAIL)
2210 {
2211 PyErr_SetVim(_("cannot save undo information"));
2212 vim_free(save);
2213 }
2214 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2215 {
2216 PyErr_SetVim(_("cannot replace line"));
2217 vim_free(save);
2218 }
2219 else
2220 changed_bytes((linenr_T)n, 0);
2221
2222 curbuf = savebuf;
2223
2224 /* Check that the cursor is not beyond the end of the line now. */
2225 if (buf == curwin->w_buffer)
2226 check_cursor_col();
2227
2228 if (PyErr_Occurred() || VimErrorCheck())
2229 return FAIL;
2230
2231 if (len_change)
2232 *len_change = 0;
2233
2234 return OK;
2235 }
2236 else
2237 {
2238 PyErr_BadArgument();
2239 return FAIL;
2240 }
2241}
2242
Bram Moolenaar19e60942011-06-19 00:27:51 +02002243/* Replace a range of lines in the specified buffer. The line numbers are in
2244 * Vim format (1-based). The range is from lo up to, but not including, hi.
2245 * The replacement lines are given as a Python list of string objects. The
2246 * list is checked for validity and correct format. Errors are returned as a
2247 * value of FAIL. The return value is OK on success.
2248 * If OK is returned and len_change is not NULL, *len_change
2249 * is set to the change in the buffer length.
2250 */
2251 static int
2252SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2253{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002254 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002255 * There are three cases:
2256 * 1. NULL, or None - this is a deletion.
2257 * 2. A list - this is a replacement.
2258 * 3. Anything else - this is an error.
2259 */
2260 if (list == Py_None || list == NULL)
2261 {
2262 PyInt i;
2263 PyInt n = (int)(hi - lo);
2264 buf_T *savebuf = curbuf;
2265
2266 PyErr_Clear();
2267 curbuf = buf;
2268
2269 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2270 PyErr_SetVim(_("cannot save undo information"));
2271 else
2272 {
2273 for (i = 0; i < n; ++i)
2274 {
2275 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2276 {
2277 PyErr_SetVim(_("cannot delete line"));
2278 break;
2279 }
2280 }
2281 if (buf == curwin->w_buffer)
2282 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2283 deleted_lines_mark((linenr_T)lo, (long)i);
2284 }
2285
2286 curbuf = savebuf;
2287
2288 if (PyErr_Occurred() || VimErrorCheck())
2289 return FAIL;
2290
2291 if (len_change)
2292 *len_change = -n;
2293
2294 return OK;
2295 }
2296 else if (PyList_Check(list))
2297 {
2298 PyInt i;
2299 PyInt new_len = PyList_Size(list);
2300 PyInt old_len = hi - lo;
2301 PyInt extra = 0; /* lines added to text, can be negative */
2302 char **array;
2303 buf_T *savebuf;
2304
2305 if (new_len == 0) /* avoid allocating zero bytes */
2306 array = NULL;
2307 else
2308 {
2309 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2310 if (array == NULL)
2311 {
2312 PyErr_NoMemory();
2313 return FAIL;
2314 }
2315 }
2316
2317 for (i = 0; i < new_len; ++i)
2318 {
2319 PyObject *line = PyList_GetItem(list, i);
2320
2321 array[i] = StringToLine(line);
2322 if (array[i] == NULL)
2323 {
2324 while (i)
2325 vim_free(array[--i]);
2326 vim_free(array);
2327 return FAIL;
2328 }
2329 }
2330
2331 savebuf = curbuf;
2332
2333 PyErr_Clear();
2334 curbuf = buf;
2335
2336 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2337 PyErr_SetVim(_("cannot save undo information"));
2338
2339 /* If the size of the range is reducing (ie, new_len < old_len) we
2340 * need to delete some old_len. We do this at the start, by
2341 * repeatedly deleting line "lo".
2342 */
2343 if (!PyErr_Occurred())
2344 {
2345 for (i = 0; i < old_len - new_len; ++i)
2346 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2347 {
2348 PyErr_SetVim(_("cannot delete line"));
2349 break;
2350 }
2351 extra -= i;
2352 }
2353
2354 /* For as long as possible, replace the existing old_len with the
2355 * new old_len. This is a more efficient operation, as it requires
2356 * less memory allocation and freeing.
2357 */
2358 if (!PyErr_Occurred())
2359 {
2360 for (i = 0; i < old_len && i < new_len; ++i)
2361 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2362 == FAIL)
2363 {
2364 PyErr_SetVim(_("cannot replace line"));
2365 break;
2366 }
2367 }
2368 else
2369 i = 0;
2370
2371 /* Now we may need to insert the remaining new old_len. If we do, we
2372 * must free the strings as we finish with them (we can't pass the
2373 * responsibility to vim in this case).
2374 */
2375 if (!PyErr_Occurred())
2376 {
2377 while (i < new_len)
2378 {
2379 if (ml_append((linenr_T)(lo + i - 1),
2380 (char_u *)array[i], 0, FALSE) == FAIL)
2381 {
2382 PyErr_SetVim(_("cannot insert line"));
2383 break;
2384 }
2385 vim_free(array[i]);
2386 ++i;
2387 ++extra;
2388 }
2389 }
2390
2391 /* Free any left-over old_len, as a result of an error */
2392 while (i < new_len)
2393 {
2394 vim_free(array[i]);
2395 ++i;
2396 }
2397
2398 /* Free the array of old_len. All of its contents have now
2399 * been dealt with (either freed, or the responsibility passed
2400 * to vim.
2401 */
2402 vim_free(array);
2403
2404 /* Adjust marks. Invalidate any which lie in the
2405 * changed range, and move any in the remainder of the buffer.
2406 */
2407 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2408 (long)MAXLNUM, (long)extra);
2409 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2410
2411 if (buf == curwin->w_buffer)
2412 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2413
2414 curbuf = savebuf;
2415
2416 if (PyErr_Occurred() || VimErrorCheck())
2417 return FAIL;
2418
2419 if (len_change)
2420 *len_change = new_len - old_len;
2421
2422 return OK;
2423 }
2424 else
2425 {
2426 PyErr_BadArgument();
2427 return FAIL;
2428 }
2429}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002430
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002431/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002432 * The line number is in Vim format (1-based). The lines to be inserted are
2433 * given as a Python list of string objects or as a single string. The lines
2434 * to be added are checked for validity and correct format. Errors are
2435 * returned as a value of FAIL. The return value is OK on success.
2436 * If OK is returned and len_change is not NULL, *len_change
2437 * is set to the change in the buffer length.
2438 */
2439 static int
2440InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2441{
2442 /* First of all, we check the type of the supplied Python object.
2443 * It must be a string or a list, or the call is in error.
2444 */
2445 if (PyString_Check(lines))
2446 {
2447 char *str = StringToLine(lines);
2448 buf_T *savebuf;
2449
2450 if (str == NULL)
2451 return FAIL;
2452
2453 savebuf = curbuf;
2454
2455 PyErr_Clear();
2456 curbuf = buf;
2457
2458 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2459 PyErr_SetVim(_("cannot save undo information"));
2460 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2461 PyErr_SetVim(_("cannot insert line"));
2462 else
2463 appended_lines_mark((linenr_T)n, 1L);
2464
2465 vim_free(str);
2466 curbuf = savebuf;
2467 update_screen(VALID);
2468
2469 if (PyErr_Occurred() || VimErrorCheck())
2470 return FAIL;
2471
2472 if (len_change)
2473 *len_change = 1;
2474
2475 return OK;
2476 }
2477 else if (PyList_Check(lines))
2478 {
2479 PyInt i;
2480 PyInt size = PyList_Size(lines);
2481 char **array;
2482 buf_T *savebuf;
2483
2484 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2485 if (array == NULL)
2486 {
2487 PyErr_NoMemory();
2488 return FAIL;
2489 }
2490
2491 for (i = 0; i < size; ++i)
2492 {
2493 PyObject *line = PyList_GetItem(lines, i);
2494 array[i] = StringToLine(line);
2495
2496 if (array[i] == NULL)
2497 {
2498 while (i)
2499 vim_free(array[--i]);
2500 vim_free(array);
2501 return FAIL;
2502 }
2503 }
2504
2505 savebuf = curbuf;
2506
2507 PyErr_Clear();
2508 curbuf = buf;
2509
2510 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2511 PyErr_SetVim(_("cannot save undo information"));
2512 else
2513 {
2514 for (i = 0; i < size; ++i)
2515 {
2516 if (ml_append((linenr_T)(n + i),
2517 (char_u *)array[i], 0, FALSE) == FAIL)
2518 {
2519 PyErr_SetVim(_("cannot insert line"));
2520
2521 /* Free the rest of the lines */
2522 while (i < size)
2523 vim_free(array[i++]);
2524
2525 break;
2526 }
2527 vim_free(array[i]);
2528 }
2529 if (i > 0)
2530 appended_lines_mark((linenr_T)n, (long)i);
2531 }
2532
2533 /* Free the array of lines. All of its contents have now
2534 * been freed.
2535 */
2536 vim_free(array);
2537
2538 curbuf = savebuf;
2539 update_screen(VALID);
2540
2541 if (PyErr_Occurred() || VimErrorCheck())
2542 return FAIL;
2543
2544 if (len_change)
2545 *len_change = size;
2546
2547 return OK;
2548 }
2549 else
2550 {
2551 PyErr_BadArgument();
2552 return FAIL;
2553 }
2554}
2555
2556/*
2557 * Common routines for buffers and line ranges
2558 * -------------------------------------------
2559 */
2560
2561 static int
2562CheckBuffer(BufferObject *this)
2563{
2564 if (this->buf == INVALID_BUFFER_VALUE)
2565 {
2566 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2567 return -1;
2568 }
2569
2570 return 0;
2571}
2572
2573 static PyObject *
2574RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2575{
2576 if (CheckBuffer(self))
2577 return NULL;
2578
2579 if (n < 0 || n > end - start)
2580 {
2581 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2582 return NULL;
2583 }
2584
2585 return GetBufferLine(self->buf, n+start);
2586}
2587
2588 static PyObject *
2589RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2590{
2591 PyInt size;
2592
2593 if (CheckBuffer(self))
2594 return NULL;
2595
2596 size = end - start + 1;
2597
2598 if (lo < 0)
2599 lo = 0;
2600 else if (lo > size)
2601 lo = size;
2602 if (hi < 0)
2603 hi = 0;
2604 if (hi < lo)
2605 hi = lo;
2606 else if (hi > size)
2607 hi = size;
2608
2609 return GetBufferLineList(self->buf, lo+start, hi+start);
2610}
2611
2612 static PyInt
2613RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2614{
2615 PyInt len_change;
2616
2617 if (CheckBuffer(self))
2618 return -1;
2619
2620 if (n < 0 || n > end - start)
2621 {
2622 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2623 return -1;
2624 }
2625
2626 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2627 return -1;
2628
2629 if (new_end)
2630 *new_end = end + len_change;
2631
2632 return 0;
2633}
2634
Bram Moolenaar19e60942011-06-19 00:27:51 +02002635 static PyInt
2636RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2637{
2638 PyInt size;
2639 PyInt len_change;
2640
2641 /* Self must be a valid buffer */
2642 if (CheckBuffer(self))
2643 return -1;
2644
2645 /* Sort out the slice range */
2646 size = end - start + 1;
2647
2648 if (lo < 0)
2649 lo = 0;
2650 else if (lo > size)
2651 lo = size;
2652 if (hi < 0)
2653 hi = 0;
2654 if (hi < lo)
2655 hi = lo;
2656 else if (hi > size)
2657 hi = size;
2658
2659 if (SetBufferLineList(self->buf, lo + start, hi + start,
2660 val, &len_change) == FAIL)
2661 return -1;
2662
2663 if (new_end)
2664 *new_end = end + len_change;
2665
2666 return 0;
2667}
2668
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002669
2670 static PyObject *
2671RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2672{
2673 PyObject *lines;
2674 PyInt len_change;
2675 PyInt max;
2676 PyInt n;
2677
2678 if (CheckBuffer(self))
2679 return NULL;
2680
2681 max = n = end - start + 1;
2682
2683 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2684 return NULL;
2685
2686 if (n < 0 || n > max)
2687 {
2688 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2689 return NULL;
2690 }
2691
2692 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2693 return NULL;
2694
2695 if (new_end)
2696 *new_end = end + len_change;
2697
2698 Py_INCREF(Py_None);
2699 return Py_None;
2700}
2701
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002702/* Range object - Definitions
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002703 */
2704
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002705static PyTypeObject RangeType;
2706
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002707typedef struct
2708{
2709 PyObject_HEAD
2710 BufferObject *buf;
2711 PyInt start;
2712 PyInt end;
2713} RangeObject;
2714
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002715static void RangeDestructor(PyObject *);
2716static PySequenceMethods RangeAsSeq;
2717static PyMappingMethods RangeAsMapping;
2718
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002719 static PyObject *
2720RangeNew(buf_T *buf, PyInt start, PyInt end)
2721{
2722 BufferObject *bufr;
2723 RangeObject *self;
2724 self = PyObject_NEW(RangeObject, &RangeType);
2725 if (self == NULL)
2726 return NULL;
2727
2728 bufr = (BufferObject *)BufferNew(buf);
2729 if (bufr == NULL)
2730 {
2731 Py_DECREF(self);
2732 return NULL;
2733 }
2734 Py_INCREF(bufr);
2735
2736 self->buf = bufr;
2737 self->start = start;
2738 self->end = end;
2739
2740 return (PyObject *)(self);
2741}
2742
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002743 static void
2744RangeDestructor(PyObject *self)
2745{
2746 Py_DECREF(((RangeObject *)(self))->buf);
2747 DESTRUCTOR_FINISH(self);
2748}
2749
2750static PyTypeObject BufferType;
2751static PyObject *BufferRepr(PyObject *);
2752static PySequenceMethods BufferAsSeq;
2753static PyMappingMethods BufferAsMapping;
2754
2755 static void
2756BufferDestructor(PyObject *self)
2757{
2758 BufferObject *this = (BufferObject *)(self);
2759
2760 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2761#if PY_MAJOR_VERSION >= 3
2762 this->buf->b_python3_ref = NULL;
2763#else
2764 this->buf->b_python_ref = NULL;
2765#endif
2766
2767 DESTRUCTOR_FINISH(self);
2768}
2769
2770 static PyObject *
2771BufferAttr(BufferObject *this, char *name)
2772{
2773 if (strcmp(name, "name") == 0)
2774 return Py_BuildValue("s", this->buf->b_ffname);
2775 else if (strcmp(name, "number") == 0)
2776 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02002777 else if (strcmp(name, "vars") == 0)
2778 return DictionaryNew(this->buf->b_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02002779 else if (strcmp(name, "options") == 0)
2780 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2781 (PyObject *) this);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002782 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02002783 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002784 else
2785 return NULL;
2786}
2787
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002788 static PyObject *
2789BufferAppend(PyObject *self, PyObject *args)
2790{
2791 return RBAppend((BufferObject *)(self), args, 1,
2792 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2793 NULL);
2794}
2795
2796 static PyObject *
2797BufferMark(PyObject *self, PyObject *args)
2798{
2799 pos_T *posp;
2800 char *pmark;
2801 char mark;
2802 buf_T *curbuf_save;
2803
2804 if (CheckBuffer((BufferObject *)(self)))
2805 return NULL;
2806
2807 if (!PyArg_ParseTuple(args, "s", &pmark))
2808 return NULL;
2809 mark = *pmark;
2810
2811 curbuf_save = curbuf;
2812 curbuf = ((BufferObject *)(self))->buf;
2813 posp = getmark(mark, FALSE);
2814 curbuf = curbuf_save;
2815
2816 if (posp == NULL)
2817 {
2818 PyErr_SetVim(_("invalid mark name"));
2819 return NULL;
2820 }
2821
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002822 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002823 if (VimErrorCheck())
2824 return NULL;
2825
2826 if (posp->lnum <= 0)
2827 {
2828 /* Or raise an error? */
2829 Py_INCREF(Py_None);
2830 return Py_None;
2831 }
2832
2833 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2834}
2835
2836 static PyObject *
2837BufferRange(PyObject *self, PyObject *args)
2838{
2839 PyInt start;
2840 PyInt end;
2841
2842 if (CheckBuffer((BufferObject *)(self)))
2843 return NULL;
2844
2845 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2846 return NULL;
2847
2848 return RangeNew(((BufferObject *)(self))->buf, start, end);
2849}
2850
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002851 static PyObject *
2852BufferRepr(PyObject *self)
2853{
2854 static char repr[100];
2855 BufferObject *this = (BufferObject *)(self);
2856
2857 if (this->buf == INVALID_BUFFER_VALUE)
2858 {
2859 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2860 return PyString_FromString(repr);
2861 }
2862 else
2863 {
2864 char *name = (char *)this->buf->b_fname;
2865 PyInt len;
2866
2867 if (name == NULL)
2868 name = "";
2869 len = strlen(name);
2870
2871 if (len > 35)
2872 name = name + (35 - len);
2873
2874 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2875
2876 return PyString_FromString(repr);
2877 }
2878}
2879
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002880static struct PyMethodDef BufferMethods[] = {
2881 /* name, function, calling, documentation */
2882 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2883 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2884 {"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 +01002885#if PY_VERSION_HEX >= 0x03000000
2886 {"__dir__", BufferDir, 4, "List its attributes" },
2887#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002888 { NULL, NULL, 0, NULL }
2889};
2890
2891 static PyObject *
2892RangeAppend(PyObject *self, PyObject *args)
2893{
2894 return RBAppend(((RangeObject *)(self))->buf, args,
2895 ((RangeObject *)(self))->start,
2896 ((RangeObject *)(self))->end,
2897 &((RangeObject *)(self))->end);
2898}
2899
2900 static PyInt
2901RangeLength(PyObject *self)
2902{
2903 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2904 if (CheckBuffer(((RangeObject *)(self))->buf))
2905 return -1; /* ??? */
2906
2907 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2908}
2909
2910 static PyObject *
2911RangeItem(PyObject *self, PyInt n)
2912{
2913 return RBItem(((RangeObject *)(self))->buf, n,
2914 ((RangeObject *)(self))->start,
2915 ((RangeObject *)(self))->end);
2916}
2917
2918 static PyObject *
2919RangeRepr(PyObject *self)
2920{
2921 static char repr[100];
2922 RangeObject *this = (RangeObject *)(self);
2923
2924 if (this->buf->buf == INVALID_BUFFER_VALUE)
2925 {
2926 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2927 (self));
2928 return PyString_FromString(repr);
2929 }
2930 else
2931 {
2932 char *name = (char *)this->buf->buf->b_fname;
2933 int len;
2934
2935 if (name == NULL)
2936 name = "";
2937 len = (int)strlen(name);
2938
2939 if (len > 45)
2940 name = name + (45 - len);
2941
2942 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2943 len > 45 ? "..." : "", name,
2944 this->start, this->end);
2945
2946 return PyString_FromString(repr);
2947 }
2948}
2949
2950 static PyObject *
2951RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2952{
2953 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2954 ((RangeObject *)(self))->start,
2955 ((RangeObject *)(self))->end);
2956}
2957
2958/*
2959 * Line range object - Definitions
2960 */
2961
2962static struct PyMethodDef RangeMethods[] = {
2963 /* name, function, calling, documentation */
2964 {"append", RangeAppend, 1, "Append data to the Vim range" },
2965 { NULL, NULL, 0, NULL }
2966};
2967
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002968/* Current items object - Implementation
2969 */
2970
2971static PyInt RangeStart;
2972static PyInt RangeEnd;
2973
2974 static PyObject *
2975CurrentGetattr(PyObject *self UNUSED, char *name)
2976{
2977 if (strcmp(name, "buffer") == 0)
2978 return (PyObject *)BufferNew(curbuf);
2979 else if (strcmp(name, "window") == 0)
2980 return (PyObject *)WindowNew(curwin);
2981 else if (strcmp(name, "line") == 0)
2982 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2983 else if (strcmp(name, "range") == 0)
2984 return RangeNew(curbuf, RangeStart, RangeEnd);
2985 else if (strcmp(name,"__members__") == 0)
2986 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2987 else
2988 {
2989 PyErr_SetString(PyExc_AttributeError, name);
2990 return NULL;
2991 }
2992}
2993
2994 static int
2995CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2996{
2997 if (strcmp(name, "line") == 0)
2998 {
2999 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3000 return -1;
3001
3002 return 0;
3003 }
3004 else
3005 {
3006 PyErr_SetString(PyExc_AttributeError, name);
3007 return -1;
3008 }
3009}
3010
Bram Moolenaardb913952012-06-29 12:54:53 +02003011 static void
3012set_ref_in_py(const int copyID)
3013{
3014 pylinkedlist_T *cur;
3015 dict_T *dd;
3016 list_T *ll;
3017
3018 if (lastdict != NULL)
3019 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3020 {
3021 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3022 if (dd->dv_copyID != copyID)
3023 {
3024 dd->dv_copyID = copyID;
3025 set_ref_in_ht(&dd->dv_hashtab, copyID);
3026 }
3027 }
3028
3029 if (lastlist != NULL)
3030 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3031 {
3032 ll = ((ListObject *) (cur->pll_obj))->list;
3033 if (ll->lv_copyID != copyID)
3034 {
3035 ll->lv_copyID = copyID;
3036 set_ref_in_list(ll, copyID);
3037 }
3038 }
3039}
3040
3041 static int
3042set_string_copy(char_u *str, typval_T *tv)
3043{
3044 tv->vval.v_string = vim_strsave(str);
3045 if (tv->vval.v_string == NULL)
3046 {
3047 PyErr_NoMemory();
3048 return -1;
3049 }
3050 return 0;
3051}
3052
Bram Moolenaardb913952012-06-29 12:54:53 +02003053typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3054
3055 static int
3056convert_dl(PyObject *obj, typval_T *tv,
3057 pytotvfunc py_to_tv, PyObject *lookupDict)
3058{
3059 PyObject *capsule;
3060 char hexBuf[sizeof(void *) * 2 + 3];
3061
3062 sprintf(hexBuf, "%p", obj);
3063
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003064# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003065 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003066# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003067 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003068# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003069 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003070 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003071# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003072 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003073# else
3074 capsule = PyCObject_FromVoidPtr(tv, NULL);
3075# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003076 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3077 Py_DECREF(capsule);
3078 if (py_to_tv(obj, tv, lookupDict) == -1)
3079 {
3080 tv->v_type = VAR_UNKNOWN;
3081 return -1;
3082 }
3083 /* As we are not using copy_tv which increments reference count we must
3084 * do it ourself. */
3085 switch(tv->v_type)
3086 {
3087 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3088 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3089 }
3090 }
3091 else
3092 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003093 typval_T *v;
3094
3095# ifdef PY_USE_CAPSULE
3096 v = PyCapsule_GetPointer(capsule, NULL);
3097# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003098 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003099# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003100 copy_tv(v, tv);
3101 }
3102 return 0;
3103}
3104
3105 static int
3106ConvertFromPyObject(PyObject *obj, typval_T *tv)
3107{
3108 PyObject *lookup_dict;
3109 int r;
3110
3111 lookup_dict = PyDict_New();
3112 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3113 Py_DECREF(lookup_dict);
3114 return r;
3115}
3116
3117 static int
3118_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3119{
3120 if (obj->ob_type == &DictionaryType)
3121 {
3122 tv->v_type = VAR_DICT;
3123 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3124 ++tv->vval.v_dict->dv_refcount;
3125 }
3126 else if (obj->ob_type == &ListType)
3127 {
3128 tv->v_type = VAR_LIST;
3129 tv->vval.v_list = (((ListObject *)(obj))->list);
3130 ++tv->vval.v_list->lv_refcount;
3131 }
3132 else if (obj->ob_type == &FunctionType)
3133 {
3134 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3135 return -1;
3136
3137 tv->v_type = VAR_FUNC;
3138 func_ref(tv->vval.v_string);
3139 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003140 else if (PyBytes_Check(obj))
3141 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003142 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003143
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003144 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3145 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003146 if (result == NULL)
3147 return -1;
3148
3149 if (set_string_copy(result, tv) == -1)
3150 return -1;
3151
3152 tv->v_type = VAR_STRING;
3153 }
3154 else if (PyUnicode_Check(obj))
3155 {
3156 PyObject *bytes;
3157 char_u *result;
3158
Bram Moolenaardb913952012-06-29 12:54:53 +02003159 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3160 if (bytes == NULL)
3161 return -1;
3162
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003163 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3164 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003165 if (result == NULL)
3166 return -1;
3167
3168 if (set_string_copy(result, tv) == -1)
3169 {
3170 Py_XDECREF(bytes);
3171 return -1;
3172 }
3173 Py_XDECREF(bytes);
3174
3175 tv->v_type = VAR_STRING;
3176 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003177#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003178 else if (PyInt_Check(obj))
3179 {
3180 tv->v_type = VAR_NUMBER;
3181 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3182 }
3183#endif
3184 else if (PyLong_Check(obj))
3185 {
3186 tv->v_type = VAR_NUMBER;
3187 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3188 }
3189 else if (PyDict_Check(obj))
3190 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3191#ifdef FEAT_FLOAT
3192 else if (PyFloat_Check(obj))
3193 {
3194 tv->v_type = VAR_FLOAT;
3195 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3196 }
3197#endif
3198 else if (PyIter_Check(obj))
3199 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3200 else if (PySequence_Check(obj))
3201 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3202 else if (PyMapping_Check(obj))
3203 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3204 else
3205 {
3206 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
3207 return -1;
3208 }
3209 return 0;
3210}
3211
3212 static PyObject *
3213ConvertToPyObject(typval_T *tv)
3214{
3215 if (tv == NULL)
3216 {
3217 PyErr_SetVim(_("NULL reference passed"));
3218 return NULL;
3219 }
3220 switch (tv->v_type)
3221 {
3222 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003223 return PyBytes_FromString(tv->vval.v_string == NULL
3224 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003225 case VAR_NUMBER:
3226 return PyLong_FromLong((long) tv->vval.v_number);
3227#ifdef FEAT_FLOAT
3228 case VAR_FLOAT:
3229 return PyFloat_FromDouble((double) tv->vval.v_float);
3230#endif
3231 case VAR_LIST:
3232 return ListNew(tv->vval.v_list);
3233 case VAR_DICT:
3234 return DictionaryNew(tv->vval.v_dict);
3235 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003236 return FunctionNew(tv->vval.v_string == NULL
3237 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003238 case VAR_UNKNOWN:
3239 Py_INCREF(Py_None);
3240 return Py_None;
3241 default:
3242 PyErr_SetVim(_("internal error: invalid value type"));
3243 return NULL;
3244 }
3245}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003246
3247typedef struct
3248{
3249 PyObject_HEAD
3250} CurrentObject;
3251static PyTypeObject CurrentType;
3252
3253 static void
3254init_structs(void)
3255{
3256 vim_memset(&OutputType, 0, sizeof(OutputType));
3257 OutputType.tp_name = "vim.message";
3258 OutputType.tp_basicsize = sizeof(OutputObject);
3259 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3260 OutputType.tp_doc = "vim message object";
3261 OutputType.tp_methods = OutputMethods;
3262#if PY_MAJOR_VERSION >= 3
3263 OutputType.tp_getattro = OutputGetattro;
3264 OutputType.tp_setattro = OutputSetattro;
3265 OutputType.tp_alloc = call_PyType_GenericAlloc;
3266 OutputType.tp_new = call_PyType_GenericNew;
3267 OutputType.tp_free = call_PyObject_Free;
3268#else
3269 OutputType.tp_getattr = OutputGetattr;
3270 OutputType.tp_setattr = OutputSetattr;
3271#endif
3272
3273 vim_memset(&BufferType, 0, sizeof(BufferType));
3274 BufferType.tp_name = "vim.buffer";
3275 BufferType.tp_basicsize = sizeof(BufferType);
3276 BufferType.tp_dealloc = BufferDestructor;
3277 BufferType.tp_repr = BufferRepr;
3278 BufferType.tp_as_sequence = &BufferAsSeq;
3279 BufferType.tp_as_mapping = &BufferAsMapping;
3280 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3281 BufferType.tp_doc = "vim buffer object";
3282 BufferType.tp_methods = BufferMethods;
3283#if PY_MAJOR_VERSION >= 3
3284 BufferType.tp_getattro = BufferGetattro;
3285 BufferType.tp_alloc = call_PyType_GenericAlloc;
3286 BufferType.tp_new = call_PyType_GenericNew;
3287 BufferType.tp_free = call_PyObject_Free;
3288#else
3289 BufferType.tp_getattr = BufferGetattr;
3290#endif
3291
3292 vim_memset(&WindowType, 0, sizeof(WindowType));
3293 WindowType.tp_name = "vim.window";
3294 WindowType.tp_basicsize = sizeof(WindowObject);
3295 WindowType.tp_dealloc = WindowDestructor;
3296 WindowType.tp_repr = WindowRepr;
3297 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3298 WindowType.tp_doc = "vim Window object";
3299 WindowType.tp_methods = WindowMethods;
3300#if PY_MAJOR_VERSION >= 3
3301 WindowType.tp_getattro = WindowGetattro;
3302 WindowType.tp_setattro = WindowSetattro;
3303 WindowType.tp_alloc = call_PyType_GenericAlloc;
3304 WindowType.tp_new = call_PyType_GenericNew;
3305 WindowType.tp_free = call_PyObject_Free;
3306#else
3307 WindowType.tp_getattr = WindowGetattr;
3308 WindowType.tp_setattr = WindowSetattr;
3309#endif
3310
3311 vim_memset(&BufListType, 0, sizeof(BufListType));
3312 BufListType.tp_name = "vim.bufferlist";
3313 BufListType.tp_basicsize = sizeof(BufListObject);
3314 BufListType.tp_as_sequence = &BufListAsSeq;
3315 BufListType.tp_flags = Py_TPFLAGS_DEFAULT;
3316 BufferType.tp_doc = "vim buffer list";
3317
3318 vim_memset(&WinListType, 0, sizeof(WinListType));
3319 WinListType.tp_name = "vim.windowlist";
3320 WinListType.tp_basicsize = sizeof(WinListType);
3321 WinListType.tp_as_sequence = &WinListAsSeq;
3322 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3323 WinListType.tp_doc = "vim window list";
3324
3325 vim_memset(&RangeType, 0, sizeof(RangeType));
3326 RangeType.tp_name = "vim.range";
3327 RangeType.tp_basicsize = sizeof(RangeObject);
3328 RangeType.tp_dealloc = RangeDestructor;
3329 RangeType.tp_repr = RangeRepr;
3330 RangeType.tp_as_sequence = &RangeAsSeq;
3331 RangeType.tp_as_mapping = &RangeAsMapping;
3332 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3333 RangeType.tp_doc = "vim Range object";
3334 RangeType.tp_methods = RangeMethods;
3335#if PY_MAJOR_VERSION >= 3
3336 RangeType.tp_getattro = RangeGetattro;
3337 RangeType.tp_alloc = call_PyType_GenericAlloc;
3338 RangeType.tp_new = call_PyType_GenericNew;
3339 RangeType.tp_free = call_PyObject_Free;
3340#else
3341 RangeType.tp_getattr = RangeGetattr;
3342#endif
3343
3344 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3345 CurrentType.tp_name = "vim.currentdata";
3346 CurrentType.tp_basicsize = sizeof(CurrentObject);
3347 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3348 CurrentType.tp_doc = "vim current object";
3349#if PY_MAJOR_VERSION >= 3
3350 CurrentType.tp_getattro = CurrentGetattro;
3351 CurrentType.tp_setattro = CurrentSetattro;
3352#else
3353 CurrentType.tp_getattr = CurrentGetattr;
3354 CurrentType.tp_setattr = CurrentSetattr;
3355#endif
3356
3357 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3358 DictionaryType.tp_name = "vim.dictionary";
3359 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3360 DictionaryType.tp_dealloc = DictionaryDestructor;
3361 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3362 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3363 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3364 DictionaryType.tp_methods = DictionaryMethods;
3365#if PY_MAJOR_VERSION >= 3
3366 DictionaryType.tp_getattro = DictionaryGetattro;
3367 DictionaryType.tp_setattro = DictionarySetattro;
3368#else
3369 DictionaryType.tp_getattr = DictionaryGetattr;
3370 DictionaryType.tp_setattr = DictionarySetattr;
3371#endif
3372
3373 vim_memset(&ListType, 0, sizeof(ListType));
3374 ListType.tp_name = "vim.list";
3375 ListType.tp_dealloc = ListDestructor;
3376 ListType.tp_basicsize = sizeof(ListObject);
3377 ListType.tp_as_sequence = &ListAsSeq;
3378 ListType.tp_as_mapping = &ListAsMapping;
3379 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3380 ListType.tp_doc = "list pushing modifications to vim structure";
3381 ListType.tp_methods = ListMethods;
3382#if PY_MAJOR_VERSION >= 3
3383 ListType.tp_getattro = ListGetattro;
3384 ListType.tp_setattro = ListSetattro;
3385#else
3386 ListType.tp_getattr = ListGetattr;
3387 ListType.tp_setattr = ListSetattr;
3388#endif
3389
3390 vim_memset(&FunctionType, 0, sizeof(FunctionType));
3391 FunctionType.tp_name = "vim.list";
3392 FunctionType.tp_basicsize = sizeof(FunctionObject);
3393 FunctionType.tp_dealloc = FunctionDestructor;
3394 FunctionType.tp_call = FunctionCall;
3395 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3396 FunctionType.tp_doc = "object that calls vim function";
3397 FunctionType.tp_methods = FunctionMethods;
3398#if PY_MAJOR_VERSION >= 3
3399 FunctionType.tp_getattro = FunctionGetattro;
3400#else
3401 FunctionType.tp_getattr = FunctionGetattr;
3402#endif
3403
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003404 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3405 OptionsType.tp_name = "vim.options";
3406 OptionsType.tp_basicsize = sizeof(OptionsObject);
3407 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3408 OptionsType.tp_doc = "object for manipulating options";
3409 OptionsType.tp_as_mapping = &OptionsAsMapping;
3410 OptionsType.tp_dealloc = OptionsDestructor;
3411
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003412#if PY_MAJOR_VERSION >= 3
3413 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3414 vimmodule.m_name = "vim";
3415 vimmodule.m_doc = "Vim Python interface\n";
3416 vimmodule.m_size = -1;
3417 vimmodule.m_methods = VimMethods;
3418#endif
3419}