blob: 6370bd18a2fb05a35287a3c965baeefafd0a01c0 [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))
30
31static int ConvertFromPyObject(PyObject *, typval_T *);
32static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
33
34static PyInt RangeStart;
35static PyInt RangeEnd;
36
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020037/*
38 * obtain a lock on the Vim data structures
39 */
40 static void
41Python_Lock_Vim(void)
42{
43}
44
45/*
46 * release a lock on the Vim data structures
47 */
48 static void
49Python_Release_Vim(void)
50{
51}
52
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020053/* Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020054 */
55
Bram Moolenaar2eea1982010-09-21 16:49:37 +020056/* Function to write a line, points to either msg() or emsg(). */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020057typedef void (*writefn)(char_u *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020058
59static PyTypeObject OutputType;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020060
61typedef struct
62{
63 PyObject_HEAD
64 long softspace;
65 long error;
66} OutputObject;
67
Bram Moolenaar77045652012-09-21 13:46:06 +020068 static int
69OutputSetattr(PyObject *self, char *name, PyObject *val)
70{
71 if (val == NULL)
72 {
73 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes"));
74 return -1;
75 }
76
77 if (strcmp(name, "softspace") == 0)
78 {
79 if (!PyInt_Check(val))
80 {
81 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
82 return -1;
83 }
84
85 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
86 return 0;
87 }
88
89 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
90 return -1;
91}
92
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020093/* Buffer IO, we write one whole line at a time. */
94static garray_T io_ga = {0, 0, 1, 80, NULL};
95static writefn old_fn = NULL;
96
97 static void
98PythonIO_Flush(void)
99{
100 if (old_fn != NULL && io_ga.ga_len > 0)
101 {
102 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
103 old_fn((char_u *)io_ga.ga_data);
104 }
105 io_ga.ga_len = 0;
106}
107
108 static void
109writer(writefn fn, char_u *str, PyInt n)
110{
111 char_u *ptr;
112
113 /* Flush when switching output function. */
114 if (fn != old_fn)
115 PythonIO_Flush();
116 old_fn = fn;
117
118 /* Write each NL separated line. Text after the last NL is kept for
119 * writing later. */
120 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
121 {
122 PyInt len = ptr - str;
123
124 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
125 break;
126
127 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
128 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
129 fn((char_u *)io_ga.ga_data);
130 str = ptr + 1;
131 n -= len + 1;
132 io_ga.ga_len = 0;
133 }
134
135 /* Put the remaining text into io_ga for later printing. */
136 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
137 {
138 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
139 io_ga.ga_len += (int)n;
140 }
141}
142
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200143 static PyObject *
144OutputWrite(PyObject *self, PyObject *args)
145{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200146 Py_ssize_t len = 0;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200147 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200148 int error = ((OutputObject *)(self))->error;
149
Bram Moolenaar27564802011-09-07 19:30:21 +0200150 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200151 return NULL;
152
153 Py_BEGIN_ALLOW_THREADS
154 Python_Lock_Vim();
155 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
156 Python_Release_Vim();
157 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200158 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200159
160 Py_INCREF(Py_None);
161 return Py_None;
162}
163
164 static PyObject *
165OutputWritelines(PyObject *self, PyObject *args)
166{
167 PyInt n;
168 PyInt i;
169 PyObject *list;
170 int error = ((OutputObject *)(self))->error;
171
172 if (!PyArg_ParseTuple(args, "O", &list))
173 return NULL;
174 Py_INCREF(list);
175
Bram Moolenaardb913952012-06-29 12:54:53 +0200176 if (!PyList_Check(list))
177 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200178 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
179 Py_DECREF(list);
180 return NULL;
181 }
182
183 n = PyList_Size(list);
184
185 for (i = 0; i < n; ++i)
186 {
187 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200188 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200189 PyInt len;
190
Bram Moolenaardb913952012-06-29 12:54:53 +0200191 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
192 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200193 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
194 Py_DECREF(list);
195 return NULL;
196 }
197
198 Py_BEGIN_ALLOW_THREADS
199 Python_Lock_Vim();
200 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
201 Python_Release_Vim();
202 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200203 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200204 }
205
206 Py_DECREF(list);
207 Py_INCREF(Py_None);
208 return Py_None;
209}
210
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100211 static PyObject *
212OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
213{
214 /* do nothing */
215 Py_INCREF(Py_None);
216 return Py_None;
217}
218
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200219/***************/
220
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200221static struct PyMethodDef OutputMethods[] = {
222 /* name, function, calling, documentation */
223 {"write", OutputWrite, 1, ""},
224 {"writelines", OutputWritelines, 1, ""},
225 {"flush", OutputFlush, 1, ""},
226 { NULL, NULL, 0, NULL}
227};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200228
229static OutputObject Output =
230{
231 PyObject_HEAD_INIT(&OutputType)
232 0,
233 0
234};
235
236static OutputObject Error =
237{
238 PyObject_HEAD_INIT(&OutputType)
239 0,
240 1
241};
242
243 static int
244PythonIO_Init_io(void)
245{
246 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
247 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
248
249 if (PyErr_Occurred())
250 {
251 EMSG(_("E264: Python: Error initialising I/O objects"));
252 return -1;
253 }
254
255 return 0;
256}
257
258
259static PyObject *VimError;
260
261/* Check to see whether a Vim error has been reported, or a keyboard
262 * interrupt has been detected.
263 */
264 static int
265VimErrorCheck(void)
266{
267 if (got_int)
268 {
269 PyErr_SetNone(PyExc_KeyboardInterrupt);
270 return 1;
271 }
272 else if (did_emsg && !PyErr_Occurred())
273 {
274 PyErr_SetNone(VimError);
275 return 1;
276 }
277
278 return 0;
279}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200280
281/* Vim module - Implementation
282 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200283
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200284 static PyObject *
285VimCommand(PyObject *self UNUSED, PyObject *args)
286{
287 char *cmd;
288 PyObject *result;
289
290 if (!PyArg_ParseTuple(args, "s", &cmd))
291 return NULL;
292
293 PyErr_Clear();
294
295 Py_BEGIN_ALLOW_THREADS
296 Python_Lock_Vim();
297
298 do_cmdline_cmd((char_u *)cmd);
299 update_screen(VALID);
300
301 Python_Release_Vim();
302 Py_END_ALLOW_THREADS
303
304 if (VimErrorCheck())
305 result = NULL;
306 else
307 result = Py_None;
308
309 Py_XINCREF(result);
310 return result;
311}
312
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200313/*
314 * Function to translate a typval_T into a PyObject; this will recursively
315 * translate lists/dictionaries into their Python equivalents.
316 *
317 * The depth parameter is to avoid infinite recursion, set it to 1 when
318 * you call VimToPython.
319 */
320 static PyObject *
321VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
322{
323 PyObject *result;
324 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200325 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200326
327 /* Avoid infinite recursion */
328 if (depth > 100)
329 {
330 Py_INCREF(Py_None);
331 result = Py_None;
332 return result;
333 }
334
335 /* Check if we run into a recursive loop. The item must be in lookupDict
336 * then and we can use it again. */
337 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
338 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
339 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200340 sprintf(ptrBuf, "%p",
341 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
342 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200343 result = PyDict_GetItemString(lookupDict, ptrBuf);
344 if (result != NULL)
345 {
346 Py_INCREF(result);
347 return result;
348 }
349 }
350
351 if (our_tv->v_type == VAR_STRING)
352 {
Bram Moolenaard1f13fd2012-10-05 21:30:07 +0200353 result = Py_BuildValue("s", our_tv->vval.v_string == NULL
354 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200355 }
356 else if (our_tv->v_type == VAR_NUMBER)
357 {
358 char buf[NUMBUFLEN];
359
360 /* For backwards compatibility numbers are stored as strings. */
361 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
362 result = Py_BuildValue("s", buf);
363 }
364# ifdef FEAT_FLOAT
365 else if (our_tv->v_type == VAR_FLOAT)
366 {
367 char buf[NUMBUFLEN];
368
369 sprintf(buf, "%f", our_tv->vval.v_float);
370 result = Py_BuildValue("s", buf);
371 }
372# endif
373 else if (our_tv->v_type == VAR_LIST)
374 {
375 list_T *list = our_tv->vval.v_list;
376 listitem_T *curr;
377
378 result = PyList_New(0);
379
380 if (list != NULL)
381 {
382 PyDict_SetItemString(lookupDict, ptrBuf, result);
383
384 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
385 {
386 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
387 PyList_Append(result, newObj);
388 Py_DECREF(newObj);
389 }
390 }
391 }
392 else if (our_tv->v_type == VAR_DICT)
393 {
394 result = PyDict_New();
395
396 if (our_tv->vval.v_dict != NULL)
397 {
398 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
399 long_u todo = ht->ht_used;
400 hashitem_T *hi;
401 dictitem_T *di;
402
403 PyDict_SetItemString(lookupDict, ptrBuf, result);
404
405 for (hi = ht->ht_array; todo > 0; ++hi)
406 {
407 if (!HASHITEM_EMPTY(hi))
408 {
409 --todo;
410
411 di = dict_lookup(hi);
412 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
413 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
414 Py_DECREF(newObj);
415 }
416 }
417 }
418 }
419 else
420 {
421 Py_INCREF(Py_None);
422 result = Py_None;
423 }
424
425 return result;
426}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200427
428 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200429VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200430{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200431 char *expr;
432 typval_T *our_tv;
433 PyObject *result;
434 PyObject *lookup_dict;
435
436 if (!PyArg_ParseTuple(args, "s", &expr))
437 return NULL;
438
439 Py_BEGIN_ALLOW_THREADS
440 Python_Lock_Vim();
441 our_tv = eval_expr((char_u *)expr, NULL);
442
443 Python_Release_Vim();
444 Py_END_ALLOW_THREADS
445
446 if (our_tv == NULL)
447 {
448 PyErr_SetVim(_("invalid expression"));
449 return NULL;
450 }
451
452 /* Convert the Vim type into a Python type. Create a dictionary that's
453 * used to check for recursive loops. */
454 lookup_dict = PyDict_New();
455 result = VimToPython(our_tv, 1, lookup_dict);
456 Py_DECREF(lookup_dict);
457
458
459 Py_BEGIN_ALLOW_THREADS
460 Python_Lock_Vim();
461 free_tv(our_tv);
462 Python_Release_Vim();
463 Py_END_ALLOW_THREADS
464
465 return result;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200466}
467
Bram Moolenaardb913952012-06-29 12:54:53 +0200468static PyObject *ConvertToPyObject(typval_T *);
469
470 static PyObject *
471VimEvalPy(PyObject *self UNUSED, PyObject *args UNUSED)
472{
Bram Moolenaardb913952012-06-29 12:54:53 +0200473 char *expr;
474 typval_T *our_tv;
475 PyObject *result;
476
477 if (!PyArg_ParseTuple(args, "s", &expr))
478 return NULL;
479
480 Py_BEGIN_ALLOW_THREADS
481 Python_Lock_Vim();
482 our_tv = eval_expr((char_u *)expr, NULL);
483
484 Python_Release_Vim();
485 Py_END_ALLOW_THREADS
486
487 if (our_tv == NULL)
488 {
489 PyErr_SetVim(_("invalid expression"));
490 return NULL;
491 }
492
493 result = ConvertToPyObject(our_tv);
494 Py_BEGIN_ALLOW_THREADS
495 Python_Lock_Vim();
496 free_tv(our_tv);
497 Python_Release_Vim();
498 Py_END_ALLOW_THREADS
499
500 return result;
Bram Moolenaardb913952012-06-29 12:54:53 +0200501}
502
503 static PyObject *
504VimStrwidth(PyObject *self UNUSED, PyObject *args)
505{
506 char *expr;
507
508 if (!PyArg_ParseTuple(args, "s", &expr))
509 return NULL;
510
Bram Moolenaara54bf402012-12-05 16:30:07 +0100511 return PyLong_FromLong(
512#ifdef FEAT_MBYTE
513 mb_string2cells((char_u *)expr, (int)STRLEN(expr))
514#else
515 STRLEN(expr)
516#endif
517 );
Bram Moolenaardb913952012-06-29 12:54:53 +0200518}
519
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200520/*
521 * Vim module - Definitions
522 */
523
524static struct PyMethodDef VimMethods[] = {
525 /* name, function, calling, documentation */
526 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
527 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200528 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
529 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200530 { NULL, NULL, 0, NULL }
531};
532
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200533/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200534 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200535 */
536
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200537static PyTypeObject IterType;
538
539typedef PyObject *(*nextfun)(void **);
540typedef void (*destructorfun)(void *);
541
542/* Main purpose of this object is removing the need for do python initialization
543 * (i.e. PyType_Ready and setting type attributes) for a big bunch of objects.
544 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200545
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200546typedef struct
547{
548 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200549 void *cur;
550 nextfun next;
551 destructorfun destruct;
552} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200553
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200554 static PyObject *
555IterNew(void *start, destructorfun destruct, nextfun next)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200556{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200557 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200558
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200559 self = PyObject_NEW(IterObject, &IterType);
560 self->cur = start;
561 self->next = next;
562 self->destruct = destruct;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200563
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200564 return (PyObject *)(self);
565}
566
567 static void
568IterDestructor(PyObject *self)
569{
570 IterObject *this = (IterObject *)(self);
571
572 this->destruct(this->cur);
573
574 DESTRUCTOR_FINISH(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200575}
576
577 static PyObject *
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200578IterNext(PyObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200579{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200580 IterObject *this = (IterObject *)(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200581
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200582 return this->next(&this->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200583}
584
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200585 static PyObject *
586IterIter(PyObject *self)
587{
588 return self;
589}
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200590
Bram Moolenaardb913952012-06-29 12:54:53 +0200591typedef struct pylinkedlist_S {
592 struct pylinkedlist_S *pll_next;
593 struct pylinkedlist_S *pll_prev;
594 PyObject *pll_obj;
595} pylinkedlist_T;
596
597static pylinkedlist_T *lastdict = NULL;
598static pylinkedlist_T *lastlist = NULL;
599
600 static void
601pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
602{
603 if (ref->pll_prev == NULL)
604 {
605 if (ref->pll_next == NULL)
606 {
607 *last = NULL;
608 return;
609 }
610 }
611 else
612 ref->pll_prev->pll_next = ref->pll_next;
613
614 if (ref->pll_next == NULL)
615 *last = ref->pll_prev;
616 else
617 ref->pll_next->pll_prev = ref->pll_prev;
618}
619
620 static void
621pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
622{
623 if (*last == NULL)
624 ref->pll_prev = NULL;
625 else
626 {
627 (*last)->pll_next = ref;
628 ref->pll_prev = *last;
629 }
630 ref->pll_next = NULL;
631 ref->pll_obj = self;
632 *last = ref;
633}
634
635static PyTypeObject DictionaryType;
636
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200637#define DICTKEY_GET_NOTEMPTY(err) \
638 DICTKEY_GET(err) \
639 if (*key == NUL) \
640 { \
641 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
642 return err; \
643 }
644
Bram Moolenaardb913952012-06-29 12:54:53 +0200645typedef struct
646{
647 PyObject_HEAD
648 dict_T *dict;
649 pylinkedlist_T ref;
650} DictionaryObject;
651
652 static PyObject *
653DictionaryNew(dict_T *dict)
654{
655 DictionaryObject *self;
656
657 self = PyObject_NEW(DictionaryObject, &DictionaryType);
658 if (self == NULL)
659 return NULL;
660 self->dict = dict;
661 ++dict->dv_refcount;
662
663 pyll_add((PyObject *)(self), &self->ref, &lastdict);
664
665 return (PyObject *)(self);
666}
667
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200668 static void
669DictionaryDestructor(PyObject *self)
670{
671 DictionaryObject *this = ((DictionaryObject *) (self));
672
673 pyll_remove(&this->ref, &lastdict);
674 dict_unref(this->dict);
675
676 DESTRUCTOR_FINISH(self);
677}
678
Bram Moolenaardb913952012-06-29 12:54:53 +0200679 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200680DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200681{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200682 DictionaryObject *this = (DictionaryObject *)(self);
683
Bram Moolenaar66b79852012-09-21 14:00:35 +0200684 if (val == NULL)
685 {
686 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
687 return -1;
688 }
689
690 if (strcmp(name, "locked") == 0)
691 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200692 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200693 {
694 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
695 return -1;
696 }
697 else
698 {
699 if (!PyBool_Check(val))
700 {
701 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
702 return -1;
703 }
704
705 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200706 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200707 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200708 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200709 }
710 return 0;
711 }
712 else
713 {
714 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
715 return -1;
716 }
717}
718
719 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200720DictionaryLength(PyObject *self)
721{
722 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
723}
724
725 static PyObject *
726DictionaryItem(PyObject *self, PyObject *keyObject)
727{
728 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200729 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200730 DICTKEY_DECL
731
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200732 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200733
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200734 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
735
Bram Moolenaar696c2112012-09-21 13:43:14 +0200736 DICTKEY_UNREF
737
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200738 if (di == NULL)
739 {
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200740 PyErr_SetString(PyExc_KeyError, _("no such key in dictionary"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200741 return NULL;
742 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200743
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200744 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200745}
746
747 static PyInt
748DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
749{
750 char_u *key;
751 typval_T tv;
752 dict_T *d = ((DictionaryObject *)(self))->dict;
753 dictitem_T *di;
754 DICTKEY_DECL
755
756 if (d->dv_lock)
757 {
758 PyErr_SetVim(_("dict is locked"));
759 return -1;
760 }
761
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200762 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200763
764 di = dict_find(d, key, -1);
765
766 if (valObject == NULL)
767 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200768 hashitem_T *hi;
769
Bram Moolenaardb913952012-06-29 12:54:53 +0200770 if (di == NULL)
771 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200772 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200773 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
774 return -1;
775 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200776 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200777 hash_remove(&d->dv_hashtab, hi);
778 dictitem_free(di);
779 return 0;
780 }
781
782 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200783 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200784
785 if (di == NULL)
786 {
787 di = dictitem_alloc(key);
788 if (di == NULL)
789 {
790 PyErr_NoMemory();
791 return -1;
792 }
793 di->di_tv.v_lock = 0;
794
795 if (dict_add(d, di) == FAIL)
796 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200797 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200798 vim_free(di);
799 PyErr_SetVim(_("failed to add key to dictionary"));
800 return -1;
801 }
802 }
803 else
804 clear_tv(&di->di_tv);
805
806 DICTKEY_UNREF
807
808 copy_tv(&tv, &di->di_tv);
809 return 0;
810}
811
812 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100813DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200814{
815 dict_T *dict = ((DictionaryObject *)(self))->dict;
816 long_u todo = dict->dv_hashtab.ht_used;
817 Py_ssize_t i = 0;
818 PyObject *r;
819 hashitem_T *hi;
820
821 r = PyList_New(todo);
822 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
823 {
824 if (!HASHITEM_EMPTY(hi))
825 {
826 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
827 --todo;
828 ++i;
829 }
830 }
831 return r;
832}
833
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200834static PyMappingMethods DictionaryAsMapping = {
835 (lenfunc) DictionaryLength,
836 (binaryfunc) DictionaryItem,
837 (objobjargproc) DictionaryAssItem,
838};
839
Bram Moolenaardb913952012-06-29 12:54:53 +0200840static struct PyMethodDef DictionaryMethods[] = {
841 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
842 { NULL, NULL, 0, NULL }
843};
844
845static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200846static PySequenceMethods ListAsSeq;
847static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200848
849typedef struct
850{
851 PyObject_HEAD
852 list_T *list;
853 pylinkedlist_T ref;
854} ListObject;
855
856 static PyObject *
857ListNew(list_T *list)
858{
859 ListObject *self;
860
861 self = PyObject_NEW(ListObject, &ListType);
862 if (self == NULL)
863 return NULL;
864 self->list = list;
865 ++list->lv_refcount;
866
867 pyll_add((PyObject *)(self), &self->ref, &lastlist);
868
869 return (PyObject *)(self);
870}
871
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200872 static void
873ListDestructor(PyObject *self)
874{
875 ListObject *this = (ListObject *)(self);
876
877 pyll_remove(&this->ref, &lastlist);
878 list_unref(this->list);
879
880 DESTRUCTOR_FINISH(self);
881}
882
Bram Moolenaardb913952012-06-29 12:54:53 +0200883 static int
884list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
885{
886 Py_ssize_t i;
887 Py_ssize_t lsize = PySequence_Size(obj);
888 PyObject *litem;
889 listitem_T *li;
890
891 for(i=0; i<lsize; i++)
892 {
893 li = listitem_alloc();
894 if (li == NULL)
895 {
896 PyErr_NoMemory();
897 return -1;
898 }
899 li->li_tv.v_lock = 0;
900
901 litem = PySequence_GetItem(obj, i);
902 if (litem == NULL)
903 return -1;
904 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
905 return -1;
906
907 list_append(l, li);
908 }
909 return 0;
910}
911
Bram Moolenaardb913952012-06-29 12:54:53 +0200912 static PyInt
913ListLength(PyObject *self)
914{
915 return ((PyInt) (((ListObject *) (self))->list->lv_len));
916}
917
918 static PyObject *
919ListItem(PyObject *self, Py_ssize_t index)
920{
921 listitem_T *li;
922
923 if (index>=ListLength(self))
924 {
925 PyErr_SetString(PyExc_IndexError, "list index out of range");
926 return NULL;
927 }
928 li = list_find(((ListObject *) (self))->list, (long) index);
929 if (li == NULL)
930 {
931 PyErr_SetVim(_("internal error: failed to get vim list item"));
932 return NULL;
933 }
934 return ConvertToPyObject(&li->li_tv);
935}
936
937#define PROC_RANGE \
938 if (last < 0) {\
939 if (last < -size) \
940 last = 0; \
941 else \
942 last += size; \
943 } \
944 if (first < 0) \
945 first = 0; \
946 if (first > size) \
947 first = size; \
948 if (last > size) \
949 last = size;
950
951 static PyObject *
952ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
953{
954 PyInt i;
955 PyInt size = ListLength(self);
956 PyInt n;
957 PyObject *list;
958 int reversed = 0;
959
960 PROC_RANGE
961 if (first >= last)
962 first = last;
963
964 n = last-first;
965 list = PyList_New(n);
966 if (list == NULL)
967 return NULL;
968
969 for (i = 0; i < n; ++i)
970 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200971 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +0200972 if (item == NULL)
973 {
974 Py_DECREF(list);
975 return NULL;
976 }
977
978 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
979 {
980 Py_DECREF(item);
981 Py_DECREF(list);
982 return NULL;
983 }
984 }
985
986 return list;
987}
988
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200989typedef struct
990{
991 listwatch_T lw;
992 list_T *list;
993} listiterinfo_T;
994
995 static void
996ListIterDestruct(listiterinfo_T *lii)
997{
998 list_rem_watch(lii->list, &lii->lw);
999 PyMem_Free(lii);
1000}
1001
1002 static PyObject *
1003ListIterNext(listiterinfo_T **lii)
1004{
1005 PyObject *r;
1006
1007 if (!((*lii)->lw.lw_item))
1008 return NULL;
1009
1010 if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
1011 return NULL;
1012
1013 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
1014
1015 return r;
1016}
1017
1018 static PyObject *
1019ListIter(PyObject *self)
1020{
1021 listiterinfo_T *lii;
1022 list_T *l = ((ListObject *) (self))->list;
1023
1024 if (!(lii = PyMem_New(listiterinfo_T, 1)))
1025 {
1026 PyErr_NoMemory();
1027 return NULL;
1028 }
1029
1030 list_add_watch(l, &lii->lw);
1031 lii->lw.lw_item = l->lv_first;
1032 lii->list = l;
1033
1034 return IterNew(lii,
1035 (destructorfun) ListIterDestruct, (nextfun) ListIterNext);
1036}
1037
Bram Moolenaardb913952012-06-29 12:54:53 +02001038 static int
1039ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1040{
1041 typval_T tv;
1042 list_T *l = ((ListObject *) (self))->list;
1043 listitem_T *li;
1044 Py_ssize_t length = ListLength(self);
1045
1046 if (l->lv_lock)
1047 {
1048 PyErr_SetVim(_("list is locked"));
1049 return -1;
1050 }
1051 if (index>length || (index==length && obj==NULL))
1052 {
1053 PyErr_SetString(PyExc_IndexError, "list index out of range");
1054 return -1;
1055 }
1056
1057 if (obj == NULL)
1058 {
1059 li = list_find(l, (long) index);
1060 list_remove(l, li, li);
1061 clear_tv(&li->li_tv);
1062 vim_free(li);
1063 return 0;
1064 }
1065
1066 if (ConvertFromPyObject(obj, &tv) == -1)
1067 return -1;
1068
1069 if (index == length)
1070 {
1071 if (list_append_tv(l, &tv) == FAIL)
1072 {
1073 PyErr_SetVim(_("Failed to add item to list"));
1074 return -1;
1075 }
1076 }
1077 else
1078 {
1079 li = list_find(l, (long) index);
1080 clear_tv(&li->li_tv);
1081 copy_tv(&tv, &li->li_tv);
1082 }
1083 return 0;
1084}
1085
1086 static int
1087ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1088{
1089 PyInt size = ListLength(self);
1090 Py_ssize_t i;
1091 Py_ssize_t lsize;
1092 PyObject *litem;
1093 listitem_T *li;
1094 listitem_T *next;
1095 typval_T v;
1096 list_T *l = ((ListObject *) (self))->list;
1097
1098 if (l->lv_lock)
1099 {
1100 PyErr_SetVim(_("list is locked"));
1101 return -1;
1102 }
1103
1104 PROC_RANGE
1105
1106 if (first == size)
1107 li = NULL;
1108 else
1109 {
1110 li = list_find(l, (long) first);
1111 if (li == NULL)
1112 {
1113 PyErr_SetVim(_("internal error: no vim list item"));
1114 return -1;
1115 }
1116 if (last > first)
1117 {
1118 i = last - first;
1119 while (i-- && li != NULL)
1120 {
1121 next = li->li_next;
1122 listitem_remove(l, li);
1123 li = next;
1124 }
1125 }
1126 }
1127
1128 if (obj == NULL)
1129 return 0;
1130
1131 if (!PyList_Check(obj))
1132 {
1133 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1134 return -1;
1135 }
1136
1137 lsize = PyList_Size(obj);
1138
1139 for(i=0; i<lsize; i++)
1140 {
1141 litem = PyList_GetItem(obj, i);
1142 if (litem == NULL)
1143 return -1;
1144 if (ConvertFromPyObject(litem, &v) == -1)
1145 return -1;
1146 if (list_insert_tv(l, &v, li) == FAIL)
1147 {
1148 PyErr_SetVim(_("internal error: failed to add item to list"));
1149 return -1;
1150 }
1151 }
1152 return 0;
1153}
1154
1155 static PyObject *
1156ListConcatInPlace(PyObject *self, PyObject *obj)
1157{
1158 list_T *l = ((ListObject *) (self))->list;
1159 PyObject *lookup_dict;
1160
1161 if (l->lv_lock)
1162 {
1163 PyErr_SetVim(_("list is locked"));
1164 return NULL;
1165 }
1166
1167 if (!PySequence_Check(obj))
1168 {
1169 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1170 return NULL;
1171 }
1172
1173 lookup_dict = PyDict_New();
1174 if (list_py_concat(l, obj, lookup_dict) == -1)
1175 {
1176 Py_DECREF(lookup_dict);
1177 return NULL;
1178 }
1179 Py_DECREF(lookup_dict);
1180
1181 Py_INCREF(self);
1182 return self;
1183}
1184
Bram Moolenaar66b79852012-09-21 14:00:35 +02001185 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001186ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001187{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001188 ListObject *this = (ListObject *)(self);
1189
Bram Moolenaar66b79852012-09-21 14:00:35 +02001190 if (val == NULL)
1191 {
1192 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
1193 return -1;
1194 }
1195
1196 if (strcmp(name, "locked") == 0)
1197 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001198 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001199 {
1200 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
1201 return -1;
1202 }
1203 else
1204 {
1205 if (!PyBool_Check(val))
1206 {
1207 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
1208 return -1;
1209 }
1210
1211 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001212 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001213 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001214 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001215 }
1216 return 0;
1217 }
1218 else
1219 {
1220 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
1221 return -1;
1222 }
1223}
1224
Bram Moolenaardb913952012-06-29 12:54:53 +02001225static struct PyMethodDef ListMethods[] = {
1226 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1227 { NULL, NULL, 0, NULL }
1228};
1229
1230typedef struct
1231{
1232 PyObject_HEAD
1233 char_u *name;
1234} FunctionObject;
1235
1236static PyTypeObject FunctionType;
1237
1238 static PyObject *
1239FunctionNew(char_u *name)
1240{
1241 FunctionObject *self;
1242
1243 self = PyObject_NEW(FunctionObject, &FunctionType);
1244 if (self == NULL)
1245 return NULL;
1246 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1247 if (self->name == NULL)
1248 {
1249 PyErr_NoMemory();
1250 return NULL;
1251 }
1252 STRCPY(self->name, name);
1253 func_ref(name);
1254 return (PyObject *)(self);
1255}
1256
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001257 static void
1258FunctionDestructor(PyObject *self)
1259{
1260 FunctionObject *this = (FunctionObject *) (self);
1261
1262 func_unref(this->name);
1263 PyMem_Del(this->name);
1264
1265 DESTRUCTOR_FINISH(self);
1266}
1267
Bram Moolenaardb913952012-06-29 12:54:53 +02001268 static PyObject *
1269FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1270{
1271 FunctionObject *this = (FunctionObject *)(self);
1272 char_u *name = this->name;
1273 typval_T args;
1274 typval_T selfdicttv;
1275 typval_T rettv;
1276 dict_T *selfdict = NULL;
1277 PyObject *selfdictObject;
1278 PyObject *result;
1279 int error;
1280
1281 if (ConvertFromPyObject(argsObject, &args) == -1)
1282 return NULL;
1283
1284 if (kwargs != NULL)
1285 {
1286 selfdictObject = PyDict_GetItemString(kwargs, "self");
1287 if (selfdictObject != NULL)
1288 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001289 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001290 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001291 PyErr_SetString(PyExc_TypeError,
1292 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001293 clear_tv(&args);
1294 return NULL;
1295 }
1296 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1297 return NULL;
1298 selfdict = selfdicttv.vval.v_dict;
1299 }
1300 }
1301
1302 error = func_call(name, &args, selfdict, &rettv);
1303 if (error != OK)
1304 {
1305 result = NULL;
1306 PyErr_SetVim(_("failed to run function"));
1307 }
1308 else
1309 result = ConvertToPyObject(&rettv);
1310
1311 /* FIXME Check what should really be cleared. */
1312 clear_tv(&args);
1313 clear_tv(&rettv);
1314 /*
1315 * if (selfdict!=NULL)
1316 * clear_tv(selfdicttv);
1317 */
1318
1319 return result;
1320}
1321
1322static struct PyMethodDef FunctionMethods[] = {
1323 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1324 { NULL, NULL, 0, NULL }
1325};
1326
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001327/*
1328 * Options object
1329 */
1330
1331static PyTypeObject OptionsType;
1332
1333typedef int (*checkfun)(void *);
1334
1335typedef struct
1336{
1337 PyObject_HEAD
1338 int opt_type;
1339 void *from;
1340 checkfun Check;
1341 PyObject *fromObj;
1342} OptionsObject;
1343
1344 static PyObject *
1345OptionsItem(OptionsObject *this, PyObject *keyObject)
1346{
1347 char_u *key;
1348 int flags;
1349 long numval;
1350 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001351 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001352
1353 if (this->Check(this->from))
1354 return NULL;
1355
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001356 DICTKEY_GET_NOTEMPTY(NULL)
1357
1358 flags = get_option_value_strict(key, &numval, &stringval,
1359 this->opt_type, this->from);
1360
1361 DICTKEY_UNREF
1362
1363 if (flags == 0)
1364 {
1365 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1366 return NULL;
1367 }
1368
1369 if (flags & SOPT_UNSET)
1370 {
1371 Py_INCREF(Py_None);
1372 return Py_None;
1373 }
1374 else if (flags & SOPT_BOOL)
1375 {
1376 PyObject *r;
1377 r = numval ? Py_True : Py_False;
1378 Py_INCREF(r);
1379 return r;
1380 }
1381 else if (flags & SOPT_NUM)
1382 return PyInt_FromLong(numval);
1383 else if (flags & SOPT_STRING)
1384 {
1385 if (stringval)
1386 return PyBytes_FromString((char *) stringval);
1387 else
1388 {
1389 PyErr_SetString(PyExc_ValueError, "Unable to get option value");
1390 return NULL;
1391 }
1392 }
1393 else
1394 {
1395 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1396 return NULL;
1397 }
1398}
1399
1400 static int
1401set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1402 char_u *key;
1403 int numval;
1404 char_u *stringval;
1405 int opt_flags;
1406 int opt_type;
1407 void *from;
1408{
1409 win_T *save_curwin;
1410 tabpage_T *save_curtab;
1411 aco_save_T aco;
1412 int r = 0;
1413
1414 switch (opt_type)
1415 {
1416 case SREQ_WIN:
1417 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1418 == FAIL)
1419 {
1420 PyErr_SetVim("Problem while switching windows.");
1421 return -1;
1422 }
1423 set_option_value(key, numval, stringval, opt_flags);
1424 restore_win(save_curwin, save_curtab);
1425 break;
1426 case SREQ_BUF:
1427 aucmd_prepbuf(&aco, (buf_T *) from);
1428 set_option_value(key, numval, stringval, opt_flags);
1429 aucmd_restbuf(&aco);
1430 break;
1431 case SREQ_GLOBAL:
1432 set_option_value(key, numval, stringval, opt_flags);
1433 break;
1434 }
1435 return r;
1436}
1437
1438 static int
1439OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1440{
1441 char_u *key;
1442 int flags;
1443 int opt_flags;
1444 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001445 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001446
1447 if (this->Check(this->from))
1448 return -1;
1449
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001450 DICTKEY_GET_NOTEMPTY(-1)
1451
1452 flags = get_option_value_strict(key, NULL, NULL,
1453 this->opt_type, this->from);
1454
1455 DICTKEY_UNREF
1456
1457 if (flags == 0)
1458 {
1459 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1460 return -1;
1461 }
1462
1463 if (valObject == NULL)
1464 {
1465 if (this->opt_type == SREQ_GLOBAL)
1466 {
1467 PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
1468 return -1;
1469 }
1470 else if (!(flags & SOPT_GLOBAL))
1471 {
1472 PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
1473 "global value");
1474 return -1;
1475 }
1476 else
1477 {
1478 unset_global_local_option(key, this->from);
1479 return 0;
1480 }
1481 }
1482
1483 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1484
1485 if (flags & SOPT_BOOL)
1486 {
1487 if (!PyBool_Check(valObject))
1488 {
1489 PyErr_SetString(PyExc_ValueError, "Object must be boolean");
1490 return -1;
1491 }
1492
1493 r = set_option_value_for(key, (valObject == Py_True), NULL, opt_flags,
1494 this->opt_type, this->from);
1495 }
1496 else if (flags & SOPT_NUM)
1497 {
1498 int val;
1499
1500#if PY_MAJOR_VERSION < 3
1501 if (PyInt_Check(valObject))
1502 val = PyInt_AsLong(valObject);
1503 else
1504#endif
1505 if (PyLong_Check(valObject))
1506 val = PyLong_AsLong(valObject);
1507 else
1508 {
1509 PyErr_SetString(PyExc_ValueError, "Object must be integer");
1510 return -1;
1511 }
1512
1513 r = set_option_value_for(key, val, NULL, opt_flags,
1514 this->opt_type, this->from);
1515 }
1516 else
1517 {
1518 char_u *val;
1519 if (PyBytes_Check(valObject))
1520 {
1521
1522 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1523 return -1;
1524 if (val == NULL)
1525 return -1;
1526
1527 val = vim_strsave(val);
1528 }
1529 else if (PyUnicode_Check(valObject))
1530 {
1531 PyObject *bytes;
1532
1533 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1534 if (bytes == NULL)
1535 return -1;
1536
1537 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1538 return -1;
1539 if (val == NULL)
1540 return -1;
1541
1542 val = vim_strsave(val);
1543 Py_XDECREF(bytes);
1544 }
1545 else
1546 {
1547 PyErr_SetString(PyExc_ValueError, "Object must be string");
1548 return -1;
1549 }
1550
1551 r = set_option_value_for(key, 0, val, opt_flags,
1552 this->opt_type, this->from);
1553 vim_free(val);
1554 }
1555
1556 return r;
1557}
1558
1559 static int
1560dummy_check(void *arg UNUSED)
1561{
1562 return 0;
1563}
1564
1565 static PyObject *
1566OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1567{
1568 OptionsObject *self;
1569
1570 self = PyObject_NEW(OptionsObject, &OptionsType);
1571 if (self == NULL)
1572 return NULL;
1573
1574 self->opt_type = opt_type;
1575 self->from = from;
1576 self->Check = Check;
1577 self->fromObj = fromObj;
1578 if (fromObj)
1579 Py_INCREF(fromObj);
1580
1581 return (PyObject *)(self);
1582}
1583
1584 static void
1585OptionsDestructor(PyObject *self)
1586{
1587 if (((OptionsObject *)(self))->fromObj)
1588 Py_DECREF(((OptionsObject *)(self))->fromObj);
1589 DESTRUCTOR_FINISH(self);
1590}
1591
1592static PyMappingMethods OptionsAsMapping = {
1593 (lenfunc) NULL,
1594 (binaryfunc) OptionsItem,
1595 (objobjargproc) OptionsAssItem,
1596};
1597
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001598/* Window object
1599 */
1600
1601typedef struct
1602{
1603 PyObject_HEAD
1604 win_T *win;
1605} WindowObject;
1606
1607static int WindowSetattr(PyObject *, char *, PyObject *);
1608static PyObject *WindowRepr(PyObject *);
1609static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001610
1611 static int
1612CheckWindow(WindowObject *this)
1613{
1614 if (this->win == INVALID_WINDOW_VALUE)
1615 {
1616 PyErr_SetVim(_("attempt to refer to deleted window"));
1617 return -1;
1618 }
1619
1620 return 0;
1621}
1622
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001623 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001624WindowNew(win_T *win)
1625{
1626 /* We need to handle deletion of windows underneath us.
1627 * If we add a "w_python*_ref" field to the win_T structure,
1628 * then we can get at it in win_free() in vim. We then
1629 * need to create only ONE Python object per window - if
1630 * we try to create a second, just INCREF the existing one
1631 * and return it. The (single) Python object referring to
1632 * the window is stored in "w_python*_ref".
1633 * On a win_free() we set the Python object's win_T* field
1634 * to an invalid value. We trap all uses of a window
1635 * object, and reject them if the win_T* field is invalid.
1636 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001637 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001638 * w_python_ref and w_python3_ref fields respectively.
1639 */
1640
1641 WindowObject *self;
1642
1643 if (WIN_PYTHON_REF(win))
1644 {
1645 self = WIN_PYTHON_REF(win);
1646 Py_INCREF(self);
1647 }
1648 else
1649 {
1650 self = PyObject_NEW(WindowObject, &WindowType);
1651 if (self == NULL)
1652 return NULL;
1653 self->win = win;
1654 WIN_PYTHON_REF(win) = self;
1655 }
1656
1657 return (PyObject *)(self);
1658}
1659
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001660 static void
1661WindowDestructor(PyObject *self)
1662{
1663 WindowObject *this = (WindowObject *)(self);
1664
1665 if (this->win && this->win != INVALID_WINDOW_VALUE)
1666 WIN_PYTHON_REF(this->win) = NULL;
1667
1668 DESTRUCTOR_FINISH(self);
1669}
1670
Bram Moolenaar971db462013-05-12 18:44:48 +02001671 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001672WindowAttr(WindowObject *this, char *name)
1673{
1674 if (strcmp(name, "buffer") == 0)
1675 return (PyObject *)BufferNew(this->win->w_buffer);
1676 else if (strcmp(name, "cursor") == 0)
1677 {
1678 pos_T *pos = &this->win->w_cursor;
1679
1680 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1681 }
1682 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001683 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001684#ifdef FEAT_WINDOWS
1685 else if (strcmp(name, "row") == 0)
1686 return PyLong_FromLong((long)(this->win->w_winrow));
1687#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001688#ifdef FEAT_VERTSPLIT
1689 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001690 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001691 else if (strcmp(name, "col") == 0)
1692 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001693#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001694 else if (strcmp(name, "vars") == 0)
1695 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001696 else if (strcmp(name, "options") == 0)
1697 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1698 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001699 else if (strcmp(name, "number") == 0)
1700 return PyLong_FromLong((long) get_win_number(this->win));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001701 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001702 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1703 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001704 else
1705 return NULL;
1706}
1707
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001708 static int
1709WindowSetattr(PyObject *self, char *name, PyObject *val)
1710{
1711 WindowObject *this = (WindowObject *)(self);
1712
1713 if (CheckWindow(this))
1714 return -1;
1715
1716 if (strcmp(name, "buffer") == 0)
1717 {
1718 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1719 return -1;
1720 }
1721 else if (strcmp(name, "cursor") == 0)
1722 {
1723 long lnum;
1724 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001725
1726 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1727 return -1;
1728
1729 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1730 {
1731 PyErr_SetVim(_("cursor position outside buffer"));
1732 return -1;
1733 }
1734
1735 /* Check for keyboard interrupts */
1736 if (VimErrorCheck())
1737 return -1;
1738
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001739 this->win->w_cursor.lnum = lnum;
1740 this->win->w_cursor.col = col;
1741#ifdef FEAT_VIRTUALEDIT
1742 this->win->w_cursor.coladd = 0;
1743#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001744 /* When column is out of range silently correct it. */
1745 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001746
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001747 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001748 return 0;
1749 }
1750 else if (strcmp(name, "height") == 0)
1751 {
1752 int height;
1753 win_T *savewin;
1754
1755 if (!PyArg_Parse(val, "i", &height))
1756 return -1;
1757
1758#ifdef FEAT_GUI
1759 need_mouse_correct = TRUE;
1760#endif
1761 savewin = curwin;
1762 curwin = this->win;
1763 win_setheight(height);
1764 curwin = savewin;
1765
1766 /* Check for keyboard interrupts */
1767 if (VimErrorCheck())
1768 return -1;
1769
1770 return 0;
1771 }
1772#ifdef FEAT_VERTSPLIT
1773 else if (strcmp(name, "width") == 0)
1774 {
1775 int width;
1776 win_T *savewin;
1777
1778 if (!PyArg_Parse(val, "i", &width))
1779 return -1;
1780
1781#ifdef FEAT_GUI
1782 need_mouse_correct = TRUE;
1783#endif
1784 savewin = curwin;
1785 curwin = this->win;
1786 win_setwidth(width);
1787 curwin = savewin;
1788
1789 /* Check for keyboard interrupts */
1790 if (VimErrorCheck())
1791 return -1;
1792
1793 return 0;
1794 }
1795#endif
1796 else
1797 {
1798 PyErr_SetString(PyExc_AttributeError, name);
1799 return -1;
1800 }
1801}
1802
1803 static PyObject *
1804WindowRepr(PyObject *self)
1805{
1806 static char repr[100];
1807 WindowObject *this = (WindowObject *)(self);
1808
1809 if (this->win == INVALID_WINDOW_VALUE)
1810 {
1811 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1812 return PyString_FromString(repr);
1813 }
1814 else
1815 {
Bram Moolenaar6d216452013-05-12 19:00:41 +02001816 int w = get_win_number(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001817
Bram Moolenaar6d216452013-05-12 19:00:41 +02001818 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001819 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1820 (self));
1821 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001822 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001823
1824 return PyString_FromString(repr);
1825 }
1826}
1827
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001828static struct PyMethodDef WindowMethods[] = {
1829 /* name, function, calling, documentation */
1830 { NULL, NULL, 0, NULL }
1831};
1832
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001833/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001834 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001835 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001836
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001837static PyTypeObject WinListType;
1838static PySequenceMethods WinListAsSeq;
1839
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001840typedef struct
1841{
1842 PyObject_HEAD
1843} WinListObject;
1844
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001845 static PyInt
1846WinListLength(PyObject *self UNUSED)
1847{
1848 win_T *w = firstwin;
1849 PyInt n = 0;
1850
1851 while (w != NULL)
1852 {
1853 ++n;
1854 w = W_NEXT(w);
1855 }
1856
1857 return n;
1858}
1859
1860 static PyObject *
1861WinListItem(PyObject *self UNUSED, PyInt n)
1862{
1863 win_T *w;
1864
1865 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1866 if (n == 0)
1867 return WindowNew(w);
1868
1869 PyErr_SetString(PyExc_IndexError, _("no such window"));
1870 return NULL;
1871}
1872
1873/* Convert a Python string into a Vim line.
1874 *
1875 * The result is in allocated memory. All internal nulls are replaced by
1876 * newline characters. It is an error for the string to contain newline
1877 * characters.
1878 *
1879 * On errors, the Python exception data is set, and NULL is returned.
1880 */
1881 static char *
1882StringToLine(PyObject *obj)
1883{
1884 const char *str;
1885 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001886 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001887 PyInt len;
1888 PyInt i;
1889 char *p;
1890
1891 if (obj == NULL || !PyString_Check(obj))
1892 {
1893 PyErr_BadArgument();
1894 return NULL;
1895 }
1896
Bram Moolenaar19e60942011-06-19 00:27:51 +02001897 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1898 str = PyString_AsString(bytes);
1899 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001900
1901 /*
1902 * Error checking: String must not contain newlines, as we
1903 * are replacing a single line, and we must replace it with
1904 * a single line.
1905 * A trailing newline is removed, so that append(f.readlines()) works.
1906 */
1907 p = memchr(str, '\n', len);
1908 if (p != NULL)
1909 {
1910 if (p == str + len - 1)
1911 --len;
1912 else
1913 {
1914 PyErr_SetVim(_("string cannot contain newlines"));
1915 return NULL;
1916 }
1917 }
1918
1919 /* Create a copy of the string, with internal nulls replaced by
1920 * newline characters, as is the vim convention.
1921 */
1922 save = (char *)alloc((unsigned)(len+1));
1923 if (save == NULL)
1924 {
1925 PyErr_NoMemory();
1926 return NULL;
1927 }
1928
1929 for (i = 0; i < len; ++i)
1930 {
1931 if (str[i] == '\0')
1932 save[i] = '\n';
1933 else
1934 save[i] = str[i];
1935 }
1936
1937 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001938 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001939
1940 return save;
1941}
1942
1943/* Get a line from the specified buffer. The line number is
1944 * in Vim format (1-based). The line is returned as a Python
1945 * string object.
1946 */
1947 static PyObject *
1948GetBufferLine(buf_T *buf, PyInt n)
1949{
1950 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1951}
1952
1953
1954/* Get a list of lines from the specified buffer. The line numbers
1955 * are in Vim format (1-based). The range is from lo up to, but not
1956 * including, hi. The list is returned as a Python list of string objects.
1957 */
1958 static PyObject *
1959GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1960{
1961 PyInt i;
1962 PyInt n = hi - lo;
1963 PyObject *list = PyList_New(n);
1964
1965 if (list == NULL)
1966 return NULL;
1967
1968 for (i = 0; i < n; ++i)
1969 {
1970 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1971
1972 /* Error check - was the Python string creation OK? */
1973 if (str == NULL)
1974 {
1975 Py_DECREF(list);
1976 return NULL;
1977 }
1978
1979 /* Set the list item */
1980 if (PyList_SetItem(list, i, str))
1981 {
1982 Py_DECREF(str);
1983 Py_DECREF(list);
1984 return NULL;
1985 }
1986 }
1987
1988 /* The ownership of the Python list is passed to the caller (ie,
1989 * the caller should Py_DECREF() the object when it is finished
1990 * with it).
1991 */
1992
1993 return list;
1994}
1995
1996/*
1997 * Check if deleting lines made the cursor position invalid.
1998 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1999 * deleted).
2000 */
2001 static void
2002py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2003{
2004 if (curwin->w_cursor.lnum >= lo)
2005 {
2006 /* Adjust the cursor position if it's in/after the changed
2007 * lines. */
2008 if (curwin->w_cursor.lnum >= hi)
2009 {
2010 curwin->w_cursor.lnum += extra;
2011 check_cursor_col();
2012 }
2013 else if (extra < 0)
2014 {
2015 curwin->w_cursor.lnum = lo;
2016 check_cursor();
2017 }
2018 else
2019 check_cursor_col();
2020 changed_cline_bef_curs();
2021 }
2022 invalidate_botline();
2023}
2024
Bram Moolenaar19e60942011-06-19 00:27:51 +02002025/*
2026 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002027 * in Vim format (1-based). The replacement line is given as
2028 * a Python string object. The object is checked for validity
2029 * and correct format. Errors are returned as a value of FAIL.
2030 * The return value is OK on success.
2031 * If OK is returned and len_change is not NULL, *len_change
2032 * is set to the change in the buffer length.
2033 */
2034 static int
2035SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2036{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002037 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002038 * There are three cases:
2039 * 1. NULL, or None - this is a deletion.
2040 * 2. A string - this is a replacement.
2041 * 3. Anything else - this is an error.
2042 */
2043 if (line == Py_None || line == NULL)
2044 {
2045 buf_T *savebuf = curbuf;
2046
2047 PyErr_Clear();
2048 curbuf = buf;
2049
2050 if (u_savedel((linenr_T)n, 1L) == FAIL)
2051 PyErr_SetVim(_("cannot save undo information"));
2052 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2053 PyErr_SetVim(_("cannot delete line"));
2054 else
2055 {
2056 if (buf == curwin->w_buffer)
2057 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2058 deleted_lines_mark((linenr_T)n, 1L);
2059 }
2060
2061 curbuf = savebuf;
2062
2063 if (PyErr_Occurred() || VimErrorCheck())
2064 return FAIL;
2065
2066 if (len_change)
2067 *len_change = -1;
2068
2069 return OK;
2070 }
2071 else if (PyString_Check(line))
2072 {
2073 char *save = StringToLine(line);
2074 buf_T *savebuf = curbuf;
2075
2076 if (save == NULL)
2077 return FAIL;
2078
2079 /* We do not need to free "save" if ml_replace() consumes it. */
2080 PyErr_Clear();
2081 curbuf = buf;
2082
2083 if (u_savesub((linenr_T)n) == FAIL)
2084 {
2085 PyErr_SetVim(_("cannot save undo information"));
2086 vim_free(save);
2087 }
2088 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2089 {
2090 PyErr_SetVim(_("cannot replace line"));
2091 vim_free(save);
2092 }
2093 else
2094 changed_bytes((linenr_T)n, 0);
2095
2096 curbuf = savebuf;
2097
2098 /* Check that the cursor is not beyond the end of the line now. */
2099 if (buf == curwin->w_buffer)
2100 check_cursor_col();
2101
2102 if (PyErr_Occurred() || VimErrorCheck())
2103 return FAIL;
2104
2105 if (len_change)
2106 *len_change = 0;
2107
2108 return OK;
2109 }
2110 else
2111 {
2112 PyErr_BadArgument();
2113 return FAIL;
2114 }
2115}
2116
Bram Moolenaar19e60942011-06-19 00:27:51 +02002117/* Replace a range of lines in the specified buffer. The line numbers are in
2118 * Vim format (1-based). The range is from lo up to, but not including, hi.
2119 * The replacement lines are given as a Python list of string objects. The
2120 * list is checked for validity and correct format. Errors are returned as a
2121 * value of FAIL. The return value is OK on success.
2122 * If OK is returned and len_change is not NULL, *len_change
2123 * is set to the change in the buffer length.
2124 */
2125 static int
2126SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2127{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002128 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002129 * There are three cases:
2130 * 1. NULL, or None - this is a deletion.
2131 * 2. A list - this is a replacement.
2132 * 3. Anything else - this is an error.
2133 */
2134 if (list == Py_None || list == NULL)
2135 {
2136 PyInt i;
2137 PyInt n = (int)(hi - lo);
2138 buf_T *savebuf = curbuf;
2139
2140 PyErr_Clear();
2141 curbuf = buf;
2142
2143 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2144 PyErr_SetVim(_("cannot save undo information"));
2145 else
2146 {
2147 for (i = 0; i < n; ++i)
2148 {
2149 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2150 {
2151 PyErr_SetVim(_("cannot delete line"));
2152 break;
2153 }
2154 }
2155 if (buf == curwin->w_buffer)
2156 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2157 deleted_lines_mark((linenr_T)lo, (long)i);
2158 }
2159
2160 curbuf = savebuf;
2161
2162 if (PyErr_Occurred() || VimErrorCheck())
2163 return FAIL;
2164
2165 if (len_change)
2166 *len_change = -n;
2167
2168 return OK;
2169 }
2170 else if (PyList_Check(list))
2171 {
2172 PyInt i;
2173 PyInt new_len = PyList_Size(list);
2174 PyInt old_len = hi - lo;
2175 PyInt extra = 0; /* lines added to text, can be negative */
2176 char **array;
2177 buf_T *savebuf;
2178
2179 if (new_len == 0) /* avoid allocating zero bytes */
2180 array = NULL;
2181 else
2182 {
2183 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2184 if (array == NULL)
2185 {
2186 PyErr_NoMemory();
2187 return FAIL;
2188 }
2189 }
2190
2191 for (i = 0; i < new_len; ++i)
2192 {
2193 PyObject *line = PyList_GetItem(list, i);
2194
2195 array[i] = StringToLine(line);
2196 if (array[i] == NULL)
2197 {
2198 while (i)
2199 vim_free(array[--i]);
2200 vim_free(array);
2201 return FAIL;
2202 }
2203 }
2204
2205 savebuf = curbuf;
2206
2207 PyErr_Clear();
2208 curbuf = buf;
2209
2210 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2211 PyErr_SetVim(_("cannot save undo information"));
2212
2213 /* If the size of the range is reducing (ie, new_len < old_len) we
2214 * need to delete some old_len. We do this at the start, by
2215 * repeatedly deleting line "lo".
2216 */
2217 if (!PyErr_Occurred())
2218 {
2219 for (i = 0; i < old_len - new_len; ++i)
2220 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2221 {
2222 PyErr_SetVim(_("cannot delete line"));
2223 break;
2224 }
2225 extra -= i;
2226 }
2227
2228 /* For as long as possible, replace the existing old_len with the
2229 * new old_len. This is a more efficient operation, as it requires
2230 * less memory allocation and freeing.
2231 */
2232 if (!PyErr_Occurred())
2233 {
2234 for (i = 0; i < old_len && i < new_len; ++i)
2235 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2236 == FAIL)
2237 {
2238 PyErr_SetVim(_("cannot replace line"));
2239 break;
2240 }
2241 }
2242 else
2243 i = 0;
2244
2245 /* Now we may need to insert the remaining new old_len. If we do, we
2246 * must free the strings as we finish with them (we can't pass the
2247 * responsibility to vim in this case).
2248 */
2249 if (!PyErr_Occurred())
2250 {
2251 while (i < new_len)
2252 {
2253 if (ml_append((linenr_T)(lo + i - 1),
2254 (char_u *)array[i], 0, FALSE) == FAIL)
2255 {
2256 PyErr_SetVim(_("cannot insert line"));
2257 break;
2258 }
2259 vim_free(array[i]);
2260 ++i;
2261 ++extra;
2262 }
2263 }
2264
2265 /* Free any left-over old_len, as a result of an error */
2266 while (i < new_len)
2267 {
2268 vim_free(array[i]);
2269 ++i;
2270 }
2271
2272 /* Free the array of old_len. All of its contents have now
2273 * been dealt with (either freed, or the responsibility passed
2274 * to vim.
2275 */
2276 vim_free(array);
2277
2278 /* Adjust marks. Invalidate any which lie in the
2279 * changed range, and move any in the remainder of the buffer.
2280 */
2281 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2282 (long)MAXLNUM, (long)extra);
2283 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2284
2285 if (buf == curwin->w_buffer)
2286 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2287
2288 curbuf = savebuf;
2289
2290 if (PyErr_Occurred() || VimErrorCheck())
2291 return FAIL;
2292
2293 if (len_change)
2294 *len_change = new_len - old_len;
2295
2296 return OK;
2297 }
2298 else
2299 {
2300 PyErr_BadArgument();
2301 return FAIL;
2302 }
2303}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002304
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002305/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002306 * The line number is in Vim format (1-based). The lines to be inserted are
2307 * given as a Python list of string objects or as a single string. The lines
2308 * to be added are checked for validity and correct format. Errors are
2309 * returned as a value of FAIL. The return value is OK on success.
2310 * If OK is returned and len_change is not NULL, *len_change
2311 * is set to the change in the buffer length.
2312 */
2313 static int
2314InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2315{
2316 /* First of all, we check the type of the supplied Python object.
2317 * It must be a string or a list, or the call is in error.
2318 */
2319 if (PyString_Check(lines))
2320 {
2321 char *str = StringToLine(lines);
2322 buf_T *savebuf;
2323
2324 if (str == NULL)
2325 return FAIL;
2326
2327 savebuf = curbuf;
2328
2329 PyErr_Clear();
2330 curbuf = buf;
2331
2332 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2333 PyErr_SetVim(_("cannot save undo information"));
2334 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2335 PyErr_SetVim(_("cannot insert line"));
2336 else
2337 appended_lines_mark((linenr_T)n, 1L);
2338
2339 vim_free(str);
2340 curbuf = savebuf;
2341 update_screen(VALID);
2342
2343 if (PyErr_Occurred() || VimErrorCheck())
2344 return FAIL;
2345
2346 if (len_change)
2347 *len_change = 1;
2348
2349 return OK;
2350 }
2351 else if (PyList_Check(lines))
2352 {
2353 PyInt i;
2354 PyInt size = PyList_Size(lines);
2355 char **array;
2356 buf_T *savebuf;
2357
2358 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2359 if (array == NULL)
2360 {
2361 PyErr_NoMemory();
2362 return FAIL;
2363 }
2364
2365 for (i = 0; i < size; ++i)
2366 {
2367 PyObject *line = PyList_GetItem(lines, i);
2368 array[i] = StringToLine(line);
2369
2370 if (array[i] == NULL)
2371 {
2372 while (i)
2373 vim_free(array[--i]);
2374 vim_free(array);
2375 return FAIL;
2376 }
2377 }
2378
2379 savebuf = curbuf;
2380
2381 PyErr_Clear();
2382 curbuf = buf;
2383
2384 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2385 PyErr_SetVim(_("cannot save undo information"));
2386 else
2387 {
2388 for (i = 0; i < size; ++i)
2389 {
2390 if (ml_append((linenr_T)(n + i),
2391 (char_u *)array[i], 0, FALSE) == FAIL)
2392 {
2393 PyErr_SetVim(_("cannot insert line"));
2394
2395 /* Free the rest of the lines */
2396 while (i < size)
2397 vim_free(array[i++]);
2398
2399 break;
2400 }
2401 vim_free(array[i]);
2402 }
2403 if (i > 0)
2404 appended_lines_mark((linenr_T)n, (long)i);
2405 }
2406
2407 /* Free the array of lines. All of its contents have now
2408 * been freed.
2409 */
2410 vim_free(array);
2411
2412 curbuf = savebuf;
2413 update_screen(VALID);
2414
2415 if (PyErr_Occurred() || VimErrorCheck())
2416 return FAIL;
2417
2418 if (len_change)
2419 *len_change = size;
2420
2421 return OK;
2422 }
2423 else
2424 {
2425 PyErr_BadArgument();
2426 return FAIL;
2427 }
2428}
2429
2430/*
2431 * Common routines for buffers and line ranges
2432 * -------------------------------------------
2433 */
2434
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002435typedef struct
2436{
2437 PyObject_HEAD
2438 buf_T *buf;
2439} BufferObject;
2440
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002441 static int
2442CheckBuffer(BufferObject *this)
2443{
2444 if (this->buf == INVALID_BUFFER_VALUE)
2445 {
2446 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2447 return -1;
2448 }
2449
2450 return 0;
2451}
2452
2453 static PyObject *
2454RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2455{
2456 if (CheckBuffer(self))
2457 return NULL;
2458
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002459 if (end == -1)
2460 end = self->buf->b_ml.ml_line_count;
2461
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002462 if (n < 0)
2463 n += end - start + 1;
2464
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002465 if (n < 0 || n > end - start)
2466 {
2467 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2468 return NULL;
2469 }
2470
2471 return GetBufferLine(self->buf, n+start);
2472}
2473
2474 static PyObject *
2475RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2476{
2477 PyInt size;
2478
2479 if (CheckBuffer(self))
2480 return NULL;
2481
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002482 if (end == -1)
2483 end = self->buf->b_ml.ml_line_count;
2484
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002485 size = end - start + 1;
2486
2487 if (lo < 0)
2488 lo = 0;
2489 else if (lo > size)
2490 lo = size;
2491 if (hi < 0)
2492 hi = 0;
2493 if (hi < lo)
2494 hi = lo;
2495 else if (hi > size)
2496 hi = size;
2497
2498 return GetBufferLineList(self->buf, lo+start, hi+start);
2499}
2500
2501 static PyInt
2502RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2503{
2504 PyInt len_change;
2505
2506 if (CheckBuffer(self))
2507 return -1;
2508
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002509 if (end == -1)
2510 end = self->buf->b_ml.ml_line_count;
2511
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002512 if (n < 0)
2513 n += end - start + 1;
2514
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002515 if (n < 0 || n > end - start)
2516 {
2517 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2518 return -1;
2519 }
2520
2521 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2522 return -1;
2523
2524 if (new_end)
2525 *new_end = end + len_change;
2526
2527 return 0;
2528}
2529
Bram Moolenaar19e60942011-06-19 00:27:51 +02002530 static PyInt
2531RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2532{
2533 PyInt size;
2534 PyInt len_change;
2535
2536 /* Self must be a valid buffer */
2537 if (CheckBuffer(self))
2538 return -1;
2539
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002540 if (end == -1)
2541 end = self->buf->b_ml.ml_line_count;
2542
Bram Moolenaar19e60942011-06-19 00:27:51 +02002543 /* Sort out the slice range */
2544 size = end - start + 1;
2545
2546 if (lo < 0)
2547 lo = 0;
2548 else if (lo > size)
2549 lo = size;
2550 if (hi < 0)
2551 hi = 0;
2552 if (hi < lo)
2553 hi = lo;
2554 else if (hi > size)
2555 hi = size;
2556
2557 if (SetBufferLineList(self->buf, lo + start, hi + start,
2558 val, &len_change) == FAIL)
2559 return -1;
2560
2561 if (new_end)
2562 *new_end = end + len_change;
2563
2564 return 0;
2565}
2566
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002567
2568 static PyObject *
2569RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2570{
2571 PyObject *lines;
2572 PyInt len_change;
2573 PyInt max;
2574 PyInt n;
2575
2576 if (CheckBuffer(self))
2577 return NULL;
2578
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002579 if (end == -1)
2580 end = self->buf->b_ml.ml_line_count;
2581
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002582 max = n = end - start + 1;
2583
2584 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2585 return NULL;
2586
2587 if (n < 0 || n > max)
2588 {
2589 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2590 return NULL;
2591 }
2592
2593 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2594 return NULL;
2595
2596 if (new_end)
2597 *new_end = end + len_change;
2598
2599 Py_INCREF(Py_None);
2600 return Py_None;
2601}
2602
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002603/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002604 */
2605
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002606static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002607static PySequenceMethods RangeAsSeq;
2608static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002609
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002610typedef struct
2611{
2612 PyObject_HEAD
2613 BufferObject *buf;
2614 PyInt start;
2615 PyInt end;
2616} RangeObject;
2617
2618 static PyObject *
2619RangeNew(buf_T *buf, PyInt start, PyInt end)
2620{
2621 BufferObject *bufr;
2622 RangeObject *self;
2623 self = PyObject_NEW(RangeObject, &RangeType);
2624 if (self == NULL)
2625 return NULL;
2626
2627 bufr = (BufferObject *)BufferNew(buf);
2628 if (bufr == NULL)
2629 {
2630 Py_DECREF(self);
2631 return NULL;
2632 }
2633 Py_INCREF(bufr);
2634
2635 self->buf = bufr;
2636 self->start = start;
2637 self->end = end;
2638
2639 return (PyObject *)(self);
2640}
2641
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002642 static void
2643RangeDestructor(PyObject *self)
2644{
2645 Py_DECREF(((RangeObject *)(self))->buf);
2646 DESTRUCTOR_FINISH(self);
2647}
2648
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002649 static PyInt
2650RangeLength(PyObject *self)
2651{
2652 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2653 if (CheckBuffer(((RangeObject *)(self))->buf))
2654 return -1; /* ??? */
2655
2656 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2657}
2658
2659 static PyObject *
2660RangeItem(PyObject *self, PyInt n)
2661{
2662 return RBItem(((RangeObject *)(self))->buf, n,
2663 ((RangeObject *)(self))->start,
2664 ((RangeObject *)(self))->end);
2665}
2666
2667 static PyObject *
2668RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2669{
2670 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2671 ((RangeObject *)(self))->start,
2672 ((RangeObject *)(self))->end);
2673}
2674
2675 static PyObject *
2676RangeAppend(PyObject *self, PyObject *args)
2677{
2678 return RBAppend(((RangeObject *)(self))->buf, args,
2679 ((RangeObject *)(self))->start,
2680 ((RangeObject *)(self))->end,
2681 &((RangeObject *)(self))->end);
2682}
2683
2684 static PyObject *
2685RangeRepr(PyObject *self)
2686{
2687 static char repr[100];
2688 RangeObject *this = (RangeObject *)(self);
2689
2690 if (this->buf->buf == INVALID_BUFFER_VALUE)
2691 {
2692 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2693 (self));
2694 return PyString_FromString(repr);
2695 }
2696 else
2697 {
2698 char *name = (char *)this->buf->buf->b_fname;
2699 int len;
2700
2701 if (name == NULL)
2702 name = "";
2703 len = (int)strlen(name);
2704
2705 if (len > 45)
2706 name = name + (45 - len);
2707
2708 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2709 len > 45 ? "..." : "", name,
2710 this->start, this->end);
2711
2712 return PyString_FromString(repr);
2713 }
2714}
2715
2716static struct PyMethodDef RangeMethods[] = {
2717 /* name, function, calling, documentation */
2718 {"append", RangeAppend, 1, "Append data to the Vim range" },
2719 { NULL, NULL, 0, NULL }
2720};
2721
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002722static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002723static PySequenceMethods BufferAsSeq;
2724static PyMappingMethods BufferAsMapping;
2725
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002726 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002727BufferNew(buf_T *buf)
2728{
2729 /* We need to handle deletion of buffers underneath us.
2730 * If we add a "b_python*_ref" field to the buf_T structure,
2731 * then we can get at it in buf_freeall() in vim. We then
2732 * need to create only ONE Python object per buffer - if
2733 * we try to create a second, just INCREF the existing one
2734 * and return it. The (single) Python object referring to
2735 * the buffer is stored in "b_python*_ref".
2736 * Question: what to do on a buf_freeall(). We'll probably
2737 * have to either delete the Python object (DECREF it to
2738 * zero - a bad idea, as it leaves dangling refs!) or
2739 * set the buf_T * value to an invalid value (-1?), which
2740 * means we need checks in all access functions... Bah.
2741 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002742 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02002743 * b_python_ref and b_python3_ref fields respectively.
2744 */
2745
2746 BufferObject *self;
2747
2748 if (BUF_PYTHON_REF(buf) != NULL)
2749 {
2750 self = BUF_PYTHON_REF(buf);
2751 Py_INCREF(self);
2752 }
2753 else
2754 {
2755 self = PyObject_NEW(BufferObject, &BufferType);
2756 if (self == NULL)
2757 return NULL;
2758 self->buf = buf;
2759 BUF_PYTHON_REF(buf) = self;
2760 }
2761
2762 return (PyObject *)(self);
2763}
2764
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002765 static void
2766BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002767{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002768 BufferObject *this = (BufferObject *)(self);
2769
2770 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2771 BUF_PYTHON_REF(this->buf) = NULL;
2772
2773 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002774}
2775
Bram Moolenaar971db462013-05-12 18:44:48 +02002776 static PyInt
2777BufferLength(PyObject *self)
2778{
2779 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2780 if (CheckBuffer((BufferObject *)(self)))
2781 return -1; /* ??? */
2782
2783 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2784}
2785
2786 static PyObject *
2787BufferItem(PyObject *self, PyInt n)
2788{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002789 return RBItem((BufferObject *)(self), n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002790}
2791
2792 static PyObject *
2793BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2794{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002795 return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002796}
2797
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002798 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002799BufferAttr(BufferObject *this, char *name)
2800{
2801 if (strcmp(name, "name") == 0)
2802 return Py_BuildValue("s", this->buf->b_ffname);
2803 else if (strcmp(name, "number") == 0)
2804 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
2805 else if (strcmp(name, "vars") == 0)
2806 return DictionaryNew(this->buf->b_vars);
2807 else if (strcmp(name, "options") == 0)
2808 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2809 (PyObject *) this);
2810 else if (strcmp(name,"__members__") == 0)
2811 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
2812 else
2813 return NULL;
2814}
2815
2816 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002817BufferAppend(PyObject *self, PyObject *args)
2818{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002819 return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002820}
2821
2822 static PyObject *
2823BufferMark(PyObject *self, PyObject *args)
2824{
2825 pos_T *posp;
2826 char *pmark;
2827 char mark;
2828 buf_T *curbuf_save;
2829
2830 if (CheckBuffer((BufferObject *)(self)))
2831 return NULL;
2832
2833 if (!PyArg_ParseTuple(args, "s", &pmark))
2834 return NULL;
2835 mark = *pmark;
2836
2837 curbuf_save = curbuf;
2838 curbuf = ((BufferObject *)(self))->buf;
2839 posp = getmark(mark, FALSE);
2840 curbuf = curbuf_save;
2841
2842 if (posp == NULL)
2843 {
2844 PyErr_SetVim(_("invalid mark name"));
2845 return NULL;
2846 }
2847
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002848 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002849 if (VimErrorCheck())
2850 return NULL;
2851
2852 if (posp->lnum <= 0)
2853 {
2854 /* Or raise an error? */
2855 Py_INCREF(Py_None);
2856 return Py_None;
2857 }
2858
2859 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2860}
2861
2862 static PyObject *
2863BufferRange(PyObject *self, PyObject *args)
2864{
2865 PyInt start;
2866 PyInt end;
2867
2868 if (CheckBuffer((BufferObject *)(self)))
2869 return NULL;
2870
2871 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2872 return NULL;
2873
2874 return RangeNew(((BufferObject *)(self))->buf, start, end);
2875}
2876
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002877 static PyObject *
2878BufferRepr(PyObject *self)
2879{
2880 static char repr[100];
2881 BufferObject *this = (BufferObject *)(self);
2882
2883 if (this->buf == INVALID_BUFFER_VALUE)
2884 {
2885 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2886 return PyString_FromString(repr);
2887 }
2888 else
2889 {
2890 char *name = (char *)this->buf->b_fname;
2891 PyInt len;
2892
2893 if (name == NULL)
2894 name = "";
2895 len = strlen(name);
2896
2897 if (len > 35)
2898 name = name + (35 - len);
2899
2900 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2901
2902 return PyString_FromString(repr);
2903 }
2904}
2905
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002906static struct PyMethodDef BufferMethods[] = {
2907 /* name, function, calling, documentation */
2908 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2909 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2910 {"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 +01002911#if PY_VERSION_HEX >= 0x03000000
2912 {"__dir__", BufferDir, 4, "List its attributes" },
2913#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002914 { NULL, NULL, 0, NULL }
2915};
2916
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02002917/*
2918 * Buffer list object - Implementation
2919 */
2920
2921static PyTypeObject BufMapType;
2922
2923typedef struct
2924{
2925 PyObject_HEAD
2926} BufMapObject;
2927
2928 static PyInt
2929BufMapLength(PyObject *self UNUSED)
2930{
2931 buf_T *b = firstbuf;
2932 PyInt n = 0;
2933
2934 while (b)
2935 {
2936 ++n;
2937 b = b->b_next;
2938 }
2939
2940 return n;
2941}
2942
2943 static PyObject *
2944BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
2945{
2946 buf_T *b;
2947 int bnr;
2948
2949#if PY_MAJOR_VERSION < 3
2950 if (PyInt_Check(keyObject))
2951 bnr = PyInt_AsLong(keyObject);
2952 else
2953#endif
2954 if (PyLong_Check(keyObject))
2955 bnr = PyLong_AsLong(keyObject);
2956 else
2957 {
2958 PyErr_SetString(PyExc_ValueError, _("key must be integer"));
2959 return NULL;
2960 }
2961
2962 b = buflist_findnr(bnr);
2963
2964 if (b)
2965 return BufferNew(b);
2966 else
2967 {
2968 PyErr_SetString(PyExc_KeyError, _("no such buffer"));
2969 return NULL;
2970 }
2971}
2972
2973 static void
2974BufMapIterDestruct(PyObject *buffer)
2975{
2976 /* Iteration was stopped before all buffers were processed */
2977 if (buffer)
2978 {
2979 Py_DECREF(buffer);
2980 }
2981}
2982
2983 static PyObject *
2984BufMapIterNext(PyObject **buffer)
2985{
2986 PyObject *next;
2987 PyObject *r;
2988
2989 if (!*buffer)
2990 return NULL;
2991
2992 r = *buffer;
2993
2994 if (CheckBuffer((BufferObject *)(r)))
2995 {
2996 *buffer = NULL;
2997 return NULL;
2998 }
2999
3000 if (!((BufferObject *)(r))->buf->b_next)
3001 next = NULL;
3002 else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
3003 return NULL;
3004 *buffer = next;
3005 /* Do not increment reference: we no longer hold it (decref), but whoever on
3006 * other side will hold (incref). Decref+incref = nothing.
3007 */
3008 return r;
3009}
3010
3011 static PyObject *
3012BufMapIter(PyObject *self UNUSED)
3013{
3014 PyObject *buffer;
3015
3016 buffer = BufferNew(firstbuf);
3017 return IterNew(buffer,
3018 (destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext);
3019}
3020
3021static PyMappingMethods BufMapAsMapping = {
3022 (lenfunc) BufMapLength,
3023 (binaryfunc) BufMapItem,
3024 (objobjargproc) 0,
3025};
3026
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003027/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003028 */
3029
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003030 static PyObject *
3031CurrentGetattr(PyObject *self UNUSED, char *name)
3032{
3033 if (strcmp(name, "buffer") == 0)
3034 return (PyObject *)BufferNew(curbuf);
3035 else if (strcmp(name, "window") == 0)
3036 return (PyObject *)WindowNew(curwin);
3037 else if (strcmp(name, "line") == 0)
3038 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3039 else if (strcmp(name, "range") == 0)
3040 return RangeNew(curbuf, RangeStart, RangeEnd);
3041 else if (strcmp(name,"__members__") == 0)
3042 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
3043 else
3044 {
3045 PyErr_SetString(PyExc_AttributeError, name);
3046 return NULL;
3047 }
3048}
3049
3050 static int
3051CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3052{
3053 if (strcmp(name, "line") == 0)
3054 {
3055 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3056 return -1;
3057
3058 return 0;
3059 }
3060 else
3061 {
3062 PyErr_SetString(PyExc_AttributeError, name);
3063 return -1;
3064 }
3065}
3066
Bram Moolenaardb913952012-06-29 12:54:53 +02003067 static void
3068set_ref_in_py(const int copyID)
3069{
3070 pylinkedlist_T *cur;
3071 dict_T *dd;
3072 list_T *ll;
3073
3074 if (lastdict != NULL)
3075 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3076 {
3077 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3078 if (dd->dv_copyID != copyID)
3079 {
3080 dd->dv_copyID = copyID;
3081 set_ref_in_ht(&dd->dv_hashtab, copyID);
3082 }
3083 }
3084
3085 if (lastlist != NULL)
3086 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3087 {
3088 ll = ((ListObject *) (cur->pll_obj))->list;
3089 if (ll->lv_copyID != copyID)
3090 {
3091 ll->lv_copyID = copyID;
3092 set_ref_in_list(ll, copyID);
3093 }
3094 }
3095}
3096
3097 static int
3098set_string_copy(char_u *str, typval_T *tv)
3099{
3100 tv->vval.v_string = vim_strsave(str);
3101 if (tv->vval.v_string == NULL)
3102 {
3103 PyErr_NoMemory();
3104 return -1;
3105 }
3106 return 0;
3107}
3108
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003109 static int
3110pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3111{
3112 dict_T *d;
3113 char_u *key;
3114 dictitem_T *di;
3115 PyObject *keyObject;
3116 PyObject *valObject;
3117 Py_ssize_t iter = 0;
3118
3119 d = dict_alloc();
3120 if (d == NULL)
3121 {
3122 PyErr_NoMemory();
3123 return -1;
3124 }
3125
3126 tv->v_type = VAR_DICT;
3127 tv->vval.v_dict = d;
3128
3129 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
3130 {
3131 DICTKEY_DECL
3132
3133 if (keyObject == NULL)
3134 return -1;
3135 if (valObject == NULL)
3136 return -1;
3137
3138 DICTKEY_GET_NOTEMPTY(-1)
3139
3140 di = dictitem_alloc(key);
3141
3142 DICTKEY_UNREF
3143
3144 if (di == NULL)
3145 {
3146 PyErr_NoMemory();
3147 return -1;
3148 }
3149 di->di_tv.v_lock = 0;
3150
3151 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3152 {
3153 vim_free(di);
3154 return -1;
3155 }
3156 if (dict_add(d, di) == FAIL)
3157 {
3158 vim_free(di);
3159 PyErr_SetVim(_("failed to add key to dictionary"));
3160 return -1;
3161 }
3162 }
3163 return 0;
3164}
3165
3166 static int
3167pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3168{
3169 dict_T *d;
3170 char_u *key;
3171 dictitem_T *di;
3172 PyObject *list;
3173 PyObject *litem;
3174 PyObject *keyObject;
3175 PyObject *valObject;
3176 Py_ssize_t lsize;
3177
3178 d = dict_alloc();
3179 if (d == NULL)
3180 {
3181 PyErr_NoMemory();
3182 return -1;
3183 }
3184
3185 tv->v_type = VAR_DICT;
3186 tv->vval.v_dict = d;
3187
3188 list = PyMapping_Items(obj);
3189 if (list == NULL)
3190 return -1;
3191 lsize = PyList_Size(list);
3192 while (lsize--)
3193 {
3194 DICTKEY_DECL
3195
3196 litem = PyList_GetItem(list, lsize);
3197 if (litem == NULL)
3198 {
3199 Py_DECREF(list);
3200 return -1;
3201 }
3202
3203 keyObject = PyTuple_GetItem(litem, 0);
3204 if (keyObject == NULL)
3205 {
3206 Py_DECREF(list);
3207 Py_DECREF(litem);
3208 return -1;
3209 }
3210
3211 DICTKEY_GET_NOTEMPTY(-1)
3212
3213 valObject = PyTuple_GetItem(litem, 1);
3214 if (valObject == NULL)
3215 {
3216 Py_DECREF(list);
3217 Py_DECREF(litem);
3218 return -1;
3219 }
3220
3221 di = dictitem_alloc(key);
3222
3223 DICTKEY_UNREF
3224
3225 if (di == NULL)
3226 {
3227 Py_DECREF(list);
3228 Py_DECREF(litem);
3229 PyErr_NoMemory();
3230 return -1;
3231 }
3232 di->di_tv.v_lock = 0;
3233
3234 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3235 {
3236 vim_free(di);
3237 Py_DECREF(list);
3238 Py_DECREF(litem);
3239 return -1;
3240 }
3241 if (dict_add(d, di) == FAIL)
3242 {
3243 vim_free(di);
3244 Py_DECREF(list);
3245 Py_DECREF(litem);
3246 PyErr_SetVim(_("failed to add key to dictionary"));
3247 return -1;
3248 }
3249 Py_DECREF(litem);
3250 }
3251 Py_DECREF(list);
3252 return 0;
3253}
3254
3255 static int
3256pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3257{
3258 list_T *l;
3259
3260 l = list_alloc();
3261 if (l == NULL)
3262 {
3263 PyErr_NoMemory();
3264 return -1;
3265 }
3266
3267 tv->v_type = VAR_LIST;
3268 tv->vval.v_list = l;
3269
3270 if (list_py_concat(l, obj, lookupDict) == -1)
3271 return -1;
3272
3273 return 0;
3274}
3275
3276 static int
3277pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3278{
3279 PyObject *iterator = PyObject_GetIter(obj);
3280 PyObject *item;
3281 list_T *l;
3282 listitem_T *li;
3283
3284 l = list_alloc();
3285
3286 if (l == NULL)
3287 {
3288 PyErr_NoMemory();
3289 return -1;
3290 }
3291
3292 tv->vval.v_list = l;
3293 tv->v_type = VAR_LIST;
3294
3295
3296 if (iterator == NULL)
3297 return -1;
3298
3299 while ((item = PyIter_Next(obj)))
3300 {
3301 li = listitem_alloc();
3302 if (li == NULL)
3303 {
3304 PyErr_NoMemory();
3305 return -1;
3306 }
3307 li->li_tv.v_lock = 0;
3308
3309 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3310 return -1;
3311
3312 list_append(l, li);
3313
3314 Py_DECREF(item);
3315 }
3316
3317 Py_DECREF(iterator);
3318 return 0;
3319}
3320
Bram Moolenaardb913952012-06-29 12:54:53 +02003321typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3322
3323 static int
3324convert_dl(PyObject *obj, typval_T *tv,
3325 pytotvfunc py_to_tv, PyObject *lookupDict)
3326{
3327 PyObject *capsule;
3328 char hexBuf[sizeof(void *) * 2 + 3];
3329
3330 sprintf(hexBuf, "%p", obj);
3331
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003332# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003333 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003334# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003335 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003336# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003337 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003338 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003339# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003340 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003341# else
3342 capsule = PyCObject_FromVoidPtr(tv, NULL);
3343# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003344 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3345 Py_DECREF(capsule);
3346 if (py_to_tv(obj, tv, lookupDict) == -1)
3347 {
3348 tv->v_type = VAR_UNKNOWN;
3349 return -1;
3350 }
3351 /* As we are not using copy_tv which increments reference count we must
3352 * do it ourself. */
3353 switch(tv->v_type)
3354 {
3355 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3356 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3357 }
3358 }
3359 else
3360 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003361 typval_T *v;
3362
3363# ifdef PY_USE_CAPSULE
3364 v = PyCapsule_GetPointer(capsule, NULL);
3365# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003366 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003367# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003368 copy_tv(v, tv);
3369 }
3370 return 0;
3371}
3372
3373 static int
3374ConvertFromPyObject(PyObject *obj, typval_T *tv)
3375{
3376 PyObject *lookup_dict;
3377 int r;
3378
3379 lookup_dict = PyDict_New();
3380 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3381 Py_DECREF(lookup_dict);
3382 return r;
3383}
3384
3385 static int
3386_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3387{
3388 if (obj->ob_type == &DictionaryType)
3389 {
3390 tv->v_type = VAR_DICT;
3391 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3392 ++tv->vval.v_dict->dv_refcount;
3393 }
3394 else if (obj->ob_type == &ListType)
3395 {
3396 tv->v_type = VAR_LIST;
3397 tv->vval.v_list = (((ListObject *)(obj))->list);
3398 ++tv->vval.v_list->lv_refcount;
3399 }
3400 else if (obj->ob_type == &FunctionType)
3401 {
3402 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3403 return -1;
3404
3405 tv->v_type = VAR_FUNC;
3406 func_ref(tv->vval.v_string);
3407 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003408 else if (PyBytes_Check(obj))
3409 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003410 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003411
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003412 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3413 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003414 if (result == NULL)
3415 return -1;
3416
3417 if (set_string_copy(result, tv) == -1)
3418 return -1;
3419
3420 tv->v_type = VAR_STRING;
3421 }
3422 else if (PyUnicode_Check(obj))
3423 {
3424 PyObject *bytes;
3425 char_u *result;
3426
Bram Moolenaardb913952012-06-29 12:54:53 +02003427 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3428 if (bytes == NULL)
3429 return -1;
3430
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003431 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3432 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003433 if (result == NULL)
3434 return -1;
3435
3436 if (set_string_copy(result, tv) == -1)
3437 {
3438 Py_XDECREF(bytes);
3439 return -1;
3440 }
3441 Py_XDECREF(bytes);
3442
3443 tv->v_type = VAR_STRING;
3444 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003445#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003446 else if (PyInt_Check(obj))
3447 {
3448 tv->v_type = VAR_NUMBER;
3449 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3450 }
3451#endif
3452 else if (PyLong_Check(obj))
3453 {
3454 tv->v_type = VAR_NUMBER;
3455 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3456 }
3457 else if (PyDict_Check(obj))
3458 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3459#ifdef FEAT_FLOAT
3460 else if (PyFloat_Check(obj))
3461 {
3462 tv->v_type = VAR_FLOAT;
3463 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3464 }
3465#endif
3466 else if (PyIter_Check(obj))
3467 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3468 else if (PySequence_Check(obj))
3469 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3470 else if (PyMapping_Check(obj))
3471 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3472 else
3473 {
3474 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
3475 return -1;
3476 }
3477 return 0;
3478}
3479
3480 static PyObject *
3481ConvertToPyObject(typval_T *tv)
3482{
3483 if (tv == NULL)
3484 {
3485 PyErr_SetVim(_("NULL reference passed"));
3486 return NULL;
3487 }
3488 switch (tv->v_type)
3489 {
3490 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003491 return PyBytes_FromString(tv->vval.v_string == NULL
3492 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003493 case VAR_NUMBER:
3494 return PyLong_FromLong((long) tv->vval.v_number);
3495#ifdef FEAT_FLOAT
3496 case VAR_FLOAT:
3497 return PyFloat_FromDouble((double) tv->vval.v_float);
3498#endif
3499 case VAR_LIST:
3500 return ListNew(tv->vval.v_list);
3501 case VAR_DICT:
3502 return DictionaryNew(tv->vval.v_dict);
3503 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003504 return FunctionNew(tv->vval.v_string == NULL
3505 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003506 case VAR_UNKNOWN:
3507 Py_INCREF(Py_None);
3508 return Py_None;
3509 default:
3510 PyErr_SetVim(_("internal error: invalid value type"));
3511 return NULL;
3512 }
3513}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003514
3515typedef struct
3516{
3517 PyObject_HEAD
3518} CurrentObject;
3519static PyTypeObject CurrentType;
3520
3521 static void
3522init_structs(void)
3523{
3524 vim_memset(&OutputType, 0, sizeof(OutputType));
3525 OutputType.tp_name = "vim.message";
3526 OutputType.tp_basicsize = sizeof(OutputObject);
3527 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3528 OutputType.tp_doc = "vim message object";
3529 OutputType.tp_methods = OutputMethods;
3530#if PY_MAJOR_VERSION >= 3
3531 OutputType.tp_getattro = OutputGetattro;
3532 OutputType.tp_setattro = OutputSetattro;
3533 OutputType.tp_alloc = call_PyType_GenericAlloc;
3534 OutputType.tp_new = call_PyType_GenericNew;
3535 OutputType.tp_free = call_PyObject_Free;
3536#else
3537 OutputType.tp_getattr = OutputGetattr;
3538 OutputType.tp_setattr = OutputSetattr;
3539#endif
3540
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003541 vim_memset(&IterType, 0, sizeof(IterType));
3542 IterType.tp_name = "vim.iter";
3543 IterType.tp_basicsize = sizeof(IterObject);
3544 IterType.tp_flags = Py_TPFLAGS_DEFAULT;
3545 IterType.tp_doc = "generic iterator object";
3546 IterType.tp_iter = IterIter;
3547 IterType.tp_iternext = IterNext;
3548
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003549 vim_memset(&BufferType, 0, sizeof(BufferType));
3550 BufferType.tp_name = "vim.buffer";
3551 BufferType.tp_basicsize = sizeof(BufferType);
3552 BufferType.tp_dealloc = BufferDestructor;
3553 BufferType.tp_repr = BufferRepr;
3554 BufferType.tp_as_sequence = &BufferAsSeq;
3555 BufferType.tp_as_mapping = &BufferAsMapping;
3556 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3557 BufferType.tp_doc = "vim buffer object";
3558 BufferType.tp_methods = BufferMethods;
3559#if PY_MAJOR_VERSION >= 3
3560 BufferType.tp_getattro = BufferGetattro;
3561 BufferType.tp_alloc = call_PyType_GenericAlloc;
3562 BufferType.tp_new = call_PyType_GenericNew;
3563 BufferType.tp_free = call_PyObject_Free;
3564#else
3565 BufferType.tp_getattr = BufferGetattr;
3566#endif
3567
3568 vim_memset(&WindowType, 0, sizeof(WindowType));
3569 WindowType.tp_name = "vim.window";
3570 WindowType.tp_basicsize = sizeof(WindowObject);
3571 WindowType.tp_dealloc = WindowDestructor;
3572 WindowType.tp_repr = WindowRepr;
3573 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3574 WindowType.tp_doc = "vim Window object";
3575 WindowType.tp_methods = WindowMethods;
3576#if PY_MAJOR_VERSION >= 3
3577 WindowType.tp_getattro = WindowGetattro;
3578 WindowType.tp_setattro = WindowSetattro;
3579 WindowType.tp_alloc = call_PyType_GenericAlloc;
3580 WindowType.tp_new = call_PyType_GenericNew;
3581 WindowType.tp_free = call_PyObject_Free;
3582#else
3583 WindowType.tp_getattr = WindowGetattr;
3584 WindowType.tp_setattr = WindowSetattr;
3585#endif
3586
Bram Moolenaardfa38d42013-05-15 13:38:47 +02003587 vim_memset(&BufMapType, 0, sizeof(BufMapType));
3588 BufMapType.tp_name = "vim.bufferlist";
3589 BufMapType.tp_basicsize = sizeof(BufMapObject);
3590 BufMapType.tp_as_mapping = &BufMapAsMapping;
3591 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003592 BufMapType.tp_iter = BufMapIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003593 BufferType.tp_doc = "vim buffer list";
3594
3595 vim_memset(&WinListType, 0, sizeof(WinListType));
3596 WinListType.tp_name = "vim.windowlist";
3597 WinListType.tp_basicsize = sizeof(WinListType);
3598 WinListType.tp_as_sequence = &WinListAsSeq;
3599 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3600 WinListType.tp_doc = "vim window list";
3601
3602 vim_memset(&RangeType, 0, sizeof(RangeType));
3603 RangeType.tp_name = "vim.range";
3604 RangeType.tp_basicsize = sizeof(RangeObject);
3605 RangeType.tp_dealloc = RangeDestructor;
3606 RangeType.tp_repr = RangeRepr;
3607 RangeType.tp_as_sequence = &RangeAsSeq;
3608 RangeType.tp_as_mapping = &RangeAsMapping;
3609 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3610 RangeType.tp_doc = "vim Range object";
3611 RangeType.tp_methods = RangeMethods;
3612#if PY_MAJOR_VERSION >= 3
3613 RangeType.tp_getattro = RangeGetattro;
3614 RangeType.tp_alloc = call_PyType_GenericAlloc;
3615 RangeType.tp_new = call_PyType_GenericNew;
3616 RangeType.tp_free = call_PyObject_Free;
3617#else
3618 RangeType.tp_getattr = RangeGetattr;
3619#endif
3620
3621 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3622 CurrentType.tp_name = "vim.currentdata";
3623 CurrentType.tp_basicsize = sizeof(CurrentObject);
3624 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3625 CurrentType.tp_doc = "vim current object";
3626#if PY_MAJOR_VERSION >= 3
3627 CurrentType.tp_getattro = CurrentGetattro;
3628 CurrentType.tp_setattro = CurrentSetattro;
3629#else
3630 CurrentType.tp_getattr = CurrentGetattr;
3631 CurrentType.tp_setattr = CurrentSetattr;
3632#endif
3633
3634 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3635 DictionaryType.tp_name = "vim.dictionary";
3636 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3637 DictionaryType.tp_dealloc = DictionaryDestructor;
3638 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3639 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3640 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3641 DictionaryType.tp_methods = DictionaryMethods;
3642#if PY_MAJOR_VERSION >= 3
3643 DictionaryType.tp_getattro = DictionaryGetattro;
3644 DictionaryType.tp_setattro = DictionarySetattro;
3645#else
3646 DictionaryType.tp_getattr = DictionaryGetattr;
3647 DictionaryType.tp_setattr = DictionarySetattr;
3648#endif
3649
3650 vim_memset(&ListType, 0, sizeof(ListType));
3651 ListType.tp_name = "vim.list";
3652 ListType.tp_dealloc = ListDestructor;
3653 ListType.tp_basicsize = sizeof(ListObject);
3654 ListType.tp_as_sequence = &ListAsSeq;
3655 ListType.tp_as_mapping = &ListAsMapping;
3656 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3657 ListType.tp_doc = "list pushing modifications to vim structure";
3658 ListType.tp_methods = ListMethods;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003659 ListType.tp_iter = ListIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003660#if PY_MAJOR_VERSION >= 3
3661 ListType.tp_getattro = ListGetattro;
3662 ListType.tp_setattro = ListSetattro;
3663#else
3664 ListType.tp_getattr = ListGetattr;
3665 ListType.tp_setattr = ListSetattr;
3666#endif
3667
3668 vim_memset(&FunctionType, 0, sizeof(FunctionType));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003669 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003670 FunctionType.tp_basicsize = sizeof(FunctionObject);
3671 FunctionType.tp_dealloc = FunctionDestructor;
3672 FunctionType.tp_call = FunctionCall;
3673 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3674 FunctionType.tp_doc = "object that calls vim function";
3675 FunctionType.tp_methods = FunctionMethods;
3676#if PY_MAJOR_VERSION >= 3
3677 FunctionType.tp_getattro = FunctionGetattro;
3678#else
3679 FunctionType.tp_getattr = FunctionGetattr;
3680#endif
3681
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003682 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3683 OptionsType.tp_name = "vim.options";
3684 OptionsType.tp_basicsize = sizeof(OptionsObject);
3685 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3686 OptionsType.tp_doc = "object for manipulating options";
3687 OptionsType.tp_as_mapping = &OptionsAsMapping;
3688 OptionsType.tp_dealloc = OptionsDestructor;
3689
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003690#if PY_MAJOR_VERSION >= 3
3691 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3692 vimmodule.m_name = "vim";
3693 vimmodule.m_doc = "Vim Python interface\n";
3694 vimmodule.m_size = -1;
3695 vimmodule.m_methods = VimMethods;
3696#endif
3697}