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