blob: fd500330ef6cbfead656a1dd2068364e7b3e10f4 [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
Bram Moolenaard620aa92013-05-17 16:40:06 +020025#define DOPY_FUNC "_vim_pydo"
Bram Moolenaar91805fc2011-06-26 04:01:44 +020026
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020027#define PyErr_SetVim(str) PyErr_SetString(VimError, str)
28
29#define INVALID_BUFFER_VALUE ((buf_T *)(-1))
30#define INVALID_WINDOW_VALUE ((win_T *)(-1))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +020031#define INVALID_TABPAGE_VALUE ((tabpage_T *)(-1))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020032
Bram Moolenaarb52f4c02013-05-21 18:19:38 +020033typedef void (*rangeinitializer)(void *);
34typedef void (*runner)(const char *, void *, PyGILState_STATE *);
35
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020036static int ConvertFromPyObject(PyObject *, typval_T *);
37static int _ConvertFromPyObject(PyObject *, typval_T *, PyObject *);
Bram Moolenaarcabf80f2013-05-17 16:18:33 +020038static PyObject *WindowNew(win_T *, tabpage_T *);
39static PyObject *BufferNew (buf_T *);
40static PyObject *LineToString(const char *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020041
42static PyInt RangeStart;
43static PyInt RangeEnd;
44
Bram Moolenaarb52f4c02013-05-21 18:19:38 +020045static PyObject *globals;
46
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020047/*
48 * obtain a lock on the Vim data structures
49 */
50 static void
51Python_Lock_Vim(void)
52{
53}
54
55/*
56 * release a lock on the Vim data structures
57 */
58 static void
59Python_Release_Vim(void)
60{
61}
62
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020063/* Output buffer management
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020064 */
65
Bram Moolenaar2eea1982010-09-21 16:49:37 +020066/* Function to write a line, points to either msg() or emsg(). */
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020067typedef void (*writefn)(char_u *);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +020068
69static PyTypeObject OutputType;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +020070
71typedef struct
72{
73 PyObject_HEAD
74 long softspace;
75 long error;
76} OutputObject;
77
Bram Moolenaar77045652012-09-21 13:46:06 +020078 static int
79OutputSetattr(PyObject *self, char *name, PyObject *val)
80{
81 if (val == NULL)
82 {
Bram Moolenaar8661b172013-05-15 15:44:28 +020083 PyErr_SetString(PyExc_AttributeError,
84 _("can't delete OutputObject attributes"));
Bram Moolenaar77045652012-09-21 13:46:06 +020085 return -1;
86 }
87
88 if (strcmp(name, "softspace") == 0)
89 {
90 if (!PyInt_Check(val))
91 {
92 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer"));
93 return -1;
94 }
95
96 ((OutputObject *)(self))->softspace = PyInt_AsLong(val);
97 return 0;
98 }
99
100 PyErr_SetString(PyExc_AttributeError, _("invalid attribute"));
101 return -1;
102}
103
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200104/* Buffer IO, we write one whole line at a time. */
105static garray_T io_ga = {0, 0, 1, 80, NULL};
106static writefn old_fn = NULL;
107
108 static void
109PythonIO_Flush(void)
110{
111 if (old_fn != NULL && io_ga.ga_len > 0)
112 {
113 ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
114 old_fn((char_u *)io_ga.ga_data);
115 }
116 io_ga.ga_len = 0;
117}
118
119 static void
120writer(writefn fn, char_u *str, PyInt n)
121{
122 char_u *ptr;
123
124 /* Flush when switching output function. */
125 if (fn != old_fn)
126 PythonIO_Flush();
127 old_fn = fn;
128
129 /* Write each NL separated line. Text after the last NL is kept for
130 * writing later. */
131 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
132 {
133 PyInt len = ptr - str;
134
135 if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
136 break;
137
138 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
139 ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
140 fn((char_u *)io_ga.ga_data);
141 str = ptr + 1;
142 n -= len + 1;
143 io_ga.ga_len = 0;
144 }
145
146 /* Put the remaining text into io_ga for later printing. */
147 if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
148 {
149 mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
150 io_ga.ga_len += (int)n;
151 }
152}
153
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200154 static PyObject *
155OutputWrite(PyObject *self, PyObject *args)
156{
Bram Moolenaare8cdcef2012-09-12 20:21:43 +0200157 Py_ssize_t len = 0;
Bram Moolenaar19e60942011-06-19 00:27:51 +0200158 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200159 int error = ((OutputObject *)(self))->error;
160
Bram Moolenaar27564802011-09-07 19:30:21 +0200161 if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200162 return NULL;
163
164 Py_BEGIN_ALLOW_THREADS
165 Python_Lock_Vim();
166 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
167 Python_Release_Vim();
168 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200169 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200170
171 Py_INCREF(Py_None);
172 return Py_None;
173}
174
175 static PyObject *
176OutputWritelines(PyObject *self, PyObject *args)
177{
178 PyInt n;
179 PyInt i;
180 PyObject *list;
181 int error = ((OutputObject *)(self))->error;
182
183 if (!PyArg_ParseTuple(args, "O", &list))
184 return NULL;
185 Py_INCREF(list);
186
Bram Moolenaardb913952012-06-29 12:54:53 +0200187 if (!PyList_Check(list))
188 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200189 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
190 Py_DECREF(list);
191 return NULL;
192 }
193
194 n = PyList_Size(list);
195
196 for (i = 0; i < n; ++i)
197 {
198 PyObject *line = PyList_GetItem(list, i);
Bram Moolenaar19e60942011-06-19 00:27:51 +0200199 char *str = NULL;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200200 PyInt len;
201
Bram Moolenaardb913952012-06-29 12:54:53 +0200202 if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len))
203 {
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200204 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
205 Py_DECREF(list);
206 return NULL;
207 }
208
209 Py_BEGIN_ALLOW_THREADS
210 Python_Lock_Vim();
211 writer((writefn)(error ? emsg : msg), (char_u *)str, len);
212 Python_Release_Vim();
213 Py_END_ALLOW_THREADS
Bram Moolenaar19e60942011-06-19 00:27:51 +0200214 PyMem_Free(str);
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200215 }
216
217 Py_DECREF(list);
218 Py_INCREF(Py_None);
219 return Py_None;
220}
221
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100222 static PyObject *
223OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
224{
225 /* do nothing */
226 Py_INCREF(Py_None);
227 return Py_None;
228}
229
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200230/***************/
231
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200232static struct PyMethodDef OutputMethods[] = {
233 /* name, function, calling, documentation */
234 {"write", OutputWrite, 1, ""},
235 {"writelines", OutputWritelines, 1, ""},
236 {"flush", OutputFlush, 1, ""},
237 { NULL, NULL, 0, NULL}
238};
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200239
240static OutputObject Output =
241{
242 PyObject_HEAD_INIT(&OutputType)
243 0,
244 0
245};
246
247static OutputObject Error =
248{
249 PyObject_HEAD_INIT(&OutputType)
250 0,
251 1
252};
253
254 static int
255PythonIO_Init_io(void)
256{
257 PySys_SetObject("stdout", (PyObject *)(void *)&Output);
258 PySys_SetObject("stderr", (PyObject *)(void *)&Error);
259
260 if (PyErr_Occurred())
261 {
262 EMSG(_("E264: Python: Error initialising I/O objects"));
263 return -1;
264 }
265
266 return 0;
267}
268
269
270static PyObject *VimError;
271
272/* Check to see whether a Vim error has been reported, or a keyboard
273 * interrupt has been detected.
274 */
275 static int
276VimErrorCheck(void)
277{
278 if (got_int)
279 {
280 PyErr_SetNone(PyExc_KeyboardInterrupt);
281 return 1;
282 }
283 else if (did_emsg && !PyErr_Occurred())
284 {
285 PyErr_SetNone(VimError);
286 return 1;
287 }
288
289 return 0;
290}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200291
292/* Vim module - Implementation
293 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200294
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200295 static PyObject *
296VimCommand(PyObject *self UNUSED, PyObject *args)
297{
298 char *cmd;
299 PyObject *result;
300
301 if (!PyArg_ParseTuple(args, "s", &cmd))
302 return NULL;
303
304 PyErr_Clear();
305
306 Py_BEGIN_ALLOW_THREADS
307 Python_Lock_Vim();
308
309 do_cmdline_cmd((char_u *)cmd);
310 update_screen(VALID);
311
312 Python_Release_Vim();
313 Py_END_ALLOW_THREADS
314
315 if (VimErrorCheck())
316 result = NULL;
317 else
318 result = Py_None;
319
320 Py_XINCREF(result);
321 return result;
322}
323
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200324/*
325 * Function to translate a typval_T into a PyObject; this will recursively
326 * translate lists/dictionaries into their Python equivalents.
327 *
328 * The depth parameter is to avoid infinite recursion, set it to 1 when
329 * you call VimToPython.
330 */
331 static PyObject *
332VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
333{
334 PyObject *result;
335 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200336 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200337
338 /* Avoid infinite recursion */
339 if (depth > 100)
340 {
341 Py_INCREF(Py_None);
342 result = Py_None;
343 return result;
344 }
345
346 /* Check if we run into a recursive loop. The item must be in lookupDict
347 * then and we can use it again. */
348 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
349 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
350 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200351 sprintf(ptrBuf, "%p",
352 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
353 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200354 result = PyDict_GetItemString(lookupDict, ptrBuf);
355 if (result != NULL)
356 {
357 Py_INCREF(result);
358 return result;
359 }
360 }
361
362 if (our_tv->v_type == VAR_STRING)
363 {
Bram Moolenaard1f13fd2012-10-05 21:30:07 +0200364 result = Py_BuildValue("s", our_tv->vval.v_string == NULL
365 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200366 }
367 else if (our_tv->v_type == VAR_NUMBER)
368 {
369 char buf[NUMBUFLEN];
370
371 /* For backwards compatibility numbers are stored as strings. */
372 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
373 result = Py_BuildValue("s", buf);
374 }
375# ifdef FEAT_FLOAT
376 else if (our_tv->v_type == VAR_FLOAT)
377 {
378 char buf[NUMBUFLEN];
379
380 sprintf(buf, "%f", our_tv->vval.v_float);
381 result = Py_BuildValue("s", buf);
382 }
383# endif
384 else if (our_tv->v_type == VAR_LIST)
385 {
386 list_T *list = our_tv->vval.v_list;
387 listitem_T *curr;
388
389 result = PyList_New(0);
390
391 if (list != NULL)
392 {
393 PyDict_SetItemString(lookupDict, ptrBuf, result);
394
395 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
396 {
397 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
398 PyList_Append(result, newObj);
399 Py_DECREF(newObj);
400 }
401 }
402 }
403 else if (our_tv->v_type == VAR_DICT)
404 {
405 result = PyDict_New();
406
407 if (our_tv->vval.v_dict != NULL)
408 {
409 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
410 long_u todo = ht->ht_used;
411 hashitem_T *hi;
412 dictitem_T *di;
413
414 PyDict_SetItemString(lookupDict, ptrBuf, result);
415
416 for (hi = ht->ht_array; todo > 0; ++hi)
417 {
418 if (!HASHITEM_EMPTY(hi))
419 {
420 --todo;
421
422 di = dict_lookup(hi);
423 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
424 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
425 Py_DECREF(newObj);
426 }
427 }
428 }
429 }
430 else
431 {
432 Py_INCREF(Py_None);
433 result = Py_None;
434 }
435
436 return result;
437}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200438
439 static PyObject *
Bram Moolenaar09092152010-08-08 16:38:42 +0200440VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200441{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200442 char *expr;
443 typval_T *our_tv;
444 PyObject *result;
445 PyObject *lookup_dict;
446
447 if (!PyArg_ParseTuple(args, "s", &expr))
448 return NULL;
449
450 Py_BEGIN_ALLOW_THREADS
451 Python_Lock_Vim();
452 our_tv = eval_expr((char_u *)expr, NULL);
453
454 Python_Release_Vim();
455 Py_END_ALLOW_THREADS
456
457 if (our_tv == NULL)
458 {
459 PyErr_SetVim(_("invalid expression"));
460 return NULL;
461 }
462
463 /* Convert the Vim type into a Python type. Create a dictionary that's
464 * used to check for recursive loops. */
465 lookup_dict = PyDict_New();
466 result = VimToPython(our_tv, 1, lookup_dict);
467 Py_DECREF(lookup_dict);
468
469
470 Py_BEGIN_ALLOW_THREADS
471 Python_Lock_Vim();
472 free_tv(our_tv);
473 Python_Release_Vim();
474 Py_END_ALLOW_THREADS
475
476 return result;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200477}
478
Bram Moolenaardb913952012-06-29 12:54:53 +0200479static PyObject *ConvertToPyObject(typval_T *);
480
481 static PyObject *
Bram Moolenaar9e74e302013-05-17 21:20:17 +0200482VimEvalPy(PyObject *self UNUSED, PyObject *args)
Bram Moolenaardb913952012-06-29 12:54:53 +0200483{
Bram Moolenaardb913952012-06-29 12:54:53 +0200484 char *expr;
485 typval_T *our_tv;
486 PyObject *result;
487
488 if (!PyArg_ParseTuple(args, "s", &expr))
489 return NULL;
490
491 Py_BEGIN_ALLOW_THREADS
492 Python_Lock_Vim();
493 our_tv = eval_expr((char_u *)expr, NULL);
494
495 Python_Release_Vim();
496 Py_END_ALLOW_THREADS
497
498 if (our_tv == NULL)
499 {
500 PyErr_SetVim(_("invalid expression"));
501 return NULL;
502 }
503
504 result = ConvertToPyObject(our_tv);
505 Py_BEGIN_ALLOW_THREADS
506 Python_Lock_Vim();
507 free_tv(our_tv);
508 Python_Release_Vim();
509 Py_END_ALLOW_THREADS
510
511 return result;
Bram Moolenaardb913952012-06-29 12:54:53 +0200512}
513
514 static PyObject *
515VimStrwidth(PyObject *self UNUSED, PyObject *args)
516{
517 char *expr;
518
519 if (!PyArg_ParseTuple(args, "s", &expr))
520 return NULL;
521
Bram Moolenaara54bf402012-12-05 16:30:07 +0100522 return PyLong_FromLong(
523#ifdef FEAT_MBYTE
524 mb_string2cells((char_u *)expr, (int)STRLEN(expr))
525#else
526 STRLEN(expr)
527#endif
528 );
Bram Moolenaardb913952012-06-29 12:54:53 +0200529}
530
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200531/*
532 * Vim module - Definitions
533 */
534
535static struct PyMethodDef VimMethods[] = {
536 /* name, function, calling, documentation */
537 {"command", VimCommand, 1, "Execute a Vim ex-mode command" },
538 {"eval", VimEval, 1, "Evaluate an expression using Vim evaluator" },
Bram Moolenaar2afa3232012-06-29 16:28:28 +0200539 {"bindeval", VimEvalPy, 1, "Like eval(), but returns objects attached to vim ones"},
540 {"strwidth", VimStrwidth, 1, "Screen string width, counts <Tab> as having width 1"},
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200541 { NULL, NULL, 0, NULL }
542};
543
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200544/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200545 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200546 */
547
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200548static PyTypeObject IterType;
549
550typedef PyObject *(*nextfun)(void **);
551typedef void (*destructorfun)(void *);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200552typedef int (*traversefun)(void *, visitproc, void *);
553typedef int (*clearfun)(void **);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200554
Bram Moolenaar9e74e302013-05-17 21:20:17 +0200555/* Main purpose of this object is removing the need for do python
556 * initialization (i.e. PyType_Ready and setting type attributes) for a big
557 * bunch of objects. */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200558
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200559typedef struct
560{
561 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200562 void *cur;
563 nextfun next;
564 destructorfun destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200565 traversefun traverse;
566 clearfun clear;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200567} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200568
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200569 static PyObject *
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200570IterNew(void *start, destructorfun destruct, nextfun next, traversefun traverse,
571 clearfun clear)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200572{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200573 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200574
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200575 self = PyObject_NEW(IterObject, &IterType);
576 self->cur = start;
577 self->next = next;
578 self->destruct = destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200579 self->traverse = traverse;
580 self->clear = clear;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200581
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200582 return (PyObject *)(self);
583}
584
585 static void
586IterDestructor(PyObject *self)
587{
588 IterObject *this = (IterObject *)(self);
589
590 this->destruct(this->cur);
591
592 DESTRUCTOR_FINISH(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200593}
594
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200595 static int
596IterTraverse(PyObject *self, visitproc visit, void *arg)
597{
598 IterObject *this = (IterObject *)(self);
599
600 if (this->traverse != NULL)
601 return this->traverse(this->cur, visit, arg);
602 else
603 return 0;
604}
605
Bram Moolenaar9e74e302013-05-17 21:20:17 +0200606/* Mac OSX defines clear() somewhere. */
607#ifdef clear
608# undef clear
609#endif
610
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200611 static int
612IterClear(PyObject *self)
613{
614 IterObject *this = (IterObject *)(self);
615
616 if (this->clear != NULL)
617 return this->clear(&this->cur);
618 else
619 return 0;
620}
621
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200622 static PyObject *
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200623IterNext(PyObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200624{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200625 IterObject *this = (IterObject *)(self);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200626
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200627 return this->next(&this->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200628}
629
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200630 static PyObject *
631IterIter(PyObject *self)
632{
633 return self;
634}
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200635
Bram Moolenaardb913952012-06-29 12:54:53 +0200636typedef struct pylinkedlist_S {
637 struct pylinkedlist_S *pll_next;
638 struct pylinkedlist_S *pll_prev;
639 PyObject *pll_obj;
640} pylinkedlist_T;
641
642static pylinkedlist_T *lastdict = NULL;
643static pylinkedlist_T *lastlist = NULL;
644
645 static void
646pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
647{
648 if (ref->pll_prev == NULL)
649 {
650 if (ref->pll_next == NULL)
651 {
652 *last = NULL;
653 return;
654 }
655 }
656 else
657 ref->pll_prev->pll_next = ref->pll_next;
658
659 if (ref->pll_next == NULL)
660 *last = ref->pll_prev;
661 else
662 ref->pll_next->pll_prev = ref->pll_prev;
663}
664
665 static void
666pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
667{
668 if (*last == NULL)
669 ref->pll_prev = NULL;
670 else
671 {
672 (*last)->pll_next = ref;
673 ref->pll_prev = *last;
674 }
675 ref->pll_next = NULL;
676 ref->pll_obj = self;
677 *last = ref;
678}
679
680static PyTypeObject DictionaryType;
681
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200682#define DICTKEY_GET_NOTEMPTY(err) \
683 DICTKEY_GET(err) \
684 if (*key == NUL) \
685 { \
686 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
687 return err; \
688 }
689
Bram Moolenaardb913952012-06-29 12:54:53 +0200690typedef struct
691{
692 PyObject_HEAD
693 dict_T *dict;
694 pylinkedlist_T ref;
695} DictionaryObject;
696
697 static PyObject *
698DictionaryNew(dict_T *dict)
699{
700 DictionaryObject *self;
701
702 self = PyObject_NEW(DictionaryObject, &DictionaryType);
703 if (self == NULL)
704 return NULL;
705 self->dict = dict;
706 ++dict->dv_refcount;
707
708 pyll_add((PyObject *)(self), &self->ref, &lastdict);
709
710 return (PyObject *)(self);
711}
712
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200713 static void
714DictionaryDestructor(PyObject *self)
715{
716 DictionaryObject *this = ((DictionaryObject *) (self));
717
718 pyll_remove(&this->ref, &lastdict);
719 dict_unref(this->dict);
720
721 DESTRUCTOR_FINISH(self);
722}
723
Bram Moolenaardb913952012-06-29 12:54:53 +0200724 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200725DictionarySetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200726{
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200727 DictionaryObject *this = (DictionaryObject *)(self);
728
Bram Moolenaar66b79852012-09-21 14:00:35 +0200729 if (val == NULL)
730 {
731 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
732 return -1;
733 }
734
735 if (strcmp(name, "locked") == 0)
736 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200737 if (this->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200738 {
739 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
740 return -1;
741 }
742 else
743 {
Bram Moolenaarb983f752013-05-15 16:11:50 +0200744 int istrue = PyObject_IsTrue(val);
745 if (istrue == -1)
746 return -1;
747 else if (istrue)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200748 this->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200749 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200750 this->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200751 }
752 return 0;
753 }
754 else
755 {
756 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
757 return -1;
758 }
759}
760
761 static PyInt
Bram Moolenaardb913952012-06-29 12:54:53 +0200762DictionaryLength(PyObject *self)
763{
764 return ((PyInt) ((((DictionaryObject *)(self))->dict->dv_hashtab.ht_used)));
765}
766
767 static PyObject *
768DictionaryItem(PyObject *self, PyObject *keyObject)
769{
770 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200771 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200772 DICTKEY_DECL
773
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200774 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200775
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200776 di = dict_find(((DictionaryObject *) (self))->dict, key, -1);
777
Bram Moolenaar696c2112012-09-21 13:43:14 +0200778 DICTKEY_UNREF
779
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200780 if (di == NULL)
781 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200782 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200783 return NULL;
784 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200785
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200786 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200787}
788
789 static PyInt
790DictionaryAssItem(PyObject *self, PyObject *keyObject, PyObject *valObject)
791{
792 char_u *key;
793 typval_T tv;
794 dict_T *d = ((DictionaryObject *)(self))->dict;
795 dictitem_T *di;
796 DICTKEY_DECL
797
798 if (d->dv_lock)
799 {
800 PyErr_SetVim(_("dict is locked"));
801 return -1;
802 }
803
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200804 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200805
806 di = dict_find(d, key, -1);
807
808 if (valObject == NULL)
809 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200810 hashitem_T *hi;
811
Bram Moolenaardb913952012-06-29 12:54:53 +0200812 if (di == NULL)
813 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200814 DICTKEY_UNREF
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200815 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaardb913952012-06-29 12:54:53 +0200816 return -1;
817 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200818 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200819 hash_remove(&d->dv_hashtab, hi);
820 dictitem_free(di);
821 return 0;
822 }
823
824 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200825 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200826
827 if (di == NULL)
828 {
829 di = dictitem_alloc(key);
830 if (di == NULL)
831 {
832 PyErr_NoMemory();
833 return -1;
834 }
835 di->di_tv.v_lock = 0;
836
837 if (dict_add(d, di) == FAIL)
838 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200839 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200840 vim_free(di);
841 PyErr_SetVim(_("failed to add key to dictionary"));
842 return -1;
843 }
844 }
845 else
846 clear_tv(&di->di_tv);
847
848 DICTKEY_UNREF
849
850 copy_tv(&tv, &di->di_tv);
851 return 0;
852}
853
854 static PyObject *
Bram Moolenaarb2c5a5a2013-02-14 22:11:39 +0100855DictionaryListKeys(PyObject *self UNUSED)
Bram Moolenaardb913952012-06-29 12:54:53 +0200856{
857 dict_T *dict = ((DictionaryObject *)(self))->dict;
858 long_u todo = dict->dv_hashtab.ht_used;
859 Py_ssize_t i = 0;
860 PyObject *r;
861 hashitem_T *hi;
862
863 r = PyList_New(todo);
864 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
865 {
866 if (!HASHITEM_EMPTY(hi))
867 {
868 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
869 --todo;
870 ++i;
871 }
872 }
873 return r;
874}
875
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200876static PyMappingMethods DictionaryAsMapping = {
877 (lenfunc) DictionaryLength,
878 (binaryfunc) DictionaryItem,
879 (objobjargproc) DictionaryAssItem,
880};
881
Bram Moolenaardb913952012-06-29 12:54:53 +0200882static struct PyMethodDef DictionaryMethods[] = {
883 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
884 { NULL, NULL, 0, NULL }
885};
886
887static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200888static PySequenceMethods ListAsSeq;
889static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200890
891typedef struct
892{
893 PyObject_HEAD
894 list_T *list;
895 pylinkedlist_T ref;
896} ListObject;
897
898 static PyObject *
899ListNew(list_T *list)
900{
901 ListObject *self;
902
903 self = PyObject_NEW(ListObject, &ListType);
904 if (self == NULL)
905 return NULL;
906 self->list = list;
907 ++list->lv_refcount;
908
909 pyll_add((PyObject *)(self), &self->ref, &lastlist);
910
911 return (PyObject *)(self);
912}
913
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200914 static void
915ListDestructor(PyObject *self)
916{
917 ListObject *this = (ListObject *)(self);
918
919 pyll_remove(&this->ref, &lastlist);
920 list_unref(this->list);
921
922 DESTRUCTOR_FINISH(self);
923}
924
Bram Moolenaardb913952012-06-29 12:54:53 +0200925 static int
926list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
927{
928 Py_ssize_t i;
929 Py_ssize_t lsize = PySequence_Size(obj);
930 PyObject *litem;
931 listitem_T *li;
932
933 for(i=0; i<lsize; i++)
934 {
935 li = listitem_alloc();
936 if (li == NULL)
937 {
938 PyErr_NoMemory();
939 return -1;
940 }
941 li->li_tv.v_lock = 0;
942
943 litem = PySequence_GetItem(obj, i);
944 if (litem == NULL)
945 return -1;
946 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
947 return -1;
948
949 list_append(l, li);
950 }
951 return 0;
952}
953
Bram Moolenaardb913952012-06-29 12:54:53 +0200954 static PyInt
955ListLength(PyObject *self)
956{
957 return ((PyInt) (((ListObject *) (self))->list->lv_len));
958}
959
960 static PyObject *
961ListItem(PyObject *self, Py_ssize_t index)
962{
963 listitem_T *li;
964
965 if (index>=ListLength(self))
966 {
Bram Moolenaar8661b172013-05-15 15:44:28 +0200967 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +0200968 return NULL;
969 }
970 li = list_find(((ListObject *) (self))->list, (long) index);
971 if (li == NULL)
972 {
973 PyErr_SetVim(_("internal error: failed to get vim list item"));
974 return NULL;
975 }
976 return ConvertToPyObject(&li->li_tv);
977}
978
979#define PROC_RANGE \
980 if (last < 0) {\
981 if (last < -size) \
982 last = 0; \
983 else \
984 last += size; \
985 } \
986 if (first < 0) \
987 first = 0; \
988 if (first > size) \
989 first = size; \
990 if (last > size) \
991 last = size;
992
993 static PyObject *
994ListSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last)
995{
996 PyInt i;
997 PyInt size = ListLength(self);
998 PyInt n;
999 PyObject *list;
1000 int reversed = 0;
1001
1002 PROC_RANGE
1003 if (first >= last)
1004 first = last;
1005
1006 n = last-first;
1007 list = PyList_New(n);
1008 if (list == NULL)
1009 return NULL;
1010
1011 for (i = 0; i < n; ++i)
1012 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +02001013 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +02001014 if (item == NULL)
1015 {
1016 Py_DECREF(list);
1017 return NULL;
1018 }
1019
1020 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
1021 {
1022 Py_DECREF(item);
1023 Py_DECREF(list);
1024 return NULL;
1025 }
1026 }
1027
1028 return list;
1029}
1030
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001031typedef struct
1032{
1033 listwatch_T lw;
1034 list_T *list;
1035} listiterinfo_T;
1036
1037 static void
1038ListIterDestruct(listiterinfo_T *lii)
1039{
1040 list_rem_watch(lii->list, &lii->lw);
1041 PyMem_Free(lii);
1042}
1043
1044 static PyObject *
1045ListIterNext(listiterinfo_T **lii)
1046{
1047 PyObject *r;
1048
1049 if (!((*lii)->lw.lw_item))
1050 return NULL;
1051
1052 if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
1053 return NULL;
1054
1055 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
1056
1057 return r;
1058}
1059
1060 static PyObject *
1061ListIter(PyObject *self)
1062{
1063 listiterinfo_T *lii;
1064 list_T *l = ((ListObject *) (self))->list;
1065
1066 if (!(lii = PyMem_New(listiterinfo_T, 1)))
1067 {
1068 PyErr_NoMemory();
1069 return NULL;
1070 }
1071
1072 list_add_watch(l, &lii->lw);
1073 lii->lw.lw_item = l->lv_first;
1074 lii->list = l;
1075
1076 return IterNew(lii,
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001077 (destructorfun) ListIterDestruct, (nextfun) ListIterNext,
1078 NULL, NULL);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001079}
1080
Bram Moolenaardb913952012-06-29 12:54:53 +02001081 static int
1082ListAssItem(PyObject *self, Py_ssize_t index, PyObject *obj)
1083{
1084 typval_T tv;
1085 list_T *l = ((ListObject *) (self))->list;
1086 listitem_T *li;
1087 Py_ssize_t length = ListLength(self);
1088
1089 if (l->lv_lock)
1090 {
1091 PyErr_SetVim(_("list is locked"));
1092 return -1;
1093 }
1094 if (index>length || (index==length && obj==NULL))
1095 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001096 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001097 return -1;
1098 }
1099
1100 if (obj == NULL)
1101 {
1102 li = list_find(l, (long) index);
1103 list_remove(l, li, li);
1104 clear_tv(&li->li_tv);
1105 vim_free(li);
1106 return 0;
1107 }
1108
1109 if (ConvertFromPyObject(obj, &tv) == -1)
1110 return -1;
1111
1112 if (index == length)
1113 {
1114 if (list_append_tv(l, &tv) == FAIL)
1115 {
1116 PyErr_SetVim(_("Failed to add item to list"));
1117 return -1;
1118 }
1119 }
1120 else
1121 {
1122 li = list_find(l, (long) index);
1123 clear_tv(&li->li_tv);
1124 copy_tv(&tv, &li->li_tv);
1125 }
1126 return 0;
1127}
1128
1129 static int
1130ListAssSlice(PyObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
1131{
1132 PyInt size = ListLength(self);
1133 Py_ssize_t i;
1134 Py_ssize_t lsize;
1135 PyObject *litem;
1136 listitem_T *li;
1137 listitem_T *next;
1138 typval_T v;
1139 list_T *l = ((ListObject *) (self))->list;
1140
1141 if (l->lv_lock)
1142 {
1143 PyErr_SetVim(_("list is locked"));
1144 return -1;
1145 }
1146
1147 PROC_RANGE
1148
1149 if (first == size)
1150 li = NULL;
1151 else
1152 {
1153 li = list_find(l, (long) first);
1154 if (li == NULL)
1155 {
1156 PyErr_SetVim(_("internal error: no vim list item"));
1157 return -1;
1158 }
1159 if (last > first)
1160 {
1161 i = last - first;
1162 while (i-- && li != NULL)
1163 {
1164 next = li->li_next;
1165 listitem_remove(l, li);
1166 li = next;
1167 }
1168 }
1169 }
1170
1171 if (obj == NULL)
1172 return 0;
1173
1174 if (!PyList_Check(obj))
1175 {
1176 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1177 return -1;
1178 }
1179
1180 lsize = PyList_Size(obj);
1181
1182 for(i=0; i<lsize; i++)
1183 {
1184 litem = PyList_GetItem(obj, i);
1185 if (litem == NULL)
1186 return -1;
1187 if (ConvertFromPyObject(litem, &v) == -1)
1188 return -1;
1189 if (list_insert_tv(l, &v, li) == FAIL)
1190 {
1191 PyErr_SetVim(_("internal error: failed to add item to list"));
1192 return -1;
1193 }
1194 }
1195 return 0;
1196}
1197
1198 static PyObject *
1199ListConcatInPlace(PyObject *self, PyObject *obj)
1200{
1201 list_T *l = ((ListObject *) (self))->list;
1202 PyObject *lookup_dict;
1203
1204 if (l->lv_lock)
1205 {
1206 PyErr_SetVim(_("list is locked"));
1207 return NULL;
1208 }
1209
1210 if (!PySequence_Check(obj))
1211 {
1212 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1213 return NULL;
1214 }
1215
1216 lookup_dict = PyDict_New();
1217 if (list_py_concat(l, obj, lookup_dict) == -1)
1218 {
1219 Py_DECREF(lookup_dict);
1220 return NULL;
1221 }
1222 Py_DECREF(lookup_dict);
1223
1224 Py_INCREF(self);
1225 return self;
1226}
1227
Bram Moolenaar66b79852012-09-21 14:00:35 +02001228 static int
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001229ListSetattr(PyObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001230{
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001231 ListObject *this = (ListObject *)(self);
1232
Bram Moolenaar66b79852012-09-21 14:00:35 +02001233 if (val == NULL)
1234 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001235 PyErr_SetString(PyExc_AttributeError,
1236 _("cannot delete vim.dictionary attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001237 return -1;
1238 }
1239
1240 if (strcmp(name, "locked") == 0)
1241 {
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001242 if (this->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001243 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001244 PyErr_SetString(PyExc_TypeError, _("cannot modify fixed list"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001245 return -1;
1246 }
1247 else
1248 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02001249 int istrue = PyObject_IsTrue(val);
1250 if (istrue == -1)
1251 return -1;
1252 else if (istrue)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001253 this->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001254 else
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001255 this->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001256 }
1257 return 0;
1258 }
1259 else
1260 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001261 PyErr_SetString(PyExc_AttributeError, _("cannot set this attribute"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001262 return -1;
1263 }
1264}
1265
Bram Moolenaardb913952012-06-29 12:54:53 +02001266static struct PyMethodDef ListMethods[] = {
1267 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1268 { NULL, NULL, 0, NULL }
1269};
1270
1271typedef struct
1272{
1273 PyObject_HEAD
1274 char_u *name;
1275} FunctionObject;
1276
1277static PyTypeObject FunctionType;
1278
1279 static PyObject *
1280FunctionNew(char_u *name)
1281{
1282 FunctionObject *self;
1283
1284 self = PyObject_NEW(FunctionObject, &FunctionType);
1285 if (self == NULL)
1286 return NULL;
1287 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1288 if (self->name == NULL)
1289 {
1290 PyErr_NoMemory();
1291 return NULL;
1292 }
1293 STRCPY(self->name, name);
1294 func_ref(name);
1295 return (PyObject *)(self);
1296}
1297
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001298 static void
1299FunctionDestructor(PyObject *self)
1300{
1301 FunctionObject *this = (FunctionObject *) (self);
1302
1303 func_unref(this->name);
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02001304 PyMem_Free(this->name);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001305
1306 DESTRUCTOR_FINISH(self);
1307}
1308
Bram Moolenaardb913952012-06-29 12:54:53 +02001309 static PyObject *
1310FunctionCall(PyObject *self, PyObject *argsObject, PyObject *kwargs)
1311{
1312 FunctionObject *this = (FunctionObject *)(self);
1313 char_u *name = this->name;
1314 typval_T args;
1315 typval_T selfdicttv;
1316 typval_T rettv;
1317 dict_T *selfdict = NULL;
1318 PyObject *selfdictObject;
1319 PyObject *result;
1320 int error;
1321
1322 if (ConvertFromPyObject(argsObject, &args) == -1)
1323 return NULL;
1324
1325 if (kwargs != NULL)
1326 {
1327 selfdictObject = PyDict_GetItemString(kwargs, "self");
1328 if (selfdictObject != NULL)
1329 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001330 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001331 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001332 PyErr_SetString(PyExc_TypeError,
1333 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001334 clear_tv(&args);
1335 return NULL;
1336 }
1337 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1338 return NULL;
1339 selfdict = selfdicttv.vval.v_dict;
1340 }
1341 }
1342
Bram Moolenaar71700b82013-05-15 17:49:05 +02001343 Py_BEGIN_ALLOW_THREADS
1344 Python_Lock_Vim();
1345
Bram Moolenaardb913952012-06-29 12:54:53 +02001346 error = func_call(name, &args, selfdict, &rettv);
Bram Moolenaar71700b82013-05-15 17:49:05 +02001347
1348 Python_Release_Vim();
1349 Py_END_ALLOW_THREADS
1350
Bram Moolenaardb913952012-06-29 12:54:53 +02001351 if (error != OK)
1352 {
1353 result = NULL;
1354 PyErr_SetVim(_("failed to run function"));
1355 }
1356 else
1357 result = ConvertToPyObject(&rettv);
1358
1359 /* FIXME Check what should really be cleared. */
1360 clear_tv(&args);
1361 clear_tv(&rettv);
1362 /*
1363 * if (selfdict!=NULL)
1364 * clear_tv(selfdicttv);
1365 */
1366
1367 return result;
1368}
1369
1370static struct PyMethodDef FunctionMethods[] = {
1371 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1372 { NULL, NULL, 0, NULL }
1373};
1374
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001375/*
1376 * Options object
1377 */
1378
1379static PyTypeObject OptionsType;
1380
1381typedef int (*checkfun)(void *);
1382
1383typedef struct
1384{
1385 PyObject_HEAD
1386 int opt_type;
1387 void *from;
1388 checkfun Check;
1389 PyObject *fromObj;
1390} OptionsObject;
1391
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001392 static int
1393dummy_check(void *arg UNUSED)
1394{
1395 return 0;
1396}
1397
1398 static PyObject *
1399OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1400{
1401 OptionsObject *self;
1402
1403 self = PyObject_NEW(OptionsObject, &OptionsType);
1404 if (self == NULL)
1405 return NULL;
1406
1407 self->opt_type = opt_type;
1408 self->from = from;
1409 self->Check = Check;
1410 self->fromObj = fromObj;
1411 if (fromObj)
1412 Py_INCREF(fromObj);
1413
1414 return (PyObject *)(self);
1415}
1416
1417 static void
1418OptionsDestructor(PyObject *self)
1419{
1420 if (((OptionsObject *)(self))->fromObj)
1421 Py_DECREF(((OptionsObject *)(self))->fromObj);
1422 DESTRUCTOR_FINISH(self);
1423}
1424
1425 static int
1426OptionsTraverse(PyObject *self, visitproc visit, void *arg)
1427{
1428 Py_VISIT(((OptionsObject *)(self))->fromObj);
1429 return 0;
1430}
1431
1432 static int
1433OptionsClear(PyObject *self)
1434{
1435 Py_CLEAR(((OptionsObject *)(self))->fromObj);
1436 return 0;
1437}
1438
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001439 static PyObject *
1440OptionsItem(OptionsObject *this, PyObject *keyObject)
1441{
1442 char_u *key;
1443 int flags;
1444 long numval;
1445 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001446 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001447
1448 if (this->Check(this->from))
1449 return NULL;
1450
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001451 DICTKEY_GET_NOTEMPTY(NULL)
1452
1453 flags = get_option_value_strict(key, &numval, &stringval,
1454 this->opt_type, this->from);
1455
1456 DICTKEY_UNREF
1457
1458 if (flags == 0)
1459 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001460 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001461 return NULL;
1462 }
1463
1464 if (flags & SOPT_UNSET)
1465 {
1466 Py_INCREF(Py_None);
1467 return Py_None;
1468 }
1469 else if (flags & SOPT_BOOL)
1470 {
1471 PyObject *r;
1472 r = numval ? Py_True : Py_False;
1473 Py_INCREF(r);
1474 return r;
1475 }
1476 else if (flags & SOPT_NUM)
1477 return PyInt_FromLong(numval);
1478 else if (flags & SOPT_STRING)
1479 {
1480 if (stringval)
1481 return PyBytes_FromString((char *) stringval);
1482 else
1483 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001484 PyErr_SetString(PyExc_RuntimeError,
1485 _("unable to get option value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001486 return NULL;
1487 }
1488 }
1489 else
1490 {
1491 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1492 return NULL;
1493 }
1494}
1495
1496 static int
1497set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1498 char_u *key;
1499 int numval;
1500 char_u *stringval;
1501 int opt_flags;
1502 int opt_type;
1503 void *from;
1504{
1505 win_T *save_curwin;
1506 tabpage_T *save_curtab;
Bram Moolenaar105bc352013-05-17 16:03:57 +02001507 buf_T *save_curbuf;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001508 int r = 0;
1509
1510 switch (opt_type)
1511 {
1512 case SREQ_WIN:
Bram Moolenaar105bc352013-05-17 16:03:57 +02001513 if (switch_win(&save_curwin, &save_curtab, (win_T *)from,
1514 win_find_tabpage((win_T *)from)) == FAIL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001515 {
1516 PyErr_SetVim("Problem while switching windows.");
1517 return -1;
1518 }
1519 set_option_value(key, numval, stringval, opt_flags);
1520 restore_win(save_curwin, save_curtab);
1521 break;
1522 case SREQ_BUF:
Bram Moolenaar105bc352013-05-17 16:03:57 +02001523 switch_buffer(&save_curbuf, (buf_T *)from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001524 set_option_value(key, numval, stringval, opt_flags);
Bram Moolenaar105bc352013-05-17 16:03:57 +02001525 restore_buffer(save_curbuf);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001526 break;
1527 case SREQ_GLOBAL:
1528 set_option_value(key, numval, stringval, opt_flags);
1529 break;
1530 }
1531 return r;
1532}
1533
1534 static int
1535OptionsAssItem(OptionsObject *this, PyObject *keyObject, PyObject *valObject)
1536{
1537 char_u *key;
1538 int flags;
1539 int opt_flags;
1540 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001541 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001542
1543 if (this->Check(this->from))
1544 return -1;
1545
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001546 DICTKEY_GET_NOTEMPTY(-1)
1547
1548 flags = get_option_value_strict(key, NULL, NULL,
1549 this->opt_type, this->from);
1550
1551 DICTKEY_UNREF
1552
1553 if (flags == 0)
1554 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001555 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001556 return -1;
1557 }
1558
1559 if (valObject == NULL)
1560 {
1561 if (this->opt_type == SREQ_GLOBAL)
1562 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001563 PyErr_SetString(PyExc_ValueError,
1564 _("unable to unset global option"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001565 return -1;
1566 }
1567 else if (!(flags & SOPT_GLOBAL))
1568 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001569 PyErr_SetString(PyExc_ValueError, _("unable to unset option "
1570 "without global value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001571 return -1;
1572 }
1573 else
1574 {
1575 unset_global_local_option(key, this->from);
1576 return 0;
1577 }
1578 }
1579
1580 opt_flags = (this->opt_type ? OPT_LOCAL : OPT_GLOBAL);
1581
1582 if (flags & SOPT_BOOL)
1583 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02001584 int istrue = PyObject_IsTrue(valObject);
1585 if (istrue == -1)
1586 return -1;
1587 r = set_option_value_for(key, istrue, NULL,
Bram Moolenaar03db85b2013-05-15 14:51:35 +02001588 opt_flags, this->opt_type, this->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001589 }
1590 else if (flags & SOPT_NUM)
1591 {
1592 int val;
1593
1594#if PY_MAJOR_VERSION < 3
1595 if (PyInt_Check(valObject))
1596 val = PyInt_AsLong(valObject);
1597 else
1598#endif
1599 if (PyLong_Check(valObject))
1600 val = PyLong_AsLong(valObject);
1601 else
1602 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001603 PyErr_SetString(PyExc_TypeError, _("object must be integer"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001604 return -1;
1605 }
1606
1607 r = set_option_value_for(key, val, NULL, opt_flags,
1608 this->opt_type, this->from);
1609 }
1610 else
1611 {
1612 char_u *val;
1613 if (PyBytes_Check(valObject))
1614 {
1615
1616 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1617 return -1;
1618 if (val == NULL)
1619 return -1;
1620
1621 val = vim_strsave(val);
1622 }
1623 else if (PyUnicode_Check(valObject))
1624 {
1625 PyObject *bytes;
1626
1627 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1628 if (bytes == NULL)
1629 return -1;
1630
1631 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1632 return -1;
1633 if (val == NULL)
1634 return -1;
1635
1636 val = vim_strsave(val);
1637 Py_XDECREF(bytes);
1638 }
1639 else
1640 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001641 PyErr_SetString(PyExc_TypeError, _("object must be string"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001642 return -1;
1643 }
1644
1645 r = set_option_value_for(key, 0, val, opt_flags,
1646 this->opt_type, this->from);
1647 vim_free(val);
1648 }
1649
1650 return r;
1651}
1652
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001653static PyMappingMethods OptionsAsMapping = {
1654 (lenfunc) NULL,
1655 (binaryfunc) OptionsItem,
1656 (objobjargproc) OptionsAssItem,
1657};
1658
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001659/* Tabpage object
1660 */
1661
1662typedef struct
1663{
1664 PyObject_HEAD
1665 tabpage_T *tab;
1666} TabPageObject;
1667
1668static PyObject *WinListNew(TabPageObject *tabObject);
1669
1670static PyTypeObject TabPageType;
1671
1672 static int
1673CheckTabPage(TabPageObject *this)
1674{
1675 if (this->tab == INVALID_TABPAGE_VALUE)
1676 {
1677 PyErr_SetVim(_("attempt to refer to deleted tab page"));
1678 return -1;
1679 }
1680
1681 return 0;
1682}
1683
1684 static PyObject *
1685TabPageNew(tabpage_T *tab)
1686{
1687 TabPageObject *self;
1688
1689 if (TAB_PYTHON_REF(tab))
1690 {
1691 self = TAB_PYTHON_REF(tab);
1692 Py_INCREF(self);
1693 }
1694 else
1695 {
1696 self = PyObject_NEW(TabPageObject, &TabPageType);
1697 if (self == NULL)
1698 return NULL;
1699 self->tab = tab;
1700 TAB_PYTHON_REF(tab) = self;
1701 }
1702
1703 return (PyObject *)(self);
1704}
1705
1706 static void
1707TabPageDestructor(PyObject *self)
1708{
1709 TabPageObject *this = (TabPageObject *)(self);
1710
1711 if (this->tab && this->tab != INVALID_TABPAGE_VALUE)
1712 TAB_PYTHON_REF(this->tab) = NULL;
1713
1714 DESTRUCTOR_FINISH(self);
1715}
1716
1717 static PyObject *
1718TabPageAttr(TabPageObject *this, char *name)
1719{
1720 if (strcmp(name, "windows") == 0)
1721 return WinListNew(this);
1722 else if (strcmp(name, "number") == 0)
1723 return PyLong_FromLong((long) get_tab_number(this->tab));
1724 else if (strcmp(name, "vars") == 0)
1725 return DictionaryNew(this->tab->tp_vars);
1726 else if (strcmp(name, "window") == 0)
1727 {
1728 /* For current tab window.c does not bother to set or update tp_curwin
1729 */
1730 if (this->tab == curtab)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001731 return WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001732 else
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001733 return WindowNew(this->tab->tp_curwin, this->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001734 }
1735 return NULL;
1736}
1737
1738 static PyObject *
1739TabPageRepr(PyObject *self)
1740{
1741 static char repr[100];
1742 TabPageObject *this = (TabPageObject *)(self);
1743
1744 if (this->tab == INVALID_TABPAGE_VALUE)
1745 {
1746 vim_snprintf(repr, 100, _("<tabpage object (deleted) at %p>"), (self));
1747 return PyString_FromString(repr);
1748 }
1749 else
1750 {
1751 int t = get_tab_number(this->tab);
1752
1753 if (t == 0)
1754 vim_snprintf(repr, 100, _("<tabpage object (unknown) at %p>"),
1755 (self));
1756 else
1757 vim_snprintf(repr, 100, _("<tabpage %d>"), t - 1);
1758
1759 return PyString_FromString(repr);
1760 }
1761}
1762
1763static struct PyMethodDef TabPageMethods[] = {
1764 /* name, function, calling, documentation */
1765 { NULL, NULL, 0, NULL }
1766};
1767
1768/*
1769 * Window list object
1770 */
1771
1772static PyTypeObject TabListType;
1773static PySequenceMethods TabListAsSeq;
1774
1775typedef struct
1776{
1777 PyObject_HEAD
1778} TabListObject;
1779
1780 static PyInt
1781TabListLength(PyObject *self UNUSED)
1782{
1783 tabpage_T *tp = first_tabpage;
1784 PyInt n = 0;
1785
1786 while (tp != NULL)
1787 {
1788 ++n;
1789 tp = tp->tp_next;
1790 }
1791
1792 return n;
1793}
1794
1795 static PyObject *
1796TabListItem(PyObject *self UNUSED, PyInt n)
1797{
1798 tabpage_T *tp;
1799
1800 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, --n)
1801 if (n == 0)
1802 return TabPageNew(tp);
1803
1804 PyErr_SetString(PyExc_IndexError, _("no such tab page"));
1805 return NULL;
1806}
1807
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001808/* Window object
1809 */
1810
1811typedef struct
1812{
1813 PyObject_HEAD
1814 win_T *win;
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001815 TabPageObject *tabObject;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001816} WindowObject;
1817
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001818static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001819
1820 static int
1821CheckWindow(WindowObject *this)
1822{
1823 if (this->win == INVALID_WINDOW_VALUE)
1824 {
1825 PyErr_SetVim(_("attempt to refer to deleted window"));
1826 return -1;
1827 }
1828
1829 return 0;
1830}
1831
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001832 static PyObject *
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001833WindowNew(win_T *win, tabpage_T *tab)
Bram Moolenaar971db462013-05-12 18:44:48 +02001834{
1835 /* We need to handle deletion of windows underneath us.
1836 * If we add a "w_python*_ref" field to the win_T structure,
1837 * then we can get at it in win_free() in vim. We then
1838 * need to create only ONE Python object per window - if
1839 * we try to create a second, just INCREF the existing one
1840 * and return it. The (single) Python object referring to
1841 * the window is stored in "w_python*_ref".
1842 * On a win_free() we set the Python object's win_T* field
1843 * to an invalid value. We trap all uses of a window
1844 * object, and reject them if the win_T* field is invalid.
1845 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001846 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001847 * w_python_ref and w_python3_ref fields respectively.
1848 */
1849
1850 WindowObject *self;
1851
1852 if (WIN_PYTHON_REF(win))
1853 {
1854 self = WIN_PYTHON_REF(win);
1855 Py_INCREF(self);
1856 }
1857 else
1858 {
1859 self = PyObject_NEW(WindowObject, &WindowType);
1860 if (self == NULL)
1861 return NULL;
1862 self->win = win;
1863 WIN_PYTHON_REF(win) = self;
1864 }
1865
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001866 self->tabObject = ((TabPageObject *)(TabPageNew(tab)));
1867
Bram Moolenaar971db462013-05-12 18:44:48 +02001868 return (PyObject *)(self);
1869}
1870
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001871 static void
1872WindowDestructor(PyObject *self)
1873{
1874 WindowObject *this = (WindowObject *)(self);
1875
1876 if (this->win && this->win != INVALID_WINDOW_VALUE)
1877 WIN_PYTHON_REF(this->win) = NULL;
1878
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001879 Py_DECREF(((PyObject *)(this->tabObject)));
1880
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001881 DESTRUCTOR_FINISH(self);
1882}
1883
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001884 static win_T *
1885get_firstwin(TabPageObject *tabObject)
1886{
1887 if (tabObject)
1888 {
1889 if (CheckTabPage(tabObject))
1890 return NULL;
1891 /* For current tab window.c does not bother to set or update tp_firstwin
1892 */
1893 else if (tabObject->tab == curtab)
1894 return firstwin;
1895 else
1896 return tabObject->tab->tp_firstwin;
1897 }
1898 else
1899 return firstwin;
1900}
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001901 static int
1902WindowTraverse(PyObject *self, visitproc visit, void *arg)
1903{
1904 Py_VISIT(((PyObject *)(((WindowObject *)(self))->tabObject)));
1905 return 0;
1906}
1907
1908 static int
1909WindowClear(PyObject *self)
1910{
1911 Py_CLEAR((((WindowObject *)(self))->tabObject));
1912 return 0;
1913}
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001914
Bram Moolenaar971db462013-05-12 18:44:48 +02001915 static PyObject *
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001916WindowAttr(WindowObject *this, char *name)
1917{
1918 if (strcmp(name, "buffer") == 0)
1919 return (PyObject *)BufferNew(this->win->w_buffer);
1920 else if (strcmp(name, "cursor") == 0)
1921 {
1922 pos_T *pos = &this->win->w_cursor;
1923
1924 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1925 }
1926 else if (strcmp(name, "height") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001927 return PyLong_FromLong((long)(this->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001928#ifdef FEAT_WINDOWS
1929 else if (strcmp(name, "row") == 0)
1930 return PyLong_FromLong((long)(this->win->w_winrow));
1931#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001932#ifdef FEAT_VERTSPLIT
1933 else if (strcmp(name, "width") == 0)
Bram Moolenaar99add412013-05-12 19:09:51 +02001934 return PyLong_FromLong((long)(W_WIDTH(this->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001935 else if (strcmp(name, "col") == 0)
1936 return PyLong_FromLong((long)(W_WINCOL(this->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001937#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001938 else if (strcmp(name, "vars") == 0)
1939 return DictionaryNew(this->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001940 else if (strcmp(name, "options") == 0)
1941 return OptionsNew(SREQ_WIN, this->win, (checkfun) CheckWindow,
1942 (PyObject *) this);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001943 else if (strcmp(name, "number") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001944 {
1945 if (CheckTabPage(this->tabObject))
1946 return NULL;
1947 return PyLong_FromLong((long)
1948 get_win_number(this->win, get_firstwin(this->tabObject)));
1949 }
1950 else if (strcmp(name, "tabpage") == 0)
1951 {
1952 Py_INCREF(this->tabObject);
1953 return (PyObject *)(this->tabObject);
1954 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001955 else if (strcmp(name,"__members__") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001956 return Py_BuildValue("[sssssssss]", "buffer", "cursor", "height",
1957 "vars", "options", "number", "row", "col", "tabpage");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001958 else
1959 return NULL;
1960}
1961
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001962 static int
1963WindowSetattr(PyObject *self, char *name, PyObject *val)
1964{
1965 WindowObject *this = (WindowObject *)(self);
1966
1967 if (CheckWindow(this))
1968 return -1;
1969
1970 if (strcmp(name, "buffer") == 0)
1971 {
1972 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1973 return -1;
1974 }
1975 else if (strcmp(name, "cursor") == 0)
1976 {
1977 long lnum;
1978 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001979
1980 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1981 return -1;
1982
1983 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
1984 {
1985 PyErr_SetVim(_("cursor position outside buffer"));
1986 return -1;
1987 }
1988
1989 /* Check for keyboard interrupts */
1990 if (VimErrorCheck())
1991 return -1;
1992
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001993 this->win->w_cursor.lnum = lnum;
1994 this->win->w_cursor.col = col;
1995#ifdef FEAT_VIRTUALEDIT
1996 this->win->w_cursor.coladd = 0;
1997#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02001998 /* When column is out of range silently correct it. */
1999 check_cursor_col_win(this->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002000
Bram Moolenaar03a807a2011-07-07 15:08:58 +02002001 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002002 return 0;
2003 }
2004 else if (strcmp(name, "height") == 0)
2005 {
2006 int height;
2007 win_T *savewin;
2008
2009 if (!PyArg_Parse(val, "i", &height))
2010 return -1;
2011
2012#ifdef FEAT_GUI
2013 need_mouse_correct = TRUE;
2014#endif
2015 savewin = curwin;
2016 curwin = this->win;
2017 win_setheight(height);
2018 curwin = savewin;
2019
2020 /* Check for keyboard interrupts */
2021 if (VimErrorCheck())
2022 return -1;
2023
2024 return 0;
2025 }
2026#ifdef FEAT_VERTSPLIT
2027 else if (strcmp(name, "width") == 0)
2028 {
2029 int width;
2030 win_T *savewin;
2031
2032 if (!PyArg_Parse(val, "i", &width))
2033 return -1;
2034
2035#ifdef FEAT_GUI
2036 need_mouse_correct = TRUE;
2037#endif
2038 savewin = curwin;
2039 curwin = this->win;
2040 win_setwidth(width);
2041 curwin = savewin;
2042
2043 /* Check for keyboard interrupts */
2044 if (VimErrorCheck())
2045 return -1;
2046
2047 return 0;
2048 }
2049#endif
2050 else
2051 {
2052 PyErr_SetString(PyExc_AttributeError, name);
2053 return -1;
2054 }
2055}
2056
2057 static PyObject *
2058WindowRepr(PyObject *self)
2059{
2060 static char repr[100];
2061 WindowObject *this = (WindowObject *)(self);
2062
2063 if (this->win == INVALID_WINDOW_VALUE)
2064 {
2065 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
2066 return PyString_FromString(repr);
2067 }
2068 else
2069 {
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002070 int w = get_win_number(this->win, firstwin);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002071
Bram Moolenaar6d216452013-05-12 19:00:41 +02002072 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002073 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2074 (self));
2075 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02002076 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002077
2078 return PyString_FromString(repr);
2079 }
2080}
2081
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002082static struct PyMethodDef WindowMethods[] = {
2083 /* name, function, calling, documentation */
2084 { NULL, NULL, 0, NULL }
2085};
2086
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002087/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002088 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002089 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002090
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002091static PyTypeObject WinListType;
2092static PySequenceMethods WinListAsSeq;
2093
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002094typedef struct
2095{
2096 PyObject_HEAD
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002097 TabPageObject *tabObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002098} WinListObject;
2099
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002100 static PyObject *
2101WinListNew(TabPageObject *tabObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002102{
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002103 WinListObject *self;
2104
2105 self = PyObject_NEW(WinListObject, &WinListType);
2106 self->tabObject = tabObject;
2107 Py_INCREF(tabObject);
2108
2109 return (PyObject *)(self);
2110}
2111
2112 static void
2113WinListDestructor(PyObject *self)
2114{
2115 TabPageObject *tabObject = ((WinListObject *)(self))->tabObject;
2116
2117 if (tabObject)
2118 Py_DECREF((PyObject *)(tabObject));
2119
2120 DESTRUCTOR_FINISH(self);
2121}
2122
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002123 static PyInt
2124WinListLength(PyObject *self)
2125{
2126 win_T *w;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002127 PyInt n = 0;
2128
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02002129 if (!(w = get_firstwin(((WinListObject *)(self))->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002130 return -1;
2131
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002132 while (w != NULL)
2133 {
2134 ++n;
2135 w = W_NEXT(w);
2136 }
2137
2138 return n;
2139}
2140
2141 static PyObject *
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002142WinListItem(PyObject *self, PyInt n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002143{
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02002144 WinListObject *this = ((WinListObject *)(self));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002145 win_T *w;
2146
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02002147 if (!(w = get_firstwin(this->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002148 return NULL;
2149
2150 for (; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002151 if (n == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02002152 return WindowNew(w, this->tabObject? this->tabObject->tab: curtab);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002153
2154 PyErr_SetString(PyExc_IndexError, _("no such window"));
2155 return NULL;
2156}
2157
2158/* Convert a Python string into a Vim line.
2159 *
2160 * The result is in allocated memory. All internal nulls are replaced by
2161 * newline characters. It is an error for the string to contain newline
2162 * characters.
2163 *
2164 * On errors, the Python exception data is set, and NULL is returned.
2165 */
2166 static char *
2167StringToLine(PyObject *obj)
2168{
2169 const char *str;
2170 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002171 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002172 PyInt len;
2173 PyInt i;
2174 char *p;
2175
2176 if (obj == NULL || !PyString_Check(obj))
2177 {
2178 PyErr_BadArgument();
2179 return NULL;
2180 }
2181
Bram Moolenaar19e60942011-06-19 00:27:51 +02002182 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
2183 str = PyString_AsString(bytes);
2184 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002185
2186 /*
2187 * Error checking: String must not contain newlines, as we
2188 * are replacing a single line, and we must replace it with
2189 * a single line.
2190 * A trailing newline is removed, so that append(f.readlines()) works.
2191 */
2192 p = memchr(str, '\n', len);
2193 if (p != NULL)
2194 {
2195 if (p == str + len - 1)
2196 --len;
2197 else
2198 {
2199 PyErr_SetVim(_("string cannot contain newlines"));
2200 return NULL;
2201 }
2202 }
2203
2204 /* Create a copy of the string, with internal nulls replaced by
2205 * newline characters, as is the vim convention.
2206 */
2207 save = (char *)alloc((unsigned)(len+1));
2208 if (save == NULL)
2209 {
2210 PyErr_NoMemory();
2211 return NULL;
2212 }
2213
2214 for (i = 0; i < len; ++i)
2215 {
2216 if (str[i] == '\0')
2217 save[i] = '\n';
2218 else
2219 save[i] = str[i];
2220 }
2221
2222 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02002223 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002224
2225 return save;
2226}
2227
2228/* Get a line from the specified buffer. The line number is
2229 * in Vim format (1-based). The line is returned as a Python
2230 * string object.
2231 */
2232 static PyObject *
2233GetBufferLine(buf_T *buf, PyInt n)
2234{
2235 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2236}
2237
2238
2239/* Get a list of lines from the specified buffer. The line numbers
2240 * are in Vim format (1-based). The range is from lo up to, but not
2241 * including, hi. The list is returned as a Python list of string objects.
2242 */
2243 static PyObject *
2244GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2245{
2246 PyInt i;
2247 PyInt n = hi - lo;
2248 PyObject *list = PyList_New(n);
2249
2250 if (list == NULL)
2251 return NULL;
2252
2253 for (i = 0; i < n; ++i)
2254 {
2255 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2256
2257 /* Error check - was the Python string creation OK? */
2258 if (str == NULL)
2259 {
2260 Py_DECREF(list);
2261 return NULL;
2262 }
2263
2264 /* Set the list item */
2265 if (PyList_SetItem(list, i, str))
2266 {
2267 Py_DECREF(str);
2268 Py_DECREF(list);
2269 return NULL;
2270 }
2271 }
2272
2273 /* The ownership of the Python list is passed to the caller (ie,
2274 * the caller should Py_DECREF() the object when it is finished
2275 * with it).
2276 */
2277
2278 return list;
2279}
2280
2281/*
2282 * Check if deleting lines made the cursor position invalid.
2283 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2284 * deleted).
2285 */
2286 static void
2287py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2288{
2289 if (curwin->w_cursor.lnum >= lo)
2290 {
2291 /* Adjust the cursor position if it's in/after the changed
2292 * lines. */
2293 if (curwin->w_cursor.lnum >= hi)
2294 {
2295 curwin->w_cursor.lnum += extra;
2296 check_cursor_col();
2297 }
2298 else if (extra < 0)
2299 {
2300 curwin->w_cursor.lnum = lo;
2301 check_cursor();
2302 }
2303 else
2304 check_cursor_col();
2305 changed_cline_bef_curs();
2306 }
2307 invalidate_botline();
2308}
2309
Bram Moolenaar19e60942011-06-19 00:27:51 +02002310/*
2311 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002312 * in Vim format (1-based). The replacement line is given as
2313 * a Python string object. The object is checked for validity
2314 * and correct format. Errors are returned as a value of FAIL.
2315 * The return value is OK on success.
2316 * If OK is returned and len_change is not NULL, *len_change
2317 * is set to the change in the buffer length.
2318 */
2319 static int
2320SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2321{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002322 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002323 * There are three cases:
2324 * 1. NULL, or None - this is a deletion.
2325 * 2. A string - this is a replacement.
2326 * 3. Anything else - this is an error.
2327 */
2328 if (line == Py_None || line == NULL)
2329 {
Bram Moolenaar105bc352013-05-17 16:03:57 +02002330 buf_T *savebuf;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002331
2332 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002333 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002334
2335 if (u_savedel((linenr_T)n, 1L) == FAIL)
2336 PyErr_SetVim(_("cannot save undo information"));
2337 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2338 PyErr_SetVim(_("cannot delete line"));
2339 else
2340 {
Bram Moolenaar105bc352013-05-17 16:03:57 +02002341 if (buf == savebuf)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002342 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2343 deleted_lines_mark((linenr_T)n, 1L);
2344 }
2345
Bram Moolenaar105bc352013-05-17 16:03:57 +02002346 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002347
2348 if (PyErr_Occurred() || VimErrorCheck())
2349 return FAIL;
2350
2351 if (len_change)
2352 *len_change = -1;
2353
2354 return OK;
2355 }
2356 else if (PyString_Check(line))
2357 {
2358 char *save = StringToLine(line);
Bram Moolenaar105bc352013-05-17 16:03:57 +02002359 buf_T *savebuf;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002360
2361 if (save == NULL)
2362 return FAIL;
2363
2364 /* We do not need to free "save" if ml_replace() consumes it. */
2365 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002366 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002367
2368 if (u_savesub((linenr_T)n) == FAIL)
2369 {
2370 PyErr_SetVim(_("cannot save undo information"));
2371 vim_free(save);
2372 }
2373 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2374 {
2375 PyErr_SetVim(_("cannot replace line"));
2376 vim_free(save);
2377 }
2378 else
2379 changed_bytes((linenr_T)n, 0);
2380
Bram Moolenaar105bc352013-05-17 16:03:57 +02002381 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002382
2383 /* Check that the cursor is not beyond the end of the line now. */
Bram Moolenaar105bc352013-05-17 16:03:57 +02002384 if (buf == savebuf)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002385 check_cursor_col();
2386
2387 if (PyErr_Occurred() || VimErrorCheck())
2388 return FAIL;
2389
2390 if (len_change)
2391 *len_change = 0;
2392
2393 return OK;
2394 }
2395 else
2396 {
2397 PyErr_BadArgument();
2398 return FAIL;
2399 }
2400}
2401
Bram Moolenaar19e60942011-06-19 00:27:51 +02002402/* Replace a range of lines in the specified buffer. The line numbers are in
2403 * Vim format (1-based). The range is from lo up to, but not including, hi.
2404 * The replacement lines are given as a Python list of string objects. The
2405 * list is checked for validity and correct format. Errors are returned as a
2406 * value of FAIL. The return value is OK on success.
2407 * If OK is returned and len_change is not NULL, *len_change
2408 * is set to the change in the buffer length.
2409 */
2410 static int
2411SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2412{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002413 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002414 * There are three cases:
2415 * 1. NULL, or None - this is a deletion.
2416 * 2. A list - this is a replacement.
2417 * 3. Anything else - this is an error.
2418 */
2419 if (list == Py_None || list == NULL)
2420 {
2421 PyInt i;
2422 PyInt n = (int)(hi - lo);
Bram Moolenaar105bc352013-05-17 16:03:57 +02002423 buf_T *savebuf;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002424
2425 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002426 switch_buffer(&savebuf, buf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002427
2428 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2429 PyErr_SetVim(_("cannot save undo information"));
2430 else
2431 {
2432 for (i = 0; i < n; ++i)
2433 {
2434 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2435 {
2436 PyErr_SetVim(_("cannot delete line"));
2437 break;
2438 }
2439 }
Bram Moolenaar105bc352013-05-17 16:03:57 +02002440 if (buf == savebuf)
Bram Moolenaar19e60942011-06-19 00:27:51 +02002441 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2442 deleted_lines_mark((linenr_T)lo, (long)i);
2443 }
2444
Bram Moolenaar105bc352013-05-17 16:03:57 +02002445 restore_buffer(savebuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002446
2447 if (PyErr_Occurred() || VimErrorCheck())
2448 return FAIL;
2449
2450 if (len_change)
2451 *len_change = -n;
2452
2453 return OK;
2454 }
2455 else if (PyList_Check(list))
2456 {
2457 PyInt i;
2458 PyInt new_len = PyList_Size(list);
2459 PyInt old_len = hi - lo;
2460 PyInt extra = 0; /* lines added to text, can be negative */
2461 char **array;
2462 buf_T *savebuf;
2463
2464 if (new_len == 0) /* avoid allocating zero bytes */
2465 array = NULL;
2466 else
2467 {
2468 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2469 if (array == NULL)
2470 {
2471 PyErr_NoMemory();
2472 return FAIL;
2473 }
2474 }
2475
2476 for (i = 0; i < new_len; ++i)
2477 {
2478 PyObject *line = PyList_GetItem(list, i);
2479
2480 array[i] = StringToLine(line);
2481 if (array[i] == NULL)
2482 {
2483 while (i)
2484 vim_free(array[--i]);
2485 vim_free(array);
2486 return FAIL;
2487 }
2488 }
2489
Bram Moolenaar19e60942011-06-19 00:27:51 +02002490 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002491
2492 // START of region without "return". Must call restore_buffer()!
2493 switch_buffer(&savebuf, buf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002494
2495 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2496 PyErr_SetVim(_("cannot save undo information"));
2497
2498 /* If the size of the range is reducing (ie, new_len < old_len) we
2499 * need to delete some old_len. We do this at the start, by
2500 * repeatedly deleting line "lo".
2501 */
2502 if (!PyErr_Occurred())
2503 {
2504 for (i = 0; i < old_len - new_len; ++i)
2505 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2506 {
2507 PyErr_SetVim(_("cannot delete line"));
2508 break;
2509 }
2510 extra -= i;
2511 }
2512
2513 /* For as long as possible, replace the existing old_len with the
2514 * new old_len. This is a more efficient operation, as it requires
2515 * less memory allocation and freeing.
2516 */
2517 if (!PyErr_Occurred())
2518 {
2519 for (i = 0; i < old_len && i < new_len; ++i)
2520 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2521 == FAIL)
2522 {
2523 PyErr_SetVim(_("cannot replace line"));
2524 break;
2525 }
2526 }
2527 else
2528 i = 0;
2529
2530 /* Now we may need to insert the remaining new old_len. If we do, we
2531 * must free the strings as we finish with them (we can't pass the
2532 * responsibility to vim in this case).
2533 */
2534 if (!PyErr_Occurred())
2535 {
2536 while (i < new_len)
2537 {
2538 if (ml_append((linenr_T)(lo + i - 1),
2539 (char_u *)array[i], 0, FALSE) == FAIL)
2540 {
2541 PyErr_SetVim(_("cannot insert line"));
2542 break;
2543 }
2544 vim_free(array[i]);
2545 ++i;
2546 ++extra;
2547 }
2548 }
2549
2550 /* Free any left-over old_len, as a result of an error */
2551 while (i < new_len)
2552 {
2553 vim_free(array[i]);
2554 ++i;
2555 }
2556
2557 /* Free the array of old_len. All of its contents have now
2558 * been dealt with (either freed, or the responsibility passed
2559 * to vim.
2560 */
2561 vim_free(array);
2562
2563 /* Adjust marks. Invalidate any which lie in the
2564 * changed range, and move any in the remainder of the buffer.
2565 */
2566 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2567 (long)MAXLNUM, (long)extra);
2568 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2569
Bram Moolenaar105bc352013-05-17 16:03:57 +02002570 if (buf == savebuf)
Bram Moolenaar19e60942011-06-19 00:27:51 +02002571 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2572
Bram Moolenaar105bc352013-05-17 16:03:57 +02002573 // END of region without "return".
2574 restore_buffer(savebuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002575
2576 if (PyErr_Occurred() || VimErrorCheck())
2577 return FAIL;
2578
2579 if (len_change)
2580 *len_change = new_len - old_len;
2581
2582 return OK;
2583 }
2584 else
2585 {
2586 PyErr_BadArgument();
2587 return FAIL;
2588 }
2589}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002590
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002591/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002592 * The line number is in Vim format (1-based). The lines to be inserted are
2593 * given as a Python list of string objects or as a single string. The lines
2594 * to be added are checked for validity and correct format. Errors are
2595 * returned as a value of FAIL. The return value is OK on success.
2596 * If OK is returned and len_change is not NULL, *len_change
2597 * is set to the change in the buffer length.
2598 */
2599 static int
2600InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2601{
2602 /* First of all, we check the type of the supplied Python object.
2603 * It must be a string or a list, or the call is in error.
2604 */
2605 if (PyString_Check(lines))
2606 {
2607 char *str = StringToLine(lines);
2608 buf_T *savebuf;
2609
2610 if (str == NULL)
2611 return FAIL;
2612
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002613 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002614 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002615
2616 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2617 PyErr_SetVim(_("cannot save undo information"));
2618 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2619 PyErr_SetVim(_("cannot insert line"));
2620 else
2621 appended_lines_mark((linenr_T)n, 1L);
2622
2623 vim_free(str);
Bram Moolenaar105bc352013-05-17 16:03:57 +02002624 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002625 update_screen(VALID);
2626
2627 if (PyErr_Occurred() || VimErrorCheck())
2628 return FAIL;
2629
2630 if (len_change)
2631 *len_change = 1;
2632
2633 return OK;
2634 }
2635 else if (PyList_Check(lines))
2636 {
2637 PyInt i;
2638 PyInt size = PyList_Size(lines);
2639 char **array;
2640 buf_T *savebuf;
2641
2642 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2643 if (array == NULL)
2644 {
2645 PyErr_NoMemory();
2646 return FAIL;
2647 }
2648
2649 for (i = 0; i < size; ++i)
2650 {
2651 PyObject *line = PyList_GetItem(lines, i);
2652 array[i] = StringToLine(line);
2653
2654 if (array[i] == NULL)
2655 {
2656 while (i)
2657 vim_free(array[--i]);
2658 vim_free(array);
2659 return FAIL;
2660 }
2661 }
2662
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002663 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002664 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002665
2666 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2667 PyErr_SetVim(_("cannot save undo information"));
2668 else
2669 {
2670 for (i = 0; i < size; ++i)
2671 {
2672 if (ml_append((linenr_T)(n + i),
2673 (char_u *)array[i], 0, FALSE) == FAIL)
2674 {
2675 PyErr_SetVim(_("cannot insert line"));
2676
2677 /* Free the rest of the lines */
2678 while (i < size)
2679 vim_free(array[i++]);
2680
2681 break;
2682 }
2683 vim_free(array[i]);
2684 }
2685 if (i > 0)
2686 appended_lines_mark((linenr_T)n, (long)i);
2687 }
2688
2689 /* Free the array of lines. All of its contents have now
2690 * been freed.
2691 */
2692 vim_free(array);
2693
Bram Moolenaar105bc352013-05-17 16:03:57 +02002694 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002695 update_screen(VALID);
2696
2697 if (PyErr_Occurred() || VimErrorCheck())
2698 return FAIL;
2699
2700 if (len_change)
2701 *len_change = size;
2702
2703 return OK;
2704 }
2705 else
2706 {
2707 PyErr_BadArgument();
2708 return FAIL;
2709 }
2710}
2711
2712/*
2713 * Common routines for buffers and line ranges
2714 * -------------------------------------------
2715 */
2716
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002717typedef struct
2718{
2719 PyObject_HEAD
2720 buf_T *buf;
2721} BufferObject;
2722
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002723 static int
2724CheckBuffer(BufferObject *this)
2725{
2726 if (this->buf == INVALID_BUFFER_VALUE)
2727 {
2728 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2729 return -1;
2730 }
2731
2732 return 0;
2733}
2734
2735 static PyObject *
2736RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2737{
2738 if (CheckBuffer(self))
2739 return NULL;
2740
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002741 if (end == -1)
2742 end = self->buf->b_ml.ml_line_count;
2743
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002744 if (n < 0)
2745 n += end - start + 1;
2746
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002747 if (n < 0 || n > end - start)
2748 {
2749 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2750 return NULL;
2751 }
2752
2753 return GetBufferLine(self->buf, n+start);
2754}
2755
2756 static PyObject *
2757RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2758{
2759 PyInt size;
2760
2761 if (CheckBuffer(self))
2762 return NULL;
2763
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002764 if (end == -1)
2765 end = self->buf->b_ml.ml_line_count;
2766
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002767 size = end - start + 1;
2768
2769 if (lo < 0)
2770 lo = 0;
2771 else if (lo > size)
2772 lo = size;
2773 if (hi < 0)
2774 hi = 0;
2775 if (hi < lo)
2776 hi = lo;
2777 else if (hi > size)
2778 hi = size;
2779
2780 return GetBufferLineList(self->buf, lo+start, hi+start);
2781}
2782
2783 static PyInt
2784RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2785{
2786 PyInt len_change;
2787
2788 if (CheckBuffer(self))
2789 return -1;
2790
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002791 if (end == -1)
2792 end = self->buf->b_ml.ml_line_count;
2793
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002794 if (n < 0)
2795 n += end - start + 1;
2796
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002797 if (n < 0 || n > end - start)
2798 {
2799 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2800 return -1;
2801 }
2802
2803 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2804 return -1;
2805
2806 if (new_end)
2807 *new_end = end + len_change;
2808
2809 return 0;
2810}
2811
Bram Moolenaar19e60942011-06-19 00:27:51 +02002812 static PyInt
2813RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2814{
2815 PyInt size;
2816 PyInt len_change;
2817
2818 /* Self must be a valid buffer */
2819 if (CheckBuffer(self))
2820 return -1;
2821
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002822 if (end == -1)
2823 end = self->buf->b_ml.ml_line_count;
2824
Bram Moolenaar19e60942011-06-19 00:27:51 +02002825 /* Sort out the slice range */
2826 size = end - start + 1;
2827
2828 if (lo < 0)
2829 lo = 0;
2830 else if (lo > size)
2831 lo = size;
2832 if (hi < 0)
2833 hi = 0;
2834 if (hi < lo)
2835 hi = lo;
2836 else if (hi > size)
2837 hi = size;
2838
2839 if (SetBufferLineList(self->buf, lo + start, hi + start,
2840 val, &len_change) == FAIL)
2841 return -1;
2842
2843 if (new_end)
2844 *new_end = end + len_change;
2845
2846 return 0;
2847}
2848
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002849
2850 static PyObject *
2851RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2852{
2853 PyObject *lines;
2854 PyInt len_change;
2855 PyInt max;
2856 PyInt n;
2857
2858 if (CheckBuffer(self))
2859 return NULL;
2860
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002861 if (end == -1)
2862 end = self->buf->b_ml.ml_line_count;
2863
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002864 max = n = end - start + 1;
2865
2866 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2867 return NULL;
2868
2869 if (n < 0 || n > max)
2870 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02002871 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002872 return NULL;
2873 }
2874
2875 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2876 return NULL;
2877
2878 if (new_end)
2879 *new_end = end + len_change;
2880
2881 Py_INCREF(Py_None);
2882 return Py_None;
2883}
2884
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002885/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002886 */
2887
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002888static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002889static PySequenceMethods RangeAsSeq;
2890static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002891
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002892typedef struct
2893{
2894 PyObject_HEAD
2895 BufferObject *buf;
2896 PyInt start;
2897 PyInt end;
2898} RangeObject;
2899
2900 static PyObject *
2901RangeNew(buf_T *buf, PyInt start, PyInt end)
2902{
2903 BufferObject *bufr;
2904 RangeObject *self;
2905 self = PyObject_NEW(RangeObject, &RangeType);
2906 if (self == NULL)
2907 return NULL;
2908
2909 bufr = (BufferObject *)BufferNew(buf);
2910 if (bufr == NULL)
2911 {
2912 Py_DECREF(self);
2913 return NULL;
2914 }
2915 Py_INCREF(bufr);
2916
2917 self->buf = bufr;
2918 self->start = start;
2919 self->end = end;
2920
2921 return (PyObject *)(self);
2922}
2923
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002924 static void
2925RangeDestructor(PyObject *self)
2926{
2927 Py_DECREF(((RangeObject *)(self))->buf);
2928 DESTRUCTOR_FINISH(self);
2929}
2930
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002931 static PyInt
2932RangeLength(PyObject *self)
2933{
2934 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
2935 if (CheckBuffer(((RangeObject *)(self))->buf))
2936 return -1; /* ??? */
2937
2938 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
2939}
2940
2941 static PyObject *
2942RangeItem(PyObject *self, PyInt n)
2943{
2944 return RBItem(((RangeObject *)(self))->buf, n,
2945 ((RangeObject *)(self))->start,
2946 ((RangeObject *)(self))->end);
2947}
2948
2949 static PyObject *
2950RangeSlice(PyObject *self, PyInt lo, PyInt hi)
2951{
2952 return RBSlice(((RangeObject *)(self))->buf, lo, hi,
2953 ((RangeObject *)(self))->start,
2954 ((RangeObject *)(self))->end);
2955}
2956
2957 static PyObject *
2958RangeAppend(PyObject *self, PyObject *args)
2959{
2960 return RBAppend(((RangeObject *)(self))->buf, args,
2961 ((RangeObject *)(self))->start,
2962 ((RangeObject *)(self))->end,
2963 &((RangeObject *)(self))->end);
2964}
2965
2966 static PyObject *
2967RangeRepr(PyObject *self)
2968{
2969 static char repr[100];
2970 RangeObject *this = (RangeObject *)(self);
2971
2972 if (this->buf->buf == INVALID_BUFFER_VALUE)
2973 {
2974 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2975 (self));
2976 return PyString_FromString(repr);
2977 }
2978 else
2979 {
2980 char *name = (char *)this->buf->buf->b_fname;
2981 int len;
2982
2983 if (name == NULL)
2984 name = "";
2985 len = (int)strlen(name);
2986
2987 if (len > 45)
2988 name = name + (45 - len);
2989
2990 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
2991 len > 45 ? "..." : "", name,
2992 this->start, this->end);
2993
2994 return PyString_FromString(repr);
2995 }
2996}
2997
2998static struct PyMethodDef RangeMethods[] = {
2999 /* name, function, calling, documentation */
3000 {"append", RangeAppend, 1, "Append data to the Vim range" },
3001 { NULL, NULL, 0, NULL }
3002};
3003
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003004static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003005static PySequenceMethods BufferAsSeq;
3006static PyMappingMethods BufferAsMapping;
3007
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003008 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02003009BufferNew(buf_T *buf)
3010{
3011 /* We need to handle deletion of buffers underneath us.
3012 * If we add a "b_python*_ref" field to the buf_T structure,
3013 * then we can get at it in buf_freeall() in vim. We then
3014 * need to create only ONE Python object per buffer - if
3015 * we try to create a second, just INCREF the existing one
3016 * and return it. The (single) Python object referring to
3017 * the buffer is stored in "b_python*_ref".
3018 * Question: what to do on a buf_freeall(). We'll probably
3019 * have to either delete the Python object (DECREF it to
3020 * zero - a bad idea, as it leaves dangling refs!) or
3021 * set the buf_T * value to an invalid value (-1?), which
3022 * means we need checks in all access functions... Bah.
3023 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003024 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02003025 * b_python_ref and b_python3_ref fields respectively.
3026 */
3027
3028 BufferObject *self;
3029
3030 if (BUF_PYTHON_REF(buf) != NULL)
3031 {
3032 self = BUF_PYTHON_REF(buf);
3033 Py_INCREF(self);
3034 }
3035 else
3036 {
3037 self = PyObject_NEW(BufferObject, &BufferType);
3038 if (self == NULL)
3039 return NULL;
3040 self->buf = buf;
3041 BUF_PYTHON_REF(buf) = self;
3042 }
3043
3044 return (PyObject *)(self);
3045}
3046
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003047 static void
3048BufferDestructor(PyObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003049{
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003050 BufferObject *this = (BufferObject *)(self);
3051
3052 if (this->buf && this->buf != INVALID_BUFFER_VALUE)
3053 BUF_PYTHON_REF(this->buf) = NULL;
3054
3055 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003056}
3057
Bram Moolenaar971db462013-05-12 18:44:48 +02003058 static PyInt
3059BufferLength(PyObject *self)
3060{
3061 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
3062 if (CheckBuffer((BufferObject *)(self)))
3063 return -1; /* ??? */
3064
3065 return (PyInt)(((BufferObject *)(self))->buf->b_ml.ml_line_count);
3066}
3067
3068 static PyObject *
3069BufferItem(PyObject *self, PyInt n)
3070{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02003071 return RBItem((BufferObject *)(self), n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02003072}
3073
3074 static PyObject *
3075BufferSlice(PyObject *self, PyInt lo, PyInt hi)
3076{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02003077 return RBSlice((BufferObject *)(self), lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02003078}
3079
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003080 static PyObject *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003081BufferAttr(BufferObject *this, char *name)
3082{
3083 if (strcmp(name, "name") == 0)
3084 return Py_BuildValue("s", this->buf->b_ffname);
3085 else if (strcmp(name, "number") == 0)
3086 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum);
3087 else if (strcmp(name, "vars") == 0)
3088 return DictionaryNew(this->buf->b_vars);
3089 else if (strcmp(name, "options") == 0)
3090 return OptionsNew(SREQ_BUF, this->buf, (checkfun) CheckBuffer,
3091 (PyObject *) this);
3092 else if (strcmp(name,"__members__") == 0)
3093 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
3094 else
3095 return NULL;
3096}
3097
3098 static PyObject *
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003099BufferAppend(PyObject *self, PyObject *args)
3100{
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02003101 return RBAppend((BufferObject *)(self), args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003102}
3103
3104 static PyObject *
3105BufferMark(PyObject *self, PyObject *args)
3106{
3107 pos_T *posp;
3108 char *pmark;
3109 char mark;
Bram Moolenaar105bc352013-05-17 16:03:57 +02003110 buf_T *savebuf;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003111
3112 if (CheckBuffer((BufferObject *)(self)))
3113 return NULL;
3114
3115 if (!PyArg_ParseTuple(args, "s", &pmark))
3116 return NULL;
3117 mark = *pmark;
3118
Bram Moolenaar105bc352013-05-17 16:03:57 +02003119 switch_buffer(&savebuf, ((BufferObject *)(self))->buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003120 posp = getmark(mark, FALSE);
Bram Moolenaar105bc352013-05-17 16:03:57 +02003121 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003122
3123 if (posp == NULL)
3124 {
3125 PyErr_SetVim(_("invalid mark name"));
3126 return NULL;
3127 }
3128
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003129 /* Check for keyboard interrupt */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003130 if (VimErrorCheck())
3131 return NULL;
3132
3133 if (posp->lnum <= 0)
3134 {
3135 /* Or raise an error? */
3136 Py_INCREF(Py_None);
3137 return Py_None;
3138 }
3139
3140 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
3141}
3142
3143 static PyObject *
3144BufferRange(PyObject *self, PyObject *args)
3145{
3146 PyInt start;
3147 PyInt end;
3148
3149 if (CheckBuffer((BufferObject *)(self)))
3150 return NULL;
3151
3152 if (!PyArg_ParseTuple(args, "nn", &start, &end))
3153 return NULL;
3154
3155 return RangeNew(((BufferObject *)(self))->buf, start, end);
3156}
3157
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003158 static PyObject *
3159BufferRepr(PyObject *self)
3160{
3161 static char repr[100];
3162 BufferObject *this = (BufferObject *)(self);
3163
3164 if (this->buf == INVALID_BUFFER_VALUE)
3165 {
3166 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
3167 return PyString_FromString(repr);
3168 }
3169 else
3170 {
3171 char *name = (char *)this->buf->b_fname;
3172 PyInt len;
3173
3174 if (name == NULL)
3175 name = "";
3176 len = strlen(name);
3177
3178 if (len > 35)
3179 name = name + (35 - len);
3180
3181 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
3182
3183 return PyString_FromString(repr);
3184 }
3185}
3186
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003187static struct PyMethodDef BufferMethods[] = {
3188 /* name, function, calling, documentation */
3189 {"append", BufferAppend, 1, "Append data to Vim buffer" },
3190 {"mark", BufferMark, 1, "Return (row,col) representing position of named mark" },
3191 {"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 +01003192#if PY_VERSION_HEX >= 0x03000000
3193 {"__dir__", BufferDir, 4, "List its attributes" },
3194#endif
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003195 { NULL, NULL, 0, NULL }
3196};
3197
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003198/*
3199 * Buffer list object - Implementation
3200 */
3201
3202static PyTypeObject BufMapType;
3203
3204typedef struct
3205{
3206 PyObject_HEAD
3207} BufMapObject;
3208
3209 static PyInt
3210BufMapLength(PyObject *self UNUSED)
3211{
3212 buf_T *b = firstbuf;
3213 PyInt n = 0;
3214
3215 while (b)
3216 {
3217 ++n;
3218 b = b->b_next;
3219 }
3220
3221 return n;
3222}
3223
3224 static PyObject *
3225BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
3226{
3227 buf_T *b;
3228 int bnr;
3229
3230#if PY_MAJOR_VERSION < 3
3231 if (PyInt_Check(keyObject))
3232 bnr = PyInt_AsLong(keyObject);
3233 else
3234#endif
3235 if (PyLong_Check(keyObject))
3236 bnr = PyLong_AsLong(keyObject);
3237 else
3238 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003239 PyErr_SetString(PyExc_TypeError, _("key must be integer"));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003240 return NULL;
3241 }
3242
3243 b = buflist_findnr(bnr);
3244
3245 if (b)
3246 return BufferNew(b);
3247 else
3248 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003249 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003250 return NULL;
3251 }
3252}
3253
3254 static void
3255BufMapIterDestruct(PyObject *buffer)
3256{
3257 /* Iteration was stopped before all buffers were processed */
3258 if (buffer)
3259 {
3260 Py_DECREF(buffer);
3261 }
3262}
3263
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003264 static int
3265BufMapIterTraverse(PyObject *buffer, visitproc visit, void *arg)
3266{
3267 Py_VISIT(buffer);
3268 return 0;
3269}
3270
3271 static int
3272BufMapIterClear(PyObject **buffer)
3273{
3274 Py_CLEAR(*buffer);
3275 return 0;
3276}
3277
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003278 static PyObject *
3279BufMapIterNext(PyObject **buffer)
3280{
3281 PyObject *next;
3282 PyObject *r;
3283
3284 if (!*buffer)
3285 return NULL;
3286
3287 r = *buffer;
3288
3289 if (CheckBuffer((BufferObject *)(r)))
3290 {
3291 *buffer = NULL;
3292 return NULL;
3293 }
3294
3295 if (!((BufferObject *)(r))->buf->b_next)
3296 next = NULL;
3297 else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
3298 return NULL;
3299 *buffer = next;
Bram Moolenaar9e74e302013-05-17 21:20:17 +02003300 /* Do not increment reference: we no longer hold it (decref), but whoever
3301 * on other side will hold (incref). Decref+incref = nothing. */
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003302 return r;
3303}
3304
3305 static PyObject *
3306BufMapIter(PyObject *self UNUSED)
3307{
3308 PyObject *buffer;
3309
3310 buffer = BufferNew(firstbuf);
3311 return IterNew(buffer,
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003312 (destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext,
3313 (traversefun) BufMapIterTraverse, (clearfun) BufMapIterClear);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003314}
3315
3316static PyMappingMethods BufMapAsMapping = {
3317 (lenfunc) BufMapLength,
3318 (binaryfunc) BufMapItem,
3319 (objobjargproc) 0,
3320};
3321
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003322/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003323 */
3324
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003325 static PyObject *
3326CurrentGetattr(PyObject *self UNUSED, char *name)
3327{
3328 if (strcmp(name, "buffer") == 0)
3329 return (PyObject *)BufferNew(curbuf);
3330 else if (strcmp(name, "window") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02003331 return (PyObject *)WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003332 else if (strcmp(name, "tabpage") == 0)
3333 return (PyObject *)TabPageNew(curtab);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003334 else if (strcmp(name, "line") == 0)
3335 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3336 else if (strcmp(name, "range") == 0)
3337 return RangeNew(curbuf, RangeStart, RangeEnd);
3338 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003339 return Py_BuildValue("[sssss]", "buffer", "window", "line", "range",
3340 "tabpage");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003341 else
3342 {
3343 PyErr_SetString(PyExc_AttributeError, name);
3344 return NULL;
3345 }
3346}
3347
3348 static int
3349CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3350{
3351 if (strcmp(name, "line") == 0)
3352 {
3353 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3354 return -1;
3355
3356 return 0;
3357 }
Bram Moolenaare7614592013-05-15 15:51:08 +02003358 else if (strcmp(name, "buffer") == 0)
3359 {
3360 int count;
3361
3362 if (value->ob_type != &BufferType)
3363 {
3364 PyErr_SetString(PyExc_TypeError, _("expected vim.buffer object"));
3365 return -1;
3366 }
3367
3368 if (CheckBuffer((BufferObject *)(value)))
3369 return -1;
3370 count = ((BufferObject *)(value))->buf->b_fnum;
3371
3372 if (do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, count, 0) == FAIL)
3373 {
3374 PyErr_SetVim(_("failed to switch to given buffer"));
3375 return -1;
3376 }
3377
3378 return 0;
3379 }
3380 else if (strcmp(name, "window") == 0)
3381 {
3382 int count;
3383
3384 if (value->ob_type != &WindowType)
3385 {
3386 PyErr_SetString(PyExc_TypeError, _("expected vim.window object"));
3387 return -1;
3388 }
3389
3390 if (CheckWindow((WindowObject *)(value)))
3391 return -1;
3392 count = get_win_number(((WindowObject *)(value))->win, firstwin);
3393
3394 if (!count)
3395 {
3396 PyErr_SetString(PyExc_ValueError,
3397 _("failed to find window in the current tab page"));
3398 return -1;
3399 }
3400
3401 win_goto(((WindowObject *)(value))->win);
3402 if (((WindowObject *)(value))->win != curwin)
3403 {
3404 PyErr_SetString(PyExc_RuntimeError,
3405 _("did not switch to the specified window"));
3406 return -1;
3407 }
3408
3409 return 0;
3410 }
3411 else if (strcmp(name, "tabpage") == 0)
3412 {
3413 if (value->ob_type != &TabPageType)
3414 {
3415 PyErr_SetString(PyExc_TypeError, _("expected vim.tabpage object"));
3416 return -1;
3417 }
3418
3419 if (CheckTabPage((TabPageObject *)(value)))
3420 return -1;
3421
3422 goto_tabpage_tp(((TabPageObject *)(value))->tab, TRUE, TRUE);
3423 if (((TabPageObject *)(value))->tab != curtab)
3424 {
3425 PyErr_SetString(PyExc_RuntimeError,
3426 _("did not switch to the specified tab page"));
3427 return -1;
3428 }
3429
3430 return 0;
3431 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003432 else
3433 {
3434 PyErr_SetString(PyExc_AttributeError, name);
3435 return -1;
3436 }
3437}
3438
Bram Moolenaardb913952012-06-29 12:54:53 +02003439 static void
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02003440init_range_cmd(exarg_T *eap)
3441{
3442 RangeStart = eap->line1;
3443 RangeEnd = eap->line2;
3444}
3445
3446 static void
3447init_range_eval(typval_T *rettv UNUSED)
3448{
3449 RangeStart = (PyInt) curwin->w_cursor.lnum;
3450 RangeEnd = RangeStart;
3451}
3452
3453 static void
3454run_cmd(const char *cmd, void *arg UNUSED, PyGILState_STATE *pygilstate UNUSED)
3455{
3456 PyRun_SimpleString((char *) cmd);
3457}
3458
3459static const char *code_hdr = "def " DOPY_FUNC "(line, linenr):\n ";
3460static int code_hdr_len = 30;
3461
3462 static void
3463run_do(const char *cmd, void *arg UNUSED, PyGILState_STATE *pygilstate)
3464{
3465 PyInt lnum;
3466 size_t len;
3467 char *code;
3468 int status;
3469 PyObject *pyfunc, *pymain;
3470
3471 if (u_save(RangeStart - 1, RangeEnd + 1) != OK)
3472 {
3473 EMSG(_("cannot save undo information"));
3474 return;
3475 }
3476
3477 len = code_hdr_len + STRLEN(cmd);
3478 code = PyMem_New(char, len + 1);
3479 memcpy(code, code_hdr, code_hdr_len);
3480 STRCPY(code + code_hdr_len, cmd);
3481 status = PyRun_SimpleString(code);
3482 PyMem_Free(code);
3483
3484 if (status)
3485 {
3486 EMSG(_("failed to run the code"));
3487 return;
3488 }
3489
3490 status = 0;
3491 pymain = PyImport_AddModule("__main__");
3492 pyfunc = PyObject_GetAttrString(pymain, DOPY_FUNC);
3493 PyGILState_Release(*pygilstate);
3494
3495 for (lnum = RangeStart; lnum <= RangeEnd; ++lnum)
3496 {
3497 PyObject *line, *linenr, *ret;
3498
3499 *pygilstate = PyGILState_Ensure();
3500 if (!(line = GetBufferLine(curbuf, lnum)))
3501 goto err;
3502 if (!(linenr = PyInt_FromLong((long) lnum)))
3503 {
3504 Py_DECREF(line);
3505 goto err;
3506 }
3507 ret = PyObject_CallFunctionObjArgs(pyfunc, line, linenr, NULL);
3508 Py_DECREF(line);
3509 Py_DECREF(linenr);
3510 if (!ret)
3511 goto err;
3512
3513 if (ret != Py_None)
3514 if (SetBufferLine(curbuf, lnum, ret, NULL) == FAIL)
3515 goto err;
3516
3517 Py_XDECREF(ret);
3518 PythonIO_Flush();
3519 PyGILState_Release(*pygilstate);
3520 }
3521 goto out;
3522err:
3523 *pygilstate = PyGILState_Ensure();
3524 PyErr_PrintEx(0);
3525 PythonIO_Flush();
3526 status = 1;
3527out:
3528 if (!status)
3529 *pygilstate = PyGILState_Ensure();
3530 Py_DECREF(pyfunc);
3531 PyObject_SetAttrString(pymain, DOPY_FUNC, NULL);
3532 if (status)
3533 return;
3534 check_cursor();
3535 update_curbuf(NOT_VALID);
3536}
3537
3538 static void
3539run_eval(const char *cmd, typval_T *rettv, PyGILState_STATE *pygilstate UNUSED)
3540{
3541 PyObject *r;
3542
3543 r = PyRun_String((char *) cmd, Py_eval_input, globals, globals);
3544 if (r == NULL)
3545 {
3546 if (PyErr_Occurred() && !msg_silent)
3547 PyErr_PrintEx(0);
3548 EMSG(_("E858: Eval did not return a valid python object"));
3549 }
3550 else
3551 {
3552 if (ConvertFromPyObject(r, rettv) == -1)
3553 EMSG(_("E859: Failed to convert returned python object to vim value"));
3554 Py_DECREF(r);
3555 }
3556 PyErr_Clear();
3557}
3558
3559 static void
Bram Moolenaardb913952012-06-29 12:54:53 +02003560set_ref_in_py(const int copyID)
3561{
3562 pylinkedlist_T *cur;
3563 dict_T *dd;
3564 list_T *ll;
3565
3566 if (lastdict != NULL)
3567 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3568 {
3569 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3570 if (dd->dv_copyID != copyID)
3571 {
3572 dd->dv_copyID = copyID;
3573 set_ref_in_ht(&dd->dv_hashtab, copyID);
3574 }
3575 }
3576
3577 if (lastlist != NULL)
3578 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3579 {
3580 ll = ((ListObject *) (cur->pll_obj))->list;
3581 if (ll->lv_copyID != copyID)
3582 {
3583 ll->lv_copyID = copyID;
3584 set_ref_in_list(ll, copyID);
3585 }
3586 }
3587}
3588
3589 static int
3590set_string_copy(char_u *str, typval_T *tv)
3591{
3592 tv->vval.v_string = vim_strsave(str);
3593 if (tv->vval.v_string == NULL)
3594 {
3595 PyErr_NoMemory();
3596 return -1;
3597 }
3598 return 0;
3599}
3600
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003601 static int
3602pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3603{
3604 dict_T *d;
3605 char_u *key;
3606 dictitem_T *di;
3607 PyObject *keyObject;
3608 PyObject *valObject;
3609 Py_ssize_t iter = 0;
3610
3611 d = dict_alloc();
3612 if (d == NULL)
3613 {
3614 PyErr_NoMemory();
3615 return -1;
3616 }
3617
3618 tv->v_type = VAR_DICT;
3619 tv->vval.v_dict = d;
3620
3621 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
3622 {
3623 DICTKEY_DECL
3624
3625 if (keyObject == NULL)
3626 return -1;
3627 if (valObject == NULL)
3628 return -1;
3629
3630 DICTKEY_GET_NOTEMPTY(-1)
3631
3632 di = dictitem_alloc(key);
3633
3634 DICTKEY_UNREF
3635
3636 if (di == NULL)
3637 {
3638 PyErr_NoMemory();
3639 return -1;
3640 }
3641 di->di_tv.v_lock = 0;
3642
3643 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3644 {
3645 vim_free(di);
3646 return -1;
3647 }
3648 if (dict_add(d, di) == FAIL)
3649 {
3650 vim_free(di);
3651 PyErr_SetVim(_("failed to add key to dictionary"));
3652 return -1;
3653 }
3654 }
3655 return 0;
3656}
3657
3658 static int
3659pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3660{
3661 dict_T *d;
3662 char_u *key;
3663 dictitem_T *di;
3664 PyObject *list;
3665 PyObject *litem;
3666 PyObject *keyObject;
3667 PyObject *valObject;
3668 Py_ssize_t lsize;
3669
3670 d = dict_alloc();
3671 if (d == NULL)
3672 {
3673 PyErr_NoMemory();
3674 return -1;
3675 }
3676
3677 tv->v_type = VAR_DICT;
3678 tv->vval.v_dict = d;
3679
3680 list = PyMapping_Items(obj);
3681 if (list == NULL)
3682 return -1;
3683 lsize = PyList_Size(list);
3684 while (lsize--)
3685 {
3686 DICTKEY_DECL
3687
3688 litem = PyList_GetItem(list, lsize);
3689 if (litem == NULL)
3690 {
3691 Py_DECREF(list);
3692 return -1;
3693 }
3694
3695 keyObject = PyTuple_GetItem(litem, 0);
3696 if (keyObject == NULL)
3697 {
3698 Py_DECREF(list);
3699 Py_DECREF(litem);
3700 return -1;
3701 }
3702
3703 DICTKEY_GET_NOTEMPTY(-1)
3704
3705 valObject = PyTuple_GetItem(litem, 1);
3706 if (valObject == NULL)
3707 {
3708 Py_DECREF(list);
3709 Py_DECREF(litem);
3710 return -1;
3711 }
3712
3713 di = dictitem_alloc(key);
3714
3715 DICTKEY_UNREF
3716
3717 if (di == NULL)
3718 {
3719 Py_DECREF(list);
3720 Py_DECREF(litem);
3721 PyErr_NoMemory();
3722 return -1;
3723 }
3724 di->di_tv.v_lock = 0;
3725
3726 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3727 {
3728 vim_free(di);
3729 Py_DECREF(list);
3730 Py_DECREF(litem);
3731 return -1;
3732 }
3733 if (dict_add(d, di) == FAIL)
3734 {
3735 vim_free(di);
3736 Py_DECREF(list);
3737 Py_DECREF(litem);
3738 PyErr_SetVim(_("failed to add key to dictionary"));
3739 return -1;
3740 }
3741 Py_DECREF(litem);
3742 }
3743 Py_DECREF(list);
3744 return 0;
3745}
3746
3747 static int
3748pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3749{
3750 list_T *l;
3751
3752 l = list_alloc();
3753 if (l == NULL)
3754 {
3755 PyErr_NoMemory();
3756 return -1;
3757 }
3758
3759 tv->v_type = VAR_LIST;
3760 tv->vval.v_list = l;
3761
3762 if (list_py_concat(l, obj, lookupDict) == -1)
3763 return -1;
3764
3765 return 0;
3766}
3767
3768 static int
3769pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3770{
3771 PyObject *iterator = PyObject_GetIter(obj);
3772 PyObject *item;
3773 list_T *l;
3774 listitem_T *li;
3775
3776 l = list_alloc();
3777
3778 if (l == NULL)
3779 {
3780 PyErr_NoMemory();
3781 return -1;
3782 }
3783
3784 tv->vval.v_list = l;
3785 tv->v_type = VAR_LIST;
3786
3787
3788 if (iterator == NULL)
3789 return -1;
3790
3791 while ((item = PyIter_Next(obj)))
3792 {
3793 li = listitem_alloc();
3794 if (li == NULL)
3795 {
3796 PyErr_NoMemory();
3797 return -1;
3798 }
3799 li->li_tv.v_lock = 0;
3800
3801 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3802 return -1;
3803
3804 list_append(l, li);
3805
3806 Py_DECREF(item);
3807 }
3808
3809 Py_DECREF(iterator);
3810 return 0;
3811}
3812
Bram Moolenaardb913952012-06-29 12:54:53 +02003813typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3814
3815 static int
3816convert_dl(PyObject *obj, typval_T *tv,
3817 pytotvfunc py_to_tv, PyObject *lookupDict)
3818{
3819 PyObject *capsule;
3820 char hexBuf[sizeof(void *) * 2 + 3];
3821
3822 sprintf(hexBuf, "%p", obj);
3823
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003824# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003825 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003826# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003827 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003828# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003829 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003830 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003831# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003832 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003833# else
3834 capsule = PyCObject_FromVoidPtr(tv, NULL);
3835# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003836 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3837 Py_DECREF(capsule);
3838 if (py_to_tv(obj, tv, lookupDict) == -1)
3839 {
3840 tv->v_type = VAR_UNKNOWN;
3841 return -1;
3842 }
3843 /* As we are not using copy_tv which increments reference count we must
3844 * do it ourself. */
3845 switch(tv->v_type)
3846 {
3847 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3848 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3849 }
3850 }
3851 else
3852 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003853 typval_T *v;
3854
3855# ifdef PY_USE_CAPSULE
3856 v = PyCapsule_GetPointer(capsule, NULL);
3857# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003858 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003859# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003860 copy_tv(v, tv);
3861 }
3862 return 0;
3863}
3864
3865 static int
3866ConvertFromPyObject(PyObject *obj, typval_T *tv)
3867{
3868 PyObject *lookup_dict;
3869 int r;
3870
3871 lookup_dict = PyDict_New();
3872 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3873 Py_DECREF(lookup_dict);
3874 return r;
3875}
3876
3877 static int
3878_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3879{
3880 if (obj->ob_type == &DictionaryType)
3881 {
3882 tv->v_type = VAR_DICT;
3883 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3884 ++tv->vval.v_dict->dv_refcount;
3885 }
3886 else if (obj->ob_type == &ListType)
3887 {
3888 tv->v_type = VAR_LIST;
3889 tv->vval.v_list = (((ListObject *)(obj))->list);
3890 ++tv->vval.v_list->lv_refcount;
3891 }
3892 else if (obj->ob_type == &FunctionType)
3893 {
3894 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3895 return -1;
3896
3897 tv->v_type = VAR_FUNC;
3898 func_ref(tv->vval.v_string);
3899 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003900 else if (PyBytes_Check(obj))
3901 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003902 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003903
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003904 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3905 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003906 if (result == NULL)
3907 return -1;
3908
3909 if (set_string_copy(result, tv) == -1)
3910 return -1;
3911
3912 tv->v_type = VAR_STRING;
3913 }
3914 else if (PyUnicode_Check(obj))
3915 {
3916 PyObject *bytes;
3917 char_u *result;
3918
Bram Moolenaardb913952012-06-29 12:54:53 +02003919 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3920 if (bytes == NULL)
3921 return -1;
3922
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003923 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3924 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003925 if (result == NULL)
3926 return -1;
3927
3928 if (set_string_copy(result, tv) == -1)
3929 {
3930 Py_XDECREF(bytes);
3931 return -1;
3932 }
3933 Py_XDECREF(bytes);
3934
3935 tv->v_type = VAR_STRING;
3936 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003937#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003938 else if (PyInt_Check(obj))
3939 {
3940 tv->v_type = VAR_NUMBER;
3941 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3942 }
3943#endif
3944 else if (PyLong_Check(obj))
3945 {
3946 tv->v_type = VAR_NUMBER;
3947 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3948 }
3949 else if (PyDict_Check(obj))
3950 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3951#ifdef FEAT_FLOAT
3952 else if (PyFloat_Check(obj))
3953 {
3954 tv->v_type = VAR_FLOAT;
3955 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3956 }
3957#endif
3958 else if (PyIter_Check(obj))
3959 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3960 else if (PySequence_Check(obj))
3961 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3962 else if (PyMapping_Check(obj))
3963 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3964 else
3965 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003966 PyErr_SetString(PyExc_TypeError,
3967 _("unable to convert to vim structure"));
Bram Moolenaardb913952012-06-29 12:54:53 +02003968 return -1;
3969 }
3970 return 0;
3971}
3972
3973 static PyObject *
3974ConvertToPyObject(typval_T *tv)
3975{
3976 if (tv == NULL)
3977 {
3978 PyErr_SetVim(_("NULL reference passed"));
3979 return NULL;
3980 }
3981 switch (tv->v_type)
3982 {
3983 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003984 return PyBytes_FromString(tv->vval.v_string == NULL
3985 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003986 case VAR_NUMBER:
3987 return PyLong_FromLong((long) tv->vval.v_number);
3988#ifdef FEAT_FLOAT
3989 case VAR_FLOAT:
3990 return PyFloat_FromDouble((double) tv->vval.v_float);
3991#endif
3992 case VAR_LIST:
3993 return ListNew(tv->vval.v_list);
3994 case VAR_DICT:
3995 return DictionaryNew(tv->vval.v_dict);
3996 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02003997 return FunctionNew(tv->vval.v_string == NULL
3998 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02003999 case VAR_UNKNOWN:
4000 Py_INCREF(Py_None);
4001 return Py_None;
4002 default:
4003 PyErr_SetVim(_("internal error: invalid value type"));
4004 return NULL;
4005 }
4006}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004007
4008typedef struct
4009{
4010 PyObject_HEAD
4011} CurrentObject;
4012static PyTypeObject CurrentType;
4013
4014 static void
4015init_structs(void)
4016{
4017 vim_memset(&OutputType, 0, sizeof(OutputType));
4018 OutputType.tp_name = "vim.message";
4019 OutputType.tp_basicsize = sizeof(OutputObject);
4020 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
4021 OutputType.tp_doc = "vim message object";
4022 OutputType.tp_methods = OutputMethods;
4023#if PY_MAJOR_VERSION >= 3
4024 OutputType.tp_getattro = OutputGetattro;
4025 OutputType.tp_setattro = OutputSetattro;
4026 OutputType.tp_alloc = call_PyType_GenericAlloc;
4027 OutputType.tp_new = call_PyType_GenericNew;
4028 OutputType.tp_free = call_PyObject_Free;
4029#else
4030 OutputType.tp_getattr = OutputGetattr;
4031 OutputType.tp_setattr = OutputSetattr;
4032#endif
4033
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004034 vim_memset(&IterType, 0, sizeof(IterType));
4035 IterType.tp_name = "vim.iter";
4036 IterType.tp_basicsize = sizeof(IterObject);
4037 IterType.tp_flags = Py_TPFLAGS_DEFAULT;
4038 IterType.tp_doc = "generic iterator object";
4039 IterType.tp_iter = IterIter;
4040 IterType.tp_iternext = IterNext;
Bram Moolenaar2cd73622013-05-15 19:07:47 +02004041 IterType.tp_dealloc = IterDestructor;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02004042 IterType.tp_traverse = IterTraverse;
4043 IterType.tp_clear = IterClear;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004044
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004045 vim_memset(&BufferType, 0, sizeof(BufferType));
4046 BufferType.tp_name = "vim.buffer";
4047 BufferType.tp_basicsize = sizeof(BufferType);
4048 BufferType.tp_dealloc = BufferDestructor;
4049 BufferType.tp_repr = BufferRepr;
4050 BufferType.tp_as_sequence = &BufferAsSeq;
4051 BufferType.tp_as_mapping = &BufferAsMapping;
4052 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
4053 BufferType.tp_doc = "vim buffer object";
4054 BufferType.tp_methods = BufferMethods;
4055#if PY_MAJOR_VERSION >= 3
4056 BufferType.tp_getattro = BufferGetattro;
4057 BufferType.tp_alloc = call_PyType_GenericAlloc;
4058 BufferType.tp_new = call_PyType_GenericNew;
4059 BufferType.tp_free = call_PyObject_Free;
4060#else
4061 BufferType.tp_getattr = BufferGetattr;
4062#endif
4063
4064 vim_memset(&WindowType, 0, sizeof(WindowType));
4065 WindowType.tp_name = "vim.window";
4066 WindowType.tp_basicsize = sizeof(WindowObject);
4067 WindowType.tp_dealloc = WindowDestructor;
4068 WindowType.tp_repr = WindowRepr;
4069 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
4070 WindowType.tp_doc = "vim Window object";
4071 WindowType.tp_methods = WindowMethods;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02004072 WindowType.tp_traverse = WindowTraverse;
4073 WindowType.tp_clear = WindowClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004074#if PY_MAJOR_VERSION >= 3
4075 WindowType.tp_getattro = WindowGetattro;
4076 WindowType.tp_setattro = WindowSetattro;
4077 WindowType.tp_alloc = call_PyType_GenericAlloc;
4078 WindowType.tp_new = call_PyType_GenericNew;
4079 WindowType.tp_free = call_PyObject_Free;
4080#else
4081 WindowType.tp_getattr = WindowGetattr;
4082 WindowType.tp_setattr = WindowSetattr;
4083#endif
4084
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004085 vim_memset(&TabPageType, 0, sizeof(TabPageType));
4086 TabPageType.tp_name = "vim.tabpage";
4087 TabPageType.tp_basicsize = sizeof(TabPageObject);
4088 TabPageType.tp_dealloc = TabPageDestructor;
4089 TabPageType.tp_repr = TabPageRepr;
4090 TabPageType.tp_flags = Py_TPFLAGS_DEFAULT;
4091 TabPageType.tp_doc = "vim tab page object";
4092 TabPageType.tp_methods = TabPageMethods;
4093#if PY_MAJOR_VERSION >= 3
4094 TabPageType.tp_getattro = TabPageGetattro;
4095 TabPageType.tp_alloc = call_PyType_GenericAlloc;
4096 TabPageType.tp_new = call_PyType_GenericNew;
4097 TabPageType.tp_free = call_PyObject_Free;
4098#else
4099 TabPageType.tp_getattr = TabPageGetattr;
4100#endif
4101
Bram Moolenaardfa38d42013-05-15 13:38:47 +02004102 vim_memset(&BufMapType, 0, sizeof(BufMapType));
4103 BufMapType.tp_name = "vim.bufferlist";
4104 BufMapType.tp_basicsize = sizeof(BufMapObject);
4105 BufMapType.tp_as_mapping = &BufMapAsMapping;
4106 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004107 BufMapType.tp_iter = BufMapIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004108 BufferType.tp_doc = "vim buffer list";
4109
4110 vim_memset(&WinListType, 0, sizeof(WinListType));
4111 WinListType.tp_name = "vim.windowlist";
4112 WinListType.tp_basicsize = sizeof(WinListType);
4113 WinListType.tp_as_sequence = &WinListAsSeq;
4114 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
4115 WinListType.tp_doc = "vim window list";
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004116 WinListType.tp_dealloc = WinListDestructor;
4117
4118 vim_memset(&TabListType, 0, sizeof(TabListType));
4119 TabListType.tp_name = "vim.tabpagelist";
4120 TabListType.tp_basicsize = sizeof(TabListType);
4121 TabListType.tp_as_sequence = &TabListAsSeq;
4122 TabListType.tp_flags = Py_TPFLAGS_DEFAULT;
4123 TabListType.tp_doc = "vim tab page list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004124
4125 vim_memset(&RangeType, 0, sizeof(RangeType));
4126 RangeType.tp_name = "vim.range";
4127 RangeType.tp_basicsize = sizeof(RangeObject);
4128 RangeType.tp_dealloc = RangeDestructor;
4129 RangeType.tp_repr = RangeRepr;
4130 RangeType.tp_as_sequence = &RangeAsSeq;
4131 RangeType.tp_as_mapping = &RangeAsMapping;
4132 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
4133 RangeType.tp_doc = "vim Range object";
4134 RangeType.tp_methods = RangeMethods;
4135#if PY_MAJOR_VERSION >= 3
4136 RangeType.tp_getattro = RangeGetattro;
4137 RangeType.tp_alloc = call_PyType_GenericAlloc;
4138 RangeType.tp_new = call_PyType_GenericNew;
4139 RangeType.tp_free = call_PyObject_Free;
4140#else
4141 RangeType.tp_getattr = RangeGetattr;
4142#endif
4143
4144 vim_memset(&CurrentType, 0, sizeof(CurrentType));
4145 CurrentType.tp_name = "vim.currentdata";
4146 CurrentType.tp_basicsize = sizeof(CurrentObject);
4147 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
4148 CurrentType.tp_doc = "vim current object";
4149#if PY_MAJOR_VERSION >= 3
4150 CurrentType.tp_getattro = CurrentGetattro;
4151 CurrentType.tp_setattro = CurrentSetattro;
4152#else
4153 CurrentType.tp_getattr = CurrentGetattr;
4154 CurrentType.tp_setattr = CurrentSetattr;
4155#endif
4156
4157 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
4158 DictionaryType.tp_name = "vim.dictionary";
4159 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
4160 DictionaryType.tp_dealloc = DictionaryDestructor;
4161 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
4162 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
4163 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
4164 DictionaryType.tp_methods = DictionaryMethods;
4165#if PY_MAJOR_VERSION >= 3
4166 DictionaryType.tp_getattro = DictionaryGetattro;
4167 DictionaryType.tp_setattro = DictionarySetattro;
4168#else
4169 DictionaryType.tp_getattr = DictionaryGetattr;
4170 DictionaryType.tp_setattr = DictionarySetattr;
4171#endif
4172
4173 vim_memset(&ListType, 0, sizeof(ListType));
4174 ListType.tp_name = "vim.list";
4175 ListType.tp_dealloc = ListDestructor;
4176 ListType.tp_basicsize = sizeof(ListObject);
4177 ListType.tp_as_sequence = &ListAsSeq;
4178 ListType.tp_as_mapping = &ListAsMapping;
4179 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
4180 ListType.tp_doc = "list pushing modifications to vim structure";
4181 ListType.tp_methods = ListMethods;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004182 ListType.tp_iter = ListIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004183#if PY_MAJOR_VERSION >= 3
4184 ListType.tp_getattro = ListGetattro;
4185 ListType.tp_setattro = ListSetattro;
4186#else
4187 ListType.tp_getattr = ListGetattr;
4188 ListType.tp_setattr = ListSetattr;
4189#endif
4190
4191 vim_memset(&FunctionType, 0, sizeof(FunctionType));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004192 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004193 FunctionType.tp_basicsize = sizeof(FunctionObject);
4194 FunctionType.tp_dealloc = FunctionDestructor;
4195 FunctionType.tp_call = FunctionCall;
4196 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
4197 FunctionType.tp_doc = "object that calls vim function";
4198 FunctionType.tp_methods = FunctionMethods;
4199#if PY_MAJOR_VERSION >= 3
4200 FunctionType.tp_getattro = FunctionGetattro;
4201#else
4202 FunctionType.tp_getattr = FunctionGetattr;
4203#endif
4204
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02004205 vim_memset(&OptionsType, 0, sizeof(OptionsType));
4206 OptionsType.tp_name = "vim.options";
4207 OptionsType.tp_basicsize = sizeof(OptionsObject);
4208 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
4209 OptionsType.tp_doc = "object for manipulating options";
4210 OptionsType.tp_as_mapping = &OptionsAsMapping;
4211 OptionsType.tp_dealloc = OptionsDestructor;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02004212 OptionsType.tp_traverse = OptionsTraverse;
4213 OptionsType.tp_clear = OptionsClear;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02004214
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004215#if PY_MAJOR_VERSION >= 3
4216 vim_memset(&vimmodule, 0, sizeof(vimmodule));
4217 vimmodule.m_name = "vim";
4218 vimmodule.m_doc = "Vim Python interface\n";
4219 vimmodule.m_size = -1;
4220 vimmodule.m_methods = VimMethods;
4221#endif
4222}