blob: 18088f88f211ebcbe406d3e77afbdc4e928596d2 [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
Bram Moolenaard6e39182013-05-21 18:30:34 +020079OutputSetattr(OutputObject *self, char *name, PyObject *val)
Bram Moolenaar77045652012-09-21 13:46:06 +020080{
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
Bram Moolenaard6e39182013-05-21 18:30:34 +020096 self->softspace = PyInt_AsLong(val);
Bram Moolenaar77045652012-09-21 13:46:06 +020097 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 *
Bram Moolenaard6e39182013-05-21 18:30:34 +0200155OutputWrite(OutputObject *self, PyObject *args)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200156{
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 Moolenaard6e39182013-05-21 18:30:34 +0200159 int error = self->error;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200160
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 *
Bram Moolenaard6e39182013-05-21 18:30:34 +0200176OutputWritelines(OutputObject *self, PyObject *args)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200177{
178 PyInt n;
179 PyInt i;
180 PyObject *list;
Bram Moolenaard6e39182013-05-21 18:30:34 +0200181 int error = self->error;
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200182
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 *
Bram Moolenaar182dc4f2013-05-21 19:01:55 +0200223OutputFlush(PyObject *self UNUSED)
Bram Moolenaara29a37d2011-03-22 15:47:44 +0100224{
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[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +0200233 /* name, function, calling, doc */
234 {"write", (PyCFunction)OutputWrite, METH_VARARGS, ""},
235 {"writelines", (PyCFunction)OutputWritelines, METH_VARARGS, ""},
236 {"flush", (PyCFunction)OutputFlush, METH_NOARGS, ""},
237 { NULL, NULL, 0, NULL}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200238};
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 */
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200275
276 static void
277VimTryStart(void)
278{
279 ++trylevel;
280}
281
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200282 static int
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200283VimTryEnd(void)
284{
285 --trylevel;
286 if (got_int)
287 {
288 PyErr_SetNone(PyExc_KeyboardInterrupt);
289 return 1;
290 }
291 else if (!did_throw)
292 return 0;
293 else if (PyErr_Occurred())
294 return 1;
295 else
296 {
297 PyErr_SetVim((char *) current_exception->value);
298 discard_current_exception();
299 return 1;
300 }
301}
302
303 static int
304VimCheckInterrupt(void)
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200305{
306 if (got_int)
307 {
308 PyErr_SetNone(PyExc_KeyboardInterrupt);
309 return 1;
310 }
Bram Moolenaar170bf1a2010-07-24 23:51:45 +0200311 return 0;
312}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200313
314/* Vim module - Implementation
315 */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200316
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200317 static PyObject *
318VimCommand(PyObject *self UNUSED, PyObject *args)
319{
320 char *cmd;
321 PyObject *result;
322
323 if (!PyArg_ParseTuple(args, "s", &cmd))
324 return NULL;
325
326 PyErr_Clear();
327
328 Py_BEGIN_ALLOW_THREADS
329 Python_Lock_Vim();
330
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200331 VimTryStart();
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200332 do_cmdline_cmd((char_u *)cmd);
333 update_screen(VALID);
334
335 Python_Release_Vim();
336 Py_END_ALLOW_THREADS
337
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200338 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200339 result = NULL;
340 else
341 result = Py_None;
342
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200343
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200344 Py_XINCREF(result);
345 return result;
346}
347
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200348/*
349 * Function to translate a typval_T into a PyObject; this will recursively
350 * translate lists/dictionaries into their Python equivalents.
351 *
352 * The depth parameter is to avoid infinite recursion, set it to 1 when
353 * you call VimToPython.
354 */
355 static PyObject *
356VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
357{
358 PyObject *result;
359 PyObject *newObj;
Bram Moolenaardb913952012-06-29 12:54:53 +0200360 char ptrBuf[sizeof(void *) * 2 + 3];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200361
362 /* Avoid infinite recursion */
363 if (depth > 100)
364 {
365 Py_INCREF(Py_None);
366 result = Py_None;
367 return result;
368 }
369
370 /* Check if we run into a recursive loop. The item must be in lookupDict
371 * then and we can use it again. */
372 if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
373 || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
374 {
Bram Moolenaardb913952012-06-29 12:54:53 +0200375 sprintf(ptrBuf, "%p",
376 our_tv->v_type == VAR_LIST ? (void *)our_tv->vval.v_list
377 : (void *)our_tv->vval.v_dict);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200378 result = PyDict_GetItemString(lookupDict, ptrBuf);
379 if (result != NULL)
380 {
381 Py_INCREF(result);
382 return result;
383 }
384 }
385
386 if (our_tv->v_type == VAR_STRING)
387 {
Bram Moolenaard1f13fd2012-10-05 21:30:07 +0200388 result = Py_BuildValue("s", our_tv->vval.v_string == NULL
389 ? "" : (char *)our_tv->vval.v_string);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200390 }
391 else if (our_tv->v_type == VAR_NUMBER)
392 {
393 char buf[NUMBUFLEN];
394
395 /* For backwards compatibility numbers are stored as strings. */
396 sprintf(buf, "%ld", (long)our_tv->vval.v_number);
397 result = Py_BuildValue("s", buf);
398 }
399# ifdef FEAT_FLOAT
400 else if (our_tv->v_type == VAR_FLOAT)
401 {
402 char buf[NUMBUFLEN];
403
404 sprintf(buf, "%f", our_tv->vval.v_float);
405 result = Py_BuildValue("s", buf);
406 }
407# endif
408 else if (our_tv->v_type == VAR_LIST)
409 {
410 list_T *list = our_tv->vval.v_list;
411 listitem_T *curr;
412
413 result = PyList_New(0);
414
415 if (list != NULL)
416 {
417 PyDict_SetItemString(lookupDict, ptrBuf, result);
418
419 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
420 {
421 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
422 PyList_Append(result, newObj);
423 Py_DECREF(newObj);
424 }
425 }
426 }
427 else if (our_tv->v_type == VAR_DICT)
428 {
429 result = PyDict_New();
430
431 if (our_tv->vval.v_dict != NULL)
432 {
433 hashtab_T *ht = &our_tv->vval.v_dict->dv_hashtab;
434 long_u todo = ht->ht_used;
435 hashitem_T *hi;
436 dictitem_T *di;
437
438 PyDict_SetItemString(lookupDict, ptrBuf, result);
439
440 for (hi = ht->ht_array; todo > 0; ++hi)
441 {
442 if (!HASHITEM_EMPTY(hi))
443 {
444 --todo;
445
446 di = dict_lookup(hi);
447 newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
448 PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
449 Py_DECREF(newObj);
450 }
451 }
452 }
453 }
454 else
455 {
456 Py_INCREF(Py_None);
457 result = Py_None;
458 }
459
460 return result;
461}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200462
463 static PyObject *
Bram Moolenaar774267b2013-05-21 20:51:59 +0200464VimEval(PyObject *self UNUSED, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200465{
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200466 char *expr;
467 typval_T *our_tv;
468 PyObject *result;
469 PyObject *lookup_dict;
470
471 if (!PyArg_ParseTuple(args, "s", &expr))
472 return NULL;
473
474 Py_BEGIN_ALLOW_THREADS
475 Python_Lock_Vim();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200476 VimTryStart();
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200477 our_tv = eval_expr((char_u *)expr, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200478 Python_Release_Vim();
479 Py_END_ALLOW_THREADS
480
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200481 if (VimTryEnd())
482 return NULL;
483
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200484 if (our_tv == NULL)
485 {
486 PyErr_SetVim(_("invalid expression"));
487 return NULL;
488 }
489
490 /* Convert the Vim type into a Python type. Create a dictionary that's
491 * used to check for recursive loops. */
492 lookup_dict = PyDict_New();
493 result = VimToPython(our_tv, 1, lookup_dict);
494 Py_DECREF(lookup_dict);
495
496
497 Py_BEGIN_ALLOW_THREADS
498 Python_Lock_Vim();
499 free_tv(our_tv);
500 Python_Release_Vim();
501 Py_END_ALLOW_THREADS
502
503 return result;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200504}
505
Bram Moolenaardb913952012-06-29 12:54:53 +0200506static PyObject *ConvertToPyObject(typval_T *);
507
508 static PyObject *
Bram Moolenaar9e74e302013-05-17 21:20:17 +0200509VimEvalPy(PyObject *self UNUSED, PyObject *args)
Bram Moolenaardb913952012-06-29 12:54:53 +0200510{
Bram Moolenaardb913952012-06-29 12:54:53 +0200511 char *expr;
512 typval_T *our_tv;
513 PyObject *result;
514
515 if (!PyArg_ParseTuple(args, "s", &expr))
516 return NULL;
517
518 Py_BEGIN_ALLOW_THREADS
519 Python_Lock_Vim();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200520 VimTryStart();
Bram Moolenaardb913952012-06-29 12:54:53 +0200521 our_tv = eval_expr((char_u *)expr, NULL);
Bram Moolenaardb913952012-06-29 12:54:53 +0200522 Python_Release_Vim();
523 Py_END_ALLOW_THREADS
524
Bram Moolenaara7b64ce2013-05-21 20:40:40 +0200525 if (VimTryEnd())
526 return NULL;
527
Bram Moolenaardb913952012-06-29 12:54:53 +0200528 if (our_tv == NULL)
529 {
530 PyErr_SetVim(_("invalid expression"));
531 return NULL;
532 }
533
534 result = ConvertToPyObject(our_tv);
535 Py_BEGIN_ALLOW_THREADS
536 Python_Lock_Vim();
537 free_tv(our_tv);
538 Python_Release_Vim();
539 Py_END_ALLOW_THREADS
540
541 return result;
Bram Moolenaardb913952012-06-29 12:54:53 +0200542}
543
544 static PyObject *
545VimStrwidth(PyObject *self UNUSED, PyObject *args)
546{
547 char *expr;
548
549 if (!PyArg_ParseTuple(args, "s", &expr))
550 return NULL;
551
Bram Moolenaara54bf402012-12-05 16:30:07 +0100552 return PyLong_FromLong(
553#ifdef FEAT_MBYTE
554 mb_string2cells((char_u *)expr, (int)STRLEN(expr))
555#else
556 STRLEN(expr)
557#endif
558 );
Bram Moolenaardb913952012-06-29 12:54:53 +0200559}
560
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200561/*
562 * Vim module - Definitions
563 */
564
565static struct PyMethodDef VimMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +0200566 /* name, function, calling, documentation */
567 {"command", VimCommand, METH_VARARGS, "Execute a Vim ex-mode command" },
568 {"eval", VimEval, METH_VARARGS, "Evaluate an expression using Vim evaluator" },
569 {"bindeval", VimEvalPy, METH_VARARGS, "Like eval(), but returns objects attached to vim ones"},
570 {"strwidth", VimStrwidth, METH_VARARGS, "Screen string width, counts <Tab> as having width 1"},
571 { NULL, NULL, 0, NULL }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200572};
573
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200574/*
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200575 * Generic iterator object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200576 */
577
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200578static PyTypeObject IterType;
579
580typedef PyObject *(*nextfun)(void **);
581typedef void (*destructorfun)(void *);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200582typedef int (*traversefun)(void *, visitproc, void *);
583typedef int (*clearfun)(void **);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200584
Bram Moolenaar9e74e302013-05-17 21:20:17 +0200585/* Main purpose of this object is removing the need for do python
586 * initialization (i.e. PyType_Ready and setting type attributes) for a big
587 * bunch of objects. */
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200588
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200589typedef struct
590{
591 PyObject_HEAD
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200592 void *cur;
593 nextfun next;
594 destructorfun destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200595 traversefun traverse;
596 clearfun clear;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200597} IterObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200598
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200599 static PyObject *
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200600IterNew(void *start, destructorfun destruct, nextfun next, traversefun traverse,
601 clearfun clear)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200602{
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200603 IterObject *self;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200604
Bram Moolenaar774267b2013-05-21 20:51:59 +0200605 self = PyObject_GC_New(IterObject, &IterType);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200606 self->cur = start;
607 self->next = next;
608 self->destruct = destruct;
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200609 self->traverse = traverse;
610 self->clear = clear;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200611
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200612 return (PyObject *)(self);
613}
614
615 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +0200616IterDestructor(IterObject *self)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200617{
Bram Moolenaar774267b2013-05-21 20:51:59 +0200618 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaard6e39182013-05-21 18:30:34 +0200619 self->destruct(self->cur);
Bram Moolenaar774267b2013-05-21 20:51:59 +0200620 PyObject_GC_Del((void *)(self));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200621}
622
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200623 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +0200624IterTraverse(IterObject *self, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200625{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200626 if (self->traverse != NULL)
627 return self->traverse(self->cur, visit, arg);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200628 else
629 return 0;
630}
631
Bram Moolenaar9e74e302013-05-17 21:20:17 +0200632/* Mac OSX defines clear() somewhere. */
633#ifdef clear
634# undef clear
635#endif
636
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200637 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +0200638IterClear(IterObject *self)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200639{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200640 if (self->clear != NULL)
641 return self->clear(&self->cur);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +0200642 else
643 return 0;
644}
645
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200646 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +0200647IterNext(IterObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200648{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200649 return self->next(&self->cur);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +0200650}
651
Bram Moolenaarb6c589a2013-05-15 14:39:52 +0200652 static PyObject *
653IterIter(PyObject *self)
654{
655 return self;
656}
Bram Moolenaardfa38d42013-05-15 13:38:47 +0200657
Bram Moolenaardb913952012-06-29 12:54:53 +0200658typedef struct pylinkedlist_S {
659 struct pylinkedlist_S *pll_next;
660 struct pylinkedlist_S *pll_prev;
661 PyObject *pll_obj;
662} pylinkedlist_T;
663
664static pylinkedlist_T *lastdict = NULL;
665static pylinkedlist_T *lastlist = NULL;
666
667 static void
668pyll_remove(pylinkedlist_T *ref, pylinkedlist_T **last)
669{
670 if (ref->pll_prev == NULL)
671 {
672 if (ref->pll_next == NULL)
673 {
674 *last = NULL;
675 return;
676 }
677 }
678 else
679 ref->pll_prev->pll_next = ref->pll_next;
680
681 if (ref->pll_next == NULL)
682 *last = ref->pll_prev;
683 else
684 ref->pll_next->pll_prev = ref->pll_prev;
685}
686
687 static void
688pyll_add(PyObject *self, pylinkedlist_T *ref, pylinkedlist_T **last)
689{
690 if (*last == NULL)
691 ref->pll_prev = NULL;
692 else
693 {
694 (*last)->pll_next = ref;
695 ref->pll_prev = *last;
696 }
697 ref->pll_next = NULL;
698 ref->pll_obj = self;
699 *last = ref;
700}
701
702static PyTypeObject DictionaryType;
703
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200704#define DICTKEY_GET_NOTEMPTY(err) \
705 DICTKEY_GET(err) \
706 if (*key == NUL) \
707 { \
708 PyErr_SetString(PyExc_ValueError, _("empty keys are not allowed")); \
709 return err; \
710 }
711
Bram Moolenaardb913952012-06-29 12:54:53 +0200712typedef struct
713{
714 PyObject_HEAD
715 dict_T *dict;
716 pylinkedlist_T ref;
717} DictionaryObject;
718
719 static PyObject *
720DictionaryNew(dict_T *dict)
721{
722 DictionaryObject *self;
723
724 self = PyObject_NEW(DictionaryObject, &DictionaryType);
725 if (self == NULL)
726 return NULL;
727 self->dict = dict;
728 ++dict->dv_refcount;
729
730 pyll_add((PyObject *)(self), &self->ref, &lastdict);
731
732 return (PyObject *)(self);
733}
734
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200735 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +0200736DictionaryDestructor(DictionaryObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200737{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200738 pyll_remove(&self->ref, &lastdict);
739 dict_unref(self->dict);
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200740
741 DESTRUCTOR_FINISH(self);
742}
743
Bram Moolenaardb913952012-06-29 12:54:53 +0200744 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +0200745DictionarySetattr(DictionaryObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200746{
747 if (val == NULL)
748 {
749 PyErr_SetString(PyExc_AttributeError, _("Cannot delete DictionaryObject attributes"));
750 return -1;
751 }
752
753 if (strcmp(name, "locked") == 0)
754 {
Bram Moolenaard6e39182013-05-21 18:30:34 +0200755 if (self->dict->dv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +0200756 {
757 PyErr_SetString(PyExc_TypeError, _("Cannot modify fixed dictionary"));
758 return -1;
759 }
760 else
761 {
Bram Moolenaarb983f752013-05-15 16:11:50 +0200762 int istrue = PyObject_IsTrue(val);
763 if (istrue == -1)
764 return -1;
765 else if (istrue)
Bram Moolenaard6e39182013-05-21 18:30:34 +0200766 self->dict->dv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200767 else
Bram Moolenaard6e39182013-05-21 18:30:34 +0200768 self->dict->dv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +0200769 }
770 return 0;
771 }
772 else
773 {
774 PyErr_SetString(PyExc_AttributeError, _("Cannot set this attribute"));
775 return -1;
776 }
777}
778
779 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +0200780DictionaryLength(DictionaryObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +0200781{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200782 return ((PyInt) (self->dict->dv_hashtab.ht_used));
Bram Moolenaardb913952012-06-29 12:54:53 +0200783}
784
785 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +0200786DictionaryItem(DictionaryObject *self, PyObject *keyObject)
Bram Moolenaardb913952012-06-29 12:54:53 +0200787{
788 char_u *key;
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200789 dictitem_T *di;
Bram Moolenaardb913952012-06-29 12:54:53 +0200790 DICTKEY_DECL
791
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200792 DICTKEY_GET_NOTEMPTY(NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +0200793
Bram Moolenaard6e39182013-05-21 18:30:34 +0200794 di = dict_find(self->dict, key, -1);
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200795
Bram Moolenaar696c2112012-09-21 13:43:14 +0200796 DICTKEY_UNREF
797
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200798 if (di == NULL)
799 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200800 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200801 return NULL;
802 }
Bram Moolenaardb913952012-06-29 12:54:53 +0200803
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200804 return ConvertToPyObject(&di->di_tv);
Bram Moolenaardb913952012-06-29 12:54:53 +0200805}
806
807 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +0200808DictionaryAssItem(DictionaryObject *self, PyObject *keyObject, PyObject *valObject)
Bram Moolenaardb913952012-06-29 12:54:53 +0200809{
810 char_u *key;
811 typval_T tv;
Bram Moolenaard6e39182013-05-21 18:30:34 +0200812 dict_T *d = self->dict;
Bram Moolenaardb913952012-06-29 12:54:53 +0200813 dictitem_T *di;
814 DICTKEY_DECL
815
816 if (d->dv_lock)
817 {
818 PyErr_SetVim(_("dict is locked"));
819 return -1;
820 }
821
Bram Moolenaar231e1a12012-09-05 18:45:28 +0200822 DICTKEY_GET_NOTEMPTY(-1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200823
824 di = dict_find(d, key, -1);
825
826 if (valObject == NULL)
827 {
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200828 hashitem_T *hi;
829
Bram Moolenaardb913952012-06-29 12:54:53 +0200830 if (di == NULL)
831 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200832 DICTKEY_UNREF
Bram Moolenaar4d188da2013-05-15 15:35:09 +0200833 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaardb913952012-06-29 12:54:53 +0200834 return -1;
835 }
Bram Moolenaarf27839c2012-06-29 16:19:50 +0200836 hi = hash_find(&d->dv_hashtab, di->di_key);
Bram Moolenaardb913952012-06-29 12:54:53 +0200837 hash_remove(&d->dv_hashtab, hi);
838 dictitem_free(di);
839 return 0;
840 }
841
842 if (ConvertFromPyObject(valObject, &tv) == -1)
Bram Moolenaardb913952012-06-29 12:54:53 +0200843 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +0200844
845 if (di == NULL)
846 {
847 di = dictitem_alloc(key);
848 if (di == NULL)
849 {
850 PyErr_NoMemory();
851 return -1;
852 }
853 di->di_tv.v_lock = 0;
854
855 if (dict_add(d, di) == FAIL)
856 {
Bram Moolenaar696c2112012-09-21 13:43:14 +0200857 DICTKEY_UNREF
Bram Moolenaardb913952012-06-29 12:54:53 +0200858 vim_free(di);
859 PyErr_SetVim(_("failed to add key to dictionary"));
860 return -1;
861 }
862 }
863 else
864 clear_tv(&di->di_tv);
865
866 DICTKEY_UNREF
867
868 copy_tv(&tv, &di->di_tv);
869 return 0;
870}
871
872 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +0200873DictionaryListKeys(DictionaryObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +0200874{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200875 dict_T *dict = self->dict;
Bram Moolenaardb913952012-06-29 12:54:53 +0200876 long_u todo = dict->dv_hashtab.ht_used;
877 Py_ssize_t i = 0;
878 PyObject *r;
879 hashitem_T *hi;
880
881 r = PyList_New(todo);
882 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
883 {
884 if (!HASHITEM_EMPTY(hi))
885 {
886 PyList_SetItem(r, i, PyBytes_FromString((char *)(hi->hi_key)));
887 --todo;
888 ++i;
889 }
890 }
891 return r;
892}
893
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +0200894static PyMappingMethods DictionaryAsMapping = {
895 (lenfunc) DictionaryLength,
896 (binaryfunc) DictionaryItem,
897 (objobjargproc) DictionaryAssItem,
898};
899
Bram Moolenaardb913952012-06-29 12:54:53 +0200900static struct PyMethodDef DictionaryMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +0200901 {"keys", (PyCFunction)DictionaryListKeys, METH_NOARGS, ""},
902 { NULL, NULL, 0, NULL }
Bram Moolenaardb913952012-06-29 12:54:53 +0200903};
904
905static PyTypeObject ListType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200906static PySequenceMethods ListAsSeq;
907static PyMappingMethods ListAsMapping;
Bram Moolenaardb913952012-06-29 12:54:53 +0200908
909typedef struct
910{
911 PyObject_HEAD
912 list_T *list;
913 pylinkedlist_T ref;
914} ListObject;
915
916 static PyObject *
917ListNew(list_T *list)
918{
919 ListObject *self;
920
921 self = PyObject_NEW(ListObject, &ListType);
922 if (self == NULL)
923 return NULL;
924 self->list = list;
925 ++list->lv_refcount;
926
927 pyll_add((PyObject *)(self), &self->ref, &lastlist);
928
929 return (PyObject *)(self);
930}
931
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200932 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +0200933ListDestructor(ListObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200934{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200935 pyll_remove(&self->ref, &lastlist);
936 list_unref(self->list);
Bram Moolenaar4d1da492013-04-24 13:39:15 +0200937
938 DESTRUCTOR_FINISH(self);
939}
940
Bram Moolenaardb913952012-06-29 12:54:53 +0200941 static int
942list_py_concat(list_T *l, PyObject *obj, PyObject *lookupDict)
943{
944 Py_ssize_t i;
945 Py_ssize_t lsize = PySequence_Size(obj);
946 PyObject *litem;
947 listitem_T *li;
948
949 for(i=0; i<lsize; i++)
950 {
951 li = listitem_alloc();
952 if (li == NULL)
953 {
954 PyErr_NoMemory();
955 return -1;
956 }
957 li->li_tv.v_lock = 0;
958
959 litem = PySequence_GetItem(obj, i);
960 if (litem == NULL)
961 return -1;
962 if (_ConvertFromPyObject(litem, &li->li_tv, lookupDict) == -1)
963 return -1;
964
965 list_append(l, li);
966 }
967 return 0;
968}
969
Bram Moolenaardb913952012-06-29 12:54:53 +0200970 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +0200971ListLength(ListObject *self)
Bram Moolenaardb913952012-06-29 12:54:53 +0200972{
Bram Moolenaard6e39182013-05-21 18:30:34 +0200973 return ((PyInt) (self->list->lv_len));
Bram Moolenaardb913952012-06-29 12:54:53 +0200974}
975
976 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +0200977ListItem(ListObject *self, Py_ssize_t index)
Bram Moolenaardb913952012-06-29 12:54:53 +0200978{
979 listitem_T *li;
980
Bram Moolenaard6e39182013-05-21 18:30:34 +0200981 if (index >= ListLength(self))
Bram Moolenaardb913952012-06-29 12:54:53 +0200982 {
Bram Moolenaar8661b172013-05-15 15:44:28 +0200983 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +0200984 return NULL;
985 }
Bram Moolenaard6e39182013-05-21 18:30:34 +0200986 li = list_find(self->list, (long) index);
Bram Moolenaardb913952012-06-29 12:54:53 +0200987 if (li == NULL)
988 {
989 PyErr_SetVim(_("internal error: failed to get vim list item"));
990 return NULL;
991 }
992 return ConvertToPyObject(&li->li_tv);
993}
994
995#define PROC_RANGE \
996 if (last < 0) {\
997 if (last < -size) \
998 last = 0; \
999 else \
1000 last += size; \
1001 } \
1002 if (first < 0) \
1003 first = 0; \
1004 if (first > size) \
1005 first = size; \
1006 if (last > size) \
1007 last = size;
1008
1009 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001010ListSlice(ListObject *self, Py_ssize_t first, Py_ssize_t last)
Bram Moolenaardb913952012-06-29 12:54:53 +02001011{
1012 PyInt i;
1013 PyInt size = ListLength(self);
1014 PyInt n;
1015 PyObject *list;
1016 int reversed = 0;
1017
1018 PROC_RANGE
1019 if (first >= last)
1020 first = last;
1021
1022 n = last-first;
1023 list = PyList_New(n);
1024 if (list == NULL)
1025 return NULL;
1026
1027 for (i = 0; i < n; ++i)
1028 {
Bram Moolenaar24b11fb2013-04-05 19:32:36 +02001029 PyObject *item = ListItem(self, first + i);
Bram Moolenaardb913952012-06-29 12:54:53 +02001030 if (item == NULL)
1031 {
1032 Py_DECREF(list);
1033 return NULL;
1034 }
1035
1036 if ((PyList_SetItem(list, ((reversed)?(n-i-1):(i)), item)))
1037 {
1038 Py_DECREF(item);
1039 Py_DECREF(list);
1040 return NULL;
1041 }
1042 }
1043
1044 return list;
1045}
1046
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001047typedef struct
1048{
1049 listwatch_T lw;
1050 list_T *list;
1051} listiterinfo_T;
1052
1053 static void
1054ListIterDestruct(listiterinfo_T *lii)
1055{
1056 list_rem_watch(lii->list, &lii->lw);
1057 PyMem_Free(lii);
1058}
1059
1060 static PyObject *
1061ListIterNext(listiterinfo_T **lii)
1062{
1063 PyObject *r;
1064
1065 if (!((*lii)->lw.lw_item))
1066 return NULL;
1067
1068 if (!(r = ConvertToPyObject(&((*lii)->lw.lw_item->li_tv))))
1069 return NULL;
1070
1071 (*lii)->lw.lw_item = (*lii)->lw.lw_item->li_next;
1072
1073 return r;
1074}
1075
1076 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001077ListIter(ListObject *self)
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001078{
1079 listiterinfo_T *lii;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001080 list_T *l = self->list;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001081
1082 if (!(lii = PyMem_New(listiterinfo_T, 1)))
1083 {
1084 PyErr_NoMemory();
1085 return NULL;
1086 }
1087
1088 list_add_watch(l, &lii->lw);
1089 lii->lw.lw_item = l->lv_first;
1090 lii->list = l;
1091
1092 return IterNew(lii,
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001093 (destructorfun) ListIterDestruct, (nextfun) ListIterNext,
1094 NULL, NULL);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02001095}
1096
Bram Moolenaardb913952012-06-29 12:54:53 +02001097 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001098ListAssItem(ListObject *self, Py_ssize_t index, PyObject *obj)
Bram Moolenaardb913952012-06-29 12:54:53 +02001099{
1100 typval_T tv;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001101 list_T *l = self->list;
Bram Moolenaardb913952012-06-29 12:54:53 +02001102 listitem_T *li;
1103 Py_ssize_t length = ListLength(self);
1104
1105 if (l->lv_lock)
1106 {
1107 PyErr_SetVim(_("list is locked"));
1108 return -1;
1109 }
1110 if (index>length || (index==length && obj==NULL))
1111 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001112 PyErr_SetString(PyExc_IndexError, _("list index out of range"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001113 return -1;
1114 }
1115
1116 if (obj == NULL)
1117 {
1118 li = list_find(l, (long) index);
1119 list_remove(l, li, li);
1120 clear_tv(&li->li_tv);
1121 vim_free(li);
1122 return 0;
1123 }
1124
1125 if (ConvertFromPyObject(obj, &tv) == -1)
1126 return -1;
1127
1128 if (index == length)
1129 {
1130 if (list_append_tv(l, &tv) == FAIL)
1131 {
1132 PyErr_SetVim(_("Failed to add item to list"));
1133 return -1;
1134 }
1135 }
1136 else
1137 {
1138 li = list_find(l, (long) index);
1139 clear_tv(&li->li_tv);
1140 copy_tv(&tv, &li->li_tv);
1141 }
1142 return 0;
1143}
1144
1145 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001146ListAssSlice(ListObject *self, Py_ssize_t first, Py_ssize_t last, PyObject *obj)
Bram Moolenaardb913952012-06-29 12:54:53 +02001147{
1148 PyInt size = ListLength(self);
1149 Py_ssize_t i;
1150 Py_ssize_t lsize;
1151 PyObject *litem;
1152 listitem_T *li;
1153 listitem_T *next;
1154 typval_T v;
Bram Moolenaard6e39182013-05-21 18:30:34 +02001155 list_T *l = self->list;
Bram Moolenaardb913952012-06-29 12:54:53 +02001156
1157 if (l->lv_lock)
1158 {
1159 PyErr_SetVim(_("list is locked"));
1160 return -1;
1161 }
1162
1163 PROC_RANGE
1164
1165 if (first == size)
1166 li = NULL;
1167 else
1168 {
1169 li = list_find(l, (long) first);
1170 if (li == NULL)
1171 {
1172 PyErr_SetVim(_("internal error: no vim list item"));
1173 return -1;
1174 }
1175 if (last > first)
1176 {
1177 i = last - first;
1178 while (i-- && li != NULL)
1179 {
1180 next = li->li_next;
1181 listitem_remove(l, li);
1182 li = next;
1183 }
1184 }
1185 }
1186
1187 if (obj == NULL)
1188 return 0;
1189
1190 if (!PyList_Check(obj))
1191 {
1192 PyErr_SetString(PyExc_TypeError, _("can only assign lists to slice"));
1193 return -1;
1194 }
1195
1196 lsize = PyList_Size(obj);
1197
1198 for(i=0; i<lsize; i++)
1199 {
1200 litem = PyList_GetItem(obj, i);
1201 if (litem == NULL)
1202 return -1;
1203 if (ConvertFromPyObject(litem, &v) == -1)
1204 return -1;
1205 if (list_insert_tv(l, &v, li) == FAIL)
1206 {
1207 PyErr_SetVim(_("internal error: failed to add item to list"));
1208 return -1;
1209 }
1210 }
1211 return 0;
1212}
1213
1214 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001215ListConcatInPlace(ListObject *self, PyObject *obj)
Bram Moolenaardb913952012-06-29 12:54:53 +02001216{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001217 list_T *l = self->list;
Bram Moolenaardb913952012-06-29 12:54:53 +02001218 PyObject *lookup_dict;
1219
1220 if (l->lv_lock)
1221 {
1222 PyErr_SetVim(_("list is locked"));
1223 return NULL;
1224 }
1225
1226 if (!PySequence_Check(obj))
1227 {
1228 PyErr_SetString(PyExc_TypeError, _("can only concatenate with lists"));
1229 return NULL;
1230 }
1231
1232 lookup_dict = PyDict_New();
1233 if (list_py_concat(l, obj, lookup_dict) == -1)
1234 {
1235 Py_DECREF(lookup_dict);
1236 return NULL;
1237 }
1238 Py_DECREF(lookup_dict);
1239
1240 Py_INCREF(self);
Bram Moolenaard6e39182013-05-21 18:30:34 +02001241 return (PyObject *)(self);
Bram Moolenaardb913952012-06-29 12:54:53 +02001242}
1243
Bram Moolenaar66b79852012-09-21 14:00:35 +02001244 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001245ListSetattr(ListObject *self, char *name, PyObject *val)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001246{
1247 if (val == NULL)
1248 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001249 PyErr_SetString(PyExc_AttributeError,
1250 _("cannot delete vim.dictionary attributes"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001251 return -1;
1252 }
1253
1254 if (strcmp(name, "locked") == 0)
1255 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001256 if (self->list->lv_lock == VAR_FIXED)
Bram Moolenaar66b79852012-09-21 14:00:35 +02001257 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001258 PyErr_SetString(PyExc_TypeError, _("cannot modify fixed list"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001259 return -1;
1260 }
1261 else
1262 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02001263 int istrue = PyObject_IsTrue(val);
1264 if (istrue == -1)
1265 return -1;
1266 else if (istrue)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001267 self->list->lv_lock = VAR_LOCKED;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001268 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02001269 self->list->lv_lock = 0;
Bram Moolenaar66b79852012-09-21 14:00:35 +02001270 }
1271 return 0;
1272 }
1273 else
1274 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001275 PyErr_SetString(PyExc_AttributeError, _("cannot set this attribute"));
Bram Moolenaar66b79852012-09-21 14:00:35 +02001276 return -1;
1277 }
1278}
1279
Bram Moolenaardb913952012-06-29 12:54:53 +02001280static struct PyMethodDef ListMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02001281 {"extend", (PyCFunction)ListConcatInPlace, METH_O, ""},
1282 { NULL, NULL, 0, NULL }
Bram Moolenaardb913952012-06-29 12:54:53 +02001283};
1284
1285typedef struct
1286{
1287 PyObject_HEAD
1288 char_u *name;
1289} FunctionObject;
1290
1291static PyTypeObject FunctionType;
1292
1293 static PyObject *
1294FunctionNew(char_u *name)
1295{
1296 FunctionObject *self;
1297
1298 self = PyObject_NEW(FunctionObject, &FunctionType);
1299 if (self == NULL)
1300 return NULL;
1301 self->name = PyMem_New(char_u, STRLEN(name) + 1);
1302 if (self->name == NULL)
1303 {
1304 PyErr_NoMemory();
1305 return NULL;
1306 }
1307 STRCPY(self->name, name);
1308 func_ref(name);
1309 return (PyObject *)(self);
1310}
1311
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001312 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02001313FunctionDestructor(FunctionObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001314{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001315 func_unref(self->name);
1316 PyMem_Free(self->name);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001317
1318 DESTRUCTOR_FINISH(self);
1319}
1320
Bram Moolenaardb913952012-06-29 12:54:53 +02001321 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001322FunctionCall(FunctionObject *self, PyObject *argsObject, PyObject *kwargs)
Bram Moolenaardb913952012-06-29 12:54:53 +02001323{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001324 char_u *name = self->name;
Bram Moolenaardb913952012-06-29 12:54:53 +02001325 typval_T args;
1326 typval_T selfdicttv;
1327 typval_T rettv;
1328 dict_T *selfdict = NULL;
1329 PyObject *selfdictObject;
1330 PyObject *result;
1331 int error;
1332
1333 if (ConvertFromPyObject(argsObject, &args) == -1)
1334 return NULL;
1335
1336 if (kwargs != NULL)
1337 {
1338 selfdictObject = PyDict_GetItemString(kwargs, "self");
1339 if (selfdictObject != NULL)
1340 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001341 if (!PyMapping_Check(selfdictObject))
Bram Moolenaardb913952012-06-29 12:54:53 +02001342 {
Bram Moolenaar9581b5f2012-07-25 15:36:04 +02001343 PyErr_SetString(PyExc_TypeError,
1344 _("'self' argument must be a dictionary"));
Bram Moolenaardb913952012-06-29 12:54:53 +02001345 clear_tv(&args);
1346 return NULL;
1347 }
1348 if (ConvertFromPyObject(selfdictObject, &selfdicttv) == -1)
1349 return NULL;
1350 selfdict = selfdicttv.vval.v_dict;
1351 }
1352 }
1353
Bram Moolenaar71700b82013-05-15 17:49:05 +02001354 Py_BEGIN_ALLOW_THREADS
1355 Python_Lock_Vim();
1356
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001357 VimTryStart();
Bram Moolenaardb913952012-06-29 12:54:53 +02001358 error = func_call(name, &args, selfdict, &rettv);
Bram Moolenaar71700b82013-05-15 17:49:05 +02001359
1360 Python_Release_Vim();
1361 Py_END_ALLOW_THREADS
1362
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001363 if (VimTryEnd())
1364 result = NULL;
1365 else if (error != OK)
Bram Moolenaardb913952012-06-29 12:54:53 +02001366 {
1367 result = NULL;
1368 PyErr_SetVim(_("failed to run function"));
1369 }
1370 else
1371 result = ConvertToPyObject(&rettv);
1372
1373 /* FIXME Check what should really be cleared. */
1374 clear_tv(&args);
1375 clear_tv(&rettv);
1376 /*
1377 * if (selfdict!=NULL)
1378 * clear_tv(selfdicttv);
1379 */
1380
1381 return result;
1382}
1383
1384static struct PyMethodDef FunctionMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02001385 {"__call__", (PyCFunction)FunctionCall, METH_VARARGS|METH_KEYWORDS, ""},
1386 { NULL, NULL, 0, NULL}
Bram Moolenaardb913952012-06-29 12:54:53 +02001387};
1388
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001389/*
1390 * Options object
1391 */
1392
1393static PyTypeObject OptionsType;
1394
1395typedef int (*checkfun)(void *);
1396
1397typedef struct
1398{
1399 PyObject_HEAD
1400 int opt_type;
1401 void *from;
1402 checkfun Check;
1403 PyObject *fromObj;
1404} OptionsObject;
1405
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001406 static int
1407dummy_check(void *arg UNUSED)
1408{
1409 return 0;
1410}
1411
1412 static PyObject *
1413OptionsNew(int opt_type, void *from, checkfun Check, PyObject *fromObj)
1414{
1415 OptionsObject *self;
1416
Bram Moolenaar774267b2013-05-21 20:51:59 +02001417 self = PyObject_GC_New(OptionsObject, &OptionsType);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001418 if (self == NULL)
1419 return NULL;
1420
1421 self->opt_type = opt_type;
1422 self->from = from;
1423 self->Check = Check;
1424 self->fromObj = fromObj;
1425 if (fromObj)
1426 Py_INCREF(fromObj);
1427
1428 return (PyObject *)(self);
1429}
1430
1431 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02001432OptionsDestructor(OptionsObject *self)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001433{
Bram Moolenaar774267b2013-05-21 20:51:59 +02001434 PyObject_GC_UnTrack((void *)(self));
1435 Py_XDECREF(self->fromObj);
1436 PyObject_GC_Del((void *)(self));
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001437}
1438
1439 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001440OptionsTraverse(OptionsObject *self, visitproc visit, void *arg)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001441{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001442 Py_VISIT(self->fromObj);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001443 return 0;
1444}
1445
1446 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001447OptionsClear(OptionsObject *self)
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001448{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001449 Py_CLEAR(self->fromObj);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02001450 return 0;
1451}
1452
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001453 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001454OptionsItem(OptionsObject *self, PyObject *keyObject)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001455{
1456 char_u *key;
1457 int flags;
1458 long numval;
1459 char_u *stringval;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001460 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001461
Bram Moolenaard6e39182013-05-21 18:30:34 +02001462 if (self->Check(self->from))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001463 return NULL;
1464
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001465 DICTKEY_GET_NOTEMPTY(NULL)
1466
1467 flags = get_option_value_strict(key, &numval, &stringval,
Bram Moolenaard6e39182013-05-21 18:30:34 +02001468 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001469
1470 DICTKEY_UNREF
1471
1472 if (flags == 0)
1473 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001474 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001475 return NULL;
1476 }
1477
1478 if (flags & SOPT_UNSET)
1479 {
1480 Py_INCREF(Py_None);
1481 return Py_None;
1482 }
1483 else if (flags & SOPT_BOOL)
1484 {
1485 PyObject *r;
1486 r = numval ? Py_True : Py_False;
1487 Py_INCREF(r);
1488 return r;
1489 }
1490 else if (flags & SOPT_NUM)
1491 return PyInt_FromLong(numval);
1492 else if (flags & SOPT_STRING)
1493 {
1494 if (stringval)
1495 return PyBytes_FromString((char *) stringval);
1496 else
1497 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001498 PyErr_SetString(PyExc_RuntimeError,
1499 _("unable to get option value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001500 return NULL;
1501 }
1502 }
1503 else
1504 {
1505 PyErr_SetVim("Internal error: unknown option type. Should not happen");
1506 return NULL;
1507 }
1508}
1509
1510 static int
1511set_option_value_for(key, numval, stringval, opt_flags, opt_type, from)
1512 char_u *key;
1513 int numval;
1514 char_u *stringval;
1515 int opt_flags;
1516 int opt_type;
1517 void *from;
1518{
1519 win_T *save_curwin;
1520 tabpage_T *save_curtab;
Bram Moolenaar105bc352013-05-17 16:03:57 +02001521 buf_T *save_curbuf;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001522
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001523 VimTryStart();
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001524 switch (opt_type)
1525 {
1526 case SREQ_WIN:
Bram Moolenaar105bc352013-05-17 16:03:57 +02001527 if (switch_win(&save_curwin, &save_curtab, (win_T *)from,
1528 win_find_tabpage((win_T *)from)) == FAIL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001529 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001530 if (VimTryEnd())
1531 return -1;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001532 PyErr_SetVim("Problem while switching windows.");
1533 return -1;
1534 }
1535 set_option_value(key, numval, stringval, opt_flags);
1536 restore_win(save_curwin, save_curtab);
1537 break;
1538 case SREQ_BUF:
Bram Moolenaar105bc352013-05-17 16:03:57 +02001539 switch_buffer(&save_curbuf, (buf_T *)from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001540 set_option_value(key, numval, stringval, opt_flags);
Bram Moolenaar105bc352013-05-17 16:03:57 +02001541 restore_buffer(save_curbuf);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001542 break;
1543 case SREQ_GLOBAL:
1544 set_option_value(key, numval, stringval, opt_flags);
1545 break;
1546 }
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001547 return VimTryEnd();
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001548}
1549
1550 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001551OptionsAssItem(OptionsObject *self, PyObject *keyObject, PyObject *valObject)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001552{
1553 char_u *key;
1554 int flags;
1555 int opt_flags;
1556 int r = 0;
Bram Moolenaar161fb5e2013-05-06 06:26:15 +02001557 DICTKEY_DECL
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001558
Bram Moolenaard6e39182013-05-21 18:30:34 +02001559 if (self->Check(self->from))
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001560 return -1;
1561
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001562 DICTKEY_GET_NOTEMPTY(-1)
1563
1564 flags = get_option_value_strict(key, NULL, NULL,
Bram Moolenaard6e39182013-05-21 18:30:34 +02001565 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001566
1567 DICTKEY_UNREF
1568
1569 if (flags == 0)
1570 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02001571 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001572 return -1;
1573 }
1574
1575 if (valObject == NULL)
1576 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001577 if (self->opt_type == SREQ_GLOBAL)
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001578 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001579 PyErr_SetString(PyExc_ValueError,
1580 _("unable to unset global option"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001581 return -1;
1582 }
1583 else if (!(flags & SOPT_GLOBAL))
1584 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001585 PyErr_SetString(PyExc_ValueError, _("unable to unset option "
1586 "without global value"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001587 return -1;
1588 }
1589 else
1590 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001591 unset_global_local_option(key, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001592 return 0;
1593 }
1594 }
1595
Bram Moolenaard6e39182013-05-21 18:30:34 +02001596 opt_flags = (self->opt_type ? OPT_LOCAL : OPT_GLOBAL);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001597
1598 if (flags & SOPT_BOOL)
1599 {
Bram Moolenaarb983f752013-05-15 16:11:50 +02001600 int istrue = PyObject_IsTrue(valObject);
1601 if (istrue == -1)
1602 return -1;
1603 r = set_option_value_for(key, istrue, NULL,
Bram Moolenaard6e39182013-05-21 18:30:34 +02001604 opt_flags, self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001605 }
1606 else if (flags & SOPT_NUM)
1607 {
1608 int val;
1609
1610#if PY_MAJOR_VERSION < 3
1611 if (PyInt_Check(valObject))
1612 val = PyInt_AsLong(valObject);
1613 else
1614#endif
1615 if (PyLong_Check(valObject))
1616 val = PyLong_AsLong(valObject);
1617 else
1618 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001619 PyErr_SetString(PyExc_TypeError, _("object must be integer"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001620 return -1;
1621 }
1622
1623 r = set_option_value_for(key, val, NULL, opt_flags,
Bram Moolenaard6e39182013-05-21 18:30:34 +02001624 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001625 }
1626 else
1627 {
1628 char_u *val;
1629 if (PyBytes_Check(valObject))
1630 {
1631
1632 if (PyString_AsStringAndSize(valObject, (char **) &val, NULL) == -1)
1633 return -1;
1634 if (val == NULL)
1635 return -1;
1636
1637 val = vim_strsave(val);
1638 }
1639 else if (PyUnicode_Check(valObject))
1640 {
1641 PyObject *bytes;
1642
1643 bytes = PyUnicode_AsEncodedString(valObject, (char *)ENC_OPT, NULL);
1644 if (bytes == NULL)
1645 return -1;
1646
1647 if(PyString_AsStringAndSize(bytes, (char **) &val, NULL) == -1)
1648 return -1;
1649 if (val == NULL)
1650 return -1;
1651
1652 val = vim_strsave(val);
1653 Py_XDECREF(bytes);
1654 }
1655 else
1656 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02001657 PyErr_SetString(PyExc_TypeError, _("object must be string"));
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001658 return -1;
1659 }
1660
1661 r = set_option_value_for(key, 0, val, opt_flags,
Bram Moolenaard6e39182013-05-21 18:30:34 +02001662 self->opt_type, self->from);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001663 vim_free(val);
1664 }
1665
1666 return r;
1667}
1668
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001669static PyMappingMethods OptionsAsMapping = {
1670 (lenfunc) NULL,
1671 (binaryfunc) OptionsItem,
1672 (objobjargproc) OptionsAssItem,
1673};
1674
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001675/* Tabpage object
1676 */
1677
1678typedef struct
1679{
1680 PyObject_HEAD
1681 tabpage_T *tab;
1682} TabPageObject;
1683
1684static PyObject *WinListNew(TabPageObject *tabObject);
1685
1686static PyTypeObject TabPageType;
1687
1688 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001689CheckTabPage(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001690{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001691 if (self->tab == INVALID_TABPAGE_VALUE)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001692 {
1693 PyErr_SetVim(_("attempt to refer to deleted tab page"));
1694 return -1;
1695 }
1696
1697 return 0;
1698}
1699
1700 static PyObject *
1701TabPageNew(tabpage_T *tab)
1702{
1703 TabPageObject *self;
1704
1705 if (TAB_PYTHON_REF(tab))
1706 {
1707 self = TAB_PYTHON_REF(tab);
1708 Py_INCREF(self);
1709 }
1710 else
1711 {
1712 self = PyObject_NEW(TabPageObject, &TabPageType);
1713 if (self == NULL)
1714 return NULL;
1715 self->tab = tab;
1716 TAB_PYTHON_REF(tab) = self;
1717 }
1718
1719 return (PyObject *)(self);
1720}
1721
1722 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02001723TabPageDestructor(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001724{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001725 if (self->tab && self->tab != INVALID_TABPAGE_VALUE)
1726 TAB_PYTHON_REF(self->tab) = NULL;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001727
1728 DESTRUCTOR_FINISH(self);
1729}
1730
1731 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001732TabPageAttr(TabPageObject *self, char *name)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001733{
1734 if (strcmp(name, "windows") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001735 return WinListNew(self);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001736 else if (strcmp(name, "number") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001737 return PyLong_FromLong((long) get_tab_number(self->tab));
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001738 else if (strcmp(name, "vars") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001739 return DictionaryNew(self->tab->tp_vars);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001740 else if (strcmp(name, "window") == 0)
1741 {
1742 /* For current tab window.c does not bother to set or update tp_curwin
1743 */
Bram Moolenaard6e39182013-05-21 18:30:34 +02001744 if (self->tab == curtab)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001745 return WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001746 else
Bram Moolenaard6e39182013-05-21 18:30:34 +02001747 return WindowNew(self->tab->tp_curwin, self->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001748 }
1749 return NULL;
1750}
1751
1752 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001753TabPageRepr(TabPageObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001754{
1755 static char repr[100];
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001756
Bram Moolenaard6e39182013-05-21 18:30:34 +02001757 if (self->tab == INVALID_TABPAGE_VALUE)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001758 {
1759 vim_snprintf(repr, 100, _("<tabpage object (deleted) at %p>"), (self));
1760 return PyString_FromString(repr);
1761 }
1762 else
1763 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001764 int t = get_tab_number(self->tab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02001765
1766 if (t == 0)
1767 vim_snprintf(repr, 100, _("<tabpage object (unknown) at %p>"),
1768 (self));
1769 else
1770 vim_snprintf(repr, 100, _("<tabpage %d>"), t - 1);
1771
1772 return PyString_FromString(repr);
1773 }
1774}
1775
1776static struct PyMethodDef TabPageMethods[] = {
1777 /* name, function, calling, documentation */
1778 { NULL, NULL, 0, NULL }
1779};
1780
1781/*
1782 * Window list object
1783 */
1784
1785static PyTypeObject TabListType;
1786static PySequenceMethods TabListAsSeq;
1787
1788typedef struct
1789{
1790 PyObject_HEAD
1791} TabListObject;
1792
1793 static PyInt
1794TabListLength(PyObject *self UNUSED)
1795{
1796 tabpage_T *tp = first_tabpage;
1797 PyInt n = 0;
1798
1799 while (tp != NULL)
1800 {
1801 ++n;
1802 tp = tp->tp_next;
1803 }
1804
1805 return n;
1806}
1807
1808 static PyObject *
1809TabListItem(PyObject *self UNUSED, PyInt n)
1810{
1811 tabpage_T *tp;
1812
1813 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next, --n)
1814 if (n == 0)
1815 return TabPageNew(tp);
1816
1817 PyErr_SetString(PyExc_IndexError, _("no such tab page"));
1818 return NULL;
1819}
1820
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001821/* Window object
1822 */
1823
1824typedef struct
1825{
1826 PyObject_HEAD
1827 win_T *win;
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001828 TabPageObject *tabObject;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001829} WindowObject;
1830
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001831static PyTypeObject WindowType;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001832
1833 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001834CheckWindow(WindowObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001835{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001836 if (self->win == INVALID_WINDOW_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001837 {
1838 PyErr_SetVim(_("attempt to refer to deleted window"));
1839 return -1;
1840 }
1841
1842 return 0;
1843}
1844
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001845 static PyObject *
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001846WindowNew(win_T *win, tabpage_T *tab)
Bram Moolenaar971db462013-05-12 18:44:48 +02001847{
1848 /* We need to handle deletion of windows underneath us.
1849 * If we add a "w_python*_ref" field to the win_T structure,
1850 * then we can get at it in win_free() in vim. We then
1851 * need to create only ONE Python object per window - if
1852 * we try to create a second, just INCREF the existing one
1853 * and return it. The (single) Python object referring to
1854 * the window is stored in "w_python*_ref".
1855 * On a win_free() we set the Python object's win_T* field
1856 * to an invalid value. We trap all uses of a window
1857 * object, and reject them if the win_T* field is invalid.
1858 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001859 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02001860 * w_python_ref and w_python3_ref fields respectively.
1861 */
1862
1863 WindowObject *self;
1864
1865 if (WIN_PYTHON_REF(win))
1866 {
1867 self = WIN_PYTHON_REF(win);
1868 Py_INCREF(self);
1869 }
1870 else
1871 {
Bram Moolenaar774267b2013-05-21 20:51:59 +02001872 self = PyObject_GC_New(WindowObject, &WindowType);
Bram Moolenaar971db462013-05-12 18:44:48 +02001873 if (self == NULL)
1874 return NULL;
1875 self->win = win;
1876 WIN_PYTHON_REF(win) = self;
1877 }
1878
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001879 self->tabObject = ((TabPageObject *)(TabPageNew(tab)));
1880
Bram Moolenaar971db462013-05-12 18:44:48 +02001881 return (PyObject *)(self);
1882}
1883
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001884 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02001885WindowDestructor(WindowObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001886{
Bram Moolenaar774267b2013-05-21 20:51:59 +02001887 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaard6e39182013-05-21 18:30:34 +02001888 if (self->win && self->win != INVALID_WINDOW_VALUE)
1889 WIN_PYTHON_REF(self->win) = NULL;
Bram Moolenaar774267b2013-05-21 20:51:59 +02001890 Py_XDECREF(((PyObject *)(self->tabObject)));
1891 PyObject_GC_Del((void *)(self));
1892}
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001893
Bram Moolenaar774267b2013-05-21 20:51:59 +02001894 static int
1895WindowTraverse(WindowObject *self, visitproc visit, void *arg)
1896{
1897 Py_VISIT(((PyObject *)(self->tabObject)));
1898 return 0;
1899}
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001900
Bram Moolenaar774267b2013-05-21 20:51:59 +02001901 static int
1902WindowClear(WindowObject *self)
1903{
1904 Py_CLEAR(self->tabObject);
1905 return 0;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02001906}
1907
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001908 static win_T *
1909get_firstwin(TabPageObject *tabObject)
1910{
1911 if (tabObject)
1912 {
1913 if (CheckTabPage(tabObject))
1914 return NULL;
1915 /* For current tab window.c does not bother to set or update tp_firstwin
1916 */
1917 else if (tabObject->tab == curtab)
1918 return firstwin;
1919 else
1920 return tabObject->tab->tp_firstwin;
1921 }
1922 else
1923 return firstwin;
1924}
1925
Bram Moolenaar971db462013-05-12 18:44:48 +02001926 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02001927WindowAttr(WindowObject *self, char *name)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001928{
1929 if (strcmp(name, "buffer") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001930 return (PyObject *)BufferNew(self->win->w_buffer);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001931 else if (strcmp(name, "cursor") == 0)
1932 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001933 pos_T *pos = &self->win->w_cursor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001934
1935 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col));
1936 }
1937 else if (strcmp(name, "height") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001938 return PyLong_FromLong((long)(self->win->w_height));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001939#ifdef FEAT_WINDOWS
1940 else if (strcmp(name, "row") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001941 return PyLong_FromLong((long)(self->win->w_winrow));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001942#endif
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001943#ifdef FEAT_VERTSPLIT
1944 else if (strcmp(name, "width") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001945 return PyLong_FromLong((long)(W_WIDTH(self->win)));
Bram Moolenaar4e5dfb52013-05-12 19:30:31 +02001946 else if (strcmp(name, "col") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001947 return PyLong_FromLong((long)(W_WINCOL(self->win)));
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001948#endif
Bram Moolenaar230bb3f2013-04-24 14:07:45 +02001949 else if (strcmp(name, "vars") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001950 return DictionaryNew(self->win->w_vars);
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02001951 else if (strcmp(name, "options") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001952 return OptionsNew(SREQ_WIN, self->win, (checkfun) CheckWindow,
1953 (PyObject *) self);
Bram Moolenaar6d216452013-05-12 19:00:41 +02001954 else if (strcmp(name, "number") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001955 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001956 if (CheckTabPage(self->tabObject))
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001957 return NULL;
1958 return PyLong_FromLong((long)
Bram Moolenaard6e39182013-05-21 18:30:34 +02001959 get_win_number(self->win, get_firstwin(self->tabObject)));
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001960 }
1961 else if (strcmp(name, "tabpage") == 0)
1962 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02001963 Py_INCREF(self->tabObject);
1964 return (PyObject *)(self->tabObject);
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001965 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001966 else if (strcmp(name,"__members__") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02001967 return Py_BuildValue("[sssssssss]", "buffer", "cursor", "height",
1968 "vars", "options", "number", "row", "col", "tabpage");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02001969 else
1970 return NULL;
1971}
1972
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001973 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02001974WindowSetattr(WindowObject *self, char *name, PyObject *val)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001975{
Bram Moolenaard6e39182013-05-21 18:30:34 +02001976 if (CheckWindow(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001977 return -1;
1978
1979 if (strcmp(name, "buffer") == 0)
1980 {
1981 PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
1982 return -1;
1983 }
1984 else if (strcmp(name, "cursor") == 0)
1985 {
1986 long lnum;
1987 long col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001988
1989 if (!PyArg_Parse(val, "(ll)", &lnum, &col))
1990 return -1;
1991
Bram Moolenaard6e39182013-05-21 18:30:34 +02001992 if (lnum <= 0 || lnum > self->win->w_buffer->b_ml.ml_line_count)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02001993 {
1994 PyErr_SetVim(_("cursor position outside buffer"));
1995 return -1;
1996 }
1997
1998 /* Check for keyboard interrupts */
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02001999 if (VimCheckInterrupt())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002000 return -1;
2001
Bram Moolenaard6e39182013-05-21 18:30:34 +02002002 self->win->w_cursor.lnum = lnum;
2003 self->win->w_cursor.col = col;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002004#ifdef FEAT_VIRTUALEDIT
Bram Moolenaard6e39182013-05-21 18:30:34 +02002005 self->win->w_cursor.coladd = 0;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002006#endif
Bram Moolenaar03a807a2011-07-07 15:08:58 +02002007 /* When column is out of range silently correct it. */
Bram Moolenaard6e39182013-05-21 18:30:34 +02002008 check_cursor_col_win(self->win);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002009
Bram Moolenaar03a807a2011-07-07 15:08:58 +02002010 update_screen(VALID);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002011 return 0;
2012 }
2013 else if (strcmp(name, "height") == 0)
2014 {
2015 int height;
2016 win_T *savewin;
2017
2018 if (!PyArg_Parse(val, "i", &height))
2019 return -1;
2020
2021#ifdef FEAT_GUI
2022 need_mouse_correct = TRUE;
2023#endif
2024 savewin = curwin;
Bram Moolenaard6e39182013-05-21 18:30:34 +02002025 curwin = self->win;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002026
2027 VimTryStart();
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002028 win_setheight(height);
2029 curwin = savewin;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002030 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002031 return -1;
2032
2033 return 0;
2034 }
2035#ifdef FEAT_VERTSPLIT
2036 else if (strcmp(name, "width") == 0)
2037 {
2038 int width;
2039 win_T *savewin;
2040
2041 if (!PyArg_Parse(val, "i", &width))
2042 return -1;
2043
2044#ifdef FEAT_GUI
2045 need_mouse_correct = TRUE;
2046#endif
2047 savewin = curwin;
Bram Moolenaard6e39182013-05-21 18:30:34 +02002048 curwin = self->win;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002049
2050 VimTryStart();
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002051 win_setwidth(width);
2052 curwin = savewin;
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002053 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002054 return -1;
2055
2056 return 0;
2057 }
2058#endif
2059 else
2060 {
2061 PyErr_SetString(PyExc_AttributeError, name);
2062 return -1;
2063 }
2064}
2065
2066 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02002067WindowRepr(WindowObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002068{
2069 static char repr[100];
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002070
Bram Moolenaard6e39182013-05-21 18:30:34 +02002071 if (self->win == INVALID_WINDOW_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002072 {
2073 vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
2074 return PyString_FromString(repr);
2075 }
2076 else
2077 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02002078 int w = get_win_number(self->win, firstwin);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002079
Bram Moolenaar6d216452013-05-12 19:00:41 +02002080 if (w == 0)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002081 vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
2082 (self));
2083 else
Bram Moolenaar6d216452013-05-12 19:00:41 +02002084 vim_snprintf(repr, 100, _("<window %d>"), w - 1);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002085
2086 return PyString_FromString(repr);
2087 }
2088}
2089
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002090static struct PyMethodDef WindowMethods[] = {
2091 /* name, function, calling, documentation */
2092 { NULL, NULL, 0, NULL }
2093};
2094
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002095/*
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002096 * Window list object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002097 */
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002098
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002099static PyTypeObject WinListType;
2100static PySequenceMethods WinListAsSeq;
2101
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002102typedef struct
2103{
2104 PyObject_HEAD
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002105 TabPageObject *tabObject;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002106} WinListObject;
2107
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002108 static PyObject *
2109WinListNew(TabPageObject *tabObject)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002110{
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002111 WinListObject *self;
2112
2113 self = PyObject_NEW(WinListObject, &WinListType);
2114 self->tabObject = tabObject;
2115 Py_INCREF(tabObject);
2116
2117 return (PyObject *)(self);
2118}
2119
2120 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02002121WinListDestructor(WinListObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002122{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002123 TabPageObject *tabObject = self->tabObject;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002124
2125 if (tabObject)
2126 Py_DECREF((PyObject *)(tabObject));
2127
2128 DESTRUCTOR_FINISH(self);
2129}
2130
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002131 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02002132WinListLength(WinListObject *self)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002133{
2134 win_T *w;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002135 PyInt n = 0;
2136
Bram Moolenaard6e39182013-05-21 18:30:34 +02002137 if (!(w = get_firstwin(self->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002138 return -1;
2139
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002140 while (w != NULL)
2141 {
2142 ++n;
2143 w = W_NEXT(w);
2144 }
2145
2146 return n;
2147}
2148
2149 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02002150WinListItem(WinListObject *self, PyInt n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002151{
2152 win_T *w;
2153
Bram Moolenaard6e39182013-05-21 18:30:34 +02002154 if (!(w = get_firstwin(self->tabObject)))
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02002155 return NULL;
2156
2157 for (; w != NULL; w = W_NEXT(w), --n)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002158 if (n == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02002159 return WindowNew(w, self->tabObject? self->tabObject->tab: curtab);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002160
2161 PyErr_SetString(PyExc_IndexError, _("no such window"));
2162 return NULL;
2163}
2164
2165/* Convert a Python string into a Vim line.
2166 *
2167 * The result is in allocated memory. All internal nulls are replaced by
2168 * newline characters. It is an error for the string to contain newline
2169 * characters.
2170 *
2171 * On errors, the Python exception data is set, and NULL is returned.
2172 */
2173 static char *
2174StringToLine(PyObject *obj)
2175{
2176 const char *str;
2177 char *save;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002178 PyObject *bytes;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002179 PyInt len;
2180 PyInt i;
2181 char *p;
2182
2183 if (obj == NULL || !PyString_Check(obj))
2184 {
2185 PyErr_BadArgument();
2186 return NULL;
2187 }
2188
Bram Moolenaar19e60942011-06-19 00:27:51 +02002189 bytes = PyString_AsBytes(obj); /* for Python 2 this does nothing */
2190 str = PyString_AsString(bytes);
2191 len = PyString_Size(bytes);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002192
2193 /*
2194 * Error checking: String must not contain newlines, as we
2195 * are replacing a single line, and we must replace it with
2196 * a single line.
2197 * A trailing newline is removed, so that append(f.readlines()) works.
2198 */
2199 p = memchr(str, '\n', len);
2200 if (p != NULL)
2201 {
2202 if (p == str + len - 1)
2203 --len;
2204 else
2205 {
2206 PyErr_SetVim(_("string cannot contain newlines"));
2207 return NULL;
2208 }
2209 }
2210
2211 /* Create a copy of the string, with internal nulls replaced by
2212 * newline characters, as is the vim convention.
2213 */
2214 save = (char *)alloc((unsigned)(len+1));
2215 if (save == NULL)
2216 {
2217 PyErr_NoMemory();
2218 return NULL;
2219 }
2220
2221 for (i = 0; i < len; ++i)
2222 {
2223 if (str[i] == '\0')
2224 save[i] = '\n';
2225 else
2226 save[i] = str[i];
2227 }
2228
2229 save[i] = '\0';
Bram Moolenaar19e60942011-06-19 00:27:51 +02002230 PyString_FreeBytes(bytes); /* Python 2 does nothing here */
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002231
2232 return save;
2233}
2234
2235/* Get a line from the specified buffer. The line number is
2236 * in Vim format (1-based). The line is returned as a Python
2237 * string object.
2238 */
2239 static PyObject *
2240GetBufferLine(buf_T *buf, PyInt n)
2241{
2242 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
2243}
2244
2245
2246/* Get a list of lines from the specified buffer. The line numbers
2247 * are in Vim format (1-based). The range is from lo up to, but not
2248 * including, hi. The list is returned as a Python list of string objects.
2249 */
2250 static PyObject *
2251GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
2252{
2253 PyInt i;
2254 PyInt n = hi - lo;
2255 PyObject *list = PyList_New(n);
2256
2257 if (list == NULL)
2258 return NULL;
2259
2260 for (i = 0; i < n; ++i)
2261 {
2262 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
2263
2264 /* Error check - was the Python string creation OK? */
2265 if (str == NULL)
2266 {
2267 Py_DECREF(list);
2268 return NULL;
2269 }
2270
2271 /* Set the list item */
2272 if (PyList_SetItem(list, i, str))
2273 {
2274 Py_DECREF(str);
2275 Py_DECREF(list);
2276 return NULL;
2277 }
2278 }
2279
2280 /* The ownership of the Python list is passed to the caller (ie,
2281 * the caller should Py_DECREF() the object when it is finished
2282 * with it).
2283 */
2284
2285 return list;
2286}
2287
2288/*
2289 * Check if deleting lines made the cursor position invalid.
2290 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2291 * deleted).
2292 */
2293 static void
2294py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
2295{
2296 if (curwin->w_cursor.lnum >= lo)
2297 {
2298 /* Adjust the cursor position if it's in/after the changed
2299 * lines. */
2300 if (curwin->w_cursor.lnum >= hi)
2301 {
2302 curwin->w_cursor.lnum += extra;
2303 check_cursor_col();
2304 }
2305 else if (extra < 0)
2306 {
2307 curwin->w_cursor.lnum = lo;
2308 check_cursor();
2309 }
2310 else
2311 check_cursor_col();
2312 changed_cline_bef_curs();
2313 }
2314 invalidate_botline();
2315}
2316
Bram Moolenaar19e60942011-06-19 00:27:51 +02002317/*
2318 * Replace a line in the specified buffer. The line number is
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002319 * in Vim format (1-based). The replacement line is given as
2320 * a Python string object. The object is checked for validity
2321 * and correct format. Errors are returned as a value of FAIL.
2322 * The return value is OK on success.
2323 * If OK is returned and len_change is not NULL, *len_change
2324 * is set to the change in the buffer length.
2325 */
2326 static int
2327SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
2328{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002329 /* First of all, we check the type of the supplied Python object.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002330 * There are three cases:
2331 * 1. NULL, or None - this is a deletion.
2332 * 2. A string - this is a replacement.
2333 * 3. Anything else - this is an error.
2334 */
2335 if (line == Py_None || line == NULL)
2336 {
Bram Moolenaar105bc352013-05-17 16:03:57 +02002337 buf_T *savebuf;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002338
2339 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002340 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002341
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002342 VimTryStart();
2343
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002344 if (u_savedel((linenr_T)n, 1L) == FAIL)
2345 PyErr_SetVim(_("cannot save undo information"));
2346 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
2347 PyErr_SetVim(_("cannot delete line"));
2348 else
2349 {
Bram Moolenaar105bc352013-05-17 16:03:57 +02002350 if (buf == savebuf)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002351 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
2352 deleted_lines_mark((linenr_T)n, 1L);
2353 }
2354
Bram Moolenaar105bc352013-05-17 16:03:57 +02002355 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002356
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002357 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002358 return FAIL;
2359
2360 if (len_change)
2361 *len_change = -1;
2362
2363 return OK;
2364 }
2365 else if (PyString_Check(line))
2366 {
2367 char *save = StringToLine(line);
Bram Moolenaar105bc352013-05-17 16:03:57 +02002368 buf_T *savebuf;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002369
2370 if (save == NULL)
2371 return FAIL;
2372
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002373 VimTryStart();
2374
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002375 /* We do not need to free "save" if ml_replace() consumes it. */
2376 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002377 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002378
2379 if (u_savesub((linenr_T)n) == FAIL)
2380 {
2381 PyErr_SetVim(_("cannot save undo information"));
2382 vim_free(save);
2383 }
2384 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
2385 {
2386 PyErr_SetVim(_("cannot replace line"));
2387 vim_free(save);
2388 }
2389 else
2390 changed_bytes((linenr_T)n, 0);
2391
Bram Moolenaar105bc352013-05-17 16:03:57 +02002392 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002393
2394 /* Check that the cursor is not beyond the end of the line now. */
Bram Moolenaar105bc352013-05-17 16:03:57 +02002395 if (buf == savebuf)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002396 check_cursor_col();
2397
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002398 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002399 return FAIL;
2400
2401 if (len_change)
2402 *len_change = 0;
2403
2404 return OK;
2405 }
2406 else
2407 {
2408 PyErr_BadArgument();
2409 return FAIL;
2410 }
2411}
2412
Bram Moolenaar19e60942011-06-19 00:27:51 +02002413/* Replace a range of lines in the specified buffer. The line numbers are in
2414 * Vim format (1-based). The range is from lo up to, but not including, hi.
2415 * The replacement lines are given as a Python list of string objects. The
2416 * list is checked for validity and correct format. Errors are returned as a
2417 * value of FAIL. The return value is OK on success.
2418 * If OK is returned and len_change is not NULL, *len_change
2419 * is set to the change in the buffer length.
2420 */
2421 static int
2422SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
2423{
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002424 /* First of all, we check the type of the supplied Python object.
Bram Moolenaar19e60942011-06-19 00:27:51 +02002425 * There are three cases:
2426 * 1. NULL, or None - this is a deletion.
2427 * 2. A list - this is a replacement.
2428 * 3. Anything else - this is an error.
2429 */
2430 if (list == Py_None || list == NULL)
2431 {
2432 PyInt i;
2433 PyInt n = (int)(hi - lo);
Bram Moolenaar105bc352013-05-17 16:03:57 +02002434 buf_T *savebuf;
Bram Moolenaar19e60942011-06-19 00:27:51 +02002435
2436 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002437 VimTryStart();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002438 switch_buffer(&savebuf, buf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002439
2440 if (u_savedel((linenr_T)lo, (long)n) == FAIL)
2441 PyErr_SetVim(_("cannot save undo information"));
2442 else
2443 {
2444 for (i = 0; i < n; ++i)
2445 {
2446 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2447 {
2448 PyErr_SetVim(_("cannot delete line"));
2449 break;
2450 }
2451 }
Bram Moolenaar105bc352013-05-17 16:03:57 +02002452 if (buf == savebuf)
Bram Moolenaar19e60942011-06-19 00:27:51 +02002453 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
2454 deleted_lines_mark((linenr_T)lo, (long)i);
2455 }
2456
Bram Moolenaar105bc352013-05-17 16:03:57 +02002457 restore_buffer(savebuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002458
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002459 if (VimTryEnd())
Bram Moolenaar19e60942011-06-19 00:27:51 +02002460 return FAIL;
2461
2462 if (len_change)
2463 *len_change = -n;
2464
2465 return OK;
2466 }
2467 else if (PyList_Check(list))
2468 {
2469 PyInt i;
2470 PyInt new_len = PyList_Size(list);
2471 PyInt old_len = hi - lo;
2472 PyInt extra = 0; /* lines added to text, can be negative */
2473 char **array;
2474 buf_T *savebuf;
2475
2476 if (new_len == 0) /* avoid allocating zero bytes */
2477 array = NULL;
2478 else
2479 {
2480 array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
2481 if (array == NULL)
2482 {
2483 PyErr_NoMemory();
2484 return FAIL;
2485 }
2486 }
2487
2488 for (i = 0; i < new_len; ++i)
2489 {
2490 PyObject *line = PyList_GetItem(list, i);
2491
2492 array[i] = StringToLine(line);
2493 if (array[i] == NULL)
2494 {
2495 while (i)
2496 vim_free(array[--i]);
2497 vim_free(array);
2498 return FAIL;
2499 }
2500 }
2501
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002502 VimTryStart();
Bram Moolenaar19e60942011-06-19 00:27:51 +02002503 PyErr_Clear();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002504
2505 // START of region without "return". Must call restore_buffer()!
2506 switch_buffer(&savebuf, buf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002507
2508 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2509 PyErr_SetVim(_("cannot save undo information"));
2510
2511 /* If the size of the range is reducing (ie, new_len < old_len) we
2512 * need to delete some old_len. We do this at the start, by
2513 * repeatedly deleting line "lo".
2514 */
2515 if (!PyErr_Occurred())
2516 {
2517 for (i = 0; i < old_len - new_len; ++i)
2518 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2519 {
2520 PyErr_SetVim(_("cannot delete line"));
2521 break;
2522 }
2523 extra -= i;
2524 }
2525
2526 /* For as long as possible, replace the existing old_len with the
2527 * new old_len. This is a more efficient operation, as it requires
2528 * less memory allocation and freeing.
2529 */
2530 if (!PyErr_Occurred())
2531 {
2532 for (i = 0; i < old_len && i < new_len; ++i)
2533 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
2534 == FAIL)
2535 {
2536 PyErr_SetVim(_("cannot replace line"));
2537 break;
2538 }
2539 }
2540 else
2541 i = 0;
2542
2543 /* Now we may need to insert the remaining new old_len. If we do, we
2544 * must free the strings as we finish with them (we can't pass the
2545 * responsibility to vim in this case).
2546 */
2547 if (!PyErr_Occurred())
2548 {
2549 while (i < new_len)
2550 {
2551 if (ml_append((linenr_T)(lo + i - 1),
2552 (char_u *)array[i], 0, FALSE) == FAIL)
2553 {
2554 PyErr_SetVim(_("cannot insert line"));
2555 break;
2556 }
2557 vim_free(array[i]);
2558 ++i;
2559 ++extra;
2560 }
2561 }
2562
2563 /* Free any left-over old_len, as a result of an error */
2564 while (i < new_len)
2565 {
2566 vim_free(array[i]);
2567 ++i;
2568 }
2569
2570 /* Free the array of old_len. All of its contents have now
2571 * been dealt with (either freed, or the responsibility passed
2572 * to vim.
2573 */
2574 vim_free(array);
2575
2576 /* Adjust marks. Invalidate any which lie in the
2577 * changed range, and move any in the remainder of the buffer.
2578 */
2579 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
2580 (long)MAXLNUM, (long)extra);
2581 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2582
Bram Moolenaar105bc352013-05-17 16:03:57 +02002583 if (buf == savebuf)
Bram Moolenaar19e60942011-06-19 00:27:51 +02002584 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
2585
Bram Moolenaar105bc352013-05-17 16:03:57 +02002586 // END of region without "return".
2587 restore_buffer(savebuf);
Bram Moolenaar19e60942011-06-19 00:27:51 +02002588
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002589 if (VimTryEnd())
Bram Moolenaar19e60942011-06-19 00:27:51 +02002590 return FAIL;
2591
2592 if (len_change)
2593 *len_change = new_len - old_len;
2594
2595 return OK;
2596 }
2597 else
2598 {
2599 PyErr_BadArgument();
2600 return FAIL;
2601 }
2602}
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002603
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002604/* Insert a number of lines into the specified buffer after the specified line.
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002605 * The line number is in Vim format (1-based). The lines to be inserted are
2606 * given as a Python list of string objects or as a single string. The lines
2607 * to be added are checked for validity and correct format. Errors are
2608 * returned as a value of FAIL. The return value is OK on success.
2609 * If OK is returned and len_change is not NULL, *len_change
2610 * is set to the change in the buffer length.
2611 */
2612 static int
2613InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
2614{
2615 /* First of all, we check the type of the supplied Python object.
2616 * It must be a string or a list, or the call is in error.
2617 */
2618 if (PyString_Check(lines))
2619 {
2620 char *str = StringToLine(lines);
2621 buf_T *savebuf;
2622
2623 if (str == NULL)
2624 return FAIL;
2625
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002626 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002627 VimTryStart();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002628 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002629
2630 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2631 PyErr_SetVim(_("cannot save undo information"));
2632 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2633 PyErr_SetVim(_("cannot insert line"));
2634 else
2635 appended_lines_mark((linenr_T)n, 1L);
2636
2637 vim_free(str);
Bram Moolenaar105bc352013-05-17 16:03:57 +02002638 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002639 update_screen(VALID);
2640
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002641 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002642 return FAIL;
2643
2644 if (len_change)
2645 *len_change = 1;
2646
2647 return OK;
2648 }
2649 else if (PyList_Check(lines))
2650 {
2651 PyInt i;
2652 PyInt size = PyList_Size(lines);
2653 char **array;
2654 buf_T *savebuf;
2655
2656 array = (char **)alloc((unsigned)(size * sizeof(char *)));
2657 if (array == NULL)
2658 {
2659 PyErr_NoMemory();
2660 return FAIL;
2661 }
2662
2663 for (i = 0; i < size; ++i)
2664 {
2665 PyObject *line = PyList_GetItem(lines, i);
2666 array[i] = StringToLine(line);
2667
2668 if (array[i] == NULL)
2669 {
2670 while (i)
2671 vim_free(array[--i]);
2672 vim_free(array);
2673 return FAIL;
2674 }
2675 }
2676
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002677 PyErr_Clear();
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002678 VimTryStart();
Bram Moolenaar105bc352013-05-17 16:03:57 +02002679 switch_buffer(&savebuf, buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002680
2681 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2682 PyErr_SetVim(_("cannot save undo information"));
2683 else
2684 {
2685 for (i = 0; i < size; ++i)
2686 {
2687 if (ml_append((linenr_T)(n + i),
2688 (char_u *)array[i], 0, FALSE) == FAIL)
2689 {
2690 PyErr_SetVim(_("cannot insert line"));
2691
2692 /* Free the rest of the lines */
2693 while (i < size)
2694 vim_free(array[i++]);
2695
2696 break;
2697 }
2698 vim_free(array[i]);
2699 }
2700 if (i > 0)
2701 appended_lines_mark((linenr_T)n, (long)i);
2702 }
2703
2704 /* Free the array of lines. All of its contents have now
2705 * been freed.
2706 */
2707 vim_free(array);
2708
Bram Moolenaar105bc352013-05-17 16:03:57 +02002709 restore_buffer(savebuf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002710 update_screen(VALID);
2711
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002712 if (VimTryEnd())
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002713 return FAIL;
2714
2715 if (len_change)
2716 *len_change = size;
2717
2718 return OK;
2719 }
2720 else
2721 {
2722 PyErr_BadArgument();
2723 return FAIL;
2724 }
2725}
2726
2727/*
2728 * Common routines for buffers and line ranges
2729 * -------------------------------------------
2730 */
2731
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002732typedef struct
2733{
2734 PyObject_HEAD
2735 buf_T *buf;
2736} BufferObject;
2737
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002738 static int
Bram Moolenaard6e39182013-05-21 18:30:34 +02002739CheckBuffer(BufferObject *self)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002740{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002741 if (self->buf == INVALID_BUFFER_VALUE)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002742 {
2743 PyErr_SetVim(_("attempt to refer to deleted buffer"));
2744 return -1;
2745 }
2746
2747 return 0;
2748}
2749
2750 static PyObject *
2751RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
2752{
2753 if (CheckBuffer(self))
2754 return NULL;
2755
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002756 if (end == -1)
2757 end = self->buf->b_ml.ml_line_count;
2758
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002759 if (n < 0)
2760 n += end - start + 1;
2761
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002762 if (n < 0 || n > end - start)
2763 {
2764 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2765 return NULL;
2766 }
2767
2768 return GetBufferLine(self->buf, n+start);
2769}
2770
2771 static PyObject *
2772RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
2773{
2774 PyInt size;
2775
2776 if (CheckBuffer(self))
2777 return NULL;
2778
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002779 if (end == -1)
2780 end = self->buf->b_ml.ml_line_count;
2781
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002782 size = end - start + 1;
2783
2784 if (lo < 0)
2785 lo = 0;
2786 else if (lo > size)
2787 lo = size;
2788 if (hi < 0)
2789 hi = 0;
2790 if (hi < lo)
2791 hi = lo;
2792 else if (hi > size)
2793 hi = size;
2794
2795 return GetBufferLineList(self->buf, lo+start, hi+start);
2796}
2797
2798 static PyInt
2799RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2800{
2801 PyInt len_change;
2802
2803 if (CheckBuffer(self))
2804 return -1;
2805
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002806 if (end == -1)
2807 end = self->buf->b_ml.ml_line_count;
2808
Bram Moolenaarbd80f352013-05-12 21:16:23 +02002809 if (n < 0)
2810 n += end - start + 1;
2811
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002812 if (n < 0 || n > end - start)
2813 {
2814 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
2815 return -1;
2816 }
2817
2818 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
2819 return -1;
2820
2821 if (new_end)
2822 *new_end = end + len_change;
2823
2824 return 0;
2825}
2826
Bram Moolenaar19e60942011-06-19 00:27:51 +02002827 static PyInt
2828RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
2829{
2830 PyInt size;
2831 PyInt len_change;
2832
2833 /* Self must be a valid buffer */
2834 if (CheckBuffer(self))
2835 return -1;
2836
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002837 if (end == -1)
2838 end = self->buf->b_ml.ml_line_count;
2839
Bram Moolenaar19e60942011-06-19 00:27:51 +02002840 /* Sort out the slice range */
2841 size = end - start + 1;
2842
2843 if (lo < 0)
2844 lo = 0;
2845 else if (lo > size)
2846 lo = size;
2847 if (hi < 0)
2848 hi = 0;
2849 if (hi < lo)
2850 hi = lo;
2851 else if (hi > size)
2852 hi = size;
2853
2854 if (SetBufferLineList(self->buf, lo + start, hi + start,
2855 val, &len_change) == FAIL)
2856 return -1;
2857
2858 if (new_end)
2859 *new_end = end + len_change;
2860
2861 return 0;
2862}
2863
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002864
2865 static PyObject *
2866RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
2867{
2868 PyObject *lines;
2869 PyInt len_change;
2870 PyInt max;
2871 PyInt n;
2872
2873 if (CheckBuffer(self))
2874 return NULL;
2875
Bram Moolenaar8f1723d2013-05-12 20:36:14 +02002876 if (end == -1)
2877 end = self->buf->b_ml.ml_line_count;
2878
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002879 max = n = end - start + 1;
2880
2881 if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
2882 return NULL;
2883
2884 if (n < 0 || n > max)
2885 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02002886 PyErr_SetString(PyExc_IndexError, _("line number out of range"));
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002887 return NULL;
2888 }
2889
2890 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
2891 return NULL;
2892
2893 if (new_end)
2894 *new_end = end + len_change;
2895
2896 Py_INCREF(Py_None);
2897 return Py_None;
2898}
2899
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002900/* Range object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002901 */
2902
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002903static PyTypeObject RangeType;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002904static PySequenceMethods RangeAsSeq;
2905static PyMappingMethods RangeAsMapping;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002906
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002907typedef struct
2908{
2909 PyObject_HEAD
2910 BufferObject *buf;
2911 PyInt start;
2912 PyInt end;
2913} RangeObject;
2914
2915 static PyObject *
2916RangeNew(buf_T *buf, PyInt start, PyInt end)
2917{
2918 BufferObject *bufr;
2919 RangeObject *self;
Bram Moolenaar774267b2013-05-21 20:51:59 +02002920 self = PyObject_GC_New(RangeObject, &RangeType);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02002921 if (self == NULL)
2922 return NULL;
2923
2924 bufr = (BufferObject *)BufferNew(buf);
2925 if (bufr == NULL)
2926 {
2927 Py_DECREF(self);
2928 return NULL;
2929 }
2930 Py_INCREF(bufr);
2931
2932 self->buf = bufr;
2933 self->start = start;
2934 self->end = end;
2935
2936 return (PyObject *)(self);
2937}
2938
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002939 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02002940RangeDestructor(RangeObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002941{
Bram Moolenaar774267b2013-05-21 20:51:59 +02002942 PyObject_GC_UnTrack((void *)(self));
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02002943 Py_XDECREF(self->buf);
Bram Moolenaar774267b2013-05-21 20:51:59 +02002944 PyObject_GC_Del((void *)(self));
2945}
2946
2947 static int
2948RangeTraverse(RangeObject *self, visitproc visit, void *arg)
2949{
2950 Py_VISIT(((PyObject *)(self->buf)));
2951 return 0;
2952}
2953
2954 static int
2955RangeClear(RangeObject *self)
2956{
2957 Py_CLEAR(self->buf);
2958 return 0;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02002959}
2960
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002961 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02002962RangeLength(RangeObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002963{
2964 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
Bram Moolenaard6e39182013-05-21 18:30:34 +02002965 if (CheckBuffer(self->buf))
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002966 return -1; /* ??? */
2967
Bram Moolenaard6e39182013-05-21 18:30:34 +02002968 return (self->end - self->start + 1);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002969}
2970
2971 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02002972RangeItem(RangeObject *self, PyInt n)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002973{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002974 return RBItem(self->buf, n, self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002975}
2976
2977 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02002978RangeSlice(RangeObject *self, PyInt lo, PyInt hi)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002979{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002980 return RBSlice(self->buf, lo, hi, self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002981}
2982
2983 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02002984RangeAppend(RangeObject *self, PyObject *args)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002985{
Bram Moolenaard6e39182013-05-21 18:30:34 +02002986 return RBAppend(self->buf, args, self->start, self->end, &self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002987}
2988
2989 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02002990RangeRepr(RangeObject *self)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002991{
2992 static char repr[100];
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002993
Bram Moolenaard6e39182013-05-21 18:30:34 +02002994 if (self->buf->buf == INVALID_BUFFER_VALUE)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02002995 {
2996 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
2997 (self));
2998 return PyString_FromString(repr);
2999 }
3000 else
3001 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003002 char *name = (char *)self->buf->buf->b_fname;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003003 int len;
3004
3005 if (name == NULL)
3006 name = "";
3007 len = (int)strlen(name);
3008
3009 if (len > 45)
3010 name = name + (45 - len);
3011
3012 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
3013 len > 45 ? "..." : "", name,
Bram Moolenaard6e39182013-05-21 18:30:34 +02003014 self->start, self->end);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003015
3016 return PyString_FromString(repr);
3017 }
3018}
3019
3020static struct PyMethodDef RangeMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02003021 /* name, function, calling, documentation */
3022 {"append", (PyCFunction)RangeAppend, METH_VARARGS, "Append data to the Vim range" },
3023 { NULL, NULL, 0, NULL }
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003024};
3025
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003026static PyTypeObject BufferType;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003027static PySequenceMethods BufferAsSeq;
3028static PyMappingMethods BufferAsMapping;
3029
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003030 static PyObject *
Bram Moolenaar971db462013-05-12 18:44:48 +02003031BufferNew(buf_T *buf)
3032{
3033 /* We need to handle deletion of buffers underneath us.
3034 * If we add a "b_python*_ref" field to the buf_T structure,
3035 * then we can get at it in buf_freeall() in vim. We then
3036 * need to create only ONE Python object per buffer - if
3037 * we try to create a second, just INCREF the existing one
3038 * and return it. The (single) Python object referring to
3039 * the buffer is stored in "b_python*_ref".
3040 * Question: what to do on a buf_freeall(). We'll probably
3041 * have to either delete the Python object (DECREF it to
3042 * zero - a bad idea, as it leaves dangling refs!) or
3043 * set the buf_T * value to an invalid value (-1?), which
3044 * means we need checks in all access functions... Bah.
3045 *
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003046 * Python2 and Python3 get different fields and different objects:
Bram Moolenaar971db462013-05-12 18:44:48 +02003047 * b_python_ref and b_python3_ref fields respectively.
3048 */
3049
3050 BufferObject *self;
3051
3052 if (BUF_PYTHON_REF(buf) != NULL)
3053 {
3054 self = BUF_PYTHON_REF(buf);
3055 Py_INCREF(self);
3056 }
3057 else
3058 {
3059 self = PyObject_NEW(BufferObject, &BufferType);
3060 if (self == NULL)
3061 return NULL;
3062 self->buf = buf;
3063 BUF_PYTHON_REF(buf) = self;
3064 }
3065
3066 return (PyObject *)(self);
3067}
3068
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003069 static void
Bram Moolenaard6e39182013-05-21 18:30:34 +02003070BufferDestructor(BufferObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003071{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003072 if (self->buf && self->buf != INVALID_BUFFER_VALUE)
3073 BUF_PYTHON_REF(self->buf) = NULL;
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003074
3075 DESTRUCTOR_FINISH(self);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003076}
3077
Bram Moolenaar971db462013-05-12 18:44:48 +02003078 static PyInt
Bram Moolenaard6e39182013-05-21 18:30:34 +02003079BufferLength(BufferObject *self)
Bram Moolenaar971db462013-05-12 18:44:48 +02003080{
3081 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
Bram Moolenaard6e39182013-05-21 18:30:34 +02003082 if (CheckBuffer(self))
Bram Moolenaar971db462013-05-12 18:44:48 +02003083 return -1; /* ??? */
3084
Bram Moolenaard6e39182013-05-21 18:30:34 +02003085 return (PyInt)(self->buf->b_ml.ml_line_count);
Bram Moolenaar971db462013-05-12 18:44:48 +02003086}
3087
3088 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003089BufferItem(BufferObject *self, PyInt n)
Bram Moolenaar971db462013-05-12 18:44:48 +02003090{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003091 return RBItem(self, n, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02003092}
3093
3094 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003095BufferSlice(BufferObject *self, PyInt lo, PyInt hi)
Bram Moolenaar971db462013-05-12 18:44:48 +02003096{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003097 return RBSlice(self, lo, hi, 1, -1);
Bram Moolenaar971db462013-05-12 18:44:48 +02003098}
3099
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003100 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003101BufferAttr(BufferObject *self, char *name)
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003102{
3103 if (strcmp(name, "name") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02003104 return Py_BuildValue("s", self->buf->b_ffname);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003105 else if (strcmp(name, "number") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02003106 return Py_BuildValue(Py_ssize_t_fmt, self->buf->b_fnum);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003107 else if (strcmp(name, "vars") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02003108 return DictionaryNew(self->buf->b_vars);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003109 else if (strcmp(name, "options") == 0)
Bram Moolenaard6e39182013-05-21 18:30:34 +02003110 return OptionsNew(SREQ_BUF, self->buf, (checkfun) CheckBuffer,
3111 (PyObject *) self);
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003112 else if (strcmp(name,"__members__") == 0)
3113 return Py_BuildValue("[ssss]", "name", "number", "vars", "options");
3114 else
3115 return NULL;
3116}
3117
3118 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003119BufferAppend(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003120{
Bram Moolenaard6e39182013-05-21 18:30:34 +02003121 return RBAppend(self, args, 1, -1, NULL);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003122}
3123
3124 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003125BufferMark(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003126{
3127 pos_T *posp;
3128 char *pmark;
3129 char mark;
Bram Moolenaar105bc352013-05-17 16:03:57 +02003130 buf_T *savebuf;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003131
Bram Moolenaard6e39182013-05-21 18:30:34 +02003132 if (CheckBuffer(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003133 return NULL;
3134
3135 if (!PyArg_ParseTuple(args, "s", &pmark))
3136 return NULL;
3137 mark = *pmark;
3138
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003139 VimTryStart();
Bram Moolenaard6e39182013-05-21 18:30:34 +02003140 switch_buffer(&savebuf, self->buf);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003141 posp = getmark(mark, FALSE);
Bram Moolenaar105bc352013-05-17 16:03:57 +02003142 restore_buffer(savebuf);
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003143 if (VimTryEnd())
3144 return NULL;
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003145
3146 if (posp == NULL)
3147 {
3148 PyErr_SetVim(_("invalid mark name"));
3149 return NULL;
3150 }
3151
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003152 if (posp->lnum <= 0)
3153 {
3154 /* Or raise an error? */
3155 Py_INCREF(Py_None);
3156 return Py_None;
3157 }
3158
3159 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
3160}
3161
3162 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003163BufferRange(BufferObject *self, PyObject *args)
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003164{
3165 PyInt start;
3166 PyInt end;
3167
Bram Moolenaard6e39182013-05-21 18:30:34 +02003168 if (CheckBuffer(self))
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003169 return NULL;
3170
3171 if (!PyArg_ParseTuple(args, "nn", &start, &end))
3172 return NULL;
3173
Bram Moolenaard6e39182013-05-21 18:30:34 +02003174 return RangeNew(self->buf, start, end);
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003175}
3176
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003177 static PyObject *
Bram Moolenaard6e39182013-05-21 18:30:34 +02003178BufferRepr(BufferObject *self)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003179{
3180 static char repr[100];
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003181
Bram Moolenaard6e39182013-05-21 18:30:34 +02003182 if (self->buf == INVALID_BUFFER_VALUE)
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003183 {
3184 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self));
3185 return PyString_FromString(repr);
3186 }
3187 else
3188 {
Bram Moolenaard6e39182013-05-21 18:30:34 +02003189 char *name = (char *)self->buf->b_fname;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003190 PyInt len;
3191
3192 if (name == NULL)
3193 name = "";
3194 len = strlen(name);
3195
3196 if (len > 35)
3197 name = name + (35 - len);
3198
3199 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name);
3200
3201 return PyString_FromString(repr);
3202 }
3203}
3204
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003205static struct PyMethodDef BufferMethods[] = {
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02003206 /* name, function, calling, documentation */
3207 {"append", (PyCFunction)BufferAppend, METH_VARARGS, "Append data to Vim buffer" },
3208 {"mark", (PyCFunction)BufferMark, METH_VARARGS, "Return (row,col) representing position of named mark" },
3209 {"range", (PyCFunction)BufferRange, METH_VARARGS, "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 +01003210#if PY_VERSION_HEX >= 0x03000000
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02003211 {"__dir__", (PyCFunction)BufferDir, METH_NOARGS, "List buffer attributes" },
Bram Moolenaar7f85d292012-02-04 20:17:26 +01003212#endif
Bram Moolenaar182dc4f2013-05-21 19:01:55 +02003213 { NULL, NULL, 0, NULL }
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003214};
3215
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003216/*
3217 * Buffer list object - Implementation
3218 */
3219
3220static PyTypeObject BufMapType;
3221
3222typedef struct
3223{
3224 PyObject_HEAD
3225} BufMapObject;
3226
3227 static PyInt
3228BufMapLength(PyObject *self UNUSED)
3229{
3230 buf_T *b = firstbuf;
3231 PyInt n = 0;
3232
3233 while (b)
3234 {
3235 ++n;
3236 b = b->b_next;
3237 }
3238
3239 return n;
3240}
3241
3242 static PyObject *
3243BufMapItem(PyObject *self UNUSED, PyObject *keyObject)
3244{
3245 buf_T *b;
3246 int bnr;
3247
3248#if PY_MAJOR_VERSION < 3
3249 if (PyInt_Check(keyObject))
3250 bnr = PyInt_AsLong(keyObject);
3251 else
3252#endif
3253 if (PyLong_Check(keyObject))
3254 bnr = PyLong_AsLong(keyObject);
3255 else
3256 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003257 PyErr_SetString(PyExc_TypeError, _("key must be integer"));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003258 return NULL;
3259 }
3260
3261 b = buflist_findnr(bnr);
3262
3263 if (b)
3264 return BufferNew(b);
3265 else
3266 {
Bram Moolenaar4d188da2013-05-15 15:35:09 +02003267 PyErr_SetObject(PyExc_KeyError, keyObject);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003268 return NULL;
3269 }
3270}
3271
3272 static void
3273BufMapIterDestruct(PyObject *buffer)
3274{
3275 /* Iteration was stopped before all buffers were processed */
3276 if (buffer)
3277 {
3278 Py_DECREF(buffer);
3279 }
3280}
3281
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003282 static int
3283BufMapIterTraverse(PyObject *buffer, visitproc visit, void *arg)
3284{
Bram Moolenaar774267b2013-05-21 20:51:59 +02003285 if (buffer)
3286 Py_VISIT(buffer);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003287 return 0;
3288}
3289
3290 static int
3291BufMapIterClear(PyObject **buffer)
3292{
Bram Moolenaar774267b2013-05-21 20:51:59 +02003293 if (*buffer)
3294 Py_CLEAR(*buffer);
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003295 return 0;
3296}
3297
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003298 static PyObject *
3299BufMapIterNext(PyObject **buffer)
3300{
3301 PyObject *next;
3302 PyObject *r;
3303
3304 if (!*buffer)
3305 return NULL;
3306
3307 r = *buffer;
3308
3309 if (CheckBuffer((BufferObject *)(r)))
3310 {
3311 *buffer = NULL;
3312 return NULL;
3313 }
3314
3315 if (!((BufferObject *)(r))->buf->b_next)
3316 next = NULL;
3317 else if (!(next = BufferNew(((BufferObject *)(r))->buf->b_next)))
3318 return NULL;
3319 *buffer = next;
Bram Moolenaar9e74e302013-05-17 21:20:17 +02003320 /* Do not increment reference: we no longer hold it (decref), but whoever
3321 * on other side will hold (incref). Decref+incref = nothing. */
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003322 return r;
3323}
3324
3325 static PyObject *
3326BufMapIter(PyObject *self UNUSED)
3327{
3328 PyObject *buffer;
3329
3330 buffer = BufferNew(firstbuf);
3331 return IterNew(buffer,
Bram Moolenaarcfef5ff2013-05-17 16:24:32 +02003332 (destructorfun) BufMapIterDestruct, (nextfun) BufMapIterNext,
3333 (traversefun) BufMapIterTraverse, (clearfun) BufMapIterClear);
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02003334}
3335
3336static PyMappingMethods BufMapAsMapping = {
3337 (lenfunc) BufMapLength,
3338 (binaryfunc) BufMapItem,
3339 (objobjargproc) 0,
3340};
3341
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003342/* Current items object
Bram Moolenaarca8a4df2010-07-31 19:54:14 +02003343 */
3344
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003345 static PyObject *
3346CurrentGetattr(PyObject *self UNUSED, char *name)
3347{
3348 if (strcmp(name, "buffer") == 0)
3349 return (PyObject *)BufferNew(curbuf);
3350 else if (strcmp(name, "window") == 0)
Bram Moolenaarcabf80f2013-05-17 16:18:33 +02003351 return (PyObject *)WindowNew(curwin, curtab);
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003352 else if (strcmp(name, "tabpage") == 0)
3353 return (PyObject *)TabPageNew(curtab);
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003354 else if (strcmp(name, "line") == 0)
3355 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum);
3356 else if (strcmp(name, "range") == 0)
3357 return RangeNew(curbuf, RangeStart, RangeEnd);
3358 else if (strcmp(name,"__members__") == 0)
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02003359 return Py_BuildValue("[sssss]", "buffer", "window", "line", "range",
3360 "tabpage");
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003361 else
3362 {
3363 PyErr_SetString(PyExc_AttributeError, name);
3364 return NULL;
3365 }
3366}
3367
3368 static int
3369CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value)
3370{
3371 if (strcmp(name, "line") == 0)
3372 {
3373 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL)
3374 return -1;
3375
3376 return 0;
3377 }
Bram Moolenaare7614592013-05-15 15:51:08 +02003378 else if (strcmp(name, "buffer") == 0)
3379 {
3380 int count;
3381
3382 if (value->ob_type != &BufferType)
3383 {
3384 PyErr_SetString(PyExc_TypeError, _("expected vim.buffer object"));
3385 return -1;
3386 }
3387
3388 if (CheckBuffer((BufferObject *)(value)))
3389 return -1;
3390 count = ((BufferObject *)(value))->buf->b_fnum;
3391
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003392 VimTryStart();
Bram Moolenaare7614592013-05-15 15:51:08 +02003393 if (do_buffer(DOBUF_GOTO, DOBUF_FIRST, FORWARD, count, 0) == FAIL)
3394 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003395 if (VimTryEnd())
3396 return -1;
Bram Moolenaare7614592013-05-15 15:51:08 +02003397 PyErr_SetVim(_("failed to switch to given buffer"));
3398 return -1;
3399 }
3400
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003401 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02003402 }
3403 else if (strcmp(name, "window") == 0)
3404 {
3405 int count;
3406
3407 if (value->ob_type != &WindowType)
3408 {
3409 PyErr_SetString(PyExc_TypeError, _("expected vim.window object"));
3410 return -1;
3411 }
3412
3413 if (CheckWindow((WindowObject *)(value)))
3414 return -1;
3415 count = get_win_number(((WindowObject *)(value))->win, firstwin);
3416
3417 if (!count)
3418 {
3419 PyErr_SetString(PyExc_ValueError,
3420 _("failed to find window in the current tab page"));
3421 return -1;
3422 }
3423
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003424 VimTryStart();
Bram Moolenaare7614592013-05-15 15:51:08 +02003425 win_goto(((WindowObject *)(value))->win);
3426 if (((WindowObject *)(value))->win != curwin)
3427 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003428 if (VimTryEnd())
3429 return -1;
Bram Moolenaare7614592013-05-15 15:51:08 +02003430 PyErr_SetString(PyExc_RuntimeError,
3431 _("did not switch to the specified window"));
3432 return -1;
3433 }
3434
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003435 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02003436 }
3437 else if (strcmp(name, "tabpage") == 0)
3438 {
3439 if (value->ob_type != &TabPageType)
3440 {
3441 PyErr_SetString(PyExc_TypeError, _("expected vim.tabpage object"));
3442 return -1;
3443 }
3444
3445 if (CheckTabPage((TabPageObject *)(value)))
3446 return -1;
3447
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003448 VimTryStart();
Bram Moolenaare7614592013-05-15 15:51:08 +02003449 goto_tabpage_tp(((TabPageObject *)(value))->tab, TRUE, TRUE);
3450 if (((TabPageObject *)(value))->tab != curtab)
3451 {
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003452 if (VimTryEnd())
3453 return -1;
Bram Moolenaare7614592013-05-15 15:51:08 +02003454 PyErr_SetString(PyExc_RuntimeError,
3455 _("did not switch to the specified tab page"));
3456 return -1;
3457 }
3458
Bram Moolenaara7b64ce2013-05-21 20:40:40 +02003459 return VimTryEnd();
Bram Moolenaare7614592013-05-15 15:51:08 +02003460 }
Bram Moolenaar4d1da492013-04-24 13:39:15 +02003461 else
3462 {
3463 PyErr_SetString(PyExc_AttributeError, name);
3464 return -1;
3465 }
3466}
3467
Bram Moolenaardb913952012-06-29 12:54:53 +02003468 static void
Bram Moolenaarb52f4c02013-05-21 18:19:38 +02003469init_range_cmd(exarg_T *eap)
3470{
3471 RangeStart = eap->line1;
3472 RangeEnd = eap->line2;
3473}
3474
3475 static void
3476init_range_eval(typval_T *rettv UNUSED)
3477{
3478 RangeStart = (PyInt) curwin->w_cursor.lnum;
3479 RangeEnd = RangeStart;
3480}
3481
3482 static void
3483run_cmd(const char *cmd, void *arg UNUSED, PyGILState_STATE *pygilstate UNUSED)
3484{
3485 PyRun_SimpleString((char *) cmd);
3486}
3487
3488static const char *code_hdr = "def " DOPY_FUNC "(line, linenr):\n ";
3489static int code_hdr_len = 30;
3490
3491 static void
3492run_do(const char *cmd, void *arg UNUSED, PyGILState_STATE *pygilstate)
3493{
3494 PyInt lnum;
3495 size_t len;
3496 char *code;
3497 int status;
3498 PyObject *pyfunc, *pymain;
3499
3500 if (u_save(RangeStart - 1, RangeEnd + 1) != OK)
3501 {
3502 EMSG(_("cannot save undo information"));
3503 return;
3504 }
3505
3506 len = code_hdr_len + STRLEN(cmd);
3507 code = PyMem_New(char, len + 1);
3508 memcpy(code, code_hdr, code_hdr_len);
3509 STRCPY(code + code_hdr_len, cmd);
3510 status = PyRun_SimpleString(code);
3511 PyMem_Free(code);
3512
3513 if (status)
3514 {
3515 EMSG(_("failed to run the code"));
3516 return;
3517 }
3518
3519 status = 0;
3520 pymain = PyImport_AddModule("__main__");
3521 pyfunc = PyObject_GetAttrString(pymain, DOPY_FUNC);
3522 PyGILState_Release(*pygilstate);
3523
3524 for (lnum = RangeStart; lnum <= RangeEnd; ++lnum)
3525 {
3526 PyObject *line, *linenr, *ret;
3527
3528 *pygilstate = PyGILState_Ensure();
3529 if (!(line = GetBufferLine(curbuf, lnum)))
3530 goto err;
3531 if (!(linenr = PyInt_FromLong((long) lnum)))
3532 {
3533 Py_DECREF(line);
3534 goto err;
3535 }
3536 ret = PyObject_CallFunctionObjArgs(pyfunc, line, linenr, NULL);
3537 Py_DECREF(line);
3538 Py_DECREF(linenr);
3539 if (!ret)
3540 goto err;
3541
3542 if (ret != Py_None)
3543 if (SetBufferLine(curbuf, lnum, ret, NULL) == FAIL)
3544 goto err;
3545
3546 Py_XDECREF(ret);
3547 PythonIO_Flush();
3548 PyGILState_Release(*pygilstate);
3549 }
3550 goto out;
3551err:
3552 *pygilstate = PyGILState_Ensure();
3553 PyErr_PrintEx(0);
3554 PythonIO_Flush();
3555 status = 1;
3556out:
3557 if (!status)
3558 *pygilstate = PyGILState_Ensure();
3559 Py_DECREF(pyfunc);
3560 PyObject_SetAttrString(pymain, DOPY_FUNC, NULL);
3561 if (status)
3562 return;
3563 check_cursor();
3564 update_curbuf(NOT_VALID);
3565}
3566
3567 static void
3568run_eval(const char *cmd, typval_T *rettv, PyGILState_STATE *pygilstate UNUSED)
3569{
3570 PyObject *r;
3571
3572 r = PyRun_String((char *) cmd, Py_eval_input, globals, globals);
3573 if (r == NULL)
3574 {
3575 if (PyErr_Occurred() && !msg_silent)
3576 PyErr_PrintEx(0);
3577 EMSG(_("E858: Eval did not return a valid python object"));
3578 }
3579 else
3580 {
3581 if (ConvertFromPyObject(r, rettv) == -1)
3582 EMSG(_("E859: Failed to convert returned python object to vim value"));
3583 Py_DECREF(r);
3584 }
3585 PyErr_Clear();
3586}
3587
3588 static void
Bram Moolenaardb913952012-06-29 12:54:53 +02003589set_ref_in_py(const int copyID)
3590{
3591 pylinkedlist_T *cur;
3592 dict_T *dd;
3593 list_T *ll;
3594
3595 if (lastdict != NULL)
3596 for(cur = lastdict ; cur != NULL ; cur = cur->pll_prev)
3597 {
3598 dd = ((DictionaryObject *) (cur->pll_obj))->dict;
3599 if (dd->dv_copyID != copyID)
3600 {
3601 dd->dv_copyID = copyID;
3602 set_ref_in_ht(&dd->dv_hashtab, copyID);
3603 }
3604 }
3605
3606 if (lastlist != NULL)
3607 for(cur = lastlist ; cur != NULL ; cur = cur->pll_prev)
3608 {
3609 ll = ((ListObject *) (cur->pll_obj))->list;
3610 if (ll->lv_copyID != copyID)
3611 {
3612 ll->lv_copyID = copyID;
3613 set_ref_in_list(ll, copyID);
3614 }
3615 }
3616}
3617
3618 static int
3619set_string_copy(char_u *str, typval_T *tv)
3620{
3621 tv->vval.v_string = vim_strsave(str);
3622 if (tv->vval.v_string == NULL)
3623 {
3624 PyErr_NoMemory();
3625 return -1;
3626 }
3627 return 0;
3628}
3629
Bram Moolenaar3d0c52d2013-05-12 19:45:35 +02003630 static int
3631pydict_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3632{
3633 dict_T *d;
3634 char_u *key;
3635 dictitem_T *di;
3636 PyObject *keyObject;
3637 PyObject *valObject;
3638 Py_ssize_t iter = 0;
3639
3640 d = dict_alloc();
3641 if (d == NULL)
3642 {
3643 PyErr_NoMemory();
3644 return -1;
3645 }
3646
3647 tv->v_type = VAR_DICT;
3648 tv->vval.v_dict = d;
3649
3650 while (PyDict_Next(obj, &iter, &keyObject, &valObject))
3651 {
3652 DICTKEY_DECL
3653
3654 if (keyObject == NULL)
3655 return -1;
3656 if (valObject == NULL)
3657 return -1;
3658
3659 DICTKEY_GET_NOTEMPTY(-1)
3660
3661 di = dictitem_alloc(key);
3662
3663 DICTKEY_UNREF
3664
3665 if (di == NULL)
3666 {
3667 PyErr_NoMemory();
3668 return -1;
3669 }
3670 di->di_tv.v_lock = 0;
3671
3672 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3673 {
3674 vim_free(di);
3675 return -1;
3676 }
3677 if (dict_add(d, di) == FAIL)
3678 {
3679 vim_free(di);
3680 PyErr_SetVim(_("failed to add key to dictionary"));
3681 return -1;
3682 }
3683 }
3684 return 0;
3685}
3686
3687 static int
3688pymap_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3689{
3690 dict_T *d;
3691 char_u *key;
3692 dictitem_T *di;
3693 PyObject *list;
3694 PyObject *litem;
3695 PyObject *keyObject;
3696 PyObject *valObject;
3697 Py_ssize_t lsize;
3698
3699 d = dict_alloc();
3700 if (d == NULL)
3701 {
3702 PyErr_NoMemory();
3703 return -1;
3704 }
3705
3706 tv->v_type = VAR_DICT;
3707 tv->vval.v_dict = d;
3708
3709 list = PyMapping_Items(obj);
3710 if (list == NULL)
3711 return -1;
3712 lsize = PyList_Size(list);
3713 while (lsize--)
3714 {
3715 DICTKEY_DECL
3716
3717 litem = PyList_GetItem(list, lsize);
3718 if (litem == NULL)
3719 {
3720 Py_DECREF(list);
3721 return -1;
3722 }
3723
3724 keyObject = PyTuple_GetItem(litem, 0);
3725 if (keyObject == NULL)
3726 {
3727 Py_DECREF(list);
3728 Py_DECREF(litem);
3729 return -1;
3730 }
3731
3732 DICTKEY_GET_NOTEMPTY(-1)
3733
3734 valObject = PyTuple_GetItem(litem, 1);
3735 if (valObject == NULL)
3736 {
3737 Py_DECREF(list);
3738 Py_DECREF(litem);
3739 return -1;
3740 }
3741
3742 di = dictitem_alloc(key);
3743
3744 DICTKEY_UNREF
3745
3746 if (di == NULL)
3747 {
3748 Py_DECREF(list);
3749 Py_DECREF(litem);
3750 PyErr_NoMemory();
3751 return -1;
3752 }
3753 di->di_tv.v_lock = 0;
3754
3755 if (_ConvertFromPyObject(valObject, &di->di_tv, lookupDict) == -1)
3756 {
3757 vim_free(di);
3758 Py_DECREF(list);
3759 Py_DECREF(litem);
3760 return -1;
3761 }
3762 if (dict_add(d, di) == FAIL)
3763 {
3764 vim_free(di);
3765 Py_DECREF(list);
3766 Py_DECREF(litem);
3767 PyErr_SetVim(_("failed to add key to dictionary"));
3768 return -1;
3769 }
3770 Py_DECREF(litem);
3771 }
3772 Py_DECREF(list);
3773 return 0;
3774}
3775
3776 static int
3777pyseq_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3778{
3779 list_T *l;
3780
3781 l = list_alloc();
3782 if (l == NULL)
3783 {
3784 PyErr_NoMemory();
3785 return -1;
3786 }
3787
3788 tv->v_type = VAR_LIST;
3789 tv->vval.v_list = l;
3790
3791 if (list_py_concat(l, obj, lookupDict) == -1)
3792 return -1;
3793
3794 return 0;
3795}
3796
3797 static int
3798pyiter_to_tv(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3799{
3800 PyObject *iterator = PyObject_GetIter(obj);
3801 PyObject *item;
3802 list_T *l;
3803 listitem_T *li;
3804
3805 l = list_alloc();
3806
3807 if (l == NULL)
3808 {
3809 PyErr_NoMemory();
3810 return -1;
3811 }
3812
3813 tv->vval.v_list = l;
3814 tv->v_type = VAR_LIST;
3815
3816
3817 if (iterator == NULL)
3818 return -1;
3819
3820 while ((item = PyIter_Next(obj)))
3821 {
3822 li = listitem_alloc();
3823 if (li == NULL)
3824 {
3825 PyErr_NoMemory();
3826 return -1;
3827 }
3828 li->li_tv.v_lock = 0;
3829
3830 if (_ConvertFromPyObject(item, &li->li_tv, lookupDict) == -1)
3831 return -1;
3832
3833 list_append(l, li);
3834
3835 Py_DECREF(item);
3836 }
3837
3838 Py_DECREF(iterator);
3839 return 0;
3840}
3841
Bram Moolenaardb913952012-06-29 12:54:53 +02003842typedef int (*pytotvfunc)(PyObject *, typval_T *, PyObject *);
3843
3844 static int
3845convert_dl(PyObject *obj, typval_T *tv,
3846 pytotvfunc py_to_tv, PyObject *lookupDict)
3847{
3848 PyObject *capsule;
3849 char hexBuf[sizeof(void *) * 2 + 3];
3850
3851 sprintf(hexBuf, "%p", obj);
3852
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003853# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003854 capsule = PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003855# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003856 capsule = (PyObject *)PyDict_GetItemString(lookupDict, hexBuf);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003857# endif
Bram Moolenaar221d6872012-06-30 13:34:34 +02003858 if (capsule == NULL)
Bram Moolenaardb913952012-06-29 12:54:53 +02003859 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003860# ifdef PY_USE_CAPSULE
Bram Moolenaardb913952012-06-29 12:54:53 +02003861 capsule = PyCapsule_New(tv, NULL, NULL);
Bram Moolenaar221d6872012-06-30 13:34:34 +02003862# else
3863 capsule = PyCObject_FromVoidPtr(tv, NULL);
3864# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003865 PyDict_SetItemString(lookupDict, hexBuf, capsule);
3866 Py_DECREF(capsule);
3867 if (py_to_tv(obj, tv, lookupDict) == -1)
3868 {
3869 tv->v_type = VAR_UNKNOWN;
3870 return -1;
3871 }
3872 /* As we are not using copy_tv which increments reference count we must
3873 * do it ourself. */
3874 switch(tv->v_type)
3875 {
3876 case VAR_DICT: ++tv->vval.v_dict->dv_refcount; break;
3877 case VAR_LIST: ++tv->vval.v_list->lv_refcount; break;
3878 }
3879 }
3880 else
3881 {
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003882 typval_T *v;
3883
3884# ifdef PY_USE_CAPSULE
3885 v = PyCapsule_GetPointer(capsule, NULL);
3886# else
Bram Moolenaar221d6872012-06-30 13:34:34 +02003887 v = PyCObject_AsVoidPtr(capsule);
Bram Moolenaar2afa3232012-06-29 16:28:28 +02003888# endif
Bram Moolenaardb913952012-06-29 12:54:53 +02003889 copy_tv(v, tv);
3890 }
3891 return 0;
3892}
3893
3894 static int
3895ConvertFromPyObject(PyObject *obj, typval_T *tv)
3896{
3897 PyObject *lookup_dict;
3898 int r;
3899
3900 lookup_dict = PyDict_New();
3901 r = _ConvertFromPyObject(obj, tv, lookup_dict);
3902 Py_DECREF(lookup_dict);
3903 return r;
3904}
3905
3906 static int
3907_ConvertFromPyObject(PyObject *obj, typval_T *tv, PyObject *lookupDict)
3908{
3909 if (obj->ob_type == &DictionaryType)
3910 {
3911 tv->v_type = VAR_DICT;
3912 tv->vval.v_dict = (((DictionaryObject *)(obj))->dict);
3913 ++tv->vval.v_dict->dv_refcount;
3914 }
3915 else if (obj->ob_type == &ListType)
3916 {
3917 tv->v_type = VAR_LIST;
3918 tv->vval.v_list = (((ListObject *)(obj))->list);
3919 ++tv->vval.v_list->lv_refcount;
3920 }
3921 else if (obj->ob_type == &FunctionType)
3922 {
3923 if (set_string_copy(((FunctionObject *) (obj))->name, tv) == -1)
3924 return -1;
3925
3926 tv->v_type = VAR_FUNC;
3927 func_ref(tv->vval.v_string);
3928 }
Bram Moolenaardb913952012-06-29 12:54:53 +02003929 else if (PyBytes_Check(obj))
3930 {
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003931 char_u *result;
Bram Moolenaardb913952012-06-29 12:54:53 +02003932
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003933 if (PyString_AsStringAndSize(obj, (char **) &result, NULL) == -1)
3934 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003935 if (result == NULL)
3936 return -1;
3937
3938 if (set_string_copy(result, tv) == -1)
3939 return -1;
3940
3941 tv->v_type = VAR_STRING;
3942 }
3943 else if (PyUnicode_Check(obj))
3944 {
3945 PyObject *bytes;
3946 char_u *result;
3947
Bram Moolenaardb913952012-06-29 12:54:53 +02003948 bytes = PyUnicode_AsEncodedString(obj, (char *)ENC_OPT, NULL);
3949 if (bytes == NULL)
3950 return -1;
3951
Bram Moolenaarafa6b9a2012-09-05 19:09:11 +02003952 if(PyString_AsStringAndSize(bytes, (char **) &result, NULL) == -1)
3953 return -1;
Bram Moolenaardb913952012-06-29 12:54:53 +02003954 if (result == NULL)
3955 return -1;
3956
3957 if (set_string_copy(result, tv) == -1)
3958 {
3959 Py_XDECREF(bytes);
3960 return -1;
3961 }
3962 Py_XDECREF(bytes);
3963
3964 tv->v_type = VAR_STRING;
3965 }
Bram Moolenaar335e0b62013-04-24 13:47:45 +02003966#if PY_MAJOR_VERSION < 3
Bram Moolenaardb913952012-06-29 12:54:53 +02003967 else if (PyInt_Check(obj))
3968 {
3969 tv->v_type = VAR_NUMBER;
3970 tv->vval.v_number = (varnumber_T) PyInt_AsLong(obj);
3971 }
3972#endif
3973 else if (PyLong_Check(obj))
3974 {
3975 tv->v_type = VAR_NUMBER;
3976 tv->vval.v_number = (varnumber_T) PyLong_AsLong(obj);
3977 }
3978 else if (PyDict_Check(obj))
3979 return convert_dl(obj, tv, pydict_to_tv, lookupDict);
3980#ifdef FEAT_FLOAT
3981 else if (PyFloat_Check(obj))
3982 {
3983 tv->v_type = VAR_FLOAT;
3984 tv->vval.v_float = (float_T) PyFloat_AsDouble(obj);
3985 }
3986#endif
3987 else if (PyIter_Check(obj))
3988 return convert_dl(obj, tv, pyiter_to_tv, lookupDict);
3989 else if (PySequence_Check(obj))
3990 return convert_dl(obj, tv, pyseq_to_tv, lookupDict);
3991 else if (PyMapping_Check(obj))
3992 return convert_dl(obj, tv, pymap_to_tv, lookupDict);
3993 else
3994 {
Bram Moolenaar8661b172013-05-15 15:44:28 +02003995 PyErr_SetString(PyExc_TypeError,
3996 _("unable to convert to vim structure"));
Bram Moolenaardb913952012-06-29 12:54:53 +02003997 return -1;
3998 }
3999 return 0;
4000}
4001
4002 static PyObject *
4003ConvertToPyObject(typval_T *tv)
4004{
4005 if (tv == NULL)
4006 {
4007 PyErr_SetVim(_("NULL reference passed"));
4008 return NULL;
4009 }
4010 switch (tv->v_type)
4011 {
4012 case VAR_STRING:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02004013 return PyBytes_FromString(tv->vval.v_string == NULL
4014 ? "" : (char *)tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02004015 case VAR_NUMBER:
4016 return PyLong_FromLong((long) tv->vval.v_number);
4017#ifdef FEAT_FLOAT
4018 case VAR_FLOAT:
4019 return PyFloat_FromDouble((double) tv->vval.v_float);
4020#endif
4021 case VAR_LIST:
4022 return ListNew(tv->vval.v_list);
4023 case VAR_DICT:
4024 return DictionaryNew(tv->vval.v_dict);
4025 case VAR_FUNC:
Bram Moolenaard1f13fd2012-10-05 21:30:07 +02004026 return FunctionNew(tv->vval.v_string == NULL
4027 ? (char_u *)"" : tv->vval.v_string);
Bram Moolenaardb913952012-06-29 12:54:53 +02004028 case VAR_UNKNOWN:
4029 Py_INCREF(Py_None);
4030 return Py_None;
4031 default:
4032 PyErr_SetVim(_("internal error: invalid value type"));
4033 return NULL;
4034 }
4035}
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004036
4037typedef struct
4038{
4039 PyObject_HEAD
4040} CurrentObject;
4041static PyTypeObject CurrentType;
4042
4043 static void
4044init_structs(void)
4045{
4046 vim_memset(&OutputType, 0, sizeof(OutputType));
4047 OutputType.tp_name = "vim.message";
4048 OutputType.tp_basicsize = sizeof(OutputObject);
4049 OutputType.tp_flags = Py_TPFLAGS_DEFAULT;
4050 OutputType.tp_doc = "vim message object";
4051 OutputType.tp_methods = OutputMethods;
4052#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004053 OutputType.tp_getattro = (getattrofunc)OutputGetattro;
4054 OutputType.tp_setattro = (setattrofunc)OutputSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004055 OutputType.tp_alloc = call_PyType_GenericAlloc;
4056 OutputType.tp_new = call_PyType_GenericNew;
4057 OutputType.tp_free = call_PyObject_Free;
4058#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004059 OutputType.tp_getattr = (getattrfunc)OutputGetattr;
4060 OutputType.tp_setattr = (setattrfunc)OutputSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004061#endif
4062
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004063 vim_memset(&IterType, 0, sizeof(IterType));
4064 IterType.tp_name = "vim.iter";
4065 IterType.tp_basicsize = sizeof(IterObject);
4066 IterType.tp_flags = Py_TPFLAGS_DEFAULT;
4067 IterType.tp_doc = "generic iterator object";
Bram Moolenaard6e39182013-05-21 18:30:34 +02004068 IterType.tp_iter = (getiterfunc)IterIter;
4069 IterType.tp_iternext = (iternextfunc)IterNext;
4070 IterType.tp_dealloc = (destructor)IterDestructor;
4071 IterType.tp_traverse = (traverseproc)IterTraverse;
4072 IterType.tp_clear = (inquiry)IterClear;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004073
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004074 vim_memset(&BufferType, 0, sizeof(BufferType));
4075 BufferType.tp_name = "vim.buffer";
4076 BufferType.tp_basicsize = sizeof(BufferType);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004077 BufferType.tp_dealloc = (destructor)BufferDestructor;
4078 BufferType.tp_repr = (reprfunc)BufferRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004079 BufferType.tp_as_sequence = &BufferAsSeq;
4080 BufferType.tp_as_mapping = &BufferAsMapping;
4081 BufferType.tp_flags = Py_TPFLAGS_DEFAULT;
4082 BufferType.tp_doc = "vim buffer object";
4083 BufferType.tp_methods = BufferMethods;
4084#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004085 BufferType.tp_getattro = (getattrofunc)BufferGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004086 BufferType.tp_alloc = call_PyType_GenericAlloc;
4087 BufferType.tp_new = call_PyType_GenericNew;
4088 BufferType.tp_free = call_PyObject_Free;
4089#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004090 BufferType.tp_getattr = (getattrfunc)BufferGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004091#endif
4092
4093 vim_memset(&WindowType, 0, sizeof(WindowType));
4094 WindowType.tp_name = "vim.window";
4095 WindowType.tp_basicsize = sizeof(WindowObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004096 WindowType.tp_dealloc = (destructor)WindowDestructor;
4097 WindowType.tp_repr = (reprfunc)WindowRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004098 WindowType.tp_flags = Py_TPFLAGS_DEFAULT;
4099 WindowType.tp_doc = "vim Window object";
4100 WindowType.tp_methods = WindowMethods;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004101 WindowType.tp_traverse = (traverseproc)WindowTraverse;
4102 WindowType.tp_clear = (inquiry)WindowClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004103#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004104 WindowType.tp_getattro = (getattrofunc)WindowGetattro;
4105 WindowType.tp_setattro = (setattrofunc)WindowSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004106 WindowType.tp_alloc = call_PyType_GenericAlloc;
4107 WindowType.tp_new = call_PyType_GenericNew;
4108 WindowType.tp_free = call_PyObject_Free;
4109#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004110 WindowType.tp_getattr = (getattrfunc)WindowGetattr;
4111 WindowType.tp_setattr = (setattrfunc)WindowSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004112#endif
4113
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004114 vim_memset(&TabPageType, 0, sizeof(TabPageType));
4115 TabPageType.tp_name = "vim.tabpage";
4116 TabPageType.tp_basicsize = sizeof(TabPageObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004117 TabPageType.tp_dealloc = (destructor)TabPageDestructor;
4118 TabPageType.tp_repr = (reprfunc)TabPageRepr;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004119 TabPageType.tp_flags = Py_TPFLAGS_DEFAULT;
4120 TabPageType.tp_doc = "vim tab page object";
4121 TabPageType.tp_methods = TabPageMethods;
4122#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004123 TabPageType.tp_getattro = (getattrofunc)TabPageGetattro;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004124 TabPageType.tp_alloc = call_PyType_GenericAlloc;
4125 TabPageType.tp_new = call_PyType_GenericNew;
4126 TabPageType.tp_free = call_PyObject_Free;
4127#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004128 TabPageType.tp_getattr = (getattrfunc)TabPageGetattr;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004129#endif
4130
Bram Moolenaardfa38d42013-05-15 13:38:47 +02004131 vim_memset(&BufMapType, 0, sizeof(BufMapType));
4132 BufMapType.tp_name = "vim.bufferlist";
4133 BufMapType.tp_basicsize = sizeof(BufMapObject);
4134 BufMapType.tp_as_mapping = &BufMapAsMapping;
4135 BufMapType.tp_flags = Py_TPFLAGS_DEFAULT;
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004136 BufMapType.tp_iter = BufMapIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004137 BufferType.tp_doc = "vim buffer list";
4138
4139 vim_memset(&WinListType, 0, sizeof(WinListType));
4140 WinListType.tp_name = "vim.windowlist";
4141 WinListType.tp_basicsize = sizeof(WinListType);
4142 WinListType.tp_as_sequence = &WinListAsSeq;
4143 WinListType.tp_flags = Py_TPFLAGS_DEFAULT;
4144 WinListType.tp_doc = "vim window list";
Bram Moolenaard6e39182013-05-21 18:30:34 +02004145 WinListType.tp_dealloc = (destructor)WinListDestructor;
Bram Moolenaar5e538ec2013-05-15 15:12:29 +02004146
4147 vim_memset(&TabListType, 0, sizeof(TabListType));
4148 TabListType.tp_name = "vim.tabpagelist";
4149 TabListType.tp_basicsize = sizeof(TabListType);
4150 TabListType.tp_as_sequence = &TabListAsSeq;
4151 TabListType.tp_flags = Py_TPFLAGS_DEFAULT;
4152 TabListType.tp_doc = "vim tab page list";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004153
4154 vim_memset(&RangeType, 0, sizeof(RangeType));
4155 RangeType.tp_name = "vim.range";
4156 RangeType.tp_basicsize = sizeof(RangeObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004157 RangeType.tp_dealloc = (destructor)RangeDestructor;
4158 RangeType.tp_repr = (reprfunc)RangeRepr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004159 RangeType.tp_as_sequence = &RangeAsSeq;
4160 RangeType.tp_as_mapping = &RangeAsMapping;
4161 RangeType.tp_flags = Py_TPFLAGS_DEFAULT;
4162 RangeType.tp_doc = "vim Range object";
4163 RangeType.tp_methods = RangeMethods;
Bram Moolenaar774267b2013-05-21 20:51:59 +02004164 RangeType.tp_traverse = (traverseproc)RangeTraverse;
4165 RangeType.tp_clear = (inquiry)RangeClear;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004166#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004167 RangeType.tp_getattro = (getattrofunc)RangeGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004168 RangeType.tp_alloc = call_PyType_GenericAlloc;
4169 RangeType.tp_new = call_PyType_GenericNew;
4170 RangeType.tp_free = call_PyObject_Free;
4171#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004172 RangeType.tp_getattr = (getattrfunc)RangeGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004173#endif
4174
4175 vim_memset(&CurrentType, 0, sizeof(CurrentType));
4176 CurrentType.tp_name = "vim.currentdata";
4177 CurrentType.tp_basicsize = sizeof(CurrentObject);
4178 CurrentType.tp_flags = Py_TPFLAGS_DEFAULT;
4179 CurrentType.tp_doc = "vim current object";
4180#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004181 CurrentType.tp_getattro = (getattrofunc)CurrentGetattro;
4182 CurrentType.tp_setattro = (setattrofunc)CurrentSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004183#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004184 CurrentType.tp_getattr = (getattrfunc)CurrentGetattr;
4185 CurrentType.tp_setattr = (setattrfunc)CurrentSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004186#endif
4187
4188 vim_memset(&DictionaryType, 0, sizeof(DictionaryType));
4189 DictionaryType.tp_name = "vim.dictionary";
4190 DictionaryType.tp_basicsize = sizeof(DictionaryObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004191 DictionaryType.tp_dealloc = (destructor)DictionaryDestructor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004192 DictionaryType.tp_as_mapping = &DictionaryAsMapping;
4193 DictionaryType.tp_flags = Py_TPFLAGS_DEFAULT;
4194 DictionaryType.tp_doc = "dictionary pushing modifications to vim structure";
4195 DictionaryType.tp_methods = DictionaryMethods;
4196#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004197 DictionaryType.tp_getattro = (getattrofunc)DictionaryGetattro;
4198 DictionaryType.tp_setattro = (setattrofunc)DictionarySetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004199#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004200 DictionaryType.tp_getattr = (getattrfunc)DictionaryGetattr;
4201 DictionaryType.tp_setattr = (setattrfunc)DictionarySetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004202#endif
4203
4204 vim_memset(&ListType, 0, sizeof(ListType));
4205 ListType.tp_name = "vim.list";
Bram Moolenaard6e39182013-05-21 18:30:34 +02004206 ListType.tp_dealloc = (destructor)ListDestructor;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004207 ListType.tp_basicsize = sizeof(ListObject);
4208 ListType.tp_as_sequence = &ListAsSeq;
4209 ListType.tp_as_mapping = &ListAsMapping;
4210 ListType.tp_flags = Py_TPFLAGS_DEFAULT;
4211 ListType.tp_doc = "list pushing modifications to vim structure";
4212 ListType.tp_methods = ListMethods;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004213 ListType.tp_iter = (getiterfunc)ListIter;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004214#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004215 ListType.tp_getattro = (getattrofunc)ListGetattro;
4216 ListType.tp_setattro = (setattrofunc)ListSetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004217#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004218 ListType.tp_getattr = (getattrfunc)ListGetattr;
4219 ListType.tp_setattr = (setattrfunc)ListSetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004220#endif
4221
4222 vim_memset(&FunctionType, 0, sizeof(FunctionType));
Bram Moolenaarb6c589a2013-05-15 14:39:52 +02004223 FunctionType.tp_name = "vim.function";
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004224 FunctionType.tp_basicsize = sizeof(FunctionObject);
Bram Moolenaard6e39182013-05-21 18:30:34 +02004225 FunctionType.tp_dealloc = (destructor)FunctionDestructor;
4226 FunctionType.tp_call = (ternaryfunc)FunctionCall;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004227 FunctionType.tp_flags = Py_TPFLAGS_DEFAULT;
4228 FunctionType.tp_doc = "object that calls vim function";
4229 FunctionType.tp_methods = FunctionMethods;
4230#if PY_MAJOR_VERSION >= 3
Bram Moolenaard6e39182013-05-21 18:30:34 +02004231 FunctionType.tp_getattro = (getattrofunc)FunctionGetattro;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004232#else
Bram Moolenaard6e39182013-05-21 18:30:34 +02004233 FunctionType.tp_getattr = (getattrfunc)FunctionGetattr;
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004234#endif
4235
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02004236 vim_memset(&OptionsType, 0, sizeof(OptionsType));
4237 OptionsType.tp_name = "vim.options";
4238 OptionsType.tp_basicsize = sizeof(OptionsObject);
4239 OptionsType.tp_flags = Py_TPFLAGS_DEFAULT;
4240 OptionsType.tp_doc = "object for manipulating options";
4241 OptionsType.tp_as_mapping = &OptionsAsMapping;
Bram Moolenaard6e39182013-05-21 18:30:34 +02004242 OptionsType.tp_dealloc = (destructor)OptionsDestructor;
4243 OptionsType.tp_traverse = (traverseproc)OptionsTraverse;
4244 OptionsType.tp_clear = (inquiry)OptionsClear;
Bram Moolenaar84e0f6c2013-05-06 03:52:55 +02004245
Bram Moolenaar4d1da492013-04-24 13:39:15 +02004246#if PY_MAJOR_VERSION >= 3
4247 vim_memset(&vimmodule, 0, sizeof(vimmodule));
4248 vimmodule.m_name = "vim";
4249 vimmodule.m_doc = "Vim Python interface\n";
4250 vimmodule.m_size = -1;
4251 vimmodule.m_methods = VimMethods;
4252#endif
4253}
Bram Moolenaar1dc28782013-05-21 19:11:01 +02004254
4255#define PYTYPE_READY(type) \
4256 if (PyType_Ready(&type)) \
4257 return -1;
4258
4259 static int
4260init_types()
4261{
4262 PYTYPE_READY(IterType);
4263 PYTYPE_READY(BufferType);
4264 PYTYPE_READY(RangeType);
4265 PYTYPE_READY(WindowType);
4266 PYTYPE_READY(TabPageType);
4267 PYTYPE_READY(BufMapType);
4268 PYTYPE_READY(WinListType);
4269 PYTYPE_READY(TabListType);
4270 PYTYPE_READY(CurrentType);
4271 PYTYPE_READY(DictionaryType);
4272 PYTYPE_READY(ListType);
4273 PYTYPE_READY(FunctionType);
4274 PYTYPE_READY(OptionsType);
4275 PYTYPE_READY(OutputType);
4276 return 0;
4277}
4278
4279static BufMapObject TheBufferMap =
4280{
4281 PyObject_HEAD_INIT(&BufMapType)
4282};
4283
4284static WinListObject TheWindowList =
4285{
4286 PyObject_HEAD_INIT(&WinListType)
4287 NULL
4288};
4289
4290static CurrentObject TheCurrent =
4291{
4292 PyObject_HEAD_INIT(&CurrentType)
4293};
4294
4295static TabListObject TheTabPageList =
4296{
4297 PyObject_HEAD_INIT(&TabListType)
4298};
4299
4300static struct numeric_constant {
4301 char *name;
4302 int value;
4303} numeric_constants[] = {
4304 {"VAR_LOCKED", VAR_LOCKED},
4305 {"VAR_FIXED", VAR_FIXED},
4306 {"VAR_SCOPE", VAR_SCOPE},
4307 {"VAR_DEF_SCOPE", VAR_DEF_SCOPE},
4308};
4309
4310static struct object_constant {
4311 char *name;
4312 PyObject *value;
4313} object_constants[] = {
4314 {"buffers", (PyObject *)(void *)&TheBufferMap},
4315 {"windows", (PyObject *)(void *)&TheWindowList},
4316 {"tabpages", (PyObject *)(void *)&TheTabPageList},
4317 {"current", (PyObject *)(void *)&TheCurrent},
Bram Moolenaarcac867a2013-05-21 19:50:34 +02004318
4319 {"Buffer", (PyObject *)&BufferType},
4320 {"Range", (PyObject *)&RangeType},
4321 {"Window", (PyObject *)&WindowType},
4322 {"TabPage", (PyObject *)&TabPageType},
4323 {"Dictionary", (PyObject *)&DictionaryType},
4324 {"List", (PyObject *)&ListType},
4325 {"Function", (PyObject *)&FunctionType},
4326 {"Options", (PyObject *)&OptionsType},
Bram Moolenaar1dc28782013-05-21 19:11:01 +02004327};
4328
4329typedef int (*object_adder)(PyObject *, const char *, PyObject *);
4330
4331#define ADD_OBJECT(m, name, obj) \
4332 if (add_object(m, name, obj)) \
4333 return -1;
4334
4335#define ADD_CHECKED_OBJECT(m, name, obj) \
4336 { \
4337 PyObject *value = obj; \
4338 if (!value) \
4339 return -1; \
4340 ADD_OBJECT(m, name, value); \
4341 }
4342
4343 static int
4344populate_module(PyObject *m, object_adder add_object)
4345{
4346 int i;
4347
4348 for (i = 0; i < (int)(sizeof(numeric_constants)
4349 / sizeof(struct numeric_constant));
4350 ++i)
4351 ADD_CHECKED_OBJECT(m, numeric_constants[i].name,
4352 PyInt_FromLong(numeric_constants[i].value));
4353
4354 for (i = 0; i < (int)(sizeof(object_constants)
4355 / sizeof(struct object_constant));
4356 ++i)
4357 {
4358 PyObject *value;
4359
4360 value = object_constants[i].value;
4361 Py_INCREF(value);
4362 ADD_OBJECT(m, object_constants[i].name, value);
4363 }
4364
4365 if (!(VimError = PyErr_NewException("vim.error", NULL, NULL)))
4366 return -1;
4367 ADD_OBJECT(m, "error", VimError);
4368
4369 ADD_CHECKED_OBJECT(m, "vars", DictionaryNew(&globvardict));
4370 ADD_CHECKED_OBJECT(m, "vvars", DictionaryNew(&vimvardict));
4371 ADD_CHECKED_OBJECT(m, "options",
4372 OptionsNew(SREQ_GLOBAL, NULL, dummy_check, NULL));
4373 return 0;
4374}