blob: 6f9166950a2ed61e4108c7805556b768a08d517d [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
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200567#if 0 /* unused */
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200568 static void
569IterDestructor(PyObject *self)
570{
571 IterObject *this = (IterObject *)(self);
572
573 this->destruct(this->cur);
574
575 DESTRUCTOR_FINISH(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200576}
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200577#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200578
579 static PyObject *
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200580IterNext(PyObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200581{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200582 IterObject *this = (IterObject *)(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200583
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200584 return this->next(&this->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200585}
586
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200587 static PyObject *
588IterIter(PyObject *self)
589{
590 return self;
591}
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200592
Bram Moolenaardb913952012-06-29 12:54:53 +0200593typedef struct pylinkedlist_S {
594 struct pylinkedlist_S *pll_next;
595 struct pylinkedlist_S *pll_prev;
596 PyObject *pll_obj;
597} pylinkedlist_T;
598
599static pylinkedlist_T *lastdict = NULL;
600static pylinkedlist_T *lastlist = NULL;
601
602 static void
603pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
604{
605 if (ref->pll_prev == NULL)
606 {
607 if (ref->pll_next == NULL)
608 {
609 *last = NULL;
610 return;
611 }
612 }
613 else
614 ref->pll_prev->pll_next = ref->pll_next;
615
616 if (ref->pll_next == NULL)
617 *last = ref->pll_prev;
618 else
619 ref->pll_next->pll_prev = ref->pll_prev;
620}
621
622 static void
623pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
624{
625 if (*last == NULL)
626 ref->pll_prev = NULL;
627 else
628 {
629 (*last)->pll_next = ref;
630 ref->pll_prev = *last;
631 }
632 ref->pll_next = NULL;
633 ref->pll_obj = self;
634 *last = ref;
635}
636
637static PyTypeObject DictionaryType;
638
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200639#define DICTKEY_GET_NOTEMPTY(err) \
640 DICTKEY_GET(err) \
641 if (*key == NUL) \
642 { \
643 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
644 return err; \
645 }
646
Bram Moolenaardb913952012-06-29 12:54:53 +0200647typedef struct
648{
649 PyObject_HEAD
650 dict_T *dict;
651 pylinkedlist_T ref;
652} DictionaryObject;
653
654 static PyObject *
655DictionaryNew(dict_T *dict)
656{
657 DictionaryObject *self;
658
659 self = PyObject_NEW(DictionaryObject, &DictionaryType);
660 if (self == NULL)
661 return NULL;
662 self->dict = dict;
663 ++dict->dv_refcount;
664
665 pyll_add((PyObject *)(self), &self->ref, &lastdict);
666
667 return (PyObject *)(self);
668}
669
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200670 static void
671DictionaryDestructor(PyObject *self)
672{
673 DictionaryObject *this = ((DictionaryObject *) (self));
674
675 pyll_remove(&this->ref, &lastdict);
676 dict_unref(this->dict);
677
678 DESTRUCTOR_FINISH(self);
679}
680
Bram Moolenaardb913952012-06-29 12:54:53 +0200681 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200682DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200683{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200684 DictionaryObject *this = (DictionaryObject *)(self);
685
Bram Moolenaar66b79852012-09-21 14:00:35 +0200686 if (val == NULL)
687 {
688 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
689 return -1;
690 }
691
692 if (strcmp(name, "locked") == 0)
693 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200694 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200695 {
696 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
697 return -1;
698 }
699 else
700 {
Bram Moolenaar03db85b2013-05-15 14:51:35 +0200701 if (PyObject_IsTrue(val))
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200702 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200703 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200704 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200705 }
706 return 0;
707 }
708 else
709 {
710 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
711 return -1;
712 }
713}
714
715 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200716DictionaryLength(PyObject *self)
717{
718 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
719}
720
721 static PyObject *
722DictionaryItem(PyObject *self, PyObject *keyObject)
723{
724 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200725 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200726 DICTKEY_DECL
727
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200728 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200729
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200730 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
731
Bram Moolenaar696c2112012-09-21 13:43:14 +0200732 DICTKEY_UNREF
733
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200734 if (di == NULL)
735 {
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200736 PyErr_SetString(PyExc_KeyError, _("no such key in dictionary"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200737 return NULL;
738 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200739
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200740 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200741}
742
743 static PyInt
744DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
745{
746 char_u *key;
747 typval_T tv;
748 dict_T *d = ((DictionaryObject *)(self))->dict;
749 dictitem_T *di;
750 DICTKEY_DECL
751
752 if (d->dv_lock)
753 {
754 PyErr_SetVim(_("dict is locked"));
755 return -1;
756 }
757
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200758 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200759
760 di = dict_find(d, key, -1);
761
762 if (valObject == NULL)
763 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200764 hashitem_T *hi;
765
Bram Moolenaardb913952012-06-29 12:54:53 +0200766 if (di == NULL)
767 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200768 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200769 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
770 return -1;
771 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200772 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200773 hash_remove(&d->dv_hashtab, hi);
774 dictitem_free(di);
775 return 0;
776 }
777
778 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200779 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200780
781 if (di == NULL)
782 {
783 di = dictitem_alloc(key);
784 if (di == NULL)
785 {
786 PyErr_NoMemory();
787 return -1;
788 }
789 di->di_tv.v_lock = 0;
790
791 if (dict_add(d, di) == FAIL)
792 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200793 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200794 vim_free(di);
795 PyErr_SetVim(_("failed to add key to dictionary"));
796 return -1;
797 }
798 }
799 else
800 clear_tv(&di->di_tv);
801
802 DICTKEY_UNREF
803
804 copy_tv(&tv, &di->di_tv);
805 return 0;
806}
807
808 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100809DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200810{
811 dict_T *dict = ((DictionaryObject *)(self))->dict;
812 long_u todo = dict->dv_hashtab.ht_used;
813 Py_ssize_t i = 0;
814 PyObject *r;
815 hashitem_T *hi;
816
817 r = PyList_New(todo);
818 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
819 {
820 if (!HASHITEM_EMPTY(hi))
821 {
822 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
823 --todo;
824 ++i;
825 }
826 }
827 return r;
828}
829
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200830static PyMappingMethods DictionaryAsMapping = {
831 (lenfunc) DictionaryLength,
832 (binaryfunc) DictionaryItem,
833 (objobjargproc) DictionaryAssItem,
834};
835
Bram Moolenaardb913952012-06-29 12:54:53 +0200836static struct PyMethodDef DictionaryMethods[] = {
837 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
838 { NULL, NULL, 0, NULL }
839};
840
841static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200842static PySequenceMethods ListAsSeq;
843static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200844
845typedef struct
846{
847 PyObject_HEAD
848 list_T *list;
849 pylinkedlist_T ref;
850} ListObject;
851
852 static PyObject *
853ListNew(list_T *list)
854{
855 ListObject *self;
856
857 self = PyObject_NEW(ListObject, &ListType);
858 if (self == NULL)
859 return NULL;
860 self->list = list;
861 ++list->lv_refcount;
862
863 pyll_add((PyObject *)(self), &self->ref, &lastlist);
864
865 return (PyObject *)(self);
866}
867
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200868 static void
869ListDestructor(PyObject *self)
870{
871 ListObject *this = (ListObject *)(self);
872
873 pyll_remove(&this->ref, &lastlist);
874 list_unref(this->list);
875
876 DESTRUCTOR_FINISH(self);
877}
878
Bram Moolenaardb913952012-06-29 12:54:53 +0200879 static int
880list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
881{
882 Py_ssize_t i;
883 Py_ssize_t lsize = PySequence_Size(obj);
884 PyObject *litem;
885 listitem_T *li;
886
887 for(i=0; i<lsize; i++)
888 {
889 li = listitem_alloc();
890 if (li == NULL)
891 {
892 PyErr_NoMemory();
893 return -1;
894 }
895 li->li_tv.v_lock = 0;
896
897 litem = PySequence_GetItem(obj, i);
898 if (litem == NULL)
899 return -1;
900 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
901 return -1;
902
903 list_append(l, li);
904 }
905 return 0;
906}
907
Bram Moolenaardb913952012-06-29 12:54:53 +0200908 static PyInt
909ListLength(PyObject *self)
910{
911 return ((PyInt) (((ListObject *) (self))->list->lv_len));
912}
913
914 static PyObject *
915ListItem(PyObject *self, Py_ssize_t index)
916{
917 listitem_T *li;
918
919 if (index>=ListLength(self))
920 {
921 PyErr_SetString(PyExc_IndexError, "list index out of range");
922 return NULL;
923 }
924 li = list_find(((ListObject *) (self))->list, (long) index);
925 if (li == NULL)
926 {
927 PyErr_SetVim(_("internal error: failed to get vim list item"));
928 return NULL;
929 }
930 return ConvertToPyObject(&li->li_tv);
931}
932
933#define PROC_RANGE \
934 if (last < 0) {\
935 if (last < -size) \
936 last = 0; \
937 else \
938 last += size; \
939 } \
940 if (first < 0) \
941 first = 0; \
942 if (first > size) \
943 first = size; \
944 if (last > size) \
945 last = size;
946
947 static PyObject *
948ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
949{
950 PyInt i;
951 PyInt size = ListLength(self);
952 PyInt n;
953 PyObject *list;
954 int reversed = 0;
955
956 PROC_RANGE
957 if (first >= last)
958 first = last;
959
960 n = last-first;
961 list = PyList_New(n);
962 if (list == NULL)
963 return NULL;
964
965 for (i = 0; i < n; ++i)
966 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200967 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +0200968 if (item == NULL)
969 {
970 Py_DECREF(list);
971 return NULL;
972 }
973
974 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
975 {
976 Py_DECREF(item);
977 Py_DECREF(list);
978 return NULL;
979 }
980 }
981
982 return list;
983}
984
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200985typedef struct
986{
987 listwatch_T lw;
988 list_T *list;
989} listiterinfo_T;
990
991 static void
992ListIterDestruct(listiterinfo_T *lii)
993{
994 list_rem_watch(lii->list, &lii->lw);
995 PyMem_Free(lii);
996}
997
998 static PyObject *
999ListIterNext(listiterinfo_T **lii)
1000{
1001 PyObject *r;
1002
1003 if (!((*lii)->lw.lw_item))
1004 return NULL;
1005
1006 if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
1007 return NULL;
1008
1009 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
1010
1011 return r;
1012}
1013
1014 static PyObject *
1015ListIter(PyObject *self)
1016{
1017 listiterinfo_T *lii;
1018 list_T *l = ((ListObject *) (self))->list;
1019
1020 if (!(lii = PyMem_New(listiterinfo_T, 1)))
1021 {
1022 PyErr_NoMemory();
1023 return NULL;
1024 }
1025
1026 list_add_watch(l, &lii->lw);
1027 lii->lw.lw_item = l->lv_first;
1028 lii->list = l;
1029
1030 return IterNew(lii,
1031 (destructorfun) ListIterDestruct, (nextfun) ListIterNext);
1032}
1033
Bram Moolenaardb913952012-06-29 12:54:53 +02001034 static int
1035ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1036{
1037 typval_T tv;
1038 list_T *l = ((ListObject *) (self))->list;
1039 listitem_T *li;
1040 Py_ssize_t length = ListLength(self);
1041
1042 if (l->lv_lock)
1043 {
1044 PyErr_SetVim(_("list is locked"));
1045 return -1;
1046 }
1047 if (index>length || (index==length && obj==NULL))
1048 {
1049 PyErr_SetString(PyExc_IndexError, "list index out of range");
1050 return -1;
1051 }
1052
1053 if (obj == NULL)
1054 {
1055 li = list_find(l, (long) index);
1056 list_remove(l, li, li);
1057 clear_tv(&li->li_tv);
1058 vim_free(li);
1059 return 0;
1060 }
1061
1062 if (ConvertFromPyObject(obj, &tv) == -1)
1063 return -1;
1064
1065 if (index == length)
1066 {
1067 if (list_append_tv(l, &tv) == FAIL)
1068 {
1069 PyErr_SetVim(_("Failed to add item to list"));
1070 return -1;
1071 }
1072 }
1073 else
1074 {
1075 li = list_find(l, (long) index);
1076 clear_tv(&li->li_tv);
1077 copy_tv(&tv, &li->li_tv);
1078 }
1079 return 0;
1080}
1081
1082 static int
1083ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1084{
1085 PyInt size = ListLength(self);
1086 Py_ssize_t i;
1087 Py_ssize_t lsize;
1088 PyObject *litem;
1089 listitem_T *li;
1090 listitem_T *next;
1091 typval_T v;
1092 list_T *l = ((ListObject *) (self))->list;
1093
1094 if (l->lv_lock)
1095 {
1096 PyErr_SetVim(_("list is locked"));
1097 return -1;
1098 }
1099
1100 PROC_RANGE
1101
1102 if (first == size)
1103 li = NULL;
1104 else
1105 {
1106 li = list_find(l, (long) first);
1107 if (li == NULL)
1108 {
1109 PyErr_SetVim(_("internal error: no vim list item"));
1110 return -1;
1111 }
1112 if (last > first)
1113 {
1114 i = last - first;
1115 while (i-- && li != NULL)
1116 {
1117 next = li->li_next;
1118 listitem_remove(l, li);
1119 li = next;
1120 }
1121 }
1122 }
1123
1124 if (obj == NULL)
1125 return 0;
1126
1127 if (!PyList_Check(obj))
1128 {
1129 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1130 return -1;
1131 }
1132
1133 lsize = PyList_Size(obj);
1134
1135 for(i=0; i<lsize; i++)
1136 {
1137 litem = PyList_GetItem(obj, i);
1138 if (litem == NULL)
1139 return -1;
1140 if (ConvertFromPyObject(litem, &v) == -1)
1141 return -1;
1142 if (list_insert_tv(l, &v, li) == FAIL)
1143 {
1144 PyErr_SetVim(_("internal error: failed to add item to list"));
1145 return -1;
1146 }
1147 }
1148 return 0;
1149}
1150
1151 static PyObject *
1152ListConcatInPlace(PyObject *self, PyObject *obj)
1153{
1154 list_T *l = ((ListObject *) (self))->list;
1155 PyObject *lookup_dict;
1156
1157 if (l->lv_lock)
1158 {
1159 PyErr_SetVim(_("list is locked"));
1160 return NULL;
1161 }
1162
1163 if (!PySequence_Check(obj))
1164 {
1165 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1166 return NULL;
1167 }
1168
1169 lookup_dict = PyDict_New();
1170 if (list_py_concat(l, obj, lookup_dict) == -1)
1171 {
1172 Py_DECREF(lookup_dict);
1173 return NULL;
1174 }
1175 Py_DECREF(lookup_dict);
1176
1177 Py_INCREF(self);
1178 return self;
1179}
1180
Bram Moolenaar66b79852012-09-21 14:00:35 +02001181 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001182ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001183{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001184 ListObject *this = (ListObject *)(self);
1185
Bram Moolenaar66b79852012-09-21 14:00:35 +02001186 if (val == NULL)
1187 {
1188 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
1189 return -1;
1190 }
1191
1192 if (strcmp(name, "locked") == 0)
1193 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001194 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001195 {
1196 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
1197 return -1;
1198 }
1199 else
1200 {
Bram Moolenaar03db85b2013-05-15 14:51:35 +02001201 if (PyObject_IsTrue(val))
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001202 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001203 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001204 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001205 }
1206 return 0;
1207 }
1208 else
1209 {
1210 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
1211 return -1;
1212 }
1213}
1214
Bram Moolenaardb913952012-06-29 12:54:53 +02001215static struct PyMethodDef ListMethods[] = {
1216 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1217 { NULL, NULL, 0, NULL }
1218};
1219
1220typedef struct
1221{
1222 PyObject_HEAD
1223 char_u *name;
1224} FunctionObject;
1225
1226static PyTypeObject FunctionType;
1227
1228 static PyObject *
1229FunctionNew(char_u *name)
1230{
1231 FunctionObject *self;
1232
1233 self = PyObject_NEW(FunctionObject, &FunctionType);
1234 if (self == NULL)
1235 return NULL;
1236 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1237 if (self->name == NULL)
1238 {
1239 PyErr_NoMemory();
1240 return NULL;
1241 }
1242 STRCPY(self->name, name);
1243 func_ref(name);
1244 return (PyObject *)(self);
1245}
1246
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001247 static void
1248FunctionDestructor(PyObject *self)
1249{
1250 FunctionObject *this = (FunctionObject *) (self);
1251
1252 func_unref(this->name);
1253 PyMem_Del(this->name);
1254
1255 DESTRUCTOR_FINISH(self);
1256}
1257
Bram Moolenaardb913952012-06-29 12:54:53 +02001258 static PyObject *
1259FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1260{
1261 FunctionObject *this = (FunctionObject *)(self);
1262 char_u *name = this->name;
1263 typval_T args;
1264 typval_T selfdicttv;
1265 typval_T rettv;
1266 dict_T *selfdict = NULL;
1267 PyObject *selfdictObject;
1268 PyObject *result;
1269 int error;
1270
1271 if (ConvertFromPyObject(argsObject, &args) == -1)
1272 return NULL;
1273
1274 if (kwargs != NULL)
1275 {
1276 selfdictObject = PyDict_GetItemString(kwargs, "self");
1277 if (selfdictObject != NULL)
1278 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001279 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001280 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001281 PyErr_SetString(PyExc_TypeError,
1282 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001283 clear_tv(&args);
1284 return NULL;
1285 }
1286 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1287 return NULL;
1288 selfdict = selfdicttv.vval.v_dict;
1289 }
1290 }
1291
1292 error = func_call(name, &args, selfdict, &rettv);
1293 if (error != OK)
1294 {
1295 result = NULL;
1296 PyErr_SetVim(_("failed to run function"));
1297 }
1298 else
1299 result = ConvertToPyObject(&rettv);
1300
1301 /* FIXME Check what should really be cleared. */
1302 clear_tv(&args);
1303 clear_tv(&rettv);
1304 /*
1305 * if (selfdict!=NULL)
1306 * clear_tv(selfdicttv);
1307 */
1308
1309 return result;
1310}
1311
1312static struct PyMethodDef FunctionMethods[] = {
1313 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1314 { NULL, NULL, 0, NULL }
1315};
1316
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001317/*
1318 * Options object
1319 */
1320
1321static PyTypeObject OptionsType;
1322
1323typedef int (*checkfun)(void *);
1324
1325typedef struct
1326{
1327 PyObject_HEAD
1328 int opt_type;
1329 void *from;
1330 checkfun Check;
1331 PyObject *fromObj;
1332} OptionsObject;
1333
1334 static PyObject *
1335OptionsItem(OptionsObject *this, PyObject *keyObject)
1336{
1337 char_u *key;
1338 int flags;
1339 long numval;
1340 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001341 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001342
1343 if (this->Check(this->from))
1344 return NULL;
1345
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001346 DICTKEY_GET_NOTEMPTY(NULL)
1347
1348 flags = get_option_value_strict(key, &numval, &stringval,
1349 this->opt_type, this->from);
1350
1351 DICTKEY_UNREF
1352
1353 if (flags == 0)
1354 {
1355 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1356 return NULL;
1357 }
1358
1359 if (flags & SOPT_UNSET)
1360 {
1361 Py_INCREF(Py_None);
1362 return Py_None;
1363 }
1364 else if (flags & SOPT_BOOL)
1365 {
1366 PyObject *r;
1367 r = numval ? Py_True : Py_False;
1368 Py_INCREF(r);
1369 return r;
1370 }
1371 else if (flags & SOPT_NUM)
1372 return PyInt_FromLong(numval);
1373 else if (flags & SOPT_STRING)
1374 {
1375 if (stringval)
1376 return PyBytes_FromString((char *) stringval);
1377 else
1378 {
1379 PyErr_SetString(PyExc_ValueError, "Unable to get option value");
1380 return NULL;
1381 }
1382 }
1383 else
1384 {
1385 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1386 return NULL;
1387 }
1388}
1389
1390 static int
1391set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1392 char_u *key;
1393 int numval;
1394 char_u *stringval;
1395 int opt_flags;
1396 int opt_type;
1397 void *from;
1398{
1399 win_T *save_curwin;
1400 tabpage_T *save_curtab;
1401 aco_save_T aco;
1402 int r = 0;
1403
1404 switch (opt_type)
1405 {
1406 case SREQ_WIN:
1407 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1408 == FAIL)
1409 {
1410 PyErr_SetVim("Problem while switching windows.");
1411 return -1;
1412 }
1413 set_option_value(key, numval, stringval, opt_flags);
1414 restore_win(save_curwin, save_curtab);
1415 break;
1416 case SREQ_BUF:
1417 aucmd_prepbuf(&aco, (buf_T *) from);
1418 set_option_value(key, numval, stringval, opt_flags);
1419 aucmd_restbuf(&aco);
1420 break;
1421 case SREQ_GLOBAL:
1422 set_option_value(key, numval, stringval, opt_flags);
1423 break;
1424 }
1425 return r;
1426}
1427
1428 static int
1429OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1430{
1431 char_u *key;
1432 int flags;
1433 int opt_flags;
1434 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001435 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001436
1437 if (this->Check(this->from))
1438 return -1;
1439
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001440 DICTKEY_GET_NOTEMPTY(-1)
1441
1442 flags = get_option_value_strict(key, NULL, NULL,
1443 this->opt_type, this->from);
1444
1445 DICTKEY_UNREF
1446
1447 if (flags == 0)
1448 {
1449 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1450 return -1;
1451 }
1452
1453 if (valObject == NULL)
1454 {
1455 if (this->opt_type == SREQ_GLOBAL)
1456 {
1457 PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
1458 return -1;
1459 }
1460 else if (!(flags & SOPT_GLOBAL))
1461 {
1462 PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
1463 "global value");
1464 return -1;
1465 }
1466 else
1467 {
1468 unset_global_local_option(key, this->from);
1469 return 0;
1470 }
1471 }
1472
1473 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1474
1475 if (flags & SOPT_BOOL)
1476 {
Bram Moolenaar03db85b2013-05-15 14:51:35 +02001477 r = set_option_value_for(key, PyObject_IsTrue(valObject), NULL,
1478 opt_flags, this->opt_type, this->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001479 }
1480 else if (flags & SOPT_NUM)
1481 {
1482 int val;
1483
1484#if PY_MAJOR_VERSION < 3
1485 if (PyInt_Check(valObject))
1486 val = PyInt_AsLong(valObject);
1487 else
1488#endif
1489 if (PyLong_Check(valObject))
1490 val = PyLong_AsLong(valObject);
1491 else
1492 {
1493 PyErr_SetString(PyExc_ValueError, "Object must be integer");
1494 return -1;
1495 }
1496
1497 r = set_option_value_for(key, val, NULL, opt_flags,
1498 this->opt_type, this->from);
1499 }
1500 else
1501 {
1502 char_u *val;
1503 if (PyBytes_Check(valObject))
1504 {
1505
1506 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1507 return -1;
1508 if (val == NULL)
1509 return -1;
1510
1511 val = vim_strsave(val);
1512 }
1513 else if (PyUnicode_Check(valObject))
1514 {
1515 PyObject *bytes;
1516
1517 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1518 if (bytes == NULL)
1519 return -1;
1520
1521 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1522 return -1;
1523 if (val == NULL)
1524 return -1;
1525
1526 val = vim_strsave(val);
1527 Py_XDECREF(bytes);
1528 }
1529 else
1530 {
1531 PyErr_SetString(PyExc_ValueError, "Object must be string");
1532 return -1;
1533 }
1534
1535 r = set_option_value_for(key, 0, val, opt_flags,
1536 this->opt_type, this->from);
1537 vim_free(val);
1538 }
1539
1540 return r;
1541}
1542
1543 static int
1544dummy_check(void *arg UNUSED)
1545{
1546 return 0;
1547}
1548
1549 static PyObject *
1550OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1551{
1552 OptionsObject *self;
1553
1554 self = PyObject_NEW(OptionsObject, &OptionsType);
1555 if (self == NULL)
1556 return NULL;
1557
1558 self->opt_type = opt_type;
1559 self->from = from;
1560 self->Check = Check;
1561 self->fromObj = fromObj;
1562 if (fromObj)
1563 Py_INCREF(fromObj);
1564
1565 return (PyObject *)(self);
1566}
1567
1568 static void
1569OptionsDestructor(PyObject *self)
1570{
1571 if (((OptionsObject *)(self))->fromObj)
1572 Py_DECREF(((OptionsObject *)(self))->fromObj);
1573 DESTRUCTOR_FINISH(self);
1574}
1575
1576static PyMappingMethods OptionsAsMapping = {
1577 (lenfunc) NULL,
1578 (binaryfunc) OptionsItem,
1579 (objobjargproc) OptionsAssItem,
1580};
1581
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001582/* Window object
1583 */
1584
1585typedef struct
1586{
1587 PyObject_HEAD
1588 win_T *win;
1589} WindowObject;
1590
1591static int WindowSetattr(PyObject *, char *, PyObject *);
1592static PyObject *WindowRepr(PyObject *);
1593static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001594
1595 static int
1596CheckWindow(WindowObject *this)
1597{
1598 if (this->win == INVALID_WINDOW_VALUE)
1599 {
1600 PyErr_SetVim(_("attempt to refer to deleted window"));
1601 return -1;
1602 }
1603
1604 return 0;
1605}
1606
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001607 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001608WindowNew(win_T *win)
1609{
1610 /* We need to handle deletion of windows underneath us.
1611 * If we add a "w_python*_ref" field to the win_T structure,
1612 * then we can get at it in win_free() in vim. We then
1613 * need to create only ONE Python object per window - if
1614 * we try to create a second, just INCREF the existing one
1615 * and return it. The (single) Python object referring to
1616 * the window is stored in "w_python*_ref".
1617 * On a win_free() we set the Python object's win_T* field
1618 * to an invalid value. We trap all uses of a window
1619 * object, and reject them if the win_T* field is invalid.
1620 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001621 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001622 * w_python_ref and w_python3_ref fields respectively.
1623 */
1624
1625 WindowObject *self;
1626
1627 if (WIN_PYTHON_REF(win))
1628 {
1629 self = WIN_PYTHON_REF(win);
1630 Py_INCREF(self);
1631 }
1632 else
1633 {
1634 self = PyObject_NEW(WindowObject, &WindowType);
1635 if (self == NULL)
1636 return NULL;
1637 self->win = win;
1638 WIN_PYTHON_REF(win) = self;
1639 }
1640
1641 return (PyObject *)(self);
1642}
1643
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001644 static void
1645WindowDestructor(PyObject *self)
1646{
1647 WindowObject *this = (WindowObject *)(self);
1648
1649 if (this->win && this->win != INVALID_WINDOW_VALUE)
1650 WIN_PYTHON_REF(this->win) = NULL;
1651
1652 DESTRUCTOR_FINISH(self);
1653}
1654
Bram Moolenaar971db462013-05-12 18:44:48 +02001655 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001656WindowAttr(WindowObject *this, char *name)
1657{
1658 if (strcmp(name, "buffer") == 0)
1659 return (PyObject *)BufferNew(this->win->w_buffer);
1660 else if (strcmp(name, "cursor") == 0)
1661 {
1662 pos_T *pos = &this->win->w_cursor;
1663
1664 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1665 }
1666 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001667 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001668#ifdef FEAT_WINDOWS
1669 else if (strcmp(name, "row") == 0)
1670 return PyLong_FromLong((long)(this->win->w_winrow));
1671#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001672#ifdef FEAT_VERTSPLIT
1673 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001674 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001675 else if (strcmp(name, "col") == 0)
1676 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001677#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001678 else if (strcmp(name, "vars") == 0)
1679 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001680 else if (strcmp(name, "options") == 0)
1681 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1682 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001683 else if (strcmp(name, "number") == 0)
1684 return PyLong_FromLong((long) get_win_number(this->win));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001685 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001686 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1687 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001688 else
1689 return NULL;
1690}
1691
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001692 static int
1693WindowSetattr(PyObject *self, char *name, PyObject *val)
1694{
1695 WindowObject *this = (WindowObject *)(self);
1696
1697 if (CheckWindow(this))
1698 return -1;
1699
1700 if (strcmp(name, "buffer") == 0)
1701 {
1702 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1703 return -1;
1704 }
1705 else if (strcmp(name, "cursor") == 0)
1706 {
1707 long lnum;
1708 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001709
1710 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1711 return -1;
1712
1713 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1714 {
1715 PyErr_SetVim(_("cursor position outside buffer"));
1716 return -1;
1717 }
1718
1719 /* Check for keyboard interrupts */
1720 if (VimErrorCheck())
1721 return -1;
1722
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001723 this->win->w_cursor.lnum = lnum;
1724 this->win->w_cursor.col = col;
1725#ifdef FEAT_VIRTUALEDIT
1726 this->win->w_cursor.coladd = 0;
1727#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001728 /* When column is out of range silently correct it. */
1729 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001730
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001731 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001732 return 0;
1733 }
1734 else if (strcmp(name, "height") == 0)
1735 {
1736 int height;
1737 win_T *savewin;
1738
1739 if (!PyArg_Parse(val, "i", &height))
1740 return -1;
1741
1742#ifdef FEAT_GUI
1743 need_mouse_correct = TRUE;
1744#endif
1745 savewin = curwin;
1746 curwin = this->win;
1747 win_setheight(height);
1748 curwin = savewin;
1749
1750 /* Check for keyboard interrupts */
1751 if (VimErrorCheck())
1752 return -1;
1753
1754 return 0;
1755 }
1756#ifdef FEAT_VERTSPLIT
1757 else if (strcmp(name, "width") == 0)
1758 {
1759 int width;
1760 win_T *savewin;
1761
1762 if (!PyArg_Parse(val, "i", &width))
1763 return -1;
1764
1765#ifdef FEAT_GUI
1766 need_mouse_correct = TRUE;
1767#endif
1768 savewin = curwin;
1769 curwin = this->win;
1770 win_setwidth(width);
1771 curwin = savewin;
1772
1773 /* Check for keyboard interrupts */
1774 if (VimErrorCheck())
1775 return -1;
1776
1777 return 0;
1778 }
1779#endif
1780 else
1781 {
1782 PyErr_SetString(PyExc_AttributeError, name);
1783 return -1;
1784 }
1785}
1786
1787 static PyObject *
1788WindowRepr(PyObject *self)
1789{
1790 static char repr[100];
1791 WindowObject *this = (WindowObject *)(self);
1792
1793 if (this->win == INVALID_WINDOW_VALUE)
1794 {
1795 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1796 return PyString_FromString(repr);
1797 }
1798 else
1799 {
Bram Moolenaar6d216452013-05-12 19:00:41 +02001800 int w = get_win_number(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001801
Bram Moolenaar6d216452013-05-12 19:00:41 +02001802 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001803 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1804 (self));
1805 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001806 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001807
1808 return PyString_FromString(repr);
1809 }
1810}
1811
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001812static struct PyMethodDef WindowMethods[] = {
1813 /* name, function, calling, documentation */
1814 { NULL, NULL, 0, NULL }
1815};
1816
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001817/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001818 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001819 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001820
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001821static PyTypeObject WinListType;
1822static PySequenceMethods WinListAsSeq;
1823
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001824typedef struct
1825{
1826 PyObject_HEAD
1827} WinListObject;
1828
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001829 static PyInt
1830WinListLength(PyObject *self UNUSED)
1831{
1832 win_T *w = firstwin;
1833 PyInt n = 0;
1834
1835 while (w != NULL)
1836 {
1837 ++n;
1838 w = W_NEXT(w);
1839 }
1840
1841 return n;
1842}
1843
1844 static PyObject *
1845WinListItem(PyObject *self UNUSED, PyInt n)
1846{
1847 win_T *w;
1848
1849 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1850 if (n == 0)
1851 return WindowNew(w);
1852
1853 PyErr_SetString(PyExc_IndexError, _("no such window"));
1854 return NULL;
1855}
1856
1857/* Convert a Python string into a Vim line.
1858 *
1859 * The result is in allocated memory. All internal nulls are replaced by
1860 * newline characters. It is an error for the string to contain newline
1861 * characters.
1862 *
1863 * On errors, the Python exception data is set, and NULL is returned.
1864 */
1865 static char *
1866StringToLine(PyObject *obj)
1867{
1868 const char *str;
1869 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001870 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001871 PyInt len;
1872 PyInt i;
1873 char *p;
1874
1875 if (obj == NULL || !PyString_Check(obj))
1876 {
1877 PyErr_BadArgument();
1878 return NULL;
1879 }
1880
Bram Moolenaar19e60942011-06-19 00:27:51 +02001881 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1882 str = PyString_AsString(bytes);
1883 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001884
1885 /*
1886 * Error checking: String must not contain newlines, as we
1887 * are replacing a single line, and we must replace it with
1888 * a single line.
1889 * A trailing newline is removed, so that append(f.readlines()) works.
1890 */
1891 p = memchr(str, '\n', len);
1892 if (p != NULL)
1893 {
1894 if (p == str + len - 1)
1895 --len;
1896 else
1897 {
1898 PyErr_SetVim(_("string cannot contain newlines"));
1899 return NULL;
1900 }
1901 }
1902
1903 /* Create a copy of the string, with internal nulls replaced by
1904 * newline characters, as is the vim convention.
1905 */
1906 save = (char *)alloc((unsigned)(len+1));
1907 if (save == NULL)
1908 {
1909 PyErr_NoMemory();
1910 return NULL;
1911 }
1912
1913 for (i = 0; i < len; ++i)
1914 {
1915 if (str[i] == '\0')
1916 save[i] = '\n';
1917 else
1918 save[i] = str[i];
1919 }
1920
1921 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001922 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001923
1924 return save;
1925}
1926
1927/* Get a line from the specified buffer. The line number is
1928 * in Vim format (1-based). The line is returned as a Python
1929 * string object.
1930 */
1931 static PyObject *
1932GetBufferLine(buf_T *buf, PyInt n)
1933{
1934 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1935}
1936
1937
1938/* Get a list of lines from the specified buffer. The line numbers
1939 * are in Vim format (1-based). The range is from lo up to, but not
1940 * including, hi. The list is returned as a Python list of string objects.
1941 */
1942 static PyObject *
1943GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1944{
1945 PyInt i;
1946 PyInt n = hi - lo;
1947 PyObject *list = PyList_New(n);
1948
1949 if (list == NULL)
1950 return NULL;
1951
1952 for (i = 0; i < n; ++i)
1953 {
1954 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1955
1956 /* Error check - was the Python string creation OK? */
1957 if (str == NULL)
1958 {
1959 Py_DECREF(list);
1960 return NULL;
1961 }
1962
1963 /* Set the list item */
1964 if (PyList_SetItem(list, i, str))
1965 {
1966 Py_DECREF(str);
1967 Py_DECREF(list);
1968 return NULL;
1969 }
1970 }
1971
1972 /* The ownership of the Python list is passed to the caller (ie,
1973 * the caller should Py_DECREF() the object when it is finished
1974 * with it).
1975 */
1976
1977 return list;
1978}
1979
1980/*
1981 * Check if deleting lines made the cursor position invalid.
1982 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1983 * deleted).
1984 */
1985 static void
1986py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1987{
1988 if (curwin->w_cursor.lnum >= lo)
1989 {
1990 /* Adjust the cursor position if it's in/after the changed
1991 * lines. */
1992 if (curwin->w_cursor.lnum >= hi)
1993 {
1994 curwin->w_cursor.lnum += extra;
1995 check_cursor_col();
1996 }
1997 else if (extra < 0)
1998 {
1999 curwin->w_cursor.lnum = lo;
2000 check_cursor();
2001 }
2002 else
2003 check_cursor_col();
2004 changed_cline_bef_curs();
2005 }
2006 invalidate_botline();
2007}
2008
Bram Moolenaar19e60942011-06-19 00:27:51 +02002009/*
2010 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002011 * in Vim format (1-based). The replacement line is given as
2012 * a Python string object. The object is checked for validity
2013 * and correct format. Errors are returned as a value of FAIL.
2014 * The return value is OK on success.
2015 * If OK is returned and len_change is not NULL, *len_change
2016 * is set to the change in the buffer length.
2017 */
2018 static int
2019SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2020{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002021 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002022 * There are three cases:
2023 * 1. NULL, or None - this is a deletion.
2024 * 2. A string - this is a replacement.
2025 * 3. Anything else - this is an error.
2026 */
2027 if (line == Py_None || line == NULL)
2028 {
2029 buf_T *savebuf = curbuf;
2030
2031 PyErr_Clear();
2032 curbuf = buf;
2033
2034 if (u_savedel((linenr_T)n, 1L) == FAIL)
2035 PyErr_SetVim(_("cannot save undo information"));
2036 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2037 PyErr_SetVim(_("cannot delete line"));
2038 else
2039 {
2040 if (buf == curwin->w_buffer)
2041 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2042 deleted_lines_mark((linenr_T)n, 1L);
2043 }
2044
2045 curbuf = savebuf;
2046
2047 if (PyErr_Occurred() || VimErrorCheck())
2048 return FAIL;
2049
2050 if (len_change)
2051 *len_change = -1;
2052
2053 return OK;
2054 }
2055 else if (PyString_Check(line))
2056 {
2057 char *save = StringToLine(line);
2058 buf_T *savebuf = curbuf;
2059
2060 if (save == NULL)
2061 return FAIL;
2062
2063 /* We do not need to free "save" if ml_replace() consumes it. */
2064 PyErr_Clear();
2065 curbuf = buf;
2066
2067 if (u_savesub((linenr_T)n) == FAIL)
2068 {
2069 PyErr_SetVim(_("cannot save undo information"));
2070 vim_free(save);
2071 }
2072 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2073 {
2074 PyErr_SetVim(_("cannot replace line"));
2075 vim_free(save);
2076 }
2077 else
2078 changed_bytes((linenr_T)n, 0);
2079
2080 curbuf = savebuf;
2081
2082 /* Check that the cursor is not beyond the end of the line now. */
2083 if (buf == curwin->w_buffer)
2084 check_cursor_col();
2085
2086 if (PyErr_Occurred() || VimErrorCheck())
2087 return FAIL;
2088
2089 if (len_change)
2090 *len_change = 0;
2091
2092 return OK;
2093 }
2094 else
2095 {
2096 PyErr_BadArgument();
2097 return FAIL;
2098 }
2099}
2100
Bram Moolenaar19e60942011-06-19 00:27:51 +02002101/* Replace a range of lines in the specified buffer. The line numbers are in
2102 * Vim format (1-based). The range is from lo up to, but not including, hi.
2103 * The replacement lines are given as a Python list of string objects. The
2104 * list is checked for validity and correct format. Errors are returned as a
2105 * value of FAIL. The return value is OK on success.
2106 * If OK is returned and len_change is not NULL, *len_change
2107 * is set to the change in the buffer length.
2108 */
2109 static int
2110SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2111{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002112 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002113 * There are three cases:
2114 * 1. NULL, or None - this is a deletion.
2115 * 2. A list - this is a replacement.
2116 * 3. Anything else - this is an error.
2117 */
2118 if (list == Py_None || list == NULL)
2119 {
2120 PyInt i;
2121 PyInt n = (int)(hi - lo);
2122 buf_T *savebuf = curbuf;
2123
2124 PyErr_Clear();
2125 curbuf = buf;
2126
2127 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2128 PyErr_SetVim(_("cannot save undo information"));
2129 else
2130 {
2131 for (i = 0; i < n; ++i)
2132 {
2133 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2134 {
2135 PyErr_SetVim(_("cannot delete line"));
2136 break;
2137 }
2138 }
2139 if (buf == curwin->w_buffer)
2140 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2141 deleted_lines_mark((linenr_T)lo, (long)i);
2142 }
2143
2144 curbuf = savebuf;
2145
2146 if (PyErr_Occurred() || VimErrorCheck())
2147 return FAIL;
2148
2149 if (len_change)
2150 *len_change = -n;
2151
2152 return OK;
2153 }
2154 else if (PyList_Check(list))
2155 {
2156 PyInt i;
2157 PyInt new_len = PyList_Size(list);
2158 PyInt old_len = hi - lo;
2159 PyInt extra = 0; /* lines added to text, can be negative */
2160 char **array;
2161 buf_T *savebuf;
2162
2163 if (new_len == 0) /* avoid allocating zero bytes */
2164 array = NULL;
2165 else
2166 {
2167 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2168 if (array == NULL)
2169 {
2170 PyErr_NoMemory();
2171 return FAIL;
2172 }
2173 }
2174
2175 for (i = 0; i < new_len; ++i)
2176 {
2177 PyObject *line = PyList_GetItem(list, i);
2178
2179 array[i] = StringToLine(line);
2180 if (array[i] == NULL)
2181 {
2182 while (i)
2183 vim_free(array[--i]);
2184 vim_free(array);
2185 return FAIL;
2186 }
2187 }
2188
2189 savebuf = curbuf;
2190
2191 PyErr_Clear();
2192 curbuf = buf;
2193
2194 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2195 PyErr_SetVim(_("cannot save undo information"));
2196
2197 /* If the size of the range is reducing (ie, new_len < old_len) we
2198 * need to delete some old_len. We do this at the start, by
2199 * repeatedly deleting line "lo".
2200 */
2201 if (!PyErr_Occurred())
2202 {
2203 for (i = 0; i < old_len - new_len; ++i)
2204 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2205 {
2206 PyErr_SetVim(_("cannot delete line"));
2207 break;
2208 }
2209 extra -= i;
2210 }
2211
2212 /* For as long as possible, replace the existing old_len with the
2213 * new old_len. This is a more efficient operation, as it requires
2214 * less memory allocation and freeing.
2215 */
2216 if (!PyErr_Occurred())
2217 {
2218 for (i = 0; i < old_len && i < new_len; ++i)
2219 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2220 == FAIL)
2221 {
2222 PyErr_SetVim(_("cannot replace line"));
2223 break;
2224 }
2225 }
2226 else
2227 i = 0;
2228
2229 /* Now we may need to insert the remaining new old_len. If we do, we
2230 * must free the strings as we finish with them (we can't pass the
2231 * responsibility to vim in this case).
2232 */
2233 if (!PyErr_Occurred())
2234 {
2235 while (i < new_len)
2236 {
2237 if (ml_append((linenr_T)(lo + i - 1),
2238 (char_u *)array[i], 0, FALSE) == FAIL)
2239 {
2240 PyErr_SetVim(_("cannot insert line"));
2241 break;
2242 }
2243 vim_free(array[i]);
2244 ++i;
2245 ++extra;
2246 }
2247 }
2248
2249 /* Free any left-over old_len, as a result of an error */
2250 while (i < new_len)
2251 {
2252 vim_free(array[i]);
2253 ++i;
2254 }
2255
2256 /* Free the array of old_len. All of its contents have now
2257 * been dealt with (either freed, or the responsibility passed
2258 * to vim.
2259 */
2260 vim_free(array);
2261
2262 /* Adjust marks. Invalidate any which lie in the
2263 * changed range, and move any in the remainder of the buffer.
2264 */
2265 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2266 (long)MAXLNUM, (long)extra);
2267 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2268
2269 if (buf == curwin->w_buffer)
2270 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2271
2272 curbuf = savebuf;
2273
2274 if (PyErr_Occurred() || VimErrorCheck())
2275 return FAIL;
2276
2277 if (len_change)
2278 *len_change = new_len - old_len;
2279
2280 return OK;
2281 }
2282 else
2283 {
2284 PyErr_BadArgument();
2285 return FAIL;
2286 }
2287}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002288
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002289/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002290 * The line number is in Vim format (1-based). The lines to be inserted are
2291 * given as a Python list of string objects or as a single string. The lines
2292 * to be added are checked for validity and correct format. Errors are
2293 * returned as a value of FAIL. The return value is OK on success.
2294 * If OK is returned and len_change is not NULL, *len_change
2295 * is set to the change in the buffer length.
2296 */
2297 static int
2298InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2299{
2300 /* First of all, we check the type of the supplied Python object.
2301 * It must be a string or a list, or the call is in error.
2302 */
2303 if (PyString_Check(lines))
2304 {
2305 char *str = StringToLine(lines);
2306 buf_T *savebuf;
2307
2308 if (str == NULL)
2309 return FAIL;
2310
2311 savebuf = curbuf;
2312
2313 PyErr_Clear();
2314 curbuf = buf;
2315
2316 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2317 PyErr_SetVim(_("cannot save undo information"));
2318 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2319 PyErr_SetVim(_("cannot insert line"));
2320 else
2321 appended_lines_mark((linenr_T)n, 1L);
2322
2323 vim_free(str);
2324 curbuf = savebuf;
2325 update_screen(VALID);
2326
2327 if (PyErr_Occurred() || VimErrorCheck())
2328 return FAIL;
2329
2330 if (len_change)
2331 *len_change = 1;
2332
2333 return OK;
2334 }
2335 else if (PyList_Check(lines))
2336 {
2337 PyInt i;
2338 PyInt size = PyList_Size(lines);
2339 char **array;
2340 buf_T *savebuf;
2341
2342 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2343 if (array == NULL)
2344 {
2345 PyErr_NoMemory();
2346 return FAIL;
2347 }
2348
2349 for (i = 0; i < size; ++i)
2350 {
2351 PyObject *line = PyList_GetItem(lines, i);
2352 array[i] = StringToLine(line);
2353
2354 if (array[i] == NULL)
2355 {
2356 while (i)
2357 vim_free(array[--i]);
2358 vim_free(array);
2359 return FAIL;
2360 }
2361 }
2362
2363 savebuf = curbuf;
2364
2365 PyErr_Clear();
2366 curbuf = buf;
2367
2368 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2369 PyErr_SetVim(_("cannot save undo information"));
2370 else
2371 {
2372 for (i = 0; i < size; ++i)
2373 {
2374 if (ml_append((linenr_T)(n + i),
2375 (char_u *)array[i], 0, FALSE) == FAIL)
2376 {
2377 PyErr_SetVim(_("cannot insert line"));
2378
2379 /* Free the rest of the lines */
2380 while (i < size)
2381 vim_free(array[i++]);
2382
2383 break;
2384 }
2385 vim_free(array[i]);
2386 }
2387 if (i > 0)
2388 appended_lines_mark((linenr_T)n, (long)i);
2389 }
2390
2391 /* Free the array of lines. All of its contents have now
2392 * been freed.
2393 */
2394 vim_free(array);
2395
2396 curbuf = savebuf;
2397 update_screen(VALID);
2398
2399 if (PyErr_Occurred() || VimErrorCheck())
2400 return FAIL;
2401
2402 if (len_change)
2403 *len_change = size;
2404
2405 return OK;
2406 }
2407 else
2408 {
2409 PyErr_BadArgument();
2410 return FAIL;
2411 }
2412}
2413
2414/*
2415 * Common routines for buffers and line ranges
2416 * -------------------------------------------
2417 */
2418
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002419typedef struct
2420{
2421 PyObject_HEAD
2422 buf_T *buf;
2423} BufferObject;
2424
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002425 static int
2426CheckBuffer(BufferObject *this)
2427{
2428 if (this->buf == INVALID_BUFFER_VALUE)
2429 {
2430 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2431 return -1;
2432 }
2433
2434 return 0;
2435}
2436
2437 static PyObject *
2438RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2439{
2440 if (CheckBuffer(self))
2441 return NULL;
2442
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002443 if (end == -1)
2444 end = self->buf->b_ml.ml_line_count;
2445
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002446 if (n < 0)
2447 n += end - start + 1;
2448
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002449 if (n < 0 || n > end - start)
2450 {
2451 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2452 return NULL;
2453 }
2454
2455 return GetBufferLine(self->buf, n+start);
2456}
2457
2458 static PyObject *
2459RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2460{
2461 PyInt size;
2462
2463 if (CheckBuffer(self))
2464 return NULL;
2465
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002466 if (end == -1)
2467 end = self->buf->b_ml.ml_line_count;
2468
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002469 size = end - start + 1;
2470
2471 if (lo < 0)
2472 lo = 0;
2473 else if (lo > size)
2474 lo = size;
2475 if (hi < 0)
2476 hi = 0;
2477 if (hi < lo)
2478 hi = lo;
2479 else if (hi > size)
2480 hi = size;
2481
2482 return GetBufferLineList(self->buf, lo+start, hi+start);
2483}
2484
2485 static PyInt
2486RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2487{
2488 PyInt len_change;
2489
2490 if (CheckBuffer(self))
2491 return -1;
2492
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002493 if (end == -1)
2494 end = self->buf->b_ml.ml_line_count;
2495
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002496 if (n < 0)
2497 n += end - start + 1;
2498
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002499 if (n < 0 || n > end - start)
2500 {
2501 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2502 return -1;
2503 }
2504
2505 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2506 return -1;
2507
2508 if (new_end)
2509 *new_end = end + len_change;
2510
2511 return 0;
2512}
2513
Bram Moolenaar19e60942011-06-19 00:27:51 +02002514 static PyInt
2515RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2516{
2517 PyInt size;
2518 PyInt len_change;
2519
2520 /* Self must be a valid buffer */
2521 if (CheckBuffer(self))
2522 return -1;
2523
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002524 if (end == -1)
2525 end = self->buf->b_ml.ml_line_count;
2526
Bram Moolenaar19e60942011-06-19 00:27:51 +02002527 /* Sort out the slice range */
2528 size = end - start + 1;
2529
2530 if (lo < 0)
2531 lo = 0;
2532 else if (lo > size)
2533 lo = size;
2534 if (hi < 0)
2535 hi = 0;
2536 if (hi < lo)
2537 hi = lo;
2538 else if (hi > size)
2539 hi = size;
2540
2541 if (SetBufferLineList(self->buf, lo + start, hi + start,
2542 val, &len_change) == FAIL)
2543 return -1;
2544
2545 if (new_end)
2546 *new_end = end + len_change;
2547
2548 return 0;
2549}
2550
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002551
2552 static PyObject *
2553RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2554{
2555 PyObject *lines;
2556 PyInt len_change;
2557 PyInt max;
2558 PyInt n;
2559
2560 if (CheckBuffer(self))
2561 return NULL;
2562
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002563 if (end == -1)
2564 end = self->buf->b_ml.ml_line_count;
2565
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002566 max = n = end - start + 1;
2567
2568 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2569 return NULL;
2570
2571 if (n < 0 || n > max)
2572 {
2573 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2574 return NULL;
2575 }
2576
2577 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2578 return NULL;
2579
2580 if (new_end)
2581 *new_end = end + len_change;
2582
2583 Py_INCREF(Py_None);
2584 return Py_None;
2585}
2586
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002587/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002588 */
2589
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002590static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002591static PySequenceMethods RangeAsSeq;
2592static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002593
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002594typedef struct
2595{
2596 PyObject_HEAD
2597 BufferObject *buf;
2598 PyInt start;
2599 PyInt end;
2600} RangeObject;
2601
2602 static PyObject *
2603RangeNew(buf_T *buf, PyInt start, PyInt end)
2604{
2605 BufferObject *bufr;
2606 RangeObject *self;
2607 self = PyObject_NEW(RangeObject, &RangeType);
2608 if (self == NULL)
2609 return NULL;
2610
2611 bufr = (BufferObject *)BufferNew(buf);
2612 if (bufr == NULL)
2613 {
2614 Py_DECREF(self);
2615 return NULL;
2616 }
2617 Py_INCREF(bufr);
2618
2619 self->buf = bufr;
2620 self->start = start;
2621 self->end = end;
2622
2623 return (PyObject *)(self);
2624}
2625
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002626 static void
2627RangeDestructor(PyObject *self)
2628{
2629 Py_DECREF(((RangeObject *)(self))->buf);
2630 DESTRUCTOR_FINISH(self);
2631}
2632
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002633 static PyInt
2634RangeLength(PyObject *self)
2635{
2636 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2637 if (CheckBuffer(((RangeObject *)(self))->buf))
2638 return -1; /* ??? */
2639
2640 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2641}
2642
2643 static PyObject *
2644RangeItem(PyObject *self, PyInt n)
2645{
2646 return RBItem(((RangeObject *)(self))->buf, n,
2647 ((RangeObject *)(self))->start,
2648 ((RangeObject *)(self))->end);
2649}
2650
2651 static PyObject *
2652RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2653{
2654 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2655 ((RangeObject *)(self))->start,
2656 ((RangeObject *)(self))->end);
2657}
2658
2659 static PyObject *
2660RangeAppend(PyObject *self, PyObject *args)
2661{
2662 return RBAppend(((RangeObject *)(self))->buf, args,
2663 ((RangeObject *)(self))->start,
2664 ((RangeObject *)(self))->end,
2665 &((RangeObject *)(self))->end);
2666}
2667
2668 static PyObject *
2669RangeRepr(PyObject *self)
2670{
2671 static char repr[100];
2672 RangeObject *this = (RangeObject *)(self);
2673
2674 if (this->buf->buf == INVALID_BUFFER_VALUE)
2675 {
2676 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2677 (self));
2678 return PyString_FromString(repr);
2679 }
2680 else
2681 {
2682 char *name = (char *)this->buf->buf->b_fname;
2683 int len;
2684
2685 if (name == NULL)
2686 name = "";
2687 len = (int)strlen(name);
2688
2689 if (len > 45)
2690 name = name + (45 - len);
2691
2692 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2693 len > 45 ? "..." : "", name,
2694 this->start, this->end);
2695
2696 return PyString_FromString(repr);
2697 }
2698}
2699
2700static struct PyMethodDef RangeMethods[] = {
2701 /* name, function, calling, documentation */
2702 {"append", RangeAppend, 1, "Append data to the Vim range" },
2703 { NULL, NULL, 0, NULL }
2704};
2705
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002706static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002707static PySequenceMethods BufferAsSeq;
2708static PyMappingMethods BufferAsMapping;
2709
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002710 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002711BufferNew(buf_T *buf)
2712{
2713 /* We need to handle deletion of buffers underneath us.
2714 * If we add a "b_python*_ref" field to the buf_T structure,
2715 * then we can get at it in buf_freeall() in vim. We then
2716 * need to create only ONE Python object per buffer - if
2717 * we try to create a second, just INCREF the existing one
2718 * and return it. The (single) Python object referring to
2719 * the buffer is stored in "b_python*_ref".
2720 * Question: what to do on a buf_freeall(). We'll probably
2721 * have to either delete the Python object (DECREF it to
2722 * zero - a bad idea, as it leaves dangling refs!) or
2723 * set the buf_T * value to an invalid value (-1?), which
2724 * means we need checks in all access functions... Bah.
2725 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002726 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02002727 * b_python_ref and b_python3_ref fields respectively.
2728 */
2729
2730 BufferObject *self;
2731
2732 if (BUF_PYTHON_REF(buf) != NULL)
2733 {
2734 self = BUF_PYTHON_REF(buf);
2735 Py_INCREF(self);
2736 }
2737 else
2738 {
2739 self = PyObject_NEW(BufferObject, &BufferType);
2740 if (self == NULL)
2741 return NULL;
2742 self->buf = buf;
2743 BUF_PYTHON_REF(buf) = self;
2744 }
2745
2746 return (PyObject *)(self);
2747}
2748
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002749 static void
2750BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002751{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002752 BufferObject *this = (BufferObject *)(self);
2753
2754 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2755 BUF_PYTHON_REF(this->buf) = NULL;
2756
2757 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002758}
2759
Bram Moolenaar971db462013-05-12 18:44:48 +02002760 static PyInt
2761BufferLength(PyObject *self)
2762{
2763 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2764 if (CheckBuffer((BufferObject *)(self)))
2765 return -1; /* ??? */
2766
2767 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2768}
2769
2770 static PyObject *
2771BufferItem(PyObject *self, PyInt n)
2772{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002773 return RBItem((BufferObject *)(self), n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002774}
2775
2776 static PyObject *
2777BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2778{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002779 return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002780}
2781
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002782 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002783BufferAttr(BufferObject *this, char *name)
2784{
2785 if (strcmp(name, "name") == 0)
2786 return Py_BuildValue("s", this->buf->b_ffname);
2787 else if (strcmp(name, "number") == 0)
2788 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
2789 else if (strcmp(name, "vars") == 0)
2790 return DictionaryNew(this->buf->b_vars);
2791 else if (strcmp(name, "options") == 0)
2792 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2793 (PyObject *) this);
2794 else if (strcmp(name,"__members__") == 0)
2795 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
2796 else
2797 return NULL;
2798}
2799
2800 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002801BufferAppend(PyObject *self, PyObject *args)
2802{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002803 return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002804}
2805
2806 static PyObject *
2807BufferMark(PyObject *self, PyObject *args)
2808{
2809 pos_T *posp;
2810 char *pmark;
2811 char mark;
2812 buf_T *curbuf_save;
2813
2814 if (CheckBuffer((BufferObject *)(self)))
2815 return NULL;
2816
2817 if (!PyArg_ParseTuple(args, "s", &pmark))
2818 return NULL;
2819 mark = *pmark;
2820
2821 curbuf_save = curbuf;
2822 curbuf = ((BufferObject *)(self))->buf;
2823 posp = getmark(mark, FALSE);
2824 curbuf = curbuf_save;
2825
2826 if (posp == NULL)
2827 {
2828 PyErr_SetVim(_("invalid mark name"));
2829 return NULL;
2830 }
2831
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002832 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002833 if (VimErrorCheck())
2834 return NULL;
2835
2836 if (posp->lnum <= 0)
2837 {
2838 /* Or raise an error? */
2839 Py_INCREF(Py_None);
2840 return Py_None;
2841 }
2842
2843 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2844}
2845
2846 static PyObject *
2847BufferRange(PyObject *self, PyObject *args)
2848{
2849 PyInt start;
2850 PyInt end;
2851
2852 if (CheckBuffer((BufferObject *)(self)))
2853 return NULL;
2854
2855 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2856 return NULL;
2857
2858 return RangeNew(((BufferObject *)(self))->buf, start, end);
2859}
2860
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002861 static PyObject *
2862BufferRepr(PyObject *self)
2863{
2864 static char repr[100];
2865 BufferObject *this = (BufferObject *)(self);
2866
2867 if (this->buf == INVALID_BUFFER_VALUE)
2868 {
2869 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2870 return PyString_FromString(repr);
2871 }
2872 else
2873 {
2874 char *name = (char *)this->buf->b_fname;
2875 PyInt len;
2876
2877 if (name == NULL)
2878 name = "";
2879 len = strlen(name);
2880
2881 if (len > 35)
2882 name = name + (35 - len);
2883
2884 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2885
2886 return PyString_FromString(repr);
2887 }
2888}
2889
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002890static struct PyMethodDef BufferMethods[] = {
2891 /* name, function, calling, documentation */
2892 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2893 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2894 {"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 +01002895#if PY_VERSION_HEX >= 0x03000000
2896 {"__dir__", BufferDir, 4, "List its attributes" },
2897#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002898 { NULL, NULL, 0, NULL }
2899};
2900
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02002901/*
2902 * Buffer list object - Implementation
2903 */
2904
2905static PyTypeObject BufMapType;
2906
2907typedef struct
2908{
2909 PyObject_HEAD
2910} BufMapObject;
2911
2912 static PyInt
2913BufMapLength(PyObject *self UNUSED)
2914{
2915 buf_T *b = firstbuf;
2916 PyInt n = 0;
2917
2918 while (b)
2919 {
2920 ++n;
2921 b = b->b_next;
2922 }
2923
2924 return n;
2925}
2926
2927 static PyObject *
2928BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
2929{
2930 buf_T *b;
2931 int bnr;
2932
2933#if PY_MAJOR_VERSION < 3
2934 if (PyInt_Check(keyObject))
2935 bnr = PyInt_AsLong(keyObject);
2936 else
2937#endif
2938 if (PyLong_Check(keyObject))
2939 bnr = PyLong_AsLong(keyObject);
2940 else
2941 {
2942 PyErr_SetString(PyExc_ValueError, _("key must be integer"));
2943 return NULL;
2944 }
2945
2946 b = buflist_findnr(bnr);
2947
2948 if (b)
2949 return BufferNew(b);
2950 else
2951 {
2952 PyErr_SetString(PyExc_KeyError, _("no such buffer"));
2953 return NULL;
2954 }
2955}
2956
2957 static void
2958BufMapIterDestruct(PyObject *buffer)
2959{
2960 /* Iteration was stopped before all buffers were processed */
2961 if (buffer)
2962 {
2963 Py_DECREF(buffer);
2964 }
2965}
2966
2967 static PyObject *
2968BufMapIterNext(PyObject **buffer)
2969{
2970 PyObject *next;
2971 PyObject *r;
2972
2973 if (!*buffer)
2974 return NULL;
2975
2976 r = *buffer;
2977
2978 if (CheckBuffer((BufferObject *)(r)))
2979 {
2980 *buffer = NULL;
2981 return NULL;
2982 }
2983
2984 if (!((BufferObject *)(r))->buf->b_next)
2985 next = NULL;
2986 else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
2987 return NULL;
2988 *buffer = next;
2989 /* Do not increment reference: we no longer hold it (decref), but whoever on
2990 * other side will hold (incref). Decref+incref = nothing.
2991 */
2992 return r;
2993}
2994
2995 static PyObject *
2996BufMapIter(PyObject *self UNUSED)
2997{
2998 PyObject *buffer;
2999
3000 buffer = BufferNew(firstbuf);
3001 return IterNew(buffer,
3002 (destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext);
3003}
3004
3005static PyMappingMethods BufMapAsMapping = {
3006 (lenfunc) BufMapLength,
3007 (binaryfunc) BufMapItem,
3008 (objobjargproc) 0,
3009};
3010
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003011/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003012 */
3013
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003014 static PyObject *
3015CurrentGetattr(PyObject *self UNUSED, char *name)
3016{
3017 if (strcmp(name, "buffer") == 0)
3018 return (PyObject *)BufferNew(curbuf);
3019 else if (strcmp(name, "window") == 0)
3020 return (PyObject *)WindowNew(curwin);
3021 else if (strcmp(name, "line") == 0)
3022 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3023 else if (strcmp(name, "range") == 0)
3024 return RangeNew(curbuf, RangeStart, RangeEnd);
3025 else if (strcmp(name,"__members__") == 0)
3026 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
3027 else
3028 {
3029 PyErr_SetString(PyExc_AttributeError, name);
3030 return NULL;
3031 }
3032}
3033
3034 static int
3035CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3036{
3037 if (strcmp(name, "line") == 0)
3038 {
3039 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3040 return -1;
3041
3042 return 0;
3043 }
3044 else
3045 {
3046 PyErr_SetString(PyExc_AttributeError, name);
3047 return -1;
3048 }
3049}
3050
Bram Moolenaardb913952012-06-29 12:54:53 +02003051 static void
3052set_ref_in_py(const int copyID)
3053{
3054 pylinkedlist_T *cur;
3055 dict_T *dd;
3056 list_T *ll;
3057
3058 if (lastdict != NULL)
3059 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3060 {
3061 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3062 if (dd->dv_copyID != copyID)
3063 {
3064 dd->dv_copyID = copyID;
3065 set_ref_in_ht(&dd->dv_hashtab, copyID);
3066 }
3067 }
3068
3069 if (lastlist != NULL)
3070 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3071 {
3072 ll = ((ListObject *) (cur->pll_obj))->list;
3073 if (ll->lv_copyID != copyID)
3074 {
3075 ll->lv_copyID = copyID;
3076 set_ref_in_list(ll, copyID);
3077 }
3078 }
3079}
3080
3081 static int
3082set_string_copy(char_u *str, typval_T *tv)
3083{
3084 tv->vval.v_string = vim_strsave(str);
3085 if (tv->vval.v_string == NULL)
3086 {
3087 PyErr_NoMemory();
3088 return -1;
3089 }
3090 return 0;
3091}
3092
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003093 static int
3094pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3095{
3096 dict_T *d;
3097 char_u *key;
3098 dictitem_T *di;
3099 PyObject *keyObject;
3100 PyObject *valObject;
3101 Py_ssize_t iter = 0;
3102
3103 d = dict_alloc();
3104 if (d == NULL)
3105 {
3106 PyErr_NoMemory();
3107 return -1;
3108 }
3109
3110 tv->v_type = VAR_DICT;
3111 tv->vval.v_dict = d;
3112
3113 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
3114 {
3115 DICTKEY_DECL
3116
3117 if (keyObject == NULL)
3118 return -1;
3119 if (valObject == NULL)
3120 return -1;
3121
3122 DICTKEY_GET_NOTEMPTY(-1)
3123
3124 di = dictitem_alloc(key);
3125
3126 DICTKEY_UNREF
3127
3128 if (di == NULL)
3129 {
3130 PyErr_NoMemory();
3131 return -1;
3132 }
3133 di->di_tv.v_lock = 0;
3134
3135 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3136 {
3137 vim_free(di);
3138 return -1;
3139 }
3140 if (dict_add(d, di) == FAIL)
3141 {
3142 vim_free(di);
3143 PyErr_SetVim(_("failed to add key to dictionary"));
3144 return -1;
3145 }
3146 }
3147 return 0;
3148}
3149
3150 static int
3151pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3152{
3153 dict_T *d;
3154 char_u *key;
3155 dictitem_T *di;
3156 PyObject *list;
3157 PyObject *litem;
3158 PyObject *keyObject;
3159 PyObject *valObject;
3160 Py_ssize_t lsize;
3161
3162 d = dict_alloc();
3163 if (d == NULL)
3164 {
3165 PyErr_NoMemory();
3166 return -1;
3167 }
3168
3169 tv->v_type = VAR_DICT;
3170 tv->vval.v_dict = d;
3171
3172 list = PyMapping_Items(obj);
3173 if (list == NULL)
3174 return -1;
3175 lsize = PyList_Size(list);
3176 while (lsize--)
3177 {
3178 DICTKEY_DECL
3179
3180 litem = PyList_GetItem(list, lsize);
3181 if (litem == NULL)
3182 {
3183 Py_DECREF(list);
3184 return -1;
3185 }
3186
3187 keyObject = PyTuple_GetItem(litem, 0);
3188 if (keyObject == NULL)
3189 {
3190 Py_DECREF(list);
3191 Py_DECREF(litem);
3192 return -1;
3193 }
3194
3195 DICTKEY_GET_NOTEMPTY(-1)
3196
3197 valObject = PyTuple_GetItem(litem, 1);
3198 if (valObject == NULL)
3199 {
3200 Py_DECREF(list);
3201 Py_DECREF(litem);
3202 return -1;
3203 }
3204
3205 di = dictitem_alloc(key);
3206
3207 DICTKEY_UNREF
3208
3209 if (di == NULL)
3210 {
3211 Py_DECREF(list);
3212 Py_DECREF(litem);
3213 PyErr_NoMemory();
3214 return -1;
3215 }
3216 di->di_tv.v_lock = 0;
3217
3218 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3219 {
3220 vim_free(di);
3221 Py_DECREF(list);
3222 Py_DECREF(litem);
3223 return -1;
3224 }
3225 if (dict_add(d, di) == FAIL)
3226 {
3227 vim_free(di);
3228 Py_DECREF(list);
3229 Py_DECREF(litem);
3230 PyErr_SetVim(_("failed to add key to dictionary"));
3231 return -1;
3232 }
3233 Py_DECREF(litem);
3234 }
3235 Py_DECREF(list);
3236 return 0;
3237}
3238
3239 static int
3240pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3241{
3242 list_T *l;
3243
3244 l = list_alloc();
3245 if (l == NULL)
3246 {
3247 PyErr_NoMemory();
3248 return -1;
3249 }
3250
3251 tv->v_type = VAR_LIST;
3252 tv->vval.v_list = l;
3253
3254 if (list_py_concat(l, obj, lookupDict) == -1)
3255 return -1;
3256
3257 return 0;
3258}
3259
3260 static int
3261pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3262{
3263 PyObject *iterator = PyObject_GetIter(obj);
3264 PyObject *item;
3265 list_T *l;
3266 listitem_T *li;
3267
3268 l = list_alloc();
3269
3270 if (l == NULL)
3271 {
3272 PyErr_NoMemory();
3273 return -1;
3274 }
3275
3276 tv->vval.v_list = l;
3277 tv->v_type = VAR_LIST;
3278
3279
3280 if (iterator == NULL)
3281 return -1;
3282
3283 while ((item = PyIter_Next(obj)))
3284 {
3285 li = listitem_alloc();
3286 if (li == NULL)
3287 {
3288 PyErr_NoMemory();
3289 return -1;
3290 }
3291 li->li_tv.v_lock = 0;
3292
3293 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3294 return -1;
3295
3296 list_append(l, li);
3297
3298 Py_DECREF(item);
3299 }
3300
3301 Py_DECREF(iterator);
3302 return 0;
3303}
3304
Bram Moolenaardb913952012-06-29 12:54:53 +02003305typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3306
3307 static int
3308convert_dl(PyObject *obj, typval_T *tv,
3309 pytotvfunc py_to_tv, PyObject *lookupDict)
3310{
3311 PyObject *capsule;
3312 char hexBuf[sizeof(void *) * 2 + 3];
3313
3314 sprintf(hexBuf, "%p", obj);
3315
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003316# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003317 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003318# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003319 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003320# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003321 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003322 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003323# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003324 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003325# else
3326 capsule = PyCObject_FromVoidPtr(tv, NULL);
3327# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003328 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3329 Py_DECREF(capsule);
3330 if (py_to_tv(obj, tv, lookupDict) == -1)
3331 {
3332 tv->v_type = VAR_UNKNOWN;
3333 return -1;
3334 }
3335 /* As we are not using copy_tv which increments reference count we must
3336 * do it ourself. */
3337 switch(tv->v_type)
3338 {
3339 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3340 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3341 }
3342 }
3343 else
3344 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003345 typval_T *v;
3346
3347# ifdef PY_USE_CAPSULE
3348 v = PyCapsule_GetPointer(capsule, NULL);
3349# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003350 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003351# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003352 copy_tv(v, tv);
3353 }
3354 return 0;
3355}
3356
3357 static int
3358ConvertFromPyObject(PyObject *obj, typval_T *tv)
3359{
3360 PyObject *lookup_dict;
3361 int r;
3362
3363 lookup_dict = PyDict_New();
3364 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3365 Py_DECREF(lookup_dict);
3366 return r;
3367}
3368
3369 static int
3370_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3371{
3372 if (obj->ob_type == &DictionaryType)
3373 {
3374 tv->v_type = VAR_DICT;
3375 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3376 ++tv->vval.v_dict->dv_refcount;
3377 }
3378 else if (obj->ob_type == &ListType)
3379 {
3380 tv->v_type = VAR_LIST;
3381 tv->vval.v_list = (((ListObject *)(obj))->list);
3382 ++tv->vval.v_list->lv_refcount;
3383 }
3384 else if (obj->ob_type == &FunctionType)
3385 {
3386 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3387 return -1;
3388
3389 tv->v_type = VAR_FUNC;
3390 func_ref(tv->vval.v_string);
3391 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003392 else if (PyBytes_Check(obj))
3393 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003394 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003395
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003396 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3397 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003398 if (result == NULL)
3399 return -1;
3400
3401 if (set_string_copy(result, tv) == -1)
3402 return -1;
3403
3404 tv->v_type = VAR_STRING;
3405 }
3406 else if (PyUnicode_Check(obj))
3407 {
3408 PyObject *bytes;
3409 char_u *result;
3410
Bram Moolenaardb913952012-06-29 12:54:53 +02003411 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3412 if (bytes == NULL)
3413 return -1;
3414
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003415 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3416 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003417 if (result == NULL)
3418 return -1;
3419
3420 if (set_string_copy(result, tv) == -1)
3421 {
3422 Py_XDECREF(bytes);
3423 return -1;
3424 }
3425 Py_XDECREF(bytes);
3426
3427 tv->v_type = VAR_STRING;
3428 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003429#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003430 else if (PyInt_Check(obj))
3431 {
3432 tv->v_type = VAR_NUMBER;
3433 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3434 }
3435#endif
3436 else if (PyLong_Check(obj))
3437 {
3438 tv->v_type = VAR_NUMBER;
3439 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3440 }
3441 else if (PyDict_Check(obj))
3442 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3443#ifdef FEAT_FLOAT
3444 else if (PyFloat_Check(obj))
3445 {
3446 tv->v_type = VAR_FLOAT;
3447 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3448 }
3449#endif
3450 else if (PyIter_Check(obj))
3451 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3452 else if (PySequence_Check(obj))
3453 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3454 else if (PyMapping_Check(obj))
3455 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3456 else
3457 {
3458 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
3459 return -1;
3460 }
3461 return 0;
3462}
3463
3464 static PyObject *
3465ConvertToPyObject(typval_T *tv)
3466{
3467 if (tv == NULL)
3468 {
3469 PyErr_SetVim(_("NULL reference passed"));
3470 return NULL;
3471 }
3472 switch (tv->v_type)
3473 {
3474 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003475 return PyBytes_FromString(tv->vval.v_string == NULL
3476 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003477 case VAR_NUMBER:
3478 return PyLong_FromLong((long) tv->vval.v_number);
3479#ifdef FEAT_FLOAT
3480 case VAR_FLOAT:
3481 return PyFloat_FromDouble((double) tv->vval.v_float);
3482#endif
3483 case VAR_LIST:
3484 return ListNew(tv->vval.v_list);
3485 case VAR_DICT:
3486 return DictionaryNew(tv->vval.v_dict);
3487 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003488 return FunctionNew(tv->vval.v_string == NULL
3489 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003490 case VAR_UNKNOWN:
3491 Py_INCREF(Py_None);
3492 return Py_None;
3493 default:
3494 PyErr_SetVim(_("internal error: invalid value type"));
3495 return NULL;
3496 }
3497}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003498
3499typedef struct
3500{
3501 PyObject_HEAD
3502} CurrentObject;
3503static PyTypeObject CurrentType;
3504
3505 static void
3506init_structs(void)
3507{
3508 vim_memset(&OutputType, 0, sizeof(OutputType));
3509 OutputType.tp_name = "vim.message";
3510 OutputType.tp_basicsize = sizeof(OutputObject);
3511 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3512 OutputType.tp_doc = "vim message object";
3513 OutputType.tp_methods = OutputMethods;
3514#if PY_MAJOR_VERSION >= 3
3515 OutputType.tp_getattro = OutputGetattro;
3516 OutputType.tp_setattro = OutputSetattro;
3517 OutputType.tp_alloc = call_PyType_GenericAlloc;
3518 OutputType.tp_new = call_PyType_GenericNew;
3519 OutputType.tp_free = call_PyObject_Free;
3520#else
3521 OutputType.tp_getattr = OutputGetattr;
3522 OutputType.tp_setattr = OutputSetattr;
3523#endif
3524
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003525 vim_memset(&IterType, 0, sizeof(IterType));
3526 IterType.tp_name = "vim.iter";
3527 IterType.tp_basicsize = sizeof(IterObject);
3528 IterType.tp_flags = Py_TPFLAGS_DEFAULT;
3529 IterType.tp_doc = "generic iterator object";
3530 IterType.tp_iter = IterIter;
3531 IterType.tp_iternext = IterNext;
3532
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003533 vim_memset(&BufferType, 0, sizeof(BufferType));
3534 BufferType.tp_name = "vim.buffer";
3535 BufferType.tp_basicsize = sizeof(BufferType);
3536 BufferType.tp_dealloc = BufferDestructor;
3537 BufferType.tp_repr = BufferRepr;
3538 BufferType.tp_as_sequence = &BufferAsSeq;
3539 BufferType.tp_as_mapping = &BufferAsMapping;
3540 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3541 BufferType.tp_doc = "vim buffer object";
3542 BufferType.tp_methods = BufferMethods;
3543#if PY_MAJOR_VERSION >= 3
3544 BufferType.tp_getattro = BufferGetattro;
3545 BufferType.tp_alloc = call_PyType_GenericAlloc;
3546 BufferType.tp_new = call_PyType_GenericNew;
3547 BufferType.tp_free = call_PyObject_Free;
3548#else
3549 BufferType.tp_getattr = BufferGetattr;
3550#endif
3551
3552 vim_memset(&WindowType, 0, sizeof(WindowType));
3553 WindowType.tp_name = "vim.window";
3554 WindowType.tp_basicsize = sizeof(WindowObject);
3555 WindowType.tp_dealloc = WindowDestructor;
3556 WindowType.tp_repr = WindowRepr;
3557 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3558 WindowType.tp_doc = "vim Window object";
3559 WindowType.tp_methods = WindowMethods;
3560#if PY_MAJOR_VERSION >= 3
3561 WindowType.tp_getattro = WindowGetattro;
3562 WindowType.tp_setattro = WindowSetattro;
3563 WindowType.tp_alloc = call_PyType_GenericAlloc;
3564 WindowType.tp_new = call_PyType_GenericNew;
3565 WindowType.tp_free = call_PyObject_Free;
3566#else
3567 WindowType.tp_getattr = WindowGetattr;
3568 WindowType.tp_setattr = WindowSetattr;
3569#endif
3570
Bram Moolenaardfa38d42013-05-15 13:38:47 +02003571 vim_memset(&BufMapType, 0, sizeof(BufMapType));
3572 BufMapType.tp_name = "vim.bufferlist";
3573 BufMapType.tp_basicsize = sizeof(BufMapObject);
3574 BufMapType.tp_as_mapping = &BufMapAsMapping;
3575 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003576 BufMapType.tp_iter = BufMapIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003577 BufferType.tp_doc = "vim buffer list";
3578
3579 vim_memset(&WinListType, 0, sizeof(WinListType));
3580 WinListType.tp_name = "vim.windowlist";
3581 WinListType.tp_basicsize = sizeof(WinListType);
3582 WinListType.tp_as_sequence = &WinListAsSeq;
3583 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3584 WinListType.tp_doc = "vim window list";
3585
3586 vim_memset(&RangeType, 0, sizeof(RangeType));
3587 RangeType.tp_name = "vim.range";
3588 RangeType.tp_basicsize = sizeof(RangeObject);
3589 RangeType.tp_dealloc = RangeDestructor;
3590 RangeType.tp_repr = RangeRepr;
3591 RangeType.tp_as_sequence = &RangeAsSeq;
3592 RangeType.tp_as_mapping = &RangeAsMapping;
3593 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3594 RangeType.tp_doc = "vim Range object";
3595 RangeType.tp_methods = RangeMethods;
3596#if PY_MAJOR_VERSION >= 3
3597 RangeType.tp_getattro = RangeGetattro;
3598 RangeType.tp_alloc = call_PyType_GenericAlloc;
3599 RangeType.tp_new = call_PyType_GenericNew;
3600 RangeType.tp_free = call_PyObject_Free;
3601#else
3602 RangeType.tp_getattr = RangeGetattr;
3603#endif
3604
3605 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3606 CurrentType.tp_name = "vim.currentdata";
3607 CurrentType.tp_basicsize = sizeof(CurrentObject);
3608 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3609 CurrentType.tp_doc = "vim current object";
3610#if PY_MAJOR_VERSION >= 3
3611 CurrentType.tp_getattro = CurrentGetattro;
3612 CurrentType.tp_setattro = CurrentSetattro;
3613#else
3614 CurrentType.tp_getattr = CurrentGetattr;
3615 CurrentType.tp_setattr = CurrentSetattr;
3616#endif
3617
3618 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3619 DictionaryType.tp_name = "vim.dictionary";
3620 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3621 DictionaryType.tp_dealloc = DictionaryDestructor;
3622 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3623 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3624 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3625 DictionaryType.tp_methods = DictionaryMethods;
3626#if PY_MAJOR_VERSION >= 3
3627 DictionaryType.tp_getattro = DictionaryGetattro;
3628 DictionaryType.tp_setattro = DictionarySetattro;
3629#else
3630 DictionaryType.tp_getattr = DictionaryGetattr;
3631 DictionaryType.tp_setattr = DictionarySetattr;
3632#endif
3633
3634 vim_memset(&ListType, 0, sizeof(ListType));
3635 ListType.tp_name = "vim.list";
3636 ListType.tp_dealloc = ListDestructor;
3637 ListType.tp_basicsize = sizeof(ListObject);
3638 ListType.tp_as_sequence = &ListAsSeq;
3639 ListType.tp_as_mapping = &ListAsMapping;
3640 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3641 ListType.tp_doc = "list pushing modifications to vim structure";
3642 ListType.tp_methods = ListMethods;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003643 ListType.tp_iter = ListIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003644#if PY_MAJOR_VERSION >= 3
3645 ListType.tp_getattro = ListGetattro;
3646 ListType.tp_setattro = ListSetattro;
3647#else
3648 ListType.tp_getattr = ListGetattr;
3649 ListType.tp_setattr = ListSetattr;
3650#endif
3651
3652 vim_memset(&FunctionType, 0, sizeof(FunctionType));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003653 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003654 FunctionType.tp_basicsize = sizeof(FunctionObject);
3655 FunctionType.tp_dealloc = FunctionDestructor;
3656 FunctionType.tp_call = FunctionCall;
3657 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3658 FunctionType.tp_doc = "object that calls vim function";
3659 FunctionType.tp_methods = FunctionMethods;
3660#if PY_MAJOR_VERSION >= 3
3661 FunctionType.tp_getattro = FunctionGetattro;
3662#else
3663 FunctionType.tp_getattr = FunctionGetattr;
3664#endif
3665
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003666 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3667 OptionsType.tp_name = "vim.options";
3668 OptionsType.tp_basicsize = sizeof(OptionsObject);
3669 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3670 OptionsType.tp_doc = "object for manipulating options";
3671 OptionsType.tp_as_mapping = &OptionsAsMapping;
3672 OptionsType.tp_dealloc = OptionsDestructor;
3673
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003674#if PY_MAJOR_VERSION >= 3
3675 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3676 vimmodule.m_name = "vim";
3677 vimmodule.m_doc = "Vim Python interface\n";
3678 vimmodule.m_size = -1;
3679 vimmodule.m_methods = VimMethods;
3680#endif
3681}