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