blob: b4d074bf17a2dd4291bf7cdbb443eea6e531c83d [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/*
534 * Buffer list object - Implementation
535 */
536
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200537static PyTypeObject BufMapType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200538
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200539typedef struct
540{
541 PyObject_HEAD
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200542} BufMapObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200543
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200544 static PyInt
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200545BufMapLength(PyObject *self UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200546{
547 buf_T *b = firstbuf;
548 PyInt n = 0;
549
550 while (b)
551 {
552 ++n;
553 b = b->b_next;
554 }
555
556 return n;
557}
558
559 static PyObject *
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200560BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200561{
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200562 buf_T *b;
563 int bnr;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200564
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200565#if PY_MAJOR_VERSION < 3
566 if (PyInt_Check(keyObject))
567 bnr = PyInt_AsLong(keyObject);
568 else
569#endif
570 if (PyLong_Check(keyObject))
571 bnr = PyLong_AsLong(keyObject);
572 else
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200573 {
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200574 PyErr_SetString(PyExc_ValueError, _("key must be integer"));
575 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200576 }
577
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200578 b = buflist_findnr(bnr);
579
580 if (b)
581 return BufferNew(b);
582 else
583 {
584 PyErr_SetString(PyExc_KeyError, _("no such buffer"));
585 return NULL;
586 }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200587}
588
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200589static PyMappingMethods BufMapAsMapping = {
590 (lenfunc) BufMapLength,
591 (binaryfunc) BufMapItem,
592 (objobjargproc) 0,
593};
594
Bram Moolenaardb913952012-06-29 12:54:53 +0200595typedef struct pylinkedlist_S {
596 struct pylinkedlist_S *pll_next;
597 struct pylinkedlist_S *pll_prev;
598 PyObject *pll_obj;
599} pylinkedlist_T;
600
601static pylinkedlist_T *lastdict = NULL;
602static pylinkedlist_T *lastlist = NULL;
603
604 static void
605pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
606{
607 if (ref->pll_prev == NULL)
608 {
609 if (ref->pll_next == NULL)
610 {
611 *last = NULL;
612 return;
613 }
614 }
615 else
616 ref->pll_prev->pll_next = ref->pll_next;
617
618 if (ref->pll_next == NULL)
619 *last = ref->pll_prev;
620 else
621 ref->pll_next->pll_prev = ref->pll_prev;
622}
623
624 static void
625pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
626{
627 if (*last == NULL)
628 ref->pll_prev = NULL;
629 else
630 {
631 (*last)->pll_next = ref;
632 ref->pll_prev = *last;
633 }
634 ref->pll_next = NULL;
635 ref->pll_obj = self;
636 *last = ref;
637}
638
639static PyTypeObject DictionaryType;
640
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200641#define DICTKEY_GET_NOTEMPTY(err) \
642 DICTKEY_GET(err) \
643 if (*key == NUL) \
644 { \
645 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
646 return err; \
647 }
648
Bram Moolenaardb913952012-06-29 12:54:53 +0200649typedef struct
650{
651 PyObject_HEAD
652 dict_T *dict;
653 pylinkedlist_T ref;
654} DictionaryObject;
655
656 static PyObject *
657DictionaryNew(dict_T *dict)
658{
659 DictionaryObject *self;
660
661 self = PyObject_NEW(DictionaryObject, &DictionaryType);
662 if (self == NULL)
663 return NULL;
664 self->dict = dict;
665 ++dict->dv_refcount;
666
667 pyll_add((PyObject *)(self), &self->ref, &lastdict);
668
669 return (PyObject *)(self);
670}
671
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200672 static void
673DictionaryDestructor(PyObject *self)
674{
675 DictionaryObject *this = ((DictionaryObject *) (self));
676
677 pyll_remove(&this->ref, &lastdict);
678 dict_unref(this->dict);
679
680 DESTRUCTOR_FINISH(self);
681}
682
Bram Moolenaardb913952012-06-29 12:54:53 +0200683 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200684DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200685{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200686 DictionaryObject *this = (DictionaryObject *)(self);
687
Bram Moolenaar66b79852012-09-21 14:00:35 +0200688 if (val == NULL)
689 {
690 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
691 return -1;
692 }
693
694 if (strcmp(name, "locked") == 0)
695 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200696 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200697 {
698 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
699 return -1;
700 }
701 else
702 {
703 if (!PyBool_Check(val))
704 {
705 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
706 return -1;
707 }
708
709 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200710 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200711 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200712 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200713 }
714 return 0;
715 }
716 else
717 {
718 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
719 return -1;
720 }
721}
722
723 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200724DictionaryLength(PyObject *self)
725{
726 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
727}
728
729 static PyObject *
730DictionaryItem(PyObject *self, PyObject *keyObject)
731{
732 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200733 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200734 DICTKEY_DECL
735
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200736 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200737
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200738 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
739
Bram Moolenaar696c2112012-09-21 13:43:14 +0200740 DICTKEY_UNREF
741
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200742 if (di == NULL)
743 {
Bram Moolenaaraf6abb92013-04-24 13:04:26 +0200744 PyErr_SetString(PyExc_KeyError, _("no such key in dictionary"));
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200745 return NULL;
746 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200747
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200748 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200749}
750
751 static PyInt
752DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
753{
754 char_u *key;
755 typval_T tv;
756 dict_T *d = ((DictionaryObject *)(self))->dict;
757 dictitem_T *di;
758 DICTKEY_DECL
759
760 if (d->dv_lock)
761 {
762 PyErr_SetVim(_("dict is locked"));
763 return -1;
764 }
765
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200766 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200767
768 di = dict_find(d, key, -1);
769
770 if (valObject == NULL)
771 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200772 hashitem_T *hi;
773
Bram Moolenaardb913952012-06-29 12:54:53 +0200774 if (di == NULL)
775 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200776 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200777 PyErr_SetString(PyExc_IndexError, _("no such key in dictionary"));
778 return -1;
779 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200780 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200781 hash_remove(&d->dv_hashtab, hi);
782 dictitem_free(di);
783 return 0;
784 }
785
786 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200787 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200788
789 if (di == NULL)
790 {
791 di = dictitem_alloc(key);
792 if (di == NULL)
793 {
794 PyErr_NoMemory();
795 return -1;
796 }
797 di->di_tv.v_lock = 0;
798
799 if (dict_add(d, di) == FAIL)
800 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200801 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200802 vim_free(di);
803 PyErr_SetVim(_("failed to add key to dictionary"));
804 return -1;
805 }
806 }
807 else
808 clear_tv(&di->di_tv);
809
810 DICTKEY_UNREF
811
812 copy_tv(&tv, &di->di_tv);
813 return 0;
814}
815
816 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100817DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200818{
819 dict_T *dict = ((DictionaryObject *)(self))->dict;
820 long_u todo = dict->dv_hashtab.ht_used;
821 Py_ssize_t i = 0;
822 PyObject *r;
823 hashitem_T *hi;
824
825 r = PyList_New(todo);
826 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
827 {
828 if (!HASHITEM_EMPTY(hi))
829 {
830 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
831 --todo;
832 ++i;
833 }
834 }
835 return r;
836}
837
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200838static PyMappingMethods DictionaryAsMapping = {
839 (lenfunc) DictionaryLength,
840 (binaryfunc) DictionaryItem,
841 (objobjargproc) DictionaryAssItem,
842};
843
Bram Moolenaardb913952012-06-29 12:54:53 +0200844static struct PyMethodDef DictionaryMethods[] = {
845 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
846 { NULL, NULL, 0, NULL }
847};
848
849static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200850static PySequenceMethods ListAsSeq;
851static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200852
853typedef struct
854{
855 PyObject_HEAD
856 list_T *list;
857 pylinkedlist_T ref;
858} ListObject;
859
860 static PyObject *
861ListNew(list_T *list)
862{
863 ListObject *self;
864
865 self = PyObject_NEW(ListObject, &ListType);
866 if (self == NULL)
867 return NULL;
868 self->list = list;
869 ++list->lv_refcount;
870
871 pyll_add((PyObject *)(self), &self->ref, &lastlist);
872
873 return (PyObject *)(self);
874}
875
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200876 static void
877ListDestructor(PyObject *self)
878{
879 ListObject *this = (ListObject *)(self);
880
881 pyll_remove(&this->ref, &lastlist);
882 list_unref(this->list);
883
884 DESTRUCTOR_FINISH(self);
885}
886
Bram Moolenaardb913952012-06-29 12:54:53 +0200887 static int
888list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
889{
890 Py_ssize_t i;
891 Py_ssize_t lsize = PySequence_Size(obj);
892 PyObject *litem;
893 listitem_T *li;
894
895 for(i=0; i<lsize; i++)
896 {
897 li = listitem_alloc();
898 if (li == NULL)
899 {
900 PyErr_NoMemory();
901 return -1;
902 }
903 li->li_tv.v_lock = 0;
904
905 litem = PySequence_GetItem(obj, i);
906 if (litem == NULL)
907 return -1;
908 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
909 return -1;
910
911 list_append(l, li);
912 }
913 return 0;
914}
915
Bram Moolenaardb913952012-06-29 12:54:53 +0200916 static PyInt
917ListLength(PyObject *self)
918{
919 return ((PyInt) (((ListObject *) (self))->list->lv_len));
920}
921
922 static PyObject *
923ListItem(PyObject *self, Py_ssize_t index)
924{
925 listitem_T *li;
926
927 if (index>=ListLength(self))
928 {
929 PyErr_SetString(PyExc_IndexError, "list index out of range");
930 return NULL;
931 }
932 li = list_find(((ListObject *) (self))->list, (long) index);
933 if (li == NULL)
934 {
935 PyErr_SetVim(_("internal error: failed to get vim list item"));
936 return NULL;
937 }
938 return ConvertToPyObject(&li->li_tv);
939}
940
941#define PROC_RANGE \
942 if (last < 0) {\
943 if (last < -size) \
944 last = 0; \
945 else \
946 last += size; \
947 } \
948 if (first < 0) \
949 first = 0; \
950 if (first > size) \
951 first = size; \
952 if (last > size) \
953 last = size;
954
955 static PyObject *
956ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
957{
958 PyInt i;
959 PyInt size = ListLength(self);
960 PyInt n;
961 PyObject *list;
962 int reversed = 0;
963
964 PROC_RANGE
965 if (first >= last)
966 first = last;
967
968 n = last-first;
969 list = PyList_New(n);
970 if (list == NULL)
971 return NULL;
972
973 for (i = 0; i < n; ++i)
974 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +0200975 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +0200976 if (item == NULL)
977 {
978 Py_DECREF(list);
979 return NULL;
980 }
981
982 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
983 {
984 Py_DECREF(item);
985 Py_DECREF(list);
986 return NULL;
987 }
988 }
989
990 return list;
991}
992
993 static int
994ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
995{
996 typval_T tv;
997 list_T *l = ((ListObject *) (self))->list;
998 listitem_T *li;
999 Py_ssize_t length = ListLength(self);
1000
1001 if (l->lv_lock)
1002 {
1003 PyErr_SetVim(_("list is locked"));
1004 return -1;
1005 }
1006 if (index>length || (index==length && obj==NULL))
1007 {
1008 PyErr_SetString(PyExc_IndexError, "list index out of range");
1009 return -1;
1010 }
1011
1012 if (obj == NULL)
1013 {
1014 li = list_find(l, (long) index);
1015 list_remove(l, li, li);
1016 clear_tv(&li->li_tv);
1017 vim_free(li);
1018 return 0;
1019 }
1020
1021 if (ConvertFromPyObject(obj, &tv) == -1)
1022 return -1;
1023
1024 if (index == length)
1025 {
1026 if (list_append_tv(l, &tv) == FAIL)
1027 {
1028 PyErr_SetVim(_("Failed to add item to list"));
1029 return -1;
1030 }
1031 }
1032 else
1033 {
1034 li = list_find(l, (long) index);
1035 clear_tv(&li->li_tv);
1036 copy_tv(&tv, &li->li_tv);
1037 }
1038 return 0;
1039}
1040
1041 static int
1042ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1043{
1044 PyInt size = ListLength(self);
1045 Py_ssize_t i;
1046 Py_ssize_t lsize;
1047 PyObject *litem;
1048 listitem_T *li;
1049 listitem_T *next;
1050 typval_T v;
1051 list_T *l = ((ListObject *) (self))->list;
1052
1053 if (l->lv_lock)
1054 {
1055 PyErr_SetVim(_("list is locked"));
1056 return -1;
1057 }
1058
1059 PROC_RANGE
1060
1061 if (first == size)
1062 li = NULL;
1063 else
1064 {
1065 li = list_find(l, (long) first);
1066 if (li == NULL)
1067 {
1068 PyErr_SetVim(_("internal error: no vim list item"));
1069 return -1;
1070 }
1071 if (last > first)
1072 {
1073 i = last - first;
1074 while (i-- && li != NULL)
1075 {
1076 next = li->li_next;
1077 listitem_remove(l, li);
1078 li = next;
1079 }
1080 }
1081 }
1082
1083 if (obj == NULL)
1084 return 0;
1085
1086 if (!PyList_Check(obj))
1087 {
1088 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1089 return -1;
1090 }
1091
1092 lsize = PyList_Size(obj);
1093
1094 for(i=0; i<lsize; i++)
1095 {
1096 litem = PyList_GetItem(obj, i);
1097 if (litem == NULL)
1098 return -1;
1099 if (ConvertFromPyObject(litem, &v) == -1)
1100 return -1;
1101 if (list_insert_tv(l, &v, li) == FAIL)
1102 {
1103 PyErr_SetVim(_("internal error: failed to add item to list"));
1104 return -1;
1105 }
1106 }
1107 return 0;
1108}
1109
1110 static PyObject *
1111ListConcatInPlace(PyObject *self, PyObject *obj)
1112{
1113 list_T *l = ((ListObject *) (self))->list;
1114 PyObject *lookup_dict;
1115
1116 if (l->lv_lock)
1117 {
1118 PyErr_SetVim(_("list is locked"));
1119 return NULL;
1120 }
1121
1122 if (!PySequence_Check(obj))
1123 {
1124 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1125 return NULL;
1126 }
1127
1128 lookup_dict = PyDict_New();
1129 if (list_py_concat(l, obj, lookup_dict) == -1)
1130 {
1131 Py_DECREF(lookup_dict);
1132 return NULL;
1133 }
1134 Py_DECREF(lookup_dict);
1135
1136 Py_INCREF(self);
1137 return self;
1138}
1139
Bram Moolenaar66b79852012-09-21 14:00:35 +02001140 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001141ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001142{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001143 ListObject *this = (ListObject *)(self);
1144
Bram Moolenaar66b79852012-09-21 14:00:35 +02001145 if (val == NULL)
1146 {
1147 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
1148 return -1;
1149 }
1150
1151 if (strcmp(name, "locked") == 0)
1152 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001153 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001154 {
1155 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed list"));
1156 return -1;
1157 }
1158 else
1159 {
1160 if (!PyBool_Check(val))
1161 {
1162 PyErr_SetString(PyExc_TypeError, _("Only boolean objects are allowed"));
1163 return -1;
1164 }
1165
1166 if (val == Py_True)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001167 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001168 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001169 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001170 }
1171 return 0;
1172 }
1173 else
1174 {
1175 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
1176 return -1;
1177 }
1178}
1179
Bram Moolenaardb913952012-06-29 12:54:53 +02001180static struct PyMethodDef ListMethods[] = {
1181 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1182 { NULL, NULL, 0, NULL }
1183};
1184
1185typedef struct
1186{
1187 PyObject_HEAD
1188 char_u *name;
1189} FunctionObject;
1190
1191static PyTypeObject FunctionType;
1192
1193 static PyObject *
1194FunctionNew(char_u *name)
1195{
1196 FunctionObject *self;
1197
1198 self = PyObject_NEW(FunctionObject, &FunctionType);
1199 if (self == NULL)
1200 return NULL;
1201 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1202 if (self->name == NULL)
1203 {
1204 PyErr_NoMemory();
1205 return NULL;
1206 }
1207 STRCPY(self->name, name);
1208 func_ref(name);
1209 return (PyObject *)(self);
1210}
1211
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001212 static void
1213FunctionDestructor(PyObject *self)
1214{
1215 FunctionObject *this = (FunctionObject *) (self);
1216
1217 func_unref(this->name);
1218 PyMem_Del(this->name);
1219
1220 DESTRUCTOR_FINISH(self);
1221}
1222
Bram Moolenaardb913952012-06-29 12:54:53 +02001223 static PyObject *
1224FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1225{
1226 FunctionObject *this = (FunctionObject *)(self);
1227 char_u *name = this->name;
1228 typval_T args;
1229 typval_T selfdicttv;
1230 typval_T rettv;
1231 dict_T *selfdict = NULL;
1232 PyObject *selfdictObject;
1233 PyObject *result;
1234 int error;
1235
1236 if (ConvertFromPyObject(argsObject, &args) == -1)
1237 return NULL;
1238
1239 if (kwargs != NULL)
1240 {
1241 selfdictObject = PyDict_GetItemString(kwargs, "self");
1242 if (selfdictObject != NULL)
1243 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001244 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001245 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001246 PyErr_SetString(PyExc_TypeError,
1247 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001248 clear_tv(&args);
1249 return NULL;
1250 }
1251 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1252 return NULL;
1253 selfdict = selfdicttv.vval.v_dict;
1254 }
1255 }
1256
1257 error = func_call(name, &args, selfdict, &rettv);
1258 if (error != OK)
1259 {
1260 result = NULL;
1261 PyErr_SetVim(_("failed to run function"));
1262 }
1263 else
1264 result = ConvertToPyObject(&rettv);
1265
1266 /* FIXME Check what should really be cleared. */
1267 clear_tv(&args);
1268 clear_tv(&rettv);
1269 /*
1270 * if (selfdict!=NULL)
1271 * clear_tv(selfdicttv);
1272 */
1273
1274 return result;
1275}
1276
1277static struct PyMethodDef FunctionMethods[] = {
1278 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1279 { NULL, NULL, 0, NULL }
1280};
1281
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001282/*
1283 * Options object
1284 */
1285
1286static PyTypeObject OptionsType;
1287
1288typedef int (*checkfun)(void *);
1289
1290typedef struct
1291{
1292 PyObject_HEAD
1293 int opt_type;
1294 void *from;
1295 checkfun Check;
1296 PyObject *fromObj;
1297} OptionsObject;
1298
1299 static PyObject *
1300OptionsItem(OptionsObject *this, PyObject *keyObject)
1301{
1302 char_u *key;
1303 int flags;
1304 long numval;
1305 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001306 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001307
1308 if (this->Check(this->from))
1309 return NULL;
1310
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001311 DICTKEY_GET_NOTEMPTY(NULL)
1312
1313 flags = get_option_value_strict(key, &numval, &stringval,
1314 this->opt_type, this->from);
1315
1316 DICTKEY_UNREF
1317
1318 if (flags == 0)
1319 {
1320 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1321 return NULL;
1322 }
1323
1324 if (flags & SOPT_UNSET)
1325 {
1326 Py_INCREF(Py_None);
1327 return Py_None;
1328 }
1329 else if (flags & SOPT_BOOL)
1330 {
1331 PyObject *r;
1332 r = numval ? Py_True : Py_False;
1333 Py_INCREF(r);
1334 return r;
1335 }
1336 else if (flags & SOPT_NUM)
1337 return PyInt_FromLong(numval);
1338 else if (flags & SOPT_STRING)
1339 {
1340 if (stringval)
1341 return PyBytes_FromString((char *) stringval);
1342 else
1343 {
1344 PyErr_SetString(PyExc_ValueError, "Unable to get option value");
1345 return NULL;
1346 }
1347 }
1348 else
1349 {
1350 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1351 return NULL;
1352 }
1353}
1354
1355 static int
1356set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1357 char_u *key;
1358 int numval;
1359 char_u *stringval;
1360 int opt_flags;
1361 int opt_type;
1362 void *from;
1363{
1364 win_T *save_curwin;
1365 tabpage_T *save_curtab;
1366 aco_save_T aco;
1367 int r = 0;
1368
1369 switch (opt_type)
1370 {
1371 case SREQ_WIN:
1372 if (switch_win(&save_curwin, &save_curtab, (win_T *) from, curtab)
1373 == FAIL)
1374 {
1375 PyErr_SetVim("Problem while switching windows.");
1376 return -1;
1377 }
1378 set_option_value(key, numval, stringval, opt_flags);
1379 restore_win(save_curwin, save_curtab);
1380 break;
1381 case SREQ_BUF:
1382 aucmd_prepbuf(&aco, (buf_T *) from);
1383 set_option_value(key, numval, stringval, opt_flags);
1384 aucmd_restbuf(&aco);
1385 break;
1386 case SREQ_GLOBAL:
1387 set_option_value(key, numval, stringval, opt_flags);
1388 break;
1389 }
1390 return r;
1391}
1392
1393 static int
1394OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1395{
1396 char_u *key;
1397 int flags;
1398 int opt_flags;
1399 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001400 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001401
1402 if (this->Check(this->from))
1403 return -1;
1404
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001405 DICTKEY_GET_NOTEMPTY(-1)
1406
1407 flags = get_option_value_strict(key, NULL, NULL,
1408 this->opt_type, this->from);
1409
1410 DICTKEY_UNREF
1411
1412 if (flags == 0)
1413 {
1414 PyErr_SetString(PyExc_KeyError, "Option does not exist in given scope");
1415 return -1;
1416 }
1417
1418 if (valObject == NULL)
1419 {
1420 if (this->opt_type == SREQ_GLOBAL)
1421 {
1422 PyErr_SetString(PyExc_ValueError, "Unable to unset global option");
1423 return -1;
1424 }
1425 else if (!(flags & SOPT_GLOBAL))
1426 {
1427 PyErr_SetString(PyExc_ValueError, "Unable to unset option without "
1428 "global value");
1429 return -1;
1430 }
1431 else
1432 {
1433 unset_global_local_option(key, this->from);
1434 return 0;
1435 }
1436 }
1437
1438 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1439
1440 if (flags & SOPT_BOOL)
1441 {
1442 if (!PyBool_Check(valObject))
1443 {
1444 PyErr_SetString(PyExc_ValueError, "Object must be boolean");
1445 return -1;
1446 }
1447
1448 r = set_option_value_for(key, (valObject == Py_True), NULL, opt_flags,
1449 this->opt_type, this->from);
1450 }
1451 else if (flags & SOPT_NUM)
1452 {
1453 int val;
1454
1455#if PY_MAJOR_VERSION < 3
1456 if (PyInt_Check(valObject))
1457 val = PyInt_AsLong(valObject);
1458 else
1459#endif
1460 if (PyLong_Check(valObject))
1461 val = PyLong_AsLong(valObject);
1462 else
1463 {
1464 PyErr_SetString(PyExc_ValueError, "Object must be integer");
1465 return -1;
1466 }
1467
1468 r = set_option_value_for(key, val, NULL, opt_flags,
1469 this->opt_type, this->from);
1470 }
1471 else
1472 {
1473 char_u *val;
1474 if (PyBytes_Check(valObject))
1475 {
1476
1477 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1478 return -1;
1479 if (val == NULL)
1480 return -1;
1481
1482 val = vim_strsave(val);
1483 }
1484 else if (PyUnicode_Check(valObject))
1485 {
1486 PyObject *bytes;
1487
1488 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1489 if (bytes == NULL)
1490 return -1;
1491
1492 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1493 return -1;
1494 if (val == NULL)
1495 return -1;
1496
1497 val = vim_strsave(val);
1498 Py_XDECREF(bytes);
1499 }
1500 else
1501 {
1502 PyErr_SetString(PyExc_ValueError, "Object must be string");
1503 return -1;
1504 }
1505
1506 r = set_option_value_for(key, 0, val, opt_flags,
1507 this->opt_type, this->from);
1508 vim_free(val);
1509 }
1510
1511 return r;
1512}
1513
1514 static int
1515dummy_check(void *arg UNUSED)
1516{
1517 return 0;
1518}
1519
1520 static PyObject *
1521OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1522{
1523 OptionsObject *self;
1524
1525 self = PyObject_NEW(OptionsObject, &OptionsType);
1526 if (self == NULL)
1527 return NULL;
1528
1529 self->opt_type = opt_type;
1530 self->from = from;
1531 self->Check = Check;
1532 self->fromObj = fromObj;
1533 if (fromObj)
1534 Py_INCREF(fromObj);
1535
1536 return (PyObject *)(self);
1537}
1538
1539 static void
1540OptionsDestructor(PyObject *self)
1541{
1542 if (((OptionsObject *)(self))->fromObj)
1543 Py_DECREF(((OptionsObject *)(self))->fromObj);
1544 DESTRUCTOR_FINISH(self);
1545}
1546
1547static PyMappingMethods OptionsAsMapping = {
1548 (lenfunc) NULL,
1549 (binaryfunc) OptionsItem,
1550 (objobjargproc) OptionsAssItem,
1551};
1552
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001553/* Window object
1554 */
1555
1556typedef struct
1557{
1558 PyObject_HEAD
1559 win_T *win;
1560} WindowObject;
1561
1562static int WindowSetattr(PyObject *, char *, PyObject *);
1563static PyObject *WindowRepr(PyObject *);
1564static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001565
1566 static int
1567CheckWindow(WindowObject *this)
1568{
1569 if (this->win == INVALID_WINDOW_VALUE)
1570 {
1571 PyErr_SetVim(_("attempt to refer to deleted window"));
1572 return -1;
1573 }
1574
1575 return 0;
1576}
1577
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001578 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02001579WindowNew(win_T *win)
1580{
1581 /* We need to handle deletion of windows underneath us.
1582 * If we add a "w_python*_ref" field to the win_T structure,
1583 * then we can get at it in win_free() in vim. We then
1584 * need to create only ONE Python object per window - if
1585 * we try to create a second, just INCREF the existing one
1586 * and return it. The (single) Python object referring to
1587 * the window is stored in "w_python*_ref".
1588 * On a win_free() we set the Python object's win_T* field
1589 * to an invalid value. We trap all uses of a window
1590 * object, and reject them if the win_T* field is invalid.
1591 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001592 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001593 * w_python_ref and w_python3_ref fields respectively.
1594 */
1595
1596 WindowObject *self;
1597
1598 if (WIN_PYTHON_REF(win))
1599 {
1600 self = WIN_PYTHON_REF(win);
1601 Py_INCREF(self);
1602 }
1603 else
1604 {
1605 self = PyObject_NEW(WindowObject, &WindowType);
1606 if (self == NULL)
1607 return NULL;
1608 self->win = win;
1609 WIN_PYTHON_REF(win) = self;
1610 }
1611
1612 return (PyObject *)(self);
1613}
1614
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001615 static void
1616WindowDestructor(PyObject *self)
1617{
1618 WindowObject *this = (WindowObject *)(self);
1619
1620 if (this->win && this->win != INVALID_WINDOW_VALUE)
1621 WIN_PYTHON_REF(this->win) = NULL;
1622
1623 DESTRUCTOR_FINISH(self);
1624}
1625
Bram Moolenaar971db462013-05-12 18:44:48 +02001626 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001627WindowAttr(WindowObject *this, char *name)
1628{
1629 if (strcmp(name, "buffer") == 0)
1630 return (PyObject *)BufferNew(this->win->w_buffer);
1631 else if (strcmp(name, "cursor") == 0)
1632 {
1633 pos_T *pos = &this->win->w_cursor;
1634
1635 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1636 }
1637 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001638 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001639#ifdef FEAT_WINDOWS
1640 else if (strcmp(name, "row") == 0)
1641 return PyLong_FromLong((long)(this->win->w_winrow));
1642#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001643#ifdef FEAT_VERTSPLIT
1644 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001645 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001646 else if (strcmp(name, "col") == 0)
1647 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001648#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001649 else if (strcmp(name, "vars") == 0)
1650 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001651 else if (strcmp(name, "options") == 0)
1652 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1653 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001654 else if (strcmp(name, "number") == 0)
1655 return PyLong_FromLong((long) get_win_number(this->win));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001656 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001657 return Py_BuildValue("[ssssssss]", "buffer", "cursor", "height", "vars",
1658 "options", "number", "row", "col");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001659 else
1660 return NULL;
1661}
1662
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001663 static int
1664WindowSetattr(PyObject *self, char *name, PyObject *val)
1665{
1666 WindowObject *this = (WindowObject *)(self);
1667
1668 if (CheckWindow(this))
1669 return -1;
1670
1671 if (strcmp(name, "buffer") == 0)
1672 {
1673 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1674 return -1;
1675 }
1676 else if (strcmp(name, "cursor") == 0)
1677 {
1678 long lnum;
1679 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001680
1681 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1682 return -1;
1683
1684 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1685 {
1686 PyErr_SetVim(_("cursor position outside buffer"));
1687 return -1;
1688 }
1689
1690 /* Check for keyboard interrupts */
1691 if (VimErrorCheck())
1692 return -1;
1693
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001694 this->win->w_cursor.lnum = lnum;
1695 this->win->w_cursor.col = col;
1696#ifdef FEAT_VIRTUALEDIT
1697 this->win->w_cursor.coladd = 0;
1698#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001699 /* When column is out of range silently correct it. */
1700 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001701
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001702 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001703 return 0;
1704 }
1705 else if (strcmp(name, "height") == 0)
1706 {
1707 int height;
1708 win_T *savewin;
1709
1710 if (!PyArg_Parse(val, "i", &height))
1711 return -1;
1712
1713#ifdef FEAT_GUI
1714 need_mouse_correct = TRUE;
1715#endif
1716 savewin = curwin;
1717 curwin = this->win;
1718 win_setheight(height);
1719 curwin = savewin;
1720
1721 /* Check for keyboard interrupts */
1722 if (VimErrorCheck())
1723 return -1;
1724
1725 return 0;
1726 }
1727#ifdef FEAT_VERTSPLIT
1728 else if (strcmp(name, "width") == 0)
1729 {
1730 int width;
1731 win_T *savewin;
1732
1733 if (!PyArg_Parse(val, "i", &width))
1734 return -1;
1735
1736#ifdef FEAT_GUI
1737 need_mouse_correct = TRUE;
1738#endif
1739 savewin = curwin;
1740 curwin = this->win;
1741 win_setwidth(width);
1742 curwin = savewin;
1743
1744 /* Check for keyboard interrupts */
1745 if (VimErrorCheck())
1746 return -1;
1747
1748 return 0;
1749 }
1750#endif
1751 else
1752 {
1753 PyErr_SetString(PyExc_AttributeError, name);
1754 return -1;
1755 }
1756}
1757
1758 static PyObject *
1759WindowRepr(PyObject *self)
1760{
1761 static char repr[100];
1762 WindowObject *this = (WindowObject *)(self);
1763
1764 if (this->win == INVALID_WINDOW_VALUE)
1765 {
1766 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
1767 return PyString_FromString(repr);
1768 }
1769 else
1770 {
Bram Moolenaar6d216452013-05-12 19:00:41 +02001771 int w = get_win_number(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001772
Bram Moolenaar6d216452013-05-12 19:00:41 +02001773 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001774 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
1775 (self));
1776 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02001777 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001778
1779 return PyString_FromString(repr);
1780 }
1781}
1782
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001783static struct PyMethodDef WindowMethods[] = {
1784 /* name, function, calling, documentation */
1785 { NULL, NULL, 0, NULL }
1786};
1787
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001788/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001789 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001790 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001791
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001792static PyTypeObject WinListType;
1793static PySequenceMethods WinListAsSeq;
1794
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001795typedef struct
1796{
1797 PyObject_HEAD
1798} WinListObject;
1799
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001800 static PyInt
1801WinListLength(PyObject *self UNUSED)
1802{
1803 win_T *w = firstwin;
1804 PyInt n = 0;
1805
1806 while (w != NULL)
1807 {
1808 ++n;
1809 w = W_NEXT(w);
1810 }
1811
1812 return n;
1813}
1814
1815 static PyObject *
1816WinListItem(PyObject *self UNUSED, PyInt n)
1817{
1818 win_T *w;
1819
1820 for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
1821 if (n == 0)
1822 return WindowNew(w);
1823
1824 PyErr_SetString(PyExc_IndexError, _("no such window"));
1825 return NULL;
1826}
1827
1828/* Convert a Python string into a Vim line.
1829 *
1830 * The result is in allocated memory. All internal nulls are replaced by
1831 * newline characters. It is an error for the string to contain newline
1832 * characters.
1833 *
1834 * On errors, the Python exception data is set, and NULL is returned.
1835 */
1836 static char *
1837StringToLine(PyObject *obj)
1838{
1839 const char *str;
1840 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02001841 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001842 PyInt len;
1843 PyInt i;
1844 char *p;
1845
1846 if (obj == NULL || !PyString_Check(obj))
1847 {
1848 PyErr_BadArgument();
1849 return NULL;
1850 }
1851
Bram Moolenaar19e60942011-06-19 00:27:51 +02001852 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
1853 str = PyString_AsString(bytes);
1854 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001855
1856 /*
1857 * Error checking: String must not contain newlines, as we
1858 * are replacing a single line, and we must replace it with
1859 * a single line.
1860 * A trailing newline is removed, so that append(f.readlines()) works.
1861 */
1862 p = memchr(str, '\n', len);
1863 if (p != NULL)
1864 {
1865 if (p == str + len - 1)
1866 --len;
1867 else
1868 {
1869 PyErr_SetVim(_("string cannot contain newlines"));
1870 return NULL;
1871 }
1872 }
1873
1874 /* Create a copy of the string, with internal nulls replaced by
1875 * newline characters, as is the vim convention.
1876 */
1877 save = (char *)alloc((unsigned)(len+1));
1878 if (save == NULL)
1879 {
1880 PyErr_NoMemory();
1881 return NULL;
1882 }
1883
1884 for (i = 0; i < len; ++i)
1885 {
1886 if (str[i] == '\0')
1887 save[i] = '\n';
1888 else
1889 save[i] = str[i];
1890 }
1891
1892 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02001893 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001894
1895 return save;
1896}
1897
1898/* Get a line from the specified buffer. The line number is
1899 * in Vim format (1-based). The line is returned as a Python
1900 * string object.
1901 */
1902 static PyObject *
1903GetBufferLine(buf_T *buf, PyInt n)
1904{
1905 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
1906}
1907
1908
1909/* Get a list of lines from the specified buffer. The line numbers
1910 * are in Vim format (1-based). The range is from lo up to, but not
1911 * including, hi. The list is returned as a Python list of string objects.
1912 */
1913 static PyObject *
1914GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
1915{
1916 PyInt i;
1917 PyInt n = hi - lo;
1918 PyObject *list = PyList_New(n);
1919
1920 if (list == NULL)
1921 return NULL;
1922
1923 for (i = 0; i < n; ++i)
1924 {
1925 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
1926
1927 /* Error check - was the Python string creation OK? */
1928 if (str == NULL)
1929 {
1930 Py_DECREF(list);
1931 return NULL;
1932 }
1933
1934 /* Set the list item */
1935 if (PyList_SetItem(list, i, str))
1936 {
1937 Py_DECREF(str);
1938 Py_DECREF(list);
1939 return NULL;
1940 }
1941 }
1942
1943 /* The ownership of the Python list is passed to the caller (ie,
1944 * the caller should Py_DECREF() the object when it is finished
1945 * with it).
1946 */
1947
1948 return list;
1949}
1950
1951/*
1952 * Check if deleting lines made the cursor position invalid.
1953 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
1954 * deleted).
1955 */
1956 static void
1957py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
1958{
1959 if (curwin->w_cursor.lnum >= lo)
1960 {
1961 /* Adjust the cursor position if it's in/after the changed
1962 * lines. */
1963 if (curwin->w_cursor.lnum >= hi)
1964 {
1965 curwin->w_cursor.lnum += extra;
1966 check_cursor_col();
1967 }
1968 else if (extra < 0)
1969 {
1970 curwin->w_cursor.lnum = lo;
1971 check_cursor();
1972 }
1973 else
1974 check_cursor_col();
1975 changed_cline_bef_curs();
1976 }
1977 invalidate_botline();
1978}
1979
Bram Moolenaar19e60942011-06-19 00:27:51 +02001980/*
1981 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001982 * in Vim format (1-based). The replacement line is given as
1983 * a Python string object. The object is checked for validity
1984 * and correct format. Errors are returned as a value of FAIL.
1985 * The return value is OK on success.
1986 * If OK is returned and len_change is not NULL, *len_change
1987 * is set to the change in the buffer length.
1988 */
1989 static int
1990SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
1991{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001992 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001993 * There are three cases:
1994 * 1. NULL, or None - this is a deletion.
1995 * 2. A string - this is a replacement.
1996 * 3. Anything else - this is an error.
1997 */
1998 if (line == Py_None || line == NULL)
1999 {
2000 buf_T *savebuf = curbuf;
2001
2002 PyErr_Clear();
2003 curbuf = buf;
2004
2005 if (u_savedel((linenr_T)n, 1L) == FAIL)
2006 PyErr_SetVim(_("cannot save undo information"));
2007 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2008 PyErr_SetVim(_("cannot delete line"));
2009 else
2010 {
2011 if (buf == curwin->w_buffer)
2012 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2013 deleted_lines_mark((linenr_T)n, 1L);
2014 }
2015
2016 curbuf = savebuf;
2017
2018 if (PyErr_Occurred() || VimErrorCheck())
2019 return FAIL;
2020
2021 if (len_change)
2022 *len_change = -1;
2023
2024 return OK;
2025 }
2026 else if (PyString_Check(line))
2027 {
2028 char *save = StringToLine(line);
2029 buf_T *savebuf = curbuf;
2030
2031 if (save == NULL)
2032 return FAIL;
2033
2034 /* We do not need to free "save" if ml_replace() consumes it. */
2035 PyErr_Clear();
2036 curbuf = buf;
2037
2038 if (u_savesub((linenr_T)n) == FAIL)
2039 {
2040 PyErr_SetVim(_("cannot save undo information"));
2041 vim_free(save);
2042 }
2043 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2044 {
2045 PyErr_SetVim(_("cannot replace line"));
2046 vim_free(save);
2047 }
2048 else
2049 changed_bytes((linenr_T)n, 0);
2050
2051 curbuf = savebuf;
2052
2053 /* Check that the cursor is not beyond the end of the line now. */
2054 if (buf == curwin->w_buffer)
2055 check_cursor_col();
2056
2057 if (PyErr_Occurred() || VimErrorCheck())
2058 return FAIL;
2059
2060 if (len_change)
2061 *len_change = 0;
2062
2063 return OK;
2064 }
2065 else
2066 {
2067 PyErr_BadArgument();
2068 return FAIL;
2069 }
2070}
2071
Bram Moolenaar19e60942011-06-19 00:27:51 +02002072/* Replace a range of lines in the specified buffer. The line numbers are in
2073 * Vim format (1-based). The range is from lo up to, but not including, hi.
2074 * The replacement lines are given as a Python list of string objects. The
2075 * list is checked for validity and correct format. Errors are returned as a
2076 * value of FAIL. The return value is OK on success.
2077 * If OK is returned and len_change is not NULL, *len_change
2078 * is set to the change in the buffer length.
2079 */
2080 static int
2081SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2082{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002083 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002084 * There are three cases:
2085 * 1. NULL, or None - this is a deletion.
2086 * 2. A list - this is a replacement.
2087 * 3. Anything else - this is an error.
2088 */
2089 if (list == Py_None || list == NULL)
2090 {
2091 PyInt i;
2092 PyInt n = (int)(hi - lo);
2093 buf_T *savebuf = curbuf;
2094
2095 PyErr_Clear();
2096 curbuf = buf;
2097
2098 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2099 PyErr_SetVim(_("cannot save undo information"));
2100 else
2101 {
2102 for (i = 0; i < n; ++i)
2103 {
2104 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2105 {
2106 PyErr_SetVim(_("cannot delete line"));
2107 break;
2108 }
2109 }
2110 if (buf == curwin->w_buffer)
2111 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2112 deleted_lines_mark((linenr_T)lo, (long)i);
2113 }
2114
2115 curbuf = savebuf;
2116
2117 if (PyErr_Occurred() || VimErrorCheck())
2118 return FAIL;
2119
2120 if (len_change)
2121 *len_change = -n;
2122
2123 return OK;
2124 }
2125 else if (PyList_Check(list))
2126 {
2127 PyInt i;
2128 PyInt new_len = PyList_Size(list);
2129 PyInt old_len = hi - lo;
2130 PyInt extra = 0; /* lines added to text, can be negative */
2131 char **array;
2132 buf_T *savebuf;
2133
2134 if (new_len == 0) /* avoid allocating zero bytes */
2135 array = NULL;
2136 else
2137 {
2138 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2139 if (array == NULL)
2140 {
2141 PyErr_NoMemory();
2142 return FAIL;
2143 }
2144 }
2145
2146 for (i = 0; i < new_len; ++i)
2147 {
2148 PyObject *line = PyList_GetItem(list, i);
2149
2150 array[i] = StringToLine(line);
2151 if (array[i] == NULL)
2152 {
2153 while (i)
2154 vim_free(array[--i]);
2155 vim_free(array);
2156 return FAIL;
2157 }
2158 }
2159
2160 savebuf = curbuf;
2161
2162 PyErr_Clear();
2163 curbuf = buf;
2164
2165 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2166 PyErr_SetVim(_("cannot save undo information"));
2167
2168 /* If the size of the range is reducing (ie, new_len < old_len) we
2169 * need to delete some old_len. We do this at the start, by
2170 * repeatedly deleting line "lo".
2171 */
2172 if (!PyErr_Occurred())
2173 {
2174 for (i = 0; i < old_len - new_len; ++i)
2175 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2176 {
2177 PyErr_SetVim(_("cannot delete line"));
2178 break;
2179 }
2180 extra -= i;
2181 }
2182
2183 /* For as long as possible, replace the existing old_len with the
2184 * new old_len. This is a more efficient operation, as it requires
2185 * less memory allocation and freeing.
2186 */
2187 if (!PyErr_Occurred())
2188 {
2189 for (i = 0; i < old_len && i < new_len; ++i)
2190 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2191 == FAIL)
2192 {
2193 PyErr_SetVim(_("cannot replace line"));
2194 break;
2195 }
2196 }
2197 else
2198 i = 0;
2199
2200 /* Now we may need to insert the remaining new old_len. If we do, we
2201 * must free the strings as we finish with them (we can't pass the
2202 * responsibility to vim in this case).
2203 */
2204 if (!PyErr_Occurred())
2205 {
2206 while (i < new_len)
2207 {
2208 if (ml_append((linenr_T)(lo + i - 1),
2209 (char_u *)array[i], 0, FALSE) == FAIL)
2210 {
2211 PyErr_SetVim(_("cannot insert line"));
2212 break;
2213 }
2214 vim_free(array[i]);
2215 ++i;
2216 ++extra;
2217 }
2218 }
2219
2220 /* Free any left-over old_len, as a result of an error */
2221 while (i < new_len)
2222 {
2223 vim_free(array[i]);
2224 ++i;
2225 }
2226
2227 /* Free the array of old_len. All of its contents have now
2228 * been dealt with (either freed, or the responsibility passed
2229 * to vim.
2230 */
2231 vim_free(array);
2232
2233 /* Adjust marks. Invalidate any which lie in the
2234 * changed range, and move any in the remainder of the buffer.
2235 */
2236 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2237 (long)MAXLNUM, (long)extra);
2238 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2239
2240 if (buf == curwin->w_buffer)
2241 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2242
2243 curbuf = savebuf;
2244
2245 if (PyErr_Occurred() || VimErrorCheck())
2246 return FAIL;
2247
2248 if (len_change)
2249 *len_change = new_len - old_len;
2250
2251 return OK;
2252 }
2253 else
2254 {
2255 PyErr_BadArgument();
2256 return FAIL;
2257 }
2258}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002259
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002260/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002261 * The line number is in Vim format (1-based). The lines to be inserted are
2262 * given as a Python list of string objects or as a single string. The lines
2263 * to be added are checked for validity and correct format. Errors are
2264 * returned as a value of FAIL. The return value is OK on success.
2265 * If OK is returned and len_change is not NULL, *len_change
2266 * is set to the change in the buffer length.
2267 */
2268 static int
2269InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2270{
2271 /* First of all, we check the type of the supplied Python object.
2272 * It must be a string or a list, or the call is in error.
2273 */
2274 if (PyString_Check(lines))
2275 {
2276 char *str = StringToLine(lines);
2277 buf_T *savebuf;
2278
2279 if (str == NULL)
2280 return FAIL;
2281
2282 savebuf = curbuf;
2283
2284 PyErr_Clear();
2285 curbuf = buf;
2286
2287 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2288 PyErr_SetVim(_("cannot save undo information"));
2289 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2290 PyErr_SetVim(_("cannot insert line"));
2291 else
2292 appended_lines_mark((linenr_T)n, 1L);
2293
2294 vim_free(str);
2295 curbuf = savebuf;
2296 update_screen(VALID);
2297
2298 if (PyErr_Occurred() || VimErrorCheck())
2299 return FAIL;
2300
2301 if (len_change)
2302 *len_change = 1;
2303
2304 return OK;
2305 }
2306 else if (PyList_Check(lines))
2307 {
2308 PyInt i;
2309 PyInt size = PyList_Size(lines);
2310 char **array;
2311 buf_T *savebuf;
2312
2313 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2314 if (array == NULL)
2315 {
2316 PyErr_NoMemory();
2317 return FAIL;
2318 }
2319
2320 for (i = 0; i < size; ++i)
2321 {
2322 PyObject *line = PyList_GetItem(lines, i);
2323 array[i] = StringToLine(line);
2324
2325 if (array[i] == NULL)
2326 {
2327 while (i)
2328 vim_free(array[--i]);
2329 vim_free(array);
2330 return FAIL;
2331 }
2332 }
2333
2334 savebuf = curbuf;
2335
2336 PyErr_Clear();
2337 curbuf = buf;
2338
2339 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2340 PyErr_SetVim(_("cannot save undo information"));
2341 else
2342 {
2343 for (i = 0; i < size; ++i)
2344 {
2345 if (ml_append((linenr_T)(n + i),
2346 (char_u *)array[i], 0, FALSE) == FAIL)
2347 {
2348 PyErr_SetVim(_("cannot insert line"));
2349
2350 /* Free the rest of the lines */
2351 while (i < size)
2352 vim_free(array[i++]);
2353
2354 break;
2355 }
2356 vim_free(array[i]);
2357 }
2358 if (i > 0)
2359 appended_lines_mark((linenr_T)n, (long)i);
2360 }
2361
2362 /* Free the array of lines. All of its contents have now
2363 * been freed.
2364 */
2365 vim_free(array);
2366
2367 curbuf = savebuf;
2368 update_screen(VALID);
2369
2370 if (PyErr_Occurred() || VimErrorCheck())
2371 return FAIL;
2372
2373 if (len_change)
2374 *len_change = size;
2375
2376 return OK;
2377 }
2378 else
2379 {
2380 PyErr_BadArgument();
2381 return FAIL;
2382 }
2383}
2384
2385/*
2386 * Common routines for buffers and line ranges
2387 * -------------------------------------------
2388 */
2389
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002390typedef struct
2391{
2392 PyObject_HEAD
2393 buf_T *buf;
2394} BufferObject;
2395
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002396 static int
2397CheckBuffer(BufferObject *this)
2398{
2399 if (this->buf == INVALID_BUFFER_VALUE)
2400 {
2401 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2402 return -1;
2403 }
2404
2405 return 0;
2406}
2407
2408 static PyObject *
2409RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2410{
2411 if (CheckBuffer(self))
2412 return NULL;
2413
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002414 if (end == -1)
2415 end = self->buf->b_ml.ml_line_count;
2416
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002417 if (n < 0)
2418 n += end - start + 1;
2419
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002420 if (n < 0 || n > end - start)
2421 {
2422 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2423 return NULL;
2424 }
2425
2426 return GetBufferLine(self->buf, n+start);
2427}
2428
2429 static PyObject *
2430RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2431{
2432 PyInt size;
2433
2434 if (CheckBuffer(self))
2435 return NULL;
2436
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002437 if (end == -1)
2438 end = self->buf->b_ml.ml_line_count;
2439
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002440 size = end - start + 1;
2441
2442 if (lo < 0)
2443 lo = 0;
2444 else if (lo > size)
2445 lo = size;
2446 if (hi < 0)
2447 hi = 0;
2448 if (hi < lo)
2449 hi = lo;
2450 else if (hi > size)
2451 hi = size;
2452
2453 return GetBufferLineList(self->buf, lo+start, hi+start);
2454}
2455
2456 static PyInt
2457RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2458{
2459 PyInt len_change;
2460
2461 if (CheckBuffer(self))
2462 return -1;
2463
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002464 if (end == -1)
2465 end = self->buf->b_ml.ml_line_count;
2466
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002467 if (n < 0)
2468 n += end - start + 1;
2469
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002470 if (n < 0 || n > end - start)
2471 {
2472 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2473 return -1;
2474 }
2475
2476 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2477 return -1;
2478
2479 if (new_end)
2480 *new_end = end + len_change;
2481
2482 return 0;
2483}
2484
Bram Moolenaar19e60942011-06-19 00:27:51 +02002485 static PyInt
2486RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2487{
2488 PyInt size;
2489 PyInt len_change;
2490
2491 /* Self must be a valid buffer */
2492 if (CheckBuffer(self))
2493 return -1;
2494
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002495 if (end == -1)
2496 end = self->buf->b_ml.ml_line_count;
2497
Bram Moolenaar19e60942011-06-19 00:27:51 +02002498 /* Sort out the slice range */
2499 size = end - start + 1;
2500
2501 if (lo < 0)
2502 lo = 0;
2503 else if (lo > size)
2504 lo = size;
2505 if (hi < 0)
2506 hi = 0;
2507 if (hi < lo)
2508 hi = lo;
2509 else if (hi > size)
2510 hi = size;
2511
2512 if (SetBufferLineList(self->buf, lo + start, hi + start,
2513 val, &len_change) == FAIL)
2514 return -1;
2515
2516 if (new_end)
2517 *new_end = end + len_change;
2518
2519 return 0;
2520}
2521
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002522
2523 static PyObject *
2524RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2525{
2526 PyObject *lines;
2527 PyInt len_change;
2528 PyInt max;
2529 PyInt n;
2530
2531 if (CheckBuffer(self))
2532 return NULL;
2533
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002534 if (end == -1)
2535 end = self->buf->b_ml.ml_line_count;
2536
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002537 max = n = end - start + 1;
2538
2539 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2540 return NULL;
2541
2542 if (n < 0 || n > max)
2543 {
2544 PyErr_SetString(PyExc_ValueError, _("line number out of range"));
2545 return NULL;
2546 }
2547
2548 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2549 return NULL;
2550
2551 if (new_end)
2552 *new_end = end + len_change;
2553
2554 Py_INCREF(Py_None);
2555 return Py_None;
2556}
2557
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002558/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002559 */
2560
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002561static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002562static PySequenceMethods RangeAsSeq;
2563static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002564
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002565typedef struct
2566{
2567 PyObject_HEAD
2568 BufferObject *buf;
2569 PyInt start;
2570 PyInt end;
2571} RangeObject;
2572
2573 static PyObject *
2574RangeNew(buf_T *buf, PyInt start, PyInt end)
2575{
2576 BufferObject *bufr;
2577 RangeObject *self;
2578 self = PyObject_NEW(RangeObject, &RangeType);
2579 if (self == NULL)
2580 return NULL;
2581
2582 bufr = (BufferObject *)BufferNew(buf);
2583 if (bufr == NULL)
2584 {
2585 Py_DECREF(self);
2586 return NULL;
2587 }
2588 Py_INCREF(bufr);
2589
2590 self->buf = bufr;
2591 self->start = start;
2592 self->end = end;
2593
2594 return (PyObject *)(self);
2595}
2596
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002597 static void
2598RangeDestructor(PyObject *self)
2599{
2600 Py_DECREF(((RangeObject *)(self))->buf);
2601 DESTRUCTOR_FINISH(self);
2602}
2603
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002604 static PyInt
2605RangeLength(PyObject *self)
2606{
2607 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2608 if (CheckBuffer(((RangeObject *)(self))->buf))
2609 return -1; /* ??? */
2610
2611 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2612}
2613
2614 static PyObject *
2615RangeItem(PyObject *self, PyInt n)
2616{
2617 return RBItem(((RangeObject *)(self))->buf, n,
2618 ((RangeObject *)(self))->start,
2619 ((RangeObject *)(self))->end);
2620}
2621
2622 static PyObject *
2623RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2624{
2625 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2626 ((RangeObject *)(self))->start,
2627 ((RangeObject *)(self))->end);
2628}
2629
2630 static PyObject *
2631RangeAppend(PyObject *self, PyObject *args)
2632{
2633 return RBAppend(((RangeObject *)(self))->buf, args,
2634 ((RangeObject *)(self))->start,
2635 ((RangeObject *)(self))->end,
2636 &((RangeObject *)(self))->end);
2637}
2638
2639 static PyObject *
2640RangeRepr(PyObject *self)
2641{
2642 static char repr[100];
2643 RangeObject *this = (RangeObject *)(self);
2644
2645 if (this->buf->buf == INVALID_BUFFER_VALUE)
2646 {
2647 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2648 (self));
2649 return PyString_FromString(repr);
2650 }
2651 else
2652 {
2653 char *name = (char *)this->buf->buf->b_fname;
2654 int len;
2655
2656 if (name == NULL)
2657 name = "";
2658 len = (int)strlen(name);
2659
2660 if (len > 45)
2661 name = name + (45 - len);
2662
2663 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2664 len > 45 ? "..." : "", name,
2665 this->start, this->end);
2666
2667 return PyString_FromString(repr);
2668 }
2669}
2670
2671static struct PyMethodDef RangeMethods[] = {
2672 /* name, function, calling, documentation */
2673 {"append", RangeAppend, 1, "Append data to the Vim range" },
2674 { NULL, NULL, 0, NULL }
2675};
2676
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002677static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002678static PySequenceMethods BufferAsSeq;
2679static PyMappingMethods BufferAsMapping;
2680
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002681 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02002682BufferNew(buf_T *buf)
2683{
2684 /* We need to handle deletion of buffers underneath us.
2685 * If we add a "b_python*_ref" field to the buf_T structure,
2686 * then we can get at it in buf_freeall() in vim. We then
2687 * need to create only ONE Python object per buffer - if
2688 * we try to create a second, just INCREF the existing one
2689 * and return it. The (single) Python object referring to
2690 * the buffer is stored in "b_python*_ref".
2691 * Question: what to do on a buf_freeall(). We'll probably
2692 * have to either delete the Python object (DECREF it to
2693 * zero - a bad idea, as it leaves dangling refs!) or
2694 * set the buf_T * value to an invalid value (-1?), which
2695 * means we need checks in all access functions... Bah.
2696 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002697 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02002698 * b_python_ref and b_python3_ref fields respectively.
2699 */
2700
2701 BufferObject *self;
2702
2703 if (BUF_PYTHON_REF(buf) != NULL)
2704 {
2705 self = BUF_PYTHON_REF(buf);
2706 Py_INCREF(self);
2707 }
2708 else
2709 {
2710 self = PyObject_NEW(BufferObject, &BufferType);
2711 if (self == NULL)
2712 return NULL;
2713 self->buf = buf;
2714 BUF_PYTHON_REF(buf) = self;
2715 }
2716
2717 return (PyObject *)(self);
2718}
2719
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002720 static void
2721BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002722{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002723 BufferObject *this = (BufferObject *)(self);
2724
2725 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
2726 BUF_PYTHON_REF(this->buf) = NULL;
2727
2728 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002729}
2730
Bram Moolenaar971db462013-05-12 18:44:48 +02002731 static PyInt
2732BufferLength(PyObject *self)
2733{
2734 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2735 if (CheckBuffer((BufferObject *)(self)))
2736 return -1; /* ??? */
2737
2738 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
2739}
2740
2741 static PyObject *
2742BufferItem(PyObject *self, PyInt n)
2743{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002744 return RBItem((BufferObject *)(self), n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002745}
2746
2747 static PyObject *
2748BufferSlice(PyObject *self, PyInt lo, PyInt hi)
2749{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002750 return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02002751}
2752
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002753 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002754BufferAttr(BufferObject *this, char *name)
2755{
2756 if (strcmp(name, "name") == 0)
2757 return Py_BuildValue("s", this->buf->b_ffname);
2758 else if (strcmp(name, "number") == 0)
2759 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
2760 else if (strcmp(name, "vars") == 0)
2761 return DictionaryNew(this->buf->b_vars);
2762 else if (strcmp(name, "options") == 0)
2763 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
2764 (PyObject *) this);
2765 else if (strcmp(name,"__members__") == 0)
2766 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
2767 else
2768 return NULL;
2769}
2770
2771 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002772BufferAppend(PyObject *self, PyObject *args)
2773{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002774 return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002775}
2776
2777 static PyObject *
2778BufferMark(PyObject *self, PyObject *args)
2779{
2780 pos_T *posp;
2781 char *pmark;
2782 char mark;
2783 buf_T *curbuf_save;
2784
2785 if (CheckBuffer((BufferObject *)(self)))
2786 return NULL;
2787
2788 if (!PyArg_ParseTuple(args, "s", &pmark))
2789 return NULL;
2790 mark = *pmark;
2791
2792 curbuf_save = curbuf;
2793 curbuf = ((BufferObject *)(self))->buf;
2794 posp = getmark(mark, FALSE);
2795 curbuf = curbuf_save;
2796
2797 if (posp == NULL)
2798 {
2799 PyErr_SetVim(_("invalid mark name"));
2800 return NULL;
2801 }
2802
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002803 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002804 if (VimErrorCheck())
2805 return NULL;
2806
2807 if (posp->lnum <= 0)
2808 {
2809 /* Or raise an error? */
2810 Py_INCREF(Py_None);
2811 return Py_None;
2812 }
2813
2814 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
2815}
2816
2817 static PyObject *
2818BufferRange(PyObject *self, PyObject *args)
2819{
2820 PyInt start;
2821 PyInt end;
2822
2823 if (CheckBuffer((BufferObject *)(self)))
2824 return NULL;
2825
2826 if (!PyArg_ParseTuple(args, "nn", &start, &end))
2827 return NULL;
2828
2829 return RangeNew(((BufferObject *)(self))->buf, start, end);
2830}
2831
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002832 static PyObject *
2833BufferRepr(PyObject *self)
2834{
2835 static char repr[100];
2836 BufferObject *this = (BufferObject *)(self);
2837
2838 if (this->buf == INVALID_BUFFER_VALUE)
2839 {
2840 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
2841 return PyString_FromString(repr);
2842 }
2843 else
2844 {
2845 char *name = (char *)this->buf->b_fname;
2846 PyInt len;
2847
2848 if (name == NULL)
2849 name = "";
2850 len = strlen(name);
2851
2852 if (len > 35)
2853 name = name + (35 - len);
2854
2855 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
2856
2857 return PyString_FromString(repr);
2858 }
2859}
2860
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002861static struct PyMethodDef BufferMethods[] = {
2862 /* name, function, calling, documentation */
2863 {"append", BufferAppend, 1, "Append data to Vim buffer" },
2864 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
2865 {"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 +01002866#if PY_VERSION_HEX >= 0x03000000
2867 {"__dir__", BufferDir, 4, "List its attributes" },
2868#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002869 { NULL, NULL, 0, NULL }
2870};
2871
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002872/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002873 */
2874
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002875 static PyObject *
2876CurrentGetattr(PyObject *self UNUSED, char *name)
2877{
2878 if (strcmp(name, "buffer") == 0)
2879 return (PyObject *)BufferNew(curbuf);
2880 else if (strcmp(name, "window") == 0)
2881 return (PyObject *)WindowNew(curwin);
2882 else if (strcmp(name, "line") == 0)
2883 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
2884 else if (strcmp(name, "range") == 0)
2885 return RangeNew(curbuf, RangeStart, RangeEnd);
2886 else if (strcmp(name,"__members__") == 0)
2887 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range");
2888 else
2889 {
2890 PyErr_SetString(PyExc_AttributeError, name);
2891 return NULL;
2892 }
2893}
2894
2895 static int
2896CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
2897{
2898 if (strcmp(name, "line") == 0)
2899 {
2900 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
2901 return -1;
2902
2903 return 0;
2904 }
2905 else
2906 {
2907 PyErr_SetString(PyExc_AttributeError, name);
2908 return -1;
2909 }
2910}
2911
Bram Moolenaardb913952012-06-29 12:54:53 +02002912 static void
2913set_ref_in_py(const int copyID)
2914{
2915 pylinkedlist_T *cur;
2916 dict_T *dd;
2917 list_T *ll;
2918
2919 if (lastdict != NULL)
2920 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
2921 {
2922 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
2923 if (dd->dv_copyID != copyID)
2924 {
2925 dd->dv_copyID = copyID;
2926 set_ref_in_ht(&dd->dv_hashtab, copyID);
2927 }
2928 }
2929
2930 if (lastlist != NULL)
2931 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
2932 {
2933 ll = ((ListObject *) (cur->pll_obj))->list;
2934 if (ll->lv_copyID != copyID)
2935 {
2936 ll->lv_copyID = copyID;
2937 set_ref_in_list(ll, copyID);
2938 }
2939 }
2940}
2941
2942 static int
2943set_string_copy(char_u *str, typval_T *tv)
2944{
2945 tv->vval.v_string = vim_strsave(str);
2946 if (tv->vval.v_string == NULL)
2947 {
2948 PyErr_NoMemory();
2949 return -1;
2950 }
2951 return 0;
2952}
2953
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002954 static int
2955pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
2956{
2957 dict_T *d;
2958 char_u *key;
2959 dictitem_T *di;
2960 PyObject *keyObject;
2961 PyObject *valObject;
2962 Py_ssize_t iter = 0;
2963
2964 d = dict_alloc();
2965 if (d == NULL)
2966 {
2967 PyErr_NoMemory();
2968 return -1;
2969 }
2970
2971 tv->v_type = VAR_DICT;
2972 tv->vval.v_dict = d;
2973
2974 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
2975 {
2976 DICTKEY_DECL
2977
2978 if (keyObject == NULL)
2979 return -1;
2980 if (valObject == NULL)
2981 return -1;
2982
2983 DICTKEY_GET_NOTEMPTY(-1)
2984
2985 di = dictitem_alloc(key);
2986
2987 DICTKEY_UNREF
2988
2989 if (di == NULL)
2990 {
2991 PyErr_NoMemory();
2992 return -1;
2993 }
2994 di->di_tv.v_lock = 0;
2995
2996 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
2997 {
2998 vim_free(di);
2999 return -1;
3000 }
3001 if (dict_add(d, di) == FAIL)
3002 {
3003 vim_free(di);
3004 PyErr_SetVim(_("failed to add key to dictionary"));
3005 return -1;
3006 }
3007 }
3008 return 0;
3009}
3010
3011 static int
3012pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3013{
3014 dict_T *d;
3015 char_u *key;
3016 dictitem_T *di;
3017 PyObject *list;
3018 PyObject *litem;
3019 PyObject *keyObject;
3020 PyObject *valObject;
3021 Py_ssize_t lsize;
3022
3023 d = dict_alloc();
3024 if (d == NULL)
3025 {
3026 PyErr_NoMemory();
3027 return -1;
3028 }
3029
3030 tv->v_type = VAR_DICT;
3031 tv->vval.v_dict = d;
3032
3033 list = PyMapping_Items(obj);
3034 if (list == NULL)
3035 return -1;
3036 lsize = PyList_Size(list);
3037 while (lsize--)
3038 {
3039 DICTKEY_DECL
3040
3041 litem = PyList_GetItem(list, lsize);
3042 if (litem == NULL)
3043 {
3044 Py_DECREF(list);
3045 return -1;
3046 }
3047
3048 keyObject = PyTuple_GetItem(litem, 0);
3049 if (keyObject == NULL)
3050 {
3051 Py_DECREF(list);
3052 Py_DECREF(litem);
3053 return -1;
3054 }
3055
3056 DICTKEY_GET_NOTEMPTY(-1)
3057
3058 valObject = PyTuple_GetItem(litem, 1);
3059 if (valObject == NULL)
3060 {
3061 Py_DECREF(list);
3062 Py_DECREF(litem);
3063 return -1;
3064 }
3065
3066 di = dictitem_alloc(key);
3067
3068 DICTKEY_UNREF
3069
3070 if (di == NULL)
3071 {
3072 Py_DECREF(list);
3073 Py_DECREF(litem);
3074 PyErr_NoMemory();
3075 return -1;
3076 }
3077 di->di_tv.v_lock = 0;
3078
3079 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3080 {
3081 vim_free(di);
3082 Py_DECREF(list);
3083 Py_DECREF(litem);
3084 return -1;
3085 }
3086 if (dict_add(d, di) == FAIL)
3087 {
3088 vim_free(di);
3089 Py_DECREF(list);
3090 Py_DECREF(litem);
3091 PyErr_SetVim(_("failed to add key to dictionary"));
3092 return -1;
3093 }
3094 Py_DECREF(litem);
3095 }
3096 Py_DECREF(list);
3097 return 0;
3098}
3099
3100 static int
3101pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3102{
3103 list_T *l;
3104
3105 l = list_alloc();
3106 if (l == NULL)
3107 {
3108 PyErr_NoMemory();
3109 return -1;
3110 }
3111
3112 tv->v_type = VAR_LIST;
3113 tv->vval.v_list = l;
3114
3115 if (list_py_concat(l, obj, lookupDict) == -1)
3116 return -1;
3117
3118 return 0;
3119}
3120
3121 static int
3122pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3123{
3124 PyObject *iterator = PyObject_GetIter(obj);
3125 PyObject *item;
3126 list_T *l;
3127 listitem_T *li;
3128
3129 l = list_alloc();
3130
3131 if (l == NULL)
3132 {
3133 PyErr_NoMemory();
3134 return -1;
3135 }
3136
3137 tv->vval.v_list = l;
3138 tv->v_type = VAR_LIST;
3139
3140
3141 if (iterator == NULL)
3142 return -1;
3143
3144 while ((item = PyIter_Next(obj)))
3145 {
3146 li = listitem_alloc();
3147 if (li == NULL)
3148 {
3149 PyErr_NoMemory();
3150 return -1;
3151 }
3152 li->li_tv.v_lock = 0;
3153
3154 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3155 return -1;
3156
3157 list_append(l, li);
3158
3159 Py_DECREF(item);
3160 }
3161
3162 Py_DECREF(iterator);
3163 return 0;
3164}
3165
Bram Moolenaardb913952012-06-29 12:54:53 +02003166typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3167
3168 static int
3169convert_dl(PyObject *obj, typval_T *tv,
3170 pytotvfunc py_to_tv, PyObject *lookupDict)
3171{
3172 PyObject *capsule;
3173 char hexBuf[sizeof(void *) * 2 + 3];
3174
3175 sprintf(hexBuf, "%p", obj);
3176
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003177# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003178 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003179# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003180 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003181# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003182 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003183 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003184# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003185 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003186# else
3187 capsule = PyCObject_FromVoidPtr(tv, NULL);
3188# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003189 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3190 Py_DECREF(capsule);
3191 if (py_to_tv(obj, tv, lookupDict) == -1)
3192 {
3193 tv->v_type = VAR_UNKNOWN;
3194 return -1;
3195 }
3196 /* As we are not using copy_tv which increments reference count we must
3197 * do it ourself. */
3198 switch(tv->v_type)
3199 {
3200 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3201 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3202 }
3203 }
3204 else
3205 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003206 typval_T *v;
3207
3208# ifdef PY_USE_CAPSULE
3209 v = PyCapsule_GetPointer(capsule, NULL);
3210# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003211 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003212# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003213 copy_tv(v, tv);
3214 }
3215 return 0;
3216}
3217
3218 static int
3219ConvertFromPyObject(PyObject *obj, typval_T *tv)
3220{
3221 PyObject *lookup_dict;
3222 int r;
3223
3224 lookup_dict = PyDict_New();
3225 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3226 Py_DECREF(lookup_dict);
3227 return r;
3228}
3229
3230 static int
3231_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3232{
3233 if (obj->ob_type == &DictionaryType)
3234 {
3235 tv->v_type = VAR_DICT;
3236 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3237 ++tv->vval.v_dict->dv_refcount;
3238 }
3239 else if (obj->ob_type == &ListType)
3240 {
3241 tv->v_type = VAR_LIST;
3242 tv->vval.v_list = (((ListObject *)(obj))->list);
3243 ++tv->vval.v_list->lv_refcount;
3244 }
3245 else if (obj->ob_type == &FunctionType)
3246 {
3247 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3248 return -1;
3249
3250 tv->v_type = VAR_FUNC;
3251 func_ref(tv->vval.v_string);
3252 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003253 else if (PyBytes_Check(obj))
3254 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003255 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003256
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003257 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3258 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003259 if (result == NULL)
3260 return -1;
3261
3262 if (set_string_copy(result, tv) == -1)
3263 return -1;
3264
3265 tv->v_type = VAR_STRING;
3266 }
3267 else if (PyUnicode_Check(obj))
3268 {
3269 PyObject *bytes;
3270 char_u *result;
3271
Bram Moolenaardb913952012-06-29 12:54:53 +02003272 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3273 if (bytes == NULL)
3274 return -1;
3275
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003276 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3277 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003278 if (result == NULL)
3279 return -1;
3280
3281 if (set_string_copy(result, tv) == -1)
3282 {
3283 Py_XDECREF(bytes);
3284 return -1;
3285 }
3286 Py_XDECREF(bytes);
3287
3288 tv->v_type = VAR_STRING;
3289 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003290#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003291 else if (PyInt_Check(obj))
3292 {
3293 tv->v_type = VAR_NUMBER;
3294 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3295 }
3296#endif
3297 else if (PyLong_Check(obj))
3298 {
3299 tv->v_type = VAR_NUMBER;
3300 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3301 }
3302 else if (PyDict_Check(obj))
3303 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3304#ifdef FEAT_FLOAT
3305 else if (PyFloat_Check(obj))
3306 {
3307 tv->v_type = VAR_FLOAT;
3308 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3309 }
3310#endif
3311 else if (PyIter_Check(obj))
3312 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3313 else if (PySequence_Check(obj))
3314 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3315 else if (PyMapping_Check(obj))
3316 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3317 else
3318 {
3319 PyErr_SetString(PyExc_TypeError, _("unable to convert to vim structure"));
3320 return -1;
3321 }
3322 return 0;
3323}
3324
3325 static PyObject *
3326ConvertToPyObject(typval_T *tv)
3327{
3328 if (tv == NULL)
3329 {
3330 PyErr_SetVim(_("NULL reference passed"));
3331 return NULL;
3332 }
3333 switch (tv->v_type)
3334 {
3335 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003336 return PyBytes_FromString(tv->vval.v_string == NULL
3337 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003338 case VAR_NUMBER:
3339 return PyLong_FromLong((long) tv->vval.v_number);
3340#ifdef FEAT_FLOAT
3341 case VAR_FLOAT:
3342 return PyFloat_FromDouble((double) tv->vval.v_float);
3343#endif
3344 case VAR_LIST:
3345 return ListNew(tv->vval.v_list);
3346 case VAR_DICT:
3347 return DictionaryNew(tv->vval.v_dict);
3348 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003349 return FunctionNew(tv->vval.v_string == NULL
3350 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003351 case VAR_UNKNOWN:
3352 Py_INCREF(Py_None);
3353 return Py_None;
3354 default:
3355 PyErr_SetVim(_("internal error: invalid value type"));
3356 return NULL;
3357 }
3358}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003359
3360typedef struct
3361{
3362 PyObject_HEAD
3363} CurrentObject;
3364static PyTypeObject CurrentType;
3365
3366 static void
3367init_structs(void)
3368{
3369 vim_memset(&OutputType, 0, sizeof(OutputType));
3370 OutputType.tp_name = "vim.message";
3371 OutputType.tp_basicsize = sizeof(OutputObject);
3372 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
3373 OutputType.tp_doc = "vim message object";
3374 OutputType.tp_methods = OutputMethods;
3375#if PY_MAJOR_VERSION >= 3
3376 OutputType.tp_getattro = OutputGetattro;
3377 OutputType.tp_setattro = OutputSetattro;
3378 OutputType.tp_alloc = call_PyType_GenericAlloc;
3379 OutputType.tp_new = call_PyType_GenericNew;
3380 OutputType.tp_free = call_PyObject_Free;
3381#else
3382 OutputType.tp_getattr = OutputGetattr;
3383 OutputType.tp_setattr = OutputSetattr;
3384#endif
3385
3386 vim_memset(&BufferType, 0, sizeof(BufferType));
3387 BufferType.tp_name = "vim.buffer";
3388 BufferType.tp_basicsize = sizeof(BufferType);
3389 BufferType.tp_dealloc = BufferDestructor;
3390 BufferType.tp_repr = BufferRepr;
3391 BufferType.tp_as_sequence = &BufferAsSeq;
3392 BufferType.tp_as_mapping = &BufferAsMapping;
3393 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
3394 BufferType.tp_doc = "vim buffer object";
3395 BufferType.tp_methods = BufferMethods;
3396#if PY_MAJOR_VERSION >= 3
3397 BufferType.tp_getattro = BufferGetattro;
3398 BufferType.tp_alloc = call_PyType_GenericAlloc;
3399 BufferType.tp_new = call_PyType_GenericNew;
3400 BufferType.tp_free = call_PyObject_Free;
3401#else
3402 BufferType.tp_getattr = BufferGetattr;
3403#endif
3404
3405 vim_memset(&WindowType, 0, sizeof(WindowType));
3406 WindowType.tp_name = "vim.window";
3407 WindowType.tp_basicsize = sizeof(WindowObject);
3408 WindowType.tp_dealloc = WindowDestructor;
3409 WindowType.tp_repr = WindowRepr;
3410 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
3411 WindowType.tp_doc = "vim Window object";
3412 WindowType.tp_methods = WindowMethods;
3413#if PY_MAJOR_VERSION >= 3
3414 WindowType.tp_getattro = WindowGetattro;
3415 WindowType.tp_setattro = WindowSetattro;
3416 WindowType.tp_alloc = call_PyType_GenericAlloc;
3417 WindowType.tp_new = call_PyType_GenericNew;
3418 WindowType.tp_free = call_PyObject_Free;
3419#else
3420 WindowType.tp_getattr = WindowGetattr;
3421 WindowType.tp_setattr = WindowSetattr;
3422#endif
3423
Bram Moolenaardfa38d42013-05-15 13:38:47 +02003424 vim_memset(&BufMapType, 0, sizeof(BufMapType));
3425 BufMapType.tp_name = "vim.bufferlist";
3426 BufMapType.tp_basicsize = sizeof(BufMapObject);
3427 BufMapType.tp_as_mapping = &BufMapAsMapping;
3428 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003429 BufferType.tp_doc = "vim buffer list";
3430
3431 vim_memset(&WinListType, 0, sizeof(WinListType));
3432 WinListType.tp_name = "vim.windowlist";
3433 WinListType.tp_basicsize = sizeof(WinListType);
3434 WinListType.tp_as_sequence = &WinListAsSeq;
3435 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
3436 WinListType.tp_doc = "vim window list";
3437
3438 vim_memset(&RangeType, 0, sizeof(RangeType));
3439 RangeType.tp_name = "vim.range";
3440 RangeType.tp_basicsize = sizeof(RangeObject);
3441 RangeType.tp_dealloc = RangeDestructor;
3442 RangeType.tp_repr = RangeRepr;
3443 RangeType.tp_as_sequence = &RangeAsSeq;
3444 RangeType.tp_as_mapping = &RangeAsMapping;
3445 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
3446 RangeType.tp_doc = "vim Range object";
3447 RangeType.tp_methods = RangeMethods;
3448#if PY_MAJOR_VERSION >= 3
3449 RangeType.tp_getattro = RangeGetattro;
3450 RangeType.tp_alloc = call_PyType_GenericAlloc;
3451 RangeType.tp_new = call_PyType_GenericNew;
3452 RangeType.tp_free = call_PyObject_Free;
3453#else
3454 RangeType.tp_getattr = RangeGetattr;
3455#endif
3456
3457 vim_memset(&CurrentType, 0, sizeof(CurrentType));
3458 CurrentType.tp_name = "vim.currentdata";
3459 CurrentType.tp_basicsize = sizeof(CurrentObject);
3460 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
3461 CurrentType.tp_doc = "vim current object";
3462#if PY_MAJOR_VERSION >= 3
3463 CurrentType.tp_getattro = CurrentGetattro;
3464 CurrentType.tp_setattro = CurrentSetattro;
3465#else
3466 CurrentType.tp_getattr = CurrentGetattr;
3467 CurrentType.tp_setattr = CurrentSetattr;
3468#endif
3469
3470 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
3471 DictionaryType.tp_name = "vim.dictionary";
3472 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
3473 DictionaryType.tp_dealloc = DictionaryDestructor;
3474 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
3475 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
3476 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
3477 DictionaryType.tp_methods = DictionaryMethods;
3478#if PY_MAJOR_VERSION >= 3
3479 DictionaryType.tp_getattro = DictionaryGetattro;
3480 DictionaryType.tp_setattro = DictionarySetattro;
3481#else
3482 DictionaryType.tp_getattr = DictionaryGetattr;
3483 DictionaryType.tp_setattr = DictionarySetattr;
3484#endif
3485
3486 vim_memset(&ListType, 0, sizeof(ListType));
3487 ListType.tp_name = "vim.list";
3488 ListType.tp_dealloc = ListDestructor;
3489 ListType.tp_basicsize = sizeof(ListObject);
3490 ListType.tp_as_sequence = &ListAsSeq;
3491 ListType.tp_as_mapping = &ListAsMapping;
3492 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
3493 ListType.tp_doc = "list pushing modifications to vim structure";
3494 ListType.tp_methods = ListMethods;
3495#if PY_MAJOR_VERSION >= 3
3496 ListType.tp_getattro = ListGetattro;
3497 ListType.tp_setattro = ListSetattro;
3498#else
3499 ListType.tp_getattr = ListGetattr;
3500 ListType.tp_setattr = ListSetattr;
3501#endif
3502
3503 vim_memset(&FunctionType, 0, sizeof(FunctionType));
3504 FunctionType.tp_name = "vim.list";
3505 FunctionType.tp_basicsize = sizeof(FunctionObject);
3506 FunctionType.tp_dealloc = FunctionDestructor;
3507 FunctionType.tp_call = FunctionCall;
3508 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
3509 FunctionType.tp_doc = "object that calls vim function";
3510 FunctionType.tp_methods = FunctionMethods;
3511#if PY_MAJOR_VERSION >= 3
3512 FunctionType.tp_getattro = FunctionGetattro;
3513#else
3514 FunctionType.tp_getattr = FunctionGetattr;
3515#endif
3516
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02003517 vim_memset(&OptionsType, 0, sizeof(OptionsType));
3518 OptionsType.tp_name = "vim.options";
3519 OptionsType.tp_basicsize = sizeof(OptionsObject);
3520 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
3521 OptionsType.tp_doc = "object for manipulating options";
3522 OptionsType.tp_as_mapping = &OptionsAsMapping;
3523 OptionsType.tp_dealloc = OptionsDestructor;
3524
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003525#if PY_MAJOR_VERSION >= 3
3526 vim_memset(&vimmodule, 0, sizeof(vimmodule));
3527 vimmodule.m_name = "vim";
3528 vimmodule.m_doc = "Vim Python interface\n";
3529 vimmodule.m_size = -1;
3530 vimmodule.m_methods = VimMethods;
3531#endif
3532}