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. 11 * Changes for Unix by David Leonard. 12 * 13 * This consists of four parts: 14 * 1. Python interpreter main program 15 * 2. Python output stream: writes output via [e]msg(). 16 * 3. Implementation of the Vim module for Python 17 * 4. Utility functions for handling the interface between Vim and Python. 18 */ 19 20 #include "vim.h" 21 22 #include <stdio.h> 23 #include <stdarg.h> 24 #include <limits.h> 25 26 /* Python.h defines _POSIX_THREADS itself (if needed) */ 27 #ifdef _POSIX_THREADS 28 # undef _POSIX_THREADS 29 #endif 30 31 #if defined(_WIN32) && defined (HAVE_FCNTL_H) 32 # undef HAVE_FCNTL_H 33 #endif 34 35 #ifdef _DEBUG 36 # undef _DEBUG 37 #endif 38 39 #ifdef HAVE_STDARG_H 40 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */ 41 #endif 42 43 #include <Python.h> 44 #if defined(MACOS) && !defined(MACOS_X_UNIX) 45 # include "macglue.h" 46 # include <CodeFragments.h> 47 #endif 48 #undef main /* Defined in python.h - aargh */ 49 #undef HAVE_FCNTL_H /* Clash with os_win32.h */ 50 51 #if !defined(FEAT_PYTHON) && defined(PROTO) 52 /* Use this to be able to generate prototypes without python being used. */ 53 # define PyObject int 54 # define PyThreadState int 55 # define PyTypeObject int 56 struct PyMethodDef { int a; }; 57 # define PySequenceMethods int 58 #endif 59 60 /* Parser flags */ 61 #define single_input 256 62 #define file_input 257 63 #define eval_input 258 64 65 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0 66 /* Python 2.3: can invoke ":python" recursively. */ 67 # define PY_CAN_RECURSE 68 #endif 69 70 #if defined(DYNAMIC_PYTHON) || defined(PROTO) 71 # ifndef DYNAMIC_PYTHON 72 # define HINSTANCE int /* for generating prototypes */ 73 # endif 74 75 /* 76 * Wrapper defines 77 */ 78 # define PyArg_Parse dll_PyArg_Parse 79 # define PyArg_ParseTuple dll_PyArg_ParseTuple 80 # define PyDict_SetItemString dll_PyDict_SetItemString 81 # define PyErr_BadArgument dll_PyErr_BadArgument 82 # define PyErr_Clear dll_PyErr_Clear 83 # define PyErr_NoMemory dll_PyErr_NoMemory 84 # define PyErr_Occurred dll_PyErr_Occurred 85 # define PyErr_SetNone dll_PyErr_SetNone 86 # define PyErr_SetString dll_PyErr_SetString 87 # define PyEval_InitThreads dll_PyEval_InitThreads 88 # define PyEval_RestoreThread dll_PyEval_RestoreThread 89 # define PyEval_SaveThread dll_PyEval_SaveThread 90 # ifdef PY_CAN_RECURSE 91 # define PyGILState_Ensure dll_PyGILState_Ensure 92 # define PyGILState_Release dll_PyGILState_Release 93 # endif 94 # define PyInt_AsLong dll_PyInt_AsLong 95 # define PyInt_FromLong dll_PyInt_FromLong 96 # define PyInt_Type (*dll_PyInt_Type) 97 # define PyList_GetItem dll_PyList_GetItem 98 # define PyList_New dll_PyList_New 99 # define PyList_SetItem dll_PyList_SetItem 100 # define PyList_Size dll_PyList_Size 101 # define PyList_Type (*dll_PyList_Type) 102 # define PyImport_ImportModule dll_PyImport_ImportModule 103 # define PyDict_GetItemString dll_PyDict_GetItemString 104 # define PyModule_GetDict dll_PyModule_GetDict 105 # define PyRun_SimpleString dll_PyRun_SimpleString 106 # define PyString_AsString dll_PyString_AsString 107 # define PyString_FromString dll_PyString_FromString 108 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize 109 # define PyString_Size dll_PyString_Size 110 # define PyString_Type (*dll_PyString_Type) 111 # define PySys_SetObject dll_PySys_SetObject 112 # define PySys_SetArgv dll_PySys_SetArgv 113 # define PyType_Type (*dll_PyType_Type) 114 # define Py_BuildValue dll_Py_BuildValue 115 # define Py_FindMethod dll_Py_FindMethod 116 # define Py_InitModule4 dll_Py_InitModule4 117 # define Py_Initialize dll_Py_Initialize 118 # define Py_Finalize dll_Py_Finalize 119 # define Py_IsInitialized dll_Py_IsInitialized 120 # define _PyObject_New dll__PyObject_New 121 # define _Py_NoneStruct (*dll__Py_NoneStruct) 122 # define PyObject_Init dll__PyObject_Init 123 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000 124 # define PyType_IsSubtype dll_PyType_IsSubtype 125 # endif 126 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000 127 # define PyObject_Malloc dll_PyObject_Malloc 128 # define PyObject_Free dll_PyObject_Free 129 # endif 130 131 /* 132 * Pointers for dynamic link 133 */ 134 static int(*dll_PyArg_Parse)(PyObject *, char *, ...); 135 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...); 136 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item); 137 static int(*dll_PyErr_BadArgument)(void); 138 static void(*dll_PyErr_Clear)(void); 139 static PyObject*(*dll_PyErr_NoMemory)(void); 140 static PyObject*(*dll_PyErr_Occurred)(void); 141 static void(*dll_PyErr_SetNone)(PyObject *); 142 static void(*dll_PyErr_SetString)(PyObject *, const char *); 143 static void(*dll_PyEval_InitThreads)(void); 144 static void(*dll_PyEval_RestoreThread)(PyThreadState *); 145 static PyThreadState*(*dll_PyEval_SaveThread)(void); 146 # ifdef PY_CAN_RECURSE 147 static PyGILState_STATE (*dll_PyGILState_Ensure)(void); 148 static void (*dll_PyGILState_Release)(PyGILState_STATE); 149 #endif 150 static long(*dll_PyInt_AsLong)(PyObject *); 151 static PyObject*(*dll_PyInt_FromLong)(long); 152 static PyTypeObject* dll_PyInt_Type; 153 static PyObject*(*dll_PyList_GetItem)(PyObject *, int); 154 static PyObject*(*dll_PyList_New)(int size); 155 static int(*dll_PyList_SetItem)(PyObject *, int, PyObject *); 156 static int(*dll_PyList_Size)(PyObject *); 157 static PyTypeObject* dll_PyList_Type; 158 static PyObject*(*dll_PyImport_ImportModule)(const char *); 159 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *); 160 static PyObject*(*dll_PyModule_GetDict)(PyObject *); 161 static int(*dll_PyRun_SimpleString)(char *); 162 static char*(*dll_PyString_AsString)(PyObject *); 163 static PyObject*(*dll_PyString_FromString)(const char *); 164 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, int); 165 static int(*dll_PyString_Size)(PyObject *); 166 static PyTypeObject* dll_PyString_Type; 167 static int(*dll_PySys_SetObject)(char *, PyObject *); 168 static int(*dll_PySys_SetArgv)(int, char **); 169 static PyTypeObject* dll_PyType_Type; 170 static PyObject*(*dll_Py_BuildValue)(char *, ...); 171 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *); 172 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int); 173 static void(*dll_Py_Initialize)(void); 174 static void(*dll_Py_Finalize)(void); 175 static int(*dll_Py_IsInitialized)(void); 176 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *); 177 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *); 178 static PyObject* dll__Py_NoneStruct; 179 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000 180 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *); 181 # endif 182 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000 183 static void* (*dll_PyObject_Malloc)(size_t); 184 static void (*dll_PyObject_Free)(void*); 185 # endif 186 187 static HINSTANCE hinstPython = 0; /* Instance of python.dll */ 188 189 /* Imported exception objects */ 190 static PyObject *imp_PyExc_AttributeError; 191 static PyObject *imp_PyExc_IndexError; 192 static PyObject *imp_PyExc_KeyboardInterrupt; 193 static PyObject *imp_PyExc_TypeError; 194 static PyObject *imp_PyExc_ValueError; 195 196 # define PyExc_AttributeError imp_PyExc_AttributeError 197 # define PyExc_IndexError imp_PyExc_IndexError 198 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt 199 # define PyExc_TypeError imp_PyExc_TypeError 200 # define PyExc_ValueError imp_PyExc_ValueError 201 202 /* 203 * Table of name to function pointer of python. 204 */ 205 # define PYTHON_PROC FARPROC 206 static struct 207 { 208 char *name; 209 PYTHON_PROC *ptr; 210 } python_funcname_table[] = 211 { 212 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse}, 213 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple}, 214 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString}, 215 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument}, 216 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear}, 217 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory}, 218 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred}, 219 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone}, 220 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString}, 221 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads}, 222 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread}, 223 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread}, 224 # ifdef PY_CAN_RECURSE 225 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure}, 226 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release}, 227 # endif 228 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong}, 229 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong}, 230 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type}, 231 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem}, 232 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New}, 233 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem}, 234 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size}, 235 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type}, 236 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule}, 237 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString}, 238 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict}, 239 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString}, 240 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString}, 241 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString}, 242 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize}, 243 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size}, 244 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type}, 245 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject}, 246 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv}, 247 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type}, 248 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue}, 249 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod}, 250 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4}, 251 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize}, 252 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize}, 253 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized}, 254 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New}, 255 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init}, 256 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct}, 257 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000 258 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype}, 259 # endif 260 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000 261 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc}, 262 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free}, 263 # endif 264 {"", NULL}, 265 }; 266 267 /* 268 * Free python.dll 269 */ 270 static void 271 end_dynamic_python(void) 272 { 273 if (hinstPython) 274 { 275 FreeLibrary(hinstPython); 276 hinstPython = 0; 277 } 278 } 279 280 /* 281 * Load library and get all pointers. 282 * Parameter 'libname' provides name of DLL. 283 * Return OK or FAIL. 284 */ 285 static int 286 python_runtime_link_init(char *libname, int verbose) 287 { 288 int i; 289 290 if (hinstPython) 291 return OK; 292 hinstPython = LoadLibrary(libname); 293 if (!hinstPython) 294 { 295 if (verbose) 296 EMSG2(_(e_loadlib), libname); 297 return FAIL; 298 } 299 300 for (i = 0; python_funcname_table[i].ptr; ++i) 301 { 302 if ((*python_funcname_table[i].ptr = GetProcAddress(hinstPython, 303 python_funcname_table[i].name)) == NULL) 304 { 305 FreeLibrary(hinstPython); 306 hinstPython = 0; 307 if (verbose) 308 EMSG2(_(e_loadfunc), python_funcname_table[i].name); 309 return FAIL; 310 } 311 } 312 return OK; 313 } 314 315 /* 316 * If python is enabled (there is installed python on Windows system) return 317 * TRUE, else FALSE. 318 */ 319 int 320 python_enabled(verbose) 321 int verbose; 322 { 323 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK; 324 } 325 326 /* Load the standard Python exceptions - don't import the symbols from the 327 * DLL, as this can cause errors (importing data symbols is not reliable). 328 */ 329 static void get_exceptions __ARGS((void)); 330 331 static void 332 get_exceptions() 333 { 334 PyObject *exmod = PyImport_ImportModule("exceptions"); 335 PyObject *exdict = PyModule_GetDict(exmod); 336 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError"); 337 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError"); 338 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt"); 339 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError"); 340 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError"); 341 Py_XINCREF(imp_PyExc_AttributeError); 342 Py_XINCREF(imp_PyExc_IndexError); 343 Py_XINCREF(imp_PyExc_KeyboardInterrupt); 344 Py_XINCREF(imp_PyExc_TypeError); 345 Py_XINCREF(imp_PyExc_ValueError); 346 Py_XDECREF(exmod); 347 } 348 #endif /* DYNAMIC_PYTHON */ 349 350 /****************************************************** 351 * Internal function prototypes. 352 */ 353 354 static void DoPythonCommand(exarg_T *, const char *); 355 static int RangeStart; 356 static int RangeEnd; 357 358 static void PythonIO_Flush(void); 359 static int PythonIO_Init(void); 360 static int PythonMod_Init(void); 361 362 /* Utility functions for the vim/python interface 363 * ---------------------------------------------- 364 */ 365 static PyObject *GetBufferLine(buf_T *, int); 366 static PyObject *GetBufferLineList(buf_T *, int, int); 367 368 static int SetBufferLine(buf_T *, int, PyObject *, int *); 369 static int SetBufferLineList(buf_T *, int, int, PyObject *, int *); 370 static int InsertBufferLines(buf_T *, int, PyObject *, int *); 371 372 static PyObject *LineToString(const char *); 373 static char *StringToLine(PyObject *); 374 375 static int VimErrorCheck(void); 376 377 #define PyErr_SetVim(str) PyErr_SetString(VimError, str) 378 379 /****************************************************** 380 * 1. Python interpreter main program. 381 */ 382 383 static int initialised = 0; 384 385 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ 386 typedef PyObject PyThreadState; 387 #endif 388 389 #ifdef PY_CAN_RECURSE 390 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED; 391 #else 392 static PyThreadState *saved_python_thread = NULL; 393 #endif 394 395 /* 396 * Suspend a thread of the Python interpreter, other threads are allowed to 397 * run. 398 */ 399 static void 400 Python_SaveThread(void) 401 { 402 #ifdef PY_CAN_RECURSE 403 PyGILState_Release(pygilstate); 404 #else 405 saved_python_thread = PyEval_SaveThread(); 406 #endif 407 } 408 409 /* 410 * Restore a thread of the Python interpreter, waits for other threads to 411 * block. 412 */ 413 static void 414 Python_RestoreThread(void) 415 { 416 #ifdef PY_CAN_RECURSE 417 pygilstate = PyGILState_Ensure(); 418 #else 419 PyEval_RestoreThread(saved_python_thread); 420 saved_python_thread = NULL; 421 #endif 422 } 423 424 /* 425 * obtain a lock on the Vim data structures 426 */ 427 static void Python_Lock_Vim(void) 428 { 429 } 430 431 /* 432 * release a lock on the Vim data structures 433 */ 434 static void Python_Release_Vim(void) 435 { 436 } 437 438 void 439 python_end() 440 { 441 #ifdef DYNAMIC_PYTHON 442 if (hinstPython && Py_IsInitialized()) 443 { 444 Python_RestoreThread(); /* enter python */ 445 Py_Finalize(); 446 } 447 end_dynamic_python(); 448 #else 449 if (Py_IsInitialized()) 450 { 451 Python_RestoreThread(); /* enter python */ 452 Py_Finalize(); 453 } 454 #endif 455 } 456 457 static int 458 Python_Init(void) 459 { 460 if (!initialised) 461 { 462 #ifdef DYNAMIC_PYTHON 463 if (!python_enabled(TRUE)) 464 { 465 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); 466 goto fail; 467 } 468 #endif 469 470 #if !defined(MACOS) || defined(MACOS_X_UNIX) 471 Py_Initialize(); 472 #else 473 PyMac_Initialize(); 474 #endif 475 /* initialise threads */ 476 PyEval_InitThreads(); 477 478 #ifdef DYNAMIC_PYTHON 479 get_exceptions(); 480 #endif 481 482 if (PythonIO_Init()) 483 goto fail; 484 485 if (PythonMod_Init()) 486 goto fail; 487 488 /* the first python thread is vim's, release the lock */ 489 Python_SaveThread(); 490 491 initialised = 1; 492 } 493 494 return 0; 495 496 fail: 497 /* We call PythonIO_Flush() here to print any Python errors. 498 * This is OK, as it is possible to call this function even 499 * if PythonIO_Init() has not completed successfully (it will 500 * not do anything in this case). 501 */ 502 PythonIO_Flush(); 503 return -1; 504 } 505 506 /* 507 * External interface 508 */ 509 static void 510 DoPythonCommand(exarg_T *eap, const char *cmd) 511 { 512 #ifndef PY_CAN_RECURSE 513 static int recursive = 0; 514 #endif 515 #if defined(MACOS) && !defined(MACOS_X_UNIX) 516 GrafPtr oldPort; 517 #endif 518 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) 519 char *saved_locale; 520 #endif 521 522 #ifndef PY_CAN_RECURSE 523 if (recursive) 524 { 525 EMSG(_("E659: Cannot invoke Python recursively")); 526 return; 527 } 528 ++recursive; 529 #endif 530 531 #if defined(MACOS) && !defined(MACOS_X_UNIX) 532 GetPort(&oldPort); 533 /* Check if the Python library is available */ 534 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress) 535 goto theend; 536 #endif 537 if (Python_Init()) 538 goto theend; 539 540 RangeStart = eap->line1; 541 RangeEnd = eap->line2; 542 Python_Release_Vim(); /* leave vim */ 543 544 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) 545 /* Python only works properly when the LC_NUMERIC locale is "C". */ 546 saved_locale = setlocale(LC_NUMERIC, NULL); 547 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0) 548 saved_locale = NULL; 549 else 550 { 551 /* Need to make a copy, value may change when setting new locale. */ 552 saved_locale = (char *)vim_strsave((char_u *)saved_locale); 553 (void)setlocale(LC_NUMERIC, "C"); 554 } 555 #endif 556 557 Python_RestoreThread(); /* enter python */ 558 559 PyRun_SimpleString((char *)(cmd)); 560 561 Python_SaveThread(); /* leave python */ 562 563 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) 564 if (saved_locale != NULL) 565 { 566 (void)setlocale(LC_NUMERIC, saved_locale); 567 vim_free(saved_locale); 568 } 569 #endif 570 571 Python_Lock_Vim(); /* enter vim */ 572 PythonIO_Flush(); 573 #if defined(MACOS) && !defined(MACOS_X_UNIX) 574 SetPort(oldPort); 575 #endif 576 577 theend: 578 #ifndef PY_CAN_RECURSE 579 --recursive; 580 #endif 581 return; /* keeps lint happy */ 582 } 583 584 /* 585 * ":python" 586 */ 587 void 588 ex_python(exarg_T *eap) 589 { 590 char_u *script; 591 592 script = script_get(eap, eap->arg); 593 if (!eap->skip) 594 { 595 if (script == NULL) 596 DoPythonCommand(eap, (char *)eap->arg); 597 else 598 DoPythonCommand(eap, (char *)script); 599 } 600 vim_free(script); 601 } 602 603 #define BUFFER_SIZE 1024 604 605 /* 606 * ":pyfile" 607 */ 608 void 609 ex_pyfile(exarg_T *eap) 610 { 611 static char buffer[BUFFER_SIZE]; 612 const char *file = (char *)eap->arg; 613 char *p; 614 615 /* Have to do it like this. PyRun_SimpleFile requires you to pass a 616 * stdio file pointer, but Vim and the Python DLL are compiled with 617 * different options under Windows, meaning that stdio pointers aren't 618 * compatible between the two. Yuk. 619 * 620 * Put the string "execfile('file')" into buffer. But, we need to 621 * escape any backslashes or single quotes in the file name, so that 622 * Python won't mangle the file name. 623 */ 624 strcpy(buffer, "execfile('"); 625 p = buffer + 10; /* size of "execfile('" */ 626 627 while (*file && p < buffer + (BUFFER_SIZE - 3)) 628 { 629 if (*file == '\\' || *file == '\'') 630 *p++ = '\\'; 631 *p++ = *file++; 632 } 633 634 /* If we didn't finish the file name, we hit a buffer overflow */ 635 if (*file != '\0') 636 return; 637 638 /* Put in the terminating "')" and a null */ 639 *p++ = '\''; 640 *p++ = ')'; 641 *p++ = '\0'; 642 643 /* Execute the file */ 644 DoPythonCommand(eap, buffer); 645 } 646 647 /****************************************************** 648 * 2. Python output stream: writes output via [e]msg(). 649 */ 650 651 /* Implementation functions 652 */ 653 654 static PyObject *OutputGetattr(PyObject *, char *); 655 static int OutputSetattr(PyObject *, char *, PyObject *); 656 657 static PyObject *OutputWrite(PyObject *, PyObject *); 658 static PyObject *OutputWritelines(PyObject *, PyObject *); 659 660 typedef void (*writefn)(char_u *); 661 static void writer(writefn fn, char_u *str, int n); 662 663 /* Output object definition 664 */ 665 666 typedef struct 667 { 668 PyObject_HEAD 669 long softspace; 670 long error; 671 } OutputObject; 672 673 static struct PyMethodDef OutputMethods[] = { 674 /* name, function, calling, documentation */ 675 {"write", OutputWrite, 1, "" }, 676 {"writelines", OutputWritelines, 1, "" }, 677 { NULL, NULL, 0, NULL } 678 }; 679 680 static PyTypeObject OutputType = { 681 PyObject_HEAD_INIT(0) 682 0, 683 "message", 684 sizeof(OutputObject), 685 0, 686 687 (destructor) 0, 688 (printfunc) 0, 689 (getattrfunc) OutputGetattr, 690 (setattrfunc) OutputSetattr, 691 (cmpfunc) 0, 692 (reprfunc) 0, 693 694 0, /* as number */ 695 0, /* as sequence */ 696 0, /* as mapping */ 697 698 (hashfunc) 0, 699 (ternaryfunc) 0, 700 (reprfunc) 0 701 }; 702 703 /*************/ 704 705 static PyObject * 706 OutputGetattr(PyObject *self, char *name) 707 { 708 if (strcmp(name, "softspace") == 0) 709 return PyInt_FromLong(((OutputObject *)(self))->softspace); 710 711 return Py_FindMethod(OutputMethods, self, name); 712 } 713 714 static int 715 OutputSetattr(PyObject *self, char *name, PyObject *val) 716 { 717 if (val == NULL) { 718 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes")); 719 return -1; 720 } 721 722 if (strcmp(name, "softspace") == 0) 723 { 724 if (!PyInt_Check(val)) { 725 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer")); 726 return -1; 727 } 728 729 ((OutputObject *)(self))->softspace = PyInt_AsLong(val); 730 return 0; 731 } 732 733 PyErr_SetString(PyExc_AttributeError, _("invalid attribute")); 734 return -1; 735 } 736 737 /*************/ 738 739 static PyObject * 740 OutputWrite(PyObject *self, PyObject *args) 741 { 742 int len; 743 char *str; 744 int error = ((OutputObject *)(self))->error; 745 746 if (!PyArg_ParseTuple(args, "s#", &str, &len)) 747 return NULL; 748 749 Py_BEGIN_ALLOW_THREADS 750 Python_Lock_Vim(); 751 writer((writefn)(error ? emsg : msg), (char_u *)str, len); 752 Python_Release_Vim(); 753 Py_END_ALLOW_THREADS 754 755 Py_INCREF(Py_None); 756 return Py_None; 757 } 758 759 static PyObject * 760 OutputWritelines(PyObject *self, PyObject *args) 761 { 762 int n; 763 int i; 764 PyObject *list; 765 int error = ((OutputObject *)(self))->error; 766 767 if (!PyArg_ParseTuple(args, "O", &list)) 768 return NULL; 769 Py_INCREF(list); 770 771 if (!PyList_Check(list)) { 772 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings")); 773 Py_DECREF(list); 774 return NULL; 775 } 776 777 n = PyList_Size(list); 778 779 for (i = 0; i < n; ++i) 780 { 781 PyObject *line = PyList_GetItem(list, i); 782 char *str; 783 int len; 784 785 if (!PyArg_Parse(line, "s#", &str, &len)) { 786 PyErr_SetString(PyExc_TypeError, _("writelines() requires list of strings")); 787 Py_DECREF(list); 788 return NULL; 789 } 790 791 Py_BEGIN_ALLOW_THREADS 792 Python_Lock_Vim(); 793 writer((writefn)(error ? emsg : msg), (char_u *)str, len); 794 Python_Release_Vim(); 795 Py_END_ALLOW_THREADS 796 } 797 798 Py_DECREF(list); 799 Py_INCREF(Py_None); 800 return Py_None; 801 } 802 803 /* Output buffer management 804 */ 805 806 static char_u *buffer = NULL; 807 static int buffer_len = 0; 808 static int buffer_size = 0; 809 810 static writefn old_fn = NULL; 811 812 static void 813 buffer_ensure(int n) 814 { 815 int new_size; 816 char_u *new_buffer; 817 818 if (n < buffer_size) 819 return; 820 821 new_size = buffer_size; 822 while (new_size < n) 823 new_size += 80; 824 825 if (new_size != buffer_size) 826 { 827 new_buffer = alloc((unsigned)new_size); 828 if (new_buffer == NULL) 829 return; 830 831 if (buffer) 832 { 833 memcpy(new_buffer, buffer, buffer_len); 834 vim_free(buffer); 835 } 836 837 buffer = new_buffer; 838 buffer_size = new_size; 839 } 840 } 841 842 static void 843 PythonIO_Flush(void) 844 { 845 if (old_fn && buffer_len) 846 { 847 buffer[buffer_len] = 0; 848 old_fn(buffer); 849 } 850 851 buffer_len = 0; 852 } 853 854 static void 855 writer(writefn fn, char_u *str, int n) 856 { 857 char_u *ptr; 858 859 if (fn != old_fn && old_fn != NULL) 860 PythonIO_Flush(); 861 862 old_fn = fn; 863 864 while (n > 0 && (ptr = memchr(str, '\n', n)) != NULL) 865 { 866 int len = ptr - str; 867 868 buffer_ensure(buffer_len + len + 1); 869 870 memcpy(buffer + buffer_len, str, len); 871 buffer_len += len; 872 buffer[buffer_len] = 0; 873 fn(buffer); 874 str = ptr + 1; 875 n -= len + 1; 876 buffer_len = 0; 877 } 878 879 /* Put the remaining text into the buffer for later printing */ 880 buffer_ensure(buffer_len + n + 1); 881 memcpy(buffer + buffer_len, str, n); 882 buffer_len += n; 883 } 884 885 /***************/ 886 887 static OutputObject Output = 888 { 889 PyObject_HEAD_INIT(&OutputType) 890 0, 891 0 892 }; 893 894 static OutputObject Error = 895 { 896 PyObject_HEAD_INIT(&OutputType) 897 0, 898 1 899 }; 900 901 static int 902 PythonIO_Init(void) 903 { 904 /* Fixups... */ 905 OutputType.ob_type = &PyType_Type; 906 907 PySys_SetObject("stdout", (PyObject *)(void *)&Output); 908 PySys_SetObject("stderr", (PyObject *)(void *)&Error); 909 910 if (PyErr_Occurred()) 911 { 912 EMSG(_("E264: Python: Error initialising I/O objects")); 913 return -1; 914 } 915 916 return 0; 917 } 918 919 /****************************************************** 920 * 3. Implementation of the Vim module for Python 921 */ 922 923 /* Vim module - Implementation functions 924 * ------------------------------------- 925 */ 926 927 static PyObject *VimError; 928 929 static PyObject *VimCommand(PyObject *, PyObject *); 930 static PyObject *VimEval(PyObject *, PyObject *); 931 932 /* Window type - Implementation functions 933 * -------------------------------------- 934 */ 935 936 typedef struct 937 { 938 PyObject_HEAD 939 win_T *win; 940 } 941 WindowObject; 942 943 #define INVALID_WINDOW_VALUE ((win_T *)(-1)) 944 945 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType) 946 947 static PyObject *WindowNew(win_T *); 948 949 static void WindowDestructor(PyObject *); 950 static PyObject *WindowGetattr(PyObject *, char *); 951 static int WindowSetattr(PyObject *, char *, PyObject *); 952 static PyObject *WindowRepr(PyObject *); 953 954 /* Buffer type - Implementation functions 955 * -------------------------------------- 956 */ 957 958 typedef struct 959 { 960 PyObject_HEAD 961 buf_T *buf; 962 } 963 BufferObject; 964 965 #define INVALID_BUFFER_VALUE ((buf_T *)(-1)) 966 967 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType) 968 969 static PyObject *BufferNew (buf_T *); 970 971 static void BufferDestructor(PyObject *); 972 static PyObject *BufferGetattr(PyObject *, char *); 973 static PyObject *BufferRepr(PyObject *); 974 975 static int BufferLength(PyObject *); 976 static PyObject *BufferItem(PyObject *, int); 977 static PyObject *BufferSlice(PyObject *, int, int); 978 static int BufferAssItem(PyObject *, int, PyObject *); 979 static int BufferAssSlice(PyObject *, int, int, PyObject *); 980 981 static PyObject *BufferAppend(PyObject *, PyObject *); 982 static PyObject *BufferMark(PyObject *, PyObject *); 983 static PyObject *BufferRange(PyObject *, PyObject *); 984 985 /* Line range type - Implementation functions 986 * -------------------------------------- 987 */ 988 989 typedef struct 990 { 991 PyObject_HEAD 992 BufferObject *buf; 993 int start; 994 int end; 995 } 996 RangeObject; 997 998 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType) 999 1000 static PyObject *RangeNew(buf_T *, int, int); 1001 1002 static void RangeDestructor(PyObject *); 1003 static PyObject *RangeGetattr(PyObject *, char *); 1004 static PyObject *RangeRepr(PyObject *); 1005 1006 static int RangeLength(PyObject *); 1007 static PyObject *RangeItem(PyObject *, int); 1008 static PyObject *RangeSlice(PyObject *, int, int); 1009 static int RangeAssItem(PyObject *, int, PyObject *); 1010 static int RangeAssSlice(PyObject *, int, int, PyObject *); 1011 1012 static PyObject *RangeAppend(PyObject *, PyObject *); 1013 1014 /* Window list type - Implementation functions 1015 * ------------------------------------------- 1016 */ 1017 1018 static int WinListLength(PyObject *); 1019 static PyObject *WinListItem(PyObject *, int); 1020 1021 /* Buffer list type - Implementation functions 1022 * ------------------------------------------- 1023 */ 1024 1025 static int BufListLength(PyObject *); 1026 static PyObject *BufListItem(PyObject *, int); 1027 1028 /* Current objects type - Implementation functions 1029 * ----------------------------------------------- 1030 */ 1031 1032 static PyObject *CurrentGetattr(PyObject *, char *); 1033 static int CurrentSetattr(PyObject *, char *, PyObject *); 1034 1035 /* Vim module - Definitions 1036 */ 1037 1038 static struct PyMethodDef VimMethods[] = { 1039 /* name, function, calling, documentation */ 1040 {"command", VimCommand, 1, "" }, 1041 {"eval", VimEval, 1, "" }, 1042 { NULL, NULL, 0, NULL } 1043 }; 1044 1045 /* Vim module - Implementation 1046 */ 1047 /*ARGSUSED*/ 1048 static PyObject * 1049 VimCommand(PyObject *self, PyObject *args) 1050 { 1051 char *cmd; 1052 PyObject *result; 1053 1054 if (!PyArg_ParseTuple(args, "s", &cmd)) 1055 return NULL; 1056 1057 PyErr_Clear(); 1058 1059 Py_BEGIN_ALLOW_THREADS 1060 Python_Lock_Vim(); 1061 1062 do_cmdline_cmd((char_u *)cmd); 1063 update_screen(VALID); 1064 1065 Python_Release_Vim(); 1066 Py_END_ALLOW_THREADS 1067 1068 if (VimErrorCheck()) 1069 result = NULL; 1070 else 1071 result = Py_None; 1072 1073 Py_XINCREF(result); 1074 return result; 1075 } 1076 1077 /*ARGSUSED*/ 1078 static PyObject * 1079 VimEval(PyObject *self, PyObject *args) 1080 { 1081 #ifdef FEAT_EVAL 1082 char *expr; 1083 char *str; 1084 PyObject *result; 1085 1086 if (!PyArg_ParseTuple(args, "s", &expr)) 1087 return NULL; 1088 1089 Py_BEGIN_ALLOW_THREADS 1090 Python_Lock_Vim(); 1091 str = (char *)eval_to_string((char_u *)expr, NULL); 1092 Python_Release_Vim(); 1093 Py_END_ALLOW_THREADS 1094 1095 if (str == NULL) 1096 { 1097 PyErr_SetVim(_("invalid expression")); 1098 return NULL; 1099 } 1100 1101 result = Py_BuildValue("s", str); 1102 1103 Py_BEGIN_ALLOW_THREADS 1104 Python_Lock_Vim(); 1105 vim_free(str); 1106 Python_Release_Vim(); 1107 Py_END_ALLOW_THREADS 1108 1109 return result; 1110 #else 1111 PyErr_SetVim(_("expressions disabled at compile time")); 1112 return NULL; 1113 #endif 1114 } 1115 1116 /* Common routines for buffers and line ranges 1117 * ------------------------------------------- 1118 */ 1119 static int 1120 CheckBuffer(BufferObject *this) 1121 { 1122 if (this->buf == INVALID_BUFFER_VALUE) 1123 { 1124 PyErr_SetVim(_("attempt to refer to deleted buffer")); 1125 return -1; 1126 } 1127 1128 return 0; 1129 } 1130 1131 static PyObject * 1132 RBItem(BufferObject *self, int n, int start, int end) 1133 { 1134 if (CheckBuffer(self)) 1135 return NULL; 1136 1137 if (n < 0 || n > end - start) 1138 { 1139 PyErr_SetString(PyExc_IndexError, _("line number out of range")); 1140 return NULL; 1141 } 1142 1143 return GetBufferLine(self->buf, n+start); 1144 } 1145 1146 static PyObject * 1147 RBSlice(BufferObject *self, int lo, int hi, int start, int end) 1148 { 1149 int size; 1150 1151 if (CheckBuffer(self)) 1152 return NULL; 1153 1154 size = end - start + 1; 1155 1156 if (lo < 0) 1157 lo = 0; 1158 else if (lo > size) 1159 lo = size; 1160 if (hi < 0) 1161 hi = 0; 1162 if (hi < lo) 1163 hi = lo; 1164 else if (hi > size) 1165 hi = size; 1166 1167 return GetBufferLineList(self->buf, lo+start, hi+start); 1168 } 1169 1170 static int 1171 RBAssItem(BufferObject *self, int n, PyObject *val, int start, int end, int *new_end) 1172 { 1173 int len_change; 1174 1175 if (CheckBuffer(self)) 1176 return -1; 1177 1178 if (n < 0 || n > end - start) 1179 { 1180 PyErr_SetString(PyExc_IndexError, _("line number out of range")); 1181 return -1; 1182 } 1183 1184 if (SetBufferLine(self->buf, n+start, val, &len_change) == FAIL) 1185 return -1; 1186 1187 if (new_end) 1188 *new_end = end + len_change; 1189 1190 return 0; 1191 } 1192 1193 static int 1194 RBAssSlice(BufferObject *self, int lo, int hi, PyObject *val, int start, int end, int *new_end) 1195 { 1196 int size; 1197 int len_change; 1198 1199 /* Self must be a valid buffer */ 1200 if (CheckBuffer(self)) 1201 return -1; 1202 1203 /* Sort out the slice range */ 1204 size = end - start + 1; 1205 1206 if (lo < 0) 1207 lo = 0; 1208 else if (lo > size) 1209 lo = size; 1210 if (hi < 0) 1211 hi = 0; 1212 if (hi < lo) 1213 hi = lo; 1214 else if (hi > size) 1215 hi = size; 1216 1217 if (SetBufferLineList(self->buf, lo+start, hi+start, val, &len_change) == FAIL) 1218 return -1; 1219 1220 if (new_end) 1221 *new_end = end + len_change; 1222 1223 return 0; 1224 } 1225 1226 static PyObject * 1227 RBAppend(BufferObject *self, PyObject *args, int start, int end, int *new_end) 1228 { 1229 PyObject *lines; 1230 int len_change; 1231 int max; 1232 int n; 1233 1234 if (CheckBuffer(self)) 1235 return NULL; 1236 1237 max = n = end - start + 1; 1238 1239 if (!PyArg_ParseTuple(args, "O|i", &lines, &n)) 1240 return NULL; 1241 1242 if (n < 0 || n > max) 1243 { 1244 PyErr_SetString(PyExc_ValueError, _("line number out of range")); 1245 return NULL; 1246 } 1247 1248 if (InsertBufferLines(self->buf, n + start - 1, lines, &len_change) == FAIL) 1249 return NULL; 1250 1251 if (new_end) 1252 *new_end = end + len_change; 1253 1254 Py_INCREF(Py_None); 1255 return Py_None; 1256 } 1257 1258 1259 /* Buffer object - Definitions 1260 */ 1261 1262 static struct PyMethodDef BufferMethods[] = { 1263 /* name, function, calling, documentation */ 1264 {"append", BufferAppend, 1, "" }, 1265 {"mark", BufferMark, 1, "" }, 1266 {"range", BufferRange, 1, "" }, 1267 { NULL, NULL, 0, NULL } 1268 }; 1269 1270 static PySequenceMethods BufferAsSeq = { 1271 (inquiry) BufferLength, /* sq_length, len(x) */ 1272 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */ 1273 (intargfunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */ 1274 (intargfunc) BufferItem, /* sq_item, x[i] */ 1275 (intintargfunc) BufferSlice, /* sq_slice, x[i:j] */ 1276 (intobjargproc) BufferAssItem, /* sq_ass_item, x[i]=v */ 1277 (intintobjargproc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */ 1278 }; 1279 1280 static PyTypeObject BufferType = { 1281 PyObject_HEAD_INIT(0) 1282 0, 1283 "buffer", 1284 sizeof(BufferObject), 1285 0, 1286 1287 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */ 1288 (printfunc) 0, /* tp_print, print x */ 1289 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */ 1290 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 1291 (cmpfunc) 0, /* tp_compare, x>y */ 1292 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */ 1293 1294 0, /* as number */ 1295 &BufferAsSeq, /* as sequence */ 1296 0, /* as mapping */ 1297 1298 (hashfunc) 0, /* tp_hash, dict(x) */ 1299 (ternaryfunc) 0, /* tp_call, x() */ 1300 (reprfunc) 0, /* tp_str, str(x) */ 1301 }; 1302 1303 /* Buffer object - Implementation 1304 */ 1305 1306 static PyObject * 1307 BufferNew(buf_T *buf) 1308 { 1309 /* We need to handle deletion of buffers underneath us. 1310 * If we add a "python_ref" field to the buf_T structure, 1311 * then we can get at it in buf_freeall() in vim. We then 1312 * need to create only ONE Python object per buffer - if 1313 * we try to create a second, just INCREF the existing one 1314 * and return it. The (single) Python object referring to 1315 * the buffer is stored in "python_ref". 1316 * Question: what to do on a buf_freeall(). We'll probably 1317 * have to either delete the Python object (DECREF it to 1318 * zero - a bad idea, as it leaves dangling refs!) or 1319 * set the buf_T * value to an invalid value (-1?), which 1320 * means we need checks in all access functions... Bah. 1321 */ 1322 1323 BufferObject *self; 1324 1325 if (buf->python_ref) 1326 { 1327 self = buf->python_ref; 1328 Py_INCREF(self); 1329 } 1330 else 1331 { 1332 self = PyObject_NEW(BufferObject, &BufferType); 1333 if (self == NULL) 1334 return NULL; 1335 self->buf = buf; 1336 buf->python_ref = self; 1337 } 1338 1339 return (PyObject *)(self); 1340 } 1341 1342 static void 1343 BufferDestructor(PyObject *self) 1344 { 1345 BufferObject *this = (BufferObject *)(self); 1346 1347 if (this->buf && this->buf != INVALID_BUFFER_VALUE) 1348 this->buf->python_ref = NULL; 1349 1350 PyMem_DEL(self); 1351 } 1352 1353 static PyObject * 1354 BufferGetattr(PyObject *self, char *name) 1355 { 1356 BufferObject *this = (BufferObject *)(self); 1357 1358 if (CheckBuffer(this)) 1359 return NULL; 1360 1361 if (strcmp(name, "name") == 0) 1362 return Py_BuildValue("s",this->buf->b_ffname); 1363 else if (strcmp(name, "number") == 0) 1364 return Py_BuildValue("i",this->buf->b_fnum); 1365 else if (strcmp(name,"__members__") == 0) 1366 return Py_BuildValue("[ss]", "name", "number"); 1367 else 1368 return Py_FindMethod(BufferMethods, self, name); 1369 } 1370 1371 static PyObject * 1372 BufferRepr(PyObject *self) 1373 { 1374 static char repr[100]; 1375 BufferObject *this = (BufferObject *)(self); 1376 1377 if (this->buf == INVALID_BUFFER_VALUE) 1378 { 1379 vim_snprintf(repr, 100, _("<buffer object (deleted) at %8lX>"), 1380 (long)(self)); 1381 return PyString_FromString(repr); 1382 } 1383 else 1384 { 1385 char *name = (char *)this->buf->b_fname; 1386 int len; 1387 1388 if (name == NULL) 1389 name = ""; 1390 len = strlen(name); 1391 1392 if (len > 35) 1393 name = name + (35 - len); 1394 1395 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name); 1396 1397 return PyString_FromString(repr); 1398 } 1399 } 1400 1401 /******************/ 1402 1403 static int 1404 BufferLength(PyObject *self) 1405 { 1406 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */ 1407 if (CheckBuffer((BufferObject *)(self))) 1408 return -1; /* ??? */ 1409 1410 return (((BufferObject *)(self))->buf->b_ml.ml_line_count); 1411 } 1412 1413 static PyObject * 1414 BufferItem(PyObject *self, int n) 1415 { 1416 return RBItem((BufferObject *)(self), n, 1, 1417 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count); 1418 } 1419 1420 static PyObject * 1421 BufferSlice(PyObject *self, int lo, int hi) 1422 { 1423 return RBSlice((BufferObject *)(self), lo, hi, 1, 1424 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count); 1425 } 1426 1427 static int 1428 BufferAssItem(PyObject *self, int n, PyObject *val) 1429 { 1430 return RBAssItem((BufferObject *)(self), n, val, 1, 1431 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count, 1432 NULL); 1433 } 1434 1435 static int 1436 BufferAssSlice(PyObject *self, int lo, int hi, PyObject *val) 1437 { 1438 return RBAssSlice((BufferObject *)(self), lo, hi, val, 1, 1439 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count, 1440 NULL); 1441 } 1442 1443 static PyObject * 1444 BufferAppend(PyObject *self, PyObject *args) 1445 { 1446 return RBAppend((BufferObject *)(self), args, 1, 1447 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count, 1448 NULL); 1449 } 1450 1451 static PyObject * 1452 BufferMark(PyObject *self, PyObject *args) 1453 { 1454 pos_T *posp; 1455 char mark; 1456 buf_T *curbuf_save; 1457 1458 if (CheckBuffer((BufferObject *)(self))) 1459 return NULL; 1460 1461 if (!PyArg_ParseTuple(args, "c", &mark)) 1462 return NULL; 1463 1464 curbuf_save = curbuf; 1465 curbuf = ((BufferObject *)(self))->buf; 1466 posp = getmark(mark, FALSE); 1467 curbuf = curbuf_save; 1468 1469 if (posp == NULL) 1470 { 1471 PyErr_SetVim(_("invalid mark name")); 1472 return NULL; 1473 } 1474 1475 /* Ckeck for keyboard interrupt */ 1476 if (VimErrorCheck()) 1477 return NULL; 1478 1479 if (posp->lnum <= 0) 1480 { 1481 /* Or raise an error? */ 1482 Py_INCREF(Py_None); 1483 return Py_None; 1484 } 1485 1486 return Py_BuildValue("(ll)", (long)(posp->lnum), (long)(posp->col)); 1487 } 1488 1489 static PyObject * 1490 BufferRange(PyObject *self, PyObject *args) 1491 { 1492 int start; 1493 int end; 1494 1495 if (CheckBuffer((BufferObject *)(self))) 1496 return NULL; 1497 1498 if (!PyArg_ParseTuple(args, "ii", &start, &end)) 1499 return NULL; 1500 1501 return RangeNew(((BufferObject *)(self))->buf, start, end); 1502 } 1503 1504 /* Line range object - Definitions 1505 */ 1506 1507 static struct PyMethodDef RangeMethods[] = { 1508 /* name, function, calling, documentation */ 1509 {"append", RangeAppend, 1, "" }, 1510 { NULL, NULL, 0, NULL } 1511 }; 1512 1513 static PySequenceMethods RangeAsSeq = { 1514 (inquiry) RangeLength, /* sq_length, len(x) */ 1515 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */ 1516 (intargfunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */ 1517 (intargfunc) RangeItem, /* sq_item, x[i] */ 1518 (intintargfunc) RangeSlice, /* sq_slice, x[i:j] */ 1519 (intobjargproc) RangeAssItem, /* sq_ass_item, x[i]=v */ 1520 (intintobjargproc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */ 1521 }; 1522 1523 static PyTypeObject RangeType = { 1524 PyObject_HEAD_INIT(0) 1525 0, 1526 "range", 1527 sizeof(RangeObject), 1528 0, 1529 1530 (destructor) RangeDestructor, /* tp_dealloc, refcount==0 */ 1531 (printfunc) 0, /* tp_print, print x */ 1532 (getattrfunc) RangeGetattr, /* tp_getattr, x.attr */ 1533 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 1534 (cmpfunc) 0, /* tp_compare, x>y */ 1535 (reprfunc) RangeRepr, /* tp_repr, `x`, print x */ 1536 1537 0, /* as number */ 1538 &RangeAsSeq, /* as sequence */ 1539 0, /* as mapping */ 1540 1541 (hashfunc) 0, /* tp_hash, dict(x) */ 1542 (ternaryfunc) 0, /* tp_call, x() */ 1543 (reprfunc) 0, /* tp_str, str(x) */ 1544 }; 1545 1546 /* Line range object - Implementation 1547 */ 1548 1549 static PyObject * 1550 RangeNew(buf_T *buf, int start, int end) 1551 { 1552 BufferObject *bufr; 1553 RangeObject *self; 1554 self = PyObject_NEW(RangeObject, &RangeType); 1555 if (self == NULL) 1556 return NULL; 1557 1558 bufr = (BufferObject *)BufferNew(buf); 1559 if (bufr == NULL) 1560 { 1561 PyMem_DEL(self); 1562 return NULL; 1563 } 1564 Py_INCREF(bufr); 1565 1566 self->buf = bufr; 1567 self->start = start; 1568 self->end = end; 1569 1570 return (PyObject *)(self); 1571 } 1572 1573 static void 1574 RangeDestructor(PyObject *self) 1575 { 1576 Py_DECREF(((RangeObject *)(self))->buf); 1577 PyMem_DEL(self); 1578 } 1579 1580 static PyObject * 1581 RangeGetattr(PyObject *self, char *name) 1582 { 1583 if (strcmp(name, "start") == 0) 1584 return Py_BuildValue("i",((RangeObject *)(self))->start - 1); 1585 else if (strcmp(name, "end") == 0) 1586 return Py_BuildValue("i",((RangeObject *)(self))->end - 1); 1587 else 1588 return Py_FindMethod(RangeMethods, self, name); 1589 } 1590 1591 static PyObject * 1592 RangeRepr(PyObject *self) 1593 { 1594 static char repr[100]; 1595 RangeObject *this = (RangeObject *)(self); 1596 1597 if (this->buf->buf == INVALID_BUFFER_VALUE) 1598 { 1599 vim_snprintf(repr, 100, "<range object (for deleted buffer) at %8lX>", 1600 (long)(self)); 1601 return PyString_FromString(repr); 1602 } 1603 else 1604 { 1605 char *name = (char *)this->buf->buf->b_fname; 1606 int len; 1607 1608 if (name == NULL) 1609 name = ""; 1610 len = strlen(name); 1611 1612 if (len > 45) 1613 name = name + (45 - len); 1614 1615 vim_snprintf(repr, 100, "<range %s%s (%d:%d)>", 1616 len > 45 ? "..." : "", name, 1617 this->start, this->end); 1618 1619 return PyString_FromString(repr); 1620 } 1621 } 1622 1623 /****************/ 1624 1625 static int 1626 RangeLength(PyObject *self) 1627 { 1628 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */ 1629 if (CheckBuffer(((RangeObject *)(self))->buf)) 1630 return -1; /* ??? */ 1631 1632 return (((RangeObject *)(self))->end - ((RangeObject *)(self))->start + 1); 1633 } 1634 1635 static PyObject * 1636 RangeItem(PyObject *self, int n) 1637 { 1638 return RBItem(((RangeObject *)(self))->buf, n, 1639 ((RangeObject *)(self))->start, 1640 ((RangeObject *)(self))->end); 1641 } 1642 1643 static PyObject * 1644 RangeSlice(PyObject *self, int lo, int hi) 1645 { 1646 return RBSlice(((RangeObject *)(self))->buf, lo, hi, 1647 ((RangeObject *)(self))->start, 1648 ((RangeObject *)(self))->end); 1649 } 1650 1651 static int 1652 RangeAssItem(PyObject *self, int n, PyObject *val) 1653 { 1654 return RBAssItem(((RangeObject *)(self))->buf, n, val, 1655 ((RangeObject *)(self))->start, 1656 ((RangeObject *)(self))->end, 1657 &((RangeObject *)(self))->end); 1658 } 1659 1660 static int 1661 RangeAssSlice(PyObject *self, int lo, int hi, PyObject *val) 1662 { 1663 return RBAssSlice(((RangeObject *)(self))->buf, lo, hi, val, 1664 ((RangeObject *)(self))->start, 1665 ((RangeObject *)(self))->end, 1666 &((RangeObject *)(self))->end); 1667 } 1668 1669 static PyObject * 1670 RangeAppend(PyObject *self, PyObject *args) 1671 { 1672 return RBAppend(((RangeObject *)(self))->buf, args, 1673 ((RangeObject *)(self))->start, 1674 ((RangeObject *)(self))->end, 1675 &((RangeObject *)(self))->end); 1676 } 1677 1678 /* Buffer list object - Definitions 1679 */ 1680 1681 typedef struct 1682 { 1683 PyObject_HEAD 1684 } 1685 BufListObject; 1686 1687 static PySequenceMethods BufListAsSeq = { 1688 (inquiry) BufListLength, /* sq_length, len(x) */ 1689 (binaryfunc) 0, /* sq_concat, x+y */ 1690 (intargfunc) 0, /* sq_repeat, x*n */ 1691 (intargfunc) BufListItem, /* sq_item, x[i] */ 1692 (intintargfunc) 0, /* sq_slice, x[i:j] */ 1693 (intobjargproc) 0, /* sq_ass_item, x[i]=v */ 1694 (intintobjargproc) 0, /* sq_ass_slice, x[i:j]=v */ 1695 }; 1696 1697 static PyTypeObject BufListType = { 1698 PyObject_HEAD_INIT(0) 1699 0, 1700 "buffer list", 1701 sizeof(BufListObject), 1702 0, 1703 1704 (destructor) 0, /* tp_dealloc, refcount==0 */ 1705 (printfunc) 0, /* tp_print, print x */ 1706 (getattrfunc) 0, /* tp_getattr, x.attr */ 1707 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 1708 (cmpfunc) 0, /* tp_compare, x>y */ 1709 (reprfunc) 0, /* tp_repr, `x`, print x */ 1710 1711 0, /* as number */ 1712 &BufListAsSeq, /* as sequence */ 1713 0, /* as mapping */ 1714 1715 (hashfunc) 0, /* tp_hash, dict(x) */ 1716 (ternaryfunc) 0, /* tp_call, x() */ 1717 (reprfunc) 0, /* tp_str, str(x) */ 1718 }; 1719 1720 /* Buffer list object - Implementation 1721 */ 1722 1723 /*ARGSUSED*/ 1724 static int 1725 BufListLength(PyObject *self) 1726 { 1727 buf_T *b = firstbuf; 1728 int n = 0; 1729 1730 while (b) 1731 { 1732 ++n; 1733 b = b->b_next; 1734 } 1735 1736 return n; 1737 } 1738 1739 /*ARGSUSED*/ 1740 static PyObject * 1741 BufListItem(PyObject *self, int n) 1742 { 1743 buf_T *b; 1744 1745 for (b = firstbuf; b; b = b->b_next, --n) 1746 { 1747 if (n == 0) 1748 return BufferNew(b); 1749 } 1750 1751 PyErr_SetString(PyExc_IndexError, _("no such buffer")); 1752 return NULL; 1753 } 1754 1755 /* Window object - Definitions 1756 */ 1757 1758 static struct PyMethodDef WindowMethods[] = { 1759 /* name, function, calling, documentation */ 1760 { NULL, NULL, 0, NULL } 1761 }; 1762 1763 static PyTypeObject WindowType = { 1764 PyObject_HEAD_INIT(0) 1765 0, 1766 "window", 1767 sizeof(WindowObject), 1768 0, 1769 1770 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */ 1771 (printfunc) 0, /* tp_print, print x */ 1772 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */ 1773 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */ 1774 (cmpfunc) 0, /* tp_compare, x>y */ 1775 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */ 1776 1777 0, /* as number */ 1778 0, /* as sequence */ 1779 0, /* as mapping */ 1780 1781 (hashfunc) 0, /* tp_hash, dict(x) */ 1782 (ternaryfunc) 0, /* tp_call, x() */ 1783 (reprfunc) 0, /* tp_str, str(x) */ 1784 }; 1785 1786 /* Window object - Implementation 1787 */ 1788 1789 static PyObject * 1790 WindowNew(win_T *win) 1791 { 1792 /* We need to handle deletion of windows underneath us. 1793 * If we add a "python_ref" field to the win_T structure, 1794 * then we can get at it in win_free() in vim. We then 1795 * need to create only ONE Python object per window - if 1796 * we try to create a second, just INCREF the existing one 1797 * and return it. The (single) Python object referring to 1798 * the window is stored in "python_ref". 1799 * On a win_free() we set the Python object's win_T* field 1800 * to an invalid value. We trap all uses of a window 1801 * object, and reject them if the win_T* field is invalid. 1802 */ 1803 1804 WindowObject *self; 1805 1806 if (win->python_ref) 1807 { 1808 self = win->python_ref; 1809 Py_INCREF(self); 1810 } 1811 else 1812 { 1813 self = PyObject_NEW(WindowObject, &WindowType); 1814 if (self == NULL) 1815 return NULL; 1816 self->win = win; 1817 win->python_ref = self; 1818 } 1819 1820 return (PyObject *)(self); 1821 } 1822 1823 static void 1824 WindowDestructor(PyObject *self) 1825 { 1826 WindowObject *this = (WindowObject *)(self); 1827 1828 if (this->win && this->win != INVALID_WINDOW_VALUE) 1829 this->win->python_ref = NULL; 1830 1831 PyMem_DEL(self); 1832 } 1833 1834 static int 1835 CheckWindow(WindowObject *this) 1836 { 1837 if (this->win == INVALID_WINDOW_VALUE) 1838 { 1839 PyErr_SetVim(_("attempt to refer to deleted window")); 1840 return -1; 1841 } 1842 1843 return 0; 1844 } 1845 1846 static PyObject * 1847 WindowGetattr(PyObject *self, char *name) 1848 { 1849 WindowObject *this = (WindowObject *)(self); 1850 1851 if (CheckWindow(this)) 1852 return NULL; 1853 1854 if (strcmp(name, "buffer") == 0) 1855 return (PyObject *)BufferNew(this->win->w_buffer); 1856 else if (strcmp(name, "cursor") == 0) 1857 { 1858 pos_T *pos = &this->win->w_cursor; 1859 1860 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col)); 1861 } 1862 else if (strcmp(name, "height") == 0) 1863 return Py_BuildValue("l", (long)(this->win->w_height)); 1864 #ifdef FEAT_VERTSPLIT 1865 else if (strcmp(name, "width") == 0) 1866 return Py_BuildValue("l", (long)(W_WIDTH(this->win))); 1867 #endif 1868 else if (strcmp(name,"__members__") == 0) 1869 return Py_BuildValue("[sss]", "buffer", "cursor", "height"); 1870 else 1871 return Py_FindMethod(WindowMethods, self, name); 1872 } 1873 1874 static int 1875 WindowSetattr(PyObject *self, char *name, PyObject *val) 1876 { 1877 WindowObject *this = (WindowObject *)(self); 1878 1879 if (CheckWindow(this)) 1880 return -1; 1881 1882 if (strcmp(name, "buffer") == 0) 1883 { 1884 PyErr_SetString(PyExc_TypeError, _("readonly attribute")); 1885 return -1; 1886 } 1887 else if (strcmp(name, "cursor") == 0) 1888 { 1889 long lnum; 1890 long col; 1891 1892 if (!PyArg_Parse(val, "(ll)", &lnum, &col)) 1893 return -1; 1894 1895 if (lnum <= 0 || lnum > this->win->w_buffer->b_ml.ml_line_count) 1896 { 1897 PyErr_SetVim(_("cursor position outside buffer")); 1898 return -1; 1899 } 1900 1901 /* Check for keyboard interrupts */ 1902 if (VimErrorCheck()) 1903 return -1; 1904 1905 /* NO CHECK ON COLUMN - SEEMS NOT TO MATTER */ 1906 1907 this->win->w_cursor.lnum = lnum; 1908 this->win->w_cursor.col = col; 1909 update_screen(VALID); 1910 1911 return 0; 1912 } 1913 else if (strcmp(name, "height") == 0) 1914 { 1915 int height; 1916 win_T *savewin; 1917 1918 if (!PyArg_Parse(val, "i", &height)) 1919 return -1; 1920 1921 #ifdef FEAT_GUI 1922 need_mouse_correct = TRUE; 1923 #endif 1924 savewin = curwin; 1925 curwin = this->win; 1926 win_setheight(height); 1927 curwin = savewin; 1928 1929 /* Check for keyboard interrupts */ 1930 if (VimErrorCheck()) 1931 return -1; 1932 1933 return 0; 1934 } 1935 #ifdef FEAT_VERTSPLIT 1936 else if (strcmp(name, "width") == 0) 1937 { 1938 int width; 1939 win_T *savewin; 1940 1941 if (!PyArg_Parse(val, "i", &width)) 1942 return -1; 1943 1944 #ifdef FEAT_GUI 1945 need_mouse_correct = TRUE; 1946 #endif 1947 savewin = curwin; 1948 curwin = this->win; 1949 win_setwidth(width); 1950 curwin = savewin; 1951 1952 /* Check for keyboard interrupts */ 1953 if (VimErrorCheck()) 1954 return -1; 1955 1956 return 0; 1957 } 1958 #endif 1959 else 1960 { 1961 PyErr_SetString(PyExc_AttributeError, name); 1962 return -1; 1963 } 1964 } 1965 1966 static PyObject * 1967 WindowRepr(PyObject *self) 1968 { 1969 static char repr[100]; 1970 WindowObject *this = (WindowObject *)(self); 1971 1972 if (this->win == INVALID_WINDOW_VALUE) 1973 { 1974 vim_snprintf(repr, 100, _("<window object (deleted) at %.8lX>"), 1975 (long)(self)); 1976 return PyString_FromString(repr); 1977 } 1978 else 1979 { 1980 int i = 0; 1981 win_T *w; 1982 1983 for (w = firstwin; w != NULL && w != this->win; w = W_NEXT(w)) 1984 ++i; 1985 1986 if (w == NULL) 1987 vim_snprintf(repr, 100, _("<window object (unknown) at %.8lX>"), 1988 (long)(self)); 1989 else 1990 vim_snprintf(repr, 100, _("<window %d>"), i); 1991 1992 return PyString_FromString(repr); 1993 } 1994 } 1995 1996 /* Window list object - Definitions 1997 */ 1998 1999 typedef struct 2000 { 2001 PyObject_HEAD 2002 } 2003 WinListObject; 2004 2005 static PySequenceMethods WinListAsSeq = { 2006 (inquiry) WinListLength, /* sq_length, len(x) */ 2007 (binaryfunc) 0, /* sq_concat, x+y */ 2008 (intargfunc) 0, /* sq_repeat, x*n */ 2009 (intargfunc) WinListItem, /* sq_item, x[i] */ 2010 (intintargfunc) 0, /* sq_slice, x[i:j] */ 2011 (intobjargproc) 0, /* sq_ass_item, x[i]=v */ 2012 (intintobjargproc) 0, /* sq_ass_slice, x[i:j]=v */ 2013 }; 2014 2015 static PyTypeObject WinListType = { 2016 PyObject_HEAD_INIT(0) 2017 0, 2018 "window list", 2019 sizeof(WinListObject), 2020 0, 2021 2022 (destructor) 0, /* tp_dealloc, refcount==0 */ 2023 (printfunc) 0, /* tp_print, print x */ 2024 (getattrfunc) 0, /* tp_getattr, x.attr */ 2025 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 2026 (cmpfunc) 0, /* tp_compare, x>y */ 2027 (reprfunc) 0, /* tp_repr, `x`, print x */ 2028 2029 0, /* as number */ 2030 &WinListAsSeq, /* as sequence */ 2031 0, /* as mapping */ 2032 2033 (hashfunc) 0, /* tp_hash, dict(x) */ 2034 (ternaryfunc) 0, /* tp_call, x() */ 2035 (reprfunc) 0, /* tp_str, str(x) */ 2036 }; 2037 2038 /* Window list object - Implementation 2039 */ 2040 /*ARGSUSED*/ 2041 static int 2042 WinListLength(PyObject *self) 2043 { 2044 win_T *w = firstwin; 2045 int n = 0; 2046 2047 while (w) 2048 { 2049 ++n; 2050 w = W_NEXT(w); 2051 } 2052 2053 return n; 2054 } 2055 2056 /*ARGSUSED*/ 2057 static PyObject * 2058 WinListItem(PyObject *self, int n) 2059 { 2060 win_T *w; 2061 2062 for (w = firstwin; w; w = W_NEXT(w), --n) 2063 if (n == 0) 2064 return WindowNew(w); 2065 2066 PyErr_SetString(PyExc_IndexError, _("no such window")); 2067 return NULL; 2068 } 2069 2070 /* Current items object - Definitions 2071 */ 2072 2073 typedef struct 2074 { 2075 PyObject_HEAD 2076 } 2077 CurrentObject; 2078 2079 static PyTypeObject CurrentType = { 2080 PyObject_HEAD_INIT(0) 2081 0, 2082 "current data", 2083 sizeof(CurrentObject), 2084 0, 2085 2086 (destructor) 0, /* tp_dealloc, refcount==0 */ 2087 (printfunc) 0, /* tp_print, print x */ 2088 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */ 2089 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */ 2090 (cmpfunc) 0, /* tp_compare, x>y */ 2091 (reprfunc) 0, /* tp_repr, `x`, print x */ 2092 2093 0, /* as number */ 2094 0, /* as sequence */ 2095 0, /* as mapping */ 2096 2097 (hashfunc) 0, /* tp_hash, dict(x) */ 2098 (ternaryfunc) 0, /* tp_call, x() */ 2099 (reprfunc) 0, /* tp_str, str(x) */ 2100 }; 2101 2102 /* Current items object - Implementation 2103 */ 2104 /*ARGSUSED*/ 2105 static PyObject * 2106 CurrentGetattr(PyObject *self, char *name) 2107 { 2108 if (strcmp(name, "buffer") == 0) 2109 return (PyObject *)BufferNew(curbuf); 2110 else if (strcmp(name, "window") == 0) 2111 return (PyObject *)WindowNew(curwin); 2112 else if (strcmp(name, "line") == 0) 2113 return GetBufferLine(curbuf, (int)curwin->w_cursor.lnum); 2114 else if (strcmp(name, "range") == 0) 2115 return RangeNew(curbuf, RangeStart, RangeEnd); 2116 else if (strcmp(name,"__members__") == 0) 2117 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range"); 2118 else 2119 { 2120 PyErr_SetString(PyExc_AttributeError, name); 2121 return NULL; 2122 } 2123 } 2124 2125 /*ARGSUSED*/ 2126 static int 2127 CurrentSetattr(PyObject *self, char *name, PyObject *value) 2128 { 2129 if (strcmp(name, "line") == 0) 2130 { 2131 if (SetBufferLine(curbuf, (int)curwin->w_cursor.lnum, value, NULL) == FAIL) 2132 return -1; 2133 2134 return 0; 2135 } 2136 else 2137 { 2138 PyErr_SetString(PyExc_AttributeError, name); 2139 return -1; 2140 } 2141 } 2142 2143 /* External interface 2144 */ 2145 2146 void 2147 python_buffer_free(buf_T *buf) 2148 { 2149 if (buf->python_ref) 2150 { 2151 BufferObject *bp = buf->python_ref; 2152 bp->buf = INVALID_BUFFER_VALUE; 2153 buf->python_ref = NULL; 2154 } 2155 } 2156 2157 #if defined(FEAT_WINDOWS) || defined(PROTO) 2158 void 2159 python_window_free(win_T *win) 2160 { 2161 if (win->python_ref) 2162 { 2163 WindowObject *wp = win->python_ref; 2164 wp->win = INVALID_WINDOW_VALUE; 2165 win->python_ref = NULL; 2166 } 2167 } 2168 #endif 2169 2170 static BufListObject TheBufferList = 2171 { 2172 PyObject_HEAD_INIT(&BufListType) 2173 }; 2174 2175 static WinListObject TheWindowList = 2176 { 2177 PyObject_HEAD_INIT(&WinListType) 2178 }; 2179 2180 static CurrentObject TheCurrent = 2181 { 2182 PyObject_HEAD_INIT(&CurrentType) 2183 }; 2184 2185 static int 2186 PythonMod_Init(void) 2187 { 2188 PyObject *mod; 2189 PyObject *dict; 2190 static char *(argv[2]) = {"", NULL}; 2191 2192 /* Fixups... */ 2193 BufferType.ob_type = &PyType_Type; 2194 RangeType.ob_type = &PyType_Type; 2195 WindowType.ob_type = &PyType_Type; 2196 BufListType.ob_type = &PyType_Type; 2197 WinListType.ob_type = &PyType_Type; 2198 CurrentType.ob_type = &PyType_Type; 2199 2200 /* Set sys.argv[] to avoid a crash in warn(). */ 2201 PySys_SetArgv(1, argv); 2202 2203 mod = Py_InitModule("vim", VimMethods); 2204 dict = PyModule_GetDict(mod); 2205 2206 VimError = Py_BuildValue("s", "vim.error"); 2207 2208 PyDict_SetItemString(dict, "error", VimError); 2209 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList); 2210 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent); 2211 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList); 2212 2213 if (PyErr_Occurred()) 2214 return -1; 2215 2216 return 0; 2217 } 2218 2219 /************************************************************************* 2220 * 4. Utility functions for handling the interface between Vim and Python. 2221 */ 2222 2223 /* Get a line from the specified buffer. The line number is 2224 * in Vim format (1-based). The line is returned as a Python 2225 * string object. 2226 */ 2227 static PyObject * 2228 GetBufferLine(buf_T *buf, int n) 2229 { 2230 return LineToString((char *)ml_get_buf(buf, (linenr_T)n, FALSE)); 2231 } 2232 2233 /* Get a list of lines from the specified buffer. The line numbers 2234 * are in Vim format (1-based). The range is from lo up to, but not 2235 * including, hi. The list is returned as a Python list of string objects. 2236 */ 2237 static PyObject * 2238 GetBufferLineList(buf_T *buf, int lo, int hi) 2239 { 2240 int i; 2241 int n = hi - lo; 2242 PyObject *list = PyList_New(n); 2243 2244 if (list == NULL) 2245 return NULL; 2246 2247 for (i = 0; i < n; ++i) 2248 { 2249 PyObject *str = LineToString((char *)ml_get_buf(buf, (linenr_T)(lo+i), FALSE)); 2250 2251 /* Error check - was the Python string creation OK? */ 2252 if (str == NULL) 2253 { 2254 Py_DECREF(list); 2255 return NULL; 2256 } 2257 2258 /* Set the list item */ 2259 if (PyList_SetItem(list, i, str)) 2260 { 2261 Py_DECREF(str); 2262 Py_DECREF(list); 2263 return NULL; 2264 } 2265 } 2266 2267 /* The ownership of the Python list is passed to the caller (ie, 2268 * the caller should Py_DECREF() the object when it is finished 2269 * with it). 2270 */ 2271 2272 return list; 2273 } 2274 2275 /* 2276 * Check if deleting lines made the cursor position invalid. 2277 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if 2278 * deleted). 2279 */ 2280 static void 2281 py_fix_cursor(int lo, int hi, int extra) 2282 { 2283 if (curwin->w_cursor.lnum >= lo) 2284 { 2285 /* Adjust the cursor position if it's in/after the changed 2286 * lines. */ 2287 if (curwin->w_cursor.lnum >= hi) 2288 { 2289 curwin->w_cursor.lnum += extra; 2290 check_cursor_col(); 2291 } 2292 else if (extra < 0) 2293 { 2294 curwin->w_cursor.lnum = lo; 2295 check_cursor(); 2296 } 2297 changed_cline_bef_curs(); 2298 } 2299 invalidate_botline(); 2300 } 2301 2302 /* Replace a line in the specified buffer. The line number is 2303 * in Vim format (1-based). The replacement line is given as 2304 * a Python string object. The object is checked for validity 2305 * and correct format. Errors are returned as a value of FAIL. 2306 * The return value is OK on success. 2307 * If OK is returned and len_change is not NULL, *len_change 2308 * is set to the change in the buffer length. 2309 */ 2310 static int 2311 SetBufferLine(buf_T *buf, int n, PyObject *line, int *len_change) 2312 { 2313 /* First of all, we check the thpe of the supplied Python object. 2314 * There are three cases: 2315 * 1. NULL, or None - this is a deletion. 2316 * 2. A string - this is a replacement. 2317 * 3. Anything else - this is an error. 2318 */ 2319 if (line == Py_None || line == NULL) 2320 { 2321 buf_T *savebuf = curbuf; 2322 2323 PyErr_Clear(); 2324 curbuf = buf; 2325 2326 if (u_savedel((linenr_T)n, 1L) == FAIL) 2327 PyErr_SetVim(_("cannot save undo information")); 2328 else if (ml_delete((linenr_T)n, FALSE) == FAIL) 2329 PyErr_SetVim(_("cannot delete line")); 2330 else 2331 { 2332 deleted_lines_mark((linenr_T)n, 1L); 2333 if (buf == curwin->w_buffer) 2334 py_fix_cursor(n, n + 1, -1); 2335 } 2336 2337 curbuf = savebuf; 2338 2339 if (PyErr_Occurred() || VimErrorCheck()) 2340 return FAIL; 2341 2342 if (len_change) 2343 *len_change = -1; 2344 2345 return OK; 2346 } 2347 else if (PyString_Check(line)) 2348 { 2349 char *save = StringToLine(line); 2350 buf_T *savebuf = curbuf; 2351 2352 if (save == NULL) 2353 return FAIL; 2354 2355 /* We do not need to free "save" if ml_replace() consumes it. */ 2356 PyErr_Clear(); 2357 curbuf = buf; 2358 2359 if (u_savesub((linenr_T)n) == FAIL) 2360 { 2361 PyErr_SetVim(_("cannot save undo information")); 2362 vim_free(save); 2363 } 2364 else if (ml_replace((linenr_T)n, (char_u *)save, FALSE) == FAIL) 2365 { 2366 PyErr_SetVim(_("cannot replace line")); 2367 vim_free(save); 2368 } 2369 else 2370 changed_bytes((linenr_T)n, 0); 2371 2372 curbuf = savebuf; 2373 2374 if (PyErr_Occurred() || VimErrorCheck()) 2375 return FAIL; 2376 2377 if (len_change) 2378 *len_change = 0; 2379 2380 return OK; 2381 } 2382 else 2383 { 2384 PyErr_BadArgument(); 2385 return FAIL; 2386 } 2387 } 2388 2389 /* Replace a range of lines in the specified buffer. The line numbers are in 2390 * Vim format (1-based). The range is from lo up to, but not including, hi. 2391 * The replacement lines are given as a Python list of string objects. The 2392 * list is checked for validity and correct format. Errors are returned as a 2393 * value of FAIL. The return value is OK on success. 2394 * If OK is returned and len_change is not NULL, *len_change 2395 * is set to the change in the buffer length. 2396 */ 2397 static int 2398 SetBufferLineList(buf_T *buf, int lo, int hi, PyObject *list, int *len_change) 2399 { 2400 /* First of all, we check the thpe of the supplied Python object. 2401 * There are three cases: 2402 * 1. NULL, or None - this is a deletion. 2403 * 2. A list - this is a replacement. 2404 * 3. Anything else - this is an error. 2405 */ 2406 if (list == Py_None || list == NULL) 2407 { 2408 int i; 2409 int n = hi - lo; 2410 buf_T *savebuf = curbuf; 2411 2412 PyErr_Clear(); 2413 curbuf = buf; 2414 2415 if (u_savedel((linenr_T)lo, (long)n) == FAIL) 2416 PyErr_SetVim(_("cannot save undo information")); 2417 else 2418 { 2419 for (i = 0; i < n; ++i) 2420 { 2421 if (ml_delete((linenr_T)lo, FALSE) == FAIL) 2422 { 2423 PyErr_SetVim(_("cannot delete line")); 2424 break; 2425 } 2426 } 2427 deleted_lines_mark((linenr_T)lo, (long)i); 2428 2429 if (buf == curwin->w_buffer) 2430 py_fix_cursor(lo, hi, -n); 2431 } 2432 2433 curbuf = savebuf; 2434 2435 if (PyErr_Occurred() || VimErrorCheck()) 2436 return FAIL; 2437 2438 if (len_change) 2439 *len_change = -n; 2440 2441 return OK; 2442 } 2443 else if (PyList_Check(list)) 2444 { 2445 int i; 2446 int new_len = PyList_Size(list); 2447 int old_len = hi - lo; 2448 int extra = 0; /* lines added to text, can be negative */ 2449 char **array; 2450 buf_T *savebuf; 2451 2452 if (new_len == 0) /* avoid allocating zero bytes */ 2453 array = NULL; 2454 else 2455 { 2456 array = (char **)alloc((unsigned)(new_len * sizeof(char *))); 2457 if (array == NULL) 2458 { 2459 PyErr_NoMemory(); 2460 return FAIL; 2461 } 2462 } 2463 2464 for (i = 0; i < new_len; ++i) 2465 { 2466 PyObject *line = PyList_GetItem(list, i); 2467 2468 array[i] = StringToLine(line); 2469 if (array[i] == NULL) 2470 { 2471 while (i) 2472 vim_free(array[--i]); 2473 vim_free(array); 2474 return FAIL; 2475 } 2476 } 2477 2478 savebuf = curbuf; 2479 2480 PyErr_Clear(); 2481 curbuf = buf; 2482 2483 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL) 2484 PyErr_SetVim(_("cannot save undo information")); 2485 2486 /* If the size of the range is reducing (ie, new_len < old_len) we 2487 * need to delete some old_len. We do this at the start, by 2488 * repeatedly deleting line "lo". 2489 */ 2490 if (!PyErr_Occurred()) 2491 { 2492 for (i = 0; i < old_len - new_len; ++i) 2493 if (ml_delete((linenr_T)lo, FALSE) == FAIL) 2494 { 2495 PyErr_SetVim(_("cannot delete line")); 2496 break; 2497 } 2498 extra -= i; 2499 } 2500 2501 /* For as long as possible, replace the existing old_len with the 2502 * new old_len. This is a more efficient operation, as it requires 2503 * less memory allocation and freeing. 2504 */ 2505 if (!PyErr_Occurred()) 2506 { 2507 for (i = 0; i < old_len && i < new_len; ++i) 2508 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], FALSE) 2509 == FAIL) 2510 { 2511 PyErr_SetVim(_("cannot replace line")); 2512 break; 2513 } 2514 } 2515 else 2516 i = 0; 2517 2518 /* Now we may need to insert the remaining new old_len. If we do, we 2519 * must free the strings as we finish with them (we can't pass the 2520 * responsibility to vim in this case). 2521 */ 2522 if (!PyErr_Occurred()) 2523 { 2524 while (i < new_len) 2525 { 2526 if (ml_append((linenr_T)(lo + i - 1), 2527 (char_u *)array[i], 0, FALSE) == FAIL) 2528 { 2529 PyErr_SetVim(_("cannot insert line")); 2530 break; 2531 } 2532 vim_free(array[i]); 2533 ++i; 2534 ++extra; 2535 } 2536 } 2537 2538 /* Free any left-over old_len, as a result of an error */ 2539 while (i < new_len) 2540 { 2541 vim_free(array[i]); 2542 ++i; 2543 } 2544 2545 /* Free the array of old_len. All of its contents have now 2546 * been dealt with (either freed, or the responsibility passed 2547 * to vim. 2548 */ 2549 vim_free(array); 2550 2551 /* Adjust marks. Invalidate any which lie in the 2552 * changed range, and move any in the remainder of the buffer. 2553 */ 2554 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1), 2555 (long)MAXLNUM, (long)extra); 2556 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra); 2557 2558 if (buf == curwin->w_buffer) 2559 py_fix_cursor(lo, hi, extra); 2560 2561 curbuf = savebuf; 2562 2563 if (PyErr_Occurred() || VimErrorCheck()) 2564 return FAIL; 2565 2566 if (len_change) 2567 *len_change = new_len - old_len; 2568 2569 return OK; 2570 } 2571 else 2572 { 2573 PyErr_BadArgument(); 2574 return FAIL; 2575 } 2576 } 2577 2578 /* Insert a number of lines into the specified buffer after the specifed line. 2579 * The line number is in Vim format (1-based). The lines to be inserted are 2580 * given as a Python list of string objects or as a single string. The lines 2581 * to be added are checked for validity and correct format. Errors are 2582 * returned as a value of FAIL. The return value is OK on success. 2583 * If OK is returned and len_change is not NULL, *len_change 2584 * is set to the change in the buffer length. 2585 */ 2586 static int 2587 InsertBufferLines(buf_T *buf, int n, PyObject *lines, int *len_change) 2588 { 2589 /* First of all, we check the type of the supplied Python object. 2590 * It must be a string or a list, or the call is in error. 2591 */ 2592 if (PyString_Check(lines)) 2593 { 2594 char *str = StringToLine(lines); 2595 buf_T *savebuf; 2596 2597 if (str == NULL) 2598 return FAIL; 2599 2600 savebuf = curbuf; 2601 2602 PyErr_Clear(); 2603 curbuf = buf; 2604 2605 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL) 2606 PyErr_SetVim(_("cannot save undo information")); 2607 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL) 2608 PyErr_SetVim(_("cannot insert line")); 2609 else 2610 appended_lines_mark((linenr_T)n, 1L); 2611 2612 vim_free(str); 2613 curbuf = savebuf; 2614 update_screen(VALID); 2615 2616 if (PyErr_Occurred() || VimErrorCheck()) 2617 return FAIL; 2618 2619 if (len_change) 2620 *len_change = 1; 2621 2622 return OK; 2623 } 2624 else if (PyList_Check(lines)) 2625 { 2626 int i; 2627 int size = PyList_Size(lines); 2628 char **array; 2629 buf_T *savebuf; 2630 2631 array = (char **)alloc((unsigned)(size * sizeof(char *))); 2632 if (array == NULL) 2633 { 2634 PyErr_NoMemory(); 2635 return FAIL; 2636 } 2637 2638 for (i = 0; i < size; ++i) 2639 { 2640 PyObject *line = PyList_GetItem(lines, i); 2641 array[i] = StringToLine(line); 2642 2643 if (array[i] == NULL) 2644 { 2645 while (i) 2646 vim_free(array[--i]); 2647 vim_free(array); 2648 return FAIL; 2649 } 2650 } 2651 2652 savebuf = curbuf; 2653 2654 PyErr_Clear(); 2655 curbuf = buf; 2656 2657 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL) 2658 PyErr_SetVim(_("cannot save undo information")); 2659 else 2660 { 2661 for (i = 0; i < size; ++i) 2662 { 2663 if (ml_append((linenr_T)(n + i), 2664 (char_u *)array[i], 0, FALSE) == FAIL) 2665 { 2666 PyErr_SetVim(_("cannot insert line")); 2667 2668 /* Free the rest of the lines */ 2669 while (i < size) 2670 vim_free(array[i++]); 2671 2672 break; 2673 } 2674 vim_free(array[i]); 2675 } 2676 if (i > 0) 2677 appended_lines_mark((linenr_T)n, (long)i); 2678 } 2679 2680 /* Free the array of lines. All of its contents have now 2681 * been freed. 2682 */ 2683 vim_free(array); 2684 2685 curbuf = savebuf; 2686 update_screen(VALID); 2687 2688 if (PyErr_Occurred() || VimErrorCheck()) 2689 return FAIL; 2690 2691 if (len_change) 2692 *len_change = size; 2693 2694 return OK; 2695 } 2696 else 2697 { 2698 PyErr_BadArgument(); 2699 return FAIL; 2700 } 2701 } 2702 2703 /* Convert a Vim line into a Python string. 2704 * All internal newlines are replaced by null characters. 2705 * 2706 * On errors, the Python exception data is set, and NULL is returned. 2707 */ 2708 static PyObject * 2709 LineToString(const char *str) 2710 { 2711 PyObject *result; 2712 int len = strlen(str); 2713 char *p; 2714 2715 /* Allocate an Python string object, with uninitialised contents. We 2716 * must do it this way, so that we can modify the string in place 2717 * later. See the Python source, Objects/stringobject.c for details. 2718 */ 2719 result = PyString_FromStringAndSize(NULL, len); 2720 if (result == NULL) 2721 return NULL; 2722 2723 p = PyString_AsString(result); 2724 2725 while (*str) 2726 { 2727 if (*str == '\n') 2728 *p = '\0'; 2729 else 2730 *p = *str; 2731 2732 ++p; 2733 ++str; 2734 } 2735 2736 return result; 2737 } 2738 2739 /* Convert a Python string into a Vim line. 2740 * 2741 * The result is in allocated memory. All internal nulls are replaced by 2742 * newline characters. It is an error for the string to contain newline 2743 * characters. 2744 * 2745 * On errors, the Python exception data is set, and NULL is returned. 2746 */ 2747 static char * 2748 StringToLine(PyObject *obj) 2749 { 2750 const char *str; 2751 char *save; 2752 int len; 2753 int i; 2754 char *p; 2755 2756 if (obj == NULL || !PyString_Check(obj)) 2757 { 2758 PyErr_BadArgument(); 2759 return NULL; 2760 } 2761 2762 str = PyString_AsString(obj); 2763 len = PyString_Size(obj); 2764 2765 /* 2766 * Error checking: String must not contain newlines, as we 2767 * are replacing a single line, and we must replace it with 2768 * a single line. 2769 * A trailing newline is removed, so that append(f.readlines()) works. 2770 */ 2771 p = memchr(str, '\n', len); 2772 if (p != NULL) 2773 { 2774 if (p == str + len - 1) 2775 --len; 2776 else 2777 { 2778 PyErr_SetVim(_("string cannot contain newlines")); 2779 return NULL; 2780 } 2781 } 2782 2783 /* Create a copy of the string, with internal nulls replaced by 2784 * newline characters, as is the vim convention. 2785 */ 2786 save = (char *)alloc((unsigned)(len+1)); 2787 if (save == NULL) 2788 { 2789 PyErr_NoMemory(); 2790 return NULL; 2791 } 2792 2793 for (i = 0; i < len; ++i) 2794 { 2795 if (str[i] == '\0') 2796 save[i] = '\n'; 2797 else 2798 save[i] = str[i]; 2799 } 2800 2801 save[i] = '\0'; 2802 2803 return save; 2804 } 2805 2806 /* Check to see whether a Vim error has been reported, or a keyboard 2807 * interrupt has been detected. 2808 */ 2809 static int 2810 VimErrorCheck(void) 2811 { 2812 if (got_int) 2813 { 2814 PyErr_SetNone(PyExc_KeyboardInterrupt); 2815 return 1; 2816 } 2817 else if (did_emsg && !PyErr_Occurred()) 2818 { 2819 PyErr_SetNone(VimError); 2820 return 1; 2821 } 2822 2823 return 0; 2824 } 2825 2826 2827 /* Don't generate a prototype for the next function, it generates an error on 2828 * newer Python versions. */ 2829 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO) 2830 2831 char * 2832 Py_GetProgramName(void) 2833 { 2834 return "vim"; 2835 } 2836 #endif /* Python 1.4 */ 2837