fork for IVI
[profile/ivi/vim.git] / src / if_py_both.h
1 /* vi:set ts=8 sts=4 sw=4:
2  *
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 /*
10  * Python extensions by Paul Moore, David Leonard, Roland Puntaier.
11  *
12  * Common code for if_python.c and if_python3.c.
13  */
14
15 #ifdef FEAT_MBYTE
16 # define ENC_OPT p_enc
17 #else
18 # define ENC_OPT "latin1"
19 #endif
20
21 /*
22  * obtain a lock on the Vim data structures
23  */
24     static void
25 Python_Lock_Vim(void)
26 {
27 }
28
29 /*
30  * release a lock on the Vim data structures
31  */
32     static void
33 Python_Release_Vim(void)
34 {
35 }
36
37 /* Output object definition
38  */
39
40 static PyObject *OutputWrite(PyObject *, PyObject *);
41 static PyObject *OutputWritelines(PyObject *, PyObject *);
42 static PyObject *OutputFlush(PyObject *, PyObject *);
43
44 /* Function to write a line, points to either msg() or emsg(). */
45 typedef void (*writefn)(char_u *);
46 static void writer(writefn fn, char_u *str, PyInt n);
47
48 typedef struct
49 {
50     PyObject_HEAD
51     long softspace;
52     long error;
53 } OutputObject;
54
55 static struct PyMethodDef OutputMethods[] = {
56     /* name,        function,           calling,    documentation */
57     {"write",       OutputWrite,        1,          ""},
58     {"writelines",  OutputWritelines,   1,          ""},
59     {"flush",       OutputFlush,        1,          ""},
60     { NULL,         NULL,               0,          NULL}
61 };
62
63 #define PyErr_SetVim(str) PyErr_SetString(VimError, str)
64
65 /*************/
66
67 /* Output buffer management
68  */
69
70     static PyObject *
71 OutputWrite(PyObject *self, PyObject *args)
72 {
73     int len;
74     char *str = NULL;
75     int error = ((OutputObject *)(self))->error;
76
77     if (!PyArg_ParseTuple(args, "et#", ENC_OPT, &str, &len))
78         return NULL;
79
80     Py_BEGIN_ALLOW_THREADS
81     Python_Lock_Vim();
82     writer((writefn)(error ? emsg : msg), (char_u *)str, len);
83     Python_Release_Vim();
84     Py_END_ALLOW_THREADS
85     PyMem_Free(str);
86
87     Py_INCREF(Py_None);
88     return Py_None;
89 }
90
91     static PyObject *
92 OutputWritelines(PyObject *self, PyObject *args)
93 {
94     PyInt n;
95     PyInt i;
96     PyObject *list;
97     int error = ((OutputObject *)(self))->error;
98
99     if (!PyArg_ParseTuple(args, "O", &list))
100         return NULL;
101     Py_INCREF(list);
102
103     if (!PyList_Check(list)) {
104         PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
105         Py_DECREF(list);
106         return NULL;
107     }
108
109     n = PyList_Size(list);
110
111     for (i = 0; i < n; ++i)
112     {
113         PyObject *line = PyList_GetItem(list, i);
114         char *str = NULL;
115         PyInt len;
116
117         if (!PyArg_Parse(line, "et#", ENC_OPT, &str, &len)) {
118             PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings"));
119             Py_DECREF(list);
120             return NULL;
121         }
122
123         Py_BEGIN_ALLOW_THREADS
124         Python_Lock_Vim();
125         writer((writefn)(error ? emsg : msg), (char_u *)str, len);
126         Python_Release_Vim();
127         Py_END_ALLOW_THREADS
128         PyMem_Free(str);
129     }
130
131     Py_DECREF(list);
132     Py_INCREF(Py_None);
133     return Py_None;
134 }
135
136     static PyObject *
137 OutputFlush(PyObject *self UNUSED, PyObject *args UNUSED)
138 {
139     /* do nothing */
140     Py_INCREF(Py_None);
141     return Py_None;
142 }
143
144
145 /* Buffer IO, we write one whole line at a time. */
146 static garray_T io_ga = {0, 0, 1, 80, NULL};
147 static writefn old_fn = NULL;
148
149     static void
150 PythonIO_Flush(void)
151 {
152     if (old_fn != NULL && io_ga.ga_len > 0)
153     {
154         ((char_u *)io_ga.ga_data)[io_ga.ga_len] = NUL;
155         old_fn((char_u *)io_ga.ga_data);
156     }
157     io_ga.ga_len = 0;
158 }
159
160     static void
161 writer(writefn fn, char_u *str, PyInt n)
162 {
163     char_u *ptr;
164
165     /* Flush when switching output function. */
166     if (fn != old_fn)
167         PythonIO_Flush();
168     old_fn = fn;
169
170     /* Write each NL separated line.  Text after the last NL is kept for
171      * writing later. */
172     while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL)
173     {
174         PyInt len = ptr - str;
175
176         if (ga_grow(&io_ga, (int)(len + 1)) == FAIL)
177             break;
178
179         mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)len);
180         ((char *)io_ga.ga_data)[io_ga.ga_len + len] = NUL;
181         fn((char_u *)io_ga.ga_data);
182         str = ptr + 1;
183         n -= len + 1;
184         io_ga.ga_len = 0;
185     }
186
187     /* Put the remaining text into io_ga for later printing. */
188     if (n > 0 && ga_grow(&io_ga, (int)(n + 1)) == OK)
189     {
190         mch_memmove(((char *)io_ga.ga_data) + io_ga.ga_len, str, (size_t)n);
191         io_ga.ga_len += (int)n;
192     }
193 }
194
195 /***************/
196
197 static PyTypeObject OutputType;
198
199 static OutputObject Output =
200 {
201     PyObject_HEAD_INIT(&OutputType)
202     0,
203     0
204 };
205
206 static OutputObject Error =
207 {
208     PyObject_HEAD_INIT(&OutputType)
209     0,
210     1
211 };
212
213     static int
214 PythonIO_Init_io(void)
215 {
216     PySys_SetObject("stdout", (PyObject *)(void *)&Output);
217     PySys_SetObject("stderr", (PyObject *)(void *)&Error);
218
219     if (PyErr_Occurred())
220     {
221         EMSG(_("E264: Python: Error initialising I/O objects"));
222         return -1;
223     }
224
225     return 0;
226 }
227
228
229 static PyObject *VimError;
230
231 /* Check to see whether a Vim error has been reported, or a keyboard
232  * interrupt has been detected.
233  */
234     static int
235 VimErrorCheck(void)
236 {
237     if (got_int)
238     {
239         PyErr_SetNone(PyExc_KeyboardInterrupt);
240         return 1;
241     }
242     else if (did_emsg && !PyErr_Occurred())
243     {
244         PyErr_SetNone(VimError);
245         return 1;
246     }
247
248     return 0;
249 }
250
251 /* Vim module - Implementation
252  */
253     static PyObject *
254 VimCommand(PyObject *self UNUSED, PyObject *args)
255 {
256     char *cmd;
257     PyObject *result;
258
259     if (!PyArg_ParseTuple(args, "s", &cmd))
260         return NULL;
261
262     PyErr_Clear();
263
264     Py_BEGIN_ALLOW_THREADS
265     Python_Lock_Vim();
266
267     do_cmdline_cmd((char_u *)cmd);
268     update_screen(VALID);
269
270     Python_Release_Vim();
271     Py_END_ALLOW_THREADS
272
273     if (VimErrorCheck())
274         result = NULL;
275     else
276         result = Py_None;
277
278     Py_XINCREF(result);
279     return result;
280 }
281
282 #ifdef FEAT_EVAL
283 /*
284  * Function to translate a typval_T into a PyObject; this will recursively
285  * translate lists/dictionaries into their Python equivalents.
286  *
287  * The depth parameter is to avoid infinite recursion, set it to 1 when
288  * you call VimToPython.
289  */
290     static PyObject *
291 VimToPython(typval_T *our_tv, int depth, PyObject *lookupDict)
292 {
293     PyObject    *result;
294     PyObject    *newObj;
295     char        ptrBuf[NUMBUFLEN];
296
297     /* Avoid infinite recursion */
298     if (depth > 100)
299     {
300         Py_INCREF(Py_None);
301         result = Py_None;
302         return result;
303     }
304
305     /* Check if we run into a recursive loop.  The item must be in lookupDict
306      * then and we can use it again. */
307     if ((our_tv->v_type == VAR_LIST && our_tv->vval.v_list != NULL)
308             || (our_tv->v_type == VAR_DICT && our_tv->vval.v_dict != NULL))
309     {
310         sprintf(ptrBuf, PRINTF_DECIMAL_LONG_U,
311                 our_tv->v_type == VAR_LIST ? (long_u)our_tv->vval.v_list
312                                            : (long_u)our_tv->vval.v_dict);
313         result = PyDict_GetItemString(lookupDict, ptrBuf);
314         if (result != NULL)
315         {
316             Py_INCREF(result);
317             return result;
318         }
319     }
320
321     if (our_tv->v_type == VAR_STRING)
322     {
323         result = Py_BuildValue("s", our_tv->vval.v_string);
324     }
325     else if (our_tv->v_type == VAR_NUMBER)
326     {
327         char buf[NUMBUFLEN];
328
329         /* For backwards compatibility numbers are stored as strings. */
330         sprintf(buf, "%ld", (long)our_tv->vval.v_number);
331         result = Py_BuildValue("s", buf);
332     }
333 # ifdef FEAT_FLOAT
334     else if (our_tv->v_type == VAR_FLOAT)
335     {
336         char buf[NUMBUFLEN];
337
338         sprintf(buf, "%f", our_tv->vval.v_float);
339         result = Py_BuildValue("s", buf);
340     }
341 # endif
342     else if (our_tv->v_type == VAR_LIST)
343     {
344         list_T          *list = our_tv->vval.v_list;
345         listitem_T      *curr;
346
347         result = PyList_New(0);
348
349         if (list != NULL)
350         {
351             PyDict_SetItemString(lookupDict, ptrBuf, result);
352
353             for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
354             {
355                 newObj = VimToPython(&curr->li_tv, depth + 1, lookupDict);
356                 PyList_Append(result, newObj);
357                 Py_DECREF(newObj);
358             }
359         }
360     }
361     else if (our_tv->v_type == VAR_DICT)
362     {
363         result = PyDict_New();
364
365         if (our_tv->vval.v_dict != NULL)
366         {
367             hashtab_T   *ht = &our_tv->vval.v_dict->dv_hashtab;
368             long_u      todo = ht->ht_used;
369             hashitem_T  *hi;
370             dictitem_T  *di;
371
372             PyDict_SetItemString(lookupDict, ptrBuf, result);
373
374             for (hi = ht->ht_array; todo > 0; ++hi)
375             {
376                 if (!HASHITEM_EMPTY(hi))
377                 {
378                     --todo;
379
380                     di = dict_lookup(hi);
381                     newObj = VimToPython(&di->di_tv, depth + 1, lookupDict);
382                     PyDict_SetItemString(result, (char *)hi->hi_key, newObj);
383                     Py_DECREF(newObj);
384                 }
385             }
386         }
387     }
388     else
389     {
390         Py_INCREF(Py_None);
391         result = Py_None;
392     }
393
394     return result;
395 }
396 #endif
397
398     static PyObject *
399 VimEval(PyObject *self UNUSED, PyObject *args UNUSED)
400 {
401 #ifdef FEAT_EVAL
402     char        *expr;
403     typval_T    *our_tv;
404     PyObject    *result;
405     PyObject    *lookup_dict;
406
407     if (!PyArg_ParseTuple(args, "s", &expr))
408         return NULL;
409
410     Py_BEGIN_ALLOW_THREADS
411     Python_Lock_Vim();
412     our_tv = eval_expr((char_u *)expr, NULL);
413
414     Python_Release_Vim();
415     Py_END_ALLOW_THREADS
416
417     if (our_tv == NULL)
418     {
419         PyErr_SetVim(_("invalid expression"));
420         return NULL;
421     }
422
423     /* Convert the Vim type into a Python type.  Create a dictionary that's
424      * used to check for recursive loops. */
425     lookup_dict = PyDict_New();
426     result = VimToPython(our_tv, 1, lookup_dict);
427     Py_DECREF(lookup_dict);
428
429
430     Py_BEGIN_ALLOW_THREADS
431     Python_Lock_Vim();
432     free_tv(our_tv);
433     Python_Release_Vim();
434     Py_END_ALLOW_THREADS
435
436     return result;
437 #else
438     PyErr_SetVim(_("expressions disabled at compile time"));
439     return NULL;
440 #endif
441 }
442
443 /*
444  * Vim module - Definitions
445  */
446
447 static struct PyMethodDef VimMethods[] = {
448     /* name,         function,          calling,    documentation */
449     {"command",      VimCommand,        1,          "Execute a Vim ex-mode command" },
450     {"eval",         VimEval,           1,          "Evaluate an expression using Vim evaluator" },
451     { NULL,          NULL,              0,          NULL }
452 };
453
454 typedef struct
455 {
456     PyObject_HEAD
457     buf_T *buf;
458 }
459 BufferObject;
460
461 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
462
463 /*
464  * Buffer list object - Implementation
465  */
466
467     static PyInt
468 BufListLength(PyObject *self UNUSED)
469 {
470     buf_T       *b = firstbuf;
471     PyInt       n = 0;
472
473     while (b)
474     {
475         ++n;
476         b = b->b_next;
477     }
478
479     return n;
480 }
481
482     static PyObject *
483 BufListItem(PyObject *self UNUSED, PyInt n)
484 {
485     buf_T *b;
486
487     for (b = firstbuf; b; b = b->b_next, --n)
488     {
489         if (n == 0)
490             return BufferNew(b);
491     }
492
493     PyErr_SetString(PyExc_IndexError, _("no such buffer"));
494     return NULL;
495 }
496
497 typedef struct
498 {
499     PyObject_HEAD
500     win_T       *win;
501 } WindowObject;
502
503 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
504
505     static int
506 CheckWindow(WindowObject *this)
507 {
508     if (this->win == INVALID_WINDOW_VALUE)
509     {
510         PyErr_SetVim(_("attempt to refer to deleted window"));
511         return -1;
512     }
513
514     return 0;
515 }
516
517 static int WindowSetattr(PyObject *, char *, PyObject *);
518 static PyObject *WindowRepr(PyObject *);
519
520     static int
521 WindowSetattr(PyObject *self, char *name, PyObject *val)
522 {
523     WindowObject *this = (WindowObject *)(self);
524
525     if (CheckWindow(this))
526         return -1;
527
528     if (strcmp(name, "buffer") == 0)
529     {
530         PyErr_SetString(PyExc_TypeError, _("readonly attribute"));
531         return -1;
532     }
533     else if (strcmp(name, "cursor") == 0)
534     {
535         long lnum;
536         long col;
537
538         if (!PyArg_Parse(val, "(ll)", &lnum, &col))
539             return -1;
540
541         if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count)
542         {
543             PyErr_SetVim(_("cursor position outside buffer"));
544             return -1;
545         }
546
547         /* Check for keyboard interrupts */
548         if (VimErrorCheck())
549             return -1;
550
551         this->win->w_cursor.lnum = lnum;
552         this->win->w_cursor.col = col;
553 #ifdef FEAT_VIRTUALEDIT
554         this->win->w_cursor.coladd = 0;
555 #endif
556         /* When column is out of range silently correct it. */
557         check_cursor_col_win(this->win);
558
559         update_screen(VALID);
560         return 0;
561     }
562     else if (strcmp(name, "height") == 0)
563     {
564         int     height;
565         win_T   *savewin;
566
567         if (!PyArg_Parse(val, "i", &height))
568             return -1;
569
570 #ifdef FEAT_GUI
571         need_mouse_correct = TRUE;
572 #endif
573         savewin = curwin;
574         curwin = this->win;
575         win_setheight(height);
576         curwin = savewin;
577
578         /* Check for keyboard interrupts */
579         if (VimErrorCheck())
580             return -1;
581
582         return 0;
583     }
584 #ifdef FEAT_VERTSPLIT
585     else if (strcmp(name, "width") == 0)
586     {
587         int     width;
588         win_T   *savewin;
589
590         if (!PyArg_Parse(val, "i", &width))
591             return -1;
592
593 #ifdef FEAT_GUI
594         need_mouse_correct = TRUE;
595 #endif
596         savewin = curwin;
597         curwin = this->win;
598         win_setwidth(width);
599         curwin = savewin;
600
601         /* Check for keyboard interrupts */
602         if (VimErrorCheck())
603             return -1;
604
605         return 0;
606     }
607 #endif
608     else
609     {
610         PyErr_SetString(PyExc_AttributeError, name);
611         return -1;
612     }
613 }
614
615     static PyObject *
616 WindowRepr(PyObject *self)
617 {
618     static char repr[100];
619     WindowObject *this = (WindowObject *)(self);
620
621     if (this->win == INVALID_WINDOW_VALUE)
622     {
623         vim_snprintf(repr, 100, _("<window object (deleted) at %p>"), (self));
624         return PyString_FromString(repr);
625     }
626     else
627     {
628         int     i = 0;
629         win_T   *w;
630
631         for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w))
632             ++i;
633
634         if (w == NULL)
635             vim_snprintf(repr, 100, _("<window object (unknown) at %p>"),
636                                                                       (self));
637         else
638             vim_snprintf(repr, 100, _("<window %d>"), i);
639
640         return PyString_FromString(repr);
641     }
642 }
643
644 /*
645  * Window list object - Implementation
646  */
647     static PyInt
648 WinListLength(PyObject *self UNUSED)
649 {
650     win_T       *w = firstwin;
651     PyInt       n = 0;
652
653     while (w != NULL)
654     {
655         ++n;
656         w = W_NEXT(w);
657     }
658
659     return n;
660 }
661
662     static PyObject *
663 WinListItem(PyObject *self UNUSED, PyInt n)
664 {
665     win_T *w;
666
667     for (w = firstwin; w != NULL; w = W_NEXT(w), --n)
668         if (n == 0)
669             return WindowNew(w);
670
671     PyErr_SetString(PyExc_IndexError, _("no such window"));
672     return NULL;
673 }
674
675 /* Convert a Python string into a Vim line.
676  *
677  * The result is in allocated memory. All internal nulls are replaced by
678  * newline characters. It is an error for the string to contain newline
679  * characters.
680  *
681  * On errors, the Python exception data is set, and NULL is returned.
682  */
683     static char *
684 StringToLine(PyObject *obj)
685 {
686     const char *str;
687     char *save;
688     PyObject *bytes;
689     PyInt len;
690     PyInt i;
691     char *p;
692
693     if (obj == NULL || !PyString_Check(obj))
694     {
695         PyErr_BadArgument();
696         return NULL;
697     }
698
699     bytes = PyString_AsBytes(obj);  /* for Python 2 this does nothing */
700     str = PyString_AsString(bytes);
701     len = PyString_Size(bytes);
702
703     /*
704      * Error checking: String must not contain newlines, as we
705      * are replacing a single line, and we must replace it with
706      * a single line.
707      * A trailing newline is removed, so that append(f.readlines()) works.
708      */
709     p = memchr(str, '\n', len);
710     if (p != NULL)
711     {
712         if (p == str + len - 1)
713             --len;
714         else
715         {
716             PyErr_SetVim(_("string cannot contain newlines"));
717             return NULL;
718         }
719     }
720
721     /* Create a copy of the string, with internal nulls replaced by
722      * newline characters, as is the vim convention.
723      */
724     save = (char *)alloc((unsigned)(len+1));
725     if (save == NULL)
726     {
727         PyErr_NoMemory();
728         return NULL;
729     }
730
731     for (i = 0; i < len; ++i)
732     {
733         if (str[i] == '\0')
734             save[i] = '\n';
735         else
736             save[i] = str[i];
737     }
738
739     save[i] = '\0';
740     PyString_FreeBytes(bytes);  /* Python 2 does nothing here */
741
742     return save;
743 }
744
745 /* Get a line from the specified buffer. The line number is
746  * in Vim format (1-based). The line is returned as a Python
747  * string object.
748  */
749     static PyObject *
750 GetBufferLine(buf_T *buf, PyInt n)
751 {
752     return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE));
753 }
754
755
756 /* Get a list of lines from the specified buffer. The line numbers
757  * are in Vim format (1-based). The range is from lo up to, but not
758  * including, hi. The list is returned as a Python list of string objects.
759  */
760     static PyObject *
761 GetBufferLineList(buf_T *buf, PyInt lo, PyInt hi)
762 {
763     PyInt i;
764     PyInt n = hi - lo;
765     PyObject *list = PyList_New(n);
766
767     if (list == NULL)
768         return NULL;
769
770     for (i = 0; i < n; ++i)
771     {
772         PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE));
773
774         /* Error check - was the Python string creation OK? */
775         if (str == NULL)
776         {
777             Py_DECREF(list);
778             return NULL;
779         }
780
781         /* Set the list item */
782         if (PyList_SetItem(list, i, str))
783         {
784             Py_DECREF(str);
785             Py_DECREF(list);
786             return NULL;
787         }
788     }
789
790     /* The ownership of the Python list is passed to the caller (ie,
791      * the caller should Py_DECREF() the object when it is finished
792      * with it).
793      */
794
795     return list;
796 }
797
798 /*
799  * Check if deleting lines made the cursor position invalid.
800  * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
801  * deleted).
802  */
803     static void
804 py_fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
805 {
806     if (curwin->w_cursor.lnum >= lo)
807     {
808         /* Adjust the cursor position if it's in/after the changed
809          * lines. */
810         if (curwin->w_cursor.lnum >= hi)
811         {
812             curwin->w_cursor.lnum += extra;
813             check_cursor_col();
814         }
815         else if (extra < 0)
816         {
817             curwin->w_cursor.lnum = lo;
818             check_cursor();
819         }
820         else
821             check_cursor_col();
822         changed_cline_bef_curs();
823     }
824     invalidate_botline();
825 }
826
827 /*
828  * Replace a line in the specified buffer. The line number is
829  * in Vim format (1-based). The replacement line is given as
830  * a Python string object. The object is checked for validity
831  * and correct format. Errors are returned as a value of FAIL.
832  * The return value is OK on success.
833  * If OK is returned and len_change is not NULL, *len_change
834  * is set to the change in the buffer length.
835  */
836     static int
837 SetBufferLine(buf_T *buf, PyInt n, PyObject *line, PyInt *len_change)
838 {
839     /* First of all, we check the thpe of the supplied Python object.
840      * There are three cases:
841      *    1. NULL, or None - this is a deletion.
842      *    2. A string      - this is a replacement.
843      *    3. Anything else - this is an error.
844      */
845     if (line == Py_None || line == NULL)
846     {
847         buf_T *savebuf = curbuf;
848
849         PyErr_Clear();
850         curbuf = buf;
851
852         if (u_savedel((linenr_T)n, 1L) == FAIL)
853             PyErr_SetVim(_("cannot save undo information"));
854         else if (ml_delete((linenr_T)n, FALSE) == FAIL)
855             PyErr_SetVim(_("cannot delete line"));
856         else
857         {
858             if (buf == curwin->w_buffer)
859                 py_fix_cursor((linenr_T)n, (linenr_T)n + 1, (linenr_T)-1);
860             deleted_lines_mark((linenr_T)n, 1L);
861         }
862
863         curbuf = savebuf;
864
865         if (PyErr_Occurred() || VimErrorCheck())
866             return FAIL;
867
868         if (len_change)
869             *len_change = -1;
870
871         return OK;
872     }
873     else if (PyString_Check(line))
874     {
875         char *save = StringToLine(line);
876         buf_T *savebuf = curbuf;
877
878         if (save == NULL)
879             return FAIL;
880
881         /* We do not need to free "save" if ml_replace() consumes it. */
882         PyErr_Clear();
883         curbuf = buf;
884
885         if (u_savesub((linenr_T)n) == FAIL)
886         {
887             PyErr_SetVim(_("cannot save undo information"));
888             vim_free(save);
889         }
890         else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL)
891         {
892             PyErr_SetVim(_("cannot replace line"));
893             vim_free(save);
894         }
895         else
896             changed_bytes((linenr_T)n, 0);
897
898         curbuf = savebuf;
899
900         /* Check that the cursor is not beyond the end of the line now. */
901         if (buf == curwin->w_buffer)
902             check_cursor_col();
903
904         if (PyErr_Occurred() || VimErrorCheck())
905             return FAIL;
906
907         if (len_change)
908             *len_change = 0;
909
910         return OK;
911     }
912     else
913     {
914         PyErr_BadArgument();
915         return FAIL;
916     }
917 }
918
919 /* Replace a range of lines in the specified buffer. The line numbers are in
920  * Vim format (1-based). The range is from lo up to, but not including, hi.
921  * The replacement lines are given as a Python list of string objects. The
922  * list is checked for validity and correct format. Errors are returned as a
923  * value of FAIL.  The return value is OK on success.
924  * If OK is returned and len_change is not NULL, *len_change
925  * is set to the change in the buffer length.
926  */
927     static int
928 SetBufferLineList(buf_T *buf, PyInt lo, PyInt hi, PyObject *list, PyInt *len_change)
929 {
930     /* First of all, we check the thpe of the supplied Python object.
931      * There are three cases:
932      *    1. NULL, or None - this is a deletion.
933      *    2. A list        - this is a replacement.
934      *    3. Anything else - this is an error.
935      */
936     if (list == Py_None || list == NULL)
937     {
938         PyInt   i;
939         PyInt   n = (int)(hi - lo);
940         buf_T   *savebuf = curbuf;
941
942         PyErr_Clear();
943         curbuf = buf;
944
945         if (u_savedel((linenr_T)lo, (long)n) == FAIL)
946             PyErr_SetVim(_("cannot save undo information"));
947         else
948         {
949             for (i = 0; i < n; ++i)
950             {
951                 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
952                 {
953                     PyErr_SetVim(_("cannot delete line"));
954                     break;
955                 }
956             }
957             if (buf == curwin->w_buffer)
958                 py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)-n);
959             deleted_lines_mark((linenr_T)lo, (long)i);
960         }
961
962         curbuf = savebuf;
963
964         if (PyErr_Occurred() || VimErrorCheck())
965             return FAIL;
966
967         if (len_change)
968             *len_change = -n;
969
970         return OK;
971     }
972     else if (PyList_Check(list))
973     {
974         PyInt   i;
975         PyInt   new_len = PyList_Size(list);
976         PyInt   old_len = hi - lo;
977         PyInt   extra = 0;      /* lines added to text, can be negative */
978         char    **array;
979         buf_T   *savebuf;
980
981         if (new_len == 0)       /* avoid allocating zero bytes */
982             array = NULL;
983         else
984         {
985             array = (char **)alloc((unsigned)(new_len * sizeof(char *)));
986             if (array == NULL)
987             {
988                 PyErr_NoMemory();
989                 return FAIL;
990             }
991         }
992
993         for (i = 0; i < new_len; ++i)
994         {
995             PyObject *line = PyList_GetItem(list, i);
996
997             array[i] = StringToLine(line);
998             if (array[i] == NULL)
999             {
1000                 while (i)
1001                     vim_free(array[--i]);
1002                 vim_free(array);
1003                 return FAIL;
1004             }
1005         }
1006
1007         savebuf = curbuf;
1008
1009         PyErr_Clear();
1010         curbuf = buf;
1011
1012         if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
1013             PyErr_SetVim(_("cannot save undo information"));
1014
1015         /* If the size of the range is reducing (ie, new_len < old_len) we
1016          * need to delete some old_len. We do this at the start, by
1017          * repeatedly deleting line "lo".
1018          */
1019         if (!PyErr_Occurred())
1020         {
1021             for (i = 0; i < old_len - new_len; ++i)
1022                 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
1023                 {
1024                     PyErr_SetVim(_("cannot delete line"));
1025                     break;
1026                 }
1027             extra -= i;
1028         }
1029
1030         /* For as long as possible, replace the existing old_len with the
1031          * new old_len. This is a more efficient operation, as it requires
1032          * less memory allocation and freeing.
1033          */
1034         if (!PyErr_Occurred())
1035         {
1036             for (i = 0; i < old_len && i < new_len; ++i)
1037                 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE)
1038                                                                       == FAIL)
1039                 {
1040                     PyErr_SetVim(_("cannot replace line"));
1041                     break;
1042                 }
1043         }
1044         else
1045             i = 0;
1046
1047         /* Now we may need to insert the remaining new old_len. If we do, we
1048          * must free the strings as we finish with them (we can't pass the
1049          * responsibility to vim in this case).
1050          */
1051         if (!PyErr_Occurred())
1052         {
1053             while (i < new_len)
1054             {
1055                 if (ml_append((linenr_T)(lo + i - 1),
1056                                         (char_u *)array[i], 0, FALSE) == FAIL)
1057                 {
1058                     PyErr_SetVim(_("cannot insert line"));
1059                     break;
1060                 }
1061                 vim_free(array[i]);
1062                 ++i;
1063                 ++extra;
1064             }
1065         }
1066
1067         /* Free any left-over old_len, as a result of an error */
1068         while (i < new_len)
1069         {
1070             vim_free(array[i]);
1071             ++i;
1072         }
1073
1074         /* Free the array of old_len. All of its contents have now
1075          * been dealt with (either freed, or the responsibility passed
1076          * to vim.
1077          */
1078         vim_free(array);
1079
1080         /* Adjust marks. Invalidate any which lie in the
1081          * changed range, and move any in the remainder of the buffer.
1082          */
1083         mark_adjust((linenr_T)lo, (linenr_T)(hi - 1),
1084                                                   (long)MAXLNUM, (long)extra);
1085         changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
1086
1087         if (buf == curwin->w_buffer)
1088             py_fix_cursor((linenr_T)lo, (linenr_T)hi, (linenr_T)extra);
1089
1090         curbuf = savebuf;
1091
1092         if (PyErr_Occurred() || VimErrorCheck())
1093             return FAIL;
1094
1095         if (len_change)
1096             *len_change = new_len - old_len;
1097
1098         return OK;
1099     }
1100     else
1101     {
1102         PyErr_BadArgument();
1103         return FAIL;
1104     }
1105 }
1106
1107 /* Insert a number of lines into the specified buffer after the specifed line.
1108  * The line number is in Vim format (1-based). The lines to be inserted are
1109  * given as a Python list of string objects or as a single string. The lines
1110  * to be added are checked for validity and correct format. Errors are
1111  * returned as a value of FAIL.  The return value is OK on success.
1112  * If OK is returned and len_change is not NULL, *len_change
1113  * is set to the change in the buffer length.
1114  */
1115     static int
1116 InsertBufferLines(buf_T *buf, PyInt n, PyObject *lines, PyInt *len_change)
1117 {
1118     /* First of all, we check the type of the supplied Python object.
1119      * It must be a string or a list, or the call is in error.
1120      */
1121     if (PyString_Check(lines))
1122     {
1123         char    *str = StringToLine(lines);
1124         buf_T   *savebuf;
1125
1126         if (str == NULL)
1127             return FAIL;
1128
1129         savebuf = curbuf;
1130
1131         PyErr_Clear();
1132         curbuf = buf;
1133
1134         if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
1135             PyErr_SetVim(_("cannot save undo information"));
1136         else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
1137             PyErr_SetVim(_("cannot insert line"));
1138         else
1139             appended_lines_mark((linenr_T)n, 1L);
1140
1141         vim_free(str);
1142         curbuf = savebuf;
1143         update_screen(VALID);
1144
1145         if (PyErr_Occurred() || VimErrorCheck())
1146             return FAIL;
1147
1148         if (len_change)
1149             *len_change = 1;
1150
1151         return OK;
1152     }
1153     else if (PyList_Check(lines))
1154     {
1155         PyInt   i;
1156         PyInt   size = PyList_Size(lines);
1157         char    **array;
1158         buf_T   *savebuf;
1159
1160         array = (char **)alloc((unsigned)(size * sizeof(char *)));
1161         if (array == NULL)
1162         {
1163             PyErr_NoMemory();
1164             return FAIL;
1165         }
1166
1167         for (i = 0; i < size; ++i)
1168         {
1169             PyObject *line = PyList_GetItem(lines, i);
1170             array[i] = StringToLine(line);
1171
1172             if (array[i] == NULL)
1173             {
1174                 while (i)
1175                     vim_free(array[--i]);
1176                 vim_free(array);
1177                 return FAIL;
1178             }
1179         }
1180
1181         savebuf = curbuf;
1182
1183         PyErr_Clear();
1184         curbuf = buf;
1185
1186         if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
1187             PyErr_SetVim(_("cannot save undo information"));
1188         else
1189         {
1190             for (i = 0; i < size; ++i)
1191             {
1192                 if (ml_append((linenr_T)(n + i),
1193                                         (char_u *)array[i], 0, FALSE) == FAIL)
1194                 {
1195                     PyErr_SetVim(_("cannot insert line"));
1196
1197                     /* Free the rest of the lines */
1198                     while (i < size)
1199                         vim_free(array[i++]);
1200
1201                     break;
1202                 }
1203                 vim_free(array[i]);
1204             }
1205             if (i > 0)
1206                 appended_lines_mark((linenr_T)n, (long)i);
1207         }
1208
1209         /* Free the array of lines. All of its contents have now
1210          * been freed.
1211          */
1212         vim_free(array);
1213
1214         curbuf = savebuf;
1215         update_screen(VALID);
1216
1217         if (PyErr_Occurred() || VimErrorCheck())
1218             return FAIL;
1219
1220         if (len_change)
1221             *len_change = size;
1222
1223         return OK;
1224     }
1225     else
1226     {
1227         PyErr_BadArgument();
1228         return FAIL;
1229     }
1230 }
1231
1232 /*
1233  * Common routines for buffers and line ranges
1234  * -------------------------------------------
1235  */
1236
1237     static int
1238 CheckBuffer(BufferObject *this)
1239 {
1240     if (this->buf == INVALID_BUFFER_VALUE)
1241     {
1242         PyErr_SetVim(_("attempt to refer to deleted buffer"));
1243         return -1;
1244     }
1245
1246     return 0;
1247 }
1248
1249     static PyObject *
1250 RBItem(BufferObject *self, PyInt n, PyInt start, PyInt end)
1251 {
1252     if (CheckBuffer(self))
1253         return NULL;
1254
1255     if (n < 0 || n > end - start)
1256     {
1257         PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1258         return NULL;
1259     }
1260
1261     return GetBufferLine(self->buf, n+start);
1262 }
1263
1264     static PyObject *
1265 RBSlice(BufferObject *self, PyInt lo, PyInt hi, PyInt start, PyInt end)
1266 {
1267     PyInt size;
1268
1269     if (CheckBuffer(self))
1270         return NULL;
1271
1272     size = end - start + 1;
1273
1274     if (lo < 0)
1275         lo = 0;
1276     else if (lo > size)
1277         lo = size;
1278     if (hi < 0)
1279         hi = 0;
1280     if (hi < lo)
1281         hi = lo;
1282     else if (hi > size)
1283         hi = size;
1284
1285     return GetBufferLineList(self->buf, lo+start, hi+start);
1286 }
1287
1288     static PyInt
1289 RBAsItem(BufferObject *self, PyInt n, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1290 {
1291     PyInt len_change;
1292
1293     if (CheckBuffer(self))
1294         return -1;
1295
1296     if (n < 0 || n > end - start)
1297     {
1298         PyErr_SetString(PyExc_IndexError, _("line number out of range"));
1299         return -1;
1300     }
1301
1302     if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL)
1303         return -1;
1304
1305     if (new_end)
1306         *new_end = end + len_change;
1307
1308     return 0;
1309 }
1310
1311     static PyInt
1312 RBAsSlice(BufferObject *self, PyInt lo, PyInt hi, PyObject *val, PyInt start, PyInt end, PyInt *new_end)
1313 {
1314     PyInt size;
1315     PyInt len_change;
1316
1317     /* Self must be a valid buffer */
1318     if (CheckBuffer(self))
1319         return -1;
1320
1321     /* Sort out the slice range */
1322     size = end - start + 1;
1323
1324     if (lo < 0)
1325         lo = 0;
1326     else if (lo > size)
1327         lo = size;
1328     if (hi < 0)
1329         hi = 0;
1330     if (hi < lo)
1331         hi = lo;
1332     else if (hi > size)
1333         hi = size;
1334
1335     if (SetBufferLineList(self->buf, lo + start, hi + start,
1336                                                     val, &len_change) == FAIL)
1337         return -1;
1338
1339     if (new_end)
1340         *new_end = end + len_change;
1341
1342     return 0;
1343 }
1344
1345
1346     static PyObject *
1347 RBAppend(BufferObject *self, PyObject *args, PyInt start, PyInt end, PyInt *new_end)
1348 {
1349     PyObject *lines;
1350     PyInt len_change;
1351     PyInt max;
1352     PyInt n;
1353
1354     if (CheckBuffer(self))
1355         return NULL;
1356
1357     max = n = end - start + 1;
1358
1359     if (!PyArg_ParseTuple(args, "O|n", &lines, &n))
1360         return NULL;
1361
1362     if (n < 0 || n > max)
1363     {
1364         PyErr_SetString(PyExc_ValueError, _("line number out of range"));
1365         return NULL;
1366     }
1367
1368     if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL)
1369         return NULL;
1370
1371     if (new_end)
1372         *new_end = end + len_change;
1373
1374     Py_INCREF(Py_None);
1375     return Py_None;
1376 }
1377
1378
1379 /* Buffer object - Definitions
1380  */
1381
1382 typedef struct
1383 {
1384     PyObject_HEAD
1385     BufferObject *buf;
1386     PyInt start;
1387     PyInt end;
1388 } RangeObject;
1389
1390     static PyObject *
1391 RangeNew(buf_T *buf, PyInt start, PyInt end)
1392 {
1393     BufferObject *bufr;
1394     RangeObject *self;
1395     self = PyObject_NEW(RangeObject, &RangeType);
1396     if (self == NULL)
1397         return NULL;
1398
1399     bufr = (BufferObject *)BufferNew(buf);
1400     if (bufr == NULL)
1401     {
1402         Py_DECREF(self);
1403         return NULL;
1404     }
1405     Py_INCREF(bufr);
1406
1407     self->buf = bufr;
1408     self->start = start;
1409     self->end = end;
1410
1411     return (PyObject *)(self);
1412 }
1413
1414     static PyObject *
1415 BufferAppend(PyObject *self, PyObject *args)
1416 {
1417     return RBAppend((BufferObject *)(self), args, 1,
1418                     (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1419                     NULL);
1420 }
1421
1422     static PyObject *
1423 BufferMark(PyObject *self, PyObject *args)
1424 {
1425     pos_T       *posp;
1426     char        *pmark;
1427     char        mark;
1428     buf_T       *curbuf_save;
1429
1430     if (CheckBuffer((BufferObject *)(self)))
1431         return NULL;
1432
1433     if (!PyArg_ParseTuple(args, "s", &pmark))
1434         return NULL;
1435     mark = *pmark;
1436
1437     curbuf_save = curbuf;
1438     curbuf = ((BufferObject *)(self))->buf;
1439     posp = getmark(mark, FALSE);
1440     curbuf = curbuf_save;
1441
1442     if (posp == NULL)
1443     {
1444         PyErr_SetVim(_("invalid mark name"));
1445         return NULL;
1446     }
1447
1448     /* Ckeck for keyboard interrupt */
1449     if (VimErrorCheck())
1450         return NULL;
1451
1452     if (posp->lnum <= 0)
1453     {
1454         /* Or raise an error? */
1455         Py_INCREF(Py_None);
1456         return Py_None;
1457     }
1458
1459     return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col));
1460 }
1461
1462     static PyObject *
1463 BufferRange(PyObject *self, PyObject *args)
1464 {
1465     PyInt start;
1466     PyInt end;
1467
1468     if (CheckBuffer((BufferObject *)(self)))
1469         return NULL;
1470
1471     if (!PyArg_ParseTuple(args, "nn", &start, &end))
1472         return NULL;
1473
1474     return RangeNew(((BufferObject *)(self))->buf, start, end);
1475 }
1476
1477 static struct PyMethodDef BufferMethods[] = {
1478     /* name,        function,           calling,    documentation */
1479     {"append",      BufferAppend,       1,          "Append data to Vim buffer" },
1480     {"mark",        BufferMark,         1,          "Return (row,col) representing position of named mark" },
1481     {"range",       BufferRange,        1,          "Return a range object which represents the part of the given buffer between line numbers s and e" },
1482     { NULL,         NULL,               0,          NULL }
1483 };
1484
1485     static PyObject *
1486 RangeAppend(PyObject *self, PyObject *args)
1487 {
1488     return RBAppend(((RangeObject *)(self))->buf, args,
1489                     ((RangeObject *)(self))->start,
1490                     ((RangeObject *)(self))->end,
1491                     &((RangeObject *)(self))->end);
1492 }
1493
1494     static PyInt
1495 RangeLength(PyObject *self)
1496 {
1497     /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */
1498     if (CheckBuffer(((RangeObject *)(self))->buf))
1499         return -1; /* ??? */
1500
1501     return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1);
1502 }
1503
1504     static PyObject *
1505 RangeItem(PyObject *self, PyInt n)
1506 {
1507     return RBItem(((RangeObject *)(self))->buf, n,
1508                   ((RangeObject *)(self))->start,
1509                   ((RangeObject *)(self))->end);
1510 }
1511
1512     static PyObject *
1513 RangeRepr(PyObject *self)
1514 {
1515     static char repr[100];
1516     RangeObject *this = (RangeObject *)(self);
1517
1518     if (this->buf->buf == INVALID_BUFFER_VALUE)
1519     {
1520         vim_snprintf(repr, 100, "<range object (for deleted buffer) at %p>",
1521                                                                       (self));
1522         return PyString_FromString(repr);
1523     }
1524     else
1525     {
1526         char *name = (char *)this->buf->buf->b_fname;
1527         int len;
1528
1529         if (name == NULL)
1530             name = "";
1531         len = (int)strlen(name);
1532
1533         if (len > 45)
1534             name = name + (45 - len);
1535
1536         vim_snprintf(repr, 100, "<range %s%s (%d:%d)>",
1537                 len > 45 ? "..." : "", name,
1538                 this->start, this->end);
1539
1540         return PyString_FromString(repr);
1541     }
1542 }
1543
1544     static PyObject *
1545 RangeSlice(PyObject *self, PyInt lo, PyInt hi)
1546 {
1547     return RBSlice(((RangeObject *)(self))->buf, lo, hi,
1548                    ((RangeObject *)(self))->start,
1549                    ((RangeObject *)(self))->end);
1550 }
1551
1552 /*
1553  * Line range object - Definitions
1554  */
1555
1556 static struct PyMethodDef RangeMethods[] = {
1557     /* name,        function,           calling,    documentation */
1558     {"append",      RangeAppend,        1,          "Append data to the Vim range" },
1559     { NULL,         NULL,               0,          NULL }
1560 };
1561