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