blob: 0a1ef1b9e6e51c8c6f638bc01916bc39a03a5412 [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
313#ifdef FEAT_EVAL
314/*
315 * Function to translate a typval_T into a PyObject; this will recursively
316 * translate lists/dictionaries into their Python equivalents.
317 *
318 * The depth parameter is to avoid infinite recursion, set it to 1 when
319 * you call VimToPython.
320 */
321 static PyObject *
322VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
323{
324 PyObject *result;
325 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200326 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200327
328 /* Avoid infinite recursion */
329 if (depth > 100)
330 {
331 Py_INCREF(Py_None);
332 result = Py_None;
333 return result;
334 }
335
336 /* Check if we run into a recursive loop. The item must be in lookupDict
337 * then and we can use it again. */
338 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
339 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
340 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200341 sprintf(ptrBuf, "%p",
342 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
343 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200344 result = PyDict_GetItemString(lookupDict, ptrBuf);
345 if (result != NULL)
346 {
347 Py_INCREF(result);
348 return result;
349 }
350 }
351
352 if (our_tv->v_type == VAR_STRING)
353 {
354 result = Py_BuildValue("s", our_tv->vval.v_string);
355 }
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}
427#endif
428
429 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200430VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200431{
432#ifdef FEAT_EVAL
433 char *expr;
434 typval_T *our_tv;
435 PyObject *result;
436 PyObject *lookup_dict;
437
438 if (!PyArg_ParseTuple(args, "s", &expr))
439 return NULL;
440
441 Py_BEGIN_ALLOW_THREADS
442 Python_Lock_Vim();
443 our_tv = eval_expr((char_u *)expr, NULL);
444
445 Python_Release_Vim();
446 Py_END_ALLOW_THREADS
447
448 if (our_tv == NULL)
449 {
450 PyErr_SetVim(_("invalid expression"));
451 return NULL;
452 }
453
454 /* Convert the Vim type into a Python type. Create a dictionary that's
455 * used to check for recursive loops. */
456 lookup_dict = PyDict_New();
457 result = VimToPython(our_tv, 1, lookup_dict);
458 Py_DECREF(lookup_dict);
459
460
461 Py_BEGIN_ALLOW_THREADS
462 Python_Lock_Vim();
463 free_tv(our_tv);
464 Python_Release_Vim();
465 Py_END_ALLOW_THREADS
466
467 return result;
468#else
469 PyErr_SetVim(_("expressions disabled at compile time"));
470 return NULL;
471#endif
472}
473
Bram Moolenaardb913952012-06-29 12:54:53 +0200474static PyObject *ConvertToPyObject(typval_T *);
475
476 static PyObject *
477VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
478{
479#ifdef FEAT_EVAL
480 char *expr;
481 typval_T *our_tv;
482 PyObject *result;
483
484 if (!PyArg_ParseTuple(args, "s", &expr))
485 return NULL;
486
487 Py_BEGIN_ALLOW_THREADS
488 Python_Lock_Vim();
489 our_tv = eval_expr((char_u *)expr, NULL);
490
491 Python_Release_Vim();
492 Py_END_ALLOW_THREADS
493
494 if (our_tv == NULL)
495 {
496 PyErr_SetVim(_("invalid expression"));
497 return NULL;
498 }
499
500 result = ConvertToPyObject(our_tv);
501 Py_BEGIN_ALLOW_THREADS
502 Python_Lock_Vim();
503 free_tv(our_tv);
504 Python_Release_Vim();
505 Py_END_ALLOW_THREADS
506
507 return result;
508#else
509 PyErr_SetVim(_("expressions disabled at compile time"));
510 return NULL;
511#endif
512}
513
514 static PyObject *
515VimStrwidth(PyObject *self UNUSED, PyObject *args)
516{
517 char *expr;
518
519 if (!PyArg_ParseTuple(args, "s", &expr))
520 return NULL;
521
Bram Moolenaar3cd3e7a2012-06-29 17:52:02 +0200522 return PyLong_FromLong(mb_string2cells((char_u *)expr, (int)STRLEN(expr)));
Bram Moolenaardb913952012-06-29 12:54:53 +0200523}
524
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200525/*
526 * Vim module - Definitions
527 */
528
529static struct PyMethodDef VimMethods[] = {
530 /* name, function, calling, documentation */
531 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
532 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200533 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
534 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200535 { NULL, NULL, 0, NULL }
536};
537
538typedef struct
539{
540 PyObject_HEAD
541 buf_T *buf;
Bram Moolenaardb913952012-06-29 12:54:53 +0200542} BufferObject;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200543
544#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
545
546/*
547 * Buffer list object - Implementation
548 */
549
550 static PyInt
551BufListLength(PyObject *self UNUSED)
552{
553 buf_T *b = firstbuf;
554 PyInt n = 0;
555
556 while (b)
557 {
558 ++n;
559 b = b->b_next;
560 }
561
562 return n;
563}
564
565 static PyObject *
566BufListItem(PyObject *self UNUSED, PyInt n)
567{
568 buf_T *b;
569
570 for (b = firstbuf; b; b = b->b_next, --n)
571 {
572 if (n == 0)
573 return BufferNew(b);
574 }
575
576 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
577 return NULL;
578}
579
580typedef struct
581{
582 PyObject_HEAD
583 win_T *win;
584} WindowObject;
585
Bram Moolenaardb913952012-06-29 12:54:53 +0200586static int ConvertFromPyObject(PyObject *, typval_T *);
587static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
588
589typedef struct pylinkedlist_S {
590 struct pylinkedlist_S *pll_next;
591 struct pylinkedlist_S *pll_prev;
592 PyObject *pll_obj;
593} pylinkedlist_T;
594
595static pylinkedlist_T *lastdict = NULL;
596static pylinkedlist_T *lastlist = NULL;
597
598 static void
599pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
600{
601 if (ref->pll_prev == NULL)
602 {
603 if (ref->pll_next == NULL)
604 {
605 *last = NULL;
606 return;
607 }
608 }
609 else
610 ref->pll_prev->pll_next = ref->pll_next;
611
612 if (ref->pll_next == NULL)
613 *last = ref->pll_prev;
614 else
615 ref->pll_next->pll_prev = ref->pll_prev;
616}
617
618 static void
619pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
620{
621 if (*last == NULL)
622 ref->pll_prev = NULL;
623 else
624 {
625 (*last)->pll_next = ref;
626 ref->pll_prev = *last;
627 }
628 ref->pll_next = NULL;
629 ref->pll_obj = self;
630 *last = ref;
631}
632
633static PyTypeObject DictionaryType;
634
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200635#define DICTKEY_GET_NOTEMPTY(err) \
636 DICTKEY_GET(err) \
637 if (*key == NUL) \
638 { \
639 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
640 return err; \
641 }
642
Bram Moolenaardb913952012-06-29 12:54:53 +0200643typedef struct
644{
645 PyObject_HEAD
646 dict_T *dict;
647 pylinkedlist_T ref;
648} DictionaryObject;
649
650 static PyObject *
651DictionaryNew(dict_T *dict)
652{
653 DictionaryObject *self;
654
655 self = PyObject_NEW(DictionaryObject, &DictionaryType);
656 if (self == NULL)
657 return NULL;
658 self->dict = dict;
659 ++dict->dv_refcount;
660
661 pyll_add((PyObject *)(self), &self->ref, &lastdict);
662
663 return (PyObject *)(self);
664}
665
666 static int
667pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
668{
669 dict_T *d;
670 char_u *key;
671 dictitem_T *di;
672 PyObject *keyObject;
673 PyObject *valObject;
674 Py_ssize_t iter = 0;
675
676 d = dict_alloc();
677 if (d == NULL)
678 {
679 PyErr_NoMemory();
680 return -1;
681 }
682
683 tv->v_type = VAR_DICT;
684 tv->vval.v_dict = d;
685
686 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
687 {
688 DICTKEY_DECL
689
690 if (keyObject == NULL)
691 return -1;
692 if (valObject == NULL)
693 return -1;
694
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200695 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200696
697 di = dictitem_alloc(key);
698
699 DICTKEY_UNREF
700
701 if (di == NULL)
702 {
703 PyErr_NoMemory();
704 return -1;
705 }
706 di->di_tv.v_lock = 0;
707
708 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
709 {
710 vim_free(di);
711 return -1;
712 }
713 if (dict_add(d, di) == FAIL)
714 {
715 vim_free(di);
716 PyErr_SetVim(_("failed to add key to dictionary"));
717 return -1;
718 }
719 }
720 return 0;
721}
722
723 static int
724pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
725{
726 dict_T *d;
727 char_u *key;
728 dictitem_T *di;
729 PyObject *list;
730 PyObject *litem;
731 PyObject *keyObject;
732 PyObject *valObject;
733 Py_ssize_t lsize;
734
735 d = dict_alloc();
736 if (d == NULL)
737 {
738 PyErr_NoMemory();
739 return -1;
740 }
741
742 tv->v_type = VAR_DICT;
743 tv->vval.v_dict = d;
744
745 list = PyMapping_Items(obj);
746 lsize = PyList_Size(list);
747 while (lsize--)
748 {
749 DICTKEY_DECL
750
751 litem = PyList_GetItem(list, lsize);
752 if (litem == NULL)
753 {
754 Py_DECREF(list);
755 return -1;
756 }
757
758 keyObject = PyTuple_GetItem(litem, 0);
759 if (keyObject == NULL)
760 {
761 Py_DECREF(list);
762 Py_DECREF(litem);
763 return -1;
764 }
765
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200766 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200767
768 valObject = PyTuple_GetItem(litem, 1);
769 if (valObject == NULL)
770 {
771 Py_DECREF(list);
772 Py_DECREF(litem);
773 return -1;
774 }
775
776 di = dictitem_alloc(key);
777
778 DICTKEY_UNREF
779
780 if (di == NULL)
781 {
782 Py_DECREF(list);
783 Py_DECREF(litem);
784 PyErr_NoMemory();
785 return -1;
786 }
787 di->di_tv.v_lock = 0;
788
789 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
790 {
791 vim_free(di);
792 Py_DECREF(list);
793 Py_DECREF(litem);
794 return -1;
795 }
796 if (dict_add(d, di) == FAIL)
797 {
798 vim_free(di);
799 Py_DECREF(list);
800 Py_DECREF(litem);
801 PyErr_SetVim(_("failed to add key to dictionary"));
802 return -1;
803 }
804 Py_DECREF(litem);
805 }
806 Py_DECREF(list);
807 return 0;
808}
809
810 static PyInt
Bram Moolenaar66b79852012-09-21 14:00:35 +0200811DictionarySetattr(DictionaryObject *self, char *name, PyObject *val)
812{
813 if (val == NULL)
814 {
815 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
816 return -1;
817 }
818
819 if (strcmp(name, "locked") == 0)
820 {
821 if (self->dict->dv_lock == VAR_FIXED)
822 {
823 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
824 return -1;
825 }
826 else
827 {
828 if (!PyBool_Check(val))
829 {
830 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
831 return -1;
832 }
833
834 if (val == Py_True)
835 self->dict->dv_lock = VAR_LOCKED;
836 else
837 self->dict->dv_lock = 0;
838 }
839 return 0;
840 }
841 else
842 {
843 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
844 return -1;
845 }
846}
847
848 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200849DictionaryLength(PyObject *self)
850{
851 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
852}
853
854 static PyObject *
855DictionaryItem(PyObject *self, PyObject *keyObject)
856{
857 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200858 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200859 DICTKEY_DECL
860
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200861 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200862
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200863 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
864
Bram Moolenaar696c2112012-09-21 13:43:14 +0200865 DICTKEY_UNREF
866
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200867 if (di == NULL)
868 {
869 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
870 return NULL;
871 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200872
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200873 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200874}
875
876 static PyInt
877DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
878{
879 char_u *key;
880 typval_T tv;
881 dict_T *d = ((DictionaryObject *)(self))->dict;
882 dictitem_T *di;
883 DICTKEY_DECL
884
885 if (d->dv_lock)
886 {
887 PyErr_SetVim(_("dict is locked"));
888 return -1;
889 }
890
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200891 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200892
893 di = dict_find(d, key, -1);
894
895 if (valObject == NULL)
896 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200897 hashitem_T *hi;
898
Bram Moolenaardb913952012-06-29 12:54:53 +0200899 if (di == NULL)
900 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200901 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200902 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
903 return -1;
904 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200905 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200906 hash_remove(&d->dv_hashtab, hi);
907 dictitem_free(di);
908 return 0;
909 }
910
911 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200912 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200913
914 if (di == NULL)
915 {
916 di = dictitem_alloc(key);
917 if (di == NULL)
918 {
919 PyErr_NoMemory();
920 return -1;
921 }
922 di->di_tv.v_lock = 0;
923
924 if (dict_add(d, di) == FAIL)
925 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200926 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200927 vim_free(di);
928 PyErr_SetVim(_("failed to add key to dictionary"));
929 return -1;
930 }
931 }
932 else
933 clear_tv(&di->di_tv);
934
935 DICTKEY_UNREF
936
937 copy_tv(&tv, &di->di_tv);
938 return 0;
939}
940
941 static PyObject *
942DictionaryListKeys(PyObject *self)
943{
944 dict_T *dict = ((DictionaryObject *)(self))->dict;
945 long_u todo = dict->dv_hashtab.ht_used;
946 Py_ssize_t i = 0;
947 PyObject *r;
948 hashitem_T *hi;
949
950 r = PyList_New(todo);
951 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
952 {
953 if (!HASHITEM_EMPTY(hi))
954 {
955 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
956 --todo;
957 ++i;
958 }
959 }
960 return r;
961}
962
963static struct PyMethodDef DictionaryMethods[] = {
964 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
965 { NULL, NULL, 0, NULL }
966};
967
968static PyTypeObject ListType;
969
970typedef struct
971{
972 PyObject_HEAD
973 list_T *list;
974 pylinkedlist_T ref;
975} ListObject;
976
977 static PyObject *
978ListNew(list_T *list)
979{
980 ListObject *self;
981
982 self = PyObject_NEW(ListObject, &ListType);
983 if (self == NULL)
984 return NULL;
985 self->list = list;
986 ++list->lv_refcount;
987
988 pyll_add((PyObject *)(self), &self->ref, &lastlist);
989
990 return (PyObject *)(self);
991}
992
993 static int
994list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
995{
996 Py_ssize_t i;
997 Py_ssize_t lsize = PySequence_Size(obj);
998 PyObject *litem;
999 listitem_T *li;
1000
1001 for(i=0; i<lsize; i++)
1002 {
1003 li = listitem_alloc();
1004 if (li == NULL)
1005 {
1006 PyErr_NoMemory();
1007 return -1;
1008 }
1009 li->li_tv.v_lock = 0;
1010
1011 litem = PySequence_GetItem(obj, i);
1012 if (litem == NULL)
1013 return -1;
1014 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
1015 return -1;
1016
1017 list_append(l, li);
1018 }
1019 return 0;
1020}
1021
1022 static int
1023pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
1024{
1025 list_T *l;
1026
1027 l = list_alloc();
1028 if (l == NULL)
1029 {
1030 PyErr_NoMemory();
1031 return -1;
1032 }
1033
1034 tv->v_type = VAR_LIST;
1035 tv->vval.v_list = l;
1036
1037 if (list_py_concat(l, obj, lookupDict) == -1)
1038 return -1;
1039
1040 return 0;
1041}
1042
1043 static int
1044pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
1045{
1046 PyObject *iterator = PyObject_GetIter(obj);
1047 PyObject *item;
1048 list_T *l;
1049 listitem_T *li;
1050
1051 l = list_alloc();
1052
1053 if (l == NULL)
1054 {
1055 PyErr_NoMemory();
1056 return -1;
1057 }
1058
1059 tv->vval.v_list = l;
1060 tv->v_type = VAR_LIST;
1061
1062
1063 if (iterator == NULL)
1064 return -1;
1065
1066 while ((item = PyIter_Next(obj)))
1067 {
1068 li = listitem_alloc();
1069 if (li == NULL)
1070 {
1071 PyErr_NoMemory();
1072 return -1;
1073 }
1074 li->li_tv.v_lock = 0;
1075
1076 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
1077 return -1;
1078
1079 list_append(l, li);
1080
1081 Py_DECREF(item);
1082 }
1083
1084 Py_DECREF(iterator);
1085 return 0;
1086}
1087
1088 static PyInt
1089ListLength(PyObject *self)
1090{
1091 return ((PyInt) (((ListObject *) (self))->list->lv_len));
1092}
1093
1094 static PyObject *
1095ListItem(PyObject *self, Py_ssize_t index)
1096{
1097 listitem_T *li;
1098
1099 if (index>=ListLength(self))
1100 {
1101 PyErr_SetString(PyExc_IndexError, "list index out of range");
1102 return NULL;
1103 }
1104 li = list_find(((ListObject *) (self))->list, (long) index);
1105 if (li == NULL)
1106 {
1107 PyErr_SetVim(_("internal error: failed to get vim list item"));
1108 return NULL;
1109 }
1110 return ConvertToPyObject(&li->li_tv);
1111}
1112
1113#define PROC_RANGE \
1114 if (last < 0) {\
1115 if (last < -size) \
1116 last = 0; \
1117 else \
1118 last += size; \
1119 } \
1120 if (first < 0) \
1121 first = 0; \
1122 if (first > size) \
1123 first = size; \
1124 if (last > size) \
1125 last = size;
1126
1127 static PyObject *
1128ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
1129{
1130 PyInt i;
1131 PyInt size = ListLength(self);
1132 PyInt n;
1133 PyObject *list;
1134 int reversed = 0;
1135
1136 PROC_RANGE
1137 if (first >= last)
1138 first = last;
1139
1140 n = last-first;
1141 list = PyList_New(n);
1142 if (list == NULL)
1143 return NULL;
1144
1145 for (i = 0; i < n; ++i)
1146 {
1147 PyObject *item = ListItem(self, i);
1148 if (item == NULL)
1149 {
1150 Py_DECREF(list);
1151 return NULL;
1152 }
1153
1154 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
1155 {
1156 Py_DECREF(item);
1157 Py_DECREF(list);
1158 return NULL;
1159 }
1160 }
1161
1162 return list;
1163}
1164
1165 static int
1166ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1167{
1168 typval_T tv;
1169 list_T *l = ((ListObject *) (self))->list;
1170 listitem_T *li;
1171 Py_ssize_t length = ListLength(self);
1172
1173 if (l->lv_lock)
1174 {
1175 PyErr_SetVim(_("list is locked"));
1176 return -1;
1177 }
1178 if (index>length || (index==length && obj==NULL))
1179 {
1180 PyErr_SetString(PyExc_IndexError, "list index out of range");
1181 return -1;
1182 }
1183
1184 if (obj == NULL)
1185 {
1186 li = list_find(l, (long) index);
1187 list_remove(l, li, li);
1188 clear_tv(&li->li_tv);
1189 vim_free(li);
1190 return 0;
1191 }
1192
1193 if (ConvertFromPyObject(obj, &tv) == -1)
1194 return -1;
1195
1196 if (index == length)
1197 {
1198 if (list_append_tv(l, &tv) == FAIL)
1199 {
1200 PyErr_SetVim(_("Failed to add item to list"));
1201 return -1;
1202 }
1203 }
1204 else
1205 {
1206 li = list_find(l, (long) index);
1207 clear_tv(&li->li_tv);
1208 copy_tv(&tv, &li->li_tv);
1209 }
1210 return 0;
1211}
1212
1213 static int
1214ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1215{
1216 PyInt size = ListLength(self);
1217 Py_ssize_t i;
1218 Py_ssize_t lsize;
1219 PyObject *litem;
1220 listitem_T *li;
1221 listitem_T *next;
1222 typval_T v;
1223 list_T *l = ((ListObject *) (self))->list;
1224
1225 if (l->lv_lock)
1226 {
1227 PyErr_SetVim(_("list is locked"));
1228 return -1;
1229 }
1230
1231 PROC_RANGE
1232
1233 if (first == size)
1234 li = NULL;
1235 else
1236 {
1237 li = list_find(l, (long) first);
1238 if (li == NULL)
1239 {
1240 PyErr_SetVim(_("internal error: no vim list item"));
1241 return -1;
1242 }
1243 if (last > first)
1244 {
1245 i = last - first;
1246 while (i-- && li != NULL)
1247 {
1248 next = li->li_next;
1249 listitem_remove(l, li);
1250 li = next;
1251 }
1252 }
1253 }
1254
1255 if (obj == NULL)
1256 return 0;
1257
1258 if (!PyList_Check(obj))
1259 {
1260 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1261 return -1;
1262 }
1263
1264 lsize = PyList_Size(obj);
1265
1266 for(i=0; i<lsize; i++)
1267 {
1268 litem = PyList_GetItem(obj, i);
1269 if (litem == NULL)
1270 return -1;
1271 if (ConvertFromPyObject(litem, &v) == -1)
1272 return -1;
1273 if (list_insert_tv(l, &v, li) == FAIL)
1274 {
1275 PyErr_SetVim(_("internal error: failed to add item to list"));
1276 return -1;
1277 }
1278 }
1279 return 0;
1280}
1281
1282 static PyObject *
1283ListConcatInPlace(PyObject *self, PyObject *obj)
1284{
1285 list_T *l = ((ListObject *) (self))->list;
1286 PyObject *lookup_dict;
1287
1288 if (l->lv_lock)
1289 {
1290 PyErr_SetVim(_("list is locked"));
1291 return NULL;
1292 }
1293
1294 if (!PySequence_Check(obj))
1295 {
1296 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1297 return NULL;
1298 }
1299
1300 lookup_dict = PyDict_New();
1301 if (list_py_concat(l, obj, lookup_dict) == -1)
1302 {
1303 Py_DECREF(lookup_dict);
1304 return NULL;
1305 }
1306 Py_DECREF(lookup_dict);
1307
1308 Py_INCREF(self);
1309 return self;
1310}
1311
Bram Moolenaar66b79852012-09-21 14:00:35 +02001312 static int
1313ListSetattr(ListObject *self, char *name, PyObject *val)
1314{
1315 if (val == NULL)
1316 {
1317 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
1318 return -1;
1319 }
1320
1321 if (strcmp(name, "locked") == 0)
1322 {
1323 if (self->list->lv_lock == VAR_FIXED)
1324 {
1325 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
1326 return -1;
1327 }
1328 else
1329 {
1330 if (!PyBool_Check(val))
1331 {
1332 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
1333 return -1;
1334 }
1335
1336 if (val == Py_True)
1337 self->list->lv_lock = VAR_LOCKED;
1338 else
1339 self->list->lv_lock = 0;
1340 }
1341 return 0;
1342 }
1343 else
1344 {
1345 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
1346 return -1;
1347 }
1348}
1349
Bram Moolenaardb913952012-06-29 12:54:53 +02001350static struct PyMethodDef ListMethods[] = {
1351 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1352 { NULL, NULL, 0, NULL }
1353};
1354
1355typedef struct
1356{
1357 PyObject_HEAD
1358 char_u *name;
1359} FunctionObject;
1360
1361static PyTypeObject FunctionType;
1362
1363 static PyObject *
1364FunctionNew(char_u *name)
1365{
1366 FunctionObject *self;
1367
1368 self = PyObject_NEW(FunctionObject, &FunctionType);
1369 if (self == NULL)
1370 return NULL;
1371 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1372 if (self->name == NULL)
1373 {
1374 PyErr_NoMemory();
1375 return NULL;
1376 }
1377 STRCPY(self->name, name);
1378 func_ref(name);
1379 return (PyObject *)(self);
1380}
1381
1382 static PyObject *
1383FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1384{
1385 FunctionObject *this = (FunctionObject *)(self);
1386 char_u *name = this->name;
1387 typval_T args;
1388 typval_T selfdicttv;
1389 typval_T rettv;
1390 dict_T *selfdict = NULL;
1391 PyObject *selfdictObject;
1392 PyObject *result;
1393 int error;
1394
1395 if (ConvertFromPyObject(argsObject, &args) == -1)
1396 return NULL;
1397
1398 if (kwargs != NULL)
1399 {
1400 selfdictObject = PyDict_GetItemString(kwargs, "self");
1401 if (selfdictObject != NULL)
1402 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001403 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001404 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001405 PyErr_SetString(PyExc_TypeError,
1406 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001407 clear_tv(&args);
1408 return NULL;
1409 }
1410 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1411 return NULL;
1412 selfdict = selfdicttv.vval.v_dict;
1413 }
1414 }
1415
1416 error = func_call(name, &args, selfdict, &rettv);
1417 if (error != OK)
1418 {
1419 result = NULL;
1420 PyErr_SetVim(_("failed to run function"));
1421 }
1422 else
1423 result = ConvertToPyObject(&rettv);
1424
1425 /* FIXME Check what should really be cleared. */
1426 clear_tv(&args);
1427 clear_tv(&rettv);
1428 /*
1429 * if (selfdict!=NULL)
1430 * clear_tv(selfdicttv);
1431 */
1432
1433 return result;
1434}
1435
1436static struct PyMethodDef FunctionMethods[] = {
1437 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1438 { NULL, NULL, 0, NULL }
1439};
1440
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001441#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1442
1443 static int
1444CheckWindow(WindowObject *this)
1445{
1446 if (this->win == INVALID_WINDOW_VALUE)
1447 {
1448 PyErr_SetVim(_("attempt to refer to deleted window"));
1449 return -1;
1450 }
1451
1452 return 0;
1453}
1454
1455static int WindowSetattr(PyObject *, char *, PyObject *);
1456static PyObject *WindowRepr(PyObject *);
1457
1458 static int
1459WindowSetattr(PyObject *self, char *name, PyObject *val)
1460{
1461 WindowObject *this = (WindowObject *)(self);
1462
1463 if (CheckWindow(this))
1464 return -1;
1465
1466 if (strcmp(name, "buffer") == 0)
1467 {
1468 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1469 return -1;
1470 }
1471 else if (strcmp(name, "cursor") == 0)
1472 {
1473 long lnum;
1474 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001475
1476 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1477 return -1;
1478
1479 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1480 {
1481 PyErr_SetVim(_("cursor position outside buffer"));
1482 return -1;
1483 }
1484
1485 /* Check for keyboard interrupts */
1486 if (VimErrorCheck())
1487 return -1;
1488
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001489 this->win->w_cursor.lnum = lnum;
1490 this->win->w_cursor.col = col;
1491#ifdef FEAT_VIRTUALEDIT
1492 this->win->w_cursor.coladd = 0;
1493#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001494 /* When column is out of range silently correct it. */
1495 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001496
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001497 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001498 return 0;
1499 }
1500 else if (strcmp(name, "height") == 0)
1501 {
1502 int height;
1503 win_T *savewin;
1504
1505 if (!PyArg_Parse(val, "i", &height))
1506 return -1;
1507
1508#ifdef FEAT_GUI
1509 need_mouse_correct = TRUE;
1510#endif
1511 savewin = curwin;
1512 curwin = this->win;
1513 win_setheight(height);
1514 curwin = savewin;
1515
1516 /* Check for keyboard interrupts */
1517 if (VimErrorCheck())
1518 return -1;
1519
1520 return 0;
1521 }
1522#ifdef FEAT_VERTSPLIT
1523 else if (strcmp(name, "width") == 0)
1524 {
1525 int width;
1526 win_T *savewin;
1527
1528 if (!PyArg_Parse(val, "i", &width))
1529 return -1;
1530
1531#ifdef FEAT_GUI
1532 need_mouse_correct = TRUE;
1533#endif
1534 savewin = curwin;
1535 curwin = this->win;
1536 win_setwidth(width);
1537 curwin = savewin;
1538
1539 /* Check for keyboard interrupts */
1540 if (VimErrorCheck())
1541 return -1;
1542
1543 return 0;
1544 }
1545#endif
1546 else
1547 {
1548 PyErr_SetString(PyExc_AttributeError, name);
1549 return -1;
1550 }
1551}
1552
1553 static PyObject *
1554WindowRepr(PyObject *self)
1555{
1556 static char repr[100];
1557 WindowObject *this = (WindowObject *)(self);
1558
1559 if (this->win == INVALID_WINDOW_VALUE)
1560 {
1561 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1562 return PyString_FromString(repr);
1563 }
1564 else
1565 {
1566 int i = 0;
1567 win_T *w;
1568
1569 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
1570 ++i;
1571
1572 if (w == NULL)
1573 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1574 (self));
1575 else
1576 vim_snprintf(repr, 100, _("<window %d>"), i);
1577
1578 return PyString_FromString(repr);
1579 }
1580}
1581
1582/*
1583 * Window list object - Implementation
1584 */
1585 static PyInt
1586WinListLength(PyObject *self UNUSED)
1587{
1588 win_T *w = firstwin;
1589 PyInt n = 0;
1590
1591 while (w != NULL)
1592 {
1593 ++n;
1594 w = W_NEXT(w);
1595 }
1596
1597 return n;
1598}
1599
1600 static PyObject *
1601WinListItem(PyObject *self UNUSED, PyInt n)
1602{
1603 win_T *w;
1604
1605 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1606 if (n == 0)
1607 return WindowNew(w);
1608
1609 PyErr_SetString(PyExc_IndexError, _("no such window"));
1610 return NULL;
1611}
1612
1613/* Convert a Python string into a Vim line.
1614 *
1615 * The result is in allocated memory. All internal nulls are replaced by
1616 * newline characters. It is an error for the string to contain newline
1617 * characters.
1618 *
1619 * On errors, the Python exception data is set, and NULL is returned.
1620 */
1621 static char *
1622StringToLine(PyObject *obj)
1623{
1624 const char *str;
1625 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001626 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001627 PyInt len;
1628 PyInt i;
1629 char *p;
1630
1631 if (obj == NULL || !PyString_Check(obj))
1632 {
1633 PyErr_BadArgument();
1634 return NULL;
1635 }
1636
Bram Moolenaar19e60942011-06-19 00:27:51 +02001637 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1638 str = PyString_AsString(bytes);
1639 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001640
1641 /*
1642 * Error checking: String must not contain newlines, as we
1643 * are replacing a single line, and we must replace it with
1644 * a single line.
1645 * A trailing newline is removed, so that append(f.readlines()) works.
1646 */
1647 p = memchr(str, '\n', len);
1648 if (p != NULL)
1649 {
1650 if (p == str + len - 1)
1651 --len;
1652 else
1653 {
1654 PyErr_SetVim(_("string cannot contain newlines"));
1655 return NULL;
1656 }
1657 }
1658
1659 /* Create a copy of the string, with internal nulls replaced by
1660 * newline characters, as is the vim convention.
1661 */
1662 save = (char *)alloc((unsigned)(len+1));
1663 if (save == NULL)
1664 {
1665 PyErr_NoMemory();
1666 return NULL;
1667 }
1668
1669 for (i = 0; i < len; ++i)
1670 {
1671 if (str[i] == '\0')
1672 save[i] = '\n';
1673 else
1674 save[i] = str[i];
1675 }
1676
1677 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001678 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001679
1680 return save;
1681}
1682
1683/* Get a line from the specified buffer. The line number is
1684 * in Vim format (1-based). The line is returned as a Python
1685 * string object.
1686 */
1687 static PyObject *
1688GetBufferLine(buf_T *buf, PyInt n)
1689{
1690 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1691}
1692
1693
1694/* Get a list of lines from the specified buffer. The line numbers
1695 * are in Vim format (1-based). The range is from lo up to, but not
1696 * including, hi. The list is returned as a Python list of string objects.
1697 */
1698 static PyObject *
1699GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1700{
1701 PyInt i;
1702 PyInt n = hi - lo;
1703 PyObject *list = PyList_New(n);
1704
1705 if (list == NULL)
1706 return NULL;
1707
1708 for (i = 0; i < n; ++i)
1709 {
1710 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1711
1712 /* Error check - was the Python string creation OK? */
1713 if (str == NULL)
1714 {
1715 Py_DECREF(list);
1716 return NULL;
1717 }
1718
1719 /* Set the list item */
1720 if (PyList_SetItem(list, i, str))
1721 {
1722 Py_DECREF(str);
1723 Py_DECREF(list);
1724 return NULL;
1725 }
1726 }
1727
1728 /* The ownership of the Python list is passed to the caller (ie,
1729 * the caller should Py_DECREF() the object when it is finished
1730 * with it).
1731 */
1732
1733 return list;
1734}
1735
1736/*
1737 * Check if deleting lines made the cursor position invalid.
1738 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1739 * deleted).
1740 */
1741 static void
1742py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1743{
1744 if (curwin->w_cursor.lnum >= lo)
1745 {
1746 /* Adjust the cursor position if it's in/after the changed
1747 * lines. */
1748 if (curwin->w_cursor.lnum >= hi)
1749 {
1750 curwin->w_cursor.lnum += extra;
1751 check_cursor_col();
1752 }
1753 else if (extra < 0)
1754 {
1755 curwin->w_cursor.lnum = lo;
1756 check_cursor();
1757 }
1758 else
1759 check_cursor_col();
1760 changed_cline_bef_curs();
1761 }
1762 invalidate_botline();
1763}
1764
Bram Moolenaar19e60942011-06-19 00:27:51 +02001765/*
1766 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001767 * in Vim format (1-based). The replacement line is given as
1768 * a Python string object. The object is checked for validity
1769 * and correct format. Errors are returned as a value of FAIL.
1770 * The return value is OK on success.
1771 * If OK is returned and len_change is not NULL, *len_change
1772 * is set to the change in the buffer length.
1773 */
1774 static int
1775SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
1776{
1777 /* First of all, we check the thpe of the supplied Python object.
1778 * There are three cases:
1779 * 1. NULL, or None - this is a deletion.
1780 * 2. A string - this is a replacement.
1781 * 3. Anything else - this is an error.
1782 */
1783 if (line == Py_None || line == NULL)
1784 {
1785 buf_T *savebuf = curbuf;
1786
1787 PyErr_Clear();
1788 curbuf = buf;
1789
1790 if (u_savedel((linenr_T)n, 1L) == FAIL)
1791 PyErr_SetVim(_("cannot save undo information"));
1792 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
1793 PyErr_SetVim(_("cannot delete line"));
1794 else
1795 {
1796 if (buf == curwin->w_buffer)
1797 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
1798 deleted_lines_mark((linenr_T)n, 1L);
1799 }
1800
1801 curbuf = savebuf;
1802
1803 if (PyErr_Occurred() || VimErrorCheck())
1804 return FAIL;
1805
1806 if (len_change)
1807 *len_change = -1;
1808
1809 return OK;
1810 }
1811 else if (PyString_Check(line))
1812 {
1813 char *save = StringToLine(line);
1814 buf_T *savebuf = curbuf;
1815
1816 if (save == NULL)
1817 return FAIL;
1818
1819 /* We do not need to free "save" if ml_replace() consumes it. */
1820 PyErr_Clear();
1821 curbuf = buf;
1822
1823 if (u_savesub((linenr_T)n) == FAIL)
1824 {
1825 PyErr_SetVim(_("cannot save undo information"));
1826 vim_free(save);
1827 }
1828 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
1829 {
1830 PyErr_SetVim(_("cannot replace line"));
1831 vim_free(save);
1832 }
1833 else
1834 changed_bytes((linenr_T)n, 0);
1835
1836 curbuf = savebuf;
1837
1838 /* Check that the cursor is not beyond the end of the line now. */
1839 if (buf == curwin->w_buffer)
1840 check_cursor_col();
1841
1842 if (PyErr_Occurred() || VimErrorCheck())
1843 return FAIL;
1844
1845 if (len_change)
1846 *len_change = 0;
1847
1848 return OK;
1849 }
1850 else
1851 {
1852 PyErr_BadArgument();
1853 return FAIL;
1854 }
1855}
1856
Bram Moolenaar19e60942011-06-19 00:27:51 +02001857/* Replace a range of lines in the specified buffer. The line numbers are in
1858 * Vim format (1-based). The range is from lo up to, but not including, hi.
1859 * The replacement lines are given as a Python list of string objects. The
1860 * list is checked for validity and correct format. Errors are returned as a
1861 * value of FAIL. The return value is OK on success.
1862 * If OK is returned and len_change is not NULL, *len_change
1863 * is set to the change in the buffer length.
1864 */
1865 static int
1866SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
1867{
1868 /* First of all, we check the thpe of the supplied Python object.
1869 * There are three cases:
1870 * 1. NULL, or None - this is a deletion.
1871 * 2. A list - this is a replacement.
1872 * 3. Anything else - this is an error.
1873 */
1874 if (list == Py_None || list == NULL)
1875 {
1876 PyInt i;
1877 PyInt n = (int)(hi - lo);
1878 buf_T *savebuf = curbuf;
1879
1880 PyErr_Clear();
1881 curbuf = buf;
1882
1883 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
1884 PyErr_SetVim(_("cannot save undo information"));
1885 else
1886 {
1887 for (i = 0; i < n; ++i)
1888 {
1889 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1890 {
1891 PyErr_SetVim(_("cannot delete line"));
1892 break;
1893 }
1894 }
1895 if (buf == curwin->w_buffer)
1896 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
1897 deleted_lines_mark((linenr_T)lo, (long)i);
1898 }
1899
1900 curbuf = savebuf;
1901
1902 if (PyErr_Occurred() || VimErrorCheck())
1903 return FAIL;
1904
1905 if (len_change)
1906 *len_change = -n;
1907
1908 return OK;
1909 }
1910 else if (PyList_Check(list))
1911 {
1912 PyInt i;
1913 PyInt new_len = PyList_Size(list);
1914 PyInt old_len = hi - lo;
1915 PyInt extra = 0; /* lines added to text, can be negative */
1916 char **array;
1917 buf_T *savebuf;
1918
1919 if (new_len == 0) /* avoid allocating zero bytes */
1920 array = NULL;
1921 else
1922 {
1923 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
1924 if (array == NULL)
1925 {
1926 PyErr_NoMemory();
1927 return FAIL;
1928 }
1929 }
1930
1931 for (i = 0; i < new_len; ++i)
1932 {
1933 PyObject *line = PyList_GetItem(list, i);
1934
1935 array[i] = StringToLine(line);
1936 if (array[i] == NULL)
1937 {
1938 while (i)
1939 vim_free(array[--i]);
1940 vim_free(array);
1941 return FAIL;
1942 }
1943 }
1944
1945 savebuf = curbuf;
1946
1947 PyErr_Clear();
1948 curbuf = buf;
1949
1950 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
1951 PyErr_SetVim(_("cannot save undo information"));
1952
1953 /* If the size of the range is reducing (ie, new_len < old_len) we
1954 * need to delete some old_len. We do this at the start, by
1955 * repeatedly deleting line "lo".
1956 */
1957 if (!PyErr_Occurred())
1958 {
1959 for (i = 0; i < old_len - new_len; ++i)
1960 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1961 {
1962 PyErr_SetVim(_("cannot delete line"));
1963 break;
1964 }
1965 extra -= i;
1966 }
1967
1968 /* For as long as possible, replace the existing old_len with the
1969 * new old_len. This is a more efficient operation, as it requires
1970 * less memory allocation and freeing.
1971 */
1972 if (!PyErr_Occurred())
1973 {
1974 for (i = 0; i < old_len && i < new_len; ++i)
1975 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
1976 == FAIL)
1977 {
1978 PyErr_SetVim(_("cannot replace line"));
1979 break;
1980 }
1981 }
1982 else
1983 i = 0;
1984
1985 /* Now we may need to insert the remaining new old_len. If we do, we
1986 * must free the strings as we finish with them (we can't pass the
1987 * responsibility to vim in this case).
1988 */
1989 if (!PyErr_Occurred())
1990 {
1991 while (i < new_len)
1992 {
1993 if (ml_append((linenr_T)(lo + i - 1),
1994 (char_u *)array[i], 0, FALSE) == FAIL)
1995 {
1996 PyErr_SetVim(_("cannot insert line"));
1997 break;
1998 }
1999 vim_free(array[i]);
2000 ++i;
2001 ++extra;
2002 }
2003 }
2004
2005 /* Free any left-over old_len, as a result of an error */
2006 while (i < new_len)
2007 {
2008 vim_free(array[i]);
2009 ++i;
2010 }
2011
2012 /* Free the array of old_len. All of its contents have now
2013 * been dealt with (either freed, or the responsibility passed
2014 * to vim.
2015 */
2016 vim_free(array);
2017
2018 /* Adjust marks. Invalidate any which lie in the
2019 * changed range, and move any in the remainder of the buffer.
2020 */
2021 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2022 (long)MAXLNUM, (long)extra);
2023 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2024
2025 if (buf == curwin->w_buffer)
2026 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2027
2028 curbuf = savebuf;
2029
2030 if (PyErr_Occurred() || VimErrorCheck())
2031 return FAIL;
2032
2033 if (len_change)
2034 *len_change = new_len - old_len;
2035
2036 return OK;
2037 }
2038 else
2039 {
2040 PyErr_BadArgument();
2041 return FAIL;
2042 }
2043}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002044
2045/* Insert a number of lines into the specified buffer after the specifed line.
2046 * The line number is in Vim format (1-based). The lines to be inserted are
2047 * given as a Python list of string objects or as a single string. The lines
2048 * to be added are checked for validity and correct format. Errors are
2049 * returned as a value of FAIL. The return value is OK on success.
2050 * If OK is returned and len_change is not NULL, *len_change
2051 * is set to the change in the buffer length.
2052 */
2053 static int
2054InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2055{
2056 /* First of all, we check the type of the supplied Python object.
2057 * It must be a string or a list, or the call is in error.
2058 */
2059 if (PyString_Check(lines))
2060 {
2061 char *str = StringToLine(lines);
2062 buf_T *savebuf;
2063
2064 if (str == NULL)
2065 return FAIL;
2066
2067 savebuf = curbuf;
2068
2069 PyErr_Clear();
2070 curbuf = buf;
2071
2072 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2073 PyErr_SetVim(_("cannot save undo information"));
2074 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2075 PyErr_SetVim(_("cannot insert line"));
2076 else
2077 appended_lines_mark((linenr_T)n, 1L);
2078
2079 vim_free(str);
2080 curbuf = savebuf;
2081 update_screen(VALID);
2082
2083 if (PyErr_Occurred() || VimErrorCheck())
2084 return FAIL;
2085
2086 if (len_change)
2087 *len_change = 1;
2088
2089 return OK;
2090 }
2091 else if (PyList_Check(lines))
2092 {
2093 PyInt i;
2094 PyInt size = PyList_Size(lines);
2095 char **array;
2096 buf_T *savebuf;
2097
2098 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2099 if (array == NULL)
2100 {
2101 PyErr_NoMemory();
2102 return FAIL;
2103 }
2104
2105 for (i = 0; i < size; ++i)
2106 {
2107 PyObject *line = PyList_GetItem(lines, i);
2108 array[i] = StringToLine(line);
2109
2110 if (array[i] == NULL)
2111 {
2112 while (i)
2113 vim_free(array[--i]);
2114 vim_free(array);
2115 return FAIL;
2116 }
2117 }
2118
2119 savebuf = curbuf;
2120
2121 PyErr_Clear();
2122 curbuf = buf;
2123
2124 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2125 PyErr_SetVim(_("cannot save undo information"));
2126 else
2127 {
2128 for (i = 0; i < size; ++i)
2129 {
2130 if (ml_append((linenr_T)(n + i),
2131 (char_u *)array[i], 0, FALSE) == FAIL)
2132 {
2133 PyErr_SetVim(_("cannot insert line"));
2134
2135 /* Free the rest of the lines */
2136 while (i < size)
2137 vim_free(array[i++]);
2138
2139 break;
2140 }
2141 vim_free(array[i]);
2142 }
2143 if (i > 0)
2144 appended_lines_mark((linenr_T)n, (long)i);
2145 }
2146
2147 /* Free the array of lines. All of its contents have now
2148 * been freed.
2149 */
2150 vim_free(array);
2151
2152 curbuf = savebuf;
2153 update_screen(VALID);
2154
2155 if (PyErr_Occurred() || VimErrorCheck())
2156 return FAIL;
2157
2158 if (len_change)
2159 *len_change = size;
2160
2161 return OK;
2162 }
2163 else
2164 {
2165 PyErr_BadArgument();
2166 return FAIL;
2167 }
2168}
2169
2170/*
2171 * Common routines for buffers and line ranges
2172 * -------------------------------------------
2173 */
2174
2175 static int
2176CheckBuffer(BufferObject *this)
2177{
2178 if (this->buf == INVALID_BUFFER_VALUE)
2179 {
2180 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2181 return -1;
2182 }
2183
2184 return 0;
2185}
2186
2187 static PyObject *
2188RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2189{
2190 if (CheckBuffer(self))
2191 return NULL;
2192
2193 if (n < 0 || n > end - start)
2194 {
2195 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2196 return NULL;
2197 }
2198
2199 return GetBufferLine(self->buf, n+start);
2200}
2201
2202 static PyObject *
2203RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2204{
2205 PyInt size;
2206
2207 if (CheckBuffer(self))
2208 return NULL;
2209
2210 size = end - start + 1;
2211
2212 if (lo < 0)
2213 lo = 0;
2214 else if (lo > size)
2215 lo = size;
2216 if (hi < 0)
2217 hi = 0;
2218 if (hi < lo)
2219 hi = lo;
2220 else if (hi > size)
2221 hi = size;
2222
2223 return GetBufferLineList(self->buf, lo+start, hi+start);
2224}
2225
2226 static PyInt
2227RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2228{
2229 PyInt len_change;
2230
2231 if (CheckBuffer(self))
2232 return -1;
2233
2234 if (n < 0 || n > end - start)
2235 {
2236 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2237 return -1;
2238 }
2239
2240 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2241 return -1;
2242
2243 if (new_end)
2244 *new_end = end + len_change;
2245
2246 return 0;
2247}
2248
Bram Moolenaar19e60942011-06-19 00:27:51 +02002249 static PyInt
2250RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2251{
2252 PyInt size;
2253 PyInt len_change;
2254
2255 /* Self must be a valid buffer */
2256 if (CheckBuffer(self))
2257 return -1;
2258
2259 /* Sort out the slice range */
2260 size = end - start + 1;
2261
2262 if (lo < 0)
2263 lo = 0;
2264 else if (lo > size)
2265 lo = size;
2266 if (hi < 0)
2267 hi = 0;
2268 if (hi < lo)
2269 hi = lo;
2270 else if (hi > size)
2271 hi = size;
2272
2273 if (SetBufferLineList(self->buf, lo + start, hi + start,
2274 val, &len_change) == FAIL)
2275 return -1;
2276
2277 if (new_end)
2278 *new_end = end + len_change;
2279
2280 return 0;
2281}
2282
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002283
2284 static PyObject *
2285RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2286{
2287 PyObject *lines;
2288 PyInt len_change;
2289 PyInt max;
2290 PyInt n;
2291
2292 if (CheckBuffer(self))
2293 return NULL;
2294
2295 max = n = end - start + 1;
2296
2297 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2298 return NULL;
2299
2300 if (n < 0 || n > max)
2301 {
2302 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2303 return NULL;
2304 }
2305
2306 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2307 return NULL;
2308
2309 if (new_end)
2310 *new_end = end + len_change;
2311
2312 Py_INCREF(Py_None);
2313 return Py_None;
2314}
2315
2316
2317/* Buffer object - Definitions
2318 */
2319
2320typedef struct
2321{
2322 PyObject_HEAD
2323 BufferObject *buf;
2324 PyInt start;
2325 PyInt end;
2326} RangeObject;
2327
2328 static PyObject *
2329RangeNew(buf_T *buf, PyInt start, PyInt end)
2330{
2331 BufferObject *bufr;
2332 RangeObject *self;
2333 self = PyObject_NEW(RangeObject, &RangeType);
2334 if (self == NULL)
2335 return NULL;
2336
2337 bufr = (BufferObject *)BufferNew(buf);
2338 if (bufr == NULL)
2339 {
2340 Py_DECREF(self);
2341 return NULL;
2342 }
2343 Py_INCREF(bufr);
2344
2345 self->buf = bufr;
2346 self->start = start;
2347 self->end = end;
2348
2349 return (PyObject *)(self);
2350}
2351
2352 static PyObject *
2353BufferAppend(PyObject *self, PyObject *args)
2354{
2355 return RBAppend((BufferObject *)(self), args, 1,
2356 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2357 NULL);
2358}
2359
2360 static PyObject *
2361BufferMark(PyObject *self, PyObject *args)
2362{
2363 pos_T *posp;
2364 char *pmark;
2365 char mark;
2366 buf_T *curbuf_save;
2367
2368 if (CheckBuffer((BufferObject *)(self)))
2369 return NULL;
2370
2371 if (!PyArg_ParseTuple(args, "s", &pmark))
2372 return NULL;
2373 mark = *pmark;
2374
2375 curbuf_save = curbuf;
2376 curbuf = ((BufferObject *)(self))->buf;
2377 posp = getmark(mark, FALSE);
2378 curbuf = curbuf_save;
2379
2380 if (posp == NULL)
2381 {
2382 PyErr_SetVim(_("invalid mark name"));
2383 return NULL;
2384 }
2385
2386 /* Ckeck for keyboard interrupt */
2387 if (VimErrorCheck())
2388 return NULL;
2389
2390 if (posp->lnum <= 0)
2391 {
2392 /* Or raise an error? */
2393 Py_INCREF(Py_None);
2394 return Py_None;
2395 }
2396
2397 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2398}
2399
2400 static PyObject *
2401BufferRange(PyObject *self, PyObject *args)
2402{
2403 PyInt start;
2404 PyInt end;
2405
2406 if (CheckBuffer((BufferObject *)(self)))
2407 return NULL;
2408
2409 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2410 return NULL;
2411
2412 return RangeNew(((BufferObject *)(self))->buf, start, end);
2413}
2414
2415static struct PyMethodDef BufferMethods[] = {
2416 /* name, function, calling, documentation */
2417 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2418 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2419 {"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 +01002420#if PY_VERSION_HEX >= 0x03000000
2421 {"__dir__", BufferDir, 4, "List its attributes" },
2422#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002423 { NULL, NULL, 0, NULL }
2424};
2425
2426 static PyObject *
2427RangeAppend(PyObject *self, PyObject *args)
2428{
2429 return RBAppend(((RangeObject *)(self))->buf, args,
2430 ((RangeObject *)(self))->start,
2431 ((RangeObject *)(self))->end,
2432 &((RangeObject *)(self))->end);
2433}
2434
2435 static PyInt
2436RangeLength(PyObject *self)
2437{
2438 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2439 if (CheckBuffer(((RangeObject *)(self))->buf))
2440 return -1; /* ??? */
2441
2442 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2443}
2444
2445 static PyObject *
2446RangeItem(PyObject *self, PyInt n)
2447{
2448 return RBItem(((RangeObject *)(self))->buf, n,
2449 ((RangeObject *)(self))->start,
2450 ((RangeObject *)(self))->end);
2451}
2452
2453 static PyObject *
2454RangeRepr(PyObject *self)
2455{
2456 static char repr[100];
2457 RangeObject *this = (RangeObject *)(self);
2458
2459 if (this->buf->buf == INVALID_BUFFER_VALUE)
2460 {
2461 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2462 (self));
2463 return PyString_FromString(repr);
2464 }
2465 else
2466 {
2467 char *name = (char *)this->buf->buf->b_fname;
2468 int len;
2469
2470 if (name == NULL)
2471 name = "";
2472 len = (int)strlen(name);
2473
2474 if (len > 45)
2475 name = name + (45 - len);
2476
2477 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2478 len > 45 ? "..." : "", name,
2479 this->start, this->end);
2480
2481 return PyString_FromString(repr);
2482 }
2483}
2484
2485 static PyObject *
2486RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2487{
2488 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2489 ((RangeObject *)(self))->start,
2490 ((RangeObject *)(self))->end);
2491}
2492
2493/*
2494 * Line range object - Definitions
2495 */
2496
2497static struct PyMethodDef RangeMethods[] = {
2498 /* name, function, calling, documentation */
2499 {"append", RangeAppend, 1, "Append data to the Vim range" },
2500 { NULL, NULL, 0, NULL }
2501};
2502
Bram Moolenaardb913952012-06-29 12:54:53 +02002503 static void
2504set_ref_in_py(const int copyID)
2505{
2506 pylinkedlist_T *cur;
2507 dict_T *dd;
2508 list_T *ll;
2509
2510 if (lastdict != NULL)
2511 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
2512 {
2513 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
2514 if (dd->dv_copyID != copyID)
2515 {
2516 dd->dv_copyID = copyID;
2517 set_ref_in_ht(&dd->dv_hashtab, copyID);
2518 }
2519 }
2520
2521 if (lastlist != NULL)
2522 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
2523 {
2524 ll = ((ListObject *) (cur->pll_obj))->list;
2525 if (ll->lv_copyID != copyID)
2526 {
2527 ll->lv_copyID = copyID;
2528 set_ref_in_list(ll, copyID);
2529 }
2530 }
2531}
2532
2533 static int
2534set_string_copy(char_u *str, typval_T *tv)
2535{
2536 tv->vval.v_string = vim_strsave(str);
2537 if (tv->vval.v_string == NULL)
2538 {
2539 PyErr_NoMemory();
2540 return -1;
2541 }
2542 return 0;
2543}
2544
2545#ifdef FEAT_EVAL
2546typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
2547
2548 static int
2549convert_dl(PyObject *obj, typval_T *tv,
2550 pytotvfunc py_to_tv, PyObject *lookupDict)
2551{
2552 PyObject *capsule;
2553 char hexBuf[sizeof(void *) * 2 + 3];
2554
2555 sprintf(hexBuf, "%p", obj);
2556
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002557# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002558 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002559# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002560 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002561# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02002562 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02002563 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002564# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002565 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02002566# else
2567 capsule = PyCObject_FromVoidPtr(tv, NULL);
2568# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002569 PyDict_SetItemString(lookupDict, hexBuf, capsule);
2570 Py_DECREF(capsule);
2571 if (py_to_tv(obj, tv, lookupDict) == -1)
2572 {
2573 tv->v_type = VAR_UNKNOWN;
2574 return -1;
2575 }
2576 /* As we are not using copy_tv which increments reference count we must
2577 * do it ourself. */
2578 switch(tv->v_type)
2579 {
2580 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
2581 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
2582 }
2583 }
2584 else
2585 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002586 typval_T *v;
2587
2588# ifdef PY_USE_CAPSULE
2589 v = PyCapsule_GetPointer(capsule, NULL);
2590# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002591 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002592# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002593 copy_tv(v, tv);
2594 }
2595 return 0;
2596}
2597
2598 static int
2599ConvertFromPyObject(PyObject *obj, typval_T *tv)
2600{
2601 PyObject *lookup_dict;
2602 int r;
2603
2604 lookup_dict = PyDict_New();
2605 r = _ConvertFromPyObject(obj, tv, lookup_dict);
2606 Py_DECREF(lookup_dict);
2607 return r;
2608}
2609
2610 static int
2611_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2612{
2613 if (obj->ob_type == &DictionaryType)
2614 {
2615 tv->v_type = VAR_DICT;
2616 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
2617 ++tv->vval.v_dict->dv_refcount;
2618 }
2619 else if (obj->ob_type == &ListType)
2620 {
2621 tv->v_type = VAR_LIST;
2622 tv->vval.v_list = (((ListObject *)(obj))->list);
2623 ++tv->vval.v_list->lv_refcount;
2624 }
2625 else if (obj->ob_type == &FunctionType)
2626 {
2627 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
2628 return -1;
2629
2630 tv->v_type = VAR_FUNC;
2631 func_ref(tv->vval.v_string);
2632 }
2633#if PY_MAJOR_VERSION >= 3
2634 else if (PyBytes_Check(obj))
2635 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002636 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02002637
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002638 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
2639 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002640 if (result == NULL)
2641 return -1;
2642
2643 if (set_string_copy(result, tv) == -1)
2644 return -1;
2645
2646 tv->v_type = VAR_STRING;
2647 }
2648 else if (PyUnicode_Check(obj))
2649 {
2650 PyObject *bytes;
2651 char_u *result;
2652
2653 bytes = PyString_AsBytes(obj);
2654 if (bytes == NULL)
2655 return -1;
2656
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002657 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
2658 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002659 if (result == NULL)
2660 return -1;
2661
2662 if (set_string_copy(result, tv) == -1)
2663 {
2664 Py_XDECREF(bytes);
2665 return -1;
2666 }
2667 Py_XDECREF(bytes);
2668
2669 tv->v_type = VAR_STRING;
2670 }
2671#else
2672 else if (PyUnicode_Check(obj))
2673 {
2674 PyObject *bytes;
2675 char_u *result;
2676
2677 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
2678 if (bytes == NULL)
2679 return -1;
2680
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002681 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
2682 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002683 if (result == NULL)
2684 return -1;
2685
2686 if (set_string_copy(result, tv) == -1)
2687 {
2688 Py_XDECREF(bytes);
2689 return -1;
2690 }
2691 Py_XDECREF(bytes);
2692
2693 tv->v_type = VAR_STRING;
2694 }
2695 else if (PyString_Check(obj))
2696 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002697 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02002698
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002699 if(PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
2700 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002701 if (result == NULL)
2702 return -1;
2703
2704 if (set_string_copy(result, tv) == -1)
2705 return -1;
2706
2707 tv->v_type = VAR_STRING;
2708 }
2709 else if (PyInt_Check(obj))
2710 {
2711 tv->v_type = VAR_NUMBER;
2712 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
2713 }
2714#endif
2715 else if (PyLong_Check(obj))
2716 {
2717 tv->v_type = VAR_NUMBER;
2718 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
2719 }
2720 else if (PyDict_Check(obj))
2721 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
2722#ifdef FEAT_FLOAT
2723 else if (PyFloat_Check(obj))
2724 {
2725 tv->v_type = VAR_FLOAT;
2726 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
2727 }
2728#endif
2729 else if (PyIter_Check(obj))
2730 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
2731 else if (PySequence_Check(obj))
2732 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
2733 else if (PyMapping_Check(obj))
2734 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
2735 else
2736 {
2737 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
2738 return -1;
2739 }
2740 return 0;
2741}
2742
2743 static PyObject *
2744ConvertToPyObject(typval_T *tv)
2745{
2746 if (tv == NULL)
2747 {
2748 PyErr_SetVim(_("NULL reference passed"));
2749 return NULL;
2750 }
2751 switch (tv->v_type)
2752 {
2753 case VAR_STRING:
2754 return PyBytes_FromString((char *) tv->vval.v_string);
2755 case VAR_NUMBER:
2756 return PyLong_FromLong((long) tv->vval.v_number);
2757#ifdef FEAT_FLOAT
2758 case VAR_FLOAT:
2759 return PyFloat_FromDouble((double) tv->vval.v_float);
2760#endif
2761 case VAR_LIST:
2762 return ListNew(tv->vval.v_list);
2763 case VAR_DICT:
2764 return DictionaryNew(tv->vval.v_dict);
2765 case VAR_FUNC:
2766 return FunctionNew(tv->vval.v_string);
2767 case VAR_UNKNOWN:
2768 Py_INCREF(Py_None);
2769 return Py_None;
2770 default:
2771 PyErr_SetVim(_("internal error: invalid value type"));
2772 return NULL;
2773 }
2774}
2775#endif