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 <limits.h> 23 24 /* Python.h defines _POSIX_THREADS itself (if needed) */ 25 #ifdef _POSIX_THREADS 26 # undef _POSIX_THREADS 27 #endif 28 29 #if defined(_WIN32) && defined(HAVE_FCNTL_H) 30 # undef HAVE_FCNTL_H 31 #endif 32 33 #ifdef _DEBUG 34 # undef _DEBUG 35 #endif 36 37 #ifdef HAVE_STDARG_H 38 # undef HAVE_STDARG_H /* Python's config.h defines it as well. */ 39 #endif 40 #ifdef _POSIX_C_SOURCE 41 # undef _POSIX_C_SOURCE /* pyconfig.h defines it as well. */ 42 #endif 43 #ifdef _XOPEN_SOURCE 44 # undef _XOPEN_SOURCE /* pyconfig.h defines it as well. */ 45 #endif 46 47 #define PY_SSIZE_T_CLEAN 48 49 #include <Python.h> 50 #if defined(MACOS) && !defined(MACOS_X_UNIX) 51 # include "macglue.h" 52 # include <CodeFragments.h> 53 #endif 54 #undef main /* Defined in python.h - aargh */ 55 #undef HAVE_FCNTL_H /* Clash with os_win32.h */ 56 57 static void init_structs(void); 58 59 /* No-op conversion functions, use with care! */ 60 #define PyString_AsBytes(obj) (obj) 61 #define PyString_FreeBytes(obj) 62 63 #if !defined(FEAT_PYTHON) && defined(PROTO) 64 /* Use this to be able to generate prototypes without python being used. */ 65 # define PyObject Py_ssize_t 66 # define PyThreadState Py_ssize_t 67 # define PyTypeObject Py_ssize_t 68 struct PyMethodDef { Py_ssize_t a; }; 69 # define PySequenceMethods Py_ssize_t 70 #endif 71 72 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02050000 73 # define PyInt Py_ssize_t 74 # define PyInquiry lenfunc 75 # define PyIntArgFunc ssizeargfunc 76 # define PyIntIntArgFunc ssizessizeargfunc 77 # define PyIntObjArgProc ssizeobjargproc 78 # define PyIntIntObjArgProc ssizessizeobjargproc 79 # define Py_ssize_t_fmt "n" 80 #else 81 # define PyInt int 82 # define PyInquiry inquiry 83 # define PyIntArgFunc intargfunc 84 # define PyIntIntArgFunc intintargfunc 85 # define PyIntObjArgProc intobjargproc 86 # define PyIntIntObjArgProc intintobjargproc 87 # define Py_ssize_t_fmt "i" 88 #endif 89 90 /* Parser flags */ 91 #define single_input 256 92 #define file_input 257 93 #define eval_input 258 94 95 #if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x020300F0 96 /* Python 2.3: can invoke ":python" recursively. */ 97 # define PY_CAN_RECURSE 98 #endif 99 100 # if defined(DYNAMIC_PYTHON) || defined(PROTO) 101 # ifndef DYNAMIC_PYTHON 102 # define HINSTANCE long_u /* for generating prototypes */ 103 # endif 104 105 # ifndef WIN3264 106 # include <dlfcn.h> 107 # define FARPROC void* 108 # define HINSTANCE void* 109 # if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL) 110 # define load_dll(n) dlopen((n), RTLD_LAZY) 111 # else 112 # define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL) 113 # endif 114 # define close_dll dlclose 115 # define symbol_from_dll dlsym 116 # else 117 # define load_dll vimLoadLib 118 # define close_dll FreeLibrary 119 # define symbol_from_dll GetProcAddress 120 # endif 121 122 /* This makes if_python.c compile without warnings against Python 2.5 123 * on Win32 and Win64. */ 124 # undef PyRun_SimpleString 125 # undef PyArg_Parse 126 # undef PyArg_ParseTuple 127 # undef Py_BuildValue 128 # undef Py_InitModule4 129 # undef Py_InitModule4_64 130 131 /* 132 * Wrapper defines 133 */ 134 # define PyArg_Parse dll_PyArg_Parse 135 # define PyArg_ParseTuple dll_PyArg_ParseTuple 136 # define PyMem_Free dll_PyMem_Free 137 # define PyDict_SetItemString dll_PyDict_SetItemString 138 # define PyErr_BadArgument dll_PyErr_BadArgument 139 # define PyErr_Clear dll_PyErr_Clear 140 # define PyErr_NoMemory dll_PyErr_NoMemory 141 # define PyErr_Occurred dll_PyErr_Occurred 142 # define PyErr_SetNone dll_PyErr_SetNone 143 # define PyErr_SetString dll_PyErr_SetString 144 # define PyEval_InitThreads dll_PyEval_InitThreads 145 # define PyEval_RestoreThread dll_PyEval_RestoreThread 146 # define PyEval_SaveThread dll_PyEval_SaveThread 147 # ifdef PY_CAN_RECURSE 148 # define PyGILState_Ensure dll_PyGILState_Ensure 149 # define PyGILState_Release dll_PyGILState_Release 150 # endif 151 # define PyInt_AsLong dll_PyInt_AsLong 152 # define PyInt_FromLong dll_PyInt_FromLong 153 # define PyInt_Type (*dll_PyInt_Type) 154 # define PyList_GetItem dll_PyList_GetItem 155 # define PyList_Append dll_PyList_Append 156 # define PyList_New dll_PyList_New 157 # define PyList_SetItem dll_PyList_SetItem 158 # define PyList_Size dll_PyList_Size 159 # define PyList_Type (*dll_PyList_Type) 160 # define PyImport_ImportModule dll_PyImport_ImportModule 161 # define PyDict_New dll_PyDict_New 162 # define PyDict_GetItemString dll_PyDict_GetItemString 163 # define PyModule_GetDict dll_PyModule_GetDict 164 # define PyRun_SimpleString dll_PyRun_SimpleString 165 # define PyString_AsString dll_PyString_AsString 166 # define PyString_FromString dll_PyString_FromString 167 # define PyString_FromStringAndSize dll_PyString_FromStringAndSize 168 # define PyString_Size dll_PyString_Size 169 # define PyString_Type (*dll_PyString_Type) 170 # define PySys_SetObject dll_PySys_SetObject 171 # define PySys_SetArgv dll_PySys_SetArgv 172 # define PyType_Type (*dll_PyType_Type) 173 # define PyType_Ready (*dll_PyType_Ready) 174 # define Py_BuildValue dll_Py_BuildValue 175 # define Py_FindMethod dll_Py_FindMethod 176 # define Py_InitModule4 dll_Py_InitModule4 177 # define Py_SetPythonHome dll_Py_SetPythonHome 178 # define Py_Initialize dll_Py_Initialize 179 # define Py_Finalize dll_Py_Finalize 180 # define Py_IsInitialized dll_Py_IsInitialized 181 # define _PyObject_New dll__PyObject_New 182 # define _Py_NoneStruct (*dll__Py_NoneStruct) 183 # define PyObject_Init dll__PyObject_Init 184 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000 185 # define PyType_IsSubtype dll_PyType_IsSubtype 186 # endif 187 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000 188 # define PyObject_Malloc dll_PyObject_Malloc 189 # define PyObject_Free dll_PyObject_Free 190 # endif 191 192 /* 193 * Pointers for dynamic link 194 */ 195 static int(*dll_PyArg_Parse)(PyObject *, char *, ...); 196 static int(*dll_PyArg_ParseTuple)(PyObject *, char *, ...); 197 static int(*dll_PyMem_Free)(void *); 198 static int(*dll_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item); 199 static int(*dll_PyErr_BadArgument)(void); 200 static void(*dll_PyErr_Clear)(void); 201 static PyObject*(*dll_PyErr_NoMemory)(void); 202 static PyObject*(*dll_PyErr_Occurred)(void); 203 static void(*dll_PyErr_SetNone)(PyObject *); 204 static void(*dll_PyErr_SetString)(PyObject *, const char *); 205 static void(*dll_PyEval_InitThreads)(void); 206 static void(*dll_PyEval_RestoreThread)(PyThreadState *); 207 static PyThreadState*(*dll_PyEval_SaveThread)(void); 208 # ifdef PY_CAN_RECURSE 209 static PyGILState_STATE (*dll_PyGILState_Ensure)(void); 210 static void (*dll_PyGILState_Release)(PyGILState_STATE); 211 #endif 212 static long(*dll_PyInt_AsLong)(PyObject *); 213 static PyObject*(*dll_PyInt_FromLong)(long); 214 static PyTypeObject* dll_PyInt_Type; 215 static PyObject*(*dll_PyList_GetItem)(PyObject *, PyInt); 216 static PyObject*(*dll_PyList_Append)(PyObject *, PyObject *); 217 static PyObject*(*dll_PyList_New)(PyInt size); 218 static int(*dll_PyList_SetItem)(PyObject *, PyInt, PyObject *); 219 static PyInt(*dll_PyList_Size)(PyObject *); 220 static PyTypeObject* dll_PyList_Type; 221 static PyObject*(*dll_PyImport_ImportModule)(const char *); 222 static PyObject*(*dll_PyDict_New)(void); 223 static PyObject*(*dll_PyDict_GetItemString)(PyObject *, const char *); 224 static PyObject*(*dll_PyModule_GetDict)(PyObject *); 225 static int(*dll_PyRun_SimpleString)(char *); 226 static char*(*dll_PyString_AsString)(PyObject *); 227 static PyObject*(*dll_PyString_FromString)(const char *); 228 static PyObject*(*dll_PyString_FromStringAndSize)(const char *, PyInt); 229 static PyInt(*dll_PyString_Size)(PyObject *); 230 static PyTypeObject* dll_PyString_Type; 231 static int(*dll_PySys_SetObject)(char *, PyObject *); 232 static int(*dll_PySys_SetArgv)(int, char **); 233 static PyTypeObject* dll_PyType_Type; 234 static int (*dll_PyType_Ready)(PyTypeObject *type); 235 static PyObject*(*dll_Py_BuildValue)(char *, ...); 236 static PyObject*(*dll_Py_FindMethod)(struct PyMethodDef[], PyObject *, char *); 237 static PyObject*(*dll_Py_InitModule4)(char *, struct PyMethodDef *, char *, PyObject *, int); 238 static void(*dll_Py_SetPythonHome)(char *home); 239 static void(*dll_Py_Initialize)(void); 240 static void(*dll_Py_Finalize)(void); 241 static int(*dll_Py_IsInitialized)(void); 242 static PyObject*(*dll__PyObject_New)(PyTypeObject *, PyObject *); 243 static PyObject*(*dll__PyObject_Init)(PyObject *, PyTypeObject *); 244 static PyObject* dll__Py_NoneStruct; 245 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000 246 static int (*dll_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *); 247 # endif 248 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000 249 static void* (*dll_PyObject_Malloc)(size_t); 250 static void (*dll_PyObject_Free)(void*); 251 # endif 252 253 static HINSTANCE hinstPython = 0; /* Instance of python.dll */ 254 255 /* Imported exception objects */ 256 static PyObject *imp_PyExc_AttributeError; 257 static PyObject *imp_PyExc_IndexError; 258 static PyObject *imp_PyExc_KeyboardInterrupt; 259 static PyObject *imp_PyExc_TypeError; 260 static PyObject *imp_PyExc_ValueError; 261 262 # define PyExc_AttributeError imp_PyExc_AttributeError 263 # define PyExc_IndexError imp_PyExc_IndexError 264 # define PyExc_KeyboardInterrupt imp_PyExc_KeyboardInterrupt 265 # define PyExc_TypeError imp_PyExc_TypeError 266 # define PyExc_ValueError imp_PyExc_ValueError 267 268 /* 269 * Table of name to function pointer of python. 270 */ 271 # define PYTHON_PROC FARPROC 272 static struct 273 { 274 char *name; 275 PYTHON_PROC *ptr; 276 } python_funcname_table[] = 277 { 278 {"PyArg_Parse", (PYTHON_PROC*)&dll_PyArg_Parse}, 279 {"PyArg_ParseTuple", (PYTHON_PROC*)&dll_PyArg_ParseTuple}, 280 {"PyMem_Free", (PYTHON_PROC*)&dll_PyMem_Free}, 281 {"PyDict_SetItemString", (PYTHON_PROC*)&dll_PyDict_SetItemString}, 282 {"PyErr_BadArgument", (PYTHON_PROC*)&dll_PyErr_BadArgument}, 283 {"PyErr_Clear", (PYTHON_PROC*)&dll_PyErr_Clear}, 284 {"PyErr_NoMemory", (PYTHON_PROC*)&dll_PyErr_NoMemory}, 285 {"PyErr_Occurred", (PYTHON_PROC*)&dll_PyErr_Occurred}, 286 {"PyErr_SetNone", (PYTHON_PROC*)&dll_PyErr_SetNone}, 287 {"PyErr_SetString", (PYTHON_PROC*)&dll_PyErr_SetString}, 288 {"PyEval_InitThreads", (PYTHON_PROC*)&dll_PyEval_InitThreads}, 289 {"PyEval_RestoreThread", (PYTHON_PROC*)&dll_PyEval_RestoreThread}, 290 {"PyEval_SaveThread", (PYTHON_PROC*)&dll_PyEval_SaveThread}, 291 # ifdef PY_CAN_RECURSE 292 {"PyGILState_Ensure", (PYTHON_PROC*)&dll_PyGILState_Ensure}, 293 {"PyGILState_Release", (PYTHON_PROC*)&dll_PyGILState_Release}, 294 # endif 295 {"PyInt_AsLong", (PYTHON_PROC*)&dll_PyInt_AsLong}, 296 {"PyInt_FromLong", (PYTHON_PROC*)&dll_PyInt_FromLong}, 297 {"PyInt_Type", (PYTHON_PROC*)&dll_PyInt_Type}, 298 {"PyList_GetItem", (PYTHON_PROC*)&dll_PyList_GetItem}, 299 {"PyList_Append", (PYTHON_PROC*)&dll_PyList_Append}, 300 {"PyList_New", (PYTHON_PROC*)&dll_PyList_New}, 301 {"PyList_SetItem", (PYTHON_PROC*)&dll_PyList_SetItem}, 302 {"PyList_Size", (PYTHON_PROC*)&dll_PyList_Size}, 303 {"PyList_Type", (PYTHON_PROC*)&dll_PyList_Type}, 304 {"PyImport_ImportModule", (PYTHON_PROC*)&dll_PyImport_ImportModule}, 305 {"PyDict_GetItemString", (PYTHON_PROC*)&dll_PyDict_GetItemString}, 306 {"PyDict_New", (PYTHON_PROC*)&dll_PyDict_New}, 307 {"PyModule_GetDict", (PYTHON_PROC*)&dll_PyModule_GetDict}, 308 {"PyRun_SimpleString", (PYTHON_PROC*)&dll_PyRun_SimpleString}, 309 {"PyString_AsString", (PYTHON_PROC*)&dll_PyString_AsString}, 310 {"PyString_FromString", (PYTHON_PROC*)&dll_PyString_FromString}, 311 {"PyString_FromStringAndSize", (PYTHON_PROC*)&dll_PyString_FromStringAndSize}, 312 {"PyString_Size", (PYTHON_PROC*)&dll_PyString_Size}, 313 {"PyString_Type", (PYTHON_PROC*)&dll_PyString_Type}, 314 {"PySys_SetObject", (PYTHON_PROC*)&dll_PySys_SetObject}, 315 {"PySys_SetArgv", (PYTHON_PROC*)&dll_PySys_SetArgv}, 316 {"PyType_Type", (PYTHON_PROC*)&dll_PyType_Type}, 317 {"PyType_Ready", (PYTHON_PROC*)&dll_PyType_Ready}, 318 {"Py_BuildValue", (PYTHON_PROC*)&dll_Py_BuildValue}, 319 {"Py_FindMethod", (PYTHON_PROC*)&dll_Py_FindMethod}, 320 # if (PY_VERSION_HEX >= 0x02050000) && SIZEOF_SIZE_T != SIZEOF_INT 321 {"Py_InitModule4_64", (PYTHON_PROC*)&dll_Py_InitModule4}, 322 # else 323 {"Py_InitModule4", (PYTHON_PROC*)&dll_Py_InitModule4}, 324 # endif 325 {"Py_SetPythonHome", (PYTHON_PROC*)&dll_Py_SetPythonHome}, 326 {"Py_Initialize", (PYTHON_PROC*)&dll_Py_Initialize}, 327 {"Py_Finalize", (PYTHON_PROC*)&dll_Py_Finalize}, 328 {"Py_IsInitialized", (PYTHON_PROC*)&dll_Py_IsInitialized}, 329 {"_PyObject_New", (PYTHON_PROC*)&dll__PyObject_New}, 330 {"PyObject_Init", (PYTHON_PROC*)&dll__PyObject_Init}, 331 {"_Py_NoneStruct", (PYTHON_PROC*)&dll__Py_NoneStruct}, 332 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02020000 333 {"PyType_IsSubtype", (PYTHON_PROC*)&dll_PyType_IsSubtype}, 334 # endif 335 # if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02030000 336 {"PyObject_Malloc", (PYTHON_PROC*)&dll_PyObject_Malloc}, 337 {"PyObject_Free", (PYTHON_PROC*)&dll_PyObject_Free}, 338 # endif 339 {"", NULL}, 340 }; 341 342 /* 343 * Free python.dll 344 */ 345 static void 346 end_dynamic_python(void) 347 { 348 if (hinstPython) 349 { 350 close_dll(hinstPython); 351 hinstPython = 0; 352 } 353 } 354 355 /* 356 * Load library and get all pointers. 357 * Parameter 'libname' provides name of DLL. 358 * Return OK or FAIL. 359 */ 360 static int 361 python_runtime_link_init(char *libname, int verbose) 362 { 363 int i; 364 365 #if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON3) 366 /* Can't have Python and Python3 loaded at the same time. 367 * It cause a crash, because RTLD_GLOBAL is needed for 368 * standard C extension libraries of one or both python versions. */ 369 if (python3_loaded()) 370 { 371 EMSG(_("E836: This Vim cannot execute :python after using :py3")); 372 return FAIL; 373 } 374 #endif 375 376 if (hinstPython) 377 return OK; 378 hinstPython = load_dll(libname); 379 if (!hinstPython) 380 { 381 if (verbose) 382 EMSG2(_(e_loadlib), libname); 383 return FAIL; 384 } 385 386 for (i = 0; python_funcname_table[i].ptr; ++i) 387 { 388 if ((*python_funcname_table[i].ptr = symbol_from_dll(hinstPython, 389 python_funcname_table[i].name)) == NULL) 390 { 391 close_dll(hinstPython); 392 hinstPython = 0; 393 if (verbose) 394 EMSG2(_(e_loadfunc), python_funcname_table[i].name); 395 return FAIL; 396 } 397 } 398 return OK; 399 } 400 401 /* 402 * If python is enabled (there is installed python on Windows system) return 403 * TRUE, else FALSE. 404 */ 405 int 406 python_enabled(int verbose) 407 { 408 return python_runtime_link_init(DYNAMIC_PYTHON_DLL, verbose) == OK; 409 } 410 411 /* 412 * Load the standard Python exceptions - don't import the symbols from the 413 * DLL, as this can cause errors (importing data symbols is not reliable). 414 */ 415 static void 416 get_exceptions(void) 417 { 418 PyObject *exmod = PyImport_ImportModule("exceptions"); 419 PyObject *exdict = PyModule_GetDict(exmod); 420 imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError"); 421 imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError"); 422 imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt"); 423 imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError"); 424 imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError"); 425 Py_XINCREF(imp_PyExc_AttributeError); 426 Py_XINCREF(imp_PyExc_IndexError); 427 Py_XINCREF(imp_PyExc_KeyboardInterrupt); 428 Py_XINCREF(imp_PyExc_TypeError); 429 Py_XINCREF(imp_PyExc_ValueError); 430 Py_XDECREF(exmod); 431 } 432 #endif /* DYNAMIC_PYTHON */ 433 434 static PyObject *BufferNew (buf_T *); 435 static PyObject *WindowNew(win_T *); 436 static PyObject *LineToString(const char *); 437 438 static PyTypeObject RangeType; 439 440 /* 441 * Include the code shared with if_python3.c 442 */ 443 #include "if_py_both.h" 444 445 446 /****************************************************** 447 * Internal function prototypes. 448 */ 449 450 static PyInt RangeStart; 451 static PyInt RangeEnd; 452 453 static void PythonIO_Flush(void); 454 static int PythonIO_Init(void); 455 static int PythonMod_Init(void); 456 457 /* Utility functions for the vim/python interface 458 * ---------------------------------------------- 459 */ 460 461 static int SetBufferLineList(buf_T *, PyInt, PyInt, PyObject *, PyInt *); 462 463 464 /****************************************************** 465 * 1. Python interpreter main program. 466 */ 467 468 static int initialised = 0; 469 470 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ 471 typedef PyObject PyThreadState; 472 #endif 473 474 #ifdef PY_CAN_RECURSE 475 static PyGILState_STATE pygilstate = PyGILState_UNLOCKED; 476 #else 477 static PyThreadState *saved_python_thread = NULL; 478 #endif 479 480 /* 481 * Suspend a thread of the Python interpreter, other threads are allowed to 482 * run. 483 */ 484 static void 485 Python_SaveThread(void) 486 { 487 #ifdef PY_CAN_RECURSE 488 PyGILState_Release(pygilstate); 489 #else 490 saved_python_thread = PyEval_SaveThread(); 491 #endif 492 } 493 494 /* 495 * Restore a thread of the Python interpreter, waits for other threads to 496 * block. 497 */ 498 static void 499 Python_RestoreThread(void) 500 { 501 #ifdef PY_CAN_RECURSE 502 pygilstate = PyGILState_Ensure(); 503 #else 504 PyEval_RestoreThread(saved_python_thread); 505 saved_python_thread = NULL; 506 #endif 507 } 508 509 void 510 python_end() 511 { 512 static int recurse = 0; 513 514 /* If a crash occurs while doing this, don't try again. */ 515 if (recurse != 0) 516 return; 517 518 ++recurse; 519 520 #ifdef DYNAMIC_PYTHON 521 if (hinstPython && Py_IsInitialized()) 522 { 523 Python_RestoreThread(); /* enter python */ 524 Py_Finalize(); 525 } 526 end_dynamic_python(); 527 #else 528 if (Py_IsInitialized()) 529 { 530 Python_RestoreThread(); /* enter python */ 531 Py_Finalize(); 532 } 533 #endif 534 535 --recurse; 536 } 537 538 #if (defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON3)) || defined(PROTO) 539 int 540 python_loaded() 541 { 542 return (hinstPython != 0); 543 } 544 #endif 545 546 static int 547 Python_Init(void) 548 { 549 if (!initialised) 550 { 551 #ifdef DYNAMIC_PYTHON 552 if (!python_enabled(TRUE)) 553 { 554 EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); 555 goto fail; 556 } 557 #endif 558 559 #ifdef PYTHON_HOME 560 Py_SetPythonHome(PYTHON_HOME); 561 #endif 562 563 init_structs(); 564 565 #if !defined(MACOS) || defined(MACOS_X_UNIX) 566 Py_Initialize(); 567 #else 568 PyMac_Initialize(); 569 #endif 570 /* initialise threads */ 571 PyEval_InitThreads(); 572 573 #ifdef DYNAMIC_PYTHON 574 get_exceptions(); 575 #endif 576 577 if (PythonIO_Init()) 578 goto fail; 579 580 if (PythonMod_Init()) 581 goto fail; 582 583 /* Remove the element from sys.path that was added because of our 584 * argv[0] value in PythonMod_Init(). Previously we used an empty 585 * string, but dependinding on the OS we then get an empty entry or 586 * the current directory in sys.path. */ 587 PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)"); 588 589 /* the first python thread is vim's, release the lock */ 590 Python_SaveThread(); 591 592 initialised = 1; 593 } 594 595 return 0; 596 597 fail: 598 /* We call PythonIO_Flush() here to print any Python errors. 599 * This is OK, as it is possible to call this function even 600 * if PythonIO_Init() has not completed successfully (it will 601 * not do anything in this case). 602 */ 603 PythonIO_Flush(); 604 return -1; 605 } 606 607 /* 608 * External interface 609 */ 610 static void 611 DoPythonCommand(exarg_T *eap, const char *cmd) 612 { 613 #ifndef PY_CAN_RECURSE 614 static int recursive = 0; 615 #endif 616 #if defined(MACOS) && !defined(MACOS_X_UNIX) 617 GrafPtr oldPort; 618 #endif 619 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) 620 char *saved_locale; 621 #endif 622 623 #ifndef PY_CAN_RECURSE 624 if (recursive) 625 { 626 EMSG(_("E659: Cannot invoke Python recursively")); 627 return; 628 } 629 ++recursive; 630 #endif 631 632 #if defined(MACOS) && !defined(MACOS_X_UNIX) 633 GetPort(&oldPort); 634 /* Check if the Python library is available */ 635 if ((Ptr)PyMac_Initialize == (Ptr)kUnresolvedCFragSymbolAddress) 636 goto theend; 637 #endif 638 if (Python_Init()) 639 goto theend; 640 641 RangeStart = eap->line1; 642 RangeEnd = eap->line2; 643 Python_Release_Vim(); /* leave vim */ 644 645 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) 646 /* Python only works properly when the LC_NUMERIC locale is "C". */ 647 saved_locale = setlocale(LC_NUMERIC, NULL); 648 if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0) 649 saved_locale = NULL; 650 else 651 { 652 /* Need to make a copy, value may change when setting new locale. */ 653 saved_locale = (char *)vim_strsave((char_u *)saved_locale); 654 (void)setlocale(LC_NUMERIC, "C"); 655 } 656 #endif 657 658 Python_RestoreThread(); /* enter python */ 659 660 PyRun_SimpleString((char *)(cmd)); 661 662 Python_SaveThread(); /* leave python */ 663 664 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE) 665 if (saved_locale != NULL) 666 { 667 (void)setlocale(LC_NUMERIC, saved_locale); 668 vim_free(saved_locale); 669 } 670 #endif 671 672 Python_Lock_Vim(); /* enter vim */ 673 PythonIO_Flush(); 674 #if defined(MACOS) && !defined(MACOS_X_UNIX) 675 SetPort(oldPort); 676 #endif 677 678 theend: 679 #ifndef PY_CAN_RECURSE 680 --recursive; 681 #endif 682 return; /* keeps lint happy */ 683 } 684 685 /* 686 * ":python" 687 */ 688 void 689 ex_python(exarg_T *eap) 690 { 691 char_u *script; 692 693 script = script_get(eap, eap->arg); 694 if (!eap->skip) 695 { 696 if (script == NULL) 697 DoPythonCommand(eap, (char *)eap->arg); 698 else 699 DoPythonCommand(eap, (char *)script); 700 } 701 vim_free(script); 702 } 703 704 #define BUFFER_SIZE 1024 705 706 /* 707 * ":pyfile" 708 */ 709 void 710 ex_pyfile(exarg_T *eap) 711 { 712 static char buffer[BUFFER_SIZE]; 713 const char *file = (char *)eap->arg; 714 char *p; 715 716 /* Have to do it like this. PyRun_SimpleFile requires you to pass a 717 * stdio file pointer, but Vim and the Python DLL are compiled with 718 * different options under Windows, meaning that stdio pointers aren't 719 * compatible between the two. Yuk. 720 * 721 * Put the string "execfile('file')" into buffer. But, we need to 722 * escape any backslashes or single quotes in the file name, so that 723 * Python won't mangle the file name. 724 */ 725 strcpy(buffer, "execfile('"); 726 p = buffer + 10; /* size of "execfile('" */ 727 728 while (*file && p < buffer + (BUFFER_SIZE - 3)) 729 { 730 if (*file == '\\' || *file == '\'') 731 *p++ = '\\'; 732 *p++ = *file++; 733 } 734 735 /* If we didn't finish the file name, we hit a buffer overflow */ 736 if (*file != '\0') 737 return; 738 739 /* Put in the terminating "')" and a null */ 740 *p++ = '\''; 741 *p++ = ')'; 742 *p++ = '\0'; 743 744 /* Execute the file */ 745 DoPythonCommand(eap, buffer); 746 } 747 748 /****************************************************** 749 * 2. Python output stream: writes output via [e]msg(). 750 */ 751 752 /* Implementation functions 753 */ 754 755 static PyObject * 756 OutputGetattr(PyObject *self, char *name) 757 { 758 if (strcmp(name, "softspace") == 0) 759 return PyInt_FromLong(((OutputObject *)(self))->softspace); 760 761 return Py_FindMethod(OutputMethods, self, name); 762 } 763 764 static int 765 OutputSetattr(PyObject *self, char *name, PyObject *val) 766 { 767 if (val == NULL) { 768 PyErr_SetString(PyExc_AttributeError, _("can't delete OutputObject attributes")); 769 return -1; 770 } 771 772 if (strcmp(name, "softspace") == 0) 773 { 774 if (!PyInt_Check(val)) { 775 PyErr_SetString(PyExc_TypeError, _("softspace must be an integer")); 776 return -1; 777 } 778 779 ((OutputObject *)(self))->softspace = PyInt_AsLong(val); 780 return 0; 781 } 782 783 PyErr_SetString(PyExc_AttributeError, _("invalid attribute")); 784 return -1; 785 } 786 787 /***************/ 788 789 static int 790 PythonIO_Init(void) 791 { 792 /* Fixups... */ 793 PyType_Ready(&OutputType); 794 795 return PythonIO_Init_io(); 796 } 797 798 /****************************************************** 799 * 3. Implementation of the Vim module for Python 800 */ 801 802 /* Window type - Implementation functions 803 * -------------------------------------- 804 */ 805 806 #define WindowType_Check(obj) ((obj)->ob_type == &WindowType) 807 808 static void WindowDestructor(PyObject *); 809 static PyObject *WindowGetattr(PyObject *, char *); 810 811 /* Buffer type - Implementation functions 812 * -------------------------------------- 813 */ 814 815 #define BufferType_Check(obj) ((obj)->ob_type == &BufferType) 816 817 static void BufferDestructor(PyObject *); 818 static PyObject *BufferGetattr(PyObject *, char *); 819 static PyObject *BufferRepr(PyObject *); 820 821 static PyInt BufferLength(PyObject *); 822 static PyObject *BufferItem(PyObject *, PyInt); 823 static PyObject *BufferSlice(PyObject *, PyInt, PyInt); 824 static PyInt BufferAssItem(PyObject *, PyInt, PyObject *); 825 static PyInt BufferAssSlice(PyObject *, PyInt, PyInt, PyObject *); 826 827 /* Line range type - Implementation functions 828 * -------------------------------------- 829 */ 830 831 #define RangeType_Check(obj) ((obj)->ob_type == &RangeType) 832 833 static PyInt RangeAssItem(PyObject *, PyInt, PyObject *); 834 static PyInt RangeAssSlice(PyObject *, PyInt, PyInt, PyObject *); 835 836 /* Current objects type - Implementation functions 837 * ----------------------------------------------- 838 */ 839 840 static PyObject *CurrentGetattr(PyObject *, char *); 841 static int CurrentSetattr(PyObject *, char *, PyObject *); 842 843 static PySequenceMethods BufferAsSeq = { 844 (PyInquiry) BufferLength, /* sq_length, len(x) */ 845 (binaryfunc) 0, /* BufferConcat, */ /* sq_concat, x+y */ 846 (PyIntArgFunc) 0, /* BufferRepeat, */ /* sq_repeat, x*n */ 847 (PyIntArgFunc) BufferItem, /* sq_item, x[i] */ 848 (PyIntIntArgFunc) BufferSlice, /* sq_slice, x[i:j] */ 849 (PyIntObjArgProc) BufferAssItem, /* sq_ass_item, x[i]=v */ 850 (PyIntIntObjArgProc) BufferAssSlice, /* sq_ass_slice, x[i:j]=v */ 851 }; 852 853 static PyTypeObject BufferType = { 854 PyObject_HEAD_INIT(0) 855 0, 856 "buffer", 857 sizeof(BufferObject), 858 0, 859 860 (destructor) BufferDestructor, /* tp_dealloc, refcount==0 */ 861 (printfunc) 0, /* tp_print, print x */ 862 (getattrfunc) BufferGetattr, /* tp_getattr, x.attr */ 863 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 864 (cmpfunc) 0, /* tp_compare, x>y */ 865 (reprfunc) BufferRepr, /* tp_repr, `x`, print x */ 866 867 0, /* as number */ 868 &BufferAsSeq, /* as sequence */ 869 0, /* as mapping */ 870 871 (hashfunc) 0, /* tp_hash, dict(x) */ 872 (ternaryfunc) 0, /* tp_call, x() */ 873 (reprfunc) 0, /* tp_str, str(x) */ 874 }; 875 876 /* Buffer object - Implementation 877 */ 878 879 static PyObject * 880 BufferNew(buf_T *buf) 881 { 882 /* We need to handle deletion of buffers underneath us. 883 * If we add a "b_python_ref" field to the buf_T structure, 884 * then we can get at it in buf_freeall() in vim. We then 885 * need to create only ONE Python object per buffer - if 886 * we try to create a second, just INCREF the existing one 887 * and return it. The (single) Python object referring to 888 * the buffer is stored in "b_python_ref". 889 * Question: what to do on a buf_freeall(). We'll probably 890 * have to either delete the Python object (DECREF it to 891 * zero - a bad idea, as it leaves dangling refs!) or 892 * set the buf_T * value to an invalid value (-1?), which 893 * means we need checks in all access functions... Bah. 894 */ 895 896 BufferObject *self; 897 898 if (buf->b_python_ref != NULL) 899 { 900 self = buf->b_python_ref; 901 Py_INCREF(self); 902 } 903 else 904 { 905 self = PyObject_NEW(BufferObject, &BufferType); 906 if (self == NULL) 907 return NULL; 908 self->buf = buf; 909 buf->b_python_ref = self; 910 } 911 912 return (PyObject *)(self); 913 } 914 915 static void 916 BufferDestructor(PyObject *self) 917 { 918 BufferObject *this = (BufferObject *)(self); 919 920 if (this->buf && this->buf != INVALID_BUFFER_VALUE) 921 this->buf->b_python_ref = NULL; 922 923 Py_DECREF(self); 924 } 925 926 static PyObject * 927 BufferGetattr(PyObject *self, char *name) 928 { 929 BufferObject *this = (BufferObject *)(self); 930 931 if (CheckBuffer(this)) 932 return NULL; 933 934 if (strcmp(name, "name") == 0) 935 return Py_BuildValue("s", this->buf->b_ffname); 936 else if (strcmp(name, "number") == 0) 937 return Py_BuildValue(Py_ssize_t_fmt, this->buf->b_fnum); 938 else if (strcmp(name,"__members__") == 0) 939 return Py_BuildValue("[ss]", "name", "number"); 940 else 941 return Py_FindMethod(BufferMethods, self, name); 942 } 943 944 static PyObject * 945 BufferRepr(PyObject *self) 946 { 947 static char repr[100]; 948 BufferObject *this = (BufferObject *)(self); 949 950 if (this->buf == INVALID_BUFFER_VALUE) 951 { 952 vim_snprintf(repr, 100, _("<buffer object (deleted) at %p>"), (self)); 953 return PyString_FromString(repr); 954 } 955 else 956 { 957 char *name = (char *)this->buf->b_fname; 958 PyInt len; 959 960 if (name == NULL) 961 name = ""; 962 len = strlen(name); 963 964 if (len > 35) 965 name = name + (35 - len); 966 967 vim_snprintf(repr, 100, "<buffer %s%s>", len > 35 ? "..." : "", name); 968 969 return PyString_FromString(repr); 970 } 971 } 972 973 /******************/ 974 975 static PyInt 976 BufferLength(PyObject *self) 977 { 978 /* HOW DO WE SIGNAL AN ERROR FROM THIS FUNCTION? */ 979 if (CheckBuffer((BufferObject *)(self))) 980 return -1; /* ??? */ 981 982 return (((BufferObject *)(self))->buf->b_ml.ml_line_count); 983 } 984 985 static PyObject * 986 BufferItem(PyObject *self, PyInt n) 987 { 988 return RBItem((BufferObject *)(self), n, 1, 989 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count); 990 } 991 992 static PyObject * 993 BufferSlice(PyObject *self, PyInt lo, PyInt hi) 994 { 995 return RBSlice((BufferObject *)(self), lo, hi, 1, 996 (int)((BufferObject *)(self))->buf->b_ml.ml_line_count); 997 } 998 999 static PyInt 1000 BufferAssItem(PyObject *self, PyInt n, PyObject *val) 1001 { 1002 return RBAsItem((BufferObject *)(self), n, val, 1, 1003 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count, 1004 NULL); 1005 } 1006 1007 static PyInt 1008 BufferAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val) 1009 { 1010 return RBAsSlice((BufferObject *)(self), lo, hi, val, 1, 1011 (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count, 1012 NULL); 1013 } 1014 1015 static PySequenceMethods RangeAsSeq = { 1016 (PyInquiry) RangeLength, /* sq_length, len(x) */ 1017 (binaryfunc) 0, /* RangeConcat, */ /* sq_concat, x+y */ 1018 (PyIntArgFunc) 0, /* RangeRepeat, */ /* sq_repeat, x*n */ 1019 (PyIntArgFunc) RangeItem, /* sq_item, x[i] */ 1020 (PyIntIntArgFunc) RangeSlice, /* sq_slice, x[i:j] */ 1021 (PyIntObjArgProc) RangeAssItem, /* sq_ass_item, x[i]=v */ 1022 (PyIntIntObjArgProc) RangeAssSlice, /* sq_ass_slice, x[i:j]=v */ 1023 }; 1024 1025 /* Line range object - Implementation 1026 */ 1027 1028 static void 1029 RangeDestructor(PyObject *self) 1030 { 1031 Py_DECREF(((RangeObject *)(self))->buf); 1032 Py_DECREF(self); 1033 } 1034 1035 static PyObject * 1036 RangeGetattr(PyObject *self, char *name) 1037 { 1038 if (strcmp(name, "start") == 0) 1039 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->start - 1); 1040 else if (strcmp(name, "end") == 0) 1041 return Py_BuildValue(Py_ssize_t_fmt, ((RangeObject *)(self))->end - 1); 1042 else 1043 return Py_FindMethod(RangeMethods, self, name); 1044 } 1045 1046 /****************/ 1047 1048 static PyInt 1049 RangeAssItem(PyObject *self, PyInt n, PyObject *val) 1050 { 1051 return RBAsItem(((RangeObject *)(self))->buf, n, val, 1052 ((RangeObject *)(self))->start, 1053 ((RangeObject *)(self))->end, 1054 &((RangeObject *)(self))->end); 1055 } 1056 1057 static PyInt 1058 RangeAssSlice(PyObject *self, PyInt lo, PyInt hi, PyObject *val) 1059 { 1060 return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val, 1061 ((RangeObject *)(self))->start, 1062 ((RangeObject *)(self))->end, 1063 &((RangeObject *)(self))->end); 1064 } 1065 1066 /* Buffer list object - Definitions 1067 */ 1068 1069 typedef struct 1070 { 1071 PyObject_HEAD 1072 } BufListObject; 1073 1074 static PySequenceMethods BufListAsSeq = { 1075 (PyInquiry) BufListLength, /* sq_length, len(x) */ 1076 (binaryfunc) 0, /* sq_concat, x+y */ 1077 (PyIntArgFunc) 0, /* sq_repeat, x*n */ 1078 (PyIntArgFunc) BufListItem, /* sq_item, x[i] */ 1079 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */ 1080 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */ 1081 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */ 1082 }; 1083 1084 static PyTypeObject BufListType = { 1085 PyObject_HEAD_INIT(0) 1086 0, 1087 "buffer list", 1088 sizeof(BufListObject), 1089 0, 1090 1091 (destructor) 0, /* tp_dealloc, refcount==0 */ 1092 (printfunc) 0, /* tp_print, print x */ 1093 (getattrfunc) 0, /* tp_getattr, x.attr */ 1094 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 1095 (cmpfunc) 0, /* tp_compare, x>y */ 1096 (reprfunc) 0, /* tp_repr, `x`, print x */ 1097 1098 0, /* as number */ 1099 &BufListAsSeq, /* as sequence */ 1100 0, /* as mapping */ 1101 1102 (hashfunc) 0, /* tp_hash, dict(x) */ 1103 (ternaryfunc) 0, /* tp_call, x() */ 1104 (reprfunc) 0, /* tp_str, str(x) */ 1105 }; 1106 1107 /* Window object - Definitions 1108 */ 1109 1110 static struct PyMethodDef WindowMethods[] = { 1111 /* name, function, calling, documentation */ 1112 { NULL, NULL, 0, NULL } 1113 }; 1114 1115 static PyTypeObject WindowType = { 1116 PyObject_HEAD_INIT(0) 1117 0, 1118 "window", 1119 sizeof(WindowObject), 1120 0, 1121 1122 (destructor) WindowDestructor, /* tp_dealloc, refcount==0 */ 1123 (printfunc) 0, /* tp_print, print x */ 1124 (getattrfunc) WindowGetattr, /* tp_getattr, x.attr */ 1125 (setattrfunc) WindowSetattr, /* tp_setattr, x.attr=v */ 1126 (cmpfunc) 0, /* tp_compare, x>y */ 1127 (reprfunc) WindowRepr, /* tp_repr, `x`, print x */ 1128 1129 0, /* as number */ 1130 0, /* as sequence */ 1131 0, /* as mapping */ 1132 1133 (hashfunc) 0, /* tp_hash, dict(x) */ 1134 (ternaryfunc) 0, /* tp_call, x() */ 1135 (reprfunc) 0, /* tp_str, str(x) */ 1136 }; 1137 1138 /* Window object - Implementation 1139 */ 1140 1141 static PyObject * 1142 WindowNew(win_T *win) 1143 { 1144 /* We need to handle deletion of windows underneath us. 1145 * If we add a "w_python_ref" field to the win_T structure, 1146 * then we can get at it in win_free() in vim. We then 1147 * need to create only ONE Python object per window - if 1148 * we try to create a second, just INCREF the existing one 1149 * and return it. The (single) Python object referring to 1150 * the window is stored in "w_python_ref". 1151 * On a win_free() we set the Python object's win_T* field 1152 * to an invalid value. We trap all uses of a window 1153 * object, and reject them if the win_T* field is invalid. 1154 */ 1155 1156 WindowObject *self; 1157 1158 if (win->w_python_ref) 1159 { 1160 self = win->w_python_ref; 1161 Py_INCREF(self); 1162 } 1163 else 1164 { 1165 self = PyObject_NEW(WindowObject, &WindowType); 1166 if (self == NULL) 1167 return NULL; 1168 self->win = win; 1169 win->w_python_ref = self; 1170 } 1171 1172 return (PyObject *)(self); 1173 } 1174 1175 static void 1176 WindowDestructor(PyObject *self) 1177 { 1178 WindowObject *this = (WindowObject *)(self); 1179 1180 if (this->win && this->win != INVALID_WINDOW_VALUE) 1181 this->win->w_python_ref = NULL; 1182 1183 Py_DECREF(self); 1184 } 1185 1186 static PyObject * 1187 WindowGetattr(PyObject *self, char *name) 1188 { 1189 WindowObject *this = (WindowObject *)(self); 1190 1191 if (CheckWindow(this)) 1192 return NULL; 1193 1194 if (strcmp(name, "buffer") == 0) 1195 return (PyObject *)BufferNew(this->win->w_buffer); 1196 else if (strcmp(name, "cursor") == 0) 1197 { 1198 pos_T *pos = &this->win->w_cursor; 1199 1200 return Py_BuildValue("(ll)", (long)(pos->lnum), (long)(pos->col)); 1201 } 1202 else if (strcmp(name, "height") == 0) 1203 return Py_BuildValue("l", (long)(this->win->w_height)); 1204 #ifdef FEAT_VERTSPLIT 1205 else if (strcmp(name, "width") == 0) 1206 return Py_BuildValue("l", (long)(W_WIDTH(this->win))); 1207 #endif 1208 else if (strcmp(name,"__members__") == 0) 1209 return Py_BuildValue("[sss]", "buffer", "cursor", "height"); 1210 else 1211 return Py_FindMethod(WindowMethods, self, name); 1212 } 1213 1214 /* Window list object - Definitions 1215 */ 1216 1217 typedef struct 1218 { 1219 PyObject_HEAD 1220 } 1221 WinListObject; 1222 1223 static PySequenceMethods WinListAsSeq = { 1224 (PyInquiry) WinListLength, /* sq_length, len(x) */ 1225 (binaryfunc) 0, /* sq_concat, x+y */ 1226 (PyIntArgFunc) 0, /* sq_repeat, x*n */ 1227 (PyIntArgFunc) WinListItem, /* sq_item, x[i] */ 1228 (PyIntIntArgFunc) 0, /* sq_slice, x[i:j] */ 1229 (PyIntObjArgProc) 0, /* sq_ass_item, x[i]=v */ 1230 (PyIntIntObjArgProc) 0, /* sq_ass_slice, x[i:j]=v */ 1231 }; 1232 1233 static PyTypeObject WinListType = { 1234 PyObject_HEAD_INIT(0) 1235 0, 1236 "window list", 1237 sizeof(WinListObject), 1238 0, 1239 1240 (destructor) 0, /* tp_dealloc, refcount==0 */ 1241 (printfunc) 0, /* tp_print, print x */ 1242 (getattrfunc) 0, /* tp_getattr, x.attr */ 1243 (setattrfunc) 0, /* tp_setattr, x.attr=v */ 1244 (cmpfunc) 0, /* tp_compare, x>y */ 1245 (reprfunc) 0, /* tp_repr, `x`, print x */ 1246 1247 0, /* as number */ 1248 &WinListAsSeq, /* as sequence */ 1249 0, /* as mapping */ 1250 1251 (hashfunc) 0, /* tp_hash, dict(x) */ 1252 (ternaryfunc) 0, /* tp_call, x() */ 1253 (reprfunc) 0, /* tp_str, str(x) */ 1254 }; 1255 1256 /* Current items object - Definitions 1257 */ 1258 1259 typedef struct 1260 { 1261 PyObject_HEAD 1262 } CurrentObject; 1263 1264 static PyTypeObject CurrentType = { 1265 PyObject_HEAD_INIT(0) 1266 0, 1267 "current data", 1268 sizeof(CurrentObject), 1269 0, 1270 1271 (destructor) 0, /* tp_dealloc, refcount==0 */ 1272 (printfunc) 0, /* tp_print, print x */ 1273 (getattrfunc) CurrentGetattr, /* tp_getattr, x.attr */ 1274 (setattrfunc) CurrentSetattr, /* tp_setattr, x.attr=v */ 1275 (cmpfunc) 0, /* tp_compare, x>y */ 1276 (reprfunc) 0, /* tp_repr, `x`, print x */ 1277 1278 0, /* as number */ 1279 0, /* as sequence */ 1280 0, /* as mapping */ 1281 1282 (hashfunc) 0, /* tp_hash, dict(x) */ 1283 (ternaryfunc) 0, /* tp_call, x() */ 1284 (reprfunc) 0, /* tp_str, str(x) */ 1285 }; 1286 1287 /* Current items object - Implementation 1288 */ 1289 static PyObject * 1290 CurrentGetattr(PyObject *self UNUSED, char *name) 1291 { 1292 if (strcmp(name, "buffer") == 0) 1293 return (PyObject *)BufferNew(curbuf); 1294 else if (strcmp(name, "window") == 0) 1295 return (PyObject *)WindowNew(curwin); 1296 else if (strcmp(name, "line") == 0) 1297 return GetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum); 1298 else if (strcmp(name, "range") == 0) 1299 return RangeNew(curbuf, RangeStart, RangeEnd); 1300 else if (strcmp(name,"__members__") == 0) 1301 return Py_BuildValue("[ssss]", "buffer", "window", "line", "range"); 1302 else 1303 { 1304 PyErr_SetString(PyExc_AttributeError, name); 1305 return NULL; 1306 } 1307 } 1308 1309 static int 1310 CurrentSetattr(PyObject *self UNUSED, char *name, PyObject *value) 1311 { 1312 if (strcmp(name, "line") == 0) 1313 { 1314 if (SetBufferLine(curbuf, (PyInt)curwin->w_cursor.lnum, value, NULL) == FAIL) 1315 return -1; 1316 1317 return 0; 1318 } 1319 else 1320 { 1321 PyErr_SetString(PyExc_AttributeError, name); 1322 return -1; 1323 } 1324 } 1325 1326 /* External interface 1327 */ 1328 1329 void 1330 python_buffer_free(buf_T *buf) 1331 { 1332 if (buf->b_python_ref != NULL) 1333 { 1334 BufferObject *bp = buf->b_python_ref; 1335 bp->buf = INVALID_BUFFER_VALUE; 1336 buf->b_python_ref = NULL; 1337 } 1338 } 1339 1340 #if defined(FEAT_WINDOWS) || defined(PROTO) 1341 void 1342 python_window_free(win_T *win) 1343 { 1344 if (win->w_python_ref != NULL) 1345 { 1346 WindowObject *wp = win->w_python_ref; 1347 wp->win = INVALID_WINDOW_VALUE; 1348 win->w_python_ref = NULL; 1349 } 1350 } 1351 #endif 1352 1353 static BufListObject TheBufferList = 1354 { 1355 PyObject_HEAD_INIT(&BufListType) 1356 }; 1357 1358 static WinListObject TheWindowList = 1359 { 1360 PyObject_HEAD_INIT(&WinListType) 1361 }; 1362 1363 static CurrentObject TheCurrent = 1364 { 1365 PyObject_HEAD_INIT(&CurrentType) 1366 }; 1367 1368 static int 1369 PythonMod_Init(void) 1370 { 1371 PyObject *mod; 1372 PyObject *dict; 1373 /* The special value is removed from sys.path in Python_Init(). */ 1374 static char *(argv[2]) = {"/must>not&exist/foo", NULL}; 1375 1376 /* Fixups... */ 1377 PyType_Ready(&BufferType); 1378 PyType_Ready(&RangeType); 1379 PyType_Ready(&WindowType); 1380 PyType_Ready(&BufListType); 1381 PyType_Ready(&WinListType); 1382 PyType_Ready(&CurrentType); 1383 1384 /* Set sys.argv[] to avoid a crash in warn(). */ 1385 PySys_SetArgv(1, argv); 1386 1387 mod = Py_InitModule4("vim", VimMethods, (char *)NULL, (PyObject *)NULL, PYTHON_API_VERSION); 1388 dict = PyModule_GetDict(mod); 1389 1390 VimError = Py_BuildValue("s", "vim.error"); 1391 1392 PyDict_SetItemString(dict, "error", VimError); 1393 PyDict_SetItemString(dict, "buffers", (PyObject *)(void *)&TheBufferList); 1394 PyDict_SetItemString(dict, "current", (PyObject *)(void *)&TheCurrent); 1395 PyDict_SetItemString(dict, "windows", (PyObject *)(void *)&TheWindowList); 1396 1397 if (PyErr_Occurred()) 1398 return -1; 1399 1400 return 0; 1401 } 1402 1403 /************************************************************************* 1404 * 4. Utility functions for handling the interface between Vim and Python. 1405 */ 1406 1407 /* Convert a Vim line into a Python string. 1408 * All internal newlines are replaced by null characters. 1409 * 1410 * On errors, the Python exception data is set, and NULL is returned. 1411 */ 1412 static PyObject * 1413 LineToString(const char *str) 1414 { 1415 PyObject *result; 1416 PyInt len = strlen(str); 1417 char *p; 1418 1419 /* Allocate an Python string object, with uninitialised contents. We 1420 * must do it this way, so that we can modify the string in place 1421 * later. See the Python source, Objects/stringobject.c for details. 1422 */ 1423 result = PyString_FromStringAndSize(NULL, len); 1424 if (result == NULL) 1425 return NULL; 1426 1427 p = PyString_AsString(result); 1428 1429 while (*str) 1430 { 1431 if (*str == '\n') 1432 *p = '\0'; 1433 else 1434 *p = *str; 1435 1436 ++p; 1437 ++str; 1438 } 1439 1440 return result; 1441 } 1442 1443 1444 /* Don't generate a prototype for the next function, it generates an error on 1445 * newer Python versions. */ 1446 #if PYTHON_API_VERSION < 1007 /* Python 1.4 */ && !defined(PROTO) 1447 1448 char * 1449 Py_GetProgramName(void) 1450 { 1451 return "vim"; 1452 } 1453 #endif /* Python 1.4 */ 1454 1455 static void 1456 init_structs(void) 1457 { 1458 vim_memset(&OutputType, 0, sizeof(OutputType)); 1459 OutputType.tp_name = "message"; 1460 OutputType.tp_basicsize = sizeof(OutputObject); 1461 OutputType.tp_getattr = OutputGetattr; 1462 OutputType.tp_setattr = OutputSetattr; 1463 1464 vim_memset(&RangeType, 0, sizeof(RangeType)); 1465 RangeType.tp_name = "range"; 1466 RangeType.tp_basicsize = sizeof(RangeObject); 1467 RangeType.tp_dealloc = RangeDestructor; 1468 RangeType.tp_getattr = RangeGetattr; 1469 RangeType.tp_repr = RangeRepr; 1470 RangeType.tp_as_sequence = &RangeAsSeq; 1471 } 1472