blob: 3267f814781f92d890c67a00e275c94fe8d84e35 [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/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020010 * Python extensions by Paul Moore, David Leonard, Roland Puntaier, Nikolay
11 * Pavlov.
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020012 *
13 * Common code for if_python.c and if_python3.c.
14 */
15
Bram Moolenaarc1a995d2012-08-08 16:05:07 +020016#if PY_VERSION_HEX < 0x02050000
17typedef int Py_ssize_t; /* Python 2.4 and earlier don't have this type. */
18#endif
19
Bram Moolenaar91805fc2011-06-26 04:01:44 +020020#ifdef FEAT_MBYTE
21# define ENC_OPT p_enc
22#else
23# define ENC_OPT "latin1"
24#endif
25
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020026#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
27
28#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
29#define INVALID_WINDOW_VALUE ((win_T *)(-1))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +020030#define INVALID_TABPAGE_VALUE ((tabpage_T *)(-1))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020031
32static int ConvertFromPyObject(PyObject *, typval_T *);
33static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
34
35static PyInt RangeStart;
36static PyInt RangeEnd;
37
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020038/*
39 * obtain a lock on the Vim data structures
40 */
41 static void
42Python_Lock_Vim(void)
43{
44}
45
46/*
47 * release a lock on the Vim data structures
48 */
49 static void
50Python_Release_Vim(void)
51{
52}
53
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020054/* Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020055 */
56
Bram Moolenaar2eea1982010-09-21 16:49:37 +020057/* Function to write a line, points to either msg() or emsg(). */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020058typedef void (*writefn)(char_u *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020059
60static PyTypeObject OutputType;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020061
62typedef struct
63{
64 PyObject_HEAD
65 long softspace;
66 long error;
67} OutputObject;
68
Bram Moolenaar77045652012-09-21 13:46:06 +020069 static int
70OutputSetattr(PyObject *self, char *name, PyObject *val)
71{
72 if (val == NULL)
73 {
Bram Moolenaar8661b172013-05-15 15:44:28 +020074 PyErr_SetString(PyExc_AttributeError,
75 _("can't delete OutputObject attributes"));
Bram Moolenaar77045652012-09-21 13:46:06 +020076 return -1;
77 }
78
79 if (strcmp(name, "softspace") == 0)
80 {
81 if (!PyInt_Check(val))
82 {
83 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
84 return -1;
85 }
86
87 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
88 return 0;
89 }
90
91 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
92 return -1;
93}
94
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020095/* Buffer IO, we write one whole line at a time. */
96static garray_T io_ga = {0, 0, 1, 80, NULL};
97static writefn old_fn = NULL;
98
99 static void
100PythonIO_Flush(void)
101{
102 if (old_fn != NULL && io_ga.ga_len > 0)
103 {
104 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
105 old_fn((char_u *)io_ga.ga_data);
106 }
107 io_ga.ga_len = 0;
108}
109
110 static void
111writer(writefn fn, char_u *str, PyInt n)
112{
113 char_u *ptr;
114
115 /* Flush when switching output function. */
116 if (fn != old_fn)
117 PythonIO_Flush();
118 old_fn = fn;
119
120 /* Write each NL separated line. Text after the last NL is kept for
121 * writing later. */
122 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
123 {
124 PyInt len = ptr - str;
125
126 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
127 break;
128
129 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
130 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
131 fn((char_u *)io_ga.ga_data);
132 str = ptr + 1;
133 n -= len + 1;
134 io_ga.ga_len = 0;
135 }
136
137 /* Put the remaining text into io_ga for later printing. */
138 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
139 {
140 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
141 io_ga.ga_len += (int)n;
142 }
143}
144
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200145 static PyObject *
146OutputWrite(PyObject *self, PyObject *args)
147{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200148 Py_ssize_t len = 0;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200149 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200150 int error = ((OutputObject *)(self))->error;
151
Bram Moolenaar27564802011-09-07 19:30:21 +0200152 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200153 return NULL;
154
155 Py_BEGIN_ALLOW_THREADS
156 Python_Lock_Vim();
157 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
158 Python_Release_Vim();
159 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200160 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200161
162 Py_INCREF(Py_None);
163 return Py_None;
164}
165
166 static PyObject *
167OutputWritelines(PyObject *self, PyObject *args)
168{
169 PyInt n;
170 PyInt i;
171 PyObject *list;
172 int error = ((OutputObject *)(self))->error;
173
174 if (!PyArg_ParseTuple(args, "O", &list))
175 return NULL;
176 Py_INCREF(list);
177
Bram Moolenaardb913952012-06-29 12:54:53 +0200178 if (!PyList_Check(list))
179 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200180 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
181 Py_DECREF(list);
182 return NULL;
183 }
184
185 n = PyList_Size(list);
186
187 for (i = 0; i < n; ++i)
188 {
189 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200190 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200191 PyInt len;
192
Bram Moolenaardb913952012-06-29 12:54:53 +0200193 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
194 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200195 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
196 Py_DECREF(list);
197 return NULL;
198 }
199
200 Py_BEGIN_ALLOW_THREADS
201 Python_Lock_Vim();
202 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
203 Python_Release_Vim();
204 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200205 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200206 }
207
208 Py_DECREF(list);
209 Py_INCREF(Py_None);
210 return Py_None;
211}
212
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100213 static PyObject *
214OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
215{
216 /* do nothing */
217 Py_INCREF(Py_None);
218 return Py_None;
219}
220
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200221/***************/
222
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200223static struct PyMethodDef OutputMethods[] = {
224 /* name, function, calling, documentation */
225 {"write", OutputWrite, 1, ""},
226 {"writelines", OutputWritelines, 1, ""},
227 {"flush", OutputFlush, 1, ""},
228 { NULL, NULL, 0, NULL}
229};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200230
231static OutputObject Output =
232{
233 PyObject_HEAD_INIT(&OutputType)
234 0,
235 0
236};
237
238static OutputObject Error =
239{
240 PyObject_HEAD_INIT(&OutputType)
241 0,
242 1
243};
244
245 static int
246PythonIO_Init_io(void)
247{
248 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
249 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
250
251 if (PyErr_Occurred())
252 {
253 EMSG(_("E264: Python: Error initialising I/O objects"));
254 return -1;
255 }
256
257 return 0;
258}
259
260
261static PyObject *VimError;
262
263/* Check to see whether a Vim error has been reported, or a keyboard
264 * interrupt has been detected.
265 */
266 static int
267VimErrorCheck(void)
268{
269 if (got_int)
270 {
271 PyErr_SetNone(PyExc_KeyboardInterrupt);
272 return 1;
273 }
274 else if (did_emsg && !PyErr_Occurred())
275 {
276 PyErr_SetNone(VimError);
277 return 1;
278 }
279
280 return 0;
281}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200282
283/* Vim module - Implementation
284 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200285
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200286 static PyObject *
287VimCommand(PyObject *self UNUSED, PyObject *args)
288{
289 char *cmd;
290 PyObject *result;
291
292 if (!PyArg_ParseTuple(args, "s", &cmd))
293 return NULL;
294
295 PyErr_Clear();
296
297 Py_BEGIN_ALLOW_THREADS
298 Python_Lock_Vim();
299
300 do_cmdline_cmd((char_u *)cmd);
301 update_screen(VALID);
302
303 Python_Release_Vim();
304 Py_END_ALLOW_THREADS
305
306 if (VimErrorCheck())
307 result = NULL;
308 else
309 result = Py_None;
310
311 Py_XINCREF(result);
312 return result;
313}
314
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200315/*
316 * Function to translate a typval_T into a PyObject; this will recursively
317 * translate lists/dictionaries into their Python equivalents.
318 *
319 * The depth parameter is to avoid infinite recursion, set it to 1 when
320 * you call VimToPython.
321 */
322 static PyObject *
323VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
324{
325 PyObject *result;
326 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200327 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200328
329 /* Avoid infinite recursion */
330 if (depth > 100)
331 {
332 Py_INCREF(Py_None);
333 result = Py_None;
334 return result;
335 }
336
337 /* Check if we run into a recursive loop. The item must be in lookupDict
338 * then and we can use it again. */
339 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
340 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
341 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200342 sprintf(ptrBuf, "%p",
343 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
344 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200345 result = PyDict_GetItemString(lookupDict, ptrBuf);
346 if (result != NULL)
347 {
348 Py_INCREF(result);
349 return result;
350 }
351 }
352
353 if (our_tv->v_type == VAR_STRING)
354 {
Bram Moolenaard1f13fd2012-10-05 21:30:07 +0200355 result = Py_BuildValue("s", our_tv->vval.v_string == NULL
356 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200357 }
358 else if (our_tv->v_type == VAR_NUMBER)
359 {
360 char buf[NUMBUFLEN];
361
362 /* For backwards compatibility numbers are stored as strings. */
363 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
364 result = Py_BuildValue("s", buf);
365 }
366# ifdef FEAT_FLOAT
367 else if (our_tv->v_type == VAR_FLOAT)
368 {
369 char buf[NUMBUFLEN];
370
371 sprintf(buf, "%f", our_tv->vval.v_float);
372 result = Py_BuildValue("s", buf);
373 }
374# endif
375 else if (our_tv->v_type == VAR_LIST)
376 {
377 list_T *list = our_tv->vval.v_list;
378 listitem_T *curr;
379
380 result = PyList_New(0);
381
382 if (list != NULL)
383 {
384 PyDict_SetItemString(lookupDict, ptrBuf, result);
385
386 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
387 {
388 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
389 PyList_Append(result, newObj);
390 Py_DECREF(newObj);
391 }
392 }
393 }
394 else if (our_tv->v_type == VAR_DICT)
395 {
396 result = PyDict_New();
397
398 if (our_tv->vval.v_dict != NULL)
399 {
400 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
401 long_u todo = ht->ht_used;
402 hashitem_T *hi;
403 dictitem_T *di;
404
405 PyDict_SetItemString(lookupDict, ptrBuf, result);
406
407 for (hi = ht->ht_array; todo > 0; ++hi)
408 {
409 if (!HASHITEM_EMPTY(hi))
410 {
411 --todo;
412
413 di = dict_lookup(hi);
414 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
415 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
416 Py_DECREF(newObj);
417 }
418 }
419 }
420 }
421 else
422 {
423 Py_INCREF(Py_None);
424 result = Py_None;
425 }
426
427 return result;
428}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200429
430 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200431VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200432{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200433 char *expr;
434 typval_T *our_tv;
435 PyObject *result;
436 PyObject *lookup_dict;
437
438 if (!PyArg_ParseTuple(args, "s", &expr))
439 return NULL;
440
441 Py_BEGIN_ALLOW_THREADS
442 Python_Lock_Vim();
443 our_tv = eval_expr((char_u *)expr, NULL);
444
445 Python_Release_Vim();
446 Py_END_ALLOW_THREADS
447
448 if (our_tv == NULL)
449 {
450 PyErr_SetVim(_("invalid expression"));
451 return NULL;
452 }
453
454 /* Convert the Vim type into a Python type. Create a dictionary that's
455 * used to check for recursive loops. */
456 lookup_dict = PyDict_New();
457 result = VimToPython(our_tv, 1, lookup_dict);
458 Py_DECREF(lookup_dict);
459
460
461 Py_BEGIN_ALLOW_THREADS
462 Python_Lock_Vim();
463 free_tv(our_tv);
464 Python_Release_Vim();
465 Py_END_ALLOW_THREADS
466
467 return result;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200468}
469
Bram Moolenaardb913952012-06-29 12:54:53 +0200470static PyObject *ConvertToPyObject(typval_T *);
471
472 static PyObject *
473VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
474{
Bram Moolenaardb913952012-06-29 12:54:53 +0200475 char *expr;
476 typval_T *our_tv;
477 PyObject *result;
478
479 if (!PyArg_ParseTuple(args, "s", &expr))
480 return NULL;
481
482 Py_BEGIN_ALLOW_THREADS
483 Python_Lock_Vim();
484 our_tv = eval_expr((char_u *)expr, NULL);
485
486 Python_Release_Vim();
487 Py_END_ALLOW_THREADS
488
489 if (our_tv == NULL)
490 {
491 PyErr_SetVim(_("invalid expression"));
492 return NULL;
493 }
494
495 result = ConvertToPyObject(our_tv);
496 Py_BEGIN_ALLOW_THREADS
497 Python_Lock_Vim();
498 free_tv(our_tv);
499 Python_Release_Vim();
500 Py_END_ALLOW_THREADS
501
502 return result;
Bram Moolenaardb913952012-06-29 12:54:53 +0200503}
504
505 static PyObject *
506VimStrwidth(PyObject *self UNUSED, PyObject *args)
507{
508 char *expr;
509
510 if (!PyArg_ParseTuple(args, "s", &expr))
511 return NULL;
512
Bram Moolenaara54bf402012-12-05 16:30:07 +0100513 return PyLong_FromLong(
514#ifdef FEAT_MBYTE
515 mb_string2cells((char_u *)expr, (int)STRLEN(expr))
516#else
517 STRLEN(expr)
518#endif
519 );
Bram Moolenaardb913952012-06-29 12:54:53 +0200520}
521
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200522/*
523 * Vim module - Definitions
524 */
525
526static struct PyMethodDef VimMethods[] = {
527 /* name, function, calling, documentation */
528 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
529 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200530 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
531 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200532 { NULL, NULL, 0, NULL }
533};
534
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200535/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200536 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200537 */
538
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200539static PyTypeObject IterType;
540
541typedef PyObject *(*nextfun)(void **);
542typedef void (*destructorfun)(void *);
543
544/* Main purpose of this object is removing the need for do python initialization
545 * (i.e. PyType_Ready and setting type attributes) for a big bunch of objects.
546 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200547
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200548typedef struct
549{
550 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200551 void *cur;
552 nextfun next;
553 destructorfun destruct;
554} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200555
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200556 static PyObject *
557IterNew(void *start, destructorfun destruct, nextfun next)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200558{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200559 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200560
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200561 self = PyObject_NEW(IterObject, &IterType);
562 self->cur = start;
563 self->next = next;
564 self->destruct = destruct;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200565
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200566 return (PyObject *)(self);
567}
568
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200569#if 0 /* unused */
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200570 static void
571IterDestructor(PyObject *self)
572{
573 IterObject *this = (IterObject *)(self);
574
575 this->destruct(this->cur);
576
577 DESTRUCTOR_FINISH(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200578}
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200579#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200580
581 static PyObject *
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200582IterNext(PyObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200583{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200584 IterObject *this = (IterObject *)(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200585
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200586 return this->next(&this->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200587}
588
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200589 static PyObject *
590IterIter(PyObject *self)
591{
592 return self;
593}
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200594
Bram Moolenaardb913952012-06-29 12:54:53 +0200595typedef struct pylinkedlist_S {
596 struct pylinkedlist_S *pll_next;
597 struct pylinkedlist_S *pll_prev;
598 PyObject *pll_obj;
599} pylinkedlist_T;
600
601static pylinkedlist_T *lastdict = NULL;
602static pylinkedlist_T *lastlist = NULL;
603
604 static void
605pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
606{
607 if (ref->pll_prev == NULL)
608 {
609 if (ref->pll_next == NULL)
610 {
611 *last = NULL;
612 return;
613 }
614 }
615 else
616 ref->pll_prev->pll_next = ref->pll_next;
617
618 if (ref->pll_next == NULL)
619 *last = ref->pll_prev;
620 else
621 ref->pll_next->pll_prev = ref->pll_prev;
622}
623
624 static void
625pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
626{
627 if (*last == NULL)
628 ref->pll_prev = NULL;
629 else
630 {
631 (*last)->pll_next = ref;
632 ref->pll_prev = *last;
633 }
634 ref->pll_next = NULL;
635 ref->pll_obj = self;
636 *last = ref;
637}
638
639static PyTypeObject DictionaryType;
640
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200641#define DICTKEY_GET_NOTEMPTY(err) \
642 DICTKEY_GET(err) \
643 if (*key == NUL) \
644 { \
645 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
646 return err; \
647 }
648
Bram Moolenaardb913952012-06-29 12:54:53 +0200649typedef struct
650{
651 PyObject_HEAD
652 dict_T *dict;
653 pylinkedlist_T ref;
654} DictionaryObject;
655
656 static PyObject *
657DictionaryNew(dict_T *dict)
658{
659 DictionaryObject *self;
660
661 self = PyObject_NEW(DictionaryObject, &DictionaryType);
662 if (self == NULL)
663 return NULL;
664 self->dict = dict;
665 ++dict->dv_refcount;
666
667 pyll_add((PyObject *)(self), &self->ref, &lastdict);
668
669 return (PyObject *)(self);
670}
671
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200672 static void
673DictionaryDestructor(PyObject *self)
674{
675 DictionaryObject *this = ((DictionaryObject *) (self));
676
677 pyll_remove(&this->ref, &lastdict);
678 dict_unref(this->dict);
679
680 DESTRUCTOR_FINISH(self);
681}
682
Bram Moolenaardb913952012-06-29 12:54:53 +0200683 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200684DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200685{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200686 DictionaryObject *this = (DictionaryObject *)(self);
687
Bram Moolenaar66b79852012-09-21 14:00:35 +0200688 if (val == NULL)
689 {
690 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
691 return -1;
692 }
693
694 if (strcmp(name, "locked") == 0)
695 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200696 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200697 {
698 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
699 return -1;
700 }
701 else
702 {
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200703 if (PyObject_IsTrue(val))
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200704 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200705 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200706 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200707 }
708 return 0;
709 }
710 else
711 {
712 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
713 return -1;
714 }
715}
716
717 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200718DictionaryLength(PyObject *self)
719{
720 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
721}
722
723 static PyObject *
724DictionaryItem(PyObject *self, PyObject *keyObject)
725{
726 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200727 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200728 DICTKEY_DECL
729
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200730 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200731
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200732 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
733
Bram Moolenaar696c2112012-09-21 13:43:14 +0200734 DICTKEY_UNREF
735
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200736 if (di == NULL)
737 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200738 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200739 return NULL;
740 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200741
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200742 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200743}
744
745 static PyInt
746DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
747{
748 char_u *key;
749 typval_T tv;
750 dict_T *d = ((DictionaryObject *)(self))->dict;
751 dictitem_T *di;
752 DICTKEY_DECL
753
754 if (d->dv_lock)
755 {
756 PyErr_SetVim(_("dict is locked"));
757 return -1;
758 }
759
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200760 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200761
762 di = dict_find(d, key, -1);
763
764 if (valObject == NULL)
765 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200766 hashitem_T *hi;
767
Bram Moolenaardb913952012-06-29 12:54:53 +0200768 if (di == NULL)
769 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200770 DICTKEY_UNREF
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200771 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaardb913952012-06-29 12:54:53 +0200772 return -1;
773 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200774 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200775 hash_remove(&d->dv_hashtab, hi);
776 dictitem_free(di);
777 return 0;
778 }
779
780 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200781 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200782
783 if (di == NULL)
784 {
785 di = dictitem_alloc(key);
786 if (di == NULL)
787 {
788 PyErr_NoMemory();
789 return -1;
790 }
791 di->di_tv.v_lock = 0;
792
793 if (dict_add(d, di) == FAIL)
794 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200795 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200796 vim_free(di);
797 PyErr_SetVim(_("failed to add key to dictionary"));
798 return -1;
799 }
800 }
801 else
802 clear_tv(&di->di_tv);
803
804 DICTKEY_UNREF
805
806 copy_tv(&tv, &di->di_tv);
807 return 0;
808}
809
810 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100811DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200812{
813 dict_T *dict = ((DictionaryObject *)(self))->dict;
814 long_u todo = dict->dv_hashtab.ht_used;
815 Py_ssize_t i = 0;
816 PyObject *r;
817 hashitem_T *hi;
818
819 r = PyList_New(todo);
820 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
821 {
822 if (!HASHITEM_EMPTY(hi))
823 {
824 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
825 --todo;
826 ++i;
827 }
828 }
829 return r;
830}
831
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200832static PyMappingMethods DictionaryAsMapping = {
833 (lenfunc) DictionaryLength,
834 (binaryfunc) DictionaryItem,
835 (objobjargproc) DictionaryAssItem,
836};
837
Bram Moolenaardb913952012-06-29 12:54:53 +0200838static struct PyMethodDef DictionaryMethods[] = {
839 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
840 { NULL, NULL, 0, NULL }
841};
842
843static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200844static PySequenceMethods ListAsSeq;
845static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200846
847typedef struct
848{
849 PyObject_HEAD
850 list_T *list;
851 pylinkedlist_T ref;
852} ListObject;
853
854 static PyObject *
855ListNew(list_T *list)
856{
857 ListObject *self;
858
859 self = PyObject_NEW(ListObject, &ListType);
860 if (self == NULL)
861 return NULL;
862 self->list = list;
863 ++list->lv_refcount;
864
865 pyll_add((PyObject *)(self), &self->ref, &lastlist);
866
867 return (PyObject *)(self);
868}
869
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200870 static void
871ListDestructor(PyObject *self)
872{
873 ListObject *this = (ListObject *)(self);
874
875 pyll_remove(&this->ref, &lastlist);
876 list_unref(this->list);
877
878 DESTRUCTOR_FINISH(self);
879}
880
Bram Moolenaardb913952012-06-29 12:54:53 +0200881 static int
882list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
883{
884 Py_ssize_t i;
885 Py_ssize_t lsize = PySequence_Size(obj);
886 PyObject *litem;
887 listitem_T *li;
888
889 for(i=0; i<lsize; i++)
890 {
891 li = listitem_alloc();
892 if (li == NULL)
893 {
894 PyErr_NoMemory();
895 return -1;
896 }
897 li->li_tv.v_lock = 0;
898
899 litem = PySequence_GetItem(obj, i);
900 if (litem == NULL)
901 return -1;
902 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
903 return -1;
904
905 list_append(l, li);
906 }
907 return 0;
908}
909
Bram Moolenaardb913952012-06-29 12:54:53 +0200910 static PyInt
911ListLength(PyObject *self)
912{
913 return ((PyInt) (((ListObject *) (self))->list->lv_len));
914}
915
916 static PyObject *
917ListItem(PyObject *self, Py_ssize_t index)
918{
919 listitem_T *li;
920
921 if (index>=ListLength(self))
922 {
Bram Moolenaar8661b172013-05-15 15:44:28 +0200923 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +0200924 return NULL;
925 }
926 li = list_find(((ListObject *) (self))->list, (long) index);
927 if (li == NULL)
928 {
929 PyErr_SetVim(_("internal error: failed to get vim list item"));
930 return NULL;
931 }
932 return ConvertToPyObject(&li->li_tv);
933}
934
935#define PROC_RANGE \
936 if (last < 0) {\
937 if (last < -size) \
938 last = 0; \
939 else \
940 last += size; \
941 } \
942 if (first < 0) \
943 first = 0; \
944 if (first > size) \
945 first = size; \
946 if (last > size) \
947 last = size;
948
949 static PyObject *
950ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
951{
952 PyInt i;
953 PyInt size = ListLength(self);
954 PyInt n;
955 PyObject *list;
956 int reversed = 0;
957
958 PROC_RANGE
959 if (first >= last)
960 first = last;
961
962 n = last-first;
963 list = PyList_New(n);
964 if (list == NULL)
965 return NULL;
966
967 for (i = 0; i < n; ++i)
968 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200969 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +0200970 if (item == NULL)
971 {
972 Py_DECREF(list);
973 return NULL;
974 }
975
976 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
977 {
978 Py_DECREF(item);
979 Py_DECREF(list);
980 return NULL;
981 }
982 }
983
984 return list;
985}
986
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200987typedef struct
988{
989 listwatch_T lw;
990 list_T *list;
991} listiterinfo_T;
992
993 static void
994ListIterDestruct(listiterinfo_T *lii)
995{
996 list_rem_watch(lii->list, &lii->lw);
997 PyMem_Free(lii);
998}
999
1000 static PyObject *
1001ListIterNext(listiterinfo_T **lii)
1002{
1003 PyObject *r;
1004
1005 if (!((*lii)->lw.lw_item))
1006 return NULL;
1007
1008 if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
1009 return NULL;
1010
1011 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
1012
1013 return r;
1014}
1015
1016 static PyObject *
1017ListIter(PyObject *self)
1018{
1019 listiterinfo_T *lii;
1020 list_T *l = ((ListObject *) (self))->list;
1021
1022 if (!(lii = PyMem_New(listiterinfo_T, 1)))
1023 {
1024 PyErr_NoMemory();
1025 return NULL;
1026 }
1027
1028 list_add_watch(l, &lii->lw);
1029 lii->lw.lw_item = l->lv_first;
1030 lii->list = l;
1031
1032 return IterNew(lii,
1033 (destructorfun) ListIterDestruct, (nextfun) ListIterNext);
1034}
1035
Bram Moolenaardb913952012-06-29 12:54:53 +02001036 static int
1037ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1038{
1039 typval_T tv;
1040 list_T *l = ((ListObject *) (self))->list;
1041 listitem_T *li;
1042 Py_ssize_t length = ListLength(self);
1043
1044 if (l->lv_lock)
1045 {
1046 PyErr_SetVim(_("list is locked"));
1047 return -1;
1048 }
1049 if (index>length || (index==length && obj==NULL))
1050 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001051 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001052 return -1;
1053 }
1054
1055 if (obj == NULL)
1056 {
1057 li = list_find(l, (long) index);
1058 list_remove(l, li, li);
1059 clear_tv(&li->li_tv);
1060 vim_free(li);
1061 return 0;
1062 }
1063
1064 if (ConvertFromPyObject(obj, &tv) == -1)
1065 return -1;
1066
1067 if (index == length)
1068 {
1069 if (list_append_tv(l, &tv) == FAIL)
1070 {
1071 PyErr_SetVim(_("Failed to add item to list"));
1072 return -1;
1073 }
1074 }
1075 else
1076 {
1077 li = list_find(l, (long) index);
1078 clear_tv(&li->li_tv);
1079 copy_tv(&tv, &li->li_tv);
1080 }
1081 return 0;
1082}
1083
1084 static int
1085ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1086{
1087 PyInt size = ListLength(self);
1088 Py_ssize_t i;
1089 Py_ssize_t lsize;
1090 PyObject *litem;
1091 listitem_T *li;
1092 listitem_T *next;
1093 typval_T v;
1094 list_T *l = ((ListObject *) (self))->list;
1095
1096 if (l->lv_lock)
1097 {
1098 PyErr_SetVim(_("list is locked"));
1099 return -1;
1100 }
1101
1102 PROC_RANGE
1103
1104 if (first == size)
1105 li = NULL;
1106 else
1107 {
1108 li = list_find(l, (long) first);
1109 if (li == NULL)
1110 {
1111 PyErr_SetVim(_("internal error: no vim list item"));
1112 return -1;
1113 }
1114 if (last > first)
1115 {
1116 i = last - first;
1117 while (i-- && li != NULL)
1118 {
1119 next = li->li_next;
1120 listitem_remove(l, li);
1121 li = next;
1122 }
1123 }
1124 }
1125
1126 if (obj == NULL)
1127 return 0;
1128
1129 if (!PyList_Check(obj))
1130 {
1131 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1132 return -1;
1133 }
1134
1135 lsize = PyList_Size(obj);
1136
1137 for(i=0; i<lsize; i++)
1138 {
1139 litem = PyList_GetItem(obj, i);
1140 if (litem == NULL)
1141 return -1;
1142 if (ConvertFromPyObject(litem, &v) == -1)
1143 return -1;
1144 if (list_insert_tv(l, &v, li) == FAIL)
1145 {
1146 PyErr_SetVim(_("internal error: failed to add item to list"));
1147 return -1;
1148 }
1149 }
1150 return 0;
1151}
1152
1153 static PyObject *
1154ListConcatInPlace(PyObject *self, PyObject *obj)
1155{
1156 list_T *l = ((ListObject *) (self))->list;
1157 PyObject *lookup_dict;
1158
1159 if (l->lv_lock)
1160 {
1161 PyErr_SetVim(_("list is locked"));
1162 return NULL;
1163 }
1164
1165 if (!PySequence_Check(obj))
1166 {
1167 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1168 return NULL;
1169 }
1170
1171 lookup_dict = PyDict_New();
1172 if (list_py_concat(l, obj, lookup_dict) == -1)
1173 {
1174 Py_DECREF(lookup_dict);
1175 return NULL;
1176 }
1177 Py_DECREF(lookup_dict);
1178
1179 Py_INCREF(self);
1180 return self;
1181}
1182
Bram Moolenaar66b79852012-09-21 14:00:35 +02001183 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001184ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001185{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001186 ListObject *this = (ListObject *)(self);
1187
Bram Moolenaar66b79852012-09-21 14:00:35 +02001188 if (val == NULL)
1189 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001190 PyErr_SetString(PyExc_AttributeError,
1191 _("cannot delete vim.dictionary attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001192 return -1;
1193 }
1194
1195 if (strcmp(name, "locked") == 0)
1196 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001197 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001198 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001199 PyErr_SetString(PyExc_TypeError, _("cannot modify fixed list"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001200 return -1;
1201 }
1202 else
1203 {
Bram Moolenaar03db85b2013-05-15 14:51:35 +02001204 if (PyObject_IsTrue(val))
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001205 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001206 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001207 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001208 }
1209 return 0;
1210 }
1211 else
1212 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001213 PyErr_SetString(PyExc_AttributeError, _("cannot set this attribute"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001214 return -1;
1215 }
1216}
1217
Bram Moolenaardb913952012-06-29 12:54:53 +02001218static struct PyMethodDef ListMethods[] = {
1219 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1220 { NULL, NULL, 0, NULL }
1221};
1222
1223typedef struct
1224{
1225 PyObject_HEAD
1226 char_u *name;
1227} FunctionObject;
1228
1229static PyTypeObject FunctionType;
1230
1231 static PyObject *
1232FunctionNew(char_u *name)
1233{
1234 FunctionObject *self;
1235
1236 self = PyObject_NEW(FunctionObject, &FunctionType);
1237 if (self == NULL)
1238 return NULL;
1239 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1240 if (self->name == NULL)
1241 {
1242 PyErr_NoMemory();
1243 return NULL;
1244 }
1245 STRCPY(self->name, name);
1246 func_ref(name);
1247 return (PyObject *)(self);
1248}
1249
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001250 static void
1251FunctionDestructor(PyObject *self)
1252{
1253 FunctionObject *this = (FunctionObject *) (self);
1254
1255 func_unref(this->name);
1256 PyMem_Del(this->name);
1257
1258 DESTRUCTOR_FINISH(self);
1259}
1260
Bram Moolenaardb913952012-06-29 12:54:53 +02001261 static PyObject *
1262FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1263{
1264 FunctionObject *this = (FunctionObject *)(self);
1265 char_u *name = this->name;
1266 typval_T args;
1267 typval_T selfdicttv;
1268 typval_T rettv;
1269 dict_T *selfdict = NULL;
1270 PyObject *selfdictObject;
1271 PyObject *result;
1272 int error;
1273
1274 if (ConvertFromPyObject(argsObject, &args) == -1)
1275 return NULL;
1276
1277 if (kwargs != NULL)
1278 {
1279 selfdictObject = PyDict_GetItemString(kwargs, "self");
1280 if (selfdictObject != NULL)
1281 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001282 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001283 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001284 PyErr_SetString(PyExc_TypeError,
1285 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001286 clear_tv(&args);
1287 return NULL;
1288 }
1289 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1290 return NULL;
1291 selfdict = selfdicttv.vval.v_dict;
1292 }
1293 }
1294
1295 error = func_call(name, &args, selfdict, &rettv);
1296 if (error != OK)
1297 {
1298 result = NULL;
1299 PyErr_SetVim(_("failed to run function"));
1300 }
1301 else
1302 result = ConvertToPyObject(&rettv);
1303
1304 /* FIXME Check what should really be cleared. */
1305 clear_tv(&args);
1306 clear_tv(&rettv);
1307 /*
1308 * if (selfdict!=NULL)
1309 * clear_tv(selfdicttv);
1310 */
1311
1312 return result;
1313}
1314
1315static struct PyMethodDef FunctionMethods[] = {
1316 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1317 { NULL, NULL, 0, NULL }
1318};
1319
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001320/*
1321 * Options object
1322 */
1323
1324static PyTypeObject OptionsType;
1325
1326typedef int (*checkfun)(void *);
1327
1328typedef struct
1329{
1330 PyObject_HEAD
1331 int opt_type;
1332 void *from;
1333 checkfun Check;
1334 PyObject *fromObj;
1335} OptionsObject;
1336
1337 static PyObject *
1338OptionsItem(OptionsObject *this, PyObject *keyObject)
1339{
1340 char_u *key;
1341 int flags;
1342 long numval;
1343 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001344 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001345
1346 if (this->Check(this->from))
1347 return NULL;
1348
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001349 DICTKEY_GET_NOTEMPTY(NULL)
1350
1351 flags = get_option_value_strict(key, &numval, &stringval,
1352 this->opt_type, this->from);
1353
1354 DICTKEY_UNREF
1355
1356 if (flags == 0)
1357 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001358 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001359 return NULL;
1360 }
1361
1362 if (flags & SOPT_UNSET)
1363 {
1364 Py_INCREF(Py_None);
1365 return Py_None;
1366 }
1367 else if (flags & SOPT_BOOL)
1368 {
1369 PyObject *r;
1370 r = numval ? Py_True : Py_False;
1371 Py_INCREF(r);
1372 return r;
1373 }
1374 else if (flags & SOPT_NUM)
1375 return PyInt_FromLong(numval);
1376 else if (flags & SOPT_STRING)
1377 {
1378 if (stringval)
1379 return PyBytes_FromString((char *) stringval);
1380 else
1381 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001382 PyErr_SetString(PyExc_RuntimeError,
1383 _("unable to get option value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001384 return NULL;
1385 }
1386 }
1387 else
1388 {
1389 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1390 return NULL;
1391 }
1392}
1393
1394 static int
1395set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1396 char_u *key;
1397 int numval;
1398 char_u *stringval;
1399 int opt_flags;
1400 int opt_type;
1401 void *from;
1402{
1403 win_T *save_curwin;
1404 tabpage_T *save_curtab;
1405 aco_save_T aco;
1406 int r = 0;
1407
1408 switch (opt_type)
1409 {
1410 case SREQ_WIN:
1411 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1412 == FAIL)
1413 {
1414 PyErr_SetVim("Problem while switching windows.");
1415 return -1;
1416 }
1417 set_option_value(key, numval, stringval, opt_flags);
1418 restore_win(save_curwin, save_curtab);
1419 break;
1420 case SREQ_BUF:
1421 aucmd_prepbuf(&aco, (buf_T *) from);
1422 set_option_value(key, numval, stringval, opt_flags);
1423 aucmd_restbuf(&aco);
1424 break;
1425 case SREQ_GLOBAL:
1426 set_option_value(key, numval, stringval, opt_flags);
1427 break;
1428 }
1429 return r;
1430}
1431
1432 static int
1433OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1434{
1435 char_u *key;
1436 int flags;
1437 int opt_flags;
1438 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001439 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001440
1441 if (this->Check(this->from))
1442 return -1;
1443
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001444 DICTKEY_GET_NOTEMPTY(-1)
1445
1446 flags = get_option_value_strict(key, NULL, NULL,
1447 this->opt_type, this->from);
1448
1449 DICTKEY_UNREF
1450
1451 if (flags == 0)
1452 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001453 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001454 return -1;
1455 }
1456
1457 if (valObject == NULL)
1458 {
1459 if (this->opt_type == SREQ_GLOBAL)
1460 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001461 PyErr_SetString(PyExc_ValueError,
1462 _("unable to unset global option"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001463 return -1;
1464 }
1465 else if (!(flags & SOPT_GLOBAL))
1466 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001467 PyErr_SetString(PyExc_ValueError, _("unable to unset option "
1468 "without global value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001469 return -1;
1470 }
1471 else
1472 {
1473 unset_global_local_option(key, this->from);
1474 return 0;
1475 }
1476 }
1477
1478 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1479
1480 if (flags & SOPT_BOOL)
1481 {
Bram Moolenaar03db85b2013-05-15 14:51:35 +02001482 r = set_option_value_for(key, PyObject_IsTrue(valObject), NULL,
1483 opt_flags, this->opt_type, this->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001484 }
1485 else if (flags & SOPT_NUM)
1486 {
1487 int val;
1488
1489#if PY_MAJOR_VERSION < 3
1490 if (PyInt_Check(valObject))
1491 val = PyInt_AsLong(valObject);
1492 else
1493#endif
1494 if (PyLong_Check(valObject))
1495 val = PyLong_AsLong(valObject);
1496 else
1497 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001498 PyErr_SetString(PyExc_TypeError, _("object must be integer"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001499 return -1;
1500 }
1501
1502 r = set_option_value_for(key, val, NULL, opt_flags,
1503 this->opt_type, this->from);
1504 }
1505 else
1506 {
1507 char_u *val;
1508 if (PyBytes_Check(valObject))
1509 {
1510
1511 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1512 return -1;
1513 if (val == NULL)
1514 return -1;
1515
1516 val = vim_strsave(val);
1517 }
1518 else if (PyUnicode_Check(valObject))
1519 {
1520 PyObject *bytes;
1521
1522 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1523 if (bytes == NULL)
1524 return -1;
1525
1526 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1527 return -1;
1528 if (val == NULL)
1529 return -1;
1530
1531 val = vim_strsave(val);
1532 Py_XDECREF(bytes);
1533 }
1534 else
1535 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001536 PyErr_SetString(PyExc_TypeError, _("object must be string"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001537 return -1;
1538 }
1539
1540 r = set_option_value_for(key, 0, val, opt_flags,
1541 this->opt_type, this->from);
1542 vim_free(val);
1543 }
1544
1545 return r;
1546}
1547
1548 static int
1549dummy_check(void *arg UNUSED)
1550{
1551 return 0;
1552}
1553
1554 static PyObject *
1555OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1556{
1557 OptionsObject *self;
1558
1559 self = PyObject_NEW(OptionsObject, &OptionsType);
1560 if (self == NULL)
1561 return NULL;
1562
1563 self->opt_type = opt_type;
1564 self->from = from;
1565 self->Check = Check;
1566 self->fromObj = fromObj;
1567 if (fromObj)
1568 Py_INCREF(fromObj);
1569
1570 return (PyObject *)(self);
1571}
1572
1573 static void
1574OptionsDestructor(PyObject *self)
1575{
1576 if (((OptionsObject *)(self))->fromObj)
1577 Py_DECREF(((OptionsObject *)(self))->fromObj);
1578 DESTRUCTOR_FINISH(self);
1579}
1580
1581static PyMappingMethods OptionsAsMapping = {
1582 (lenfunc) NULL,
1583 (binaryfunc) OptionsItem,
1584 (objobjargproc) OptionsAssItem,
1585};
1586
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001587/* Tabpage object
1588 */
1589
1590typedef struct
1591{
1592 PyObject_HEAD
1593 tabpage_T *tab;
1594} TabPageObject;
1595
1596static PyObject *WinListNew(TabPageObject *tabObject);
1597
1598static PyTypeObject TabPageType;
1599
1600 static int
1601CheckTabPage(TabPageObject *this)
1602{
1603 if (this->tab == INVALID_TABPAGE_VALUE)
1604 {
1605 PyErr_SetVim(_("attempt to refer to deleted tab page"));
1606 return -1;
1607 }
1608
1609 return 0;
1610}
1611
1612 static PyObject *
1613TabPageNew(tabpage_T *tab)
1614{
1615 TabPageObject *self;
1616
1617 if (TAB_PYTHON_REF(tab))
1618 {
1619 self = TAB_PYTHON_REF(tab);
1620 Py_INCREF(self);
1621 }
1622 else
1623 {
1624 self = PyObject_NEW(TabPageObject, &TabPageType);
1625 if (self == NULL)
1626 return NULL;
1627 self->tab = tab;
1628 TAB_PYTHON_REF(tab) = self;
1629 }
1630
1631 return (PyObject *)(self);
1632}
1633
1634 static void
1635TabPageDestructor(PyObject *self)
1636{
1637 TabPageObject *this = (TabPageObject *)(self);
1638
1639 if (this->tab && this->tab != INVALID_TABPAGE_VALUE)
1640 TAB_PYTHON_REF(this->tab) = NULL;
1641
1642 DESTRUCTOR_FINISH(self);
1643}
1644
1645 static PyObject *
1646TabPageAttr(TabPageObject *this, char *name)
1647{
1648 if (strcmp(name, "windows") == 0)
1649 return WinListNew(this);
1650 else if (strcmp(name, "number") == 0)
1651 return PyLong_FromLong((long) get_tab_number(this->tab));
1652 else if (strcmp(name, "vars") == 0)
1653 return DictionaryNew(this->tab->tp_vars);
1654 else if (strcmp(name, "window") == 0)
1655 {
1656 /* For current tab window.c does not bother to set or update tp_curwin
1657 */
1658 if (this->tab == curtab)
1659 return WindowNew(curwin);
1660 else
1661 return WindowNew(this->tab->tp_curwin);
1662 }
1663 return NULL;
1664}
1665
1666 static PyObject *
1667TabPageRepr(PyObject *self)
1668{
1669 static char repr[100];
1670 TabPageObject *this = (TabPageObject *)(self);
1671
1672 if (this->tab == INVALID_TABPAGE_VALUE)
1673 {
1674 vim_snprintf(repr, 100, _("<tabpage object (deleted) at %p>"), (self));
1675 return PyString_FromString(repr);
1676 }
1677 else
1678 {
1679 int t = get_tab_number(this->tab);
1680
1681 if (t == 0)
1682 vim_snprintf(repr, 100, _("<tabpage object (unknown) at %p>"),
1683 (self));
1684 else
1685 vim_snprintf(repr, 100, _("<tabpage %d>"), t - 1);
1686
1687 return PyString_FromString(repr);
1688 }
1689}
1690
1691static struct PyMethodDef TabPageMethods[] = {
1692 /* name, function, calling, documentation */
1693 { NULL, NULL, 0, NULL }
1694};
1695
1696/*
1697 * Window list object
1698 */
1699
1700static PyTypeObject TabListType;
1701static PySequenceMethods TabListAsSeq;
1702
1703typedef struct
1704{
1705 PyObject_HEAD
1706} TabListObject;
1707
1708 static PyInt
1709TabListLength(PyObject *self UNUSED)
1710{
1711 tabpage_T *tp = first_tabpage;
1712 PyInt n = 0;
1713
1714 while (tp != NULL)
1715 {
1716 ++n;
1717 tp = tp->tp_next;
1718 }
1719
1720 return n;
1721}
1722
1723 static PyObject *
1724TabListItem(PyObject *self UNUSED, PyInt n)
1725{
1726 tabpage_T *tp;
1727
1728 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, --n)
1729 if (n == 0)
1730 return TabPageNew(tp);
1731
1732 PyErr_SetString(PyExc_IndexError, _("no such tab page"));
1733 return NULL;
1734}
1735
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001736/* Window object
1737 */
1738
1739typedef struct
1740{
1741 PyObject_HEAD
1742 win_T *win;
1743} WindowObject;
1744
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001745static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001746
1747 static int
1748CheckWindow(WindowObject *this)
1749{
1750 if (this->win == INVALID_WINDOW_VALUE)
1751 {
1752 PyErr_SetVim(_("attempt to refer to deleted window"));
1753 return -1;
1754 }
1755
1756 return 0;
1757}
1758
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001759 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001760WindowNew(win_T *win)
1761{
1762 /* We need to handle deletion of windows underneath us.
1763 * If we add a "w_python*_ref" field to the win_T structure,
1764 * then we can get at it in win_free() in vim. We then
1765 * need to create only ONE Python object per window - if
1766 * we try to create a second, just INCREF the existing one
1767 * and return it. The (single) Python object referring to
1768 * the window is stored in "w_python*_ref".
1769 * On a win_free() we set the Python object's win_T* field
1770 * to an invalid value. We trap all uses of a window
1771 * object, and reject them if the win_T* field is invalid.
1772 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001773 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001774 * w_python_ref and w_python3_ref fields respectively.
1775 */
1776
1777 WindowObject *self;
1778
1779 if (WIN_PYTHON_REF(win))
1780 {
1781 self = WIN_PYTHON_REF(win);
1782 Py_INCREF(self);
1783 }
1784 else
1785 {
1786 self = PyObject_NEW(WindowObject, &WindowType);
1787 if (self == NULL)
1788 return NULL;
1789 self->win = win;
1790 WIN_PYTHON_REF(win) = self;
1791 }
1792
1793 return (PyObject *)(self);
1794}
1795
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001796 static void
1797WindowDestructor(PyObject *self)
1798{
1799 WindowObject *this = (WindowObject *)(self);
1800
1801 if (this->win && this->win != INVALID_WINDOW_VALUE)
1802 WIN_PYTHON_REF(this->win) = NULL;
1803
1804 DESTRUCTOR_FINISH(self);
1805}
1806
Bram Moolenaar971db462013-05-12 18:44:48 +02001807 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001808WindowAttr(WindowObject *this, char *name)
1809{
1810 if (strcmp(name, "buffer") == 0)
1811 return (PyObject *)BufferNew(this->win->w_buffer);
1812 else if (strcmp(name, "cursor") == 0)
1813 {
1814 pos_T *pos = &this->win->w_cursor;
1815
1816 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1817 }
1818 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001819 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001820#ifdef FEAT_WINDOWS
1821 else if (strcmp(name, "row") == 0)
1822 return PyLong_FromLong((long)(this->win->w_winrow));
1823#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001824#ifdef FEAT_VERTSPLIT
1825 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001826 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001827 else if (strcmp(name, "col") == 0)
1828 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001829#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001830 else if (strcmp(name, "vars") == 0)
1831 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001832 else if (strcmp(name, "options") == 0)
1833 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1834 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001835 else if (strcmp(name, "number") == 0)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001836 return PyLong_FromLong((long) get_win_number(this->win, firstwin));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001837 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001838 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1839 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001840 else
1841 return NULL;
1842}
1843
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001844 static int
1845WindowSetattr(PyObject *self, char *name, PyObject *val)
1846{
1847 WindowObject *this = (WindowObject *)(self);
1848
1849 if (CheckWindow(this))
1850 return -1;
1851
1852 if (strcmp(name, "buffer") == 0)
1853 {
1854 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1855 return -1;
1856 }
1857 else if (strcmp(name, "cursor") == 0)
1858 {
1859 long lnum;
1860 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001861
1862 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1863 return -1;
1864
1865 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1866 {
1867 PyErr_SetVim(_("cursor position outside buffer"));
1868 return -1;
1869 }
1870
1871 /* Check for keyboard interrupts */
1872 if (VimErrorCheck())
1873 return -1;
1874
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001875 this->win->w_cursor.lnum = lnum;
1876 this->win->w_cursor.col = col;
1877#ifdef FEAT_VIRTUALEDIT
1878 this->win->w_cursor.coladd = 0;
1879#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001880 /* When column is out of range silently correct it. */
1881 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001882
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001883 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001884 return 0;
1885 }
1886 else if (strcmp(name, "height") == 0)
1887 {
1888 int height;
1889 win_T *savewin;
1890
1891 if (!PyArg_Parse(val, "i", &height))
1892 return -1;
1893
1894#ifdef FEAT_GUI
1895 need_mouse_correct = TRUE;
1896#endif
1897 savewin = curwin;
1898 curwin = this->win;
1899 win_setheight(height);
1900 curwin = savewin;
1901
1902 /* Check for keyboard interrupts */
1903 if (VimErrorCheck())
1904 return -1;
1905
1906 return 0;
1907 }
1908#ifdef FEAT_VERTSPLIT
1909 else if (strcmp(name, "width") == 0)
1910 {
1911 int width;
1912 win_T *savewin;
1913
1914 if (!PyArg_Parse(val, "i", &width))
1915 return -1;
1916
1917#ifdef FEAT_GUI
1918 need_mouse_correct = TRUE;
1919#endif
1920 savewin = curwin;
1921 curwin = this->win;
1922 win_setwidth(width);
1923 curwin = savewin;
1924
1925 /* Check for keyboard interrupts */
1926 if (VimErrorCheck())
1927 return -1;
1928
1929 return 0;
1930 }
1931#endif
1932 else
1933 {
1934 PyErr_SetString(PyExc_AttributeError, name);
1935 return -1;
1936 }
1937}
1938
1939 static PyObject *
1940WindowRepr(PyObject *self)
1941{
1942 static char repr[100];
1943 WindowObject *this = (WindowObject *)(self);
1944
1945 if (this->win == INVALID_WINDOW_VALUE)
1946 {
1947 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1948 return PyString_FromString(repr);
1949 }
1950 else
1951 {
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001952 int w = get_win_number(this->win, firstwin);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001953
Bram Moolenaar6d216452013-05-12 19:00:41 +02001954 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001955 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1956 (self));
1957 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001958 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001959
1960 return PyString_FromString(repr);
1961 }
1962}
1963
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001964static struct PyMethodDef WindowMethods[] = {
1965 /* name, function, calling, documentation */
1966 { NULL, NULL, 0, NULL }
1967};
1968
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001969/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001970 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001971 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001972
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001973static PyTypeObject WinListType;
1974static PySequenceMethods WinListAsSeq;
1975
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001976typedef struct
1977{
1978 PyObject_HEAD
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001979 TabPageObject *tabObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001980} WinListObject;
1981
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001982 static PyObject *
1983WinListNew(TabPageObject *tabObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001984{
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001985 WinListObject *self;
1986
1987 self = PyObject_NEW(WinListObject, &WinListType);
1988 self->tabObject = tabObject;
1989 Py_INCREF(tabObject);
1990
1991 return (PyObject *)(self);
1992}
1993
1994 static void
1995WinListDestructor(PyObject *self)
1996{
1997 TabPageObject *tabObject = ((WinListObject *)(self))->tabObject;
1998
1999 if (tabObject)
2000 Py_DECREF((PyObject *)(tabObject));
2001
2002 DESTRUCTOR_FINISH(self);
2003}
2004
2005 static win_T *
2006get_firstwin(WinListObject *this)
2007{
2008 if (this->tabObject)
2009 {
2010 if (CheckTabPage(this->tabObject))
2011 return NULL;
2012 /* For current tab window.c does not bother to set or update tp_firstwin
2013 */
2014 else if (this->tabObject->tab == curtab)
2015 return firstwin;
2016 else
2017 return this->tabObject->tab->tp_firstwin;
2018 }
2019 else
2020 return firstwin;
2021}
2022
2023 static PyInt
2024WinListLength(PyObject *self)
2025{
2026 win_T *w;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002027 PyInt n = 0;
2028
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002029 if (!(w = get_firstwin((WinListObject *)(self))))
2030 return -1;
2031
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002032 while (w != NULL)
2033 {
2034 ++n;
2035 w = W_NEXT(w);
2036 }
2037
2038 return n;
2039}
2040
2041 static PyObject *
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002042WinListItem(PyObject *self, PyInt n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002043{
2044 win_T *w;
2045
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002046 if (!(w = get_firstwin((WinListObject *)(self))))
2047 return NULL;
2048
2049 for (; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002050 if (n == 0)
2051 return WindowNew(w);
2052
2053 PyErr_SetString(PyExc_IndexError, _("no such window"));
2054 return NULL;
2055}
2056
2057/* Convert a Python string into a Vim line.
2058 *
2059 * The result is in allocated memory. All internal nulls are replaced by
2060 * newline characters. It is an error for the string to contain newline
2061 * characters.
2062 *
2063 * On errors, the Python exception data is set, and NULL is returned.
2064 */
2065 static char *
2066StringToLine(PyObject *obj)
2067{
2068 const char *str;
2069 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002070 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002071 PyInt len;
2072 PyInt i;
2073 char *p;
2074
2075 if (obj == NULL || !PyString_Check(obj))
2076 {
2077 PyErr_BadArgument();
2078 return NULL;
2079 }
2080
Bram Moolenaar19e60942011-06-19 00:27:51 +02002081 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
2082 str = PyString_AsString(bytes);
2083 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002084
2085 /*
2086 * Error checking: String must not contain newlines, as we
2087 * are replacing a single line, and we must replace it with
2088 * a single line.
2089 * A trailing newline is removed, so that append(f.readlines()) works.
2090 */
2091 p = memchr(str, '\n', len);
2092 if (p != NULL)
2093 {
2094 if (p == str + len - 1)
2095 --len;
2096 else
2097 {
2098 PyErr_SetVim(_("string cannot contain newlines"));
2099 return NULL;
2100 }
2101 }
2102
2103 /* Create a copy of the string, with internal nulls replaced by
2104 * newline characters, as is the vim convention.
2105 */
2106 save = (char *)alloc((unsigned)(len+1));
2107 if (save == NULL)
2108 {
2109 PyErr_NoMemory();
2110 return NULL;
2111 }
2112
2113 for (i = 0; i < len; ++i)
2114 {
2115 if (str[i] == '\0')
2116 save[i] = '\n';
2117 else
2118 save[i] = str[i];
2119 }
2120
2121 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02002122 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002123
2124 return save;
2125}
2126
2127/* Get a line from the specified buffer. The line number is
2128 * in Vim format (1-based). The line is returned as a Python
2129 * string object.
2130 */
2131 static PyObject *
2132GetBufferLine(buf_T *buf, PyInt n)
2133{
2134 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2135}
2136
2137
2138/* Get a list of lines from the specified buffer. The line numbers
2139 * are in Vim format (1-based). The range is from lo up to, but not
2140 * including, hi. The list is returned as a Python list of string objects.
2141 */
2142 static PyObject *
2143GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2144{
2145 PyInt i;
2146 PyInt n = hi - lo;
2147 PyObject *list = PyList_New(n);
2148
2149 if (list == NULL)
2150 return NULL;
2151
2152 for (i = 0; i < n; ++i)
2153 {
2154 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2155
2156 /* Error check - was the Python string creation OK? */
2157 if (str == NULL)
2158 {
2159 Py_DECREF(list);
2160 return NULL;
2161 }
2162
2163 /* Set the list item */
2164 if (PyList_SetItem(list, i, str))
2165 {
2166 Py_DECREF(str);
2167 Py_DECREF(list);
2168 return NULL;
2169 }
2170 }
2171
2172 /* The ownership of the Python list is passed to the caller (ie,
2173 * the caller should Py_DECREF() the object when it is finished
2174 * with it).
2175 */
2176
2177 return list;
2178}
2179
2180/*
2181 * Check if deleting lines made the cursor position invalid.
2182 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2183 * deleted).
2184 */
2185 static void
2186py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2187{
2188 if (curwin->w_cursor.lnum >= lo)
2189 {
2190 /* Adjust the cursor position if it's in/after the changed
2191 * lines. */
2192 if (curwin->w_cursor.lnum >= hi)
2193 {
2194 curwin->w_cursor.lnum += extra;
2195 check_cursor_col();
2196 }
2197 else if (extra < 0)
2198 {
2199 curwin->w_cursor.lnum = lo;
2200 check_cursor();
2201 }
2202 else
2203 check_cursor_col();
2204 changed_cline_bef_curs();
2205 }
2206 invalidate_botline();
2207}
2208
Bram Moolenaar19e60942011-06-19 00:27:51 +02002209/*
2210 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002211 * in Vim format (1-based). The replacement line is given as
2212 * a Python string object. The object is checked for validity
2213 * and correct format. Errors are returned as a value of FAIL.
2214 * The return value is OK on success.
2215 * If OK is returned and len_change is not NULL, *len_change
2216 * is set to the change in the buffer length.
2217 */
2218 static int
2219SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2220{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002221 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002222 * There are three cases:
2223 * 1. NULL, or None - this is a deletion.
2224 * 2. A string - this is a replacement.
2225 * 3. Anything else - this is an error.
2226 */
2227 if (line == Py_None || line == NULL)
2228 {
2229 buf_T *savebuf = curbuf;
2230
2231 PyErr_Clear();
2232 curbuf = buf;
2233
2234 if (u_savedel((linenr_T)n, 1L) == FAIL)
2235 PyErr_SetVim(_("cannot save undo information"));
2236 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2237 PyErr_SetVim(_("cannot delete line"));
2238 else
2239 {
2240 if (buf == curwin->w_buffer)
2241 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2242 deleted_lines_mark((linenr_T)n, 1L);
2243 }
2244
2245 curbuf = savebuf;
2246
2247 if (PyErr_Occurred() || VimErrorCheck())
2248 return FAIL;
2249
2250 if (len_change)
2251 *len_change = -1;
2252
2253 return OK;
2254 }
2255 else if (PyString_Check(line))
2256 {
2257 char *save = StringToLine(line);
2258 buf_T *savebuf = curbuf;
2259
2260 if (save == NULL)
2261 return FAIL;
2262
2263 /* We do not need to free "save" if ml_replace() consumes it. */
2264 PyErr_Clear();
2265 curbuf = buf;
2266
2267 if (u_savesub((linenr_T)n) == FAIL)
2268 {
2269 PyErr_SetVim(_("cannot save undo information"));
2270 vim_free(save);
2271 }
2272 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2273 {
2274 PyErr_SetVim(_("cannot replace line"));
2275 vim_free(save);
2276 }
2277 else
2278 changed_bytes((linenr_T)n, 0);
2279
2280 curbuf = savebuf;
2281
2282 /* Check that the cursor is not beyond the end of the line now. */
2283 if (buf == curwin->w_buffer)
2284 check_cursor_col();
2285
2286 if (PyErr_Occurred() || VimErrorCheck())
2287 return FAIL;
2288
2289 if (len_change)
2290 *len_change = 0;
2291
2292 return OK;
2293 }
2294 else
2295 {
2296 PyErr_BadArgument();
2297 return FAIL;
2298 }
2299}
2300
Bram Moolenaar19e60942011-06-19 00:27:51 +02002301/* Replace a range of lines in the specified buffer. The line numbers are in
2302 * Vim format (1-based). The range is from lo up to, but not including, hi.
2303 * The replacement lines are given as a Python list of string objects. The
2304 * list is checked for validity and correct format. Errors are returned as a
2305 * value of FAIL. The return value is OK on success.
2306 * If OK is returned and len_change is not NULL, *len_change
2307 * is set to the change in the buffer length.
2308 */
2309 static int
2310SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2311{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002312 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002313 * There are three cases:
2314 * 1. NULL, or None - this is a deletion.
2315 * 2. A list - this is a replacement.
2316 * 3. Anything else - this is an error.
2317 */
2318 if (list == Py_None || list == NULL)
2319 {
2320 PyInt i;
2321 PyInt n = (int)(hi - lo);
2322 buf_T *savebuf = curbuf;
2323
2324 PyErr_Clear();
2325 curbuf = buf;
2326
2327 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2328 PyErr_SetVim(_("cannot save undo information"));
2329 else
2330 {
2331 for (i = 0; i < n; ++i)
2332 {
2333 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2334 {
2335 PyErr_SetVim(_("cannot delete line"));
2336 break;
2337 }
2338 }
2339 if (buf == curwin->w_buffer)
2340 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2341 deleted_lines_mark((linenr_T)lo, (long)i);
2342 }
2343
2344 curbuf = savebuf;
2345
2346 if (PyErr_Occurred() || VimErrorCheck())
2347 return FAIL;
2348
2349 if (len_change)
2350 *len_change = -n;
2351
2352 return OK;
2353 }
2354 else if (PyList_Check(list))
2355 {
2356 PyInt i;
2357 PyInt new_len = PyList_Size(list);
2358 PyInt old_len = hi - lo;
2359 PyInt extra = 0; /* lines added to text, can be negative */
2360 char **array;
2361 buf_T *savebuf;
2362
2363 if (new_len == 0) /* avoid allocating zero bytes */
2364 array = NULL;
2365 else
2366 {
2367 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2368 if (array == NULL)
2369 {
2370 PyErr_NoMemory();
2371 return FAIL;
2372 }
2373 }
2374
2375 for (i = 0; i < new_len; ++i)
2376 {
2377 PyObject *line = PyList_GetItem(list, i);
2378
2379 array[i] = StringToLine(line);
2380 if (array[i] == NULL)
2381 {
2382 while (i)
2383 vim_free(array[--i]);
2384 vim_free(array);
2385 return FAIL;
2386 }
2387 }
2388
2389 savebuf = curbuf;
2390
2391 PyErr_Clear();
2392 curbuf = buf;
2393
2394 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2395 PyErr_SetVim(_("cannot save undo information"));
2396
2397 /* If the size of the range is reducing (ie, new_len < old_len) we
2398 * need to delete some old_len. We do this at the start, by
2399 * repeatedly deleting line "lo".
2400 */
2401 if (!PyErr_Occurred())
2402 {
2403 for (i = 0; i < old_len - new_len; ++i)
2404 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2405 {
2406 PyErr_SetVim(_("cannot delete line"));
2407 break;
2408 }
2409 extra -= i;
2410 }
2411
2412 /* For as long as possible, replace the existing old_len with the
2413 * new old_len. This is a more efficient operation, as it requires
2414 * less memory allocation and freeing.
2415 */
2416 if (!PyErr_Occurred())
2417 {
2418 for (i = 0; i < old_len && i < new_len; ++i)
2419 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2420 == FAIL)
2421 {
2422 PyErr_SetVim(_("cannot replace line"));
2423 break;
2424 }
2425 }
2426 else
2427 i = 0;
2428
2429 /* Now we may need to insert the remaining new old_len. If we do, we
2430 * must free the strings as we finish with them (we can't pass the
2431 * responsibility to vim in this case).
2432 */
2433 if (!PyErr_Occurred())
2434 {
2435 while (i < new_len)
2436 {
2437 if (ml_append((linenr_T)(lo + i - 1),
2438 (char_u *)array[i], 0, FALSE) == FAIL)
2439 {
2440 PyErr_SetVim(_("cannot insert line"));
2441 break;
2442 }
2443 vim_free(array[i]);
2444 ++i;
2445 ++extra;
2446 }
2447 }
2448
2449 /* Free any left-over old_len, as a result of an error */
2450 while (i < new_len)
2451 {
2452 vim_free(array[i]);
2453 ++i;
2454 }
2455
2456 /* Free the array of old_len. All of its contents have now
2457 * been dealt with (either freed, or the responsibility passed
2458 * to vim.
2459 */
2460 vim_free(array);
2461
2462 /* Adjust marks. Invalidate any which lie in the
2463 * changed range, and move any in the remainder of the buffer.
2464 */
2465 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2466 (long)MAXLNUM, (long)extra);
2467 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2468
2469 if (buf == curwin->w_buffer)
2470 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2471
2472 curbuf = savebuf;
2473
2474 if (PyErr_Occurred() || VimErrorCheck())
2475 return FAIL;
2476
2477 if (len_change)
2478 *len_change = new_len - old_len;
2479
2480 return OK;
2481 }
2482 else
2483 {
2484 PyErr_BadArgument();
2485 return FAIL;
2486 }
2487}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002488
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002489/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002490 * The line number is in Vim format (1-based). The lines to be inserted are
2491 * given as a Python list of string objects or as a single string. The lines
2492 * to be added are checked for validity and correct format. Errors are
2493 * returned as a value of FAIL. The return value is OK on success.
2494 * If OK is returned and len_change is not NULL, *len_change
2495 * is set to the change in the buffer length.
2496 */
2497 static int
2498InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2499{
2500 /* First of all, we check the type of the supplied Python object.
2501 * It must be a string or a list, or the call is in error.
2502 */
2503 if (PyString_Check(lines))
2504 {
2505 char *str = StringToLine(lines);
2506 buf_T *savebuf;
2507
2508 if (str == NULL)
2509 return FAIL;
2510
2511 savebuf = curbuf;
2512
2513 PyErr_Clear();
2514 curbuf = buf;
2515
2516 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2517 PyErr_SetVim(_("cannot save undo information"));
2518 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2519 PyErr_SetVim(_("cannot insert line"));
2520 else
2521 appended_lines_mark((linenr_T)n, 1L);
2522
2523 vim_free(str);
2524 curbuf = savebuf;
2525 update_screen(VALID);
2526
2527 if (PyErr_Occurred() || VimErrorCheck())
2528 return FAIL;
2529
2530 if (len_change)
2531 *len_change = 1;
2532
2533 return OK;
2534 }
2535 else if (PyList_Check(lines))
2536 {
2537 PyInt i;
2538 PyInt size = PyList_Size(lines);
2539 char **array;
2540 buf_T *savebuf;
2541
2542 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2543 if (array == NULL)
2544 {
2545 PyErr_NoMemory();
2546 return FAIL;
2547 }
2548
2549 for (i = 0; i < size; ++i)
2550 {
2551 PyObject *line = PyList_GetItem(lines, i);
2552 array[i] = StringToLine(line);
2553
2554 if (array[i] == NULL)
2555 {
2556 while (i)
2557 vim_free(array[--i]);
2558 vim_free(array);
2559 return FAIL;
2560 }
2561 }
2562
2563 savebuf = curbuf;
2564
2565 PyErr_Clear();
2566 curbuf = buf;
2567
2568 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2569 PyErr_SetVim(_("cannot save undo information"));
2570 else
2571 {
2572 for (i = 0; i < size; ++i)
2573 {
2574 if (ml_append((linenr_T)(n + i),
2575 (char_u *)array[i], 0, FALSE) == FAIL)
2576 {
2577 PyErr_SetVim(_("cannot insert line"));
2578
2579 /* Free the rest of the lines */
2580 while (i < size)
2581 vim_free(array[i++]);
2582
2583 break;
2584 }
2585 vim_free(array[i]);
2586 }
2587 if (i > 0)
2588 appended_lines_mark((linenr_T)n, (long)i);
2589 }
2590
2591 /* Free the array of lines. All of its contents have now
2592 * been freed.
2593 */
2594 vim_free(array);
2595
2596 curbuf = savebuf;
2597 update_screen(VALID);
2598
2599 if (PyErr_Occurred() || VimErrorCheck())
2600 return FAIL;
2601
2602 if (len_change)
2603 *len_change = size;
2604
2605 return OK;
2606 }
2607 else
2608 {
2609 PyErr_BadArgument();
2610 return FAIL;
2611 }
2612}
2613
2614/*
2615 * Common routines for buffers and line ranges
2616 * -------------------------------------------
2617 */
2618
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002619typedef struct
2620{
2621 PyObject_HEAD
2622 buf_T *buf;
2623} BufferObject;
2624
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002625 static int
2626CheckBuffer(BufferObject *this)
2627{
2628 if (this->buf == INVALID_BUFFER_VALUE)
2629 {
2630 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2631 return -1;
2632 }
2633
2634 return 0;
2635}
2636
2637 static PyObject *
2638RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2639{
2640 if (CheckBuffer(self))
2641 return NULL;
2642
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002643 if (end == -1)
2644 end = self->buf->b_ml.ml_line_count;
2645
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002646 if (n < 0)
2647 n += end - start + 1;
2648
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002649 if (n < 0 || n > end - start)
2650 {
2651 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2652 return NULL;
2653 }
2654
2655 return GetBufferLine(self->buf, n+start);
2656}
2657
2658 static PyObject *
2659RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2660{
2661 PyInt size;
2662
2663 if (CheckBuffer(self))
2664 return NULL;
2665
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002666 if (end == -1)
2667 end = self->buf->b_ml.ml_line_count;
2668
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002669 size = end - start + 1;
2670
2671 if (lo < 0)
2672 lo = 0;
2673 else if (lo > size)
2674 lo = size;
2675 if (hi < 0)
2676 hi = 0;
2677 if (hi < lo)
2678 hi = lo;
2679 else if (hi > size)
2680 hi = size;
2681
2682 return GetBufferLineList(self->buf, lo+start, hi+start);
2683}
2684
2685 static PyInt
2686RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2687{
2688 PyInt len_change;
2689
2690 if (CheckBuffer(self))
2691 return -1;
2692
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002693 if (end == -1)
2694 end = self->buf->b_ml.ml_line_count;
2695
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002696 if (n < 0)
2697 n += end - start + 1;
2698
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002699 if (n < 0 || n > end - start)
2700 {
2701 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2702 return -1;
2703 }
2704
2705 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2706 return -1;
2707
2708 if (new_end)
2709 *new_end = end + len_change;
2710
2711 return 0;
2712}
2713
Bram Moolenaar19e60942011-06-19 00:27:51 +02002714 static PyInt
2715RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2716{
2717 PyInt size;
2718 PyInt len_change;
2719
2720 /* Self must be a valid buffer */
2721 if (CheckBuffer(self))
2722 return -1;
2723
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002724 if (end == -1)
2725 end = self->buf->b_ml.ml_line_count;
2726
Bram Moolenaar19e60942011-06-19 00:27:51 +02002727 /* Sort out the slice range */
2728 size = end - start + 1;
2729
2730 if (lo < 0)
2731 lo = 0;
2732 else if (lo > size)
2733 lo = size;
2734 if (hi < 0)
2735 hi = 0;
2736 if (hi < lo)
2737 hi = lo;
2738 else if (hi > size)
2739 hi = size;
2740
2741 if (SetBufferLineList(self->buf, lo + start, hi + start,
2742 val, &len_change) == FAIL)
2743 return -1;
2744
2745 if (new_end)
2746 *new_end = end + len_change;
2747
2748 return 0;
2749}
2750
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002751
2752 static PyObject *
2753RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2754{
2755 PyObject *lines;
2756 PyInt len_change;
2757 PyInt max;
2758 PyInt n;
2759
2760 if (CheckBuffer(self))
2761 return NULL;
2762
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002763 if (end == -1)
2764 end = self->buf->b_ml.ml_line_count;
2765
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002766 max = n = end - start + 1;
2767
2768 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2769 return NULL;
2770
2771 if (n < 0 || n > max)
2772 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02002773 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002774 return NULL;
2775 }
2776
2777 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2778 return NULL;
2779
2780 if (new_end)
2781 *new_end = end + len_change;
2782
2783 Py_INCREF(Py_None);
2784 return Py_None;
2785}
2786
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002787/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002788 */
2789
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002790static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002791static PySequenceMethods RangeAsSeq;
2792static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002793
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002794typedef struct
2795{
2796 PyObject_HEAD
2797 BufferObject *buf;
2798 PyInt start;
2799 PyInt end;
2800} RangeObject;
2801
2802 static PyObject *
2803RangeNew(buf_T *buf, PyInt start, PyInt end)
2804{
2805 BufferObject *bufr;
2806 RangeObject *self;
2807 self = PyObject_NEW(RangeObject, &RangeType);
2808 if (self == NULL)
2809 return NULL;
2810
2811 bufr = (BufferObject *)BufferNew(buf);
2812 if (bufr == NULL)
2813 {
2814 Py_DECREF(self);
2815 return NULL;
2816 }
2817 Py_INCREF(bufr);
2818
2819 self->buf = bufr;
2820 self->start = start;
2821 self->end = end;
2822
2823 return (PyObject *)(self);
2824}
2825
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002826 static void
2827RangeDestructor(PyObject *self)
2828{
2829 Py_DECREF(((RangeObject *)(self))->buf);
2830 DESTRUCTOR_FINISH(self);
2831}
2832
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002833 static PyInt
2834RangeLength(PyObject *self)
2835{
2836 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2837 if (CheckBuffer(((RangeObject *)(self))->buf))
2838 return -1; /* ??? */
2839
2840 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2841}
2842
2843 static PyObject *
2844RangeItem(PyObject *self, PyInt n)
2845{
2846 return RBItem(((RangeObject *)(self))->buf, n,
2847 ((RangeObject *)(self))->start,
2848 ((RangeObject *)(self))->end);
2849}
2850
2851 static PyObject *
2852RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2853{
2854 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2855 ((RangeObject *)(self))->start,
2856 ((RangeObject *)(self))->end);
2857}
2858
2859 static PyObject *
2860RangeAppend(PyObject *self, PyObject *args)
2861{
2862 return RBAppend(((RangeObject *)(self))->buf, args,
2863 ((RangeObject *)(self))->start,
2864 ((RangeObject *)(self))->end,
2865 &((RangeObject *)(self))->end);
2866}
2867
2868 static PyObject *
2869RangeRepr(PyObject *self)
2870{
2871 static char repr[100];
2872 RangeObject *this = (RangeObject *)(self);
2873
2874 if (this->buf->buf == INVALID_BUFFER_VALUE)
2875 {
2876 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2877 (self));
2878 return PyString_FromString(repr);
2879 }
2880 else
2881 {
2882 char *name = (char *)this->buf->buf->b_fname;
2883 int len;
2884
2885 if (name == NULL)
2886 name = "";
2887 len = (int)strlen(name);
2888
2889 if (len > 45)
2890 name = name + (45 - len);
2891
2892 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2893 len > 45 ? "..." : "", name,
2894 this->start, this->end);
2895
2896 return PyString_FromString(repr);
2897 }
2898}
2899
2900static struct PyMethodDef RangeMethods[] = {
2901 /* name, function, calling, documentation */
2902 {"append", RangeAppend, 1, "Append data to the Vim range" },
2903 { NULL, NULL, 0, NULL }
2904};
2905
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002906static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002907static PySequenceMethods BufferAsSeq;
2908static PyMappingMethods BufferAsMapping;
2909
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002910 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002911BufferNew(buf_T *buf)
2912{
2913 /* We need to handle deletion of buffers underneath us.
2914 * If we add a "b_python*_ref" field to the buf_T structure,
2915 * then we can get at it in buf_freeall() in vim. We then
2916 * need to create only ONE Python object per buffer - if
2917 * we try to create a second, just INCREF the existing one
2918 * and return it. The (single) Python object referring to
2919 * the buffer is stored in "b_python*_ref".
2920 * Question: what to do on a buf_freeall(). We'll probably
2921 * have to either delete the Python object (DECREF it to
2922 * zero - a bad idea, as it leaves dangling refs!) or
2923 * set the buf_T * value to an invalid value (-1?), which
2924 * means we need checks in all access functions... Bah.
2925 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002926 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02002927 * b_python_ref and b_python3_ref fields respectively.
2928 */
2929
2930 BufferObject *self;
2931
2932 if (BUF_PYTHON_REF(buf) != NULL)
2933 {
2934 self = BUF_PYTHON_REF(buf);
2935 Py_INCREF(self);
2936 }
2937 else
2938 {
2939 self = PyObject_NEW(BufferObject, &BufferType);
2940 if (self == NULL)
2941 return NULL;
2942 self->buf = buf;
2943 BUF_PYTHON_REF(buf) = self;
2944 }
2945
2946 return (PyObject *)(self);
2947}
2948
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002949 static void
2950BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002951{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002952 BufferObject *this = (BufferObject *)(self);
2953
2954 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2955 BUF_PYTHON_REF(this->buf) = NULL;
2956
2957 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002958}
2959
Bram Moolenaar971db462013-05-12 18:44:48 +02002960 static PyInt
2961BufferLength(PyObject *self)
2962{
2963 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2964 if (CheckBuffer((BufferObject *)(self)))
2965 return -1; /* ??? */
2966
2967 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2968}
2969
2970 static PyObject *
2971BufferItem(PyObject *self, PyInt n)
2972{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002973 return RBItem((BufferObject *)(self), n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002974}
2975
2976 static PyObject *
2977BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2978{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002979 return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002980}
2981
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002982 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002983BufferAttr(BufferObject *this, char *name)
2984{
2985 if (strcmp(name, "name") == 0)
2986 return Py_BuildValue("s", this->buf->b_ffname);
2987 else if (strcmp(name, "number") == 0)
2988 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
2989 else if (strcmp(name, "vars") == 0)
2990 return DictionaryNew(this->buf->b_vars);
2991 else if (strcmp(name, "options") == 0)
2992 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2993 (PyObject *) this);
2994 else if (strcmp(name,"__members__") == 0)
2995 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
2996 else
2997 return NULL;
2998}
2999
3000 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003001BufferAppend(PyObject *self, PyObject *args)
3002{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02003003 return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003004}
3005
3006 static PyObject *
3007BufferMark(PyObject *self, PyObject *args)
3008{
3009 pos_T *posp;
3010 char *pmark;
3011 char mark;
3012 buf_T *curbuf_save;
3013
3014 if (CheckBuffer((BufferObject *)(self)))
3015 return NULL;
3016
3017 if (!PyArg_ParseTuple(args, "s", &pmark))
3018 return NULL;
3019 mark = *pmark;
3020
3021 curbuf_save = curbuf;
3022 curbuf = ((BufferObject *)(self))->buf;
3023 posp = getmark(mark, FALSE);
3024 curbuf = curbuf_save;
3025
3026 if (posp == NULL)
3027 {
3028 PyErr_SetVim(_("invalid mark name"));
3029 return NULL;
3030 }
3031
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003032 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003033 if (VimErrorCheck())
3034 return NULL;
3035
3036 if (posp->lnum <= 0)
3037 {
3038 /* Or raise an error? */
3039 Py_INCREF(Py_None);
3040 return Py_None;
3041 }
3042
3043 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
3044}
3045
3046 static PyObject *
3047BufferRange(PyObject *self, PyObject *args)
3048{
3049 PyInt start;
3050 PyInt end;
3051
3052 if (CheckBuffer((BufferObject *)(self)))
3053 return NULL;
3054
3055 if (!PyArg_ParseTuple(args, "nn", &start, &end))
3056 return NULL;
3057
3058 return RangeNew(((BufferObject *)(self))->buf, start, end);
3059}
3060
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003061 static PyObject *
3062BufferRepr(PyObject *self)
3063{
3064 static char repr[100];
3065 BufferObject *this = (BufferObject *)(self);
3066
3067 if (this->buf == INVALID_BUFFER_VALUE)
3068 {
3069 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
3070 return PyString_FromString(repr);
3071 }
3072 else
3073 {
3074 char *name = (char *)this->buf->b_fname;
3075 PyInt len;
3076
3077 if (name == NULL)
3078 name = "";
3079 len = strlen(name);
3080
3081 if (len > 35)
3082 name = name + (35 - len);
3083
3084 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
3085
3086 return PyString_FromString(repr);
3087 }
3088}
3089
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003090static struct PyMethodDef BufferMethods[] = {
3091 /* name, function, calling, documentation */
3092 {"append", BufferAppend, 1, "Append data to Vim buffer" },
3093 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
3094 {"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 +01003095#if PY_VERSION_HEX >= 0x03000000
3096 {"__dir__", BufferDir, 4, "List its attributes" },
3097#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003098 { NULL, NULL, 0, NULL }
3099};
3100
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003101/*
3102 * Buffer list object - Implementation
3103 */
3104
3105static PyTypeObject BufMapType;
3106
3107typedef struct
3108{
3109 PyObject_HEAD
3110} BufMapObject;
3111
3112 static PyInt
3113BufMapLength(PyObject *self UNUSED)
3114{
3115 buf_T *b = firstbuf;
3116 PyInt n = 0;
3117
3118 while (b)
3119 {
3120 ++n;
3121 b = b->b_next;
3122 }
3123
3124 return n;
3125}
3126
3127 static PyObject *
3128BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
3129{
3130 buf_T *b;
3131 int bnr;
3132
3133#if PY_MAJOR_VERSION < 3
3134 if (PyInt_Check(keyObject))
3135 bnr = PyInt_AsLong(keyObject);
3136 else
3137#endif
3138 if (PyLong_Check(keyObject))
3139 bnr = PyLong_AsLong(keyObject);
3140 else
3141 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003142 PyErr_SetString(PyExc_TypeError, _("key must be integer"));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003143 return NULL;
3144 }
3145
3146 b = buflist_findnr(bnr);
3147
3148 if (b)
3149 return BufferNew(b);
3150 else
3151 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003152 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003153 return NULL;
3154 }
3155}
3156
3157 static void
3158BufMapIterDestruct(PyObject *buffer)
3159{
3160 /* Iteration was stopped before all buffers were processed */
3161 if (buffer)
3162 {
3163 Py_DECREF(buffer);
3164 }
3165}
3166
3167 static PyObject *
3168BufMapIterNext(PyObject **buffer)
3169{
3170 PyObject *next;
3171 PyObject *r;
3172
3173 if (!*buffer)
3174 return NULL;
3175
3176 r = *buffer;
3177
3178 if (CheckBuffer((BufferObject *)(r)))
3179 {
3180 *buffer = NULL;
3181 return NULL;
3182 }
3183
3184 if (!((BufferObject *)(r))->buf->b_next)
3185 next = NULL;
3186 else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
3187 return NULL;
3188 *buffer = next;
3189 /* Do not increment reference: we no longer hold it (decref), but whoever on
3190 * other side will hold (incref). Decref+incref = nothing.
3191 */
3192 return r;
3193}
3194
3195 static PyObject *
3196BufMapIter(PyObject *self UNUSED)
3197{
3198 PyObject *buffer;
3199
3200 buffer = BufferNew(firstbuf);
3201 return IterNew(buffer,
3202 (destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext);
3203}
3204
3205static PyMappingMethods BufMapAsMapping = {
3206 (lenfunc) BufMapLength,
3207 (binaryfunc) BufMapItem,
3208 (objobjargproc) 0,
3209};
3210
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003211/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003212 */
3213
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003214 static PyObject *
3215CurrentGetattr(PyObject *self UNUSED, char *name)
3216{
3217 if (strcmp(name, "buffer") == 0)
3218 return (PyObject *)BufferNew(curbuf);
3219 else if (strcmp(name, "window") == 0)
3220 return (PyObject *)WindowNew(curwin);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003221 else if (strcmp(name, "tabpage") == 0)
3222 return (PyObject *)TabPageNew(curtab);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003223 else if (strcmp(name, "line") == 0)
3224 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3225 else if (strcmp(name, "range") == 0)
3226 return RangeNew(curbuf, RangeStart, RangeEnd);
3227 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003228 return Py_BuildValue("[sssss]", "buffer", "window", "line", "range",
3229 "tabpage");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003230 else
3231 {
3232 PyErr_SetString(PyExc_AttributeError, name);
3233 return NULL;
3234 }
3235}
3236
3237 static int
3238CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3239{
3240 if (strcmp(name, "line") == 0)
3241 {
3242 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3243 return -1;
3244
3245 return 0;
3246 }
3247 else
3248 {
3249 PyErr_SetString(PyExc_AttributeError, name);
3250 return -1;
3251 }
3252}
3253
Bram Moolenaardb913952012-06-29 12:54:53 +02003254 static void
3255set_ref_in_py(const int copyID)
3256{
3257 pylinkedlist_T *cur;
3258 dict_T *dd;
3259 list_T *ll;
3260
3261 if (lastdict != NULL)
3262 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3263 {
3264 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3265 if (dd->dv_copyID != copyID)
3266 {
3267 dd->dv_copyID = copyID;
3268 set_ref_in_ht(&dd->dv_hashtab, copyID);
3269 }
3270 }
3271
3272 if (lastlist != NULL)
3273 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3274 {
3275 ll = ((ListObject *) (cur->pll_obj))->list;
3276 if (ll->lv_copyID != copyID)
3277 {
3278 ll->lv_copyID = copyID;
3279 set_ref_in_list(ll, copyID);
3280 }
3281 }
3282}
3283
3284 static int
3285set_string_copy(char_u *str, typval_T *tv)
3286{
3287 tv->vval.v_string = vim_strsave(str);
3288 if (tv->vval.v_string == NULL)
3289 {
3290 PyErr_NoMemory();
3291 return -1;
3292 }
3293 return 0;
3294}
3295
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003296 static int
3297pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3298{
3299 dict_T *d;
3300 char_u *key;
3301 dictitem_T *di;
3302 PyObject *keyObject;
3303 PyObject *valObject;
3304 Py_ssize_t iter = 0;
3305
3306 d = dict_alloc();
3307 if (d == NULL)
3308 {
3309 PyErr_NoMemory();
3310 return -1;
3311 }
3312
3313 tv->v_type = VAR_DICT;
3314 tv->vval.v_dict = d;
3315
3316 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
3317 {
3318 DICTKEY_DECL
3319
3320 if (keyObject == NULL)
3321 return -1;
3322 if (valObject == NULL)
3323 return -1;
3324
3325 DICTKEY_GET_NOTEMPTY(-1)
3326
3327 di = dictitem_alloc(key);
3328
3329 DICTKEY_UNREF
3330
3331 if (di == NULL)
3332 {
3333 PyErr_NoMemory();
3334 return -1;
3335 }
3336 di->di_tv.v_lock = 0;
3337
3338 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3339 {
3340 vim_free(di);
3341 return -1;
3342 }
3343 if (dict_add(d, di) == FAIL)
3344 {
3345 vim_free(di);
3346 PyErr_SetVim(_("failed to add key to dictionary"));
3347 return -1;
3348 }
3349 }
3350 return 0;
3351}
3352
3353 static int
3354pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3355{
3356 dict_T *d;
3357 char_u *key;
3358 dictitem_T *di;
3359 PyObject *list;
3360 PyObject *litem;
3361 PyObject *keyObject;
3362 PyObject *valObject;
3363 Py_ssize_t lsize;
3364
3365 d = dict_alloc();
3366 if (d == NULL)
3367 {
3368 PyErr_NoMemory();
3369 return -1;
3370 }
3371
3372 tv->v_type = VAR_DICT;
3373 tv->vval.v_dict = d;
3374
3375 list = PyMapping_Items(obj);
3376 if (list == NULL)
3377 return -1;
3378 lsize = PyList_Size(list);
3379 while (lsize--)
3380 {
3381 DICTKEY_DECL
3382
3383 litem = PyList_GetItem(list, lsize);
3384 if (litem == NULL)
3385 {
3386 Py_DECREF(list);
3387 return -1;
3388 }
3389
3390 keyObject = PyTuple_GetItem(litem, 0);
3391 if (keyObject == NULL)
3392 {
3393 Py_DECREF(list);
3394 Py_DECREF(litem);
3395 return -1;
3396 }
3397
3398 DICTKEY_GET_NOTEMPTY(-1)
3399
3400 valObject = PyTuple_GetItem(litem, 1);
3401 if (valObject == NULL)
3402 {
3403 Py_DECREF(list);
3404 Py_DECREF(litem);
3405 return -1;
3406 }
3407
3408 di = dictitem_alloc(key);
3409
3410 DICTKEY_UNREF
3411
3412 if (di == NULL)
3413 {
3414 Py_DECREF(list);
3415 Py_DECREF(litem);
3416 PyErr_NoMemory();
3417 return -1;
3418 }
3419 di->di_tv.v_lock = 0;
3420
3421 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3422 {
3423 vim_free(di);
3424 Py_DECREF(list);
3425 Py_DECREF(litem);
3426 return -1;
3427 }
3428 if (dict_add(d, di) == FAIL)
3429 {
3430 vim_free(di);
3431 Py_DECREF(list);
3432 Py_DECREF(litem);
3433 PyErr_SetVim(_("failed to add key to dictionary"));
3434 return -1;
3435 }
3436 Py_DECREF(litem);
3437 }
3438 Py_DECREF(list);
3439 return 0;
3440}
3441
3442 static int
3443pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3444{
3445 list_T *l;
3446
3447 l = list_alloc();
3448 if (l == NULL)
3449 {
3450 PyErr_NoMemory();
3451 return -1;
3452 }
3453
3454 tv->v_type = VAR_LIST;
3455 tv->vval.v_list = l;
3456
3457 if (list_py_concat(l, obj, lookupDict) == -1)
3458 return -1;
3459
3460 return 0;
3461}
3462
3463 static int
3464pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3465{
3466 PyObject *iterator = PyObject_GetIter(obj);
3467 PyObject *item;
3468 list_T *l;
3469 listitem_T *li;
3470
3471 l = list_alloc();
3472
3473 if (l == NULL)
3474 {
3475 PyErr_NoMemory();
3476 return -1;
3477 }
3478
3479 tv->vval.v_list = l;
3480 tv->v_type = VAR_LIST;
3481
3482
3483 if (iterator == NULL)
3484 return -1;
3485
3486 while ((item = PyIter_Next(obj)))
3487 {
3488 li = listitem_alloc();
3489 if (li == NULL)
3490 {
3491 PyErr_NoMemory();
3492 return -1;
3493 }
3494 li->li_tv.v_lock = 0;
3495
3496 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3497 return -1;
3498
3499 list_append(l, li);
3500
3501 Py_DECREF(item);
3502 }
3503
3504 Py_DECREF(iterator);
3505 return 0;
3506}
3507
Bram Moolenaardb913952012-06-29 12:54:53 +02003508typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3509
3510 static int
3511convert_dl(PyObject *obj, typval_T *tv,
3512 pytotvfunc py_to_tv, PyObject *lookupDict)
3513{
3514 PyObject *capsule;
3515 char hexBuf[sizeof(void *) * 2 + 3];
3516
3517 sprintf(hexBuf, "%p", obj);
3518
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003519# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003520 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003521# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003522 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003523# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003524 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003525 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003526# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003527 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003528# else
3529 capsule = PyCObject_FromVoidPtr(tv, NULL);
3530# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003531 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3532 Py_DECREF(capsule);
3533 if (py_to_tv(obj, tv, lookupDict) == -1)
3534 {
3535 tv->v_type = VAR_UNKNOWN;
3536 return -1;
3537 }
3538 /* As we are not using copy_tv which increments reference count we must
3539 * do it ourself. */
3540 switch(tv->v_type)
3541 {
3542 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3543 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3544 }
3545 }
3546 else
3547 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003548 typval_T *v;
3549
3550# ifdef PY_USE_CAPSULE
3551 v = PyCapsule_GetPointer(capsule, NULL);
3552# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003553 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003554# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003555 copy_tv(v, tv);
3556 }
3557 return 0;
3558}
3559
3560 static int
3561ConvertFromPyObject(PyObject *obj, typval_T *tv)
3562{
3563 PyObject *lookup_dict;
3564 int r;
3565
3566 lookup_dict = PyDict_New();
3567 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3568 Py_DECREF(lookup_dict);
3569 return r;
3570}
3571
3572 static int
3573_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3574{
3575 if (obj->ob_type == &DictionaryType)
3576 {
3577 tv->v_type = VAR_DICT;
3578 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3579 ++tv->vval.v_dict->dv_refcount;
3580 }
3581 else if (obj->ob_type == &ListType)
3582 {
3583 tv->v_type = VAR_LIST;
3584 tv->vval.v_list = (((ListObject *)(obj))->list);
3585 ++tv->vval.v_list->lv_refcount;
3586 }
3587 else if (obj->ob_type == &FunctionType)
3588 {
3589 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3590 return -1;
3591
3592 tv->v_type = VAR_FUNC;
3593 func_ref(tv->vval.v_string);
3594 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003595 else if (PyBytes_Check(obj))
3596 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003597 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003598
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003599 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3600 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003601 if (result == NULL)
3602 return -1;
3603
3604 if (set_string_copy(result, tv) == -1)
3605 return -1;
3606
3607 tv->v_type = VAR_STRING;
3608 }
3609 else if (PyUnicode_Check(obj))
3610 {
3611 PyObject *bytes;
3612 char_u *result;
3613
Bram Moolenaardb913952012-06-29 12:54:53 +02003614 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3615 if (bytes == NULL)
3616 return -1;
3617
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003618 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3619 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003620 if (result == NULL)
3621 return -1;
3622
3623 if (set_string_copy(result, tv) == -1)
3624 {
3625 Py_XDECREF(bytes);
3626 return -1;
3627 }
3628 Py_XDECREF(bytes);
3629
3630 tv->v_type = VAR_STRING;
3631 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003632#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003633 else if (PyInt_Check(obj))
3634 {
3635 tv->v_type = VAR_NUMBER;
3636 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3637 }
3638#endif
3639 else if (PyLong_Check(obj))
3640 {
3641 tv->v_type = VAR_NUMBER;
3642 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3643 }
3644 else if (PyDict_Check(obj))
3645 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3646#ifdef FEAT_FLOAT
3647 else if (PyFloat_Check(obj))
3648 {
3649 tv->v_type = VAR_FLOAT;
3650 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3651 }
3652#endif
3653 else if (PyIter_Check(obj))
3654 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3655 else if (PySequence_Check(obj))
3656 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3657 else if (PyMapping_Check(obj))
3658 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3659 else
3660 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003661 PyErr_SetString(PyExc_TypeError,
3662 _("unable to convert to vim structure"));
Bram Moolenaardb913952012-06-29 12:54:53 +02003663 return -1;
3664 }
3665 return 0;
3666}
3667
3668 static PyObject *
3669ConvertToPyObject(typval_T *tv)
3670{
3671 if (tv == NULL)
3672 {
3673 PyErr_SetVim(_("NULL reference passed"));
3674 return NULL;
3675 }
3676 switch (tv->v_type)
3677 {
3678 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003679 return PyBytes_FromString(tv->vval.v_string == NULL
3680 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003681 case VAR_NUMBER:
3682 return PyLong_FromLong((long) tv->vval.v_number);
3683#ifdef FEAT_FLOAT
3684 case VAR_FLOAT:
3685 return PyFloat_FromDouble((double) tv->vval.v_float);
3686#endif
3687 case VAR_LIST:
3688 return ListNew(tv->vval.v_list);
3689 case VAR_DICT:
3690 return DictionaryNew(tv->vval.v_dict);
3691 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003692 return FunctionNew(tv->vval.v_string == NULL
3693 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003694 case VAR_UNKNOWN:
3695 Py_INCREF(Py_None);
3696 return Py_None;
3697 default:
3698 PyErr_SetVim(_("internal error: invalid value type"));
3699 return NULL;
3700 }
3701}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003702
3703typedef struct
3704{
3705 PyObject_HEAD
3706} CurrentObject;
3707static PyTypeObject CurrentType;
3708
3709 static void
3710init_structs(void)
3711{
3712 vim_memset(&OutputType, 0, sizeof(OutputType));
3713 OutputType.tp_name = "vim.message";
3714 OutputType.tp_basicsize = sizeof(OutputObject);
3715 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3716 OutputType.tp_doc = "vim message object";
3717 OutputType.tp_methods = OutputMethods;
3718#if PY_MAJOR_VERSION >= 3
3719 OutputType.tp_getattro = OutputGetattro;
3720 OutputType.tp_setattro = OutputSetattro;
3721 OutputType.tp_alloc = call_PyType_GenericAlloc;
3722 OutputType.tp_new = call_PyType_GenericNew;
3723 OutputType.tp_free = call_PyObject_Free;
3724#else
3725 OutputType.tp_getattr = OutputGetattr;
3726 OutputType.tp_setattr = OutputSetattr;
3727#endif
3728
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003729 vim_memset(&IterType, 0, sizeof(IterType));
3730 IterType.tp_name = "vim.iter";
3731 IterType.tp_basicsize = sizeof(IterObject);
3732 IterType.tp_flags = Py_TPFLAGS_DEFAULT;
3733 IterType.tp_doc = "generic iterator object";
3734 IterType.tp_iter = IterIter;
3735 IterType.tp_iternext = IterNext;
3736
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003737 vim_memset(&BufferType, 0, sizeof(BufferType));
3738 BufferType.tp_name = "vim.buffer";
3739 BufferType.tp_basicsize = sizeof(BufferType);
3740 BufferType.tp_dealloc = BufferDestructor;
3741 BufferType.tp_repr = BufferRepr;
3742 BufferType.tp_as_sequence = &BufferAsSeq;
3743 BufferType.tp_as_mapping = &BufferAsMapping;
3744 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3745 BufferType.tp_doc = "vim buffer object";
3746 BufferType.tp_methods = BufferMethods;
3747#if PY_MAJOR_VERSION >= 3
3748 BufferType.tp_getattro = BufferGetattro;
3749 BufferType.tp_alloc = call_PyType_GenericAlloc;
3750 BufferType.tp_new = call_PyType_GenericNew;
3751 BufferType.tp_free = call_PyObject_Free;
3752#else
3753 BufferType.tp_getattr = BufferGetattr;
3754#endif
3755
3756 vim_memset(&WindowType, 0, sizeof(WindowType));
3757 WindowType.tp_name = "vim.window";
3758 WindowType.tp_basicsize = sizeof(WindowObject);
3759 WindowType.tp_dealloc = WindowDestructor;
3760 WindowType.tp_repr = WindowRepr;
3761 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3762 WindowType.tp_doc = "vim Window object";
3763 WindowType.tp_methods = WindowMethods;
3764#if PY_MAJOR_VERSION >= 3
3765 WindowType.tp_getattro = WindowGetattro;
3766 WindowType.tp_setattro = WindowSetattro;
3767 WindowType.tp_alloc = call_PyType_GenericAlloc;
3768 WindowType.tp_new = call_PyType_GenericNew;
3769 WindowType.tp_free = call_PyObject_Free;
3770#else
3771 WindowType.tp_getattr = WindowGetattr;
3772 WindowType.tp_setattr = WindowSetattr;
3773#endif
3774
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003775 vim_memset(&TabPageType, 0, sizeof(TabPageType));
3776 TabPageType.tp_name = "vim.tabpage";
3777 TabPageType.tp_basicsize = sizeof(TabPageObject);
3778 TabPageType.tp_dealloc = TabPageDestructor;
3779 TabPageType.tp_repr = TabPageRepr;
3780 TabPageType.tp_flags = Py_TPFLAGS_DEFAULT;
3781 TabPageType.tp_doc = "vim tab page object";
3782 TabPageType.tp_methods = TabPageMethods;
3783#if PY_MAJOR_VERSION >= 3
3784 TabPageType.tp_getattro = TabPageGetattro;
3785 TabPageType.tp_alloc = call_PyType_GenericAlloc;
3786 TabPageType.tp_new = call_PyType_GenericNew;
3787 TabPageType.tp_free = call_PyObject_Free;
3788#else
3789 TabPageType.tp_getattr = TabPageGetattr;
3790#endif
3791
Bram Moolenaardfa38d42013-05-15 13:38:47 +02003792 vim_memset(&BufMapType, 0, sizeof(BufMapType));
3793 BufMapType.tp_name = "vim.bufferlist";
3794 BufMapType.tp_basicsize = sizeof(BufMapObject);
3795 BufMapType.tp_as_mapping = &BufMapAsMapping;
3796 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003797 BufMapType.tp_iter = BufMapIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003798 BufferType.tp_doc = "vim buffer list";
3799
3800 vim_memset(&WinListType, 0, sizeof(WinListType));
3801 WinListType.tp_name = "vim.windowlist";
3802 WinListType.tp_basicsize = sizeof(WinListType);
3803 WinListType.tp_as_sequence = &WinListAsSeq;
3804 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3805 WinListType.tp_doc = "vim window list";
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003806 WinListType.tp_dealloc = WinListDestructor;
3807
3808 vim_memset(&TabListType, 0, sizeof(TabListType));
3809 TabListType.tp_name = "vim.tabpagelist";
3810 TabListType.tp_basicsize = sizeof(TabListType);
3811 TabListType.tp_as_sequence = &TabListAsSeq;
3812 TabListType.tp_flags = Py_TPFLAGS_DEFAULT;
3813 TabListType.tp_doc = "vim tab page list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003814
3815 vim_memset(&RangeType, 0, sizeof(RangeType));
3816 RangeType.tp_name = "vim.range";
3817 RangeType.tp_basicsize = sizeof(RangeObject);
3818 RangeType.tp_dealloc = RangeDestructor;
3819 RangeType.tp_repr = RangeRepr;
3820 RangeType.tp_as_sequence = &RangeAsSeq;
3821 RangeType.tp_as_mapping = &RangeAsMapping;
3822 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3823 RangeType.tp_doc = "vim Range object";
3824 RangeType.tp_methods = RangeMethods;
3825#if PY_MAJOR_VERSION >= 3
3826 RangeType.tp_getattro = RangeGetattro;
3827 RangeType.tp_alloc = call_PyType_GenericAlloc;
3828 RangeType.tp_new = call_PyType_GenericNew;
3829 RangeType.tp_free = call_PyObject_Free;
3830#else
3831 RangeType.tp_getattr = RangeGetattr;
3832#endif
3833
3834 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3835 CurrentType.tp_name = "vim.currentdata";
3836 CurrentType.tp_basicsize = sizeof(CurrentObject);
3837 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3838 CurrentType.tp_doc = "vim current object";
3839#if PY_MAJOR_VERSION >= 3
3840 CurrentType.tp_getattro = CurrentGetattro;
3841 CurrentType.tp_setattro = CurrentSetattro;
3842#else
3843 CurrentType.tp_getattr = CurrentGetattr;
3844 CurrentType.tp_setattr = CurrentSetattr;
3845#endif
3846
3847 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3848 DictionaryType.tp_name = "vim.dictionary";
3849 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3850 DictionaryType.tp_dealloc = DictionaryDestructor;
3851 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3852 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3853 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3854 DictionaryType.tp_methods = DictionaryMethods;
3855#if PY_MAJOR_VERSION >= 3
3856 DictionaryType.tp_getattro = DictionaryGetattro;
3857 DictionaryType.tp_setattro = DictionarySetattro;
3858#else
3859 DictionaryType.tp_getattr = DictionaryGetattr;
3860 DictionaryType.tp_setattr = DictionarySetattr;
3861#endif
3862
3863 vim_memset(&ListType, 0, sizeof(ListType));
3864 ListType.tp_name = "vim.list";
3865 ListType.tp_dealloc = ListDestructor;
3866 ListType.tp_basicsize = sizeof(ListObject);
3867 ListType.tp_as_sequence = &ListAsSeq;
3868 ListType.tp_as_mapping = &ListAsMapping;
3869 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3870 ListType.tp_doc = "list pushing modifications to vim structure";
3871 ListType.tp_methods = ListMethods;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003872 ListType.tp_iter = ListIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003873#if PY_MAJOR_VERSION >= 3
3874 ListType.tp_getattro = ListGetattro;
3875 ListType.tp_setattro = ListSetattro;
3876#else
3877 ListType.tp_getattr = ListGetattr;
3878 ListType.tp_setattr = ListSetattr;
3879#endif
3880
3881 vim_memset(&FunctionType, 0, sizeof(FunctionType));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003882 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003883 FunctionType.tp_basicsize = sizeof(FunctionObject);
3884 FunctionType.tp_dealloc = FunctionDestructor;
3885 FunctionType.tp_call = FunctionCall;
3886 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3887 FunctionType.tp_doc = "object that calls vim function";
3888 FunctionType.tp_methods = FunctionMethods;
3889#if PY_MAJOR_VERSION >= 3
3890 FunctionType.tp_getattro = FunctionGetattro;
3891#else
3892 FunctionType.tp_getattr = FunctionGetattr;
3893#endif
3894
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003895 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3896 OptionsType.tp_name = "vim.options";
3897 OptionsType.tp_basicsize = sizeof(OptionsObject);
3898 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3899 OptionsType.tp_doc = "object for manipulating options";
3900 OptionsType.tp_as_mapping = &OptionsAsMapping;
3901 OptionsType.tp_dealloc = OptionsDestructor;
3902
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003903#if PY_MAJOR_VERSION >= 3
3904 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3905 vimmodule.m_name = "vim";
3906 vimmodule.m_doc = "Vim Python interface\n";
3907 vimmodule.m_size = -1;
3908 vimmodule.m_methods = VimMethods;
3909#endif
3910}