xref: /vim-8.2.3635/src/if_ruby.c (revision bc073092)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Ruby interface by Shugo Maeda
6  *   with improvements by SegPhault (Ryan Paul)
7  *   with improvements by Jon Maken
8  *
9  * Do ":help uganda"  in Vim to read copying and usage conditions.
10  * Do ":help credits" in Vim to see a list of people who contributed.
11  * See README.txt for an overview of the Vim source code.
12  */
13 
14 #ifdef HAVE_CONFIG_H
15 # include "auto/config.h"
16 #endif
17 
18 #include <stdio.h>
19 #include <string.h>
20 
21 #ifdef _WIN32
22 # if !defined(DYNAMIC_RUBY_VER) || (DYNAMIC_RUBY_VER < 18)
23 #   define NT
24 # endif
25 # ifndef DYNAMIC_RUBY
26 #  define IMPORT /* For static dll usage __declspec(dllimport) */
27 #  define RUBYEXTERN __declspec(dllimport)
28 # endif
29 #endif
30 #ifndef RUBYEXTERN
31 # define RUBYEXTERN extern
32 #endif
33 
34 #ifdef DYNAMIC_RUBY
35 /*
36  * This is tricky.  In ruby.h there is (inline) function rb_class_of()
37  * definition.  This function use these variables.  But we want function to
38  * use dll_* variables.
39  */
40 # define rb_cFalseClass		(*dll_rb_cFalseClass)
41 # define rb_cFixnum		(*dll_rb_cFixnum)
42 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
43 #  define rb_cFloat		(*dll_rb_cFloat)
44 # endif
45 # define rb_cNilClass		(*dll_rb_cNilClass)
46 # define rb_cSymbol		(*dll_rb_cSymbol)
47 # define rb_cTrueClass		(*dll_rb_cTrueClass)
48 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
49 /*
50  * On ver 1.8, all Ruby functions are exported with "__declspec(dllimport)"
51  * in ruby.h.  But it causes trouble for these variables, because it is
52  * defined in this file.  When defined this RUBY_EXPORT it modified to
53  * "extern" and be able to avoid this problem.
54  */
55 #  define RUBY_EXPORT
56 # endif
57 
58 #if !(defined(WIN32) || defined(_WIN64))
59 # include <dlfcn.h>
60 # define HINSTANCE void*
61 # define RUBY_PROC void*
62 # define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
63 # define symbol_from_dll dlsym
64 # define close_dll dlclose
65 #else
66 # define RUBY_PROC FARPROC
67 # define load_dll vimLoadLib
68 # define symbol_from_dll GetProcAddress
69 # define close_dll FreeLibrary
70 #endif
71 
72 #endif  /* ifdef DYNAMIC_RUBY */
73 
74 /* suggested by Ariya Mizutani */
75 #if (_MSC_VER == 1200)
76 # undef _WIN32_WINNT
77 #endif
78 
79 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 19) \
80     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19)
81 # define RUBY19_OR_LATER 1
82 #endif
83 
84 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 20) \
85     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20)
86 # define RUBY20_OR_LATER 1
87 #endif
88 
89 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19
90 /* Ruby 1.9 defines a number of static functions which use rb_num2long and
91  * rb_int2big */
92 # define rb_num2long rb_num2long_stub
93 # define rb_int2big rb_int2big_stub
94 #endif
95 
96 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 \
97 	&& VIM_SIZEOF_INT < VIM_SIZEOF_LONG
98 /* Ruby 1.9 defines a number of static functions which use rb_fix2int and
99  * rb_num2int if VIM_SIZEOF_INT < VIM_SIZEOF_LONG (64bit) */
100 # define rb_fix2int rb_fix2int_stub
101 # define rb_num2int rb_num2int_stub
102 #endif
103 
104 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
105 /* Ruby 2.1 adds new GC called RGenGC and RARRAY_PTR uses
106  * rb_gc_writebarrier_unprotect_promoted if USE_RGENGC  */
107 # define rb_gc_writebarrier_unprotect_promoted rb_gc_writebarrier_unprotect_promoted_stub
108 #endif
109 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
110 # define rb_gc_writebarrier_unprotect rb_gc_writebarrier_unprotect_stub
111 #endif
112 
113 #include <ruby.h>
114 #ifdef RUBY19_OR_LATER
115 # include <ruby/encoding.h>
116 #endif
117 
118 #undef off_t	/* ruby defines off_t as _int64, Mingw uses long */
119 #undef EXTERN
120 #undef _
121 
122 /* T_DATA defined both by Ruby and Mac header files, hack around it... */
123 #if defined(MACOS_X_UNIX) || defined(macintosh)
124 # define __OPENTRANSPORT__
125 # define __OPENTRANSPORTPROTOCOL__
126 # define __OPENTRANSPORTPROVIDERS__
127 #endif
128 
129 /*
130  * The TypedData_XXX macro family can be used since Ruby 1.9.2 but
131  * rb_data_type_t changed in 1.9.3, therefore require at least 2.0.
132  * The old Data_XXX macro family was deprecated on Ruby 2.2.
133  * Use TypedData_XXX if available.
134  */
135 #if defined(TypedData_Wrap_Struct) && defined(RUBY20_OR_LATER)
136 # define USE_TYPEDDATA	1
137 #endif
138 
139 /*
140  * Backward compatibility for Ruby 1.8 and earlier.
141  * Ruby 1.9 does not provide STR2CSTR, instead StringValuePtr is provided.
142  * Ruby 1.9 does not provide RXXX(s)->len and RXXX(s)->ptr, instead
143  * RXXX_LEN(s) and RXXX_PTR(s) are provided.
144  */
145 #ifndef StringValuePtr
146 # define StringValuePtr(s) STR2CSTR(s)
147 #endif
148 #ifndef RARRAY_LEN
149 # define RARRAY_LEN(s) RARRAY(s)->len
150 #endif
151 #ifndef RARRAY_PTR
152 # define RARRAY_PTR(s) RARRAY(s)->ptr
153 #endif
154 #ifndef RSTRING_LEN
155 # define RSTRING_LEN(s) RSTRING(s)->len
156 #endif
157 #ifndef RSTRING_PTR
158 # define RSTRING_PTR(s) RSTRING(s)->ptr
159 #endif
160 
161 #include "vim.h"
162 #include "version.h"
163 
164 #if defined(PROTO) && !defined(FEAT_RUBY)
165 /* Define these to be able to generate the function prototypes. */
166 # define VALUE int
167 # define RUBY_DATA_FUNC int
168 #endif
169 
170 static int ruby_initialized = 0;
171 static void *ruby_stack_start;
172 static VALUE objtbl;
173 
174 static VALUE mVIM;
175 static VALUE cBuffer;
176 static VALUE cVimWindow;
177 static VALUE eDeletedBufferError;
178 static VALUE eDeletedWindowError;
179 
180 static int ensure_ruby_initialized(void);
181 static void error_print(int);
182 static void ruby_io_init(void);
183 static void ruby_vim_init(void);
184 
185 #if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
186 # if defined(__ia64) && !defined(ruby_init_stack)
187 #  define ruby_init_stack(addr) ruby_init_stack((addr), rb_ia64_bsp())
188 # endif
189 #endif
190 
191 #if defined(DYNAMIC_RUBY) || defined(PROTO)
192 # if defined(PROTO) && !defined(HINSTANCE)
193 #  define HINSTANCE int		/* for generating prototypes */
194 # endif
195 
196 /*
197  * Wrapper defines
198  */
199 # define rb_assoc_new			dll_rb_assoc_new
200 # define rb_cObject			(*dll_rb_cObject)
201 # define rb_check_type			dll_rb_check_type
202 # ifdef USE_TYPEDDATA
203 #  define rb_check_typeddata		dll_rb_check_typeddata
204 # endif
205 # define rb_class_path			dll_rb_class_path
206 # ifdef USE_TYPEDDATA
207 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
208 #   define rb_data_typed_object_wrap	dll_rb_data_typed_object_wrap
209 #  else
210 #   define rb_data_typed_object_alloc	dll_rb_data_typed_object_alloc
211 #  endif
212 # else
213 #  define rb_data_object_alloc		dll_rb_data_object_alloc
214 # endif
215 # define rb_define_class_under		dll_rb_define_class_under
216 # define rb_define_const			dll_rb_define_const
217 # define rb_define_global_function	dll_rb_define_global_function
218 # define rb_define_method		dll_rb_define_method
219 # define rb_define_module		dll_rb_define_module
220 # define rb_define_module_function	dll_rb_define_module_function
221 # define rb_define_singleton_method	dll_rb_define_singleton_method
222 # define rb_define_virtual_variable	dll_rb_define_virtual_variable
223 # define rb_stdout			(*dll_rb_stdout)
224 # define rb_eArgError			(*dll_rb_eArgError)
225 # define rb_eIndexError			(*dll_rb_eIndexError)
226 # define rb_eRuntimeError		(*dll_rb_eRuntimeError)
227 # define rb_eStandardError		(*dll_rb_eStandardError)
228 # define rb_eval_string_protect		dll_rb_eval_string_protect
229 # define rb_global_variable		dll_rb_global_variable
230 # define rb_hash_aset			dll_rb_hash_aset
231 # define rb_hash_new			dll_rb_hash_new
232 # define rb_inspect			dll_rb_inspect
233 # define rb_int2inum			dll_rb_int2inum
234 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
235 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER <= 18
236 #   define rb_fix2int			dll_rb_fix2int
237 #   define rb_num2int			dll_rb_num2int
238 #  endif
239 #  define rb_num2uint			dll_rb_num2uint
240 # endif
241 # define rb_lastline_get			dll_rb_lastline_get
242 # define rb_lastline_set			dll_rb_lastline_set
243 # define rb_load_protect			dll_rb_load_protect
244 # ifndef RUBY19_OR_LATER
245 #  define rb_num2long			dll_rb_num2long
246 # endif
247 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER <= 19
248 #  define rb_num2ulong			dll_rb_num2ulong
249 # endif
250 # define rb_obj_alloc			dll_rb_obj_alloc
251 # define rb_obj_as_string		dll_rb_obj_as_string
252 # define rb_obj_id			dll_rb_obj_id
253 # define rb_raise			dll_rb_raise
254 # define rb_str_cat			dll_rb_str_cat
255 # define rb_str_concat			dll_rb_str_concat
256 # define rb_str_new			dll_rb_str_new
257 # ifdef rb_str_new2
258 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */
259 #  define need_rb_str_new_cstr 1
260 /* Ruby's headers #define rb_str_new_cstr to make use of GCC's
261  * __builtin_constant_p extension. */
262 #  undef rb_str_new_cstr
263 #  define rb_str_new_cstr		dll_rb_str_new_cstr
264 # else
265 #  define rb_str_new2			dll_rb_str_new2
266 # endif
267 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
268 #  define rb_string_value		dll_rb_string_value
269 #  define rb_string_value_ptr		dll_rb_string_value_ptr
270 #  define rb_float_new			dll_rb_float_new
271 #  define rb_ary_new			dll_rb_ary_new
272 #  define rb_ary_push			dll_rb_ary_push
273 #  if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
274 #   ifdef __ia64
275 #    define rb_ia64_bsp			dll_rb_ia64_bsp
276 #    undef ruby_init_stack
277 #    define ruby_init_stack(addr)	dll_ruby_init_stack((addr), rb_ia64_bsp())
278 #   else
279 #    define ruby_init_stack		dll_ruby_init_stack
280 #   endif
281 #  endif
282 # else
283 #  define rb_str2cstr			dll_rb_str2cstr
284 # endif
285 # ifdef RUBY19_OR_LATER
286 #  define rb_errinfo			dll_rb_errinfo
287 # else
288 #  define ruby_errinfo			(*dll_ruby_errinfo)
289 # endif
290 # define ruby_init			dll_ruby_init
291 # define ruby_init_loadpath		dll_ruby_init_loadpath
292 # ifdef WIN3264
293 #  define NtInitialize			dll_NtInitialize
294 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
295 #   define rb_w32_snprintf		dll_rb_w32_snprintf
296 #  endif
297 # endif
298 
299 # ifdef RUBY19_OR_LATER
300 #  define ruby_script			dll_ruby_script
301 #  define rb_enc_find_index		dll_rb_enc_find_index
302 #  define rb_enc_find			dll_rb_enc_find
303 #  define rb_enc_str_new			dll_rb_enc_str_new
304 #  define rb_sprintf			dll_rb_sprintf
305 #  define rb_require			dll_rb_require
306 #  define ruby_options			dll_ruby_options
307 # endif
308 
309 /*
310  * Pointers for dynamic link
311  */
312 static VALUE (*dll_rb_assoc_new) (VALUE, VALUE);
313 VALUE *dll_rb_cFalseClass;
314 VALUE *dll_rb_cFixnum;
315 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
316 VALUE *dll_rb_cFloat;
317 # endif
318 VALUE *dll_rb_cNilClass;
319 static VALUE *dll_rb_cObject;
320 VALUE *dll_rb_cSymbol;
321 VALUE *dll_rb_cTrueClass;
322 static void (*dll_rb_check_type) (VALUE,int);
323 # ifdef USE_TYPEDDATA
324 static void *(*dll_rb_check_typeddata) (VALUE,const rb_data_type_t *);
325 # endif
326 static VALUE (*dll_rb_class_path) (VALUE);
327 # ifdef USE_TYPEDDATA
328 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
329 static VALUE (*dll_rb_data_typed_object_wrap) (VALUE, void*, const rb_data_type_t *);
330 #  else
331 static VALUE (*dll_rb_data_typed_object_alloc) (VALUE, void*, const rb_data_type_t *);
332 #  endif
333 # else
334 static VALUE (*dll_rb_data_object_alloc) (VALUE, void*, RUBY_DATA_FUNC, RUBY_DATA_FUNC);
335 # endif
336 static VALUE (*dll_rb_define_class_under) (VALUE, const char*, VALUE);
337 static void (*dll_rb_define_const) (VALUE,const char*,VALUE);
338 static void (*dll_rb_define_global_function) (const char*,VALUE(*)(),int);
339 static void (*dll_rb_define_method) (VALUE,const char*,VALUE(*)(),int);
340 static VALUE (*dll_rb_define_module) (const char*);
341 static void (*dll_rb_define_module_function) (VALUE,const char*,VALUE(*)(),int);
342 static void (*dll_rb_define_singleton_method) (VALUE,const char*,VALUE(*)(),int);
343 static void (*dll_rb_define_virtual_variable) (const char*,VALUE(*)(),void(*)());
344 static VALUE *dll_rb_stdout;
345 static VALUE *dll_rb_eArgError;
346 static VALUE *dll_rb_eIndexError;
347 static VALUE *dll_rb_eRuntimeError;
348 static VALUE *dll_rb_eStandardError;
349 static VALUE (*dll_rb_eval_string_protect) (const char*, int*);
350 static void (*dll_rb_global_variable) (VALUE*);
351 static VALUE (*dll_rb_hash_aset) (VALUE, VALUE, VALUE);
352 static VALUE (*dll_rb_hash_new) (void);
353 static VALUE (*dll_rb_inspect) (VALUE);
354 static VALUE (*dll_rb_int2inum) (long);
355 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
356 static long (*dll_rb_fix2int) (VALUE);
357 static long (*dll_rb_num2int) (VALUE);
358 static unsigned long (*dll_rb_num2uint) (VALUE);
359 # endif
360 static VALUE (*dll_rb_lastline_get) (void);
361 static void (*dll_rb_lastline_set) (VALUE);
362 static void (*dll_rb_load_protect) (VALUE, int, int*);
363 static long (*dll_rb_num2long) (VALUE);
364 static unsigned long (*dll_rb_num2ulong) (VALUE);
365 static VALUE (*dll_rb_obj_alloc) (VALUE);
366 static VALUE (*dll_rb_obj_as_string) (VALUE);
367 static VALUE (*dll_rb_obj_id) (VALUE);
368 static void (*dll_rb_raise) (VALUE, const char*, ...);
369 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
370 static VALUE (*dll_rb_string_value) (volatile VALUE*);
371 # else
372 static char *(*dll_rb_str2cstr) (VALUE,int*);
373 # endif
374 static VALUE (*dll_rb_str_cat) (VALUE, const char*, long);
375 static VALUE (*dll_rb_str_concat) (VALUE, VALUE);
376 static VALUE (*dll_rb_str_new) (const char*, long);
377 # ifdef need_rb_str_new_cstr
378 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */
379 static VALUE (*dll_rb_str_new_cstr) (const char*);
380 # else
381 static VALUE (*dll_rb_str_new2) (const char*);
382 # endif
383 # ifdef RUBY19_OR_LATER
384 static VALUE (*dll_rb_errinfo) (void);
385 # else
386 static VALUE *dll_ruby_errinfo;
387 # endif
388 static void (*dll_ruby_init) (void);
389 static void (*dll_ruby_init_loadpath) (void);
390 # ifdef WIN3264
391 static void (*dll_NtInitialize) (int*, char***);
392 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
393 static int (*dll_rb_w32_snprintf)(char*, size_t, const char*, ...);
394 #  endif
395 # endif
396 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
397 static char * (*dll_rb_string_value_ptr) (volatile VALUE*);
398 static VALUE (*dll_rb_float_new) (double);
399 static VALUE (*dll_rb_ary_new) (void);
400 static VALUE (*dll_rb_ary_push) (VALUE, VALUE);
401 #  if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
402 #   ifdef __ia64
403 static void * (*dll_rb_ia64_bsp) (void);
404 static void (*dll_ruby_init_stack)(VALUE*, void*);
405 #   else
406 static void (*dll_ruby_init_stack)(VALUE*);
407 #   endif
408 #  endif
409 # endif
410 # ifdef RUBY19_OR_LATER
411 static VALUE (*dll_rb_int2big)(SIGNED_VALUE);
412 # endif
413 
414 # ifdef RUBY19_OR_LATER
415 static void (*dll_ruby_script) (const char*);
416 static int (*dll_rb_enc_find_index) (const char*);
417 static rb_encoding* (*dll_rb_enc_find) (const char*);
418 static VALUE (*dll_rb_enc_str_new) (const char*, long, rb_encoding*);
419 static VALUE (*dll_rb_sprintf) (const char*, ...);
420 static VALUE (*dll_rb_require) (const char*);
421 static void* (*ruby_options)(int, char**);
422 # endif
423 
424 # if defined(USE_RGENGC) && USE_RGENGC
425 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
426 static void (*dll_rb_gc_writebarrier_unprotect_promoted)(VALUE);
427 #  else
428 static void (*dll_rb_gc_writebarrier_unprotect)(VALUE obj);
429 #  endif
430 # endif
431 
432 # if defined(RUBY19_OR_LATER) && !defined(PROTO)
433 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
434 long rb_num2long_stub(VALUE x)
435 #  else
436 SIGNED_VALUE rb_num2long_stub(VALUE x)
437 #  endif
438 {
439     return dll_rb_num2long(x);
440 }
441 VALUE rb_int2big_stub(SIGNED_VALUE x)
442 {
443     return dll_rb_int2big(x);
444 }
445 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 \
446 	&& VIM_SIZEOF_INT < VIM_SIZEOF_LONG
447 long rb_fix2int_stub(VALUE x)
448 {
449     return dll_rb_fix2int(x);
450 }
451 long rb_num2int_stub(VALUE x)
452 {
453     return dll_rb_num2int(x);
454 }
455 #  endif
456 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
457 VALUE
458 rb_float_new_in_heap(double d)
459 {
460     return dll_rb_float_new(d);
461 }
462 #   if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
463 unsigned long rb_num2ulong(VALUE x)
464 #   else
465 VALUE rb_num2ulong(VALUE x)
466 #   endif
467 {
468     return (long)RSHIFT((SIGNED_VALUE)(x),1);
469 }
470 #  endif
471 # endif
472 
473    /* Do not generate a prototype here, VALUE isn't always defined. */
474 # if defined(USE_RGENGC) && USE_RGENGC && !defined(PROTO)
475 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
476 void rb_gc_writebarrier_unprotect_promoted_stub(VALUE obj)
477 {
478     dll_rb_gc_writebarrier_unprotect_promoted(obj);
479 }
480 #  else
481 void rb_gc_writebarrier_unprotect_stub(VALUE obj)
482 {
483     dll_rb_gc_writebarrier_unprotect(obj);
484 }
485 #  endif
486 # endif
487 
488 static HINSTANCE hinstRuby = NULL; /* Instance of ruby.dll */
489 
490 /*
491  * Table of name to function pointer of ruby.
492  */
493 static struct
494 {
495     char *name;
496     RUBY_PROC *ptr;
497 } ruby_funcname_table[] =
498 {
499     {"rb_assoc_new", (RUBY_PROC*)&dll_rb_assoc_new},
500     {"rb_cFalseClass", (RUBY_PROC*)&dll_rb_cFalseClass},
501     {"rb_cFixnum", (RUBY_PROC*)&dll_rb_cFixnum},
502 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
503     {"rb_cFloat", (RUBY_PROC*)&dll_rb_cFloat},
504 # endif
505     {"rb_cNilClass", (RUBY_PROC*)&dll_rb_cNilClass},
506     {"rb_cObject", (RUBY_PROC*)&dll_rb_cObject},
507     {"rb_cSymbol", (RUBY_PROC*)&dll_rb_cSymbol},
508     {"rb_cTrueClass", (RUBY_PROC*)&dll_rb_cTrueClass},
509     {"rb_check_type", (RUBY_PROC*)&dll_rb_check_type},
510 # ifdef USE_TYPEDDATA
511     {"rb_check_typeddata", (RUBY_PROC*)&dll_rb_check_typeddata},
512 # endif
513     {"rb_class_path", (RUBY_PROC*)&dll_rb_class_path},
514 # ifdef USE_TYPEDDATA
515 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
516     {"rb_data_typed_object_wrap", (RUBY_PROC*)&dll_rb_data_typed_object_wrap},
517 #  else
518     {"rb_data_typed_object_alloc", (RUBY_PROC*)&dll_rb_data_typed_object_alloc},
519 #  endif
520 # else
521     {"rb_data_object_alloc", (RUBY_PROC*)&dll_rb_data_object_alloc},
522 # endif
523     {"rb_define_class_under", (RUBY_PROC*)&dll_rb_define_class_under},
524     {"rb_define_const", (RUBY_PROC*)&dll_rb_define_const},
525     {"rb_define_global_function", (RUBY_PROC*)&dll_rb_define_global_function},
526     {"rb_define_method", (RUBY_PROC*)&dll_rb_define_method},
527     {"rb_define_module", (RUBY_PROC*)&dll_rb_define_module},
528     {"rb_define_module_function", (RUBY_PROC*)&dll_rb_define_module_function},
529     {"rb_define_singleton_method", (RUBY_PROC*)&dll_rb_define_singleton_method},
530     {"rb_define_virtual_variable", (RUBY_PROC*)&dll_rb_define_virtual_variable},
531     {"rb_stdout", (RUBY_PROC*)&dll_rb_stdout},
532     {"rb_eArgError", (RUBY_PROC*)&dll_rb_eArgError},
533     {"rb_eIndexError", (RUBY_PROC*)&dll_rb_eIndexError},
534     {"rb_eRuntimeError", (RUBY_PROC*)&dll_rb_eRuntimeError},
535     {"rb_eStandardError", (RUBY_PROC*)&dll_rb_eStandardError},
536     {"rb_eval_string_protect", (RUBY_PROC*)&dll_rb_eval_string_protect},
537     {"rb_global_variable", (RUBY_PROC*)&dll_rb_global_variable},
538     {"rb_hash_aset", (RUBY_PROC*)&dll_rb_hash_aset},
539     {"rb_hash_new", (RUBY_PROC*)&dll_rb_hash_new},
540     {"rb_inspect", (RUBY_PROC*)&dll_rb_inspect},
541     {"rb_int2inum", (RUBY_PROC*)&dll_rb_int2inum},
542 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
543     {"rb_fix2int", (RUBY_PROC*)&dll_rb_fix2int},
544     {"rb_num2int", (RUBY_PROC*)&dll_rb_num2int},
545     {"rb_num2uint", (RUBY_PROC*)&dll_rb_num2uint},
546 # endif
547     {"rb_lastline_get", (RUBY_PROC*)&dll_rb_lastline_get},
548     {"rb_lastline_set", (RUBY_PROC*)&dll_rb_lastline_set},
549     {"rb_load_protect", (RUBY_PROC*)&dll_rb_load_protect},
550     {"rb_num2long", (RUBY_PROC*)&dll_rb_num2long},
551     {"rb_num2ulong", (RUBY_PROC*)&dll_rb_num2ulong},
552     {"rb_obj_alloc", (RUBY_PROC*)&dll_rb_obj_alloc},
553     {"rb_obj_as_string", (RUBY_PROC*)&dll_rb_obj_as_string},
554     {"rb_obj_id", (RUBY_PROC*)&dll_rb_obj_id},
555     {"rb_raise", (RUBY_PROC*)&dll_rb_raise},
556 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
557     {"rb_string_value", (RUBY_PROC*)&dll_rb_string_value},
558 # else
559     {"rb_str2cstr", (RUBY_PROC*)&dll_rb_str2cstr},
560 # endif
561     {"rb_str_cat", (RUBY_PROC*)&dll_rb_str_cat},
562     {"rb_str_concat", (RUBY_PROC*)&dll_rb_str_concat},
563     {"rb_str_new", (RUBY_PROC*)&dll_rb_str_new},
564 # ifdef need_rb_str_new_cstr
565     {"rb_str_new_cstr", (RUBY_PROC*)&dll_rb_str_new_cstr},
566 # else
567     {"rb_str_new2", (RUBY_PROC*)&dll_rb_str_new2},
568 # endif
569 # ifdef RUBY19_OR_LATER
570     {"rb_errinfo", (RUBY_PROC*)&dll_rb_errinfo},
571 # else
572     {"ruby_errinfo", (RUBY_PROC*)&dll_ruby_errinfo},
573 # endif
574     {"ruby_init", (RUBY_PROC*)&dll_ruby_init},
575     {"ruby_init_loadpath", (RUBY_PROC*)&dll_ruby_init_loadpath},
576 # ifdef WIN3264
577     {
578 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER < 19
579     "NtInitialize",
580 #  else
581     "ruby_sysinit",
582 #  endif
583 			(RUBY_PROC*)&dll_NtInitialize},
584 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
585     {"rb_w32_snprintf", (RUBY_PROC*)&dll_rb_w32_snprintf},
586 #  endif
587 # endif
588 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
589     {"rb_string_value_ptr", (RUBY_PROC*)&dll_rb_string_value_ptr},
590 #  if DYNAMIC_RUBY_VER <= 19
591     {"rb_float_new", (RUBY_PROC*)&dll_rb_float_new},
592 #  else
593     {"rb_float_new_in_heap", (RUBY_PROC*)&dll_rb_float_new},
594 #  endif
595     {"rb_ary_new", (RUBY_PROC*)&dll_rb_ary_new},
596     {"rb_ary_push", (RUBY_PROC*)&dll_rb_ary_push},
597 # endif
598 # ifdef RUBY19_OR_LATER
599     {"rb_int2big", (RUBY_PROC*)&dll_rb_int2big},
600     {"ruby_script", (RUBY_PROC*)&dll_ruby_script},
601     {"rb_enc_find_index", (RUBY_PROC*)&dll_rb_enc_find_index},
602     {"rb_enc_find", (RUBY_PROC*)&dll_rb_enc_find},
603     {"rb_enc_str_new", (RUBY_PROC*)&dll_rb_enc_str_new},
604     {"rb_sprintf", (RUBY_PROC*)&dll_rb_sprintf},
605     {"rb_require", (RUBY_PROC*)&dll_rb_require},
606     {"ruby_options", (RUBY_PROC*)&dll_ruby_options},
607 # endif
608 # if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
609 #  ifdef __ia64
610     {"rb_ia64_bsp", (RUBY_PROC*)&dll_rb_ia64_bsp},
611 #  endif
612     {"ruby_init_stack", (RUBY_PROC*)&dll_ruby_init_stack},
613 # endif
614 # if defined(USE_RGENGC) && USE_RGENGC
615 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
616     {"rb_gc_writebarrier_unprotect_promoted", (RUBY_PROC*)&dll_rb_gc_writebarrier_unprotect_promoted},
617 #  else
618     {"rb_gc_writebarrier_unprotect", (RUBY_PROC*)&dll_rb_gc_writebarrier_unprotect},
619 #  endif
620 # endif
621     {"", NULL},
622 };
623 
624 /*
625  * Free ruby.dll
626  */
627     static void
628 end_dynamic_ruby(void)
629 {
630     if (hinstRuby)
631     {
632 	close_dll(hinstRuby);
633 	hinstRuby = NULL;
634     }
635 }
636 
637 /*
638  * Load library and get all pointers.
639  * Parameter 'libname' provides name of DLL.
640  * Return OK or FAIL.
641  */
642     static int
643 ruby_runtime_link_init(char *libname, int verbose)
644 {
645     int i;
646 
647     if (hinstRuby)
648 	return OK;
649     hinstRuby = load_dll(libname);
650     if (!hinstRuby)
651     {
652 	if (verbose)
653 	    EMSG2(_(e_loadlib), libname);
654 	return FAIL;
655     }
656 
657     for (i = 0; ruby_funcname_table[i].ptr; ++i)
658     {
659 	if (!(*ruby_funcname_table[i].ptr = symbol_from_dll(hinstRuby,
660 			ruby_funcname_table[i].name)))
661 	{
662 	    close_dll(hinstRuby);
663 	    hinstRuby = NULL;
664 	    if (verbose)
665 		EMSG2(_(e_loadfunc), ruby_funcname_table[i].name);
666 	    return FAIL;
667 	}
668     }
669     return OK;
670 }
671 
672 /*
673  * If ruby is enabled (there is installed ruby on Windows system) return TRUE,
674  * else FALSE.
675  */
676     int
677 ruby_enabled(int verbose)
678 {
679     return ruby_runtime_link_init((char *)p_rubydll, verbose) == OK;
680 }
681 #endif /* defined(DYNAMIC_RUBY) || defined(PROTO) */
682 
683     void
684 ruby_end(void)
685 {
686 #ifdef DYNAMIC_RUBY
687     end_dynamic_ruby();
688 #endif
689 }
690 
691 void ex_ruby(exarg_T *eap)
692 {
693     int state;
694     char *script = NULL;
695 
696     script = (char *)script_get(eap, eap->arg);
697     if (!eap->skip && ensure_ruby_initialized())
698     {
699 	if (script == NULL)
700 	    rb_eval_string_protect((char *)eap->arg, &state);
701 	else
702 	    rb_eval_string_protect(script, &state);
703 	if (state)
704 	    error_print(state);
705     }
706     vim_free(script);
707 }
708 
709 /*
710  *  In Ruby 1.9 or later, ruby String object has encoding.
711  *  conversion buffer string of vim to ruby String object using
712  *  VIM encoding option.
713  */
714     static VALUE
715 vim_str2rb_enc_str(const char *s)
716 {
717 #ifdef RUBY19_OR_LATER
718     int isnum;
719     long lval;
720     char_u *sval;
721     rb_encoding *enc;
722 
723     isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
724     if (isnum == 0)
725     {
726 	enc = rb_enc_find((char *)sval);
727 	vim_free(sval);
728 	if (enc) {
729 	    return rb_enc_str_new(s, strlen(s), enc);
730 	}
731     }
732 #endif
733     return rb_str_new2(s);
734 }
735 
736     static VALUE
737 eval_enc_string_protect(const char *str, int *state)
738 {
739 #ifdef RUBY19_OR_LATER
740     int isnum;
741     long lval;
742     char_u *sval;
743     rb_encoding *enc;
744     VALUE v;
745 
746     isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
747     if (isnum == 0)
748     {
749 	enc = rb_enc_find((char *)sval);
750 	vim_free(sval);
751 	if (enc)
752 	{
753 	    v = rb_sprintf("#-*- coding:%s -*-\n%s", rb_enc_name(enc), str);
754 	    return rb_eval_string_protect(StringValuePtr(v), state);
755 	}
756     }
757 #endif
758     return rb_eval_string_protect(str, state);
759 }
760 
761 void ex_rubydo(exarg_T *eap)
762 {
763     int state;
764     linenr_T i;
765 
766     if (ensure_ruby_initialized())
767     {
768 	if (u_save(eap->line1 - 1, eap->line2 + 1) != OK)
769 	    return;
770 	for (i = eap->line1; i <= eap->line2; i++) {
771 	    VALUE line;
772 
773 	    line = vim_str2rb_enc_str((char *)ml_get(i));
774 	    rb_lastline_set(line);
775 	    eval_enc_string_protect((char *) eap->arg, &state);
776 	    if (state) {
777 		error_print(state);
778 		break;
779 	    }
780 	    line = rb_lastline_get();
781 	    if (!NIL_P(line)) {
782 		if (TYPE(line) != T_STRING) {
783 		    EMSG(_("E265: $_ must be an instance of String"));
784 		    return;
785 		}
786 		ml_replace(i, (char_u *) StringValuePtr(line), 1);
787 		changed();
788 #ifdef SYNTAX_HL
789 		syn_changed(i); /* recompute syntax hl. for this line */
790 #endif
791 	    }
792 	}
793 	check_cursor();
794 	update_curbuf(NOT_VALID);
795     }
796 }
797 
798 void ex_rubyfile(exarg_T *eap)
799 {
800     int state;
801 
802     if (ensure_ruby_initialized())
803     {
804 	rb_load_protect(rb_str_new2((char *) eap->arg), 0, &state);
805 	if (state) error_print(state);
806     }
807 }
808 
809 void ruby_buffer_free(buf_T *buf)
810 {
811     if (buf->b_ruby_ref)
812     {
813 	rb_hash_aset(objtbl, rb_obj_id((VALUE) buf->b_ruby_ref), Qnil);
814 	RDATA(buf->b_ruby_ref)->data = NULL;
815     }
816 }
817 
818 void ruby_window_free(win_T *win)
819 {
820     if (win->w_ruby_ref)
821     {
822 	rb_hash_aset(objtbl, rb_obj_id((VALUE) win->w_ruby_ref), Qnil);
823 	RDATA(win->w_ruby_ref)->data = NULL;
824     }
825 }
826 
827 static int ensure_ruby_initialized(void)
828 {
829     if (!ruby_initialized)
830     {
831 #ifdef DYNAMIC_RUBY
832 	if (ruby_enabled(TRUE))
833 	{
834 #endif
835 #ifdef _WIN32
836 	    /* suggested by Ariya Mizutani */
837 	    int argc = 1;
838 	    char *argv[] = {"gvim.exe"};
839 	    char **argvp = argv;
840 	    NtInitialize(&argc, &argvp);
841 #endif
842 	    {
843 #if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
844 		ruby_init_stack(ruby_stack_start);
845 #endif
846 		ruby_init();
847 	    }
848 #ifdef RUBY19_OR_LATER
849 	    {
850 		int dummy_argc = 2;
851 		char *dummy_argv[] = {"vim-ruby", "-e0"};
852 		ruby_options(dummy_argc, dummy_argv);
853 	    }
854 	    ruby_script("vim-ruby");
855 #else
856 	    ruby_init_loadpath();
857 #endif
858 	    ruby_io_init();
859 	    ruby_vim_init();
860 	    ruby_initialized = 1;
861 #ifdef DYNAMIC_RUBY
862 	}
863 	else
864 	{
865 	    EMSG(_("E266: Sorry, this command is disabled, the Ruby library could not be loaded."));
866 	    return 0;
867 	}
868 #endif
869     }
870     return ruby_initialized;
871 }
872 
873 static void error_print(int state)
874 {
875 #ifndef DYNAMIC_RUBY
876 #if !(defined(RUBY_VERSION) && RUBY_VERSION >= 19) \
877     && !(defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19)
878     RUBYEXTERN VALUE ruby_errinfo;
879 #endif
880 #endif
881     VALUE eclass;
882     VALUE einfo;
883     char buff[BUFSIZ];
884 
885 #define TAG_RETURN	0x1
886 #define TAG_BREAK	0x2
887 #define TAG_NEXT	0x3
888 #define TAG_RETRY	0x4
889 #define TAG_REDO	0x5
890 #define TAG_RAISE	0x6
891 #define TAG_THROW	0x7
892 #define TAG_FATAL	0x8
893 #define TAG_MASK	0xf
894 
895     switch (state) {
896     case TAG_RETURN:
897 	EMSG(_("E267: unexpected return"));
898 	break;
899     case TAG_NEXT:
900 	EMSG(_("E268: unexpected next"));
901 	break;
902     case TAG_BREAK:
903 	EMSG(_("E269: unexpected break"));
904 	break;
905     case TAG_REDO:
906 	EMSG(_("E270: unexpected redo"));
907 	break;
908     case TAG_RETRY:
909 	EMSG(_("E271: retry outside of rescue clause"));
910 	break;
911     case TAG_RAISE:
912     case TAG_FATAL:
913 #ifdef RUBY19_OR_LATER
914 	eclass = CLASS_OF(rb_errinfo());
915 	einfo = rb_obj_as_string(rb_errinfo());
916 #else
917 	eclass = CLASS_OF(ruby_errinfo);
918 	einfo = rb_obj_as_string(ruby_errinfo);
919 #endif
920 	if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0) {
921 	    EMSG(_("E272: unhandled exception"));
922 	}
923 	else {
924 	    VALUE epath;
925 	    char *p;
926 
927 	    epath = rb_class_path(eclass);
928 	    vim_snprintf(buff, BUFSIZ, "%s: %s",
929 		     RSTRING_PTR(epath), RSTRING_PTR(einfo));
930 	    p = strchr(buff, '\n');
931 	    if (p) *p = '\0';
932 	    EMSG(buff);
933 	}
934 	break;
935     default:
936 	vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state);
937 	EMSG(buff);
938 	break;
939     }
940 }
941 
942 static VALUE vim_message(VALUE self UNUSED, VALUE str)
943 {
944     char *buff, *p;
945 
946     str = rb_obj_as_string(str);
947     if (RSTRING_LEN(str) > 0)
948     {
949 	/* Only do this when the string isn't empty, alloc(0) causes trouble. */
950 	buff = ALLOCA_N(char, RSTRING_LEN(str));
951 	strcpy(buff, RSTRING_PTR(str));
952 	p = strchr(buff, '\n');
953 	if (p) *p = '\0';
954 	MSG(buff);
955     }
956     else
957     {
958 	MSG("");
959     }
960     return Qnil;
961 }
962 
963 static VALUE vim_set_option(VALUE self UNUSED, VALUE str)
964 {
965     do_set((char_u *)StringValuePtr(str), 0);
966     update_screen(NOT_VALID);
967     return Qnil;
968 }
969 
970 static VALUE vim_command(VALUE self UNUSED, VALUE str)
971 {
972     do_cmdline_cmd((char_u *)StringValuePtr(str));
973     return Qnil;
974 }
975 
976 #ifdef FEAT_EVAL
977 static VALUE vim_to_ruby(typval_T *tv)
978 {
979     VALUE result = Qnil;
980 
981     if (tv->v_type == VAR_STRING)
982     {
983 	result = rb_str_new2(tv->vval.v_string == NULL
984 					  ? "" : (char *)(tv->vval.v_string));
985     }
986     else if (tv->v_type == VAR_NUMBER)
987     {
988 	result = INT2NUM(tv->vval.v_number);
989     }
990 # ifdef FEAT_FLOAT
991     else if (tv->v_type == VAR_FLOAT)
992     {
993 	result = rb_float_new(tv->vval.v_float);
994     }
995 # endif
996     else if (tv->v_type == VAR_LIST)
997     {
998 	list_T      *list = tv->vval.v_list;
999 	listitem_T  *curr;
1000 
1001 	result = rb_ary_new();
1002 
1003 	if (list != NULL)
1004 	{
1005 	    for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1006 	    {
1007 		rb_ary_push(result, vim_to_ruby(&curr->li_tv));
1008 	    }
1009 	}
1010     }
1011     else if (tv->v_type == VAR_DICT)
1012     {
1013 	result = rb_hash_new();
1014 
1015 	if (tv->vval.v_dict != NULL)
1016 	{
1017 	    hashtab_T   *ht = &tv->vval.v_dict->dv_hashtab;
1018 	    long_u      todo = ht->ht_used;
1019 	    hashitem_T  *hi;
1020 	    dictitem_T  *di;
1021 
1022 	    for (hi = ht->ht_array; todo > 0; ++hi)
1023 	    {
1024 		if (!HASHITEM_EMPTY(hi))
1025 		{
1026 		    --todo;
1027 
1028 		    di = dict_lookup(hi);
1029 		    rb_hash_aset(result, rb_str_new2((char *)hi->hi_key),
1030 						     vim_to_ruby(&di->di_tv));
1031 		}
1032 	    }
1033 	}
1034     }
1035     else if (tv->v_type == VAR_SPECIAL)
1036     {
1037 	if (tv->vval.v_number <= VVAL_TRUE)
1038 	    result = INT2NUM(tv->vval.v_number);
1039     } /* else return Qnil; */
1040 
1041     return result;
1042 }
1043 #endif
1044 
1045 static VALUE vim_evaluate(VALUE self UNUSED, VALUE str)
1046 {
1047 #ifdef FEAT_EVAL
1048     typval_T    *tv;
1049     VALUE       result;
1050 
1051     tv = eval_expr((char_u *)StringValuePtr(str), NULL);
1052     if (tv == NULL)
1053     {
1054 	return Qnil;
1055     }
1056     result = vim_to_ruby(tv);
1057 
1058     free_tv(tv);
1059 
1060     return result;
1061 #else
1062     return Qnil;
1063 #endif
1064 }
1065 
1066 #ifdef USE_TYPEDDATA
1067 static size_t buffer_dsize(const void *buf);
1068 
1069 static const rb_data_type_t buffer_type = {
1070     "vim_buffer",
1071     {0, 0, buffer_dsize, {0, 0}},
1072     0, 0,
1073 # ifdef RUBY_TYPED_FREE_IMMEDIATELY
1074     0,
1075 # endif
1076 };
1077 
1078 static size_t buffer_dsize(const void *buf UNUSED)
1079 {
1080     return sizeof(buf_T);
1081 }
1082 #endif
1083 
1084 static VALUE buffer_new(buf_T *buf)
1085 {
1086     if (buf->b_ruby_ref)
1087     {
1088 	return (VALUE) buf->b_ruby_ref;
1089     }
1090     else
1091     {
1092 #ifdef USE_TYPEDDATA
1093 	VALUE obj = TypedData_Wrap_Struct(cBuffer, &buffer_type, buf);
1094 #else
1095 	VALUE obj = Data_Wrap_Struct(cBuffer, 0, 0, buf);
1096 #endif
1097 	buf->b_ruby_ref = (void *) obj;
1098 	rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1099 	return obj;
1100     }
1101 }
1102 
1103 static buf_T *get_buf(VALUE obj)
1104 {
1105     buf_T *buf;
1106 
1107 #ifdef USE_TYPEDDATA
1108     TypedData_Get_Struct(obj, buf_T, &buffer_type, buf);
1109 #else
1110     Data_Get_Struct(obj, buf_T, buf);
1111 #endif
1112     if (buf == NULL)
1113 	rb_raise(eDeletedBufferError, "attempt to refer to deleted buffer");
1114     return buf;
1115 }
1116 
1117 static VALUE buffer_s_current(void)
1118 {
1119     return buffer_new(curbuf);
1120 }
1121 
1122 static VALUE buffer_s_count(void)
1123 {
1124     buf_T *b;
1125     int n = 0;
1126 
1127     for (b = firstbuf; b != NULL; b = b->b_next)
1128     {
1129 	/*  Deleted buffers should not be counted
1130 	 *    SegPhault - 01/07/05 */
1131 	if (b->b_p_bl)
1132 	    n++;
1133     }
1134 
1135     return INT2NUM(n);
1136 }
1137 
1138 static VALUE buffer_s_aref(VALUE self UNUSED, VALUE num)
1139 {
1140     buf_T *b;
1141     int n = NUM2INT(num);
1142 
1143     for (b = firstbuf; b != NULL; b = b->b_next)
1144     {
1145 	/*  Deleted buffers should not be counted
1146 	 *    SegPhault - 01/07/05 */
1147 	if (!b->b_p_bl)
1148 	    continue;
1149 
1150 	if (n == 0)
1151 	    return buffer_new(b);
1152 
1153 	n--;
1154     }
1155     return Qnil;
1156 }
1157 
1158 static VALUE buffer_name(VALUE self)
1159 {
1160     buf_T *buf = get_buf(self);
1161 
1162     return buf->b_ffname ? rb_str_new2((char *)buf->b_ffname) : Qnil;
1163 }
1164 
1165 static VALUE buffer_number(VALUE self)
1166 {
1167     buf_T *buf = get_buf(self);
1168 
1169     return INT2NUM(buf->b_fnum);
1170 }
1171 
1172 static VALUE buffer_count(VALUE self)
1173 {
1174     buf_T *buf = get_buf(self);
1175 
1176     return INT2NUM(buf->b_ml.ml_line_count);
1177 }
1178 
1179 static VALUE get_buffer_line(buf_T *buf, linenr_T n)
1180 {
1181     if (n <= 0 || n > buf->b_ml.ml_line_count)
1182 	rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
1183     return vim_str2rb_enc_str((char *)ml_get_buf(buf, n, FALSE));
1184 }
1185 
1186 static VALUE buffer_aref(VALUE self, VALUE num)
1187 {
1188     buf_T *buf = get_buf(self);
1189 
1190     if (buf != NULL)
1191 	return get_buffer_line(buf, (linenr_T)NUM2LONG(num));
1192     return Qnil; /* For stop warning */
1193 }
1194 
1195 static VALUE set_buffer_line(buf_T *buf, linenr_T n, VALUE str)
1196 {
1197     char	*line = StringValuePtr(str);
1198     aco_save_T	aco;
1199 
1200     if (n > 0 && n <= buf->b_ml.ml_line_count && line != NULL)
1201     {
1202 	/* set curwin/curbuf for "buf" and save some things */
1203 	aucmd_prepbuf(&aco, buf);
1204 
1205 	if (u_savesub(n) == OK) {
1206 	    ml_replace(n, (char_u *)line, TRUE);
1207 	    changed();
1208 #ifdef SYNTAX_HL
1209 	    syn_changed(n); /* recompute syntax hl. for this line */
1210 #endif
1211 	}
1212 
1213 	/* restore curwin/curbuf and a few other things */
1214 	aucmd_restbuf(&aco);
1215 	/* Careful: autocommands may have made "buf" invalid! */
1216 
1217 	update_curbuf(NOT_VALID);
1218     }
1219     else
1220     {
1221 	rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
1222     }
1223     return str;
1224 }
1225 
1226 static VALUE buffer_aset(VALUE self, VALUE num, VALUE str)
1227 {
1228     buf_T *buf = get_buf(self);
1229 
1230     if (buf != NULL)
1231 	return set_buffer_line(buf, (linenr_T)NUM2LONG(num), str);
1232     return str;
1233 }
1234 
1235 static VALUE buffer_delete(VALUE self, VALUE num)
1236 {
1237     buf_T	*buf = get_buf(self);
1238     long	n = NUM2LONG(num);
1239     aco_save_T	aco;
1240 
1241     if (n > 0 && n <= buf->b_ml.ml_line_count)
1242     {
1243 	/* set curwin/curbuf for "buf" and save some things */
1244 	aucmd_prepbuf(&aco, buf);
1245 
1246 	if (u_savedel(n, 1) == OK) {
1247 	    ml_delete(n, 0);
1248 
1249 	    /* Changes to non-active buffers should properly refresh
1250 	     *   SegPhault - 01/09/05 */
1251 	    deleted_lines_mark(n, 1L);
1252 
1253 	    changed();
1254 	}
1255 
1256 	/* restore curwin/curbuf and a few other things */
1257 	aucmd_restbuf(&aco);
1258 	/* Careful: autocommands may have made "buf" invalid! */
1259 
1260 	update_curbuf(NOT_VALID);
1261     }
1262     else
1263     {
1264 	rb_raise(rb_eIndexError, "line number %ld out of range", n);
1265     }
1266     return Qnil;
1267 }
1268 
1269 static VALUE buffer_append(VALUE self, VALUE num, VALUE str)
1270 {
1271     buf_T	*buf = get_buf(self);
1272     char	*line = StringValuePtr(str);
1273     long	n = NUM2LONG(num);
1274     aco_save_T	aco;
1275 
1276     if (line == NULL)
1277     {
1278 	rb_raise(rb_eIndexError, "NULL line");
1279     }
1280     else if (n >= 0 && n <= buf->b_ml.ml_line_count)
1281     {
1282 	/* set curwin/curbuf for "buf" and save some things */
1283 	aucmd_prepbuf(&aco, buf);
1284 
1285 	if (u_inssub(n + 1) == OK) {
1286 	    ml_append(n, (char_u *) line, (colnr_T) 0, FALSE);
1287 
1288 	    /*  Changes to non-active buffers should properly refresh screen
1289 	     *    SegPhault - 12/20/04 */
1290 	    appended_lines_mark(n, 1L);
1291 
1292 	    changed();
1293 	}
1294 
1295 	/* restore curwin/curbuf and a few other things */
1296 	aucmd_restbuf(&aco);
1297 	/* Careful: autocommands may have made "buf" invalid! */
1298 
1299 	update_curbuf(NOT_VALID);
1300     }
1301     else
1302     {
1303 	rb_raise(rb_eIndexError, "line number %ld out of range", n);
1304     }
1305     return str;
1306 }
1307 
1308 #ifdef USE_TYPEDDATA
1309 static size_t window_dsize(const void *buf);
1310 
1311 static const rb_data_type_t window_type = {
1312     "vim_window",
1313     {0, 0, window_dsize, {0, 0}},
1314     0, 0,
1315 # ifdef RUBY_TYPED_FREE_IMMEDIATELY
1316     0,
1317 # endif
1318 };
1319 
1320 static size_t window_dsize(const void *win UNUSED)
1321 {
1322     return sizeof(win_T);
1323 }
1324 #endif
1325 
1326 static VALUE window_new(win_T *win)
1327 {
1328     if (win->w_ruby_ref)
1329     {
1330 	return (VALUE) win->w_ruby_ref;
1331     }
1332     else
1333     {
1334 #ifdef USE_TYPEDDATA
1335 	VALUE obj = TypedData_Wrap_Struct(cVimWindow, &window_type, win);
1336 #else
1337 	VALUE obj = Data_Wrap_Struct(cVimWindow, 0, 0, win);
1338 #endif
1339 	win->w_ruby_ref = (void *) obj;
1340 	rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1341 	return obj;
1342     }
1343 }
1344 
1345 static win_T *get_win(VALUE obj)
1346 {
1347     win_T *win;
1348 
1349 #ifdef USE_TYPEDDATA
1350     TypedData_Get_Struct(obj, win_T, &window_type, win);
1351 #else
1352     Data_Get_Struct(obj, win_T, win);
1353 #endif
1354     if (win == NULL)
1355 	rb_raise(eDeletedWindowError, "attempt to refer to deleted window");
1356     return win;
1357 }
1358 
1359 static VALUE window_s_current(void)
1360 {
1361     return window_new(curwin);
1362 }
1363 
1364 /*
1365  * Added line manipulation functions
1366  *    SegPhault - 03/07/05
1367  */
1368 static VALUE line_s_current(void)
1369 {
1370     return get_buffer_line(curbuf, curwin->w_cursor.lnum);
1371 }
1372 
1373 static VALUE set_current_line(VALUE self UNUSED, VALUE str)
1374 {
1375     return set_buffer_line(curbuf, curwin->w_cursor.lnum, str);
1376 }
1377 
1378 static VALUE current_line_number(void)
1379 {
1380     return INT2FIX((int)curwin->w_cursor.lnum);
1381 }
1382 
1383 
1384 
1385 static VALUE window_s_count(void)
1386 {
1387 #ifdef FEAT_WINDOWS
1388     win_T	*w;
1389     int n = 0;
1390 
1391     for (w = firstwin; w != NULL; w = w->w_next)
1392 	n++;
1393     return INT2NUM(n);
1394 #else
1395     return INT2NUM(1);
1396 #endif
1397 }
1398 
1399 static VALUE window_s_aref(VALUE self UNUSED, VALUE num)
1400 {
1401     win_T *w;
1402     int n = NUM2INT(num);
1403 
1404 #ifndef FEAT_WINDOWS
1405     w = curwin;
1406 #else
1407     for (w = firstwin; w != NULL; w = w->w_next, --n)
1408 #endif
1409 	if (n == 0)
1410 	    return window_new(w);
1411     return Qnil;
1412 }
1413 
1414 static VALUE window_buffer(VALUE self)
1415 {
1416     win_T *win = get_win(self);
1417 
1418     return buffer_new(win->w_buffer);
1419 }
1420 
1421 static VALUE window_height(VALUE self)
1422 {
1423     win_T *win = get_win(self);
1424 
1425     return INT2NUM(win->w_height);
1426 }
1427 
1428 static VALUE window_set_height(VALUE self, VALUE height)
1429 {
1430     win_T *win = get_win(self);
1431     win_T *savewin = curwin;
1432 
1433     curwin = win;
1434     win_setheight(NUM2INT(height));
1435     curwin = savewin;
1436     return height;
1437 }
1438 
1439 static VALUE window_width(VALUE self UNUSED)
1440 {
1441     return INT2NUM(W_WIDTH(get_win(self)));
1442 }
1443 
1444 static VALUE window_set_width(VALUE self UNUSED, VALUE width)
1445 {
1446 #ifdef FEAT_VERTSPLIT
1447     win_T *win = get_win(self);
1448     win_T *savewin = curwin;
1449 
1450     curwin = win;
1451     win_setwidth(NUM2INT(width));
1452     curwin = savewin;
1453 #endif
1454     return width;
1455 }
1456 
1457 static VALUE window_cursor(VALUE self)
1458 {
1459     win_T *win = get_win(self);
1460 
1461     return rb_assoc_new(INT2NUM(win->w_cursor.lnum), INT2NUM(win->w_cursor.col));
1462 }
1463 
1464 static VALUE window_set_cursor(VALUE self, VALUE pos)
1465 {
1466     VALUE lnum, col;
1467     win_T *win = get_win(self);
1468 
1469     Check_Type(pos, T_ARRAY);
1470     if (RARRAY_LEN(pos) != 2)
1471 	rb_raise(rb_eArgError, "array length must be 2");
1472     lnum = RARRAY_PTR(pos)[0];
1473     col = RARRAY_PTR(pos)[1];
1474     win->w_cursor.lnum = NUM2LONG(lnum);
1475     win->w_cursor.col = NUM2UINT(col);
1476     check_cursor();		    /* put cursor on an existing line */
1477     update_screen(NOT_VALID);
1478     return Qnil;
1479 }
1480 
1481 static VALUE f_nop(VALUE self UNUSED)
1482 {
1483     return Qnil;
1484 }
1485 
1486 static VALUE f_p(int argc, VALUE *argv, VALUE self UNUSED)
1487 {
1488     int i;
1489     VALUE str = rb_str_new("", 0);
1490 
1491     for (i = 0; i < argc; i++) {
1492 	if (i > 0) rb_str_cat(str, ", ", 2);
1493 	rb_str_concat(str, rb_inspect(argv[i]));
1494     }
1495     MSG(RSTRING_PTR(str));
1496     return Qnil;
1497 }
1498 
1499 static void ruby_io_init(void)
1500 {
1501 #ifndef DYNAMIC_RUBY
1502     RUBYEXTERN VALUE rb_stdout;
1503 #endif
1504 
1505     rb_stdout = rb_obj_alloc(rb_cObject);
1506     rb_define_singleton_method(rb_stdout, "write", vim_message, 1);
1507     rb_define_singleton_method(rb_stdout, "flush", f_nop, 0);
1508     rb_define_global_function("p", f_p, -1);
1509 }
1510 
1511 static void ruby_vim_init(void)
1512 {
1513     objtbl = rb_hash_new();
1514     rb_global_variable(&objtbl);
1515 
1516     /* The Vim module used to be called "VIM", but "Vim" is better.  Make an
1517      * alias "VIM" for backwards compatibility. */
1518     mVIM = rb_define_module("Vim");
1519     rb_define_const(rb_cObject, "VIM", mVIM);
1520     rb_define_const(mVIM, "VERSION_MAJOR", INT2NUM(VIM_VERSION_MAJOR));
1521     rb_define_const(mVIM, "VERSION_MINOR", INT2NUM(VIM_VERSION_MINOR));
1522     rb_define_const(mVIM, "VERSION_BUILD", INT2NUM(VIM_VERSION_BUILD));
1523     rb_define_const(mVIM, "VERSION_PATCHLEVEL", INT2NUM(VIM_VERSION_PATCHLEVEL));
1524     rb_define_const(mVIM, "VERSION_SHORT", rb_str_new2(VIM_VERSION_SHORT));
1525     rb_define_const(mVIM, "VERSION_MEDIUM", rb_str_new2(VIM_VERSION_MEDIUM));
1526     rb_define_const(mVIM, "VERSION_LONG", rb_str_new2(VIM_VERSION_LONG));
1527     rb_define_const(mVIM, "VERSION_LONG_DATE", rb_str_new2(VIM_VERSION_LONG_DATE));
1528     rb_define_module_function(mVIM, "message", vim_message, 1);
1529     rb_define_module_function(mVIM, "set_option", vim_set_option, 1);
1530     rb_define_module_function(mVIM, "command", vim_command, 1);
1531     rb_define_module_function(mVIM, "evaluate", vim_evaluate, 1);
1532 
1533     eDeletedBufferError = rb_define_class_under(mVIM, "DeletedBufferError",
1534 						rb_eStandardError);
1535     eDeletedWindowError = rb_define_class_under(mVIM, "DeletedWindowError",
1536 						rb_eStandardError);
1537 
1538     cBuffer = rb_define_class_under(mVIM, "Buffer", rb_cObject);
1539     rb_define_singleton_method(cBuffer, "current", buffer_s_current, 0);
1540     rb_define_singleton_method(cBuffer, "count", buffer_s_count, 0);
1541     rb_define_singleton_method(cBuffer, "[]", buffer_s_aref, 1);
1542     rb_define_method(cBuffer, "name", buffer_name, 0);
1543     rb_define_method(cBuffer, "number", buffer_number, 0);
1544     rb_define_method(cBuffer, "count", buffer_count, 0);
1545     rb_define_method(cBuffer, "length", buffer_count, 0);
1546     rb_define_method(cBuffer, "[]", buffer_aref, 1);
1547     rb_define_method(cBuffer, "[]=", buffer_aset, 2);
1548     rb_define_method(cBuffer, "delete", buffer_delete, 1);
1549     rb_define_method(cBuffer, "append", buffer_append, 2);
1550 
1551     /* Added line manipulation functions
1552      *   SegPhault - 03/07/05 */
1553     rb_define_method(cBuffer, "line_number", current_line_number, 0);
1554     rb_define_method(cBuffer, "line", line_s_current, 0);
1555     rb_define_method(cBuffer, "line=", set_current_line, 1);
1556 
1557 
1558     cVimWindow = rb_define_class_under(mVIM, "Window", rb_cObject);
1559     rb_define_singleton_method(cVimWindow, "current", window_s_current, 0);
1560     rb_define_singleton_method(cVimWindow, "count", window_s_count, 0);
1561     rb_define_singleton_method(cVimWindow, "[]", window_s_aref, 1);
1562     rb_define_method(cVimWindow, "buffer", window_buffer, 0);
1563     rb_define_method(cVimWindow, "height", window_height, 0);
1564     rb_define_method(cVimWindow, "height=", window_set_height, 1);
1565     rb_define_method(cVimWindow, "width", window_width, 0);
1566     rb_define_method(cVimWindow, "width=", window_set_width, 1);
1567     rb_define_method(cVimWindow, "cursor", window_cursor, 0);
1568     rb_define_method(cVimWindow, "cursor=", window_set_cursor, 1);
1569 
1570     rb_define_virtual_variable("$curbuf", buffer_s_current, 0);
1571     rb_define_virtual_variable("$curwin", window_s_current, 0);
1572 }
1573 
1574 void vim_ruby_init(void *stack_start)
1575 {
1576     /* should get machine stack start address early in main function */
1577     ruby_stack_start = stack_start;
1578 }
1579