blob: 0909981c22fbcff2c60c435643cbf591d91b8342 [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
811DictionaryLength(PyObject *self)
812{
813 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
814}
815
816 static PyObject *
817DictionaryItem(PyObject *self, PyObject *keyObject)
818{
819 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200820 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200821 DICTKEY_DECL
822
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200823 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200824
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200825 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
826
Bram Moolenaar696c2112012-09-21 13:43:14 +0200827 DICTKEY_UNREF
828
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200829 if (di == NULL)
830 {
831 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
832 return NULL;
833 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200834
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200835 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200836}
837
838 static PyInt
839DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
840{
841 char_u *key;
842 typval_T tv;
843 dict_T *d = ((DictionaryObject *)(self))->dict;
844 dictitem_T *di;
845 DICTKEY_DECL
846
847 if (d->dv_lock)
848 {
849 PyErr_SetVim(_("dict is locked"));
850 return -1;
851 }
852
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200853 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200854
855 di = dict_find(d, key, -1);
856
857 if (valObject == NULL)
858 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200859 hashitem_T *hi;
860
Bram Moolenaardb913952012-06-29 12:54:53 +0200861 if (di == NULL)
862 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200863 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200864 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
865 return -1;
866 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200867 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200868 hash_remove(&d->dv_hashtab, hi);
869 dictitem_free(di);
870 return 0;
871 }
872
873 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200874 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200875
876 if (di == NULL)
877 {
878 di = dictitem_alloc(key);
879 if (di == NULL)
880 {
881 PyErr_NoMemory();
882 return -1;
883 }
884 di->di_tv.v_lock = 0;
885
886 if (dict_add(d, di) == FAIL)
887 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200888 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200889 vim_free(di);
890 PyErr_SetVim(_("failed to add key to dictionary"));
891 return -1;
892 }
893 }
894 else
895 clear_tv(&di->di_tv);
896
897 DICTKEY_UNREF
898
899 copy_tv(&tv, &di->di_tv);
900 return 0;
901}
902
903 static PyObject *
904DictionaryListKeys(PyObject *self)
905{
906 dict_T *dict = ((DictionaryObject *)(self))->dict;
907 long_u todo = dict->dv_hashtab.ht_used;
908 Py_ssize_t i = 0;
909 PyObject *r;
910 hashitem_T *hi;
911
912 r = PyList_New(todo);
913 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
914 {
915 if (!HASHITEM_EMPTY(hi))
916 {
917 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
918 --todo;
919 ++i;
920 }
921 }
922 return r;
923}
924
925static struct PyMethodDef DictionaryMethods[] = {
926 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
927 { NULL, NULL, 0, NULL }
928};
929
930static PyTypeObject ListType;
931
932typedef struct
933{
934 PyObject_HEAD
935 list_T *list;
936 pylinkedlist_T ref;
937} ListObject;
938
939 static PyObject *
940ListNew(list_T *list)
941{
942 ListObject *self;
943
944 self = PyObject_NEW(ListObject, &ListType);
945 if (self == NULL)
946 return NULL;
947 self->list = list;
948 ++list->lv_refcount;
949
950 pyll_add((PyObject *)(self), &self->ref, &lastlist);
951
952 return (PyObject *)(self);
953}
954
955 static int
956list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
957{
958 Py_ssize_t i;
959 Py_ssize_t lsize = PySequence_Size(obj);
960 PyObject *litem;
961 listitem_T *li;
962
963 for(i=0; i<lsize; i++)
964 {
965 li = listitem_alloc();
966 if (li == NULL)
967 {
968 PyErr_NoMemory();
969 return -1;
970 }
971 li->li_tv.v_lock = 0;
972
973 litem = PySequence_GetItem(obj, i);
974 if (litem == NULL)
975 return -1;
976 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
977 return -1;
978
979 list_append(l, li);
980 }
981 return 0;
982}
983
984 static int
985pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
986{
987 list_T *l;
988
989 l = list_alloc();
990 if (l == NULL)
991 {
992 PyErr_NoMemory();
993 return -1;
994 }
995
996 tv->v_type = VAR_LIST;
997 tv->vval.v_list = l;
998
999 if (list_py_concat(l, obj, lookupDict) == -1)
1000 return -1;
1001
1002 return 0;
1003}
1004
1005 static int
1006pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
1007{
1008 PyObject *iterator = PyObject_GetIter(obj);
1009 PyObject *item;
1010 list_T *l;
1011 listitem_T *li;
1012
1013 l = list_alloc();
1014
1015 if (l == NULL)
1016 {
1017 PyErr_NoMemory();
1018 return -1;
1019 }
1020
1021 tv->vval.v_list = l;
1022 tv->v_type = VAR_LIST;
1023
1024
1025 if (iterator == NULL)
1026 return -1;
1027
1028 while ((item = PyIter_Next(obj)))
1029 {
1030 li = listitem_alloc();
1031 if (li == NULL)
1032 {
1033 PyErr_NoMemory();
1034 return -1;
1035 }
1036 li->li_tv.v_lock = 0;
1037
1038 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
1039 return -1;
1040
1041 list_append(l, li);
1042
1043 Py_DECREF(item);
1044 }
1045
1046 Py_DECREF(iterator);
1047 return 0;
1048}
1049
1050 static PyInt
1051ListLength(PyObject *self)
1052{
1053 return ((PyInt) (((ListObject *) (self))->list->lv_len));
1054}
1055
1056 static PyObject *
1057ListItem(PyObject *self, Py_ssize_t index)
1058{
1059 listitem_T *li;
1060
1061 if (index>=ListLength(self))
1062 {
1063 PyErr_SetString(PyExc_IndexError, "list index out of range");
1064 return NULL;
1065 }
1066 li = list_find(((ListObject *) (self))->list, (long) index);
1067 if (li == NULL)
1068 {
1069 PyErr_SetVim(_("internal error: failed to get vim list item"));
1070 return NULL;
1071 }
1072 return ConvertToPyObject(&li->li_tv);
1073}
1074
1075#define PROC_RANGE \
1076 if (last < 0) {\
1077 if (last < -size) \
1078 last = 0; \
1079 else \
1080 last += size; \
1081 } \
1082 if (first < 0) \
1083 first = 0; \
1084 if (first > size) \
1085 first = size; \
1086 if (last > size) \
1087 last = size;
1088
1089 static PyObject *
1090ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
1091{
1092 PyInt i;
1093 PyInt size = ListLength(self);
1094 PyInt n;
1095 PyObject *list;
1096 int reversed = 0;
1097
1098 PROC_RANGE
1099 if (first >= last)
1100 first = last;
1101
1102 n = last-first;
1103 list = PyList_New(n);
1104 if (list == NULL)
1105 return NULL;
1106
1107 for (i = 0; i < n; ++i)
1108 {
1109 PyObject *item = ListItem(self, i);
1110 if (item == NULL)
1111 {
1112 Py_DECREF(list);
1113 return NULL;
1114 }
1115
1116 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
1117 {
1118 Py_DECREF(item);
1119 Py_DECREF(list);
1120 return NULL;
1121 }
1122 }
1123
1124 return list;
1125}
1126
1127 static int
1128ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1129{
1130 typval_T tv;
1131 list_T *l = ((ListObject *) (self))->list;
1132 listitem_T *li;
1133 Py_ssize_t length = ListLength(self);
1134
1135 if (l->lv_lock)
1136 {
1137 PyErr_SetVim(_("list is locked"));
1138 return -1;
1139 }
1140 if (index>length || (index==length && obj==NULL))
1141 {
1142 PyErr_SetString(PyExc_IndexError, "list index out of range");
1143 return -1;
1144 }
1145
1146 if (obj == NULL)
1147 {
1148 li = list_find(l, (long) index);
1149 list_remove(l, li, li);
1150 clear_tv(&li->li_tv);
1151 vim_free(li);
1152 return 0;
1153 }
1154
1155 if (ConvertFromPyObject(obj, &tv) == -1)
1156 return -1;
1157
1158 if (index == length)
1159 {
1160 if (list_append_tv(l, &tv) == FAIL)
1161 {
1162 PyErr_SetVim(_("Failed to add item to list"));
1163 return -1;
1164 }
1165 }
1166 else
1167 {
1168 li = list_find(l, (long) index);
1169 clear_tv(&li->li_tv);
1170 copy_tv(&tv, &li->li_tv);
1171 }
1172 return 0;
1173}
1174
1175 static int
1176ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1177{
1178 PyInt size = ListLength(self);
1179 Py_ssize_t i;
1180 Py_ssize_t lsize;
1181 PyObject *litem;
1182 listitem_T *li;
1183 listitem_T *next;
1184 typval_T v;
1185 list_T *l = ((ListObject *) (self))->list;
1186
1187 if (l->lv_lock)
1188 {
1189 PyErr_SetVim(_("list is locked"));
1190 return -1;
1191 }
1192
1193 PROC_RANGE
1194
1195 if (first == size)
1196 li = NULL;
1197 else
1198 {
1199 li = list_find(l, (long) first);
1200 if (li == NULL)
1201 {
1202 PyErr_SetVim(_("internal error: no vim list item"));
1203 return -1;
1204 }
1205 if (last > first)
1206 {
1207 i = last - first;
1208 while (i-- && li != NULL)
1209 {
1210 next = li->li_next;
1211 listitem_remove(l, li);
1212 li = next;
1213 }
1214 }
1215 }
1216
1217 if (obj == NULL)
1218 return 0;
1219
1220 if (!PyList_Check(obj))
1221 {
1222 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1223 return -1;
1224 }
1225
1226 lsize = PyList_Size(obj);
1227
1228 for(i=0; i<lsize; i++)
1229 {
1230 litem = PyList_GetItem(obj, i);
1231 if (litem == NULL)
1232 return -1;
1233 if (ConvertFromPyObject(litem, &v) == -1)
1234 return -1;
1235 if (list_insert_tv(l, &v, li) == FAIL)
1236 {
1237 PyErr_SetVim(_("internal error: failed to add item to list"));
1238 return -1;
1239 }
1240 }
1241 return 0;
1242}
1243
1244 static PyObject *
1245ListConcatInPlace(PyObject *self, PyObject *obj)
1246{
1247 list_T *l = ((ListObject *) (self))->list;
1248 PyObject *lookup_dict;
1249
1250 if (l->lv_lock)
1251 {
1252 PyErr_SetVim(_("list is locked"));
1253 return NULL;
1254 }
1255
1256 if (!PySequence_Check(obj))
1257 {
1258 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1259 return NULL;
1260 }
1261
1262 lookup_dict = PyDict_New();
1263 if (list_py_concat(l, obj, lookup_dict) == -1)
1264 {
1265 Py_DECREF(lookup_dict);
1266 return NULL;
1267 }
1268 Py_DECREF(lookup_dict);
1269
1270 Py_INCREF(self);
1271 return self;
1272}
1273
1274static struct PyMethodDef ListMethods[] = {
1275 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1276 { NULL, NULL, 0, NULL }
1277};
1278
1279typedef struct
1280{
1281 PyObject_HEAD
1282 char_u *name;
1283} FunctionObject;
1284
1285static PyTypeObject FunctionType;
1286
1287 static PyObject *
1288FunctionNew(char_u *name)
1289{
1290 FunctionObject *self;
1291
1292 self = PyObject_NEW(FunctionObject, &FunctionType);
1293 if (self == NULL)
1294 return NULL;
1295 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1296 if (self->name == NULL)
1297 {
1298 PyErr_NoMemory();
1299 return NULL;
1300 }
1301 STRCPY(self->name, name);
1302 func_ref(name);
1303 return (PyObject *)(self);
1304}
1305
1306 static PyObject *
1307FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1308{
1309 FunctionObject *this = (FunctionObject *)(self);
1310 char_u *name = this->name;
1311 typval_T args;
1312 typval_T selfdicttv;
1313 typval_T rettv;
1314 dict_T *selfdict = NULL;
1315 PyObject *selfdictObject;
1316 PyObject *result;
1317 int error;
1318
1319 if (ConvertFromPyObject(argsObject, &args) == -1)
1320 return NULL;
1321
1322 if (kwargs != NULL)
1323 {
1324 selfdictObject = PyDict_GetItemString(kwargs, "self");
1325 if (selfdictObject != NULL)
1326 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001327 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001328 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001329 PyErr_SetString(PyExc_TypeError,
1330 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001331 clear_tv(&args);
1332 return NULL;
1333 }
1334 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1335 return NULL;
1336 selfdict = selfdicttv.vval.v_dict;
1337 }
1338 }
1339
1340 error = func_call(name, &args, selfdict, &rettv);
1341 if (error != OK)
1342 {
1343 result = NULL;
1344 PyErr_SetVim(_("failed to run function"));
1345 }
1346 else
1347 result = ConvertToPyObject(&rettv);
1348
1349 /* FIXME Check what should really be cleared. */
1350 clear_tv(&args);
1351 clear_tv(&rettv);
1352 /*
1353 * if (selfdict!=NULL)
1354 * clear_tv(selfdicttv);
1355 */
1356
1357 return result;
1358}
1359
1360static struct PyMethodDef FunctionMethods[] = {
1361 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1362 { NULL, NULL, 0, NULL }
1363};
1364
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001365#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1366
1367 static int
1368CheckWindow(WindowObject *this)
1369{
1370 if (this->win == INVALID_WINDOW_VALUE)
1371 {
1372 PyErr_SetVim(_("attempt to refer to deleted window"));
1373 return -1;
1374 }
1375
1376 return 0;
1377}
1378
1379static int WindowSetattr(PyObject *, char *, PyObject *);
1380static PyObject *WindowRepr(PyObject *);
1381
1382 static int
1383WindowSetattr(PyObject *self, char *name, PyObject *val)
1384{
1385 WindowObject *this = (WindowObject *)(self);
1386
1387 if (CheckWindow(this))
1388 return -1;
1389
1390 if (strcmp(name, "buffer") == 0)
1391 {
1392 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1393 return -1;
1394 }
1395 else if (strcmp(name, "cursor") == 0)
1396 {
1397 long lnum;
1398 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001399
1400 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1401 return -1;
1402
1403 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1404 {
1405 PyErr_SetVim(_("cursor position outside buffer"));
1406 return -1;
1407 }
1408
1409 /* Check for keyboard interrupts */
1410 if (VimErrorCheck())
1411 return -1;
1412
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001413 this->win->w_cursor.lnum = lnum;
1414 this->win->w_cursor.col = col;
1415#ifdef FEAT_VIRTUALEDIT
1416 this->win->w_cursor.coladd = 0;
1417#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001418 /* When column is out of range silently correct it. */
1419 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001420
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001421 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001422 return 0;
1423 }
1424 else if (strcmp(name, "height") == 0)
1425 {
1426 int height;
1427 win_T *savewin;
1428
1429 if (!PyArg_Parse(val, "i", &height))
1430 return -1;
1431
1432#ifdef FEAT_GUI
1433 need_mouse_correct = TRUE;
1434#endif
1435 savewin = curwin;
1436 curwin = this->win;
1437 win_setheight(height);
1438 curwin = savewin;
1439
1440 /* Check for keyboard interrupts */
1441 if (VimErrorCheck())
1442 return -1;
1443
1444 return 0;
1445 }
1446#ifdef FEAT_VERTSPLIT
1447 else if (strcmp(name, "width") == 0)
1448 {
1449 int width;
1450 win_T *savewin;
1451
1452 if (!PyArg_Parse(val, "i", &width))
1453 return -1;
1454
1455#ifdef FEAT_GUI
1456 need_mouse_correct = TRUE;
1457#endif
1458 savewin = curwin;
1459 curwin = this->win;
1460 win_setwidth(width);
1461 curwin = savewin;
1462
1463 /* Check for keyboard interrupts */
1464 if (VimErrorCheck())
1465 return -1;
1466
1467 return 0;
1468 }
1469#endif
1470 else
1471 {
1472 PyErr_SetString(PyExc_AttributeError, name);
1473 return -1;
1474 }
1475}
1476
1477 static PyObject *
1478WindowRepr(PyObject *self)
1479{
1480 static char repr[100];
1481 WindowObject *this = (WindowObject *)(self);
1482
1483 if (this->win == INVALID_WINDOW_VALUE)
1484 {
1485 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1486 return PyString_FromString(repr);
1487 }
1488 else
1489 {
1490 int i = 0;
1491 win_T *w;
1492
1493 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
1494 ++i;
1495
1496 if (w == NULL)
1497 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1498 (self));
1499 else
1500 vim_snprintf(repr, 100, _("<window %d>"), i);
1501
1502 return PyString_FromString(repr);
1503 }
1504}
1505
1506/*
1507 * Window list object - Implementation
1508 */
1509 static PyInt
1510WinListLength(PyObject *self UNUSED)
1511{
1512 win_T *w = firstwin;
1513 PyInt n = 0;
1514
1515 while (w != NULL)
1516 {
1517 ++n;
1518 w = W_NEXT(w);
1519 }
1520
1521 return n;
1522}
1523
1524 static PyObject *
1525WinListItem(PyObject *self UNUSED, PyInt n)
1526{
1527 win_T *w;
1528
1529 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1530 if (n == 0)
1531 return WindowNew(w);
1532
1533 PyErr_SetString(PyExc_IndexError, _("no such window"));
1534 return NULL;
1535}
1536
1537/* Convert a Python string into a Vim line.
1538 *
1539 * The result is in allocated memory. All internal nulls are replaced by
1540 * newline characters. It is an error for the string to contain newline
1541 * characters.
1542 *
1543 * On errors, the Python exception data is set, and NULL is returned.
1544 */
1545 static char *
1546StringToLine(PyObject *obj)
1547{
1548 const char *str;
1549 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001550 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001551 PyInt len;
1552 PyInt i;
1553 char *p;
1554
1555 if (obj == NULL || !PyString_Check(obj))
1556 {
1557 PyErr_BadArgument();
1558 return NULL;
1559 }
1560
Bram Moolenaar19e60942011-06-19 00:27:51 +02001561 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1562 str = PyString_AsString(bytes);
1563 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001564
1565 /*
1566 * Error checking: String must not contain newlines, as we
1567 * are replacing a single line, and we must replace it with
1568 * a single line.
1569 * A trailing newline is removed, so that append(f.readlines()) works.
1570 */
1571 p = memchr(str, '\n', len);
1572 if (p != NULL)
1573 {
1574 if (p == str + len - 1)
1575 --len;
1576 else
1577 {
1578 PyErr_SetVim(_("string cannot contain newlines"));
1579 return NULL;
1580 }
1581 }
1582
1583 /* Create a copy of the string, with internal nulls replaced by
1584 * newline characters, as is the vim convention.
1585 */
1586 save = (char *)alloc((unsigned)(len+1));
1587 if (save == NULL)
1588 {
1589 PyErr_NoMemory();
1590 return NULL;
1591 }
1592
1593 for (i = 0; i < len; ++i)
1594 {
1595 if (str[i] == '\0')
1596 save[i] = '\n';
1597 else
1598 save[i] = str[i];
1599 }
1600
1601 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001602 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001603
1604 return save;
1605}
1606
1607/* Get a line from the specified buffer. The line number is
1608 * in Vim format (1-based). The line is returned as a Python
1609 * string object.
1610 */
1611 static PyObject *
1612GetBufferLine(buf_T *buf, PyInt n)
1613{
1614 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1615}
1616
1617
1618/* Get a list of lines from the specified buffer. The line numbers
1619 * are in Vim format (1-based). The range is from lo up to, but not
1620 * including, hi. The list is returned as a Python list of string objects.
1621 */
1622 static PyObject *
1623GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1624{
1625 PyInt i;
1626 PyInt n = hi - lo;
1627 PyObject *list = PyList_New(n);
1628
1629 if (list == NULL)
1630 return NULL;
1631
1632 for (i = 0; i < n; ++i)
1633 {
1634 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1635
1636 /* Error check - was the Python string creation OK? */
1637 if (str == NULL)
1638 {
1639 Py_DECREF(list);
1640 return NULL;
1641 }
1642
1643 /* Set the list item */
1644 if (PyList_SetItem(list, i, str))
1645 {
1646 Py_DECREF(str);
1647 Py_DECREF(list);
1648 return NULL;
1649 }
1650 }
1651
1652 /* The ownership of the Python list is passed to the caller (ie,
1653 * the caller should Py_DECREF() the object when it is finished
1654 * with it).
1655 */
1656
1657 return list;
1658}
1659
1660/*
1661 * Check if deleting lines made the cursor position invalid.
1662 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1663 * deleted).
1664 */
1665 static void
1666py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1667{
1668 if (curwin->w_cursor.lnum >= lo)
1669 {
1670 /* Adjust the cursor position if it's in/after the changed
1671 * lines. */
1672 if (curwin->w_cursor.lnum >= hi)
1673 {
1674 curwin->w_cursor.lnum += extra;
1675 check_cursor_col();
1676 }
1677 else if (extra < 0)
1678 {
1679 curwin->w_cursor.lnum = lo;
1680 check_cursor();
1681 }
1682 else
1683 check_cursor_col();
1684 changed_cline_bef_curs();
1685 }
1686 invalidate_botline();
1687}
1688
Bram Moolenaar19e60942011-06-19 00:27:51 +02001689/*
1690 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001691 * in Vim format (1-based). The replacement line is given as
1692 * a Python string object. The object is checked for validity
1693 * and correct format. Errors are returned as a value of FAIL.
1694 * The return value is OK on success.
1695 * If OK is returned and len_change is not NULL, *len_change
1696 * is set to the change in the buffer length.
1697 */
1698 static int
1699SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
1700{
1701 /* First of all, we check the thpe of the supplied Python object.
1702 * There are three cases:
1703 * 1. NULL, or None - this is a deletion.
1704 * 2. A string - this is a replacement.
1705 * 3. Anything else - this is an error.
1706 */
1707 if (line == Py_None || line == NULL)
1708 {
1709 buf_T *savebuf = curbuf;
1710
1711 PyErr_Clear();
1712 curbuf = buf;
1713
1714 if (u_savedel((linenr_T)n, 1L) == FAIL)
1715 PyErr_SetVim(_("cannot save undo information"));
1716 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
1717 PyErr_SetVim(_("cannot delete line"));
1718 else
1719 {
1720 if (buf == curwin->w_buffer)
1721 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
1722 deleted_lines_mark((linenr_T)n, 1L);
1723 }
1724
1725 curbuf = savebuf;
1726
1727 if (PyErr_Occurred() || VimErrorCheck())
1728 return FAIL;
1729
1730 if (len_change)
1731 *len_change = -1;
1732
1733 return OK;
1734 }
1735 else if (PyString_Check(line))
1736 {
1737 char *save = StringToLine(line);
1738 buf_T *savebuf = curbuf;
1739
1740 if (save == NULL)
1741 return FAIL;
1742
1743 /* We do not need to free "save" if ml_replace() consumes it. */
1744 PyErr_Clear();
1745 curbuf = buf;
1746
1747 if (u_savesub((linenr_T)n) == FAIL)
1748 {
1749 PyErr_SetVim(_("cannot save undo information"));
1750 vim_free(save);
1751 }
1752 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
1753 {
1754 PyErr_SetVim(_("cannot replace line"));
1755 vim_free(save);
1756 }
1757 else
1758 changed_bytes((linenr_T)n, 0);
1759
1760 curbuf = savebuf;
1761
1762 /* Check that the cursor is not beyond the end of the line now. */
1763 if (buf == curwin->w_buffer)
1764 check_cursor_col();
1765
1766 if (PyErr_Occurred() || VimErrorCheck())
1767 return FAIL;
1768
1769 if (len_change)
1770 *len_change = 0;
1771
1772 return OK;
1773 }
1774 else
1775 {
1776 PyErr_BadArgument();
1777 return FAIL;
1778 }
1779}
1780
Bram Moolenaar19e60942011-06-19 00:27:51 +02001781/* Replace a range of lines in the specified buffer. The line numbers are in
1782 * Vim format (1-based). The range is from lo up to, but not including, hi.
1783 * The replacement lines are given as a Python list of string objects. The
1784 * list is checked for validity and correct format. Errors are returned as a
1785 * value of FAIL. The return value is OK on success.
1786 * If OK is returned and len_change is not NULL, *len_change
1787 * is set to the change in the buffer length.
1788 */
1789 static int
1790SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
1791{
1792 /* First of all, we check the thpe of the supplied Python object.
1793 * There are three cases:
1794 * 1. NULL, or None - this is a deletion.
1795 * 2. A list - this is a replacement.
1796 * 3. Anything else - this is an error.
1797 */
1798 if (list == Py_None || list == NULL)
1799 {
1800 PyInt i;
1801 PyInt n = (int)(hi - lo);
1802 buf_T *savebuf = curbuf;
1803
1804 PyErr_Clear();
1805 curbuf = buf;
1806
1807 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
1808 PyErr_SetVim(_("cannot save undo information"));
1809 else
1810 {
1811 for (i = 0; i < n; ++i)
1812 {
1813 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1814 {
1815 PyErr_SetVim(_("cannot delete line"));
1816 break;
1817 }
1818 }
1819 if (buf == curwin->w_buffer)
1820 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
1821 deleted_lines_mark((linenr_T)lo, (long)i);
1822 }
1823
1824 curbuf = savebuf;
1825
1826 if (PyErr_Occurred() || VimErrorCheck())
1827 return FAIL;
1828
1829 if (len_change)
1830 *len_change = -n;
1831
1832 return OK;
1833 }
1834 else if (PyList_Check(list))
1835 {
1836 PyInt i;
1837 PyInt new_len = PyList_Size(list);
1838 PyInt old_len = hi - lo;
1839 PyInt extra = 0; /* lines added to text, can be negative */
1840 char **array;
1841 buf_T *savebuf;
1842
1843 if (new_len == 0) /* avoid allocating zero bytes */
1844 array = NULL;
1845 else
1846 {
1847 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
1848 if (array == NULL)
1849 {
1850 PyErr_NoMemory();
1851 return FAIL;
1852 }
1853 }
1854
1855 for (i = 0; i < new_len; ++i)
1856 {
1857 PyObject *line = PyList_GetItem(list, i);
1858
1859 array[i] = StringToLine(line);
1860 if (array[i] == NULL)
1861 {
1862 while (i)
1863 vim_free(array[--i]);
1864 vim_free(array);
1865 return FAIL;
1866 }
1867 }
1868
1869 savebuf = curbuf;
1870
1871 PyErr_Clear();
1872 curbuf = buf;
1873
1874 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
1875 PyErr_SetVim(_("cannot save undo information"));
1876
1877 /* If the size of the range is reducing (ie, new_len < old_len) we
1878 * need to delete some old_len. We do this at the start, by
1879 * repeatedly deleting line "lo".
1880 */
1881 if (!PyErr_Occurred())
1882 {
1883 for (i = 0; i < old_len - new_len; ++i)
1884 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1885 {
1886 PyErr_SetVim(_("cannot delete line"));
1887 break;
1888 }
1889 extra -= i;
1890 }
1891
1892 /* For as long as possible, replace the existing old_len with the
1893 * new old_len. This is a more efficient operation, as it requires
1894 * less memory allocation and freeing.
1895 */
1896 if (!PyErr_Occurred())
1897 {
1898 for (i = 0; i < old_len && i < new_len; ++i)
1899 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
1900 == FAIL)
1901 {
1902 PyErr_SetVim(_("cannot replace line"));
1903 break;
1904 }
1905 }
1906 else
1907 i = 0;
1908
1909 /* Now we may need to insert the remaining new old_len. If we do, we
1910 * must free the strings as we finish with them (we can't pass the
1911 * responsibility to vim in this case).
1912 */
1913 if (!PyErr_Occurred())
1914 {
1915 while (i < new_len)
1916 {
1917 if (ml_append((linenr_T)(lo + i - 1),
1918 (char_u *)array[i], 0, FALSE) == FAIL)
1919 {
1920 PyErr_SetVim(_("cannot insert line"));
1921 break;
1922 }
1923 vim_free(array[i]);
1924 ++i;
1925 ++extra;
1926 }
1927 }
1928
1929 /* Free any left-over old_len, as a result of an error */
1930 while (i < new_len)
1931 {
1932 vim_free(array[i]);
1933 ++i;
1934 }
1935
1936 /* Free the array of old_len. All of its contents have now
1937 * been dealt with (either freed, or the responsibility passed
1938 * to vim.
1939 */
1940 vim_free(array);
1941
1942 /* Adjust marks. Invalidate any which lie in the
1943 * changed range, and move any in the remainder of the buffer.
1944 */
1945 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
1946 (long)MAXLNUM, (long)extra);
1947 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
1948
1949 if (buf == curwin->w_buffer)
1950 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
1951
1952 curbuf = savebuf;
1953
1954 if (PyErr_Occurred() || VimErrorCheck())
1955 return FAIL;
1956
1957 if (len_change)
1958 *len_change = new_len - old_len;
1959
1960 return OK;
1961 }
1962 else
1963 {
1964 PyErr_BadArgument();
1965 return FAIL;
1966 }
1967}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001968
1969/* Insert a number of lines into the specified buffer after the specifed line.
1970 * The line number is in Vim format (1-based). The lines to be inserted are
1971 * given as a Python list of string objects or as a single string. The lines
1972 * to be added are checked for validity and correct format. Errors are
1973 * returned as a value of FAIL. The return value is OK on success.
1974 * If OK is returned and len_change is not NULL, *len_change
1975 * is set to the change in the buffer length.
1976 */
1977 static int
1978InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
1979{
1980 /* First of all, we check the type of the supplied Python object.
1981 * It must be a string or a list, or the call is in error.
1982 */
1983 if (PyString_Check(lines))
1984 {
1985 char *str = StringToLine(lines);
1986 buf_T *savebuf;
1987
1988 if (str == NULL)
1989 return FAIL;
1990
1991 savebuf = curbuf;
1992
1993 PyErr_Clear();
1994 curbuf = buf;
1995
1996 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
1997 PyErr_SetVim(_("cannot save undo information"));
1998 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
1999 PyErr_SetVim(_("cannot insert line"));
2000 else
2001 appended_lines_mark((linenr_T)n, 1L);
2002
2003 vim_free(str);
2004 curbuf = savebuf;
2005 update_screen(VALID);
2006
2007 if (PyErr_Occurred() || VimErrorCheck())
2008 return FAIL;
2009
2010 if (len_change)
2011 *len_change = 1;
2012
2013 return OK;
2014 }
2015 else if (PyList_Check(lines))
2016 {
2017 PyInt i;
2018 PyInt size = PyList_Size(lines);
2019 char **array;
2020 buf_T *savebuf;
2021
2022 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2023 if (array == NULL)
2024 {
2025 PyErr_NoMemory();
2026 return FAIL;
2027 }
2028
2029 for (i = 0; i < size; ++i)
2030 {
2031 PyObject *line = PyList_GetItem(lines, i);
2032 array[i] = StringToLine(line);
2033
2034 if (array[i] == NULL)
2035 {
2036 while (i)
2037 vim_free(array[--i]);
2038 vim_free(array);
2039 return FAIL;
2040 }
2041 }
2042
2043 savebuf = curbuf;
2044
2045 PyErr_Clear();
2046 curbuf = buf;
2047
2048 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2049 PyErr_SetVim(_("cannot save undo information"));
2050 else
2051 {
2052 for (i = 0; i < size; ++i)
2053 {
2054 if (ml_append((linenr_T)(n + i),
2055 (char_u *)array[i], 0, FALSE) == FAIL)
2056 {
2057 PyErr_SetVim(_("cannot insert line"));
2058
2059 /* Free the rest of the lines */
2060 while (i < size)
2061 vim_free(array[i++]);
2062
2063 break;
2064 }
2065 vim_free(array[i]);
2066 }
2067 if (i > 0)
2068 appended_lines_mark((linenr_T)n, (long)i);
2069 }
2070
2071 /* Free the array of lines. All of its contents have now
2072 * been freed.
2073 */
2074 vim_free(array);
2075
2076 curbuf = savebuf;
2077 update_screen(VALID);
2078
2079 if (PyErr_Occurred() || VimErrorCheck())
2080 return FAIL;
2081
2082 if (len_change)
2083 *len_change = size;
2084
2085 return OK;
2086 }
2087 else
2088 {
2089 PyErr_BadArgument();
2090 return FAIL;
2091 }
2092}
2093
2094/*
2095 * Common routines for buffers and line ranges
2096 * -------------------------------------------
2097 */
2098
2099 static int
2100CheckBuffer(BufferObject *this)
2101{
2102 if (this->buf == INVALID_BUFFER_VALUE)
2103 {
2104 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2105 return -1;
2106 }
2107
2108 return 0;
2109}
2110
2111 static PyObject *
2112RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2113{
2114 if (CheckBuffer(self))
2115 return NULL;
2116
2117 if (n < 0 || n > end - start)
2118 {
2119 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2120 return NULL;
2121 }
2122
2123 return GetBufferLine(self->buf, n+start);
2124}
2125
2126 static PyObject *
2127RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2128{
2129 PyInt size;
2130
2131 if (CheckBuffer(self))
2132 return NULL;
2133
2134 size = end - start + 1;
2135
2136 if (lo < 0)
2137 lo = 0;
2138 else if (lo > size)
2139 lo = size;
2140 if (hi < 0)
2141 hi = 0;
2142 if (hi < lo)
2143 hi = lo;
2144 else if (hi > size)
2145 hi = size;
2146
2147 return GetBufferLineList(self->buf, lo+start, hi+start);
2148}
2149
2150 static PyInt
2151RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2152{
2153 PyInt len_change;
2154
2155 if (CheckBuffer(self))
2156 return -1;
2157
2158 if (n < 0 || n > end - start)
2159 {
2160 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2161 return -1;
2162 }
2163
2164 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2165 return -1;
2166
2167 if (new_end)
2168 *new_end = end + len_change;
2169
2170 return 0;
2171}
2172
Bram Moolenaar19e60942011-06-19 00:27:51 +02002173 static PyInt
2174RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2175{
2176 PyInt size;
2177 PyInt len_change;
2178
2179 /* Self must be a valid buffer */
2180 if (CheckBuffer(self))
2181 return -1;
2182
2183 /* Sort out the slice range */
2184 size = end - start + 1;
2185
2186 if (lo < 0)
2187 lo = 0;
2188 else if (lo > size)
2189 lo = size;
2190 if (hi < 0)
2191 hi = 0;
2192 if (hi < lo)
2193 hi = lo;
2194 else if (hi > size)
2195 hi = size;
2196
2197 if (SetBufferLineList(self->buf, lo + start, hi + start,
2198 val, &len_change) == FAIL)
2199 return -1;
2200
2201 if (new_end)
2202 *new_end = end + len_change;
2203
2204 return 0;
2205}
2206
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002207
2208 static PyObject *
2209RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2210{
2211 PyObject *lines;
2212 PyInt len_change;
2213 PyInt max;
2214 PyInt n;
2215
2216 if (CheckBuffer(self))
2217 return NULL;
2218
2219 max = n = end - start + 1;
2220
2221 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2222 return NULL;
2223
2224 if (n < 0 || n > max)
2225 {
2226 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2227 return NULL;
2228 }
2229
2230 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2231 return NULL;
2232
2233 if (new_end)
2234 *new_end = end + len_change;
2235
2236 Py_INCREF(Py_None);
2237 return Py_None;
2238}
2239
2240
2241/* Buffer object - Definitions
2242 */
2243
2244typedef struct
2245{
2246 PyObject_HEAD
2247 BufferObject *buf;
2248 PyInt start;
2249 PyInt end;
2250} RangeObject;
2251
2252 static PyObject *
2253RangeNew(buf_T *buf, PyInt start, PyInt end)
2254{
2255 BufferObject *bufr;
2256 RangeObject *self;
2257 self = PyObject_NEW(RangeObject, &RangeType);
2258 if (self == NULL)
2259 return NULL;
2260
2261 bufr = (BufferObject *)BufferNew(buf);
2262 if (bufr == NULL)
2263 {
2264 Py_DECREF(self);
2265 return NULL;
2266 }
2267 Py_INCREF(bufr);
2268
2269 self->buf = bufr;
2270 self->start = start;
2271 self->end = end;
2272
2273 return (PyObject *)(self);
2274}
2275
2276 static PyObject *
2277BufferAppend(PyObject *self, PyObject *args)
2278{
2279 return RBAppend((BufferObject *)(self), args, 1,
2280 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2281 NULL);
2282}
2283
2284 static PyObject *
2285BufferMark(PyObject *self, PyObject *args)
2286{
2287 pos_T *posp;
2288 char *pmark;
2289 char mark;
2290 buf_T *curbuf_save;
2291
2292 if (CheckBuffer((BufferObject *)(self)))
2293 return NULL;
2294
2295 if (!PyArg_ParseTuple(args, "s", &pmark))
2296 return NULL;
2297 mark = *pmark;
2298
2299 curbuf_save = curbuf;
2300 curbuf = ((BufferObject *)(self))->buf;
2301 posp = getmark(mark, FALSE);
2302 curbuf = curbuf_save;
2303
2304 if (posp == NULL)
2305 {
2306 PyErr_SetVim(_("invalid mark name"));
2307 return NULL;
2308 }
2309
2310 /* Ckeck for keyboard interrupt */
2311 if (VimErrorCheck())
2312 return NULL;
2313
2314 if (posp->lnum <= 0)
2315 {
2316 /* Or raise an error? */
2317 Py_INCREF(Py_None);
2318 return Py_None;
2319 }
2320
2321 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2322}
2323
2324 static PyObject *
2325BufferRange(PyObject *self, PyObject *args)
2326{
2327 PyInt start;
2328 PyInt end;
2329
2330 if (CheckBuffer((BufferObject *)(self)))
2331 return NULL;
2332
2333 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2334 return NULL;
2335
2336 return RangeNew(((BufferObject *)(self))->buf, start, end);
2337}
2338
2339static struct PyMethodDef BufferMethods[] = {
2340 /* name, function, calling, documentation */
2341 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2342 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2343 {"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 +01002344#if PY_VERSION_HEX >= 0x03000000
2345 {"__dir__", BufferDir, 4, "List its attributes" },
2346#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002347 { NULL, NULL, 0, NULL }
2348};
2349
2350 static PyObject *
2351RangeAppend(PyObject *self, PyObject *args)
2352{
2353 return RBAppend(((RangeObject *)(self))->buf, args,
2354 ((RangeObject *)(self))->start,
2355 ((RangeObject *)(self))->end,
2356 &((RangeObject *)(self))->end);
2357}
2358
2359 static PyInt
2360RangeLength(PyObject *self)
2361{
2362 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2363 if (CheckBuffer(((RangeObject *)(self))->buf))
2364 return -1; /* ??? */
2365
2366 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2367}
2368
2369 static PyObject *
2370RangeItem(PyObject *self, PyInt n)
2371{
2372 return RBItem(((RangeObject *)(self))->buf, n,
2373 ((RangeObject *)(self))->start,
2374 ((RangeObject *)(self))->end);
2375}
2376
2377 static PyObject *
2378RangeRepr(PyObject *self)
2379{
2380 static char repr[100];
2381 RangeObject *this = (RangeObject *)(self);
2382
2383 if (this->buf->buf == INVALID_BUFFER_VALUE)
2384 {
2385 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2386 (self));
2387 return PyString_FromString(repr);
2388 }
2389 else
2390 {
2391 char *name = (char *)this->buf->buf->b_fname;
2392 int len;
2393
2394 if (name == NULL)
2395 name = "";
2396 len = (int)strlen(name);
2397
2398 if (len > 45)
2399 name = name + (45 - len);
2400
2401 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2402 len > 45 ? "..." : "", name,
2403 this->start, this->end);
2404
2405 return PyString_FromString(repr);
2406 }
2407}
2408
2409 static PyObject *
2410RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2411{
2412 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2413 ((RangeObject *)(self))->start,
2414 ((RangeObject *)(self))->end);
2415}
2416
2417/*
2418 * Line range object - Definitions
2419 */
2420
2421static struct PyMethodDef RangeMethods[] = {
2422 /* name, function, calling, documentation */
2423 {"append", RangeAppend, 1, "Append data to the Vim range" },
2424 { NULL, NULL, 0, NULL }
2425};
2426
Bram Moolenaardb913952012-06-29 12:54:53 +02002427 static void
2428set_ref_in_py(const int copyID)
2429{
2430 pylinkedlist_T *cur;
2431 dict_T *dd;
2432 list_T *ll;
2433
2434 if (lastdict != NULL)
2435 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
2436 {
2437 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
2438 if (dd->dv_copyID != copyID)
2439 {
2440 dd->dv_copyID = copyID;
2441 set_ref_in_ht(&dd->dv_hashtab, copyID);
2442 }
2443 }
2444
2445 if (lastlist != NULL)
2446 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
2447 {
2448 ll = ((ListObject *) (cur->pll_obj))->list;
2449 if (ll->lv_copyID != copyID)
2450 {
2451 ll->lv_copyID = copyID;
2452 set_ref_in_list(ll, copyID);
2453 }
2454 }
2455}
2456
2457 static int
2458set_string_copy(char_u *str, typval_T *tv)
2459{
2460 tv->vval.v_string = vim_strsave(str);
2461 if (tv->vval.v_string == NULL)
2462 {
2463 PyErr_NoMemory();
2464 return -1;
2465 }
2466 return 0;
2467}
2468
2469#ifdef FEAT_EVAL
2470typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
2471
2472 static int
2473convert_dl(PyObject *obj, typval_T *tv,
2474 pytotvfunc py_to_tv, PyObject *lookupDict)
2475{
2476 PyObject *capsule;
2477 char hexBuf[sizeof(void *) * 2 + 3];
2478
2479 sprintf(hexBuf, "%p", obj);
2480
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002481# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002482 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002483# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002484 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002485# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02002486 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02002487 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002488# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002489 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02002490# else
2491 capsule = PyCObject_FromVoidPtr(tv, NULL);
2492# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002493 PyDict_SetItemString(lookupDict, hexBuf, capsule);
2494 Py_DECREF(capsule);
2495 if (py_to_tv(obj, tv, lookupDict) == -1)
2496 {
2497 tv->v_type = VAR_UNKNOWN;
2498 return -1;
2499 }
2500 /* As we are not using copy_tv which increments reference count we must
2501 * do it ourself. */
2502 switch(tv->v_type)
2503 {
2504 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
2505 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
2506 }
2507 }
2508 else
2509 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002510 typval_T *v;
2511
2512# ifdef PY_USE_CAPSULE
2513 v = PyCapsule_GetPointer(capsule, NULL);
2514# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002515 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002516# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002517 copy_tv(v, tv);
2518 }
2519 return 0;
2520}
2521
2522 static int
2523ConvertFromPyObject(PyObject *obj, typval_T *tv)
2524{
2525 PyObject *lookup_dict;
2526 int r;
2527
2528 lookup_dict = PyDict_New();
2529 r = _ConvertFromPyObject(obj, tv, lookup_dict);
2530 Py_DECREF(lookup_dict);
2531 return r;
2532}
2533
2534 static int
2535_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2536{
2537 if (obj->ob_type == &DictionaryType)
2538 {
2539 tv->v_type = VAR_DICT;
2540 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
2541 ++tv->vval.v_dict->dv_refcount;
2542 }
2543 else if (obj->ob_type == &ListType)
2544 {
2545 tv->v_type = VAR_LIST;
2546 tv->vval.v_list = (((ListObject *)(obj))->list);
2547 ++tv->vval.v_list->lv_refcount;
2548 }
2549 else if (obj->ob_type == &FunctionType)
2550 {
2551 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
2552 return -1;
2553
2554 tv->v_type = VAR_FUNC;
2555 func_ref(tv->vval.v_string);
2556 }
2557#if PY_MAJOR_VERSION >= 3
2558 else if (PyBytes_Check(obj))
2559 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002560 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02002561
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002562 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
2563 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002564 if (result == NULL)
2565 return -1;
2566
2567 if (set_string_copy(result, tv) == -1)
2568 return -1;
2569
2570 tv->v_type = VAR_STRING;
2571 }
2572 else if (PyUnicode_Check(obj))
2573 {
2574 PyObject *bytes;
2575 char_u *result;
2576
2577 bytes = PyString_AsBytes(obj);
2578 if (bytes == NULL)
2579 return -1;
2580
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002581 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
2582 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002583 if (result == NULL)
2584 return -1;
2585
2586 if (set_string_copy(result, tv) == -1)
2587 {
2588 Py_XDECREF(bytes);
2589 return -1;
2590 }
2591 Py_XDECREF(bytes);
2592
2593 tv->v_type = VAR_STRING;
2594 }
2595#else
2596 else if (PyUnicode_Check(obj))
2597 {
2598 PyObject *bytes;
2599 char_u *result;
2600
2601 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
2602 if (bytes == NULL)
2603 return -1;
2604
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002605 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
2606 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002607 if (result == NULL)
2608 return -1;
2609
2610 if (set_string_copy(result, tv) == -1)
2611 {
2612 Py_XDECREF(bytes);
2613 return -1;
2614 }
2615 Py_XDECREF(bytes);
2616
2617 tv->v_type = VAR_STRING;
2618 }
2619 else if (PyString_Check(obj))
2620 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002621 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02002622
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02002623 if(PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
2624 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02002625 if (result == NULL)
2626 return -1;
2627
2628 if (set_string_copy(result, tv) == -1)
2629 return -1;
2630
2631 tv->v_type = VAR_STRING;
2632 }
2633 else if (PyInt_Check(obj))
2634 {
2635 tv->v_type = VAR_NUMBER;
2636 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
2637 }
2638#endif
2639 else if (PyLong_Check(obj))
2640 {
2641 tv->v_type = VAR_NUMBER;
2642 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
2643 }
2644 else if (PyDict_Check(obj))
2645 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
2646#ifdef FEAT_FLOAT
2647 else if (PyFloat_Check(obj))
2648 {
2649 tv->v_type = VAR_FLOAT;
2650 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
2651 }
2652#endif
2653 else if (PyIter_Check(obj))
2654 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
2655 else if (PySequence_Check(obj))
2656 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
2657 else if (PyMapping_Check(obj))
2658 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
2659 else
2660 {
2661 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
2662 return -1;
2663 }
2664 return 0;
2665}
2666
2667 static PyObject *
2668ConvertToPyObject(typval_T *tv)
2669{
2670 if (tv == NULL)
2671 {
2672 PyErr_SetVim(_("NULL reference passed"));
2673 return NULL;
2674 }
2675 switch (tv->v_type)
2676 {
2677 case VAR_STRING:
2678 return PyBytes_FromString((char *) tv->vval.v_string);
2679 case VAR_NUMBER:
2680 return PyLong_FromLong((long) tv->vval.v_number);
2681#ifdef FEAT_FLOAT
2682 case VAR_FLOAT:
2683 return PyFloat_FromDouble((double) tv->vval.v_float);
2684#endif
2685 case VAR_LIST:
2686 return ListNew(tv->vval.v_list);
2687 case VAR_DICT:
2688 return DictionaryNew(tv->vval.v_dict);
2689 case VAR_FUNC:
2690 return FunctionNew(tv->vval.v_string);
2691 case VAR_UNKNOWN:
2692 Py_INCREF(Py_None);
2693 return Py_None;
2694 default:
2695 PyErr_SetVim(_("internal error: invalid value type"));
2696 return NULL;
2697 }
2698}
2699#endif