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