blob: 931ecb98a78ffc1f730bea327d389911cacc9230 [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
74 static PyObject *
75OutputWrite(PyObject *self, PyObject *args)
76{
Bram Moolenaarac0ddc12012-09-05 17:28:21 +020077 Py_ssize_t len;
Bram Moolenaar19e60942011-06-19 00:27:51 +020078 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020079 int error = ((OutputObject *)(self))->error;
80
Bram Moolenaar27564802011-09-07 19:30:21 +020081 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020082 return NULL;
83
84 Py_BEGIN_ALLOW_THREADS
85 Python_Lock_Vim();
86 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
87 Python_Release_Vim();
88 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +020089 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020090
91 Py_INCREF(Py_None);
92 return Py_None;
93}
94
95 static PyObject *
96OutputWritelines(PyObject *self, PyObject *args)
97{
98 PyInt n;
99 PyInt i;
100 PyObject *list;
101 int error = ((OutputObject *)(self))->error;
102
103 if (!PyArg_ParseTuple(args, "O", &list))
104 return NULL;
105 Py_INCREF(list);
106
Bram Moolenaardb913952012-06-29 12:54:53 +0200107 if (!PyList_Check(list))
108 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200109 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
110 Py_DECREF(list);
111 return NULL;
112 }
113
114 n = PyList_Size(list);
115
116 for (i = 0; i < n; ++i)
117 {
118 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200119 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200120 PyInt len;
121
Bram Moolenaardb913952012-06-29 12:54:53 +0200122 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
123 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200124 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
125 Py_DECREF(list);
126 return NULL;
127 }
128
129 Py_BEGIN_ALLOW_THREADS
130 Python_Lock_Vim();
131 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
132 Python_Release_Vim();
133 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200134 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200135 }
136
137 Py_DECREF(list);
138 Py_INCREF(Py_None);
139 return Py_None;
140}
141
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100142 static PyObject *
143OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
144{
145 /* do nothing */
146 Py_INCREF(Py_None);
147 return Py_None;
148}
149
150
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200151/* Buffer IO, we write one whole line at a time. */
152static garray_T io_ga = {0, 0, 1, 80, NULL};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200153static writefn old_fn = NULL;
154
155 static void
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200156PythonIO_Flush(void)
157{
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200158 if (old_fn != NULL && io_ga.ga_len > 0)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200159 {
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200160 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
161 old_fn((char_u *)io_ga.ga_data);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200162 }
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200163 io_ga.ga_len = 0;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200164}
165
166 static void
167writer(writefn fn, char_u *str, PyInt n)
168{
169 char_u *ptr;
170
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200171 /* Flush when switching output function. */
172 if (fn != old_fn)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200173 PythonIO_Flush();
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200174 old_fn = fn;
175
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200176 /* Write each NL separated line. Text after the last NL is kept for
177 * writing later. */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200178 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
179 {
180 PyInt len = ptr - str;
181
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200182 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200183 break;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200184
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200185 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
186 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
187 fn((char_u *)io_ga.ga_data);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200188 str = ptr + 1;
189 n -= len + 1;
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200190 io_ga.ga_len = 0;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200191 }
192
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200193 /* Put the remaining text into io_ga for later printing. */
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200194 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200195 {
196 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200197 io_ga.ga_len += (int)n;
Bram Moolenaar2eea1982010-09-21 16:49:37 +0200198 }
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200199}
200
201/***************/
202
203static PyTypeObject OutputType;
204
205static OutputObject Output =
206{
207 PyObject_HEAD_INIT(&OutputType)
208 0,
209 0
210};
211
212static OutputObject Error =
213{
214 PyObject_HEAD_INIT(&OutputType)
215 0,
216 1
217};
218
219 static int
220PythonIO_Init_io(void)
221{
222 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
223 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
224
225 if (PyErr_Occurred())
226 {
227 EMSG(_("E264: Python: Error initialising I/O objects"));
228 return -1;
229 }
230
231 return 0;
232}
233
234
235static PyObject *VimError;
236
237/* Check to see whether a Vim error has been reported, or a keyboard
238 * interrupt has been detected.
239 */
240 static int
241VimErrorCheck(void)
242{
243 if (got_int)
244 {
245 PyErr_SetNone(PyExc_KeyboardInterrupt);
246 return 1;
247 }
248 else if (did_emsg && !PyErr_Occurred())
249 {
250 PyErr_SetNone(VimError);
251 return 1;
252 }
253
254 return 0;
255}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200256
257/* Vim module - Implementation
258 */
259 static PyObject *
260VimCommand(PyObject *self UNUSED, PyObject *args)
261{
262 char *cmd;
263 PyObject *result;
264
265 if (!PyArg_ParseTuple(args, "s", &cmd))
266 return NULL;
267
268 PyErr_Clear();
269
270 Py_BEGIN_ALLOW_THREADS
271 Python_Lock_Vim();
272
273 do_cmdline_cmd((char_u *)cmd);
274 update_screen(VALID);
275
276 Python_Release_Vim();
277 Py_END_ALLOW_THREADS
278
279 if (VimErrorCheck())
280 result = NULL;
281 else
282 result = Py_None;
283
284 Py_XINCREF(result);
285 return result;
286}
287
288#ifdef FEAT_EVAL
289/*
290 * Function to translate a typval_T into a PyObject; this will recursively
291 * translate lists/dictionaries into their Python equivalents.
292 *
293 * The depth parameter is to avoid infinite recursion, set it to 1 when
294 * you call VimToPython.
295 */
296 static PyObject *
297VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
298{
299 PyObject *result;
300 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200301 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200302
303 /* Avoid infinite recursion */
304 if (depth > 100)
305 {
306 Py_INCREF(Py_None);
307 result = Py_None;
308 return result;
309 }
310
311 /* Check if we run into a recursive loop. The item must be in lookupDict
312 * then and we can use it again. */
313 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
314 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
315 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200316 sprintf(ptrBuf, "%p",
317 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
318 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200319 result = PyDict_GetItemString(lookupDict, ptrBuf);
320 if (result != NULL)
321 {
322 Py_INCREF(result);
323 return result;
324 }
325 }
326
327 if (our_tv->v_type == VAR_STRING)
328 {
329 result = Py_BuildValue("s", our_tv->vval.v_string);
330 }
331 else if (our_tv->v_type == VAR_NUMBER)
332 {
333 char buf[NUMBUFLEN];
334
335 /* For backwards compatibility numbers are stored as strings. */
336 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
337 result = Py_BuildValue("s", buf);
338 }
339# ifdef FEAT_FLOAT
340 else if (our_tv->v_type == VAR_FLOAT)
341 {
342 char buf[NUMBUFLEN];
343
344 sprintf(buf, "%f", our_tv->vval.v_float);
345 result = Py_BuildValue("s", buf);
346 }
347# endif
348 else if (our_tv->v_type == VAR_LIST)
349 {
350 list_T *list = our_tv->vval.v_list;
351 listitem_T *curr;
352
353 result = PyList_New(0);
354
355 if (list != NULL)
356 {
357 PyDict_SetItemString(lookupDict, ptrBuf, result);
358
359 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
360 {
361 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
362 PyList_Append(result, newObj);
363 Py_DECREF(newObj);
364 }
365 }
366 }
367 else if (our_tv->v_type == VAR_DICT)
368 {
369 result = PyDict_New();
370
371 if (our_tv->vval.v_dict != NULL)
372 {
373 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
374 long_u todo = ht->ht_used;
375 hashitem_T *hi;
376 dictitem_T *di;
377
378 PyDict_SetItemString(lookupDict, ptrBuf, result);
379
380 for (hi = ht->ht_array; todo > 0; ++hi)
381 {
382 if (!HASHITEM_EMPTY(hi))
383 {
384 --todo;
385
386 di = dict_lookup(hi);
387 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
388 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
389 Py_DECREF(newObj);
390 }
391 }
392 }
393 }
394 else
395 {
396 Py_INCREF(Py_None);
397 result = Py_None;
398 }
399
400 return result;
401}
402#endif
403
404 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200405VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200406{
407#ifdef FEAT_EVAL
408 char *expr;
409 typval_T *our_tv;
410 PyObject *result;
411 PyObject *lookup_dict;
412
413 if (!PyArg_ParseTuple(args, "s", &expr))
414 return NULL;
415
416 Py_BEGIN_ALLOW_THREADS
417 Python_Lock_Vim();
418 our_tv = eval_expr((char_u *)expr, NULL);
419
420 Python_Release_Vim();
421 Py_END_ALLOW_THREADS
422
423 if (our_tv == NULL)
424 {
425 PyErr_SetVim(_("invalid expression"));
426 return NULL;
427 }
428
429 /* Convert the Vim type into a Python type. Create a dictionary that's
430 * used to check for recursive loops. */
431 lookup_dict = PyDict_New();
432 result = VimToPython(our_tv, 1, lookup_dict);
433 Py_DECREF(lookup_dict);
434
435
436 Py_BEGIN_ALLOW_THREADS
437 Python_Lock_Vim();
438 free_tv(our_tv);
439 Python_Release_Vim();
440 Py_END_ALLOW_THREADS
441
442 return result;
443#else
444 PyErr_SetVim(_("expressions disabled at compile time"));
445 return NULL;
446#endif
447}
448
Bram Moolenaardb913952012-06-29 12:54:53 +0200449static PyObject *ConvertToPyObject(typval_T *);
450
451 static PyObject *
452VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
453{
454#ifdef FEAT_EVAL
455 char *expr;
456 typval_T *our_tv;
457 PyObject *result;
458
459 if (!PyArg_ParseTuple(args, "s", &expr))
460 return NULL;
461
462 Py_BEGIN_ALLOW_THREADS
463 Python_Lock_Vim();
464 our_tv = eval_expr((char_u *)expr, NULL);
465
466 Python_Release_Vim();
467 Py_END_ALLOW_THREADS
468
469 if (our_tv == NULL)
470 {
471 PyErr_SetVim(_("invalid expression"));
472 return NULL;
473 }
474
475 result = ConvertToPyObject(our_tv);
476 Py_BEGIN_ALLOW_THREADS
477 Python_Lock_Vim();
478 free_tv(our_tv);
479 Python_Release_Vim();
480 Py_END_ALLOW_THREADS
481
482 return result;
483#else
484 PyErr_SetVim(_("expressions disabled at compile time"));
485 return NULL;
486#endif
487}
488
489 static PyObject *
490VimStrwidth(PyObject *self UNUSED, PyObject *args)
491{
492 char *expr;
493
494 if (!PyArg_ParseTuple(args, "s", &expr))
495 return NULL;
496
Bram Moolenaar3cd3e7a2012-06-29 17:52:02 +0200497 return PyLong_FromLong(mb_string2cells((char_u *)expr, (int)STRLEN(expr)));
Bram Moolenaardb913952012-06-29 12:54:53 +0200498}
499
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200500/*
501 * Vim module - Definitions
502 */
503
504static struct PyMethodDef VimMethods[] = {
505 /* name, function, calling, documentation */
506 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
507 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200508 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
509 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200510 { NULL, NULL, 0, NULL }
511};
512
513typedef struct
514{
515 PyObject_HEAD
516 buf_T *buf;
Bram Moolenaardb913952012-06-29 12:54:53 +0200517} BufferObject;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200518
519#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
520
521/*
522 * Buffer list object - Implementation
523 */
524
525 static PyInt
526BufListLength(PyObject *self UNUSED)
527{
528 buf_T *b = firstbuf;
529 PyInt n = 0;
530
531 while (b)
532 {
533 ++n;
534 b = b->b_next;
535 }
536
537 return n;
538}
539
540 static PyObject *
541BufListItem(PyObject *self UNUSED, PyInt n)
542{
543 buf_T *b;
544
545 for (b = firstbuf; b; b = b->b_next, --n)
546 {
547 if (n == 0)
548 return BufferNew(b);
549 }
550
551 PyErr_SetString(PyExc_IndexError, _("no such buffer"));
552 return NULL;
553}
554
555typedef struct
556{
557 PyObject_HEAD
558 win_T *win;
559} WindowObject;
560
Bram Moolenaardb913952012-06-29 12:54:53 +0200561static int ConvertFromPyObject(PyObject *, typval_T *);
562static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
563
564typedef struct pylinkedlist_S {
565 struct pylinkedlist_S *pll_next;
566 struct pylinkedlist_S *pll_prev;
567 PyObject *pll_obj;
568} pylinkedlist_T;
569
570static pylinkedlist_T *lastdict = NULL;
571static pylinkedlist_T *lastlist = NULL;
572
573 static void
574pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
575{
576 if (ref->pll_prev == NULL)
577 {
578 if (ref->pll_next == NULL)
579 {
580 *last = NULL;
581 return;
582 }
583 }
584 else
585 ref->pll_prev->pll_next = ref->pll_next;
586
587 if (ref->pll_next == NULL)
588 *last = ref->pll_prev;
589 else
590 ref->pll_next->pll_prev = ref->pll_prev;
591}
592
593 static void
594pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
595{
596 if (*last == NULL)
597 ref->pll_prev = NULL;
598 else
599 {
600 (*last)->pll_next = ref;
601 ref->pll_prev = *last;
602 }
603 ref->pll_next = NULL;
604 ref->pll_obj = self;
605 *last = ref;
606}
607
608static PyTypeObject DictionaryType;
609
610typedef struct
611{
612 PyObject_HEAD
613 dict_T *dict;
614 pylinkedlist_T ref;
615} DictionaryObject;
616
617 static PyObject *
618DictionaryNew(dict_T *dict)
619{
620 DictionaryObject *self;
621
622 self = PyObject_NEW(DictionaryObject, &DictionaryType);
623 if (self == NULL)
624 return NULL;
625 self->dict = dict;
626 ++dict->dv_refcount;
627
628 pyll_add((PyObject *)(self), &self->ref, &lastdict);
629
630 return (PyObject *)(self);
631}
632
633 static int
634pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
635{
636 dict_T *d;
637 char_u *key;
638 dictitem_T *di;
639 PyObject *keyObject;
640 PyObject *valObject;
641 Py_ssize_t iter = 0;
642
643 d = dict_alloc();
644 if (d == NULL)
645 {
646 PyErr_NoMemory();
647 return -1;
648 }
649
650 tv->v_type = VAR_DICT;
651 tv->vval.v_dict = d;
652
653 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
654 {
655 DICTKEY_DECL
656
657 if (keyObject == NULL)
658 return -1;
659 if (valObject == NULL)
660 return -1;
661
662 DICTKEY_GET(-1)
663
664 di = dictitem_alloc(key);
665
666 DICTKEY_UNREF
667
668 if (di == NULL)
669 {
670 PyErr_NoMemory();
671 return -1;
672 }
673 di->di_tv.v_lock = 0;
674
675 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
676 {
677 vim_free(di);
678 return -1;
679 }
680 if (dict_add(d, di) == FAIL)
681 {
682 vim_free(di);
683 PyErr_SetVim(_("failed to add key to dictionary"));
684 return -1;
685 }
686 }
687 return 0;
688}
689
690 static int
691pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
692{
693 dict_T *d;
694 char_u *key;
695 dictitem_T *di;
696 PyObject *list;
697 PyObject *litem;
698 PyObject *keyObject;
699 PyObject *valObject;
700 Py_ssize_t lsize;
701
702 d = dict_alloc();
703 if (d == NULL)
704 {
705 PyErr_NoMemory();
706 return -1;
707 }
708
709 tv->v_type = VAR_DICT;
710 tv->vval.v_dict = d;
711
712 list = PyMapping_Items(obj);
713 lsize = PyList_Size(list);
714 while (lsize--)
715 {
716 DICTKEY_DECL
717
718 litem = PyList_GetItem(list, lsize);
719 if (litem == NULL)
720 {
721 Py_DECREF(list);
722 return -1;
723 }
724
725 keyObject = PyTuple_GetItem(litem, 0);
726 if (keyObject == NULL)
727 {
728 Py_DECREF(list);
729 Py_DECREF(litem);
730 return -1;
731 }
732
733 DICTKEY_GET(-1)
734
735 valObject = PyTuple_GetItem(litem, 1);
736 if (valObject == NULL)
737 {
738 Py_DECREF(list);
739 Py_DECREF(litem);
740 return -1;
741 }
742
743 di = dictitem_alloc(key);
744
745 DICTKEY_UNREF
746
747 if (di == NULL)
748 {
749 Py_DECREF(list);
750 Py_DECREF(litem);
751 PyErr_NoMemory();
752 return -1;
753 }
754 di->di_tv.v_lock = 0;
755
756 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
757 {
758 vim_free(di);
759 Py_DECREF(list);
760 Py_DECREF(litem);
761 return -1;
762 }
763 if (dict_add(d, di) == FAIL)
764 {
765 vim_free(di);
766 Py_DECREF(list);
767 Py_DECREF(litem);
768 PyErr_SetVim(_("failed to add key to dictionary"));
769 return -1;
770 }
771 Py_DECREF(litem);
772 }
773 Py_DECREF(list);
774 return 0;
775}
776
777 static PyInt
778DictionaryLength(PyObject *self)
779{
780 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
781}
782
783 static PyObject *
784DictionaryItem(PyObject *self, PyObject *keyObject)
785{
786 char_u *key;
787 dictitem_T *val;
788 DICTKEY_DECL
789
790 DICTKEY_GET(NULL)
791
792 val = dict_find(((DictionaryObject *) (self))->dict, key, -1);
793
794 DICTKEY_UNREF
795
796 return ConvertToPyObject(&val->di_tv);
797}
798
799 static PyInt
800DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
801{
802 char_u *key;
803 typval_T tv;
804 dict_T *d = ((DictionaryObject *)(self))->dict;
805 dictitem_T *di;
806 DICTKEY_DECL
807
808 if (d->dv_lock)
809 {
810 PyErr_SetVim(_("dict is locked"));
811 return -1;
812 }
813
814 DICTKEY_GET(-1)
815
816 di = dict_find(d, key, -1);
817
818 if (valObject == NULL)
819 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200820 hashitem_T *hi;
821
Bram Moolenaardb913952012-06-29 12:54:53 +0200822 if (di == NULL)
823 {
824 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
825 return -1;
826 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200827 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200828 hash_remove(&d->dv_hashtab, hi);
829 dictitem_free(di);
830 return 0;
831 }
832
833 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200834 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200835
836 if (di == NULL)
837 {
838 di = dictitem_alloc(key);
839 if (di == NULL)
840 {
841 PyErr_NoMemory();
842 return -1;
843 }
844 di->di_tv.v_lock = 0;
845
846 if (dict_add(d, di) == FAIL)
847 {
848 vim_free(di);
849 PyErr_SetVim(_("failed to add key to dictionary"));
850 return -1;
851 }
852 }
853 else
854 clear_tv(&di->di_tv);
855
856 DICTKEY_UNREF
857
858 copy_tv(&tv, &di->di_tv);
859 return 0;
860}
861
862 static PyObject *
863DictionaryListKeys(PyObject *self)
864{
865 dict_T *dict = ((DictionaryObject *)(self))->dict;
866 long_u todo = dict->dv_hashtab.ht_used;
867 Py_ssize_t i = 0;
868 PyObject *r;
869 hashitem_T *hi;
870
871 r = PyList_New(todo);
872 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
873 {
874 if (!HASHITEM_EMPTY(hi))
875 {
876 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
877 --todo;
878 ++i;
879 }
880 }
881 return r;
882}
883
884static struct PyMethodDef DictionaryMethods[] = {
885 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
886 { NULL, NULL, 0, NULL }
887};
888
889static PyTypeObject ListType;
890
891typedef struct
892{
893 PyObject_HEAD
894 list_T *list;
895 pylinkedlist_T ref;
896} ListObject;
897
898 static PyObject *
899ListNew(list_T *list)
900{
901 ListObject *self;
902
903 self = PyObject_NEW(ListObject, &ListType);
904 if (self == NULL)
905 return NULL;
906 self->list = list;
907 ++list->lv_refcount;
908
909 pyll_add((PyObject *)(self), &self->ref, &lastlist);
910
911 return (PyObject *)(self);
912}
913
914 static int
915list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
916{
917 Py_ssize_t i;
918 Py_ssize_t lsize = PySequence_Size(obj);
919 PyObject *litem;
920 listitem_T *li;
921
922 for(i=0; i<lsize; i++)
923 {
924 li = listitem_alloc();
925 if (li == NULL)
926 {
927 PyErr_NoMemory();
928 return -1;
929 }
930 li->li_tv.v_lock = 0;
931
932 litem = PySequence_GetItem(obj, i);
933 if (litem == NULL)
934 return -1;
935 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
936 return -1;
937
938 list_append(l, li);
939 }
940 return 0;
941}
942
943 static int
944pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
945{
946 list_T *l;
947
948 l = list_alloc();
949 if (l == NULL)
950 {
951 PyErr_NoMemory();
952 return -1;
953 }
954
955 tv->v_type = VAR_LIST;
956 tv->vval.v_list = l;
957
958 if (list_py_concat(l, obj, lookupDict) == -1)
959 return -1;
960
961 return 0;
962}
963
964 static int
965pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
966{
967 PyObject *iterator = PyObject_GetIter(obj);
968 PyObject *item;
969 list_T *l;
970 listitem_T *li;
971
972 l = list_alloc();
973
974 if (l == NULL)
975 {
976 PyErr_NoMemory();
977 return -1;
978 }
979
980 tv->vval.v_list = l;
981 tv->v_type = VAR_LIST;
982
983
984 if (iterator == NULL)
985 return -1;
986
987 while ((item = PyIter_Next(obj)))
988 {
989 li = listitem_alloc();
990 if (li == NULL)
991 {
992 PyErr_NoMemory();
993 return -1;
994 }
995 li->li_tv.v_lock = 0;
996
997 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
998 return -1;
999
1000 list_append(l, li);
1001
1002 Py_DECREF(item);
1003 }
1004
1005 Py_DECREF(iterator);
1006 return 0;
1007}
1008
1009 static PyInt
1010ListLength(PyObject *self)
1011{
1012 return ((PyInt) (((ListObject *) (self))->list->lv_len));
1013}
1014
1015 static PyObject *
1016ListItem(PyObject *self, Py_ssize_t index)
1017{
1018 listitem_T *li;
1019
1020 if (index>=ListLength(self))
1021 {
1022 PyErr_SetString(PyExc_IndexError, "list index out of range");
1023 return NULL;
1024 }
1025 li = list_find(((ListObject *) (self))->list, (long) index);
1026 if (li == NULL)
1027 {
1028 PyErr_SetVim(_("internal error: failed to get vim list item"));
1029 return NULL;
1030 }
1031 return ConvertToPyObject(&li->li_tv);
1032}
1033
1034#define PROC_RANGE \
1035 if (last < 0) {\
1036 if (last < -size) \
1037 last = 0; \
1038 else \
1039 last += size; \
1040 } \
1041 if (first < 0) \
1042 first = 0; \
1043 if (first > size) \
1044 first = size; \
1045 if (last > size) \
1046 last = size;
1047
1048 static PyObject *
1049ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
1050{
1051 PyInt i;
1052 PyInt size = ListLength(self);
1053 PyInt n;
1054 PyObject *list;
1055 int reversed = 0;
1056
1057 PROC_RANGE
1058 if (first >= last)
1059 first = last;
1060
1061 n = last-first;
1062 list = PyList_New(n);
1063 if (list == NULL)
1064 return NULL;
1065
1066 for (i = 0; i < n; ++i)
1067 {
1068 PyObject *item = ListItem(self, i);
1069 if (item == NULL)
1070 {
1071 Py_DECREF(list);
1072 return NULL;
1073 }
1074
1075 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
1076 {
1077 Py_DECREF(item);
1078 Py_DECREF(list);
1079 return NULL;
1080 }
1081 }
1082
1083 return list;
1084}
1085
1086 static int
1087ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1088{
1089 typval_T tv;
1090 list_T *l = ((ListObject *) (self))->list;
1091 listitem_T *li;
1092 Py_ssize_t length = ListLength(self);
1093
1094 if (l->lv_lock)
1095 {
1096 PyErr_SetVim(_("list is locked"));
1097 return -1;
1098 }
1099 if (index>length || (index==length && obj==NULL))
1100 {
1101 PyErr_SetString(PyExc_IndexError, "list index out of range");
1102 return -1;
1103 }
1104
1105 if (obj == NULL)
1106 {
1107 li = list_find(l, (long) index);
1108 list_remove(l, li, li);
1109 clear_tv(&li->li_tv);
1110 vim_free(li);
1111 return 0;
1112 }
1113
1114 if (ConvertFromPyObject(obj, &tv) == -1)
1115 return -1;
1116
1117 if (index == length)
1118 {
1119 if (list_append_tv(l, &tv) == FAIL)
1120 {
1121 PyErr_SetVim(_("Failed to add item to list"));
1122 return -1;
1123 }
1124 }
1125 else
1126 {
1127 li = list_find(l, (long) index);
1128 clear_tv(&li->li_tv);
1129 copy_tv(&tv, &li->li_tv);
1130 }
1131 return 0;
1132}
1133
1134 static int
1135ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1136{
1137 PyInt size = ListLength(self);
1138 Py_ssize_t i;
1139 Py_ssize_t lsize;
1140 PyObject *litem;
1141 listitem_T *li;
1142 listitem_T *next;
1143 typval_T v;
1144 list_T *l = ((ListObject *) (self))->list;
1145
1146 if (l->lv_lock)
1147 {
1148 PyErr_SetVim(_("list is locked"));
1149 return -1;
1150 }
1151
1152 PROC_RANGE
1153
1154 if (first == size)
1155 li = NULL;
1156 else
1157 {
1158 li = list_find(l, (long) first);
1159 if (li == NULL)
1160 {
1161 PyErr_SetVim(_("internal error: no vim list item"));
1162 return -1;
1163 }
1164 if (last > first)
1165 {
1166 i = last - first;
1167 while (i-- && li != NULL)
1168 {
1169 next = li->li_next;
1170 listitem_remove(l, li);
1171 li = next;
1172 }
1173 }
1174 }
1175
1176 if (obj == NULL)
1177 return 0;
1178
1179 if (!PyList_Check(obj))
1180 {
1181 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1182 return -1;
1183 }
1184
1185 lsize = PyList_Size(obj);
1186
1187 for(i=0; i<lsize; i++)
1188 {
1189 litem = PyList_GetItem(obj, i);
1190 if (litem == NULL)
1191 return -1;
1192 if (ConvertFromPyObject(litem, &v) == -1)
1193 return -1;
1194 if (list_insert_tv(l, &v, li) == FAIL)
1195 {
1196 PyErr_SetVim(_("internal error: failed to add item to list"));
1197 return -1;
1198 }
1199 }
1200 return 0;
1201}
1202
1203 static PyObject *
1204ListConcatInPlace(PyObject *self, PyObject *obj)
1205{
1206 list_T *l = ((ListObject *) (self))->list;
1207 PyObject *lookup_dict;
1208
1209 if (l->lv_lock)
1210 {
1211 PyErr_SetVim(_("list is locked"));
1212 return NULL;
1213 }
1214
1215 if (!PySequence_Check(obj))
1216 {
1217 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1218 return NULL;
1219 }
1220
1221 lookup_dict = PyDict_New();
1222 if (list_py_concat(l, obj, lookup_dict) == -1)
1223 {
1224 Py_DECREF(lookup_dict);
1225 return NULL;
1226 }
1227 Py_DECREF(lookup_dict);
1228
1229 Py_INCREF(self);
1230 return self;
1231}
1232
1233static struct PyMethodDef ListMethods[] = {
1234 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1235 { NULL, NULL, 0, NULL }
1236};
1237
1238typedef struct
1239{
1240 PyObject_HEAD
1241 char_u *name;
1242} FunctionObject;
1243
1244static PyTypeObject FunctionType;
1245
1246 static PyObject *
1247FunctionNew(char_u *name)
1248{
1249 FunctionObject *self;
1250
1251 self = PyObject_NEW(FunctionObject, &FunctionType);
1252 if (self == NULL)
1253 return NULL;
1254 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1255 if (self->name == NULL)
1256 {
1257 PyErr_NoMemory();
1258 return NULL;
1259 }
1260 STRCPY(self->name, name);
1261 func_ref(name);
1262 return (PyObject *)(self);
1263}
1264
1265 static PyObject *
1266FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1267{
1268 FunctionObject *this = (FunctionObject *)(self);
1269 char_u *name = this->name;
1270 typval_T args;
1271 typval_T selfdicttv;
1272 typval_T rettv;
1273 dict_T *selfdict = NULL;
1274 PyObject *selfdictObject;
1275 PyObject *result;
1276 int error;
1277
1278 if (ConvertFromPyObject(argsObject, &args) == -1)
1279 return NULL;
1280
1281 if (kwargs != NULL)
1282 {
1283 selfdictObject = PyDict_GetItemString(kwargs, "self");
1284 if (selfdictObject != NULL)
1285 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001286 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001287 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001288 PyErr_SetString(PyExc_TypeError,
1289 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001290 clear_tv(&args);
1291 return NULL;
1292 }
1293 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1294 return NULL;
1295 selfdict = selfdicttv.vval.v_dict;
1296 }
1297 }
1298
1299 error = func_call(name, &args, selfdict, &rettv);
1300 if (error != OK)
1301 {
1302 result = NULL;
1303 PyErr_SetVim(_("failed to run function"));
1304 }
1305 else
1306 result = ConvertToPyObject(&rettv);
1307
1308 /* FIXME Check what should really be cleared. */
1309 clear_tv(&args);
1310 clear_tv(&rettv);
1311 /*
1312 * if (selfdict!=NULL)
1313 * clear_tv(selfdicttv);
1314 */
1315
1316 return result;
1317}
1318
1319static struct PyMethodDef FunctionMethods[] = {
1320 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1321 { NULL, NULL, 0, NULL }
1322};
1323
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001324#define INVALID_WINDOW_VALUE ((win_T *)(-1))
1325
1326 static int
1327CheckWindow(WindowObject *this)
1328{
1329 if (this->win == INVALID_WINDOW_VALUE)
1330 {
1331 PyErr_SetVim(_("attempt to refer to deleted window"));
1332 return -1;
1333 }
1334
1335 return 0;
1336}
1337
1338static int WindowSetattr(PyObject *, char *, PyObject *);
1339static PyObject *WindowRepr(PyObject *);
1340
1341 static int
1342WindowSetattr(PyObject *self, char *name, PyObject *val)
1343{
1344 WindowObject *this = (WindowObject *)(self);
1345
1346 if (CheckWindow(this))
1347 return -1;
1348
1349 if (strcmp(name, "buffer") == 0)
1350 {
1351 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1352 return -1;
1353 }
1354 else if (strcmp(name, "cursor") == 0)
1355 {
1356 long lnum;
1357 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001358
1359 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1360 return -1;
1361
1362 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1363 {
1364 PyErr_SetVim(_("cursor position outside buffer"));
1365 return -1;
1366 }
1367
1368 /* Check for keyboard interrupts */
1369 if (VimErrorCheck())
1370 return -1;
1371
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001372 this->win->w_cursor.lnum = lnum;
1373 this->win->w_cursor.col = col;
1374#ifdef FEAT_VIRTUALEDIT
1375 this->win->w_cursor.coladd = 0;
1376#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001377 /* When column is out of range silently correct it. */
1378 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001379
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001380 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001381 return 0;
1382 }
1383 else if (strcmp(name, "height") == 0)
1384 {
1385 int height;
1386 win_T *savewin;
1387
1388 if (!PyArg_Parse(val, "i", &height))
1389 return -1;
1390
1391#ifdef FEAT_GUI
1392 need_mouse_correct = TRUE;
1393#endif
1394 savewin = curwin;
1395 curwin = this->win;
1396 win_setheight(height);
1397 curwin = savewin;
1398
1399 /* Check for keyboard interrupts */
1400 if (VimErrorCheck())
1401 return -1;
1402
1403 return 0;
1404 }
1405#ifdef FEAT_VERTSPLIT
1406 else if (strcmp(name, "width") == 0)
1407 {
1408 int width;
1409 win_T *savewin;
1410
1411 if (!PyArg_Parse(val, "i", &width))
1412 return -1;
1413
1414#ifdef FEAT_GUI
1415 need_mouse_correct = TRUE;
1416#endif
1417 savewin = curwin;
1418 curwin = this->win;
1419 win_setwidth(width);
1420 curwin = savewin;
1421
1422 /* Check for keyboard interrupts */
1423 if (VimErrorCheck())
1424 return -1;
1425
1426 return 0;
1427 }
1428#endif
1429 else
1430 {
1431 PyErr_SetString(PyExc_AttributeError, name);
1432 return -1;
1433 }
1434}
1435
1436 static PyObject *
1437WindowRepr(PyObject *self)
1438{
1439 static char repr[100];
1440 WindowObject *this = (WindowObject *)(self);
1441
1442 if (this->win == INVALID_WINDOW_VALUE)
1443 {
1444 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1445 return PyString_FromString(repr);
1446 }
1447 else
1448 {
1449 int i = 0;
1450 win_T *w;
1451
1452 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
1453 ++i;
1454
1455 if (w == NULL)
1456 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1457 (self));
1458 else
1459 vim_snprintf(repr, 100, _("<window %d>"), i);
1460
1461 return PyString_FromString(repr);
1462 }
1463}
1464
1465/*
1466 * Window list object - Implementation
1467 */
1468 static PyInt
1469WinListLength(PyObject *self UNUSED)
1470{
1471 win_T *w = firstwin;
1472 PyInt n = 0;
1473
1474 while (w != NULL)
1475 {
1476 ++n;
1477 w = W_NEXT(w);
1478 }
1479
1480 return n;
1481}
1482
1483 static PyObject *
1484WinListItem(PyObject *self UNUSED, PyInt n)
1485{
1486 win_T *w;
1487
1488 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1489 if (n == 0)
1490 return WindowNew(w);
1491
1492 PyErr_SetString(PyExc_IndexError, _("no such window"));
1493 return NULL;
1494}
1495
1496/* Convert a Python string into a Vim line.
1497 *
1498 * The result is in allocated memory. All internal nulls are replaced by
1499 * newline characters. It is an error for the string to contain newline
1500 * characters.
1501 *
1502 * On errors, the Python exception data is set, and NULL is returned.
1503 */
1504 static char *
1505StringToLine(PyObject *obj)
1506{
1507 const char *str;
1508 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001509 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001510 PyInt len;
1511 PyInt i;
1512 char *p;
1513
1514 if (obj == NULL || !PyString_Check(obj))
1515 {
1516 PyErr_BadArgument();
1517 return NULL;
1518 }
1519
Bram Moolenaar19e60942011-06-19 00:27:51 +02001520 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1521 str = PyString_AsString(bytes);
1522 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001523
1524 /*
1525 * Error checking: String must not contain newlines, as we
1526 * are replacing a single line, and we must replace it with
1527 * a single line.
1528 * A trailing newline is removed, so that append(f.readlines()) works.
1529 */
1530 p = memchr(str, '\n', len);
1531 if (p != NULL)
1532 {
1533 if (p == str + len - 1)
1534 --len;
1535 else
1536 {
1537 PyErr_SetVim(_("string cannot contain newlines"));
1538 return NULL;
1539 }
1540 }
1541
1542 /* Create a copy of the string, with internal nulls replaced by
1543 * newline characters, as is the vim convention.
1544 */
1545 save = (char *)alloc((unsigned)(len+1));
1546 if (save == NULL)
1547 {
1548 PyErr_NoMemory();
1549 return NULL;
1550 }
1551
1552 for (i = 0; i < len; ++i)
1553 {
1554 if (str[i] == '\0')
1555 save[i] = '\n';
1556 else
1557 save[i] = str[i];
1558 }
1559
1560 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001561 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001562
1563 return save;
1564}
1565
1566/* Get a line from the specified buffer. The line number is
1567 * in Vim format (1-based). The line is returned as a Python
1568 * string object.
1569 */
1570 static PyObject *
1571GetBufferLine(buf_T *buf, PyInt n)
1572{
1573 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1574}
1575
1576
1577/* Get a list of lines from the specified buffer. The line numbers
1578 * are in Vim format (1-based). The range is from lo up to, but not
1579 * including, hi. The list is returned as a Python list of string objects.
1580 */
1581 static PyObject *
1582GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1583{
1584 PyInt i;
1585 PyInt n = hi - lo;
1586 PyObject *list = PyList_New(n);
1587
1588 if (list == NULL)
1589 return NULL;
1590
1591 for (i = 0; i < n; ++i)
1592 {
1593 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1594
1595 /* Error check - was the Python string creation OK? */
1596 if (str == NULL)
1597 {
1598 Py_DECREF(list);
1599 return NULL;
1600 }
1601
1602 /* Set the list item */
1603 if (PyList_SetItem(list, i, str))
1604 {
1605 Py_DECREF(str);
1606 Py_DECREF(list);
1607 return NULL;
1608 }
1609 }
1610
1611 /* The ownership of the Python list is passed to the caller (ie,
1612 * the caller should Py_DECREF() the object when it is finished
1613 * with it).
1614 */
1615
1616 return list;
1617}
1618
1619/*
1620 * Check if deleting lines made the cursor position invalid.
1621 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1622 * deleted).
1623 */
1624 static void
1625py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1626{
1627 if (curwin->w_cursor.lnum >= lo)
1628 {
1629 /* Adjust the cursor position if it's in/after the changed
1630 * lines. */
1631 if (curwin->w_cursor.lnum >= hi)
1632 {
1633 curwin->w_cursor.lnum += extra;
1634 check_cursor_col();
1635 }
1636 else if (extra < 0)
1637 {
1638 curwin->w_cursor.lnum = lo;
1639 check_cursor();
1640 }
1641 else
1642 check_cursor_col();
1643 changed_cline_bef_curs();
1644 }
1645 invalidate_botline();
1646}
1647
Bram Moolenaar19e60942011-06-19 00:27:51 +02001648/*
1649 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001650 * in Vim format (1-based). The replacement line is given as
1651 * a Python string object. The object is checked for validity
1652 * and correct format. Errors are returned as a value of FAIL.
1653 * The return value is OK on success.
1654 * If OK is returned and len_change is not NULL, *len_change
1655 * is set to the change in the buffer length.
1656 */
1657 static int
1658SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
1659{
1660 /* First of all, we check the thpe of the supplied Python object.
1661 * There are three cases:
1662 * 1. NULL, or None - this is a deletion.
1663 * 2. A string - this is a replacement.
1664 * 3. Anything else - this is an error.
1665 */
1666 if (line == Py_None || line == NULL)
1667 {
1668 buf_T *savebuf = curbuf;
1669
1670 PyErr_Clear();
1671 curbuf = buf;
1672
1673 if (u_savedel((linenr_T)n, 1L) == FAIL)
1674 PyErr_SetVim(_("cannot save undo information"));
1675 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
1676 PyErr_SetVim(_("cannot delete line"));
1677 else
1678 {
1679 if (buf == curwin->w_buffer)
1680 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
1681 deleted_lines_mark((linenr_T)n, 1L);
1682 }
1683
1684 curbuf = savebuf;
1685
1686 if (PyErr_Occurred() || VimErrorCheck())
1687 return FAIL;
1688
1689 if (len_change)
1690 *len_change = -1;
1691
1692 return OK;
1693 }
1694 else if (PyString_Check(line))
1695 {
1696 char *save = StringToLine(line);
1697 buf_T *savebuf = curbuf;
1698
1699 if (save == NULL)
1700 return FAIL;
1701
1702 /* We do not need to free "save" if ml_replace() consumes it. */
1703 PyErr_Clear();
1704 curbuf = buf;
1705
1706 if (u_savesub((linenr_T)n) == FAIL)
1707 {
1708 PyErr_SetVim(_("cannot save undo information"));
1709 vim_free(save);
1710 }
1711 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
1712 {
1713 PyErr_SetVim(_("cannot replace line"));
1714 vim_free(save);
1715 }
1716 else
1717 changed_bytes((linenr_T)n, 0);
1718
1719 curbuf = savebuf;
1720
1721 /* Check that the cursor is not beyond the end of the line now. */
1722 if (buf == curwin->w_buffer)
1723 check_cursor_col();
1724
1725 if (PyErr_Occurred() || VimErrorCheck())
1726 return FAIL;
1727
1728 if (len_change)
1729 *len_change = 0;
1730
1731 return OK;
1732 }
1733 else
1734 {
1735 PyErr_BadArgument();
1736 return FAIL;
1737 }
1738}
1739
Bram Moolenaar19e60942011-06-19 00:27:51 +02001740/* Replace a range of lines in the specified buffer. The line numbers are in
1741 * Vim format (1-based). The range is from lo up to, but not including, hi.
1742 * The replacement lines are given as a Python list of string objects. The
1743 * list is checked for validity and correct format. Errors are returned as a
1744 * value of FAIL. The return value is OK on success.
1745 * If OK is returned and len_change is not NULL, *len_change
1746 * is set to the change in the buffer length.
1747 */
1748 static int
1749SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
1750{
1751 /* First of all, we check the thpe of the supplied Python object.
1752 * There are three cases:
1753 * 1. NULL, or None - this is a deletion.
1754 * 2. A list - this is a replacement.
1755 * 3. Anything else - this is an error.
1756 */
1757 if (list == Py_None || list == NULL)
1758 {
1759 PyInt i;
1760 PyInt n = (int)(hi - lo);
1761 buf_T *savebuf = curbuf;
1762
1763 PyErr_Clear();
1764 curbuf = buf;
1765
1766 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
1767 PyErr_SetVim(_("cannot save undo information"));
1768 else
1769 {
1770 for (i = 0; i < n; ++i)
1771 {
1772 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1773 {
1774 PyErr_SetVim(_("cannot delete line"));
1775 break;
1776 }
1777 }
1778 if (buf == curwin->w_buffer)
1779 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
1780 deleted_lines_mark((linenr_T)lo, (long)i);
1781 }
1782
1783 curbuf = savebuf;
1784
1785 if (PyErr_Occurred() || VimErrorCheck())
1786 return FAIL;
1787
1788 if (len_change)
1789 *len_change = -n;
1790
1791 return OK;
1792 }
1793 else if (PyList_Check(list))
1794 {
1795 PyInt i;
1796 PyInt new_len = PyList_Size(list);
1797 PyInt old_len = hi - lo;
1798 PyInt extra = 0; /* lines added to text, can be negative */
1799 char **array;
1800 buf_T *savebuf;
1801
1802 if (new_len == 0) /* avoid allocating zero bytes */
1803 array = NULL;
1804 else
1805 {
1806 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
1807 if (array == NULL)
1808 {
1809 PyErr_NoMemory();
1810 return FAIL;
1811 }
1812 }
1813
1814 for (i = 0; i < new_len; ++i)
1815 {
1816 PyObject *line = PyList_GetItem(list, i);
1817
1818 array[i] = StringToLine(line);
1819 if (array[i] == NULL)
1820 {
1821 while (i)
1822 vim_free(array[--i]);
1823 vim_free(array);
1824 return FAIL;
1825 }
1826 }
1827
1828 savebuf = curbuf;
1829
1830 PyErr_Clear();
1831 curbuf = buf;
1832
1833 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
1834 PyErr_SetVim(_("cannot save undo information"));
1835
1836 /* If the size of the range is reducing (ie, new_len < old_len) we
1837 * need to delete some old_len. We do this at the start, by
1838 * repeatedly deleting line "lo".
1839 */
1840 if (!PyErr_Occurred())
1841 {
1842 for (i = 0; i < old_len - new_len; ++i)
1843 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1844 {
1845 PyErr_SetVim(_("cannot delete line"));
1846 break;
1847 }
1848 extra -= i;
1849 }
1850
1851 /* For as long as possible, replace the existing old_len with the
1852 * new old_len. This is a more efficient operation, as it requires
1853 * less memory allocation and freeing.
1854 */
1855 if (!PyErr_Occurred())
1856 {
1857 for (i = 0; i < old_len && i < new_len; ++i)
1858 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
1859 == FAIL)
1860 {
1861 PyErr_SetVim(_("cannot replace line"));
1862 break;
1863 }
1864 }
1865 else
1866 i = 0;
1867
1868 /* Now we may need to insert the remaining new old_len. If we do, we
1869 * must free the strings as we finish with them (we can't pass the
1870 * responsibility to vim in this case).
1871 */
1872 if (!PyErr_Occurred())
1873 {
1874 while (i < new_len)
1875 {
1876 if (ml_append((linenr_T)(lo + i - 1),
1877 (char_u *)array[i], 0, FALSE) == FAIL)
1878 {
1879 PyErr_SetVim(_("cannot insert line"));
1880 break;
1881 }
1882 vim_free(array[i]);
1883 ++i;
1884 ++extra;
1885 }
1886 }
1887
1888 /* Free any left-over old_len, as a result of an error */
1889 while (i < new_len)
1890 {
1891 vim_free(array[i]);
1892 ++i;
1893 }
1894
1895 /* Free the array of old_len. All of its contents have now
1896 * been dealt with (either freed, or the responsibility passed
1897 * to vim.
1898 */
1899 vim_free(array);
1900
1901 /* Adjust marks. Invalidate any which lie in the
1902 * changed range, and move any in the remainder of the buffer.
1903 */
1904 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
1905 (long)MAXLNUM, (long)extra);
1906 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
1907
1908 if (buf == curwin->w_buffer)
1909 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
1910
1911 curbuf = savebuf;
1912
1913 if (PyErr_Occurred() || VimErrorCheck())
1914 return FAIL;
1915
1916 if (len_change)
1917 *len_change = new_len - old_len;
1918
1919 return OK;
1920 }
1921 else
1922 {
1923 PyErr_BadArgument();
1924 return FAIL;
1925 }
1926}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001927
1928/* Insert a number of lines into the specified buffer after the specifed line.
1929 * The line number is in Vim format (1-based). The lines to be inserted are
1930 * given as a Python list of string objects or as a single string. The lines
1931 * to be added are checked for validity and correct format. Errors are
1932 * returned as a value of FAIL. The return value is OK on success.
1933 * If OK is returned and len_change is not NULL, *len_change
1934 * is set to the change in the buffer length.
1935 */
1936 static int
1937InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
1938{
1939 /* First of all, we check the type of the supplied Python object.
1940 * It must be a string or a list, or the call is in error.
1941 */
1942 if (PyString_Check(lines))
1943 {
1944 char *str = StringToLine(lines);
1945 buf_T *savebuf;
1946
1947 if (str == NULL)
1948 return FAIL;
1949
1950 savebuf = curbuf;
1951
1952 PyErr_Clear();
1953 curbuf = buf;
1954
1955 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
1956 PyErr_SetVim(_("cannot save undo information"));
1957 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
1958 PyErr_SetVim(_("cannot insert line"));
1959 else
1960 appended_lines_mark((linenr_T)n, 1L);
1961
1962 vim_free(str);
1963 curbuf = savebuf;
1964 update_screen(VALID);
1965
1966 if (PyErr_Occurred() || VimErrorCheck())
1967 return FAIL;
1968
1969 if (len_change)
1970 *len_change = 1;
1971
1972 return OK;
1973 }
1974 else if (PyList_Check(lines))
1975 {
1976 PyInt i;
1977 PyInt size = PyList_Size(lines);
1978 char **array;
1979 buf_T *savebuf;
1980
1981 array = (char **)alloc((unsigned)(size * sizeof(char *)));
1982 if (array == NULL)
1983 {
1984 PyErr_NoMemory();
1985 return FAIL;
1986 }
1987
1988 for (i = 0; i < size; ++i)
1989 {
1990 PyObject *line = PyList_GetItem(lines, i);
1991 array[i] = StringToLine(line);
1992
1993 if (array[i] == NULL)
1994 {
1995 while (i)
1996 vim_free(array[--i]);
1997 vim_free(array);
1998 return FAIL;
1999 }
2000 }
2001
2002 savebuf = curbuf;
2003
2004 PyErr_Clear();
2005 curbuf = buf;
2006
2007 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2008 PyErr_SetVim(_("cannot save undo information"));
2009 else
2010 {
2011 for (i = 0; i < size; ++i)
2012 {
2013 if (ml_append((linenr_T)(n + i),
2014 (char_u *)array[i], 0, FALSE) == FAIL)
2015 {
2016 PyErr_SetVim(_("cannot insert line"));
2017
2018 /* Free the rest of the lines */
2019 while (i < size)
2020 vim_free(array[i++]);
2021
2022 break;
2023 }
2024 vim_free(array[i]);
2025 }
2026 if (i > 0)
2027 appended_lines_mark((linenr_T)n, (long)i);
2028 }
2029
2030 /* Free the array of lines. All of its contents have now
2031 * been freed.
2032 */
2033 vim_free(array);
2034
2035 curbuf = savebuf;
2036 update_screen(VALID);
2037
2038 if (PyErr_Occurred() || VimErrorCheck())
2039 return FAIL;
2040
2041 if (len_change)
2042 *len_change = size;
2043
2044 return OK;
2045 }
2046 else
2047 {
2048 PyErr_BadArgument();
2049 return FAIL;
2050 }
2051}
2052
2053/*
2054 * Common routines for buffers and line ranges
2055 * -------------------------------------------
2056 */
2057
2058 static int
2059CheckBuffer(BufferObject *this)
2060{
2061 if (this->buf == INVALID_BUFFER_VALUE)
2062 {
2063 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2064 return -1;
2065 }
2066
2067 return 0;
2068}
2069
2070 static PyObject *
2071RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2072{
2073 if (CheckBuffer(self))
2074 return NULL;
2075
2076 if (n < 0 || n > end - start)
2077 {
2078 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2079 return NULL;
2080 }
2081
2082 return GetBufferLine(self->buf, n+start);
2083}
2084
2085 static PyObject *
2086RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2087{
2088 PyInt size;
2089
2090 if (CheckBuffer(self))
2091 return NULL;
2092
2093 size = end - start + 1;
2094
2095 if (lo < 0)
2096 lo = 0;
2097 else if (lo > size)
2098 lo = size;
2099 if (hi < 0)
2100 hi = 0;
2101 if (hi < lo)
2102 hi = lo;
2103 else if (hi > size)
2104 hi = size;
2105
2106 return GetBufferLineList(self->buf, lo+start, hi+start);
2107}
2108
2109 static PyInt
2110RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2111{
2112 PyInt len_change;
2113
2114 if (CheckBuffer(self))
2115 return -1;
2116
2117 if (n < 0 || n > end - start)
2118 {
2119 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2120 return -1;
2121 }
2122
2123 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2124 return -1;
2125
2126 if (new_end)
2127 *new_end = end + len_change;
2128
2129 return 0;
2130}
2131
Bram Moolenaar19e60942011-06-19 00:27:51 +02002132 static PyInt
2133RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2134{
2135 PyInt size;
2136 PyInt len_change;
2137
2138 /* Self must be a valid buffer */
2139 if (CheckBuffer(self))
2140 return -1;
2141
2142 /* Sort out the slice range */
2143 size = end - start + 1;
2144
2145 if (lo < 0)
2146 lo = 0;
2147 else if (lo > size)
2148 lo = size;
2149 if (hi < 0)
2150 hi = 0;
2151 if (hi < lo)
2152 hi = lo;
2153 else if (hi > size)
2154 hi = size;
2155
2156 if (SetBufferLineList(self->buf, lo + start, hi + start,
2157 val, &len_change) == FAIL)
2158 return -1;
2159
2160 if (new_end)
2161 *new_end = end + len_change;
2162
2163 return 0;
2164}
2165
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002166
2167 static PyObject *
2168RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2169{
2170 PyObject *lines;
2171 PyInt len_change;
2172 PyInt max;
2173 PyInt n;
2174
2175 if (CheckBuffer(self))
2176 return NULL;
2177
2178 max = n = end - start + 1;
2179
2180 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2181 return NULL;
2182
2183 if (n < 0 || n > max)
2184 {
2185 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2186 return NULL;
2187 }
2188
2189 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2190 return NULL;
2191
2192 if (new_end)
2193 *new_end = end + len_change;
2194
2195 Py_INCREF(Py_None);
2196 return Py_None;
2197}
2198
2199
2200/* Buffer object - Definitions
2201 */
2202
2203typedef struct
2204{
2205 PyObject_HEAD
2206 BufferObject *buf;
2207 PyInt start;
2208 PyInt end;
2209} RangeObject;
2210
2211 static PyObject *
2212RangeNew(buf_T *buf, PyInt start, PyInt end)
2213{
2214 BufferObject *bufr;
2215 RangeObject *self;
2216 self = PyObject_NEW(RangeObject, &RangeType);
2217 if (self == NULL)
2218 return NULL;
2219
2220 bufr = (BufferObject *)BufferNew(buf);
2221 if (bufr == NULL)
2222 {
2223 Py_DECREF(self);
2224 return NULL;
2225 }
2226 Py_INCREF(bufr);
2227
2228 self->buf = bufr;
2229 self->start = start;
2230 self->end = end;
2231
2232 return (PyObject *)(self);
2233}
2234
2235 static PyObject *
2236BufferAppend(PyObject *self, PyObject *args)
2237{
2238 return RBAppend((BufferObject *)(self), args, 1,
2239 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
2240 NULL);
2241}
2242
2243 static PyObject *
2244BufferMark(PyObject *self, PyObject *args)
2245{
2246 pos_T *posp;
2247 char *pmark;
2248 char mark;
2249 buf_T *curbuf_save;
2250
2251 if (CheckBuffer((BufferObject *)(self)))
2252 return NULL;
2253
2254 if (!PyArg_ParseTuple(args, "s", &pmark))
2255 return NULL;
2256 mark = *pmark;
2257
2258 curbuf_save = curbuf;
2259 curbuf = ((BufferObject *)(self))->buf;
2260 posp = getmark(mark, FALSE);
2261 curbuf = curbuf_save;
2262
2263 if (posp == NULL)
2264 {
2265 PyErr_SetVim(_("invalid mark name"));
2266 return NULL;
2267 }
2268
2269 /* Ckeck for keyboard interrupt */
2270 if (VimErrorCheck())
2271 return NULL;
2272
2273 if (posp->lnum <= 0)
2274 {
2275 /* Or raise an error? */
2276 Py_INCREF(Py_None);
2277 return Py_None;
2278 }
2279
2280 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2281}
2282
2283 static PyObject *
2284BufferRange(PyObject *self, PyObject *args)
2285{
2286 PyInt start;
2287 PyInt end;
2288
2289 if (CheckBuffer((BufferObject *)(self)))
2290 return NULL;
2291
2292 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2293 return NULL;
2294
2295 return RangeNew(((BufferObject *)(self))->buf, start, end);
2296}
2297
2298static struct PyMethodDef BufferMethods[] = {
2299 /* name, function, calling, documentation */
2300 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2301 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2302 {"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 +01002303#if PY_VERSION_HEX >= 0x03000000
2304 {"__dir__", BufferDir, 4, "List its attributes" },
2305#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002306 { NULL, NULL, 0, NULL }
2307};
2308
2309 static PyObject *
2310RangeAppend(PyObject *self, PyObject *args)
2311{
2312 return RBAppend(((RangeObject *)(self))->buf, args,
2313 ((RangeObject *)(self))->start,
2314 ((RangeObject *)(self))->end,
2315 &((RangeObject *)(self))->end);
2316}
2317
2318 static PyInt
2319RangeLength(PyObject *self)
2320{
2321 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2322 if (CheckBuffer(((RangeObject *)(self))->buf))
2323 return -1; /* ??? */
2324
2325 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2326}
2327
2328 static PyObject *
2329RangeItem(PyObject *self, PyInt n)
2330{
2331 return RBItem(((RangeObject *)(self))->buf, n,
2332 ((RangeObject *)(self))->start,
2333 ((RangeObject *)(self))->end);
2334}
2335
2336 static PyObject *
2337RangeRepr(PyObject *self)
2338{
2339 static char repr[100];
2340 RangeObject *this = (RangeObject *)(self);
2341
2342 if (this->buf->buf == INVALID_BUFFER_VALUE)
2343 {
2344 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2345 (self));
2346 return PyString_FromString(repr);
2347 }
2348 else
2349 {
2350 char *name = (char *)this->buf->buf->b_fname;
2351 int len;
2352
2353 if (name == NULL)
2354 name = "";
2355 len = (int)strlen(name);
2356
2357 if (len > 45)
2358 name = name + (45 - len);
2359
2360 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2361 len > 45 ? "..." : "", name,
2362 this->start, this->end);
2363
2364 return PyString_FromString(repr);
2365 }
2366}
2367
2368 static PyObject *
2369RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2370{
2371 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2372 ((RangeObject *)(self))->start,
2373 ((RangeObject *)(self))->end);
2374}
2375
2376/*
2377 * Line range object - Definitions
2378 */
2379
2380static struct PyMethodDef RangeMethods[] = {
2381 /* name, function, calling, documentation */
2382 {"append", RangeAppend, 1, "Append data to the Vim range" },
2383 { NULL, NULL, 0, NULL }
2384};
2385
Bram Moolenaardb913952012-06-29 12:54:53 +02002386 static void
2387set_ref_in_py(const int copyID)
2388{
2389 pylinkedlist_T *cur;
2390 dict_T *dd;
2391 list_T *ll;
2392
2393 if (lastdict != NULL)
2394 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
2395 {
2396 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
2397 if (dd->dv_copyID != copyID)
2398 {
2399 dd->dv_copyID = copyID;
2400 set_ref_in_ht(&dd->dv_hashtab, copyID);
2401 }
2402 }
2403
2404 if (lastlist != NULL)
2405 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
2406 {
2407 ll = ((ListObject *) (cur->pll_obj))->list;
2408 if (ll->lv_copyID != copyID)
2409 {
2410 ll->lv_copyID = copyID;
2411 set_ref_in_list(ll, copyID);
2412 }
2413 }
2414}
2415
2416 static int
2417set_string_copy(char_u *str, typval_T *tv)
2418{
2419 tv->vval.v_string = vim_strsave(str);
2420 if (tv->vval.v_string == NULL)
2421 {
2422 PyErr_NoMemory();
2423 return -1;
2424 }
2425 return 0;
2426}
2427
2428#ifdef FEAT_EVAL
2429typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
2430
2431 static int
2432convert_dl(PyObject *obj, typval_T *tv,
2433 pytotvfunc py_to_tv, PyObject *lookupDict)
2434{
2435 PyObject *capsule;
2436 char hexBuf[sizeof(void *) * 2 + 3];
2437
2438 sprintf(hexBuf, "%p", obj);
2439
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002440# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002441 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002442# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002443 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002444# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02002445 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02002446 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002447# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02002448 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02002449# else
2450 capsule = PyCObject_FromVoidPtr(tv, NULL);
2451# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002452 PyDict_SetItemString(lookupDict, hexBuf, capsule);
2453 Py_DECREF(capsule);
2454 if (py_to_tv(obj, tv, lookupDict) == -1)
2455 {
2456 tv->v_type = VAR_UNKNOWN;
2457 return -1;
2458 }
2459 /* As we are not using copy_tv which increments reference count we must
2460 * do it ourself. */
2461 switch(tv->v_type)
2462 {
2463 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
2464 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
2465 }
2466 }
2467 else
2468 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002469 typval_T *v;
2470
2471# ifdef PY_USE_CAPSULE
2472 v = PyCapsule_GetPointer(capsule, NULL);
2473# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02002474 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02002475# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02002476 copy_tv(v, tv);
2477 }
2478 return 0;
2479}
2480
2481 static int
2482ConvertFromPyObject(PyObject *obj, typval_T *tv)
2483{
2484 PyObject *lookup_dict;
2485 int r;
2486
2487 lookup_dict = PyDict_New();
2488 r = _ConvertFromPyObject(obj, tv, lookup_dict);
2489 Py_DECREF(lookup_dict);
2490 return r;
2491}
2492
2493 static int
2494_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2495{
2496 if (obj->ob_type == &DictionaryType)
2497 {
2498 tv->v_type = VAR_DICT;
2499 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
2500 ++tv->vval.v_dict->dv_refcount;
2501 }
2502 else if (obj->ob_type == &ListType)
2503 {
2504 tv->v_type = VAR_LIST;
2505 tv->vval.v_list = (((ListObject *)(obj))->list);
2506 ++tv->vval.v_list->lv_refcount;
2507 }
2508 else if (obj->ob_type == &FunctionType)
2509 {
2510 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
2511 return -1;
2512
2513 tv->v_type = VAR_FUNC;
2514 func_ref(tv->vval.v_string);
2515 }
2516#if PY_MAJOR_VERSION >= 3
2517 else if (PyBytes_Check(obj))
2518 {
2519 char_u *result = (char_u *) PyBytes_AsString(obj);
2520
2521 if (result == NULL)
2522 return -1;
2523
2524 if (set_string_copy(result, tv) == -1)
2525 return -1;
2526
2527 tv->v_type = VAR_STRING;
2528 }
2529 else if (PyUnicode_Check(obj))
2530 {
2531 PyObject *bytes;
2532 char_u *result;
2533
2534 bytes = PyString_AsBytes(obj);
2535 if (bytes == NULL)
2536 return -1;
2537
2538 result = (char_u *) PyBytes_AsString(bytes);
2539 if (result == NULL)
2540 return -1;
2541
2542 if (set_string_copy(result, tv) == -1)
2543 {
2544 Py_XDECREF(bytes);
2545 return -1;
2546 }
2547 Py_XDECREF(bytes);
2548
2549 tv->v_type = VAR_STRING;
2550 }
2551#else
2552 else if (PyUnicode_Check(obj))
2553 {
2554 PyObject *bytes;
2555 char_u *result;
2556
2557 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
2558 if (bytes == NULL)
2559 return -1;
2560
2561 result=(char_u *) PyString_AsString(bytes);
2562 if (result == NULL)
2563 return -1;
2564
2565 if (set_string_copy(result, tv) == -1)
2566 {
2567 Py_XDECREF(bytes);
2568 return -1;
2569 }
2570 Py_XDECREF(bytes);
2571
2572 tv->v_type = VAR_STRING;
2573 }
2574 else if (PyString_Check(obj))
2575 {
2576 char_u *result = (char_u *) PyString_AsString(obj);
2577
2578 if (result == NULL)
2579 return -1;
2580
2581 if (set_string_copy(result, tv) == -1)
2582 return -1;
2583
2584 tv->v_type = VAR_STRING;
2585 }
2586 else if (PyInt_Check(obj))
2587 {
2588 tv->v_type = VAR_NUMBER;
2589 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
2590 }
2591#endif
2592 else if (PyLong_Check(obj))
2593 {
2594 tv->v_type = VAR_NUMBER;
2595 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
2596 }
2597 else if (PyDict_Check(obj))
2598 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
2599#ifdef FEAT_FLOAT
2600 else if (PyFloat_Check(obj))
2601 {
2602 tv->v_type = VAR_FLOAT;
2603 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
2604 }
2605#endif
2606 else if (PyIter_Check(obj))
2607 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
2608 else if (PySequence_Check(obj))
2609 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
2610 else if (PyMapping_Check(obj))
2611 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
2612 else
2613 {
2614 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
2615 return -1;
2616 }
2617 return 0;
2618}
2619
2620 static PyObject *
2621ConvertToPyObject(typval_T *tv)
2622{
2623 if (tv == NULL)
2624 {
2625 PyErr_SetVim(_("NULL reference passed"));
2626 return NULL;
2627 }
2628 switch (tv->v_type)
2629 {
2630 case VAR_STRING:
2631 return PyBytes_FromString((char *) tv->vval.v_string);
2632 case VAR_NUMBER:
2633 return PyLong_FromLong((long) tv->vval.v_number);
2634#ifdef FEAT_FLOAT
2635 case VAR_FLOAT:
2636 return PyFloat_FromDouble((double) tv->vval.v_float);
2637#endif
2638 case VAR_LIST:
2639 return ListNew(tv->vval.v_list);
2640 case VAR_DICT:
2641 return DictionaryNew(tv->vval.v_dict);
2642 case VAR_FUNC:
2643 return FunctionNew(tv->vval.v_string);
2644 case VAR_UNKNOWN:
2645 Py_INCREF(Py_None);
2646 return Py_None;
2647 default:
2648 PyErr_SetVim(_("internal error: invalid value type"));
2649 return NULL;
2650 }
2651}
2652#endif